diff --git a/HOW_TO_BUILD b/HOW_TO_BUILD new file mode 100644 index 0000000..eeb307e --- /dev/null +++ b/HOW_TO_BUILD @@ -0,0 +1,64 @@ +E3 is a Maven based JAVA project. + +Tools advised to manage, build and run project are: +- Eclipse STS +- Maven 3.0.3 -> Packaged with Eclipse STS +- RedHat based Linux VM to use one line installation + + +USING SOURCE CODE: +- Get the project +- Copy /maven/settings.xml on the {user.home}/.m2/ directory +- Create a new project: + - Right click in the Package Explorer window -> New -> Project... + - Choose general/Project + - Give a name (E3 for our example) and click Finish +- Import files in STS: + - Load source code by using the archive example: + - Right click in the Package Explorer window -> Import... + - Choose general/Archive File + - Choose the archive with all files into your new folder and click Finish + - OR Load source by another way if you prefer : SVN, Git, File System +- Import the Maven project under exposure-engine directory: + - Right click in the Package Explorer window -> Import... + - Choose Maven/Existing Maven Projects + - Select only all project under exposure-engine/pom.xml and click Finish +- Wait until your workspace is building, all dependencies must be found by Maven on the Internet + +--> Project is set up on your Eclipse STS. + + +BUILD THE PROJECT: +- Right click on your E3 project -> Run as -> Run configurations... +- Select Maven Build and click on New icon on the top +- Give a name to your configuration +- Choose your E3 project on base directory -> Browse Workspace... -> E3 -> OK +- Type "clean install -f pom-assembly.xml" in Goals textbox +- Type "build-modules,assembly" in Profiles textbox +- Click on Apply to save and on Run to make a first build + +--> Your installer module is build on the E3/target/server-side + +!!!!!!!!!!!!!!! +!!! WARNING !!! +!!!!!!!!!!!!!!! +Installation scripts make some modifications on your RedHat installation: +- Add an E3 user to run application +- Set the number of file descriptors open to the maximum +- Modify IPTABLES configuration : + - FLUSH standard settings + - Open all needed ports for E3 + - Add a setting to block all other ports + +--> See scripts on the /packaging/src/main/resources folder to see all modifications the installer made + + +INSTALL AND RUN THE PROJECT: (See the installation guide for more details) +- Transfer the e3-installer-module_XXX.tar.gz archive on your RedHat Linux VM in a temporary directory +- untar them using tar -xf e3-installer-module_XXX.tar.gz +- Go to {temp_directory}/bin directory +- run install_e3_aib.sh script : sh install_e3_aib.sh + +--> Your installation is ready on the directory /home/e3/ ! + +--> You can go to the /tests/HOW_TO_RUN_TESTS file to run SoapUI functionnal tests and validate your installation \ No newline at end of file diff --git a/LICENSE b/LICENSE new file mode 100644 index 0000000..2efc389 --- /dev/null +++ b/LICENSE @@ -0,0 +1,16 @@ +Copyright © 2012 Alcatel-Lucent. + +See the NOTICE file distributed with this work for additional +information regarding copyright ownership. +Licensed to you 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. diff --git a/Licenses/asl-2.0-license.txt b/Licenses/asl-2.0-license.txt new file mode 100644 index 0000000..d645695 --- /dev/null +++ b/Licenses/asl-2.0-license.txt @@ -0,0 +1,202 @@ + + Apache License + Version 2.0, January 2004 + http://www.apache.org/licenses/ + + TERMS AND CONDITIONS FOR USE, REPRODUCTION, AND DISTRIBUTION + + 1. Definitions. + + "License" shall mean the terms and conditions for use, reproduction, + and distribution as defined by Sections 1 through 9 of this document. + + "Licensor" shall mean the copyright owner or entity authorized by + the copyright owner that is granting the License. + + "Legal Entity" shall mean the union of the acting entity and all + other entities that control, are controlled by, or are under common + control with that entity. For the purposes of this definition, + "control" means (i) the power, direct or indirect, to cause the + direction or management of such entity, whether by contract or + otherwise, or (ii) ownership of fifty percent (50%) or more of the + outstanding shares, or (iii) beneficial ownership of such entity. + + "You" (or "Your") shall mean an individual or Legal Entity + exercising permissions granted by this License. + + "Source" form shall mean the preferred form for making modifications, + including but not limited to software source code, documentation + source, and configuration files. + + "Object" form shall mean any form resulting from mechanical + transformation or translation of a Source form, including but + not limited to compiled object code, generated documentation, + and conversions to other media types. + + "Work" shall mean the work of authorship, whether in Source or + Object form, made available under the License, as indicated by a + copyright notice that is included in or attached to the work + (an example is provided in the Appendix below). + + "Derivative Works" shall mean any work, whether in Source or Object + form, that is based on (or derived from) the Work and for which the + editorial revisions, annotations, elaborations, or other modifications + represent, as a whole, an original work of authorship. For the purposes + of this License, Derivative Works shall not include works that remain + separable from, or merely link (or bind by name) to the interfaces of, + the Work and Derivative Works thereof. + + "Contribution" shall mean any work of authorship, including + the original version of the Work and any modifications or additions + to that Work or Derivative Works thereof, that is intentionally + submitted to Licensor for inclusion in the Work by the copyright owner + or by an individual or Legal Entity authorized to submit on behalf of + the copyright owner. For the purposes of this definition, "submitted" + means any form of electronic, verbal, or written communication sent + to the Licensor or its representatives, including but not limited to + communication on electronic mailing lists, source code control systems, + and issue tracking systems that are managed by, or on behalf of, the + Licensor for the purpose of discussing and improving the Work, but + excluding communication that is conspicuously marked or otherwise + designated in writing by the copyright owner as "Not a Contribution." + + "Contributor" shall mean Licensor and any individual or Legal Entity + on behalf of whom a Contribution has been received by Licensor and + subsequently incorporated within the Work. + + 2. Grant of Copyright License. Subject to the terms and conditions of + this License, each Contributor hereby grants to You a perpetual, + worldwide, non-exclusive, no-charge, royalty-free, irrevocable + copyright license to reproduce, prepare Derivative Works of, + publicly display, publicly perform, sublicense, and distribute the + Work and such Derivative Works in Source or Object form. + + 3. Grant of Patent License. Subject to the terms and conditions of + this License, each Contributor hereby grants to You a perpetual, + worldwide, non-exclusive, no-charge, royalty-free, irrevocable + (except as stated in this section) patent license to make, have made, + use, offer to sell, sell, import, and otherwise transfer the Work, + where such license applies only to those patent claims licensable + by such Contributor that are necessarily infringed by their + Contribution(s) alone or by combination of their Contribution(s) + with the Work to which such Contribution(s) was submitted. If You + institute patent litigation against any entity (including a + cross-claim or counterclaim in a lawsuit) alleging that the Work + or a Contribution incorporated within the Work constitutes direct + or contributory patent infringement, then any patent licenses + granted to You under this License for that Work shall terminate + as of the date such litigation is filed. + + 4. Redistribution. You may reproduce and distribute copies of the + Work or Derivative Works thereof in any medium, with or without + modifications, and in Source or Object form, provided that You + meet the following conditions: + + (a) You must give any other recipients of the Work or + Derivative Works a copy of this License; and + + (b) You must cause any modified files to carry prominent notices + stating that You changed the files; and + + (c) You must retain, in the Source form of any Derivative Works + that You distribute, all copyright, patent, trademark, and + attribution notices from the Source form of the Work, + excluding those notices that do not pertain to any part of + the Derivative Works; and + + (d) If the Work includes a "NOTICE" text file as part of its + distribution, then any Derivative Works that You distribute must + include a readable copy of the attribution notices contained + within such NOTICE file, excluding those notices that do not + pertain to any part of the Derivative Works, in at least one + of the following places: within a NOTICE text file distributed + as part of the Derivative Works; within the Source form or + documentation, if provided along with the Derivative Works; or, + within a display generated by the Derivative Works, if and + wherever such third-party notices normally appear. The contents + of the NOTICE file are for informational purposes only and + do not modify the License. You may add Your own attribution + notices within Derivative Works that You distribute, alongside + or as an addendum to the NOTICE text from the Work, provided + that such additional attribution notices cannot be construed + as modifying the License. + + You may add Your own copyright statement to Your modifications and + may provide additional or different license terms and conditions + for use, reproduction, or distribution of Your modifications, or + for any such Derivative Works as a whole, provided Your use, + reproduction, and distribution of the Work otherwise complies with + the conditions stated in this License. + + 5. Submission of Contributions. Unless You explicitly state otherwise, + any Contribution intentionally submitted for inclusion in the Work + by You to the Licensor shall be under the terms and conditions of + this License, without any additional terms or conditions. + Notwithstanding the above, nothing herein shall supersede or modify + the terms of any separate license agreement you may have executed + with Licensor regarding such Contributions. + + 6. Trademarks. This License does not grant permission to use the trade + names, trademarks, service marks, or product names of the Licensor, + except as required for reasonable and customary use in describing the + origin of the Work and reproducing the content of the NOTICE file. + + 7. Disclaimer of Warranty. Unless required by applicable law or + agreed to in writing, Licensor provides the Work (and each + Contributor provides its Contributions) on an "AS IS" BASIS, + WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or + implied, including, without limitation, any warranties or conditions + of TITLE, NON-INFRINGEMENT, MERCHANTABILITY, or FITNESS FOR A + PARTICULAR PURPOSE. You are solely responsible for determining the + appropriateness of using or redistributing the Work and assume any + risks associated with Your exercise of permissions under this License. + + 8. Limitation of Liability. In no event and under no legal theory, + whether in tort (including negligence), contract, or otherwise, + unless required by applicable law (such as deliberate and grossly + negligent acts) or agreed to in writing, shall any Contributor be + liable to You for damages, including any direct, indirect, special, + incidental, or consequential damages of any character arising as a + result of this License or out of the use or inability to use the + Work (including but not limited to damages for loss of goodwill, + work stoppage, computer failure or malfunction, or any and all + other commercial damages or losses), even if such Contributor + has been advised of the possibility of such damages. + + 9. Accepting Warranty or Additional Liability. While redistributing + the Work or Derivative Works thereof, You may choose to offer, + and charge a fee for, acceptance of support, warranty, indemnity, + or other liability obligations and/or rights consistent with this + License. However, in accepting such obligations, You may act only + on Your own behalf and on Your sole responsibility, not on behalf + of any other Contributor, and only if You agree to indemnify, + defend, and hold each Contributor harmless for any liability + incurred by, or claims asserted against, such Contributor by reason + of your accepting any such warranty or additional liability. + + END OF TERMS AND CONDITIONS + + APPENDIX: How to apply the Apache License to your work. + + To apply the Apache License to your work, attach the following + boilerplate notice, with the fields enclosed by brackets "[]" + replaced with your own identifying information. (Don't include + the brackets!) The text should be enclosed in the appropriate + comment syntax for the file format. We also recommend that a + file or class name and description of purpose be included on the + same "printed page" as the copyright notice for easier + identification within third-party archives. + + Copyright [yyyy] [name of copyright owner] + + Licensed under the Apache License, Version 2.0 (the "License"); + you may not use this file except in compliance with the License. + You may obtain a copy of the License at + + http://www.apache.org/licenses/LICENSE-2.0 + + Unless required by applicable law or agreed to in writing, software + distributed under the License is distributed on an "AS IS" BASIS, + WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + See the License for the specific language governing permissions and + limitations under the License. diff --git a/Licenses/bc-license.txt b/Licenses/bc-license.txt new file mode 100644 index 0000000..5e5a0b4 --- /dev/null +++ b/Licenses/bc-license.txt @@ -0,0 +1,7 @@ +Copyright (c) 2000 - 2011 The Legion Of The Bouncy Castle (http://www.bouncycastle.org) + +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/Licenses/esb_license.txt b/Licenses/esb_license.txt new file mode 100644 index 0000000..b0e8288 --- /dev/null +++ b/Licenses/esb_license.txt @@ -0,0 +1,154 @@ +FUSE ESB v. 4.3.1 License Agreement +[Based on the Apache License Version 2.0, January 2004] + +TERMS AND CONDITIONS FOR USE, REPRODUCTION, AND DISTRIBUTION +READ THE TERMS OF THIS LICENSE AGREEMENT (“AGREEMENT”) CAREFULLY BEFORE +INSTALLING THIS WORK. BY INSTALLING THE WORK OR USING THE DOCUMENTATION PROVIDED +WITH THE WORK, YOU ARE ACCEPTING AND AGREEING TO THE TERMS OF THIS AGREEMENT. IF +YOU ARE NOT WILLING TO BE BOUND BY THE TERMS OF THIS AGREEMENT, YOU SHOULD CLICK +ON THE “DECLINE” BUTTON BELOW. +This FUSE ESB v. 4.3.1 License Agreement is made by and between YOU and Progress +Software Corporation and consists of the Apache License version 2.0 modified to +be specific to FUSE ESB v. 4.3.1, with the Additional Terms in Section 10. The +original Apache License version 2.0 can be found at +http://www.apache.org/licenses/. +1. Definitions. +“License” shall mean the terms and conditions for use, reproduction, and +distribution as defined by Sections 1 through 10 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. This Work includes a “NOTICE .txt” file. Any Derivative Works that You +distribute must include a readable copy of the attribution notices contained +within NOTICE .txt 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 .txt 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 .txt 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 .txt 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 .txt 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. +10. Additional Terms and Conditions. The terms and conditions of this License +Agreement shall apply to FUSE ESB version 4.3.0 only. The Work may contain or be +accompanied by third party software or components created and separately +licensed to You by said third parties. Some of these third-party software +components are identified in, and subject to, special license notices, terms +and/or conditions set for in a NOTICE .txt file +(http://fusesource.com/downloads/license-agreements/notices/fuseesb4-3.0) +accompanying the Work. In the event of a conflict between such additional terms +and conditions and Agreement, such additional terms and conditions will take +precedence (but solely with respect to the third party component(s) to which the +additional terms and conditions relates). This is a License Agreement, not a +transfer of copyright ownership. All copyrights remain with their respective +owners. diff --git a/Licenses/jsch-license.txt b/Licenses/jsch-license.txt new file mode 100644 index 0000000..e076c22 --- /dev/null +++ b/Licenses/jsch-license.txt @@ -0,0 +1,30 @@ +JSch 0.0.* was released under the GNU LGPL license. Later, we have switched +over to a BSD-style license. + +------------------------------------------------------------------------------ +Copyright (c) 2002-2011 Atsuhiko Yamanaka, JCraft,Inc. +All rights reserved. + +Redistribution and use in source and binary forms, with or without +modification, are permitted provided that the following conditions are met: + + 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. The names of the authors may not be used to endorse or promote products + derived from this software without specific prior written permission. + +THIS SOFTWARE IS PROVIDED ``AS IS'' AND ANY EXPRESSED 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 JCRAFT, +INC. OR ANY CONTRIBUTORS TO THIS SOFTWARE 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. diff --git a/Licenses/mit-license.txt b/Licenses/mit-license.txt new file mode 100644 index 0000000..212de3c --- /dev/null +++ b/Licenses/mit-license.txt @@ -0,0 +1,18 @@ +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/NOTICE b/NOTICE new file mode 100644 index 0000000..709790e --- /dev/null +++ b/NOTICE @@ -0,0 +1,69 @@ +The Free and Open Source Software (FOSS) products identified below are either +packaged separately or integrated together with Alcatel-Lucent product. +Each of these FOSS products was released under a license as indicated below. +Unless otherwise dictated by a FOSS license (such as GPL, LGPL, and Affero GPL) +that requires Alcatel-Lucent to grant the same rights to the parties to whom we +distribute the FOSS, your rights to use, copy, and further distribute (if applicable) +the FOSS are governed by the Alcatel-Lucent license packaged with the Alcatel-Lucent +product with which the FOSS is provided. + +For the avoidance of doubt, and without limiting any rights you may obtain independent +of Alcatel-Lucent, except as set forth in the Alcatel-Lucent license packaged +with the Alcatel-Lucent product with which the FOSS is provided: + (i) no right is granted by Alcatel-Lucent to reproduce, modify and/or redistribute + FOSS that was released under and governed by a license (such as MIT, original BSD, + new BSD, Apache, CDDL, CPL, EPL and Mozilla) that DOES NOT require Alcatel-Lucent + to grant the same rights to the parties to whom we distribute the FOSS, and + + (ii) no other licenses, express or implied, are granted, with respect to Alcatel-Lucent + intellectual property, including, without limitation, Alcatel-Lucent copyrights, + patents, trade secrets, trademarks or logos. + + (iii) In the event you are permitted to and do in fact modify any FOSS, + then notwithstanding any other provisions to the contrary, Alcatel-Lucent will + have no further liability or obligation to provide support, maintenance, warranty + or indemnity with respect to the Alcatel-Lucent products with which + the modified version of the FOSS interacts. + +=============================================================================== +FOSS used by this project are referenced below: + +Fuse ESB | 4.3.1-fuse-01-09 | Apache Software License, Version 2.0 | Licenses/esb_license.txt +hazelcast | com.hazelcast:hazelcast:2.0.1 | Apache Software License, Version 2.0 | Licenses/asl-2.0-license.txt +bcprov-jdk16 | org.bouncycastle:bcprov-jdk16:1.46 | Bouncy Castle License | Licenses/bc-license.txt +isorelax | isorelax:isorelax:20030108 | MIT License | Licenses/mit-license.txt +JSch | com.jcraft:jsch:0.1.45 | Revised BSD | Licenses/jsch-license.txt, http://www.jcraft.com/jsch/ + +=============================================================================== += +== Acknowledgements and Notices +==== + + += +== FUSE ESB related notice +==== +Fuse ESB related notice are visible in Licenses/esb_notices.txt + += +== Guava Notice | Apache Software License, Version 2.0 | Licenses/asl-2.0-license.txt, http://code.google.com/p/guava-libraries/ +==== +This project contains modified source code from the Google Guava library. +The original source code copyright notice is pasted below. + +Copyright (C) 2008 The Guava Authors + +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. + += +== Other eventual notices diff --git a/bundle/pom.xml b/bundle/pom.xml new file mode 100644 index 0000000..b81f645 --- /dev/null +++ b/bundle/pom.xml @@ -0,0 +1,754 @@ + + + 4.0.0 + + com.alu.e3 + e3-bundle + E3 Bundle + 1.0.1 + + bundle + + + 4.3.1-fuse-01-09 + 2.6.0-fuse-01-09 + 2.2 + 1.7.0 + 3.1_5 + 2.3.3 + 3.0.5.RELEASE + 1.2.0 + UTF-8 + + + + + + + + com.hazelcast + hazelcast + 2.0.1 + runtime + + + + com.hazelcast + hazelcast-client + 2.0.1 + runtime + + + + com.hazelcast + hazelcast-hibernate + 2.0.1 + runtime + + + + com.hazelcast + hazelcast-spring + 2.0.1 + runtime + + + + com.jayway.restassured + rest-assured + 1.6 + test + + + + com.jcraft + jsch + 0.1.45 + runtime + + + + commons-codec + commons-codec + 1.4 + provided + + + + commons-lang + commons-lang + 2.1 + provided + + + + isorelax + isorelax + 20030108 + runtime + + + + junit + junit + 4.8.2 + test + + + + log4j + log4j + 1.2.16 + provided + + + + org.apache.aries.jmx + org.apache.aries.jmx + 0.2-incubating + provided + + + + org.apache.camel + camel-core + ${camel.version} + provided + + + com.sun + tools + + + + + + org.apache.camel + camel-cxf + ${camel.version} + provided + + + tools + com.sun + + + + + + org.apache.camel + camel-freemarker + ${camel.version} + provided + + + tools + com.sun + + + + + + org.apache.camel + camel-http + 2.6.0-fuse-01-09 + provided + + + tools + com.sun + + + + + + org.apache.camel + camel-jetty + ${camel.version} + provided + + + tools + com.sun + + + + + + org.apache.camel + camel-spring + ${camel.version} + provided + + + com.sun + tools + + + + + + org.apache.camel + camel-test + 2.0.0 + test + + + + org.apache.cxf + cxf-bundle + 2.3.3 + test + + + org.codehaus.woodstox + woodstox-core-asl + + + org.codehaus.woodstox + stax2-api + + + + + + org.apache.cxf + cxf-rt-frontend-jaxrs + 2.3.3-fuse-01-09 + provided + + + org.codehaus.woodstox + woodstox-core-asl + + + + + + org.apache.felix + org.apache.felix.framework + 3.0.9-fuse-03-11 + provided + + + + + org.apache.servicemix.bundles + org.apache.servicemix.bundles.commons-dbcp + 1.2.2_6 + provided + + + + org.apache.servicemix.bundles + org.apache.servicemix.bundles.commons-httpclient + ${commons-httpclient.bundle.version} + provided + + + + org.apache.servicemix.bundles + org.apache.servicemix.bundles.commons-io + 1.4_1 + provided + + + + org.apache.servicemix.bundles + org.apache.servicemix.bundles.openjpa + 1.2.1_3 + provided + + + + + org.apache.servicemix.specs + org.apache.servicemix.specs.java-persistence-api-1.1.1 + 1.7.0 + provided + + + + org.apache.servicemix.specs + org.apache.servicemix.specs.jaxb-api-${jaxb.api.version} + ${servicemix.specs.version} + provided + + + + org.apache.servicemix.specs + org.apache.servicemix.specs.jsr311-api-1.1 + 1.7.0 + provided + + + + org.bouncycastle + bcprov-jdk16 + 1.46 + provided + + + + org.codehaus.woodstox + stax2-api + 3.0.3 + runtime + + + + org.eclipse.jetty + jetty-server + + 7.3.1.v20110307 + provided + + + + org.hsqldb + com.springsource.org.hsqldb + 1.8.0.10 + provided + + + + org.ops4j.pax.logging + pax-logging-api + 1.5.3 + provided + + + + org.springframework + spring-aop + ${org.springframework.version} + provided + + + + org.springframework + spring-beans + ${org.springframework.version} + provided + + + + org.springframework + spring-context + ${org.springframework.version} + provided + + + + org.springframework + spring-context-support + ${org.springframework.version} + provided + + + + org.springframework + spring-core + ${org.springframework.version} + provided + + + + org.springframework + spring-expression + ${org.springframework.version} + provided + + + + org.springframework + spring-orm + 3.0.5.RELEASE + provided + + + + org.springframework.osgi + spring-osgi-core + ${spring.osgi.version} + provided + + + org.springframework.aop + org.springframework + + + org.springframework.beans + org.springframework + + + org.springframework.context + org.springframework + + + org.springframework.core + org.springframework + + + + + + org.springframework.osgi + spring-osgi-extender + ${spring.osgi.version} + provided + + + + org.springframework.osgi + spring-osgi-io + ${spring.osgi.version} + provided + + + + org.springframework + spring-test + ${org.springframework.version} + test + + + + ${project.groupId} + auth-manager + ${project.version} + compile + + + + ${project.groupId} + common + ${project.version} + compile + + + + ${project.groupId} + gateway-common + ${project.version} + compile + + + + ${project.groupId} + gateway-rate-limits-manager + ${project.version} + compile + + + + ${project.groupId} + provisioning + ${project.version} + compile + + + + ${project.groupId} + system-manager + ${project.version} + compile + + + + ${project.groupId} + tdr-lib + ${project.version} + compile + + + + ${project.groupId} + topology + ${project.version} + compile + + + + + + + + + + org.apache.maven.plugins + maven-dependency-plugin + 2.4 + + + unpack-dependencies + compile + + unpack-dependencies + + + ${project.groupId} + target/classes + + + + + + + org.apache.felix + maven-bundle-plugin + 2.3.4 + true + + + ${project.artifactId} + ${project.version} + + org.apache.cxf.bundle + + + + + !jp.co.swiftinc.relax.*, + !org.jaxen.*, + !com.sun.msv.datatype.*, + javax.ws.rs, + javax.wsdl, + javax.xml.bind, + javax.xml.bind.annotation, + META-INF.cxf, + META-INF.cxf.osgi, + org.aopalliance.aop, + org.apache.camel, + org.apache.commons.httpclient, + org.apache.commons.httpclient.methods, + org.apache.cxf.binding, + org.apache.cxf.bus, + org.apache.cxf.bus.resource, + org.apache.cxf.bus.spring, + org.apache.cxf.configuration.spring, + org.apache.cxf.jaxrs.ext, + org.apache.cxf.jaxrs.utils, + org.apache.cxf.resource, + org.apache.cxf.transport.http_osgi, + org.slf4j, + org.springframework.aop, + org.springframework.aop.framework, + org.springframework.beans.factory.annotation, + org.springframework.beans.factory.config, + org.springframework.context, + org.springframework.remoting.rmi, + org.springframework.scheduling.concurrent, + org.springframework.scheduling.config, + org.springframework.scheduling.support, + org.springframework.scheduling.timer, + * + + + + + + bsh, + com.caucho.burlap.client, + com.caucho.burlap.io, + com.caucho.burlap.server, + com.caucho.hessian, + com.caucho.hessian.client, + com.caucho.hessian.io, + com.caucho.hessian.server, + com.hazelcast.*, + com.ibm.wsspi.uow, + com.jamonapi, + com.jcraft.jzlib, + com.jcraft.jzlib.*, + com.sun.net.httpserver, + com.sun.syndication.feed, + com.sun.syndication.feed.atom, + com.sun.syndication.feed.rss, + com.sun.syndication.io, + com.sun.xml.fastinfoset.sax, + com.sun.xml.fastinfoset.stax, + edu.emory.mathcs.backport.java.util.concurrent, + groovy.lang, + javax.annotation, + javax.crypto, + javax.crypto.*, + javax.crypto.interfaces.*, + javax.crypto.spec, + javax.crypto.spec.*, + javax.ejb, + javax.el, + javax.faces.application, + javax.faces.component, + javax.faces.context, + javax.faces.el, + javax.faces.event, + javax.imageio, + javax.imageio.metadata, + javax.imageio.stream, + javax.inject, + javax.interceptor, + javax.jms, + javax.jws, + javax.management, + javax.management.modelmbean, + javax.management.openmbean, + javax.management.remote, + javax.naming, + javax.naming.spi, + javax.net, + javax.net.ssl, + javax.persistence.spi, + javax.portlet, + javax.resource, + javax.resource.cci, + javax.resource.spi, + javax.resource.spi.endpoint, + javax.resource.spi.work, + javax.rmi, + javax.security.auth, + javax.security.auth.callback, + javax.security.auth.login, + javax.security.auth.x500, + javax.servlet, + javax.servlet.descriptor, + javax.servlet.http, + javax.servlet.jsp, + javax.servlet.jsp.el, + javax.servlet.jsp.tagext, + javax.transaction, + javax.transaction.xa, + javax.validation, + javax.validation.bootstrap, + javax.validation.metadata, + javax.validation.spi, + javax.ws.rs.*, + javax.xml.datatype, + javax.xml.namespace, + javax.xml.parsers, + javax.xml.parsers.*, + javax.xml.rpc, + javax.xml.rpc.server, + javax.xml.rpc.soap, + javax.xml.soap, + javax.xml.transform, + javax.xml.transform.dom, + javax.xml.transform.sax, + javax.xml.transform.stax, + javax.xml.transform.stream, + javax.xml.validation, + javax.xml.ws, + javax.xml.ws.handler, + javax.xml.ws.soap, + javax.xml.xpath, + junit.framework, + junit.textui, + net.sf.cglib.asm, + net.sf.cglib.core, + net.sf.cglib.proxy, + net.sf.cglib.transform.impl, + org.apache.abdera, + org.apache.abdera.factory, + org.apache.abdera.model, + org.apache.abdera.parser, + org.apache.abdera.writer, + org.apache.commons.fileupload, + org.apache.commons.fileupload.disk, + org.apache.commons.fileupload.servlet, + org.apache.commons.lang, + org.apache.commons.lang.builder, + org.apache.commons.pool, + org.apache.commons.pool.impl, + org.apache.cxf.aegis, + org.apache.cxf.aegis.type, + org.apache.geronimo.osgi.registry.api, + org.apache.log, + org.apache.log4j, + org.apache.log4j.spi, + org.apache.xml.resolver, + org.apache.xml.resolver.helpers, + org.apache.xml.resolver.tools, + org.apache.xmlbeans, + org.aspectj.bridge, + org.aspectj.lang, + org.aspectj.lang.annotation, + org.aspectj.lang.reflect, + org.aspectj.runtime.internal, + org.aspectj.util, + org.aspectj.weaver, + org.aspectj.weaver.ast, + org.aspectj.weaver.bcel, + org.aspectj.weaver.internal.tools, + org.aspectj.weaver.loadtime, + org.aspectj.weaver.patterns, + org.aspectj.weaver.reflect, + org.aspectj.weaver.tools, + org.codehaus.groovy.control, + org.codehaus.jackson, + org.codehaus.jackson.map, + org.codehaus.jackson.map.type, + org.codehaus.jackson.type, + org.hibernate, + org.hibernate.cache, + org.hibernate.cache.access, + org.hibernate.cache.entry, + org.hibernate.cache.impl.bridge, + org.hibernate.cfg,org.hibernate.classic, + org.hibernate.engine, + org.hibernate.util, + org.hibernate.validator.messageinterpolation, + org.hibernate.validator.resourceloading, + org.ietf.jgss.*, + org.joda.time, + org.joda.time.format, + org.jruby, + org.jruby.ast, + org.jruby.exceptions, + org.jruby.javasupport, + org.jruby.runtime, + org.jruby.runtime.builtin, + org.junit, + org.jvnet.fastinfoset, + org.jvnet.staxex, + org.mockito, + org.objectweb.asm,org.omg.CORBA, + org.osgi.framework, + org.osgi.service.event, + org.osgi.util.tracker, + org.relaxng.datatype, + org.slf4j.*, + org.springframework.instrument, + org.springframework.osgi.context, + org.springframework.oxm, + org.w3c.dom, + org.w3c.dom.*, + org.xml.sax, + org.xml.sax.ext, + org.xml.sax.helpers + + + + + + com.alu.e3.common.osgi.api;-split-package:=merge-first, + com.alu.e3.gateway.*;-split-package:=merge-first, + com.alu.e3.rate.model;-split-package:=merge-first + + + + com.alu.e3, + com.alu.e3.common.logging + + + target/classes + + *;scope=runtime + + + + + + + diff --git a/exposure-engine/auth-manager/pom.xml b/exposure-engine/auth-manager/pom.xml new file mode 100644 index 0000000..02d8075 --- /dev/null +++ b/exposure-engine/auth-manager/pom.xml @@ -0,0 +1,73 @@ + + + 4.0.0 + + + exposure-engine + com.alu.e3 + 1.0.1 + .. + + + auth-manager + E3 Auth Manager + http://www.alcatel-lucent.com + + + jar + + + + org.apache.httpcomponents + httpclient-osgi + 4.1.2 + provided + + + org.apache.camel + camel-http + 2.6.0-fuse-01-09 + provided + + + tools + com.sun + + + + + org.springframework + spring-test + 3.0.5.RELEASE + compile + + + org.springframework + spring-beans + 3.0.5.RELEASE + compile + + + com.alu.e3 + gateway-common + ${project.version} + jar + provided + + + com.alu.e3 + common + ${project.version} + jar + provided + + + org.mockito + mockito-core + 1.9.0 + test + + + + diff --git a/exposure-engine/auth-manager/src/main/java/com/alu/e3/auth/AuthHttpHeaders.java b/exposure-engine/auth-manager/src/main/java/com/alu/e3/auth/AuthHttpHeaders.java new file mode 100644 index 0000000..01327f0 --- /dev/null +++ b/exposure-engine/auth-manager/src/main/java/com/alu/e3/auth/AuthHttpHeaders.java @@ -0,0 +1,26 @@ +/** + * Copyright © 2012 Alcatel-Lucent. + * + * See the NOTICE file distributed with this work for additional + * information regarding copyright ownership. + * Licensed to you 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 com.alu.e3.auth; + +public enum AuthHttpHeaders { + E3_APP_IDENTITY, + E3_USERNAME, + E3_AUTHENTICATED, + Authorization; +} diff --git a/exposure-engine/auth-manager/src/main/java/com/alu/e3/auth/AuthHttpQueryParameters.java b/exposure-engine/auth-manager/src/main/java/com/alu/e3/auth/AuthHttpQueryParameters.java new file mode 100644 index 0000000..7e6a9d8 --- /dev/null +++ b/exposure-engine/auth-manager/src/main/java/com/alu/e3/auth/AuthHttpQueryParameters.java @@ -0,0 +1,25 @@ +/** + * Copyright © 2012 Alcatel-Lucent. + * + * See the NOTICE file distributed with this work for additional + * information regarding copyright ownership. + * Licensed to you 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 com.alu.e3.auth; + +public enum AuthHttpQueryParameters { + + key; // used for authKey authentication method + +} diff --git a/exposure-engine/auth-manager/src/main/java/com/alu/e3/auth/access/DataAccessRuntimeException.java b/exposure-engine/auth-manager/src/main/java/com/alu/e3/auth/access/DataAccessRuntimeException.java new file mode 100644 index 0000000..316a9c5 --- /dev/null +++ b/exposure-engine/auth-manager/src/main/java/com/alu/e3/auth/access/DataAccessRuntimeException.java @@ -0,0 +1,38 @@ +/** + * Copyright © 2012 Alcatel-Lucent. + * + * See the NOTICE file distributed with this work for additional + * information regarding copyright ownership. + * Licensed to you 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 com.alu.e3.auth.access; + +public class DataAccessRuntimeException extends RuntimeException { + + + /** + * Generated serial version UID + */ + private static final long serialVersionUID = 510993039088136958L; + + /** + * Constructor + * @param message + * @param cause + */ + public DataAccessRuntimeException(String message, Throwable cause) { + super(message, cause); + } + +} diff --git a/exposure-engine/auth-manager/src/main/java/com/alu/e3/auth/access/IAuthDataAccess.java b/exposure-engine/auth-manager/src/main/java/com/alu/e3/auth/access/IAuthDataAccess.java new file mode 100644 index 0000000..bf7e249 --- /dev/null +++ b/exposure-engine/auth-manager/src/main/java/com/alu/e3/auth/access/IAuthDataAccess.java @@ -0,0 +1,34 @@ +/** + * Copyright © 2012 Alcatel-Lucent. + * + * See the NOTICE file distributed with this work for additional + * information regarding copyright ownership. + * Licensed to you 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 com.alu.e3.auth.access; + +import com.alu.e3.common.camel.AuthReport; +import com.alu.e3.common.tools.CanonicalizedIpAddress; + +/** + * Interface IAuthDataAccess + */ +public interface IAuthDataAccess { + public AuthReport checkAllowed(String apiId); + public AuthReport checkAllowed(String authKey, String apiId); + public AuthReport checkAllowed(CanonicalizedIpAddress ip, String apiId); + public AuthReport checkAllowed(String username, String password, String apiId); + public AuthReport checkAllowed(String username, String passwordDigest, boolean isPasswordText, String nonce, String created, String apiId); + public AuthReport checkOAuthAllowed(String clientId, String clientSecret, String apiId); +} diff --git a/exposure-engine/auth-manager/src/main/java/com/alu/e3/auth/access/data/DataManagerAccess.java b/exposure-engine/auth-manager/src/main/java/com/alu/e3/auth/access/data/DataManagerAccess.java new file mode 100644 index 0000000..a81213d --- /dev/null +++ b/exposure-engine/auth-manager/src/main/java/com/alu/e3/auth/access/data/DataManagerAccess.java @@ -0,0 +1,210 @@ +/** + * Copyright © 2012 Alcatel-Lucent. + * + * See the NOTICE file distributed with this work for additional + * information regarding copyright ownership. + * Licensed to you 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 com.alu.e3.auth.access.data; + +import java.util.List; + +import com.alu.e3.auth.access.IAuthDataAccess; +import com.alu.e3.common.camel.AuthIdentity; +import com.alu.e3.common.camel.AuthReport; +import com.alu.e3.common.logging.Category; +import com.alu.e3.common.logging.CategoryLogger; +import com.alu.e3.common.logging.CategoryLoggerFactory; +import com.alu.e3.common.osgi.api.IDataManager; +import com.alu.e3.common.tools.CanonicalizedIpAddress; +import com.alu.e3.data.model.Api; +import com.alu.e3.data.model.Auth; +import com.alu.e3.data.model.CallDescriptor; +import com.alu.e3.data.model.enumeration.StatusType; + +public class DataManagerAccess implements IAuthDataAccess { + + private static final CategoryLogger logger = CategoryLoggerFactory.getLogger(DataManagerAccess.class, Category.DMGR); + + private IDataManager dataManager; + + public DataManagerAccess() {} + + /** + * @return the dataManager + */ + public IDataManager getDataManager() { + return dataManager; + } + + /** + * @param dataManager the dataManager to set + */ + public void setDataManager(IDataManager dataManager) { + this.dataManager = dataManager; + } + + @Override + public AuthReport checkAllowed(String apiId) { + + AuthReport authReport = new AuthReport(); + + // get api + Api api = this.dataManager.getApiById(apiId, false); + + if(api != null) { + + // check if the API is active (status) + authReport.setApiActive((api.getStatus() == StatusType.ACTIVE)); + + if(authReport.isApiActive()) { + + List descriptors = this.dataManager.getMatchingPolicies(api); + + if(descriptors != null) { + authReport.setAuthIdentity(new AuthIdentity()); + authReport.getAuthIdentity().setApi(api); + authReport.getAuthIdentity().getCallDescriptors().addAll(descriptors); + } else { + logger.debug("NoAuth method is not enabled"); + authReport.setNotAuthorized(true); + } + } + + } else { + logger.debug("No api found " + apiId); + authReport.setApiNotFound(true); + } + + + return authReport; + } + + @Override + public AuthReport checkAllowed(String authKey, String apiId) { + + logger.debug("Checking AuthKey [" + authKey + "] for Api [" + apiId + "]"); + Auth auth = this.dataManager.getAuthByAuthKey(authKey); + + return getAuthReport(apiId, auth); + } + + @Override + public AuthReport checkAllowed(CanonicalizedIpAddress ip, String apiId) { + + logger.debug("Checking authentication for IP address [" + ip.getIp() + "] for Api [" + apiId + "]"); + Auth auth = this.dataManager.getAuthByIP(ip.getIp()); + + return getAuthReport(apiId, auth); + } + + @Override + public AuthReport checkAllowed(String username, String password, String apiId) { + + logger.debug("Try authentication for username [" + username + "] and password [" + password + "] for Api [" + apiId + "]"); + Auth auth = this.dataManager.getAuthByUserPass(username, password); + + return getAuthReport(apiId, auth); + } + + @Override + public AuthReport checkAllowed(String username, String passwordDigest, boolean isPasswordText, String nonce, String created, String apiId) { + + logger.debug("Try authentication for username [" + username + "] for Api [" + apiId + "]"); + Auth auth = this.dataManager.getWsseAuth(username, passwordDigest, isPasswordText, nonce, created); + + return getAuthReport(apiId, auth); + } + + @Override + public AuthReport checkOAuthAllowed(String clientId, String clientSecret, String apiId) { + + logger.debug("Try authentication for cliendId [" + clientId + "] for Api [" + apiId + "]"); + Auth auth = this.dataManager.getAuthByOAuth(clientId, clientSecret); + + return getAuthReport(apiId, auth); + } + + + /** + * Gets the AuthReport from an API id and Auth + * @param apiId + * @param auth + * @return authReport instance + */ + private AuthReport getAuthReport(String apiId, Auth auth) { + + AuthReport authReport = new AuthReport(); + + // get api + Api api = this.dataManager.getApiById(apiId, false); + + if(api != null) { + + // check if the API is active (status) + authReport.setApiActive((api.getStatus() == StatusType.ACTIVE)); + + if(authReport.isApiActive()) { + + List descriptors = null; + + if(auth != null) { + + // with auth + descriptors = this.dataManager.getMatchingPolicies(api, auth); + + if (descriptors != null) { + + // check if a policy exists + boolean foundPolicy = false; + for (CallDescriptor callDescriptor : descriptors) { + if (callDescriptor.getPolicy() != null) { + foundPolicy = true; + break; + } + } + + if (foundPolicy) { + authReport.setAuthIdentity(new AuthIdentity()); + authReport.getAuthIdentity().setApi(api); + authReport.getAuthIdentity().setAuth(auth); + authReport.getAuthIdentity().getCallDescriptors().addAll(descriptors); + } else { + logger.debug("No policy found"); + authReport.setHasNoPolicy(true); + } + + } else { + logger.debug("Auth does not match with API"); + authReport.setNotAuthorized(true); + } + } else { + logger.debug("No auth found for API"); + authReport.setAuthNotFound(true); + } + + } + + } else { + logger.debug("No api found " + apiId); + authReport.setApiNotFound(true); + } + + return authReport; + } + + + + +} diff --git a/exposure-engine/auth-manager/src/main/java/com/alu/e3/auth/access/file/FileData.java b/exposure-engine/auth-manager/src/main/java/com/alu/e3/auth/access/file/FileData.java new file mode 100644 index 0000000..b722452 --- /dev/null +++ b/exposure-engine/auth-manager/src/main/java/com/alu/e3/auth/access/file/FileData.java @@ -0,0 +1,295 @@ +/** + * Copyright © 2012 Alcatel-Lucent. + * + * See the NOTICE file distributed with this work for additional + * information regarding copyright ownership. + * Licensed to you 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 com.alu.e3.auth.access.file; + +import java.io.File; +import java.io.FileNotFoundException; +import java.net.URL; +import java.util.HashSet; +import java.util.Hashtable; +import java.util.Scanner; +import java.util.Set; + +import com.alu.e3.auth.access.IAuthDataAccess; +import com.alu.e3.common.camel.AuthReport; +import com.alu.e3.common.logging.Category; +import com.alu.e3.common.logging.CategoryLogger; +import com.alu.e3.common.logging.CategoryLoggerFactory; +import com.alu.e3.common.tools.CanonicalizedIpAddress; +import com.alu.e3.auth.model.AuthIdentityHelper; + +/** + * class FileData + */ +public class FileData implements IAuthDataAccess { + + /* slf4j logger */ + private static final CategoryLogger logger = CategoryLoggerFactory.getLogger(FileData.class, Category.AUTH); + + /* members */ + File fData = null; + boolean bUseOptimized = true; + Hashtable> hashTable = null; + + /** + * Constructor + * @param filePath + */ + public FileData(String filePath) { + + logger.debug("new FileData object with file:" + filePath); + this.fData = new File(filePath); + + /* Look up in the resources if absolute path not found. */ + if (!this.fData.exists()) + { + URL fileURL = getClass().getResource("/" + filePath); + if (fileURL != null) + this.fData = new File(fileURL.getPath()); + } + + /* Store data in memory. */ + if (bUseOptimized) { + hashTable = new Hashtable>(5); + + if (!this.fData.exists()) + return; + + Scanner scanner = null; + try{ + /* loop on each line. */ + scanner = new Scanner(this.fData); + while (scanner.hasNextLine()) { + String[] words = scanner.nextLine().split(" "); + if (words.length < 2) + continue; + Set set = new HashSet(); + for(int i=1; i < words.length ; i++){ + if( ! words[i].isEmpty()) + set.add(words[i]); + } + hashTable.put(words[0], set); + } + } catch (FileNotFoundException e) { + logger.error("An Error occured:" + e.getMessage()); + e.printStackTrace(); + } + finally{ + if (scanner != null) + scanner.close(); + } + } + + } + + /** + * checkAppKey + * check if an auth key and an app id match. + */ + @Override + public AuthReport checkAllowed(String authKey, String apiId) { + + AuthReport authReport = new AuthReport(); + + logger.debug("Lookup if AuthKey:" + authKey + " is associated with appId:" + apiId); + + String appId = findString(apiId, authKey); + + if(appId != null) { + + AuthIdentityHelper authIdentityHelper = new AuthIdentityHelper(); + + authIdentityHelper.setApi(apiId); + authIdentityHelper.setAppId(appId); + authIdentityHelper.setAuth(authKey); + + authReport.setAuthIdentity( authIdentityHelper.getAuthIdentity()); + authReport.setApiActive(true); + + } else { + authReport.setNotAuthorized(true); + } + + return authReport; + } + + @Override + public AuthReport checkAllowed(String username, String password, String apiId) { + + AuthReport authReport = new AuthReport(); + + logger.debug("Lookup if username:password: " + username+":"+password + " is associated with appId:" + apiId); + + String appId = findString(apiId, username+":"+password); + + if(appId != null) { + + AuthIdentityHelper authIdentityHelper = new AuthIdentityHelper(); + + authIdentityHelper.setApi(apiId); + authIdentityHelper.setAppId(appId); + authIdentityHelper.setAuth(username, password); + + authReport.setAuthIdentity( authIdentityHelper.getAuthIdentity()); + authReport.setApiActive(true); + + } else { + authReport.setNotAuthorized(true); + } + + return authReport; + } + + @Override + public AuthReport checkAllowed(String username, String passwordDigest, boolean isPasswordText, String nonce, String created, String apiId) { + // TODO: Implement FileDate to support WSSE + return checkAllowed(username, "", apiId); + } + + @Override + public AuthReport checkAllowed(CanonicalizedIpAddress ipCanonicalized, String apiId) { + + AuthReport authReport = new AuthReport(); + + String ip = ipCanonicalized.getIp(); + + String appId = findString(apiId, ip); + + if(appId != null) { + + AuthIdentityHelper authIdentityHelper = new AuthIdentityHelper(); + + authIdentityHelper.setApi(apiId); + authIdentityHelper.setAppId(appId); + authIdentityHelper.setAuth(ipCanonicalized); + + authReport.setAuthIdentity( authIdentityHelper.getAuthIdentity()); + authReport.setApiActive(true); + + } else { + authReport.setNotAuthorized(true); + } + + return authReport; + } + + + + @Override + public AuthReport checkAllowed(String apiId) { + + AuthReport authReport = new AuthReport(); + + logger.debug("Lookup if noauth is true for appId:" + apiId); + + String appId = findString(apiId, "noauth:true"); + + if(appId != null) { + + AuthIdentityHelper authIdentityHelper = new AuthIdentityHelper(); + + authIdentityHelper.setApi(apiId); + authIdentityHelper.setAppId(appId); + + authReport.setAuthIdentity( authIdentityHelper.getAuthIdentity()); + authReport.setApiActive(true); + + } else { + authReport.setNotAuthorized(true); + } + + return authReport; + } + + @Override + public AuthReport checkOAuthAllowed(String clientId, String clientSecret, String apiId) { + + AuthReport authReport = new AuthReport(); + + logger.debug("Lookup if clientId:clientSecret: " + clientId+":"+clientSecret + " is associated with appId:" + apiId); + + String appId = findString(apiId, clientId+":"+clientSecret); + + if(appId != null) { + + AuthIdentityHelper authIdentityHelper = new AuthIdentityHelper(); + + authIdentityHelper.setApi(apiId); + authIdentityHelper.setAppId(appId); + authIdentityHelper.setOAuth(clientId, clientSecret); + + authReport.setAuthIdentity( authIdentityHelper.getAuthIdentity()); + authReport.setApiActive(true); + + } else { + authReport.setNotAuthorized(true); + } + + return authReport; + } + + String findString(String key, String value) { + /* Optimized */ + if (hashTable != null) + { + Set values = hashTable.get(key); + if(values != null) { + for(String s : values){ + if(s != null && s.equals(value)) + return key; + } + } + } + + /* If no database, return null. */ + else if (this.fData.exists() == false){ + // Do nothing + return null; + } + else { + Scanner scanner = null; + try{ + /* loop on each line. */ + scanner = new Scanner(this.fData); + while (scanner.hasNextLine()) { + String[] words = scanner.nextLine().split(" "); + if (words.length < 2) + continue; + if (words[0].equals(key)){ + for(int i=1; i < words.length ; i++){ + if(words[i].equals(value)){ + return words[i]; + } + } + } + } + } catch (FileNotFoundException e) { + logger.error("An Error occured:" + e.getMessage()); + e.printStackTrace(); + } + finally{ + if (scanner != null) + scanner.close(); + } + } + return null; + } + + +} diff --git a/exposure-engine/auth-manager/src/main/java/com/alu/e3/auth/camel/component/AuthComponent.java b/exposure-engine/auth-manager/src/main/java/com/alu/e3/auth/camel/component/AuthComponent.java new file mode 100644 index 0000000..7474d77 --- /dev/null +++ b/exposure-engine/auth-manager/src/main/java/com/alu/e3/auth/camel/component/AuthComponent.java @@ -0,0 +1,82 @@ +/** + * Copyright © 2012 Alcatel-Lucent. + * + * See the NOTICE file distributed with this work for additional + * information regarding copyright ownership. + * Licensed to you 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 com.alu.e3.auth.camel.component; + +import java.util.ArrayList; +import java.util.HashMap; +import java.util.Iterator; +import java.util.List; +import java.util.Map; +import java.util.Map.Entry; + +import org.apache.camel.CamelContext; +import org.apache.camel.CamelException; +import org.apache.camel.Endpoint; +import org.apache.camel.impl.DefaultComponent; +import org.springframework.context.annotation.Scope; +import org.springframework.stereotype.Component; + +import com.alu.e3.auth.camel.endpoint.AuthEndpoint; +import com.alu.e3.auth.executor.IAuthExecutor; +import com.alu.e3.auth.executor.IAuthExecutorFactory; + +@Component +@Scope("singleton") +public class AuthComponent extends DefaultComponent { + + private Map factories = new HashMap(); + + public AuthComponent() {} + + public AuthComponent(CamelContext camelContext) { + super(camelContext); + } + + @Override + protected Endpoint createEndpoint(String uri, String remaining, Map parameters) throws Exception { + if(!parameters.containsKey("apiId")) + throw new CamelException("apiId parameter is missing"); + + String apiId = getAndRemoveParameter(parameters, "apiId", String.class); + + List executors = new ArrayList(); + + Iterator> it = factories.entrySet().iterator(); + while (it.hasNext()) { + Map.Entry pairs = it.next(); + if(parameters.containsKey(pairs.getKey())){ + Boolean key = getAndRemoveParameter(parameters, pairs.getKey(), Boolean.class); + if(key != null && key.equals(Boolean.TRUE)){ + IAuthExecutor executor = pairs.getValue().getExecutor(this, apiId, parameters); + executors.add(executor); + } + } + } + + return new AuthEndpoint(uri, this, executors); + } + + public void registerExecutorFactory(String name, IAuthExecutorFactory executor) { + factories.put(name, executor); + } + + public void unregisterExecutorFactory(String name) { + factories.remove(name); + } +} diff --git a/exposure-engine/auth-manager/src/main/java/com/alu/e3/auth/camel/endpoint/AuthEndpoint.java b/exposure-engine/auth-manager/src/main/java/com/alu/e3/auth/camel/endpoint/AuthEndpoint.java new file mode 100644 index 0000000..df8e828 --- /dev/null +++ b/exposure-engine/auth-manager/src/main/java/com/alu/e3/auth/camel/endpoint/AuthEndpoint.java @@ -0,0 +1,68 @@ +/** + * Copyright © 2012 Alcatel-Lucent. + * + * See the NOTICE file distributed with this work for additional + * information regarding copyright ownership. + * Licensed to you 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 com.alu.e3.auth.camel.endpoint; + +import java.util.List; + +import org.apache.camel.CamelException; +import org.apache.camel.Component; +import org.apache.camel.Consumer; +import org.apache.camel.Processor; +import org.apache.camel.Producer; +import org.apache.camel.impl.DefaultEndpoint; + +import com.alu.e3.auth.camel.producer.AuthProducer; +import com.alu.e3.auth.executor.IAuthExecutor; + +public class AuthEndpoint extends DefaultEndpoint { + + private String uri; + + private List executors; + + public AuthEndpoint(String uri, Component component, List executors) throws CamelException { + super(uri, component); + this.uri = uri; + + this.executors = executors; + } + + @Override + public String getEndpointUri() { + return uri; + } + + @Override + public Producer createProducer() throws Exception { + return new AuthProducer(this, executors); + } + + @Override + public Consumer createConsumer(Processor processor) throws Exception { + // TODO Auto-generated method stub + return null; + } + + @Override + public boolean isSingleton() { + // TODO Auto-generated method stub + return false; + } + +} diff --git a/exposure-engine/auth-manager/src/main/java/com/alu/e3/auth/camel/processor/AuthPostProcessor.java b/exposure-engine/auth-manager/src/main/java/com/alu/e3/auth/camel/processor/AuthPostProcessor.java new file mode 100644 index 0000000..a68cea6 --- /dev/null +++ b/exposure-engine/auth-manager/src/main/java/com/alu/e3/auth/camel/processor/AuthPostProcessor.java @@ -0,0 +1,29 @@ +/** + * Copyright © 2012 Alcatel-Lucent. + * + * See the NOTICE file distributed with this work for additional + * information regarding copyright ownership. + * Licensed to you 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 com.alu.e3.auth.camel.processor; + +import org.apache.camel.Exchange; +import org.apache.camel.Processor; + +public class AuthPostProcessor implements Processor { + + @Override + public void process(Exchange exchange) throws Exception { + } +} diff --git a/exposure-engine/auth-manager/src/main/java/com/alu/e3/auth/camel/producer/AuthProducer.java b/exposure-engine/auth-manager/src/main/java/com/alu/e3/auth/camel/producer/AuthProducer.java new file mode 100644 index 0000000..22fd9de --- /dev/null +++ b/exposure-engine/auth-manager/src/main/java/com/alu/e3/auth/camel/producer/AuthProducer.java @@ -0,0 +1,150 @@ +/** + * Copyright © 2012 Alcatel-Lucent. + * + * See the NOTICE file distributed with this work for additional + * information regarding copyright ownership. + * Licensed to you 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 com.alu.e3.auth.camel.producer; + +import java.util.Iterator; +import java.util.List; + +import org.apache.camel.Endpoint; +import org.apache.camel.Exchange; +import org.apache.camel.impl.DefaultProducer; + +import com.alu.e3.auth.camel.endpoint.AuthEndpoint; +import com.alu.e3.auth.executor.IAuthExecutor; +import com.alu.e3.auth.model.AuthType; +import com.alu.e3.common.camel.AuthIdentity; +import com.alu.e3.common.camel.AuthReport; +import com.alu.e3.common.camel.ExchangeConstantKeys; +import com.alu.e3.common.logging.Category; +import com.alu.e3.common.logging.CategoryLogger; +import com.alu.e3.common.logging.CategoryLoggerFactory; +import com.alu.e3.gateway.common.camel.exception.GatewayException; +import com.alu.e3.gateway.common.camel.exception.GatewayExceptionCode; +import com.alu.e3.tdr.TDRConstant; +import com.alu.e3.tdr.TDRDataService; + +public class AuthProducer extends DefaultProducer { + + private static final CategoryLogger logger = CategoryLoggerFactory.getLogger(AuthProducer.class, Category.AUTH); + + private List executors; + + + public AuthProducer(Endpoint endpoint, List executors) { + super(endpoint); + if(!(endpoint instanceof AuthEndpoint)){ + throw new RuntimeException("AuthProducer does not support endpoint type:"+endpoint.getClass().getName()); + } + + this.executors = executors; + } + + @Override + public void process(Exchange exchange) throws Exception { + + logger.debug("Authentication Processor is excuted"); + + AuthType authType = AuthType.NO_AUTH; + + boolean isBasicEnabled = false; + boolean isAllowed = false; + boolean isApiActive = false; + boolean isStatusChecked = false; + AuthIdentity authIdentity = null; + + Iterator it = executors.iterator(); + while(!isAllowed && it.hasNext()) { + + IAuthExecutor executor = it.next(); + AuthReport authReport = executor.checkAllowed(exchange); + isAllowed = authReport.isAllowed(); + + if(!isStatusChecked) { + isStatusChecked = authReport.isStatusChecked(); + isApiActive = authReport.isApiActive(); + } + + if(!isBasicEnabled) { + // Check that BasicAuth method is not enabled + GatewayExceptionCode code = executor.getErrorCode(); + if(code == GatewayExceptionCode.AUTHORIZATION_BASIC) { + isBasicEnabled = true; + } + } + + if(isAllowed) { + authIdentity = authReport.getAuthIdentity(); + } + + // The last executor + authType = executor.getType(); + } + + + if(isAllowed) { + logger.debug("Request allowed to use this Api"); + } else { + logger.debug("Request not allowed to use this Api"); + manageError(isStatusChecked, isApiActive, isBasicEnabled, exchange); + } + + // Put this in the exchange for TDRs + TDRDataService.setTxTDRProperty(TDRConstant.AUTHENTICATION, authType.value(), exchange); + + // Set the authentication result in the exchange + exchange.setProperty(ExchangeConstantKeys.E3_AUTH_METHOD.toString(), authType.value()); + exchange.setProperty(ExchangeConstantKeys.E3_AUTH_IDENTITY.toString(), authIdentity); + } + + private void manageError(boolean isStatusChecked, boolean isApiActive, boolean isBasicEnabled, Exchange exchange) { + + GatewayExceptionCode authErrorCode = null; + String authErrorMessage = null; + + if(isStatusChecked) { + + if(isApiActive) { + if(isBasicEnabled) { + logger.debug("The API is active but an authorization is required"); + authErrorCode = GatewayExceptionCode.AUTHORIZATION_BASIC; + authErrorMessage = "Authorization required"; + } else { + logger.debug("The API is active but the request is not allowed"); + authErrorCode = GatewayExceptionCode.AUTHORIZATION; + authErrorMessage = "Not Authorized"; + } + + } else { + logger.debug("The API is not active, the request is rejected"); + authErrorCode = GatewayExceptionCode.API_NOT_ACTIVATED; + authErrorMessage = "API not active"; + } + + } else { + // the status of the API is not trusted, them we reject the call + logger.debug("The status of the API is not trusted, the request is rejected"); + authErrorCode = GatewayExceptionCode.AUTHORIZATION; + authErrorMessage = "Not Authorized"; + } + + Exception exception = new GatewayException(authErrorCode, authErrorMessage); + exchange.setException(exception); + } + +} diff --git a/exposure-engine/auth-manager/src/main/java/com/alu/e3/auth/executor/AppKeyExecutor.java b/exposure-engine/auth-manager/src/main/java/com/alu/e3/auth/executor/AppKeyExecutor.java new file mode 100644 index 0000000..d83c831 --- /dev/null +++ b/exposure-engine/auth-manager/src/main/java/com/alu/e3/auth/executor/AppKeyExecutor.java @@ -0,0 +1,142 @@ +/** + * Copyright © 2012 Alcatel-Lucent. + * + * See the NOTICE file distributed with this work for additional + * information regarding copyright ownership. + * Licensed to you 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 com.alu.e3.auth.executor; + +import java.util.Map; + +import org.apache.camel.Exchange; + +import com.alu.e3.auth.access.DataAccessRuntimeException; +import com.alu.e3.auth.access.IAuthDataAccess; +import com.alu.e3.auth.model.AuthType; +import com.alu.e3.common.camel.AuthReport; +import com.alu.e3.common.camel.ExchangeConstantKeys; +import com.alu.e3.common.logging.Category; +import com.alu.e3.common.logging.CategoryLogger; +import com.alu.e3.common.logging.CategoryLoggerFactory; +import com.alu.e3.gateway.common.camel.exception.GatewayExceptionCode; + +/** + * class AppKeyAuthProtocol + */ +public class AppKeyExecutor implements IAuthExecutor{ + + private static final CategoryLogger logger = CategoryLoggerFactory.getLogger(AppKeyExecutor.class, Category.AUTH); + + private String keyName = ""; + private String headerName = ""; + private String apiId = ""; + private IAuthDataAccess dataAccess; + + /** + * Constructor + */ + public AppKeyExecutor(String keyname, String headerName, String apiID, IAuthDataAccess dataAccess) { + this.keyName = keyname; + this.headerName = headerName; + this.apiId = apiID; + this.dataAccess = dataAccess; + } + + /** + * Look for the value in the http query and removes it. + * @param exchange + * @param value + */ + private void removeHttpQueryValue(Exchange exchange, String value) { + String query = exchange.getIn().getHeader(Exchange.HTTP_QUERY, String.class); + + if (query != null) { + + if (query.contains("&"+value)) { + query = query.replace("&"+value, ""); + } + else if (query.contains(value+"&")) { + query = query.replace(value+"&", ""); + } + else if (query.contains(value)) { + // on its own + query = null; + } + + exchange.getIn().setHeader(Exchange.HTTP_QUERY, query); + // if we use the following line instead then we lose all the other header values + //exchange.getOut().setHeader(Exchange.HTTP_QUERY, query); + } + } + + @Override + public AuthReport checkAllowed(Exchange exchange){ + + AuthReport authReport = new AuthReport(); + Object keyObj = null; + + Map parameters = exchange.getProperty(ExchangeConstantKeys.E3_REQUEST_PARAMETERS.toString(), Map.class); + if (parameters == null) { + logger.error("Request parameters not set"); + authReport.setBadRequest(true); + } else { + + keyObj = parameters.get(keyName); + if (keyObj == null) { // No parameter by keyName, checking for a header "headerName" + keyObj = exchange.getIn().getHeader(headerName, String.class); + if (keyObj == null) { + // Abort + logger.debug("Unable to find url parameter or header matching the provisioned api key name"); + authReport.setBadRequest(true); + } + } + } + + // if not a bad request + if(!authReport.isBadRequest()) { + + String authKey = keyObj.toString(); + logger.debug("authKey= " + authKey); + + // remove the credential from URL + removeHttpQueryValue(exchange, keyName+"="+authKey); + + // remove the credential from Header + exchange.getIn().removeHeader(headerName); + + //Call AuthManager + try { + authReport = dataAccess.checkAllowed(authKey, apiId); + } catch(DataAccessRuntimeException e) { + logger.error("Data Access Issue", e); + } catch(Exception e) { + logger.error("Data Access Issue", e); + } + } + + return authReport; + } + + @Override + public AuthType getType() { + return AuthType.AUTHKEY; + } + + @Override + public GatewayExceptionCode getErrorCode() { + return GatewayExceptionCode.AUTHORIZATION; + } + +} diff --git a/exposure-engine/auth-manager/src/main/java/com/alu/e3/auth/executor/AppKeyExecutorFactory.java b/exposure-engine/auth-manager/src/main/java/com/alu/e3/auth/executor/AppKeyExecutorFactory.java new file mode 100644 index 0000000..d5f6377 --- /dev/null +++ b/exposure-engine/auth-manager/src/main/java/com/alu/e3/auth/executor/AppKeyExecutorFactory.java @@ -0,0 +1,71 @@ +/** + * Copyright © 2012 Alcatel-Lucent. + * + * See the NOTICE file distributed with this work for additional + * information regarding copyright ownership. + * Licensed to you 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 com.alu.e3.auth.executor; + +import java.util.Map; + +import org.apache.camel.impl.DefaultComponent; +import org.springframework.stereotype.Component; + +import com.alu.e3.auth.AuthHttpQueryParameters; +import com.alu.e3.auth.access.IAuthDataAccess; +import com.alu.e3.common.E3Constant; + +@Component +public class AppKeyExecutorFactory extends BaseExecutorFactory { + + protected IAuthDataAccess dataAccess; + + public AppKeyExecutorFactory() {} + + public IAuthDataAccess getDataAccess() { + return dataAccess; + } + + public void setDataAccess(IAuthDataAccess dataAccess) { + this.dataAccess = dataAccess; + } + + @Override + public IAuthExecutor getExecutor(DefaultComponent component, String apiId, Map parameters) { + String keyName = null; + if(parameters.containsKey("keyName")){ + keyName = component.getAndRemoveParameter(parameters, "keyName", String.class); + } + if(keyName == null){ + keyName = AuthHttpQueryParameters.key.toString(); + } + + String headerName = null; + if(parameters.containsKey("headerName")){ + headerName = component.getAndRemoveParameter(parameters, "headerName", String.class); + } + if(headerName == null){ + headerName = E3Constant.DEFAULT_APP_AUTHKEY_HEADER_NAME; + } + + return new AppKeyExecutor(keyName, headerName, apiId, dataAccess); + } + + @Override + public String getName() { + return "authKey"; + } + +} diff --git a/exposure-engine/auth-manager/src/main/java/com/alu/e3/auth/executor/BaseExecutorFactory.java b/exposure-engine/auth-manager/src/main/java/com/alu/e3/auth/executor/BaseExecutorFactory.java new file mode 100644 index 0000000..9c9409a --- /dev/null +++ b/exposure-engine/auth-manager/src/main/java/com/alu/e3/auth/executor/BaseExecutorFactory.java @@ -0,0 +1,33 @@ +/** + * Copyright © 2012 Alcatel-Lucent. + * + * See the NOTICE file distributed with this work for additional + * information regarding copyright ownership. + * Licensed to you 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 com.alu.e3.auth.executor; + +import com.alu.e3.auth.camel.component.AuthComponent; + +public abstract class BaseExecutorFactory implements IAuthExecutorFactory { + private AuthComponent auth; + + public void setAuthComponent(AuthComponent component) { + auth = component; + } + + public void init() { + auth.registerExecutorFactory(getName(), this); + } +} diff --git a/exposure-engine/auth-manager/src/main/java/com/alu/e3/auth/executor/HttpBasicExecutor.java b/exposure-engine/auth-manager/src/main/java/com/alu/e3/auth/executor/HttpBasicExecutor.java new file mode 100644 index 0000000..27324b9 --- /dev/null +++ b/exposure-engine/auth-manager/src/main/java/com/alu/e3/auth/executor/HttpBasicExecutor.java @@ -0,0 +1,100 @@ +/** + * Copyright © 2012 Alcatel-Lucent. + * + * See the NOTICE file distributed with this work for additional + * information regarding copyright ownership. + * Licensed to you 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 com.alu.e3.auth.executor; + +import org.apache.camel.Exchange; +import org.apache.commons.codec.binary.Base64; + +import com.alu.e3.auth.access.IAuthDataAccess; +import com.alu.e3.auth.model.AuthType; +import com.alu.e3.common.camel.AuthReport; +import com.alu.e3.common.logging.Category; +import com.alu.e3.common.logging.CategoryLogger; +import com.alu.e3.common.logging.CategoryLoggerFactory; +import com.alu.e3.gateway.common.camel.exception.GatewayExceptionCode; + +public class HttpBasicExecutor implements IAuthExecutor { + + private static final CategoryLogger logger = CategoryLoggerFactory.getLogger(HttpBasicExecutor.class, Category.AUTH); + + private IAuthDataAccess dataAccess; + private String apiId = ""; + + public HttpBasicExecutor(String apiId, IAuthDataAccess dataAcccess){ + this.apiId = apiId; + this.dataAccess = dataAcccess; + } + + @Override + public AuthReport checkAllowed(Exchange exchange) { + + AuthReport authReport = new AuthReport(); + + String authHeader = (String) exchange.getIn().getHeader("Authorization"); + + if(authHeader != null){ + String[] chunks = authHeader.split(" "); + + // Only expect two parts: the auth scheme and the user/pass encoding + if(chunks.length == 2){ + String scheme = chunks[0]; + if("Basic".equalsIgnoreCase(scheme)){ + String base64 = chunks[1]; + String decoded = new String(Base64.decodeBase64(base64.getBytes())); + chunks = decoded.split(":"); + if(chunks.length >= 2){ + String user = chunks[0]; + String pass = chunks[1]; + // Checks if the user is allowed to use this service + authReport = dataAccess.checkAllowed(user, pass, apiId); + } + else{ + logger.debug("Unable to decode user/pass"); + authReport.setBadRequest(true); + } + } + else{ + logger.debug("Auth scheme not Basic ("+scheme+"). Cannot authenticate request"); + authReport.setBadRequest(true); + } + } + else{ + logger.debug("Improperly formed authorization header:"+authHeader); + authReport.setBadRequest(true); + } + } + else{ + logger.debug("Http Basic Authentication Header is missing"); + authReport.setBadRequest(true); + } + + return authReport; + } + + @Override + public AuthType getType() { + return AuthType.BASIC; + } + + @Override + public GatewayExceptionCode getErrorCode() { + return GatewayExceptionCode.AUTHORIZATION_BASIC; + } + +} diff --git a/exposure-engine/auth-manager/src/main/java/com/alu/e3/auth/executor/HttpBasicExecutorFactory.java b/exposure-engine/auth-manager/src/main/java/com/alu/e3/auth/executor/HttpBasicExecutorFactory.java new file mode 100644 index 0000000..709f3dd --- /dev/null +++ b/exposure-engine/auth-manager/src/main/java/com/alu/e3/auth/executor/HttpBasicExecutorFactory.java @@ -0,0 +1,52 @@ +/** + * Copyright © 2012 Alcatel-Lucent. + * + * See the NOTICE file distributed with this work for additional + * information regarding copyright ownership. + * Licensed to you 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 com.alu.e3.auth.executor; + +import java.util.Map; + +import org.apache.camel.impl.DefaultComponent; +import org.springframework.stereotype.Component; + +import com.alu.e3.auth.access.IAuthDataAccess; + +@Component +public class HttpBasicExecutorFactory extends BaseExecutorFactory { + + protected IAuthDataAccess dataAccess; + + public HttpBasicExecutorFactory() {} + + public IAuthDataAccess getDataAccess() { + return dataAccess; + } + + public void setDataAccess(IAuthDataAccess dataAccess) { + this.dataAccess = dataAccess; + } + + @Override + public IAuthExecutor getExecutor(DefaultComponent component, String apiId, Map parameters) { + return new HttpBasicExecutor(apiId, dataAccess); + } + + @Override + public String getName() { + return "basic"; + } +} diff --git a/exposure-engine/auth-manager/src/main/java/com/alu/e3/auth/executor/IAuthExecutor.java b/exposure-engine/auth-manager/src/main/java/com/alu/e3/auth/executor/IAuthExecutor.java new file mode 100644 index 0000000..1dc9c68 --- /dev/null +++ b/exposure-engine/auth-manager/src/main/java/com/alu/e3/auth/executor/IAuthExecutor.java @@ -0,0 +1,31 @@ +/** + * Copyright © 2012 Alcatel-Lucent. + * + * See the NOTICE file distributed with this work for additional + * information regarding copyright ownership. + * Licensed to you 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 com.alu.e3.auth.executor; + +import org.apache.camel.Exchange; + +import com.alu.e3.auth.model.AuthType; +import com.alu.e3.common.camel.AuthReport; +import com.alu.e3.gateway.common.camel.exception.GatewayExceptionCode; + +public interface IAuthExecutor { + public AuthReport checkAllowed(Exchange exchange); + public AuthType getType(); + public GatewayExceptionCode getErrorCode(); +} diff --git a/exposure-engine/auth-manager/src/main/java/com/alu/e3/auth/executor/IAuthExecutorFactory.java b/exposure-engine/auth-manager/src/main/java/com/alu/e3/auth/executor/IAuthExecutorFactory.java new file mode 100644 index 0000000..c3d5963 --- /dev/null +++ b/exposure-engine/auth-manager/src/main/java/com/alu/e3/auth/executor/IAuthExecutorFactory.java @@ -0,0 +1,28 @@ +/** + * Copyright © 2012 Alcatel-Lucent. + * + * See the NOTICE file distributed with this work for additional + * information regarding copyright ownership. + * Licensed to you 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 com.alu.e3.auth.executor; + +import java.util.Map; + +import org.apache.camel.impl.DefaultComponent; + +public interface IAuthExecutorFactory { + public String getName(); + public IAuthExecutor getExecutor(DefaultComponent component, String apiId, Map parameters); +} diff --git a/exposure-engine/auth-manager/src/main/java/com/alu/e3/auth/executor/IpWhitelistExecutor.java b/exposure-engine/auth-manager/src/main/java/com/alu/e3/auth/executor/IpWhitelistExecutor.java new file mode 100644 index 0000000..f3df3aa --- /dev/null +++ b/exposure-engine/auth-manager/src/main/java/com/alu/e3/auth/executor/IpWhitelistExecutor.java @@ -0,0 +1,76 @@ +/** + * Copyright © 2012 Alcatel-Lucent. + * + * See the NOTICE file distributed with this work for additional + * information regarding copyright ownership. + * Licensed to you 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 com.alu.e3.auth.executor; + +import javax.servlet.http.HttpServletRequest; + +import org.apache.camel.Exchange; + +import com.alu.e3.auth.access.IAuthDataAccess; +import com.alu.e3.auth.model.AuthType; +import com.alu.e3.common.camel.AuthReport; +import com.alu.e3.common.logging.Category; +import com.alu.e3.common.logging.CategoryLogger; +import com.alu.e3.common.logging.CategoryLoggerFactory; +import com.alu.e3.common.tools.CanonicalizedIpAddress; +import com.alu.e3.gateway.common.camel.exception.GatewayExceptionCode; + +public class IpWhitelistExecutor implements IAuthExecutor { + + private static final CategoryLogger logger = CategoryLoggerFactory.getLogger(IpWhitelistExecutor.class, Category.AUTH); + + private String apiId; + private IAuthDataAccess dataAccess; + + + public IpWhitelistExecutor(String apiId, IAuthDataAccess dataAccess) { + this.apiId = apiId; + this.dataAccess = dataAccess; + } + + @Override + public AuthReport checkAllowed(Exchange exchange) { + + AuthReport authReport = new AuthReport(); + + logger.debug("Hit the IpWhitelistExecutor.isAllowed"); + + // magic Jetty stuff + HttpServletRequest request = (HttpServletRequest) exchange.getIn().getHeader(Exchange.HTTP_SERVLET_REQUEST); + + if(request != null) { + CanonicalizedIpAddress ip = new CanonicalizedIpAddress(request.getRemoteAddr()); + authReport = dataAccess.checkAllowed(ip, apiId); + } else { + authReport.setBadRequest(true); + } + + return authReport; + } + + @Override + public AuthType getType() { + return AuthType.IP_WHITE_LIST; + } + + @Override + public GatewayExceptionCode getErrorCode() { + return GatewayExceptionCode.AUTHORIZATION; + } +} diff --git a/exposure-engine/auth-manager/src/main/java/com/alu/e3/auth/executor/IpWhitelistExecutorFactory.java b/exposure-engine/auth-manager/src/main/java/com/alu/e3/auth/executor/IpWhitelistExecutorFactory.java new file mode 100644 index 0000000..6f3a777 --- /dev/null +++ b/exposure-engine/auth-manager/src/main/java/com/alu/e3/auth/executor/IpWhitelistExecutorFactory.java @@ -0,0 +1,52 @@ +/** + * Copyright © 2012 Alcatel-Lucent. + * + * See the NOTICE file distributed with this work for additional + * information regarding copyright ownership. + * Licensed to you 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 com.alu.e3.auth.executor; + +import java.util.Map; + +import org.apache.camel.impl.DefaultComponent; + +import com.alu.e3.auth.access.IAuthDataAccess; + + +public class IpWhitelistExecutorFactory extends BaseExecutorFactory { + + protected IAuthDataAccess dataAccess; + + public IpWhitelistExecutorFactory() {} + + public IAuthDataAccess getDataAccess() { + return dataAccess; + } + + public void setDataAccess(IAuthDataAccess dataAccess) { + this.dataAccess = dataAccess; + } + + @Override + public IAuthExecutor getExecutor(DefaultComponent component, String apiId, Map parameters) { + return new IpWhitelistExecutor(apiId, dataAccess); + } + + @Override + public String getName() { + return "ipList"; + } + +} diff --git a/exposure-engine/auth-manager/src/main/java/com/alu/e3/auth/executor/NoAuthExecutor.java b/exposure-engine/auth-manager/src/main/java/com/alu/e3/auth/executor/NoAuthExecutor.java new file mode 100644 index 0000000..581ba24 --- /dev/null +++ b/exposure-engine/auth-manager/src/main/java/com/alu/e3/auth/executor/NoAuthExecutor.java @@ -0,0 +1,60 @@ +/** + * Copyright © 2012 Alcatel-Lucent. + * + * See the NOTICE file distributed with this work for additional + * information regarding copyright ownership. + * Licensed to you 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 com.alu.e3.auth.executor; + +import org.apache.camel.Exchange; + +import com.alu.e3.auth.access.IAuthDataAccess; +import com.alu.e3.auth.model.AuthType; +import com.alu.e3.common.camel.AuthReport; +import com.alu.e3.common.logging.Category; +import com.alu.e3.common.logging.CategoryLogger; +import com.alu.e3.common.logging.CategoryLoggerFactory; +import com.alu.e3.gateway.common.camel.exception.GatewayExceptionCode; + +public class NoAuthExecutor implements IAuthExecutor { + + private static final CategoryLogger logger = CategoryLoggerFactory.getLogger(NoAuthExecutor.class, Category.AUTH); + + private String apiId; + private IAuthDataAccess dataAccess; + + public NoAuthExecutor(String apiId, IAuthDataAccess dataAccess) { + this.apiId = apiId; + this.dataAccess = dataAccess; + } + + + @Override + public AuthReport checkAllowed(Exchange exchange) { + logger.debug("Check if the API allows NoAuth"); + return this.dataAccess.checkAllowed(apiId); + } + + @Override + public AuthType getType() { + return AuthType.NO_AUTH; + } + + @Override + public GatewayExceptionCode getErrorCode() { + return GatewayExceptionCode.AUTHORIZATION; + } + +} diff --git a/exposure-engine/auth-manager/src/main/java/com/alu/e3/auth/executor/NoAuthExecutorFactory.java b/exposure-engine/auth-manager/src/main/java/com/alu/e3/auth/executor/NoAuthExecutorFactory.java new file mode 100644 index 0000000..2f3a623 --- /dev/null +++ b/exposure-engine/auth-manager/src/main/java/com/alu/e3/auth/executor/NoAuthExecutorFactory.java @@ -0,0 +1,51 @@ +/** + * Copyright © 2012 Alcatel-Lucent. + * + * See the NOTICE file distributed with this work for additional + * information regarding copyright ownership. + * Licensed to you 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 com.alu.e3.auth.executor; + +import java.util.Map; + +import org.apache.camel.impl.DefaultComponent; + +import com.alu.e3.auth.access.IAuthDataAccess; + +public class NoAuthExecutorFactory extends BaseExecutorFactory { + + protected IAuthDataAccess dataAccess; + + public NoAuthExecutorFactory() {} + + public IAuthDataAccess getDataAccess() { + return dataAccess; + } + + public void setDataAccess(IAuthDataAccess dataAccess) { + this.dataAccess = dataAccess; + } + + @Override + public IAuthExecutor getExecutor(DefaultComponent component, String apiId, Map parameters) { + return new NoAuthExecutor(apiId, dataAccess); + } + + @Override + public String getName() { + return "noAuth"; + } + +} diff --git a/exposure-engine/auth-manager/src/main/java/com/alu/e3/auth/executor/WsseExecutor.java b/exposure-engine/auth-manager/src/main/java/com/alu/e3/auth/executor/WsseExecutor.java new file mode 100644 index 0000000..2d22d9c --- /dev/null +++ b/exposure-engine/auth-manager/src/main/java/com/alu/e3/auth/executor/WsseExecutor.java @@ -0,0 +1,78 @@ +/** + * Copyright © 2012 Alcatel-Lucent. + * + * See the NOTICE file distributed with this work for additional + * information regarding copyright ownership. + * Licensed to you 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 com.alu.e3.auth.executor; + +import java.io.InputStream; +import org.apache.camel.Exchange; + +import com.alu.e3.auth.access.IAuthDataAccess; +import com.alu.e3.auth.model.AuthType; +import com.alu.e3.common.logging.Category; +import com.alu.e3.common.logging.CategoryLogger; +import com.alu.e3.common.logging.CategoryLoggerFactory; +import com.alu.e3.common.tools.WsseTools; +import com.alu.e3.common.camel.AuthReport; +import com.alu.e3.gateway.common.camel.exception.GatewayExceptionCode; + +public class WsseExecutor implements IAuthExecutor{ + + private static final CategoryLogger LOG = CategoryLoggerFactory.getLogger(WsseExecutor.class, Category.AUTH); + + private IAuthDataAccess dataAccess; + private String apiId = ""; + + public WsseExecutor(String apiId, IAuthDataAccess dataAcccess){ + this.apiId = apiId; + this.dataAccess = dataAcccess; + } + + @Override + public AuthReport checkAllowed(Exchange exchange) { + + AuthReport authReport = new AuthReport();; + + InputStream in = exchange.getIn().getBody(InputStream.class); + + WsseTools.WsseUsernameToken tok = null; + + try { + tok = WsseTools.parseXml(in); + } catch (Exception e) { + LOG.debug("Parse exception: " + e.getMessage()); + authReport.setBadRequest(true); + } + + if(!authReport.isBadRequest()) { + authReport = dataAccess.checkAllowed(tok.getUsername(), tok.getPassword(), tok.isPasswordText(), tok.getNonce(), tok.getCreated(), apiId); + } + + return authReport; + } + + @Override + public AuthType getType() { + return AuthType.WSSE; + } + + @Override + public GatewayExceptionCode getErrorCode() { + return GatewayExceptionCode.AUTHORIZATION_WSSE; + } + +} diff --git a/exposure-engine/auth-manager/src/main/java/com/alu/e3/auth/executor/WsseExecutorFactory.java b/exposure-engine/auth-manager/src/main/java/com/alu/e3/auth/executor/WsseExecutorFactory.java new file mode 100644 index 0000000..66cdb7d --- /dev/null +++ b/exposure-engine/auth-manager/src/main/java/com/alu/e3/auth/executor/WsseExecutorFactory.java @@ -0,0 +1,46 @@ +/** + * Copyright © 2012 Alcatel-Lucent. + * + * See the NOTICE file distributed with this work for additional + * information regarding copyright ownership. + * Licensed to you 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 com.alu.e3.auth.executor; + +import java.util.Map; + +import org.apache.camel.impl.DefaultComponent; + +import com.alu.e3.auth.access.IAuthDataAccess; + +public class WsseExecutorFactory extends BaseExecutorFactory { + + protected IAuthDataAccess dataAccess; + + + @Override + public String getName() { + return "wsse"; + } + + @Override + public IAuthExecutor getExecutor(DefaultComponent component, String apiId, Map parameters) { + return new WsseExecutor(apiId, dataAccess); + } + + public void setDataAccess(IAuthDataAccess dataAccess) { + this.dataAccess = dataAccess; + } + +} diff --git a/exposure-engine/auth-manager/src/main/java/com/alu/e3/auth/model/AppIdentity.java b/exposure-engine/auth-manager/src/main/java/com/alu/e3/auth/model/AppIdentity.java new file mode 100644 index 0000000..db6e705 --- /dev/null +++ b/exposure-engine/auth-manager/src/main/java/com/alu/e3/auth/model/AppIdentity.java @@ -0,0 +1,40 @@ +/** + * Copyright © 2012 Alcatel-Lucent. + * + * See the NOTICE file distributed with this work for additional + * information regarding copyright ownership. + * Licensed to you 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 com.alu.e3.auth.model; + +/** + * Please use AuthIdentity instead of this one. + */ +@Deprecated +public class AppIdentity { + + private String appId; + + public AppIdentity(String appId){ + this.appId = appId; + } + + public void setAppId(String appId){ + this.appId = appId; + } + + public String getAppId(){ + return this.appId; + } +} diff --git a/exposure-engine/auth-manager/src/main/java/com/alu/e3/auth/model/AuthIdentityHelper.java b/exposure-engine/auth-manager/src/main/java/com/alu/e3/auth/model/AuthIdentityHelper.java new file mode 100644 index 0000000..b17f8eb --- /dev/null +++ b/exposure-engine/auth-manager/src/main/java/com/alu/e3/auth/model/AuthIdentityHelper.java @@ -0,0 +1,120 @@ +/** + * Copyright © 2012 Alcatel-Lucent. + * + * See the NOTICE file distributed with this work for additional + * information regarding copyright ownership. + * Licensed to you 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 com.alu.e3.auth.model; + +import com.alu.e3.common.camel.AuthIdentity; +import com.alu.e3.common.tools.CanonicalizedIpAddress; +import com.alu.e3.data.model.Api; +import com.alu.e3.data.model.Auth; +import com.alu.e3.data.model.AuthDetail; + +public class AuthIdentityHelper { + + private AuthIdentity authIdentity = null; + + public AuthIdentityHelper() { + this.authIdentity = new AuthIdentity(); + } + + /** + * @return the authIdentity + */ + public AuthIdentity getAuthIdentity() { + return authIdentity; + } + + /** + * Sets the API + * @param apiId + */ + public void setApi(String apiId) { + + Api api = new Api(); + api.setId(apiId); + + this.authIdentity.setApi(api); + } + + /** + * Sets the Auth from an auth key + * @param authKey + */ + public void setAuth(String authKey) { + + Auth auth = new Auth(); + auth.setAuthDetail(new AuthDetail()); + auth.getAuthDetail().setAuthKeyValue(authKey); + + this.authIdentity.setAuth(auth); + } + + + /** + * Sets the Auth from a user name and password + * @param userName + * @param password + */ + public void setAuth(String userName, String password) { + + Auth auth = new Auth(); + auth.setAuthDetail(new AuthDetail()); + auth.getAuthDetail().setUsername(userName); + auth.getAuthDetail().setPassword(password.getBytes()); + + this.authIdentity.setAuth(auth); + } + + + /** + * Sets the Auth from a clientId and clientSecret + * @param clientId + * @param clientSecret + */ + public void setOAuth(String clientId, String clientSecret) { + + Auth auth = new Auth(); + auth.setAuthDetail(new AuthDetail()); + auth.getAuthDetail().setClientId(clientId); + auth.getAuthDetail().setClientSecret(clientSecret); + + this.authIdentity.setAuth(auth); + } + + + /** + * Sets the Auth from a CanonicalizedIpAddress + * @param ip + */ + public void setAuth(CanonicalizedIpAddress ip) { + + Auth auth = new Auth(); + auth.setAuthDetail(new AuthDetail()); + auth.getAuthDetail().getWhiteListedIps().add(ip.getIp()); + + this.authIdentity.setAuth(auth); + } + + /** + * Sets the Application id + * @param appId + */ + public void setAppId(String appId) { + this.authIdentity.setAppId(appId); + } +} diff --git a/exposure-engine/auth-manager/src/main/java/com/alu/e3/auth/model/AuthType.java b/exposure-engine/auth-manager/src/main/java/com/alu/e3/auth/model/AuthType.java new file mode 100644 index 0000000..9097d32 --- /dev/null +++ b/exposure-engine/auth-manager/src/main/java/com/alu/e3/auth/model/AuthType.java @@ -0,0 +1,61 @@ +/** + * Copyright © 2012 Alcatel-Lucent. + * + * See the NOTICE file distributed with this work for additional + * information regarding copyright ownership. + * Licensed to you 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. + */ +// +// This file was generated by the JavaTM Architecture for XML Binding(JAXB) Reference Implementation, vhudson-jaxb-ri-2.2-27 +// See http://java.sun.com/xml/jaxb +// Any modifications to this file will be lost upon recompilation of the source schema. +// Generated on: 2012.03.19 at 02:26:36 PM CET +// + + +package com.alu.e3.auth.model; + +/** + * Enum for supported North Bound authentication types : basic, authKey, IP White List + */ +public enum AuthType { + + BASIC("basic"), + AUTHKEY("authKey"), + IP_WHITE_LIST("ipWhiteList"), + NO_AUTH("noAuth"), + // TODO: remove from open source version + O_AUTH("oAuth"), + WSSE("wsse"); + + private final String value; + + AuthType(String v) { + value = v; + } + + public String value() { + return value; + } + + public static AuthType fromValue(String v) { + for (AuthType c: AuthType.values()) { + if (c.value.equals(v)) { + return c; + } + } + throw new IllegalArgumentException(v); + } + +} diff --git a/exposure-engine/auth-manager/src/main/resources/META-INF/services/org/apache/camel/component/auth b/exposure-engine/auth-manager/src/main/resources/META-INF/services/org/apache/camel/component/auth new file mode 100644 index 0000000..1996966 --- /dev/null +++ b/exposure-engine/auth-manager/src/main/resources/META-INF/services/org/apache/camel/component/auth @@ -0,0 +1 @@ +class=com.alu.e3.auth.camel.component.AuthComponent \ No newline at end of file diff --git a/exposure-engine/auth-manager/src/main/resources/META-INF/spring-optional/auth-manager.beans-os.xml b/exposure-engine/auth-manager/src/main/resources/META-INF/spring-optional/auth-manager.beans-os.xml new file mode 100644 index 0000000..b0bc1ab --- /dev/null +++ b/exposure-engine/auth-manager/src/main/resources/META-INF/spring-optional/auth-manager.beans-os.xml @@ -0,0 +1,24 @@ + + + + + + + + + + + diff --git a/exposure-engine/auth-manager/src/main/resources/META-INF/spring-optional/auth-manager.beans.xml b/exposure-engine/auth-manager/src/main/resources/META-INF/spring-optional/auth-manager.beans.xml new file mode 100644 index 0000000..1dbd6c9 --- /dev/null +++ b/exposure-engine/auth-manager/src/main/resources/META-INF/spring-optional/auth-manager.beans.xml @@ -0,0 +1,66 @@ + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + diff --git a/exposure-engine/auth-manager/src/test/java/com/alu/e3/auth/MockAuthDataAccess.java b/exposure-engine/auth-manager/src/test/java/com/alu/e3/auth/MockAuthDataAccess.java new file mode 100644 index 0000000..c3e4c3c --- /dev/null +++ b/exposure-engine/auth-manager/src/test/java/com/alu/e3/auth/MockAuthDataAccess.java @@ -0,0 +1,136 @@ +/** + * Copyright © 2012 Alcatel-Lucent. + * + * See the NOTICE file distributed with this work for additional + * information regarding copyright ownership. + * Licensed to you 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 com.alu.e3.auth; + +import com.alu.e3.auth.access.IAuthDataAccess; +import com.alu.e3.common.camel.AuthIdentity; +import com.alu.e3.common.camel.AuthReport; +import com.alu.e3.common.tools.CanonicalizedIpAddress; + +/** + * A mock AuthManager class to help with testing. + * + */ +public class MockAuthDataAccess implements IAuthDataAccess { + + private String expectedAuthKey; + private String expectedUserPass; + private String expectedIp; + + public MockAuthDataAccess(String expectedAuthKey, String expectedUserPass, String expectedIp){ + this.expectedAuthKey = expectedAuthKey; + this.expectedUserPass = expectedUserPass; + this.expectedIp = expectedIp; + } + + @Override + public AuthReport checkAllowed(String authKey, String apiId) { + + AuthReport authReport = new AuthReport(); + + if(expectedAuthKey != null) { + + if(expectedAuthKey.equals(authKey)) { + + AuthIdentity authIdentity = new AuthIdentity(); + authIdentity.setAppId("1234"); + authReport.setAuthIdentity(authIdentity); + authReport.setApiActive(true); + + } else { + authReport.setNotAuthorized(true); + } + + } else { + authReport.setBadRequest(true); + } + + return authReport; + } + + @Override + public AuthReport checkAllowed(CanonicalizedIpAddress ip, String apiId) { + + AuthReport authReport = new AuthReport(); + + if(expectedIp != null) { + if(expectedIp.equals(ip.getIp())) { + AuthIdentity authIdentity = new AuthIdentity(); + authIdentity.setAppId("127.0.0.1"); + authReport.setAuthIdentity(authIdentity); + authReport.setApiActive(true); + } else { + authReport.setNotAuthorized(true); + } + } else { + authReport.setBadRequest(true); + } + + + return authReport; + } + + @Override + public AuthReport checkAllowed(String user, String password, String apiId) { + + AuthReport authReport = new AuthReport(); + + if(expectedUserPass != null) { + + if(expectedUserPass.equals(user+":"+password)) { + AuthIdentity authIdentity = new AuthIdentity(); + authIdentity.setAppId("2424"); + authReport.setAuthIdentity(authIdentity); + authReport.setApiActive(true); + } else { + authReport.setNotAuthorized(true); + } + } else { + authReport.setBadRequest(true); + } + + return authReport; + } + + @Override + public AuthReport checkAllowed(String username, String passwordDigest, boolean isPasswordText, String nonce, String created, String apiId) { + // TODO: Implement MockAuthDataAccess to support the WSSE test method + return checkAllowed(username, "", apiId); + } + + @Override + public AuthReport checkAllowed(String apiId) { + + AuthReport authReport = new AuthReport(); + + AuthIdentity authIdentity = new AuthIdentity(); + authIdentity.setAppId("3424"); + authReport.setAuthIdentity(authIdentity); + authReport.setApiActive(true); + + return authReport; + } + + @Override + public AuthReport checkOAuthAllowed(String clientId, String clientSecret, String apiId) { + // TODO: Implement MockAuthDataAccess to support the OAuth test method + return null; + } + +} diff --git a/exposure-engine/auth-manager/src/test/java/com/alu/e3/auth/access/data/DataManagerAccessTest.java b/exposure-engine/auth-manager/src/test/java/com/alu/e3/auth/access/data/DataManagerAccessTest.java new file mode 100644 index 0000000..e414b44 --- /dev/null +++ b/exposure-engine/auth-manager/src/test/java/com/alu/e3/auth/access/data/DataManagerAccessTest.java @@ -0,0 +1,116 @@ +/** + * Copyright © 2012 Alcatel-Lucent. + * + * See the NOTICE file distributed with this work for additional + * information regarding copyright ownership. + * Licensed to you 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 com.alu.e3.auth.access.data; + +import org.junit.Test; + +import com.alu.e3.common.camel.AuthIdentity; +import com.alu.e3.common.camel.AuthReport; +import com.alu.e3.common.tools.CanonicalizedIpAddress; +import com.alu.e3.data.model.Api; +import com.alu.e3.data.model.Auth; +import com.alu.e3.data.model.CallDescriptor; +import com.alu.e3.data.model.Policy; +import com.alu.e3.data.model.enumeration.StatusType; + +import static org.junit.Assert.assertNotNull; +import static org.junit.Assert.assertNull; + +public class DataManagerAccessTest { + + @Test + public void testDataManagerAccessApi() { + + DataManagerAccess dataAccess = new DataManagerAccess(); + MockDataManager mockDataManager = new MockDataManager(); + dataAccess.setDataManager(mockDataManager); + + // no API found + assertNull(dataAccess.checkAllowed("api").getAuthIdentity()); + + Api api = new Api(); + api.setStatus(StatusType.ACTIVE); + mockDataManager.setApi(api); + + // No policy found for the API + // assertNull(dataAccess.isAllowed("api")); + + Policy policy = new Policy(); + mockDataManager.getCallDescriptors().add(new CallDescriptor(policy, 1, 2)); + + + AuthReport authReport = dataAccess.checkAllowed("api"); + AuthIdentity authIdentity = authReport.getAuthIdentity(); + assertNotNull(authIdentity); + + assertNotNull(authIdentity.getApi() == api); // compare memory reference + assertNull(authIdentity.getAuth()); + assertNotNull(authIdentity.getCallDescriptors().get(0).getPolicy() == policy); // compare memory reference + + } + + @Test + public void testDataManagerAccessApiAuth() { + + DataManagerAccess dataAccess = new DataManagerAccess(); + MockDataManager mockDataManager = new MockDataManager(); + dataAccess.setDataManager(mockDataManager); + + Api api = new Api(); + api.setStatus(StatusType.ACTIVE); + mockDataManager.setApi(api); + + // no auth found + assertNull(dataAccess.checkAllowed("authKey", "api").getAuthIdentity()); + assertNull(dataAccess.checkAllowed("username", "password", "api").getAuthIdentity()); + assertNull(dataAccess.checkAllowed(new CanonicalizedIpAddress("127.0.0.1"), "api").getAuthIdentity()); + + Auth auth = new Auth(); + mockDataManager.setAuth(auth); + + // No policy found + assertNull(dataAccess.checkAllowed("authKey", "api").getAuthIdentity()); + assertNull(dataAccess.checkAllowed("username", "password", "api").getAuthIdentity()); + assertNull(dataAccess.checkAllowed(new CanonicalizedIpAddress("127.0.0.1"), "api").getAuthIdentity()); + + Policy policy = new Policy(); + mockDataManager.getCallDescriptors().add(new CallDescriptor(policy, 1, 2)); + + AuthIdentity authIdentity = dataAccess.checkAllowed("authKey", "api").getAuthIdentity(); + assertNotNull(authIdentity); + assertNotNull(authIdentity.getApi() == api); // compare memory reference + assertNotNull(authIdentity.getAuth() == auth); // compare memory reference + assertNotNull(authIdentity.getCallDescriptors().get(0).getPolicy() == policy); // compare memory reference + + authIdentity = dataAccess.checkAllowed("username", "password", "api").getAuthIdentity(); + assertNotNull(authIdentity); + assertNotNull(authIdentity.getApi() == api); // compare memory reference + assertNotNull(authIdentity.getAuth() == auth); // compare memory reference + assertNotNull(authIdentity.getCallDescriptors().get(0).getPolicy() == policy); // compare memory reference + + + authIdentity = dataAccess.checkAllowed(new CanonicalizedIpAddress("127.0.0.1"), "api").getAuthIdentity(); + assertNotNull(authIdentity); + assertNotNull(authIdentity.getApi() == api); // compare memory reference + assertNotNull(authIdentity.getAuth() == auth); // compare memory reference + assertNotNull(authIdentity.getCallDescriptors().get(0).getPolicy() == policy); // compare memory reference + + } + +} diff --git a/exposure-engine/auth-manager/src/test/java/com/alu/e3/auth/access/data/MockDataManager.java b/exposure-engine/auth-manager/src/test/java/com/alu/e3/auth/access/data/MockDataManager.java new file mode 100644 index 0000000..5a30d3d --- /dev/null +++ b/exposure-engine/auth-manager/src/test/java/com/alu/e3/auth/access/data/MockDataManager.java @@ -0,0 +1,680 @@ +/** + * Copyright © 2012 Alcatel-Lucent. + * + * See the NOTICE file distributed with this work for additional + * information regarding copyright ownership. + * Licensed to you 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 com.alu.e3.auth.access.data; + +import java.security.InvalidParameterException; +import java.util.ArrayList; +import java.util.Collection; +import java.util.List; +import java.util.Set; + +import com.alu.e3.common.caching.ICacheManager; +import com.alu.e3.common.caching.IEntryListener; +import com.alu.e3.common.logging.Category; +import com.alu.e3.common.osgi.api.IDataManager; +import com.alu.e3.data.CacheAck; +import com.alu.e3.data.IAuthMatcher; +import com.alu.e3.data.IDataManagerListener; +import com.alu.e3.data.IDataManagerUsedBucketIdsListener; +import com.alu.e3.data.model.Api; +import com.alu.e3.data.model.ApiJar; +import com.alu.e3.data.model.Auth; +import com.alu.e3.data.model.CallDescriptor; +import com.alu.e3.data.model.Certificate; +import com.alu.e3.data.model.CertificateRequest; +import com.alu.e3.data.model.Key; +import com.alu.e3.data.model.Limit; +import com.alu.e3.data.model.LogLevel; +import com.alu.e3.data.model.Policy; +import com.alu.e3.data.model.SSLCRL; +import com.alu.e3.data.model.enumeration.StatusType; +import com.alu.e3.data.model.sub.APIContext; +import com.alu.e3.data.model.sub.Context; +import com.alu.e3.data.model.sub.QuotaRLBucket; + +public class MockDataManager implements IDataManager { + + private Api api = null; + private Auth auth = null; + private List callDescriptors = null; + + public MockDataManager() { + } + + public MockDataManager(boolean isAlwaysHappy) { + Api api = new Api(); + api.setStatus(StatusType.ACTIVE); + this.setApi(api); + if(isAlwaysHappy) { + this.setAuth(new Auth()); + this.getCallDescriptors().add(new CallDescriptor(new Policy(), 1, 2)); + } + } + + @Override + public Set getAllApiIds() { + // TODO Auto-generated method stub + return null; + } + + @Override + public void addApi(Api api) { + // TODO Auto-generated method stub + + } + + @Override + public void updateApi(Api api) { + // TODO Auto-generated method stub + + } + + @Override + public void removeApi(String id) { + // TODO Auto-generated method stub + + } + + @Override + public Api getApiById(String id) { + return this.api; + } + + @Override + public Api getApiById(String id, boolean getFullDetails) { + // TODO Auto-generated method stub + return this.api; + } + + @Override + public Set getAllAuthIds() { + // TODO Auto-generated method stub + return null; + } + + @Override + public void addAuth(Auth auth) { + // TODO Auto-generated method stub + + } + + @Override + public void updateAuth(Auth auth) { + // TODO Auto-generated method stub + + } + + @Override + public void removeAuth(String id) { + // TODO Auto-generated method stub + + } + + @Override + public Auth getAuthById(String id) { + // TODO Auto-generated method stub + return null; + } + + @Override + public Auth getAuthById(String id, boolean getFullDetails) { + // TODO Auto-generated method stub + return null; + } + + @Override + public Set getAllPolicy() { + // TODO Auto-generated method stub + return null; + } + + @Override + public void addPolicy(Policy policy) { + // TODO Auto-generated method stub + + } + + @Override + public void updatePolicy(Policy policy) { + // TODO Auto-generated method stub + + } + + @Override + public void removePolicy(String id) { + // TODO Auto-generated method stub + + } + + @Override + public Policy getPolicyById(String id) { + // TODO Auto-generated method stub + return null; + } + + @Override + public void addAuthsToBucket(String policyId, String bucketId, + QuotaRLBucket authIds) throws InvalidParameterException { + // TODO Auto-generated method stub + + } + + @Override + public void removeAuthFromBucket(String policyId, String bucketId, + String authId) throws InvalidParameterException { + // TODO Auto-generated method stub + + } + + @Override + public void createBucket(String policyId, QuotaRLBucket authIds) + throws InvalidParameterException { + // TODO Auto-generated method stub + + } + + @Override + public void removeBucket(String policyId, String bucketId) + throws InvalidParameterException { + // TODO Auto-generated method stub + + } + + @Override + public List getMatchingPolicies(Api api) { + return this.callDescriptors; + } + + @Override + public List getMatchingPolicies(Api api, Auth auth) { + return this.callDescriptors; + } + + /** + * @param api the api to set + */ + public void setApi(Api api) { + this.api = api; + } + + /** + * @param auth the auth to set + */ + public void setAuth(Auth auth) { + this.auth = auth; + } + + /** + * @param policies the policies to set + */ + public List getCallDescriptors() { + + if(callDescriptors == null) { + callDescriptors = new ArrayList(); + } + + return this.callDescriptors; + } + + @Override + public Policy getPolicyById(String id, boolean getFullDetails) { + // TODO Auto-generated method stub + return null; + } + + @Override + public void fillLimitsById(Integer contextId, Limit limit) { + // TODO Auto-generated method stub + + } + + @Override + public Context getPolicyContextById(Integer id) { + // TODO Auto-generated method stub + return null; + } + + @Override + public APIContext getApiContextById(Integer id) { + // TODO Auto-generated method stub + return null; + } + + @Override + public Auth getAuthByAuthKey(String authKey) { + // TODO Auto-generated method stub + return this.auth; + } + + @Override + public Auth getAuthByUserPass(String username, String password) { + // TODO Auto-generated method stub + return this.auth; + } + + @Override + public Auth getWsseAuth(String username, String passwordDigest, boolean isPasswordText, String nonce, String created) { + // TODO: + return this.auth; + } + + @Override + public Auth getAuthByIP(String IP) { + // TODO Auto-generated method stub + return this.auth; + } + + @Override + public void addAuthsToBucket(List policyId, String bucketId, QuotaRLBucket authIds) throws InvalidParameterException { + // TODO Auto-generated method stub + + } + + @Override + public void removeBucket(List policyIds, String bucketId) throws InvalidParameterException { + // TODO Auto-generated method stub + + } + + @Override + public void putSettingString(String key, String value) { + // TODO Auto-generated method stub + + } + + @Override + public void clearSettingString(String key) { + // TODO Auto-generated method stub + + } + + @Override + public String getSettingString(String key) { + // TODO Auto-generated method stub + return null; + } + @Override + public void setCacheManager(ICacheManager cacheManager) { + // TODO Auto-generated method stub + } + + @Override + public boolean deployApi(String apiId, byte[] jarData) { + return false; + } + + @Override + public boolean undeployApi(String apiId) { + return false; + } + + @Override + public void postAcknowledgment(String queueName, CacheAck ack) { + + } + + @Override + public void addApiDeploymentListener(IEntryListener listener) { + + } + + @Override + public void removeApiDeploymentListener(IEntryListener listener) { + + } + + @Override + public void addListener(IDataManagerListener listener) { + + } + + @Override + public void removeListener(IDataManagerListener listener) { + + } + + @Override + public void removeListener(IDataManagerUsedBucketIdsListener listener) { + + } + + @Override + public void addKey(Key key) { + // TODO Auto-generated method stub + + } + + @Override + public Set getAllKeyIds() { + // TODO Auto-generated method stub + return null; + } + + @Override + public Key getKeyById(String id) { + // TODO Auto-generated method stub + return null; + } + + @Override + public Key getKeyById(String id, boolean getFullDetails) { + // TODO Auto-generated method stub + return null; + } + + @Override + public void updateKey(Key key) { + // TODO Auto-generated method stub + + } + + @Override + public void removeKey(String id) { + // TODO Auto-generated method stub + + } + + @Override + public void addCert(Certificate cert) { + // TODO Auto-generated method stub + + } + + @Override + public Set getAllCertIds() { + // TODO Auto-generated method stub + return null; + } + + @Override + public Certificate getCertById(String id) { + // TODO Auto-generated method stub + return null; + } + + @Override + public Certificate getCertById(String id, boolean getFullDetails) { + // TODO Auto-generated method stub + return null; + } + + @Override + public void removeCert(String id) { + // TODO Auto-generated method stub + + } + + @Override + public Key generateKey(String id) { + // TODO Auto-generated method stub + return null; + } + + @Override + public CertificateRequest getCSR(String keyId) { + // TODO Auto-generated method stub + return null; + } + + @Override + public void updateCert(Certificate certificate) { + // TODO Auto-generated method stub + + } + + @Override + public Set getAllCertIdsForKeyId(String keyId) { + // TODO Auto-generated method stub + return null; + } + + @Override + public Certificate selfSignKey(String keyId, CertificateRequest csr) { + // TODO Auto-generated method stub + return null; + } + + @Override + public void removeKeyListener(IEntryListener listener) { + // TODO Auto-generated method stub + + } + + @Override + public void addKeyListener(IEntryListener listener) { + // TODO Auto-generated method stub + + } + + @Override + public void appendAuthsToBucket(List policyIds, String bucketId, + QuotaRLBucket authIds) throws IllegalArgumentException { + // TODO Auto-generated method stub + + } + + @Override + public void setLogLevel(LogLevel logLevel) { + // TODO Auto-generated method stub + } + + @Override + public LogLevel getLogLevel() { + // TODO Auto-generated method stub + return null; + } + + @Override + public void setSMXLogLevel(LogLevel logLevel) { + // TODO Auto-generated method stub + } + + @Override + public LogLevel getSMXLogLevel() { + // TODO Auto-generated method stub + return null; + } + + @Override + public void setSyslogLevel(LogLevel logLevel) { + // TODO Auto-generated method stub + } + + @Override + public LogLevel getSyslogLevel() { + // TODO Auto-generated method stub + return null; + } + + @Override + public void reloadGateway(String ip) { + // TODO Auto-generated method stub + + } + + @Override + public void addCA(Certificate cert) { + // TODO Auto-generated method stub + + } + + @Override + public Set getAllCA() { + // TODO Auto-generated method stub + return null; + } + + @Override + public Certificate getCAById(String id) { + // TODO Auto-generated method stub + return null; + } + + @Override + public void updateCA(Certificate cert) { + // TODO Auto-generated method stub + + } + + @Override + public void removeCA(String id) { + // TODO Auto-generated method stub + + } + + @Override + public void addCRL(SSLCRL clr) { + // TODO Auto-generated method stub + + } + + @Override + public SSLCRL getCRLById(String id) { + // TODO Auto-generated method stub + return null; + } + + @Override + public void updateCRL(SSLCRL crl) { + // TODO Auto-generated method stub + + } + + @Override + public void removeCRL(String id) { + // TODO Auto-generated method stub + + } + + @Override + public Set getAllCRL() { + // TODO Auto-generated method stub + return null; + } + + @Override + public boolean isApiExist(String apiId) { + // TODO Auto-generated method stub + return true; + } + + @Override + public Collection getAllCRLValues() { + // TODO Auto-generated method stub + return null; + } + + @Override + public void addCrlListener(IEntryListener listener) { + // TODO Auto-generated method stub + + } + + @Override + public void removeCrlListener(IEntryListener listener) { + // TODO Auto-generated method stub + + } + + @Override + public void addCAListener(IEntryListener listener) { + // TODO Auto-generated method stub + + } + + @Override + public void removeCAListener(IEntryListener listener) { + // TODO Auto-generated method stub + + } + + @Override + public void addLogLevelListener(IEntryListener listener) { + // TODO Auto-generated method stub + + } + + @Override + public void removeLogLevelListener(IEntryListener listener) { + // TODO Auto-generated method stub + + } + + @Override + public ApiJar getApiJar(String apiId) { + // TODO Auto-generated method stub + return null; + } + + @Override + public Auth getAuthByOAuth(String clientId, String clientSecret) { + // TODO Auto-generated method stub + return null; + } + + @Override + public boolean endpointExists(String endpoint) { + // TODO Auto-generated method stub + return false; + } + + @Override + public Auth getAuthMatching(IAuthMatcher authMatcher) { + // TODO Auto-generated method stub + return null; + } + + @Override + public void addApiListener(IEntryListener listener) { + // TODO Auto-generated method stub + + } + + @Override + public void removeApiListener(IEntryListener listener) { + // TODO Auto-generated method stub + + } + + @Override + public void addListener(IDataManagerUsedBucketIdsListener listener) { + // TODO Auto-generated method stub + + } + + @Override + public void removeAuthsFromBucket(List policyIds, String bucketId, + List authIds) throws IllegalArgumentException { + // TODO Auto-generated method stub + + } + + @Override + public void setLoggingCategory(Category category, boolean enabled) { + // TODO Auto-generated method stub + + } + + @Override + public boolean getLoggingCategory(Category category) { + // TODO Auto-generated method stub + return false; + } + +} diff --git a/exposure-engine/auth-manager/src/test/java/com/alu/e3/auth/access/file/FileDataTest.java b/exposure-engine/auth-manager/src/test/java/com/alu/e3/auth/access/file/FileDataTest.java new file mode 100644 index 0000000..5a429fa --- /dev/null +++ b/exposure-engine/auth-manager/src/test/java/com/alu/e3/auth/access/file/FileDataTest.java @@ -0,0 +1,67 @@ +/** + * Copyright © 2012 Alcatel-Lucent. + * + * See the NOTICE file distributed with this work for additional + * information regarding copyright ownership. + * Licensed to you 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 com.alu.e3.auth.access.file; + +import static org.junit.Assert.assertNotNull; +import static org.junit.Assert.assertNull; + +import java.net.URL; + +import org.junit.Before; +import org.junit.Test; + +import com.alu.e3.common.tools.CanonicalizedIpAddress; + +public class FileDataTest { + + /* members */ + private FileData fileData = null; + private static final String DB_PATH = "/TextData.db";; + + @Before + public void setUp() throws Exception { + } + + @Test + public void test1() throws Exception { + fileData = new FileData("/notAValidFile.db"); + assertNotNull(fileData); + assertNull(fileData.checkAllowed("test", "test").getAuthIdentity()); + } + + @Test + public void testIsAssociated() throws Exception { + + URL fileURL = getClass().getResource(DB_PATH); + + fileData = new FileData(fileURL.getPath()); + + assertNotNull(fileData.checkAllowed("appKey1234", "api1234").getAuthIdentity()); + assertNotNull(fileData.checkAllowed("user", "pass", "api1234").getAuthIdentity()); + assertNotNull(fileData.checkAllowed(new CanonicalizedIpAddress("127.0.0.1"), "api1234").getAuthIdentity()); + assertNotNull(fileData.checkAllowed("api1234").getAuthIdentity()); + + + assertNull(fileData.checkAllowed("badbad", "apiASDF").getAuthIdentity()); + assertNull(fileData.checkAllowed("bad", "bad", "apiASDF").getAuthIdentity()); + assertNull(fileData.checkAllowed(new CanonicalizedIpAddress("10.0.0.1"), "apiASDF").getAuthIdentity()); + assertNull(fileData.checkAllowed("badbad", "badbad").getAuthIdentity()); + assertNull(fileData.checkAllowed("apiASDF").getAuthIdentity()); + } +} diff --git a/exposure-engine/auth-manager/src/test/java/com/alu/e3/auth/camel/AuthComponentConfigTest.java b/exposure-engine/auth-manager/src/test/java/com/alu/e3/auth/camel/AuthComponentConfigTest.java new file mode 100644 index 0000000..23b71ef --- /dev/null +++ b/exposure-engine/auth-manager/src/test/java/com/alu/e3/auth/camel/AuthComponentConfigTest.java @@ -0,0 +1,107 @@ +/** + * Copyright © 2012 Alcatel-Lucent. + * + * See the NOTICE file distributed with this work for additional + * information regarding copyright ownership. + * Licensed to you 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 com.alu.e3.auth.camel; + +import org.apache.camel.CamelException; +import org.apache.camel.impl.DefaultCamelContext; +import org.junit.Before; +import org.junit.Test; + +import com.alu.e3.auth.camel.component.AuthComponent; +import com.alu.e3.auth.executor.MockAppKeyExecutorFactory; +import com.alu.e3.auth.executor.MockHttpBasicExecutorFactory; +import com.alu.e3.auth.executor.MockIpWhitelistExecutorFactory; +import com.alu.e3.auth.executor.MockNoAuthExecutorFactory; + +/** + * This class should cover all functionality contained in the AuthEndpoint and AuthProducer classes. + * All supporting classes are mocked to isolate the functionality. + * + * + */ +//@RunWith(SpringJUnit4ClassRunner.class) +//@ContextConfiguration(locations = { "classpath:/META-INF/spring/auth-component-test.xml" }) +public class AuthComponentConfigTest { + + private AuthComponent component; + + @Before + public void before(){ + component = new AuthComponent(new DefaultCamelContext()); + component.registerExecutorFactory("authKey", new MockAppKeyExecutorFactory()); + component.registerExecutorFactory("basic", new MockHttpBasicExecutorFactory()); + component.registerExecutorFactory("ipList", new MockIpWhitelistExecutorFactory()); + component.registerExecutorFactory("noAuth", new MockNoAuthExecutorFactory()); + } + + /** + * This tests the case where HttpBasic auth is specified but no HttpBasicExecutorFactory is provided. + * In this case we expect a RuntimeException to be thrown. + * @throws Exception + */ + @Test(expected=CamelException.class) + public void testFailNoApiIdConfig() throws Exception{ + component.createEndpoint("blah?basic=true&keyName=appkey&ipList=true"); + } + + /** + * This tests the case where HttpBasic auth is specified but no HttpBasicExecutorFactory is provided. + * In this case we expect a RuntimeException to be thrown. + * @throws Exception + */ + @Test(expected=RuntimeException.class) + public void testFailHttpBasicConfig() throws Exception{ + component.unregisterExecutorFactory("basic"); + component.createEndpoint("blah?apiId=1234&basic=true"); + } + + /** + * This tests the case where AppKey auth is specified but no AppKeyExecutorFactory is provided. + * In this case we expect a RuntimeException to be thrown. + * @throws Exception + */ + @Test(expected=RuntimeException.class) + public void testFailAppKeyConfig() throws Exception{ + component.unregisterExecutorFactory("authKey"); + component.createEndpoint("blah?apiId=1234&keyName=appkey"); + } + + /** + * This tests the case where Whitelist auth is specified but no WhitelistExecutorFactory is provided. + * In this case we expect a RuntimeException to be thrown. + * @throws Exception + */ + @Test(expected=RuntimeException.class) + public void testFailWhitelistConfig() throws Exception{ + component.unregisterExecutorFactory("ipList"); + component.createEndpoint("blah?apiId=1234&ipList=true"); + } + + + /** + * This tests the case where Whitelist auth is specified but no WhitelistExecutorFactory is provided. + * In this case we expect a RuntimeException to be thrown. + * @throws Exception + */ + @Test(expected=RuntimeException.class) + public void testFailNoAuthConfig() throws Exception{ + component.unregisterExecutorFactory("noAuth"); + component.createEndpoint("blah?apiId=1234&noAuth=true"); + } +} diff --git a/exposure-engine/auth-manager/src/test/java/com/alu/e3/auth/camel/AuthProducerTest.java b/exposure-engine/auth-manager/src/test/java/com/alu/e3/auth/camel/AuthProducerTest.java new file mode 100644 index 0000000..4b41f15 --- /dev/null +++ b/exposure-engine/auth-manager/src/test/java/com/alu/e3/auth/camel/AuthProducerTest.java @@ -0,0 +1,195 @@ +/** + * Copyright © 2012 Alcatel-Lucent. + * + * See the NOTICE file distributed with this work for additional + * information regarding copyright ownership. + * Licensed to you 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 com.alu.e3.auth.camel; + +import static org.junit.Assert.assertNotNull; +import static org.junit.Assert.assertNull; + +import org.apache.camel.CamelContext; +import org.apache.camel.Exchange; +import org.apache.camel.impl.DefaultCamelContext; +import org.apache.camel.impl.DefaultExchange; +import org.junit.Before; +import org.junit.Test; + +import com.alu.e3.auth.AuthHttpHeaders; +import com.alu.e3.auth.camel.component.AuthComponent; +import com.alu.e3.auth.camel.endpoint.AuthEndpoint; +import com.alu.e3.auth.camel.producer.AuthProducer; +import com.alu.e3.auth.executor.MockAppKeyExecutorFactory; +import com.alu.e3.auth.executor.MockHttpBasicExecutorFactory; +import com.alu.e3.auth.executor.MockIpWhitelistExecutorFactory; +import com.alu.e3.auth.executor.MockNoAuthExecutorFactory; +import com.alu.e3.common.camel.ExchangeConstantKeys; + +/** + * This class should cover all functionality contained in the AuthEndpoint and AuthProducer classes. + * All supporting classes are mocked to isolate the functionality. + * + * + */ +//@RunWith(SpringJUnit4ClassRunner.class) +//@ContextConfiguration(locations = { "classpath:/META-INF/spring/auth-component-test.xml" }) +public class AuthProducerTest { + + final CamelContext context = new DefaultCamelContext(); + private AuthComponent component; + + @Before + public void before(){ + component = new AuthComponent(new DefaultCamelContext()); + component.registerExecutorFactory("authKey", new MockAppKeyExecutorFactory()); + component.registerExecutorFactory("basic", new MockHttpBasicExecutorFactory()); + component.registerExecutorFactory("ipList", new MockIpWhitelistExecutorFactory()); + component.registerExecutorFactory("noAuth", new MockNoAuthExecutorFactory()); + } + + /** + * This tests the case where the endpoint is configured correctly and we expect a successful HttpBasic authentication + * @throws Exception + */ + @Test + public void testSuccessHttpBasic() throws Exception{ + AuthEndpoint endpoint = (AuthEndpoint) component.createEndpoint("blah?apiId=1234&basic=true"); + AuthProducer producer = (AuthProducer) endpoint.createProducer(); + Exchange exchange = new DefaultExchange(context); + // Anything will work for the mock executor... it just has to be set + exchange.getIn().setHeader(AuthHttpHeaders.Authorization.toString(), "blarg"); + + producer.process(exchange); + + testAuthenticated(exchange); + } + + /** + * Utility method to help do the same asserts for the same cases. + * @param exchange + */ + private void testAuthenticated(Exchange exchange) { + assertNotNull("The Authentication header should not be null", exchange.getProperty(ExchangeConstantKeys.E3_AUTH_IDENTITY.toString())); + } + + /** + * This test the case where the endpoint is configured correctly and we expect a failed httpbasic authentication + */ + @Test + public void testFailHttpBasic() throws Exception{ + AuthEndpoint endpoint = (AuthEndpoint) component.createEndpoint("blah?apiId=1234&basic=true"); + AuthProducer producer = (AuthProducer) endpoint.createProducer(); + Exchange exchange = new DefaultExchange(context); + + producer.process(exchange); + + testNotAuthenticated(exchange); + } + + /** + * Utility method to help do the same asserts for the same cases. + * @param exchange + */ + private void testNotAuthenticated(Exchange exchange) { + assertNull("The Identity property should be null", exchange.getProperty(ExchangeConstantKeys.E3_AUTH_IDENTITY.toString())); + } + + /** + * This tests the case where the endpoint is configured correctly and we expect a successful appkey authentication + * @throws Exception + */ + @Test + public void testSuccessAppKey() throws Exception{ + AuthEndpoint endpoint = (AuthEndpoint) component.createEndpoint("blah?apiId=1234&authKey=true&keyName=appkey"); + AuthProducer producer = (AuthProducer) endpoint.createProducer(); + Exchange exchange = new DefaultExchange(context); + // Anything will work for the mock executor... it just has to be set + exchange.getIn().setHeader("appkey", "blarg"); + + producer.process(exchange); + + testAuthenticated(exchange); + } + + /** + * This test the case where the endpoint is configured correctly and we expect a failed appkey authentication + */ + @Test + public void testFailAppKey() throws Exception{ + AuthEndpoint endpoint = (AuthEndpoint) component.createEndpoint("blah?apiId=1234&authKey=true&keyName=appkey"); + AuthProducer producer = (AuthProducer) endpoint.createProducer(); + Exchange exchange = new DefaultExchange(context); + + producer.process(exchange); + + testNotAuthenticated(exchange); + } + + /** + * This tests the case where the endpoint is configured correctly and we expect a successful whitelist authentication + * @throws Exception + */ + @Test + public void testSuccessWhitelist() throws Exception{ + AuthEndpoint endpoint = (AuthEndpoint) component.createEndpoint("blah?apiId=1234&ipList=true"); + AuthProducer producer = (AuthProducer) endpoint.createProducer(); + Exchange exchange = new DefaultExchange(context); + // Anything will work for the mock executor... it just has to be set + exchange.getIn().setHeader("source-ip", "127.0.0.1"); + + producer.process(exchange); + + testAuthenticated(exchange); + } + + /** + * This test the case where the endpoint is configured correctly and we expect a failed whitelist authentication + */ + @Test + public void testFailWhitelist() throws Exception{ + AuthEndpoint endpoint = (AuthEndpoint) component.createEndpoint("blah?apiId=1234&ipList=true"); + AuthProducer producer = (AuthProducer) endpoint.createProducer(); + Exchange exchange = new DefaultExchange(context); + + producer.process(exchange); + + testNotAuthenticated(exchange); + } + + + @Test + public void testSuccessNoAuth() throws Exception{ + AuthEndpoint endpoint = (AuthEndpoint) component.createEndpoint("blah?apiId=1234&noAuth=true"); + AuthProducer producer = (AuthProducer) endpoint.createProducer(); + Exchange exchange = new DefaultExchange(context); + + producer.process(exchange); + + testAuthenticated(exchange); + } + + @Test + public void testFailNoAuth() throws Exception{ + AuthEndpoint endpoint = (AuthEndpoint) component.createEndpoint("blah?apiId=1234&noAuth=false"); + AuthProducer producer = (AuthProducer) endpoint.createProducer(); + Exchange exchange = new DefaultExchange(context); + + producer.process(exchange); + + testNotAuthenticated(exchange); + } + +} diff --git a/exposure-engine/auth-manager/src/test/java/com/alu/e3/auth/executor/AppKeyExecutorTest.java b/exposure-engine/auth-manager/src/test/java/com/alu/e3/auth/executor/AppKeyExecutorTest.java new file mode 100644 index 0000000..d67494f --- /dev/null +++ b/exposure-engine/auth-manager/src/test/java/com/alu/e3/auth/executor/AppKeyExecutorTest.java @@ -0,0 +1,144 @@ +/** + * Copyright © 2012 Alcatel-Lucent. + * + * See the NOTICE file distributed with this work for additional + * information regarding copyright ownership. + * Licensed to you 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 com.alu.e3.auth.executor; + +import java.util.HashMap; +import java.util.Map; + +import org.apache.camel.CamelContext; +import org.apache.camel.Exchange; +import org.apache.camel.impl.DefaultCamelContext; +import org.apache.camel.impl.DefaultExchange; +import static org.junit.Assert.assertNotNull; +import static org.junit.Assert.assertNull; +import org.junit.Test; + +import com.alu.e3.auth.MockAuthDataAccess; +import com.alu.e3.common.camel.AuthReport; +import com.alu.e3.common.camel.ExchangeConstantKeys; + +public class AppKeyExecutorTest { + + final CamelContext context = new DefaultCamelContext(); + final String appKeyName = "appkey"; + final String appHeaderName = "appheader"; + + @Test + public void testWin() { + Exchange exchange = new DefaultExchange(context); + + // Setting the key in the request parameters + Map parameters = new HashMap(); + parameters.put(appKeyName, "asdf"); + exchange.setProperty(ExchangeConstantKeys.E3_REQUEST_PARAMETERS.toString(), parameters); + + // Setting the key in the query - should be removed + exchange.getIn().setHeader(Exchange.HTTP_QUERY, appKeyName + "=asdf"); + + AppKeyExecutor executor = new AppKeyExecutor(appKeyName, appHeaderName, "1234", new MockAuthDataAccess("asdf", null, null)); + + AuthReport authReport = executor.checkAllowed(exchange); + + assertNotNull("This authentication should have succeeded", authReport.getAuthIdentity()); + + // Check the query parameter + assertNull("The query parameter should have been removed", exchange.getIn().getHeader(Exchange.HTTP_QUERY)); + } + + @Test + public void testWinHeader() { + Exchange exchange = new DefaultExchange(context); + exchange.setProperty(ExchangeConstantKeys.E3_REQUEST_PARAMETERS.toString(), new HashMap()); + + // Setting the key in the header - should be removed + exchange.getIn().setHeader(appHeaderName, "asdf"); + + AppKeyExecutor executor = new AppKeyExecutor(appKeyName, appHeaderName, "1234", new MockAuthDataAccess("asdf", null, null)); + + AuthReport authReport = executor.checkAllowed(exchange); + + assertNotNull("This authentication should have succeeded", authReport.getAuthIdentity()); + + // Check the query parameter + assertNull("The header should have been removed", exchange.getIn().getHeader(appHeaderName)); + } + + + @Test + public void testFailNotAllowed(){ + Exchange exchange = new DefaultExchange(context); + + // Setting the key in the request parameters + Map parameters = new HashMap(); + parameters.put(appKeyName, "asdf"); + exchange.setProperty(ExchangeConstantKeys.E3_REQUEST_PARAMETERS.toString(), parameters); + + AppKeyExecutor executor = new AppKeyExecutor(appKeyName, appHeaderName, "1234", new MockAuthDataAccess(null, null, null)); + + AuthReport authReport = executor.checkAllowed(exchange); + + assertNull("This authentication should have failed", authReport.getAuthIdentity()); + } + + @Test + public void testFailNoHeader(){ + Exchange exchange = new DefaultExchange(context); + exchange.setProperty(ExchangeConstantKeys.E3_REQUEST_PARAMETERS.toString(), new HashMap()); + + // no parameter should fail + AppKeyExecutor executor = new AppKeyExecutor(appKeyName, appHeaderName, "1234", new MockAuthDataAccess("asdf", null, null)); + + AuthReport authReport = executor.checkAllowed(exchange); + + assertNull("This authentication should have failed", authReport.getAuthIdentity()); + } + + @Test + public void testFailBadFormat(){ + Exchange exchange = new DefaultExchange(context); + + // Setting the wrong key in the request parameters + Map parameters = new HashMap(); + parameters.put(appKeyName.toUpperCase(), "asdf"); + exchange.setProperty(ExchangeConstantKeys.E3_REQUEST_PARAMETERS.toString(), parameters); + + AppKeyExecutor executor = new AppKeyExecutor(appKeyName, appHeaderName, "1234", new MockAuthDataAccess("asdf", null, null)); + + AuthReport authReport = executor.checkAllowed(exchange); + + assertNull("This authentication should have failed", authReport.getAuthIdentity()); + } + + @Test + public void testFailBadFormat2(){ + Exchange exchange = new DefaultExchange(context); + + // Setting the null key in the request parameters + Map parameters = new HashMap(); + parameters.put(appKeyName, null); + exchange.setProperty(ExchangeConstantKeys.E3_REQUEST_PARAMETERS.toString(), parameters); + + AppKeyExecutor executor = new AppKeyExecutor(appKeyName, appHeaderName, "1234", new MockAuthDataAccess("asdf", null, null)); + + AuthReport authReport = executor.checkAllowed(exchange); + + assertNull("This authentication should have failed", authReport.getAuthIdentity()); + } + +} diff --git a/exposure-engine/auth-manager/src/test/java/com/alu/e3/auth/executor/HttpBasicExecutorTest.java b/exposure-engine/auth-manager/src/test/java/com/alu/e3/auth/executor/HttpBasicExecutorTest.java new file mode 100644 index 0000000..435c1a4 --- /dev/null +++ b/exposure-engine/auth-manager/src/test/java/com/alu/e3/auth/executor/HttpBasicExecutorTest.java @@ -0,0 +1,116 @@ +/** + * Copyright © 2012 Alcatel-Lucent. + * + * See the NOTICE file distributed with this work for additional + * information regarding copyright ownership. + * Licensed to you 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 com.alu.e3.auth.executor; + +import org.apache.camel.CamelContext; +import org.apache.camel.Exchange; +import org.apache.camel.impl.DefaultCamelContext; +import org.apache.camel.impl.DefaultExchange; +import org.apache.commons.codec.binary.Base64; +import static org.junit.Assert.assertNotNull; +import static org.junit.Assert.assertNull; +import org.junit.Test; + +import com.alu.e3.auth.AuthHttpHeaders; +import com.alu.e3.auth.MockAuthDataAccess; +import com.alu.e3.common.camel.AuthReport; + +public class HttpBasicExecutorTest { + + final CamelContext context = new DefaultCamelContext(); + + @Test + public void testWin() { + Exchange exchange = new DefaultExchange(context); + + // Setting the username = "win" should succeed + exchange.getIn().setHeader(AuthHttpHeaders.Authorization.toString(), "Basic "+new String(Base64.encodeBase64("win:blarg".getBytes()))); + HttpBasicExecutor executor = new HttpBasicExecutor("123", new MockAuthDataAccess(null, "win:blarg", null)); + + AuthReport authReport = executor.checkAllowed(exchange); + + assertNotNull("This authentication should have succeeded", authReport.getAuthIdentity()); + } + + @Test + public void testFailNoEncoding(){ + Exchange exchange = new DefaultExchange(context); + + // Setting the username = "win" should succeed + exchange.getIn().setHeader(AuthHttpHeaders.Authorization.toString(), "Basic "+"win:blarg"); + HttpBasicExecutor executor = new HttpBasicExecutor("123", new MockAuthDataAccess(null, "win:blarg", null)); + + AuthReport authReport = executor.checkAllowed(exchange); + + assertNull("This authentication should have failed", authReport.getAuthIdentity()); + } + + @Test + public void testFailNoHeader(){ + Exchange exchange = new DefaultExchange(context); + + // Setting the username = "win" should succeed + HttpBasicExecutor executor = new HttpBasicExecutor("123", new MockAuthDataAccess(null, "win:blarg", null)); + + AuthReport authReport = executor.checkAllowed(exchange); + + assertNull("This authentication should have failed", authReport.getAuthIdentity()); + } + + @Test + public void testFailBadFormat(){ + Exchange exchange = new DefaultExchange(context); + + // Setting the username = "win" should succeed + exchange.getIn().setHeader(AuthHttpHeaders.Authorization.toString(), "Vlasic "+new String(Base64.encodeBase64("win:blarg".getBytes()))); + HttpBasicExecutor executor = new HttpBasicExecutor("123", new MockAuthDataAccess(null, "win:blarg", null)); + + AuthReport authReport = executor.checkAllowed(exchange); + + assertNull("This authentication should have failed", authReport.getAuthIdentity()); + } + + @Test + public void testFailBadFormat2(){ + Exchange exchange = new DefaultExchange(context); + + // Setting the username = "win" should succeed + // This one is bad because it is missing the space between Basic and the user/pass + exchange.getIn().setHeader(AuthHttpHeaders.Authorization.toString(), "Basic"+new String(Base64.encodeBase64("win:blarg".getBytes()))); + HttpBasicExecutor executor = new HttpBasicExecutor("123", new MockAuthDataAccess(null, "win:blarg", null)); + + AuthReport authReport = executor.checkAllowed(exchange); + + assertNull("This authentication should have failed", authReport.getAuthIdentity()); + } + + @Test + public void testFailNotAllowed(){ + Exchange exchange = new DefaultExchange(context); + + // This one should be denied because the MockData is rigged to return null + exchange.getIn().setHeader(AuthHttpHeaders.Authorization.toString(), "Basic "+new String(Base64.encodeBase64("win:blarg".getBytes()))); + HttpBasicExecutor executor = new HttpBasicExecutor("123", new MockAuthDataAccess(null, null, null)); + + AuthReport authReport = executor.checkAllowed(exchange); + + assertNull("This authentication should have failed", authReport.getAuthIdentity()); + } + +} diff --git a/exposure-engine/auth-manager/src/test/java/com/alu/e3/auth/executor/MockAppKeyExecutor.java b/exposure-engine/auth-manager/src/test/java/com/alu/e3/auth/executor/MockAppKeyExecutor.java new file mode 100644 index 0000000..1f1d198 --- /dev/null +++ b/exposure-engine/auth-manager/src/test/java/com/alu/e3/auth/executor/MockAppKeyExecutor.java @@ -0,0 +1,60 @@ +/** + * Copyright © 2012 Alcatel-Lucent. + * + * See the NOTICE file distributed with this work for additional + * information regarding copyright ownership. + * Licensed to you 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 com.alu.e3.auth.executor; + +import org.apache.camel.Exchange; + +import com.alu.e3.auth.model.AuthType; +import com.alu.e3.common.camel.AuthIdentity; +import com.alu.e3.common.camel.AuthReport; +import com.alu.e3.gateway.common.camel.exception.GatewayExceptionCode; + +public class MockAppKeyExecutor implements IAuthExecutor { + + @Override + public AuthReport checkAllowed(Exchange exchange) { + + AuthReport authReport = new AuthReport(); + + if(exchange.getIn().getHeaders().size() > 0) { + AuthIdentity authIdentity = new AuthIdentity(); + authIdentity.setAppId("1234"); + authReport.setAuthIdentity(authIdentity); + authReport.setApiActive(true); + } else { + authReport.setBadRequest(true); + } + + //return exchange.getIn().getHeaders().size() > 0 ? new AuthIdentity("1234") : null; + + return authReport; + } + + + @Override + public AuthType getType() { + return AuthType.AUTHKEY; + } + + @Override + public GatewayExceptionCode getErrorCode() { + return GatewayExceptionCode.AUTHORIZATION; + } + +} diff --git a/exposure-engine/auth-manager/src/test/java/com/alu/e3/auth/executor/MockAppKeyExecutorFactory.java b/exposure-engine/auth-manager/src/test/java/com/alu/e3/auth/executor/MockAppKeyExecutorFactory.java new file mode 100644 index 0000000..c3cea4c --- /dev/null +++ b/exposure-engine/auth-manager/src/test/java/com/alu/e3/auth/executor/MockAppKeyExecutorFactory.java @@ -0,0 +1,41 @@ +/** + * Copyright © 2012 Alcatel-Lucent. + * + * See the NOTICE file distributed with this work for additional + * information regarding copyright ownership. + * Licensed to you 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 com.alu.e3.auth.executor; + +import java.util.Map; + +import org.apache.camel.impl.DefaultComponent; + +public class MockAppKeyExecutorFactory extends BaseExecutorFactory { + + @Override + public IAuthExecutor getExecutor(DefaultComponent component, String apiId, + Map parameters) { + if(parameters.containsKey("keyName")){ + component.getAndRemoveParameter(parameters, "keyName", String.class); + } + return new MockAppKeyExecutor(); + } + + @Override + public String getName() { + return null; + } + +} diff --git a/exposure-engine/auth-manager/src/test/java/com/alu/e3/auth/executor/MockHttpBasicExecutor.java b/exposure-engine/auth-manager/src/test/java/com/alu/e3/auth/executor/MockHttpBasicExecutor.java new file mode 100644 index 0000000..781ca06 --- /dev/null +++ b/exposure-engine/auth-manager/src/test/java/com/alu/e3/auth/executor/MockHttpBasicExecutor.java @@ -0,0 +1,58 @@ +/** + * Copyright © 2012 Alcatel-Lucent. + * + * See the NOTICE file distributed with this work for additional + * information regarding copyright ownership. + * Licensed to you 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 com.alu.e3.auth.executor; + +import org.apache.camel.Exchange; + +import com.alu.e3.auth.AuthHttpHeaders; +import com.alu.e3.auth.model.AuthType; +import com.alu.e3.common.camel.AuthIdentity; +import com.alu.e3.common.camel.AuthReport; +import com.alu.e3.gateway.common.camel.exception.GatewayExceptionCode; + +public class MockHttpBasicExecutor implements IAuthExecutor { + + @Override + public AuthReport checkAllowed(Exchange exchange) { + + AuthReport authReport = new AuthReport(); + + if(exchange.getIn().getHeader(AuthHttpHeaders.Authorization.toString()) != null) { + AuthIdentity authIdentity = new AuthIdentity(); + authIdentity.setAppId("1234"); + authReport.setAuthIdentity(authIdentity); + authReport.setApiActive(true); + } + + //return exchange.getIn().getHeader(AuthHeaders.AuthHttpHeaders.key)==null?null:new AppIdentity("1234"); + + return authReport; + } + + @Override + public AuthType getType() { + return AuthType.BASIC; + } + + @Override + public GatewayExceptionCode getErrorCode() { + return GatewayExceptionCode.AUTHORIZATION_BASIC; + } + +} diff --git a/exposure-engine/auth-manager/src/test/java/com/alu/e3/auth/executor/MockHttpBasicExecutorFactory.java b/exposure-engine/auth-manager/src/test/java/com/alu/e3/auth/executor/MockHttpBasicExecutorFactory.java new file mode 100644 index 0000000..5cc8584 --- /dev/null +++ b/exposure-engine/auth-manager/src/test/java/com/alu/e3/auth/executor/MockHttpBasicExecutorFactory.java @@ -0,0 +1,38 @@ +/** + * Copyright © 2012 Alcatel-Lucent. + * + * See the NOTICE file distributed with this work for additional + * information regarding copyright ownership. + * Licensed to you 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 com.alu.e3.auth.executor; + +import java.util.Map; + +import org.apache.camel.impl.DefaultComponent; + +public class MockHttpBasicExecutorFactory extends BaseExecutorFactory { + + @Override + public IAuthExecutor getExecutor(DefaultComponent component, String apiId, + Map parameters) { + return new MockHttpBasicExecutor(); + } + + @Override + public String getName() { + return null; + } + +} diff --git a/exposure-engine/auth-manager/src/test/java/com/alu/e3/auth/executor/MockIpWhitelistExecutor.java b/exposure-engine/auth-manager/src/test/java/com/alu/e3/auth/executor/MockIpWhitelistExecutor.java new file mode 100644 index 0000000..956c53b --- /dev/null +++ b/exposure-engine/auth-manager/src/test/java/com/alu/e3/auth/executor/MockIpWhitelistExecutor.java @@ -0,0 +1,60 @@ +/** + * Copyright © 2012 Alcatel-Lucent. + * + * See the NOTICE file distributed with this work for additional + * information regarding copyright ownership. + * Licensed to you 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 com.alu.e3.auth.executor; + +import org.apache.camel.Exchange; + +import com.alu.e3.auth.model.AuthType; +import com.alu.e3.common.camel.AuthIdentity; +import com.alu.e3.common.camel.AuthReport; +import com.alu.e3.gateway.common.camel.exception.GatewayExceptionCode; + +public class MockIpWhitelistExecutor implements IAuthExecutor { + + @Override + public AuthReport checkAllowed(Exchange exchange) { + + AuthReport authReport = new AuthReport(); + + if(exchange.getIn().getHeaders().size() > 0) { + AuthIdentity authIdentity = new AuthIdentity(); + authIdentity.setAppId("1234"); + authReport.setAuthIdentity(authIdentity); + authReport.setApiActive(true); + + } else { + authReport.setBadRequest(true); + } + + //return exchange.getIn().getHeaders().size() > 0?new AppIdentity("1234"):null; + + return authReport; + } + + @Override + public AuthType getType() { + return AuthType.IP_WHITE_LIST; + } + + @Override + public GatewayExceptionCode getErrorCode() { + return GatewayExceptionCode.AUTHORIZATION; + } + +} diff --git a/exposure-engine/auth-manager/src/test/java/com/alu/e3/auth/executor/MockIpWhitelistExecutorFactory.java b/exposure-engine/auth-manager/src/test/java/com/alu/e3/auth/executor/MockIpWhitelistExecutorFactory.java new file mode 100644 index 0000000..c16099f --- /dev/null +++ b/exposure-engine/auth-manager/src/test/java/com/alu/e3/auth/executor/MockIpWhitelistExecutorFactory.java @@ -0,0 +1,39 @@ +/** + * Copyright © 2012 Alcatel-Lucent. + * + * See the NOTICE file distributed with this work for additional + * information regarding copyright ownership. + * Licensed to you 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 com.alu.e3.auth.executor; + +import java.util.Map; + +import org.apache.camel.impl.DefaultComponent; + + +public class MockIpWhitelistExecutorFactory extends BaseExecutorFactory { + + @Override + public IAuthExecutor getExecutor(DefaultComponent component, String apiId, + Map parameters) { + return new MockIpWhitelistExecutor(); + } + + @Override + public String getName() { + return null; + } + +} diff --git a/exposure-engine/auth-manager/src/test/java/com/alu/e3/auth/executor/MockNoAuthExecutor.java b/exposure-engine/auth-manager/src/test/java/com/alu/e3/auth/executor/MockNoAuthExecutor.java new file mode 100644 index 0000000..017af19 --- /dev/null +++ b/exposure-engine/auth-manager/src/test/java/com/alu/e3/auth/executor/MockNoAuthExecutor.java @@ -0,0 +1,53 @@ +/** + * Copyright © 2012 Alcatel-Lucent. + * + * See the NOTICE file distributed with this work for additional + * information regarding copyright ownership. + * Licensed to you 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 com.alu.e3.auth.executor; + +import org.apache.camel.Exchange; + +import com.alu.e3.auth.model.AuthType; +import com.alu.e3.common.camel.AuthIdentity; +import com.alu.e3.common.camel.AuthReport; +import com.alu.e3.gateway.common.camel.exception.GatewayExceptionCode; + +public class MockNoAuthExecutor implements IAuthExecutor { + + @Override + public AuthReport checkAllowed(Exchange exchange) { + + AuthReport authReport = new AuthReport(); + + AuthIdentity authIdentity = new AuthIdentity(); + authIdentity.setAppId("1234"); + + authReport.setAuthIdentity(authIdentity); + authReport.setApiActive(true); + + return authReport; + } + + @Override + public AuthType getType() { + return AuthType.NO_AUTH; + } + + @Override + public GatewayExceptionCode getErrorCode() { + return GatewayExceptionCode.AUTHORIZATION; + } +} diff --git a/exposure-engine/auth-manager/src/test/java/com/alu/e3/auth/executor/MockNoAuthExecutorFactory.java b/exposure-engine/auth-manager/src/test/java/com/alu/e3/auth/executor/MockNoAuthExecutorFactory.java new file mode 100644 index 0000000..a2362ec --- /dev/null +++ b/exposure-engine/auth-manager/src/test/java/com/alu/e3/auth/executor/MockNoAuthExecutorFactory.java @@ -0,0 +1,38 @@ +/** + * Copyright © 2012 Alcatel-Lucent. + * + * See the NOTICE file distributed with this work for additional + * information regarding copyright ownership. + * Licensed to you 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 com.alu.e3.auth.executor; + +import java.util.Map; + +import org.apache.camel.impl.DefaultComponent; + +public class MockNoAuthExecutorFactory extends BaseExecutorFactory { + + @Override + public IAuthExecutor getExecutor(DefaultComponent component, String apiId, + Map parameters) { + return new MockNoAuthExecutor(); + } + + @Override + public String getName() { + return null; + } + +} diff --git a/exposure-engine/auth-manager/src/test/java/com/alu/e3/auth/executor/NoAuthExecutorTest.java b/exposure-engine/auth-manager/src/test/java/com/alu/e3/auth/executor/NoAuthExecutorTest.java new file mode 100644 index 0000000..3a75ac8 --- /dev/null +++ b/exposure-engine/auth-manager/src/test/java/com/alu/e3/auth/executor/NoAuthExecutorTest.java @@ -0,0 +1,47 @@ +/** + * Copyright © 2012 Alcatel-Lucent. + * + * See the NOTICE file distributed with this work for additional + * information regarding copyright ownership. + * Licensed to you 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 com.alu.e3.auth.executor; + +import org.apache.camel.CamelContext; +import org.apache.camel.Exchange; +import org.apache.camel.impl.DefaultCamelContext; +import org.apache.camel.impl.DefaultExchange; +import static org.junit.Assert.assertNotNull; +import org.junit.Test; + +import com.alu.e3.auth.MockAuthDataAccess; +import com.alu.e3.common.camel.AuthReport; + +public class NoAuthExecutorTest { + + final CamelContext context = new DefaultCamelContext(); + + @Test + public void testNoAuth() { + + Exchange exchange = new DefaultExchange(context); + + MockAuthDataAccess mockDA = new MockAuthDataAccess(null, null, null); + NoAuthExecutor executor = new NoAuthExecutor("api3234", mockDA); + + AuthReport authReport = executor.checkAllowed(exchange); + + assertNotNull("This authentication should have succeeded", authReport.getAuthIdentity()); + } +} diff --git a/exposure-engine/auth-manager/src/test/java/com/alu/e3/auth/executor/WsseExecutorTest.java b/exposure-engine/auth-manager/src/test/java/com/alu/e3/auth/executor/WsseExecutorTest.java new file mode 100644 index 0000000..e03cab7 --- /dev/null +++ b/exposure-engine/auth-manager/src/test/java/com/alu/e3/auth/executor/WsseExecutorTest.java @@ -0,0 +1,103 @@ +/** + * Copyright © 2012 Alcatel-Lucent. + * + * See the NOTICE file distributed with this work for additional + * information regarding copyright ownership. + * Licensed to you 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 com.alu.e3.auth.executor; + +import java.security.NoSuchAlgorithmException; +import java.security.SecureRandom; +import java.util.Date; + +import org.apache.camel.CamelContext; +import org.apache.camel.Exchange; +import org.apache.camel.impl.DefaultCamelContext; +import org.apache.camel.impl.DefaultExchange; +import static org.junit.Assert.assertNotNull; +import org.junit.Test; + +import com.alu.e3.auth.MockAuthDataAccess; +import com.alu.e3.common.camel.AuthReport; +import com.alu.e3.common.tools.WsseTools; + +public class WsseExecutorTest { + + private static SecureRandom random; + + static { + try { + random = SecureRandom.getInstance("SHA1PRNG"); + } catch (NoSuchAlgorithmException e) { + throw new RuntimeException(); // missing algorithm -- should not happen + } + } + + final CamelContext context = new DefaultCamelContext(); + + private static final String XML = "" + + "\n" + + " \n" + + " wally\n" + + " weYI3nXd8LjMNVksCKFV8t3rgHh3Rw==\n" + + " WScqanjCEAC4mQoBE07sAQ==\n" + + " 2012-07-19T01:24:32Z\n" + + " \n" + + "\n" + ; + + @Test + public void testWin() { + Exchange exchange = new DefaultExchange(context); + + // Setting the username = "win" should succeed + exchange.getIn().setBody(XML); + WsseExecutor executor = new WsseExecutor("123", new MockAuthDataAccess(null, "wally:", null)); + + AuthReport authReport = executor.checkAllowed(exchange); + + assertNotNull("This authentication should have succeeded", authReport.getAuthIdentity()); + } + + public static String asXml(String username, byte[] passwordBytes) { + return asXml(username, passwordBytes, null, null); + } + + public static String asXml(String username, byte[] passwordBytes, byte[] nonceBytes, Date when) { + if (nonceBytes == null) { + nonceBytes = new byte[10]; + random.nextBytes(nonceBytes); + } + if (when == null) { + when = new Date(); + } + String nonce = WsseTools.getNonce(nonceBytes); + String created = WsseTools.getCreated(when); + String passwordDigest = WsseTools.getPasswordDigest(WsseTools.getPasswordDigestBytes(nonce, created, passwordBytes)); + return asXml(username, passwordDigest, nonce, created); + } + + public static String asXml(String username, String passwordDigest, String nonce, String created) { + return new StringBuilder() + .append("\n") + .append(" ").append(username).append("\n") + .append(" ").append(passwordDigest).append("\n") + .append(" ").append(nonce).append("\n") + .append(" ").append(created).append("\n") + .append("\n") + .toString(); + } +} diff --git a/exposure-engine/auth-manager/src/test/resources/TextData.db b/exposure-engine/auth-manager/src/test/resources/TextData.db new file mode 100644 index 0000000..c942ef0 --- /dev/null +++ b/exposure-engine/auth-manager/src/test/resources/TextData.db @@ -0,0 +1,4 @@ +api1234 appKey1234 user:pass active 127.0.0.1 ::ffff:7f00:1 ::1 noauth:true +apiASDF appKeyASDF foo:bar inactive 127.0.0.1 ::ffff:7f00:1 ::1 noauth:false +api29192 1232123 pending 127.0.0.1 ::ffff:7f00:1 ::1 noauth:false +api123123123 4123 active 127.0.0.1 ::ffff:7f00:1 ::1 noauth:false diff --git a/exposure-engine/common/pom.xml b/exposure-engine/common/pom.xml new file mode 100644 index 0000000..dfe6989 --- /dev/null +++ b/exposure-engine/common/pom.xml @@ -0,0 +1,89 @@ + + + 4.0.0 + + + exposure-engine + com.alu.e3 + 1.0.1 + .. + + + common + E3 Common + http://www.alcatel-lucent.com + + + jar + + + + com.hazelcast + hazelcast + 2.0.1 + compile + + + com.hazelcast + hazelcast-client + 2.0.1 + compile + + + com.hazelcast + hazelcast-spring + 2.0.1 + compile + + + com.hazelcast + hazelcast-hibernate + 2.0.1 + compile + + + org.apache.felix + org.apache.felix.framework + 3.0.9-fuse-03-11 + provided + + + org.apache.servicemix.bundles + org.apache.servicemix.bundles.commons-io + 1.4_1 + provided + + + org.bouncycastle + bcprov-jdk16 + 1.46 + compile + + + org.springframework.osgi + spring-osgi-extender + 1.2.0 + provided + + + org.springframework.aop + org.springframework + + + org.springframework.beans + org.springframework + + + org.springframework.context + org.springframework + + + org.springframework.core + org.springframework + + + + + + \ No newline at end of file diff --git a/exposure-engine/common/src/main/java/com/alu/e3/common/E3Constant.java b/exposure-engine/common/src/main/java/com/alu/e3/common/E3Constant.java new file mode 100644 index 0000000..7845cea --- /dev/null +++ b/exposure-engine/common/src/main/java/com/alu/e3/common/E3Constant.java @@ -0,0 +1,72 @@ +/** + * Copyright © 2012 Alcatel-Lucent. + * + * See the NOTICE file distributed with this work for additional + * information regarding copyright ownership. + * Licensed to you 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 com.alu.e3.common; + +import com.alu.e3.data.model.enumeration.ActionType; + +public class E3Constant { + + public static final String E3GATEWAY = "E3Gateway"; // represents a gateway ready to be provisioned but not yet active + public static final String E3SPEAKER = "E3Speaker"; // represents a speaker ready for election but not yet active + public static final String E3GATEWAY_ACTIVE = "E3GatewayA"; // represents an active gateway, i.e. ready to receive external connections + public static final String E3SPEAKER_ACTIVE = "E3SpeakerA"; // represents an active speaker + public static final String E3MANAGER = "E3Manager"; // represents the active manager + public static final String TDR_COLLECTOR = "TDRCollector"; // the downstream tdr collection machine + public static final String localhost = "localhost"; // the ip-address we use for the localhost + + public static final String DATA_STORAGE = "DataStorage"; + public static final String HAZELCAST_NAME = "E3Hz"; + public static final int HAZELCAST_PORT = 15701; + public static final int HAZELCAST_HANDLER_POOL_MAX_SIZE = 150; + public static final String SETTING_GATEWAY_NUMBER = "GatewayNumber"; + public static final int CACHE_ACK_TIMEOUT = 300000; + + public static final String GLOBAL_PROXY_SETTINGS = "GlobalProxySettings"; + + public static final int HEALTH_CHECK_POLLING_INTERVAL = 10000; // 10s + + public static final int GATEWAY_INTERNAL_DEFAULT_HEALTH_CHECK_PORT = 8082; + public static final int GATEWAY_DEFAULT_HEALTH_CHECK_PORT = 8083; + public static final int SPEAKER_DEFAULT_HEALTH_CHECK_PORT = 8084; + public static final int MANAGER_DEFAULT_HEALTH_CHECK_PORT = 8085; + + public static final String AGGREGATE_LOG_LOCATION = "/tmp/aggregate.log"; + + public final static ActionType DEFAULT_ERROR_ACTION = ActionType.REJECT; + + // Headers + public final static String CORRELATION_ID_HEADER_NAME = "X-LogCorrelationID"; + public final static String SUBSCRIBER_ID_HEADER_NAME = "X-SubscriberID"; + public final static String NOTIFY_URL_HEADER_NAME = "notifyUrl"; + public final static String DEFAULT_APP_AUTHKEY_HEADER_NAME = "X-App-AuthKey"; + + // TDR Collection Locations + public static final String TDR_BASE_PATH = "data/TDR"; + // These are reflected in the TDR Transfer Script. Do not modify unless the script's config is also modified + public static final String TDR_TRANSFER_CONFIG_PATH = "/home/e3/TDR_ProcessScript/config"; + public static final String TDR_TRANSFER_CONFIG_FILE = "dynamic_config"; + public static final String TDR_TRANSFER_CONFIG_KEY = "dynamic_key.pem"; + + public static final String REST_API_VERSION = "v1"; + + public static final String IS_MANAGER_PROPERTY_ENTRY = "e3.manager"; + public static final String IS_GATEWAY_PROPERTY_ENTRY = "e3.gateway"; + + public static final String MANAGER_IP_REPLACE_PATTERN = "%IP%"; +} diff --git a/exposure-engine/common/src/main/java/com/alu/e3/common/InvalidIDException.java b/exposure-engine/common/src/main/java/com/alu/e3/common/InvalidIDException.java new file mode 100644 index 0000000..e969a65 --- /dev/null +++ b/exposure-engine/common/src/main/java/com/alu/e3/common/InvalidIDException.java @@ -0,0 +1,32 @@ +/** + * Copyright © 2012 Alcatel-Lucent. + * + * See the NOTICE file distributed with this work for additional + * information regarding copyright ownership. + * Licensed to you 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 com.alu.e3.common; + +public class InvalidIDException extends RuntimeException { + + /** + * Generated serial version UID + */ + private static final long serialVersionUID = -8488797104674894669L; + + public InvalidIDException(String message) { + super(message); + } + +} diff --git a/exposure-engine/common/src/main/java/com/alu/e3/common/NotImplementedException.java b/exposure-engine/common/src/main/java/com/alu/e3/common/NotImplementedException.java new file mode 100644 index 0000000..733d182 --- /dev/null +++ b/exposure-engine/common/src/main/java/com/alu/e3/common/NotImplementedException.java @@ -0,0 +1,31 @@ +/** + * Copyright © 2012 Alcatel-Lucent. + * + * See the NOTICE file distributed with this work for additional + * information regarding copyright ownership. + * Licensed to you 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 com.alu.e3.common; + +public class NotImplementedException extends RuntimeException { + + /** + * + */ + private static final long serialVersionUID = -6197936817622973672L; + + public NotImplementedException(String message) { + super(message); + } +} diff --git a/exposure-engine/common/src/main/java/com/alu/e3/common/NullHazelcastTableException.java b/exposure-engine/common/src/main/java/com/alu/e3/common/NullHazelcastTableException.java new file mode 100644 index 0000000..4ba2188 --- /dev/null +++ b/exposure-engine/common/src/main/java/com/alu/e3/common/NullHazelcastTableException.java @@ -0,0 +1,32 @@ +/** + * Copyright © 2012 Alcatel-Lucent. + * + * See the NOTICE file distributed with this work for additional + * information regarding copyright ownership. + * Licensed to you 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 com.alu.e3.common; + +public class NullHazelcastTableException extends RuntimeException { + + /** + * Generated. + */ + private static final long serialVersionUID = 1425728768454131095L; + + public NullHazelcastTableException(String message) { + super(message); + } + +} diff --git a/exposure-engine/common/src/main/java/com/alu/e3/common/caching/BasicCacheManager.java b/exposure-engine/common/src/main/java/com/alu/e3/common/caching/BasicCacheManager.java new file mode 100644 index 0000000..71cc09f --- /dev/null +++ b/exposure-engine/common/src/main/java/com/alu/e3/common/caching/BasicCacheManager.java @@ -0,0 +1,50 @@ +/** + * Copyright © 2012 Alcatel-Lucent. + * + * See the NOTICE file distributed with this work for additional + * information regarding copyright ownership. + * Licensed to you 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 com.alu.e3.common.caching; + +import java.util.Map; + +public class BasicCacheManager implements ICacheManager { + + @Override + public ICacheTable createTable(String name, boolean isReplicated, Map properties) { + return null; + } + + @Override + public ICacheTable createOrGetTable(String name, boolean isReplicated, Map properties) { + return null; + } + + @Override + public ICacheQueue createQueue(String name, Map properties) { + return null; + } + + @Override + public ICacheQueue getOrCreateQueue(String name, Map properties) { + return null; + } + + @Override + public IAckCacheTable createAckTable(String name, boolean isReplicated, Map properties) { + return null; + } + +} diff --git a/exposure-engine/common/src/main/java/com/alu/e3/common/caching/HashCacheTable.java b/exposure-engine/common/src/main/java/com/alu/e3/common/caching/HashCacheTable.java new file mode 100644 index 0000000..9e0f949 --- /dev/null +++ b/exposure-engine/common/src/main/java/com/alu/e3/common/caching/HashCacheTable.java @@ -0,0 +1,143 @@ +/** + * Copyright © 2012 Alcatel-Lucent. + * + * See the NOTICE file distributed with this work for additional + * information regarding copyright ownership. + * Licensed to you 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 com.alu.e3.common.caching; + +import java.util.ArrayList; +import java.util.Collection; +import java.util.Collections; +import java.util.Hashtable; +import java.util.List; +import java.util.Set; + +import com.alu.e3.data.DataEntryEvent; + +public class HashCacheTable implements ICacheTable { + + private Hashtable hashTable; + private List> listeners; + + public HashCacheTable() { + hashTable = new Hashtable(); + listeners = Collections.synchronizedList(new ArrayList>()); + } + + @Override + public boolean set(K key, V value) { + hashTable.put(key, value); + + DataEntryEvent event = null; + + if(listeners.size() > 0) { + if(containsKey(key)) { + event = new DataEntryEvent(key, value); + + for(IEntryListener listener : listeners) { + listener.entryUpdated(event); + } + + } else { + event = new DataEntryEvent(key, value); + + for(IEntryListener listener : listeners) { + listener.entryAdded(event); + } + } + } + + return true; + + } + + @Override + public V get(K key) { + return hashTable.get(key); + } + + @Override + public V remove(K key) { + + DataEntryEvent event = null; + + if(listeners.size() > 0) { + event = new DataEntryEvent(key, null); + + for(IEntryListener listener : listeners) { + listener.entryRemoved(event); + } + } + + return hashTable.remove(key); + } + + @Override + public Set getAllKeys() { + return hashTable.keySet(); + } + + @Override + public Collection getAllValues() { + return hashTable.values(); + } + + @Override + public boolean containsKey(K key) { + return hashTable.containsKey(key); + } + + @Override + public void lock(K key) { + // Nothing to do + } + + @Override + public void unlock(K key) { + // Nothing to do + } + + @Override + public void clear() { + hashTable.clear(); + } + @Override + public void addEntryListener(final IEntryListener listener) { + listeners.add(listener); + } + + @Override + public void removeEntryListener(IEntryListener listener) { + listeners.remove(listener); + } + + @Override + public String getName() { + return "HashCacheTable"; + } + + @Override + public void reloadSlave(String ip) { + // TODO Auto-generated method stub + + } + + @Override + public boolean set(K key, V value, String instanceIP) { + // TODO Auto-generated method stub + return false; + } +} diff --git a/exposure-engine/common/src/main/java/com/alu/e3/common/caching/HazelcastAckCache.java b/exposure-engine/common/src/main/java/com/alu/e3/common/caching/HazelcastAckCache.java new file mode 100644 index 0000000..00d7b44 --- /dev/null +++ b/exposure-engine/common/src/main/java/com/alu/e3/common/caching/HazelcastAckCache.java @@ -0,0 +1,380 @@ +/** + * Copyright © 2012 Alcatel-Lucent. + * + * See the NOTICE file distributed with this work for additional + * information regarding copyright ownership. + * Licensed to you 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 com.alu.e3.common.caching; + +import java.util.Set; +import java.util.concurrent.TimeUnit; + +import com.alu.e3.common.E3Constant; +import com.alu.e3.common.caching.internal.MapHandler; +import com.alu.e3.common.caching.internal.HandlerPool; +import com.alu.e3.common.caching.internal.QueueHandler; +import com.alu.e3.common.tools.CommonTools; +import com.alu.e3.data.CacheAck; +import com.hazelcast.core.IMap; +import com.hazelcast.core.IQueue; + + +public class HazelcastAckCache extends HazelcastCache { + + protected HandlerPool> queueHandlerPool = new HandlerPool>(E3Constant.HAZELCAST_HANDLER_POOL_MAX_SIZE); + + @Override + public boolean set(K key, V value) { + + String queueName = value.getId(); + + boolean isManagerOnly = true; + boolean ack = true; + try { + if (isReplicated && topologyClient != null) { + Set instances = getAllInstanceIPs(); + MapHandler mapHandler = null; + QueueHandler queueHandler = null; + for (String instanceIP : instances) { + IQueue queue = null; + try { + + mapHandler = mapHandlerPool.get(new StringBuffer(instanceIP).append(localMap.getName()).toString()); + if (mapHandler==null) + { + mapHandler = new MapHandler(instanceIP, localMap.getName()); + mapHandlerPool.put(new StringBuffer(instanceIP).append(localMap.getName()).toString(), mapHandler); + }else + { + if (!mapHandler.isClientActive()) + { + mapHandler.dispose(); + String poolKey = new StringBuffer(instanceIP).append(localMap.getName()).toString(); + mapHandlerPool.remove(poolKey); + mapHandler = new MapHandler(instanceIP, localMap.getName()); + mapHandlerPool.put(poolKey, mapHandler); + } + } + + queueHandler = queueHandlerPool.get(new StringBuffer(instanceIP).append(queueName).toString()); + if (queueHandler==null) + { + queueHandler = new QueueHandler(instanceIP, queueName); + queueHandlerPool.put(new StringBuffer(instanceIP).append(queueName).toString(), queueHandler); + }else + { + if (!queueHandler.isClientActive()) + { + queueHandler.dispose(); + String poolKey = new StringBuffer(instanceIP).append(queueName).toString(); + queueHandlerPool.remove(poolKey); + queueHandler = new QueueHandler(instanceIP, queueName); + queueHandlerPool.put(poolKey, queueHandler); + } + } + + IMap map = mapHandler.getMap(); + if (map == null) + return false; + + // Getting the queue on which the listener will post the ACK + queue = queueHandler.getQueue(); + if (queue == null) + return false; + + // Remembering if the local machine is a Manager only or also a Gateway + // We are browsing gateways so if the gateway is the local machine then we + // are no more a manager only machine + if (CommonTools.isLocal(instanceIP)) { + isManagerOnly = false; + } + + ClassLoader previousClassLoader = Thread.currentThread().getContextClassLoader(); + Thread.currentThread().setContextClassLoader(HazelcastCacheManager.class.getClassLoader()); + + // Setting the value + map.put(key, value); + + // Waiting for the acknowledgment + CacheAck cacheAck = queue.poll(E3Constant.CACHE_ACK_TIMEOUT, TimeUnit.MILLISECONDS); + if(cacheAck == null) { + logger.error("Acknowledgment timeout for setting value on " + instanceIP); + } + + Thread.currentThread().setContextClassLoader(previousClassLoader); + + queue.destroy(); + + if(cacheAck == null || cacheAck == CacheAck.KO) { + ack = false; + break; + } + } catch (IllegalStateException ise) { + logger.warn("Was not able to set the entry " + key + " of the cache " + localMap.getName() + " for gateway " + instanceIP + ". This probably means that this instance is down."); + } finally { + if (queue != null) + queue.destroy(); + } + } + + // Put the value only if we are a single manager (if also a gateway, the value has been added before, in the loop) + // If we are manager only we do not need to wait for the ack + if(isManagerOnly) { + + ClassLoader previousClassLoader = Thread.currentThread().getContextClassLoader(); + Thread.currentThread().setContextClassLoader(HazelcastCacheManager.class.getClassLoader()); + + localMap.put(key, value); + + Thread.currentThread().setContextClassLoader(previousClassLoader); + } + } + } catch(InterruptedException e) { + logger.error("Unable to set value with ack", e); + ack = false; + } + + return ack; + } + + @Override + public boolean set(K key, V value, String instanceIP) { + String queueName = value.getId(); + + boolean isManagerOnly = true; + boolean ack = true; + try { + MapHandler mapHandler = null; + QueueHandler queueHandler = null; + IQueue queue = null; + try { + + mapHandler = mapHandlerPool.get(new StringBuffer(instanceIP).append(localMap.getName()).toString()); + if (mapHandler==null) + { + mapHandler = new MapHandler(instanceIP, localMap.getName()); + mapHandlerPool.put(new StringBuffer(instanceIP).append(localMap.getName()).toString(), mapHandler); + }else + { + if (!mapHandler.isClientActive()) + { + mapHandler.dispose(); + String poolKey = new StringBuffer(instanceIP).append(localMap.getName()).toString(); + mapHandlerPool.remove(poolKey); + mapHandler = new MapHandler(instanceIP, localMap.getName()); + mapHandlerPool.put(poolKey, mapHandler); + } + } + + queueHandler = queueHandlerPool.get(new StringBuffer(instanceIP).append(queueName).toString()); + if (queueHandler==null) + { + queueHandler = new QueueHandler(instanceIP, queueName); + queueHandlerPool.put(new StringBuffer(instanceIP).append(queueName).toString(), queueHandler); + } else + { + if (!queueHandler.isClientActive()) + { + queueHandler.dispose(); + String poolKey = new StringBuffer(instanceIP).append(queueName).toString(); + queueHandlerPool.remove(poolKey); + queueHandler = new QueueHandler(instanceIP, queueName); + queueHandlerPool.put(poolKey, queueHandler); + } + } + + IMap map = mapHandler.getMap(); + if (map == null) + return false; + + // Getting the queue on which the listener will post the ACK + queue = queueHandler.getQueue(); + if (queue == null) + return false; + + // Remembering if the local machine is a Manager only or also a Gateway + // We are browsing gateways so if the gateway is the local machine then we + // are no more a manager only machine + if (CommonTools.isLocal(instanceIP)) { + isManagerOnly = false; + } + + ClassLoader previousClassLoader = Thread.currentThread().getContextClassLoader(); + Thread.currentThread().setContextClassLoader(HazelcastCacheManager.class.getClassLoader()); + + // Setting the value + map.put(key, value); + + // Waiting for the acknowledgment + CacheAck cacheAck = queue.poll(E3Constant.CACHE_ACK_TIMEOUT, TimeUnit.MILLISECONDS); + if(cacheAck == null) { + logger.error("Acknowledgment timeout for setting value on " + instanceIP); + } + + Thread.currentThread().setContextClassLoader(previousClassLoader); + + queue.destroy(); + + if(cacheAck == null || cacheAck == CacheAck.KO) { + ack = false; + } + } finally { + if (queue != null) + queue.destroy(); + } + + // Put the value only if we are a single manager (if also a gateway, the value has been added before, in the loop) + // If we are manager only we do not need to wait for the ack + if(isManagerOnly) { + + ClassLoader previousClassLoader = Thread.currentThread().getContextClassLoader(); + Thread.currentThread().setContextClassLoader(HazelcastCacheManager.class.getClassLoader()); + + Thread.currentThread().setContextClassLoader(previousClassLoader); + } + } catch(InterruptedException e) { + logger.error("Unable to set value with ack", e); + ack = false; + } + + return ack; + } + + @Override + public V remove(Object key) { + V value = get(key); + if(value == null) + return null; // not grave error if the data does not exist? + + String queueName = value.getId(); + + boolean ack = true; + + if (localMap == null) { + logger.error("Attempt to remove a key in a cache without a map"); + ack = false; + } else { + + // to know if the current machine is a manager only or also a gateway + boolean isManagerOnly = true; + IQueue queue = null; + try { + if (isReplicated && topologyClient != null) { + Set instances = getAllInstanceIPs(); + + for (String instanceIP : instances) { + + MapHandler mapHandler = mapHandlerPool.get(new StringBuffer(instanceIP).append(localMap.getName()).toString()); + if (mapHandler==null) + { + mapHandler = new MapHandler(instanceIP, localMap.getName()); + mapHandlerPool.put(new StringBuffer(instanceIP).append(localMap.getName()).toString(), mapHandler); + }else + { + if (!mapHandler.isClientActive()) + { + mapHandler.dispose(); + String poolKey = new StringBuffer(instanceIP).append(localMap.getName()).toString(); + mapHandlerPool.remove(poolKey); + mapHandler = new MapHandler(instanceIP, localMap.getName()); + mapHandlerPool.put(poolKey, mapHandler); + } + } + + QueueHandler queueHandler = queueHandlerPool.get(new StringBuffer(instanceIP).append(queueName).toString()); + if (queueHandler==null) + { + queueHandler = new QueueHandler(instanceIP, queueName); + queueHandlerPool.put(new StringBuffer(instanceIP).append(queueName).toString(), queueHandler); + }else + { + if (!queueHandler.isClientActive()) + { + String poolKey = new StringBuffer(instanceIP).append(queueName).toString(); + queueHandler.dispose(); + queueHandlerPool.remove(poolKey); + queueHandler = new QueueHandler(instanceIP, queueName); + queueHandlerPool.put(poolKey, queueHandler); + } + } + + try { + + IMap map = mapHandler.getMap(); + if (map == null) + return null; + + queue = queueHandler.getQueue(); + if (queue == null) + return null; + + // Remembering if the local machine is a Manager only or also a Gateway + // We are browsing gateways so if the gateway is the local machine then we + // are no more a manager only machine + if (CommonTools.isLocal(instanceIP)) { + isManagerOnly = false; + } + + ClassLoader previousClassLoader = Thread.currentThread().getContextClassLoader(); + Thread.currentThread().setContextClassLoader(HazelcastCacheManager.class.getClassLoader()); + + // Removing the value + map.remove(key); + + // Waiting for the acknowledgment + CacheAck cacheAck = queue.poll(E3Constant.CACHE_ACK_TIMEOUT, TimeUnit.MILLISECONDS); + if(cacheAck == null) { + logger.error("Acknowledgment timeout for removing value on " + instanceIP); + } + + Thread.currentThread().setContextClassLoader(previousClassLoader); + + if(cacheAck == null || cacheAck == CacheAck.KO) { + ack = false; + break; + } + } catch (IllegalStateException ise) { + logger.warn("Was not able to set the entry " + key + " of the cache " + localMap.getName() + " for gateway " + instanceIP + ". This probably means that this instance is down."); + } finally { + if (queue != null) + queue.destroy(); + } + } + + // Remove the value only if we are a single manager (if also a gateway, the value has been removed before) + // If we are manager we do not need to wait for the ack + if(isManagerOnly) { + + ClassLoader previousClassLoader = Thread.currentThread().getContextClassLoader(); + Thread.currentThread().setContextClassLoader(HazelcastCacheManager.class.getClassLoader()); + + localMap.remove(key); + + Thread.currentThread().setContextClassLoader(previousClassLoader); + } + } + } catch(InterruptedException e) { + logger.error("Unable to set value with ack", e); + ack = false; + } + } + + if(ack) + return value; + else + return null; + } + +} diff --git a/exposure-engine/common/src/main/java/com/alu/e3/common/caching/HazelcastCache.java b/exposure-engine/common/src/main/java/com/alu/e3/common/caching/HazelcastCache.java new file mode 100644 index 0000000..c0e6428 --- /dev/null +++ b/exposure-engine/common/src/main/java/com/alu/e3/common/caching/HazelcastCache.java @@ -0,0 +1,458 @@ +/** + * Copyright © 2012 Alcatel-Lucent. + * + * See the NOTICE file distributed with this work for additional + * information regarding copyright ownership. + * Licensed to you 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 com.alu.e3.common.caching; + +import java.security.InvalidParameterException; +import java.util.Collection; +import java.util.HashMap; +import java.util.HashSet; +import java.util.Map; +import java.util.Set; + +import com.alu.e3.common.E3Constant; +import com.alu.e3.common.caching.internal.HandlerPool; +import com.alu.e3.common.caching.internal.MapHandler; +import com.alu.e3.common.logging.Category; +import com.alu.e3.common.logging.CategoryLogger; +import com.alu.e3.common.logging.CategoryLoggerFactory; +import com.alu.e3.common.osgi.api.ITopologyClient; +import com.alu.e3.data.DataEntryEvent; +import com.hazelcast.client.ClientConfig; +import com.hazelcast.client.HazelcastClient; +import com.hazelcast.core.EntryEvent; +import com.hazelcast.core.EntryListener; +import com.hazelcast.core.IMap; + +public class HazelcastCache implements ICacheTable { + + protected static final CategoryLogger logger = CategoryLoggerFactory.getLogger(HazelcastCache.class, Category.DMGR); + + protected IMap localMap; + protected boolean isReplicated = false; + protected String name; + + private Map, EntryListener> entryListenersMap; + protected ITopologyClient topologyClient; + + protected HandlerPool> mapHandlerPool = new HandlerPool>(E3Constant.HAZELCAST_HANDLER_POOL_MAX_SIZE); + + + public void setTopologyClient(ITopologyClient topologyClient) { + this.topologyClient = topologyClient; + } + + public IMap getMap() { + return localMap; + } + + @Override + public String getName() { + return name; + } + + public void setMap(IMap map) throws InvalidParameterException { + if (map == null) + throw new InvalidParameterException("The parameter map is mandatory"); + + this.localMap = map; + this.name = map.getName(); + } + + public void setIsReplicated(boolean isReplicated) { + this.isReplicated = isReplicated; + } + + @Override + public V get(Object key) { + if (localMap == null) { + logger.error("Attempt to get a key on a cache without a map"); + } + + ClassLoader previousClassLoader = Thread.currentThread().getContextClassLoader(); + Thread.currentThread().setContextClassLoader(HazelcastCacheManager.class.getClassLoader()); + + V retValue = localMap == null ? null : localMap.get(key); + + Thread.currentThread().setContextClassLoader(previousClassLoader); + + return retValue; + } + + @Override + // ---------------------------------------------- + // /!\ Do not forget to check HazelcastAckCache + // ---------------------------------------------- + public boolean set(K key, V value) { + if (localMap == null) { + logger.error("Attempt to put a key in a cache without a map"); + return false; + } + + ClassLoader previousClassLoader = Thread.currentThread().getContextClassLoader(); + Thread.currentThread().setContextClassLoader(HazelcastCacheManager.class.getClassLoader()); + + localMap.put(key, value); + + if (isReplicated && topologyClient != null) { + Set instances = getAllInstanceIPs(); + + MapHandler mapHandler = null; + for (String instanceIP : instances) { + try { + mapHandler = mapHandlerPool.get(new StringBuffer(instanceIP).append(localMap.getName()).toString()); + if (mapHandler==null) + { + mapHandler = new MapHandler(instanceIP, localMap.getName()); + mapHandlerPool.put(new StringBuffer(instanceIP).append(localMap.getName()).toString(), mapHandler); + }else + { + if (!mapHandler.isClientActive()) + { + mapHandler.dispose(); + String poolKey = new StringBuffer(instanceIP).append(localMap.getName()).toString(); + mapHandlerPool.remove(poolKey); + mapHandler = new MapHandler(instanceIP, localMap.getName()); + mapHandlerPool.put(poolKey, mapHandler); + } + } + + if (!mapHandler.isLocal()) { + IMap map = mapHandler.getMap(); + map.put(key, value); + } + } catch (IllegalStateException ise) { + logger.warn("Was not able to set the entry " + key + " of the cache " + localMap.getName() + " for gateway " + instanceIP + ". This probably means that this instance is down.", ise); + } catch(Exception e){ + logger.error("Unexpected error updating the entry " + key + " of the cache " + localMap.getName() + " for gateway " + instanceIP, e); + } + + } + } + + Thread.currentThread().setContextClassLoader(previousClassLoader); + + return true; + } + + @Override + public boolean set(K key, V value, String instanceIP) { + logger.debug("Setting map:{}, key:{} value:{} on node ip:{}", new Object[]{name, key, value, instanceIP}); + + if (localMap == null) { + logger.error("Attempt to put a key in a cache without a map"); + return false; + } + + ClassLoader previousClassLoader = Thread.currentThread().getContextClassLoader(); + Thread.currentThread().setContextClassLoader(HazelcastCacheManager.class.getClassLoader()); + + MapHandler mapHandler = null; + try { + mapHandler = mapHandlerPool.get(new StringBuffer(instanceIP).append(localMap.getName()).toString()); + if (mapHandler==null) + { + logger.debug("Creating MapHandler map:{}, key:{} on node ip:{}", new Object[]{name, key, instanceIP}); + mapHandler = new MapHandler(instanceIP, localMap.getName()); + mapHandlerPool.put(new StringBuffer(instanceIP).append(localMap.getName()).toString(), mapHandler); + }else + { + logger.debug("Reusing MapHandler map:{}, key:{} on node ip:{}", new Object[]{name, key, instanceIP}); + if (!mapHandler.isClientActive()) + { + logger.debug("Recreating MapHandler map:{}, key:{} on node ip:{}", new Object[]{name, key, instanceIP}); + mapHandler.dispose(); + String poolKey = new StringBuffer(instanceIP).append(localMap.getName()).toString(); + mapHandlerPool.remove(poolKey); + mapHandler = new MapHandler(instanceIP, localMap.getName()); + mapHandlerPool.put(poolKey, mapHandler); + } + } + + if (! mapHandler.isLocal()) { + logger.debug("Pushing value map:{}, key:{} on node ip:{}", new Object[]{name, key, instanceIP}); + IMap map = mapHandler.getMap(); + map.put(key, value); + } + } + catch (IllegalStateException ise) { + logger.error("Was not able to set the entry " + key + " of the cache " + localMap.getName() + " for gateway " + instanceIP + ". This probably means that this instance is down.", ise); + } + + Thread.currentThread().setContextClassLoader(previousClassLoader); + + return true; + } + + @Override + public void reloadSlave(String ip) { + logger.debug("Reloading table:{} for node ip:{}", name, ip); + + if (localMap == null) { + logger.error("Attempt to reload a slave cache from a master with no map"); + return; + } + + MapHandler mapHandler = mapHandlerPool.get(new StringBuffer(ip).append(localMap.getName()).toString()); + try { + if (mapHandler==null) + { + logger.debug("Creating mapHandler for table:{} for node ip:{}", name, ip); + mapHandler = new MapHandler(ip, localMap.getName()); + mapHandlerPool.put(new StringBuffer(ip).append(localMap.getName()).toString(), mapHandler); + }else + { + logger.debug("Reusing mapHandler for table:{} for node ip:{}", name, ip); + if (!mapHandler.isClientActive()) + { + logger.debug("Recreating mapHandler for table:{} for node ip:{}", name, ip); + mapHandler.dispose(); + String poolKey = new StringBuffer(ip).append(localMap.getName()).toString(); + mapHandlerPool.remove(poolKey); + mapHandler = new MapHandler(ip, localMap.getName()); + mapHandlerPool.put(poolKey, mapHandler); + } + } + IMap map = mapHandler.getMap(); + if (!mapHandler.isLocal()) { + logger.debug("Pushing allData for table:{} for node ip:{}", name, ip); + map.putAll(localMap); + } + } catch (Exception e) { + logger.error("Unable to reload slave", e); + } + } + + @Override + // ---------------------------------------------- + // /!\ Do not forget to check HazelcastAckCache + // ---------------------------------------------- + public V remove(Object key) { + + if (localMap == null) { + logger.error("Attempt to remove a key in a cache without a map"); + return null; + } + + ClassLoader previousClassLoader = Thread.currentThread().getContextClassLoader(); + Thread.currentThread().setContextClassLoader(HazelcastCacheManager.class.getClassLoader()); + + V value = localMap.remove(key); + + if (value == null) { + logger.error("Error removing a key from the master cache"); + Thread.currentThread().setContextClassLoader(previousClassLoader); + return null; + } + + if (isReplicated && topologyClient != null) { + Set instances = getAllInstanceIPs(); + + MapHandler mapHandler = null; + for (String instanceIP : instances) { + try { + mapHandler = mapHandlerPool.get(new StringBuffer(instanceIP).append(localMap.getName()).toString()); + if (mapHandler==null) + { + mapHandler = new MapHandler(instanceIP, localMap.getName()); + mapHandlerPool.put(new StringBuffer(instanceIP).append(localMap.getName()).toString(), mapHandler); + }else + { + if (!mapHandler.isClientActive()) + { + mapHandler.dispose(); + String poolKey = new StringBuffer(instanceIP).append(localMap.getName()).toString(); + mapHandlerPool.remove(poolKey); + mapHandler = new MapHandler(instanceIP, localMap.getName()); + mapHandlerPool.put(poolKey, mapHandler); + } + } + + IMap map = mapHandler.getMap(); + if (! mapHandler.isLocal()) { + map.remove(key); + } + } catch (IllegalStateException ise) { + logger.warn("Was not able to set the entry " + key + " of the cache " + localMap.getName() + " for gateway " + instanceIP + ". This probably means that this instance is down."); + } finally { + if (mapHandler != null) + mapHandler.dispose(); + } + } + } + + Thread.currentThread().setContextClassLoader(previousClassLoader); + + return value; + } + + protected Set getAllInstanceIPs() { + Set instanceIPs = new HashSet(); + + // add all gateway internal IPs to use + instanceIPs.addAll(getInternalIPs(E3Constant.E3GATEWAY)); + // add all gateway external IPs to use + instanceIPs.addAll(getExternalIPs(E3Constant.E3GATEWAY)); + + // add all speaker internal IPs to use + instanceIPs.addAll(getInternalIPs(E3Constant.E3SPEAKER)); + // add all speaker external IPs to use + instanceIPs.addAll(getExternalIPs(E3Constant.E3SPEAKER)); + + // Need to check if the same instance is twice + + return instanceIPs; + } + + private Set getInternalIPs(String type) { + // get manager area + String managerArea = topologyClient.getMyArea(); + logger.debug("Current manager area '" + managerArea + "'"); + + logger.debug("Adding gateway internal ips for manager area '" + managerArea + "'"); + // use internal ip for gateways having the same area than the manager + return topologyClient.getInternalIPsOfType(type, managerArea); + } + + private Set getExternalIPs(String type) { + // get all other areas than the manager's one + Set otherAreas = topologyClient.getAllOtherAreas(); + Set externalGatewayIPs = new HashSet(); + + // iterate through area list to gather external gateway ips + for (String area : otherAreas) { + logger.debug("Adding gateway external ips non manager for area '" + area + "'"); + externalGatewayIPs.addAll(topologyClient.getExternalIPsOfType(type, area)); + } + + return externalGatewayIPs; + } + + @Override + public boolean containsKey(Object key) { + if (localMap == null) { + logger.error("Attempt to check if a key is contained in a cache without a map"); + } + + return localMap == null ? false : localMap.containsKey(key); + } + + @Override + public Set getAllKeys() { + if (localMap == null) { + logger.error("Attempt to get all keys of a cache without a map"); + } + + return localMap == null ? new HashSet() : localMap.keySet(); + } + + @Override + public Collection getAllValues() { + if (localMap == null) { + logger.error("Attempt to get all values of a cache without a map"); + } + + return localMap == null ? new HashSet() : localMap.values(); + } + + protected HazelcastClient getHazelcastClient(String ip) { + + ClientConfig clientConfig = new ClientConfig(); + + clientConfig.addAddress(ip + ":" + E3Constant.HAZELCAST_PORT); + HazelcastClient client = HazelcastClient.newHazelcastClient(clientConfig); + + return client; + } + + @Override + public void lock(K key) { + if (localMap == null) { + logger.error("Attempt to lock a key in a cache without a map"); + } else { + localMap.lock(key); + } + } + + @Override + public void unlock(K key) { + if (localMap == null) { + logger.error("Attempt to unlock a key in a cache without a map"); + } else { + localMap.unlock(key); + } + } + + @Override + public void clear() { + if (localMap == null) { + logger.error("Attempt to clear a cache without a map"); + } else { + localMap.clear(); + } + } + + @Override + public void addEntryListener(final IEntryListener listener) { + EntryListener hzListener = new EntryListener() { + + @Override + public void entryAdded(EntryEvent event) { + DataEntryEvent dataEntryEvent = new DataEntryEvent(event.getKey(), event.getValue()); + listener.entryAdded(dataEntryEvent); + } + + @Override + public void entryRemoved(EntryEvent event) { + DataEntryEvent dataEntryEvent = new DataEntryEvent(event.getKey(), event.getValue()); + listener.entryRemoved(dataEntryEvent); + } + + @Override + public void entryUpdated(EntryEvent event) { + DataEntryEvent dataEntryEvent = new DataEntryEvent(event.getKey(), event.getValue()); + listener.entryUpdated(dataEntryEvent); + } + + @Override + public void entryEvicted(EntryEvent event) { + + } + }; + + getEntryListenersMap().put(listener, hzListener); + + localMap.addEntryListener(hzListener, true); + } + + @Override + public void removeEntryListener(IEntryListener listener) { + EntryListener hzListener = getEntryListenersMap().get(listener); + getEntryListenersMap().remove(listener); + localMap.removeEntryListener(hzListener); + } + + /** + * @return the entryListenersMap + */ + protected Map, EntryListener> getEntryListenersMap() { + if (entryListenersMap == null) + entryListenersMap = new HashMap, EntryListener>(); + return entryListenersMap; + } +} diff --git a/exposure-engine/common/src/main/java/com/alu/e3/common/caching/HazelcastCacheManager.java b/exposure-engine/common/src/main/java/com/alu/e3/common/caching/HazelcastCacheManager.java new file mode 100644 index 0000000..eff24d7 --- /dev/null +++ b/exposure-engine/common/src/main/java/com/alu/e3/common/caching/HazelcastCacheManager.java @@ -0,0 +1,270 @@ +/** + * Copyright © 2012 Alcatel-Lucent. + * + * See the NOTICE file distributed with this work for additional + * information regarding copyright ownership. + * Licensed to you 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 com.alu.e3.common.caching; + +import java.util.HashMap; +import java.util.Map; + +import com.alu.e3.common.E3Constant; +import com.alu.e3.common.logging.Category; +import com.alu.e3.common.logging.CategoryLogger; +import com.alu.e3.common.logging.CategoryLoggerFactory; +import com.alu.e3.common.osgi.api.ITopologyClient; +import com.hazelcast.config.Config; +import com.hazelcast.config.MapConfig; +import com.hazelcast.config.QueueConfig; +import com.hazelcast.core.Hazelcast; +import com.hazelcast.core.HazelcastInstance; +import com.hazelcast.core.IMap; +import com.hazelcast.core.IQueue; + +public class HazelcastCacheManager implements ICacheManager { + + private static CategoryLogger logger = CategoryLoggerFactory.getLogger(HazelcastCacheManager.class, Category.DMGR); + + protected ITopologyClient topologyClient; + + protected HazelcastInstance hazelcastInstance; + + protected Map> tables = new HashMap>(); + protected Map> queues = new HashMap>(); + + public HazelcastCacheManager() {} + + public void init() { + init(false); + } + + public void init(boolean portAutoIncrement) { + logger.debug("Init of cacheManager with portAutoIncrement: {}", portAutoIncrement); + // check if an Hazelcast instance is already running + setHazelcastInstance(Hazelcast.getHazelcastInstanceByName(E3Constant.HAZELCAST_NAME)); + + if (this.hazelcastInstance != null) { + // should not happen except when running the JUnit + logger.warn("HazelcastCacheManager: HazelcastInstance is already running"); + } + else { + logger.debug("Normal start of new HazelcastInstance"); + // create the instance + Config cfg = new Config(); + cfg.setPort(E3Constant.HAZELCAST_PORT); + cfg.setPortAutoIncrement(portAutoIncrement); + + cfg.setInstanceName(E3Constant.HAZELCAST_NAME); + + cfg.getNetworkConfig().getJoin().getMulticastConfig().setEnabled(false); + + // Close doors that are not supposed to be opened + cfg.setProperty("hazelcast.memcache.enabled", "false"); + cfg.setProperty("hazelcast.rest.enabled", "false"); + cfg.setProperty("hazelcast.mancenter.enabled", "false"); + + cfg.setProperty("hazelcast.version.check.enabled", "false"); + + + setHazelcastInstance(Hazelcast.newHazelcastInstance(cfg)); + + logger.debug("Normal start: done."); + } + } + + /** + * Called when the bundle is stopped. + */ + public void destroy() { + logger.debug("Destroy HazelcastInstance ..."); + this.hazelcastInstance.getLifecycleService().shutdown(); + + int attempt = 10; + do { + logger.debug("Waiting HazelcastInstance termination, attempt:{}", attempt); + try { + Thread.sleep(1000L); + } catch (InterruptedException e) { + logger.error("Problem while waiting HazelcastInstance to terminate !", e); + } + } while(this.hazelcastInstance.getLifecycleService().isRunning() && attempt-- > 0 ); + + // Force killing it ! + if (this.hazelcastInstance.getLifecycleService().isRunning()) + this.hazelcastInstance.getLifecycleService().kill(); + + logger.debug("Destroy: Done and forced."); + } + + public void setTopologyClient(ITopologyClient topologyClient) { + logger.debug("Set ITopologyClient on cacheManager"); + + this.topologyClient = topologyClient; + } + + public void setHazelcastInstance(HazelcastInstance hazelcastInstance) { + this.hazelcastInstance = hazelcastInstance; + } + + @Override + public ICacheTable createTable(String name, boolean isReplicated, Map properties) { + // In this method context is used as generic declaration instead of + // cause this whole class is not generic and + // we may keep in mind this.'tables' is a generic on (multiple K,V different couples). + if(tables.get(name) == null) { + setTableProperties(name, properties); + HazelcastCache table = new HazelcastCache(); + tables.put(name, table); + + IMap map = hazelcastInstance.getMap(name); + table.setMap(map); + table.setTopologyClient(topologyClient); + table.setIsReplicated(isReplicated); + + return table; + } + else { + // error: already created + return null; + } + } + + @Override + @SuppressWarnings("unchecked") + public ICacheTable createOrGetTable(String name, boolean isReplicated, Map properties) { + ICacheTable table = createTable(name, isReplicated, properties); + // Here, we really try a cast from this.'table' elements + // which are to a specific one . + if (table == null) + table = (ICacheTable) tables.get(name); + return table; + } + + @Override + public ICacheTable createAckTable(String name, boolean isReplicated, Map properties) { + // Same as createTable(...) + // but with + if(tables.get(name) == null) { + setTableProperties(name, properties); + + HazelcastAckCache table = new HazelcastAckCache(); + tables.put(name, table); + + IMap map = hazelcastInstance.getMap(name); + table.setMap(map); + table.setTopologyClient(topologyClient); + table.setIsReplicated(isReplicated); + + return table; + } + else { + // error: already created + return null; + } + } + + @Override + public ICacheQueue createQueue(String name, Map properties) { + if(queues.get(name) == null) { + setQueueProperties(name, properties); + + HazelcastCacheQueue queue = new HazelcastCacheQueue(); + queues.put(name, queue); + + IQueue hzQueue = hazelcastInstance.getQueue(name); + queue.setQueue(hzQueue); + // queue.setTopology(topology); + // queue.setIsReplicated(isReplicated); + + return queue; + } + else { + // error: already created + return null; + } + } + + @Override + public ICacheQueue getOrCreateQueue(String name, Map properties) { + @SuppressWarnings("unchecked") + ICacheQueue queue = (ICacheQueue) queues.get(name); + if(queue == null) + queue = createQueue(name, properties); + + return queue; + } + + private void setTableProperties(String name, Map properties) { + if(properties != null) { + Config cfg = hazelcastInstance.getConfig(); + MapConfig mapCfg = cfg.getMapConfig(name); + if(mapCfg == null) { + mapCfg = new MapConfig(); + cfg.addMapConfig(mapCfg); + } + + String value = null; + if((value = properties.get("eviction-policy")) != null) { + mapCfg.setEvictionPolicy(value); + } + + if((value = properties.get("eviction-percentage")) != null) { + mapCfg.setEvictionPercentage(Integer.parseInt(value)); + } + + if((value = properties.get("time-to-live-seconds")) != null) { + mapCfg.setTimeToLiveSeconds(Integer.parseInt(value)); + } + + // TODO: remove the comment to enable LDAP persistence + /* + if((value = properties.get("map-store-name")) != null) { + + String mapStoreIP = properties.get("map-store-ip"); + String mapStorePort = properties.get("map-store-port"); + String mapStoreUser = properties.get("map-store-user"); + String mapStorePassword = properties.get("map-store-password"); + + MapStoreConfig mapStoreConfig = mapCfg.getMapStoreConfig(); + + if (mapStoreConfig == null) { + mapStoreConfig = new MapStoreConfig(); + } + + mapStoreConfig.setEnabled(true); + + HazelcastDataStoreLDAP dataStore = new HazelcastDataStoreLDAP("ou="+value, mapStoreIP, mapStorePort, mapStoreUser, mapStorePassword); + + mapStoreConfig.setImplementation(dataStore); + + mapCfg.setMapStoreConfig(mapStoreConfig); + } + */ + } + } + + private void setQueueProperties(String name, Map properties) { + if(properties != null) { + Config cfg = hazelcastInstance.getConfig(); + QueueConfig queueCfg = cfg.getQueueConfig(name); + if(queueCfg == null) { + queueCfg = new QueueConfig(); + cfg.addQueueConfig(queueCfg); + } + } + } + +} diff --git a/exposure-engine/common/src/main/java/com/alu/e3/common/caching/HazelcastCacheQueue.java b/exposure-engine/common/src/main/java/com/alu/e3/common/caching/HazelcastCacheQueue.java new file mode 100644 index 0000000..4263c98 --- /dev/null +++ b/exposure-engine/common/src/main/java/com/alu/e3/common/caching/HazelcastCacheQueue.java @@ -0,0 +1,52 @@ +/** + * Copyright © 2012 Alcatel-Lucent. + * + * See the NOTICE file distributed with this work for additional + * information regarding copyright ownership. + * Licensed to you 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 com.alu.e3.common.caching; + +import java.util.concurrent.TimeUnit; + +import com.hazelcast.core.IQueue; + +public class HazelcastCacheQueue implements ICacheQueue { + + protected IQueue queue; + + public void setQueue(IQueue queue) { + this.queue = queue; + } + + @Override + public void post(E e) throws InterruptedException { + queue.put(e); + } + + @Override + public E take() throws InterruptedException { + return queue.take(); + } + + @Override + public E poll(long timeout, TimeUnit unit) throws InterruptedException { + return queue.poll(timeout, unit); + } + + +} diff --git a/exposure-engine/common/src/main/java/com/alu/e3/common/caching/IAckCacheTable.java b/exposure-engine/common/src/main/java/com/alu/e3/common/caching/IAckCacheTable.java new file mode 100644 index 0000000..9336895 --- /dev/null +++ b/exposure-engine/common/src/main/java/com/alu/e3/common/caching/IAckCacheTable.java @@ -0,0 +1,40 @@ +/** + * Copyright © 2012 Alcatel-Lucent. + * + * See the NOTICE file distributed with this work for additional + * information regarding copyright ownership. + * Licensed to you 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 com.alu.e3.common.caching; + +public interface IAckCacheTable extends ICacheTable { + + /** + * Sets an element in the table with acknowledgmenent + * @param key The key of the object to set + * @param value An IAckData object, whose id field will be used to get queue name for acknowledgment + * @return A CacheAck instance, value is null + * @throws InterruptedException + */ + boolean setWithAck(K key, V value); + + + /** + * Removes an element from the table with acknowledgmenent + * @param key The key of the object to set + * @param value An IAckData object, whose id field will be used to get queue name for acknowledgment + * @return A CacheAck instance, with value attribute corresponding to the value removed + */ + boolean removeWithAck(K key); +} \ No newline at end of file diff --git a/exposure-engine/common/src/main/java/com/alu/e3/common/caching/IAckData.java b/exposure-engine/common/src/main/java/com/alu/e3/common/caching/IAckData.java new file mode 100644 index 0000000..162840c --- /dev/null +++ b/exposure-engine/common/src/main/java/com/alu/e3/common/caching/IAckData.java @@ -0,0 +1,35 @@ +/** + * Copyright © 2012 Alcatel-Lucent. + * + * See the NOTICE file distributed with this work for additional + * information regarding copyright ownership. + * Licensed to you 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 com.alu.e3.common.caching; + +import java.io.Serializable; + +public interface IAckData extends Serializable { + /** + * Returns an id, this used will be used by an IAckCacheTable to determine on + * which queue acknowledgment data must be read/written. + * @return An id, different from null! + */ + String getId(); + + void setId(String id); +} diff --git a/exposure-engine/common/src/main/java/com/alu/e3/common/caching/ICacheManager.java b/exposure-engine/common/src/main/java/com/alu/e3/common/caching/ICacheManager.java new file mode 100644 index 0000000..6887970 --- /dev/null +++ b/exposure-engine/common/src/main/java/com/alu/e3/common/caching/ICacheManager.java @@ -0,0 +1,31 @@ +/** + * Copyright © 2012 Alcatel-Lucent. + * + * See the NOTICE file distributed with this work for additional + * information regarding copyright ownership. + * Licensed to you 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 com.alu.e3.common.caching; + +import java.util.Map; + +public interface ICacheManager { + + ICacheTable createTable(String name, boolean isReplicated, Map properties); + ICacheTable createOrGetTable(String name, boolean isReplicated, Map properties); + ICacheTable createAckTable(String name, boolean isReplicated, Map properties); + + ICacheQueue createQueue(String name, Map properties); + ICacheQueue getOrCreateQueue(String name, Map properties); +} diff --git a/exposure-engine/common/src/main/java/com/alu/e3/common/caching/ICacheQueue.java b/exposure-engine/common/src/main/java/com/alu/e3/common/caching/ICacheQueue.java new file mode 100644 index 0000000..5b2dac1 --- /dev/null +++ b/exposure-engine/common/src/main/java/com/alu/e3/common/caching/ICacheQueue.java @@ -0,0 +1,31 @@ +/** + * Copyright © 2012 Alcatel-Lucent. + * + * See the NOTICE file distributed with this work for additional + * information regarding copyright ownership. + * Licensed to you 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 com.alu.e3.common.caching; + +import java.util.concurrent.TimeUnit; + +public interface ICacheQueue { + + public abstract void post(E e) throws InterruptedException; + public abstract E take() throws InterruptedException; + public abstract E poll(long timeout, TimeUnit unit) throws InterruptedException; +} diff --git a/exposure-engine/common/src/main/java/com/alu/e3/common/caching/ICacheTable.java b/exposure-engine/common/src/main/java/com/alu/e3/common/caching/ICacheTable.java new file mode 100644 index 0000000..ea7d534 --- /dev/null +++ b/exposure-engine/common/src/main/java/com/alu/e3/common/caching/ICacheTable.java @@ -0,0 +1,50 @@ +/** + * Copyright © 2012 Alcatel-Lucent. + * + * See the NOTICE file distributed with this work for additional + * information regarding copyright ownership. + * Licensed to you 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 com.alu.e3.common.caching; + +import java.util.Collection; +import java.util.Set; + +public interface ICacheTable { + + String getName(); + + void clear(); + boolean set(K key, V value); + + V get(K key); + + V remove(K key); + + boolean containsKey(K key); + + Set getAllKeys(); + Collection getAllValues(); + + void lock(K key); + void unlock(K key); + + void addEntryListener(IEntryListener listener); + void removeEntryListener(IEntryListener listener); + + // populate a slave instance with the master content + void reloadSlave(String ip); + + boolean set(K key, V value, String instanceIP); +} diff --git a/exposure-engine/common/src/main/java/com/alu/e3/common/caching/IEntryListener.java b/exposure-engine/common/src/main/java/com/alu/e3/common/caching/IEntryListener.java new file mode 100644 index 0000000..f1cbf42 --- /dev/null +++ b/exposure-engine/common/src/main/java/com/alu/e3/common/caching/IEntryListener.java @@ -0,0 +1,35 @@ +/** + * Copyright © 2012 Alcatel-Lucent. + * + * See the NOTICE file distributed with this work for additional + * information regarding copyright ownership. + * Licensed to you 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 com.alu.e3.common.caching; + +import com.alu.e3.data.DataEntryEvent; + +/** + * Listener interface ; Used to listen on DataManager's maps for events + * + * @param key of the map entry + * @param value of the map entry + */ +public interface IEntryListener { + + void entryAdded(DataEntryEvent event); + void entryUpdated(DataEntryEvent event); + void entryRemoved(DataEntryEvent event); + +} diff --git a/exposure-engine/common/src/main/java/com/alu/e3/common/caching/ITransaction.java b/exposure-engine/common/src/main/java/com/alu/e3/common/caching/ITransaction.java new file mode 100644 index 0000000..30f07b0 --- /dev/null +++ b/exposure-engine/common/src/main/java/com/alu/e3/common/caching/ITransaction.java @@ -0,0 +1,26 @@ +/** + * Copyright © 2012 Alcatel-Lucent. + * + * See the NOTICE file distributed with this work for additional + * information regarding copyright ownership. + * Licensed to you 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 com.alu.e3.common.caching; + +public interface ITransaction { + void begin(); + void commit(); + void rollback(); + void end(); +} diff --git a/exposure-engine/common/src/main/java/com/alu/e3/common/caching/internal/Disposable.java b/exposure-engine/common/src/main/java/com/alu/e3/common/caching/internal/Disposable.java new file mode 100644 index 0000000..d68ccc9 --- /dev/null +++ b/exposure-engine/common/src/main/java/com/alu/e3/common/caching/internal/Disposable.java @@ -0,0 +1,23 @@ +/** + * Copyright © 2012 Alcatel-Lucent. + * + * See the NOTICE file distributed with this work for additional + * information regarding copyright ownership. + * Licensed to you 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 com.alu.e3.common.caching.internal; + +public interface Disposable { + void dispose(); +} diff --git a/exposure-engine/common/src/main/java/com/alu/e3/common/caching/internal/HandlerPool.java b/exposure-engine/common/src/main/java/com/alu/e3/common/caching/internal/HandlerPool.java new file mode 100644 index 0000000..fe166b0 --- /dev/null +++ b/exposure-engine/common/src/main/java/com/alu/e3/common/caching/internal/HandlerPool.java @@ -0,0 +1,75 @@ +/** + * Copyright © 2012 Alcatel-Lucent. + * + * See the NOTICE file distributed with this work for additional + * information regarding copyright ownership. + * Licensed to you 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 com.alu.e3.common.caching.internal; + + +import java.util.LinkedHashMap; +import java.util.Map; +import java.util.Map.Entry; + +public class HandlerPool extends LinkedHashMap { + + /** + * Generated serial version UID + */ + private static final long serialVersionUID = 2513162685280535426L; + + private int maximumSize; + + public HandlerPool(int maximumSize) + { + super(); + this.maximumSize = maximumSize; + } + + public HandlerPool(int initialCapacity, int maximumSize) + { + super(initialCapacity); + this.maximumSize = maximumSize; + } + + public HandlerPool(int initialCapacity, float loadFactor, int maximumSize) + { + super(initialCapacity, loadFactor); + this.maximumSize = maximumSize; + } + + public HandlerPool(int initialCapacity, float loadFactor, boolean accessOrder, int maximumSize) + { + super(initialCapacity, loadFactor, accessOrder); + this.maximumSize = maximumSize; + } + + public HandlerPool(Map m, int maximumSize) + { + super(m); + this.maximumSize = maximumSize; + } + + protected boolean removeEldestEntry(Entry arg0) { + + boolean remove = size() > this.maximumSize; + + if (remove) + { + arg0.getValue().dispose(); + } + return remove; + } +} \ No newline at end of file diff --git a/exposure-engine/common/src/main/java/com/alu/e3/common/caching/internal/MapHandler.java b/exposure-engine/common/src/main/java/com/alu/e3/common/caching/internal/MapHandler.java new file mode 100644 index 0000000..fd16c3e --- /dev/null +++ b/exposure-engine/common/src/main/java/com/alu/e3/common/caching/internal/MapHandler.java @@ -0,0 +1,85 @@ +/** + * Copyright © 2012 Alcatel-Lucent. + * + * See the NOTICE file distributed with this work for additional + * information regarding copyright ownership. + * Licensed to you 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 com.alu.e3.common.caching.internal; + +import java.util.concurrent.RejectedExecutionException; + +import com.alu.e3.common.E3Constant; +import com.alu.e3.common.tools.CommonTools; +import com.hazelcast.client.ClientConfig; +import com.hazelcast.client.HazelcastClient; +import com.hazelcast.core.Hazelcast; +import com.hazelcast.core.HazelcastInstance; +import com.hazelcast.core.IMap; + +public class MapHandler implements Disposable { + + private HazelcastClient client; + private IMap map; + + public MapHandler(String ip, String mapName) { + + if (CommonTools.isLocal(ip)) { + HazelcastInstance hzI = Hazelcast.getHazelcastInstanceByName(E3Constant.HAZELCAST_NAME); + + if (hzI != null) { + map = hzI.getMap(mapName); + } + else { + // TODO log + System.out.println("MapHandler: HazelcastInstance not found"); + } + } else { + + ClientConfig clientConfig = new ClientConfig(); + clientConfig.addAddress(ip + ":" + E3Constant.HAZELCAST_PORT); + client = HazelcastClient.newHazelcastClient(clientConfig); + map = client.getMap(mapName); + } + } + + public boolean isLocal() { + return client == null; + } + + public boolean isClientActive() + { + if (client!=null) + { + return client.isActive(); + } + else + { + return false; + } + } + + public IMap getMap() { + return map; + } + + public void dispose() { + try { + if (client!=null) + client.shutdown(); + } catch (RejectedExecutionException e) { + // Nothing to do + } + } +} diff --git a/exposure-engine/common/src/main/java/com/alu/e3/common/caching/internal/QueueHandler.java b/exposure-engine/common/src/main/java/com/alu/e3/common/caching/internal/QueueHandler.java new file mode 100644 index 0000000..38fd047 --- /dev/null +++ b/exposure-engine/common/src/main/java/com/alu/e3/common/caching/internal/QueueHandler.java @@ -0,0 +1,79 @@ +/** + * Copyright © 2012 Alcatel-Lucent. + * + * See the NOTICE file distributed with this work for additional + * information regarding copyright ownership. + * Licensed to you 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 com.alu.e3.common.caching.internal; + +import com.alu.e3.common.E3Constant; +import com.alu.e3.common.tools.CommonTools; +import com.hazelcast.client.ClientConfig; +import com.hazelcast.client.HazelcastClient; +import com.hazelcast.core.Hazelcast; +import com.hazelcast.core.HazelcastInstance; +import com.hazelcast.core.IQueue; + +public class QueueHandler implements Disposable { + + protected HazelcastClient client; + protected IQueue queue; + + public QueueHandler(String ip, String queueName) { + + if (CommonTools.isLocal(ip)) { + HazelcastInstance hzI = Hazelcast.getHazelcastInstanceByName(E3Constant.HAZELCAST_NAME); + + if (hzI != null) { + queue = hzI.getQueue(queueName); + } + else { + // TODO log + System.out.println("QueueHandler: HazelcastInstance not found"); + } + } else { + + ClientConfig clientConfig = new ClientConfig(); + clientConfig.addAddress(ip + ":" + E3Constant.HAZELCAST_PORT); + client = HazelcastClient.newHazelcastClient(clientConfig); + queue = client.getQueue(queueName); + } + } + + public boolean isLocal() { + return client == null; + } + + public boolean isClientActive() + { + if (client!=null) + { + return client.isActive(); + } + else + { + return false; + } + } + + public IQueue getQueue() { + return queue; + } + + public void dispose() { + if (client!=null) + client.shutdown(); + } +} diff --git a/exposure-engine/common/src/main/java/com/alu/e3/common/caching/ldap/HazelcastDataStoreLDAP.java b/exposure-engine/common/src/main/java/com/alu/e3/common/caching/ldap/HazelcastDataStoreLDAP.java new file mode 100644 index 0000000..9c20dad --- /dev/null +++ b/exposure-engine/common/src/main/java/com/alu/e3/common/caching/ldap/HazelcastDataStoreLDAP.java @@ -0,0 +1,164 @@ +/** + * Copyright © 2012 Alcatel-Lucent. + * + * See the NOTICE file distributed with this work for additional + * information regarding copyright ownership. + * Licensed to you 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 com.alu.e3.common.caching.ldap; + +import java.util.Collection; +import java.util.HashMap; +import java.util.HashSet; +import java.util.Hashtable; +import java.util.Map; +import java.util.Set; + +import javax.naming.Context; +import javax.naming.NameClassPair; +import javax.naming.NamingEnumeration; +import javax.naming.directory.InitialDirContext; + +import com.hazelcast.core.MapStore; + +@SuppressWarnings("rawtypes") +public class HazelcastDataStoreLDAP implements MapStore { + + private final static String LDAP_ROOT_PATH = ",ou=e3,dc=exEngine,dc=com"; + + private String basePath; + + // shared amongst all data store + private static InitialDirContext dirContext; + + // TODO: add logs + public HazelcastDataStoreLDAP(String basePath, String ip, String port, String principal, String credentials) { + + try { + this.basePath = basePath + LDAP_ROOT_PATH; + + if (dirContext == null) { + String url = "ldap://" + ip + ":" + port; + + Hashtable env = new Hashtable(); + + env.put(Context.INITIAL_CONTEXT_FACTORY, "com.sun.jndi.ldap.LdapCtxFactory"); + env.put(Context.PROVIDER_URL, url); + env.put(Context.SECURITY_AUTHENTICATION, "Simple"); + env.put(Context.SECURITY_PRINCIPAL, principal); + env.put(Context.SECURITY_CREDENTIALS, credentials); + + dirContext = new InitialDirContext(env); + } + } + catch (Exception e) { + System.out.println("HazelcastDataStoreLDAP failure"); + e.printStackTrace(); + } + } + + @Override + public Object load(Object key) { + Object obj = null; + + try { + synchronized (dirContext) { + obj = dirContext.lookup("cn="+key+","+basePath); + } + } + catch (Exception e) { + e.printStackTrace(); + } + + return obj; + } + + @Override + public Map loadAll(Collection keys) { + Map map = new HashMap(); + + for (Object key : keys) { + Object value = load(key); + map.put(key, value); + } + + return map; + } + + @Override + public Set loadAllKeys() { + Set keys = new HashSet(); + + try { + synchronized (dirContext) { + NamingEnumeration list = dirContext.list(basePath); + + while (list.hasMore()) { + NameClassPair nc = (NameClassPair)list.next(); + + // remove the "cn=" + keys.add(nc.getName().substring(3)); + } + } + } + catch (Exception e) { + e.printStackTrace(); + } + + return keys; + } + + @Override + public void delete(Object key) { + try { + synchronized (dirContext) { + dirContext.unbind("cn="+key+","+basePath); + } + } + catch (Exception e) { + e.printStackTrace(); + } + } + + @Override + public void deleteAll(Collection keys) { + for (Object key : keys) { + delete(key); + } + } + + @Override + public void store(Object key, Object value) { + try { + synchronized (dirContext) { + dirContext.rebind("cn="+key+","+basePath, value); + } + } + catch (Exception e) { + e.printStackTrace(); + } + } + + @Override + public void storeAll(Map map) { + if (map != null) { + // Weird error if using map and not map2 in the loop + @SuppressWarnings("unchecked") + Map map2 = (Map) map; + for (Map.Entry entry : map2.entrySet()) { + store(map.get(entry.getKey()), map.get(entry.getValue())); + } + } + } +} diff --git a/exposure-engine/common/src/main/java/com/alu/e3/common/camel/AuthIdentity.java b/exposure-engine/common/src/main/java/com/alu/e3/common/camel/AuthIdentity.java new file mode 100644 index 0000000..ab5326c --- /dev/null +++ b/exposure-engine/common/src/main/java/com/alu/e3/common/camel/AuthIdentity.java @@ -0,0 +1,87 @@ +/** + * Copyright © 2012 Alcatel-Lucent. + * + * See the NOTICE file distributed with this work for additional + * information regarding copyright ownership. + * Licensed to you 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 com.alu.e3.common.camel; + +import java.util.ArrayList; +import java.util.List; + +import com.alu.e3.data.model.Api; +import com.alu.e3.data.model.Auth; +import com.alu.e3.data.model.CallDescriptor; + +public class AuthIdentity { + + private Api api; + private Auth auth; + private String appId; + private List callDescriptors; + + /** + * @return the api + */ + public Api getApi() { + return api; + } + /** + * @param api the api to set + */ + public void setApi(Api api) { + this.api = api; + } + + + /** + * @return the auth + */ + public Auth getAuth() { + return auth; + } + /** + * @param auth the auth to set + */ + public void setAuth(Auth auth) { + this.auth = auth; + } + + /** + * @return the call descriptors (include policy) + */ + public List getCallDescriptors() { + + if(this.callDescriptors == null) { + this.callDescriptors = new ArrayList(); + } + + return callDescriptors; + } + + /** + * @return the appId + */ + public String getAppId() { + return appId; + } + + /** + * @param appId the appId to set + */ + public void setAppId(String appId) { + this.appId = appId; + } +} diff --git a/exposure-engine/common/src/main/java/com/alu/e3/common/camel/AuthReport.java b/exposure-engine/common/src/main/java/com/alu/e3/common/camel/AuthReport.java new file mode 100644 index 0000000..60b5c47 --- /dev/null +++ b/exposure-engine/common/src/main/java/com/alu/e3/common/camel/AuthReport.java @@ -0,0 +1,160 @@ +/** + * Copyright © 2012 Alcatel-Lucent. + * + * See the NOTICE file distributed with this work for additional + * information regarding copyright ownership. + * Licensed to you 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 com.alu.e3.common.camel; + +public class AuthReport { + + private AuthIdentity authIdentity; + private boolean isApiActive; + private boolean isStatusChecked; + private boolean isNotAuthorized; + + // error case + private boolean hasNoPolicy; + private boolean isApiNotFound; + private boolean isAuthNotFound; + private boolean isBadRequest; + + /** + * Tells if allowed or not + * @return + */ + public boolean isAllowed() { + return (authIdentity != null && isApiActive); + } + + + /** + * @return the isNotAuthorized + */ + public boolean isNotAuthorized() { + return isNotAuthorized; + } + + /** + * @param isNotAuthorized the isNotAuthorized to set + */ + public void setNotAuthorized(boolean isNotAuthorized) { + this.isNotAuthorized = isNotAuthorized; + } + + /** + * @return the hasNoPolicy + */ + public boolean hasNoPolicy() { + return hasNoPolicy; + } + + /** + * @param hasNoPolicy the hasNoPolicy to set + */ + public void setHasNoPolicy(boolean hasNoPolicy) { + this.hasNoPolicy = hasNoPolicy; + } + + /** + * @return the isApiNotFound + */ + public boolean isApiNotFound() { + return isApiNotFound; + } + + /** + * @param isApiNotFound the isApiNotFound to set + */ + public void setApiNotFound(boolean isApiNotFound) { + this.isApiNotFound = isApiNotFound; + } + + /** + * @return the authIdentity + */ + public AuthIdentity getAuthIdentity() { + return authIdentity; + } + + /** + * @param authIdentity the authIdentity to set + */ + public void setAuthIdentity(AuthIdentity authIdentity) { + this.authIdentity = authIdentity; + } + + /** + * @return the isApiActive + */ + public boolean isApiActive() { + return this.isApiActive; + } + + /** + * @param isApiActive the isApiActive to set + */ + public void setApiActive(boolean isApiActive) { + this.isApiActive = isApiActive; + this.setStatusChecked(true); + } + + /** + * @return the isAuthNotFound + */ + public boolean isAuthNotFound() { + return isAuthNotFound; + } + + /** + * @param isAuthNotFound the isAuthNotFound to set + */ + public void setAuthNotFound(boolean isAuthNotFound) { + this.isAuthNotFound = isAuthNotFound; + } + + /** + * @return the isBadrequest + */ + public boolean isBadRequest() { + return isBadRequest; + } + + /** + * @param isBadrequest the isBadrequest to set + */ + public void setBadRequest(boolean isBadRequest) { + this.isBadRequest = isBadRequest; + } + + + /** + * @return the hasStatusChecked + */ + public boolean isStatusChecked() { + return isStatusChecked; + } + + + /** + * @param hasStatusChecked the hasStatusChecked to set + */ + public void setStatusChecked(boolean isStatusChecked) { + this.isStatusChecked = isStatusChecked; + } + + + +} diff --git a/exposure-engine/common/src/main/java/com/alu/e3/common/camel/ExchangeConstantKeys.java b/exposure-engine/common/src/main/java/com/alu/e3/common/camel/ExchangeConstantKeys.java new file mode 100644 index 0000000..0622b0d --- /dev/null +++ b/exposure-engine/common/src/main/java/com/alu/e3/common/camel/ExchangeConstantKeys.java @@ -0,0 +1,69 @@ +/** + * Copyright © 2012 Alcatel-Lucent. + * + * See the NOTICE file distributed with this work for additional + * information regarding copyright ownership. + * Licensed to you 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 com.alu.e3.common.camel; + +public enum ExchangeConstantKeys { + + // PROVIONING + E3_PROVISION_ID, + E3_PROVISION_ID_ENCODED, + E3_API_ID, + E3_API_ID_ENCODED, + E3_OPERATION_NAME, + E3_REQUEST_PAYLOAD, + E3_API_ID_CREATION_MODE, + E3_API_ID_CREATION_MODE_GENERATED, + E3_API_ID_CREATION_MODE_PROVIDED, + + // AUTH + E3_AUTH_IDENTITY, + E3_AUTH_METHOD, + + // Rate Limit / Quota + E3_RATELIMIT_ACTION, + E3_RATELIMIT_OVER_QUOTA, + E3_RATELIMIT_OVER_SEC, + E3_RATELIMIT_OVER_MIN, + E3_RATELIMIT_OVER_DAY, + E3_RATELIMIT_OVER_WK, + E3_RATELIMIT_OVER_MON, + + // TDR + E3_TDR_ENABLED, + E3_GOT_SB_RESPONSE, + + // HTTP + E3_REQUEST_PARAMETERS, + + // SOAP + E3_SOAP_ACTION, + + // Model Properties + E3_MODEL_PROPERTIES, + + E3_OAUTH_REVOKE_TOKEN, + + // TODO: To be renamed to E3_API_ID_CREATION_MODE_GENERATED + GENERATED, + // TODO: To be renamed to E3_API_ID_CREATION_MODE_PROVIDED + PROVIDED, + + // HTTP status line reason phrase + E3_HTTP_STATUS_LINE_REASON_PHRASE, +} diff --git a/exposure-engine/common/src/main/java/com/alu/e3/common/healthcheck/HealthCheckFactory.java b/exposure-engine/common/src/main/java/com/alu/e3/common/healthcheck/HealthCheckFactory.java new file mode 100644 index 0000000..5d32588 --- /dev/null +++ b/exposure-engine/common/src/main/java/com/alu/e3/common/healthcheck/HealthCheckFactory.java @@ -0,0 +1,33 @@ +/** + * Copyright © 2012 Alcatel-Lucent. + * + * See the NOTICE file distributed with this work for additional + * information regarding copyright ownership. + * Licensed to you 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 com.alu.e3.common.healthcheck; + +import com.alu.e3.common.osgi.api.IHealthCheckFactory; +import com.alu.e3.data.IHealthCheckService; + +/** + * Health Check class + */ +public class HealthCheckFactory implements IHealthCheckFactory { + + @Override + public IHealthCheckService getHealthCheckService(String instanceType) { + return new HealthCheckService(instanceType); + } +} diff --git a/exposure-engine/common/src/main/java/com/alu/e3/common/healthcheck/HealthCheckService.java b/exposure-engine/common/src/main/java/com/alu/e3/common/healthcheck/HealthCheckService.java new file mode 100644 index 0000000..e2961b6 --- /dev/null +++ b/exposure-engine/common/src/main/java/com/alu/e3/common/healthcheck/HealthCheckService.java @@ -0,0 +1,152 @@ +/** + * Copyright © 2012 Alcatel-Lucent. + * + * See the NOTICE file distributed with this work for additional + * information regarding copyright ownership. + * Licensed to you 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 com.alu.e3.common.healthcheck; + +import java.io.DataOutputStream; +import java.io.IOException; +import java.net.ServerSocket; +import java.net.Socket; +import java.net.SocketException; +import java.security.InvalidParameterException; +import java.util.concurrent.atomic.AtomicBoolean; + +import com.alu.e3.common.E3Constant; +import com.alu.e3.common.osgi.api.IHealthCheckFactory; +import com.alu.e3.data.IHealthCheckService; + +/** + * Health Check class + */ +public class HealthCheckService implements IHealthCheckService, Runnable { + + /* final members. */ + private static final String HTTP_RESPONSE_OK = "HTTP/1.0 200 OK\r\nContent-Type: text/plain\r\nConnection: Close\r\n\r\nHealth check ok."; + + /* members. */ + private int listeningPort; + private ServerSocket serverSocket; + + private AtomicBoolean alive; + + private HealthCheckService() { + alive = new AtomicBoolean(true); + } + + /** + * Constructor + */ + public HealthCheckService(String instanceType) { + this(); + + if (IHealthCheckFactory.GATEWAY_INTERNAL_TYPE.equals(instanceType)) + this.listeningPort = E3Constant.GATEWAY_INTERNAL_DEFAULT_HEALTH_CHECK_PORT; + else if (IHealthCheckFactory.GATEWAY_TYPE.equals(instanceType)) + this.listeningPort = E3Constant.GATEWAY_DEFAULT_HEALTH_CHECK_PORT; + else if (IHealthCheckFactory.SPEAKER_TYPE.equals(instanceType)) + this.listeningPort = E3Constant.SPEAKER_DEFAULT_HEALTH_CHECK_PORT; + else if (IHealthCheckFactory.MANAGER_TYPE.equals(instanceType)) + this.listeningPort = E3Constant.MANAGER_DEFAULT_HEALTH_CHECK_PORT; + else throw new InvalidParameterException("Invalid instance type."); + } + + /** + * Start healthcheck service + */ + @Override + public void start() + { + try { + this.stop(); + serverSocket = new ServerSocket(listeningPort); + alive.set(true); + new Thread(this).start(); + + } catch (IOException e) { + e.printStackTrace(); + } + } + + /** + * Halt healthcheck service + */ + @Override + public void stop() + { + alive.set(false); + + if (serverSocket == null) + return; + + try { + serverSocket.close(); // if the service is running, it may make accept() fail. + } catch (IOException e) { + e.printStackTrace(); + } finally { + serverSocket = null; + } + } + + /** + * Server main loop. + */ + @Override + public void run() { + while (alive.get()) { + + /* service not started. */ + if (serverSocket == null || serverSocket.isClosed()) + return; + + try { + Socket socket = serverSocket.accept(); + DataOutputStream out = new DataOutputStream(socket.getOutputStream()); + + //writeUTF() will produce a leading byte-order character which messes up some clients + out.writeChars(HTTP_RESPONSE_OK); + out.close(); + socket.close(); + + } catch (SocketException e) { + System.out.println("Socket closed."); + } catch (IOException e) { + e.printStackTrace(); + } + } + } + + + /** + * Check if the health service is alive on the specified host. + */ + @Override + public boolean check(String host) { + + boolean bCheck = false; + + try { + Socket clientSocket = new Socket(host, listeningPort); + bCheck = clientSocket.isConnected(); + clientSocket.close(); + + } catch (Exception e) { + } + + return bCheck; + } +} diff --git a/exposure-engine/common/src/main/java/com/alu/e3/common/info/GatewayStatus.java b/exposure-engine/common/src/main/java/com/alu/e3/common/info/GatewayStatus.java new file mode 100644 index 0000000..14e0a89 --- /dev/null +++ b/exposure-engine/common/src/main/java/com/alu/e3/common/info/GatewayStatus.java @@ -0,0 +1,27 @@ +/** + * Copyright © 2012 Alcatel-Lucent. + * + * See the NOTICE file distributed with this work for additional + * information regarding copyright ownership. + * Licensed to you 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 com.alu.e3.common.info; + +public class GatewayStatus { + // /!\ Do not forget to update E3GatewayStatus type in E3 SNMP MIB (resources/mib/E3-MIB.mib) !! + public final static String DOWN = "DOWN"; + public final static String PROVISIONING = "PROVISIONING"; + public final static String PROVISIONED = "PROVISIONED"; + public final static String UP = "UP"; +} diff --git a/exposure-engine/common/src/main/java/com/alu/e3/common/info/IGatewayInfo.java b/exposure-engine/common/src/main/java/com/alu/e3/common/info/IGatewayInfo.java new file mode 100644 index 0000000..6e4be6d --- /dev/null +++ b/exposure-engine/common/src/main/java/com/alu/e3/common/info/IGatewayInfo.java @@ -0,0 +1,32 @@ +/** + * Copyright © 2012 Alcatel-Lucent. + * + * See the NOTICE file distributed with this work for additional + * information regarding copyright ownership. + * Licensed to you 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 com.alu.e3.common.info; + +public interface IGatewayInfo { + + public static final String GATEWAY_STATUS_CACHE_ENTRY = "gatewayStatus"; + public static final String GATEWAY_STATUS_TABLE_NAME = "gatewayStatusTable"; + + String getStatus(); + void setStatus(String instanceStatus); + + void addGatewayInfoListener(IGatewayInfoListener listener); + void removeGatewayInfoListener(IGatewayInfoListener listener); + +} diff --git a/exposure-engine/common/src/main/java/com/alu/e3/common/info/IGatewayInfoListener.java b/exposure-engine/common/src/main/java/com/alu/e3/common/info/IGatewayInfoListener.java new file mode 100644 index 0000000..a0c7808 --- /dev/null +++ b/exposure-engine/common/src/main/java/com/alu/e3/common/info/IGatewayInfoListener.java @@ -0,0 +1,25 @@ +/** + * Copyright © 2012 Alcatel-Lucent. + * + * See the NOTICE file distributed with this work for additional + * information regarding copyright ownership. + * Licensed to you 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 com.alu.e3.common.info; + + +public interface IGatewayInfoListener { + + void gatewayStatusChanged(String status); +} diff --git a/exposure-engine/common/src/main/java/com/alu/e3/common/info/IManagerInfo.java b/exposure-engine/common/src/main/java/com/alu/e3/common/info/IManagerInfo.java new file mode 100644 index 0000000..8484f9d --- /dev/null +++ b/exposure-engine/common/src/main/java/com/alu/e3/common/info/IManagerInfo.java @@ -0,0 +1,30 @@ +/** + * Copyright © 2012 Alcatel-Lucent. + * + * See the NOTICE file distributed with this work for additional + * information regarding copyright ownership. + * Licensed to you 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 com.alu.e3.common.info; + +public interface IManagerInfo { + + public static final String MANAGER_STATUS_CACHE_ENTRY = "managerStatus"; + + String getStatus(); + void setStatus(String status); + + void addManagerInfoListener(IManagerInfoListener listener); + void removeManagerInfoListener(IManagerInfoListener listener); +} diff --git a/exposure-engine/common/src/main/java/com/alu/e3/common/info/IManagerInfoListener.java b/exposure-engine/common/src/main/java/com/alu/e3/common/info/IManagerInfoListener.java new file mode 100644 index 0000000..1607799 --- /dev/null +++ b/exposure-engine/common/src/main/java/com/alu/e3/common/info/IManagerInfoListener.java @@ -0,0 +1,24 @@ +/** + * Copyright © 2012 Alcatel-Lucent. + * + * See the NOTICE file distributed with this work for additional + * information regarding copyright ownership. + * Licensed to you 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 com.alu.e3.common.info; + +public interface IManagerInfoListener { + + void managerStatusChanged(String status); +} diff --git a/exposure-engine/common/src/main/java/com/alu/e3/common/info/ISpeakerInfo.java b/exposure-engine/common/src/main/java/com/alu/e3/common/info/ISpeakerInfo.java new file mode 100644 index 0000000..e708eb4 --- /dev/null +++ b/exposure-engine/common/src/main/java/com/alu/e3/common/info/ISpeakerInfo.java @@ -0,0 +1,32 @@ +/** + * Copyright © 2012 Alcatel-Lucent. + * + * See the NOTICE file distributed with this work for additional + * information regarding copyright ownership. + * Licensed to you 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 com.alu.e3.common.info; + +public interface ISpeakerInfo { + + public static final String SPEAKER_STATUS_CACHE_ENTRY = "speakerStatus"; + public static final String SPEAKER_STATUS_TABLE_NAME = "speakerStatusTable"; + + String getStatus(); + void setStatus(String status); + + void addSpeakerInfoListener(ISpeakerInfoListener listener); + void removeSpeakerInfoListener(ISpeakerInfoListener listener); + +} diff --git a/exposure-engine/common/src/main/java/com/alu/e3/common/info/ISpeakerInfoListener.java b/exposure-engine/common/src/main/java/com/alu/e3/common/info/ISpeakerInfoListener.java new file mode 100644 index 0000000..a9f8dbb --- /dev/null +++ b/exposure-engine/common/src/main/java/com/alu/e3/common/info/ISpeakerInfoListener.java @@ -0,0 +1,24 @@ +/** + * Copyright © 2012 Alcatel-Lucent. + * + * See the NOTICE file distributed with this work for additional + * information regarding copyright ownership. + * Licensed to you 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 com.alu.e3.common.info; + +public interface ISpeakerInfoListener { + + void speakerStatusChanged(String status); +} diff --git a/exposure-engine/common/src/main/java/com/alu/e3/common/info/InstanceInfo.java b/exposure-engine/common/src/main/java/com/alu/e3/common/info/InstanceInfo.java new file mode 100644 index 0000000..7b276bd --- /dev/null +++ b/exposure-engine/common/src/main/java/com/alu/e3/common/info/InstanceInfo.java @@ -0,0 +1,97 @@ +/** + * Copyright © 2012 Alcatel-Lucent. + * + * See the NOTICE file distributed with this work for additional + * information regarding copyright ownership. + * Licensed to you 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 com.alu.e3.common.info; + +import com.alu.e3.common.osgi.api.IInstanceInfo; + +public class InstanceInfo implements IInstanceInfo { + + protected boolean isGateway = false; + protected boolean isSpeaker = false; + protected boolean isManager = false; + protected IGatewayInfo gatewayInfo; + protected ISpeakerInfo speakerInfo; + protected IManagerInfo managerInfo; + + public InstanceInfo() {} + + @Override + public boolean isGateway() { + return isGateway; + } + + @Override + public void setGateway(boolean isGateway) { + this.isGateway = isGateway; + } + + + @Override + public boolean isSpeaker() { + return isSpeaker; + } + + @Override + public void setSpeaker(boolean isSpeaker) { + this.isSpeaker = isSpeaker; + } + + @Override + public boolean isManager() { + return isManager; + } + + @Override + public void setManager(boolean isManager) { + this.isManager = isManager; + } + + @Override + public IGatewayInfo getGatewayInfo() { + return gatewayInfo; + } + + @Override + public void setGatewayInfo(IGatewayInfo gatewayInfo) { + this.gatewayInfo = gatewayInfo; + } + + @Override + public ISpeakerInfo getSpeakerInfo() { + return speakerInfo; + } + + @Override + public void setSpeakerInfo(ISpeakerInfo speakerInfo) { + this.speakerInfo = speakerInfo; + } + + @Override + public IManagerInfo getManagerInfo() { + return managerInfo; + } + + @Override + public void setManagerInfo(IManagerInfo managerInfo) { + this.managerInfo = managerInfo; + } +} diff --git a/exposure-engine/common/src/main/java/com/alu/e3/common/info/ManagerStatus.java b/exposure-engine/common/src/main/java/com/alu/e3/common/info/ManagerStatus.java new file mode 100644 index 0000000..8d53b92 --- /dev/null +++ b/exposure-engine/common/src/main/java/com/alu/e3/common/info/ManagerStatus.java @@ -0,0 +1,25 @@ +/** + * Copyright © 2012 Alcatel-Lucent. + * + * See the NOTICE file distributed with this work for additional + * information regarding copyright ownership. + * Licensed to you 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 com.alu.e3.common.info; + +public class ManagerStatus { + // /!\ Do not forget to update E3ManagerStatus type in E3 SNMP MIB (resources/mib/E3-MIB.mib) !! + public final static String DOWN = "DOWN"; + public final static String UP = "UP"; +} diff --git a/exposure-engine/common/src/main/java/com/alu/e3/common/info/RemoteInstanceInfo.java b/exposure-engine/common/src/main/java/com/alu/e3/common/info/RemoteInstanceInfo.java new file mode 100644 index 0000000..df57a1b --- /dev/null +++ b/exposure-engine/common/src/main/java/com/alu/e3/common/info/RemoteInstanceInfo.java @@ -0,0 +1,53 @@ +/** + * Copyright © 2012 Alcatel-Lucent. + * + * See the NOTICE file distributed with this work for additional + * information regarding copyright ownership. + * Licensed to you 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 com.alu.e3.common.info; + +import com.alu.e3.common.caching.internal.MapHandler; + +public class RemoteInstanceInfo { + + public static String getGatewayStatus(String ip) { + MapHandler mapHandler = new MapHandler(ip, IGatewayInfo.GATEWAY_STATUS_TABLE_NAME); + + return (mapHandler.getMap() == null ? GatewayStatus.DOWN : mapHandler.getMap().get(IGatewayInfo.GATEWAY_STATUS_CACHE_ENTRY)); + } + + public static void setGatewayStatus(String ip, String status) { + MapHandler mapHandler = new MapHandler(ip, IGatewayInfo.GATEWAY_STATUS_TABLE_NAME); + + if (mapHandler != null && mapHandler.getMap() != null) { + mapHandler.getMap().put(IGatewayInfo.GATEWAY_STATUS_CACHE_ENTRY, status); + } + } + + + public static String getSpeakerStatus(String ip) { + MapHandler mapHandler = new MapHandler(ip, ISpeakerInfo.SPEAKER_STATUS_TABLE_NAME); + + return (mapHandler.getMap() == null ? SpeakerStatus.DOWN : mapHandler.getMap().get(ISpeakerInfo.SPEAKER_STATUS_CACHE_ENTRY)); + } + + public static void setSpeakerStatus(String ip, String status) { + MapHandler mapHandler = new MapHandler(ip, ISpeakerInfo.SPEAKER_STATUS_TABLE_NAME); + + if (mapHandler.getMap() != null) { + mapHandler.getMap().put(ISpeakerInfo.SPEAKER_STATUS_CACHE_ENTRY, status); + } + } +} diff --git a/exposure-engine/common/src/main/java/com/alu/e3/common/info/SpeakerStatus.java b/exposure-engine/common/src/main/java/com/alu/e3/common/info/SpeakerStatus.java new file mode 100644 index 0000000..a1bc97a --- /dev/null +++ b/exposure-engine/common/src/main/java/com/alu/e3/common/info/SpeakerStatus.java @@ -0,0 +1,26 @@ +/** + * Copyright © 2012 Alcatel-Lucent. + * + * See the NOTICE file distributed with this work for additional + * information regarding copyright ownership. + * Licensed to you 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 com.alu.e3.common.info; + +public class SpeakerStatus { + // /!\ Do not forget to update E3SpeakerStatus type in E3 SNMP MIB (resources/mib/E3-MIB.mib) !! + public final static String DOWN = "DOWN"; + public final static String STARTING = "STARTING"; + public final static String UP = "UP"; +} diff --git a/exposure-engine/common/src/main/java/com/alu/e3/common/logging/Category.java b/exposure-engine/common/src/main/java/com/alu/e3/common/logging/Category.java new file mode 100644 index 0000000..ec7334c --- /dev/null +++ b/exposure-engine/common/src/main/java/com/alu/e3/common/logging/Category.java @@ -0,0 +1,104 @@ +/** + * Copyright © 2012 Alcatel-Lucent. + * + * See the NOTICE file distributed with this work for additional + * information regarding copyright ownership. + * Licensed to you 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 com.alu.e3.common.logging; + +import java.util.Arrays; +import java.util.Collections; +import java.util.EnumSet; +import java.util.Set; + +/** + * The Category class is an enum describing the types of events to be logged in the system. + * The CategoryLogger class accepts a Category parameter for classifying a logging + * message for control (enable/disable) and possible filtering. + */ +public enum Category { + + SYS("System", "System events"), + AUTH("Authentication", "Authentication events"), + PROV("Provisioning", "Provisioning events"), + SPKR("Speaker", "Speaker-generated events"), + DMGR("DataManager", "Data-manager events"), + LOG("Logging", "Logging events"); + + static private final Set disabledCategories = Collections.synchronizedSet(EnumSet.noneOf(Category.class)); + + private final String fullname; + private final String description; + + Category(String fullname, String description) + { + this.fullname = fullname; + this.description = description; + } + + public String fullname() + { + return fullname; + } + + public String description() + { + return description; + } + + public boolean enabled() + { + return Category.isCategoryEnabled(this); + } + + static public Category fromString(String name) + { + try { + return Category.valueOf(name.trim().toUpperCase()); + } catch (Exception ex) { + return null; + } + } + + public static final String valuesList = Arrays.asList(values()).toString(); + + /** + * Enable or disable logging output for the specified Category. Note + * that the null Category is always enabled and cannot + * be disabled. + * + * @param category The Category to enable or disable + * @param enabled If false, subsequent log messages classified + * with category will not be output. + * @return true if category status is actually changed + */ + static public boolean enableCategory(Category category, boolean enabled) + { + if (category == null) { + return false; + } + if (enabled) { + return disabledCategories.remove(category); + } else { + return disabledCategories.add(category); + } + } + + static public boolean isCategoryEnabled(Category category) + { + return ((category == null) || !disabledCategories.contains(category)); + } + +} diff --git a/exposure-engine/common/src/main/java/com/alu/e3/common/logging/CategoryLogger.java b/exposure-engine/common/src/main/java/com/alu/e3/common/logging/CategoryLogger.java new file mode 100644 index 0000000..c6e1d18 --- /dev/null +++ b/exposure-engine/common/src/main/java/com/alu/e3/common/logging/CategoryLogger.java @@ -0,0 +1,874 @@ +/** + * Copyright © 2012 Alcatel-Lucent. + * + * See the NOTICE file distributed with this work for additional + * information regarding copyright ownership. + * Licensed to you 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 com.alu.e3.common.logging; + +import org.slf4j.Logger; +import org.slf4j.Marker; + +import com.alu.e3.common.logging.Category; + +/** + * An org.slf4j.Logger implementation (and wrapper) that provides + * all the normal slf4j logging methods along with variants + * that take a Category parameter to classify log messages. + */ +public class CategoryLogger implements org.slf4j.Logger { + + private final Logger logger; + private final Category category; + + + CategoryLogger(Logger logger) + { + this.logger = logger; + this.category = null; + } + + CategoryLogger(Logger logger, Category category) + { + this.logger = logger; + this.category = category; + } + + /** + * The method for “tagging” logging messages for possible filtering. + * Currently, if a message is categorized, then the message text is prepended + * with the Category name enclosed in brackets ([]). + * + * @param category The Category to apply + * @param msg The original log message + * @return The tagged log message + */ + static private String categorizedMessage(Category category, String msg) + { + return category != null ? "[" + category.name() + "] " + msg : msg; + } + + + @Override + public void debug(String msg) + { + if (Category.isCategoryEnabled(this.category)) { + logger.debug(categorizedMessage(this.category, msg)); + } + } + + @Override + public void debug(String format, Object arg) + { + if (Category.isCategoryEnabled(this.category)) { + logger.debug(categorizedMessage(this.category, format), arg); + } + } + + @Override + public void debug(String format, Object[] argArray) + { + if (Category.isCategoryEnabled(this.category)) { + logger.debug(categorizedMessage(this.category, format), argArray); + } + } + + @Override + public void debug(String msg, Throwable t) + { + if (Category.isCategoryEnabled(this.category)) { + logger.debug(categorizedMessage(this.category, msg), t); + } + } + + @Override + public void debug(Marker marker, String msg) + { + if (Category.isCategoryEnabled(this.category)) { + logger.debug(marker, categorizedMessage(this.category, msg)); + } + } + + @Override + public void debug(String format, Object arg1, Object arg2) + { + if (Category.isCategoryEnabled(this.category)) { + logger.debug(categorizedMessage(this.category, format), arg1, arg2); + } + } + + @Override + public void debug(Marker marker, String format, Object arg) + { + if (Category.isCategoryEnabled(this.category)) { + logger.debug(marker, categorizedMessage(this.category, format), arg); + } + } + + @Override + public void debug(Marker marker, String format, Object[] argArray) + { + if (Category.isCategoryEnabled(this.category)) { + logger.debug(marker, categorizedMessage(this.category, format), argArray); + } + } + + @Override + public void debug(Marker marker, String msg, Throwable t) + { + if (Category.isCategoryEnabled(this.category)) { + logger.debug(marker, categorizedMessage(this.category, msg), t); + } + } + + @Override + public void debug(Marker marker, String format, Object arg1, Object arg2) + { + if (Category.isCategoryEnabled(this.category)) { + logger.debug(marker, categorizedMessage(this.category, format), arg1, arg2); + } + } + + public void debug(Category category, String msg) + { + if (Category.isCategoryEnabled(category)) { + logger.debug(categorizedMessage(category, msg)); + } + } + + public void debug(Category category, String format, Object arg) + { + if (Category.isCategoryEnabled(category)) { + logger.debug(categorizedMessage(category, format), arg); + } + } + + public void debug(Category category, String format, Object[] argArray) + { + if (Category.isCategoryEnabled(category)) { + logger.debug(categorizedMessage(category, format), argArray); + } + } + + public void debug(Category category, String msg, Throwable t) + { + if (Category.isCategoryEnabled(category)) { + logger.debug(categorizedMessage(category, msg), t); + } + } + + public void debug(Category category, Marker marker, String msg) + { + if (Category.isCategoryEnabled(category)) { + logger.debug(marker, categorizedMessage(category, msg)); + } + } + + public void debug(Category category, String format, Object arg1, Object arg2) + { + if (Category.isCategoryEnabled(category)) { + logger.debug(categorizedMessage(category, format), arg1, arg2); + } + } + + public void debug(Category category, Marker marker, String format, Object arg) + { + if (Category.isCategoryEnabled(category)) { + logger.debug(marker, categorizedMessage(category, format), arg); + } + } + + public void debug(Category category, Marker marker, String format, Object[] argArray) + { + if (Category.isCategoryEnabled(category)) { + logger.debug(marker, categorizedMessage(category, format), argArray); + } + } + + public void debug(Category category, Marker marker, String msg, Throwable t) + { + if (Category.isCategoryEnabled(category)) { + logger.debug(marker, categorizedMessage(category, msg), t); + } + } + + public void debug(Category category, Marker marker, String format, Object arg1, Object arg2) + { + if (Category.isCategoryEnabled(category)) { + logger.debug(marker, categorizedMessage(category, format), arg1, arg2); + } + } + + @Override + public void error(String msg) + { + if (Category.isCategoryEnabled(this.category)) { + logger.error(categorizedMessage(this.category, msg)); + } + } + + @Override + public void error(String format, Object arg) + { + if (Category.isCategoryEnabled(this.category)) { + logger.error(categorizedMessage(this.category, format), arg); + } + } + + @Override + public void error(String format, Object[] argArray) + { + if (Category.isCategoryEnabled(this.category)) { + logger.error(categorizedMessage(this.category, format), argArray); + } + } + + @Override + public void error(String msg, Throwable t) + { + if (Category.isCategoryEnabled(this.category)) { + logger.error(categorizedMessage(this.category, msg), t); + } + } + + @Override + public void error(Marker marker, String msg) + { + if (Category.isCategoryEnabled(this.category)) { + logger.error(marker, categorizedMessage(this.category, msg)); + } + } + + @Override + public void error(String format, Object arg1, Object arg2) + { + if (Category.isCategoryEnabled(this.category)) { + logger.error(categorizedMessage(this.category, format), arg1, arg2); + } + } + + @Override + public void error(Marker marker, String format, Object arg) + { + if (Category.isCategoryEnabled(this.category)) { + logger.error(marker, categorizedMessage(this.category, format), arg); + } + } + + @Override + public void error(Marker marker, String format, Object[] argArray) + { + if (Category.isCategoryEnabled(this.category)) { + logger.error(marker, categorizedMessage(this.category, format), argArray); + } + } + + @Override + public void error(Marker marker, String msg, Throwable t) + { + if (Category.isCategoryEnabled(this.category)) { + logger.error(marker, categorizedMessage(this.category, msg), t); + } + } + + @Override + public void error(Marker marker, String format, Object arg1, Object arg2) + { + if (Category.isCategoryEnabled(this.category)) { + logger.error(marker, categorizedMessage(this.category, format), arg1, arg2); + } + } + + public void error(Category category, String msg) + { + if (Category.isCategoryEnabled(category)) { + logger.error(categorizedMessage(category, msg)); + } + } + + public void error(Category category, String format, Object arg) + { + if (Category.isCategoryEnabled(category)) { + logger.error(categorizedMessage(category, format), arg); + } + } + + public void error(Category category, String format, Object[] argArray) + { + if (Category.isCategoryEnabled(category)) { + logger.error(categorizedMessage(category, format), argArray); + } + } + + public void error(Category category, String msg, Throwable t) + { + if (Category.isCategoryEnabled(category)) { + logger.error(categorizedMessage(category, msg), t); + } + } + + public void error(Category category, Marker marker, String msg) + { + if (Category.isCategoryEnabled(category)) { + logger.error(marker, categorizedMessage(category, msg)); + } + } + + public void error(Category category, String format, Object arg1, Object arg2) + { + if (Category.isCategoryEnabled(category)) { + logger.error(categorizedMessage(category, format), arg1, arg2); + } + } + + public void error(Category category, Marker marker, String format, Object arg) + { + if (Category.isCategoryEnabled(category)) { + logger.error(marker, categorizedMessage(category, format), arg); + } + } + + public void error(Category category, Marker marker, String format, Object[] argArray) + { + if (Category.isCategoryEnabled(category)) { + logger.error(marker, categorizedMessage(category, format), argArray); + } + } + + public void error(Category category, Marker marker, String msg, Throwable t) + { + if (Category.isCategoryEnabled(category)) { + logger.error(marker, categorizedMessage(category, msg), t); + } + } + + public void error(Category category, Marker marker, String format, Object arg1, Object arg2) + { + if (Category.isCategoryEnabled(category)) { + logger.error(marker, categorizedMessage(category, format), arg1, arg2); + } + } + + @Override + public String getName() { + return logger.getName(); + } + + @Override + public void info(String msg) { + if (Category.isCategoryEnabled(this.category)) { + logger.info(categorizedMessage(this.category, msg)); + } + } + + @Override + public void info(String format, Object arg) + { + if (Category.isCategoryEnabled(this.category)) { + logger.info(categorizedMessage(this.category, format), arg); + } + } + + @Override + public void info(String format, Object[] argArray) + { + if (Category.isCategoryEnabled(this.category)) { + logger.info(categorizedMessage(this.category, format), argArray); + } + } + + @Override + public void info(String msg, Throwable t) + { + if (Category.isCategoryEnabled(this.category)) { + logger.info(categorizedMessage(this.category, msg), t); + } + } + + @Override + public void info(Marker marker, String msg) + { + if (Category.isCategoryEnabled(this.category)) { + logger.info(marker, categorizedMessage(this.category, msg)); + } + } + + @Override + public void info(String format, Object arg1, Object arg2) + { + if (Category.isCategoryEnabled(this.category)) { + logger.info(categorizedMessage(this.category, format), arg1, arg2); + } + } + + @Override + public void info(Marker marker, String format, Object arg) + { + if (Category.isCategoryEnabled(this.category)) { + logger.info(marker, categorizedMessage(this.category, format), arg); + } + } + + @Override + public void info(Marker marker, String format, Object[] argArray) + { + if (Category.isCategoryEnabled(this.category)) { + logger.info(marker, categorizedMessage(this.category, format), argArray); + } + } + + @Override + public void info(Marker marker, String msg, Throwable t) + { + if (Category.isCategoryEnabled(this.category)) { + logger.info(marker, categorizedMessage(this.category, msg), t); + } + } + + @Override + public void info(Marker marker, String format, Object arg1, Object arg2) + { + if (Category.isCategoryEnabled(this.category)) { + logger.info(marker, categorizedMessage(this.category, format), arg1, arg2); + } + } + + public void info(Category category, String msg) { + if (Category.isCategoryEnabled(category)) { + logger.info(categorizedMessage(category, msg)); + } + } + + public void info(Category category, String format, Object arg) + { + if (Category.isCategoryEnabled(category)) { + logger.info(categorizedMessage(category, format), arg); + } + } + + public void info(Category category, String format, Object[] argArray) + { + if (Category.isCategoryEnabled(category)) { + logger.info(categorizedMessage(category, format), argArray); + } + } + + public void info(Category category, String msg, Throwable t) + { + if (Category.isCategoryEnabled(category)) { + logger.info(categorizedMessage(category, msg), t); + } + } + + public void info(Category category, Marker marker, String msg) + { + if (Category.isCategoryEnabled(category)) { + logger.info(marker, categorizedMessage(category, msg)); + } + } + + public void info(Category category, String format, Object arg1, Object arg2) + { + if (Category.isCategoryEnabled(category)) { + logger.info(categorizedMessage(category, format), arg1, arg2); + } + } + + public void info(Category category, Marker marker, String format, Object arg) + { + if (Category.isCategoryEnabled(category)) { + logger.info(marker, categorizedMessage(category, format), arg); + } + } + + public void info(Category category, Marker marker, String format, Object[] argArray) + { + if (Category.isCategoryEnabled(category)) { + logger.info(marker, categorizedMessage(category, format), argArray); + } + } + + public void info(Category category, Marker marker, String msg, Throwable t) + { + if (Category.isCategoryEnabled(category)) { + logger.info(marker, categorizedMessage(category, msg), t); + } + } + + public void info(Category category, Marker marker, String format, Object arg1, Object arg2) + { + if (Category.isCategoryEnabled(category)) { + logger.info(marker, categorizedMessage(category, format), arg1, arg2); + } + } + + @Override + public boolean isDebugEnabled() + { + return (Category.isCategoryEnabled(this.category) && logger.isDebugEnabled()); + } + + @Override + public boolean isDebugEnabled(Marker marker) + { + return (Category.isCategoryEnabled(this.category) && logger.isDebugEnabled(marker)); + } + + @Override + public boolean isErrorEnabled() + { + return (Category.isCategoryEnabled(this.category) && logger.isErrorEnabled()); + } + + @Override + public boolean isErrorEnabled(Marker marker) + { + return (Category.isCategoryEnabled(this.category) && logger.isErrorEnabled(marker)); + } + + @Override + public boolean isInfoEnabled() + { + return (Category.isCategoryEnabled(this.category) && logger.isInfoEnabled()); + } + + @Override + public boolean isInfoEnabled(Marker marker) + { + return (Category.isCategoryEnabled(this.category) && logger.isInfoEnabled(marker)); + } + + @Override + public boolean isTraceEnabled() + { + return (Category.isCategoryEnabled(this.category) && logger.isTraceEnabled()); + } + + @Override + public boolean isTraceEnabled(Marker marker) + { + return (Category.isCategoryEnabled(this.category) && logger.isTraceEnabled(marker)); + } + + @Override + public boolean isWarnEnabled() + { + return (Category.isCategoryEnabled(this.category) && logger.isWarnEnabled()); + } + + @Override + public boolean isWarnEnabled(Marker marker) + { + return (Category.isCategoryEnabled(this.category) && logger.isWarnEnabled(marker)); + } + + @Override + public void trace(String msg) + { + if (Category.isCategoryEnabled(this.category)) { + logger.trace(categorizedMessage(this.category, msg)); + } + } + + @Override + public void trace(String format, Object arg) + { + if (Category.isCategoryEnabled(this.category)) { + logger.trace(categorizedMessage(this.category, format), arg); + } + } + + @Override + public void trace(String format, Object[] argArray) + { + if (Category.isCategoryEnabled(this.category)) { + logger.trace(categorizedMessage(this.category, format), argArray); + } + } + + @Override + public void trace(String msg, Throwable t) + { + if (Category.isCategoryEnabled(this.category)) { + logger.trace(categorizedMessage(this.category, msg), t); + } + } + + @Override + public void trace(Marker marker, String msg) + { + if (Category.isCategoryEnabled(this.category)) { + logger.trace(marker, categorizedMessage(this.category, msg)); + } + } + + @Override + public void trace(String format, Object arg1, Object arg2) + { + if (Category.isCategoryEnabled(this.category)) { + logger.trace(categorizedMessage(this.category, format), arg1, arg2); + } + } + + @Override + public void trace(Marker marker, String format, Object arg) + { + if (Category.isCategoryEnabled(this.category)) { + logger.trace(marker, categorizedMessage(this.category, format), arg); + } + } + + @Override + public void trace(Marker marker, String format, Object[] argArray) + { + if (Category.isCategoryEnabled(this.category)) { + logger.trace(marker, categorizedMessage(this.category, format), argArray); + } + } + + @Override + public void trace(Marker marker, String msg, Throwable t) { + if (Category.isCategoryEnabled(this.category)) { + logger.trace(marker, categorizedMessage(this.category, msg), t); + } + } + + @Override + public void trace(Marker marker, String format, Object arg1, Object arg2) + { + if (Category.isCategoryEnabled(this.category)) { + logger.trace(marker, categorizedMessage(this.category, format), arg1, arg2); + } + } + + public void trace(Category category, String msg) + { + if (Category.isCategoryEnabled(category)) { + logger.trace(categorizedMessage(category, msg)); + } + } + + public void trace(Category category, String format, Object arg) + { + if (Category.isCategoryEnabled(category)) { + logger.trace(categorizedMessage(category, format), arg); + } + } + + public void trace(Category category, String format, Object[] argArray) + { + if (Category.isCategoryEnabled(category)) { + logger.trace(categorizedMessage(category, format), argArray); + } + } + + public void trace(Category category, String msg, Throwable t) + { + if (Category.isCategoryEnabled(category)) { + logger.trace(categorizedMessage(category, msg), t); + } + } + + public void trace(Category category, Marker marker, String msg) + { + if (Category.isCategoryEnabled(category)) { + logger.trace(marker, categorizedMessage(category, msg)); + } + } + + public void trace(Category category, String format, Object arg1, Object arg2) + { + if (Category.isCategoryEnabled(category)) { + logger.trace(categorizedMessage(category, format), arg1, arg2); + } + } + + public void trace(Category category, Marker marker, String format, Object arg) + { + if (Category.isCategoryEnabled(category)) { + logger.trace(marker, categorizedMessage(category, format), arg); + } + } + + public void trace(Category category, Marker marker, String format, Object[] argArray) + { + if (Category.isCategoryEnabled(category)) { + logger.trace(marker, categorizedMessage(category, format), argArray); + } + } + + public void trace(Category category, Marker marker, String msg, Throwable t) + { + if (Category.isCategoryEnabled(category)) { + logger.trace(marker, categorizedMessage(category, msg), t); + } + } + + public void trace(Category category, Marker marker, String format, Object arg1, Object arg2) + { + if (Category.isCategoryEnabled(category)) { + logger.trace(marker, categorizedMessage(category, format), arg1, arg2); + } + } + + @Override + public void warn(String msg) + { + if (Category.isCategoryEnabled(this.category)) { + logger.warn(categorizedMessage(this.category, msg)); + } + } + + @Override + public void warn(String format, Object arg) + { + if (Category.isCategoryEnabled(this.category)) { + logger.warn(categorizedMessage(this.category, format), arg); + } + } + + @Override + public void warn(String format, Object[] argArray) + { + if (Category.isCategoryEnabled(this.category)) { + logger.warn(categorizedMessage(this.category, format), argArray); + } + } + + @Override + public void warn(String msg, Throwable t) + { + if (Category.isCategoryEnabled(this.category)) { + logger.warn(categorizedMessage(this.category, msg), t); + } + } + + @Override + public void warn(Marker marker, String msg) + { + if (Category.isCategoryEnabled(this.category)) { + logger.warn(marker, categorizedMessage(this.category, msg)); + } + } + + @Override + public void warn(String format, Object arg1, Object arg2) + { + if (Category.isCategoryEnabled(this.category)) { + logger.warn(categorizedMessage(this.category, format), arg1, arg2); + } + } + + @Override + public void warn(Marker marker, String format, Object arg) + { + if (Category.isCategoryEnabled(this.category)) { + logger.warn(marker, categorizedMessage(this.category, format), arg); + } + } + + @Override + public void warn(Marker marker, String format, Object[] argArray) + { + if (Category.isCategoryEnabled(this.category)) { + logger.warn(marker, categorizedMessage(this.category, format), argArray); + } + } + + @Override + public void warn(Marker marker, String msg, Throwable t) + { + if (Category.isCategoryEnabled(this.category)) { + logger.warn(marker, categorizedMessage(this.category, msg), t); + } + } + + @Override + public void warn(Marker marker, String format, Object arg1, Object arg2) { + if (Category.isCategoryEnabled(this.category)) { + logger.warn(marker, categorizedMessage(this.category, format), arg1, arg2); + } + } + + public void warn(Category category, String msg) + { + if (Category.isCategoryEnabled(category)) { + logger.warn(categorizedMessage(category, msg)); + } + } + + public void warn(Category category, String format, Object arg) + { + if (Category.isCategoryEnabled(category)) { + logger.warn(categorizedMessage(category, format), arg); + } + } + + public void warn(Category category, String format, Object[] argArray) + { + if (Category.isCategoryEnabled(category)) { + logger.warn(categorizedMessage(category, format), argArray); + } + } + + public void warn(Category category, String msg, Throwable t) + { + if (Category.isCategoryEnabled(category)) { + logger.warn(categorizedMessage(category, msg), t); + } + } + + public void warn(Category category, Marker marker, String msg) + { + if (Category.isCategoryEnabled(category)) { + logger.warn(marker, categorizedMessage(category, msg)); + } + } + + public void warn(Category category, String format, Object arg1, Object arg2) + { + if (Category.isCategoryEnabled(category)) { + logger.warn(categorizedMessage(category, format), arg1, arg2); + } + } + + public void warn(Category category, Marker marker, String format, Object arg) + { + if (Category.isCategoryEnabled(category)) { + logger.warn(marker, categorizedMessage(category, format), arg); + } + } + + public void warn(Category category, Marker marker, String format, Object[] argArray) + { + if (Category.isCategoryEnabled(category)) { + logger.warn(marker, categorizedMessage(category, format), argArray); + } + } + + public void warn(Category category, Marker marker, String msg, Throwable t) + { + if (Category.isCategoryEnabled(category)) { + logger.warn(marker, categorizedMessage(category, msg), t); + } + } + + public void warn(Category category, Marker marker, String format, Object arg1, Object arg2) + { + if (Category.isCategoryEnabled(category)) { + logger.warn(marker, categorizedMessage(category, format), arg1, arg2); + } + } +} diff --git a/exposure-engine/common/src/main/java/com/alu/e3/common/logging/CategoryLoggerFactory.java b/exposure-engine/common/src/main/java/com/alu/e3/common/logging/CategoryLoggerFactory.java new file mode 100644 index 0000000..fbffebb --- /dev/null +++ b/exposure-engine/common/src/main/java/com/alu/e3/common/logging/CategoryLoggerFactory.java @@ -0,0 +1,62 @@ +/** + * Copyright © 2012 Alcatel-Lucent. + * + * See the NOTICE file distributed with this work for additional + * information regarding copyright ownership. + * Licensed to you 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 com.alu.e3.common.logging; + +import org.slf4j.LoggerFactory; +import com.alu.e3.common.logging.CategoryLogger; +import com.alu.e3.common.logging.Category; + + +/** + * A factory class to create CategoryLogger instances. + *

+ * Note that this class follows the org.slf4j.LoggerFactory model of + * using the factory pattern, even though it returns a new + * CategoryLogger with each getLogger() call. This works as expected + * because a CategoryLogger holds no state of its own, only an + * slf4j Logger member and a Category enum member. If, in the future, + * CategoryLogger is modified to contain unique state, then this + * factory class may have to account for that state when returning + * Logger instances. + */ +public class CategoryLoggerFactory { + + @SuppressWarnings("rawtypes") + public static CategoryLogger getLogger(Class cls) + { + return new CategoryLogger(LoggerFactory.getLogger(cls)); + } + + @SuppressWarnings("rawtypes") + public static CategoryLogger getLogger(Class cls, Category category) + { + return new CategoryLogger(LoggerFactory.getLogger(cls), category); + } + + public static CategoryLogger getLogger(String name) + { + return new CategoryLogger(LoggerFactory.getLogger(name)); + } + + public static CategoryLogger getLogger(String name, Category category) + { + return new CategoryLogger(LoggerFactory.getLogger(name), category); + } + +} diff --git a/exposure-engine/common/src/main/java/com/alu/e3/common/logging/LogLevelListener.java b/exposure-engine/common/src/main/java/com/alu/e3/common/logging/LogLevelListener.java new file mode 100644 index 0000000..681d2a4 --- /dev/null +++ b/exposure-engine/common/src/main/java/com/alu/e3/common/logging/LogLevelListener.java @@ -0,0 +1,196 @@ +/** + * Copyright © 2012 Alcatel-Lucent. + * + * See the NOTICE file distributed with this work for additional + * information regarding copyright ownership. + * Licensed to you 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 com.alu.e3.common.logging; + +import org.apache.log4j.Level; +import org.springframework.beans.factory.annotation.Autowired; + +import com.alu.e3.common.caching.IEntryListener; +import com.alu.e3.common.logging.LoggingUtil.LogFileSource; +import com.alu.e3.common.osgi.api.IDataManager; +import com.alu.e3.data.DataEntryEvent; +import com.alu.e3.data.IDataManagerListener; +import com.alu.e3.data.model.LogLevel; + +/** + * The LogLevelListener listens for changes to the global logLevel value (made by system-manager.LoggingManager) + * and updates the local log level appropriately. + * + */ + +public class LogLevelListener implements IDataManagerListener, IEntryListener { + + private static final CategoryLogger logger = CategoryLoggerFactory.getLogger(LogLevelListener.class, Category.LOG); + + protected IDataManager dataManager; + + /** + * Default Constructor + */ + private LogLevelListener() {} + + /* + * IDataManagerListener + */ + + /** + * Property setter, auto-wired for + * automatic fulfillment by with netbean + * + * @param dataManager The new IDataManager reference + */ + @Autowired + public void setDataManager(IDataManager dataManager) + { + this.dataManager = dataManager; + } + + /** + * Called by DataManager when it's ready (has loaded all its tables) + */ + @Override + public void dataManagerReady() + { + logger.debug("DataManager ready, registering as Log-Level Listener"); + this.dataManager.addLogLevelListener(this); + } + + public void init() + { + dataManager.addListener(this); + } + + public void destroy() + { + logger.debug("Destroying, removing as listener"); + + if (this.dataManager != null) { + this.dataManager.removeListener(this); + this.dataManager.removeLogLevelListener(this); + } + } + + /* + * IEntryListener + */ + + /** + * The (single) log level value has been added. + */ + @Override + public void entryAdded(DataEntryEvent event) + { + // The handling for adding and updating an entry are the same ... + if (event != null) { + logger.trace("[LogLevelEntryAdded] key: {}", event.getKey()); + handleLogLevelEvent(event); + logger.trace("[LogEntryAdded] Finished handling log-level event: {}", event.getKey()); + } + } + + + /** + * The log entry has been updated. + */ + @Override + public void entryUpdated(DataEntryEvent event) + { + // The handling for adding and updating an entry are the same ... + if (event != null) { + logger.trace("[LogLevelEntryUpdated] key: {}", event.getKey()); + handleLogLevelEvent(event); + logger.trace("[LogEntryUpdated] Finished handling log event for ip: {}", event.getKey()); + } + } + + + /** + * A log entry has been removed, this should probably not happen + */ + @Override + public void entryRemoved(DataEntryEvent event) + { + if (event != null) { + logger.trace("[LogEntryRemoved] for ip: {}", event.getKey()); + } + } + + /** + * Performs appropriate processing for an add or update with the LogLevel DataEntryEvent. + * + * @param event A LogLevel-specific event from the DataManager + */ + private void handleLogLevelEvent(DataEntryEvent event) { + String eventKey = event.getKey(); + LogLevel logLevel = event.getValue(); + if ((eventKey == null) || (logLevel == null)) { + return; + } + // TODO: + // The logLevelParameter idea is not yet implemented, but will be the way we will + // distinguish instance-specific set-level and get-level events + // (To be implemented when the concept of InstanceIDs is sorted out) + String[] keyAndParam = eventKey.split(":", 2); + String key = keyAndParam.length > 0 ? keyAndParam[0] : ""; + String param = keyAndParam.length > 1 ? keyAndParam[1] : ""; + logger.debug("Parsed cached log-level event key: '{}' and param: '{}'", key, param); + if (key.equals(LogLevel.logLevelKey)) { + logger.debug("New java log-level notification: ({}, {})", eventKey, event.getValue()); + logger.debug("Setting local java log-level to new (global) value: {}", logLevel.toString()); + try { + LoggingUtil.setLocalLogLevel(LogFileSource.JAVA, logLevel); + } catch (Exception ex) { + logger.error("Unable to set logLevel from cache: {}", logLevel.toString()); + } + } else if (key.equals(LogLevel.smxlogLevelKey)) { + logger.debug("New smxlog-level notification: ({}, {})", eventKey, event.getValue()); + logger.debug("Setting local smxlog-level to new (global) value: {}", logLevel.toString()); + try { + LoggingUtil.setLocalLogLevel(LogFileSource.SMX, logLevel); + } catch (Exception ex) { + logger.error("Unable to set smxlogLevel from cache: {}", logLevel.toString()); + } + } else if (key.equals(LogLevel.syslogLevelKey)) { + logger.debug("New syslog-level notification: ({}, {})", eventKey, event.getValue()); + String syslogLevel = logLevel.getSyslogLevel().name(); + logger.debug("Setting local syslog-level to new (global) value: {}", syslogLevel); + try { + NonJavaLogger.setLogLevel(syslogLevel); + } catch (Exception ex) { + logger.error("Unable to set syslogLevel from cache: {}", syslogLevel); + } + } else { + // Check if this is a logging-category specification + Category category = Category.fromString(key); + if (category != null) { + logger.debug("New category-enabled notification: ({}, {})", eventKey, event.getValue()); + // If the log-level value is log4j OFF, then the category is disabled; else, category is enabled + if (logLevel.getLevel().equals(Level.OFF)) { + logger.debug("Disabling logging category: {}", category); + Category.enableCategory(category, false); + } else { + logger.debug("Enabling logging category: {}", category); + Category.enableCategory(category, true); + } + } else { + logger.warn("Did not recognize log-level dataManager event key: {} (value: {})", eventKey, event.getValue()); + } + } + } +} diff --git a/exposure-engine/common/src/main/java/com/alu/e3/common/logging/LoggingUtil.java b/exposure-engine/common/src/main/java/com/alu/e3/common/logging/LoggingUtil.java new file mode 100644 index 0000000..a9a4298 --- /dev/null +++ b/exposure-engine/common/src/main/java/com/alu/e3/common/logging/LoggingUtil.java @@ -0,0 +1,683 @@ +/** + * Copyright © 2012 Alcatel-Lucent. + * + * See the NOTICE file distributed with this work for additional + * information regarding copyright ownership. + * Licensed to you 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 com.alu.e3.common.logging; + +import java.io.File; +import java.io.FileInputStream; +import java.io.FileWriter; +import java.io.IOException; +import java.io.InputStream; +import java.util.Scanner; +import java.util.regex.Matcher; +import java.util.regex.Pattern; +import com.alu.e3.data.model.LogLevel; + +/** + * The LoggingUtil class provides static values and functions related to logging, + * for use in getting and setting log levels and modifying config files, etc. + * + */ + +public class LoggingUtil { + + + public static final String defaultKarafPath = System.getProperty("user.home") + "/apache-servicemix"; + public static final String defaultLogPath = defaultKarafPath + "/data/log/e3.log"; + public static final String defaultSMXLogPath = defaultKarafPath + "/data/log/servicemix.log"; + public static final String defaultConfigName = "org.ops4j.pax.logging.cfg"; + public static final String defaultConfigPath = defaultKarafPath + "/etc/" + defaultConfigName; + + public static final String e3Appender = "E3Appender"; + public static final String e3Prefix = "log4j.appender." + e3Appender; + public static final String e3LoggerPrefix = "log4j.logger.com.alu.e3"; + public static final String smxAppender = "out"; + public static final String smxPrefix = "log4j.appender." + smxAppender; + public static final String smxLoggerPrefix = "log4j.rootLogger"; + + public static final String rollingFileSize = "20MB"; + public static final String maxRollingFileSize = String.valueOf(Long.MAX_VALUE); + public static final String rollingLog4jConf = "# E3 appender start\n" + + "log4j.appender.E3Appender=org.apache.log4j.RollingFileAppender\n" + + "log4j.appender.E3Appender.layout=org.apache.log4j.PatternLayout\n" + + "log4j.appender.E3Appender.layout.ConversionPattern= %-5p %d %-20c [%L] - %m%n\n" + + "log4j.appender.E3Appender.file=${logPath}\n" + + "log4j.appender.E3Appender.append=true\n" + + "log4j.appender.E3Appender.maxFileSize=" + rollingFileSize + "\n" + + "log4j.appender.E3Appender.maxBackupIndex=100\n" + + "log4j.appender.E3Appender.threshold=${level}\n" + + "log4j.logger.com.alu.e3=${level}, E3Appender\n" + + "log4j.additivity.com.alu.e3=false\n" + + "# E3 appender end"; + public static final String minRollingDatePattern = "yyyy-MM-dd-HH-mm"; + public static final String hourRollingDatePattern = "yyyy-MM-dd-HH"; + public static final String maxRollingDatePattern = "yyyy-MM"; + public static final String dailyRollingDatePattern = hourRollingDatePattern; // how often to rotate logs (if using dailyRolling)? + public static final String dailyRollingLog4jConf = "# E3 appender start\n" + + "log4j.appender.E3Appender=org.apache.log4j.DailyRollingFileAppender\n" + + "log4j.appender.E3Appender.layout=org.apache.log4j.PatternLayout\n" + + "log4j.appender.E3Appender.layout.ConversionPattern= %-5p %d %-20c [%L] - %m%n\n" + + "log4j.appender.E3Appender.file=${logPath}\n" + + "log4j.appender.E3Appender.append=true\n" + + "log4j.appender.E3Appender.DatePattern='.'" + dailyRollingDatePattern + "\n" + + "log4j.appender.E3Appender.threshold=${level}\n" + + "log4j.logger.com.alu.e3=${level}, E3Appender\n" + + "log4j.additivity.com.alu.e3=false\n" + + "# E3 appender end"; + public static final String defaultLog4jConf = dailyRollingLog4jConf; // default to daily-rolling file appender + + public static final String pathPatternString = "([-\\.a-zA-Z0-9_~\\${}" + "\\" + File.separator + "]+)"; + public static final String datePatternPatternString = "([-_yMdHm]+)"; + public static final String generationPatternString = "(\\d+)"; // one or more digits + public static final String rollingFileExtPatternString = "(\\.\\d+)"; + public static final String dailyRollingFileExtPatternString = "(\\.(\\d\\d\\d\\d[-_]\\d\\d[-_]\\d\\d([-_]\\d\\d)?([-_]\\d\\d)?))"; // hours and minutes optional + public static final String rollingFilePatternString = "(.+)" + rollingFileExtPatternString + "$"; + public static final String dailyRollingFilePatternString = "(.+)" + dailyRollingFileExtPatternString + "$"; // minutes optional + + private static final CategoryLogger logger = CategoryLoggerFactory.getLogger(LoggingUtil.class, Category.LOG); + + // Create a static object to synchronize access to the (local) logging config file + private static final Object configFileLock = new Object(); + public static Object getConfigFileLock() { + return configFileLock; + } + + // Define an enum for the (3) different types of log files we care about + public enum LogFileSource { + JAVA, SYSLOG, SMX; + } + + // Define an enum for the methods of log rotation, and the associated rotated-file extensions + public enum LogRotationMethod { + ROLLING, DAILYROLLING; + } + + // Prevent instantiation - this class is to be statically + private LoggingUtil() + { + + } + + /** + * Define some useful static patterns + */ + public static Pattern logPathPattern(String appenderPrefix) + { + return Pattern.compile("(^\\s*" + appenderPrefix + "\\.file\\s*=\\s*)" + pathPatternString + "\\s*$"); + } + + public static Pattern thresholdPattern(String appenderPrefix) + { + return Pattern.compile("(^\\s*" + appenderPrefix + "\\.threshold\\s*=\\s*)" + LogLevel.Log4JLevel.patternString + "\\s*$"); + } + + public static Pattern datePatternPattern(String appenderPrefix) { + return Pattern.compile("(^\\s*" + appenderPrefix + "\\.DatePattern\\s*=\\s*'\\.')" + datePatternPatternString + "\\s*$"); // DatePattern value must start with '.' + } + + public static final Pattern loggerPattern(String loggerPrefix, String appenderName) { + return Pattern.compile("(^\\s*" + loggerPrefix + "\\s*=\\s*)" + LogLevel.Log4JLevel.patternString + "(\\s*,.*\\b" + appenderName + "\\b.*$)"); + } + + // Convenience function to get the appropriate appender prefix + public static String appenderPrefix(LogFileSource logSource) + { + if (LogFileSource.JAVA.equals(logSource)) { + return e3Prefix; + } else if (LogFileSource.SMX.equals(logSource)) { + return smxPrefix; + } + throw new IllegalArgumentException("Invalid log-source argument: " + (logSource == null ? "(null)" : logSource)); + } + + // Convenience function to get the appropriate appender name + public static String appenderName(LogFileSource logSource) + { + if (LogFileSource.JAVA.equals(logSource)) { + return e3Appender; + } else if (LogFileSource.SMX.equals(logSource)) { + return smxAppender; + } + throw new IllegalArgumentException("Invalid log-source argument: " + (logSource == null ? "(null)" : logSource)); + } + + // Convenience function to get the appropriate logger prefix + public static String loggerPrefix(LogFileSource logSource) + { + if (LogFileSource.JAVA.equals(logSource)) { + return e3LoggerPrefix; + } else if (LogFileSource.SMX.equals(logSource)) { + return smxLoggerPrefix; + } + throw new IllegalArgumentException("Invalid log-source argument: " + (logSource == null ? "(null)" : logSource)); + } + + /** + * Parses the local logging-config file and attempts to find and return + * the path of the log-file target for the specified log source. + * Obtains shared config-file lock. + * + * @param logSource The type of log; currently accepts either + * LogFileSource.JAVA or LogFileSource.SMX + * @return Path of log file, or empty string if not found + * @throws IOException + */ + public static String getLocalLogFilePath(LogFileSource logSource) throws IOException + { + String path = null; + synchronized(getConfigFileLock()) { + path = LoggingUtil.getLogFilePathFromConfigFile(new FileInputStream(defaultConfigPath), logSource, true); + } + return path; + } + + /** + * Parses the specified logging-config file and attempts to find and return + * the path of the log-file target for the specified log source. + * Performs no locking on specified config file. + * + * @param configFilePath Path of config file (see defaultConfigPath for default) + * @param logSource The type of log; currently accepts either + * LogFileSource.JAVA or LogFileSource.SMX + * @param localHost If true, will query environment variables to expand + * any variables in the returned path; if false, will use default values to + * expand any variables + * @return Path of log file, or empty string if not found + * @throws IOException + */ + public static String getLogFilePathFromConfigFile(String configFilePath, LogFileSource logSource, boolean localHost) throws IOException + { + return LoggingUtil.getLogFilePathFromConfigFile(new FileInputStream(configFilePath), logSource, localHost); + } + + /** + * Parses the specified logging-config file and attempts to find and return + * the path of the log-file target for the specified log source. + * Performs no locking on specified config file. + * + * @param configFileStream InputStream for config-file + * @param logSource The type of log; currently accepts either + * LogFileSource.JAVA or LogFileSource.SMX + * @param localHost If true, will query environment variables to expand + * any variables in the returned path; if false, will use default values to + * expand any variables + * @return Path of log file, or empty string if not found + * @throws IOException + */ + public static String getLogFilePathFromConfigFile(InputStream configFileStream, LogFileSource logSource, boolean localHost) throws IOException + { + String logFilePath = LoggingUtil.matchGroup(configFileStream, logPathPattern(appenderPrefix(logSource)), 2); + return LoggingUtil.expandConfigVariablesInPath(logFilePath, localHost); + } + + /** + * Parses the local logging-config file and attempts to find and return + * the log-level (log4j-style) for the specified log source. + * Obtains shared config-file lock. + * + * @param logSource The type of log; currently accepts either + * LogFileSource.JAVA or LogFileSource.SMX + * @return LogLevel representing current log4j level, or null if not found + * @throws IOException + */ + public static LogLevel getLocalLogLevel(LogFileSource logSource) throws IOException + { + LogLevel level = null; + synchronized(getConfigFileLock()) { + level = LoggingUtil.getLogLevelFromConfigFile(new FileInputStream(defaultConfigPath), logSource); + } + return level; + } + + /** + * Parses the specified logging-config file and attempts to find and return + * the log-level (log4j-style) for the specified log source. + * Performs no locking on specified config file. + * + * @param configFileStream Path of config file (see defaultConfigPath for default) + * @param logSource The type of log; currently accepts either + * LogFileSource.JAVA or LogFileSource.SMX + * @return LogLevel representing current log4j level, or null if not found + * @throws IOException + */ + public static LogLevel getLogLevelFromConfigFile(String configFilePath, LogFileSource logSource) throws IOException + { + return LoggingUtil.getLogLevelFromConfigFile(new FileInputStream(configFilePath), logSource); + } + + /** + * Parses the specified logging-config file and attempts to find and return + * the log-level (log4j-style) for the specified log source. + * Performs no locking on specified config file. + * + * @param configFileStream InputStream for config-file + * @param logSource The type of log; currently accepts either + * LogFileSource.JAVA or LogFileSource.SMX + * @return LogLevel representing current log4j level, or null if not found + * @throws IOException + */ + public static LogLevel getLogLevelFromConfigFile(InputStream configFileStream, LogFileSource logSource) throws IOException + { + // For source LogFileSource.JAVA, the level is found in two places: the logger line and the appender line + // For LogFileSource.SMX, there is only the (root) logger line + // So, for simplicity check the logger line in either case + LogLevel logLevel = null; + String level = LoggingUtil.matchGroup(configFileStream, loggerPattern(loggerPrefix(logSource), appenderName(logSource)), 2); + if (LogLevel.isValidLogLevel(level)) { + logLevel = new LogLevel(level); + } + return logLevel; + + } + + /** + * Parses the local logging-config file and attempts to find and return + * the date pattern for the specified log source's target log file, which in turn + * implies a log-rotation method (Rolling or DailyRolling). + * Obtains shared config-file lock. + * + * @param logSource The type of log; currently accepts either + * LogFileSource.JAVA or LogFileSource.SMX + * @return The date pattern specified for the E3 appender, or empty string if not found + * @throws IOException + */ + public static String getLocalDatePattern(LogFileSource logSource) throws IOException + { + String pattern = null; + synchronized(getConfigFileLock()) { + pattern = LoggingUtil.getDatePatternFromConfigFile(new FileInputStream(defaultConfigPath), logSource); + } + return pattern; + } + + /** + * Parses the specified logging-config file and attempts to find and return + * the date pattern for the specified log source's target log file, which in turn + * implies a log-rotation method (Rolling or DailyRolling). + * Performs no locking on specified config file. + * + * @param configFileStream Path of config file (see defaultConfigPath for default) + * @param logSource The type of log; currently accepts either + * LogFileSource.JAVA or LogFileSource.SMX + * @return The date pattern specified for the E3 appender, or empty string if not found + * @throws IOException + */ + public static String getDatePatternFromConfigFile(InputStream configFileStream, LogFileSource logSource) throws IOException + { + return LoggingUtil.matchGroup(configFileStream, datePatternPattern(appenderPrefix(logSource)), 2); + } + + /** + * Parses the specified logging-config file and attempts to find and return + * the date pattern for the specified log source's target log file, which in turn + * implies a log-rotation method (Rolling or DailyRolling). + * Performs no locking on specified config file. + * + * @param configFileStream InputStream for config-file + * @param logSource The type of log; currently accepts either + * LogFileSource.JAVA or LogFileSource.SMX + * @return The date pattern specified for the E3 appender, or empty string if not found + * @throws IOException + */ + public static String getDatePatternFromConfigFile(String configFilePath, LogFileSource logSource) throws IOException + { + return LoggingUtil.getDatePatternFromConfigFile(new FileInputStream(configFilePath), logSource); + } + + /** + * Parses the local logging-config file and attempts to infer the log-rotation + * method used by the specified log source from a date-pattern specification. + * Obtains shared config-file lock. + * + * @param logSource The type of log; currently accepts either + * LogFileSource.JAVA or LogFileSource.SMX + * @return The inferred log-rotation method, default to ROLLING + * @throws IOException + */ + public static LogRotationMethod getLocalRotationMethod(LogFileSource logSource) throws IOException + { + LogRotationMethod method = null; + synchronized(getConfigFileLock()) { + method = LoggingUtil.getRotationMethodFromConfigFile(new FileInputStream(defaultConfigPath), logSource); + } + return method; + } + + /** + * Parses the specified logging-config file and attempts to infer the log-rotation + * method used by the specified log source from a date-pattern specification. + * Performs no locking on specified config file. + * + * @param configFileStream Path of config file (see defaultConfigPath for default) + * @param logSource The type of log; currently accepts either + * LogFileSource.JAVA or LogFileSource.SMX + * @return The inferred log-rotation method, default to ROLLING + * @throws IOException + */ + public static LogRotationMethod getRotationMethodFromConfigFile(InputStream configFileStream, LogFileSource logSource) throws IOException + { + String datePattern = LoggingUtil.getDatePatternFromConfigFile(configFileStream,logSource); + if ((datePattern != null) && (datePattern.length() != 0)) { + return LogRotationMethod.DAILYROLLING; + } else { + return LogRotationMethod.ROLLING; + } + } + + /** + * Parses the specified logging-config file and attempts to infer the log-rotation + * method used by the specified log source from a date-pattern specification. + * Performs no locking on specified config file. + * + * @param configFileStream InputStream for config-file + * @param logSource The type of log; currently accepts either + * LogFileSource.JAVA or LogFileSource.SMX + * @return The inferred log-rotation method, default to ROLLING + * @throws IOException + */ + public static LogRotationMethod getRotationMethodFromConfigFile(String configFilePath, LogFileSource logSource) throws IOException + { + return LoggingUtil.getRotationMethodFromConfigFile(new FileInputStream(configFilePath), logSource); + } + + /** + * Scans through the inputStream and looks for matches in the regex pattern, returning + * the match at the specified index. If multiple lines match, will return the + * last encountered matchgroup. + * + * @param inputStream InputStream to parse + * @param pattern Regex pattern to match each line against + * @param index Index of match group to return + * @return Any match found, last occurrence if multiple, empty string if none found + * @throws IOException + */ + public static String matchGroup(InputStream inputStream, Pattern pattern, int index) throws IOException + { + String match = ""; + if ((inputStream != null) && (pattern != null)) { + Scanner scanner = new Scanner(inputStream); // option for encoding + try { + while (scanner.hasNextLine()) { + String line = scanner.nextLine(); + // Check for config-file comment lines + if (line.matches("\\s*#.*")) { + //logger.debug("Skipping comment line: {}", line); + continue; + } + Matcher m = pattern.matcher(line); + if (m.matches()) { + // Don't break, but scan rest of lines in case there are redundant rules + //logger.debug("Found e3config match: " + line); + match = m.group(index); + } else { + logger.trace("No match between {} and {}", pattern, line); + } + } + } + finally { + scanner.close(); + } + } + return match; + } + + /** + * Sets the specified log level for the specified logSource on the local machine. + * + * @param logSource The type of log; currently accepts either + * LogFileSource.JAVA or LogFileSource.SMX + * @param logLevel New log level (log4j value) + * @return Returns true if a value was previously set + * @throws IOException + */ + public static boolean setLocalLogLevel(LogFileSource logSource, LogLevel logLevel) throws IOException + { + logger.debug("Call to setLocalLogLevel with level {} and source {}", logLevel, logSource); + if (LogFileSource.JAVA.equals(logSource)) { + return LoggingUtil.setLocalJavaLogLevel(logLevel); + } else if (LogFileSource.SMX.equals(logSource)) { + return LoggingUtil.setLocalSMXLogLevel(logLevel); + } else { + throw new IllegalArgumentException("Invalid log-file source in call to setLocalLogLevel: " + logSource); + } + } + /** + * Sets the local E3Appender (java) log level by modifying the local logging + * config file, which is watched by servicemix. If the config file doesn't + * contain either of the expected log-level rules, a new E3Appender + * section will be appended to the config file. + * + * @return Returns true if the expected rules were found and modified + * @param logLevel The new logLevel + * @throws IOException + */ + public static boolean setLocalJavaLogLevel(LogLevel newLogLevel) throws IOException + { + if (newLogLevel == null) { + throw new IllegalArgumentException("Log-level parameter must not be null!"); + } + // The E3Appender uses two threshold settings, one for the logger and one for the appender + // Find and replace both + final String newLine = System.getProperty("line.separator"); + StringBuilder modContents = new StringBuilder(); + Scanner scanner = new Scanner(new FileInputStream(LoggingUtil.defaultConfigPath)); // option for encoding + Pattern thresholdPattern = LoggingUtil.thresholdPattern(LoggingUtil.appenderPrefix(LogFileSource.JAVA)); + Pattern loggerPattern = LoggingUtil.loggerPattern(LoggingUtil.e3LoggerPrefix, LoggingUtil.e3Appender); + boolean foundThresholdRule = false; + boolean foundLoggerRule = false; + + // Use cooperative lock in LoggingUtil to synchronize access to the local config file + synchronized(LoggingUtil.getConfigFileLock()) { + // Requires re-entrant config-file lock! + if (newLogLevel.equals(getLocalLogLevel(LogFileSource.JAVA))) { + logger.debug("Java log-level set to existing level: {}", newLogLevel); + return true; + } + try { + while (scanner.hasNextLine()) { + String line = scanner.nextLine(); + // Check for config-file comment lines + if (line.matches("\\s*#.*")) { + //logger.debug("Skipping comment line: {}", line); + } else { + Matcher m = thresholdPattern.matcher(line); + if (m.matches()) { + foundThresholdRule = true; + line = m.replaceAll("$1" + newLogLevel.toString()); + } else { + m = loggerPattern.matcher(line); + if (m.matches()) { + foundLoggerRule = true; + line = m.replaceAll("$1" + newLogLevel.toString() + "$3"); + } + } + } + modContents.append(line + newLine); + } + } + finally { + scanner.close(); + } + + // If E3 rules aren't found, append the default config settings + if (!foundThresholdRule && !foundLoggerRule) { + logger.debug("Using default config lines"); + String log4jConf = defaultLog4jConf.replaceAll("\\$\\{level\\}", newLogLevel.toString()).replaceAll("\\$\\{logPath\\}", LoggingUtil.defaultLogPath); + modContents.append(newLine + log4jConf + newLine); + } + + // Write the modified contents to (active) config file, hope it's being + // watched by servicemix and so will update log level + FileWriter fw = new FileWriter(LoggingUtil.defaultConfigPath, false); + try { + fw.write(modContents.toString()); + } finally { + fw.close(); + } + } + + // Return of true means we've modified existing rules + return (foundThresholdRule && foundLoggerRule); + } + + /** + * Sets the local servicemix log level by modifying the local logging + * config file, which is watched by servicemix. If the expected rules are not + * found in the config file, this function will not add them, since + * servicemix output currently goes through the rootLogger and programmatic + * changes could have widespread side-effects. + * + * @param logLevel The new logLevel + * @return Returns true if the expected rules were found and modified + * @throws IOException + */ + public static boolean setLocalSMXLogLevel(LogLevel newLogLevel) throws IOException + { + if (newLogLevel == null) { + throw new IllegalArgumentException("Log-level parameter must not be null!"); + } + // The servicemix appender uses just one threshold setting, on the rootLogger + final String newLine = System.getProperty("line.separator"); + StringBuilder modContents = new StringBuilder(); + Scanner scanner = new Scanner(new FileInputStream(LoggingUtil.defaultConfigPath)); // option for encoding + Pattern loggerPattern = LoggingUtil.loggerPattern(LoggingUtil.smxLoggerPrefix, LoggingUtil.smxAppender); + boolean foundLoggerRule = false; + + // Use cooperative lock in LoggingUtil to synchronize access to the local config file + synchronized(LoggingUtil.getConfigFileLock()) { + // Requires re-entrant config-file lock! + if (newLogLevel.equals(getLocalLogLevel(LogFileSource.SMX))) { + logger.debug("SMX log-level set to existing level: {}", newLogLevel); + return true; + } + try { + while (scanner.hasNextLine()) { + String line = scanner.nextLine(); + // Check for config-file comment lines + if (line.matches("\\s*#.*")) { + //logger.debug("Skipping comment line: {}", line); + } else { + Matcher m = loggerPattern.matcher(line); + if (m.matches()) { + foundLoggerRule = true; + line = m.replaceAll("$1" + newLogLevel.toString() + "$3"); + } + } + modContents.append(line + newLine); + } + } + finally { + scanner.close(); + } + + // If smx appender rules aren't found we don't do anything, because we'd + // need to adjust the rootLogger settings + if (!foundLoggerRule) { + logger.warn("Couldn't find rootLogger settings for servicemix in config file: {}", LoggingUtil.defaultConfigPath); + } else { + // Write the modified contents to (active) config file, hope it's being + // watched by servicemix and so will update log level + FileWriter fw = new FileWriter(LoggingUtil.defaultConfigPath, false); + try { + fw.write(modContents.toString()); + } finally { + fw.close(); + } + } + } + + // Return of true means we've modified existing rule + return (foundLoggerRule); + } + + /** + * Replace karaf environment variables (such as "${karaf.data}") in path. + * Only works on the localhost, and when path contains at most one variable. + * + * @param path The path to parse + * @return The path with variables replaced by values + */ + public static String expandConfigVariablesInPath(String path, boolean checkEnvVars) + { + final String regexPrefix = "^(.*)\\$\\{(?i)karaf\\."; + final String regexSuffix = "(?-i)\\}(.*)$"; + final String dataRegex = regexPrefix + "data" + regexSuffix; + final String homeRegex = regexPrefix + "home" + regexSuffix; + final String baseRegex = regexPrefix + "base" + regexSuffix; + + if (path != null) { + if (path.matches(dataRegex)) { + logger.debug("Found karaf.data variable in path: {}", path); + String karafDataPath = null; + if (checkEnvVars) { + karafDataPath = System.getenv("KARAF_DATA"); + logger.debug("Env. karaf data path: {}", karafDataPath); + } + if ((karafDataPath != null) && (karafDataPath.length() > 0)) { + path = path.replaceFirst(dataRegex, "$1" + karafDataPath + "$2"); + } else { + path = path.replaceFirst(dataRegex, defaultKarafPath + File.separator + "data" + "$2"); + } + logger.debug("Replacement path: {}", path); + } else if (path.contains("${karaf.home}")) { + logger.debug("Found karaf.home variable in path: {}", path); + String karafHomePath = null; + if (checkEnvVars) { + karafHomePath = System.getenv("KARAF_HOME"); + logger.debug("Env. karaf home path: {}", karafHomePath); + } + if ((karafHomePath != null) && (karafHomePath.length() > 0)) { + path = path.replaceFirst(homeRegex, "$1" + karafHomePath + "$2"); + } else { + path = path.replaceFirst(homeRegex, defaultKarafPath + "$2"); + } + logger.debug("Replacement path: {}", path); + } else if (path.contains("${karaf.base}")) { + logger.debug("Found karaf.base variable in path: {}", path); + String karafBasePath = null; + if (checkEnvVars) { + karafBasePath = System.getenv("KARAF_BASE"); + logger.debug("Env. karaf base path: {}", karafBasePath); + } + if ((karafBasePath != null) && (karafBasePath.length() > 0)) { + path = path.replaceFirst(baseRegex, "$1" + karafBasePath + "$2"); + } else { + path = path.replaceFirst(baseRegex, defaultKarafPath + "$2"); + } + logger.debug("Replacement path: {}", path); + } + } + return path; + } + + /** + * Returns the path the the apache-servicemix/karaf install on this machine. + * Looks up the karaf path in the environment variable 'KARAF_HOME'; if this + * doesn't return a value, uses a hard-coded value. + * + * @return The path the karaf install + */ + public static String karafPath() + { + String karafHomePath = System.getenv("KARAF_HOME"); + if ((karafHomePath == null) || (karafHomePath.length() == 0)) { + karafHomePath = defaultKarafPath; + } + return karafHomePath; + } +} diff --git a/exposure-engine/common/src/main/java/com/alu/e3/common/logging/NonJavaLogger.java b/exposure-engine/common/src/main/java/com/alu/e3/common/logging/NonJavaLogger.java new file mode 100644 index 0000000..1d9fe15 --- /dev/null +++ b/exposure-engine/common/src/main/java/com/alu/e3/common/logging/NonJavaLogger.java @@ -0,0 +1,532 @@ +/** + * Copyright © 2012 Alcatel-Lucent. + * + * See the NOTICE file distributed with this work for additional + * information regarding copyright ownership. + * Licensed to you 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 com.alu.e3.common.logging; + +import java.io.File; +import java.io.FileInputStream; +import java.io.FileWriter; +import java.io.IOException; +import java.util.Scanner; +import java.util.regex.Matcher; +import java.util.regex.Pattern; + +import com.alu.e3.data.model.LogLevel; + +/** + * The NonJavaLogger class is designed to enable non-Java E3 components to log to syslog. + * + * IMPORTANT NOTE: + * In order to enable the setLogLevel() function, some entries must be made in the system sudoers file: + * + * e3 hostname=(root)NOPASSWD:/bin/cp /home/$user/tmp/e3syslog.conf /etc/rsyslog.conf + * e3 hostname=(root)NOPASSWD:/etc/init.d/rsyslog restart + * + * where "hostname" is replaced with the actual system hostname. We assume these sudoers changes will + * be performed as a part of the E3 install process. (Otherwise calls to setLogLevel() will result in + * permission-denied IOExceptions.) + * + * Some limitations on parsing syslog.conf rules: + *
    + *
  • Does not handle multiple selectors, such as "e3.info;kern.debug /var/log/e3.log" + *
  • Does not handle multiple facilities, such as "e3,cron.info /var/log/e3.log" + *
  • Does not handle level prefixes, such as "=" and "!=" + *
+ * + */ + +public class NonJavaLogger { + + private static final CategoryLogger logger = CategoryLoggerFactory.getLogger(NonJavaLogger.class, Category.LOG); + + // The E3-non-java logging parameters (in syslog) are arbitrary: + public static final String defaultLogLevel = "info"; + private static String e3Facility = "local3"; // reflects both default & syslog.conf value (if written) + + // This path is specified in the sudoers file and can't be changed here unless sudoers is also changed: + public static final String defaultLogFilePath = "/var/log/e3syslog.log"; + + // The paths and control commands for syslog are system-dependent: + // On RHEL & OS-X: configFilePath = "/etc/syslog.conf"; + // On CentOS: configFilePath = "/etc/rsyslog.conf"; + // On RHEL: syslogRestartCmd = "sudo /etc/init.d/syslog restart"; + // On CentOS: syslogRestartCmd = "sudo /etc/init.d/rsyslog restart"; + // On OS-X: syslogRestartCmd = "sudo kill -SIGHUP `cat /var/run/syslog.pid`"; + private static String configFilePath1 = "/etc/syslog.conf"; // RHEL & OS-X + private static String configFilePath2 = "/etc/rsyslog.conf"; // CentOS + private static String configFilePath = null; + private static String tmpConfigFilePath = "/home/e3/tmp/e3syslog.conf"; // arbitrary, used for copying to system file + private static String servicePath1 = "/etc/init.d/syslog"; // RHEL + private static String servicePath2 = "/etc/init.d/rsyslog"; // CentOS + private static String servicePath = null; + private static String logrotateFilePath = "/etc/logrotate.d/e3"; + private static String tmpLogrotateFilePath = "/home/e3/tmp/e3logrotate"; + + // Create a static object to synchronize access to the (local) syslog config file + private static final Object configFileLock = new Object(); + public static Object getConfigFileLock() { + return configFileLock; + } + + // Build a static syslog-line regex matching pattern for efficiency + private final static String newLine = System.getProperty("line.separator"); + private static Pattern e3RulePattern = NonJavaLogger.compileE3RulePattern(); + + // Determine the actual config-file path on this system: + private static boolean locateConfigFile() { + // Default to configFilePath1, even if we can't find an alternative + configFilePath = configFilePath1; + File configFile = new File(configFilePath); + if (configFile.exists()) { + return true; + } else { + configFile = new File(configFilePath2); + if (configFile.exists()) { + configFilePath = configFilePath2; + return true; + } + } + return false; + } + + // Determine the actual syslog service path on this system: + private static boolean locateService() { + // Default to servicePath1, even if we can't find an alternative + servicePath = servicePath1; + File serviceFile = new File(servicePath); + if (serviceFile.exists()) { + return true; + } else { + serviceFile = new File(servicePath2); + if (serviceFile.exists()) { + servicePath = servicePath2; + return true; + } + } + return false; + } + + // Recompile the pattern every time e3Facility changes + private static Pattern compileE3RulePattern() + { + return Pattern.compile("^\\s*" + e3Facility + "\\." + LogLevel.SyslogLevel.configPatternString + "(\\s+)" + LoggingUtil.pathPatternString + "\\s*$"); + } + + private static String copyConfigFileCmd() + { + return "sudo /bin/cp " + tmpConfigFilePath + " " + getConfigFilePath(); + } + + private static String syslogRestartCmd() + { + return "sudo " + getSyslogServicePath() + " restart"; + } + + private static String copyLogrotateFileCmd() + { + return "sudo /bin/cp " + tmpLogrotateFilePath + " " + getLogrotateFilePath(); + } + + private static boolean isEmpty(String s) + { + return ((s == null) || (s.length() == 0)); + } + + private static boolean replaceE3Rule(String facility, String level, String logFilePath) throws IOException + { + StringBuilder modContents = new StringBuilder(); + StringBuilder replacementRule = new StringBuilder(); + replacementRule.append((NonJavaLogger.isEmpty(facility) ? e3Facility : facility) + "."); + replacementRule.append((NonJavaLogger.isEmpty(level) ? "$1" : level) + "$2"); + replacementRule.append(NonJavaLogger.isEmpty(logFilePath) ? "$3" : logFilePath); + + Scanner scanner = new Scanner(new FileInputStream(getConfigFilePath())); // option for encoding + boolean foundE3Rule = false; + String newRule = null; + int copyExitValue = 1; + + synchronized(getConfigFileLock()) { + try { + while (scanner.hasNextLine()) { + String line = scanner.nextLine(); + // Check for comment lines (this is specific to logging-config files!) + if (!line.matches("^\\s*#.*")) { + Matcher m = e3RulePattern.matcher(line); + if (m.matches()) { + foundE3Rule = true; + logger.debug("Existing e3-syslog rule: {}", line); + line = m.replaceAll(replacementRule.toString()); + newRule = line; + } + } + modContents.append(line + newLine); + } + } + finally { + scanner.close(); + } + + // Append a new rule if none already exists + if (!foundE3Rule) { + newRule = (NonJavaLogger.isEmpty(facility) ? e3Facility : facility) + "." + + (NonJavaLogger.isEmpty(level) ? defaultLogLevel : level) + "\t\t" + + (NonJavaLogger.isEmpty(logFilePath) ? defaultLogFilePath : logFilePath); + logger.debug("Adding new e3-syslog rule: {}", newRule); + modContents.append(newLine + newRule + newLine); + } + + File tmpFile = new File(tmpConfigFilePath); + File tmpDir = tmpFile.getParentFile(); + if (!tmpDir.exists()) { + tmpDir.mkdirs(); + } + FileWriter fw = new FileWriter(tmpConfigFilePath, false); + try { + fw.write(modContents.toString()); + } finally { + fw.close(); + } + logger.debug("Attempting to copy syslog.conf: {}", copyConfigFileCmd()); + Process p = Runtime.getRuntime().exec(copyConfigFileCmd()); + try { + p.waitFor(); + copyExitValue = p.exitValue(); + logger.debug("Syslog config copy process returned {}", String.valueOf(copyExitValue)); + } catch (InterruptedException ex) { + logger.warn("Syslog config copy process was interrupted!"); + return false; + } finally { + tmpFile.delete(); + } + } + + Process p = Runtime.getRuntime().exec(syslogRestartCmd()); + int restartExitValue = 1; + logger.debug("Attempting to restart rsyslog.d: {}", syslogRestartCmd()); + try { + p.waitFor(); + restartExitValue = p.exitValue(); + logger.debug("Syslog restart process returned {}", String.valueOf(restartExitValue)); + } catch (InterruptedException ex) { + logger.warn("Syslog daemon restart process was interrupted!"); + return false; + } + + if ((copyExitValue == 0) && (restartExitValue == 0)) { + logger.debug("Successfully changed E3 syslog rule: {}", newRule); + + // Save any new facility value if we've successfully written syslog.conf + if (!NonJavaLogger.isEmpty(facility) && !facility.equals(e3Facility)) { + e3Facility = facility; + e3RulePattern = NonJavaLogger.compileE3RulePattern(); + } + } + return foundE3Rule; + } + + private static String logrotateContents(String e3LogFilePath) + { + return e3LogFilePath + " {\n" + + "missingok \n" + + "notifempty \n" + + "daily \n" + + "create 0660 e3 root \n" + + "dateext \n" + + "dateformat .%Y%m%d \n" + + "}"; + } + + private static boolean writeE3LogrotateFile(String logFilePath) throws IOException + { + boolean success = false; + boolean useTempFile = false; + String contents = logrotateContents(logFilePath); + + String writePath; + File tmpFile = null; + if (useTempFile) { + writePath = tmpLogrotateFilePath; + tmpFile = new File(writePath); + File tmpDir = tmpFile.getParentFile(); + if (!tmpDir.exists()) { + tmpDir.mkdirs(); + } + } else { + writePath = logrotateFilePath; + } + FileWriter fw = new FileWriter(writePath, false); + try { + fw.write(contents); + } finally { + fw.close(); + } + + if (useTempFile) { + logger.debug("Attempting to copy e3 logrotate config file: {}", copyLogrotateFileCmd()); + Process p = Runtime.getRuntime().exec(copyLogrotateFileCmd()); + int copyExitValue = 1; + try { + p.waitFor(); + copyExitValue = p.exitValue(); + logger.debug("Logrotate config copy process returned {}", String.valueOf(copyExitValue)); + success = (copyExitValue == 0); + } catch (InterruptedException ex) { + logger.warn("Logrotate config copy process was interrupted!"); + success = false; + } finally { + tmpFile.delete(); + } + } else { + // If we've gotten this far without an exception we've written the file + success = true; + } + + logger.debug("{} change of E3 logrotate config file: {}", success ? "Successful" : "Unsuccessful", + success ? contents : logrotateFilePath); + + return success; + } + + /** + * Attempt to parse the current syslog config file to determine + * the current log level for the E3 facility. + * + * @return The current syslog level, or null if an E3-facility rule is not found + * @throws IOException + */ + public static String getLogLevel() throws IOException + { + String level = null; + synchronized(getConfigFileLock()) { + level = LoggingUtil.matchGroup(new FileInputStream(getConfigFilePath()), e3RulePattern, 1); + } + return LogLevel.isValidSyslogLevel(level) ? level : null; + } + + /** + * Attempt to set the local syslog level for the E3 facility + * by modifying the syslog config file and restarting the syslog + * daemon. If the config file is writable but an E3 facility + * rule is not found, will add one to the config file. + * + * @param newLevel A valid syslog level, one of: + *
  • EMERG
  • ALERT
  • CRIT
  • ERR
  • WARNING
  • NOTICE
  • INFO
  • DEBUG
+ * @throws IOException + */ + public static void setLogLevel(String newLevel) throws IOException + { + logger.debug("Call to set syslog logLevel to {}", newLevel); + + if (LogLevel.isValidSyslogLevel(newLevel)) { + // Relies on config-file lock being reentrant! + synchronized(getConfigFileLock()) { + // Since modifying the syslog config file also requires a restart of the syslog deamon, + // only proceed if newLevel is different than current level + String currentSyslogLevel = NonJavaLogger.getLogLevel(); + if (newLevel.equalsIgnoreCase(currentSyslogLevel)) { + logger.debug("current local syslog level is already at {}", newLevel); + } else { + NonJavaLogger.replaceE3Rule("", newLevel, ""); + } + } + } else { + throw new IllegalArgumentException("Invalid log level value"); + } + } + + /** + * Attempts to parse the syslog config file to determine the path of + * the log-file target specified in the E3 rule. Returns an empty + * string if no rule is found, or an IOException if the config file + * is not found or cannot be opened due to insufficient permissions. + * + * @return Path of E3 syslog file, or empty string if not found + * @throws IOException + */ + public static String getLogFilePath() throws IOException + { + String path = null; + synchronized(getConfigFileLock()) { + path = LoggingUtil.matchGroup(new FileInputStream(getConfigFilePath()), e3RulePattern, 3); + } + return path; + } + + /** + * Attempt to set the syslog log-file target for the E3 facility + * by modifying the syslog config file and restarting the syslog + * daemon. If the config file is writable but an E3 facility + * rule is not found, will add one to the config file. + * + * @param newPath The new log-file path + * @throws IOException + */ + public static void setLogFilePath(String newPath) throws IOException + { + logger.debug("Call to set syslog logFilePath to {}", newPath); + String path = newPath == null ? "" : newPath.trim(); + if (path.length() == 0 || !path.matches(LoggingUtil.pathPatternString)) { + throw new IllegalArgumentException("Illegal log-file path"); + } + // Since modifying the syslog config file also requires a restart of the syslog deamon, + // only proceed if path is different than current path + // Relies on config-file lock being reentrant! + synchronized(getConfigFileLock()) { + String currentPath = NonJavaLogger.getLogFilePath(); + if (newPath.equalsIgnoreCase(currentPath)) { + logger.debug("current local syslog log-file path is already at {}", newPath); + } else { + // Change the log-rotate file first, since replaceE3Rule() also restarts the syslog daemon + writeE3LogrotateFile(path); + replaceE3Rule("", "", path); + } + } + } + + public static String getE3Facility() + { + return e3Facility; + } + + /** + * Attempt to set the E3-specific facility for syslog logging + * by modifying the syslog config file and restarting the syslog + * daemon. If the config file is writable but an E3 facility + * rule is not found, will add one to the config file. + * + * @param newPath The syslog facility to use, may not be a system facility + * @throws IOException + */ + public static void setE3Facility(String newFacility) throws IOException + { + // Allow "user" facility? + logger.debug("Call to set syslog facility to {}", newFacility); + final String sysFacilities = "(?i)(auth|authpriv|cron|daemon|kern|lpr|mail|mark|news|security|syslog|user|uucp)(?-i)"; + String facility = newFacility.trim().toLowerCase(); + if (facility.matches(sysFacilities)) { + throw new IllegalArgumentException("Can't use system facilities for E3 syslogging!"); + } + NonJavaLogger.replaceE3Rule(facility, "", ""); + } + + /** + * Returns the assumed path for the local syslog config file. + * + * @return Path for the syslog config file. + */ + public static String getConfigFilePath() + { + if (configFilePath == null) { + locateConfigFile(); + } + return configFilePath; + } + + /** + * Returns an array of known syslog config file paths. + * The current set is based on known Linux paths. + * + * @return An array of possible syslog config paths. + */ + public static String[] getAltConfigFilePaths() + { + String [] paths = {configFilePath1, configFilePath2}; + return paths; + } + + /** + * Set the path for the syslog config file to be used + * in all subsequent access operations. + * + * @param newPath Path to the syslog config file. + */ + static void setConfigFilePath(String newPath) + { + configFilePath = newPath; + } + + /** + * Returns the path to the syslog daemon, which needs to + * be restarted in order to pick up any changes made to the + * syslog config file. + * + * @return Path for the syslog daemon file. + */ + public static String getSyslogServicePath() + { + if (servicePath == null) { + locateService(); + } + return servicePath; + } + + /** + * Sets the path to the syslog daemon, which needs to + * be restarted in order to pick up any changes made to the + * syslog config file. + * + * This is normally a default but may have to be + * set on a per-system basis. + * + * @param newCmd The path to the syslog daemon + */ + static void setSyslogServicePath(String newPath) + { + servicePath = newPath; + } + + /** + * Returns the path to the e3 logrotate config file. + * + * @return The e3-logrotate file path + */ + public static String getLogrotateFilePath() + { + return logrotateFilePath; + } + + /** + * Attempt to parse the specified syslog config file to determine + * the log level for the E3 facility. This function is provided for + * use with config files retrieved from remote hosts. No locking or + * access synchronization on the config file is attempted. + * + * @return The current syslog level, or null if an E3-facility rule is not found + * @throws IOException + */ + public static String getLogLevelFromConfigFile(String configFilePath) throws IOException + { + String level = LoggingUtil.matchGroup(new FileInputStream(configFilePath), e3RulePattern, 1); + return LogLevel.isValidSyslogLevel(level) ? level : null; + } + + /** + * Attempt to parse the specified syslog config file to determine + * the log target path for the E3 facility. This function is provided for + * use with config files retrieved from remote hosts. No locking or + * access synchronization on the config file is attempted. + * + * @return The log-file path, or an empty string if an E3-facility rule is not found + * @throws IOException + */ + public static String getLogFilePathFromConfigFile(String configFilePath) throws IOException + { + return LoggingUtil.matchGroup(new FileInputStream(configFilePath), e3RulePattern, 3); + } + +} diff --git a/exposure-engine/common/src/main/java/com/alu/e3/common/osgi/api/IDataManager.java b/exposure-engine/common/src/main/java/com/alu/e3/common/osgi/api/IDataManager.java new file mode 100644 index 0000000..b61ef60 --- /dev/null +++ b/exposure-engine/common/src/main/java/com/alu/e3/common/osgi/api/IDataManager.java @@ -0,0 +1,211 @@ +/** + * Copyright © 2012 Alcatel-Lucent. + * + * See the NOTICE file distributed with this work for additional + * information regarding copyright ownership. + * Licensed to you 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 com.alu.e3.common.osgi.api; + +import java.security.InvalidParameterException; +import java.util.Collection; +import java.util.List; +import java.util.Set; + +import com.alu.e3.common.caching.ICacheManager; +import com.alu.e3.common.caching.IEntryListener; +import com.alu.e3.common.logging.Category; +import com.alu.e3.data.CacheAck; +import com.alu.e3.data.IAuthMatcher; +import com.alu.e3.data.IDataManagerListener; +import com.alu.e3.data.IDataManagerUsedBucketIdsListener; +import com.alu.e3.data.model.Api; +import com.alu.e3.data.model.ApiJar; +import com.alu.e3.data.model.Auth; +import com.alu.e3.data.model.CallDescriptor; +import com.alu.e3.data.model.Certificate; +import com.alu.e3.data.model.CertificateRequest; +import com.alu.e3.data.model.Key; +import com.alu.e3.data.model.Limit; +import com.alu.e3.data.model.LogLevel; +import com.alu.e3.data.model.Policy; +import com.alu.e3.data.model.SSLCRL; +import com.alu.e3.data.model.sub.APIContext; +import com.alu.e3.data.model.sub.Context; +import com.alu.e3.data.model.sub.QuotaRLBucket; + +public interface IDataManager { + + void addListener(IDataManagerListener listener); + void removeListener(IDataManagerListener listener); + + void addListener(IDataManagerUsedBucketIdsListener listener); + void removeListener(IDataManagerUsedBucketIdsListener listener); + + Set getAllApiIds(); + + void addApi(Api api); + + boolean endpointExists(String endpoint); + + void updateApi(Api api); + + void removeApi(String id); + + Api getApiById(String id); + + Api getApiById(String id, boolean getFullDetails); + + Set getAllAuthIds(); + + void addAuth(Auth auth); + + void updateAuth(Auth auth); + + void removeAuth(String id); + + Auth getAuthById(String id); + + Auth getAuthById(String id, boolean getFullDetails); + + Auth getAuthByAuthKey(String authKey); + + Auth getAuthByOAuth(String clientId, String clientSecret); + + Auth getAuthByUserPass(String username, String password); + + Auth getWsseAuth(String username, String passwordDigest, boolean isPasswordText, String nonce, String created); + + Auth getAuthByIP(String IP); + + Auth getAuthMatching(IAuthMatcher authMatcher); + + Set getAllPolicy(); + + void addPolicy(Policy policy); + + void updatePolicy(Policy policy); + + void removePolicy(String id); + + Policy getPolicyById(String id); + + Policy getPolicyById(String id, boolean getFullDetails); + + void addAuthsToBucket(String policyId, String bucketId, QuotaRLBucket authIds) throws InvalidParameterException; + + void addAuthsToBucket(List policyId, String bucketId, QuotaRLBucket authIds) throws InvalidParameterException; + + void appendAuthsToBucket(List policyIds, String bucketId, QuotaRLBucket authIds) throws IllegalArgumentException; + + void removeAuthFromBucket(String policyId, String bucketId, String authId) throws InvalidParameterException; + + void removeAuthsFromBucket(List policyIds, String bucketId, List authIds) throws IllegalArgumentException; + + void createBucket(String policyId, QuotaRLBucket authIds) throws InvalidParameterException; + + void removeBucket(String policyId, String bucketId) throws InvalidParameterException; + + void removeBucket(List policyIds, String bucketId) throws InvalidParameterException; + + List getMatchingPolicies(Api api); + + List getMatchingPolicies(Api api, Auth auth); + + void fillLimitsById(Integer contextId, Limit limit); + + Context getPolicyContextById(Integer id); + + APIContext getApiContextById(Integer id); + + void putSettingString(String key, String value); + + void clearSettingString(String key); + + String getSettingString(String key); + + void addKey(Key key); + Set getAllKeyIds(); + Key getKeyById(String id); + Key getKeyById(String id, boolean getFullDetails); + void updateKey(Key key); + void removeKey(String id); + + void addCert(Certificate cert); + Set getAllCertIds(); + Set getAllCertIdsForKeyId(String keyId); + Certificate getCertById(String id); + Certificate getCertById(String id, boolean getFullDetails); + void updateCert(Certificate certificate); + void removeCert(String id); + + Key generateKey(String id); + CertificateRequest getCSR(String keyId); + Certificate selfSignKey(String keyId, CertificateRequest csr); + + void removeKeyListener(IEntryListener listener); + void addKeyListener(IEntryListener listener); + + void setCacheManager(ICacheManager cacheManager); + + boolean deployApi(String apiId, byte[] jarData); + + boolean undeployApi(String apiId); + + void addApiDeploymentListener(IEntryListener listener); + + void removeApiDeploymentListener(IEntryListener listener); + + void postAcknowledgment(String localQueueName, CacheAck ack) throws InterruptedException; + + void addLogLevelListener(IEntryListener listener); + void removeLogLevelListener(IEntryListener listener); + void setLogLevel(LogLevel logLevel); + LogLevel getLogLevel(); + void setSMXLogLevel(LogLevel logLevel); + LogLevel getSMXLogLevel(); + void setSyslogLevel(LogLevel logLevel); + LogLevel getSyslogLevel(); + void setLoggingCategory(Category category, boolean enabled); + public boolean getLoggingCategory(Category category); + + void reloadGateway(String ip); + + void addCA(Certificate cert); + Set getAllCA(); + Certificate getCAById(String id); + void updateCA(Certificate cert); + void removeCA(String id); + void addCAListener(IEntryListener listener); + void removeCAListener(IEntryListener listener); + + void addCRL(com.alu.e3.data.model.SSLCRL clr); + com.alu.e3.data.model.SSLCRL getCRLById(String id); + void updateCRL(com.alu.e3.data.model.SSLCRL crl); + void removeCRL(String id); + Set getAllCRL(); + Collection getAllCRLValues(); + void addCrlListener(IEntryListener listener); + void removeCrlListener(IEntryListener listener); + + boolean isApiExist(String apiId); + ApiJar getApiJar(String apiId); + + void addApiListener(IEntryListener listener); + void removeApiListener(IEntryListener listener); + +} diff --git a/exposure-engine/common/src/main/java/com/alu/e3/common/osgi/api/IHealthCheckFactory.java b/exposure-engine/common/src/main/java/com/alu/e3/common/osgi/api/IHealthCheckFactory.java new file mode 100644 index 0000000..1a37eae --- /dev/null +++ b/exposure-engine/common/src/main/java/com/alu/e3/common/osgi/api/IHealthCheckFactory.java @@ -0,0 +1,31 @@ +/** + * Copyright © 2012 Alcatel-Lucent. + * + * See the NOTICE file distributed with this work for additional + * information regarding copyright ownership. + * Licensed to you 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 com.alu.e3.common.osgi.api; + +import com.alu.e3.data.IHealthCheckService; + +public interface IHealthCheckFactory { + + static final String GATEWAY_INTERNAL_TYPE = "gatewayI"; + static final String GATEWAY_TYPE = "gateway"; + static final String SPEAKER_TYPE = "speaker"; + static final String MANAGER_TYPE = "manager"; + + IHealthCheckService getHealthCheckService(String instanceType); +} diff --git a/exposure-engine/common/src/main/java/com/alu/e3/common/osgi/api/IInstanceInfo.java b/exposure-engine/common/src/main/java/com/alu/e3/common/osgi/api/IInstanceInfo.java new file mode 100644 index 0000000..cb761f1 --- /dev/null +++ b/exposure-engine/common/src/main/java/com/alu/e3/common/osgi/api/IInstanceInfo.java @@ -0,0 +1,48 @@ +/** + * Copyright © 2012 Alcatel-Lucent. + * + * See the NOTICE file distributed with this work for additional + * information regarding copyright ownership. + * Licensed to you 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 com.alu.e3.common.osgi.api; + +import com.alu.e3.common.info.IGatewayInfo; +import com.alu.e3.common.info.IManagerInfo; +import com.alu.e3.common.info.ISpeakerInfo; + + +public interface IInstanceInfo { + + boolean isGateway(); + void setGateway(boolean isGateway); + + boolean isSpeaker(); + void setSpeaker(boolean isSpeaker); + + boolean isManager(); + void setManager(boolean isManager); + + IGatewayInfo getGatewayInfo(); + void setGatewayInfo(IGatewayInfo gatewayInfo); + + ISpeakerInfo getSpeakerInfo(); + void setSpeakerInfo(ISpeakerInfo speakerInfo); + + IManagerInfo getManagerInfo(); + void setManagerInfo(IManagerInfo managerInfo); +} \ No newline at end of file diff --git a/exposure-engine/common/src/main/java/com/alu/e3/common/osgi/api/IKeyStoreService.java b/exposure-engine/common/src/main/java/com/alu/e3/common/osgi/api/IKeyStoreService.java new file mode 100644 index 0000000..07c8356 --- /dev/null +++ b/exposure-engine/common/src/main/java/com/alu/e3/common/osgi/api/IKeyStoreService.java @@ -0,0 +1,35 @@ +/** + * Copyright © 2012 Alcatel-Lucent. + * + * See the NOTICE file distributed with this work for additional + * information regarding copyright ownership. + * Licensed to you 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 com.alu.e3.common.osgi.api; + +import java.security.KeyStore; + +public interface IKeyStoreService extends IStoreChangedObservable { + + /** + * + * Fetch a keystore object that contains all of E3's key and cert objects + * + * @return keystore object or null if unavailable. + */ + KeyStore loadKeyStore(); + + void saveKeyStore(KeyStore ks); + +} diff --git a/exposure-engine/common/src/main/java/com/alu/e3/common/osgi/api/IStoreChangedListener.java b/exposure-engine/common/src/main/java/com/alu/e3/common/osgi/api/IStoreChangedListener.java new file mode 100644 index 0000000..b13331f --- /dev/null +++ b/exposure-engine/common/src/main/java/com/alu/e3/common/osgi/api/IStoreChangedListener.java @@ -0,0 +1,26 @@ +/** + * Copyright © 2012 Alcatel-Lucent. + * + * See the NOTICE file distributed with this work for additional + * information regarding copyright ownership. + * Licensed to you 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 com.alu.e3.common.osgi.api; + +public interface IStoreChangedListener { + /** + * Called on store changed events. + */ + void onStoreChanged(); +} diff --git a/exposure-engine/common/src/main/java/com/alu/e3/common/osgi/api/IStoreChangedObservable.java b/exposure-engine/common/src/main/java/com/alu/e3/common/osgi/api/IStoreChangedObservable.java new file mode 100644 index 0000000..4a97e0f --- /dev/null +++ b/exposure-engine/common/src/main/java/com/alu/e3/common/osgi/api/IStoreChangedObservable.java @@ -0,0 +1,30 @@ +/** + * Copyright © 2012 Alcatel-Lucent. + * + * See the NOTICE file distributed with this work for additional + * information regarding copyright ownership. + * Licensed to you 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 com.alu.e3.common.osgi.api; + +public interface IStoreChangedObservable { + /** + * Listens for store changed events. + */ + void addStoreChangedListener(IStoreChangedListener listener); + /** + * Unregisters for store changed events. + */ + void removeStoreChangedListener(IStoreChangedListener listener); +} diff --git a/exposure-engine/common/src/main/java/com/alu/e3/common/osgi/api/ITopologyClient.java b/exposure-engine/common/src/main/java/com/alu/e3/common/osgi/api/ITopologyClient.java new file mode 100644 index 0000000..a022125 --- /dev/null +++ b/exposure-engine/common/src/main/java/com/alu/e3/common/osgi/api/ITopologyClient.java @@ -0,0 +1,62 @@ +/** + * Copyright © 2012 Alcatel-Lucent. + * + * See the NOTICE file distributed with this work for additional + * information regarding copyright ownership. + * Licensed to you 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. + */ +/** + * ITopologyClient + */ +package com.alu.e3.common.osgi.api; + +import java.util.ArrayList; +import java.util.List; +import java.util.Set; + +import com.alu.e3.common.caching.ICacheManager; +import com.alu.e3.common.caching.IEntryListener; +import com.alu.e3.data.model.Instance; +import com.alu.e3.data.topology.IInstanceListener; + +public interface ITopologyClient { + + void setCacheManager(ICacheManager cacheManager); + + void addInstance(Instance inst); + boolean deleteInstance(Instance inst); + + Set getAllExternalIPsOfType(String type); + Set getAllInternalIPsOfType(String type); + List getAllInstancesOfType(String type); + + Set getExternalIPsOfType(String type, String area); + Set getInternalIPsOfType(String type, String area); + List getInstancesOfType(String type, String area); + + void addAreas(Set areas); + public void setMyArea(String area); + + String getMyArea(); + Set getAllAreas(); + Set getAllOtherAreas(); + + void addInstanceTypeListener(IEntryListener> listener); + void removeInstanceTypeListener(IEntryListener> listener); + + void addInstanceListener(IInstanceListener listener); + void removeInstanceListener(IInstanceListener listener); + + public Instance whoAmI(String type); +} diff --git a/exposure-engine/common/src/main/java/com/alu/e3/common/osgi/api/ITrustStoreService.java b/exposure-engine/common/src/main/java/com/alu/e3/common/osgi/api/ITrustStoreService.java new file mode 100644 index 0000000..d26be63 --- /dev/null +++ b/exposure-engine/common/src/main/java/com/alu/e3/common/osgi/api/ITrustStoreService.java @@ -0,0 +1,26 @@ +/** + * Copyright © 2012 Alcatel-Lucent. + * + * See the NOTICE file distributed with this work for additional + * information regarding copyright ownership. + * Licensed to you 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 com.alu.e3.common.osgi.api; + +import java.security.KeyStore; + +public interface ITrustStoreService extends IStoreChangedObservable { + KeyStore loadTrustStore(); + void saveTrustStore(KeyStore ks); +} diff --git a/exposure-engine/common/src/main/java/com/alu/e3/common/spring/SpringContextBootstrapper.java b/exposure-engine/common/src/main/java/com/alu/e3/common/spring/SpringContextBootstrapper.java new file mode 100644 index 0000000..b630966 --- /dev/null +++ b/exposure-engine/common/src/main/java/com/alu/e3/common/spring/SpringContextBootstrapper.java @@ -0,0 +1,174 @@ +/** + * Copyright © 2012 Alcatel-Lucent. + * + * See the NOTICE file distributed with this work for additional + * information regarding copyright ownership. + * Licensed to you 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 com.alu.e3.common.spring; + +import java.io.FileInputStream; +import java.io.IOException; +import java.util.Properties; + +import org.osgi.framework.BundleContext; +import org.springframework.beans.BeansException; +import org.springframework.beans.factory.annotation.Autowired; +import org.springframework.context.ApplicationContext; +import org.springframework.context.ApplicationContextAware; +import org.springframework.osgi.context.support.OsgiBundleXmlApplicationContext; + +import com.alu.e3.common.E3Constant; +import com.alu.e3.common.logging.Category; +import com.alu.e3.common.logging.CategoryLogger; +import com.alu.e3.common.logging.CategoryLoggerFactory; + + +public class SpringContextBootstrapper implements ApplicationContextAware { + + protected boolean manager; + protected boolean gateway; + protected String managerComponents; + protected String gatewayComponents; + protected String propertyFile; + + private static final CategoryLogger logger = CategoryLoggerFactory.getLogger(SpringContextBootstrapper.class, Category.SYS); + + @Autowired + protected BundleContext bundleCtx; + + protected OsgiBundleXmlApplicationContext childContextManager; + protected OsgiBundleXmlApplicationContext childContextGateway; + + public void init() { + + logger.warn("System startup"); + logger.debug("init Spring contexts (manager=" + manager + ",gateway="+ gateway + ")"); + + if (isManager()) { + childContextManager.setConfigLocations(new String[]{managerComponents}); + childContextManager.refresh(); + } + + if (isGateway()) { + childContextGateway.setConfigLocations(new String[]{gatewayComponents}); + childContextGateway.refresh(); + } + } + + public void reloadNatureProperties() { + + Properties properties = new Properties(); + FileInputStream is = null; + try { + is = new FileInputStream(propertyFile); + properties.load(is); + } catch (IOException e) { + if (is != null) { + try { + is.close(); + } catch (IOException ioe) { + // Nothing to do + } + } + } + + boolean isGateway = false, isManager = false; + String prop = properties.getProperty(E3Constant.IS_MANAGER_PROPERTY_ENTRY); + if (prop != null && prop.equalsIgnoreCase("true")) + isManager = true; + prop = properties.getProperty(E3Constant.IS_GATEWAY_PROPERTY_ENTRY); + if (prop != null && prop.equalsIgnoreCase("true")) + isGateway = true; + + /* Refresh only if state's changed. */ + if (isManager && !isManager()) + { + logger.debug("Refreshing manager Spring context."); + childContextManager.setConfigLocations(new String[]{managerComponents}); + childContextManager.refresh(); + } + setManager(isManager); + + /* Refresh only if state's changed. */ + if (isGateway && !isGateway()) + { + logger.debug("Refreshing gateway Spring context."); + childContextGateway.setConfigLocations(new String[]{gatewayComponents}); + childContextGateway.refresh(); + } + setGateway(isGateway); + } + + public void destroy(){ + if(isManager()){ + childContextManager.close(); + } + + if(isGateway()){ + childContextGateway.close(); + } + logger.warn("System shutdown"); + } + + public void setManager(boolean manager) { + this.manager = manager; + } + + public boolean isManager() { + return manager; + } + + public void setGateway(boolean gateway) { + this.gateway = gateway; + } + + public boolean isGateway() { + return gateway; + } + + public void setPropertyFile(String propertyFile) { + this.propertyFile = propertyFile; + } + + public String getPropertyFile() { + return this.propertyFile; + } + + public void setManagerComponents(String managerComponents) { + this.managerComponents = managerComponents; + } + + public void setGatewayComponents(String gatewayComponents) { + this.gatewayComponents = gatewayComponents; + } + + @Override + public void setApplicationContext(ApplicationContext context) throws BeansException { + + logger.debug("Setting ApplicationContext: manager="+manager+" gateway="+ gateway); + + //here, we have to use a context implementation having a parent context + //(ex: using the given AbstractRefreshableConfigApplicationContext would result in context overwrite) + this.childContextManager = new OsgiBundleXmlApplicationContext(context); + childContextManager.setBundleContext(bundleCtx); + + this.childContextGateway = new OsgiBundleXmlApplicationContext(context); + childContextGateway.setBundleContext(bundleCtx); + } + + public void refresh() { + init(); + } +} diff --git a/exposure-engine/common/src/main/java/com/alu/e3/common/tools/BundleTools.java b/exposure-engine/common/src/main/java/com/alu/e3/common/tools/BundleTools.java new file mode 100644 index 0000000..94cc8a9 --- /dev/null +++ b/exposure-engine/common/src/main/java/com/alu/e3/common/tools/BundleTools.java @@ -0,0 +1,43 @@ +/** + * Copyright © 2012 Alcatel-Lucent. + * + * See the NOTICE file distributed with this work for additional + * information regarding copyright ownership. + * Licensed to you 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 com.alu.e3.common.tools; + +import java.io.File; +import java.io.FileInputStream; +import java.io.InputStream; + +import org.apache.commons.io.FileUtils; +import org.apache.commons.io.IOUtils; + +public class BundleTools { + + public static byte[] file2ByteArray(InputStream fileInputStream) throws Exception { + return IOUtils.toByteArray(fileInputStream); + } + + public static byte[] file2ByteArray(File file) throws Exception { + InputStream fileInputStream = new FileInputStream(file); + + return file2ByteArray(fileInputStream); + } + + public static void byteArray2File(byte[] inputByteArray, File outputFile) throws Exception { + FileUtils.writeByteArrayToFile(outputFile, inputByteArray); + } +} diff --git a/exposure-engine/common/src/main/java/com/alu/e3/common/tools/CanonicalizedIpAddress.java b/exposure-engine/common/src/main/java/com/alu/e3/common/tools/CanonicalizedIpAddress.java new file mode 100644 index 0000000..1ca89cb --- /dev/null +++ b/exposure-engine/common/src/main/java/com/alu/e3/common/tools/CanonicalizedIpAddress.java @@ -0,0 +1,333 @@ +/* + * This file contains modified source code from the Google Guava library. + * Modifications are copyright (C) 2012 Alcatel-Lucent. + * The original source code copyright notice is pasted below. + * The original source code can be found at : http://code.google.com/p/guava-libraries/source/browse/guava/src/com/google/common/net/InetAddresses.java + */ + +/* + * Copyright (C) 2008 The Guava Authors + * + * 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 com.alu.e3.common.tools; + +import java.util.Arrays; + +public class CanonicalizedIpAddress { + + private static int IPV4_LEN = 4; + private static int IPV6_HEXTET_LEN = 8; + + private String ip; + + public CanonicalizedIpAddress(String ip) { + this.ip = canonicalize(ip); + } + + public String getIp() { + return this.ip; + } + + @Override + public int hashCode() { + return ip.hashCode(); + } + + @Override + public boolean equals(Object obj) { + if (this == obj) + return true; + if (obj == null) + return false; + if (getClass() != obj.getClass()) + return false; + if(this.ip == null){ + return ((CanonicalizedIpAddress) obj).getIp() == null; + } + return this.ip.equals(((CanonicalizedIpAddress) obj).getIp()); + } + + /** + * Returns the canonical representation of an IP address String. + * + *

+ * For IPv4 addresses, this is a passthrough, but for IPv6 addresses, the + * output follows RFC 5952 + * section 4. The main difference is that this method uses "::" for zero + * compression, while Java's version uses the uncompressed form. + * + *

+ * This method uses hexadecimal for all IPv6 addresses, including + * IPv4-mapped IPv6 addresses such as "::c000:201". The output does not + * include a Scope ID. + * + * @param ip + * sting to be converted to a canonical string + * @return {@code String} containing the text-formatted IP address + */ + public static String canonicalize(String ip) throws NumberFormatException { + if(ip == null) + throw new NumberFormatException("null ip"); + if (ip.contains(":")) { + // ipv6 - run it through the int[] grinder + int[] hextets = ipv6ToHextets(ip); + compressLongestRunOfZeroes(hextets); + return hextetsToIPv6String(hextets); + } else { + StringBuilder buf = new StringBuilder(15); + String[] octets = ip.split("\\."); + if(octets.length != IPV4_LEN) + throw new NumberFormatException("bad ipv4 format"); + for(int i=0; i < IPV4_LEN ; i++){ + int octet = Integer.parseInt(octets[i]); + if(octet < 0 || octet > 255) + throw new NumberFormatException("bad ipv4 octet"); + if(i != 0) + buf.append("."); + buf.append(Integer.toString(octet)); + } + return buf.toString(); + } + } + + public static boolean isValidIp(String ip) { + try { + CanonicalizedIpAddress.canonicalize(ip); + } catch (NumberFormatException e) { + return false; + } + return true; + } + + private static int[] ipv6ToHextets(String ip) throws NumberFormatException { + if (ip.matches("^[:0-9a-fA-F]{2,30}[0-9\\.]{7,15}$")) { + // ipv4 within ipv6 + // change "::ffff:10.0.0.1" to "::ffff:0a00:0001" + ip = ip.substring(0, ip.lastIndexOf(":") + 1) + + ipv4toipv6Segment(ip.substring(ip.lastIndexOf(":") + 1, ip.length())); + } else if (ip.contains(".")) { + throw new NumberFormatException("Bad ipv6 address: " + ip); + } + + int[] ip_byte_arr = new int[IPV6_HEXTET_LEN]; + if (ip.startsWith("::")) { + int[] end = ipv6SegmentToHextets(ip.substring(2)); + + Arrays.fill(ip_byte_arr, 0, IPV6_HEXTET_LEN - end.length, 0); + System.arraycopy(end, 0, ip_byte_arr, IPV6_HEXTET_LEN - end.length, end.length); + + } else if (ip.startsWith(":")) { + throw new NumberFormatException("bad ipv6: " + ip); + } else if (ip.endsWith("::")) { + int[] start = ipv6SegmentToHextets(ip.substring(0, ip.length() - 2)); + + System.arraycopy(start, 0, ip_byte_arr, 0, start.length); + Arrays.fill(ip_byte_arr, start.length, IPV6_HEXTET_LEN, 0); + } else if (ip.endsWith(":")) { + throw new NumberFormatException("bad ipv6: " + ip); + } else if (ip.contains("::")) { + String[] split = ip.split("::", 2); + int[] start = ipv6SegmentToHextets(split[0]); + int[] end = ipv6SegmentToHextets(split[1]); + + if(start.length + end.length == IPV6_HEXTET_LEN) + throw new NumberFormatException("ipv6 contains '::' without compression"); + + System.arraycopy(start, 0, ip_byte_arr, 0, start.length); + Arrays.fill(ip_byte_arr, start.length, IPV6_HEXTET_LEN - end.length, 0); + System.arraycopy(end, 0, ip_byte_arr, IPV6_HEXTET_LEN - end.length, end.length); + } else { + int[] full = ipv6SegmentToHextets(ip); + if (full.length != IPV6_HEXTET_LEN) + throw new NumberFormatException("ipv6 address is a bad length"); + System.arraycopy(full, 0, ip_byte_arr, 0, full.length); + } + return ip_byte_arr; + } + + /** + * convert "192.168.0.1" to "c0a8:0001" + * + * @param in + * @return + * @throws NumberFormatException + */ + private static String ipv4toipv6Segment(String in) throws NumberFormatException { + String[] bytes_str = in.split("\\."); + int[] bytes_int = new int[IPV4_LEN]; + if (bytes_str.length != IPV4_LEN) + throw new NumberFormatException("bad ipv4 address: " + in); + for (int i = 0; i < IPV4_LEN; i++) { + bytes_int[i] = Integer.parseInt(bytes_str[i]); + if (bytes_int[i] > 0xff || bytes_int[i] < 0) + throw new NumberFormatException("bad ipv4 address: " + in); + } + + return String.format("%02x%02x:%02x%02x", bytes_int[0], bytes_int[1], + bytes_int[2], bytes_int[3]); + } + + private static int[] ipv6SegmentToHextets(String ip_segment) { + if ("".equals(ip_segment)) + return new int[0]; + if (ip_segment == null || ip_segment.startsWith(":") + || ip_segment.endsWith(":") || ip_segment.contains("::")) { + throw new NumberFormatException("IPv6 address contains a bad section"); + } + + String[] hextet_str_arr = ip_segment.split(":"); + int[] ret = new int[hextet_str_arr.length]; + + for (int i = 0; i < hextet_str_arr.length; i++) { + ret[i] = Integer.parseInt(hextet_str_arr[i], 16); + if (ret[i] < 0 || ret[i] > 0xffff) + throw new NumberFormatException("bad ipv6 segment"); + } + + return ret; + } + + /** + * Identify and mark the longest run of zeroes in an IPv6 address. + * + *

+ * Only runs of two or more hextets are considered. In case of a tie, the + * leftmost run wins. If a qualifying run is found, its hextets are replaced + * by the sentinel value -1. + * + * @param hextets + * {@code int[]} mutable array of eight 16-bit hextets. + */ + private static void compressLongestRunOfZeroes(int[] hextets) { + int bestRunStart = -1; + int bestRunLength = -1; + int runStart = -1; + for (int i = 0; i < hextets.length + 1; i++) { + if (i < hextets.length && hextets[i] == 0) { + if (runStart < 0) { + runStart = i; + } + } else if (runStart >= 0) { + int runLength = i - runStart; + if (runLength > bestRunLength) { + bestRunStart = runStart; + bestRunLength = runLength; + } + runStart = -1; + } + } + if (bestRunLength >= 2) { + Arrays.fill(hextets, bestRunStart, bestRunStart + bestRunLength, -1); + } + } + + /** + * Convert a list of hextets into a human-readable IPv6 address. + * + *

+ * In order for "::" compression to work, the input should contain negative + * sentinel values in place of the elided zeroes. + * + * @param hextets + * {@code int[]} array of eight 16-bit hextets, or -1s. + */ + private static String hextetsToIPv6String(int[] hextets) { + /* + * While scanning the array, handle these state transitions: + * start->num => "num" start->gap => "::" + * num->num => ":num" num->gap => "::" + * gap->num => "num" gap->gap => "" + */ + StringBuilder buf = new StringBuilder(39); + boolean lastWasNumber = false; + for (int i = 0; i < hextets.length; i++) { + boolean thisIsNumber = hextets[i] >= 0; + if (thisIsNumber) { + if (lastWasNumber) { + buf.append(':'); + } + buf.append(Integer.toHexString(hextets[i])); + } else { + if (i == 0 || lastWasNumber) { + buf.append("::"); + } + } + lastWasNumber = thisIsNumber; + } + return buf.toString(); + } + + + + /** + * this is an incomplete state-machine-ish implementation of ipv6ToByteArr that should + * be significantly faster than the original implementation. It's sometimes + * hard to find the optimal java coding pattern, so this might not actually + * be faster. + * + * This implementation exclusively uses String.substring, String.startsWith, + * and String.indexOf are fast (they should be). No splits, no contains, and + * no lastIndexOf. + * + * @param ip + * @return + + private int[] stateMachineImplA(String ip) { + int[] start = new int[8]; + int startlen = 0; + if (ip.startsWith("::")) { + // only chop off one colon here + ip = ip.substring(1); + if (ip.startsWith("::")) { + throw new NumberFormatException( + "ipv6 address cannot start with \":::\""); + } + } else if (ip.startsWith(":")) { + throw new NumberFormatException( + "ipv6 address cannot start with a single \":\""); + } + + while (startlen < 6) { + // Stop after 6 hextets because that's when we need to check for ipv4 + if (ip.startsWith(":")) { + // recall that the first ":" was chopped off. This block is + // logic for "::" + return stateMachineImplB(ip.substring(1), start, startlen); + } + int nextcolon = ip.indexOf(":"); + + int stuff = Integer.parseInt(ip.substring(0, nextcolon), 16); + if (stuff < 0 || stuff > 0xffff) + throw new NumberFormatException("ipv6 address is bad"); + start[startlen] = stuff; + startlen++; + + // "nextcolon+1" will chop off the next colon. + ip = ip.substring(nextcolon + 1); + } + + return start; + } + + private int[] stateMachineImplB_(String ip, int[] start, int startlen) { + + // This method is only called after a "::" is found. + // Fail if "::" is ever found again. + + return null; + } + + */ +} \ No newline at end of file diff --git a/exposure-engine/common/src/main/java/com/alu/e3/common/tools/CommonTools.java b/exposure-engine/common/src/main/java/com/alu/e3/common/tools/CommonTools.java new file mode 100644 index 0000000..95b5491 --- /dev/null +++ b/exposure-engine/common/src/main/java/com/alu/e3/common/tools/CommonTools.java @@ -0,0 +1,96 @@ +/** + * Copyright © 2012 Alcatel-Lucent. + * + * See the NOTICE file distributed with this work for additional + * information regarding copyright ownership. + * Licensed to you 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 com.alu.e3.common.tools; + +import java.net.InetAddress; +import java.net.MalformedURLException; +import java.net.URL; +import java.net.UnknownHostException; + +public class CommonTools { + + protected static InetAddress localInetAddress; + + static { + if (localInetAddress == null) { + try { + localInetAddress = InetAddress.getLocalHost(); + } + catch (UnknownHostException e) { + localInetAddress = null; + } + } + } + + protected static InetAddress getLocalInetAddress() { + if (localInetAddress == null) { + try { + localInetAddress = InetAddress.getLocalHost(); + } + catch (UnknownHostException e) { + localInetAddress = null; + } + } + return localInetAddress; + } + + public static String getLocalHostname() { + return getLocalInetAddress() == null ? "" : getLocalInetAddress().getHostName(); + } + + public static String getLocalAddress() { + return getLocalInetAddress() == null ? "" : getLocalInetAddress().getHostAddress(); + } + + public static boolean isLocal(String ip) { + + boolean isLocal = "127.0.0.1".equals(ip) || "localhost".equalsIgnoreCase(ip); + + if (!isLocal && getLocalInetAddress() != null) { + isLocal = ip.equals(getLocalInetAddress().getHostAddress()) || ip.equalsIgnoreCase(getLocalInetAddress().getHostName()); + } + + return isLocal; + } + + public static String[] splitUrl(String urlToSplit) { + try { + URL url = new URL(urlToSplit); + + String strUrl = url.getProtocol() + "://" + url.getHost(); + + int port = url.getPort(); + if(port != -1) + strUrl += ":" + port; + + String path = url.getPath(); + if(path != null && !path.isEmpty()) + strUrl += path; + + return new String[]{strUrl, url.getQuery()}; + + } catch (MalformedURLException e) { + return null; + } + } + +} diff --git a/exposure-engine/common/src/main/java/com/alu/e3/common/tools/ExpiringSet.java b/exposure-engine/common/src/main/java/com/alu/e3/common/tools/ExpiringSet.java new file mode 100644 index 0000000..79a191d --- /dev/null +++ b/exposure-engine/common/src/main/java/com/alu/e3/common/tools/ExpiringSet.java @@ -0,0 +1,91 @@ +/** + * Copyright © 2012 Alcatel-Lucent. + * + * See the NOTICE file distributed with this work for additional + * information regarding copyright ownership. + * Licensed to you 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 com.alu.e3.common.tools; + +import java.util.HashSet; +import java.util.Set; +import java.util.concurrent.Executors; +import java.util.concurrent.ScheduledExecutorService; +import java.util.concurrent.TimeUnit; + +/** + * Set of auto-expiring keys. A single method is provided to check + * for a given key, and add it if it isn't already there. Each key + * is automatically removed after a certain interval, specified when + * the set is constructed. + * + * + * @param key type + */ +public class ExpiringSet { + + // auto-removal scheduler + private final ScheduledExecutorService scheduler = Executors.newScheduledThreadPool(1); + + // the set itself + private final Set set = new HashSet(); + + // how long each key should live + private final int expireSeconds; + + /** + * Constructs a new ExpiringSet from which each item will + * automatically be removed after the specified number of seconds. + * + * @param expireSeconds how long each entry should live + */ + public ExpiringSet(int expireSeconds) { + this.expireSeconds = expireSeconds; + } + + /** + * Returns true if the specified key is contained in the set. + * Otherwise it adds the key to the set and returns false. + * + * @param key the key to be checked/added + * @return true if the key was found; false if it didn't exist (and was added) + */ + public boolean contains(final E key) { + synchronized (set) { + if (set.contains(key)) { + return true; + } + set.add(key); // not found, so add it + } + scheduler.schedule(new Runnable() { // schedule automatic key removal + @Override + public void run() { + synchronized (set) { + set.remove(key); + } + } + }, expireSeconds, TimeUnit.SECONDS); + return false; + } + + /** + * Releases resources associated with this ExpiringSet. + */ + public void shutdown() { + scheduler.shutdownNow(); + synchronized (set) { + set.clear(); + } + } +} diff --git a/exposure-engine/common/src/main/java/com/alu/e3/common/tools/WsseTools.java b/exposure-engine/common/src/main/java/com/alu/e3/common/tools/WsseTools.java new file mode 100644 index 0000000..8630fe8 --- /dev/null +++ b/exposure-engine/common/src/main/java/com/alu/e3/common/tools/WsseTools.java @@ -0,0 +1,369 @@ +/** + * Copyright © 2012 Alcatel-Lucent. + * + * See the NOTICE file distributed with this work for additional + * information regarding copyright ownership. + * Licensed to you 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 com.alu.e3.common.tools; + +import java.io.IOException; +import java.io.InputStream; +import java.security.MessageDigest; +import java.security.NoSuchAlgorithmException; +import java.text.DateFormat; +import java.text.ParseException; +import java.text.SimpleDateFormat; +import java.util.Date; +import java.util.Stack; +import java.util.TimeZone; + +import javax.xml.parsers.ParserConfigurationException; +import javax.xml.parsers.SAXParserFactory; + +import org.apache.commons.codec.binary.Base64; + +import org.xml.sax.Attributes; +import org.xml.sax.InputSource; +import org.xml.sax.SAXException; + +import com.alu.e3.common.logging.Category; +import com.alu.e3.common.logging.CategoryLogger; +import com.alu.e3.common.logging.CategoryLoggerFactory; + +public class WsseTools { + + private final static CategoryLogger LOG = CategoryLoggerFactory.getLogger(WsseTools.class, Category.AUTH); + + private static final SimpleDateFormat[] matchingFormats = new SimpleDateFormat[] { + new SimpleDateFormat("yyyy-MM-dd'T'HH:mm:ss.SSS'Z'"), // Standard format + new SimpleDateFormat("yyyy-MM-dd'T'HH:mm:ss'Z'") + }; + + static { + for (SimpleDateFormat format : matchingFormats) { + format.setTimeZone(TimeZone.getTimeZone("GMT")); + } + } + + /** + * Validates the WSSE username token. + * + * @param passwordDigest the password digest -- ought to be Base64-encoded SHA-1 digest of (nonceBytes + createdBytes + passwordBytes) + * @param nonce one-time use bits + * @param created when created + * @param passwordBytes the server's copy of the shared secret + * @return true if the passwordDigest is valid, else false + */ + public static boolean isValid(String passwordDigest, String nonce, String created, byte[] passwordBytes) { + return passwordDigest.equals(new String(getPasswordDigestBytes(nonce, created, passwordBytes))); + } + + public static byte[] getNonceBytes(String nonce) { + return nonce.getBytes(); + } + + public static String getNonce(byte[] nonceBytes) { + return new String(Base64.encodeBase64(nonceBytes)); + } + + public static Date getCreatedDate(String created) throws ParseException { + Date dateParsed = null; + for (DateFormat format : matchingFormats){ + try{ + synchronized (format) { // some implementations of SimpleDateFormat are not thread-safe + dateParsed = format.parse(created); + return dateParsed; + } + }catch(Exception e){ + // Do nothing, try next format available + } + } + if(dateParsed == null) throw new ParseException("Unable to parse date: " + created, 0); + return dateParsed; + } + + public static String getCreated(Date when) { + String date = null; + for (DateFormat format : matchingFormats){ + synchronized (format) { // some implementations of SimpleDateFormat are not thread-safe + date = format.format(when); + return date; + } + } + return date; + } + + public static String getPasswordDigest(byte[] passwordDigestBytes) { + return new String(passwordDigestBytes); + } + + public static byte[] getPasswordDigestBytes(String nonce, String created, byte[] passwordBytes) { + byte[] nonceBytes = nonce != null ? Base64.decodeBase64(nonce.getBytes()) : null; + byte[] createdBytes = created != null ? created.getBytes() : null; + byte[] bytes = concatenate(nonceBytes, createdBytes, passwordBytes); + try { + return Base64.encodeBase64(MessageDigest.getInstance("SHA-1").digest(bytes)); + } catch (NoSuchAlgorithmException e) { + LOG.error(e.getMessage(), e); + throw new RuntimeException(e); // missing message digest algorithm -- should not happen + } + } + + static byte[] concatenate(byte[] ... byteArrays) { + int len = 0; + for (byte[] bytes : byteArrays) { + if (bytes != null) { + len += bytes.length; + } + } + byte[] allBytes = new byte[len]; + int off = 0; + for (byte[] bytes : byteArrays) { + if (bytes != null) { + System.arraycopy(bytes, 0, allBytes, off, bytes.length); + off += bytes.length; + } + } + return allBytes; + } + + + public static class WsseUsernameToken { + + private final String username; + private final String password; + private final String nonce; + private final String created; + private final boolean isPasswordText; + + public WsseUsernameToken(String username, String password, boolean isPasswordText, String nonce, String created) { + this.username = username; + this.password = password; + this.nonce = nonce; + this.created = created; + this.isPasswordText = isPasswordText; + } + + public String getUsername() { + return username; + } + + public String getPassword() { + return password; + } + + public String getNonce() { + return nonce; + } + + public String getCreated() { + return created; + } + + public boolean isPasswordText() { + return isPasswordText; + } + } + + public static WsseUsernameToken parseXml(InputStream in) throws ParseException, IOException { + return new WsseUsernameTokenParser().getWsseUsernameToken(in); + } + + + /** + * There's no obvious way to notify a SAX parser that we've got what we need + * and it can stop parsing. So when that condition arises we throw this. + * + */ + private static class AttentionSpanExhaustedException extends SAXException { + private static final long serialVersionUID = 7514707683730084613L; + } + + /** + * SAX parser. Can be used to extract a WSSE UsernameToken element without + * the overhead of constructing a document for the entire XML input. + * + */ + private static class WsseUsernameTokenParser extends org.xml.sax.helpers.DefaultHandler { + + // fields to contain the values being extracted + private String username; + private String passwordDigest; + private boolean isPasswordText; + private String nonce; + private String created; + + // parse state variables + private boolean closed; // the values have been extracted; ignore subsequent elements + private boolean inUsernameToken; // within UsernameToken element + private StringBuilder buf; // inter-element text accumulator + private Stack stack; // element parse stack (only used within UsernameToken) + + public WsseUsernameToken getWsseUsernameToken(InputStream in) throws ParseException, IOException { + // initialize parse state + username = null; + passwordDigest = null; + nonce = null; + created = null; + closed = false; + inUsernameToken = false; + isPasswordText = true; // default value according to specs + buf = new StringBuilder(); + stack = new Stack(); + + // get a new XML parser + javax.xml.parsers.SAXParserFactory spf = SAXParserFactory.newInstance(); + spf.setValidating(false); // No validation required + spf.setNamespaceAware(true); + javax.xml.parsers.SAXParser sp; + try { + sp = spf.newSAXParser(); + } catch (ParserConfigurationException e) { + LOG.error(e.getMessage()); + throw new RuntimeException(e); // should not happen + } catch (SAXException e) { + LOG.error(e.getMessage()); + throw new RuntimeException(e); // should not happen + } + + // parse the input stream + IOException streamResetException = null; + try { + sp.parse(new InputSource(in), this); + + } catch (AttentionSpanExhaustedException e) { + // got everything we need; bailing midstream + } catch (SAXException e) { + LOG.debug(e.getMessage()); + throw new ParseException(e.getMessage(), 0); + } catch (IOException e) { + LOG.debug(e.getMessage()); + throw new ParseException(e.getMessage(), 0); + } finally { + // Resetting inputstream to prevent loosing request's body + try { + in.reset(); + } catch (IOException e) { + streamResetException = e; + } + + // all done -- release resources + buf = null; + stack = null; + } + + if(streamResetException != null) { + throw streamResetException; + } + + // construct and return an immutable token containing the extracted values + return new WsseUsernameToken(username, passwordDigest, isPasswordText, nonce, created); + } + + /** + * Sets parse state to minimize subsequent work. Releases resources. + * May be invoked more than once. + */ + private void close() { + inUsernameToken = false; + closed = true; + buf = null; + stack = null; + } + + @Override + public void startElement(String uri, String localName, String qName, Attributes attributes) throws SAXException { + if (closed) { + return; // disregard if we've already finished extracting the UsernameToken + } + LOG.debug("startElement(\"" + uri + "\", \"" + localName + "\", \"" + qName + "\", " + attributes + ")"); + buf.setLength(0); // reset text accumulator + if ("wsse:UsernameToken".equals(qName)) { + if (inUsernameToken) { + throw new SAXException("startElement: unexpected UsernameToken in UsernameToken"); + } + inUsernameToken = true; // entering UsernameToken + } + if (inUsernameToken) { + stack.push(qName); // keep track of where we are in the UsernameToken tree + + if("wsse:Password".equals(qName)) { + String passwordType = attributes.getValue("Type"); + if(passwordType != null) { + isPasswordText = !passwordType.contains("#PasswordDigest"); + } + } + } + } + + @Override + public void characters(char[] chars, int off, int len) throws SAXException { + if (!inUsernameToken) { + return; // disregard if we're before or after the UsernameToken + } + buf.append(chars, off, len); // accumulate inter-element text + } + + @Override + public void endElement(String uri, String localName, String qName) throws SAXException { + if (!inUsernameToken) { + return; // disregard if we're before or after the UsernameToken + } + LOG.debug("endElement(\"" + uri + "\", \"" + localName + "\", \"" + qName + "\")"); + + // make sure we're where we expect to be in the tree + String popped = stack.pop(); + if (!qName.equals(popped)) { + close(); + throw new SAXException("endElement: expected \"" + popped + "\", got \"" + qName + "\""); + } + + // see if we're at the end of the UsernameToken + if ("wsse:UsernameToken".equals(qName)) { + close(); // we've got what we came for + throw new AttentionSpanExhaustedException(); // bail out of the parser + } + + // see if we're at the end of an element we're interested in + if ("wsse:Username".equals(qName)) { + ensureNotSpecified(username, "Username"); + username = buf.toString(); + } else if ("wsse:Password".equals(qName)) { + ensureNotSpecified(passwordDigest, "Password"); + passwordDigest = buf.toString(); + } else if ("wsse:Nonce".equals(qName)) { + ensureNotSpecified(nonce, "Nonce"); + nonce = buf.toString(); + } else if ("wsu:Created".equals(qName)) { + ensureNotSpecified(created, "Created"); + created = buf.toString(); + } + } + + /** + * Ensures that the specified value is null. + * + * @param value the value + * @param name the name of the value + * @throws SAXException if the value is not null + */ + private void ensureNotSpecified(String value, String name) throws SAXException { + if (value != null) { + close(); + throw new SAXException("unexpected " + name + ": previously specified"); + } + } + } +} diff --git a/exposure-engine/common/src/main/java/com/alu/e3/common/transaction/ITransaction.java b/exposure-engine/common/src/main/java/com/alu/e3/common/transaction/ITransaction.java new file mode 100644 index 0000000..164a382 --- /dev/null +++ b/exposure-engine/common/src/main/java/com/alu/e3/common/transaction/ITransaction.java @@ -0,0 +1,31 @@ +/** + * Copyright © 2012 Alcatel-Lucent. + * + * See the NOTICE file distributed with this work for additional + * information regarding copyright ownership. + * Licensed to you 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 com.alu.e3.common.transaction; + +public interface ITransaction { + + Integer getTransactionId(); + void setTransactionId(Integer setTransactionId) throws TransactionLifecyleException; + + // Transaction Lifecycle + void begin() throws TransactionLifecyleException; + void commit() throws TransactionLifecyleException; + void rollback() throws TransactionLifecyleException; + void end() throws TransactionLifecyleException; +} diff --git a/exposure-engine/common/src/main/java/com/alu/e3/common/transaction/ITransactionManager.java b/exposure-engine/common/src/main/java/com/alu/e3/common/transaction/ITransactionManager.java new file mode 100644 index 0000000..786e564 --- /dev/null +++ b/exposure-engine/common/src/main/java/com/alu/e3/common/transaction/ITransactionManager.java @@ -0,0 +1,24 @@ +/** + * Copyright © 2012 Alcatel-Lucent. + * + * See the NOTICE file distributed with this work for additional + * information regarding copyright ownership. + * Licensed to you 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 com.alu.e3.common.transaction; + +public interface ITransactionManager { + ITransaction getNewTransaction() throws TransactionLifecyleException; + TransactionContext getTransactionContext(); +} diff --git a/exposure-engine/common/src/main/java/com/alu/e3/common/transaction/Operation.java b/exposure-engine/common/src/main/java/com/alu/e3/common/transaction/Operation.java new file mode 100644 index 0000000..44082f4 --- /dev/null +++ b/exposure-engine/common/src/main/java/com/alu/e3/common/transaction/Operation.java @@ -0,0 +1,118 @@ +/** + * Copyright © 2012 Alcatel-Lucent. + * + * See the NOTICE file distributed with this work for additional + * information regarding copyright ownership. + * Licensed to you 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 com.alu.e3.common.transaction; + +import java.security.InvalidParameterException; +import java.util.ArrayList; +import java.util.List; + +import org.slf4j.Logger; +import org.slf4j.LoggerFactory; + + +import com.alu.e3.common.caching.ICacheTable; + +public class Operation { + private final static Logger log = LoggerFactory.getLogger(Operation.class); + + protected OperationType operationType; + protected K key; + protected V previousValue; + protected ICacheTable cacheTable; + protected List successfulLocalOperations ; + + public Operation(OperationType operationType, K key, V previousValue, ICacheTable cacheTable) throws InvalidParameterException { + super(); + + if (cacheTable == null) + throw new InvalidParameterException("the parameter 'cacheTable' cannot be null"); + + if (key == null) + throw new InvalidParameterException("the parameter 'key' cannot be null"); + + if (operationType == OperationType.CREATE && previousValue != null) + log.warn("An entry that is to be created but seem to have a previous value (key: " + key + ", map: " + cacheTable.getName() + ")"); + + if (operationType == OperationType.UPDATE && previousValue == null) + log.warn("An entry that is to be updated does not already exist (key: " + key + ", map: " + cacheTable.getName() + ")"); + + this.operationType = operationType; + this.key = key; + this.previousValue = previousValue; + this.cacheTable = cacheTable; + this.successfulLocalOperations = new ArrayList(); + } + + public void addSuccessfulLocalOperation (String instance) { + successfulLocalOperations.add(instance); + } + + public void removeSuccessfulLocalOperation (String instance) { + successfulLocalOperations.remove(instance); + } + + public List getSuccessfulLocalOperations () { + return successfulLocalOperations; + } + + public OperationType getOperationType() { + return operationType; + } + + public void setOperationType(OperationType operationType) { + this.operationType = operationType; + } + + public K getKey() { + return key; + } + + public void setKey(K key) { + this.key = key; + } + + public V getPreviousValue() { + return previousValue; + } + + public void setPreviousValue(V previousValue) { + this.previousValue = previousValue; + } + + public ICacheTable getCacheTable() { + return cacheTable; + } + + public void setCacheTable(ICacheTable cacheTable) { + this.cacheTable = cacheTable; + } + + public void rollback() { + if (operationType == OperationType.CREATE) { + // A new data was inserted, try to remove + cacheTable.remove(key); + } else if (operationType == OperationType.UPDATE) { + // A data was update, try to restore the previous value + cacheTable.set(key, previousValue); + } else if (operationType == OperationType.DELETE) { + // A data was update, try to restore the previous value + cacheTable.set(key, previousValue); + } + } +} diff --git a/exposure-engine/common/src/main/java/com/alu/e3/common/transaction/OperationType.java b/exposure-engine/common/src/main/java/com/alu/e3/common/transaction/OperationType.java new file mode 100644 index 0000000..b01adbc --- /dev/null +++ b/exposure-engine/common/src/main/java/com/alu/e3/common/transaction/OperationType.java @@ -0,0 +1,23 @@ +/** + * Copyright © 2012 Alcatel-Lucent. + * + * See the NOTICE file distributed with this work for additional + * information regarding copyright ownership. + * Licensed to you 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 com.alu.e3.common.transaction; + +public enum OperationType { + CREATE, READ, UPDATE, DELETE; +} diff --git a/exposure-engine/common/src/main/java/com/alu/e3/common/transaction/Transaction.java b/exposure-engine/common/src/main/java/com/alu/e3/common/transaction/Transaction.java new file mode 100644 index 0000000..3da993b --- /dev/null +++ b/exposure-engine/common/src/main/java/com/alu/e3/common/transaction/Transaction.java @@ -0,0 +1,63 @@ +/** + * Copyright © 2012 Alcatel-Lucent. + * + * See the NOTICE file distributed with this work for additional + * information regarding copyright ownership. + * Licensed to you 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 com.alu.e3.common.transaction; + +class Transaction implements ITransaction { + + protected TransactionManager transactionManager; + protected Integer transactionId; + + // Users must not create a transaction directly, but get a new instance from a com.alu.e3.common.transaction.ITrasactionManager + Transaction(TransactionManager transactionManager) { + this.transactionManager = transactionManager; + // No transactionId until the transaction has begun + transactionId = null; + } + + @Override + public Integer getTransactionId() { + return transactionId; + } + + @Override + public void setTransactionId(Integer transactionId) { + this.transactionId = transactionId; + } + + @Override + public void begin() throws TransactionLifecyleException { + transactionManager.attachTransaction(this); + } + + @Override + public void commit() throws TransactionLifecyleException { + } + + @Override + public void rollback() throws TransactionLifecyleException { + transactionManager.rollback(); + transactionManager.detachTransaction(this); + } + + @Override + public void end() throws TransactionLifecyleException { + transactionManager.detachTransaction(this); + } + +} \ No newline at end of file diff --git a/exposure-engine/common/src/main/java/com/alu/e3/common/transaction/TransactionContext.java b/exposure-engine/common/src/main/java/com/alu/e3/common/transaction/TransactionContext.java new file mode 100644 index 0000000..610a3ef --- /dev/null +++ b/exposure-engine/common/src/main/java/com/alu/e3/common/transaction/TransactionContext.java @@ -0,0 +1,84 @@ +/** + * Copyright © 2012 Alcatel-Lucent. + * + * See the NOTICE file distributed with this work for additional + * information regarding copyright ownership. + * Licensed to you 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 com.alu.e3.common.transaction; + +import java.util.ArrayList; +import java.util.List; + + +public class TransactionContext { + protected Integer transactionId; + protected List> operations; + protected boolean isRollbackOnly, isRollbacking; + protected Operation rollbackingOperation; + + public Operation getRollbackingOperation() { + return rollbackingOperation; + } + + public void setRollbackingOperation(Operation rollbackingOperation) { + this.rollbackingOperation = rollbackingOperation; + } + + public boolean isRollbacking() { + return isRollbacking; + } + + public void setRollbacking(boolean isRollbacking) { + this.isRollbacking = isRollbacking; + } + + public boolean isRollbackOnly() { + return isRollbackOnly; + } + + public void setRollbackOnly(boolean isRollbackOnly) { + this.isRollbackOnly = isRollbackOnly; + } + + public TransactionContext(Integer transactionId) { + super(); + this.transactionId = transactionId; + + operations = new ArrayList>(); + isRollbackOnly = false; + isRollbacking = false; + rollbackingOperation = null; + } + + public Integer getTransactionId() { + return transactionId; + } + + public void addOperation(Operation operation) { + operations.add(operation); + } + + public void rollback() { + isRollbackOnly = false; + isRollbacking = true; + for (int i = operations.size()-1; i >= 0; i--) { + rollbackingOperation = operations.get(i); + operations.get(i).rollback(); + } + rollbackingOperation = null; + isRollbacking = false; + } + +} diff --git a/exposure-engine/common/src/main/java/com/alu/e3/common/transaction/TransactionLifecyleException.java b/exposure-engine/common/src/main/java/com/alu/e3/common/transaction/TransactionLifecyleException.java new file mode 100644 index 0000000..eebbb10 --- /dev/null +++ b/exposure-engine/common/src/main/java/com/alu/e3/common/transaction/TransactionLifecyleException.java @@ -0,0 +1,40 @@ +/** + * Copyright © 2012 Alcatel-Lucent. + * + * See the NOTICE file distributed with this work for additional + * information regarding copyright ownership. + * Licensed to you 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 com.alu.e3.common.transaction; + +public class TransactionLifecyleException extends Exception { + + private static final long serialVersionUID = -686060422488277574L; + + public TransactionLifecyleException() { + super(); + } + + public TransactionLifecyleException(String message) { + super(message); + } + + public TransactionLifecyleException(String message, Throwable cause) { + super(message, cause); + } + + public TransactionLifecyleException(Throwable cause) { + super(cause); + } +} diff --git a/exposure-engine/common/src/main/java/com/alu/e3/common/transaction/TransactionManager.java b/exposure-engine/common/src/main/java/com/alu/e3/common/transaction/TransactionManager.java new file mode 100644 index 0000000..9485266 --- /dev/null +++ b/exposure-engine/common/src/main/java/com/alu/e3/common/transaction/TransactionManager.java @@ -0,0 +1,74 @@ +/** + * Copyright © 2012 Alcatel-Lucent. + * + * See the NOTICE file distributed with this work for additional + * information regarding copyright ownership. + * Licensed to you 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 com.alu.e3.common.transaction; + +import java.util.concurrent.atomic.AtomicInteger; + +public class TransactionManager implements ITransactionManager { + + // Using a final static counter is neither a good choice if we want a cluster-wide counter + private static final AtomicInteger counter = new AtomicInteger(0); + + private static final ThreadLocal threadLocalTransactionContext = new ThreadLocal() { + @Override + protected TransactionContext initialValue() { + return null; + } + }; + + @Override + public ITransaction getNewTransaction() throws TransactionLifecyleException { + return new Transaction(this); + } + + @Override + public TransactionContext getTransactionContext() { + return threadLocalTransactionContext.get(); + } + + public void attachTransaction(ITransaction transaction) throws TransactionLifecyleException { + if (threadLocalTransactionContext.get() != null) + throw new TransactionLifecyleException ("Can not start 2 transactions at the same time."); + + if (transaction.getTransactionId() != null) + throw new TransactionLifecyleException ("Can not add a transaction that is already in a transaction context."); + + Integer newTransactionId = counter.getAndIncrement(); + + transaction.setTransactionId(newTransactionId); + TransactionContext transactionContext = new TransactionContext(newTransactionId); + + threadLocalTransactionContext.set(transactionContext); + } + + public void detachTransaction(ITransaction transaction) throws TransactionLifecyleException { + if (threadLocalTransactionContext.get() == null) + throw new TransactionLifecyleException ("No started transaction"); + + threadLocalTransactionContext.set(null); + transaction.setTransactionId(null); + } + + public void rollback() { + TransactionContext transactionContext = threadLocalTransactionContext.get(); + if (transactionContext != null) + transactionContext.rollback(); + } + +} diff --git a/exposure-engine/common/src/main/java/com/alu/e3/data/CacheAck.java b/exposure-engine/common/src/main/java/com/alu/e3/data/CacheAck.java new file mode 100644 index 0000000..bb4a22e --- /dev/null +++ b/exposure-engine/common/src/main/java/com/alu/e3/data/CacheAck.java @@ -0,0 +1,27 @@ +/** + * Copyright © 2012 Alcatel-Lucent. + * + * See the NOTICE file distributed with this work for additional + * information regarding copyright ownership. + * Licensed to you 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 com.alu.e3.data; + +public enum CacheAck { + OK, + KO +} diff --git a/exposure-engine/common/src/main/java/com/alu/e3/data/DataEntryEvent.java b/exposure-engine/common/src/main/java/com/alu/e3/data/DataEntryEvent.java new file mode 100644 index 0000000..e27cd55 --- /dev/null +++ b/exposure-engine/common/src/main/java/com/alu/e3/data/DataEntryEvent.java @@ -0,0 +1,48 @@ +/** + * Copyright © 2012 Alcatel-Lucent. + * + * See the NOTICE file distributed with this work for additional + * information regarding copyright ownership. + * Licensed to you 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 com.alu.e3.data; + +public class DataEntryEvent { + + + protected K key; + protected V value; + + public DataEntryEvent(K key, V value) { + this.key = key; + this.value = value; + } + + /** + * @return the key + */ + public K getKey() { + return key; + } + + /** + * @return the value + */ + public V getValue() { + return value; + } +} diff --git a/exposure-engine/common/src/main/java/com/alu/e3/data/DataManager.java b/exposure-engine/common/src/main/java/com/alu/e3/data/DataManager.java new file mode 100644 index 0000000..6943a12 --- /dev/null +++ b/exposure-engine/common/src/main/java/com/alu/e3/data/DataManager.java @@ -0,0 +1,2391 @@ +/** + * Copyright © 2012 Alcatel-Lucent. + * + * See the NOTICE file distributed with this work for additional + * information regarding copyright ownership. + * Licensed to you 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 com.alu.e3.data; + +import java.text.ParseException; +import java.util.ArrayList; +import java.util.Collection; +import java.util.Date; +import java.util.HashMap; +import java.util.HashSet; +import java.util.List; +import java.util.Map; +import java.util.Set; +import java.util.UUID; +import java.util.concurrent.locks.ReentrantLock; + +import org.apache.log4j.Level; + +import com.alu.e3.common.E3Constant; +import com.alu.e3.common.InvalidIDException; +import com.alu.e3.common.NullHazelcastTableException; +import com.alu.e3.common.caching.IAckData; +import com.alu.e3.common.caching.ICacheManager; +import com.alu.e3.common.caching.ICacheQueue; +import com.alu.e3.common.caching.ICacheTable; +import com.alu.e3.common.caching.IEntryListener; +import com.alu.e3.common.caching.internal.HandlerPool; +import com.alu.e3.common.caching.internal.MapHandler; +import com.alu.e3.common.caching.internal.QueueHandler; +import com.alu.e3.common.info.GatewayStatus; +import com.alu.e3.common.info.RemoteInstanceInfo; +import com.alu.e3.common.logging.Category; +import com.alu.e3.common.logging.CategoryLogger; +import com.alu.e3.common.logging.CategoryLoggerFactory; +import com.alu.e3.common.osgi.api.IDataManager; +import com.alu.e3.common.osgi.api.ITopologyClient; +import com.alu.e3.common.tools.ExpiringSet; +import com.alu.e3.common.tools.WsseTools; +import com.alu.e3.data.model.Api; +import com.alu.e3.data.model.ApiDetail; +import com.alu.e3.data.model.ApiJar; +import com.alu.e3.data.model.Auth; +import com.alu.e3.data.model.AuthDetail; +import com.alu.e3.data.model.CallDescriptor; +import com.alu.e3.data.model.Certificate; +import com.alu.e3.data.model.CertificateDetail; +import com.alu.e3.data.model.CertificateRequest; +import com.alu.e3.data.model.Instance; +import com.alu.e3.data.model.Key; +import com.alu.e3.data.model.KeyDetail; +import com.alu.e3.data.model.Limit; +import com.alu.e3.data.model.LogLevel; +import com.alu.e3.data.model.Policy; +import com.alu.e3.data.model.SSLCRL; +import com.alu.e3.data.model.enumeration.NBAuthType; +import com.alu.e3.data.model.enumeration.StatusType; +import com.alu.e3.data.model.sub.APIContext; +import com.alu.e3.data.model.sub.ApiIds; +import com.alu.e3.data.model.sub.AuthIds; +import com.alu.e3.data.model.sub.Context; +import com.alu.e3.data.model.sub.ContextWrapper; +import com.alu.e3.data.model.sub.Counter; +import com.alu.e3.data.model.sub.QuotaRLBucket; +import com.alu.e3.data.topology.IInstanceListener; +import com.alu.e3.data.topology.InstanceEvent; + +public class DataManager implements IDataManager, IInstanceListener { + + private static final CategoryLogger logger = CategoryLoggerFactory.getLogger(DataManager.class, Category.DMGR); + + // Is tables already initialized or not. + private boolean isHazelCastTablesInitialized = false; + + // On SystemManager only + private ICacheTable cachingTableApiDetails; + private ICacheTable cachingTableAuthDetails; + private ICacheTable cachingTableAuthIdToAuthToken; + private ICacheTable cachingTableKeyDetails; + private ICacheTable cachingTableCertificateDetails; + private ICacheTable cachingTableCADetails; + + // On SystemManager only, recreated at startup + + // => At startup, check all policies and all buckets, recreate Set + private Set usedBucketIds = new HashSet(); + private Set usedEndpoints = new HashSet(); + + // On Gateway and SystemManager + private ICacheTable cachingTableApi; + private ICacheTable cachingTableAuth; + private ICacheTable cachingTableAuthIpAddress; + private ICacheTable cachingTablePolicy; + private ICacheTable cachingTableContext; + private ICacheTable cachingTableSettings; + private ICacheTable cachingTableKey; + private ICacheTable cachingTableCertificate; + private ICacheTable cachingTableLogLevel; + private ICacheTable cachingTableCA; + private ICacheTable cachingTableCRL; + + private ICacheTable cachingTableApiJars; // table with acknowledgement service + + private ICacheManager cacheManager; + private ITopologyClient topologyClient; + + protected boolean manager; + + private ReentrantLock dataManagerReadyLock = new ReentrantLock(); + + // DataManagerListeners + private Set listeners = new HashSet(); + private Set usedBucketIdslisteners = new HashSet(); + + protected HandlerPool> queueHandlerPool = new HandlerPool>(E3Constant.HAZELCAST_HANDLER_POOL_MAX_SIZE); + protected HandlerPool> mapHandlerPool = new HandlerPool>(E3Constant.HAZELCAST_HANDLER_POOL_MAX_SIZE); + + + public DataManager() { + + /* Create fake table objects. */ + cachingTableApiDetails = new SanityCheckCacheTable("cachingTableApiDetails"); + cachingTableAuthDetails = new SanityCheckCacheTable("cachingTableAuthDetails"); + cachingTableAuthIdToAuthToken = new SanityCheckCacheTable("cachingTableAuthIdToAuthToken"); + cachingTableKeyDetails = new SanityCheckCacheTable("cachingTableKeyDetails"); + cachingTableCertificateDetails = new SanityCheckCacheTable("cachingTableCertificateDetails"); + cachingTableCADetails = new SanityCheckCacheTable("cachingTableCADetails"); + + cachingTableApi = new SanityCheckCacheTable("cachingTableApi"); + cachingTableAuth = new SanityCheckCacheTable("cachingTableAuth"); + cachingTableAuthIpAddress = new SanityCheckCacheTable("cachingTableAuthIpAddress"); + cachingTablePolicy = new SanityCheckCacheTable("cachingTablePolicy"); + cachingTableContext = new SanityCheckCacheTable("cachingTableContext"); + cachingTableSettings = new SanityCheckCacheTable("cachingTableSettings"); + cachingTableKey = new SanityCheckCacheTable("cachingTableKey"); + cachingTableCertificate = new SanityCheckCacheTable("cachingTableCertificate"); + cachingTableLogLevel = new SanityCheckCacheTable("cachingTableLogLevel"); + cachingTableCA = new SanityCheckCacheTable("cachingTableCA"); + cachingTableCRL = new SanityCheckCacheTable("cachingTableCRL"); + + cachingTableApiJars = new SanityCheckCacheTable("cachingTableApiJars"); + } + + @Override + public void addListener(IDataManagerListener listener) { + + dataManagerReadyLock.lock(); + + try { + this.listeners.add(listener); + + // assume that the DataManager is already ready at bean instantiation when we aren't a manager... + if(isHazelCastTablesInitialized || !isManager()) { + listener.dataManagerReady(); + } + } + finally { + dataManagerReadyLock.unlock(); + } + + } + + @Override + public void removeListener(IDataManagerListener listener) { + this.listeners.remove(listener); + } + + + @Override + public void addListener(IDataManagerUsedBucketIdsListener listener) { + this.usedBucketIdslisteners.add(listener); + } + + + @Override + public void removeListener(IDataManagerUsedBucketIdsListener listener) { + this.usedBucketIdslisteners.remove(listener); + } + + private void populateBucketAndAPIIds() { + + for (ContextWrapper context : cachingTableContext.getAllValues()) { + APIContext apiContext = context.getApiContext(); + + if (apiContext != null) { + usedBucketIds.add(apiContext.getBucketId()); + } + } + + for (Policy policy : cachingTablePolicy.getAllValues()) { + for (QuotaRLBucket bucket : policy.getAuthIds()) { + usedBucketIds.add(bucket.getBucketId()); + } + } + + for (Api api: cachingTableApi.getAllValues()) { + usedBucketIds.add(api.getApiId()); + } + + } + + private void populateUsedEndpoints() { + for(ApiDetail ad : cachingTableApiDetails.getAllValues()){ + usedEndpoints.add(ad.getEndpoint()); + } + } + + public void setManager(boolean manager) { + this.manager = manager; + } + + private boolean isManager() { + return manager; + } + + public void init() { + if (isManager()) { + // register to know when the IP of DataStorage is changing + this.topologyClient.addInstanceListener(this); + + createDataStoreTables(); + } else { + // on the gateway, there is no data store and no replication + setCachingTableApiDetails(cacheManager.createTable("cachingTableApiDetails", false, null)); + setCachingTableAuthDetails(cacheManager.createTable("cachingTableAuthDetails", false, null)); + setCachingTableAuthIdToAuthToken(cacheManager.createTable("cachingTableAuthIdToAuthToken", false, null)); + setCachingTableKeyDetails(cacheManager.createTable("cachingTableKeyDetails", false, null)); + setCachingTableCertificateDetails(cacheManager.createTable("cachingTableCertificateDetails", false, null)); + setCachingTableCADetails(cacheManager.createTable("cachingTableCADetails", false, null)); + + setCachingTableApi(cacheManager.createTable("cachingTableApi", false, null)); + setCachingTableAuth(cacheManager.createTable("cachingTableAuth", false, null)); + setCachingTableAuthIpAddress(cacheManager.createTable("cachingTableAuthIpAddress", false, null)); + setCachingTablePolicy(cacheManager.createTable("cachingTablePolicy", false, null)); + setCachingTableKey(cacheManager.createTable("cachingTableKey", false, null)); + setCachingTableCertificate(cacheManager.createTable("cachingTableCertificate", false, null)); + setCachingTableCA(cacheManager.createTable("cachingTableCA", false, null)); + setCachingTableCRL(cacheManager.createTable("cachingTableCRL", false, null)); + + setCachingTableContext(cacheManager.createTable("cachingTableContext", false, null)); + setCachingTableSettings(cacheManager.createTable("cachingTableSettings", false, null)); + + setCachingTableApiJars(cacheManager.createAckTable("cachingTableApiJars", false, null)); + setCachingTableLogLevel(cacheManager.createTable("cachingTableLogLevel", false, null)); + + isHazelCastTablesInitialized = true; + + // Inform listeners for DataManager Ready + fireDataManagerReady(); + } + } + + public void destroy() { + if (this.topologyClient != null) { + this.topologyClient.removeInstanceListener(this); + } + } + + private void fireDataManagerReady() { + dataManagerReadyLock.lock(); + + try { + // do it on a copy of the listener in case of the listener list is modified during the loop + IDataManagerListener[] currentListOfListeners = listeners.toArray(new IDataManagerListener[]{}); + + for(IDataManagerListener listener : currentListOfListeners) { + listener.dataManagerReady(); + } + } + finally { + dataManagerReadyLock.unlock(); + } + } + + private synchronized void createDataStoreTables() { + + // protect for multiple instantiation + if (!isHazelCastTablesInitialized) { + + // create the tables if the IP of DataStorage is known + List dsInfoList = topologyClient.getAllInstancesOfType(E3Constant.DATA_STORAGE); + if (dsInfoList != null && dsInfoList.size() > 0) { + + if(logger.isDebugEnabled()){ + logger.debug("DataManager initializing cache tables"); + } + + Instance dsInfo = dsInfoList.get(0); + + Map properties = new HashMap(); + + properties.put("map-store-ip", dsInfo.getInternalIP()); + properties.put("map-store-port", dsInfo.getPort()); + properties.put("map-store-user", dsInfo.getUser()); + properties.put("map-store-password", dsInfo.getPassword()); + + properties.put("map-store-name", "apiDetails"); + setCachingTableApiDetails(cacheManager.createTable("cachingTableApiDetails", false, properties)); + properties.put("map-store-name", "authDetails"); + setCachingTableAuthDetails(cacheManager.createTable("cachingTableAuthDetails", false, properties)); + properties.put("map-store-name", "authIdToAuthToken"); + setCachingTableAuthIdToAuthToken(cacheManager.createTable("cachingTableAuthIdToAuthToken", false, properties)); + properties.put("map-store-name", "keyDetails"); + setCachingTableKeyDetails(cacheManager.createTable("cachingTableKeyDetails", false, properties)); + properties.put("map-store-name", "certificateDetails"); + setCachingTableCertificateDetails(cacheManager.createTable("cachingTableCertificateDetails", false, properties)); + properties.put("map-store-name", "caDetails"); + setCachingTableCADetails(cacheManager.createTable("cachingTableCADetails", false, properties)); + + properties.put("map-store-name", "api"); + setCachingTableApi(cacheManager.createTable("cachingTableApi", true, properties)); + properties.put("map-store-name", "auth"); + setCachingTableAuth(cacheManager.createTable("cachingTableAuth", true, properties)); + properties.put("map-store-name", "authIpAddress"); + setCachingTableAuthIpAddress(cacheManager.createTable("cachingTableAuthIpAddress", true, properties)); + properties.put("map-store-name", "policy"); + setCachingTablePolicy(cacheManager.createTable("cachingTablePolicy", true, properties)); + properties.put("map-store-name", "key"); + setCachingTableKey(cacheManager.createAckTable("cachingTableKey", true, properties)); + properties.put("map-store-name", "certificate"); + setCachingTableCertificate(cacheManager.createTable("cachingTableCertificate", true, properties)); + properties.put("map-store-name", "ca"); + setCachingTableCA(cacheManager.createAckTable("cachingTableCA", true, properties)); + properties.put("map-store-name", "crl"); + setCachingTableCRL(cacheManager.createTable("cachingTableCRL", true, properties)); + + properties.put("map-store-name", "context"); + setCachingTableContext(cacheManager.createTable("cachingTableContext", true, properties)); + setCachingTableSettings(cacheManager.createTable("cachingTableSettings", true, null)); + + properties.put("map-store-name", "jars"); + setCachingTableApiJars(cacheManager.createAckTable("cachingTableApiJars", true, properties)); + + properties.put("map-store-name", "logLevel"); + setCachingTableLogLevel(cacheManager.createTable("cachingTableLogLevel", true, properties)); + + populateBucketAndAPIIds(); + populateUsedEndpoints(); + + isHazelCastTablesInitialized = true; + + // Inform listeners for DataManager Ready + fireDataManagerReady(); + + // no need to be notified on the topology again + this.topologyClient.removeInstanceListener(this); + this.topologyClient = null; + } + } + } + + @Override + public void setCacheManager(ICacheManager cacheManager) { + this.cacheManager = cacheManager; + } + + @Override + public void reloadGateway(String ip) { + // Launch the provisioning of a gateway in a dedicated thread + (new Thread (new RunnableProvisionGateway(ip))).start(); + } + + public void setTopologyClient(ITopologyClient topologyClient) { + this.topologyClient = topologyClient; + } + + @Override + public Set getAllApiIds() { + HashSet ks = new HashSet(); + + ClassLoader previousClassLoader = Thread.currentThread().getContextClassLoader(); + Thread.currentThread().setContextClassLoader(DataManager.class.getClassLoader()); + + for (Api api : cachingTableApi.getAllValues()) { + if (!api.getInternal()) { + ks.add(api.getId()); + } + } + + Thread.currentThread().setContextClassLoader(previousClassLoader); + + return ks; + } + + @Override + public boolean isApiExist (String apiId) { + return cachingTableApi.containsKey(apiId); + } + + @Override + public void addApi(Api api) { + + if (cachingTableApi.containsKey(api.getId())) + throw new IllegalArgumentException("API already exists with that ID [" + api.getId() + "]"); + + internalSaveApiDetails(api); + + boolean ok = false; + + while (!ok) { + int idx = (int)(Math.random() * Integer.MAX_VALUE); + Integer apiId = Integer.valueOf(idx); + if (!usedBucketIds.contains(apiId)) { + api.setApiId(apiId); + usedBucketIds.add(apiId); + ok = true; + } + } + + cachingTableApi.set(api.getId(), api); + usedEndpoints.add(api.getApiDetail().getEndpoint()); + } + + @Override + public boolean endpointExists(String endpoint){ + return usedEndpoints.contains(endpoint); + } + + private void internalSaveApiDetails(Api api) + { + /* if no details, nothing to do. */ + if (api.getApiDetail() == null) + return; + + api.setStatus(api.getApiDetail().getStatus()); + + cachingTableApiDetails.set(api.getId(), api.getApiDetail()); + + // Store all contexts aside, indexed by an int + for (APIContext ctx : api.getApiDetail().getContexts()) { + boolean ok = false; + + while (!ok) { + int idx = (int)(Math.random() * Integer.MAX_VALUE); + Integer contextId = Integer.valueOf(idx); + if (!cachingTableContext.containsKey(contextId)) { + ctx.setContextId(contextId); + + // API context should also be seen as a Bucket + boolean ok2 = false; + while (!ok2) { + int idx2 = (int)(Math.random() * Integer.MAX_VALUE); + Integer bucketId = Integer.valueOf(idx2); + if (!usedBucketIds.contains(bucketId)) { + ctx.setBucketId(bucketId); + usedBucketIds.add(bucketId); + ok2 = true; + } + } + + cachingTableContext.set(contextId, new ContextWrapper(ctx)); + // If this APIContext is the default one, adding it at index 0 ; this is the place where we're + // looking for it in getMatchingPolicies + ApiIds apiIds = new ApiIds(ctx.getId(), ctx.getContextId(), ctx.getBucketId(), ctx.getStatus()==StatusType.ACTIVE); + if(ctx.isDefaultContext()) + api.getContextIds().add(0, apiIds); + else + api.getContextIds().add(apiIds); + + ok = true; + } + } + } + } + + @Override + public void updateApi(Api api) throws InvalidIDException { + + Api oldApi = cachingTableApi.get(api.getId()); + if (oldApi == null) + throw new InvalidIDException("An API with that ID [" + api.getId() + "] doesn't exist"); + + // Remove all contexts and bucket ids + for (ApiIds apiIds : oldApi.getContextIds()) { + cachingTableContext.remove(Integer.valueOf(apiIds.getApiContextId())); + usedBucketIds.remove(Integer.valueOf(apiIds.getApiBucketId())); + for (IDataManagerUsedBucketIdsListener listner : this.usedBucketIdslisteners) + { + listner.usedBucketIdsRemoved(new Integer(apiIds.getApiBucketId())); + } + } + + // Remove endpoint from the used endpoints + ApiDetail oldDetail = cachingTableApiDetails.get(api.getId()); + usedEndpoints.remove(oldDetail.getEndpoint()); + + // add updated contexts + internalSaveApiDetails(api); + + api.setPolicyIds(oldApi.getPolicyIds()); + + cachingTableApi.set(api.getId(), api); + usedEndpoints.add(api.getApiDetail().getEndpoint()); + } + + @Override + public void removeApi(String id) throws InvalidIDException { + + Api api = cachingTableApi.remove(id); + + ApiDetail detail = cachingTableApiDetails.remove(id); + + if (api == null) { + throw new InvalidIDException("An API with that ID [" + id + "] doesn't exist"); + } + + // Find the policies associated, and remove this API + for (String policyId : api.getPolicyIds()) { + Policy policy = getPolicyById(policyId); + if (policy != null) { + policy.getApiIds().remove(api.getId()); + cachingTablePolicy.set(policyId, policy); + } + } + + // Remove the contexts + for (ApiIds apiIds : api.getContextIds()) { + cachingTableContext.remove(Integer.valueOf(apiIds.getApiContextId())); + usedBucketIds.remove(new Integer(apiIds.getApiBucketId())); + for (IDataManagerUsedBucketIdsListener listner : this.usedBucketIdslisteners) + { + listner.usedBucketIdsRemoved(new Integer(apiIds.getApiBucketId())); + } + } + // Remove endpoint from the used endpoints + usedEndpoints.remove(detail.getEndpoint()); + + usedBucketIds.remove(api.getApiId()); + for (IDataManagerUsedBucketIdsListener listner : this.usedBucketIdslisteners) + { + listner.usedBucketIdsRemoved(new Integer(api.getApiId())); + } + } + + @Override + public Api getApiById(String id) { + return getApiById(id, false); + } + + + @Override + public Api getApiById(String id, boolean getFullDetails) throws InvalidIDException { + + Api api = cachingTableApi.get(id); + + if (api == null) { + throw new InvalidIDException("An API with that ID [" + id + "] doesn't exist"); + } + + if (getFullDetails) { + + ApiDetail details = cachingTableApiDetails.get(id); + + if (details != null) { + + api.setApiDetail(details); + // It's not because List is transient on ApiDetail + // that it isn't stored in hazelcast memory locally. + // For sure, it will not be replicated + details.getContexts().clear(); + // We can't be sure here to reuse existing List + // it may be not up to date. + + for (ApiIds ids : api.getContextIds()) { + details.getContexts().add(cachingTableContext.get(ids.getApiContextId()).getApiContext()); + } + } + } + else + api.setApiDetail(null); + + return api; + } + + private String byteToString(byte[] data) { + + String result = null; + + if (data != null) { + result = new String(data).toString(); + } else { + result = new String(); + } + + return result; + } + + private String createTokenFromAuth(Auth auth) { + if (auth.getAuthDetail() == null) + return null; + + if (auth.getAuthDetail().getType() == NBAuthType.AUTHKEY) + return createTokenFromAuthKey(auth.getAuthDetail().getAuthKeyValue()); + if (auth.getAuthDetail().getType() == NBAuthType.OAUTH) + return createTokenFromOAuth(auth.getAuthDetail().getClientId(), auth.getAuthDetail().getClientSecret()); + if (auth.getAuthDetail().getType() == NBAuthType.BASIC) + return createTokenFromUserPass(auth.getAuthDetail().getUsername(), byteToString(auth.getAuthDetail().getPassword())); + if (auth.getAuthDetail().getType() == NBAuthType.WSSE) + return createWsseTokenFromUser(auth.getAuthDetail().getUsername()); + if (auth.getAuthDetail().getType() == NBAuthType.IP_WHITE_LIST) + return auth.getId(); + + throw new IllegalArgumentException("Unknown authentication type [" + auth.getAuthDetail().getType() + "]"); + } + + private String createTokenFromAuthKey(String authKey) { + return authKey; + } + + private String createTokenFromOAuth(String clientId, String clientSecret) { + return clientId + ";"/* + clientSecret*/; + } + + private String createTokenFromUserPass(String username, String password) { + return username + ":" + password; + } + + private String createWsseTokenFromUser(String username) { + return username + ":"; + } + + @Override + public Set getAllAuthIds() { + return cachingTableAuthIdToAuthToken.getAllKeys(); + } + + @Override + public void addAuth(Auth auth) { + + if (cachingTableAuthIdToAuthToken.containsKey(auth.getId())) + throw new IllegalArgumentException("Auth already exists with that ID [" + auth.getId() + "]"); + + String authToken = createTokenFromAuth(auth); + + Auth auth2 = cachingTableAuth.get(authToken); + if (auth2 != null) + throw new IllegalArgumentException("An authorization with the same credentials already exist"); + + // For each IP address, check if the IP already exist + if (auth.getAuthDetail() != null) { + + if (auth.getAuthDetail().getType() == NBAuthType.IP_WHITE_LIST) { + for (String ip : auth.getAuthDetail().getWhiteListedIps()) { + if (cachingTableAuthIpAddress.containsKey(ip)) + throw new IllegalArgumentException("An authorization with the same IP address already exist"); + } + } + } + + cachingTableAuthIdToAuthToken.set(auth.getId(), authToken); + cachingTableAuth.set(authToken, auth); + + if (auth.getAuthDetail() != null) { + cachingTableAuthDetails.set(authToken, auth.getAuthDetail()); + + if (auth.getAuthDetail().getType() == NBAuthType.IP_WHITE_LIST) { + for (String ip : auth.getAuthDetail().getWhiteListedIps()) { + cachingTableAuthIpAddress.set(ip, authToken); + } + } + } + } + + @Override + public void updateAuth(Auth auth) throws InvalidIDException { + + // Get old Auth + String oldAuthToken = cachingTableAuthIdToAuthToken.get(auth.getId()); + if (oldAuthToken == null) + throw new InvalidIDException("An authorization with that ID [" + auth.getId() + "] doesn't exist"); + + // For each IP address, check if the IP already exist + if (auth.getAuthDetail() != null) { + + if (auth.getAuthDetail().getType() == NBAuthType.IP_WHITE_LIST) { + for (String ip : auth.getAuthDetail().getWhiteListedIps()) { + String authToken = cachingTableAuthIpAddress.get(ip); + if ((authToken != null) && (authToken.equals(oldAuthToken) == false)) + throw new IllegalArgumentException("An authorization with the same IP address already exist"); + } + } + } + + AuthDetail authDetail = cachingTableAuthDetails.get(oldAuthToken); + if (authDetail != null) { + + // Remove all IPs from the table, and add the new one + if (authDetail.getType() == NBAuthType.IP_WHITE_LIST) { + for (String ip : authDetail.getWhiteListedIps()) { + cachingTableAuthIpAddress.remove(ip); + } + } + } + + String authToken = createTokenFromAuth(auth); + Auth auth2; + + // Check that the token has changed or not + if (oldAuthToken.equals(authToken) == false) { + + // Check that new token doesn't exist + auth2 = cachingTableAuth.get(authToken); + if (auth2 != null) + throw new IllegalArgumentException("An authorization with the same credentials already exist"); + + // If token has changed, update association table + cachingTableAuthIdToAuthToken.set(auth.getId(), authToken); + + // Remove old auth + auth2 = cachingTableAuth.remove(oldAuthToken); + + // Remove old details + cachingTableAuthDetails.remove(oldAuthToken); + + } else { + + auth2 = cachingTableAuth.get(authToken); + if (auth2 == null) + throw new IllegalArgumentException("An Authorization with that token doesn't exist"); + + } + + auth.setPolicyContexts(auth2.getPolicyContexts()); + + if (authDetail != null) { + + // Remove all IPs from the table, and add the new one + if (authDetail.getType() == NBAuthType.IP_WHITE_LIST) { + for (String ip : authDetail.getWhiteListedIps()) { + cachingTableAuthIpAddress.remove(ip); + } + } + } + + // Update the status + for (AuthIds authId : auth.getPolicyContexts()) { + authId.setStatusActive((auth.getAuthDetail() != null)?auth.getAuthDetail().getStatus()==StatusType.ACTIVE:false); + authId.setPolicyContextId(getPolicyContextId(auth, getPolicyById(authId.getPolicyId()))); + } + + cachingTableAuth.set(authToken, auth); + + if (auth.getAuthDetail() != null) { + cachingTableAuthDetails.set(authToken, auth.getAuthDetail()); + + if (auth.getAuthDetail().getType() == NBAuthType.IP_WHITE_LIST) { + for (String ip : auth.getAuthDetail().getWhiteListedIps()) { + cachingTableAuthIpAddress.set(ip, authToken); + } + } + } + } + + @Override + public void removeAuth(String id) throws InvalidIDException { + String authToken = cachingTableAuthIdToAuthToken.get(id); + if (authToken == null) + throw new InvalidIDException("An Authorization with that ID [" + id + "] doesn't exist"); + + cachingTableAuthIdToAuthToken.remove(id); + Auth auth = cachingTableAuth.remove(authToken); + AuthDetail authDetail = cachingTableAuthDetails.remove(authToken); + + if (auth == null) { + throw new InvalidIDException("An Authorization with that token doesn't exist"); + } + + if (authDetail != null) { + if (authDetail.getType() == NBAuthType.IP_WHITE_LIST) { + for (String ip : authDetail.getWhiteListedIps()) { + cachingTableAuthIpAddress.remove(ip); + } + } + } + + // Find the policies associated, and remove this Auth + for (AuthIds authCtx : auth.getPolicyContexts()) { + String policyId = authCtx.getPolicyId(); + + Policy policy = getPolicyById(policyId); + if (policy != null) { + for(QuotaRLBucket authIds : policy.getAuthIds()) { + authIds.getAuthIds().remove(auth.getId()); + cachingTablePolicy.set(policyId, policy); + } + } + } + } + + @Override + public Auth getAuthById(String id) { + return getAuthById(id, false); + } + + @Override + public Auth getAuthById(String id, boolean getFullDetails) throws InvalidIDException { + + String authToken = cachingTableAuthIdToAuthToken.get(id); + if (authToken == null) + throw new InvalidIDException("An Authorization with that ID [" + id + "] doesn't exist"); + + return getAuthByToken(authToken, getFullDetails); + } + + private Auth getAuthByToken(String authToken, boolean getFullDetails) { + + Auth auth = cachingTableAuth.get(authToken); + if (auth == null) + return null; + + if (getFullDetails) + auth.setAuthDetail(cachingTableAuthDetails.get(authToken)); + else + auth.setAuthDetail(null); + + return auth; + } + + @Override + public Auth getAuthByAuthKey(String authKey) { + if(authKey == null) return null; + else return getAuthByToken(createTokenFromAuthKey(authKey), false); + } + + @Override + public Auth getAuthByOAuth(String clientId, String clientSecret) { + if(clientId == null || clientSecret == null) return null; + else return getAuthByToken(createTokenFromOAuth(clientId, clientSecret), false); + } + + @Override + public Auth getAuthByUserPass(String username, String password) { + if(username == null || password == null) return null; + else return getAuthByToken(createTokenFromUserPass(username, password), false); + } + + private static final int WSSE_AGE_SECONDS = 5 * 60; + + private ExpiringSet liveNonces = new ExpiringSet(WSSE_AGE_SECONDS + 30); // 30 seconds extra + + @Override + public Auth getWsseAuth(String username, String password, boolean isPasswordText, String nonce, String created) { + if(username == null || password == null) { + return null; + } + Auth auth = getAuthByToken(createWsseTokenFromUser(username), false); + if (auth != null) { + + // PasswordText + if(isPasswordText) { + String storedPassword = new String(auth.getWssePassword()); + if(storedPassword.equals(password)) { + return auth; + } else { + return null; + } + + // Digest password + } else { + if (created != null) { + long then; + try { + then = WsseTools.getCreatedDate(created).getTime(); + } catch (ParseException e) { + logger.debug("invalid WSSE: created parse error: " + created); + return null; + } + long now = System.currentTimeMillis(); + if (then > now + (WSSE_AGE_SECONDS * 1000)) { // allow client to be up to 5 minutes in the future + logger.debug("invalid WSSE: created in the future: " + created); + return null; + } else if (then < now - (WSSE_AGE_SECONDS * 1000)) { + logger.debug("invalid WSSE: old created: " + created); + return null; + } + } + if (WsseTools.isValid(password, nonce, created, auth.getWssePassword())) { + if (nonce != null && liveNonces.contains(nonce)) { + logger.debug("invalid WSSE: familiar nonce: " + nonce + " (created " + created + ")"); + return null; + } + logger.debug("valid WSSE"); + return auth; + } + logger.debug("invalid WSSE: digest validation failed"); + } + } + return null; + } + + @Override + public Auth getAuthByIP(String ip) { + + String authToken = cachingTableAuthIpAddress.get(ip); + if (authToken == null) + return null; + + return getAuthByToken(authToken, false); + } + + @Override + public Auth getAuthMatching(IAuthMatcher authMatcher) { + + Auth auth = null; + + ClassLoader previousClassLoader = Thread.currentThread().getContextClassLoader(); + + Thread.currentThread().setContextClassLoader(DataManager.class.getClassLoader()); + + for (Auth authFound : cachingTableAuth.getAllValues()) { + + if(authMatcher.isAuth(authFound)) { + auth = authFound; + break; + } + } + + Thread.currentThread().setContextClassLoader(previousClassLoader); + + return auth; + } + + + @Override + public Set getAllPolicy() { + return cachingTablePolicy.getAllKeys(); + } + + @Override + public void addPolicy(Policy policy) { + + if (cachingTablePolicy.containsKey(policy.getId())) + throw new IllegalArgumentException("Policy already exists with that ID [" + policy.getId() + "]"); + + updatePolicy(policy, false); + } + + private int getPolicyContextId(Auth auth, Policy policy) { + + for (Context ctx : policy.getContexts()) { + if ((ctx.getId() != null) && (ctx.getId().equals(auth.getPolicyContext()))) + return ctx.getContextId(); + } + + for (Context ctx : policy.getContexts()) { + if ((ctx.getId() == null ) || ctx.getId().isEmpty()) + return ctx.getContextId(); + } + + return -1; + } + + @Override + public void updatePolicy(Policy policy) { + updatePolicy(policy, true); + } + + /** + * + * @param policy + * @param update specifies if the policy is a new one or replace an existing one ; used to determine if we should check for existence or not. + */ + private void updatePolicy(Policy policy, boolean update) throws InvalidIDException { + + // First, check that the apis exist + for (String apiId : policy.getApiIds()) { + if (! isApiExist(apiId)) { + throw new InvalidIDException("An API with that ID [" + apiId + "] doesn't exist"); + } + } + + // Then, check that the auths exist + for (QuotaRLBucket bucket : policy.getAuthIds()) { + for(String authId : bucket.getAuthIds()) { + String authToken = cachingTableAuthIdToAuthToken.get(authId); + if (authToken == null) + throw new IllegalArgumentException("Auth ID [" + authId + "] not found"); + + Auth auth = cachingTableAuth.get(authToken); + if (auth == null) + throw new IllegalArgumentException("Auth token not found"); + } + } + + for (QuotaRLBucket bucket : policy.getAuthIds()) { + checkIfAuthAlreadyInPolicy(policy.getId(), bucket.getAuthIds(), bucket.getId()); + } + + Policy cachedPolicy = null; + + if(update) { + cachedPolicy = getPolicyById(policy.getId(), false); + + // Remove existing contexts + for (Integer contextId : cachedPolicy.getContextIds()) { + cachingTableContext.remove(contextId); + } + } + + policy.getContextIds().clear(); + + // TODO: Check value of quota, if changed, then reset the created date, otherwise, keep old value + //=> Speaker needs to store the created date + + // Store all contexts aside, indexed by an int + for (Context ctx : policy.getContexts()) { + boolean ok = false; + + while (!ok) { + int idx = (int)(Math.random() * Integer.MAX_VALUE); + Integer contextId = Integer.valueOf(idx); + if (!cachingTableContext.containsKey(contextId)) { + ctx.setContextId(contextId); + ctx.setCreatedDate(new Date()); + cachingTableContext.set(contextId, new ContextWrapper(ctx)); + policy.getContextIds().add(contextId); + ok = true; + } + } + } + + // Store all contexts aside, indexed by an int + for (QuotaRLBucket bucket : policy.getAuthIds()) { + boolean ok = false; + + if ((cachedPolicy != null) && ((bucket.getId() == null) || (bucket.getId().equals("")))) { + // First, try to find the current bucket in the old policy + for (QuotaRLBucket cachedBucket : cachedPolicy.getAuthIds()) { + if (cachedBucket.getId().equals(bucket.getId())) { + // Bucket was already in old policy + bucket.setBucketId(cachedBucket.getBucketId()); + cachedPolicy.getAuthIds().remove(cachedBucket); + ok = true; + break; + } + } + } + + while (!ok) { + int idx = (int)(Math.random() * Integer.MAX_VALUE); + Integer bucketId = Integer.valueOf(idx); + if (!usedBucketIds.contains(bucketId)) { + bucket.setBucketId(bucketId); + usedBucketIds.add(bucketId); + + if ((bucket.getId() == null) || (bucket.getId().equals(""))) { + bucket.setId(bucketId.toString()); + } + + ok = true; + } + } + } + + if (cachedPolicy != null) { + // Now remove all buckets which are not in the new policy + for (QuotaRLBucket cachedBucket : cachedPolicy.getAuthIds()) { + usedBucketIds.remove(cachedBucket.getBucketId()); + for (IDataManagerUsedBucketIdsListener listner : this.usedBucketIdslisteners) + { + listner.usedBucketIdsRemoved(cachedBucket.getBucketId()); + } + } + } + + cachingTablePolicy.set(policy.getId(), policy); + + // Now, iterate through all APIs and Auth in this policy and update them + for (String apiId : policy.getApiIds()) { + Api api = getApiById(apiId); + if (api.getPolicyIds().indexOf(policy.getId()) < 0) + { + api.getPolicyIds().add(policy.getId()); + cachingTableApi.set(api.getId(), api); + } + } + + for (QuotaRLBucket bucket : policy.getAuthIds()) { + for(String authId : bucket.getAuthIds()) { + String authToken = cachingTableAuthIdToAuthToken.get(authId); + if (authToken == null) + throw new IllegalArgumentException("Auth ID [" + authId + "] not found"); + + Auth auth = cachingTableAuth.get(authToken); + if (auth == null) + throw new IllegalArgumentException("Auth token not found"); + + //Add policy: add a AuthContext object with PolicyId, LimitId, BucketId (instead of just PolicyId) => LimitId should be crossed with "policyContext" on Auth + + boolean found = false; + for (AuthIds authCtx : auth.getPolicyContexts()) { + if (authCtx.getPolicyId().equals(policy.getId())) { + //update Auth with good Policy context and bucket + authCtx.setPolicyContextId(getPolicyContextId(auth, policy)); + authCtx.setPolicyBucketId(bucket.getBucketId()); + cachingTableAuth.set(authToken, auth);//updating auth + found = true; + break; + } + } + + if (!found) { + AuthDetail detail = cachingTableAuthDetails.get(authToken); + auth.getPolicyContexts().add(new AuthIds(policy.getId(), bucket.getId(), getPolicyContextId(auth, policy), bucket.getBucketId(), (detail != null)?detail.getStatus()==StatusType.ACTIVE:false)); + cachingTableAuth.set(authToken, auth); + } + } + } + } + + @Override + public void removePolicy(String id) throws InvalidIDException { + + Policy policy = cachingTablePolicy.remove(id); + if (policy == null) + throw new InvalidIDException("A Policy with that ID [" + id + "] doesn't exist"); + + // Now, iterate through all APIs and Auth in this policy and update them + for (String apiId : policy.getApiIds()) { + Api api = getApiById(apiId); + if (api != null) { + api.getPolicyIds().remove(policy.getId()); + cachingTableApi.set(api.getId(), api); + } + } + + for (QuotaRLBucket bucket : policy.getAuthIds()) { + for(String authId : bucket.getAuthIds()) { + String authToken = cachingTableAuthIdToAuthToken.get(authId); + if (authToken == null) + continue; + + Auth auth = cachingTableAuth.get(authToken); + if (auth == null) + continue; + + for (AuthIds authCtx : auth.getPolicyContexts()) { + if (authCtx.getPolicyId().equals(policy.getId())) { + auth.getPolicyContexts().remove(authCtx); + break; + } + } + cachingTableAuth.set(authToken, auth); + } + usedBucketIds.remove(bucket.getBucketId()); + for (IDataManagerUsedBucketIdsListener listner : this.usedBucketIdslisteners) + { + listner.usedBucketIdsRemoved(bucket.getBucketId()); + } + } + + // Remove the contexts + for (Integer contextId : policy.getContextIds()) { + cachingTableContext.remove(contextId); + } + } + + @Override + public Policy getPolicyById(String id) { + return getPolicyById(id, true); + } + + @Override + public Policy getPolicyById(String id, boolean getFullDetails) throws InvalidIDException { + + Policy policy = cachingTablePolicy.get(id); + if (policy == null) + throw new InvalidIDException("A Policy with that ID [" + id + "] doesn't exist"); + + if (getFullDetails) { + // It's not because List is transient on Policy + // that it is not stored in hazelcast memory _locally_. + // For sure, it will not be replicated + policy.getContexts().clear(); + // We can't be sure here to reuse existing List + // it may be not up to date. + for (Integer contextId : policy.getContextIds()) { + policy.getContexts().add(cachingTableContext.get(contextId).getPolicyContext()); + } + } + + return policy; + } + + + @Override + public void createBucket(String policyId, QuotaRLBucket bucket) throws IllegalArgumentException { + + Policy policy = getPolicyById(policyId); + + if(getBucketWithIdForPolicy(policy, bucket.getId()) != null) { + throw new IllegalArgumentException("A Bucket with this ID already exists for this policy"); + } + + policy.getAuthIds().add(bucket); + cachingTablePolicy.set(policy.getId(), policy); + + checkIfAuthAlreadyInPolicy(policyId, bucket.getAuthIds(), bucket.getId()); + + for(String authId : bucket.getAuthIds()) { + String authToken = cachingTableAuthIdToAuthToken.get(authId); + if (authToken == null) + throw new IllegalArgumentException("Auth ID [" + authId + "] not found"); + + Auth auth = cachingTableAuth.get(authToken); + if (auth == null) + throw new IllegalArgumentException("Auth token not found"); + + // Add auth to policy + if (bucket.getAuthIds().indexOf(auth.getId()) < 0) { + bucket.getAuthIds().add(auth.getId()); + cachingTablePolicy.set(policy.getId(), policy); + } + + // Add policy to auth + boolean found = false; + for (AuthIds authCtx : auth.getPolicyContexts()) { + if (authCtx.getPolicyId().equals(policy.getId())) { + //update Auth with good Policy context and bucket + authCtx.setPolicyContextId(getPolicyContextId(auth, policy)); + authCtx.setPolicyBucketId(bucket.getBucketId()); + cachingTableAuth.set(authToken, auth);//updating auth + found = true; + break; + } + } + + if (!found) { + AuthDetail detail = cachingTableAuthDetails.get(authToken); + auth.getPolicyContexts().add(new AuthIds(policyId, bucket.getId(), getPolicyContextId(auth, policy), bucket.getBucketId(), (detail != null)?detail.getStatus()==StatusType.ACTIVE:false)); + cachingTableAuth.set(authToken, auth); + } + } + } + + private void checkIfAuthAlreadyInPolicy(String policyId, List authIds, String bucketId) + { + for(String authId : authIds) { + + String authToken = cachingTableAuthIdToAuthToken.get(authId); + if (authToken == null) + throw new IllegalArgumentException("Auth ID not found"); + + Auth auth = cachingTableAuth.get(authToken); + if (auth == null) + throw new IllegalArgumentException("Auth token not found"); + + boolean found = false; + for (AuthIds authCtx : auth.getPolicyContexts()) { + if (authCtx.getPolicyId().equals(policyId)) { + if(!authCtx.getBucketId().equals(bucketId)){ + // Auth should not exist in another bucket + found = true; + } + break; + } + } + + if (found) { + throw new IllegalArgumentException("Auth " + authId +" already used on this policy by another bucket"); + } + } + } + + @Override + public void addAuthsToBucket(String policyId, String bucketId, QuotaRLBucket bucket) throws IllegalArgumentException { + + Policy policy = getPolicyById(policyId); + + // Find the correct bucket in this policy + QuotaRLBucket pAuthIds = getBucketWithIdForPolicy(policy, bucketId); + if(pAuthIds == null) { + throw new IllegalArgumentException("A Bucket with that ID [" + bucketId + "] doesn't exist for this Policy [" + policyId + "]"); + } + + checkIfAuthAlreadyInPolicy(policyId, bucket.getAuthIds(), bucketId); + + for(String authId : bucket.getAuthIds()) { + + String authToken = cachingTableAuthIdToAuthToken.get(authId); + if (authToken == null) + throw new IllegalArgumentException("Auth ID [" + authId + "] not found"); + + Auth auth = cachingTableAuth.get(authToken); + if (auth == null) + throw new IllegalArgumentException("Auth token not found"); + + // Add auth to the bucket + if (pAuthIds.getAuthIds().indexOf(auth.getId()) < 0) + { + pAuthIds.getAuthIds().add(auth.getId()); + cachingTablePolicy.set(policy.getId(), policy); + } + + // Add policy to auth + boolean found = false; + for (AuthIds authCtx : auth.getPolicyContexts()) { + if (authCtx.getPolicyId().equals(policy.getId())) { + //update Auth with good Policy context and bucket + authCtx.setPolicyContextId(getPolicyContextId(auth, policy)); + authCtx.setPolicyBucketId(bucket.getBucketId()); + cachingTableAuth.set(authToken, auth);//updating auth + found = true; + break; + } + } + + if (!found) { + AuthDetail detail = cachingTableAuthDetails.get(authToken); + auth.getPolicyContexts().add(new AuthIds(policyId, bucketId, getPolicyContextId(auth, policy), pAuthIds.getBucketId(), (detail != null)?detail.getStatus()==StatusType.ACTIVE:false)); + cachingTableAuth.set(authToken, auth); + } + } + } + + @Override + public void addAuthsToBucket(List policyIds, String bucketId, QuotaRLBucket authIds) throws IllegalArgumentException { + //cacheManager.beginTransaction(); + + for(String policyId : policyIds){ + createBucket(policyId, authIds); + } + //cacheManager.endTransaction(); + + } + + @Override + public void appendAuthsToBucket(List policyIds, String bucketId, QuotaRLBucket authIds) throws IllegalArgumentException { + //cacheManager.beginTransaction(); + + for(String policyId : policyIds){ + addAuthsToBucket(policyId, bucketId, authIds); + } + //cacheManager.endTransaction(); + + } + + @Override + public void removeAuthFromBucket(String policyId, String bucketId, String authId) throws IllegalArgumentException { + + Policy policy = getPolicyById(policyId); + + String authToken = cachingTableAuthIdToAuthToken.get(authId); + if (authToken == null) + throw new InvalidIDException("An Authorization with that ID [" + authId + "] doesn't exist"); + + Auth auth = cachingTableAuth.get(authToken); + if (auth == null) + throw new InvalidIDException("An Authorization with that token doesn't exist"); + + QuotaRLBucket pAuthIds = getBucketWithIdForPolicy(policy, bucketId); + if(pAuthIds == null) { + throw new InvalidIDException("A Bucket with that ID [" + bucketId + "] doesn't exist for this Policy [" + policyId + "]"); + } + + // Remove auth from the bucket + pAuthIds.getAuthIds().remove(auth.getId()); + cachingTablePolicy.set(policy.getId(), policy); + + // Remove policy from auth + for (AuthIds authCtx : auth.getPolicyContexts()) { + if (authCtx.getPolicyId().equals(policy.getId())) { + auth.getPolicyContexts().remove(authCtx); + cachingTableAuth.set(authToken, auth); + break; + } + } + } + + @Override + public void removeAuthsFromBucket(List policyIds, String bucketId, List authIds) throws IllegalArgumentException { + for(String authId : authIds){ + for(String policyId : policyIds){ + removeAuthFromBucket(policyId, bucketId, authId); + } + } + } + + @Override + public void removeBucket(String policyId, String bucketId) throws IllegalArgumentException { + + Policy policy = getPolicyById(policyId); + + QuotaRLBucket pAuthIds = getBucketWithIdForPolicy(policy, bucketId); + if(pAuthIds == null) { + throw new InvalidIDException("A Bucket with that ID [" + bucketId + "] doesn't exist for this Policy [" + policyId + "]"); + } + + // Iterating over Auth Ids in the bucket to remove policy from the auth + for(String authId : pAuthIds.getAuthIds()) { + + String authToken = cachingTableAuthIdToAuthToken.get(authId); + if (authToken == null) + continue; + + Auth auth = cachingTableAuth.get(authToken); + if (auth == null) + continue; + + // Remove policy from auth + for (AuthIds authCtx : auth.getPolicyContexts()) { + if (authCtx.getPolicyId().equals(policy.getId())) { + auth.getPolicyContexts().remove(authCtx); + cachingTableAuth.set(authToken, auth); + break; + } + } + } + + policy.getAuthIds().remove(pAuthIds); + cachingTablePolicy.set(policy.getId(), policy); + } + + @Override + public void removeBucket(List policyIds, String bucketId) throws IllegalArgumentException { + //cacheManager.beginTransaction(); + + for(String policyId : policyIds){ + removeBucket(policyId, bucketId); + } + //cacheManager.endTransaction(); + + } + + /** + * Utility method that iterate over policy's buckets to find a bucket for a given bucketId. + * @param policy Policy to iterate on + * @param bucketId Id of the bucket to get + * @return The corresponding bucket (AuthIds object) + */ + private QuotaRLBucket getBucketWithIdForPolicy(Policy policy, String bucketId) { + QuotaRLBucket pAuthIds = null; + for(QuotaRLBucket cAuthIds : policy.getAuthIds()) { + if(cAuthIds.getId().equalsIgnoreCase(bucketId)) { + pAuthIds = cAuthIds; + break; + } + } + return pAuthIds; + } + + @Override + public List getMatchingPolicies(Api api) { + return getMatchingPolicies(api, null); + } + + @Override + public List getMatchingPolicies(Api api, Auth auth) { + + List result = null; + + // If no Auth, check if we have an API + if (auth == null) { + + // No Auth and no API ? What are we doing here ?! + if (api != null) { + + // No Auth, but an API: return all Policies with no Auth associated + // => API doesn't have any authentification method + for (String policyIdInApi : api.getPolicyIds()) { + + Policy policy = getPolicyById(policyIdInApi); + + // Add only if no auth in policy's buckets + boolean add = true; + for(QuotaRLBucket authIds : policy.getAuthIds()) { + if (!authIds.getAuthIds().isEmpty()) { + add = false; + } + } + if(add) { + if (result == null) + result = new ArrayList(); + result.add(new CallDescriptor(policy, -1, -1)); + } + } + + // Now, add the CallDescriptor of the "default" context + if (api.getContextIds().isEmpty() == false) { + if (result == null) + result = new ArrayList(); + + // Looking for default context, placed at index 0 by addApi + ApiIds ctx = api.getContextIds().get(0); + if (ctx.isStatusActive()) + result.add(new CallDescriptor(null, ctx.getApiContextId(), ctx.getApiBucketId())); + } + } + } else { + + // We have an Auth and an API, check matching policies + for (AuthIds authCtx : auth.getPolicyContexts()) { + + String policyIdInAuth = authCtx.getPolicyId(); + + boolean policyAdded = false; + + // API may be null if Auth is for "Company" + if (api != null) { + for (String policyIdInApi : api.getPolicyIds()) { + + // Matching means that the policy is in Auth and API + if (policyIdInApi.equals(policyIdInAuth)) { + Policy policy = getPolicyById(policyIdInAuth); + if (result == null) + result = new ArrayList(); + if (authCtx.isStatusActive()) + result.add(new CallDescriptor(policy, authCtx.getPolicyContextId(), authCtx.getPolicyBucketId())); + policyAdded = true; + } + } + } + + // If the policy wasn't added... + if (!policyAdded) { + // Slow, but need to check if that policy has some API attached + Policy policy = getPolicyById(policyIdInAuth, false); + if ((policy.getApiIds() == null) || policy.getApiIds().isEmpty()) { + if (result == null) + result = new ArrayList(); + if (authCtx.isStatusActive()) + result.add(new CallDescriptor(policy, authCtx.getPolicyContextId(), authCtx.getPolicyBucketId())); + } + } + } + + // Now check the apiContext on the auth which is in the list of API + if (api != null) { + for (ApiIds ctx : api.getContextIds()) { + if (ctx.getApiContextName().equals(auth.getApiContext())) { + if (result == null) + result = new ArrayList(); + if (ctx.isStatusActive()) + result.add(new CallDescriptor(null, ctx.getApiContextId(), ctx.getApiBucketId())); + } + } + } + } + + return result; + } + + @Override + public APIContext getApiContextById(Integer id) { + + ContextWrapper ctx = cachingTableContext.get(id); + + if (ctx == null) + throw new IllegalArgumentException("There is no Context available with that ID"); + + return ctx.getApiContext(); + } + + @Override + public Context getPolicyContextById(Integer id) { + + ContextWrapper ctx = cachingTableContext.get(id); + + if (ctx == null) + throw new IllegalArgumentException("There is no Context available with that ID"); + + return ctx.getPolicyContext(); + } + + @Override + public void fillLimitsById(Integer contextId, Limit limit) { + + if (limit == null) + throw new IllegalArgumentException("Limit must not be null"); + + ContextWrapper ctx = cachingTableContext.get(contextId); + + if (ctx == null) + throw new IllegalArgumentException("There is no limit available with that ID"); + + if (ctx.getApiContext() != null) { + // It's an API Context + limit.setQuotaPerDay(null); + limit.setQuotaPerWeek(null); + limit.setQuotaPerMonth(null); + limit.setRateLimitPerMinute(new Counter(ctx.getApiContext().getMaxRateLimitTPMWarning(), ctx.getApiContext().getMaxRateLimitTPMThreshold())); + limit.setRateLimitPerSecond(new Counter(ctx.getApiContext().getMaxRateLimitTPSWarning(), ctx.getApiContext().getMaxRateLimitTPSThreshold())); + } + + if (ctx.getPolicyContext() != null) { + // It's a Policy Context + limit.setQuotaPerDay(ctx.getPolicyContext().getQuotaPerDay()); + limit.setQuotaPerWeek(ctx.getPolicyContext().getQuotaPerWeek()); + limit.setQuotaPerMonth(ctx.getPolicyContext().getQuotaPerMonth()); + limit.setRateLimitPerMinute(ctx.getPolicyContext().getRateLimitPerMinute()); + limit.setRateLimitPerSecond(ctx.getPolicyContext().getRateLimitPerSecond()); + limit.setCreatedDate(ctx.getPolicyContext().getCreatedDate()); + } + } + + @Override + public void putSettingString(String key, String value) { + cachingTableSettings.set(key, value); + } + + @Override + public void clearSettingString(String key) { + cachingTableSettings.remove(key); + } + + @Override + public String getSettingString(String key) { + return cachingTableSettings.get(key); + } + + @Override + public void addKey(Key key){ + if (cachingTableKey.containsKey(key.getId())) + throw new IllegalArgumentException("Key already exists with that ID [" + key.getId() + "]"); + + if( key.getData() == null || key.getData().isEmpty() ) + throw new IllegalArgumentException("New Keys must have key data"); + + cachingTableKeyDetails.set(key.getId(), key.getKeyDetail()); + + cachingTableKey.set(key.getId(), key); + + } + + @Override + public Set getAllKeyIds() { + return cachingTableKey.getAllKeys(); + } + + @Override + public Key getKeyById(String id) { + return getKeyById(id, false); + } + + @Override + public Key getKeyById(String id, boolean getFullDetails) throws InvalidIDException { + + if( ! cachingTableKey.containsKey(id)) + throw new InvalidIDException("A Key with that ID [" + id + "] doesn't exist"); + + Key key = cachingTableKey.get(id); + + if (getFullDetails) + key.setKeyDetail(cachingTableKeyDetails.get(id)); + else + key.setKeyDetail(null); + + return key; + } + + @Override + public void updateKey(Key key) throws InvalidIDException { + + if( ! cachingTableKey.containsKey(key.getId())) + throw new InvalidIDException("A Key with that ID [" + key.getId() + "] doesn't exist"); + + if( key.getData() != null && !key.getData().isEmpty() ) + throw new IllegalArgumentException("Key data cannot be changed with an update"); + + Key knownKey = getKeyById(key.getId(), true); + KeyDetail knownKeyDetail = knownKey.getKeyDetail(); + + if(key.getActiveCertId() != null){ + knownKey.setActiveCertId(key.getActiveCertId()); + } + + knownKey.setKeyPassphrase(key.getKeyPassphrase()); + + if(key.getKeyDetail().getName() != null){ + knownKeyDetail.setName(key.getKeyDetail().getName()); + } + + boolean success = cachingTableKey.set(key.getId(), knownKey); + + if (!success) { + throw new IllegalArgumentException("Error while updating the key"); + } + + cachingTableKeyDetails.set(key.getId(), knownKeyDetail); + } + + @Override + public void removeKey(String id) throws InvalidIDException { + + if( ! cachingTableKey.containsKey(id)) + throw new InvalidIDException("A Key with that ID [" + id + "] doesn't exist"); + + ClassLoader previousClassLoader = Thread.currentThread().getContextClassLoader(); + Thread.currentThread().setContextClassLoader(DataManager.class.getClassLoader()); + + // Remove all certificates for this key + for(CertificateDetail cd : cachingTableCertificateDetails.getAllValues()){ + if(cd.getKeyId().equals(id)){ + cachingTableCertificate.remove(cd.getId()); + cachingTableCertificateDetails.remove(cd.getId()); + } + } + + Thread.currentThread().setContextClassLoader(previousClassLoader); + + // Remove the key + cachingTableKey.remove(id); + cachingTableKeyDetails.remove(id); + } + + @Override + public void addCert(Certificate cert){ + if(cachingTableCertificate.containsKey(cert.getId())) + throw new IllegalArgumentException("Cert already exists with that ID [" + cert.getId() + "]"); + + if( cert.getData() == null || cert.getData().isEmpty() ) + throw new IllegalArgumentException("New Certificates must have data"); + + // Invalid key + if( !cachingTableKey.containsKey(cert.getCertDetail().getKeyId())){ + throw new IllegalArgumentException("The Key with that ID [" + cert.getCertDetail().getKeyId() + "] does not exist"); + } + + cachingTableCertificateDetails.set(cert.getId(), cert.getCertDetail()); + cachingTableCertificate.set(cert.getId(), cert); + } + + @Override + public Set getAllCertIds(){ + return cachingTableCertificate.getAllKeys(); + } + + @Override + public Set getAllCertIdsForKeyId(String keyId){ + + ClassLoader previousClassLoader = Thread.currentThread().getContextClassLoader(); + Thread.currentThread().setContextClassLoader(DataManager.class.getClassLoader()); + + Set result = new HashSet(); + for(CertificateDetail cd : cachingTableCertificateDetails.getAllValues()){ + if(cd.getKeyId().equals(keyId)){ + result.add(cd.getId()); + } + } + + Thread.currentThread().setContextClassLoader(previousClassLoader); + + return result; + } + + @Override + public Certificate getCertById(String id){ + return getCertById(id, false); + } + + @Override + public Certificate getCertById(String id, boolean getFullDetails) throws InvalidIDException { + if(!cachingTableCertificate.containsKey(id)) + throw new InvalidIDException("A Certificate with that ID [" + id + "] doesn't exist"); + Certificate cert = cachingTableCertificate.get(id); + + if(getFullDetails) + cert.setCertDetail(cachingTableCertificateDetails.get(id)); + else + cert.setCertDetail(null); + + return cert; + } + + @Override + public void updateCert(Certificate cert) throws InvalidIDException { + if( ! cachingTableCertificate.containsKey(cert.getId())) + throw new InvalidIDException("A Certificate with that ID [" + cert.getId() + "] doesn't exist"); + + if( cert.getData() != null && !cert.getData().isEmpty() ) + throw new IllegalArgumentException("Certificate data cannot be changed with an update"); + + + Certificate knownCert = getCertById(cert.getId(), true); + CertificateDetail knownCertDetail = knownCert.getCertDetail(); + + if(cert.getCertDetail().getName() != null){ + knownCertDetail.setName(cert.getCertDetail().getName()); + } + + if(cert.getCertDetail().getKeyId() != null){ + if( !cachingTableKey.containsKey(cert.getCertDetail().getKeyId())){ + throw new IllegalArgumentException("The Key with that ID [" + cert.getCertDetail().getKeyId() + "] does not exist"); + } + knownCertDetail.setKeyId(cert.getCertDetail().getKeyId()); + } + + cachingTableCertificate.set(cert.getId(), knownCert); + cachingTableCertificateDetails.set(cert.getId(), knownCertDetail); + } + + @Override + public void removeCert(String id) throws InvalidIDException { + if( ! cachingTableCertificate.containsKey(id)) + throw new InvalidIDException("A Certificate with that ID [" + id + "] doesn't exist"); + + // If the cert is active, disallow removal + if( cachingTableKey.get(cachingTableCertificateDetails.get(id).getKeyId()).getActiveCertId().equals(id)) + throw new IllegalArgumentException("Cannot remove active certificate"); + + cachingTableCertificate.remove(id); + cachingTableCertificateDetails.remove(id); + } + + /** + * Generate a new Key with BouncyCastle + */ + @Override + public Key generateKey(String id) { + //TODO implement bouncycastle key generation + return null; + } + + /** + * Generate a CSR with bouncycastle + */ + @Override + public CertificateRequest getCSR(String keyId){ + //TODO: implement bouncycastle csr generation + return null; + } + + /** + * Self-Sign a key with bouncycastle + */ + @Override + public Certificate selfSignKey(String keyId, CertificateRequest csr){ + //TODO: implement bouncycastle self-signing + return null; + } + + @Override + public void addKeyListener(IEntryListener listener) { + cachingTableKey.addEntryListener(listener); + } + + @Override + public void removeKeyListener(IEntryListener listener) { + cachingTableKey.removeEntryListener(listener); + } + + public void setCachedLogLevel(String key, LogLevel level) { + cachingTableLogLevel.set(key, level); + } + + public void clearCachedLogLevel(String key) { + cachingTableLogLevel.remove(key); + } + + public LogLevel getCachedLogLevel(String key) { + return cachingTableLogLevel.get(key); + } + + @Override + public void addLogLevelListener(IEntryListener listener) { + cachingTableLogLevel.addEntryListener(listener); + } + + @Override + public void removeLogLevelListener(IEntryListener listener) { + cachingTableLogLevel.removeEntryListener(listener); + } + + public void setCachedLoggingCategory(Category category, boolean enabled) { + // Use log4j level OFF to indicated disabled category, ALL for enabled + Level level = enabled ? Level.ALL : Level.OFF; + cachingTableLogLevel.set(category.toString(), new LogLevel(level)); + } + + public void clearCachedLoggingCategory(Category category) { + cachingTableLogLevel.remove(category.toString()); + } + + public boolean getCachedLoggingCategory(Category category) { + LogLevel level = cachingTableLogLevel.get(category.toString()); + if ((level != null) && level.equals(Level.OFF)) { + return false; + } + return true; + } + + + //---------------------------------------------------------------- + // *** Route deployment *** + // + // Gateways are listening on cachingTableApiJars map to be + // notified of bundle updates through cache mechanism + //---------------------------------------------------------------- + @Override + public boolean deployApi(String apiId, byte[] jarData) { + ApiJar data = new ApiJar(); + data.setId(UUID.randomUUID().toString()); + data.setData(jarData); + boolean result = cachingTableApiJars.set(apiId, data); + return result; + } + + @Override + public ApiJar getApiJar(String apiId) { + return cachingTableApiJars.get(apiId); + } + + @Override + public boolean undeployApi(String apiId) { + ApiJar undeployed = cachingTableApiJars.remove(apiId); + return undeployed != null; + } + + @Override + public void addApiDeploymentListener(IEntryListener listener) { + cachingTableApiJars.addEntryListener(listener); + } + + @Override + public void removeApiDeploymentListener(IEntryListener listener) { + cachingTableApiJars.removeEntryListener(listener); + } + + @Override + public synchronized void postAcknowledgment(String localQueueName, CacheAck ack) throws InterruptedException { + ICacheQueue localQueue = cacheManager.getOrCreateQueue(localQueueName, null); + localQueue.post(ack); + } + + @Override + public void instanceAdded(InstanceEvent event) { + if (!isManager()) return; + + if (E3Constant.DATA_STORAGE.equals(event.getType())) { + // on the manager, we need replication and data store + // Trying to create them all + // if condition are met + createDataStoreTables(); + } + } + + @Override + public void instanceRemoved(InstanceEvent event) { + // Nothing to do about data management on instance removed. + } + + @Override + public void setLogLevel(LogLevel level) { + this.setCachedLogLevel(LogLevel.logLevelKey, level); + } + + @Override + public LogLevel getLogLevel() { + return this.getCachedLogLevel(LogLevel.logLevelKey); + } + + @Override + public void setSMXLogLevel(LogLevel level) { + this.setCachedLogLevel(LogLevel.smxlogLevelKey, level); + } + + @Override + public LogLevel getSMXLogLevel() { + return this.getCachedLogLevel(LogLevel.smxlogLevelKey); + } + + @Override + public void setSyslogLevel(LogLevel level) { + this.setCachedLogLevel(LogLevel.syslogLevelKey, level); + } + + @Override + public LogLevel getSyslogLevel() { + return this.getCachedLogLevel(LogLevel.syslogLevelKey); + } + + @Override + public void setLoggingCategory(Category category, boolean enabled) { + this.setCachedLoggingCategory(category, enabled); + } + + @Override + public boolean getLoggingCategory(Category category) { + Boolean enabled = this.getCachedLoggingCategory(category); + return enabled != null ? enabled.booleanValue() : true; + } + + public class RunnableProvisionGateway implements Runnable { + + protected String ip; + + public RunnableProvisionGateway(String ip) { + super(); + this.ip = ip; + } + + @Override + public void run() { + logger.info("Running ProvisionGateway(ip:{}) ...", ip); + RemoteInstanceInfo.setGatewayStatus(ip, GatewayStatus.PROVISIONING); + + logger.debug("Loading CA/CRL for ip:{} ...", ip); + cachingTableCA.reloadSlave(ip); + cachingTableCRL.reloadSlave(ip); + + logger.debug("Loading ApiDetails for ip:{} ...", ip); + cachingTableApiDetails.reloadSlave(ip); + + logger.debug("Loading AuthDetails for ip:{} ...", ip); + cachingTableAuthDetails.reloadSlave(ip); + + logger.debug("Loading AuthIdToAuthToken for ip:{} ...", ip); + cachingTableAuthIdToAuthToken.reloadSlave(ip); + + logger.debug("Loading Auth for ip:{} ...", ip); + cachingTableAuth.reloadSlave(ip); + + logger.debug("Loading AuthIpAddress for ip:{} ...", ip); + cachingTableAuthIpAddress.reloadSlave(ip); + + logger.debug("Loading Policy for ip:{} ...", ip); + cachingTablePolicy.reloadSlave(ip); + + logger.debug("Loading Context for ip:{} ...", ip); + cachingTableContext.reloadSlave(ip); + + logger.debug("Loading Api for ip:{} ...", ip); + cachingTableApi.reloadSlave(ip); + + logger.debug("Loading Settings for ip:{} ...", ip); + cachingTableSettings.reloadSlave(ip); + + // All the routes were previously removed from the gateway + for (ApiJar apiJar: cachingTableApiJars.getAllValues()) { + logger.debug("Deploying api:{} for ip:{} ...", apiJar.getId(), ip); + reDeployApi(ip, apiJar); + } + + // Notify the gateway that its tables were all provisioned + RemoteInstanceInfo.setGatewayStatus(ip, GatewayStatus.PROVISIONED); + logger.info("ProvisionGateway(ip:{}) done.", ip); + } + + protected boolean reDeployApi(String gatewayIP, ApiJar apiJar) { + + if (apiJar == null) { + logger.warn("deploying a jar - parameter apiJar is null"); + return false; + } + + return cachingTableApiJars.set(apiJar.getId(), apiJar, gatewayIP); + } + + } + + @Override + public Set getAllCA() { + return cachingTableCA.getAllKeys(); + } + + @Override + public void addCA(Certificate cert) { + if(cachingTableCA.containsKey(cert.getId())) + throw new IllegalArgumentException("CA already exists with that ID [" + cert.getId() + "]"); + + if( cert.getData() == null || cert.getData().isEmpty() ) + throw new IllegalArgumentException("New CA must have data"); + + cachingTableCADetails.set(cert.getId(), cert.getCertDetail()); + cachingTableCA.set(cert.getId(), cert); + } + + @Override + public Certificate getCAById(String id) throws InvalidIDException { + if(!cachingTableCA.containsKey(id)) + throw new InvalidIDException("A CA with that ID [" + id + "] doesn't exist"); + Certificate cert = cachingTableCA.get(id); + cert.setCertDetail(cachingTableCADetails.get(id)); + + return cert; + } + + @Override + public void updateCA(Certificate cert) throws InvalidIDException { + if( ! cachingTableCA.containsKey(cert.getId())) + throw new InvalidIDException("A CA with that ID [" + cert.getId() + "] doesn't exist"); + + if( cert.getData() != null && !cert.getData().isEmpty() ) + throw new IllegalArgumentException("CA data cannot be changed with an update"); + + + Certificate knownCert = getCAById(cert.getId()); + CertificateDetail knownCertDetail = knownCert.getCertDetail(); + + if(cert.getCertDetail().getName() != null){ + knownCertDetail.setName(cert.getCertDetail().getName()); + } + + cachingTableCA.set(cert.getId(), knownCert); + cachingTableCADetails.set(cert.getId(), knownCertDetail); + } + + @Override + public void removeCA(String id) throws InvalidIDException { + if( ! cachingTableCA.containsKey(id)) + throw new InvalidIDException("A CA with that ID [" + id + "] doesn't exist"); + + cachingTableCA.remove(id); + cachingTableCADetails.remove(id); + } + + @Override + public void addCAListener(IEntryListener listener) { + cachingTableCA.addEntryListener(listener); + } + + @Override + public void removeCAListener(IEntryListener listener) { + cachingTableCA.removeEntryListener(listener); + } + + @Override + public void addCRL(SSLCRL clr) { + if(cachingTableCRL.containsKey(clr.getId())) + throw new IllegalArgumentException("CRL already exists with that ID [" + clr.getId() + "]"); + + if( clr.getContent() == null || clr.getContent().length() == 0) + throw new IllegalArgumentException("New CRL must have data"); + + cachingTableCRL.set(clr.getId(), clr); + } + + @Override + public SSLCRL getCRLById(String id) throws InvalidIDException { + if(!cachingTableCRL.containsKey(id)) + throw new InvalidIDException("A CRL with that ID [" + id + "] doesn't exist"); + SSLCRL crl = cachingTableCRL.get(id); + + return crl; + } + + @Override + public void updateCRL(SSLCRL crl) throws InvalidIDException { + SSLCRL knownCRL = getCRLById(crl.getId()); + + if( crl.getContent() != null && crl.getContent().length() > 0) + throw new IllegalArgumentException("CRL data cannot be changed with an update"); + + if(crl.getDisplayName() != null){ + knownCRL.setDisplayName(crl.getDisplayName()); + } + + cachingTableCRL.set(crl.getId(), knownCRL); + } + + @Override + public void removeCRL(String id) throws InvalidIDException { + if( ! cachingTableCRL.containsKey(id)) + throw new InvalidIDException("A CRL with that ID [" + id + "] doesn't exist"); + + cachingTableCRL.remove(id); + } + + @Override + public Collection getAllCRLValues() { + return cachingTableCRL.getAllValues(); + } + + @Override + public Set getAllCRL() { + return cachingTableCRL.getAllKeys(); + } + + @Override + public void addCrlListener(IEntryListener listener) { + cachingTableCRL.addEntryListener(listener); + } + + @Override + public void removeCrlListener(IEntryListener listener) { + cachingTableCRL.removeEntryListener(listener); + } + + + /** + * Public Setters + */ + + @SuppressWarnings("unchecked") + public void setCachingTableApiDetails(ICacheTable iCacheTable) { + if (iCacheTable == null) + throw new RuntimeException("Error: table cachingTableApiDetails already created."); + cachingTableApiDetails = (ICacheTable) iCacheTable; + } + + @SuppressWarnings("unchecked") + public void setCachingTableAuthDetails(ICacheTable iCacheTable) { + if (iCacheTable == null) + throw new RuntimeException("Error: table cachingTableAuthDetails already created."); + this.cachingTableAuthDetails = (ICacheTable) iCacheTable; + } + + @SuppressWarnings("unchecked") + public void setCachingTableAuthIdToAuthToken(ICacheTable iCacheTable) { + if (iCacheTable == null) + throw new RuntimeException("Error: table cachingTableAuthIdToAuthToken already created."); + this.cachingTableAuthIdToAuthToken = (ICacheTable) iCacheTable; + } + + @SuppressWarnings("unchecked") + public void setCachingTableKeyDetails(ICacheTable iCacheTable) { + if (iCacheTable == null) + throw new RuntimeException("Error: table cachingTableKeyDetails already created."); + this.cachingTableKeyDetails = (ICacheTable) iCacheTable; + } + + @SuppressWarnings("unchecked") + public void setCachingTableCertificateDetails(ICacheTable iCacheTable) { + if (iCacheTable == null) + throw new RuntimeException("Error: table cachingTableCertificateDetails already created."); + this.cachingTableCertificateDetails = (ICacheTable) iCacheTable; + } + + @SuppressWarnings("unchecked") + public void setCachingTableCADetails(ICacheTable iCacheTable) { + if (iCacheTable == null) + throw new RuntimeException("Error: table cachingTableCADetails already created."); + this.cachingTableCADetails = (ICacheTable) iCacheTable; + } + + @SuppressWarnings("unchecked") + public void setCachingTableApi(ICacheTable iCacheTable) { + if (iCacheTable == null) + throw new RuntimeException("Error: table cachingTableApi already created."); + this.cachingTableApi = (ICacheTable) iCacheTable; + } + + @SuppressWarnings("unchecked") + public void setCachingTableAuth(ICacheTable iCacheTable) { + if (iCacheTable == null) + throw new RuntimeException("Error: table cachingTableAuth already created."); + this.cachingTableAuth = (ICacheTable) iCacheTable; + } + + @SuppressWarnings("unchecked") + public void setCachingTableAuthIpAddress(ICacheTable iCacheTable) { + if (iCacheTable == null) + throw new RuntimeException("Error: table cachingTableAuthIpAddress already created."); + this.cachingTableAuthIpAddress = (ICacheTable) iCacheTable; + } + + @SuppressWarnings("unchecked") + public void setCachingTablePolicy(ICacheTable iCacheTable) { + if (iCacheTable == null) + throw new RuntimeException("Error: table cachingTablePolicy already created."); + this.cachingTablePolicy = (ICacheTable) iCacheTable; + } + + @SuppressWarnings("unchecked") + public void setCachingTableContext(ICacheTable iCacheTable) { + if (iCacheTable == null) + throw new RuntimeException("Error: table cachingTableContext already created."); + this.cachingTableContext = (ICacheTable) iCacheTable; + } + + @SuppressWarnings("unchecked") + public void setCachingTableSettings(ICacheTable iCacheTable) { + if (iCacheTable == null) + throw new RuntimeException("Error: table cachingTableSettings already created."); + this.cachingTableSettings = (ICacheTable) iCacheTable; + } + + @SuppressWarnings("unchecked") + public void setCachingTableKey(ICacheTable iCacheTable) { + if (iCacheTable == null) + throw new RuntimeException("Error: table cachingTableKey already created."); + this.cachingTableKey = (ICacheTable) iCacheTable; + } + + @SuppressWarnings("unchecked") + public void setCachingTableCertificate(ICacheTable iCacheTable) { + if (iCacheTable == null) + throw new RuntimeException("Error: table cachingTableCertificate already created."); + this.cachingTableCertificate = (ICacheTable) iCacheTable; + } + + @SuppressWarnings("unchecked") + public void setCachingTableLogLevel(ICacheTable iCacheTable) { + if (iCacheTable == null) + throw new RuntimeException("Error: table cachingTableLogLevel already created."); + this.cachingTableLogLevel = (ICacheTable) iCacheTable; + } + + @SuppressWarnings("unchecked") + public void setCachingTableCA(ICacheTable iCacheTable) { + if (iCacheTable == null) + throw new RuntimeException("Error: table cachingTableCA already created."); + this.cachingTableCA = (ICacheTable) iCacheTable; + } + + @SuppressWarnings("unchecked") + public void setCachingTableCRL(ICacheTable iCacheTable) { + if (iCacheTable == null) + throw new RuntimeException("Error: table cachingTableCRL already created."); + this.cachingTableCRL = (ICacheTable) iCacheTable; + } + + @SuppressWarnings("unchecked") + public void setCachingTableApiJars(ICacheTable iCacheTable) { + if (iCacheTable == null) + throw new RuntimeException("Error: table cachingTableApiJars already created."); + this.cachingTableApiJars = (ICacheTable) iCacheTable; + } + + public void setListeners(Set listeners) { + this.listeners = listeners; + } + + public void setUsedBucketIds(Set usedBucketIds) { + this.usedBucketIds = usedBucketIds; + } + + + @Override + public void addApiListener(IEntryListener listener) { + this.cachingTableApi.addEntryListener(listener); + } + + @Override + public void removeApiListener(IEntryListener listener) { + this.cachingTableApi.removeEntryListener(listener); + } + + /* private class that stubs a CacheTable to forbid its uses if not initialized. */ + private class SanityCheckCacheTable implements ICacheTable { + + // Stubs + @Override + public boolean containsKey(K key) { throwNullTableException(); return false; } + @Override + public boolean set(K key, V value, String instanceIP) { throwNullTableException(); return false; } + @Override + public boolean set(K key, V value) { throwNullTableException(); return false; } + @Override + public V get(K key) { throwNullTableException(); return null; } + @Override + public V remove(K key) { throwNullTableException(); return null; } + @Override + public String getName() { throwNullTableException(); return null; } + @Override + public Set getAllKeys() { throwNullTableException(); return null; } + @Override + public Collection getAllValues() { throwNullTableException(); return null; } + @Override + public void clear() { throwNullTableException(); } + @Override + public void lock(K key) { throwNullTableException(); } + @Override + public void unlock(K key) { throwNullTableException(); } + @Override + public void addEntryListener(IEntryListener listener) { throwNullTableException(); } + @Override + public void removeEntryListener(IEntryListener listener) { throwNullTableException(); } + @Override + public void reloadSlave(String ip) { throwNullTableException(); } + + // constructor + public SanityCheckCacheTable(String tableName) { + this.tableName = tableName; + } + + // throw exception because table is not initalized + private String tableName; + private void throwNullTableException() + { + throw new NullHazelcastTableException("Hazelcast table:" + tableName + " hasn't been intialized. DataManager is not ready yet."); + } + } +} + + diff --git a/exposure-engine/common/src/main/java/com/alu/e3/data/IAuthMatcher.java b/exposure-engine/common/src/main/java/com/alu/e3/data/IAuthMatcher.java new file mode 100644 index 0000000..63cf28a --- /dev/null +++ b/exposure-engine/common/src/main/java/com/alu/e3/data/IAuthMatcher.java @@ -0,0 +1,27 @@ +/** + * Copyright © 2012 Alcatel-Lucent. + * + * See the NOTICE file distributed with this work for additional + * information regarding copyright ownership. + * Licensed to you 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 com.alu.e3.data; + +import com.alu.e3.data.model.Auth; + +public interface IAuthMatcher { + + public boolean isAuth(Auth auth); + +} diff --git a/exposure-engine/common/src/main/java/com/alu/e3/data/IDataManagerListener.java b/exposure-engine/common/src/main/java/com/alu/e3/data/IDataManagerListener.java new file mode 100644 index 0000000..8f9e0ef --- /dev/null +++ b/exposure-engine/common/src/main/java/com/alu/e3/data/IDataManagerListener.java @@ -0,0 +1,28 @@ +/** + * Copyright © 2012 Alcatel-Lucent. + * + * See the NOTICE file distributed with this work for additional + * information regarding copyright ownership. + * Licensed to you 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 com.alu.e3.data; + +public interface IDataManagerListener { + + void dataManagerReady(); + +} diff --git a/exposure-engine/common/src/main/java/com/alu/e3/data/IDataManagerUsedBucketIdsListener.java b/exposure-engine/common/src/main/java/com/alu/e3/data/IDataManagerUsedBucketIdsListener.java new file mode 100644 index 0000000..8274905 --- /dev/null +++ b/exposure-engine/common/src/main/java/com/alu/e3/data/IDataManagerUsedBucketIdsListener.java @@ -0,0 +1,28 @@ +/** + * Copyright © 2012 Alcatel-Lucent. + * + * See the NOTICE file distributed with this work for additional + * information regarding copyright ownership. + * Licensed to you 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 com.alu.e3.data; + +public interface IDataManagerUsedBucketIdsListener { + + void usedBucketIdsRemoved(Integer id); + +} diff --git a/exposure-engine/common/src/main/java/com/alu/e3/data/IHealthCheckService.java b/exposure-engine/common/src/main/java/com/alu/e3/data/IHealthCheckService.java new file mode 100644 index 0000000..3df781d --- /dev/null +++ b/exposure-engine/common/src/main/java/com/alu/e3/data/IHealthCheckService.java @@ -0,0 +1,26 @@ +/** + * Copyright © 2012 Alcatel-Lucent. + * + * See the NOTICE file distributed with this work for additional + * information regarding copyright ownership. + * Licensed to you 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 com.alu.e3.data; + +public interface IHealthCheckService { + + void start(); + void stop(); + boolean check(String ip); +} diff --git a/exposure-engine/common/src/main/java/com/alu/e3/data/TopologyClient.java b/exposure-engine/common/src/main/java/com/alu/e3/data/TopologyClient.java new file mode 100644 index 0000000..5b6a289 --- /dev/null +++ b/exposure-engine/common/src/main/java/com/alu/e3/data/TopologyClient.java @@ -0,0 +1,473 @@ +/** + * Copyright © 2012 Alcatel-Lucent. + * + * See the NOTICE file distributed with this work for additional + * information regarding copyright ownership. + * Licensed to you 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 com.alu.e3.data; + +import java.net.InetAddress; +import java.net.NetworkInterface; +import java.net.SocketException; +import java.net.UnknownHostException; +import java.util.ArrayList; +import java.util.Collections; +import java.util.Enumeration; +import java.util.HashMap; +import java.util.HashSet; +import java.util.Iterator; +import java.util.LinkedList; +import java.util.List; +import java.util.Map; +import java.util.Set; + +import org.slf4j.Logger; +import org.slf4j.LoggerFactory; + +import com.alu.e3.common.caching.ICacheManager; +import com.alu.e3.common.caching.ICacheTable; +import com.alu.e3.common.caching.IEntryListener; +import com.alu.e3.common.osgi.api.ITopologyClient; +import com.alu.e3.common.tools.CanonicalizedIpAddress; +import com.alu.e3.common.tools.CommonTools; +import com.alu.e3.data.model.Instance; +import com.alu.e3.data.topology.IInstanceListener; +import com.alu.e3.data.topology.InstanceEvent; + +/** + * Class to access/set topology information in cache + */ +public class TopologyClient implements ITopologyClient { + + private static final Logger logger = LoggerFactory.getLogger(TopologyClient.class); + + private ICacheTable> cachingTableTopology; + + /* area of this instance. */ + private String currentArea; + private Set currentAreaList; + + private ICacheManager cacheManager; + + private Map whoIAm = new HashMap(); + + public TopologyClient() {} + + /** + * Set the cache manager + */ + public void setCacheManager(ICacheManager cacheManager) { + logger.debug("Set ICacheManager on TopologyClient"); + this.cacheManager = cacheManager; + } + + public void init() { + logger.debug("TopologyClient initialization"); + cachingTableTopology = cacheManager.createTable("cachingTableTopology", true, null); + } + + /** + * Add an instance + */ + public void addInstance(Instance inst) { + logger.debug("Adding instance: {}", inst); + + if (inst == null || inst.getType().isEmpty() || inst.getInternalIP().isEmpty()) + throw new IllegalArgumentException("Invalid type or ip"); + + ArrayList list = cachingTableTopology.get(inst.getType()); + if (list == null) + { + logger.debug("Creating cachingTableTopology element for type: {}", inst.getType()); + cachingTableTopology.set(inst.getType(), new ArrayList()); + list = cachingTableTopology.get(inst.getType()); + } + + for (Instance i : list) + { + if ( i.getName().equals(inst.getName()) ) + { + deleteInstance(i); + break; + } + } + + list.add(inst); + cachingTableTopology.set(inst.getType(), list); + + fireInstanceAdded(new InstanceEvent(inst)); + + // This is to clean the current cache + synchronized (this) { + currentAreaList = null; + } + + logger.debug("Instance added: {}", inst); + } + + /** + * Deletes an instance + */ + public boolean deleteInstance(Instance inst) { + ArrayList list = cachingTableTopology.get(inst.getType()); + if (list == null) + return false; + + Iterator itr = list.iterator(); + while (itr.hasNext()) { + if (itr.next().getName().equals(inst.getName())) { + itr.remove(); + cachingTableTopology.set(inst.getType(), list); + fireInstanceRemoved(new InstanceEvent(inst)); + ArrayList list22 = cachingTableTopology.get(inst.getType()); + // This is to clean the current cache + currentAreaList = null; + + return true; + } + } + return false; + } + + /** + * Get all instances info of a type. + */ + @Override + public List getAllInstancesOfType(String type) { + + if (type == null) + throw new IllegalArgumentException("Invalid type"); + + return cachingTableTopology.get(type); + } + + /** + * Get all instances info of a type. + */ + @Override + public Set getAllInternalIPsOfType(String type) { + + return this.getInternalIPsOfType(type, null); + } + + /** + * Get all instances info of a type in a given area + */ + @Override + public Set getInternalIPsOfType(String type, String area) { + + if (type == null) + throw new IllegalArgumentException("Invalid type"); + + Set set = new HashSet(); + + ArrayList list = cachingTableTopology.get(type); + if (list != null) + { + /* copy now the array to avoid concurency problems. */ + Instance[] tabInstances = new Instance[0]; + tabInstances = list.toArray(tabInstances); + + for (int i = 0; i < tabInstances.length; i++) { + Instance inst = tabInstances[i]; + + if (area == null || area.equals(inst.getArea())) + set.add(inst.getInternalIP()); + } + } + + return set; + } + + /** + * Get all instances info of a type. + */ + @Override + public Set getAllExternalIPsOfType(String type) { + + return this.getExternalIPsOfType(type, null); + } + + /** + * Get all instances info of a type in a given area + */ + @Override + public Set getExternalIPsOfType(String type, String area) { + + if (type == null) + throw new IllegalArgumentException("Invalid type"); + + Set set = new HashSet(); + + ArrayList list = cachingTableTopology.get(type); + if (list != null) + { + /* copy now the array to avoid concurency problems. */ + Instance[] tabInstances = new Instance[0]; + tabInstances = list.toArray(tabInstances); + + for (int i = 0; i < tabInstances.length; i++) { + Instance inst = tabInstances[i]; + + if (area == null || area.equals(inst.getArea())) + set.add(inst.getExternalIP()); + } + } + + return set; + } + + /** + * Get all instances info of a type in a given area. + */ + @Override + public List getInstancesOfType(String type, String area) { + + if (type == null) + throw new IllegalArgumentException("Invalid type"); + + /* copy now the array to avoid concurency problems. */ + Instance[] tabInstances = new Instance[0]; + + ArrayList tmp = cachingTableTopology.get(type); + if(tmp != null) + tabInstances = tmp.toArray(tabInstances); + + + ArrayList list = new ArrayList(); + + for (int i = 0; i < tabInstances.length; i++) { + Instance inst = tabInstances[i]; + + if (area == null || area.equals(inst.getArea())) + list.add(inst); + } + + return list; + } + + /** + * Get the current area. + */ + @Override + public String getMyArea() { + + if (currentArea != null) + return currentArea; + + Iterator itKeys = cachingTableTopology.getAllKeys().iterator(); + + while (itKeys.hasNext()) { + Instance[] tabInstances = new Instance[0]; + tabInstances = cachingTableTopology.get(itKeys.next()).toArray(tabInstances); + + for (int i = 0; i < tabInstances.length; i++) { + Instance inst = tabInstances[i]; + + if (CommonTools.isLocal(inst.getExternalIP()) || CommonTools.isLocal(inst.getInternalIP())) { + currentArea = inst.getArea(); + return currentArea; + } + } + } + + /* Area not found or error while fetching ip address. */ + return null; + } + + /** + * Get all the area available + */ + @Override + public synchronized Set getAllAreas() { + + if (currentAreaList != null) + return currentAreaList; + + currentAreaList = new HashSet(); + + Iterator itKeys = cachingTableTopology.getAllKeys().iterator(); + while (itKeys.hasNext()) { + + Instance[] tabInstances = new Instance[0]; + tabInstances = cachingTableTopology.get(itKeys.next()).toArray(tabInstances); + + for (int i = 0; i < tabInstances.length; i++) { + String area = tabInstances[i].getArea(); + if (area != null && !area.isEmpty()) + currentAreaList.add(area); + } + } + return currentAreaList; + } + + /** + * Get all the other areas available + */ + @Override + public Set getAllOtherAreas() { + + Set allAreas = this.getAllAreas(); + Set tmp = new HashSet(allAreas); + String myArea = this.getMyArea(); + tmp.remove(myArea); + + return tmp; + } + + /** + * Add listener to any change of the topology in cache + */ + public void addInstanceTypeListener(IEntryListener> listener) { + cachingTableTopology.addEntryListener(listener); + } + + /** + * Remove listener. + */ + public void removeInstanceTypeListener(IEntryListener> listener) { + cachingTableTopology.removeEntryListener(listener); + } + + /** + * The list of instance listeners + */ + private LinkedList instanceListeners = new LinkedList(); + + /** + * Add an instance listener + */ + @Override + public void addInstanceListener(IInstanceListener listener) { + instanceListeners.add(listener); + } + + /** + * Remove an instance listener + */ + @Override + public void removeInstanceListener(IInstanceListener listener) { + instanceListeners.remove(listener); + } + + /** + * Fire the instanceAdded event + */ + private void fireInstanceAdded(final InstanceEvent event) { + logger.debug("Firing instance added event for instance:{}", event.getInstance()); + + IInstanceListener[] currentListOfListeners = instanceListeners.toArray(new IInstanceListener[]{}); + + for(IInstanceListener listener : currentListOfListeners) { + listener.instanceAdded(event); + } + } + + /** + * Fire the instanceRemoved event + */ + private void fireInstanceRemoved(final InstanceEvent event) { + logger.debug("Firing instance removed event for instance:{}", event.getInstance()); + + IInstanceListener[] currentListOfListeners = instanceListeners.toArray(new IInstanceListener[]{}); + + for(IInstanceListener listener : currentListOfListeners) { + listener.instanceRemoved(event); + } + } + + @Override + public synchronized void addAreas(Set areas) { + if(currentAreaList == null){ + currentAreaList = new HashSet(); + } + this.currentAreaList.addAll(areas); + } + + public synchronized void setMyArea(String area) { + + this.currentArea = area; + } + + // If the topology hasn't entered the data cache, this function will + // NOT return whoIAm, it will return null. So, if you use this, you + // MUST include some sort of failover ID for this case + public Instance whoAmI(String type) { + if (whoIAm.get(type) != null) { + return whoIAm.get(type); + } + logger.debug("Trying to find my Instance for type: " + type); + + List instances; + instances = getAllInstancesOfType(type); + if (instances == null) { + logger.debug("Found no Instances of type."); + return null; + } + //add all possible IPs (and hostname) to this map for easy retrieval + Map ipToInstance = new HashMap(); + for (Instance inst : instances) { + String internalIP = inst.getInternalIP(); + if (!CanonicalizedIpAddress.isValidIp(internalIP)) { + try { + internalIP = InetAddress.getByName(internalIP).getHostAddress(); + } catch (UnknownHostException e) {;} + } + if (!internalIP.isEmpty()) ipToInstance.put(internalIP, inst); + + String externalIP = inst.getExternalIP(); + // if externalIP is a hostname, try to resolve it + if (!CanonicalizedIpAddress.isValidIp(externalIP)) { + try { + externalIP = InetAddress.getByName(externalIP).getHostAddress(); + } catch (UnknownHostException e) {;} + } + if (!externalIP.isEmpty()) ipToInstance.put(externalIP, inst); + + String externalDNS = inst.getExternalDNS(); + if (!externalDNS.isEmpty()) ipToInstance.put(externalDNS, inst); + } + + //check network interfaces + Enumeration nets; + try { + nets = NetworkInterface.getNetworkInterfaces(); + for (NetworkInterface netint : Collections.list(nets)) { + logger.debug("Checking Interface " + netint.getDisplayName()); + + //check ips for each interface + Enumeration inetAddresses = netint.getInetAddresses(); + for (InetAddress inetAddress : Collections.list(inetAddresses)) { + String myIp = inetAddress.getHostAddress(); + logger.debug("Checking IP : " + myIp); + + //if there is an instance associated with myIP, that is me + Instance instance = ipToInstance.get(myIp); + if (instance != null) { + whoIAm.put(type, instance); + logger.debug("Found an IP match with Instance " + instance.getName()); + return instance; + } + } + } + } catch (SocketException e) { + logger.error("Got an exception checking my Network Interfaces for matching IPs: " + + e.getMessage()); + logger.warn(e.getMessage(), e); + } + logger.debug("Could not find an Instance with a matching IP"); + return null; + } +} diff --git a/exposure-engine/common/src/main/java/com/alu/e3/data/model/Api.java b/exposure-engine/common/src/main/java/com/alu/e3/data/model/Api.java new file mode 100644 index 0000000..ddaa6fa --- /dev/null +++ b/exposure-engine/common/src/main/java/com/alu/e3/data/model/Api.java @@ -0,0 +1,174 @@ +/** + * Copyright © 2012 Alcatel-Lucent. + * + * See the NOTICE file distributed with this work for additional + * information regarding copyright ownership. + * Licensed to you 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 com.alu.e3.data.model; + +import java.io.Serializable; +import java.util.ArrayList; +import java.util.LinkedHashMap; +import java.util.List; +import java.util.Map; + +import com.alu.e3.data.model.enumeration.StatusType; +import com.alu.e3.data.model.sub.ApiIds; +import com.alu.e3.data.model.sub.ForwardProxy; +import com.alu.e3.data.model.sub.HeaderTransformation; +import com.alu.e3.data.model.sub.TdrGenerationRule; +import com.alu.e3.data.model.sub.Validation; + +public class Api implements Serializable { + /** + * USID - Unique Serial ID + */ + private static final long serialVersionUID = -4157232186322050081L; + + private String id; + private List policyIds; + private TdrGenerationRule tdrGenerationRule; + private StatusType status; + + transient private ApiDetail apiDetail; + + private List contextIds; + + private int apiId; + + private String tdrOnUse; + private String tdrOnLimitReached; + + private Validation validation; + + private Map properties; + + private Boolean headerTransEnabled = false; + + private List headerTransformations; + + private ForwardProxy localProxy; + private boolean useGlobalProxy; + + + private Boolean internal = false; + + public String getId() { + return id; + } + public void setId(String id) { + this.id = id; + } + + public List getPolicyIds() { + if (policyIds==null) policyIds = new ArrayList(); + return policyIds; + } + + public void setPolicyIds(List policyIds) { + this.policyIds = policyIds; + } + + public TdrGenerationRule getTdrGenerationRule() { + return tdrGenerationRule; + } + public void setTdrGenerationRule(TdrGenerationRule tdrGenerationRule) { + this.tdrGenerationRule = tdrGenerationRule; + } + + public void setApiDetail(ApiDetail apiDetail) { + this.apiDetail = apiDetail; + } + public ApiDetail getApiDetail() { + return apiDetail; + } + + public List getContextIds() { + if (contextIds==null) contextIds = new ArrayList(); + return contextIds; + } + + public void setApiId(int apiId) { + this.apiId = apiId; + } + + public int getApiId() { + return apiId; + } + + public void setTdrOnUse(String tdrOnUse) { + this.tdrOnUse = tdrOnUse; + } + public String getTdrOnUse() { + return tdrOnUse; + } + + public void setTdrOnLimitReached(String tdrOnLimitReached) { + this.tdrOnLimitReached = tdrOnLimitReached; + } + public String getTdrOnLimitReached() { + return tdrOnLimitReached; + } + public Validation getValidation() { + return validation; + } + public void setValidation(Validation validation) { + this.validation = validation; + } + public Map getProperties() { + if(properties==null) properties = new LinkedHashMap(); + return properties; + } + public void setProperties(Map props){ + this.properties = props; + } + public List getHeaderTransformations() { + if(headerTransformations==null) headerTransformations = new ArrayList(); + return headerTransformations; + } + public void setHeaderTransformation(List hts) { + this.headerTransformations = hts; + } + public Boolean getHeaderTransEnabled() { + return headerTransEnabled; + } + public void setHeaderTransEnabled(Boolean headerTransEnabled) { + this.headerTransEnabled = headerTransEnabled; + } + public Boolean getInternal(){ + return this.internal; + } + public void setInternal(boolean internal){ + this.internal = internal; + } + public StatusType getStatus() { + return status; + } + public void setStatus(StatusType status) { + this.status = status; + } + public ForwardProxy getLocalProxy() { + return localProxy; + } + public void setLocalProxy(ForwardProxy localProxy) { + this.localProxy = localProxy; + } + public boolean isUseGlobalProxy() { + return useGlobalProxy; + } + public void setUseGlobalProxy(boolean useGlobalProxy) { + this.useGlobalProxy = useGlobalProxy; + } +} diff --git a/exposure-engine/common/src/main/java/com/alu/e3/data/model/ApiDetail.java b/exposure-engine/common/src/main/java/com/alu/e3/data/model/ApiDetail.java new file mode 100644 index 0000000..0f08fef --- /dev/null +++ b/exposure-engine/common/src/main/java/com/alu/e3/data/model/ApiDetail.java @@ -0,0 +1,170 @@ +/** + * Copyright © 2012 Alcatel-Lucent. + * + * See the NOTICE file distributed with this work for additional + * information regarding copyright ownership. + * Licensed to you 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 com.alu.e3.data.model; + +import java.io.Serializable; +import java.util.ArrayList; +import java.util.List; + +import com.alu.e3.data.model.enumeration.ApiNotificationFormat; +import com.alu.e3.data.model.enumeration.ApiSubscriptionStep; +import com.alu.e3.data.model.enumeration.ApiType; +import com.alu.e3.data.model.enumeration.NBAuthType; +import com.alu.e3.data.model.enumeration.StatusType; +import com.alu.e3.data.model.sub.APIContext; +import com.alu.e3.data.model.sub.HTTPSType; + +public class ApiDetail implements Serializable { + /** + * USID - Unique Serial ID + */ + private static final long serialVersionUID = 8367478855366616966L; + + private String displayName; + private String version; + private ApiType type; + private ApiSubscriptionStep subscriptionStep; + private ApiNotificationFormat notificationFormat; + private String endpoint; + //Certificate for HTTPS NR request (c.f documentation) + private HTTPSType https; + private Boolean tdrEnabled; + private Boolean notification; + private List enabledAuthType; + private String authKeyName; + private String authHeaderName; + private StatusType status; + private transient List contexts; + + private String allowedMethods; + + private boolean isApiDeployed; + + public String getDisplayName() { + return displayName; + } + public void setDisplayName(String displayName) { + this.displayName = displayName; + } + + public String getVersion() { + return version; + } + public void setVersion(String version) { + this.version = version; + } + + public ApiType getType() { + return type; + } + public void setType(ApiType type) { + this.type = type; + } + + public ApiSubscriptionStep getSubscriptionStep() { + return subscriptionStep; + } + + public void setSubscriptionStep(ApiSubscriptionStep subscriptionType) { + this.subscriptionStep = subscriptionType; + } + + public ApiNotificationFormat getNotificationFormat() { + return notificationFormat; + } + + public void setNotificationFormat(ApiNotificationFormat notificationFormat) { + this.notificationFormat = notificationFormat; + } + + public String getEndpoint() { + return endpoint; + } + public void setEndpoint(String endpoint) { + this.endpoint = endpoint; + } + + public Boolean getTdrEnabled() { + return tdrEnabled; + } + public void setTdrEnabled(Boolean tdrEnabled) { + this.tdrEnabled = tdrEnabled; + } + + public Boolean getNotification() { + return notification; + } + public void setNotification(Boolean notification) { + this.notification = notification; + } + + public List getEnabledAuthType() { + if (enabledAuthType==null) enabledAuthType = new ArrayList(); + return enabledAuthType; + } + + public String getAuthKeyName() { + return authKeyName; + } + public void setAuthKeyName(String authKeyName) { + this.authKeyName = authKeyName; + } + + public String getAuthHeaderName() { + return authHeaderName; + } + public void setAuthHeaderName(String authHeaderName) { + this.authHeaderName = authHeaderName; + } + + public List getContexts() { + if (contexts==null) contexts = new ArrayList(); + return contexts; + } + + public HTTPSType getHttps() { + return https; + } + public void setHttps(HTTPSType httpsType) { + this.https = httpsType; + } + + public StatusType getStatus() { + return status; + } + + public void setStatus(StatusType status) { + this.status = status; + } + + public boolean isApiDeployed() { + return isApiDeployed; + } + + public void setIsApiDeployed(boolean isApiDeployed) { + this.isApiDeployed = isApiDeployed; + } + + public String getAllowedMethods() { + return this.allowedMethods; + } + public void setAllowedMethods(String httpMethods) { + this.allowedMethods = httpMethods; + } +} diff --git a/exposure-engine/common/src/main/java/com/alu/e3/data/model/ApiJar.java b/exposure-engine/common/src/main/java/com/alu/e3/data/model/ApiJar.java new file mode 100644 index 0000000..9531cf9 --- /dev/null +++ b/exposure-engine/common/src/main/java/com/alu/e3/data/model/ApiJar.java @@ -0,0 +1,54 @@ +/** + * Copyright © 2012 Alcatel-Lucent. + * + * See the NOTICE file distributed with this work for additional + * information regarding copyright ownership. + * Licensed to you 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 com.alu.e3.data.model; + +import java.io.Serializable; + +import com.alu.e3.common.caching.IAckData; + +public class ApiJar implements Serializable, IAckData { + + private static final long serialVersionUID = -3228468215715921089L; + + protected String id; + protected byte[] data; + + public ApiJar() { + } + + public String getId() { + return id; + } + + public void setId(String id) { + this.id = id; + } + + public byte[] getData() { + return data; + } + + public void setData(byte[] data) { + this.data = data; + } + +} diff --git a/exposure-engine/common/src/main/java/com/alu/e3/data/model/Auth.java b/exposure-engine/common/src/main/java/com/alu/e3/data/model/Auth.java new file mode 100644 index 0000000..8994ee6 --- /dev/null +++ b/exposure-engine/common/src/main/java/com/alu/e3/data/model/Auth.java @@ -0,0 +1,130 @@ +/** + * Copyright © 2012 Alcatel-Lucent. + * + * See the NOTICE file distributed with this work for additional + * information regarding copyright ownership. + * Licensed to you 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 com.alu.e3.data.model; + +import java.io.Serializable; +import java.util.ArrayList; +import java.util.HashMap; +import java.util.List; +import java.util.Map; + +import com.alu.e3.data.model.sub.AuthIds; +import com.alu.e3.data.model.sub.HeaderTransformation; +import com.alu.e3.data.model.sub.TdrGenerationRule; + +public class Auth implements Serializable { + + /** + * USID - Unique Serial ID + */ + private static final long serialVersionUID = 4591944093429136320L; + + private String id; + + private List policyContexts; + + private String apiContext; + private String policyContext; + + private TdrGenerationRule tdrGenerationRule; + transient private AuthDetail authDetail; + + private Map properties; + + private List headerTransformations; + + // Must define the wssePassword on the Auth object + // because it must be available to be examined from the Gateway. + private byte[] wssePassword; + private WSSEAuthPassType passwordType; + + public String getId() { + return id; + } + public void setId(String id) { + this.id = id; + } + + public List getPolicyContexts() { + if (policyContexts==null) policyContexts = new ArrayList(); + return policyContexts; + } + + public void setPolicyContexts(List policyContexts) { + this.policyContexts = policyContexts; + } + + public String getPolicyContext() { + return policyContext; + } + public void setPolicyContext(String value) { + this.policyContext = value; + } + public String getApiContext() { + return apiContext; + } + public void setApiContext(String value) { + this.apiContext = value; + } + + public TdrGenerationRule getTdrGenerationRule() { + return tdrGenerationRule; + } + public void setTdrGenerationRule(TdrGenerationRule tdrGenerationRule) { + this.tdrGenerationRule = tdrGenerationRule; + } + + public AuthDetail getAuthDetail() { + return authDetail; + } + public void setAuthDetail(AuthDetail authDetail) { + this.authDetail = authDetail; + } + public Map getProperties() { + if(this.properties == null){ + this.properties = new HashMap(); + } + return this.properties; + } + + public void setProperties(Map properties) { + this.properties = properties; + } + + public List getHeaderTransformations() { + return this.headerTransformations; + } + + public void setHeaderTransformation(List hts) { + this.headerTransformations = hts; + } + public byte[] getWssePassword() { + return wssePassword; + } + public void setWssePassword(byte[] wssePassword) { + this.wssePassword = wssePassword; + } + public WSSEAuthPassType getPasswordType() { + return passwordType; + } + public void setPasswordType(WSSEAuthPassType passwordType) { + this.passwordType = passwordType; + } + +} diff --git a/exposure-engine/common/src/main/java/com/alu/e3/data/model/AuthDetail.java b/exposure-engine/common/src/main/java/com/alu/e3/data/model/AuthDetail.java new file mode 100644 index 0000000..9b72188 --- /dev/null +++ b/exposure-engine/common/src/main/java/com/alu/e3/data/model/AuthDetail.java @@ -0,0 +1,89 @@ +/** + * Copyright © 2012 Alcatel-Lucent. + * + * See the NOTICE file distributed with this work for additional + * information regarding copyright ownership. + * Licensed to you 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 com.alu.e3.data.model; + +import java.io.Serializable; +import java.util.ArrayList; +import java.util.List; + +import com.alu.e3.data.model.enumeration.NBAuthType; +import com.alu.e3.data.model.enumeration.StatusType; + +public class AuthDetail implements Serializable { + /** + * USID - Unique Serial ID + */ + private static final long serialVersionUID = 1263666739020248605L; + + private StatusType status; + private NBAuthType type; + private String authKeyValue; + private String clientId; + private String clientSecret; + private String username; + private byte[] password; + private List whiteListedIps; + + public StatusType getStatus() { + return status; + } + public void setStatus(StatusType status) { + this.status = status; + } + public NBAuthType getType() { + return type; + } + public void setType(NBAuthType type) { + this.type = type; + } + public String getAuthKeyValue() { + return authKeyValue; + } + public void setAuthKeyValue(String authKeyValue) { + this.authKeyValue = authKeyValue; + } + public String getClientId() { + return clientId; + } + public void setClientId(String clientId) { + this.clientId = clientId; + } + public String getClientSecret() { + return clientSecret; + } + public void setClientSecret(String clientSecret) { + this.clientSecret = clientSecret; + } + public byte[] getPassword() { + return password; + } + public void setPassword(byte[] password) { + this.password = password; + } + public String getUsername() { + return username; + } + public void setUsername(String username) { + this.username = username; + } + public List getWhiteListedIps() { + if (whiteListedIps==null) whiteListedIps = new ArrayList(); + return whiteListedIps; + } +} diff --git a/exposure-engine/common/src/main/java/com/alu/e3/data/model/CallDescriptor.java b/exposure-engine/common/src/main/java/com/alu/e3/data/model/CallDescriptor.java new file mode 100644 index 0000000..90fa41e --- /dev/null +++ b/exposure-engine/common/src/main/java/com/alu/e3/data/model/CallDescriptor.java @@ -0,0 +1,89 @@ +/** + * Copyright © 2012 Alcatel-Lucent. + * + * See the NOTICE file distributed with this work for additional + * information regarding copyright ownership. + * Licensed to you 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 com.alu.e3.data.model; + +public class CallDescriptor { + + // May be null if the contextId/bucketId is for an ApiContext + private Policy policy; + + private Integer contextId; + + private Integer bucketId; + + public CallDescriptor(Policy policy, int contextId, int bucketId) { + this.policy = policy; + this.contextId = contextId; + this.bucketId = bucketId; + } + + public Integer getBucketId() { + return bucketId; + } + + public Integer getContextId() { + return contextId; + } + + public Policy getPolicy() { + return policy; + } + + public void setBucketId(Integer bucketId) { + this.bucketId = bucketId; + } + + public void setContextId(Integer contextId) { + this.contextId = contextId; + } + + public void setPolicy(Policy policy) { + this.policy = policy; + } + + @Override + public boolean equals(Object object) { + if (object == null) + return false; + + CallDescriptor cd = (CallDescriptor) object; + + if(!contextId.equals(cd.getContextId())) + return false; + + if(!bucketId.equals(cd.getBucketId())) + return false; + + boolean equals = false; + if(policy != null) { + if(cd.getPolicy() != null && policy.getId() != null && cd.getPolicy().getId() != null) { + equals = policy.getId().equals(cd.getPolicy().getId()); + } + } else { + if(cd.getPolicy() == null) { + equals = true; + } + } + + return equals; + + } + +} + diff --git a/exposure-engine/common/src/main/java/com/alu/e3/data/model/Certificate.java b/exposure-engine/common/src/main/java/com/alu/e3/data/model/Certificate.java new file mode 100644 index 0000000..238839e --- /dev/null +++ b/exposure-engine/common/src/main/java/com/alu/e3/data/model/Certificate.java @@ -0,0 +1,70 @@ +/** + * Copyright © 2012 Alcatel-Lucent. + * + * See the NOTICE file distributed with this work for additional + * information regarding copyright ownership. + * Licensed to you 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 com.alu.e3.data.model; + +import java.io.Serializable; + +import com.alu.e3.common.caching.IAckData; + +public class Certificate implements Serializable, IAckData { + + /** + * + */ + private static final long serialVersionUID = -7547669134719015486L; + + private String id; + + private String data; + private String password; + private transient CertificateDetail certDetail; + + public String getData() { + return data; + } + + public void setData(String data) { + this.data = data; + } + + public String getPassword() { + return password; + } + + public void setPassword(String password) { + this.password = password; + } + + public String getId() { + return id; + } + + public void setId(String id) { + this.id = id; + } + + public CertificateDetail getCertDetail() { + return certDetail; + } + + public void setCertDetail(CertificateDetail certDetail) { + this.certDetail = certDetail; + } + +} diff --git a/exposure-engine/common/src/main/java/com/alu/e3/data/model/CertificateDetail.java b/exposure-engine/common/src/main/java/com/alu/e3/data/model/CertificateDetail.java new file mode 100644 index 0000000..ca62444 --- /dev/null +++ b/exposure-engine/common/src/main/java/com/alu/e3/data/model/CertificateDetail.java @@ -0,0 +1,58 @@ +/** + * Copyright © 2012 Alcatel-Lucent. + * + * See the NOTICE file distributed with this work for additional + * information regarding copyright ownership. + * Licensed to you 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 com.alu.e3.data.model; + +import java.io.Serializable; + +public class CertificateDetail implements Serializable { + /** + * + */ + private static final long serialVersionUID = 1274720640366309712L; + + private String id; + + private String name; + private String keyId; + + public String getName() { + return name; + } + + public void setName(String name) { + this.name = name; + } + + public String getId() { + return id; + } + + public void setId(String id) { + this.id = id; + } + + public String getKeyId() { + return keyId; + } + + public void setKeyId(String keyId) { + this.keyId = keyId; + } + +} diff --git a/exposure-engine/common/src/main/java/com/alu/e3/data/model/CertificateRequest.java b/exposure-engine/common/src/main/java/com/alu/e3/data/model/CertificateRequest.java new file mode 100644 index 0000000..ba89631 --- /dev/null +++ b/exposure-engine/common/src/main/java/com/alu/e3/data/model/CertificateRequest.java @@ -0,0 +1,33 @@ +/** + * Copyright © 2012 Alcatel-Lucent. + * + * See the NOTICE file distributed with this work for additional + * information regarding copyright ownership. + * Licensed to you 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 com.alu.e3.data.model; + +public class CertificateRequest { + + private String data; + + public String getData() { + return data; + } + + public void setData(String data) { + this.data = data; + } + +} diff --git a/exposure-engine/common/src/main/java/com/alu/e3/data/model/ExtractFromType.java b/exposure-engine/common/src/main/java/com/alu/e3/data/model/ExtractFromType.java new file mode 100644 index 0000000..9f86f8e --- /dev/null +++ b/exposure-engine/common/src/main/java/com/alu/e3/data/model/ExtractFromType.java @@ -0,0 +1,25 @@ +/** + * Copyright © 2012 Alcatel-Lucent. + * + * See the NOTICE file distributed with this work for additional + * information regarding copyright ownership. + * Licensed to you 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 com.alu.e3.data.model; + +public enum ExtractFromType { + Request, + Response, + Either +} diff --git a/exposure-engine/common/src/main/java/com/alu/e3/data/model/Instance.java b/exposure-engine/common/src/main/java/com/alu/e3/data/model/Instance.java new file mode 100644 index 0000000..8d72f3c --- /dev/null +++ b/exposure-engine/common/src/main/java/com/alu/e3/data/model/Instance.java @@ -0,0 +1,171 @@ +/** + * Copyright © 2012 Alcatel-Lucent. + * + * See the NOTICE file distributed with this work for additional + * information regarding copyright ownership. + * Licensed to you 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 com.alu.e3.data.model; + +import java.io.Serializable; + +/** + * Class Instance + * + */ +public class Instance implements Serializable { + + /** + * Generated serial version UID + */ + private static final long serialVersionUID = 8190090033750980700L; + + + private String externalIP, internalIP, externalDNS; + private String type; + private String name; + private String sshKeyName; + private String user; + private String password; + private String port; + private String area; + private int sshPort = 22; + private SSHKey sshKey; + + public Instance() { + } + + public Instance(Instance inst) { + this.externalIP = inst.externalIP; + this.internalIP = inst.internalIP; + this.externalDNS = inst.externalDNS; + this.type = inst.type; + this.name = inst.name; + this.sshKeyName = inst.sshKeyName; + this.user = inst.user; + this.password = inst.password; + this.port = inst.port; + this.area = inst.area; + this.sshPort = inst.sshPort; + + SSHKey instSSHKey = inst.getSSHKey(); + + if (instSSHKey != null) { + this.sshKey = new SSHKey(instSSHKey.getName(), + instSSHKey.getPrivateKey(), instSSHKey.getPublicKey()); + } + } + + public int getSSHPort() { + return sshPort; + } + + public void setSSHPort(int sshPort) { + this.sshPort = sshPort; + } + + public SSHKey getSSHKey() { + return sshKey; + } + + public void setSSHKey(SSHKey sshKey) { + this.sshKey = sshKey; + } + + public String getExternalDNS() { + return externalDNS; + } + + public void setExternalDNS(String externalDNS) { + this.externalDNS = externalDNS; + } + + public String getType() { + return type; + } + + public void setType(String type) { + this.type = type; + } + + public String getName() { + return name; + } + + public void setName(String name) { + this.name = name; + } + + public String getExternalIP() { + return externalIP; + } + + public void setExternalIP(String externalIP) { + this.externalIP = externalIP; + } + + public String getInternalIP() { + return internalIP; + } + + public void setInternalIP(String internalIP) { + this.internalIP = internalIP; + } + + public String getSSHKeyName() { + return sshKeyName; + } + + public void setSSHKeyName(String sshKeyName) { + this.sshKeyName = sshKeyName; + } + + public String getUser() { + return user; + } + + public void setUser(String user) { + this.user = user; + } + + public String getPassword() { + return password; + } + + public void setPassword(String password) { + this.password = password; + } + + public String getPort() { + return port; + } + + public void setPort(String port) { + this.port = port; + } + + public String getArea() { + return area; + } + + public void setArea(String area) { + this.area = area; + } + + @Override + public String toString() { + return "[Instance: " + name + " " + type + " " + internalIP + " " + + externalIP + " " + area + "]"; + } +} diff --git a/exposure-engine/common/src/main/java/com/alu/e3/data/model/Key.java b/exposure-engine/common/src/main/java/com/alu/e3/data/model/Key.java new file mode 100644 index 0000000..57820b7 --- /dev/null +++ b/exposure-engine/common/src/main/java/com/alu/e3/data/model/Key.java @@ -0,0 +1,86 @@ +/** + * Copyright © 2012 Alcatel-Lucent. + * + * See the NOTICE file distributed with this work for additional + * information regarding copyright ownership. + * Licensed to you 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 com.alu.e3.data.model; + +import java.io.Serializable; + +import com.alu.e3.common.caching.IAckData; + +public class Key implements Serializable, IAckData { + /** + * + */ + private static final long serialVersionUID = 2510943073668382224L; + + private String id; + + private String data; + private String activeCertId; + private String keyPassphrase; + transient private Certificate activeCert; + transient private KeyDetail keyDetail; + + public String getData() { + return data; + } + + public void setData(String data) { + this.data = data; + } + + public String getId() { + return id; + } + + public void setId(String id) { + this.id = id; + } + + public String getActiveCertId() { + return activeCertId; + } + + public void setActiveCertId(String activecert) { + this.activeCertId = activecert; + } + + public void setKeyPassphrase(String keyPassphrase) { + this.keyPassphrase = keyPassphrase; + } + + public String getKeyPassphrase() { + return keyPassphrase; + } + + public KeyDetail getKeyDetail() { + return keyDetail; + } + + public void setKeyDetail(KeyDetail keyDetail) { + this.keyDetail = keyDetail; + } + + public Certificate getActiveCert() { + return activeCert; + } + + public void setActiveCert(Certificate activeCert) { + this.activeCert = activeCert; + } +} diff --git a/exposure-engine/common/src/main/java/com/alu/e3/data/model/KeyDetail.java b/exposure-engine/common/src/main/java/com/alu/e3/data/model/KeyDetail.java new file mode 100644 index 0000000..508f088 --- /dev/null +++ b/exposure-engine/common/src/main/java/com/alu/e3/data/model/KeyDetail.java @@ -0,0 +1,57 @@ +/** + * Copyright © 2012 Alcatel-Lucent. + * + * See the NOTICE file distributed with this work for additional + * information regarding copyright ownership. + * Licensed to you 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 com.alu.e3.data.model; + +import java.io.Serializable; + +public class KeyDetail implements Serializable { + /** + * + */ + private static final long serialVersionUID = 1274720640366309712L; + + private String id; + + private String name; + private String type; + + public String getName() { + return name; + } + + public void setName(String name) { + this.name = name; + } + + public String getId() { + return id; + } + + public void setId(String id) { + this.id = id; + } + + public String getType() { + return type; + } + + public void setType(String type) { + this.type = type; + } +} diff --git a/exposure-engine/common/src/main/java/com/alu/e3/data/model/Limit.java b/exposure-engine/common/src/main/java/com/alu/e3/data/model/Limit.java new file mode 100644 index 0000000..ccc525d --- /dev/null +++ b/exposure-engine/common/src/main/java/com/alu/e3/data/model/Limit.java @@ -0,0 +1,80 @@ +/** + * Copyright © 2012 Alcatel-Lucent. + * + * See the NOTICE file distributed with this work for additional + * information regarding copyright ownership. + * Licensed to you 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 com.alu.e3.data.model; + +import java.util.Date; + +import com.alu.e3.data.model.sub.Counter; + +public class Limit { + + private Counter quotaPerDay; + private Counter quotaPerWeek; + private Counter quotaPerMonth; + private Counter rateLimitPerSecond; + private Counter rateLimitPerMinute; + private Date createdDate; + + public Counter getQuotaPerDay() { + return quotaPerDay; + } + + public Counter getQuotaPerWeek() { + return quotaPerWeek; + } + + public Counter getQuotaPerMonth() { + return quotaPerMonth; + } + + public Counter getRateLimitPerMinute() { + return rateLimitPerMinute; + } + + public Counter getRateLimitPerSecond() { + return rateLimitPerSecond; + } + + public void setQuotaPerDay(Counter quotaPerDay) { + this.quotaPerDay = quotaPerDay; + } + + public void setQuotaPerWeek(Counter quotaPerWeek) { + this.quotaPerWeek = quotaPerWeek; + } + + public void setQuotaPerMonth(Counter quotaPerMonth) { + this.quotaPerMonth = quotaPerMonth; + } + public void setRateLimitPerMinute(Counter rateLimitPerMinute) { + this.rateLimitPerMinute = rateLimitPerMinute; + } + + public void setRateLimitPerSecond(Counter rateLimitPerSecond) { + this.rateLimitPerSecond = rateLimitPerSecond; + } + + public Date getCreatedDate() { + return createdDate; + } + + public void setCreatedDate(Date createdDate) { + this.createdDate = createdDate; + } +} diff --git a/exposure-engine/common/src/main/java/com/alu/e3/data/model/LogLevel.java b/exposure-engine/common/src/main/java/com/alu/e3/data/model/LogLevel.java new file mode 100644 index 0000000..80bfd05 --- /dev/null +++ b/exposure-engine/common/src/main/java/com/alu/e3/data/model/LogLevel.java @@ -0,0 +1,198 @@ +/** + * Copyright © 2012 Alcatel-Lucent. + * + * See the NOTICE file distributed with this work for additional + * information regarding copyright ownership. + * Licensed to you 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 com.alu.e3.data.model; + +import java.io.Serializable; +import java.util.Arrays; + +import org.apache.log4j.Level; + +/** + * Data structure for holding java log levels, using log4j conventions + * and wrapping the log4j Level class. + * + * Note: + * + * Be careful when using the LogLevel(String levelString) constructor, as + * it will return the default LogLevel if levelString cannot be parsed + * as a valid log4j level value. Use the static function + * isValidLogLevel(String levelString) to check for valid values first + * if necessary. + * + * + */ + +public class LogLevel implements Serializable { + + private static final long serialVersionUID = -2322396140902593928L; + public static final Level defaultLevel = Level.INFO; + + // Keys for logLevel table in DataManager + public static final String logLevelKey = "logLevel"; + public static final String smxlogLevelKey = "smxlogLevel"; + public static final String syslogLevelKey = "syslogLevel"; + public static final String logLevelKeyParamSeparator = ":"; + + private Level level; + private SyslogLevel syslogLevel; + + public LogLevel(Level level) + { + if (level == null) { + level = defaultLevel; + } + this.level = level; + this.syslogLevel = SyslogLevel.valueOf(this.level.getSyslogEquivalent()); + } + + /** + * LogLevel constructor from a log4j or syslog level string. + * + * Note that an invalid level string will not throw an exception, + * but will instead return the default level value. + * Use the static function isValidLogLevel(String levelString) + * or isValidSyslogLevel(String levelString) + * to check string values first. + */ + public LogLevel(String levelString) + { + // Always check log4j levels first, because the mapping from log4j + // level to syslog level is not one-to-one + if (LogLevel.isValidLogLevel(levelString)) { + this.level = Level.toLevel(levelString, defaultLevel); + this.syslogLevel = SyslogLevel.valueOf(this.level.getSyslogEquivalent()); + } else if (LogLevel.isValidSyslogLevel(levelString)) { + this.syslogLevel = Enum.valueOf(SyslogLevel.class, levelString); + Level equivLevel = this.syslogLevel.getLevelEquivalent(); + this.level = equivLevel != null ? equivLevel : defaultLevel; // does not try to find nearest match! + } else { + this.level = defaultLevel; + this.syslogLevel = SyslogLevel.valueOf(this.level.getSyslogEquivalent()); + } + + this.level = Level.toLevel(levelString, defaultLevel); + } + + public Level getLevel() + { + return level; + } + + public SyslogLevel getSyslogLevel() + { + return syslogLevel; + } + + @Override + public final String toString() + { + return level.toString(); + } + + @Override + public boolean equals(Object o) + { + if (!(o instanceof LogLevel)) { + return false; + } + LogLevel that = (LogLevel)o; + return this.level.equals(that.level); + } + + @Override + public int hashCode() + { + return level.hashCode(); + } + + + public enum Log4JLevel { + + OFF, FATAL, ERROR, WARN, INFO, DEBUG, TRACE, ALL; + + public static final String valuesList = Arrays.asList(LogLevel.Log4JLevel.values()).toString(); + public static final String patternString = "(?i)(" + valuesList.replaceAll("(^\\[|\\]$)", "").replace(", ", "|") + ")(?-i)"; + } + + public enum SyslogLevel { + + EMERG(0), ALERT(1), CRIT(2), ERR(3), WARNING(4), NOTICE(5), INFO(6), DEBUG(7); + + private final int intValue; + SyslogLevel(int intValue) {this.intValue = intValue; } + public int intValue() { return this.intValue; } + public static final String valuesList = Arrays.asList(LogLevel.SyslogLevel.values()).toString(); + public static final String patternString = "(?i)(" + valuesList.replaceAll("(^\\[|\\]$)", "").replace(", ", "|") + ")(?-i)"; + + // Also define severity level strings that are valid in syslog.conf rules + public static final String configPatternString = "(?i)(panic|emerg|alert|crit|error|err|warning|warn|notice|info|debug|\\*)(?-i)"; + + public static SyslogLevel valueOf(int i) + { + for (SyslogLevel level : SyslogLevel.values()) { + if (level.intValue == i) { + return level; + } + } + return null; + } + + /** + * Returns the equivalent (log4j) Level for a syslog-level object. Note that the + * mapping the Level.getSyslogEquivalent() function is not one-to-one, + * so the Level returned may be one of several possible equivalents. + * + * @return The equivalent Level for this SyslogLevel, or null if no equivalent found + */ + public Level getLevelEquivalent() + { + for (Log4JLevel log4jlevel : Log4JLevel.values()) { + Level level = Level.toLevel(log4jlevel.name()); + if (level.getSyslogEquivalent() == this.intValue) { + return level; + } + } + return null; + } + } + + + public static boolean isValidLogLevel(String levelString) + { + return ((levelString != null) && levelString.matches(Log4JLevel.patternString)); + } + + public static boolean isValidSyslogLevel(String levelString) + { + return ((levelString != null) && levelString.matches(SyslogLevel.patternString)); + } + + // future use + public static String logLevelKeyForIP(String ipAddress) + { + return LogLevel.logLevelKey + ":" + ipAddress; + } + + // future use + public static String syslogLevelKeyForIP(String ipAddress) + { + return LogLevel.syslogLevelKey + logLevelKeyParamSeparator + ipAddress; + } + +} diff --git a/exposure-engine/common/src/main/java/com/alu/e3/data/model/Policy.java b/exposure-engine/common/src/main/java/com/alu/e3/data/model/Policy.java new file mode 100644 index 0000000..ecbed70 --- /dev/null +++ b/exposure-engine/common/src/main/java/com/alu/e3/data/model/Policy.java @@ -0,0 +1,110 @@ +/** + * Copyright © 2012 Alcatel-Lucent. + * + * See the NOTICE file distributed with this work for additional + * information regarding copyright ownership. + * Licensed to you 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 com.alu.e3.data.model; + +import java.io.Serializable; +import java.util.ArrayList; +import java.util.HashMap; +import java.util.List; +import java.util.Map; + +import com.alu.e3.data.model.sub.Context; +import com.alu.e3.data.model.sub.HeaderTransformation; +import com.alu.e3.data.model.sub.QuotaRLBucket; +import com.alu.e3.data.model.sub.TdrGenerationRule; + +public class Policy implements Serializable { + /** + * USID - Unique Serial ID + */ + private static final long serialVersionUID = -1748894244200870901L; + + private String id; + private List apiIds; + private List authIds; + + private transient List contexts; + + private List contextIds; + + private TdrGenerationRule tdrGenerationRule; + + private String tdrOnLimitReached; + + private Map properties; + + private List headerTransformations; + + public String getId() { + return id; + } + public void setId(String id) { + this.id = id; + } + + public List getApiIds() { + if (apiIds==null) apiIds = new ArrayList(); + return apiIds; + } + public List getAuthIds() { + if (authIds==null) authIds = new ArrayList(); + return authIds; + } + + public List getContexts() { + if (contexts==null) contexts = new ArrayList(); + return contexts; + } + + public TdrGenerationRule getTdrGenerationRule() { + return tdrGenerationRule; + } + + public void setTdrGenerationRule(TdrGenerationRule tdrGenerationRules) { + this.tdrGenerationRule = tdrGenerationRules; + } + + public List getContextIds() { + if (contextIds==null) contextIds = new ArrayList(); + return contextIds; + } + + public void setTdrOnLimitReached(String tdrOnLimitReached) { + this.tdrOnLimitReached = tdrOnLimitReached; + } + public String getTdrOnLimitReached() { + return tdrOnLimitReached; + } + public Map getProperties() { + if(this.properties==null) this.properties = new HashMap(); + return this.properties; + } + + public void setProperties(Map props){ + this.properties = props; + } + + public List getHeaderTransformations() { + return this.headerTransformations; + } + + public void setHeaderTransformation(List hts) { + this.headerTransformations = hts; + } +} diff --git a/exposure-engine/common/src/main/java/com/alu/e3/data/model/SSHKey.java b/exposure-engine/common/src/main/java/com/alu/e3/data/model/SSHKey.java new file mode 100644 index 0000000..9a3a0f8 --- /dev/null +++ b/exposure-engine/common/src/main/java/com/alu/e3/data/model/SSHKey.java @@ -0,0 +1,114 @@ +/** + * Copyright © 2012 Alcatel-Lucent. + * + * See the NOTICE file distributed with this work for additional + * information regarding copyright ownership. + * Licensed to you 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 com.alu.e3.data.model; + +import java.io.Serializable; + +/** + * SSHKey class Defines a SSH key + * + */ +public class SSHKey implements Serializable { + + /** + * Generated serial version UID + */ + private static final long serialVersionUID = 6230964622405375075L; + + /* members. */ + private String m_strName; + private byte[] m_bytePrivateKey; + private byte[] m_bytePublicKey; + + /** + * Constructor + * + * @param strType + * @param strName + * @param strPrivateKeyPath + * @param strPublicKeyPath + */ + public SSHKey(String strName, byte[] bytePrivateKeyPath, + byte[] bytePublicKeyPath) { + this.m_strName = strName; + this.m_bytePrivateKey = bytePrivateKeyPath; + this.m_bytePublicKey = bytePublicKeyPath; + } + + /** + * Constructor + * + * @param strName + */ + public SSHKey(String strName) { + m_strName = strName; + } + + public String getName() { + return m_strName; + } + + public void setName(String strName) { + this.m_strName = strName; + } + + public byte[] getPrivateKey() { + return m_bytePrivateKey; + } + + public void setPrivateKey(byte[] bytePrivateKeyPath) { + this.m_bytePrivateKey = bytePrivateKeyPath; + } + + public byte[] getPublicKey() { + return m_bytePublicKey; + } + + public void setPublicKey(byte[] bytePublicKeyPath) { + this.m_bytePublicKey = bytePublicKeyPath; + } + + public String toString() { + return "[" + this.getClass().getSimpleName() + ": " + m_strName + + "\tpubKeyLen(" + m_bytePublicKey.length + ")\tprivKeyLen(" + + (m_bytePrivateKey == null ? 0 : m_bytePrivateKey.length) + ")]"; + } + + public boolean isSameKey(SSHKey that) { + if ( (this.m_bytePrivateKey == null && that.m_bytePrivateKey != null) || (this.m_bytePrivateKey != null && that.m_bytePrivateKey == null)) { + return false; + } + + if ((this.m_bytePrivateKey != null && that.m_bytePrivateKey != null)) { + if (this.m_bytePrivateKey.length != that.m_bytePrivateKey.length) + return false; + for (int i = 0; i < this.m_bytePrivateKey.length; i++) { + if (this.m_bytePrivateKey[i] != that.m_bytePrivateKey[i]) + return false; + } + } + if (this.m_bytePublicKey.length != that.m_bytePublicKey.length) + return false; + for (int i = 0; i < this.m_bytePublicKey.length; i++) { + if (this.m_bytePublicKey[i] != that.m_bytePublicKey[i]) + return false; + } + return true; + } +} diff --git a/exposure-engine/common/src/main/java/com/alu/e3/data/model/SSLCRL.java b/exposure-engine/common/src/main/java/com/alu/e3/data/model/SSLCRL.java new file mode 100644 index 0000000..9e7dde7 --- /dev/null +++ b/exposure-engine/common/src/main/java/com/alu/e3/data/model/SSLCRL.java @@ -0,0 +1,73 @@ +/** + * Copyright © 2012 Alcatel-Lucent. + * + * See the NOTICE file distributed with this work for additional + * information regarding copyright ownership. + * Licensed to you 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 com.alu.e3.data.model; + +import java.io.Serializable; + +public class SSLCRL implements Serializable { + /** + * USID - Unique Serial ID + */ + private static final long serialVersionUID = -987654244200870901L; + + /** + * The key ID. Could be provided. + */ + protected String id; + + /** + * The crl content + */ + protected String content; + + /** + * CRL display name for administration purpose. + * If not provided, will be set with CRL's Issuer. + */ + protected String displayName; + + public String getId() { + return id; + } + + + public void setId(String id) { + this.id = id; + } + + + public String getContent() { + return content; + } + + + public void setContent(String certContent) { + this.content = certContent; + } + + public String getDisplayName() { + return displayName; + } + + public void setDisplayName(String displayName) { + this.displayName = displayName; + } + + +} diff --git a/exposure-engine/common/src/main/java/com/alu/e3/data/model/WSSEAuthPassType.java b/exposure-engine/common/src/main/java/com/alu/e3/data/model/WSSEAuthPassType.java new file mode 100644 index 0000000..29dd722 --- /dev/null +++ b/exposure-engine/common/src/main/java/com/alu/e3/data/model/WSSEAuthPassType.java @@ -0,0 +1,47 @@ +/** + * Copyright © 2012 Alcatel-Lucent. + * + * See the NOTICE file distributed with this work for additional + * information regarding copyright ownership. + * Licensed to you 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 com.alu.e3.data.model; + +import javax.xml.bind.annotation.XmlEnum; +import javax.xml.bind.annotation.XmlEnumValue; +import javax.xml.bind.annotation.XmlType; + +@XmlType(name = "passwordType") +@XmlEnum +public enum WSSEAuthPassType { + @XmlEnumValue("PasswordDigest") + PASSWORD_DIGEST("PasswordDigest"), + @XmlEnumValue("PlainText") + PLAIN_TEXT("PlainText"); + + private final String value; + + WSSEAuthPassType(String v) { + value = v; + } + + public static WSSEAuthPassType fromValue(String v) { + for (WSSEAuthPassType c: WSSEAuthPassType.values()) { + if (c.value.equals(v)) { + return c; + } + } + throw new IllegalArgumentException(v); + } +} diff --git a/exposure-engine/common/src/main/java/com/alu/e3/data/model/enumeration/ActionType.java b/exposure-engine/common/src/main/java/com/alu/e3/data/model/enumeration/ActionType.java new file mode 100644 index 0000000..0ea67ad --- /dev/null +++ b/exposure-engine/common/src/main/java/com/alu/e3/data/model/enumeration/ActionType.java @@ -0,0 +1,24 @@ +/** + * Copyright © 2012 Alcatel-Lucent. + * + * See the NOTICE file distributed with this work for additional + * information regarding copyright ownership. + * Licensed to you 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 com.alu.e3.data.model.enumeration; + +public enum ActionType { + IGNORE, + REJECT +} diff --git a/exposure-engine/common/src/main/java/com/alu/e3/data/model/enumeration/ApiNotificationFormat.java b/exposure-engine/common/src/main/java/com/alu/e3/data/model/enumeration/ApiNotificationFormat.java new file mode 100644 index 0000000..7db4840 --- /dev/null +++ b/exposure-engine/common/src/main/java/com/alu/e3/data/model/enumeration/ApiNotificationFormat.java @@ -0,0 +1,24 @@ +/** + * Copyright © 2012 Alcatel-Lucent. + * + * See the NOTICE file distributed with this work for additional + * information regarding copyright ownership. + * Licensed to you 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 com.alu.e3.data.model.enumeration; + +public enum ApiNotificationFormat { + HEADER, + WS_ADDRESSING +} diff --git a/exposure-engine/common/src/main/java/com/alu/e3/data/model/enumeration/ApiSubscriptionStep.java b/exposure-engine/common/src/main/java/com/alu/e3/data/model/enumeration/ApiSubscriptionStep.java new file mode 100644 index 0000000..ab919ff --- /dev/null +++ b/exposure-engine/common/src/main/java/com/alu/e3/data/model/enumeration/ApiSubscriptionStep.java @@ -0,0 +1,24 @@ +/** + * Copyright © 2012 Alcatel-Lucent. + * + * See the NOTICE file distributed with this work for additional + * information regarding copyright ownership. + * Licensed to you 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 com.alu.e3.data.model.enumeration; + +public enum ApiSubscriptionStep { + SUBSCRIPTION, + NOTIFICATION +} diff --git a/exposure-engine/common/src/main/java/com/alu/e3/data/model/enumeration/ApiType.java b/exposure-engine/common/src/main/java/com/alu/e3/data/model/enumeration/ApiType.java new file mode 100644 index 0000000..c7ac990 --- /dev/null +++ b/exposure-engine/common/src/main/java/com/alu/e3/data/model/enumeration/ApiType.java @@ -0,0 +1,24 @@ +/** + * Copyright © 2012 Alcatel-Lucent. + * + * See the NOTICE file distributed with this work for additional + * information regarding copyright ownership. + * Licensed to you 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 com.alu.e3.data.model.enumeration; + +public enum ApiType { + PASS_THROUGH, + COMPOSITE +} diff --git a/exposure-engine/common/src/main/java/com/alu/e3/data/model/enumeration/HeaderTransformationAction.java b/exposure-engine/common/src/main/java/com/alu/e3/data/model/enumeration/HeaderTransformationAction.java new file mode 100644 index 0000000..36d3f36 --- /dev/null +++ b/exposure-engine/common/src/main/java/com/alu/e3/data/model/enumeration/HeaderTransformationAction.java @@ -0,0 +1,24 @@ +/** + * Copyright © 2012 Alcatel-Lucent. + * + * See the NOTICE file distributed with this work for additional + * information regarding copyright ownership. + * Licensed to you 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 com.alu.e3.data.model.enumeration; + +public enum HeaderTransformationAction { + ADD, + REMOVE +} diff --git a/exposure-engine/common/src/main/java/com/alu/e3/data/model/enumeration/HeaderTransformationType.java b/exposure-engine/common/src/main/java/com/alu/e3/data/model/enumeration/HeaderTransformationType.java new file mode 100644 index 0000000..2f64c72 --- /dev/null +++ b/exposure-engine/common/src/main/java/com/alu/e3/data/model/enumeration/HeaderTransformationType.java @@ -0,0 +1,25 @@ +/** + * Copyright © 2012 Alcatel-Lucent. + * + * See the NOTICE file distributed with this work for additional + * information regarding copyright ownership. + * Licensed to you 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 com.alu.e3.data.model.enumeration; + +public enum HeaderTransformationType { + REQUEST, + RESPONSE + +} diff --git a/exposure-engine/common/src/main/java/com/alu/e3/data/model/enumeration/LoadBalancingType.java b/exposure-engine/common/src/main/java/com/alu/e3/data/model/enumeration/LoadBalancingType.java new file mode 100644 index 0000000..989cb1b --- /dev/null +++ b/exposure-engine/common/src/main/java/com/alu/e3/data/model/enumeration/LoadBalancingType.java @@ -0,0 +1,23 @@ +/** + * Copyright © 2012 Alcatel-Lucent. + * + * See the NOTICE file distributed with this work for additional + * information regarding copyright ownership. + * Licensed to you 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 com.alu.e3.data.model.enumeration; + +public enum LoadBalancingType { + ROUND_ROBIN +} diff --git a/exposure-engine/common/src/main/java/com/alu/e3/data/model/enumeration/NBAuthType.java b/exposure-engine/common/src/main/java/com/alu/e3/data/model/enumeration/NBAuthType.java new file mode 100644 index 0000000..cf48977 --- /dev/null +++ b/exposure-engine/common/src/main/java/com/alu/e3/data/model/enumeration/NBAuthType.java @@ -0,0 +1,29 @@ +/** + * Copyright © 2012 Alcatel-Lucent. + * + * See the NOTICE file distributed with this work for additional + * information regarding copyright ownership. + * Licensed to you 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 com.alu.e3.data.model.enumeration; + + +public enum NBAuthType { + BASIC, + AUTHKEY, + IP_WHITE_LIST, + NO_AUTH, + OAUTH, + WSSE +} diff --git a/exposure-engine/common/src/main/java/com/alu/e3/data/model/enumeration/SchemaValidationEnum.java b/exposure-engine/common/src/main/java/com/alu/e3/data/model/enumeration/SchemaValidationEnum.java new file mode 100644 index 0000000..a79f330 --- /dev/null +++ b/exposure-engine/common/src/main/java/com/alu/e3/data/model/enumeration/SchemaValidationEnum.java @@ -0,0 +1,46 @@ +/** + * Copyright © 2012 Alcatel-Lucent. + * + * See the NOTICE file distributed with this work for additional + * information regarding copyright ownership. + * Licensed to you 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 com.alu.e3.data.model.enumeration; + + + +public enum SchemaValidationEnum { + + WSDL("wsdl"), + XSD("xsd"); + private final String value; + + SchemaValidationEnum(String v) { + value = v; + } + + public String value() { + return value; + } + + public static SchemaValidationEnum fromValue(String v) { + for (SchemaValidationEnum c: SchemaValidationEnum.values()) { + if (c.value.equals(v)) { + return c; + } + } + throw new IllegalArgumentException(v); + } + +} diff --git a/exposure-engine/common/src/main/java/com/alu/e3/data/model/enumeration/SoapVersionEnum.java b/exposure-engine/common/src/main/java/com/alu/e3/data/model/enumeration/SoapVersionEnum.java new file mode 100644 index 0000000..f5eb6f4 --- /dev/null +++ b/exposure-engine/common/src/main/java/com/alu/e3/data/model/enumeration/SoapVersionEnum.java @@ -0,0 +1,45 @@ +/** + * Copyright © 2012 Alcatel-Lucent. + * + * See the NOTICE file distributed with this work for additional + * information regarding copyright ownership. + * Licensed to you 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 com.alu.e3.data.model.enumeration; + + + +public enum SoapVersionEnum { + SOAP11("1.1"), + SOAP12("1.2"); + private final String value; + + SoapVersionEnum(String v) { + value = v; + } + + public String value() { + return value; + } + + public static SoapVersionEnum fromValue(String v) { + for (SoapVersionEnum c : SoapVersionEnum.values()) { + if (c.value.equals(v)) { + return c; + } + } + throw new IllegalArgumentException(v); + } + +} diff --git a/exposure-engine/common/src/main/java/com/alu/e3/data/model/enumeration/StatusType.java b/exposure-engine/common/src/main/java/com/alu/e3/data/model/enumeration/StatusType.java new file mode 100644 index 0000000..0f7281b --- /dev/null +++ b/exposure-engine/common/src/main/java/com/alu/e3/data/model/enumeration/StatusType.java @@ -0,0 +1,25 @@ +/** + * Copyright © 2012 Alcatel-Lucent. + * + * See the NOTICE file distributed with this work for additional + * information regarding copyright ownership. + * Licensed to you 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 com.alu.e3.data.model.enumeration; + +public enum StatusType { + ACTIVE, + INACTIVE, + PENDING +} diff --git a/exposure-engine/common/src/main/java/com/alu/e3/data/model/enumeration/TLSMode.java b/exposure-engine/common/src/main/java/com/alu/e3/data/model/enumeration/TLSMode.java new file mode 100644 index 0000000..a460dcc --- /dev/null +++ b/exposure-engine/common/src/main/java/com/alu/e3/data/model/enumeration/TLSMode.java @@ -0,0 +1,24 @@ +/** + * Copyright © 2012 Alcatel-Lucent. + * + * See the NOTICE file distributed with this work for additional + * information regarding copyright ownership. + * Licensed to you 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 com.alu.e3.data.model.enumeration; + +public enum TLSMode { + ONE_WAY, + TWO_WAY +} diff --git a/exposure-engine/common/src/main/java/com/alu/e3/data/model/sub/APIContext.java b/exposure-engine/common/src/main/java/com/alu/e3/data/model/sub/APIContext.java new file mode 100644 index 0000000..9e50b69 --- /dev/null +++ b/exposure-engine/common/src/main/java/com/alu/e3/data/model/sub/APIContext.java @@ -0,0 +1,132 @@ +/** + * Copyright © 2012 Alcatel-Lucent. + * + * See the NOTICE file distributed with this work for additional + * information regarding copyright ownership. + * Licensed to you 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 com.alu.e3.data.model.sub; + +import java.io.Serializable; +import java.util.ArrayList; +import java.util.List; + +import com.alu.e3.data.model.enumeration.LoadBalancingType; +import com.alu.e3.data.model.enumeration.StatusType; + +public class APIContext implements Serializable { + /** + * + */ + private static final long serialVersionUID = 7629408427358132353L; + + private String id; + private boolean defaultContext; + private StatusType status; + private LoadBalancing loadBalancing; + private List targetHosts; + private int maxRateLimitTPSThreshold; + private float maxRateLimitTPSWarning; + private int maxRateLimitTPMThreshold; + private float maxRateLimitTPMWarning; + private transient Integer _REAL_maxRateLimitTPSWarning; + private transient Integer _REAL_maxRateLimitTPMWarning; + + private int bucketId; + + private int contextId; + + public String getId() { + return id; + } + public void setId(String id) { + this.id = id; + } + public boolean isDefaultContext() { + return defaultContext; + } + public void setDefaultContext(boolean defaultContext) { + this.defaultContext = defaultContext; + } + + public StatusType getStatus() { + return status; + } + public void setStatus(StatusType status) { + this.status = status; + } + public LoadBalancing getLoadBalancing() { + if(loadBalancing == null) { + loadBalancing = new LoadBalancing(); + loadBalancing.setLoadBalancingType(LoadBalancingType.ROUND_ROBIN); + } + + return loadBalancing; + } + public void setLoadBalancing(LoadBalancing loadBalancing) { + this.loadBalancing = loadBalancing; + } + public List getTargetHosts() { + if(targetHosts==null) targetHosts = new ArrayList(); + return targetHosts; + } + public Integer getMaxRateLimitTPSThreshold() { + return maxRateLimitTPSThreshold; + } + public void setMaxRateLimitTPSThreshold(int maxRateLimitTPSThreshold) { + this.maxRateLimitTPSThreshold = maxRateLimitTPSThreshold; + } + public float getMaxRateLimitTPSWarning() { + return maxRateLimitTPSWarning; + } + public void setMaxRateLimitTPSWarning(float maxRateLimitTPSWarning) { + this.maxRateLimitTPSWarning = maxRateLimitTPSWarning; + } + public int getMaxRateLimitTPMThreshold() { + return maxRateLimitTPMThreshold; + } + public void setMaxRateLimitTPMThreshold(int maxRateLimitTPMThreshold) { + this.maxRateLimitTPMThreshold = maxRateLimitTPMThreshold; + } + public float getMaxRateLimitTPMWarning() { + return maxRateLimitTPMWarning; + } + public void setMaxRateLimitTPMWarning(float maxRateLimitTPMWarning) { + this.maxRateLimitTPMWarning = maxRateLimitTPMWarning; + } + + public int getBucketId() { + return bucketId; + } + public int getContextId() { + return contextId; + } + public void setBucketId(int bucketId) { + this.bucketId = bucketId; + } + public void setContextId(int contextId) { + this.contextId = contextId; + } + + public int get_REAL_maxRateLimitTPSWarning() { + if (_REAL_maxRateLimitTPSWarning==null) _REAL_maxRateLimitTPSWarning = Math.round((maxRateLimitTPSWarning/100.0f)*maxRateLimitTPSThreshold) ; + return _REAL_maxRateLimitTPSWarning; + } + + public int get_REAL_maxRateLimitTPMWarning() { + if (_REAL_maxRateLimitTPMWarning==null) _REAL_maxRateLimitTPMWarning = Math.round((maxRateLimitTPMWarning/100.0f)*maxRateLimitTPMThreshold) ; + return _REAL_maxRateLimitTPMWarning; + } + +} diff --git a/exposure-engine/common/src/main/java/com/alu/e3/data/model/sub/ApiIds.java b/exposure-engine/common/src/main/java/com/alu/e3/data/model/sub/ApiIds.java new file mode 100644 index 0000000..5004fc0 --- /dev/null +++ b/exposure-engine/common/src/main/java/com/alu/e3/data/model/sub/ApiIds.java @@ -0,0 +1,76 @@ +/** + * Copyright © 2012 Alcatel-Lucent. + * + * See the NOTICE file distributed with this work for additional + * information regarding copyright ownership. + * Licensed to you 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 com.alu.e3.data.model.sub; + +import java.io.Serializable; + +public class ApiIds implements Serializable { + + /** + * + */ + private static final long serialVersionUID = 3466986220094495971L; + + private int apiContextId; + + private String apiContextName; + + private int apiBucketId; + + private boolean statusActive; + + public ApiIds(String apiContextName, int apiContextId, int apiBucketId, boolean statusActive) { + this.apiContextName = apiContextName; + this.apiContextId = apiContextId; + this.apiBucketId = apiBucketId; + this.statusActive = statusActive; + } + + public int getApiBucketId() { + return apiBucketId; + } + + public int getApiContextId() { + return apiContextId; + } + + public String getApiContextName() { + return apiContextName; + } + + public void setApiBucketId(int apiBucketId) { + this.apiBucketId = apiBucketId; + } + + public void setApiContextId(int apiContextId) { + this.apiContextId = apiContextId; + } + + public void setApiContextName(String apiContextName) { + this.apiContextName = apiContextName; + } + + public boolean isStatusActive() { + return statusActive; + } + + public void setStatusActive(boolean statusActive) { + this.statusActive = statusActive; + } +} diff --git a/exposure-engine/common/src/main/java/com/alu/e3/data/model/sub/AuthIds.java b/exposure-engine/common/src/main/java/com/alu/e3/data/model/sub/AuthIds.java new file mode 100644 index 0000000..8ea475d --- /dev/null +++ b/exposure-engine/common/src/main/java/com/alu/e3/data/model/sub/AuthIds.java @@ -0,0 +1,87 @@ +/** + * Copyright © 2012 Alcatel-Lucent. + * + * See the NOTICE file distributed with this work for additional + * information regarding copyright ownership. + * Licensed to you 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 com.alu.e3.data.model.sub; + +import java.io.Serializable; + +public class AuthIds implements Serializable { + + /** + * + */ + private static final long serialVersionUID = 6092067815025057485L; + + private String policyId; + + private int policyContextId; + + private int policyBucketId; + + private boolean statusActive; + + private String bucketId; + + public AuthIds(String policyId, String bucketId, int policyContextId, int policyBucketId, boolean statusActive) { + this.policyId = policyId; + this.policyContextId = policyContextId; + this.policyBucketId = policyBucketId; + this.statusActive = statusActive; + this.bucketId = bucketId; + } + + public int getPolicyBucketId() { + return policyBucketId; + } + + public int getPolicyContextId() { + return policyContextId; + } + + public String getPolicyId() { + return policyId; + } + + public String getBucketId() { + return bucketId; + } + + public void setPolicyBucketId(int policyBucketId) { + this.policyBucketId = policyBucketId; + } + + public void setPolicyContextId(int policyContextId) { + this.policyContextId = policyContextId; + } + + public void setPolicyId(String policyId) { + this.policyId = policyId; + } + + public void setBucketId(String bucketId) { + this.bucketId = bucketId; + } + + public boolean isStatusActive() { + return statusActive; + } + + public void setStatusActive(boolean statusActive) { + this.statusActive = statusActive; + } +} diff --git a/exposure-engine/common/src/main/java/com/alu/e3/data/model/sub/ConnectionParameters.java b/exposure-engine/common/src/main/java/com/alu/e3/data/model/sub/ConnectionParameters.java new file mode 100644 index 0000000..9464ddb --- /dev/null +++ b/exposure-engine/common/src/main/java/com/alu/e3/data/model/sub/ConnectionParameters.java @@ -0,0 +1,62 @@ +/** + * Copyright © 2012 Alcatel-Lucent. + * + * See the NOTICE file distributed with this work for additional + * information regarding copyright ownership. + * Licensed to you 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 com.alu.e3.data.model.sub; + +import java.io.Serializable; + +public class ConnectionParameters implements Serializable { + + private static final long serialVersionUID = 8854660312017153502L; + + private static final int DEFAULT_MAX_CONNECTIONS_PER_ROUTE = 20; // Taken from org.apache.camel.component.http4.HttpComponent + private static final int DEFAULT_CONNECTION_TIMEOUT = 0; //taken from org.apache.http.params.HttpConnectionParams + private static final int DEFAULT_SOCKET_TIMEOUT = 0; //taken from org.apache.http.params.HttpConnectionParams + + private Integer maxConnections = null; + private Integer connectionTimeout = null; + private Integer socketTimeout = null; + + public ConnectionParameters(){ +// this.maxConnections = DEFAULT_MAX_CONNECTIONS_PER_ROUTE; +// this.connectionTimeout = DEFAULT_CONNECTION_TIMEOUT; +// this.socketTimeout = DEFAULT_SOCKET_TIMEOUT; + } + + public Integer getMaxConnections() { + return maxConnections; + } + public void setMaxConnections(Integer maxConnections) { + this.maxConnections = maxConnections; + } + + public Integer getConnectionTimeout() { + return connectionTimeout; + } + public void setConnectionTimeout(Integer connectionTimeout) { + this.connectionTimeout = connectionTimeout; + } + + public Integer getSocketTimeout() { + return socketTimeout; + } + public void setSocketTimeout(Integer socketTimeout) { + this.socketTimeout = socketTimeout; + } + +} diff --git a/exposure-engine/common/src/main/java/com/alu/e3/data/model/sub/Context.java b/exposure-engine/common/src/main/java/com/alu/e3/data/model/sub/Context.java new file mode 100644 index 0000000..09cd293 --- /dev/null +++ b/exposure-engine/common/src/main/java/com/alu/e3/data/model/sub/Context.java @@ -0,0 +1,99 @@ +/** + * Copyright © 2012 Alcatel-Lucent. + * + * See the NOTICE file distributed with this work for additional + * information regarding copyright ownership. + * Licensed to you 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 com.alu.e3.data.model.sub; + +import java.io.Serializable; +import java.util.Date; + +import com.alu.e3.data.model.enumeration.StatusType; + +public class Context implements Serializable { + /** + * + */ + private static final long serialVersionUID = -5290652101508735198L; + + private String id; + private StatusType status; + private Counter quotaPerDay; + private Counter quotaPerWeek; + private Counter quotaPerMonth; + private Counter rateLimitPerSecond; + private Counter rateLimitPerMinute; + private Date createdDate; + + private int contextId; + + public String getId() { + return id; + } + public void setId(String id) { + this.id = id; + } + public StatusType getStatus() { + return status; + } + public void setStatus(StatusType status) { + this.status = status; + } + public Counter getQuotaPerDay() { + return quotaPerDay; + } + public void setQuotaPerDay(Counter quotaPerDay) { + this.quotaPerDay = quotaPerDay; + } + public Counter getQuotaPerMonth() { + return quotaPerMonth; + } + public void setQuotaPerMonth(Counter quotaPerMonth) { + this.quotaPerMonth = quotaPerMonth; + } + public Counter getQuotaPerWeek() { + return quotaPerWeek; + } + public void setQuotaPerWeek(Counter quotaPerWeek) { + this.quotaPerWeek = quotaPerWeek; + } + public Counter getRateLimitPerMinute() { + return rateLimitPerMinute; + } + public void setRateLimitPerMinute(Counter rateLimitPerMinute) { + this.rateLimitPerMinute = rateLimitPerMinute; + } + public Counter getRateLimitPerSecond() { + return rateLimitPerSecond; + } + public void setRateLimitPerSecond(Counter rateLimitPerSecond) { + this.rateLimitPerSecond = rateLimitPerSecond; + } + + public void setContextId(int contextId) { + this.contextId = contextId; + } + + public int getContextId() { + return contextId; + } + public Date getCreatedDate() { + return createdDate; + } + public void setCreatedDate(Date createdDate) { + this.createdDate = createdDate; + } +} diff --git a/exposure-engine/common/src/main/java/com/alu/e3/data/model/sub/ContextWrapper.java b/exposure-engine/common/src/main/java/com/alu/e3/data/model/sub/ContextWrapper.java new file mode 100644 index 0000000..5936de5 --- /dev/null +++ b/exposure-engine/common/src/main/java/com/alu/e3/data/model/sub/ContextWrapper.java @@ -0,0 +1,56 @@ +/** + * Copyright © 2012 Alcatel-Lucent. + * + * See the NOTICE file distributed with this work for additional + * information regarding copyright ownership. + * Licensed to you 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 com.alu.e3.data.model.sub; + +import java.io.Serializable; + +public class ContextWrapper implements Serializable { + + /** + * + */ + private static final long serialVersionUID = 8844222238577803598L; + + private Context policyContext; + private APIContext apiContext; + + public ContextWrapper(Context context) { + policyContext = context; + } + + public ContextWrapper(APIContext context) { + apiContext = context; + } + + public APIContext getApiContext() { + return apiContext; + } + + public Context getPolicyContext() { + return policyContext; + } + + public void setApiContext(APIContext apiContext) { + this.apiContext = apiContext; + } + + public void setPolicyContext(Context policyContext) { + this.policyContext = policyContext; + } +} diff --git a/exposure-engine/common/src/main/java/com/alu/e3/data/model/sub/Counter.java b/exposure-engine/common/src/main/java/com/alu/e3/data/model/sub/Counter.java new file mode 100644 index 0000000..7363390 --- /dev/null +++ b/exposure-engine/common/src/main/java/com/alu/e3/data/model/sub/Counter.java @@ -0,0 +1,87 @@ +/** + * Copyright © 2012 Alcatel-Lucent. + * + * See the NOTICE file distributed with this work for additional + * information regarding copyright ownership. + * Licensed to you 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 com.alu.e3.data.model.sub; + +import java.io.Serializable; + +import com.alu.e3.common.E3Constant; + +import com.alu.e3.data.model.enumeration.ActionType; +import com.alu.e3.data.model.enumeration.StatusType; + +public class Counter implements Serializable { + /** + * + */ + private static final long serialVersionUID = -1931439800857840947L; + + private StatusType status; + private ActionType action; + private float warning; + private long threshold; + private transient Integer _REAL_warning; + + public Counter() { + + } + + public Counter(float warning, int threshold) { + this.warning = warning; + this.threshold = threshold; + this.status = StatusType.ACTIVE; + this.action = E3Constant.DEFAULT_ERROR_ACTION; + } + + public StatusType getStatus() { + return status; + } + + public void setStatus(StatusType status) { + this.status = status; + } + + public ActionType getAction() { + return action; + } + + public void setAction(ActionType action) { + this.action = action; + } + + public float getWarning() { + return warning; + } + + public void setWarning(float warning) { + this.warning = warning; + } + + public long getThreshold() { + return threshold; + } + + public void setThreshold(long threshold) { + this.threshold = threshold; + } + + public Integer get_REAL_warning() { + if (_REAL_warning==null) _REAL_warning = Math.round((warning/100.0f)*threshold); + return _REAL_warning; + } +} diff --git a/exposure-engine/common/src/main/java/com/alu/e3/data/model/sub/FailOver.java b/exposure-engine/common/src/main/java/com/alu/e3/data/model/sub/FailOver.java new file mode 100644 index 0000000..db59fcf --- /dev/null +++ b/exposure-engine/common/src/main/java/com/alu/e3/data/model/sub/FailOver.java @@ -0,0 +1,36 @@ +/** + * Copyright © 2012 Alcatel-Lucent. + * + * See the NOTICE file distributed with this work for additional + * information regarding copyright ownership. + * Licensed to you 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 com.alu.e3.data.model.sub; + +import java.io.Serializable; + +public class FailOver implements Serializable { + + private static final long serialVersionUID = 7760805584383200721L; + + private String onResponseCode; + + public String getOnResponseCode() { + return this.onResponseCode; + } + + public void setOnResponseCode(String onResponseCode) { + this.onResponseCode = onResponseCode; + } +} diff --git a/exposure-engine/common/src/main/java/com/alu/e3/data/model/sub/ForwardProxy.java b/exposure-engine/common/src/main/java/com/alu/e3/data/model/sub/ForwardProxy.java new file mode 100644 index 0000000..e42b095 --- /dev/null +++ b/exposure-engine/common/src/main/java/com/alu/e3/data/model/sub/ForwardProxy.java @@ -0,0 +1,79 @@ +/** + * Copyright © 2012 Alcatel-Lucent. + * + * See the NOTICE file distributed with this work for additional + * information regarding copyright ownership. + * Licensed to you 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 com.alu.e3.data.model.sub; + +import java.io.Serializable; + +public class ForwardProxy implements Serializable { + + private static final long serialVersionUID = 6290190762467317009L; + + private String proxyHost; + private String proxyPort; + private String proxyUser; + private String proxyPass; + + public String getProxyHost() { + return proxyHost; + } + public void setProxyHost(String value) { + this.proxyHost = value; + } + + public String getProxyPort() { + return proxyPort; + } + public void setProxyPort(String value) { + this.proxyPort = value; + } + + public String getProxyUser() { + return proxyUser; + } + public void setProxyUser(String value) { + this.proxyUser = value; + } + + public String getProxyPass() { + return proxyPass; + } + public void setProxyPass(String value) { + this.proxyPass = value; + } + + public String serialize() { + return proxyHost + "#" + proxyPort + "#" + proxyUser + "#" + proxyPass; + } + public static ForwardProxy deserialize(String s) { + String[] res = s.split("#", 4); + if (res == null) + return null; + + if (res.length < 4) + return null; + + ForwardProxy f = new ForwardProxy(); + f.setProxyHost(res[0]); + f.setProxyPort(res[1]); + f.setProxyUser(res[2]); + f.setProxyPass(res[3]); + + return f; + } +} diff --git a/exposure-engine/common/src/main/java/com/alu/e3/data/model/sub/HTTPSType.java b/exposure-engine/common/src/main/java/com/alu/e3/data/model/sub/HTTPSType.java new file mode 100644 index 0000000..4e5900e --- /dev/null +++ b/exposure-engine/common/src/main/java/com/alu/e3/data/model/sub/HTTPSType.java @@ -0,0 +1,55 @@ +/** + * Copyright © 2012 Alcatel-Lucent. + * + * See the NOTICE file distributed with this work for additional + * information regarding copyright ownership. + * Licensed to you 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 com.alu.e3.data.model.sub; + +import java.io.Serializable; + +import com.alu.e3.data.model.enumeration.TLSMode; + +public class HTTPSType implements Serializable { + /** + * + */ + private static final long serialVersionUID = -1781721795422518456L; + + protected boolean enabled; + + protected TLSMode tlsMode; + + + public boolean isEnabled() { + return enabled; + } + + + public void setEnabled(boolean enabled) { + this.enabled = enabled; + } + + + public TLSMode getTlsMode() { + return tlsMode; + } + + + public void setTlsMode(TLSMode tlsMode) { + this.tlsMode = tlsMode; + } + +} diff --git a/exposure-engine/common/src/main/java/com/alu/e3/data/model/sub/HeaderTransformation.java b/exposure-engine/common/src/main/java/com/alu/e3/data/model/sub/HeaderTransformation.java new file mode 100644 index 0000000..3dc9a2c --- /dev/null +++ b/exposure-engine/common/src/main/java/com/alu/e3/data/model/sub/HeaderTransformation.java @@ -0,0 +1,71 @@ +/** + * Copyright © 2012 Alcatel-Lucent. + * + * See the NOTICE file distributed with this work for additional + * information regarding copyright ownership. + * Licensed to you 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 com.alu.e3.data.model.sub; + +import java.io.Serializable; + +import com.alu.e3.data.model.enumeration.HeaderTransformationAction; +import com.alu.e3.data.model.enumeration.HeaderTransformationType; + +public class HeaderTransformation implements Serializable { + + /** + * + */ + private static final long serialVersionUID = 1564338343179213740L; + + protected String name; + protected String property; + protected String value; + protected HeaderTransformationType type; + protected HeaderTransformationAction action; + + public String getName() { + return name; + } + public void setName(String name) { + this.name = name; + } + public String getProperty() { + return property; + } + public void setProperty(String property) { + this.property = property; + } + public HeaderTransformationType getType() { + return type; + } + public void setType(HeaderTransformationType type) { + this.type = type; + } + public HeaderTransformationAction getAction() { + return action; + } + public void setAction(HeaderTransformationAction action) { + this.action = action; + } + public String getValue() { + return this.value; + } + public void setValue(String value2) { + this.value = value2; + } + + +} diff --git a/exposure-engine/common/src/main/java/com/alu/e3/data/model/sub/LoadBalancing.java b/exposure-engine/common/src/main/java/com/alu/e3/data/model/sub/LoadBalancing.java new file mode 100644 index 0000000..47e363a --- /dev/null +++ b/exposure-engine/common/src/main/java/com/alu/e3/data/model/sub/LoadBalancing.java @@ -0,0 +1,53 @@ +/** + * Copyright © 2012 Alcatel-Lucent. + * + * See the NOTICE file distributed with this work for additional + * information regarding copyright ownership. + * Licensed to you 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 com.alu.e3.data.model.sub; + +import java.io.Serializable; + +import com.alu.e3.data.model.enumeration.LoadBalancingType; + +public class LoadBalancing implements Serializable { + + private static final long serialVersionUID = 8407909394763675964L; + + private LoadBalancingType loadBalancingType = LoadBalancingType.ROUND_ROBIN; + private TargetHealthCheck targetHealthCheck; + private FailOver failOver; + + public LoadBalancingType getLoadBalancingType() { + return loadBalancingType; + } + public void setLoadBalancingType(LoadBalancingType loadBalancingType) { + this.loadBalancingType = loadBalancingType; + } + + public TargetHealthCheck getTargetHealthCheck() { + return targetHealthCheck; + } + public void setTargetHealthCheck(TargetHealthCheck targetHealthCheck) { + this.targetHealthCheck = targetHealthCheck; + } + + public FailOver getFailOver() { + return failOver; + } + public void setFailOver(FailOver failOver) { + this.failOver = failOver; + } +} diff --git a/exposure-engine/common/src/main/java/com/alu/e3/data/model/sub/QuotaRLBucket.java b/exposure-engine/common/src/main/java/com/alu/e3/data/model/sub/QuotaRLBucket.java new file mode 100644 index 0000000..8e5f895 --- /dev/null +++ b/exposure-engine/common/src/main/java/com/alu/e3/data/model/sub/QuotaRLBucket.java @@ -0,0 +1,57 @@ +/** + * Copyright © 2012 Alcatel-Lucent. + * + * See the NOTICE file distributed with this work for additional + * information regarding copyright ownership. + * Licensed to you 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 com.alu.e3.data.model.sub; + +import java.io.Serializable; +import java.util.ArrayList; +import java.util.List; + +public class QuotaRLBucket implements Serializable { + + /** + * + */ + private static final long serialVersionUID = -7985922344329398444L; + + private String id; + private List authIds; + + private int bucketId; + + public String getId() { + return id; + } + + public void setId(String id) { + this.id = id; + } + + public List getAuthIds() { + if (authIds==null) authIds = new ArrayList(); + return authIds; + } + + public int getBucketId() { + return bucketId; + } + + public void setBucketId(int bucketId) { + this.bucketId = bucketId; + } +} diff --git a/exposure-engine/common/src/main/java/com/alu/e3/data/model/sub/ResourceItem.java b/exposure-engine/common/src/main/java/com/alu/e3/data/model/sub/ResourceItem.java new file mode 100644 index 0000000..50f9cf2 --- /dev/null +++ b/exposure-engine/common/src/main/java/com/alu/e3/data/model/sub/ResourceItem.java @@ -0,0 +1,107 @@ +/** + * Copyright © 2012 Alcatel-Lucent. + * + * See the NOTICE file distributed with this work for additional + * information regarding copyright ownership. + * Licensed to you 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. + */ +// +// This file was generated by the JavaTM Architecture for XML Binding(JAXB) Reference Implementation, vhudson-jaxb-ri-2.2-27 +// See http://java.sun.com/xml/jaxb +// Any modifications to this file will be lost upon recompilation of the source schema. +// Generated on: 2012.06.05 at 04:21:54 PM CEST +// + + +package com.alu.e3.data.model.sub; + +import java.io.Serializable; + + + +public class ResourceItem implements Serializable{ + + + /** + * + */ + private static final long serialVersionUID = 6285596883835909980L; + protected String name; + protected String grammar; + protected boolean isMain; + + + /** + * Gets the value of the name property. + * + * @return + * possible object is + * {@link String } + * + */ + public String getName() { + return name; + } + + /** + * Sets the value of the name property. + * + * @param value + * allowed object is + * {@link String } + * + */ + public void setName(String value) { + this.name = value; + } + + /** + * Gets the value of the grammar property. + * + * @return + * possible object is + * byte[] + */ + public String getGrammar() { + return grammar; + } + + /** + * Sets the value of the grammar property. + * + * @param value + * allowed object is + * byte[] + */ + public void setGrammar(String value) { + this.grammar = value; + } + + /** + * Gets the value of the isMain property. + * + */ + public boolean isIsMain() { + return isMain; + } + + /** + * Sets the value of the isMain property. + * + */ + public void setIsMain(boolean value) { + this.isMain = value; + } + +} diff --git a/exposure-engine/common/src/main/java/com/alu/e3/data/model/sub/SBAuthentication.java b/exposure-engine/common/src/main/java/com/alu/e3/data/model/sub/SBAuthentication.java new file mode 100644 index 0000000..91928a9 --- /dev/null +++ b/exposure-engine/common/src/main/java/com/alu/e3/data/model/sub/SBAuthentication.java @@ -0,0 +1,46 @@ +/** + * Copyright © 2012 Alcatel-Lucent. + * + * See the NOTICE file distributed with this work for additional + * information regarding copyright ownership. + * Licensed to you 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 com.alu.e3.data.model.sub; + +import java.io.Serializable; +import java.util.LinkedHashMap; +import java.util.Map; + +public class SBAuthentication implements Serializable { + + /** + * + */ + private static final long serialVersionUID = 1701827080598101905L; + + private String type; + private Map keys; + + public String getType() { + return type; + } + public void setType(String type) { + this.type = type; + } + public Map getKeys() { + if (keys==null) keys = new LinkedHashMap(); + return keys; + } + +} diff --git a/exposure-engine/common/src/main/java/com/alu/e3/data/model/sub/TargetHealthCheck.java b/exposure-engine/common/src/main/java/com/alu/e3/data/model/sub/TargetHealthCheck.java new file mode 100644 index 0000000..2618f2c --- /dev/null +++ b/exposure-engine/common/src/main/java/com/alu/e3/data/model/sub/TargetHealthCheck.java @@ -0,0 +1,37 @@ +/** + * Copyright © 2012 Alcatel-Lucent. + * + * See the NOTICE file distributed with this work for additional + * information regarding copyright ownership. + * Licensed to you 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 com.alu.e3.data.model.sub; + +import java.io.Serializable; + + +public class TargetHealthCheck implements Serializable { + + private static final long serialVersionUID = 4015291207124949694L; + + protected String type; + + public String getType() { + return type; + } + + public void setType(String type) { + this.type = type; + } +} diff --git a/exposure-engine/common/src/main/java/com/alu/e3/data/model/sub/TargetHost.java b/exposure-engine/common/src/main/java/com/alu/e3/data/model/sub/TargetHost.java new file mode 100644 index 0000000..f778ee5 --- /dev/null +++ b/exposure-engine/common/src/main/java/com/alu/e3/data/model/sub/TargetHost.java @@ -0,0 +1,72 @@ +/** + * Copyright © 2012 Alcatel-Lucent. + * + * See the NOTICE file distributed with this work for additional + * information regarding copyright ownership. + * Licensed to you 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 com.alu.e3.data.model.sub; + +import java.io.Serializable; + + +public class TargetHost implements Serializable { + /** + * + */ + private static final long serialVersionUID = -1781721810022518456L; + + private String url; + private String site; + private SBAuthentication authentication; + private ConnectionParameters connectionParameter; + private ForwardProxy forwardProxy; + + // Authentifcation per targetHost ! + + public String getUrl() { + return url; + } + public void setUrl(String url) { + this.url = url; + } + + public String getSite() { + return site; + } + + public void setSite(String site) { + this.site = site; + } + + public SBAuthentication getAuthentication() { + return authentication; + } + public void setAuthentication(SBAuthentication authentication) { + this.authentication = authentication; + } + + public ConnectionParameters getConnectionParameters() { + return connectionParameter; + } + public void setConnectionParameters(ConnectionParameters connectionParameter) { + this.connectionParameter = connectionParameter; + } + public ForwardProxy getForwardProxy() { + return forwardProxy; + } + public void setForwardProxy(ForwardProxy forwardProxy) { + this.forwardProxy = forwardProxy; + } +} diff --git a/exposure-engine/common/src/main/java/com/alu/e3/data/model/sub/TdrDynamicRule.java b/exposure-engine/common/src/main/java/com/alu/e3/data/model/sub/TdrDynamicRule.java new file mode 100644 index 0000000..47b55fa --- /dev/null +++ b/exposure-engine/common/src/main/java/com/alu/e3/data/model/sub/TdrDynamicRule.java @@ -0,0 +1,69 @@ +/** + * Copyright © 2012 Alcatel-Lucent. + * + * See the NOTICE file distributed with this work for additional + * information regarding copyright ownership. + * Licensed to you 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 com.alu.e3.data.model.sub; + +import java.io.Serializable; +import java.util.ArrayList; +import java.util.List; + +import com.alu.e3.data.model.ExtractFromType; + + +public class TdrDynamicRule implements Serializable { + + /** + * + */ + private static final long serialVersionUID = 6618904536647856203L; + + private List types; + private String tdrPropName; + private String httpHeaderName; + private ExtractFromType extractFrom; + + public List getTypes() { + if (types==null) types = new ArrayList(); + return types; + } + + public String getTdrPropName() { + return tdrPropName; + } + public void setTdrPropName(String tdrPropName) { + this.tdrPropName = tdrPropName; + } + + public String getHttpHeaderName() { + return httpHeaderName; + } + public void setHttpHeaderName(String httpHeaderName) { + this.httpHeaderName = httpHeaderName; + } + + public ExtractFromType getExtractFrom() { + return extractFrom; + } + + public void setExtractFrom(ExtractFromType extractFrom) { + this.extractFrom = extractFrom; + } + + + +} diff --git a/exposure-engine/common/src/main/java/com/alu/e3/data/model/sub/TdrGenerationRule.java b/exposure-engine/common/src/main/java/com/alu/e3/data/model/sub/TdrGenerationRule.java new file mode 100644 index 0000000..4abf94e --- /dev/null +++ b/exposure-engine/common/src/main/java/com/alu/e3/data/model/sub/TdrGenerationRule.java @@ -0,0 +1,42 @@ +/** + * Copyright © 2012 Alcatel-Lucent. + * + * See the NOTICE file distributed with this work for additional + * information regarding copyright ownership. + * Licensed to you 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 com.alu.e3.data.model.sub; + +import java.io.Serializable; +import java.util.ArrayList; +import java.util.List; + +public class TdrGenerationRule implements Serializable { + /** + * + */ + private static final long serialVersionUID = 226810573258866391L; + + private List staticRules; + private List dynamicRules; + + public List getDynamicRules() { + if (dynamicRules==null) dynamicRules = new ArrayList(); + return dynamicRules; + } + public List getStaticRules() { + if (staticRules==null) staticRules = new ArrayList(); + return staticRules; + } +} diff --git a/exposure-engine/common/src/main/java/com/alu/e3/data/model/sub/TdrStaticRule.java b/exposure-engine/common/src/main/java/com/alu/e3/data/model/sub/TdrStaticRule.java new file mode 100644 index 0000000..ac79822 --- /dev/null +++ b/exposure-engine/common/src/main/java/com/alu/e3/data/model/sub/TdrStaticRule.java @@ -0,0 +1,63 @@ +/** + * Copyright © 2012 Alcatel-Lucent. + * + * See the NOTICE file distributed with this work for additional + * information regarding copyright ownership. + * Licensed to you 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 com.alu.e3.data.model.sub; + +import java.io.Serializable; +import java.util.ArrayList; +import java.util.List; + +public class TdrStaticRule implements Serializable { + + /** + * + */ + private static final long serialVersionUID = -8065677343878901269L; + + private List types; + private String tdrPropName; + private String value; + private String propertyName; + + public String getPropertyName() { + return propertyName; + } + + public void setPropertyName(String propertyName) { + this.propertyName = propertyName; + } + + public List getTypes() { + if (types==null) types = new ArrayList(); + return types; + } + + public String getValue() { + return value; + } + public void setValue(String value) { + this.value = value; + } + + public String getTdrPropName() { + return tdrPropName; + } + public void setTdrPropName(String tdrPropName) { + this.tdrPropName = tdrPropName; + } +} diff --git a/exposure-engine/common/src/main/java/com/alu/e3/data/model/sub/Validation.java b/exposure-engine/common/src/main/java/com/alu/e3/data/model/sub/Validation.java new file mode 100644 index 0000000..097dbb0 --- /dev/null +++ b/exposure-engine/common/src/main/java/com/alu/e3/data/model/sub/Validation.java @@ -0,0 +1,203 @@ +/** + * Copyright © 2012 Alcatel-Lucent. + * + * See the NOTICE file distributed with this work for additional + * information regarding copyright ownership. + * Licensed to you 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 com.alu.e3.data.model.sub; + +import java.io.Serializable; +import java.util.ArrayList; +import java.util.List; + +import com.alu.e3.data.model.enumeration.SchemaValidationEnum; +import com.alu.e3.data.model.enumeration.SoapVersionEnum; + +public class Validation implements Serializable { + + private static final long serialVersionUID = 1122965495210674643L; + /** + * + */ + protected Validation.Schema schema; + protected Validation.Xml xml; + protected Validation.Soap soap; + + /** + * Gets the value of the schema property. + * + * @return possible object is {@link Validation.Schema } + * + */ + public Validation.Schema getSchema() { + return schema; + } + + /** + * Sets the value of the schema property. + * + * @param value + * allowed object is {@link Validation.Schema } + * + */ + public void setSchema(Validation.Schema value) { + this.schema = value; + } + + /** + * Gets the value of the xml property. + * + * @return possible object is {@link Validation.Xml } + * + */ + public Validation.Xml getXml() { + return xml; + } + + /** + * Sets the value of the xml property. + * + * @param value + * allowed object is {@link Validation.Xml } + * + */ + public void setXml(Validation.Xml value) { + this.xml = value; + } + + /** + * Gets the value of the soap property. + * + * @return possible object is {@link Validation.Soap } + * + */ + public Validation.Soap getSoap() { + return soap; + } + + /** + * Sets the value of the soap property. + * + * @param value + * allowed object is {@link Validation.Soap } + * + */ + public void setSoap(Validation.Soap value) { + this.soap = value; + } + + public static class Schema implements Serializable { + + /** + * + */ + private static final long serialVersionUID = 5088762570666929286L; + + public Schema(SchemaValidationEnum type) { + super(); + this.type = type; + } + + public Schema() { + super(); + } + + protected SchemaValidationEnum type; + protected List resourcesList; + + /** + * Gets the value of the type property. + * + * @return possible object is {@link SchemaValidationEnum } + * + */ + public SchemaValidationEnum getType() { + return type; + } + + /** + * Sets the value of the type property. + * + * @param value + * allowed object is {@link SchemaValidationEnum } + * + */ + public void setType(SchemaValidationEnum value) { + this.type = value; + } + + public List getResourcesList() { + if (resourcesList == null) { + resourcesList = new ArrayList(); + } + return this.resourcesList; + } + + public void setResourcesList(List resourcesList) { + this.resourcesList = resourcesList; + } + + } + + public static class Soap implements Serializable { + + /** + * + */ + private static final long serialVersionUID = 5085689793572938225L; + protected SoapVersionEnum version; + + public Soap(SoapVersionEnum version) { + super(); + this.version = version; + } + + public Soap() { + super(); + } + + /** + * Gets the value of the version property. + * + * @return possible object is {@link String } + * + */ + public SoapVersionEnum getVersion() { + return version; + } + + /** + * Sets the value of the version property. + * + * @param value + * allowed object is {@link String } + * + */ + public void setVersion(SoapVersionEnum value) { + this.version = value; + } + + } + + public static class Xml implements Serializable { + + /** + * + */ + private static final long serialVersionUID = -4709611049934805035L; + + } + +} diff --git a/exposure-engine/common/src/main/java/com/alu/e3/data/topology/IInstanceListener.java b/exposure-engine/common/src/main/java/com/alu/e3/data/topology/IInstanceListener.java new file mode 100644 index 0000000..5c8941c --- /dev/null +++ b/exposure-engine/common/src/main/java/com/alu/e3/data/topology/IInstanceListener.java @@ -0,0 +1,26 @@ +/** + * Copyright © 2012 Alcatel-Lucent. + * + * See the NOTICE file distributed with this work for additional + * information regarding copyright ownership. + * Licensed to you 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 com.alu.e3.data.topology; + +public interface IInstanceListener { + + void instanceAdded(InstanceEvent event); + void instanceRemoved(InstanceEvent event); + +} diff --git a/exposure-engine/common/src/main/java/com/alu/e3/data/topology/InstanceEvent.java b/exposure-engine/common/src/main/java/com/alu/e3/data/topology/InstanceEvent.java new file mode 100644 index 0000000..9f9d1cf --- /dev/null +++ b/exposure-engine/common/src/main/java/com/alu/e3/data/topology/InstanceEvent.java @@ -0,0 +1,54 @@ +/** + * Copyright © 2012 Alcatel-Lucent. + * + * See the NOTICE file distributed with this work for additional + * information regarding copyright ownership. + * Licensed to you 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 com.alu.e3.data.topology; + +import com.alu.e3.data.model.Instance; + +public class InstanceEvent { + + Instance instance; + + public InstanceEvent(Instance inst) { + this.instance = inst; + } + + public String getType() { + return instance.getType(); + } + + public String getIp() { + return instance.getInternalIP(); + } + + public String getPort() { + return instance.getPort(); + } + + public String getUser() { + return instance.getUser(); + } + + public String getPwd() { + return instance.getPassword(); + } + + public Instance getInstance() { + return instance; + } +} diff --git a/exposure-engine/common/src/main/java/com/alu/e3/rate/model/ApiCall.java b/exposure-engine/common/src/main/java/com/alu/e3/rate/model/ApiCall.java new file mode 100644 index 0000000..20b3e05 --- /dev/null +++ b/exposure-engine/common/src/main/java/com/alu/e3/rate/model/ApiCall.java @@ -0,0 +1,43 @@ +/** + * Copyright © 2012 Alcatel-Lucent. + * + * See the NOTICE file distributed with this work for additional + * information regarding copyright ownership. + * Licensed to you 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 com.alu.e3.rate.model; + +public class ApiCall { + + public int bucketID; + public short apiID; + public long callTime; + public boolean callSuccess; + public boolean countedInLastPeriodMinute; + public boolean countedInLastPeriodSecond; + + + public ApiCall(int bucketID, long calltime) { + + this.bucketID=bucketID; + + this.callTime = calltime; + this.callSuccess = false; + this.countedInLastPeriodMinute = false; + this.countedInLastPeriodSecond = false; + } + + + +} diff --git a/exposure-engine/common/src/main/java/com/alu/e3/rate/model/GatewayQueueRate.java b/exposure-engine/common/src/main/java/com/alu/e3/rate/model/GatewayQueueRate.java new file mode 100644 index 0000000..fc8840c --- /dev/null +++ b/exposure-engine/common/src/main/java/com/alu/e3/rate/model/GatewayQueueRate.java @@ -0,0 +1,130 @@ +/** + * Copyright © 2012 Alcatel-Lucent. + * + * See the NOTICE file distributed with this work for additional + * information regarding copyright ownership. + * Licensed to you 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 com.alu.e3.rate.model; + +import java.io.Serializable; + +public class GatewayQueueRate implements Serializable { + + private static final long serialVersionUID = -3108794664269206723L; + + public int bucketID; + + public short localApiCallsInFirstPeriod; // all call OK + public short localApiSpeedInFirstPeriod; // all calls OK + KO + + public short localApiCallsInLastPeriodSecond; + public int localApiCallsInLastPeriodMinute; + + public GatewayQueueRate() + { + + } + + public GatewayQueueRate(int bucketID) + { + this.bucketID=bucketID; + + this.localApiCallsInFirstPeriod = 0; + this.localApiSpeedInFirstPeriod = 0; + this.localApiCallsInLastPeriodSecond = 0; + this.localApiCallsInLastPeriodMinute = 0; + } + + public boolean isReadyToRemove() + { + return ( (this.localApiCallsInFirstPeriod == 0) + && (this.localApiSpeedInFirstPeriod == 0) + && (this.localApiCallsInLastPeriodSecond == 0) + && (this.localApiCallsInLastPeriodMinute == 0) + ); + } + + /** + * @return the bucketID + */ + public int getBucketID() { + return bucketID; + } + + /** + * @param bucketID the bucketID to set + */ + public void setBucketID(int bucketID) { + this.bucketID = bucketID; + } + + /** + * @return the localApiCallsInFirstPeriod + */ + public short getLocalApiCallsInFirstPeriod() { + return localApiCallsInFirstPeriod; + } + + /** + * @param localApiCallsInFirstPeriod the localApiCallsInFirstPeriod to set + */ + public void setLocalApiCallsInFirstPeriod(short localApiCallsInFirstPeriod) { + this.localApiCallsInFirstPeriod = localApiCallsInFirstPeriod; + } + + /** + * @return the localApiSpeedInFirstPeriod + */ + public short getLocalApiSpeedInFirstPeriod() { + return localApiSpeedInFirstPeriod; + } + + /** + * @param localApiSpeedInFirstPeriod the localApiSpeedInFirstPeriod to set + */ + public void setLocalApiSpeedInFirstPeriod(short localApiSpeedInFirstPeriod) { + this.localApiSpeedInFirstPeriod = localApiSpeedInFirstPeriod; + } + + /** + * @return the localApiCallsInLastPeriodSecond + */ + public short getLocalApiCallsInLastPeriodSecond() { + return localApiCallsInLastPeriodSecond; + } + + /** + * @param localApiCallsInLastPeriodSecond the localApiCallsInLastPeriodSecond to set + */ + public void setLocalApiCallsInLastPeriodSecond( + short localApiCallsInLastPeriodSecond) { + this.localApiCallsInLastPeriodSecond = localApiCallsInLastPeriodSecond; + } + + /** + * @return the localApiCallsInLastPeriodMinute + */ + public int getLocalApiCallsInLastPeriodMinute() { + return localApiCallsInLastPeriodMinute; + } + + /** + * @param localApiCallsInLastPeriodMinute the localApiCallsInLastPeriodMinute to set + */ + public void setLocalApiCallsInLastPeriodMinute( + int localApiCallsInLastPeriodMinute) { + this.localApiCallsInLastPeriodMinute = localApiCallsInLastPeriodMinute; + } +} diff --git a/exposure-engine/common/src/main/java/com/alu/e3/rate/model/GatewayRate.java b/exposure-engine/common/src/main/java/com/alu/e3/rate/model/GatewayRate.java new file mode 100644 index 0000000..716774b --- /dev/null +++ b/exposure-engine/common/src/main/java/com/alu/e3/rate/model/GatewayRate.java @@ -0,0 +1,69 @@ +/** + * Copyright © 2012 Alcatel-Lucent. + * + * See the NOTICE file distributed with this work for additional + * information regarding copyright ownership. + * Licensed to you 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 com.alu.e3.rate.model; + +import java.io.Serializable; +import java.util.Date; + +public class GatewayRate implements Serializable { + + private static final long serialVersionUID = 2524122037873871500L; + + public int bucketID; + + public int localRateLimitSecond; + public int localRateLimitMinute; + public long localQuotaLimitDay; + public long localQuotaLimitWeek; + public long localQuotaLimitMonth; + + // TODO: use constant values instead of properties? + public short lifeTimeForlocalRateLimitSecond; + public int lifeTimeForlocalRateLimitMinute; + public int lifeTimeForlocalDailyQuota; + public int lifeTimeForlocalWeeklyQuota; + public long lifeTimeForlocalMonthlyQuota; + + public transient Date createdDate; + public transient Date nextMonthUpdate; + public transient Date nextWeekUpdate; + + public short localApiCallsSinceOneSecond; + public int localApiCallsSinceOneMinute; + public int localApiCallsSinceOneDay; + public int localApiCallsSinceOneWeek; + public long localApiCallsSinceOneMonth; + + public boolean initialized; // default limit has been set + + public GatewayRate(int bucketID) { + this.bucketID=bucketID; + + this.localRateLimitSecond=-1; + this.localRateLimitMinute=-1; + this.localQuotaLimitDay=-1; + this.localQuotaLimitWeek=-1; + this.localQuotaLimitMonth=-1; + } + + public GatewayRate(int bucketID, Date createdDate) { + this(bucketID); + this.createdDate = createdDate; + } +} diff --git a/exposure-engine/common/src/main/java/com/alu/e3/security/BaseStoreFileService.java b/exposure-engine/common/src/main/java/com/alu/e3/security/BaseStoreFileService.java new file mode 100644 index 0000000..673a7d6 --- /dev/null +++ b/exposure-engine/common/src/main/java/com/alu/e3/security/BaseStoreFileService.java @@ -0,0 +1,126 @@ +/** + * Copyright © 2012 Alcatel-Lucent. + * + * See the NOTICE file distributed with this work for additional + * information regarding copyright ownership. + * Licensed to you 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 com.alu.e3.security; + +import java.io.File; +import java.io.FileInputStream; +import java.io.FileOutputStream; +import java.io.IOException; +import java.security.KeyStore; +import java.security.Security; + +import org.bouncycastle.jce.provider.BouncyCastleProvider; + +import com.alu.e3.common.logging.Category; +import com.alu.e3.common.logging.CategoryLogger; +import com.alu.e3.common.logging.CategoryLoggerFactory; + +public class BaseStoreFileService { + + private static CategoryLogger LOG = CategoryLoggerFactory.getLogger(BaseStoreFileService.class, Category.AUTH); + + private String storePath; + private String storePassword; + + public BaseStoreFileService() {} + + public void setStorePath(String storePath) { + this.storePath = storePath; + } + + public void setStorePassword(String storePassword) { + this.storePassword = storePassword; + } + + public void init(){ + Security.addProvider(new BouncyCastleProvider()); + + File f = new File(storePath); + if(f.exists()) { + f.delete(); + } + + FileOutputStream out = null; + try { + KeyStore ks = KeyStore.getInstance("BKS"); + ks.load(null, storePassword.toCharArray()); + out = new FileOutputStream(f); + ks.store(out, storePassword.toCharArray()); + } + catch (Exception e) { + LOG.error("Unable to create the store", e); + } + finally { + if (out != null) { + try { + out.close(); + } catch (IOException e) { + // Nothing to do + } + } + } + } + + protected void destroy(){ + try { + File f = new File(storePath); + if(f.exists()) { + f.delete(); + } + } catch (Exception e) { + LOG.warn("Unable to delete:{}", storePath, e); + } + } + + public KeyStore loadStore() throws Exception { + FileInputStream out = null; + File f = new File(storePath); + + KeyStore keystore = KeyStore.getInstance("BKS"); + try { + out = new FileInputStream(f); + keystore.load(out, storePassword.toCharArray()); + } finally { + try { + if (out != null) { + out.close(); + } + } catch (IOException ioe) { + // Nothing to do + } + } + return keystore; + } + + public void saveStore(KeyStore ks) throws Exception { + FileOutputStream out = null; + File f = new File(storePath); + + try { + out = new FileOutputStream (f); + ks.store(out, storePassword.toCharArray()); + } finally { + try { + out.close(); + } catch (IOException ioe) { + // Nothing to do + } + } + } +} diff --git a/exposure-engine/common/src/main/java/com/alu/e3/security/BasicAuthenticationFilter.java b/exposure-engine/common/src/main/java/com/alu/e3/security/BasicAuthenticationFilter.java new file mode 100644 index 0000000..293567c --- /dev/null +++ b/exposure-engine/common/src/main/java/com/alu/e3/security/BasicAuthenticationFilter.java @@ -0,0 +1,94 @@ +/** + * Copyright © 2012 Alcatel-Lucent. + * + * See the NOTICE file distributed with this work for additional + * information regarding copyright ownership. + * Licensed to you 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 com.alu.e3.security; + +import javax.ws.rs.core.Response; + +import org.apache.cxf.configuration.security.AuthorizationPolicy; +import org.apache.cxf.interceptor.security.AuthenticationException; +import org.apache.cxf.jaxrs.model.ClassResourceInfo; +import org.apache.cxf.jaxrs.security.SimpleAuthorizingFilter; +import org.apache.cxf.message.Message; +public class BasicAuthenticationFilter extends SimpleAuthorizingFilter { + + private String username; + private String password; + private boolean enabled; + + public BasicAuthenticationFilter() { + + } + + public Response handleRequest(Message m, ClassResourceInfo resourceClass) { + AuthorizationPolicy policy = m + .get(AuthorizationPolicy.class); + + if(!enabled){ + // not activated + // null means success + return null; + } + + if (policy != null) { + + String givenUsername = policy.getUserName(); + String givenPassword = policy.getPassword(); + + if(username.equals(givenUsername) && password.equals(givenPassword)){ + // let request to continue + // null means success + return null; + } + } + + // authentication failed + throw new AuthenticationException("Unauthorized"); + // authentication failed, request the authetication, add the realm + // name if needed to the value of WWW-Authenticate + //return Response.status(Response.Status.UNAUTHORIZED).header("WWW-Authenticate", "Basic").build(); + + } + + public String getUsername() { + return username; + } + + public void setUsername(String username) { + this.username = username; + } + + public String getPassword() { + return password; + } + + public void setPassword(String password) { + this.password = password; + } + + public boolean isEnabled() { + return enabled; + } + + public void setEnabled(boolean enabled) { + this.enabled = enabled; + } + + + +} \ No newline at end of file diff --git a/exposure-engine/common/src/main/java/com/alu/e3/security/KeyStoreFileService.java b/exposure-engine/common/src/main/java/com/alu/e3/security/KeyStoreFileService.java new file mode 100644 index 0000000..498f44c --- /dev/null +++ b/exposure-engine/common/src/main/java/com/alu/e3/security/KeyStoreFileService.java @@ -0,0 +1,84 @@ +/** + * Copyright © 2012 Alcatel-Lucent. + * + * See the NOTICE file distributed with this work for additional + * information regarding copyright ownership. + * Licensed to you 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 com.alu.e3.security; + +import java.security.KeyStore; +import java.util.ArrayList; +import java.util.List; + +import com.alu.e3.common.logging.Category; +import com.alu.e3.common.logging.CategoryLogger; +import com.alu.e3.common.logging.CategoryLoggerFactory; +import com.alu.e3.common.osgi.api.IKeyStoreService; +import com.alu.e3.common.osgi.api.IStoreChangedListener; +import com.alu.e3.common.osgi.api.IStoreChangedObservable; + +public class KeyStoreFileService extends BaseStoreFileService implements IKeyStoreService { + + private static CategoryLogger LOG = CategoryLoggerFactory.getLogger(KeyStoreFileService.class, Category.AUTH); + + private List listeners; + + public KeyStoreFileService() { + super(); + listeners = new ArrayList(); + } + + @Override + public void addStoreChangedListener(IStoreChangedListener listener) { + listeners.add(listener); + } + + @Override + public void removeStoreChangedListener(IStoreChangedListener listener) { + listeners.remove(listener); + } + + @Override + public KeyStore loadKeyStore() { + KeyStore keystore = null; + + try { + keystore = loadStore(); + } + catch (Exception e) { + LOG.error("Unable to load the keystore", e); + } + + return keystore; + } + + @Override + public void saveKeyStore(KeyStore ks) { + + try { + saveStore(ks); + } + catch (Exception e) { + LOG.error("Unable to save the truststore", e); + } + + fireStoreChangedEvent(); + } + + private void fireStoreChangedEvent() { + for(IStoreChangedListener listener : listeners) + listener.onStoreChanged(); + } +} diff --git a/exposure-engine/common/src/main/java/com/alu/e3/security/TrustStoreFileService.java b/exposure-engine/common/src/main/java/com/alu/e3/security/TrustStoreFileService.java new file mode 100644 index 0000000..2a52509 --- /dev/null +++ b/exposure-engine/common/src/main/java/com/alu/e3/security/TrustStoreFileService.java @@ -0,0 +1,84 @@ +/** + * Copyright © 2012 Alcatel-Lucent. + * + * See the NOTICE file distributed with this work for additional + * information regarding copyright ownership. + * Licensed to you 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 com.alu.e3.security; + +import java.security.KeyStore; +import java.util.ArrayList; +import java.util.List; + +import com.alu.e3.common.logging.Category; +import com.alu.e3.common.logging.CategoryLogger; +import com.alu.e3.common.logging.CategoryLoggerFactory; +import com.alu.e3.common.osgi.api.IStoreChangedListener; +import com.alu.e3.common.osgi.api.IStoreChangedObservable; +import com.alu.e3.common.osgi.api.ITrustStoreService; + +public class TrustStoreFileService extends BaseStoreFileService implements ITrustStoreService { + + private static CategoryLogger LOG = CategoryLoggerFactory.getLogger(TrustStoreFileService.class, Category.AUTH); + + private List listeners; + + public TrustStoreFileService() { + super(); + listeners = new ArrayList(); + } + + @Override + public void addStoreChangedListener(IStoreChangedListener listener) { + listeners.add(listener); + } + + @Override + public void removeStoreChangedListener(IStoreChangedListener listener) { + listeners.remove(listener); + } + + @Override + public KeyStore loadTrustStore() { + KeyStore keystore = null; + + try { + keystore = loadStore(); + } + catch (Exception e) { + LOG.error("Unable to load the truststore", e); + } + + return keystore; + } + + @Override + public void saveTrustStore(KeyStore ks) { + + try { + saveStore(ks); + } + catch (Exception e) { + LOG.error("Unable to save the truststore", e); + } + + fireStoreChangedEvent(); + } + + private void fireStoreChangedEvent() { + for(IStoreChangedListener listener : listeners) + listener.onStoreChanged(); + } +} diff --git a/exposure-engine/common/src/main/java/com/hazelcast/GroveNodeInitializer.java b/exposure-engine/common/src/main/java/com/hazelcast/GroveNodeInitializer.java new file mode 100644 index 0000000..1278e96 --- /dev/null +++ b/exposure-engine/common/src/main/java/com/hazelcast/GroveNodeInitializer.java @@ -0,0 +1,32 @@ +/** + * Copyright © 2012 Alcatel-Lucent. + * + * See the NOTICE file distributed with this work for additional + * information regarding copyright ownership. + * Licensed to you 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 com.hazelcast; + +import com.hazelcast.custom.GroveProxyFactory; +import com.hazelcast.impl.ProxyFactory; +import com.hazelcast.impl.base.DefaultNodeInitializer; + +public class GroveNodeInitializer extends DefaultNodeInitializer { + + @Override + public ProxyFactory getProxyFactory() { + return new GroveProxyFactory(node.factory); + } + +} diff --git a/exposure-engine/common/src/main/java/com/hazelcast/custom/GroveProxyFactory.java b/exposure-engine/common/src/main/java/com/hazelcast/custom/GroveProxyFactory.java new file mode 100644 index 0000000..e1f7596 --- /dev/null +++ b/exposure-engine/common/src/main/java/com/hazelcast/custom/GroveProxyFactory.java @@ -0,0 +1,39 @@ +/** + * Copyright © 2012 Alcatel-Lucent. + * + * See the NOTICE file distributed with this work for additional + * information regarding copyright ownership. + * Licensed to you 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 com.hazelcast.custom; + +import com.hazelcast.impl.DefaultProxyFactory; +import com.hazelcast.impl.FactoryImpl; +import com.hazelcast.impl.GroveMProxyImpl; +import com.hazelcast.impl.MProxy; + +public class GroveProxyFactory extends DefaultProxyFactory { + + private FactoryImpl factory; + + public GroveProxyFactory(FactoryImpl factory) { + super(factory); + this.factory = factory; + } + + @Override + public MProxy createMapProxy(String name) { + return new GroveMProxyImpl(name, factory); + } +} diff --git a/exposure-engine/common/src/main/java/com/hazelcast/impl/GroveMProxyImpl.java b/exposure-engine/common/src/main/java/com/hazelcast/impl/GroveMProxyImpl.java new file mode 100644 index 0000000..70f4d12 --- /dev/null +++ b/exposure-engine/common/src/main/java/com/hazelcast/impl/GroveMProxyImpl.java @@ -0,0 +1,265 @@ +/** + * Copyright © 2012 Alcatel-Lucent. + * + * See the NOTICE file distributed with this work for additional + * information regarding copyright ownership. + * Licensed to you 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 com.hazelcast.impl; + +import java.util.ArrayList; +import java.util.HashMap; +import java.util.HashSet; +import java.util.List; +import java.util.Map; +import java.util.Set; +import java.util.concurrent.BlockingQueue; +import java.util.concurrent.ExecutionException; +import java.util.concurrent.ExecutorService; +import java.util.concurrent.Future; +import java.util.concurrent.LinkedBlockingQueue; +import java.util.concurrent.ThreadPoolExecutor; +import java.util.concurrent.TimeUnit; + +import com.hazelcast.core.EntryEvent; +import com.hazelcast.core.EntryListener; +import com.hazelcast.core.IMap; +import com.hazelcast.nio.Data; + +public class GroveMProxyImpl extends MProxyImpl { + + /** + * + */ + private static final long serialVersionUID = 4776207704800761598L; + + private static final String EVENT_SOURCE = "Unknown"; + + private List> listeners; + private Map>> perKeyListeners; + + /** + * Using internally an {@link ExecutorService} to change the ThreadContext during notification. + * For more details, see comment below in method fireEventToAllListeners. + */ + private ExecutorService exectuorService; + private static final int EVENTS_CORE_POOL_SIZE = 10; + private static final int EVENTS_MAXIMUM_POOL_SIZE = 10; + private static final long EVENT_KEEP_ALIVE_TIME = 1; + private static final TimeUnit EVENT_KEEP_ALIVE_TIME_UNIT = TimeUnit.MINUTES; + private BlockingQueue eventQueue; + + public GroveMProxyImpl(String name, FactoryImpl factory) { + super(name, factory); + listeners = new ArrayList>(); + perKeyListeners = new HashMap>>(); + eventQueue = new LinkedBlockingQueue(); + exectuorService = new ThreadPoolExecutor(EVENTS_CORE_POOL_SIZE, EVENTS_MAXIMUM_POOL_SIZE, EVENT_KEEP_ALIVE_TIME, EVENT_KEEP_ALIVE_TIME_UNIT, eventQueue); + } + + /** + * Called with a set AND multiple time when a remote putAll is made. + */ + @Override + public void set(Object key, Object value, long time, TimeUnit timeunit) { + super.set(key, value, time, timeunit); + putOrSetEventBroadcast(key, value, null); + } + + /** + * Synchronous Put(key, value) with synchronous {@link EntryEvent} notifications. + * @see IMap.put + */ + @Override + public Object put(Object key, Object value) { + Object oldValue = super.put(key, value); + + putOrSetEventBroadcast(key, value, oldValue); + + return oldValue; + } + + @SuppressWarnings("unchecked") + private void putOrSetEventBroadcast(Object key, Object value, Object oldValue) { + EntryEvent event; + if (isRemoteObject(key) && isRemoteObject(value)) { + if (oldValue == null) + event = new DataAwareEntryEvent(null, EntryEvent.TYPE_ADDED, EVENT_SOURCE, (Data)key, (Data)value, null, true); + else + event = new DataAwareEntryEvent(null, EntryEvent.TYPE_UPDATED, EVENT_SOURCE, (Data)key, (Data)value, (Data)oldValue, true); + } + else { + if (oldValue == null) + event = new EntryEvent(EVENT_SOURCE, null, EntryEvent.TYPE_ADDED, key, null, value); + else + event = new EntryEvent(EVENT_SOURCE, null, EntryEvent.TYPE_UPDATED, key, oldValue, value); + } + + fireEventToAllListeners(key, event); + } + + private boolean isRemoteObject(Object o) { + if (o==null) return true; + return o instanceof Data; + } + + /** + * Only called when the putAll call is made locally. + * Unless this, we must fire our event manually (locally). + * @param allEntries all entries to put + */ + @Override + @SuppressWarnings("rawtypes") + public void putAll(Map allEntries) { + //super.putAll(allEntries); + for(Object key : allEntries.keySet()) { + set(key, allEntries.get(key), 0 , TimeUnit.MILLISECONDS); + } + } + + @Override + public void clear() { + super.clear(); + } + + /** + * Globally synchronous fire event method but asynchronous between each event notification. + * @param key the key event to broadcast + * @param event the event to broadcast + */ + private void fireEventToAllListeners(Object key, final EntryEvent event) { + Set> wholeListeners = new HashSet>(); + + // Add 'global' listeners + wholeListeners.addAll(listeners); + // Add perKey listeners if any + if (perKeyListeners.containsKey(key)) + wholeListeners.addAll(perKeyListeners.get(key)); + + // We will use a serviceExectutor to : + // 1- Parallelize event broadcast + // 2- Ease join using Future + // 3- Change the thread context execution to broadcast event due to + // a Hazelcast arch. limitation: + // Executing a get(key) operation on a map that have received a client put event (Packet) + // checks the current ThreadContext and sees that we use the same 'map server' thread context + // to both, consume request packet and get the local map value + // so it decides to downCast the internal value into Data packet... + List> futureEvents = new ArrayList>(); + + // Registers the Futures ... + for(EntryListener listener : wholeListeners) { + final EntryListener toNotify = listener; + + // Keep track of the Future to join on them later + futureEvents.add( + // Submit job (=event execution) + exectuorService.submit( + new Runnable() { + @Override + public void run() { + switch(event.getEventType()) { + case ADDED: + toNotify.entryAdded(event); + break; + case EVICTED: + toNotify.entryEvicted(event); + break; + case REMOVED: + toNotify.entryRemoved(event); + break; + case UPDATED: + toNotify.entryUpdated(event); + break; + } + } + } + ) + ); + } + + // Similar to a join + for(Future futureEvent : futureEvents) { + try { + // Blocking instruction while Future runnable has not finished + futureEvent.get(); + } catch (InterruptedException e) { + throw new RuntimeException("FutureEvent had been interrupted", e); + } catch (ExecutionException e) { + throw new RuntimeException("FutureEvent execution had a problem", e); + } + } + } + + @Override + @SuppressWarnings("unchecked") + public boolean evict(Object key) { + boolean evicted = super.evict(key); + EntryEvent event; + if (isRemoteObject(key)) { + event = new DataAwareEntryEvent(null, EntryEvent.TYPE_EVICTED, EVENT_SOURCE, (Data) key, null, null, true); + } + else { + event = new EntryEvent(EVENT_SOURCE, null, EntryEvent.TYPE_EVICTED, key, null); + } + fireEventToAllListeners(key, event); + return evicted; + } + + @Override + @SuppressWarnings("unchecked") + public Object remove(Object key) { + Object oldValue = super.remove(key); + EntryEvent event; + if (isRemoteObject(key)) { + event = new DataAwareEntryEvent(null, EntryEvent.TYPE_REMOVED, EVENT_SOURCE, (Data) key, (Data)oldValue, (Data)oldValue, true); + } + else { + event = new EntryEvent(EVENT_SOURCE, null, EntryEvent.TYPE_REMOVED, key, oldValue, oldValue); + } + fireEventToAllListeners(key, event); + return oldValue; + } + + @Override + @SuppressWarnings("unchecked") + public void addEntryListener(@SuppressWarnings("rawtypes") EntryListener listener, boolean includeValue) { + listeners.add(listener); + } + + @Override + @SuppressWarnings("unchecked") + public void addEntryListener(@SuppressWarnings("rawtypes")EntryListener listener, Object key, boolean includeValue) { + if (!perKeyListeners.containsKey(key)) + perKeyListeners.put(key, new ArrayList>()); + perKeyListeners.get(key).add(listener); + } + + @Override + public void addLocalEntryListener(@SuppressWarnings("rawtypes")EntryListener entryListener) { + throw new UnsupportedOperationException("GroveMProxyImpl not yet support adding local entry listener."); + } + + @Override + public void removeEntryListener(@SuppressWarnings("rawtypes")EntryListener listener) { + listeners.remove(listener); + } + + @Override + public void removeEntryListener(@SuppressWarnings("rawtypes")EntryListener listener, Object key) { + perKeyListeners.get(key).remove(listener); + if (perKeyListeners.get(key).isEmpty()) + perKeyListeners.remove(key); + } +} diff --git a/exposure-engine/common/src/main/resources/META-INF/services/com.hazelcast.NodeInitializer b/exposure-engine/common/src/main/resources/META-INF/services/com.hazelcast.NodeInitializer new file mode 100644 index 0000000..7a1ec06 --- /dev/null +++ b/exposure-engine/common/src/main/resources/META-INF/services/com.hazelcast.NodeInitializer @@ -0,0 +1 @@ +com.hazelcast.GroveNodeInitializer \ No newline at end of file diff --git a/exposure-engine/common/src/main/resources/META-INF/spring-optional/gateway-extended.xml b/exposure-engine/common/src/main/resources/META-INF/spring-optional/gateway-extended.xml new file mode 100644 index 0000000..5b6f731 --- /dev/null +++ b/exposure-engine/common/src/main/resources/META-INF/spring-optional/gateway-extended.xml @@ -0,0 +1,13 @@ + + + + + + + + \ No newline at end of file diff --git a/exposure-engine/common/src/main/resources/META-INF/spring-optional/gateway.xml b/exposure-engine/common/src/main/resources/META-INF/spring-optional/gateway.xml new file mode 100644 index 0000000..61579e8 --- /dev/null +++ b/exposure-engine/common/src/main/resources/META-INF/spring-optional/gateway.xml @@ -0,0 +1,22 @@ + + + + + + + + + + + + + + + + + \ No newline at end of file diff --git a/exposure-engine/common/src/main/resources/META-INF/spring-optional/manager-extended.xml b/exposure-engine/common/src/main/resources/META-INF/spring-optional/manager-extended.xml new file mode 100644 index 0000000..b84012c --- /dev/null +++ b/exposure-engine/common/src/main/resources/META-INF/spring-optional/manager-extended.xml @@ -0,0 +1,9 @@ + + + + \ No newline at end of file diff --git a/exposure-engine/common/src/main/resources/META-INF/spring-optional/manager.xml b/exposure-engine/common/src/main/resources/META-INF/spring-optional/manager.xml new file mode 100644 index 0000000..4aedee4 --- /dev/null +++ b/exposure-engine/common/src/main/resources/META-INF/spring-optional/manager.xml @@ -0,0 +1,20 @@ + + + + + + + + + + + + + + + \ No newline at end of file diff --git a/exposure-engine/common/src/main/resources/META-INF/spring/common.beans.xml b/exposure-engine/common/src/main/resources/META-INF/spring/common.beans.xml new file mode 100644 index 0000000..a64d1e9 --- /dev/null +++ b/exposure-engine/common/src/main/resources/META-INF/spring/common.beans.xml @@ -0,0 +1,107 @@ + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + diff --git a/exposure-engine/common/src/main/resources/log4j.properties b/exposure-engine/common/src/main/resources/log4j.properties new file mode 100644 index 0000000..9cbf8e4 --- /dev/null +++ b/exposure-engine/common/src/main/resources/log4j.properties @@ -0,0 +1,7 @@ +log4j.rootLogger=DEBUG, CA +log4j.logger.org.apache.camel=DEBUG +log4j.logger.org.eclipse.jetty=DEBUG +log4j.logger.com.alu=DEBUG +log4j.appender.CA=org.apache.log4j.ConsoleAppender +log4j.appender.CA.layout=org.apache.log4j.PatternLayout +log4j.appender.CA.layout.ConversionPattern=%-4r [%t] %-5p %c %x - %m%n \ No newline at end of file diff --git a/exposure-engine/common/src/test/java/com/alu/e3/common/MiscTests.java b/exposure-engine/common/src/test/java/com/alu/e3/common/MiscTests.java new file mode 100644 index 0000000..c8b758b --- /dev/null +++ b/exposure-engine/common/src/test/java/com/alu/e3/common/MiscTests.java @@ -0,0 +1,127 @@ +/** + * Copyright © 2012 Alcatel-Lucent. + * + * See the NOTICE file distributed with this work for additional + * information regarding copyright ownership. + * Licensed to you 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 com.alu.e3.common; + +import static org.hamcrest.CoreMatchers.*; +import org.junit.After; +import org.junit.Before; +import org.junit.Test; + +import com.alu.e3.common.tools.CommonTools; +import com.alu.e3.data.model.CallDescriptor; +import com.alu.e3.data.model.Policy; + +import static org.junit.Assert.*; + +public class MiscTests { + + @Before + public void setUp() throws Exception { + } + + @After + public void tearDown() throws Exception { + } + + @Test + public void testSplitUrl() { + validateUrl("http://www.apple.com/test.html", "http://www.apple.com/test.html", null); + validateUrl("http://www.apple.com/path/test.html", "http://www.apple.com/path/test.html", null); + validateUrl("http://www.apple.com/test.html?key=value&key2=value2", "http://www.apple.com/test.html", "key=value&key2=value2"); + validateUrl("http://www.apple.com/path/test/test.html?key=value&key2=value2", "http://www.apple.com/path/test/test.html", "key=value&key2=value2"); + } + + private void validateUrl(String url, String part1, String part2) { + String[] parts = CommonTools.splitUrl(url); + + assertEquals(part1, parts[0]); + assertEquals(part2, parts[1]); + } + + @Test + public void testCallDescriptorsEquals() { + Policy p1 = new Policy(); + p1.setId("abcd"); + + + // same cd + CallDescriptor cd_p1 = new CallDescriptor(p1, -1, -1); + assertThat(cd_p1, is(cd_p1)); + + // different cd with same non-null policy + CallDescriptor cd2_p1 = new CallDescriptor(p1, -1, -1); + assertThat(cd2_p1, is(cd_p1)); + + // same non-null policy, different bucket id + CallDescriptor cd_p1_bucket = new CallDescriptor(p1, 0, -1); + assertThat(cd_p1_bucket, is(not(cd_p1))); + + // same non-null policy, different context id + CallDescriptor cd_p1_context = new CallDescriptor(p1, -1, 0); + assertThat(cd_p1_context, is(not(cd_p1))); + + // same non-null policy, different bucket & bucket id + CallDescriptor cd_p1_ctx_buck = new CallDescriptor(p1, 0, 0); + assertThat(cd_p1, is(not(cd_p1_ctx_buck))); + + // comparing with non null policy but null policy id + Policy p_idn = new Policy(); + CallDescriptor cd_pn_idn = new CallDescriptor(p_idn, -1, -1); + assertThat(cd_p1, is(not(cd_pn_idn))); + + // comparing with non null policy but null policy id + CallDescriptor cd_pn_idn_bucket = new CallDescriptor(p_idn, 0, -1); + assertThat(cd_p1, is(not(cd_pn_idn_bucket))); + + // comparing with non null policy but null policy id + CallDescriptor cd_pn_idn_context = new CallDescriptor(p_idn, -1, 0); + assertThat(cd_p1, is(not(cd_pn_idn_context))); + + // comparing with null policy + CallDescriptor cd_pn = new CallDescriptor(null, -1, -1); + assertThat(cd_p1, is(not(cd_pn))); + assertThat(cd_pn, is(not(cd_p1))); + + // comparing 2 null policies + CallDescriptor cd2_pn = new CallDescriptor(null, -1, -1); + assertThat(cd_pn, is(cd2_pn)); + + + // comparing with different policy but same policy id + Policy p2 = new Policy(); + p2.setId("abcd"); + + // different policy with same id + CallDescriptor cd2_p2 = new CallDescriptor(p2, -1, -1); + assertThat(cd2_p2, is(cd_p1)); + + // different policy with same id + different bucket id + CallDescriptor cd2_p2_bucket = new CallDescriptor(p1, 0, -1); + assertThat(cd2_p2_bucket, is(not(cd2_p2))); + + // different policy with same id + different context id + CallDescriptor cd2_p2_context = new CallDescriptor(p1, -1, 0); + assertThat(cd2_p2_context, is(not(cd2_p2))); + + // different policy with same id + different context & bucket id + CallDescriptor cd2_p2_ctx_buck = new CallDescriptor(p1, 0, 0); + assertThat(cd2_p2_ctx_buck, is(not(cd2_p2))); + + } +} diff --git a/exposure-engine/common/src/test/java/com/alu/e3/common/caching/Auth.java b/exposure-engine/common/src/test/java/com/alu/e3/common/caching/Auth.java new file mode 100644 index 0000000..8953b1e --- /dev/null +++ b/exposure-engine/common/src/test/java/com/alu/e3/common/caching/Auth.java @@ -0,0 +1,66 @@ +/** + * Copyright © 2012 Alcatel-Lucent. + * + * See the NOTICE file distributed with this work for additional + * information regarding copyright ownership. + * Licensed to you 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 com.alu.e3.common.caching; + +public class Auth { + protected String apiId, authK, userName, password; + + public Auth() { + } + + public Auth(String apiId, String authK, String userName, String password) { + super(); + this.apiId = apiId; + this.authK = authK; + this.userName = userName; + this.password = password; + } + + public String getApiId() { + return apiId; + } + + public void setApiId(String apiId) { + this.apiId = apiId; + } + + public String getAuthK() { + return authK; + } + + public void setAuthK(String authK) { + this.authK = authK; + } + + public String getUserName() { + return userName; + } + + public void setUserName(String userName) { + this.userName = userName; + } + + public String getPassword() { + return password; + } + + public void setPassword(String password) { + this.password = password; + } +} diff --git a/exposure-engine/common/src/test/java/com/alu/e3/common/caching/BundlesToDeployListener.java b/exposure-engine/common/src/test/java/com/alu/e3/common/caching/BundlesToDeployListener.java new file mode 100644 index 0000000..54e36e3 --- /dev/null +++ b/exposure-engine/common/src/test/java/com/alu/e3/common/caching/BundlesToDeployListener.java @@ -0,0 +1,74 @@ +/** + * Copyright © 2012 Alcatel-Lucent. + * + * See the NOTICE file distributed with this work for additional + * information regarding copyright ownership. + * Licensed to you 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 com.alu.e3.common.caching; + +import java.io.File; + +import com.alu.e3.common.tools.BundleTools; +import com.hazelcast.core.IQueue; + +public class BundlesToDeployListener implements Runnable { + protected IQueue deploymentResultQueue; + protected IQueue provisionRouteQueue; + + public BundlesToDeployListener(IQueue provisionRouteQueue, IQueue deploymentResultQueue) { + super(); + this.deploymentResultQueue = deploymentResultQueue; + this.provisionRouteQueue = provisionRouteQueue; + + Thread thread = new Thread(this); + thread.start(); + } + + protected void consume() throws Exception { + try { + // Wait for the next task to process + ProvisionRouteTask provisionRouteTask = provisionRouteQueue.take(); + + // A task was received + if (deploymentResultQueue != null) { + // populate the cache with the new rates, ... + // persist the jar + String newBundlePath = "c:\\tmp\\" + Long.toString(System.nanoTime()) + ".jar"; + BundleTools.byteArray2File(provisionRouteTask.getBundle(), new File(newBundlePath)); + + // deploy the bundle + + // And post the result of the provisioning + ProvisionRouteResult provisionRouteResult = new ProvisionRouteResult(provisionRouteTask, TaskResult.OK); + provisionRouteResult.setBundlePath(newBundlePath); + deploymentResultQueue.add(provisionRouteResult); + } + } catch (InterruptedException e) { + + } + // Wait for the next task to process + consume(); + } + + @Override + public void run() { + try { + consume(); + } catch (Exception e) { + + } + } + +} diff --git a/exposure-engine/common/src/test/java/com/alu/e3/common/caching/HazelcastCacheManagerMock.java b/exposure-engine/common/src/test/java/com/alu/e3/common/caching/HazelcastCacheManagerMock.java new file mode 100644 index 0000000..7976b60 --- /dev/null +++ b/exposure-engine/common/src/test/java/com/alu/e3/common/caching/HazelcastCacheManagerMock.java @@ -0,0 +1,59 @@ +/** + * Copyright © 2012 Alcatel-Lucent. + * + * See the NOTICE file distributed with this work for additional + * information regarding copyright ownership. + * Licensed to you 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 com.alu.e3.common.caching; + +import org.slf4j.Logger; +import org.slf4j.LoggerFactory; + +import com.alu.e3.common.E3Constant; +import com.hazelcast.config.Config; +import com.hazelcast.core.Hazelcast; + +public class HazelcastCacheManagerMock extends HazelcastCacheManager { + + private static Logger logger = LoggerFactory.getLogger(HazelcastCacheManager.class); + + @Override + public void init(){ + + // check if an Hazelcast instance is already running + setHazelcastInstance(Hazelcast.getHazelcastInstanceByName(E3Constant.HAZELCAST_NAME)); + + if (this.hazelcastInstance != null) { + // should not happen except when running the JUnit + logger.warn("WARNING: HazelcastCacheManager: HazelcastInstance is already running"); + } + else { + logger.debug("Normal start of new HazelcastInstance"); + // create the instance + Config cfg = new Config(); + cfg.setPort(E3Constant.HAZELCAST_PORT); + cfg.setPortAutoIncrement(true); + + cfg.setInstanceName(E3Constant.HAZELCAST_NAME); + + cfg.getNetworkConfig().getJoin().getMulticastConfig().setEnabled(false); + + setHazelcastInstance(Hazelcast.newHazelcastInstance(cfg)); + + logger.debug("Normal start: done."); + } + } + +} diff --git a/exposure-engine/common/src/test/java/com/alu/e3/common/caching/MockDataStore.java b/exposure-engine/common/src/test/java/com/alu/e3/common/caching/MockDataStore.java new file mode 100644 index 0000000..69fff0e --- /dev/null +++ b/exposure-engine/common/src/test/java/com/alu/e3/common/caching/MockDataStore.java @@ -0,0 +1,74 @@ +/** + * Copyright © 2012 Alcatel-Lucent. + * + * See the NOTICE file distributed with this work for additional + * information regarding copyright ownership. + * Licensed to you 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 com.alu.e3.common.caching; + +import java.util.Collection; +import java.util.HashMap; +import java.util.Map; +import java.util.Set; + +import com.hazelcast.core.MapStore; + +@SuppressWarnings("rawtypes") +public class MockDataStore implements MapStore { + + public static HashMap internalStore = new HashMap(); + + @Override + public Object load(Object key) { + return internalStore.get(key); + } + + @Override + public Map loadAll(Collection keys) { + return internalStore; + } + + @Override + public Set loadAllKeys() { + return internalStore.keySet(); + } + + @Override + public void store(Object key, Object value) { + internalStore.put(key, value); + } + + + @SuppressWarnings("unchecked") + @Override + public void storeAll(Map map) { + internalStore.putAll(map); + } + + @Override + public void delete(Object key) { + internalStore.remove(key); + } + + + @Override + public void deleteAll(Collection keys) { + for (Object key: keys) { + internalStore.remove(key); + } + } + +} + diff --git a/exposure-engine/common/src/test/java/com/alu/e3/common/caching/ProvisionRouteResult.java b/exposure-engine/common/src/test/java/com/alu/e3/common/caching/ProvisionRouteResult.java new file mode 100644 index 0000000..77e6b94 --- /dev/null +++ b/exposure-engine/common/src/test/java/com/alu/e3/common/caching/ProvisionRouteResult.java @@ -0,0 +1,53 @@ +/** + * Copyright © 2012 Alcatel-Lucent. + * + * See the NOTICE file distributed with this work for additional + * information regarding copyright ownership. + * Licensed to you 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 com.alu.e3.common.caching; + +import java.io.Serializable; + +public class ProvisionRouteResult implements Serializable { + private static final long serialVersionUID = 7834547114448233788L; + + protected long provisionRouteId; + protected TaskResult taskResult; + protected String bundlePath; + + public void setProvisionRouteId(long provisionRouteId) { + this.provisionRouteId = provisionRouteId; + } + public void setTaskResult(TaskResult taskResult) { + this.taskResult = taskResult; + } + public String getBundlePath() { + return bundlePath; + } + public void setBundlePath(String bundlePath) { + this.bundlePath = bundlePath; + } + public ProvisionRouteResult(ProvisionRouteTask provisionRouteTask, TaskResult taskResult) { + super(); + this.provisionRouteId = provisionRouteTask.getId(); + this.taskResult = taskResult; + } + public long getProvisionRouteId() { + return provisionRouteId; + } + public TaskResult getTaskResult() { + return taskResult; + } +} diff --git a/exposure-engine/common/src/test/java/com/alu/e3/common/caching/ProvisionRouteTask.java b/exposure-engine/common/src/test/java/com/alu/e3/common/caching/ProvisionRouteTask.java new file mode 100644 index 0000000..e228fc3 --- /dev/null +++ b/exposure-engine/common/src/test/java/com/alu/e3/common/caching/ProvisionRouteTask.java @@ -0,0 +1,49 @@ +/** + * Copyright © 2012 Alcatel-Lucent. + * + * See the NOTICE file distributed with this work for additional + * information regarding copyright ownership. + * Licensed to you 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 com.alu.e3.common.caching; + +import java.io.Serializable; + +public class ProvisionRouteTask implements Serializable { + private static final long serialVersionUID = -7018485375170353176L; + + protected long id; + protected byte[] bundle; + + public long getId() { + return id; + } + + public byte[] getBundle() { + return bundle; + } + + public ProvisionRouteTask(long id, byte[] bundle) { + super(); + this.id = id; + this.bundle = bundle; + } + + // This constructor can be used only when all the instances are created on the same machine + public ProvisionRouteTask(byte[] bundle) { + super(); + id = System.nanoTime(); + this.bundle = bundle; + } +} diff --git a/exposure-engine/common/src/test/java/com/alu/e3/common/caching/TaskResult.java b/exposure-engine/common/src/test/java/com/alu/e3/common/caching/TaskResult.java new file mode 100644 index 0000000..c453444 --- /dev/null +++ b/exposure-engine/common/src/test/java/com/alu/e3/common/caching/TaskResult.java @@ -0,0 +1,23 @@ +/** + * Copyright © 2012 Alcatel-Lucent. + * + * See the NOTICE file distributed with this work for additional + * information regarding copyright ownership. + * Licensed to you 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 com.alu.e3.common.caching; + +public enum TaskResult { + OK, ROLLBACK_OK, ROLLBACK_KO; +} diff --git a/exposure-engine/common/src/test/java/com/alu/e3/common/caching/TestHazelcast.java b/exposure-engine/common/src/test/java/com/alu/e3/common/caching/TestHazelcast.java new file mode 100644 index 0000000..15473a5 --- /dev/null +++ b/exposure-engine/common/src/test/java/com/alu/e3/common/caching/TestHazelcast.java @@ -0,0 +1,563 @@ +/** + * Copyright © 2012 Alcatel-Lucent. + * + * See the NOTICE file distributed with this work for additional + * information regarding copyright ownership. + * Licensed to you 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 com.alu.e3.common.caching; + +import static org.junit.Assert.assertEquals; +import static org.junit.Assert.assertNull; +import static org.junit.Assert.assertTrue; + +import java.net.InetSocketAddress; +import java.net.UnknownHostException; +import java.util.HashMap; +import java.util.Map; +import java.util.concurrent.TimeUnit; + +import org.junit.Before; +import org.junit.Ignore; +import org.junit.Test; + +import com.hazelcast.client.ClientConfig; +import com.hazelcast.client.HazelcastClient; +import com.hazelcast.config.Config; +import com.hazelcast.config.MapConfig; +import com.hazelcast.config.MapStoreConfig; +import com.hazelcast.config.MaxSizeConfig; +import com.hazelcast.config.NearCacheConfig; +import com.hazelcast.core.Hazelcast; +import com.hazelcast.core.HazelcastInstance; +import com.hazelcast.core.IMap; + +public class TestHazelcast { + + @Before + public void before() { + Hazelcast.shutdownAll(); + } + + + @Test + public void testStandaloneMode() { + + // Start 2 standalone hazelcast instances + Config cfg = new Config(); + cfg.getNetworkConfig().getJoin().getMulticastConfig().setEnabled(false); + HazelcastInstance h1 = Hazelcast.newHazelcastInstance(cfg); + HazelcastInstance h2 = Hazelcast.newHazelcastInstance(cfg); + + // Add a new key/value in the 1st instance + Map map1 = h1.getMap("testmap"); + map1.put(1, "value 1 on instance 1"); + + Map map2 = h2.getMap("testmap"); + + // Check that this key/value was added in the 1st instance and not in the 2nd instance + assertEquals(1, map1.size()); + assertEquals(0, map2.size()); + + map2.put(1, "value 1 on instance 2"); + + assertEquals("value 1 on instance 1", map1.get(1)); + assertEquals("value 1 on instance 2", map2.get(1)); + } + + @Ignore + public void testClusterMode() { + + // Start 2 clustered hazelcast instances + HazelcastInstance h1 = Hazelcast.newHazelcastInstance(null); + HazelcastInstance h2 = Hazelcast.newHazelcastInstance(null); + + // Add a key/value in the 1st instance + Map map1 = h1.getMap("testmap"); + map1.put(1, "value 1 on instance 1"); + + IMap map2 = h2.getMap("testmap"); + + // Check that this key/value was synchronized in the instance 2 + assertEquals(1, map1.size()); + assertEquals(1, map2.size()); + + assertEquals("value 1 on instance 1", map1.get(1)); + assertEquals("value 1 on instance 1", map2.get(1)); + + // Update in the instance 2 the value of a key added by the instance 1 + map2.put(1, "value 1 on instance 2"); + + // Check that this key/value was synchronized in the instance 1 + assertEquals("value 1 on instance 2", map1.get(1)); + assertEquals("value 1 on instance 2", map2.get(1)); + } + + @Test + public void testHazelcastJavaClient() throws UnknownHostException { + + Config cfg = new Config(); + cfg.getNetworkConfig().getJoin().getMulticastConfig().setEnabled(false); + HazelcastInstance h1 = Hazelcast.newHazelcastInstance(cfg); + + // Connect a client to the cluster + ClientConfig clientConfig = new ClientConfig() ; + InetSocketAddress localMemberAddress = h1.getCluster().getLocalMember().getInetSocketAddress(); + clientConfig.addInetSocketAddress(localMemberAddress); + HazelcastClient client = HazelcastClient.newHazelcastClient(clientConfig); + + // Add a key/value in the cluster using the client + String mapName = "123"; + IMap mapClient = client.getMap(mapName); + mapClient.put("key1", "value1"); + + // Check that the key/value was actually added in the cluster + IMap mapH1 = h1.getMap(mapName); + mapH1.keySet(); + assertEquals(1, mapH1.size()); + assertEquals("value1", mapH1.get("key1")); + } + + @Test + public void testMaxSizeAndEviction() { + + String mapName = new Long (System.nanoTime()).toString(); + + MaxSizeConfig maxSizeConfig = new MaxSizeConfig(); + maxSizeConfig.setSize(2); + maxSizeConfig.setMaxSizePolicy("map_size_per_jvm"); + MapConfig mapConfig = new MapConfig(); + mapConfig.setName(mapName); + mapConfig.setMaxSizeConfig(maxSizeConfig); + mapConfig.setEvictionPolicy("LRU"); + + Config config = new Config(); + Map mapConfigs = new HashMap(); + mapConfigs.put(mapName, mapConfig); + config.setMapConfigs(mapConfigs); + + // Start a new cluster of Hazelcast isntances + HazelcastInstance h1 = Hazelcast.newHazelcastInstance(config); + + IMap map = h1.getMap(mapName); + map.put("k1111111111111111111111", "v1"); + map.put("k2222222222222222222222", "v2"); + map.put("k3333333333333333333333", "v3"); + + /* + * IF the eviction policy and time-to-live are not set explicitly + * AND the map is full + * AND that no key is removed + * THEN there is an infinite loop + */ + + // Check that the map contains 2 key and not 3 + assertEquals(2, map.size()); + // Check that "k3" was actually added + assertTrue (map.containsKey("k3333333333333333333333")); + + // TODO As far as we know, the expected size should be 2, and is actually 1. Maybe a bug... To be confirmed. + /* + map.put("k3333333333333333333333", "v3.1"); + assertEquals(2, map.size()); + assertTrue (map.containsKey("k3333333333333333333333")); + */ + } + + @Ignore + public void testMapDatastore() { + + String mapName = new Long (System.nanoTime()).toString(); + + MapStoreConfig mapStoreConfig = new MapStoreConfig(); + mapStoreConfig.setEnabled(true); + mapStoreConfig.setClassName("com.alu.e3.common.caching.MockDataStore"); + + MapConfig mapConfig = new MapConfig(); + mapConfig.setName(mapName); + mapConfig.setMapStoreConfig(mapStoreConfig); + + Config config = new Config(); + Map mapConfigs = new HashMap(); + mapConfigs.put(mapName, mapConfig); + config.setMapConfigs(mapConfigs); + + // Initialize the store with 3 key/value pairs + MockDataStore.internalStore = new HashMap(); + MockDataStore.internalStore.put("key1", "value1"); + MockDataStore.internalStore.put("key2", "value2"); + MockDataStore.internalStore.put("key3", "value3"); + + // Start a new cluster of Hazelcast isntances + HazelcastInstance h1 = Hazelcast.newHazelcastInstance(config); + + IMap map = h1.getMap(mapName); + + // Check that the map is automatically loaded with the content of the persistent store + assertEquals(3, map.size()); + assertEquals("value1", map.get("key1")); + + assertNull(map.get("key4")); + + // Update the store... + MockDataStore.internalStore.put("key4", "value4"); + + // ... And check that the new key/value pair is added to the cache once requested + assertEquals(3, map.size()); + assertEquals("value4", map.get("key4")); + assertEquals(4, map.size()); + + // Update the cache... + map.put("key3", "value3-bis"); + map.put("key5", "value5"); + + // ... And check that the persistent store was updated accordingly + assertEquals(5, MockDataStore.internalStore.size()); + assertEquals("value3-bis", MockDataStore.internalStore.get("key3")); + assertEquals("value5", MockDataStore.internalStore.get("key5")); + } + + @Ignore + public void testE3Archi() { + String mapName = "apisMap"; + + NearCacheConfig nearCacheConfig = new NearCacheConfig(); + nearCacheConfig.setMaxSize(10000); + +// MapConfig mapConfig = new MapConfig(); +// mapConfig.setName(mapName); +// mapConfig.setNearCacheConfig(nearCacheConfig); + + Config config = new Config(); +// Map mapConfigs = new HashMap(); +// mapConfigs.put(mapName, mapConfig); +// config.setMapConfigs(mapConfigs); + config.getMapConfig(mapName).setNearCacheConfig(nearCacheConfig); + + HazelcastInstance hOnGtw1 = Hazelcast.newHazelcastInstance(config); + HazelcastInstance hOnGtw2 = Hazelcast.newHazelcastInstance(config); + +// hOnGtw1.getConfig().getMapConfigs() +// hOnGtw1.getConfig().getMapConfig(mapName).getNearCacheConfig() +// hOnGtw2.getConfig().getMapConfig(mapName).getNearCacheConfig() +// +// hOnGtw1.getConfig().getMapConfig(mapName). + + + IMap apisMapOnG1 = hOnGtw1.getMap(mapName); + + apisMapOnG1.put("api1", "api1Policies"); + apisMapOnG1.put("api2", "api2Policies"); +// assertEquals(2, apisMapOnG1.localKeySet().size()); + + // Check that "apisMap" is replicated on gtw2 + IMap apisMapOnG2 = hOnGtw2.getMap(mapName); + + assertEquals(2, apisMapOnG2.size()); + assertEquals(2, apisMapOnG2.localKeySet().size()); + + // Check that "apisMap" creation and updates are replicated on gtw1 + apisMapOnG2.put("api3", "api3Policies"); + assertEquals(3, apisMapOnG1.size()); + assertEquals("api3Policies", apisMapOnG1.get("api3")); + assertEquals(3, apisMapOnG2.localKeySet().size()); + assertEquals(3, apisMapOnG1.localKeySet().size()); + + apisMapOnG2.put("api3", "api3Policies-bis"); + assertEquals("api3Policies-bis", apisMapOnG1.get("api3")); + assertEquals(3, apisMapOnG2.localKeySet().size()); + assertEquals(3, apisMapOnG1.localKeySet().size()); + } + + @Ignore + public void testNearCache() { + String mapName = "apisMap"; + + NearCacheConfig nearCacheConfig = new NearCacheConfig(); + nearCacheConfig.setMaxSize(10000); + + Config config = new Config(); + config.getMapConfig(mapName).setNearCacheConfig(nearCacheConfig); + + HazelcastInstance hOnGtw1 = Hazelcast.newHazelcastInstance(config); + HazelcastInstance hOnGtw2 = Hazelcast.newHazelcastInstance(config); + + IMap apisMapOnG1 = hOnGtw1.getMap(mapName); + + apisMapOnG1.put("api1", "api1Policies"); + apisMapOnG1.put("api2", "api2Policies"); + assertEquals(2, apisMapOnG1.localKeySet().size()); + + // Check that "apisMap" is replicated on gtw2 + IMap apisMapOnG2 = hOnGtw2.getMap(mapName); + + assertEquals(2, apisMapOnG2.size()); + assertEquals(2, apisMapOnG2.localKeySet().size()); + + // Check that "apisMap" creation and updates are replicated on gtw1 + apisMapOnG2.put("api3", "api3Policies"); + assertEquals(3, apisMapOnG1.size()); + assertEquals("api3Policies", apisMapOnG1.get("api3")); + assertEquals(3, apisMapOnG2.localKeySet().size()); + assertEquals(3, apisMapOnG1.localKeySet().size()); + + apisMapOnG2.put("api3", "api3Policies-bis"); + assertEquals("api3Policies-bis", apisMapOnG1.get("api3")); + assertEquals(3, apisMapOnG2.localKeySet().size()); + assertEquals(3, apisMapOnG1.localKeySet().size()); + } + + @Ignore + public void nearCacheOn2Machines() { + String mapName = "apisMap"; + + NearCacheConfig nearCacheConfig = new NearCacheConfig(); + nearCacheConfig.setMaxSize(10000); + + Config config = new Config(); + config.getMapConfig(mapName).setNearCacheConfig(nearCacheConfig); + + HazelcastInstance hOnGtw1 = Hazelcast.newHazelcastInstance(config); + + IMap apisMapOnG1 = hOnGtw1.getMap(mapName); + + apisMapOnG1.put("api1", "api1Policies"); + apisMapOnG1.put("api2", "api2Policies"); + + assertEquals("api1Policies", apisMapOnG1.get("api1")); + assertEquals("api1Policies", apisMapOnG1.get("api1")); + assertEquals(2, apisMapOnG1.localKeySet().size()); + + System.out.println(); + } + + @Ignore + public void testBackupAsReplacementOfNearCache() { + String mapName = "apisMap"; + + Config config = new Config(); + config.getMapConfig(mapName).setBackupCount(20); + config.getMapConfig(mapName).setReadBackupData(true); + +// config.getNetworkConfig().getSocketInterceptorConfig(). + + + HazelcastInstance hOnGtw1 = Hazelcast.newHazelcastInstance(config); + assertEquals(20, hOnGtw1.getConfig().getMapConfig(mapName).getBackupCount()); + +// HazelcastInstance hOnGtw2 = Hazelcast.newHazelcastInstance(config); +// assertEquals(2, hOnGtw2.getConfig().getMapConfig(mapName).getBackupCount()); + + IMap apisMapOnG1 = hOnGtw1.getMap(mapName); + // Check that "apisMap" is replicated on gtw2 +// IMap apisMapOnG2 = hOnGtw2.getMap(mapName); + + apisMapOnG1.put("api10", "api1Policies"); +// apisMapOnG1.put("api2", "api2Policies"); +// apisMapOnG1.getLocalMapStats().getOwnedEntryCount() getBackupEntryCount() +// apisMapOnG1.getLocalMapStats().getOperationStats(). +// assertEquals(2, apisMapOnG1.localKeySet().size()); + + +// assertEquals(2, apisMapOnG2.size()); +// assertEquals(2, apisMapOnG2.localKeySet().size()); +// +// // Check that "apisMap" creation and updates are replicated on gtw1 +// apisMapOnG2.put("api3", "api3Policies"); +// assertEquals(3, apisMapOnG1.size()); +// assertEquals("api3Policies", apisMapOnG1.get("api3")); +// assertEquals(3, apisMapOnG2.localKeySet().size()); +// assertEquals(3, apisMapOnG1.localKeySet().size()); +// +// apisMapOnG2.put("api3", "api3Policies-bis"); +// assertEquals("api3Policies-bis", apisMapOnG1.get("api3")); +// assertEquals(3, apisMapOnG2.localKeySet().size()); +// assertEquals(3, apisMapOnG1.localKeySet().size()); + } + + @Test + public void testLockOnStandalone() throws InterruptedException { + Config cfg = new Config(); + cfg.getNetworkConfig().getJoin().getMulticastConfig().setEnabled(false); + + HazelcastInstance h1 = Hazelcast.newHazelcastInstance(cfg); + + String mapName = new Long (System.nanoTime()).toString(); + String key = "key", anotherKey = "anotherKey"; + + IMap map1 = h1.getMap(mapName); + map1.put(key, 1); + map1.put(anotherKey, 11); + + Thread writeThread1 = new Thread(new RunnableSimpleUpdate(key, 2, map1)); + Thread writeThread2 = new Thread(new RunnableSimpleUpdate(anotherKey, 12, map1)); + + RunnableSimpleRead runnableSimpleRead = new RunnableSimpleRead(key, map1); + assertNull(runnableSimpleRead.getValue()); + Thread readThread = new Thread(runnableSimpleRead); + + map1.lock(key); + + writeThread1.start(); + writeThread2.start(); + readThread.start(); + + Thread.sleep(2000); + + // check that locking a key does not preclude another thread to read the value + assertEquals(1, runnableSimpleRead.getValue().intValue()); + + // Check locking a key does not preclude updating another key + assertEquals(12, map1.get(anotherKey).intValue()); + + // Check that the value in the map was not updated by the concurrent thread + assertEquals(1, map1.get(key).intValue()); + + map1.put(key , 3); + // Check that the current thread + assertEquals(3, map1.get(key).intValue()); + + Thread.sleep(2000); + + // Check again that the value in the map was not updated by the concurrent thread + assertEquals(3, map1.get(key).intValue()); + + map1.unlock(key); + + Thread.sleep(2000); + + // Check that once unlocked, that the value in the map can be updated by another thread + assertEquals(2, map1.get(key).intValue()); + } + + @Test + public void testMapLockOnStandalone() throws InterruptedException { + Config cfg = new Config(); + cfg.getNetworkConfig().getJoin().getMulticastConfig().setEnabled(false); + + HazelcastInstance h1 = Hazelcast.newHazelcastInstance(cfg); + + String mapName = new Long (System.nanoTime()).toString(); + String key = "key", anotherKey = "anotherKey"; + + IMap map1 = h1.getMap(mapName); + map1.put(key, 1); + map1.put(anotherKey, 11); + + Thread writeThread1 = new Thread(new RunnableSimpleUpdate(key, 2, map1)); + Thread writeThread2 = new Thread(new RunnableSimpleUpdate(anotherKey, 12, map1)); + + RunnableSimpleRead runnableSimpleRead = new RunnableSimpleRead(key, map1); + assertNull(runnableSimpleRead.getValue()); + Thread readThread = new Thread(runnableSimpleRead); + + map1.lockMap(1, TimeUnit.SECONDS); + + writeThread1.start(); + writeThread2.start(); + readThread.start(); + + Thread.sleep(2000); + + // check that locking map does not preclude another thread to read entries + assertEquals(1, runnableSimpleRead.getValue().intValue()); + + // Check that the values in the map cannot be updated by a concurrent thread + assertEquals(1, map1.get(key).intValue()); + assertEquals(11, map1.get(anotherKey).intValue()); + + map1.put(key , 3); + map1.put(anotherKey, 13); + + Thread.sleep(2000); + + // Check again that the value in the map was not updated by the concurrent thread + assertEquals(3, map1.get(key).intValue()); + assertEquals(13, map1.get(anotherKey).intValue()); + + map1.unlockMap(); + + Thread.sleep(2000); + + // Check that once unlocked, that the value in the map can be updated by another thread + assertEquals(2, map1.get(key).intValue()); + assertEquals(12, map1.get(anotherKey).intValue()); + } + + @Test + public void testPutAll() { + Config cfg = new Config(); + cfg.getNetworkConfig().getJoin().getMulticastConfig().setEnabled(false); + + HazelcastInstance h1 = Hazelcast.newHazelcastInstance(cfg); + + String mapName = new Long (System.nanoTime()).toString(); + String mapName2 = new Long (System.nanoTime()).toString(); + + IMap map1 = h1.getMap(mapName); + IMap map2 = h1.getMap(mapName2); + + + map1.put(1, "un"); + map1.put(2, "deux"); + + map2.putAll(map1); + + assertEquals(2, map2.size()); + assertEquals("un", map2.get(1)); + assertEquals("deux", map2.get(2)); + } + + public class RunnableSimpleUpdate implements Runnable { + protected K key; + protected V value; + protected IMap map; + + public RunnableSimpleUpdate(K key, V value, IMap map) { + super(); + this.key = key; + this.value = value; + this.map = map; + } + + @Override + public void run() { + map.put(key, value); + } + + } + + public class RunnableSimpleRead implements Runnable { + protected K key; + protected V value = null; + protected IMap map; + + public RunnableSimpleRead(K key, IMap map) { + super(); + this.key = key; + this.map = map; + } + + @Override + public void run() { + value = map.get(key); + } + + public V getValue() { + return value; + } + + } + +} diff --git a/exposure-engine/common/src/test/java/com/alu/e3/common/caching/TestICacheImpl.java b/exposure-engine/common/src/test/java/com/alu/e3/common/caching/TestICacheImpl.java new file mode 100644 index 0000000..37e9e43 --- /dev/null +++ b/exposure-engine/common/src/test/java/com/alu/e3/common/caching/TestICacheImpl.java @@ -0,0 +1,212 @@ +/** + * Copyright © 2012 Alcatel-Lucent. + * + * See the NOTICE file distributed with this work for additional + * information regarding copyright ownership. + * Licensed to you 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 com.alu.e3.common.caching; + +import static org.junit.Assert.assertEquals; +import static org.junit.Assert.assertFalse; +import static org.junit.Assert.assertNotNull; +import static org.junit.Assert.assertNull; + +import java.io.File; +import java.net.UnknownHostException; +import java.util.jar.JarFile; + +import org.junit.Ignore; +import org.junit.Test; +import org.junit.runner.RunWith; +import org.springframework.beans.factory.annotation.Autowired; +import org.springframework.test.context.ContextConfiguration; +import org.springframework.test.context.junit4.SpringJUnit4ClassRunner; + +import com.alu.e3.common.tools.BundleTools; +import com.hazelcast.client.ClientConfig; +import com.hazelcast.client.HazelcastClient; +import com.hazelcast.core.HazelcastInstance; +import com.hazelcast.core.IMap; +import com.hazelcast.core.IQueue; +import com.hazelcast.core.Transaction; + +@RunWith(SpringJUnit4ClassRunner.class) +@ContextConfiguration(locations = {"classpath:common.spring-test.xml"} ) +public class TestICacheImpl { + + private final static String AUTH_MAP_NAME = "auth-cache"; + + @Autowired + protected ICacheTable authCache; + + @Autowired + protected HazelcastInstance instance; + + @Test + public void testAuthHazelcastInstance() { + assertNotNull(instance); + assertFalse(instance.getConfig().getNetworkConfig().getJoin().getMulticastConfig().isEnabled()); + + IMap map = instance.getMap(AUTH_MAP_NAME); + assertNotNull(map); + + assertEquals("LRU", instance.getConfig().getMapConfig(AUTH_MAP_NAME).getEvictionPolicy()); + } + + @Test + public void testAuthCacheSetUp() { + assertNotNull(authCache); + } + + @Test (expected=IllegalStateException.class) + public void testCommitThenRollback() { + Transaction transaction = instance.getTransaction(); + transaction.begin(); + IMap imap = instance.getMap(AUTH_MAP_NAME); + assertNull(imap.get("key")); + imap.put("key", "value"); + transaction.commit(); + // Check that when trying to rollback after having commited will throw an IllegalStageException + transaction.rollback(); + } + + @Test + public void testHazelcastJavaClient() throws UnknownHostException { + // Connect a client to the cluster + ClientConfig clientConfig = new ClientConfig() ; + clientConfig.addInetSocketAddress(instance.getCluster().getLocalMember().getInetSocketAddress()); + HazelcastClient client = HazelcastClient.newHazelcastClient(clientConfig); + + // Check that the entry is not in the cache before the client add it + assertNull(authCache.get("key1")); + + // Add a key/value in the cluster using the client + IMap mapClient = client.getMap(AUTH_MAP_NAME); + mapClient.put("key1", "value1"); + + // Check that the key/value was actually added in the cluster + assertEquals("value1", authCache.get("key1")); + } + + @Test + @Ignore + public void testJarProvisioning() throws Exception { + + String bundleFilePath = getClass().getResource("/test.jar").getFile(); + File bundleFile = new File (bundleFilePath); + + // Connect a client to the cluster + ClientConfig clientConfig = new ClientConfig() ; + clientConfig.addInetSocketAddress(instance.getCluster().getLocalMember().getInetSocketAddress()); + HazelcastClient client = HazelcastClient.newHazelcastClient(clientConfig); + + // Get a reference on the remote routes + IQueue provisionRouteQueue = client.getQueue("bundles-to-deploy"); + assertEquals(0, provisionRouteQueue.size()); + + IQueue provisionRouteResultQueue = client.getQueue("deployment-result"); + assertEquals(0, provisionRouteResultQueue.size()); + + // Send the bundle to be deployed to the Gateway/s + long provisionRouteTaskId = System.nanoTime(); + byte[] serializedBundle = BundleTools.file2ByteArray(bundleFile); + ProvisionRouteTask provisionRouteTask = new ProvisionRouteTask(provisionRouteTaskId, serializedBundle); + + provisionRouteQueue.add(provisionRouteTask); + + // Wait until the end of the deployment + ProvisionRouteResult provisionRouteResult = provisionRouteResultQueue.take(); + + JarFile generatedBundle = new JarFile(bundleFile); + String newBundlePath = provisionRouteResult.getBundlePath(); + JarFile outputBundle = new JarFile(newBundlePath); + + assertEquals (generatedBundle.size(), outputBundle.size()); + assertEquals(generatedBundle.getEntry("log4j.properties").getSize(), outputBundle.getEntry("log4j.properties").getSize()); + assertEquals(generatedBundle.getEntry("log4j.properties").getCrc(), outputBundle.getEntry("log4j.properties").getCrc()); + + // check that the provision result match with the route to be provisioned + assertEquals (provisionRouteTaskId, provisionRouteResult.getProvisionRouteId()); + + // check that the task for the route to be provisionned does not exist anymore + assertEquals(0, provisionRouteQueue.size()); + + // check that all provisioning result were processed + assertEquals(0, provisionRouteResultQueue.size()); + + // Send the bundle to be deployed to the Gateway/s + provisionRouteTaskId = System.nanoTime(); + provisionRouteTask = new ProvisionRouteTask(provisionRouteTaskId, serializedBundle); + + provisionRouteQueue.add(provisionRouteTask); + + // Wait until the end of the deployment + provisionRouteResult = provisionRouteResultQueue.take(); + + // check that the provision result match with the route to be provisioned + assertEquals (provisionRouteTaskId, provisionRouteResult.getProvisionRouteId()); + + // check that the task for the route to be provisionned does not exist anymore + assertEquals(0, provisionRouteQueue.size()); + + // check that all provisioning result were processed + assertEquals(0, provisionRouteResultQueue.size()); + } + + /* + * Utils + */ + + public class RunnableSimpleUpdate implements Runnable { + protected K key; + protected V value; + protected ICacheTable cache; + + public RunnableSimpleUpdate(K key, V value, ICacheTable cache) { + super(); + this.key = key; + this.value = value; + this.cache = cache; + } + + @Override + public void run() { + cache.set(key, value); + } + + } + + public class RunnableSimpleRead implements Runnable { + protected K key; + protected V value = null; + protected ICacheTable cache; + + public RunnableSimpleRead(K key, ICacheTable cache) { + super(); + this.key = key; + this.cache = cache; + } + + @Override + public void run() { + value = cache.get(key); + } + + public V getValue() { + return value; + } + } + +} diff --git a/exposure-engine/common/src/test/java/com/alu/e3/common/caching/transaction/TestOperation.java b/exposure-engine/common/src/test/java/com/alu/e3/common/caching/transaction/TestOperation.java new file mode 100644 index 0000000..9fcea15 --- /dev/null +++ b/exposure-engine/common/src/test/java/com/alu/e3/common/caching/transaction/TestOperation.java @@ -0,0 +1,100 @@ +/** + * Copyright © 2012 Alcatel-Lucent. + * + * See the NOTICE file distributed with this work for additional + * information regarding copyright ownership. + * Licensed to you 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 com.alu.e3.common.caching.transaction; + +import static org.junit.Assert.assertEquals; +import static org.junit.Assert.assertNotNull; +import static org.junit.Assert.assertNull; + +import java.security.InvalidParameterException; + +import org.junit.Test; + +import com.alu.e3.common.caching.HashCacheTable; +import com.alu.e3.common.transaction.Operation; +import com.alu.e3.common.transaction.OperationType; + +public class TestOperation { + + @Test (expected = InvalidParameterException.class) + public void testNewOperationIvalidParameter() { + new Operation(OperationType.CREATE, new Object(), new Object(), null); + } + + @Test (expected = InvalidParameterException.class) + public void testNewOperationIvalidParameter2() { + new Operation(OperationType.CREATE, null, new Object(), new HashCacheTable()); + } + + @Test + public void testRollbackCreate() { + HashCacheTable cacheTable = new HashCacheTable(); + + Operation operation = new Operation(OperationType.CREATE, 1, null, cacheTable); + cacheTable.set(1, "one"); + assertNotNull(cacheTable.get(1)); + + operation.rollback(); + + assertNull(cacheTable.get(1)); + } + + @Test + public void testRollbackRead() { + HashCacheTable cacheTable = new HashCacheTable(); + + cacheTable.set(1, "one"); + assertNotNull(cacheTable.get(1)); + + Operation operation = new Operation(OperationType.READ, 1, null, cacheTable); + + operation.rollback(); + + assertEquals("one", cacheTable.get(1)); + } + + @Test + public void testRollbackUpdate() { + + HashCacheTable cacheTable = new HashCacheTable(); + + Operation operation = new Operation(OperationType.UPDATE, 1, "one", cacheTable); + cacheTable.set(1, "un"); + assertEquals("un", cacheTable.get(1)); + + operation.rollback(); + + assertEquals("one", cacheTable.get(1)); + } + + @Test + public void testRollbackDelete() { + HashCacheTable cacheTable = new HashCacheTable(); + + Operation operation = new Operation(OperationType.DELETE, 1, "one", cacheTable); + cacheTable.remove(1); + assertNull(cacheTable.get(1)); + + operation.rollback(); + + assertEquals("one", cacheTable.get(1)); + } + + +} diff --git a/exposure-engine/common/src/test/java/com/alu/e3/common/caching/transaction/TestTransactionManagement.java b/exposure-engine/common/src/test/java/com/alu/e3/common/caching/transaction/TestTransactionManagement.java new file mode 100644 index 0000000..48f87f8 --- /dev/null +++ b/exposure-engine/common/src/test/java/com/alu/e3/common/caching/transaction/TestTransactionManagement.java @@ -0,0 +1,158 @@ +/** + * Copyright © 2012 Alcatel-Lucent. + * + * See the NOTICE file distributed with this work for additional + * information regarding copyright ownership. + * Licensed to you 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 com.alu.e3.common.caching.transaction; + +import static org.junit.Assert.assertNotNull; +import static org.junit.Assert.assertNull; +import static org.junit.Assert.assertEquals; +import static org.junit.Assert.assertTrue; + +import java.util.concurrent.Callable; +import java.util.concurrent.ExecutorService; +import java.util.concurrent.Executors; + +import org.junit.Test; + +import com.alu.e3.common.transaction.ITransaction; +import com.alu.e3.common.transaction.ITransactionManager; +import com.alu.e3.common.transaction.TransactionManager; +import com.alu.e3.common.transaction.TransactionContext; + +public class TestTransactionManagement { + + @Test + public void testTransactionInCurrentThread() throws Exception { + ITransactionManager txMnger = new TransactionManager(); + assertNull(txMnger.getTransactionContext()); + + // create, begin, commit, end + ITransaction tx = txMnger.getNewTransaction(); + assertNotNull(tx); + + // Not transaction id until the transaction has begun + assertNull(tx.getTransactionId()); + // Not transaction context until the transaction has begun + assertNull(txMnger.getTransactionContext()); + + + tx.begin(); + assertNotNull (tx.getTransactionId()); + assertNotNull (txMnger.getTransactionContext().getTransactionId()); + assertEquals (txMnger.getTransactionContext().getTransactionId(), tx.getTransactionId()); + + tx.commit(); + assertNotNull (tx.getTransactionId()); + assertNotNull (txMnger.getTransactionContext().getTransactionId()); + assertEquals (txMnger.getTransactionContext().getTransactionId(), tx.getTransactionId()); + + tx.end(); + assertNull(tx.getTransactionId()); + assertNull(txMnger.getTransactionContext()); + + // create, begin, rollback + tx = txMnger.getNewTransaction(); + assertNull(tx.getTransactionId()); + assertNull(txMnger.getTransactionContext()); + + tx.begin(); + assertNotNull (tx.getTransactionId()); + assertNotNull (txMnger.getTransactionContext().getTransactionId()); + assertEquals (txMnger.getTransactionContext().getTransactionId(), tx.getTransactionId()); + + tx.rollback(); + assertNull(tx.getTransactionId()); + assertNull(txMnger.getTransactionContext()); + + // begin, commit, rollback + tx = txMnger.getNewTransaction(); + assertNull(tx.getTransactionId()); + assertNull(txMnger.getTransactionContext()); + + tx.begin(); + assertNotNull (tx.getTransactionId()); + assertNotNull (txMnger.getTransactionContext().getTransactionId()); + assertEquals (txMnger.getTransactionContext().getTransactionId(), tx.getTransactionId()); + + tx.commit(); + assertNotNull (tx.getTransactionId()); + assertNotNull (txMnger.getTransactionContext().getTransactionId()); + assertEquals (txMnger.getTransactionContext().getTransactionId(), tx.getTransactionId()); + + tx.rollback(); + assertNull(tx.getTransactionId()); + assertNull(txMnger.getTransactionContext()); + } + + @Test + public void testTransactionStateOverThreads() throws Exception { + + ExecutorService executor1 = Executors.newSingleThreadScheduledExecutor(); + + // Create, then begin a transaction + TransactionContext transactionState1 = executor1.submit( new Callable() { + @Override + public TransactionContext call() throws Exception { + ITransactionManager txMnger = new TransactionManager(); + ITransaction tx = txMnger.getNewTransaction(); + tx.begin(); + return txMnger.getTransactionContext(); + } + }).get(); + + assertNotNull(transactionState1); + assertNotNull(transactionState1.getTransactionId()); + + // Later, a method in the same thread stack should be able to deal with the same transaction context + TransactionContext transactionState2 = executor1.submit( new Callable() { + @Override + public TransactionContext call() throws Exception { + ITransactionManager txMnger = new TransactionManager(); + return txMnger.getTransactionContext(); + } + }).get(); + + assertNotNull(transactionState2); + assertNotNull(transactionState2.getTransactionId()); + assertEquals(transactionState1.getTransactionId(), transactionState2.getTransactionId()); + + // The transaction in a thread must not be viewable from another thread + ExecutorService executor2 = Executors.newSingleThreadScheduledExecutor(); + TransactionContext transactionState3 = executor2.submit( new Callable() { + @Override + public TransactionContext call() throws Exception { + ITransactionManager txMnger = new TransactionManager(); + return txMnger.getTransactionContext(); + } + }).get(); + assertNull (transactionState3); + + transactionState3 = executor2.submit( new Callable() { + @Override + public TransactionContext call() throws Exception { + ITransactionManager txMnger = new TransactionManager(); + ITransaction tx = txMnger.getNewTransaction(); + tx.begin(); + return txMnger.getTransactionContext(); + } + }).get(); + + assertNotNull (transactionState3); + assertTrue(transactionState1.getTransactionId() != transactionState3.getTransactionId()); + } +} diff --git a/exposure-engine/common/src/test/java/com/alu/e3/common/healthcheck/HealthCheckServiceTest.java b/exposure-engine/common/src/test/java/com/alu/e3/common/healthcheck/HealthCheckServiceTest.java new file mode 100644 index 0000000..62278c2 --- /dev/null +++ b/exposure-engine/common/src/test/java/com/alu/e3/common/healthcheck/HealthCheckServiceTest.java @@ -0,0 +1,76 @@ +/** + * Copyright © 2012 Alcatel-Lucent. + * + * See the NOTICE file distributed with this work for additional + * information regarding copyright ownership. + * Licensed to you 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 com.alu.e3.common.healthcheck; + +import static org.junit.Assert.assertFalse; +import static org.junit.Assert.assertNotNull; +import static org.junit.Assert.assertTrue; + +import org.junit.After; +import org.junit.Before; +import org.junit.Test; + +import com.alu.e3.common.osgi.api.IHealthCheckFactory; +import com.alu.e3.data.IHealthCheckService; + +public class HealthCheckServiceTest { + + private IHealthCheckService hcs; + + public HealthCheckServiceTest() { + } + + @Before + public void setUp() throws Exception { + + hcs = new HealthCheckService(IHealthCheckFactory.GATEWAY_TYPE); + } + + @After + public void tearDown() throws Exception { + } + + @Test + public void testHealthCheck() { + assertNotNull("Check that healthcheck service is not null", hcs); + + hcs.start(); + + assertFalse(hcs.check("FakeHost")); + assertTrue(hcs.check("")); //localhost + + hcs.stop(); + } + + @Test + public void testHealthCheck2() { + assertNotNull("Check that healthcheck service is not null", hcs); + +// hcs.start(); +// +// assertFalse(hcs.check("FakeHost")); +// assertTrue(hcs.check("")); //localhost +// +// hcs.stop(); +// +// hcs.start(); +// assertTrue(hcs.check("")); //localhost +// hcs.stop(); + } +} \ No newline at end of file diff --git a/exposure-engine/common/src/test/java/com/alu/e3/common/tools/ExpiringSetTest.java b/exposure-engine/common/src/test/java/com/alu/e3/common/tools/ExpiringSetTest.java new file mode 100644 index 0000000..a46ab2f --- /dev/null +++ b/exposure-engine/common/src/test/java/com/alu/e3/common/tools/ExpiringSetTest.java @@ -0,0 +1,74 @@ +/** + * Copyright © 2012 Alcatel-Lucent. + * + * See the NOTICE file distributed with this work for additional + * information regarding copyright ownership. + * Licensed to you 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 com.alu.e3.common.tools; + +import static org.junit.Assert.*; + +import org.junit.Test; + +public class ExpiringSetTest { + + @Test + public void testCreation() { + ExpiringSet expiringSet = new ExpiringSet(5 * 60); + assertNotNull(expiringSet); + } + + @Test + public void testAdd() throws InterruptedException { + ExpiringSet expiringSet = new ExpiringSet(2); // seconds + assertFalse(expiringSet.contains("hello")); + assertTrue(expiringSet.contains("hello")); + } + + @Test + public void testExpire() throws InterruptedException { + ExpiringSet expiringSet = new ExpiringSet(2); // seconds + assertFalse(expiringSet.contains("hello")); + assertTrue(expiringSet.contains("hello")); + Thread.sleep(3 * 1000); + assertFalse(expiringSet.contains("hello")); + assertTrue(expiringSet.contains("hello")); + } + + @Test + public void testLiveExpire() throws InterruptedException { + ExpiringSet expiringSet = new ExpiringSet(2); // seconds + assertFalse(expiringSet.contains("hello")); + assertTrue(expiringSet.contains("hello")); + int i = 0; + while (i++ < 1000000) { + if (!expiringSet.contains("hello")) { + break; + } + Thread.sleep(1); + } + assertTrue(expiringSet.contains("hello")); + assert(i > 1000); + assert(i < 1000000); + } + + @Test + public void testShutdown() throws InterruptedException { + ExpiringSet expiringSet = new ExpiringSet(2); // seconds + assertFalse(expiringSet.contains("hello")); + assertTrue(expiringSet.contains("hello")); + expiringSet.shutdown(); + } +} diff --git a/exposure-engine/common/src/test/java/com/alu/e3/common/tools/WsseToolsTest.java b/exposure-engine/common/src/test/java/com/alu/e3/common/tools/WsseToolsTest.java new file mode 100644 index 0000000..da37f0c --- /dev/null +++ b/exposure-engine/common/src/test/java/com/alu/e3/common/tools/WsseToolsTest.java @@ -0,0 +1,161 @@ +/** + * Copyright © 2012 Alcatel-Lucent. + * + * See the NOTICE file distributed with this work for additional + * information regarding copyright ownership. + * Licensed to you 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 com.alu.e3.common.tools; + +import static org.junit.Assert.*; + +import java.io.ByteArrayInputStream; +import java.io.InputStream; +import java.text.ParseException; + +import org.junit.Test; + +import com.alu.e3.common.tools.WsseTools.WsseUsernameToken; + +public class WsseToolsTest { + + private static final String WSSE_XML_REQUEST = "" + + "\n" + + "\n" + + " \n" + + " \n" + + " \n" + + " wally\n" + + " c3dvcmRmaXNo\n" + + " 0123456789\n" + + " 2012-03-27T01:23:45Z\n" + + " \n" + + " \n" + + " \n" + + " \n" + + " \n" + + " My Simple Service Request\n" + + " \n" + + " \n" + + "\n" + + ""; + + private static final String WSSE_XML_PASSWORDTEXT_REQUEST = "" + + "\n" + + "\n" + + " \n" + + " \n" + + " \n" + + " wally\n" + + " c3dvcmRmaXNo\n" + + " 0123456789\n" + + " 2012-03-27T01:23:45Z\n" + + " \n" + + " \n" + + " \n" + + " \n" + + " \n" + + " My Simple Service Request\n" + + " \n" + + " \n" + + "\n" + + ""; + + private static final String BAD_WSSE_XML_REQUEST = "" + + "\n" + + "\n" + + " \n" + + " \n" + + " \n" + + " wally\n" + + " c3dvcmRmaXNo\n" + + " 0123456789\n" + + " 2012-03-27T01:23:45Z\n" +// missing + " \n" + + " \n" + + " \n" + + " \n" + + " \n" + + " My Simple Service Request\n" + + " \n" + + " \n" + + "\n" + + ""; + + private static final String BAD2_WSSE_XML_REQUEST = "" + + "\n" + + "\n" + + " \n" + + " \n" + + " \n" + + " wally\n" + + " c3dvcmRmaXNo\n" + + " 0123456789\n" + + " 2012-03-27T01:23:45Z\n" +/* extra */ + " 0123456789\n" + + " \n" + + " \n" + + " \n" + + " \n" + + " \n" + + " My Simple Service Request\n" + + " \n" + + " \n" + + "\n" + + ""; + + @Test + public void testXmlInput() throws Exception { + InputStream in = new ByteArrayInputStream(WSSE_XML_REQUEST.getBytes()); + WsseUsernameToken wsseUsernameToken = WsseTools.parseXml(in); + assertNotNull(wsseUsernameToken); + assertEquals("wally", wsseUsernameToken.getUsername()); + assertEquals("c3dvcmRmaXNo", wsseUsernameToken.getPassword()); + assertEquals("0123456789", wsseUsernameToken.getNonce()); + assertEquals("2012-03-27T01:23:45Z", wsseUsernameToken.getCreated()); + assertFalse(wsseUsernameToken.isPasswordText()); + } + + @Test + public void testXmlInputPasswordText() throws Exception { + InputStream in = new ByteArrayInputStream(WSSE_XML_PASSWORDTEXT_REQUEST.getBytes()); + WsseUsernameToken wsseUsernameToken = WsseTools.parseXml(in); + assertNotNull(wsseUsernameToken); + assertEquals("wally", wsseUsernameToken.getUsername()); + assertEquals("c3dvcmRmaXNo", wsseUsernameToken.getPassword()); + assertEquals("0123456789", wsseUsernameToken.getNonce()); + assertEquals("2012-03-27T01:23:45Z", wsseUsernameToken.getCreated()); + assertTrue(wsseUsernameToken.isPasswordText()); + } + + @Test + public void testBadXmlInput() throws ParseException { + InputStream in = new ByteArrayInputStream(BAD_WSSE_XML_REQUEST.getBytes()); + try { + WsseTools.parseXml(in); + fail("Expected parse exception (bad XML), but it didn't happen."); + } catch (Exception e) { + } + } + + @Test + public void testRedundantElement() throws ParseException { + InputStream in = new ByteArrayInputStream(BAD2_WSSE_XML_REQUEST.getBytes()); + try { + WsseTools.parseXml(in); + fail("Expected parse exception (redundant element), but it didn't happen."); + } catch (Exception e) { + } + } +} diff --git a/exposure-engine/common/src/test/java/com/alu/e3/data/DataManagerTest.java b/exposure-engine/common/src/test/java/com/alu/e3/data/DataManagerTest.java new file mode 100644 index 0000000..a23eb8c --- /dev/null +++ b/exposure-engine/common/src/test/java/com/alu/e3/data/DataManagerTest.java @@ -0,0 +1,1231 @@ +/** + * Copyright © 2012 Alcatel-Lucent. + * + * See the NOTICE file distributed with this work for additional + * information regarding copyright ownership. + * Licensed to you 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 com.alu.e3.data; + +import static org.junit.Assert.assertEquals; +import static org.junit.Assert.assertNotNull; +import static org.junit.Assert.assertNull; +import static org.junit.Assert.assertTrue; + +import java.util.ArrayList; +import java.util.List; +import java.util.Set; + +import org.junit.After; +import org.junit.Before; +import org.junit.Test; + +import com.alu.e3.common.InvalidIDException; +import com.alu.e3.common.caching.HazelcastCacheManager; +import com.alu.e3.data.model.Api; +import com.alu.e3.data.model.ApiDetail; +import com.alu.e3.data.model.Auth; +import com.alu.e3.data.model.AuthDetail; +import com.alu.e3.data.model.CallDescriptor; +import com.alu.e3.data.model.Policy; +import com.alu.e3.data.model.enumeration.NBAuthType; +import com.alu.e3.data.model.enumeration.StatusType; +import com.alu.e3.data.model.sub.QuotaRLBucket; + +public class DataManagerTest { + + private DataManager dataManager; + private HazelcastCacheManager cacheManager; + + public DataManagerTest() { + } + + @Before + public void setUp() throws Exception { + dataManager = new DataManager(); + TopologyClient topologyClient = new TopologyClient(); + dataManager.setTopologyClient(topologyClient); + cacheManager = new HazelcastCacheManager(); + cacheManager.setTopologyClient(topologyClient); + cacheManager.init(true); + dataManager.setCacheManager(cacheManager); + dataManager.init(); + } + + @After + public void tearDown() throws Exception { + cacheManager.destroy(); + dataManager.destroy(); + } + + @Test + public void testDataManager() { + assertNotNull("Check that DataManager is not null", dataManager); + } + + @Test + public void testAddGetRemoveApi() { + + // Add a new API + Api api = new Api(); + api.setId("id1"); + api.setApiDetail(new ApiDetail()); + api.getApiDetail().setEndpoint("http://www.google.com"); + dataManager.addApi(api); + + // Now, get the "simple" API and check that it's OK + Api api2 = dataManager.getApiById("id1"); + assertNotNull("API was added/returned", api2); + assertNull("API details is null", api2.getApiDetail()); + + // Now, get the "full" API and check that it's OK + Api api3 = dataManager.getApiById("id1", true); + assertNotNull("API was added/returned", api3); + assertEquals("API values are correct", api.getApiDetail().getEndpoint(), api3.getApiDetail().getEndpoint()); + + dataManager.removeApi("id1"); + + boolean isInvalidID = false; + + try { + dataManager.getApiById("id1"); + } + catch (InvalidIDException e) { + isInvalidID = true; + } + + assertTrue("API was found and removed", isInvalidID); + } + + @Test + public void testAddTwiceApi() { + + // Add a new API + Api api = new Api(); + api.setId("id1"); + api.setApiDetail(new ApiDetail()); + api.getApiDetail().setEndpoint("http://www.google.com"); + dataManager.addApi(api); + + boolean exceptionRaised = false; + try + { + dataManager.addApi(api); + } + catch(Exception e) + { + exceptionRaised = true; + } + + assertTrue("Exception raised", exceptionRaised); + + // cleanup + dataManager.removeApi(api.getId()); + } + + @Test + public void testGetAllApi() { + + // Add a new API + Api api = new Api(); + api.setId("id10"); + api.setApiDetail(new ApiDetail()); + api.getApiDetail().setEndpoint("http://www.google.com"); + dataManager.addApi(api); + + // Add a new API + Api api2 = new Api(); + api2.setId("id2"); + api2.setApiDetail(new ApiDetail()); + api2.getApiDetail().setEndpoint("http://www.yahoo.com"); + dataManager.addApi(api2); + + Set apis = dataManager.getAllApiIds(); + assertNotNull("No apis found", apis); + + List apisList = new ArrayList(); + + for (String apiStr : apis) { + apisList.add(apiStr); + } + + assertEquals("API count is correct", 2, apisList.size()); + assertTrue("Both APIs are found", (api.getId().equals(apisList.get(0)) || api2.getId().equals(apisList.get(0))) && (api.getId().equals(apisList.get(1)) || api2.getId().equals(apisList.get(1)))); + + // cleanup + dataManager.removeApi(api.getId()); + dataManager.removeApi(api2.getId()); + } + + @Test + public void testAddGetRemoveAuth() { + + // Add a new Auth + Auth auth = new Auth(); + auth.setId("id2"); + auth.setAuthDetail(new AuthDetail()); + auth.getAuthDetail().setUsername("username"); + auth.getAuthDetail().setType(NBAuthType.AUTHKEY); + auth.getAuthDetail().setAuthKeyValue("authKey"); + dataManager.addAuth(auth); + + // Now, get the "simple" Auth and check that it's OK + Auth auth2 = dataManager.getAuthById("id2"); + assertNotNull("Auth was added/returned", auth2); + assertNull("Auth details is null", auth2.getAuthDetail()); + + // Now, get the "full" Auth and check that it's OK + Auth auth3 = dataManager.getAuthById("id2", true); + assertNotNull("Auth was added/returned", auth3); + assertEquals("Auth values are correct", auth.getAuthDetail().getUsername(), auth3.getAuthDetail().getUsername()); + + dataManager.removeAuth("id2"); + + boolean isInvalidID = false; + + try { + dataManager.getAuthById("id2"); + } + catch (InvalidIDException e) { + isInvalidID = true; + } + + assertTrue("Auth was found and removed", isInvalidID); + } + + @Test + public void testAddAuthThenUpdate() { + + // Add a new Auth + Auth auth = new Auth(); + auth.setId("id2"); + auth.setAuthDetail(new AuthDetail()); + auth.getAuthDetail().setUsername("username"); + auth.getAuthDetail().setType(NBAuthType.AUTHKEY); + auth.getAuthDetail().setAuthKeyValue("authKey"); + dataManager.addAuth(auth); + + // Now, get the "simple" Auth and check that it's OK + Auth auth2 = dataManager.getAuthById("id2", true); + assertNotNull("Auth was added/returned", auth2); + + auth2.getAuthDetail().setAuthKeyValue("authKey2"); + dataManager.updateAuth(auth2); + + // Now, get the "full" Auth and check that it's OK + Auth auth3 = dataManager.getAuthById("id2", true); + assertNotNull("Auth was added/returned", auth3); + assertEquals("Auth values are correct", auth2.getAuthDetail().getAuthKeyValue(), auth3.getAuthDetail().getAuthKeyValue()); + + dataManager.removeAuth("id2"); + + boolean isInvalidID = false; + + try { + dataManager.getAuthById("id2"); + } + catch (InvalidIDException e) { + isInvalidID = true; + } + + assertTrue("Auth was found and removed", isInvalidID); + } + + @Test + public void testAddTwiceAuthSameId() { + + // Add a new Auth + Auth auth = new Auth(); + auth.setId("id2"); + auth.setAuthDetail(new AuthDetail()); + auth.getAuthDetail().setType(NBAuthType.AUTHKEY); + auth.getAuthDetail().setAuthKeyValue("authKey"); + dataManager.addAuth(auth); + + // Add a new Auth + Auth auth2 = new Auth(); + auth2.setId("id2"); + auth2.setAuthDetail(new AuthDetail()); + auth2.getAuthDetail().setType(NBAuthType.AUTHKEY); + auth2.getAuthDetail().setAuthKeyValue("authKey2"); + + boolean exceptionRaised = false; + try + { + dataManager.addAuth(auth2); + } + catch(Exception e) + { + exceptionRaised = true; + } + + assertTrue("Exception raised", exceptionRaised); + + // cleanup + dataManager.removeAuth(auth.getId()); + } + + @Test + public void testAddTwiceAuthSameToken() { + + // Add a new Auth + Auth auth = new Auth(); + auth.setId("id2"); + auth.setAuthDetail(new AuthDetail()); + auth.getAuthDetail().setUsername("username"); + auth.getAuthDetail().setType(NBAuthType.AUTHKEY); + auth.getAuthDetail().setAuthKeyValue("authKey"); + dataManager.addAuth(auth); + + Auth auth2 = new Auth(); + auth2.setId("id3"); + auth2.setAuthDetail(new AuthDetail()); + auth2.getAuthDetail().setUsername("username"); + auth2.getAuthDetail().setType(NBAuthType.AUTHKEY); + auth2.getAuthDetail().setAuthKeyValue("authKey"); + + boolean wasException = false; + try + { + dataManager.addAuth(auth2); + } + catch (Exception e) + { + wasException = true; + } + + assertTrue("Second auth with same API key was refused", wasException); + + // cleanup for next test + dataManager.removeAuth(auth.getId()); + } + + @Test + public void testAddTwiceAuthSameIP() { + + // Add a new Auth + Auth auth = new Auth(); + auth.setId("id2"); + auth.setAuthDetail(new AuthDetail()); + auth.getAuthDetail().setType(NBAuthType.IP_WHITE_LIST); + auth.getAuthDetail().getWhiteListedIps().add("12.34.56.78"); + dataManager.addAuth(auth); + + Auth auth2 = new Auth(); + auth2.setId("id3"); + auth2.setAuthDetail(new AuthDetail()); + auth2.getAuthDetail().setType(NBAuthType.IP_WHITE_LIST); + auth2.getAuthDetail().getWhiteListedIps().add("12.34.56.78"); + + boolean wasException = false; + try + { + dataManager.addAuth(auth2); + } + catch (Exception e) + { + wasException = true; + } + + assertTrue("Second auth with same API key was refused", wasException); + + // cleanup for next test + dataManager.removeAuth(auth.getId()); + + + + // Add a new Auth + auth = new Auth(); + auth.setId("id2"); + auth.setAuthDetail(new AuthDetail()); + auth.getAuthDetail().setType(NBAuthType.IP_WHITE_LIST); + auth.getAuthDetail().getWhiteListedIps().add("12.34.56.78"); + dataManager.addAuth(auth); + + auth2 = new Auth(); + auth2.setId("id3"); + auth2.setAuthDetail(new AuthDetail()); + auth2.getAuthDetail().setType(NBAuthType.IP_WHITE_LIST); + auth2.getAuthDetail().getWhiteListedIps().add("112.34.56.78"); + dataManager.addAuth(auth2); + + auth2.getAuthDetail().getWhiteListedIps().clear(); + auth2.getAuthDetail().getWhiteListedIps().add("12.34.56.78"); + + wasException = false; + try + { + dataManager.updateAuth(auth2); + } + catch (Exception e) + { + wasException = true; + } + + assertTrue("Second auth with same API key was refused", wasException); + + // cleanup for next test + dataManager.removeAuth(auth.getId()); + dataManager.removeAuth(auth2.getId()); + + } + + @Test + public void testGetAllAuth() { + + // Add a new Auth + Auth auth = new Auth(); + auth.setId("id1"); + auth.setAuthDetail(new AuthDetail()); + auth.getAuthDetail().setUsername("username1"); + auth.getAuthDetail().setType(NBAuthType.AUTHKEY); + auth.getAuthDetail().setAuthKeyValue("authKey1"); + dataManager.addAuth(auth); + + Auth auth2 = new Auth(); + auth2.setId("id2"); + auth2.setAuthDetail(new AuthDetail()); + auth2.getAuthDetail().setUsername("username"); + auth2.getAuthDetail().setType(NBAuthType.AUTHKEY); + auth2.getAuthDetail().setAuthKeyValue("authKey2"); + dataManager.addAuth(auth2); + + Set auths = dataManager.getAllAuthIds(); + assertNotNull("No auth found", auths); + + List authList = new ArrayList(); + + for (String authStr : auths) { + authList.add(authStr); + } + + assertEquals("Auth count is correct", 2, authList.size()); + assertTrue("Both Auths are found", (authList.get(0).equals(auth.getId()) || authList.get(0).equals(auth2.getId())) && (authList.get(1).equals(auth.getId()) || authList.get(1).equals(auth2.getId()))); + + // cleanup for next test + dataManager.removeAuth(auth.getId()); + dataManager.removeAuth(auth2.getId()); + } + + @Test + public void testAddGetRemovePolicy() { + + // Add a new Policy + Policy policy = new Policy(); + policy.setId("id3"); + dataManager.addPolicy(policy); + + // Now, get the API and check that it's OK + Policy policy2 = dataManager.getPolicyById("id3"); + assertNotNull("Policy was added/returned", policy2); + + dataManager.removePolicy("id3"); + + boolean isInvalidID = false; + + try { + dataManager.getPolicyById("id3"); + } + catch (InvalidIDException e) { + isInvalidID = true; + } + + assertTrue("Policy was found and removed", isInvalidID); + } + + @Test + public void testAddTwicePolicy() { + + // Add a new API + Policy policy = new Policy(); + policy.setId("id3"); + dataManager.addPolicy(policy); + + boolean exceptionRaised = false; + try + { + dataManager.addPolicy(policy); + } + catch(Exception e) + { + exceptionRaised = true; + } + + assertTrue("Exception raised", exceptionRaised); + + // cleanup + dataManager.removePolicy(policy.getId()); + } + + @Test + public void testGetAllPolicy() { + + // Add a new Policy + Policy policy = new Policy(); + policy.setId("id1"); + dataManager.addPolicy(policy); + + // Add a new Policy + Policy policy2 = new Policy(); + policy2.setId("id2"); + dataManager.addPolicy(policy2); + + Set policies = dataManager.getAllPolicy(); + assertNotNull("No policy found", policies); + + List policyList = new ArrayList(); + + for (String policyStr : policies) { + policyList.add(policyStr); + } + + assertEquals("Auth count is correct", 2, policyList.size()); + assertTrue("Both Auths are found", (policyList.get(0).equals(policy.getId()) || policyList.get(0).equals(policy2.getId())) && (policyList.get(1).equals(policy.getId()) || policyList.get(1).equals(policy2.getId()))); + + // cleanup + dataManager.removePolicy(policy.getId()); + dataManager.removePolicy(policy2.getId()); + } + + @Test + public void testAddPolicyAndUpdateApiAuthThenRemovePolicy() { + + // Add a new API + Api api = new Api(); + api.setId("id1"); + api.setApiDetail(new ApiDetail()); + dataManager.addApi(api); + + // Add a new Auth + Auth auth = new Auth(); + auth.setId("id2"); + auth.setAuthDetail(new AuthDetail()); + auth.getAuthDetail().setType(NBAuthType.AUTHKEY); + auth.getAuthDetail().setAuthKeyValue("authKey10"); + dataManager.addAuth(auth); + + // Add a new Policy + Policy policy = new Policy(); + policy.setId("id3"); + policy.getApiIds().add(api.getId()); + dataManager.addPolicy(policy); + + // Create bucket + QuotaRLBucket authIds = new QuotaRLBucket(); + authIds.setId("id3"); + authIds.getAuthIds().add(auth.getId()); + dataManager.createBucket(policy.getId(), authIds); + + // Now, get the API and check that it's OK + Api api2 = dataManager.getApiById("id1"); + assertEquals("API has new policy", policy.getId(), api2.getPolicyIds().get(0)); + + // Now, get the Auth and check that it's OK + Auth auth2 = dataManager.getAuthById("id2"); + assertEquals("Auth has new policy", policy.getId(), auth2.getPolicyContexts().get(0).getPolicyId()); + + // Check that bucket is added correctly to policy + policy = dataManager.getPolicyById(policy.getId()); + assertEquals("Correct number of buckets for policy", 1, policy.getAuthIds().size()); + assertEquals("Policy has new bucket", authIds.getId(), policy.getAuthIds().get(0).getId()); + + dataManager.removePolicy(policy.getId()); + + // Now, get the API and check that it's OK + Api api3 = dataManager.getApiById("id1"); + assertEquals("API has no policy", 0, api3.getPolicyIds().size()); + + // Now, get the API and check that it's OK + Auth auth3 = dataManager.getAuthById("id2"); + assertEquals("Auth has no policy", 0, auth3.getPolicyContexts().size()); + + // cleanup + dataManager.removeApi(api.getId()); + dataManager.removeAuth(auth.getId()); + } + + @Test + public void testAddPolicyAndUpdateApiAuthThenRemoveApi() { + + // Add a new API + Api api = new Api(); + api.setApiDetail(new ApiDetail()); + api.setId("id51"); + dataManager.addApi(api); + + // Add a new Auth + Auth auth = new Auth(); + auth.setId("id52"); + auth.setAuthDetail(new AuthDetail()); + auth.getAuthDetail().setType(NBAuthType.AUTHKEY); + auth.getAuthDetail().setAuthKeyValue("authKey20"); + dataManager.addAuth(auth); + + // Add a new Policy + Policy policy = new Policy(); + policy.setId("id53"); + policy.getApiIds().add(api.getId()); + QuotaRLBucket authIds = new QuotaRLBucket(); + authIds.setId("bucketId"); + authIds.getAuthIds().add(auth.getId()); + policy.getAuthIds().add(authIds); + dataManager.addPolicy(policy); + + dataManager.removeApi(api.getId()); + + // Now, get the Policy and check that it's OK + Policy policy2 = dataManager.getPolicyById(policy.getId()); + assertEquals("Policy has no API id", 0, policy2.getApiIds().size()); + + // cleanup + dataManager.removeAuth(auth.getId()); + } + + @Test + public void testAddPolicyAndUpdateApiAuthThenRemoveAuth() { + + // Add a new API + Api api = new Api(); + api.setId("id61"); + api.setApiDetail(new ApiDetail()); + dataManager.addApi(api); + + // Add a new Auth + Auth auth = new Auth(); + auth.setId("id62"); + auth.setAuthDetail(new AuthDetail()); + auth.getAuthDetail().setType(NBAuthType.AUTHKEY); + auth.getAuthDetail().setAuthKeyValue("authKey30"); + dataManager.addAuth(auth); + + // Add a new Policy + QuotaRLBucket authIds = new QuotaRLBucket(); + authIds.setId("id63"); + authIds.getAuthIds().add(auth.getId()); + + Policy policy = new Policy(); + policy.setId("id64"); + policy.getApiIds().add(api.getId()); + policy.getAuthIds().add(authIds); + dataManager.addPolicy(policy); + + dataManager.removeAuth(auth.getId()); + + // Now, get the Policy and check that it's OK + Policy policy2 = dataManager.getPolicyById(policy.getId()); + assertEquals("Policy has no Auth id", 0, policy2.getAuthIds().get(0).getAuthIds().size()); + + // cleanup + dataManager.removeApi(api.getId()); + } + + @Test + public void testGetMatchingPolicies() { + + // Add a new API + Api api = new Api(); + api.setApiDetail(new ApiDetail()); + api.setId("id31"); + dataManager.addApi(api); + + // Add a new API + Api api2 = new Api(); + api2.setApiDetail(new ApiDetail()); + api2.setId("id32"); + dataManager.addApi(api2); + + // Add a new API + Api api3 = new Api(); + api3.setApiDetail(new ApiDetail()); + api3.setId("id33"); + dataManager.addApi(api3); + + // Add a new API + Api api4 = new Api(); + api4.setApiDetail(new ApiDetail()); + api4.setId("id34"); + dataManager.addApi(api4); + + // Add a new Auth + Auth auth = new Auth(); + auth.setId("id31"); + AuthDetail detail = new AuthDetail(); + detail.setStatus(StatusType.ACTIVE); + auth.setAuthDetail(detail); + auth.getAuthDetail().setType(NBAuthType.AUTHKEY); + auth.getAuthDetail().setAuthKeyValue("authKey31"); + dataManager.addAuth(auth); + + // Add a new Auth + Auth auth2 = new Auth(); + auth2.setId("id32"); + AuthDetail detail2 = new AuthDetail(); + detail2.setStatus(StatusType.ACTIVE); + auth2.setAuthDetail(detail2); + auth2.getAuthDetail().setType(NBAuthType.AUTHKEY); + auth2.getAuthDetail().setAuthKeyValue("authKey32"); + dataManager.addAuth(auth2); + + // Add a new Auth + Auth auth3 = new Auth(); + auth3.setId("id33"); + AuthDetail detail3 = new AuthDetail(); + detail3.setStatus(StatusType.ACTIVE); + auth3.setAuthDetail(detail3); + auth3.getAuthDetail().setType(NBAuthType.AUTHKEY); + auth3.getAuthDetail().setAuthKeyValue("authKey33"); + dataManager.addAuth(auth3); + + // Add a new Auth + Auth auth4 = new Auth(); + auth4.setId("id34"); + AuthDetail detail4 = new AuthDetail(); + detail4.setStatus(StatusType.ACTIVE); + auth4.setAuthDetail(detail4); + auth4.getAuthDetail().setType(NBAuthType.BASIC); + auth4.getAuthDetail().setUsername("user1"); + auth4.getAuthDetail().setPassword(new byte[]{'p', 'a', 's', 's', '1'}); + dataManager.addAuth(auth4); + + // Add a new Policy: Associated to API id1 and Auth id1 + Policy policy = new Policy(); + policy.setId("id31"); + policy.getApiIds().add(api.getId()); + + // Create Bucket authIds of auth ids + QuotaRLBucket authIds = new QuotaRLBucket(); + authIds.setId("bucketId"); + authIds.getAuthIds().add(auth.getId()); + // Add bucket authIds to policy + policy.getAuthIds().add(authIds); + + dataManager.addPolicy(policy); + + // Add a new Policy: Associated to API id2, API id3 and Auth id2, id4 + Policy policy2 = new Policy(); + policy2.setId("id32"); + policy2.getApiIds().add(api2.getId()); + policy2.getApiIds().add(api3.getId()); + + // Create Bucket authIds2 of auth ids + QuotaRLBucket authIds2 = new QuotaRLBucket(); + authIds.setId("bucketId2"); + authIds2.getAuthIds().add(auth2.getId()); + authIds2.getAuthIds().add(auth4.getId()); + // Add bucket authIds2 to the policy + policy2.getAuthIds().add(authIds2); + + dataManager.addPolicy(policy2); + + + // Add a new Policy: Associatd to API id4 and no Auth + Policy policy3 = new Policy(); + policy3.setId("id33"); + policy3.getApiIds().add(api4.getId()); + dataManager.addPolicy(policy3); + + + // Add a new Policy: Associatd to no API and Auth id3 + Policy policy4 = new Policy(); + policy4.setId("id34"); + + // Create Bucket authIds4 of auth ids + QuotaRLBucket authIds4 = new QuotaRLBucket(); + authIds.setId("bucketId4"); + authIds4.getAuthIds().add(auth3.getId()); + // Add bucket authIds4 to the policy + policy4.getAuthIds().add(authIds4); + + dataManager.addPolicy(policy4); + + + // Add a new Policy: Associatd to API id3 and no Auth + Policy policy5 = new Policy(); + policy5.setId("id35"); + policy5.getApiIds().add(api3.getId()); + dataManager.addPolicy(policy5); + + + // Add a new Policy: Associatd to API id3 and Auth id3 + Policy policy6 = new Policy(); + policy6.setId("id36"); + policy6.getApiIds().add(api3.getId()); + + // Create Bucket authIds6 of auth ids + QuotaRLBucket authIds6 = new QuotaRLBucket(); + authIds.setId("bucketId6"); + authIds6.getAuthIds().add(auth3.getId()); + // Add bucket authIds6 to the policy + policy6.getAuthIds().add(authIds6); + + dataManager.addPolicy(policy6); + + + // Add a new Policy: Associatd to no API and Auth id2 + Policy policy7 = new Policy(); + policy7.setId("id37"); + + // Create Bucket authIds7 of authId2 + QuotaRLBucket authIds7 = new QuotaRLBucket(); + authIds.setId("bucketId7"); + authIds7.getAuthIds().add(auth2.getId()); + // Add bucket authIds7 to the policy + policy7.getAuthIds().add(authIds7); + + dataManager.addPolicy(policy7); + + // Fetch updated values from cache + api = dataManager.getApiById(api.getId()); + api2 = dataManager.getApiById(api2.getId()); + api3 = dataManager.getApiById(api3.getId()); + api4 = dataManager.getApiById(api4.getId()); + auth = dataManager.getAuthById(auth.getId()); + auth2 = dataManager.getAuthById(auth2.getId()); + auth3 = dataManager.getAuthById(auth3.getId()); + auth4 = dataManager.getAuthById(auth4.getId()); + + List list1 = dataManager.getMatchingPolicies(api, auth); + assertEquals("List1 has correct size", 1, list1.size()); + assertEquals("Matching policy is correct", policy.getId(), list1.get(0).getPolicy().getId()); + + List list2 = dataManager.getMatchingPolicies(api2, auth2); + assertEquals("List2 has correct size", 2, list2.size()); + assertEquals("Matching policy is correct", policy2.getId(), list2.get(0).getPolicy().getId()); + assertEquals("Matching policy is correct", policy7.getId(), list2.get(1).getPolicy().getId()); + + List list3 = dataManager.getMatchingPolicies(api3, null); + assertEquals("List3 has correct size", 1, list3.size()); + assertEquals("Matching policy is correct", policy5.getId(), list3.get(0).getPolicy().getId()); + + List list4 = dataManager.getMatchingPolicies(null, auth3); + assertEquals("List4 has correct size", 1, list4.size()); + assertEquals("Matching policy is correct", policy4.getId(), list4.get(0).getPolicy().getId()); + + List list5 = dataManager.getMatchingPolicies(api4, auth3); + assertEquals("List5 has correct size", 1, list5.size()); + assertEquals("Matching policy is correct", policy4.getId(), list5.get(0).getPolicy().getId()); + + List list6 = dataManager.getMatchingPolicies(api4, auth4); + assertNull("List6 has correct size", list6); + + List list7 = dataManager.getMatchingPolicies(null, null); + assertNull("List7 has correct size", list7); + + // cleanup + dataManager.removePolicy(policy.getId()); + dataManager.removePolicy(policy2.getId()); + dataManager.removePolicy(policy3.getId()); + dataManager.removePolicy(policy4.getId()); + dataManager.removePolicy(policy5.getId()); + dataManager.removePolicy(policy6.getId()); + dataManager.removePolicy(policy7.getId()); + dataManager.removeApi(api.getId()); + dataManager.removeApi(api2.getId()); + dataManager.removeApi(api3.getId()); + dataManager.removeApi(api4.getId()); + dataManager.removeAuth(auth.getId()); + dataManager.removeAuth(auth2.getId()); + dataManager.removeAuth(auth3.getId()); + dataManager.removeAuth(auth4.getId()); + } + + @Test + public void testAddPolicyAndUpdateApiAuthWithCreateBucketThenRemovePolicy() { + + // Add a new API + Api api = new Api(); + api.setApiDetail(new ApiDetail()); + api.setId("apiId1"); + dataManager.addApi(api); + + // Add a new Auth + Auth auth = new Auth(); + auth.setId("authId1"); + auth.setAuthDetail(new AuthDetail()); + auth.getAuthDetail().setType(NBAuthType.AUTHKEY); + auth.getAuthDetail().setAuthKeyValue("authKey"); + dataManager.addAuth(auth); + + // Add a new Policy + Policy policy = new Policy(); + policy.setId("policyId1"); + policy.getApiIds().add(api.getId()); + dataManager.addPolicy(policy); + + // Create bucket to add new Auth + QuotaRLBucket authIds = new QuotaRLBucket(); + authIds.setId("bucketId1"); + authIds.getAuthIds().add(auth.getId()); + dataManager.createBucket(policy.getId(), authIds); + // fetch updated policy from the cache + policy = dataManager.getPolicyById(policy.getId()); + + // Now, get the API and check that it's OK + Api api2 = dataManager.getApiById(api.getId()); + assertEquals("API has new policy", policy.getId(), api2.getPolicyIds().get(0)); + + // Now, get the Auth and check that it's OK + Auth auth2 = dataManager.getAuthById(auth.getId()); + assertEquals("Auth has new policy", policy.getId(), auth2.getPolicyContexts().get(0).getPolicyId()); + + // Check that bucket is added correctly to policy + assertEquals("Correct number of buckets for policy", 1, policy.getAuthIds().size()); + assertEquals("Policy has new bucket", authIds.getId(), policy.getAuthIds().get(0).getId()); + + dataManager.removePolicy(policy.getId()); + + // Now, get the API and check that it's OK + Api api3 = dataManager.getApiById(api.getId()); + assertEquals("API has no policy", 0, api3.getPolicyIds().size()); + + // Now, get the API and check that it's OK + Auth auth4 = dataManager.getAuthById(auth.getId()); + assertEquals("Auth has no policy", 0, auth4.getPolicyContexts().size()); + + // cleanup + dataManager.removeApi(api.getId()); + dataManager.removeAuth(auth.getId()); + } + + @Test + public void testAddPolicyWithBucketAndAppendAuthsThenRemovePolicy() { + + // Add a new API + Api api = new Api(); + api.setApiDetail(new ApiDetail()); + api.setId("apiId1"); + dataManager.addApi(api); + + // Prepare Auths + Auth auth = new Auth(); + auth.setId("authId1"); + auth.setAuthDetail(new AuthDetail()); + auth.getAuthDetail().setType(NBAuthType.AUTHKEY); + auth.getAuthDetail().setAuthKeyValue("authKey1"); + dataManager.addAuth(auth); + + Auth auth2 = new Auth(); + auth2.setId("authId2"); + auth2.setAuthDetail(new AuthDetail()); + auth2.getAuthDetail().setType(NBAuthType.AUTHKEY); + auth2.getAuthDetail().setAuthKeyValue("authKey2"); + dataManager.addAuth(auth2); + + // Add a new Policy + Policy policy = new Policy(); + policy.setId("policyId1"); + policy.getApiIds().add(api.getId()); + dataManager.addPolicy(policy); + + // Create bucket to add new Auth + QuotaRLBucket authIds = new QuotaRLBucket(); + authIds.setId("bucketId1"); + authIds.getAuthIds().add(auth.getId()); + dataManager.createBucket(policy.getId(), authIds); + // fetch updated policy from the cache + policy = dataManager.getPolicyById(policy.getId()); + + // Now, get the API and check that it's OK + Api gApi1 = dataManager.getApiById(api.getId()); + assertEquals("API has new policy", policy.getId(), gApi1.getPolicyIds().get(0)); + + // Now, get the Auth and check that it's OK + Auth gAuth1 = dataManager.getAuthById(auth.getId()); + assertEquals("Auth has new policy", policy.getId(), gAuth1.getPolicyContexts().get(0).getPolicyId()); + + // Check that bucket is added correctly to policy + assertEquals("Correct number of buckets for policy", 1, policy.getAuthIds().size()); + assertEquals("Policy has new bucket", authIds.getId(), policy.getAuthIds().get(0).getId()); + + // Append a new Auth to the bucket + QuotaRLBucket authIdsToAppend = new QuotaRLBucket(); + authIdsToAppend.getAuthIds().add(auth2.getId()); + dataManager.addAuthsToBucket(policy.getId(), authIds.getId(), authIdsToAppend); + // fetch updated policy from the cache + policy = dataManager.getPolicyById(policy.getId()); + + // Check that auth2 has been appended to original bucket + Auth gAuth2 = dataManager.getAuthById(auth2.getId()); + assertEquals("Auth has new policy", policy.getId(), gAuth2.getPolicyContexts().get(0).getPolicyId()); + assertEquals("Correct number of buckets for policy", 1, policy.getAuthIds().size()); + assertEquals("Correct number of auths in the bucket", 2, policy.getAuthIds().get(0).getAuthIds().size()); + + // Retry appending the same auth to the same bucket + dataManager.addAuthsToBucket(policy.getId(), authIds.getId(), authIdsToAppend); + + // fetch updated policy from the cache + policy = dataManager.getPolicyById(policy.getId()); + + // Check that auth hasn't been added twice + assertEquals("Correct number of auths in the bucket", 2, policy.getAuthIds().get(0).getAuthIds().size()); + + dataManager.removePolicy(policy.getId()); + + // Now, get the API and check that it's OK + Api gApi1_2 = dataManager.getApiById(api.getId()); + assertEquals("API has no policy", 0, gApi1_2.getPolicyIds().size()); + + // Now, get the Auth and check that it's OK + Auth gAuth1_2 = dataManager.getAuthById(auth.getId()); + assertEquals("Auth has no policy", 0, gAuth1_2.getPolicyContexts().size()); + + // Now, get the Auth and check that it's OK + Auth gAuth2_2 = dataManager.getAuthById(auth2.getId()); + assertEquals("Auth has no policy", 0, gAuth2_2.getPolicyContexts().size()); + + // cleanup + dataManager.removeApi(api.getId()); + dataManager.removeAuth(auth.getId()); + dataManager.removeAuth(auth2.getId()); + + } + + @Test + public void testAddPolicyAppendAuthsBucketsRemoveBucketsRemovePolicy() { + + // Add a new API + Api api = new Api(); + api.setId("apiId1"); + api.setApiDetail(new ApiDetail()); + dataManager.addApi(api); + + // Prepare Auths + Auth auth = new Auth(); + auth.setId("authId1"); + auth.setAuthDetail(new AuthDetail()); + auth.getAuthDetail().setType(NBAuthType.AUTHKEY); + auth.getAuthDetail().setAuthKeyValue("authKey1"); + dataManager.addAuth(auth); + + Auth auth2 = new Auth(); + auth2.setId("authId2"); + auth2.setAuthDetail(new AuthDetail()); + auth2.getAuthDetail().setType(NBAuthType.AUTHKEY); + auth2.getAuthDetail().setAuthKeyValue("authKey2"); + dataManager.addAuth(auth2); + + Auth auth3 = new Auth(); + auth3.setId("authId3"); + auth3.setAuthDetail(new AuthDetail()); + auth3.getAuthDetail().setType(NBAuthType.AUTHKEY); + auth3.getAuthDetail().setAuthKeyValue("authKey3"); + dataManager.addAuth(auth3); + + // Add a new Policy + Policy policy = new Policy(); + policy.setId("policyId1"); + policy.getApiIds().add(api.getId()); + dataManager.addPolicy(policy); + + // Create bucket to add new Auth + QuotaRLBucket authIds = new QuotaRLBucket(); + authIds.setId("bucketId1"); + authIds.getAuthIds().add(auth.getId()); + dataManager.createBucket(policy.getId(), authIds); + + // fetch policy from the cache + policy = dataManager.getPolicyById(policy.getId()); + + // Now, get the API and check that it's OK + Api gApi1 = dataManager.getApiById(api.getId()); + assertEquals("API has new policy", policy.getId(), gApi1.getPolicyIds().get(0)); + + // Now, get the Auth and check that it's OK + Auth gAuth1 = dataManager.getAuthById(auth.getId()); + assertEquals("Auth has new policy", policy.getId(), gAuth1.getPolicyContexts().get(0).getPolicyId()); + + // Check that bucket is added correctly to policy + assertEquals("Correct number of buckets for policy", 1, policy.getAuthIds().size()); + assertEquals("Policy has new bucket", authIds.getId(), policy.getAuthIds().get(0).getId()); + + // Append a new Auth to the bucket + QuotaRLBucket authIdsToAppend = new QuotaRLBucket(); + authIdsToAppend.getAuthIds().add(auth2.getId()); + dataManager.addAuthsToBucket(policy.getId(), authIds.getId(), authIdsToAppend); + + // fetch policy from the cache + policy = dataManager.getPolicyById(policy.getId()); + + // Check that auth2 has been appended to original bucket + Auth gAuth2 = dataManager.getAuthById(auth2.getId()); + assertEquals("Auth has new policy", policy.getId(), gAuth2.getPolicyContexts().get(0).getPolicyId()); + assertEquals("Correct number of buckets for policy", 1, policy.getAuthIds().size()); + assertEquals("Correct number of auths in the bucket", 2, policy.getAuthIds().get(0).getAuthIds().size()); + + // Retry appending the same auth to the same bucket + dataManager.addAuthsToBucket(policy.getId(), authIds.getId(), authIdsToAppend); + + // fetch policy from the cache + policy = dataManager.getPolicyById(policy.getId()); + + // Check that auth hasn't been added twice + assertEquals("Correct number of auths in the bucket", 2, policy.getAuthIds().get(0).getAuthIds().size()); + + // Create a new bucket containing a third auth + QuotaRLBucket authIds2 = new QuotaRLBucket(); + authIds2.setId("bucketId2"); + authIds2.getAuthIds().add(auth3.getId()); + dataManager.createBucket(policy.getId(), authIds2); + + // fetch policy from the cache + policy = dataManager.getPolicyById(policy.getId()); + + // Check that bucket has been added correctly + assertEquals("Correct number of buckets for policy", 2, policy.getAuthIds().size()); + + // Just to be sure that order is maintained + QuotaRLBucket bucket1, bucket2; + if(policy.getAuthIds().get(0).getId().equals(authIds.getId())) { + bucket1 = policy.getAuthIds().get(0); + bucket2 = policy.getAuthIds().get(1); + } else { + bucket1 = policy.getAuthIds().get(1); + bucket2 = policy.getAuthIds().get(0); + } + + assertEquals("Correct number of auths in the bucket 1", 2, bucket1.getAuthIds().size()); + assertEquals("Correct number of auths in the bucket 2", 1, bucket2.getAuthIds().size()); + + // removing auth3 from bucket2 + dataManager.removeAuthFromBucket(policy.getId(), bucket2.getId(), auth3.getId()); + + // fetch policy from the cache + policy = dataManager.getPolicyById(policy.getId()); + + assertEquals("Correct number of buckets for policy", 2, policy.getAuthIds().size()); + assertEquals("Correct number of auths in the bucket 1", 2, bucket1.getAuthIds().size()); + assertEquals("Correct number of auths in the bucket 2", 0, bucket2.getAuthIds().size()); + + // Now, get auth3 and check that it's no more associated with the policy + Auth gAuth3_2 = dataManager.getAuthById(auth3.getId()); + assertEquals("Auth has no policy", 0, gAuth3_2.getPolicyContexts().size()); + + // Removing bucket2 + dataManager.removeBucket(policy.getId(), authIds2.getId()); + assertEquals("Correct number of buckets for policy", 1, policy.getAuthIds().size()); + assertEquals("Correct number of auths in the bucket 1", 2, policy.getAuthIds().get(0).getAuthIds().size()); + + // fetch policy from the cache + policy = dataManager.getPolicyById(policy.getId()); + + // Removing bucket1 + dataManager.removeBucket(policy.getId(), authIds.getId()); + assertEquals("Correct number of buckets for policy", 0, policy.getAuthIds().size()); + + dataManager.removePolicy(policy.getId()); + + // Now, get the API and check that it's OK + Api gApi1_2 = dataManager.getApiById(api.getId()); + assertEquals("API has no policy", 0, gApi1_2.getPolicyIds().size()); + + // Now, get the Auth and check that it's OK + Auth gAuth1_2 = dataManager.getAuthById(auth.getId()); + assertEquals("Auth has no policy", 0, gAuth1_2.getPolicyContexts().size()); + + // Now, get the Auth and check that it's OK + Auth gAuth2_2 = dataManager.getAuthById(auth2.getId()); + assertEquals("Auth has no policy", 0, gAuth2_2.getPolicyContexts().size()); + + // cleanup + dataManager.removeApi(api.getId()); + dataManager.removeAuth(auth.getId()); + dataManager.removeAuth(auth2.getId()); + dataManager.removeAuth(auth3.getId()); + } + + + + + + + @Test + public void testGetMatchingPoliciesWithSeveralAuth() { + + // Add a new API + Api api = new Api(); + api.setApiDetail(new ApiDetail()); + api.setId("id31"); + dataManager.addApi(api); + + // Add a new Auth + Auth auth = new Auth(); + auth.setId("id31"); + AuthDetail detail = new AuthDetail(); + detail.setStatus(StatusType.ACTIVE); + auth.setAuthDetail(detail); + auth.getAuthDetail().setType(NBAuthType.AUTHKEY); + auth.getAuthDetail().setAuthKeyValue("authKey31"); + dataManager.addAuth(auth); + + // Add a new Auth + Auth auth2 = new Auth(); + auth2.setId("id32"); + auth2.setAuthDetail(new AuthDetail()); + auth2.getAuthDetail().setType(NBAuthType.BASIC); + auth2.getAuthDetail().setUsername("username"); + auth2.getAuthDetail().setPassword("password".getBytes()); + dataManager.addAuth(auth2); + + // Add a new Auth + Auth auth3 = new Auth(); + auth3.setId("id33"); + auth3.setAuthDetail(new AuthDetail()); + auth3.getAuthDetail().setType(NBAuthType.IP_WHITE_LIST); + auth3.getAuthDetail().getWhiteListedIps().add("12.23.45.56"); + auth3.getAuthDetail().getWhiteListedIps().add("45.45.89.65"); + dataManager.addAuth(auth3); + + // Add a new Policy: Associated to API id1 and Auth id1 + Policy policy = new Policy(); + policy.setId("id31"); + policy.getApiIds().add(api.getId()); + + // Create Bucket authIds of auth ids + QuotaRLBucket authIds = new QuotaRLBucket(); + authIds.setId("bucketId"); + authIds.getAuthIds().add(auth.getId()); + authIds.getAuthIds().add(auth2.getId()); + authIds.getAuthIds().add(auth3.getId()); + + // Add bucket authIds to policy + policy.getAuthIds().add(authIds); + + dataManager.addPolicy(policy); + + Api api_ = dataManager.getApiById(api.getId()); + Auth auth_ = dataManager.getAuthById(auth.getId()); + + List list1 = dataManager.getMatchingPolicies(api_, auth_); + assertEquals("List1 has correct size", 1, list1.size()); + assertEquals("Matching policy is correct", policy.getId(), list1.get(0).getPolicy().getId()); + + // cleanup + dataManager.removePolicy(policy.getId()); + dataManager.removeApi(api.getId()); + dataManager.removeAuth(auth.getId()); + dataManager.removeAuth(auth2.getId()); + dataManager.removeAuth(auth3.getId()); + } + + @Test + public void testSettings() { + + dataManager.putSettingString("testValue", "str"); + assertEquals("Setting has correctly been put/get", "str", dataManager.getSettingString("testValue")); + dataManager.clearSettingString("testValue"); + assertEquals("Setting has correctly been removed", null, dataManager.getSettingString("testValue")); + + } + +} diff --git a/exposure-engine/common/src/test/resources/common.spring-test.xml b/exposure-engine/common/src/test/resources/common.spring-test.xml new file mode 100644 index 0000000..110a460 --- /dev/null +++ b/exposure-engine/common/src/test/resources/common.spring-test.xml @@ -0,0 +1,40 @@ + + + + + + false + false + false + false + false + + + + + + + + + + + + + + + + + + + + + + + + + \ No newline at end of file diff --git a/exposure-engine/common/src/test/resources/test.jar b/exposure-engine/common/src/test/resources/test.jar new file mode 100644 index 0000000..1f890b0 Binary files /dev/null and b/exposure-engine/common/src/test/resources/test.jar differ diff --git a/exposure-engine/gateway-common/pom.xml b/exposure-engine/gateway-common/pom.xml new file mode 100644 index 0000000..7799a63 --- /dev/null +++ b/exposure-engine/gateway-common/pom.xml @@ -0,0 +1,102 @@ + + + 4.0.0 + + + exposure-engine + com.alu.e3 + 1.0.1 + .. + + + gateway-common + E3 Gateway Common + http://www.alcatel-lucent.com + + + jar + + + 4.3.1-fuse-01-09 + 2.6.0-fuse-01-09 + 2.2 + 1.7.0 + 3.1_5 + 2.3.3 + 3.0.5.RELEASE + 1.2.0 + + + + + org.bouncycastle + bcprov-jdk16 + 1.46 + compile + + + com.alu.e3 + common + ${project.version} + jar + provided + + + org.apache.felix + org.apache.felix.framework + 3.0.9-fuse-03-11 + provided + + + org.apache.camel + camel-jetty + ${camel.version} + provided + + + tools + com.sun + + + + + org.apache.camel + camel-http4 + ${camel.version} + provided + + + tools + com.sun + + + + + + org.springframework.osgi + spring-osgi-extender + 1.2.0 + provided + + + org.springframework.aop + org.springframework + + + org.springframework.beans + org.springframework + + + org.springframework.context + org.springframework + + + org.springframework.core + org.springframework + + + + + + diff --git a/exposure-engine/gateway-common/src/main/java/com/alu/e3/data/topology/TDRCollectorInstanceWatcher.java b/exposure-engine/gateway-common/src/main/java/com/alu/e3/data/topology/TDRCollectorInstanceWatcher.java new file mode 100644 index 0000000..63c0b5b --- /dev/null +++ b/exposure-engine/gateway-common/src/main/java/com/alu/e3/data/topology/TDRCollectorInstanceWatcher.java @@ -0,0 +1,352 @@ +/** + * Copyright © 2012 Alcatel-Lucent. + * + * See the NOTICE file distributed with this work for additional + * information regarding copyright ownership. + * Licensed to you 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 com.alu.e3.data.topology; + +import java.io.BufferedOutputStream; +import java.io.BufferedWriter; +import java.io.File; +import java.io.FileOutputStream; +import java.io.FileWriter; +import java.io.IOException; +import java.io.OutputStream; +import java.io.Writer; +import java.util.ArrayList; +import java.util.LinkedList; +import java.util.List; + +import org.slf4j.Logger; +import org.slf4j.LoggerFactory; + +import com.alu.e3.common.E3Constant; +import com.alu.e3.common.caching.IEntryListener; +import com.alu.e3.common.osgi.api.ITopologyClient; +import com.alu.e3.data.DataEntryEvent; +import com.alu.e3.data.model.Instance; +import com.alu.e3.data.model.SSHKey; + +public class TDRCollectorInstanceWatcher implements IEntryListener> { + public static final String HOST_CFG = "ra_server"; + public static final String KEY_CFG = "ssh_key"; + public static final String USER_CFG = "ssh_key_user"; + public static final String ID_CFG = "e3_id"; + public static final String CONFIG_KEYVAL_CHAR = ":"; + + private static final Logger logger = + LoggerFactory.getLogger(TDRCollectorInstanceWatcher.class); + + private ITopologyClient topologyClient; + private List TDRCollectors = new LinkedList(); + + private SSHKey key; + private String user; + private String myName = null; + + protected String writeLocation = E3Constant.TDR_TRANSFER_CONFIG_PATH; + protected String configName = E3Constant.TDR_TRANSFER_CONFIG_FILE; + protected String keyName = E3Constant.TDR_TRANSFER_CONFIG_KEY; + +// @Override +// public void instanceAdded(InstanceEvent event) { +// Instance instance = event.getInstance(); +// onInstanceAdded(instance); +// } + + private void onInstanceAdded(Instance instance) { + if (myName == null && E3Constant.E3GATEWAY.equals(instance.getType())) { + getMyName(); + if (myName != null) { + writeConfigFile(); + } + } else if (E3Constant.E3MANAGER.equals(instance.getType())) { + verifyCredentials(instance); + } else if (E3Constant.TDR_COLLECTOR.equals(instance.getType())) { + logger.debug("Adding instance " + instance.getName() + " (" + instance.getInternalIP() + ")"); + TDRCollectors.add(instance); + writeConfigFile(); + } + } + + //if more instances are registered with the same InternalIP, only the first is removed +// @Override +// public void instanceRemoved(InstanceEvent event) { +// Instance removedInstance = event.getInstance(); +// onInstanceRemoved(removedInstance); +// } + + private void onInstanceRemoved(Instance removedInstance) { + if (!E3Constant.TDR_COLLECTOR.equals(removedInstance.getType())) return; + Instance toRemove = null; + for (Instance currentInstance : TDRCollectors) { + if (currentInstance.getInternalIP().equals(removedInstance.getInternalIP())) { + toRemove = currentInstance; + } + } + if (toRemove != null) { + logger.debug("Removing instance " + removedInstance.getName() + + " (" + removedInstance.getInternalIP() + ")"); + TDRCollectors.remove(toRemove); + writeConfigFile(); + } else { + logger.warn("Tried to remove unknown instance " + removedInstance.getName() + + " (" + removedInstance.getInternalIP() + ")"); + } + } + + protected void getMyName() { + Instance inst = topologyClient.whoAmI(E3Constant.E3GATEWAY); + if (inst != null) { + myName = inst.getName(); + logger.debug("I found my name: " + myName); + } + } + + //records: where the key is, what the user is, what the TDRCollectors are, and what the ID is + protected void writeConfigFile() { + logger.debug("Writing new TDR Transfer Config File"); + if (keyName == null || user == null || TDRCollectors.isEmpty()) { + logger.debug("Missing required data for writing TDR Transfer Config File"); + return; + } + if (myName == null) getMyName(); + Writer writer = null; + try { + writer = new BufferedWriter(new FileWriter( + new File(new File(writeLocation), configName))); + if (myName != null) writer.write(ID_CFG + CONFIG_KEYVAL_CHAR + myName + "\n"); + writer.write(KEY_CFG + CONFIG_KEYVAL_CHAR + writeLocation + "/" + keyName + "\n"); + writer.write(USER_CFG + CONFIG_KEYVAL_CHAR + user + "\n"); + for (Instance instance : TDRCollectors) { + writer.write(HOST_CFG + CONFIG_KEYVAL_CHAR + instance.getInternalIP() + "\n"); + + } + } catch (IOException e) { + logger.error("Could not write config file for TDR Transfer Script!"); + logger.error(e.getMessage(), e.getStackTrace()); + return; + } finally { + if (writer != null) { + try { + writer.close(); + } catch (IOException e) { + logger.error("Could not close TDR Transfer Key writer."); + e.printStackTrace(); + return; + } + } + } + + logger.debug("TDR Transfer Config File written."); + } + + protected boolean writeKeyFile() { + logger.debug("Writing new TDR Transfer Key File."); + File keyfile = new File(new File(writeLocation), keyName); + OutputStream out = null; + try { + out = new BufferedOutputStream(new FileOutputStream( + keyfile)); + out.write(this.key.getPrivateKey()); + } catch (IOException e) { + logger.error("Could not write config file for TDR Transfer Script!"); + logger.error(e.getMessage(), e.getStackTrace()); + return false; + } finally { + if (out != null) { + try { + out.close(); + } catch (IOException e) { + logger.error("Could not close TDR Transfer Key writer."); + e.printStackTrace(); + } + } + keyfile.setWritable(false, false); + keyfile.setReadable(false, false); + keyfile.setExecutable(false, false); + keyfile.setWritable(true, true); + keyfile.setReadable(true, true); + } + return true; + } + + public void init() { + logger.debug("Starting TDRCollectorInstanceWatcher ..."); + logger.debug("Getting TDRCollectorInstance list ..."); + List nodeList; + + nodeList = topologyClient.getAllInstancesOfType(E3Constant.E3MANAGER); + if (nodeList != null && nodeList.size() != 0) { + for (Instance instance : nodeList) { + verifyCredentials(instance); + } + if (this.key == null || this.user == null) { + logger.warn("No credentials were set for instances of type " + E3Constant.TDR_COLLECTOR + + ". There will likely be problems with downstream TDR collection. "); + } + } + + nodeList = topologyClient.getAllInstancesOfType(E3Constant.TDR_COLLECTOR); + if (nodeList != null && nodeList.size() != 0) { + TDRCollectors.addAll(nodeList); + logger.debug("Writing TDR Transfer Script configuration file."); + writeConfigFile(); + } else { + logger.debug("No instances of type " + E3Constant.TDR_COLLECTOR + " were found."); + } + listenInstanceTypeListener(); + getMyName(); + logger.debug("TDRCollectorInstanceWatcher init'd."); + } + + public void destroy() { + logger.debug("Stopping TDRCollectorInstanceWatcher ..."); + logger.debug("Clearing TDRCollectorInstance list ..."); + TDRCollectors.clear(); + logger.debug("Clearing TDRCollectorInstanceWatcher listeners ..."); +// topologyClient.removeInstanceListener(this); + topologyClient.removeInstanceTypeListener(this); + logger.debug("TDRCollectorInstanceWatcher destroyed."); + } + + // This function creates the key file if one doesn't exist, and monitors + // whether multiple keys are registered. + // TDR Transfer Script only supports one key for all destinations instances, so + // only the first key registered is ever used. If there are no credentials + // or different credentials, an error is logged. + protected boolean verifyCredentials(Instance instance) { + boolean hasConsistentCredentials = true; + + SSHKey instKey = instance.getSSHKey(); + if (instKey != null) { + if (this.key == null) { + this.key = instKey; + this.user = instance.getUser(); + if (!writeKeyFile()) { + this.key = null; + this.user = null; + return false; + } + return true; + } + if (!instKey.isSameKey(this.key)) { + hasConsistentCredentials = false; + logger.error("Instance " + instance.getName() + " (" + instance.getInternalIP() + + ") uses a different key than another " + E3Constant.TDR_COLLECTOR + " instance!"); + } + if (instance.getUser() != this.user) { + hasConsistentCredentials = false; + logger.error("Instance " + instance.getName() + " (" + instance.getInternalIP() + + ") has a different user than another " + E3Constant.TDR_COLLECTOR + " instance!"); + } + } else { + logger.warn("Instance " + instance.getName() + " (" + instance.getInternalIP() + + ") has no key specified!"); + } + + return hasConsistentCredentials; + } + + + public void setWriteLocation(String value) { + writeLocation = value; + } + public String getWriteLocation() { + return writeLocation; + } + + public void setConfigName(String value) { + configName = value; + } + public String getConfigName() { + return configName; + } + + public void setKeyName(String value) { + keyName = value; + } + public String getKeyName() { + return keyName; + } + + public void setTopologyClient(ITopologyClient topologyClient) { + this.topologyClient = topologyClient; + } + +// public void listenInstanceListener() { +// topologyClient.addInstanceListener(this); +// } + + public void listenInstanceTypeListener() { + topologyClient.addInstanceTypeListener(this); + } + + public ITopologyClient getTopologyClient() { + return topologyClient; + } + + /// + + @Override + public void entryAdded(DataEntryEvent> event) { + if (event == null) { + logger.warn("Event received by the listener cannot be null"); + return; + } + if (event.getValue() == null) { + logger.warn("List of added instances cannot be null"); + return; + } + + for (Instance instance: event.getValue()) { + onInstanceAdded(instance); + } + } + + @Override + public void entryUpdated(DataEntryEvent> event) { + if (event == null) { + logger.warn("Event received by the listener cannot be null"); + return; + } + if (event.getValue() == null) { + logger.warn("List of updated instances cannot be null"); + return; + } + + for (Instance instance: event.getValue()) { + onInstanceAdded(instance); + } + } + + @Override + public void entryRemoved(DataEntryEvent> event) { + if (event == null) { + logger.warn("Event received by the listener cannot be null"); + return; + } + if (event.getValue() == null) { + logger.warn("List of removed instances cannot be null"); + return; + } + + for (Instance instance: event.getValue()) { + onInstanceRemoved(instance); + } + } + +} diff --git a/exposure-engine/gateway-common/src/main/java/com/alu/e3/gateway/ApiDeploymentManager.java b/exposure-engine/gateway-common/src/main/java/com/alu/e3/gateway/ApiDeploymentManager.java new file mode 100644 index 0000000..3063e4e --- /dev/null +++ b/exposure-engine/gateway-common/src/main/java/com/alu/e3/gateway/ApiDeploymentManager.java @@ -0,0 +1,428 @@ +/** + * Copyright © 2012 Alcatel-Lucent. + * + * See the NOTICE file distributed with this work for additional + * information regarding copyright ownership. + * Licensed to you 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 com.alu.e3.gateway; + +import java.io.ByteArrayInputStream; +import java.util.Collections; +import java.util.HashMap; +import java.util.Map; +import java.util.concurrent.Semaphore; +import java.util.concurrent.TimeUnit; + +import org.osgi.framework.Bundle; +import org.osgi.framework.BundleContext; +import org.osgi.framework.BundleEvent; +import org.osgi.framework.BundleException; +import org.osgi.framework.BundleListener; +import org.osgi.framework.ServiceReference; + +import org.springframework.beans.factory.annotation.Autowired; + +import com.alu.e3.common.caching.IEntryListener; +import com.alu.e3.common.logging.Category; +import com.alu.e3.common.logging.CategoryLogger; +import com.alu.e3.common.logging.CategoryLoggerFactory; +import com.alu.e3.common.osgi.api.IDataManager; +import com.alu.e3.data.CacheAck; +import com.alu.e3.data.DataEntryEvent; +import com.alu.e3.data.IDataManagerListener; +import com.alu.e3.data.model.ApiJar; + +public class ApiDeploymentManager implements IDataManagerListener, IEntryListener, BundleListener { + + private static final CategoryLogger logger = CategoryLoggerFactory.getLogger(ApiDeploymentManager.class, Category.PROV); + + protected static int SERVICES_LOOP_ATTEMPTS = 20; + protected static int SERVICES_LOOP_DURATION = 500; // in milliseconds + + // Prefix for bundle's location + protected static String BUNDLE_LOCATION_URI_PREFIX = "api://"; + public static String getBundleLocationURIPrefix() { + return BUNDLE_LOCATION_URI_PREFIX; + } + + protected IDataManager dataManager; + + @Autowired + protected BundleContext bundleContext; + + // Used to associate a BundleEvent with an ack queue, via Bundle's location + protected Map knownBundles; + protected Map bundleBeeingUpdated; + protected Map waitingActions; + + public ApiDeploymentManager() {} + + public void setDataManager(IDataManager dataManager) { + logger.debug("Setting DataManager"); + // set dataManager before adding as listener, otherwise, dataManagerReady might fail! + this.dataManager = dataManager; + } + + @Override + /** + * Called by DataManager when its ready (has loaded all it's tables) + */ + public void dataManagerReady() { + logger.debug("DataManager ready, registering as Api Deployment Listener"); + dataManager.addApiDeploymentListener(this); + } + + public void init() { + logger.debug("Initializing ApiDeploymentManager"); + knownBundles = Collections.synchronizedMap(new HashMap()); + bundleBeeingUpdated = Collections.synchronizedMap(new HashMap()); + waitingActions = Collections.synchronizedMap(new HashMap()); + + logger.debug("Setting as listener on BundleContext"); + bundleContext.addBundleListener(this); + + dataManager.addListener(this); + } + + /** + * Called by Spring magic + */ + public void destroy() { + logger.debug("Destroying, removing as listener"); + if(bundleContext != null) { + bundleContext.removeBundleListener(this); + } + if(dataManager != null) { + dataManager.removeListener(this); + dataManager.removeApiDeploymentListener(this); + } + } + + @Override + /** + * A route has been added. Installing the bundle. + */ + public void entryAdded(DataEntryEvent event) { + logger.debug("[EntryAdded] ApiId: " + event.getKey()); + + // A location which will identify the bundle in the bundle context + String location = BUNDLE_LOCATION_URI_PREFIX + event.getKey(); + + // The ApiJar object extracted from the event, containing the queueName to post ACKs and bundle's data + ApiJar jar = event.getValue(); + + // The queueName for ACKs is the ID field of a IAckData (ApiJar is a IAckData) + String queueName = jar.getId(); + + // Associating a location to a queueName + // This is used in bundleChanged method to retreive the queueName in which the ACK must be posted + knownBundles.put(location, queueName); + + // Start bundle installation + handleAddOrUpdateEvent(location, jar, event.getKey()); + + logger.debug("[EntryAdded] Finished handling event for apiId " + event.getKey()); + } + + + @Override + /** + * A route has been updated, uninstalling previous one and installing new one + */ + public void entryUpdated(DataEntryEvent event) { + logger.debug("[EntryUpdated] for apiId: " + event.getKey()); + + // A location which will identify the bundle in the bundle context + String location = BUNDLE_LOCATION_URI_PREFIX + event.getKey(); + + // The ApiJar object extracted from the event, containing the queueName to post ACKs and bundle's data + ApiJar jar = event.getValue(); + + // The queueName for ACKs is the ID field of a IAckData (ApiJar is a IAckData) + String queueName = jar.getId(); + + // Associating a location to a queueName + // This is used in bundleChanged method to retreive the queueName in which the ACK must be posted + knownBundles.put(location, queueName); + + // Start bundle update + handleAddOrUpdateEvent(location, jar, event.getKey()); + + logger.debug("[EntryUpdated] Finished handling event for apiId " + event.getKey()); + } + + + @Override + /** + * A route has been removed + */ + public void entryRemoved(DataEntryEvent event) { + logger.debug("[EntryRemoved] Handling event for apiId: " + event.getKey()); + String apiId = event.getKey(); + + // A location which will identify the bundle in the bundle context + String location = BUNDLE_LOCATION_URI_PREFIX + apiId; + + // The queueName for ACKs is the ID field of a IAckData (ApiJar is a IAckData) + String queueName = event.getValue().getId(); + + // The bundle to remove + Bundle bundle = getBundle(location); + + if(bundle != null) { + try { + Semaphore stopActionSemaphore = new Semaphore(0); + // Associating a location to a queueName + // This is used in bundleChanged method to retreive the queueName in which the ACK must be posted + knownBundles.put(location, queueName); + waitingActions.put(location, stopActionSemaphore); + + // Stopping the bundle + logger.debug("Stopping bundle for apiId " + apiId + ": " + bundle.getSymbolicName()); + bundle.stop(); + stopActionSemaphore.tryAcquire(10L, TimeUnit.SECONDS); + logger.debug("Stop unlocked for apiId " + apiId); + + // Uninstalling the bundle + // The ACK will be post in "bundleChanged" method, when the event "UNINSTALLED" will be fired for this bundle + logger.debug("Uninstalling bundle for apiId " + apiId + ": " + bundle.getSymbolicName()); + bundle.uninstall(); + stopActionSemaphore.tryAcquire(10L, TimeUnit.SECONDS); + logger.debug("Uninstall unlocked for apiId " + apiId); + + postAck(CacheAck.OK, queueName); + } catch (Exception e) { + logger.error("Error stopping/uninstalling bundle " + bundle.getSymbolicName() + " after update ", e); + + // post back the error in the queue + postAck(CacheAck.KO, queueName); + } finally { + // removing the queueName to prevent any later BundleEvent handling + knownBundles.remove(location); + waitingActions.remove(location); + } + } else { + // No bundle found, ignoring the request and sending an OK ack. + logger.warn("Bundle " + location + " not found in current context"); + postAck(CacheAck.OK, queueName); + } + logger.debug("[EntryRemoved] Finished handling event for apiId " + apiId); + } + + /** + * (Re)Installs a bundle + * @param location A string identifying the bundle + * @param jar The ApiJar object containing the bundle to (re)install + */ + private void handleAddOrUpdateEvent(String location, ApiJar jar, String apiId) { + String queueName = jar.getId(); + + Bundle existingBundle = getBundle(location); + try { + if(existingBundle != null) { + Semaphore stopActionSemaphore = new Semaphore(0); + // Associating a location to a queueName + // This is used in bundleChanged method to retreive the queueName in which the ACK must be posted + knownBundles.put(location, queueName); + waitingActions.put(location, stopActionSemaphore); + + // Stopping the bundle + logger.debug("Stopping bundle for apiId " + apiId + ": " + existingBundle.getSymbolicName()); + existingBundle.stop(); + stopActionSemaphore.tryAcquire(10L, TimeUnit.SECONDS); + + // Uninstalling the bundle + // The ACK will be post in "bundleChanged" method, when the event "UNINSTALLED" will be fired for this bundle + logger.debug("Uninstalling bundle for apiId " + apiId + ": " + existingBundle.getSymbolicName()); + existingBundle.uninstall(); + stopActionSemaphore.tryAcquire(10L, TimeUnit.SECONDS); + + waitingActions.remove(location); + } + + // no previous bundle, it's a fresh install so let's do it + installApiJar(location, jar); + + + } catch(Exception e) { + logger.error("An error occured while installing the bundle", e); + postAck(CacheAck.KO, queueName); + } finally { + waitingActions.remove(location); + } + } + + private void installApiJar(String location, ApiJar jar) throws BundleException { + byte[] data = jar.getData(); + ByteArrayInputStream in = new ByteArrayInputStream(data); + + Bundle bundle = bundleContext.installBundle(location, in); + bundle.start(); + } + + /** + * Browse the list of bundles to find the one matching the location parameter. + * Not optimized at all... + * @param location The location to look bundle for. + * @return Matching bundle, or null if no bundle is foudn for this location + */ + private synchronized Bundle getBundle(String location) { + // TODO optimize this + Bundle[] bundles = bundleContext.getBundles(); + Bundle foundBundle = null; + for(Bundle bundle : bundles) { + if(bundle.getLocation().equals(location)) { + foundBundle = bundle; + break; + } + } + + return foundBundle; + } + + + @Override + /** + * BundleListener + */ + public void bundleChanged(BundleEvent event) { + Bundle bundle = event.getBundle(); + String location = bundle.getLocation(); + String queueName = knownBundles.get(location); + Semaphore actionSemaphore = waitingActions.get(location); + + // Ignore event if we have no queueName for this bundle in the map + if(queueName == null) { + logger.debug("Ignoring event for bundle " + bundle.getSymbolicName()); + return; + } else { + logger.debug("Handling event of type " + event.getType() + " for bundle " + bundle.getSymbolicName()); + } + + // Preparing CacheACK to be posted + CacheAck ack = null; + + switch(event.getType()) { + case BundleEvent.STARTED: + logger.debug("Bundle " + bundle.getSymbolicName() + " STARTED"); + + // Starting a loop to check number of registered services, this allow to wait for the route to be UP + // Previously using ServiceListener (filtered with the two services CamelContext + another one) + // but took up to 20s to be notified for route startup (really random time) + boolean isBundleStarted = waitForBundleStarted(bundle); + + if(isBundleStarted) { + ack = CacheAck.OK; + } else { + logger.error("Bundle " + bundle.getSymbolicName() + " not started in time"); + ack = CacheAck.KO; + } + + break; + + case BundleEvent.UNINSTALLED: + logger.debug("Bundle " + bundle.getSymbolicName() + " UNINSTALLED"); + + if (actionSemaphore!=null) actionSemaphore.release(); + + break; + + case BundleEvent.INSTALLED: + logger.debug("Bundle " + bundle.getSymbolicName() + " INSTALLED"); + break; + case BundleEvent.RESOLVED: + logger.debug("Bundle " + bundle.getSymbolicName() + " RESOLVED"); + break; + case BundleEvent.STARTING: + logger.debug("Bundle " + bundle.getSymbolicName() + " STARTING"); + break; + case BundleEvent.STOPPED: + if (actionSemaphore!=null) actionSemaphore.release(); + logger.debug("Bundle " + bundle.getSymbolicName() + " STOPPED"); + break; + case BundleEvent.STOPPING: + logger.debug("Bundle " + bundle.getSymbolicName() + " STOPPING"); + break; + case BundleEvent.UNRESOLVED: + logger.debug("Bundle " + bundle.getSymbolicName() + " UNRESOLVED"); + break; + case BundleEvent.UPDATED: + logger.trace("Bundle " + bundle.getSymbolicName() + " UPDATED"); + break; + + default: + logger.trace("Unknown BundleEvent type"); + break; + } + + if(ack != null) { + logger.debug("Posting ack " + ack + " for bundle " + bundle.getSymbolicName() + " on queue " + queueName); + postAck(ack, queueName); + } + } + + + /** + * Utility method to post an ACK on a given queue + * @param ack The ACK to post + * @param queueName The queue name on which the ACK must be posted + */ + private void postAck(CacheAck ack, String queueName) { + try { + logger.debug("Posted ACK " + ack + " on queue " + queueName); + + // ACK will be posted on local queue + dataManager.postAcknowledgment(queueName, ack); + + } catch (InterruptedException ex) { + logger.error("Unable to post ack", ex); + } + } + + private boolean isBundleStarted(Bundle bundle) { + boolean isStarted = false; + ServiceReference[] services = bundle.getRegisteredServices(); + if (services != null && services.length>1) { + isStarted = true; + } + return isStarted; + } + + private boolean waitForBundleStarted(Bundle bundle) { + int attempts = SERVICES_LOOP_ATTEMPTS; + boolean bundleStarted = false; + + try { + while (!isBundleStarted(bundle) && attempts > 0) { + Thread.sleep(SERVICES_LOOP_DURATION); + if (logger.isDebugEnabled()) + logger.debug("Number of " + SERVICES_LOOP_DURATION + "ms attempt for route started test: " + attempts); + attempts--; + } + + bundleStarted = isBundleStarted(bundle); + + } catch(InterruptedException e) { + logger.error("Error while waiting for bundle start", e); + } + + return bundleStarted; + } + + +} diff --git a/exposure-engine/gateway-common/src/main/java/com/alu/e3/gateway/GatewayInfo.java b/exposure-engine/gateway-common/src/main/java/com/alu/e3/gateway/GatewayInfo.java new file mode 100644 index 0000000..249f70b --- /dev/null +++ b/exposure-engine/gateway-common/src/main/java/com/alu/e3/gateway/GatewayInfo.java @@ -0,0 +1,139 @@ +/** + * Copyright © 2012 Alcatel-Lucent. + * + * See the NOTICE file distributed with this work for additional + * information regarding copyright ownership. + * Licensed to you 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 com.alu.e3.gateway; + +import java.util.LinkedList; + +import com.alu.e3.common.caching.ICacheManager; +import com.alu.e3.common.caching.ICacheTable; +import com.alu.e3.common.caching.IEntryListener; +import com.alu.e3.common.info.GatewayStatus; +import com.alu.e3.common.info.IGatewayInfo; +import com.alu.e3.common.info.IGatewayInfoListener; +import com.alu.e3.common.osgi.api.IInstanceInfo; +import com.alu.e3.data.DataEntryEvent; + +/** + * Get ans set the status of the current instance. + */ +public class GatewayInfo implements IGatewayInfo, IEntryListener { + + private ICacheManager cacheManager; + private ICacheTable cachingTableGatewayInfo; + private IInstanceInfo instanceInfo; + + public void setCacheManager(ICacheManager cacheManager) { + this.cacheManager = cacheManager; + } + + public void setInstanceInfo(IInstanceInfo instanceInfo) { + this.instanceInfo = instanceInfo; + } + + public void setCachingTableGatewayInfo(ICacheTable cachingTableGatewayInfo) { + this.cachingTableGatewayInfo = cachingTableGatewayInfo; + } + + public void setGatewayInfoListeners(LinkedList gatewayInfoListeners) { + this.gatewayInfoListeners = gatewayInfoListeners; + } + + public void init() { + // Due to restart this bundle restriction + // we must createOrGet the cached table instead of create or null ! + cachingTableGatewayInfo = this.cacheManager.createOrGetTable(IGatewayInfo.GATEWAY_STATUS_TABLE_NAME, false, null); + this.setStatus(GatewayStatus.DOWN); + + // Since destroy() method has been called on restart this bundle + // We can re-call addEntryListener(...) without any doubts. + cachingTableGatewayInfo.addEntryListener(this); + + instanceInfo.setGateway(true); + instanceInfo.setGatewayInfo(this); + } + + public void destroy() + { + if (cachingTableGatewayInfo != null) + cachingTableGatewayInfo.removeEntryListener(this); + } + + @Override + public void setStatus(String instanceStatus) { + cachingTableGatewayInfo.set(IGatewayInfo.GATEWAY_STATUS_CACHE_ENTRY, instanceStatus); + } + + @Override + public String getStatus() { + String status = cachingTableGatewayInfo.get(IGatewayInfo.GATEWAY_STATUS_CACHE_ENTRY); + if(status == null) + status = GatewayStatus.DOWN; + return status; + } + + /** + * Gateway Status listener. + */ + private LinkedList gatewayInfoListeners = new LinkedList(); + + @Override + public void addGatewayInfoListener(IGatewayInfoListener listener) { + gatewayInfoListeners.add(listener); + } + + @Override + public void removeGatewayInfoListener(IGatewayInfoListener listener) { + gatewayInfoListeners.remove(listener); + } + + + /** + * Status Table listener + */ + @Override + public void entryAdded(DataEntryEvent event) { + fireGatewayStatusEvent(event); + } + + @Override + public void entryUpdated(DataEntryEvent event) { + fireGatewayStatusEvent(event); + } + + private void fireGatewayStatusEvent(DataEntryEvent event) + { + if (!IGatewayInfo.GATEWAY_STATUS_CACHE_ENTRY.equals(event.getKey())) + return; + + + IGatewayInfoListener[] listeners = null; + synchronized(this) + { + listeners = new IGatewayInfoListener[0]; + listeners = gatewayInfoListeners.toArray(listeners); + } + + for (int i = 0; i < listeners.length; i++) { + listeners[i].gatewayStatusChanged(event.getValue()); + } + } + + @Override + public void entryRemoved(DataEntryEvent event) { } +} \ No newline at end of file diff --git a/exposure-engine/gateway-common/src/main/java/com/alu/e3/gateway/GatewayWatcher.java b/exposure-engine/gateway-common/src/main/java/com/alu/e3/gateway/GatewayWatcher.java new file mode 100644 index 0000000..30d07d9 --- /dev/null +++ b/exposure-engine/gateway-common/src/main/java/com/alu/e3/gateway/GatewayWatcher.java @@ -0,0 +1,109 @@ +/** + * Copyright © 2012 Alcatel-Lucent. + * + * See the NOTICE file distributed with this work for additional + * information regarding copyright ownership. + * Licensed to you 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 com.alu.e3.gateway; + +import org.osgi.framework.Bundle; +import org.osgi.framework.BundleContext; +import org.osgi.framework.BundleException; +import org.springframework.beans.factory.annotation.Autowired; + +import com.alu.e3.common.info.GatewayStatus; +import com.alu.e3.common.info.IGatewayInfo; +import com.alu.e3.common.info.IGatewayInfoListener; +import com.alu.e3.common.logging.Category; +import com.alu.e3.common.logging.CategoryLogger; +import com.alu.e3.common.logging.CategoryLoggerFactory; +import com.alu.e3.common.osgi.api.IHealthCheckFactory; +import com.alu.e3.data.IHealthCheckService; + +public class GatewayWatcher implements IGatewayInfoListener{ + + protected static final CategoryLogger logger = CategoryLoggerFactory.getLogger(GatewayWatcher.class, Category.SYS); + + private IGatewayInfo gatewayInfo; + private IHealthCheckFactory healthCheckFactory; + private IHealthCheckService healthCheck; + private IHealthCheckService healthCheckInternal; + + protected BundleContext bundleContext; + + public GatewayWatcher() {} + + public void init() { + gatewayInfo.addGatewayInfoListener(this); + + healthCheck = healthCheckFactory.getHealthCheckService(IHealthCheckFactory.GATEWAY_TYPE); + + uninstallApiBundles(); + + healthCheckInternal = healthCheckFactory.getHealthCheckService(IHealthCheckFactory.GATEWAY_INTERNAL_TYPE); + healthCheckInternal.start(); + } + + public void setGatewayInfo(IGatewayInfo gatewayInfo) { + this.gatewayInfo = gatewayInfo; + } + + public void setHealthCheckFactory(IHealthCheckFactory healthCheckFactory) { + this.healthCheckFactory = healthCheckFactory; + } + + public void destroy() { + if (healthCheck != null) + healthCheck.stop(); + if (healthCheckInternal != null) + healthCheckInternal.stop(); + + if (gatewayInfo != null) + gatewayInfo.removeGatewayInfoListener(this); + } + + @Autowired + public void setBundleContext(BundleContext bundleContext) { + this.bundleContext = bundleContext; + } + + @Override + public void gatewayStatusChanged(String status) { + + if(GatewayStatus.PROVISIONED.equals(status)) { + + healthCheck.start(); + + gatewayInfo.setStatus(GatewayStatus.UP); + } + } + + private void uninstallApiBundles() { + String prefix = ApiDeploymentManager.BUNDLE_LOCATION_URI_PREFIX; + + Bundle[] bundles = bundleContext.getBundles(); + for(Bundle bundle : bundles) { + try { + if(bundle.getLocation().startsWith(prefix)) { + logger.debug("Uninstalling bundle " + bundle.getSymbolicName()); + bundle.uninstall(); + } + } catch (BundleException e) { + logger.error("Unable to uninstall bundle " + bundle.getSymbolicName()); + } + } + } + +} diff --git a/exposure-engine/gateway-common/src/main/java/com/alu/e3/gateway/HeaderTransHelper.java b/exposure-engine/gateway-common/src/main/java/com/alu/e3/gateway/HeaderTransHelper.java new file mode 100644 index 0000000..2cc31cb --- /dev/null +++ b/exposure-engine/gateway-common/src/main/java/com/alu/e3/gateway/HeaderTransHelper.java @@ -0,0 +1,99 @@ +/** + * Copyright © 2012 Alcatel-Lucent. + * + * See the NOTICE file distributed with this work for additional + * information regarding copyright ownership. + * Licensed to you 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 com.alu.e3.gateway; + +import java.util.HashMap; +import java.util.Iterator; +import java.util.List; +import java.util.Map; + +import org.apache.camel.Exchange; + +import com.alu.e3.common.camel.AuthIdentity; +import com.alu.e3.common.camel.ExchangeConstantKeys; +import com.alu.e3.data.model.Api; +import com.alu.e3.data.model.Auth; +import com.alu.e3.data.model.CallDescriptor; +import com.alu.e3.data.model.Policy; +import com.alu.e3.data.model.enumeration.HeaderTransformationType; +import com.alu.e3.data.model.sub.HeaderTransformation; + + +public class HeaderTransHelper { + + /** + * Private helper function to do the work of iterating all of the lists of headers and applying them to the request/response + * @param trans + * @param type + * @param properties + * @param exchange + */ + private static void applyHeaderTransforms(List trans, HeaderTransformationType type, Map properties, Exchange exchange){ + if(trans != null) + for(HeaderTransformation tran : trans){ + if(tran.getType().equals(type)){ + switch (tran.getAction()){ + case ADD: + if(tran.getValue() != null && !tran.getValue().equals("")) + exchange.getIn().setHeader(tran.getName(), tran.getValue()); + else if(tran.getProperty() != null && !tran.getProperty().equals("")) + exchange.getIn().setHeader(tran.getName(), properties.get(tran.getProperty())); + break; + case REMOVE: + exchange.getIn().removeHeader(tran.getName()); + break; + default: + break; + } + } + } + } + + /** + * Public static function to centralize the functionality of applying the transformations to the request/response + * @param type + * @param exchange + */ + public static void applyHeaderTransforms(HeaderTransformationType type, Exchange exchange){ + AuthIdentity identity = (AuthIdentity) exchange.getProperty(ExchangeConstantKeys.E3_AUTH_IDENTITY.toString()); + @SuppressWarnings("unchecked") + Map properties = (Map) exchange.getProperty(ExchangeConstantKeys.E3_MODEL_PROPERTIES.toString()); + if(properties == null) + properties = new HashMap(); + + // First add the TDRs from the API + Api api = identity.getApi(); + applyHeaderTransforms(api.getHeaderTransformations(), type, properties, exchange); + + // Next add all of the tdr values for the Policies + Iterator it = identity.getCallDescriptors().iterator(); + while(it.hasNext()){ + CallDescriptor cd = it.next(); + Policy policy = cd.getPolicy(); + if(policy != null){ + HeaderTransHelper.applyHeaderTransforms(policy.getHeaderTransformations(), type, properties, exchange); + } + } + + // Finally add the values from the Auth + Auth auth = identity.getAuth(); + if(auth != null) + HeaderTransHelper.applyHeaderTransforms(auth.getHeaderTransformations(), type, properties, exchange); + } +} diff --git a/exposure-engine/gateway-common/src/main/java/com/alu/e3/gateway/SslJettyComponentWatcher.java b/exposure-engine/gateway-common/src/main/java/com/alu/e3/gateway/SslJettyComponentWatcher.java new file mode 100644 index 0000000..3455eb7 --- /dev/null +++ b/exposure-engine/gateway-common/src/main/java/com/alu/e3/gateway/SslJettyComponentWatcher.java @@ -0,0 +1,70 @@ +/** + * Copyright © 2012 Alcatel-Lucent. + * + * See the NOTICE file distributed with this work for additional + * information regarding copyright ownership. + * Licensed to you 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 com.alu.e3.gateway; + +import java.util.Map; + +import org.apache.camel.CamelContext; +import org.slf4j.Logger; +import org.slf4j.LoggerFactory; +import org.springframework.beans.factory.annotation.Autowired; +import org.springframework.osgi.service.importer.OsgiServiceLifecycleListener; + +public class SslJettyComponentWatcher implements OsgiServiceLifecycleListener { + + private static final Logger LOG = LoggerFactory.getLogger(SslJettyComponentWatcher.class); + + private CamelContext localCamelContext; + + /** + * Retrieves the local camel context. + * @param localCamelContext + */ + @Autowired + public void setLocalCamelContext(CamelContext localCamelContext) { + this.localCamelContext = localCamelContext; + } + + public SslJettyComponentWatcher() { + LOG.debug("SslJettyComponentWatcher construction."); + } + + protected void init() { + LOG.debug("SslJettyComponentWatcher initialization ..."); + } + + protected void destroy() { + LOG.debug("SslJettyComponentWatcher destruction ..."); + localCamelContext = null; + } + + @Override + @SuppressWarnings("rawtypes") + public void bind(Object service, Map properties) throws Exception { + LOG.debug("Starting local camel context ..."); + localCamelContext.start(); + } + + @Override + @SuppressWarnings("rawtypes") + public void unbind(Object service, Map properties) throws Exception { + LOG.debug("Stopping local camel context ..."); + localCamelContext.stop(); + } +} diff --git a/exposure-engine/gateway-common/src/main/java/com/alu/e3/gateway/TargetHost2HttpRouteUtil.java b/exposure-engine/gateway-common/src/main/java/com/alu/e3/gateway/TargetHost2HttpRouteUtil.java new file mode 100644 index 0000000..5d4ad8a --- /dev/null +++ b/exposure-engine/gateway-common/src/main/java/com/alu/e3/gateway/TargetHost2HttpRouteUtil.java @@ -0,0 +1,59 @@ +/** + * Copyright © 2012 Alcatel-Lucent. + * + * See the NOTICE file distributed with this work for additional + * information regarding copyright ownership. + * Licensed to you 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 com.alu.e3.gateway; + +import java.net.URL; + +import org.apache.http.HttpHost; +import org.apache.http.conn.routing.HttpRoute; +import org.apache.log4j.Logger; + +import com.alu.e3.data.model.sub.TargetHost; + +public class TargetHost2HttpRouteUtil { + private static Logger logger = Logger.getLogger(TargetHost2HttpRouteUtil.class); + + public static HttpRoute fromTargetHost(TargetHost th){ + HttpRoute route = null; + try{ + URL url = new URL(th.getUrl()); + boolean secured = url.getProtocol().equalsIgnoreCase("HTTPS"); + + if(th.getForwardProxy() != null){ + route = new HttpRoute( + new HttpHost(url.getHost(), url.getPort()), + null, + new HttpHost(th.getForwardProxy().getProxyHost(), + Integer.parseInt(th.getForwardProxy().getProxyPort())), + secured); + } + else{ + route = new HttpRoute( + new HttpHost(url.getHost(), url.getPort()), + null, + secured); + } + + } catch(Exception e){ + logger.error(e.getMessage(), e); + } + + return route; + } +} diff --git a/exposure-engine/gateway-common/src/main/java/com/alu/e3/gateway/TdrProcessorHelper.java b/exposure-engine/gateway-common/src/main/java/com/alu/e3/gateway/TdrProcessorHelper.java new file mode 100644 index 0000000..5c7c42e --- /dev/null +++ b/exposure-engine/gateway-common/src/main/java/com/alu/e3/gateway/TdrProcessorHelper.java @@ -0,0 +1,148 @@ +/** + * Copyright © 2012 Alcatel-Lucent. + * + * See the NOTICE file distributed with this work for additional + * information regarding copyright ownership. + * Licensed to you 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 com.alu.e3.gateway; + +import java.util.HashMap; +import java.util.Iterator; +import java.util.Map; + +import org.apache.camel.Exchange; + +import com.alu.e3.common.camel.AuthIdentity; +import com.alu.e3.common.camel.ExchangeConstantKeys; +import com.alu.e3.data.model.Api; +import com.alu.e3.data.model.Auth; +import com.alu.e3.data.model.CallDescriptor; +import com.alu.e3.data.model.ExtractFromType; +import com.alu.e3.data.model.Policy; +import com.alu.e3.data.model.sub.TdrDynamicRule; +import com.alu.e3.data.model.sub.TdrGenerationRule; +import com.alu.e3.data.model.sub.TdrStaticRule; +import com.alu.e3.tdr.TDRDataService; + +public class TdrProcessorHelper { + public static void processTdrRules(Exchange exchange, ExtractFromType efType, boolean doStatic){ + AuthIdentity identity = (AuthIdentity) exchange.getProperty(ExchangeConstantKeys.E3_AUTH_IDENTITY.toString()); + if (identity == null) return; + @SuppressWarnings("unchecked") + Map properties = (Map) exchange.getProperty(ExchangeConstantKeys.E3_MODEL_PROPERTIES.toString()); + if(properties == null) + properties = new HashMap(); + + // First add the TDRs from the API + Api api = identity.getApi(); + if (api != null) + if(doStatic) + processTdrGenerationRuleStatic(api.getTdrGenerationRule(), exchange, properties); + else + processTdrGenerationRuleDynamic(api.getTdrGenerationRule(), exchange, properties, efType); + + // Next add all of the tdr values for the Policies + Iterator it = identity.getCallDescriptors().iterator(); + while(it.hasNext()){ + CallDescriptor cd = it.next(); + Policy policy = cd.getPolicy(); + if(policy != null){ + if(doStatic) + processTdrGenerationRuleStatic(policy.getTdrGenerationRule(), exchange, properties); + else + processTdrGenerationRuleDynamic(policy.getTdrGenerationRule(), exchange, properties, efType); + } + } + + // Finally add the values from the Auth + Auth auth = identity.getAuth(); + if(auth != null) + if(doStatic) + processTdrGenerationRuleStatic(auth.getTdrGenerationRule(), exchange, properties); + else + processTdrGenerationRuleDynamic(auth.getTdrGenerationRule(), exchange, properties, efType); + } + + /** + * Inner helper function to help iterate through all the TdrGenerationRules from all + * of the relevant objects, adding the TDR values to the TDRDataService. + * + * @param genRule + * @param exchange + */ + private static void processTdrGenerationRuleDynamic(TdrGenerationRule genRule, Exchange exchange, Map properties, ExtractFromType efType){ + // If the genRule is null then we don't want to continue + if(genRule == null) return; + + // First go through the dynamic rules + if(genRule.getDynamicRules() != null){ + for (TdrDynamicRule rule : genRule.getDynamicRules()) { + if(rule.getExtractFrom().equals(efType) || rule.getExtractFrom().equals(ExtractFromType.Either)){ + for(String type : rule.getTypes()){ + TDRDataService.setPropertyForType(type, + rule.getTdrPropName(), + TDRDataService.evalDynamicProperty(rule.getHttpHeaderName(), exchange), + exchange); + } + + if(rule.getTypes() == null || rule.getTypes().size() <= 0){ + TDRDataService.addCommonProperty(exchange, rule.getTdrPropName(), + TDRDataService.evalDynamicProperty(rule.getHttpHeaderName(), exchange)); + } + } + } + } + } + + private static void processTdrGenerationRuleStatic( + TdrGenerationRule genRule, Exchange exchange, + Map properties) { + if(genRule == null) return; + // If we are processing the response and there are static rules + for (TdrStaticRule rule : genRule.getStaticRules()) { + for(String type : rule.getTypes()){ + // If truly a static value + if(rule.getValue() != null && !rule.equals("")) + TDRDataService.setPropertyForType(type, + rule.getTdrPropName(), + rule.getValue(), + exchange); + // If a property value + else if(rule.getPropertyName() != null && !rule.getPropertyName().equals("")){ + String value = ""; // Default + if(properties.containsKey(rule.getPropertyName())){ + value = properties.get(rule.getPropertyName()); + } + + TDRDataService.setPropertyForType(type.toString(), + rule.getTdrPropName(), + value, + exchange); + } + } + + // If not types are specified then we'll add the property to the common Map, so it will + // be appended to ALL TDRs generated in this transaction + if(rule.getTypes() == null || rule.getTypes().size() <= 0){ + if(rule.getValue() != null && !rule.equals("")) + TDRDataService.addCommonProperty(exchange, rule.getTdrPropName(), rule.getValue()); + else if(rule.getPropertyName() != null && !rule.getPropertyName().equals("")) + TDRDataService.addCommonProperty(exchange, rule.getTdrPropName(), properties.get(rule.getPropertyName())); + } + } + } + + +} diff --git a/exposure-engine/gateway-common/src/main/java/com/alu/e3/gateway/common/camel/component/E3HttpBinding.java b/exposure-engine/gateway-common/src/main/java/com/alu/e3/gateway/common/camel/component/E3HttpBinding.java new file mode 100644 index 0000000..18ad5eb --- /dev/null +++ b/exposure-engine/gateway-common/src/main/java/com/alu/e3/gateway/common/camel/component/E3HttpBinding.java @@ -0,0 +1,117 @@ +/** + * Copyright © 2012 Alcatel-Lucent. + * + * See the NOTICE file distributed with this work for additional + * information regarding copyright ownership. + * Licensed to you 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 com.alu.e3.gateway.common.camel.component; + +import java.io.IOException; +import java.io.UnsupportedEncodingException; +import java.util.HashMap; +import java.util.Map; + +import javax.servlet.http.HttpServletRequest; +import javax.servlet.http.HttpServletResponse; + +import org.apache.camel.Exchange; +import org.apache.camel.Message; +import org.apache.camel.component.http.DefaultHttpBinding; +import org.apache.camel.component.http.HttpEndpoint; +import org.apache.camel.component.http.HttpMessage; +import org.apache.camel.spi.HeaderFilterStrategy; +import org.eclipse.jetty.http.HttpHeaderValues; +import org.eclipse.jetty.http.HttpHeaders; + +import com.alu.e3.common.camel.ExchangeConstantKeys; +import com.alu.e3.gateway.common.camel.exception.GatewayException; + +/** + * HTTP binding that doesn't write request parameters to the input headers. + * + * + */ +public class E3HttpBinding extends DefaultHttpBinding { + + @Deprecated + public E3HttpBinding() { + super(); + } + + @Deprecated + public E3HttpBinding(HeaderFilterStrategy headerFilterStrategy) { + super(headerFilterStrategy); + } + + public E3HttpBinding(HttpEndpoint endpoint) { + super(endpoint); + } + + @Override + protected void populateRequestParameters(HttpServletRequest request, HttpMessage message) + throws UnsupportedEncodingException { + + // Save the headers and set a new map for the request parameters + Map originalHeaders = message.getHeaders(); + message.setHeaders(new HashMap()); + + super.populateRequestParameters(request, message); + + // Set the request parameters map as a new exchange property, and restore + // the original headers. + message.getExchange().setProperty( + ExchangeConstantKeys.E3_REQUEST_PARAMETERS.toString(), message.getHeaders()); + message.setHeaders(originalHeaders); + } + + @SuppressWarnings("deprecation") + @Override + public void doWriteResponse(Message message, HttpServletResponse response, Exchange exchange) throws IOException { + Exception e = exchange.getProperty(Exchange.EXCEPTION_CAUGHT, Exception.class); + if (e instanceof GatewayException) { + switch (((GatewayException) e).getCode()) { + case AUTHORIZATION: + case AUTHORIZATION_BASIC: + case AUTHORIZATION_WSSE: + case RATEORQUOTA: + case VALIDATION: + // Causes the connection will be closed. + response.setHeader(HttpHeaders.CONNECTION, HttpHeaderValues.CLOSE); + } + } + + // set the status code in the response. Default is 200. + if ((message.getHeader(Exchange.HTTP_RESPONSE_CODE) != null) && + (exchange.getProperty(ExchangeConstantKeys.E3_HTTP_STATUS_LINE_REASON_PHRASE.toString()) != null)){ + int code = message.getHeader(Exchange.HTTP_RESPONSE_CODE, Integer.class); + String reason = exchange.getProperty(ExchangeConstantKeys.E3_HTTP_STATUS_LINE_REASON_PHRASE.toString(), String.class); + response.setStatus(code, reason); + + try { + // Remove HTTP_RESPONSE_CODE header in order to not overwrite + // status line reason part. + message.removeHeader(Exchange.HTTP_RESPONSE_CODE); + exchange.removeProperty(ExchangeConstantKeys.E3_HTTP_STATUS_LINE_REASON_PHRASE.toString()); + super.doWriteResponse(message, response, exchange); + } finally { + // Restore HTTP_RESPONSE_CODE + message.setHeader(Exchange.HTTP_RESPONSE_CODE, code); + } + } else { + super.doWriteResponse(message, response, exchange); + } + } + +} diff --git a/exposure-engine/gateway-common/src/main/java/com/alu/e3/gateway/common/camel/component/SslJettyHttpComponent.java b/exposure-engine/gateway-common/src/main/java/com/alu/e3/gateway/common/camel/component/SslJettyHttpComponent.java new file mode 100644 index 0000000..91b84e3 --- /dev/null +++ b/exposure-engine/gateway-common/src/main/java/com/alu/e3/gateway/common/camel/component/SslJettyHttpComponent.java @@ -0,0 +1,109 @@ +/** + * Copyright © 2012 Alcatel-Lucent. + * + * See the NOTICE file distributed with this work for additional + * information regarding copyright ownership. + * Licensed to you 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 com.alu.e3.gateway.common.camel.component; + +import java.security.KeyStore; +import java.security.cert.CRL; +import java.util.Collection; +import java.util.Map; + +import javax.net.ssl.TrustManager; + +import org.apache.camel.Endpoint; +import org.apache.camel.component.jetty.JettyHttpComponent; +import org.eclipse.jetty.http.ssl.SslContextFactory; +import org.eclipse.jetty.server.ssl.SslSelectChannelConnector; +import org.slf4j.Logger; +import org.slf4j.LoggerFactory; + +import com.alu.e3.gateway.security.E3TrustManager; + +public class SslJettyHttpComponent extends JettyHttpComponent { + + Logger LOG = LoggerFactory.getLogger(SslJettyHttpComponent.class); + + private String keyStorePath; + private String keyStorePassword; + private String keyStoreKeyPassword; + private String trustStorePath; + private String trustStorePassword; + + @Override + protected Endpoint createEndpoint(String uri, String remaining, + Map parameters) throws Exception { + uri = uri.startsWith("ssljetty:") ? uri.substring(3) : uri; + return super.createEndpoint(uri, remaining, parameters); + } + + @Override + protected SslSelectChannelConnector createSslSocketConnector() + throws Exception { + + LOG.debug("A new SSL Connector is being made!!"); + + SslContextFactory sslContextFactory = new SslContextFactory() { + @Override + protected TrustManager[] getTrustManagers(KeyStore trustStore, + Collection crls) throws Exception + { + E3TrustManager trustManager = new E3TrustManager(trustStore); + // set this flag only when there's at least one CA + setWantClientAuth(trustManager.getAcceptedIssuers().length > 0); + return new TrustManager[] {trustManager}; + } + }; + + sslContextFactory.setKeyStoreType("BKS"); + sslContextFactory.setKeyStoreProvider("BC"); + + // This password (used to encrypt keys in the keystore) must not be longer than 7 characters!!! + sslContextFactory.setKeyManagerPassword(keyStoreKeyPassword); + sslContextFactory.setKeyStorePassword(keyStorePassword); + + sslContextFactory.setKeyStore(keyStorePath); + + sslContextFactory.setTrustStoreType("BKS"); + sslContextFactory.setTrustStoreProvider("BC"); + + sslContextFactory.setTrustStorePassword(trustStorePassword); + sslContextFactory.setTrustStore(trustStorePath); + + return new SslSelectChannelConnector(sslContextFactory); + } + + public void setKeyStorePath(String keyStorePath) { + this.keyStorePath = keyStorePath; + } + + public void setKeyStorePassword(String keyStorePassword) { + this.keyStorePassword = keyStorePassword; + } + + public void setKeyStoreKeyPassword(String keyStoreKeyPassword) { + this.keyStoreKeyPassword = keyStoreKeyPassword; + } + + public void setTrustStorePath(String trustStorePath) { + this.trustStorePath = trustStorePath; + } + + public void setTrustStorePassword(String trustStorePassword) { + this.trustStorePassword = trustStorePassword; + } +} diff --git a/exposure-engine/gateway-common/src/main/java/com/alu/e3/gateway/common/camel/exception/GatewayException.java b/exposure-engine/gateway-common/src/main/java/com/alu/e3/gateway/common/camel/exception/GatewayException.java new file mode 100644 index 0000000..15cf12a --- /dev/null +++ b/exposure-engine/gateway-common/src/main/java/com/alu/e3/gateway/common/camel/exception/GatewayException.java @@ -0,0 +1,73 @@ +/** + * Copyright © 2012 Alcatel-Lucent. + * + * See the NOTICE file distributed with this work for additional + * information regarding copyright ownership. + * Licensed to you 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 com.alu.e3.gateway.common.camel.exception; + +public class GatewayException extends Exception { + + private static final long serialVersionUID = 7743794919826042257L; + + private GatewayExceptionCode code; + + private String action; + + public GatewayException(GatewayExceptionCode code, String message, Throwable cause) { + super(message, cause); + this.setCode(code); + } + + public GatewayException(GatewayExceptionCode code, String message) { + super(message); + this.setCode(code); + } + + public GatewayException(GatewayExceptionCode code, String message, String action) { + this(code, message); + this.setAction(action); + } + + /** + * @return the action + */ + public String getAction() { + return action; + } + + /** + * @param action the action to set + */ + public void setAction(String action) { + this.action = action; + } + + /** + * @return the code + */ + public GatewayExceptionCode getCode() { + return code; + } + + + /** + * @param code the code to set + */ + public void setCode(GatewayExceptionCode code) { + this.code = code; + } + +} diff --git a/exposure-engine/gateway-common/src/main/java/com/alu/e3/gateway/common/camel/exception/GatewayExceptionCode.java b/exposure-engine/gateway-common/src/main/java/com/alu/e3/gateway/common/camel/exception/GatewayExceptionCode.java new file mode 100644 index 0000000..22083b3 --- /dev/null +++ b/exposure-engine/gateway-common/src/main/java/com/alu/e3/gateway/common/camel/exception/GatewayExceptionCode.java @@ -0,0 +1,32 @@ +/** + * Copyright © 2012 Alcatel-Lucent. + * + * See the NOTICE file distributed with this work for additional + * information regarding copyright ownership. + * Licensed to you 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 com.alu.e3.gateway.common.camel.exception; + +public enum GatewayExceptionCode { + + API_NOT_ACTIVATED, + AUTHORIZATION, + AUTHORIZATION_BASIC, + AUTHORIZATION_WSSE, + RATEORQUOTA, + VALIDATION, + NOTIFY_URL, + HTTP_METHOD, + LOAD_BALANCER +} diff --git a/exposure-engine/gateway-common/src/main/java/com/alu/e3/gateway/common/camel/processor/AbstractNotifyUrlProcessor.java b/exposure-engine/gateway-common/src/main/java/com/alu/e3/gateway/common/camel/processor/AbstractNotifyUrlProcessor.java new file mode 100644 index 0000000..9af7abf --- /dev/null +++ b/exposure-engine/gateway-common/src/main/java/com/alu/e3/gateway/common/camel/processor/AbstractNotifyUrlProcessor.java @@ -0,0 +1,42 @@ +/** + * Copyright © 2012 Alcatel-Lucent. + * + * See the NOTICE file distributed with this work for additional + * information regarding copyright ownership. + * Licensed to you 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 com.alu.e3.gateway.common.camel.processor; + +import org.apache.camel.Exchange; +import org.apache.camel.Processor; + +import com.alu.e3.common.tools.CommonTools; +import com.alu.e3.gateway.common.camel.exception.GatewayException; +import com.alu.e3.gateway.common.camel.exception.GatewayExceptionCode; + +public abstract class AbstractNotifyUrlProcessor implements Processor { + + @Override + public abstract void process(Exchange exchange) throws Exception; + + protected void injectUriAndQueryString(String notifyUrl, Exchange exchange) throws GatewayException { + String[] parts = CommonTools.splitUrl(notifyUrl); + if(parts == null) + throw new GatewayException(GatewayExceptionCode.NOTIFY_URL, "Notification URL is invalid"); + + exchange.getIn().setHeader(Exchange.HTTP_URI, parts[0]); + exchange.getIn().setHeader(Exchange.HTTP_QUERY, parts[1]); + } + +} diff --git a/exposure-engine/gateway-common/src/main/java/com/alu/e3/gateway/common/camel/processor/ClientCertificateValidator.java b/exposure-engine/gateway-common/src/main/java/com/alu/e3/gateway/common/camel/processor/ClientCertificateValidator.java new file mode 100644 index 0000000..9b6065b --- /dev/null +++ b/exposure-engine/gateway-common/src/main/java/com/alu/e3/gateway/common/camel/processor/ClientCertificateValidator.java @@ -0,0 +1,45 @@ +/** + * Copyright © 2012 Alcatel-Lucent. + * + * See the NOTICE file distributed with this work for additional + * information regarding copyright ownership. + * Licensed to you 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 com.alu.e3.gateway.common.camel.processor; + +import java.security.cert.X509Certificate; + +import javax.servlet.http.HttpServletRequest; + +import org.apache.camel.Exchange; +import org.apache.camel.Processor; + +import com.alu.e3.gateway.common.camel.exception.GatewayException; +import com.alu.e3.gateway.common.camel.exception.GatewayExceptionCode; + +public class ClientCertificateValidator implements Processor { + + @Override + public void process(Exchange exchange) throws Exception { + + HttpServletRequest req = exchange.getIn().getBody(HttpServletRequest.class); + X509Certificate[] cert = (X509Certificate[]) req.getAttribute("javax.servlet.request.X509Certificate"); + + if ((cert == null) || (cert.length == 0)) { + // we don't have a client certificate => stop the request + throw new GatewayException(GatewayExceptionCode.AUTHORIZATION, "Missing certificate"); + } + } + +} diff --git a/exposure-engine/gateway-common/src/main/java/com/alu/e3/gateway/common/camel/processor/GatewayErrorProcessor.java b/exposure-engine/gateway-common/src/main/java/com/alu/e3/gateway/common/camel/processor/GatewayErrorProcessor.java new file mode 100644 index 0000000..b8d8e6b --- /dev/null +++ b/exposure-engine/gateway-common/src/main/java/com/alu/e3/gateway/common/camel/processor/GatewayErrorProcessor.java @@ -0,0 +1,98 @@ +/** + * Copyright © 2012 Alcatel-Lucent. + * + * See the NOTICE file distributed with this work for additional + * information regarding copyright ownership. + * Licensed to you 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 com.alu.e3.gateway.common.camel.processor; + +import org.apache.camel.Exchange; +import org.apache.camel.Processor; +import org.apache.log4j.Logger; + +import com.alu.e3.common.camel.ExchangeConstantKeys; +import com.alu.e3.gateway.common.camel.exception.GatewayException; +import com.alu.e3.gateway.common.camel.exception.GatewayExceptionCode; + +public class GatewayErrorProcessor implements Processor { + + private static Logger logger = Logger.getLogger(GatewayErrorProcessor.class); + + @Override + public void process(Exchange exchange) throws Exception { + + boolean isNoteSpecialized = true; + + Exception exception = exchange.getProperty(Exchange.EXCEPTION_CAUGHT, Exception.class); + + if (exception instanceof GatewayException) { + + GatewayException gatewayException = (GatewayException) exception; + + if (gatewayException.getCode() == GatewayExceptionCode.AUTHORIZATION) { + String body = "Issue: " + gatewayException.getMessage(); + createHttpErrorResponse(exchange, 401, body); + isNoteSpecialized = false; + + } else if(gatewayException.getCode() == GatewayExceptionCode.AUTHORIZATION_BASIC) { + exchange.getOut().setHeader("WWW-Authenticate", "Basic realm=\"Secure Service\""); + String body = "Issue: " + gatewayException.getMessage(); + createHttpErrorResponse(exchange, 401, body); + isNoteSpecialized = false; + + } else if(gatewayException.getCode() == GatewayExceptionCode.API_NOT_ACTIVATED) { + String body = "Issue: " + gatewayException.getMessage(); + createHttpErrorResponse(exchange, 403, body); + isNoteSpecialized = false; + + } else if(gatewayException.getCode() == GatewayExceptionCode.VALIDATION) { + String body = "Issue: " + gatewayException.getMessage(); + createHttpErrorResponse(exchange, 400, body); + isNoteSpecialized = false; + } + if (gatewayException.getCode() == GatewayExceptionCode.RATEORQUOTA) { + String body = "Issue: " + gatewayException.getMessage(); + // Based on draft "Additional HTTP Status Codes; draft-nottingham-http-new-status-02" + // http://tools.ietf.org/html/draft-nottingham-http-new-status-02#page-4 + createHttpErrorResponse(exchange, 429, "Too Many Requests", body); + isNoteSpecialized = false; + } + if (gatewayException.getCode() == GatewayExceptionCode.HTTP_METHOD) { + String body = "Issue: " + gatewayException.getMessage(); + createHttpErrorResponse(exchange, 405, body); + isNoteSpecialized = false; + } + } + + if (isNoteSpecialized) { + int errorCode = 500; + String body = "Issue: Internal Server Error\n" + exception.getMessage(); + createHttpErrorResponse(exchange, errorCode, body); + isNoteSpecialized = false; + logger.debug(exception.getMessage(), exception); + } + } + + private void createHttpErrorResponse(Exchange exchange, int errorCode, String body) { + exchange.getOut().setHeader(Exchange.HTTP_RESPONSE_CODE, errorCode); + exchange.getOut().setHeader(Exchange.CONTENT_TYPE, "text/plain"); + exchange.getOut().setBody(body); + } + + private void createHttpErrorResponse(Exchange exchange, int errorCode, String errorMessage, String body) { + exchange.setProperty(ExchangeConstantKeys.E3_HTTP_STATUS_LINE_REASON_PHRASE.toString(), errorMessage); + createHttpErrorResponse(exchange, errorCode, body); + } +} diff --git a/exposure-engine/gateway-common/src/main/java/com/alu/e3/gateway/common/camel/processor/HeaderTransRequestProcessor.java b/exposure-engine/gateway-common/src/main/java/com/alu/e3/gateway/common/camel/processor/HeaderTransRequestProcessor.java new file mode 100644 index 0000000..33c5de3 --- /dev/null +++ b/exposure-engine/gateway-common/src/main/java/com/alu/e3/gateway/common/camel/processor/HeaderTransRequestProcessor.java @@ -0,0 +1,39 @@ +/** + * Copyright © 2012 Alcatel-Lucent. + * + * See the NOTICE file distributed with this work for additional + * information regarding copyright ownership. + * Licensed to you 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 com.alu.e3.gateway.common.camel.processor; + +import org.apache.camel.Exchange; +import org.apache.camel.Processor; +import org.apache.log4j.Logger; + +import com.alu.e3.data.model.enumeration.HeaderTransformationType; +import com.alu.e3.gateway.HeaderTransHelper; + +public class HeaderTransRequestProcessor implements Processor { + private static Logger logger = Logger.getLogger(HeaderTransRequestProcessor.class); + + @Override + public void process(Exchange exchange) throws Exception { + try{ + HeaderTransHelper.applyHeaderTransforms(HeaderTransformationType.REQUEST, exchange); + } catch(Exception e){ + logger.error(e.getMessage(), e); + } + } +} diff --git a/exposure-engine/gateway-common/src/main/java/com/alu/e3/gateway/common/camel/processor/HeaderTransResponseProcessor.java b/exposure-engine/gateway-common/src/main/java/com/alu/e3/gateway/common/camel/processor/HeaderTransResponseProcessor.java new file mode 100644 index 0000000..e872dcf --- /dev/null +++ b/exposure-engine/gateway-common/src/main/java/com/alu/e3/gateway/common/camel/processor/HeaderTransResponseProcessor.java @@ -0,0 +1,39 @@ +/** + * Copyright © 2012 Alcatel-Lucent. + * + * See the NOTICE file distributed with this work for additional + * information regarding copyright ownership. + * Licensed to you 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 com.alu.e3.gateway.common.camel.processor; + +import org.apache.camel.Exchange; +import org.apache.camel.Processor; +import org.apache.log4j.Logger; + +import com.alu.e3.data.model.enumeration.HeaderTransformationType; +import com.alu.e3.gateway.HeaderTransHelper; + +public class HeaderTransResponseProcessor implements Processor { + private static Logger logger = Logger.getLogger(HeaderTransResponseProcessor.class); + + @Override + public void process(Exchange exchange) throws Exception { + try{ + HeaderTransHelper.applyHeaderTransforms(HeaderTransformationType.RESPONSE, exchange); + } catch(Exception e){ + logger.error(e.getMessage(), e); + } + } +} diff --git a/exposure-engine/gateway-common/src/main/java/com/alu/e3/gateway/common/camel/processor/HttpMethodProcessor.java b/exposure-engine/gateway-common/src/main/java/com/alu/e3/gateway/common/camel/processor/HttpMethodProcessor.java new file mode 100644 index 0000000..55dcd3d --- /dev/null +++ b/exposure-engine/gateway-common/src/main/java/com/alu/e3/gateway/common/camel/processor/HttpMethodProcessor.java @@ -0,0 +1,65 @@ +/** + * Copyright © 2012 Alcatel-Lucent. + * + * See the NOTICE file distributed with this work for additional + * information regarding copyright ownership. + * Licensed to you 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 com.alu.e3.gateway.common.camel.processor; + +import java.util.ArrayList; +import java.util.List; + +import org.apache.camel.Exchange; +import org.apache.camel.Processor; +import org.springframework.beans.factory.annotation.Autowired; + +import com.alu.e3.gateway.common.camel.exception.GatewayException; +import com.alu.e3.gateway.common.camel.exception.GatewayExceptionCode; + +public class HttpMethodProcessor implements Processor { + + private List allowedHttpMethods; + + @Autowired + public void setAllowedHttpMethods(String csv){ + allowedHttpMethods = new ArrayList(); + if(csv != null){ + for(String m : csv.split(",")){ + if(m == null || m.isEmpty()) + continue; + allowedHttpMethods.add(m.toLowerCase()); + } + } + } + + @Override + public void process(Exchange exchange) throws Exception { + if(allowedHttpMethods==null || allowedHttpMethods.isEmpty()) + return; + + Object methodheader = exchange.getIn().getHeader(Exchange.HTTP_METHOD); + if(methodheader == null){ + throw new GatewayException(GatewayExceptionCode.HTTP_METHOD, "No HTTP Method"); + } + + for(String m : allowedHttpMethods){ + if(m.equals(methodheader.toString().toLowerCase())){ + return; + } + } + + throw new GatewayException(GatewayExceptionCode.HTTP_METHOD, "Method "+methodheader.toString()+" not allowed"); + } +} diff --git a/exposure-engine/gateway-common/src/main/java/com/alu/e3/gateway/common/camel/processor/LogCorrelationIDExtractor.java b/exposure-engine/gateway-common/src/main/java/com/alu/e3/gateway/common/camel/processor/LogCorrelationIDExtractor.java new file mode 100644 index 0000000..7c6de9a --- /dev/null +++ b/exposure-engine/gateway-common/src/main/java/com/alu/e3/gateway/common/camel/processor/LogCorrelationIDExtractor.java @@ -0,0 +1,38 @@ +/** + * Copyright © 2012 Alcatel-Lucent. + * + * See the NOTICE file distributed with this work for additional + * information regarding copyright ownership. + * Licensed to you 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 com.alu.e3.gateway.common.camel.processor; + +import org.apache.camel.Exchange; +import org.apache.camel.Processor; + +import com.alu.e3.common.E3Constant; +import com.alu.e3.tdr.TDRConstant; +import com.alu.e3.tdr.TDRDataService; + +public class LogCorrelationIDExtractor implements Processor { + + @Override + public void process(Exchange exchange) throws Exception { + String correlationId = exchange.getIn().getHeader(E3Constant.CORRELATION_ID_HEADER_NAME, String.class); + if (correlationId!=null) { + TDRDataService.setTxTDRProperty(TDRConstant.CORRELATION, correlationId, exchange); + exchange.getIn().removeHeader(E3Constant.CORRELATION_ID_HEADER_NAME); + } + } +} diff --git a/exposure-engine/gateway-common/src/main/java/com/alu/e3/gateway/common/camel/processor/LogCorrelationIDGenerator.java b/exposure-engine/gateway-common/src/main/java/com/alu/e3/gateway/common/camel/processor/LogCorrelationIDGenerator.java new file mode 100644 index 0000000..93c2ee2 --- /dev/null +++ b/exposure-engine/gateway-common/src/main/java/com/alu/e3/gateway/common/camel/processor/LogCorrelationIDGenerator.java @@ -0,0 +1,45 @@ +/** + * Copyright © 2012 Alcatel-Lucent. + * + * See the NOTICE file distributed with this work for additional + * information regarding copyright ownership. + * Licensed to you 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 com.alu.e3.gateway.common.camel.processor; + +import java.util.UUID; + +import org.apache.camel.Exchange; +import org.apache.camel.Processor; + +import com.alu.e3.common.E3Constant; +import com.alu.e3.tdr.TDRConstant; +import com.alu.e3.tdr.TDRDataService; + +public class LogCorrelationIDGenerator implements Processor { + @Override + public void process(Exchange exchange) throws Exception { + long LogCorrelationIDTimestamp; + if(TDRDataService.getTxTDRProperty(TDRConstant.CLIENT_REQ_TIME, exchange) != null){ + LogCorrelationIDTimestamp = (Long) TDRDataService.getTxTDRProperty(TDRConstant.CLIENT_REQ_TIME, exchange); + }else{ + LogCorrelationIDTimestamp = System.currentTimeMillis(); + } + + String correlationid = LogCorrelationIDTimestamp + "_" + UUID.randomUUID().toString(); + exchange.getIn().setHeader(E3Constant.CORRELATION_ID_HEADER_NAME, correlationid); + + TDRDataService.setTxTDRProperty(TDRConstant.CORRELATION, correlationid, exchange); + } +} diff --git a/exposure-engine/gateway-common/src/main/java/com/alu/e3/gateway/common/camel/processor/NotifyUrlHeaderProcessor.java b/exposure-engine/gateway-common/src/main/java/com/alu/e3/gateway/common/camel/processor/NotifyUrlHeaderProcessor.java new file mode 100644 index 0000000..93bdca5 --- /dev/null +++ b/exposure-engine/gateway-common/src/main/java/com/alu/e3/gateway/common/camel/processor/NotifyUrlHeaderProcessor.java @@ -0,0 +1,36 @@ +/** + * Copyright © 2012 Alcatel-Lucent. + * + * See the NOTICE file distributed with this work for additional + * information regarding copyright ownership. + * Licensed to you 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 com.alu.e3.gateway.common.camel.processor; + +import org.apache.camel.Exchange; + +import com.alu.e3.common.E3Constant; + +public class NotifyUrlHeaderProcessor extends AbstractNotifyUrlProcessor { + + @Override + public void process(Exchange exchange) throws Exception { + + String notifyUrl = exchange.getIn().getHeader(E3Constant.NOTIFY_URL_HEADER_NAME, String.class); + + injectUriAndQueryString(notifyUrl, exchange); + + } + +} diff --git a/exposure-engine/gateway-common/src/main/java/com/alu/e3/gateway/common/camel/processor/NotifyUrlWSAProcessor.java b/exposure-engine/gateway-common/src/main/java/com/alu/e3/gateway/common/camel/processor/NotifyUrlWSAProcessor.java new file mode 100644 index 0000000..3bec208 --- /dev/null +++ b/exposure-engine/gateway-common/src/main/java/com/alu/e3/gateway/common/camel/processor/NotifyUrlWSAProcessor.java @@ -0,0 +1,40 @@ +/** + * Copyright © 2012 Alcatel-Lucent. + * + * See the NOTICE file distributed with this work for additional + * information regarding copyright ownership. + * Licensed to you 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 com.alu.e3.gateway.common.camel.processor; + +import org.apache.camel.Exchange; +import org.apache.camel.builder.xml.Namespaces; +import org.apache.camel.builder.xml.XPathBuilder; + +public class NotifyUrlWSAProcessor extends AbstractNotifyUrlProcessor { + + @Override + public void process(Exchange exchange) throws Exception { + + String notifyUrl = XPathBuilder.xpath("//To", String.class).evaluate(exchange, String.class); + + if(notifyUrl.isEmpty()) { + Namespaces ns = new Namespaces("wsa", "http://www.w3.org/2005/08/addressing"); + notifyUrl = ns.xpath("//wsa:To", String.class).evaluate(exchange, String.class); + } + + injectUriAndQueryString(notifyUrl, exchange); + } + +} diff --git a/exposure-engine/gateway-common/src/main/java/com/alu/e3/gateway/common/camel/processor/PostSouthboundTDRProcessor.java b/exposure-engine/gateway-common/src/main/java/com/alu/e3/gateway/common/camel/processor/PostSouthboundTDRProcessor.java new file mode 100644 index 0000000..0a160a2 --- /dev/null +++ b/exposure-engine/gateway-common/src/main/java/com/alu/e3/gateway/common/camel/processor/PostSouthboundTDRProcessor.java @@ -0,0 +1,60 @@ +/** + * Copyright © 2012 Alcatel-Lucent. + * + * See the NOTICE file distributed with this work for additional + * information regarding copyright ownership. + * Licensed to you 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 com.alu.e3.gateway.common.camel.processor; + +import java.net.InetAddress; +import java.net.URL; + +import org.apache.camel.Exchange; +import org.apache.camel.Processor; + +import com.alu.e3.tdr.TDRConstant; +import com.alu.e3.tdr.TDRDataService; + +/** + * This processor will get run after the response from the Southbound endpoint + * + */ +public class PostSouthboundTDRProcessor implements Processor { + + @Override + public void process(Exchange exchange) throws Exception { + TDRDataService.setTxTDRProperty(TDRConstant.TARGET_RESP_TIME, System.currentTimeMillis(), exchange); + TDRDataService.setTxTDRProperty(TDRConstant.HTTP_CODE, exchange.getIn().getHeader(Exchange.HTTP_RESPONSE_CODE), exchange); + TDRDataService.setTxTDRProperty(TDRConstant.RESP_SIZE, exchange.getIn().getHeader("Content-Length", String.class), exchange); + + // TDRConstant.TARGET_URL is null only on notification route + // TDRConstant.TARGET_URL test used to not set two times value + if(TDRDataService.getTxTDRProperty(TDRConstant.TARGET_URL, exchange) == null){ + URL targetURL = new URL(exchange.getIn().getHeader(Exchange.HTTP_URI, String.class)); + TDRDataService.setTxTDRProperty(TDRConstant.TARGET_URL, targetURL.toString(), exchange); + TDRDataService.setTxTDRProperty(TDRConstant.TARGET_IP, InetAddress.getByName(targetURL.getHost()).getHostAddress(), exchange); + }else{ + URL targetURL = new URL((String) TDRDataService.getTxTDRProperty(TDRConstant.TARGET_URL, exchange)); + TDRDataService.setTxTDRProperty(TDRConstant.TARGET_IP, InetAddress.getByName(targetURL.getHost()).getHostAddress(), exchange); + } + + if(exchange.getIn().getHeader(Exchange.HTTP_RESPONSE_CODE, Integer.class) < 400){ + TDRDataService.setTxTDRProperty(TDRConstant.EVENT_TYPE, TDRConstant.EVENT_TYPE_OK, exchange); + }else{ + TDRDataService.setTxTDRProperty(TDRConstant.EVENT_TYPE, TDRConstant.EVENT_TYPE_TARGETERROR, exchange); + } + } + +} diff --git a/exposure-engine/gateway-common/src/main/java/com/alu/e3/gateway/common/camel/processor/PreSouthboundTDRProcessor.java b/exposure-engine/gateway-common/src/main/java/com/alu/e3/gateway/common/camel/processor/PreSouthboundTDRProcessor.java new file mode 100644 index 0000000..b079177 --- /dev/null +++ b/exposure-engine/gateway-common/src/main/java/com/alu/e3/gateway/common/camel/processor/PreSouthboundTDRProcessor.java @@ -0,0 +1,47 @@ +/** + * Copyright © 2012 Alcatel-Lucent. + * + * See the NOTICE file distributed with this work for additional + * information regarding copyright ownership. + * Licensed to you 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 com.alu.e3.gateway.common.camel.processor; + +import org.apache.camel.Exchange; +import org.apache.camel.Processor; + +import com.alu.e3.common.camel.ExchangeConstantKeys; +import com.alu.e3.tdr.TDRConstant; +import com.alu.e3.tdr.TDRDataService; + +/** + * This processor will be executed just before the outgoing soutbound call. + * + * + */ +public class PreSouthboundTDRProcessor implements Processor { + + @Override + public void process(Exchange exchange) throws Exception { + // Now put the TDR values into the TDRDataService whose values have been extracted and put into the header for use here. + // We don't want these headers to go all the way to the southbound endpoint so we'll remove them after extraction. + + if(exchange.getProperty(ExchangeConstantKeys.E3_SOAP_ACTION.toString()) != null){ + TDRDataService.setTxTDRProperty(TDRConstant.SOAP_ACTION, exchange.getProperty(ExchangeConstantKeys.E3_SOAP_ACTION.toString(), String.class), exchange); + } + + // This entry needs to be as close the request as possible... so it goes last here. + TDRDataService.setTxTDRProperty(TDRConstant.TARGET_REQ_TIME, System.currentTimeMillis(), exchange); + } +} diff --git a/exposure-engine/gateway-common/src/main/java/com/alu/e3/gateway/common/camel/processor/PropertyExtractionProcessor.java b/exposure-engine/gateway-common/src/main/java/com/alu/e3/gateway/common/camel/processor/PropertyExtractionProcessor.java new file mode 100644 index 0000000..ef92e63 --- /dev/null +++ b/exposure-engine/gateway-common/src/main/java/com/alu/e3/gateway/common/camel/processor/PropertyExtractionProcessor.java @@ -0,0 +1,78 @@ +/** + * Copyright © 2012 Alcatel-Lucent. + * + * See the NOTICE file distributed with this work for additional + * information regarding copyright ownership. + * Licensed to you 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 com.alu.e3.gateway.common.camel.processor; + +import java.util.HashMap; +import java.util.Iterator; +import java.util.Map; + +import org.apache.camel.Exchange; +import org.apache.camel.Processor; + +import com.alu.e3.common.camel.AuthIdentity; +import com.alu.e3.common.camel.ExchangeConstantKeys; +import com.alu.e3.data.model.CallDescriptor; +import com.alu.e3.data.model.Policy; + +/** + * This processor is meant to go through all of the applicable model to extract + * the properties for use by Header Transformations, TDRs, etc. + * + */ +public class PropertyExtractionProcessor implements Processor { + + @Override + public void process(Exchange exchange) throws Exception { + AuthIdentity identity = (AuthIdentity) exchange.getProperty(ExchangeConstantKeys.E3_AUTH_IDENTITY.toString()); + Map props = resolveProperties(identity); + + exchange.setProperty(ExchangeConstantKeys.E3_MODEL_PROPERTIES.toString(), props); + } + + /** + * Inner function to help do the work of merging all of the property maps + * By design we have decided that properties that have naming conflicts will be resolved by the following rules + * + * auth > policy > api + * conflicts between policies will be resolved in an undefined way. + * + * @param identity + * @return + */ + private Map resolveProperties(AuthIdentity identity){ + Map props = new HashMap(); + + props.putAll(identity.getApi().getProperties()); + Iterator it = identity.getCallDescriptors().iterator(); + while(it.hasNext()){ + CallDescriptor cd = it.next(); + Policy policy = cd.getPolicy(); + if(policy != null){ + props.putAll(policy.getProperties()); + } + } + + if(identity.getAuth() != null) + props.putAll(identity.getAuth().getProperties()); + + + return props; + } + +} diff --git a/exposure-engine/gateway-common/src/main/java/com/alu/e3/gateway/common/camel/processor/SubscriberIDExtractor.java b/exposure-engine/gateway-common/src/main/java/com/alu/e3/gateway/common/camel/processor/SubscriberIDExtractor.java new file mode 100644 index 0000000..516d38f --- /dev/null +++ b/exposure-engine/gateway-common/src/main/java/com/alu/e3/gateway/common/camel/processor/SubscriberIDExtractor.java @@ -0,0 +1,79 @@ +/** + * Copyright © 2012 Alcatel-Lucent. + * + * See the NOTICE file distributed with this work for additional + * information regarding copyright ownership. + * Licensed to you 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 com.alu.e3.gateway.common.camel.processor; + +import java.util.List; + +import org.apache.camel.Exchange; +import org.apache.camel.Processor; +import com.alu.e3.common.E3Constant; +import com.alu.e3.common.camel.AuthIdentity; +import com.alu.e3.common.camel.ExchangeConstantKeys; +import com.alu.e3.common.osgi.api.IDataManager; +import com.alu.e3.data.model.Api; +import com.alu.e3.data.model.Auth; + +import com.alu.e3.data.model.CallDescriptor; + +public class SubscriberIDExtractor implements Processor { + + private IDataManager dataManager; + + public void setDataManager(IDataManager dataManager) { + this.dataManager = dataManager; + } + + public SubscriberIDExtractor() {} + + @Override + public void process(Exchange exchange) throws Exception { + + String subscriberId = exchange.getIn().getHeader(E3Constant.SUBSCRIBER_ID_HEADER_NAME, String.class); + + if(subscriberId == null) + return; + + String[] parts = subscriberId.split("\\|"); + + if(parts.length != 2) + return; + + try { + // Get current AuthIdentity + AuthIdentity authIdentity = exchange.getProperty(ExchangeConstantKeys.E3_AUTH_IDENTITY.toString(), AuthIdentity.class); + + // Get subscriber matching CallDescriptors + Api api = authIdentity.getApi(); + Auth auth = dataManager.getAuthById(parts[1]); + List subscriberDescriptors = dataManager.getMatchingPolicies(api, auth); + + // Merge lists of CallDescriptors on the current AuthIdentity + List descriptors = authIdentity.getCallDescriptors(); + for(CallDescriptor c : subscriberDescriptors) { + if(!descriptors.contains(c)) { + descriptors.add(c); + } + } + } catch(Exception e) { + // Do nothing in case of errors + } + + } + +} diff --git a/exposure-engine/gateway-common/src/main/java/com/alu/e3/gateway/common/camel/processor/SubscriberIDGenerator.java b/exposure-engine/gateway-common/src/main/java/com/alu/e3/gateway/common/camel/processor/SubscriberIDGenerator.java new file mode 100644 index 0000000..2551193 --- /dev/null +++ b/exposure-engine/gateway-common/src/main/java/com/alu/e3/gateway/common/camel/processor/SubscriberIDGenerator.java @@ -0,0 +1,48 @@ +/** + * Copyright © 2012 Alcatel-Lucent. + * + * See the NOTICE file distributed with this work for additional + * information regarding copyright ownership. + * Licensed to you 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 com.alu.e3.gateway.common.camel.processor; + +import java.util.UUID; + +import org.apache.camel.Exchange; +import org.apache.camel.Processor; + +import com.alu.e3.common.E3Constant; +import com.alu.e3.common.camel.AuthIdentity; +import com.alu.e3.common.camel.ExchangeConstantKeys; + +public class SubscriberIDGenerator implements Processor { + + @Override + public void process(Exchange exchange) throws Exception { + + AuthIdentity authIdentity = exchange.getProperty(ExchangeConstantKeys.E3_AUTH_IDENTITY.toString(), AuthIdentity.class); + + String subscriberId = null; + + //TODO: Check if It's what we need as subscriberID + if (authIdentity == null || authIdentity.getAuth() == null || authIdentity.getApi() == null) + subscriberId = UUID.randomUUID().toString(); + else + // Align subscriberId format with SubscriberIdExtractor processor! + subscriberId = new StringBuilder(authIdentity.getApi().getId()).append("|").append(authIdentity.getAuth().getId()).toString(); + + exchange.getIn().setHeader(E3Constant.SUBSCRIBER_ID_HEADER_NAME, subscriberId); + } +} diff --git a/exposure-engine/gateway-common/src/main/java/com/alu/e3/gateway/common/camel/processor/TDRRequestProcessor.java b/exposure-engine/gateway-common/src/main/java/com/alu/e3/gateway/common/camel/processor/TDRRequestProcessor.java new file mode 100644 index 0000000..5e3ec0f --- /dev/null +++ b/exposure-engine/gateway-common/src/main/java/com/alu/e3/gateway/common/camel/processor/TDRRequestProcessor.java @@ -0,0 +1,57 @@ +/** + * Copyright © 2012 Alcatel-Lucent. + * + * See the NOTICE file distributed with this work for additional + * information regarding copyright ownership. + * Licensed to you 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 com.alu.e3.gateway.common.camel.processor; + +import org.apache.camel.Exchange; +import org.apache.camel.Processor; +import org.apache.log4j.Logger; + +import com.alu.e3.common.camel.ExchangeConstantKeys; +import com.alu.e3.data.model.ExtractFromType; +import com.alu.e3.gateway.TdrProcessorHelper; + +/** + * This processor is meant to do the work of pulling the Provisioned TDR values + * out of the data model and inserting them into the TDR emission structure. + * + * + */ +public class TDRRequestProcessor implements Processor { + private static Logger logger = Logger.getLogger(TDRResponseProcessor.class); + + // The key to our Exchange property that indicates whether this has already been run. + // We only want to run it once and it could run twice if there is an error on the route. + private static String TDR_REQ_PROC_RUN_KEY = "TDR_REQ_PROC_RUN"; + + @Override + public void process(Exchange exchange) throws Exception { + try{ + Boolean alreadyRan = exchange.getProperty(TDR_REQ_PROC_RUN_KEY, Boolean.FALSE, Boolean.class); + Boolean isResponse = exchange.getProperty(ExchangeConstantKeys.E3_GOT_SB_RESPONSE.toString(), Boolean.FALSE, Boolean.class); + + if(!alreadyRan && !isResponse){ + TdrProcessorHelper.processTdrRules(exchange, ExtractFromType.Request, false); + exchange.setProperty(TDR_REQ_PROC_RUN_KEY, Boolean.TRUE); + } + } catch(Exception e){ + logger.error(e.getMessage(), e); + } + + } +} diff --git a/exposure-engine/gateway-common/src/main/java/com/alu/e3/gateway/common/camel/processor/TDRResponseProcessor.java b/exposure-engine/gateway-common/src/main/java/com/alu/e3/gateway/common/camel/processor/TDRResponseProcessor.java new file mode 100644 index 0000000..d4f33d6 --- /dev/null +++ b/exposure-engine/gateway-common/src/main/java/com/alu/e3/gateway/common/camel/processor/TDRResponseProcessor.java @@ -0,0 +1,57 @@ +/** + * Copyright © 2012 Alcatel-Lucent. + * + * See the NOTICE file distributed with this work for additional + * information regarding copyright ownership. + * Licensed to you 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 com.alu.e3.gateway.common.camel.processor; + +import org.apache.camel.Exchange; +import org.apache.camel.Processor; +import org.apache.log4j.Logger; + +import com.alu.e3.common.camel.ExchangeConstantKeys; +import com.alu.e3.data.model.ExtractFromType; +import com.alu.e3.gateway.TdrProcessorHelper; + +/** + * This processor is meant to do the work of pulling the Provisioned TDR values + * out of the data model and inserting them into the TDR emission structure. + * + * + */ +public class TDRResponseProcessor implements Processor { + private static Logger logger = Logger.getLogger(TDRResponseProcessor.class); + + // The key to our Exchange property that indicates whether this has already been run. + // We only want to run it once and it could run twice if there is an error on the route. + private static String TDR_RES_PROC_RUN_KEY = "TDR_RES_PROC_RUN"; + + @Override + public void process(Exchange exchange) throws Exception { + try{ + Boolean alreadyRan = exchange.getProperty(TDR_RES_PROC_RUN_KEY, Boolean.FALSE, Boolean.class); + Boolean isResponse = exchange.getProperty(ExchangeConstantKeys.E3_GOT_SB_RESPONSE.toString(), Boolean.FALSE, Boolean.class); + + if(!alreadyRan && isResponse){ + TdrProcessorHelper.processTdrRules(exchange, ExtractFromType.Response, false); + exchange.setProperty(TDR_RES_PROC_RUN_KEY, Boolean.TRUE); + } + } catch(Exception e){ + logger.error(e.getMessage(), e); + } + + } +} diff --git a/exposure-engine/gateway-common/src/main/java/com/alu/e3/gateway/common/camel/processor/TDRStaticProcessor.java b/exposure-engine/gateway-common/src/main/java/com/alu/e3/gateway/common/camel/processor/TDRStaticProcessor.java new file mode 100644 index 0000000..c059fef --- /dev/null +++ b/exposure-engine/gateway-common/src/main/java/com/alu/e3/gateway/common/camel/processor/TDRStaticProcessor.java @@ -0,0 +1,46 @@ +/** + * Copyright © 2012 Alcatel-Lucent. + * + * See the NOTICE file distributed with this work for additional + * information regarding copyright ownership. + * Licensed to you 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 com.alu.e3.gateway.common.camel.processor; + +import org.apache.camel.Exchange; +import org.apache.camel.Processor; +import org.apache.log4j.Logger; + +import com.alu.e3.gateway.TdrProcessorHelper; + +/** + * This processor is meant to do the work of pulling the Provisioned TDR values + * out of the data model and inserting them into the TDR emission structure. + * + * + */ +public class TDRStaticProcessor implements Processor { + private static Logger logger = Logger.getLogger(TDRResponseProcessor.class); + + @Override + public void process(Exchange exchange) throws Exception { + try{ + // Processes all of the static rules + TdrProcessorHelper.processTdrRules(exchange, null, true); + } catch(Exception e){ + logger.error(e.getMessage(), e); + } + + } +} diff --git a/exposure-engine/gateway-common/src/main/java/com/alu/e3/gateway/config/certshuffle/CrlListener.java b/exposure-engine/gateway-common/src/main/java/com/alu/e3/gateway/config/certshuffle/CrlListener.java new file mode 100644 index 0000000..ea855bd --- /dev/null +++ b/exposure-engine/gateway-common/src/main/java/com/alu/e3/gateway/config/certshuffle/CrlListener.java @@ -0,0 +1,89 @@ +/** + * Copyright © 2012 Alcatel-Lucent. + * + * See the NOTICE file distributed with this work for additional + * information regarding copyright ownership. + * Licensed to you 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 com.alu.e3.gateway.config.certshuffle; + +import java.io.ByteArrayInputStream; +import java.security.cert.CRL; +import java.security.cert.CertificateFactory; + +import org.slf4j.Logger; +import org.slf4j.LoggerFactory; + +import com.alu.e3.common.caching.IEntryListener; +import com.alu.e3.common.osgi.api.IDataManager; +import com.alu.e3.data.DataEntryEvent; +import com.alu.e3.data.IDataManagerListener; +import com.alu.e3.data.model.SSLCRL; +import com.alu.e3.gateway.security.E3TrustManager; + +public class CrlListener implements IEntryListener, IDataManagerListener{ + + private static Logger LOG = LoggerFactory.getLogger(CrlListener.class); + + private IDataManager dataManager; + + public void setDataManager(IDataManager dm) { + this.dataManager = dm; + } + + public void init() { + dataManager.addListener(this); + } + + public void destroy() { + dataManager.removeListener(this); + } + + @Override + public void dataManagerReady() { + this.dataManager.addCrlListener(this); + } + + private void addCRL(String id, SSLCRL sslCRL) { + CRL crl; + + try { + crl = CertificateFactory.getInstance("X.509").generateCRL(new ByteArrayInputStream(sslCRL.getContent().getBytes())); + E3TrustManager.addCRL(id, crl); + } + catch (Exception e) { + LOG.error("Unable to add CRL " + id, e); + } + } + + @Override + public void entryAdded(DataEntryEvent event) { + addCRL(event.getKey(), event.getValue()); + } + + @Override + public void entryUpdated(DataEntryEvent event) { + addCRL(event.getKey(), event.getValue()); + } + + @Override + public void entryRemoved(DataEntryEvent event) { + try { + E3TrustManager.removeCRL(event.getKey()); + } catch (Exception e) { + LOG.error("Unable to remove CRL " + event.getKey(), e); + } + } +} + diff --git a/exposure-engine/gateway-common/src/main/java/com/alu/e3/gateway/config/certshuffle/KeyListener.java b/exposure-engine/gateway-common/src/main/java/com/alu/e3/gateway/config/certshuffle/KeyListener.java new file mode 100644 index 0000000..a521735 --- /dev/null +++ b/exposure-engine/gateway-common/src/main/java/com/alu/e3/gateway/config/certshuffle/KeyListener.java @@ -0,0 +1,246 @@ +/** + * Copyright © 2012 Alcatel-Lucent. + * + * See the NOTICE file distributed with this work for additional + * information regarding copyright ownership. + * Licensed to you 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 com.alu.e3.gateway.config.certshuffle; + +import java.io.IOException; +import java.io.StringReader; +import java.security.KeyPair; +import java.security.KeyStore; +import java.security.KeyStoreException; +import java.security.PrivateKey; +import java.util.Arrays; + +import org.bouncycastle.openssl.PEMReader; +import org.bouncycastle.openssl.PasswordFinder; +import org.slf4j.Logger; +import org.slf4j.LoggerFactory; + +import com.alu.e3.common.InvalidIDException; +import com.alu.e3.common.caching.IEntryListener; +import com.alu.e3.common.osgi.api.IDataManager; +import com.alu.e3.common.osgi.api.IKeyStoreService; +import com.alu.e3.data.CacheAck; +import com.alu.e3.data.DataEntryEvent; +import com.alu.e3.data.IDataManagerListener; +import com.alu.e3.data.model.Certificate; +import com.alu.e3.data.model.Key; + +public class KeyListener implements IEntryListener, IDataManagerListener{ + + private static Logger LOG = LoggerFactory.getLogger(KeyListener.class); + + private IDataManager dataManager = null; + private IKeyStoreService keyStoreService = null; + private String keyStoreKeyPassword; + + /* + * Jetty and/or camel-jetty do not use key aliases! + * They simply use the first key they find in the keystore. + * So make jetty's key come up first + */ + private static String ALIAS = "1"; + + public void init() { + dataManager.addListener(this); + } + + public void destroy() { + dataManager.removeListener(this); + } + + public IDataManager getDataManager(){ + return this.dataManager; + } + + public void setDataManager(IDataManager dm){ + this.dataManager = dm; + } + + @Override + public void dataManagerReady() { + this.dataManager.addKeyListener(this); + } + + public void setKeyStoreService(IKeyStoreService kss){ + this.keyStoreService = kss; + } + + @Override + public void entryAdded(DataEntryEvent event) { + doKeyStoreUpdate(event); + } + + @Override + public void entryUpdated(DataEntryEvent event) { + doKeyStoreUpdate(event); + } + + + @Override + public void entryRemoved(DataEntryEvent event) { + + synchronized(keyStoreService) { + + CacheAck ack = CacheAck.KO; + + KeyStore ks = keyStoreService.loadKeyStore(); + + if(ks == null){ + LOG.error("Null keystore"); + } + else { + try { + if(ks.containsAlias(ALIAS)) { + ks.deleteEntry(ALIAS); + } + + keyStoreService.saveKeyStore(ks); + + ack = CacheAck.OK; + } + catch (KeyStoreException e) { + LOG.error("Error while removing the key", e); + } + } + + try { + dataManager.postAcknowledgment(event.getValue().getId(), ack); + } + catch (InterruptedException e) { + LOG.error("Error while posting acknowledgment " + event.getKey(), e); + } + } + } + + private void postAcknowledgment(String queueName, CacheAck ack) { + try { + dataManager.postAcknowledgment(queueName, ack); + } + catch (InterruptedException e) { + LOG.error("Error while posting acknowledgment", e); + } + } + + private void doKeyStoreUpdate(DataEntryEvent event) { + final Key key = event.getValue(); + Certificate cert = null; + if(key.getActiveCertId() != null && key.getActiveCertId().length() > 0) { + try { + cert = dataManager.getCertById(key.getActiveCertId()); + } + catch (InvalidIDException e) { + LOG.error("Certificate not found "+key.getActiveCertId(), e); + postAcknowledgment(key.getId(), CacheAck.KO); + return; + } + } + + if(cert == null){ + // A key has been uploaded without a certificate. Don't add it to the keystore. + // This is a standard use-case. Don't error. + postAcknowledgment(key.getId(), CacheAck.OK); + return; + } + + PrivateKey jkey = null; + java.security.cert.Certificate jcert = null; + + try { + + PasswordFinder passwordFinder = null; + + if (key.getKeyPassphrase() != null) { + passwordFinder = new PasswordFinder() { + + @Override + public char[] getPassword() { + return key.getKeyPassphrase().toCharArray(); + } + }; + } + + PEMReader pemr = new PEMReader(new StringReader(key.getData()), passwordFinder); + Object pemobj = pemr.readObject(); + if(pemobj instanceof KeyPair){ + jkey = ((KeyPair)pemobj).getPrivate(); + } else if (pemobj instanceof PrivateKey){ + jkey = (PrivateKey)pemobj; + } else { + LOG.error("The PEM object in Key "+key.getId()+" is not a Private Key"); + postAcknowledgment(key.getId(), CacheAck.KO); + return; + } + } catch(IOException e){ + LOG.error("Failed to read Key "+key.getId()+" data.", e); + postAcknowledgment(key.getId(), CacheAck.KO); + return; + } + + try{ + PEMReader pemr = new PEMReader(new StringReader(cert.getData())); + Object pemobj = pemr.readObject(); + if(pemobj instanceof java.security.cert.Certificate){ + jcert = (java.security.cert.Certificate)pemobj; + } else { + LOG.error("The PEM object in Certificate "+cert.getId()+" is not a Certificate"); + postAcknowledgment(key.getId(), CacheAck.KO); + return; + } + } catch(IOException e){ + LOG.error("Failed to read Certificate "+cert.getId()+" data.", e); + postAcknowledgment(key.getId(), CacheAck.KO); + return; + } + + synchronized(keyStoreService) { + + CacheAck ack = CacheAck.KO; + + KeyStore ks = keyStoreService.loadKeyStore(); + + if(ks == null) { + LOG.error("KeyStoreService did not give me my keystore!"); + postAcknowledgment(key.getId(), CacheAck.KO); + return; + } + + try { + if(ks.containsAlias(ALIAS)) { + ks.deleteEntry(ALIAS); + } + + ks.setKeyEntry(ALIAS, jkey, keyStoreKeyPassword.toCharArray(), (java.security.cert.Certificate[]) Arrays.asList(jcert).toArray()); + + keyStoreService.saveKeyStore(ks); + + ack = CacheAck.OK; + + } + catch (KeyStoreException e) { + LOG.error("Key not updated", e); + } + + postAcknowledgment(key.getId(), ack); + } + } + + public void setKeyStoreKeyPassword(String keyStoreKeyPassword) { + this.keyStoreKeyPassword = keyStoreKeyPassword; + } +} diff --git a/exposure-engine/gateway-common/src/main/java/com/alu/e3/gateway/config/certshuffle/TrustStoreListener.java b/exposure-engine/gateway-common/src/main/java/com/alu/e3/gateway/config/certshuffle/TrustStoreListener.java new file mode 100644 index 0000000..93e9e53 --- /dev/null +++ b/exposure-engine/gateway-common/src/main/java/com/alu/e3/gateway/config/certshuffle/TrustStoreListener.java @@ -0,0 +1,130 @@ +/** + * Copyright © 2012 Alcatel-Lucent. + * + * See the NOTICE file distributed with this work for additional + * information regarding copyright ownership. + * Licensed to you 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 com.alu.e3.gateway.config.certshuffle; + +import java.io.StringReader; +import java.security.KeyStore; +import java.security.cert.Certificate; + +import org.bouncycastle.openssl.PEMReader; +import org.slf4j.Logger; +import org.slf4j.LoggerFactory; + +import com.alu.e3.common.caching.IEntryListener; +import com.alu.e3.common.osgi.api.IDataManager; +import com.alu.e3.common.osgi.api.ITrustStoreService; +import com.alu.e3.data.CacheAck; +import com.alu.e3.data.DataEntryEvent; +import com.alu.e3.data.IDataManagerListener; + +public class TrustStoreListener implements IEntryListener, IDataManagerListener { + + private static Logger LOG = LoggerFactory.getLogger(TrustStoreListener.class); + + private ITrustStoreService trustStoreService = null; + private IDataManager dataManager; + + public void setTrustStoreService(ITrustStoreService trustStoreService) { + this.trustStoreService = trustStoreService; + } + + public void setDataManager(IDataManager dataManager) { + this.dataManager = dataManager; + } + + public void init() { + dataManager.addListener(this); + } + + public void destroy() { + dataManager.removeListener(this); + } + + @Override + public void dataManagerReady() { + dataManager.addCAListener(this); + } + + private void addCertificate(String alias, com.alu.e3.data.model.Certificate model) { + Certificate cert; + + CacheAck ack = CacheAck.KO; + + try { + PEMReader pemr = new PEMReader(new StringReader(model.getData())); + cert = (Certificate)pemr.readObject(); + + KeyStore ks = trustStoreService.loadTrustStore(); + ks.setCertificateEntry(alias, cert); + trustStoreService.saveTrustStore(ks); + + ack = CacheAck.OK; + } + catch (Exception e) { + LOG.error("Error while storing the certificate " + alias, e); + } + finally { + try { + dataManager.postAcknowledgment(model.getId(), ack); + } + catch (InterruptedException e) { + LOG.error("Error while posting acknowledgment " + alias, e); + } + } + } + + private void removeCertificate(String alias, com.alu.e3.data.model.Certificate model) { + + CacheAck ack = CacheAck.KO; + + try { + KeyStore ks = trustStoreService.loadTrustStore(); + ks.deleteEntry(alias); + trustStoreService.saveTrustStore(ks); + + ack = CacheAck.OK; + } + catch (Exception e) { + LOG.error("Error while deleting the certificate " + alias, e); + } + finally { + try { + dataManager.postAcknowledgment(model.getId(), ack); + } + catch (InterruptedException e) { + LOG.error("Error while posting acknowledgment " + alias, e); + } + } + } + + @Override + public void entryAdded(DataEntryEvent event) { + addCertificate(event.getKey(), event.getValue()); + } + + @Override + public void entryUpdated(DataEntryEvent event) { + addCertificate(event.getKey(), event.getValue()); + } + + @Override + public void entryRemoved(DataEntryEvent event) { + removeCertificate(event.getKey(), event.getValue()); + } +} diff --git a/exposure-engine/gateway-common/src/main/java/com/alu/e3/gateway/loadbalancer/HttpLoadBalancerProcessor.java b/exposure-engine/gateway-common/src/main/java/com/alu/e3/gateway/loadbalancer/HttpLoadBalancerProcessor.java new file mode 100644 index 0000000..d8967f6 --- /dev/null +++ b/exposure-engine/gateway-common/src/main/java/com/alu/e3/gateway/loadbalancer/HttpLoadBalancerProcessor.java @@ -0,0 +1,335 @@ +/** + * Copyright © 2012 Alcatel-Lucent. + * + * See the NOTICE file distributed with this work for additional + * information regarding copyright ownership. + * Licensed to you 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 com.alu.e3.gateway.loadbalancer; + +import java.net.URI; +import java.util.List; +import java.util.Map; +import java.util.concurrent.locks.ReentrantLock; + +import org.apache.camel.CamelContext; +import org.apache.camel.Exchange; +import org.apache.camel.Processor; +import org.apache.camel.component.http4.HttpComponent; +import org.apache.camel.component.http4.HttpEndpoint; +import org.apache.camel.component.http4.HttpProducer; +import org.apache.http.conn.ClientConnectionManager; +import org.apache.http.impl.client.DefaultHttpClient; +import org.apache.http.impl.conn.tsccm.ThreadSafeClientConnManager; +import org.slf4j.Logger; +import org.slf4j.LoggerFactory; +import org.springframework.osgi.service.importer.OsgiServiceLifecycleListener; + +import com.alu.e3.common.osgi.api.ITopologyClient; +import com.alu.e3.data.model.sub.ConnectionParameters; +import com.alu.e3.data.model.sub.TargetHost; +import com.alu.e3.gateway.common.camel.exception.GatewayException; +import com.alu.e3.gateway.common.camel.exception.GatewayExceptionCode; + +public class HttpLoadBalancerProcessor implements Processor, OsgiServiceLifecycleListener { + + private static final Logger LOGGER = LoggerFactory.getLogger(HttpLoadBalancerProcessor.class); + + HttpEndpoint httpEndpoint; + + private String area; + private boolean failedOver; + private int failedOverErrorCode; + private ITargetHostManager targetHostManager; + private String apiId; + private String contextId; + + private boolean isProvisioned; + + private int maxTotalConnection; + private static final int DEFAULT_CONNECTIONS_PER_ROUTE = 400; + private static final int DEFAULT_MAX_CONNECTIONS = 2000; + + private ReentrantLock lbProvisioningLock; + private ReentrantLock endpointLock; + + // Primary: load balance only on targets of the same site + private RoundrobinLoadBalancer primaryLoadBalancer; + + // Alternative: load balance on targets of different sites or without site + private RoundrobinLoadBalancer alternativeLoadBalancer; + + private final static String AREA_UNKNOWN = "unknown"; + private final static String AREA_ALTERNATIVE = "external"; + + public HttpLoadBalancerProcessor() { + this.area = AREA_UNKNOWN; + this.isProvisioned = false; + lbProvisioningLock = new ReentrantLock(); + endpointLock = new ReentrantLock(); + } + + public void setApiId(String apiId) { + this.apiId = apiId; + } + + public void setContextId(String contextId) { + this.contextId = contextId; + } + + public void setTopologyClient(ITopologyClient topologyClient) { + area = topologyClient.getMyArea(); + } + + public void setTargetHostManager(ITargetHostManager targetHostManager) { + this.targetHostManager = targetHostManager; + } + + public void setFailedOver(boolean failedOver) { + this.failedOver = failedOver; + } + + public void setFailedOverErrorCode(int failedOverErrorCode) { + this.failedOverErrorCode = failedOverErrorCode; + } + + public RoundrobinLoadBalancer getPrimaryLoadBalancer() { + if(primaryLoadBalancer == null) { + LOGGER.debug("Adding new primary load balancer for area '" +area+ "' failover '" +failedOver+ "' and fail over code '" +failedOverErrorCode+ "'"); + primaryLoadBalancer = new RoundrobinLoadBalancer(area, failedOver, failedOverErrorCode, targetHostManager); + } + + return primaryLoadBalancer; + } + + + public RoundrobinLoadBalancer getAlternativeLoadBalancer() { + if(alternativeLoadBalancer == null) { + LOGGER.debug("Adding new alternative load balancer for area '" +AREA_ALTERNATIVE+ "' failover '" +failedOver+ "' and fail over code '" +failedOverErrorCode+ "'"); + alternativeLoadBalancer = new RoundrobinLoadBalancer(AREA_ALTERNATIVE, failedOver, failedOverErrorCode, targetHostManager); + } + + return alternativeLoadBalancer; + } + + @Override + public void process(Exchange exchange) throws Exception { + + boolean success = false; + + // Provision load balancer with the list of targets + provisionLoadBalancer(); + + // Initialize endpoint + createHttpEndpoint(exchange); + + // First, try with primary targets if we have some + if(this.primaryLoadBalancer != null) { + LOGGER.debug("Processing load balancing on primary load balancer with apiId {}", apiId); + success = this.primaryLoadBalancer.process(exchange); + } + + // Now try on alternative targets + if(!success && this.alternativeLoadBalancer != null) { + LOGGER.debug("Processing load balancing on alternate load balancer with apiId {}", apiId); + success = this.alternativeLoadBalancer.process(exchange); + } + + if(!success) { + GatewayException exception = new GatewayException(GatewayExceptionCode.LOAD_BALANCER, "Issue to call the target host"); + throw exception; + } + } + + private void createHttpEndpoint(Exchange exchange) throws Exception { + if(httpEndpoint == null) { + + LOGGER.debug(">>>>>>>>>>>>> Creating HTTP Endpoint"); + + initHttpEndpoint(exchange); + + LOGGER.debug("Creating new HTTP producer"); + HttpProducer httpProducer = (HttpProducer) httpEndpoint.createProducer(); + + setDefaultHttpConnectionParams(httpProducer); + + if(this.primaryLoadBalancer != null) { + LOGGER.debug("Setting HTTP producer on primary load balancer"); + this.primaryLoadBalancer.setHttpProducer(httpProducer); + } + if(alternativeLoadBalancer != null) { + LOGGER.debug("Setting HTTP producer on alternate load balancer"); + this.alternativeLoadBalancer.setHttpProducer(httpProducer); + } + + } + } + + void initHttpEndpoint(Exchange exchange) throws Exception { + endpointLock.lock(); + try { + if(httpEndpoint == null) { + LOGGER.debug("Initializing a new HttpEndpoint ..."); + CamelContext context = exchange.getContext(); + HttpComponent httpComponent = context.getComponent("http4", HttpComponent.class); + + if(maxTotalConnection < 1) { + LOGGER.warn("Unable to determine the number of HTTP connections needed to support the API {}", apiId); + maxTotalConnection = DEFAULT_MAX_CONNECTIONS; + LOGGER.warn("The default number of HTTP connections to support the API {} is set to {}", apiId, maxTotalConnection); + } + + /* + String endpointParameters = "?throwExceptionOnFailure=false&maxTotalConnections=" + maxTotalConnection + "&connectionsPerRoute=" + + DEFAULT_CONNECTIONS_PER_ROUTE + + "&httpClient.handleRedirects=false"; + + String uriHttpEndpoint = "http4://host" + endpointParameters; + */ + + String endpointParameters = "?throwExceptionOnFailure=false&httpClient.handleRedirects=false"; + String uriHttpEndpoint = "http4://host" + endpointParameters; + + LOGGER.debug("Init the HTTP EndPoint for API {} with [{}]", apiId, uriHttpEndpoint); + + httpEndpoint = (HttpEndpoint) httpComponent.createEndpoint(uriHttpEndpoint); + // remove the parameters from the target URI + httpEndpoint.setHttpUri(new URI("http4://host")); + } else { + LOGGER.debug("HTTP endpoint already referenced); doing nothing"); + } + } finally { + endpointLock.unlock(); + } + + } + + /** + * Provisions the LoadBalancer with TargetHosts returned by TargethostManager. + */ + protected void provisionLoadBalancer() { + + if(!isProvisioned) { + // Locking... + lbProvisioningLock.lock(); + + try { + + if(!isProvisioned) { + + if(apiId != null) { + LOGGER.debug("Initialiazing LoadBalancer for API {} / Context {}", apiId, contextId); + + // Get the list of TargetReference for this ApiContext + List targets = targetHostManager.getTargetReferences(apiId, contextId); + if(targets != null) { + LOGGER.debug("Got {} references from TargetTostManager", targets.size()); + + if(targets.size() > 0) { + // Dispatching targets on load balancers depending on their site + for(TargetReference target : targets) { + + computeMaxTotalConnection(target); + + // ManagedTargethost is on same site has gateway's site, adding target to primaryLoadBalancer + if(target.getTargetHost().getSite() != null && target.getTargetHost().getSite().equals(area)) { + getPrimaryLoadBalancer().addTargetHostReference(target); + LOGGER.debug("Added TargetTost {} to primary LB", target.getReference()); + + // ManagedTargethost is on a different site than the gateway (or has no site), adding target to alternativeLoadBalancer + } else { + getAlternativeLoadBalancer().addTargetHostReference(target); + LOGGER.debug("Added TargetTost {} to alternative LB", target.getReference()); + } + } + isProvisioned = true; + } else { + LOGGER.error("Recovered empty target endpoint list for API {} / Context {}", apiId, contextId); + } + } else { + LOGGER.warn("Returned null for API {} / Context {}", apiId, contextId); + } // End of Targets != null + + } else { + LOGGER.error("ApiId is null on provisionLoadBalancer"); + + } // End of apiId != null + + } // End of !isProvisioned + else { + LOGGER.debug("Load balancer already provisionned for api {}", apiId); + } + } finally { + // Unlocking + lbProvisioningLock.unlock(); + } + } + + } + + + private void computeMaxTotalConnection(TargetReference targetReference) { + + Integer connectionsPerRoute = DEFAULT_CONNECTIONS_PER_ROUTE; + + TargetHost targetHost = targetReference.getTargetHost(); + ConnectionParameters connectionParameters = targetHost.getConnectionParameters(); + + if(connectionParameters != null) { + Integer connectionsPerRouteFound = connectionParameters.getMaxConnections(); + + if(connectionsPerRouteFound != null) { + connectionsPerRoute = connectionsPerRouteFound; + } else { + LOGGER.debug("No HTTP connectionsPerRoute for the target host {}", targetReference.getTargetHost().getUrl()); + LOGGER.debug("Set the default HTTP connectionsPerRoute for the target host {}", targetReference.getTargetHost().getUrl()); + } + + } else { + LOGGER.debug("No HTTP connectinoParameters for the target host {}", targetReference.getTargetHost().getUrl()); + } + + maxTotalConnection = maxTotalConnection + connectionsPerRoute; + + LOGGER.debug("The HTTP connectionsPerRoute is {} for the target host {}", connectionsPerRoute, targetReference.getTargetHost().getUrl()); + LOGGER.debug("Remaning maxTotalConnection is {} for API {}", maxTotalConnection, apiId); + } + + @Override + public void bind(Object service, Map properties) throws Exception { + // Nothing to do on bind service + } + + /** + * Call on osgi sslJetty component gone. + */ + @Override + public void unbind(Object service, Map properties) throws Exception { + LOGGER.debug("Cleaning HttpEndpoint ..."); + httpEndpoint=null; + } + + private void setDefaultHttpConnectionParams(HttpProducer httpProducer) { + + DefaultHttpClient client = (DefaultHttpClient) httpProducer.getHttpClient(); + + ClientConnectionManager ccm = client.getConnectionManager(); + if(ccm instanceof ThreadSafeClientConnManager){ + ThreadSafeClientConnManager tsccm = (ThreadSafeClientConnManager) ccm; + tsccm.setDefaultMaxPerRoute(DEFAULT_CONNECTIONS_PER_ROUTE); + tsccm.setMaxTotal(this.maxTotalConnection); + } + + } +} diff --git a/exposure-engine/gateway-common/src/main/java/com/alu/e3/gateway/loadbalancer/ITargetHostManager.java b/exposure-engine/gateway-common/src/main/java/com/alu/e3/gateway/loadbalancer/ITargetHostManager.java new file mode 100644 index 0000000..04e3afd --- /dev/null +++ b/exposure-engine/gateway-common/src/main/java/com/alu/e3/gateway/loadbalancer/ITargetHostManager.java @@ -0,0 +1,58 @@ +/** + * Copyright © 2012 Alcatel-Lucent. + * + * See the NOTICE file distributed with this work for additional + * information regarding copyright ownership. + * Licensed to you 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 com.alu.e3.gateway.loadbalancer; + +import java.util.List; + +/** + * Interface of TargetHostManager. + * + * A TargetHostManager acts as ManagedTargetHost Database and is used to maintain status of TargetHosts. + * HttpLoadBalancer interacts with a TargetHostManager to get all Targets on which it must loadbalance requests for a given API. + * + */ +public interface ITargetHostManager { + + /** + * Returns a list of TargetReferences for this pair ApiId/ApiContextId + * @param apiId The Api ID + * @param contextId The Api Context Id + * @return The list of TargetReferences for this pair ApiId/ApiContextId + */ + List getTargetReferences(String apiId, String contextId); + + /** + * Returns if a Target is AVAILABLE + * @param targetReference The reference string of the Target to check for + * @return true if the target is AVAILABLE, false otherwise + */ + boolean isAvailable(String targetReference); + + /** + * Mark a Target as UNAVAILABLE. + * Call this method when sending a request to this target failed. + * + * @param targetReference The reference string of the Target to mark as unavailable + */ + void notifyFailed(String targetReference); + +} diff --git a/exposure-engine/gateway-common/src/main/java/com/alu/e3/gateway/loadbalancer/LoadBalancerDisplay.java b/exposure-engine/gateway-common/src/main/java/com/alu/e3/gateway/loadbalancer/LoadBalancerDisplay.java new file mode 100644 index 0000000..6d8d3b6 --- /dev/null +++ b/exposure-engine/gateway-common/src/main/java/com/alu/e3/gateway/loadbalancer/LoadBalancerDisplay.java @@ -0,0 +1,112 @@ +/** + * Copyright © 2012 Alcatel-Lucent. + * + * See the NOTICE file distributed with this work for additional + * information regarding copyright ownership. + * Licensed to you 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 com.alu.e3.gateway.loadbalancer; + +import java.util.Map; + +import org.apache.camel.Exchange; +import org.slf4j.Logger; + +public class LoadBalancerDisplay { + + public static void logDebug(Logger logger, String name, String message) { + if(logger.isDebugEnabled()) { + logger.debug(name + " - " + message); + } + } + + public static void logError(Logger logger, String name, String message, Exception e) { + if(logger.isErrorEnabled()) { + logger.error(name + " - " + message, e); + } + + } + + public static void logError(Logger logger, String name, String message) { + if(logger.isErrorEnabled()) { + logger.error(name + " - " + message); + } + } + + public static void logWarn(Logger logger, String name, String message) { + if(logger.isWarnEnabled()) { + logger.error(name + " - " + message); + } + + } + + public static void displayExchange(Logger logger, String name, Exchange exchange, String label) { + logDebug(logger, name, ">>>>>>>>>>>>> "+ label); + logDebug(logger, name, "Exchange ID = " + exchange.getExchangeId()); + logDebug(logger, name, "-------------"); + logDebug(logger, name, "Properties = " + getMapAsString(exchange.getProperties())); + logDebug(logger, name, "IN Header = " + getMapAsString(exchange.getIn().getHeaders())); + logDebug(logger, name, "IN Body = " + getObjectAsString(exchange.getIn().getBody())); + logDebug(logger, name, "OUT Header = " + getMapAsString(exchange.getOut().getHeaders())); + logDebug(logger, name, "OUT Body = " + getObjectAsString(exchange.getOut().getBody())); + logDebug(logger, name, "============="); +} + + + public static void displayConfig(Logger logger, String name, int maxAttemptsExceeded, boolean failedOver, int failedOverErrorCode, int numberOfReferences) { + + logDebug(logger, name, "============= CONFIG ============="); + logDebug(logger, name, "Max Attempts = " + maxAttemptsExceeded); + logDebug(logger, name, "Failover = " + failedOver); + logDebug(logger, name, "Failover Error Code = " + failedOverErrorCode); + logDebug(logger, name, "Number of Target Host = " + numberOfReferences); + logDebug(logger, name, "==================================="); + } + + private static String getObjectAsString(Object object) { + + String objectAsString = null; + + if(object != null) { + try { + objectAsString = (String) object; + } catch(ClassCastException e) { + objectAsString = object.toString(); + } + } else { + objectAsString = ""; + } + + return objectAsString; + + } + + private static String getMapAsString(Map map) { + + String mapAsString = null; + StringBuffer buffer = new StringBuffer(); + + for(Map.Entry entry : map.entrySet()) { + buffer.append(entry.getKey() + "=" + entry.getValue() + "&"); + } + + mapAsString = buffer.toString(); + + if(mapAsString.endsWith("&")) { + mapAsString = mapAsString.substring(0,mapAsString.length()-1); + } + + return mapAsString; + } +} diff --git a/exposure-engine/gateway-common/src/main/java/com/alu/e3/gateway/loadbalancer/LoadBalancerException.java b/exposure-engine/gateway-common/src/main/java/com/alu/e3/gateway/loadbalancer/LoadBalancerException.java new file mode 100644 index 0000000..9fdd6ce --- /dev/null +++ b/exposure-engine/gateway-common/src/main/java/com/alu/e3/gateway/loadbalancer/LoadBalancerException.java @@ -0,0 +1,42 @@ +/** + * Copyright © 2012 Alcatel-Lucent. + * + * See the NOTICE file distributed with this work for additional + * information regarding copyright ownership. + * Licensed to you 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 com.alu.e3.gateway.loadbalancer; + +public class LoadBalancerException extends Exception { + + /** + * Generated serial version UID + */ + private static final long serialVersionUID = -7715348806686472292L; + + + public LoadBalancerException() { + super(); + } + + + public LoadBalancerException(String message, Throwable cause) { + super(message, cause); + } + + + public LoadBalancerException(String message) { + super(message); + } +} diff --git a/exposure-engine/gateway-common/src/main/java/com/alu/e3/gateway/loadbalancer/ManagedTargetHost.java b/exposure-engine/gateway-common/src/main/java/com/alu/e3/gateway/loadbalancer/ManagedTargetHost.java new file mode 100644 index 0000000..dace58f --- /dev/null +++ b/exposure-engine/gateway-common/src/main/java/com/alu/e3/gateway/loadbalancer/ManagedTargetHost.java @@ -0,0 +1,199 @@ +/** + * Copyright © 2012 Alcatel-Lucent. + * + * See the NOTICE file distributed with this work for additional + * information regarding copyright ownership. + * Licensed to you 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 com.alu.e3.gateway.loadbalancer; + +import java.net.MalformedURLException; +import java.net.URL; + +import java.util.UUID; +import java.util.concurrent.atomic.AtomicInteger; + +import org.slf4j.Logger; +import org.slf4j.LoggerFactory; + +import com.alu.e3.data.model.sub.TargetHost; +import com.alu.e3.gateway.loadbalancer.TargetHostManager.TargetStatus; +import com.alu.e3.gateway.targethealthcheck.ITargetHealthCheckService; + +/** + * Wraps a TargetHost (from E3's DataModel) with additional data used by LoadBalancer and TargetHostManager. + */ +public class ManagedTargetHost { + + private static final Logger logger = LoggerFactory.getLogger(TargetHostManager.class); + + protected final TargetHost targetHost; + + // Reference of the ManagedTargetHost, used by LoadBalancer to ask status of a ManagedTargetHost + protected String reference; + + protected TargetStatus status; + + // Number of APIs using this ManagedTargetHost + protected AtomicInteger numberOfUse; + + // Service on which this ManagedTargetHost is registered + protected ITargetHealthCheckService healthCheckService; + + /** + * Construct a new ManagedTargetHost from a TargetHost. + * Default status is AVAILABLE and numberOfUse is 0. + * @param targetHost The targetHost to add + */ + public ManagedTargetHost(TargetHost targetHost) { + this.targetHost = targetHost; + this.numberOfUse = new AtomicInteger(); + this.status = TargetStatus.AVAILABLE; + } + + /** + * Returns the associated targetHost object from DataModel + * @return The associated targetHost object from DataModel + */ + public TargetHost getTargetHost() { + return targetHost; + } + + /** + * Returns the ManagedTargetHost reference + * @return ManagedTargetHost reference + */ + public String getReference() { + return reference; + } + + /** + * Sets the ManagedTargetHost reference + * @param reference The string to set as reference for this ManagedTargetHost + */ + public void setReference(String reference) { + this.reference = reference; + } + + /** + * Returns the HealthCheckService on which this object is registered on + * @return The HealthCheckService on which this object is registered on + */ + public ITargetHealthCheckService getHealthCheckService() { + return healthCheckService; + } + + /** + * Sets the HealthCheckService on which this object is registered on. + * @param healthCheckService + */ + public void setHealthCheckService( + ITargetHealthCheckService healthCheckService) { + this.healthCheckService = healthCheckService; + } + + /** + * Returns the usage of this ManagedTargetHost, i.e. the number of deployed APIs that have the same target. + * @return usage of this ManagedTargetHost + */ + public AtomicInteger getNumberOfUse() { + return numberOfUse; + } + + /** + * Sets the usage of this ManagedTargetHost, i.e. the number of deployed APIs that have the same target. + * @param numberOfUse number of APIs + */ + public void setNumberOfUse(AtomicInteger numberOfUse) { + this.numberOfUse = numberOfUse; + } + + /** + * Returns the status of this ManagedTargetHost + * @return The status of this ManagedTargetHost + */ + public TargetStatus getStatus() { + return status; + } + + /** + * Sets the status of this ManagedTargetHost + * @param status The new status to set for this object + */ + public synchronized void setStatus(TargetStatus status) { + this.status = status; + } + + /** + * Determine if the object is AVAILABLE or not. + * @return true if status is AVAILABLE, false otherwise. + */ + public boolean isAvailable() { + return status == TargetStatus.AVAILABLE; + } + + /** + * Computes a "hash" from a TargetHost, used by TargetHostManager + * to reuse ManagedTargetHost of different APIs with same targets. + * @param targetHost The TargetHost to hash + * @return The hash, composed of protocol+host+port + */ + public static String computeTargetHostHash(TargetHost targetHost) { + return computeTargetHostHash(targetHost, ""); + } + + /** + * Hash of protocol+host+port + a custom part. + * Typically, the custom part is the name of the HealthCheckService. This means that 2 APIs with + * same target but different HealthCheck Services are two ManagedTargetHost different objects. + * @param targetHost The TargetHost to hash + * @param custom A custom value to add to the hashing + * @return A Hash of protocol+host+port+custom + */ + public static String computeTargetHostHash(TargetHost targetHost, String custom) { + URL url = parseUrl(targetHost.getUrl()); + String src = null; + + if(url != null) { + src = url.getProtocol() + url.getHost() + url.getPort() + custom; + } else { + src = UUID.randomUUID().toString(); + } + + return src; + } + + /** + * Utility method that constructs an URL from a String without throwing exceptions. + * @param strUrl The URL to explode + * @return An URL object if URL was correct, null otherwise. + */ + public static URL parseUrl(String strUrl) { + URL url = null; + try { + url = new URL(strUrl); + } catch (MalformedURLException e) { + logger.error("Error when exploding URL", e); + } + + return url; + } + + public String toString() { + return "["+ reference + " ; " + targetHost.getUrl() + " ; " + status + "]"; + } +} diff --git a/exposure-engine/gateway-common/src/main/java/com/alu/e3/gateway/loadbalancer/RoundrobinLoadBalancer.java b/exposure-engine/gateway-common/src/main/java/com/alu/e3/gateway/loadbalancer/RoundrobinLoadBalancer.java new file mode 100644 index 0000000..611c95f --- /dev/null +++ b/exposure-engine/gateway-common/src/main/java/com/alu/e3/gateway/loadbalancer/RoundrobinLoadBalancer.java @@ -0,0 +1,305 @@ +/** + * Copyright © 2012 Alcatel-Lucent. + * + * See the NOTICE file distributed with this work for additional + * information regarding copyright ownership. + * Licensed to you 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 com.alu.e3.gateway.loadbalancer; + +import java.util.ArrayList; +import java.util.List; + +import org.apache.camel.Exchange; +import org.apache.camel.component.http4.HttpProducer; +import org.apache.http.HttpHost; +import org.apache.http.auth.AuthScope; +import org.apache.http.auth.Credentials; +import org.apache.http.auth.NTCredentials; +import org.apache.http.auth.UsernamePasswordCredentials; +import org.apache.http.conn.ClientConnectionManager; +import org.apache.http.conn.params.ConnRouteParamBean; +import org.apache.http.conn.routing.HttpRoute; +import org.apache.http.impl.client.DefaultHttpClient; +import org.apache.http.impl.conn.tsccm.ThreadSafeClientConnManager; +import org.apache.http.params.HttpConnectionParamBean; +import org.apache.http.params.HttpParams; +import org.slf4j.Logger; +import org.slf4j.LoggerFactory; + +import com.alu.e3.data.model.sub.ConnectionParameters; +import com.alu.e3.data.model.sub.ForwardProxy; +import com.alu.e3.data.model.sub.TargetHost; +import com.alu.e3.gateway.TargetHost2HttpRouteUtil; +import com.alu.e3.tdr.TDRConstant; +import com.alu.e3.tdr.TDRDataService; + +public class RoundrobinLoadBalancer { + + private static final Logger LOGGER = LoggerFactory.getLogger(RoundrobinLoadBalancer.class); + + private String name; + + private boolean failedOver; + private int failedOverErrorCode; + + HttpProducer httpProducer; + + private ITargetHostManager targetHostManager; + + private List targetReferences; + + private int globalIndex; + private int maxAttemptsExceeded; + private int numberOfReferences; + + public RoundrobinLoadBalancer(String name, boolean failedover, int failedOverErrorCode, ITargetHostManager targetHostManager) { + this.name = name; + this.failedOver = failedover; + this.failedOverErrorCode = failedOverErrorCode; + this.targetReferences = new ArrayList(); + this.targetHostManager = targetHostManager; + this.maxAttemptsExceeded = 1; + this.globalIndex = 0; + } + + public void addTargetHostReference(TargetReference targetReference) { + + LoadBalancerDisplay.logDebug(LOGGER, name, "Add and register the target host " + targetReference); + + this.targetReferences.add(targetReference); + this.numberOfReferences++; + if(failedOver) { + maxAttemptsExceeded = numberOfReferences; + } + } + + public List getTargetReferences() { + return targetReferences; + } + + public void setHttpProducer(HttpProducer httpProducer) { + LOGGER.debug("Setting a new HttpProducer ..."); + this.httpProducer = httpProducer; + LoadBalancerDisplay.displayConfig(LOGGER, name, maxAttemptsExceeded, failedOver, failedOverErrorCode, numberOfReferences); + } + + + public boolean process(Exchange exchange) throws Exception { + + boolean success = false; + + // get current + int localIndex = getNextGlobalIndex(); + LoadBalancerDisplay.logDebug(LOGGER, name, "Local index served = "+localIndex); + + TargetReference targetReference = null; + + for(int attempt = 0; attempt < maxAttemptsExceeded; attempt++) { + + LoadBalancerDisplay.logDebug(LOGGER, name,"Try "+ (attempt+1) +"/"+ maxAttemptsExceeded +" to get a valid target host"); + + targetReference = targetReferences.get(localIndex); + LoadBalancerDisplay.logDebug(LOGGER, name, "Recovered target ref = '"+targetReference.getReference()+ "'. Will check if available"); + + boolean isAvailable = targetHostManager.isAvailable(targetReference.getReference()); + + if(isAvailable) { + LoadBalancerDisplay.logDebug(LOGGER, name, "Target host with reference ["+targetReference.getReference()+"] is available"); + boolean isOk = send(exchange, targetReference); + if(isOk) { + success = isOk; + LoadBalancerDisplay.logDebug(LOGGER, name, "Succss with a try "+ (attempt+1) +"/"+ maxAttemptsExceeded); + break; + } else { + LoadBalancerDisplay.logWarn(LOGGER, name, "Unable to call the target host while it is supposed to be available, notify that the target host ["+targetReference.getTargetHost().getUrl()+"] is invalid"); + targetHostManager.notifyFailed(targetReference.getReference()); + } + } else { + LoadBalancerDisplay.logDebug(LOGGER, name, "Target host with reference ["+targetReference.getReference()+"] is NOT available"); + } + ++localIndex; + if(localIndex > numberOfReferences - 1) { + LoadBalancerDisplay.logDebug(LOGGER, name, "End of reference list; setting index to first element"); + localIndex = 0; + } + } + + if(targetReference != null){ + // Put some TDR stuff that we get from HTTP + TDRDataService.setTxTDRProperty(TDRConstant.TARGET_URL, targetReference.getTargetHost().getUrl(), exchange); + } + + return success; + } + + + private synchronized int getNextGlobalIndex() { + + LoadBalancerDisplay.logDebug(LOGGER, name, "Global index found = " + globalIndex); + + int nextGlobalIndex = globalIndex; + + // compute next + ++globalIndex; + + // reset index + if(globalIndex > numberOfReferences - 1) { + globalIndex = 0; + } + + LoadBalancerDisplay.logDebug(LOGGER, name, "Next global index computed = " + globalIndex); + + return nextGlobalIndex; + } + + private boolean send(Exchange exchange, TargetReference targetReference) throws Exception { + + boolean isOk = false; + + LoadBalancerDisplay.logDebug(LOGGER, name, "Set target host [" + targetReference.getTargetHost().getUrl() + "]"); + + String url = targetReference.getTargetHost().getUrl(); + String queryParams = null; + + int delim = url.indexOf('?'); + + if (delim != -1) { + queryParams = url.substring(delim+1, url.length()); + url = url.substring(0, delim); + } + + exchange.getIn().setHeader(Exchange.HTTP_URI, url); + + if (queryParams != null) { + String oldQueryParams = (String)exchange.getIn().getHeader(Exchange.HTTP_QUERY); + + if (oldQueryParams != null) { + queryParams = oldQueryParams + "&" + queryParams; + } + + exchange.getIn().setHeader(Exchange.HTTP_QUERY, queryParams); + } + + config(targetReference.getTargetHost()); + + LoadBalancerDisplay.displayExchange(LOGGER, name, exchange, " IN"); + + LoadBalancerDisplay.logDebug(LOGGER, name, "Send HTTP request to target reference '" +targetReference.getReference()+ "'"); + + try { + + httpProducer.process(exchange); + LoadBalancerDisplay.logDebug(LOGGER, name, "Successfully sent request to target reference '" +targetReference.getReference()+ "'"); + isOk = checkResponse(exchange); + + } catch(Exception e) { + + TDRDataService.setTxTDRProperty(TDRConstant.EVENT_TYPE, TDRConstant.EVENT_TYPE_TARGETTIMEOUT, exchange); + LoadBalancerDisplay.logError(LOGGER, name, "GRAVE: Issue during the call", e); + + } + + LoadBalancerDisplay.displayExchange(LOGGER, name, exchange, " OUT"); + + return isOk; + } + + protected void config(TargetHost targetHost){ + if(targetHost == null){ + throw new RuntimeException("Targethost cannot be null!"); + } + + DefaultHttpClient client = (DefaultHttpClient) httpProducer.getHttpClient(); + HttpParams params = client.getParams(); + + ConnectionParameters connParams = targetHost.getConnectionParameters(); + if(connParams != null){ + HttpConnectionParamBean httpConnectionParamBean = new HttpConnectionParamBean(params); + if(connParams.getConnectionTimeout() != null) + httpConnectionParamBean.setConnectionTimeout(connParams.getConnectionTimeout()); + if(connParams.getSocketTimeout() != null) + httpConnectionParamBean.setSoTimeout(connParams.getSocketTimeout()); + + ClientConnectionManager ccm = client.getConnectionManager(); + if(ccm instanceof ThreadSafeClientConnManager){ + ThreadSafeClientConnManager tsccm = (ThreadSafeClientConnManager) ccm; + HttpRoute route = TargetHost2HttpRouteUtil.fromTargetHost(targetHost); + if(connParams.getMaxConnections() != null) + tsccm.setMaxForRoute(route, targetHost.getConnectionParameters().getMaxConnections()); + } + + + } else { + LOGGER.debug("Connection parameters for target host {} are NULL", targetHost.getUrl()); + } + + ForwardProxy forwardProxy = targetHost.getForwardProxy(); + if(forwardProxy != null){ + String host = forwardProxy.getProxyHost(); + String port = forwardProxy.getProxyPort(); + if(host != null && port != null){ + ConnRouteParamBean connRouteParamBean = new ConnRouteParamBean(params); + int iport = new Integer(port); + HttpHost proxy = new HttpHost(host, iport); + connRouteParamBean.setDefaultProxy(proxy); + + String user = forwardProxy.getProxyUser(); + String pass = forwardProxy.getProxyPass(); + if(user != null && pass != null){ + Credentials credentials = null; + + String ntdomain = null; //targetHost.getForwardProxy().getProxyNtDomain; + String ntworkstation = null; //targetHost.getForwardProxy().getProxyNtWorkstation(); + if(ntdomain != null || ntworkstation != null){ + credentials = new NTCredentials(user, pass, ntworkstation, ntdomain); + } else { + credentials = new UsernamePasswordCredentials(user,pass); + } + AuthScope authscope = new AuthScope(host, iport); + client.getCredentialsProvider().setCredentials(authscope, credentials); + } + } else { + LOGGER.debug("Host or port for target host {} forward proxy are NULL", targetHost.getUrl()); + } + } else { + LOGGER.debug("Forward proxy for target host {} is NULL", targetHost.getUrl()); + } + + + } + + private boolean checkResponse(Exchange exchange) { + // isOK = false : launch Failover process for trying another target + boolean isOk = false; + + int httpCode = (Integer) exchange.getOut().getHeader(Exchange.HTTP_RESPONSE_CODE); + LoadBalancerDisplay.logDebug(LOGGER, name, "HTTP request response code '" +httpCode+ "'"); + + if (httpCode != this.failedOverErrorCode) { + LoadBalancerDisplay.logDebug(LOGGER, name, "HTTP request response code '" +httpCode+ "' is not failover code"); + isOk = true; + } else { + LoadBalancerDisplay.logWarn(LOGGER, name, "Failover http error code : " + this.failedOverErrorCode + " detected, Failover process launched."); + } + + return isOk; + } + + + + + + +} diff --git a/exposure-engine/gateway-common/src/main/java/com/alu/e3/gateway/loadbalancer/TargetHostManager.java b/exposure-engine/gateway-common/src/main/java/com/alu/e3/gateway/loadbalancer/TargetHostManager.java new file mode 100644 index 0000000..9592505 --- /dev/null +++ b/exposure-engine/gateway-common/src/main/java/com/alu/e3/gateway/loadbalancer/TargetHostManager.java @@ -0,0 +1,456 @@ +/** + * Copyright © 2012 Alcatel-Lucent. + * + * See the NOTICE file distributed with this work for additional + * information regarding copyright ownership. + * Licensed to you 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 com.alu.e3.gateway.loadbalancer; + +import java.util.ArrayList; +import java.util.Collections; +import java.util.HashMap; +import java.util.List; +import java.util.Map; + +import org.slf4j.Logger; +import org.slf4j.LoggerFactory; + +import com.alu.e3.common.caching.IEntryListener; +import com.alu.e3.common.osgi.api.IDataManager; +import com.alu.e3.data.DataEntryEvent; +import com.alu.e3.data.IDataManagerListener; +import com.alu.e3.data.model.Api; +import com.alu.e3.data.model.sub.APIContext; +import com.alu.e3.data.model.sub.ApiIds; +import com.alu.e3.data.model.sub.LoadBalancing; +import com.alu.e3.data.model.sub.TargetHost; +import com.alu.e3.gateway.targethealthcheck.ITargetHealthCheckService; + +/** + * Acts as ManagedTargetHost Database and used to maintain status of TargetHosts. + * HttpLoadBalancer interacts with this TargetHostManager to get all Targets on which it must loadbalance requests for a given API. + * + * TargetHostManager listens on the DataManager for any create/update/delete API operations and populate an internal list of ManagedTargetHost. + * + * A ManagedTargetHost is a wrapper object that encapsulate a TargetHost (from E3's DataModel) and other data used by LoadBalancing (status, ...). + * There can have one ManagedTargetHost for several TargetHost objects, if they have the same protocol+host+port+healthcheck. + * Ex: API #1 (http://www.apple.com|Ping), API #2 (http://www.apple.com|Telnet), API #3 (http://www.apple.com|Ping) where Ping and Telnet are + * TargetHealthCheck types. + * API #1 and #3 must have the same "Managed target" and #2 another one. + * + */ +public class TargetHostManager implements ITargetHostManager, IEntryListener, IDataManagerListener { + + protected IDataManager dataManager; + + private static final Logger LOGGER = LoggerFactory.getLogger(TargetHostManager.class); + + public enum TargetStatus { + AVAILABLE, OVERLOADED, UNAVAILABLE + } + + // Map of ManagedTargetHosts (mapped by their reference) + protected Map targets; + + // Map>> + protected Map>> targetReferencesMap; + + // Map of HealthChech services (mapped by their name, the same one to be used in API provisioning) + protected Map targetHealthCheckServices; + + // Internal list to postpone start of services in bean initialization + private List servicesToStart; + + public TargetHostManager() { + targetHealthCheckServices = Collections.synchronizedMap(new HashMap()); + targets = Collections.synchronizedMap(new HashMap()); + targetReferencesMap = Collections.synchronizedMap(new HashMap>>()); + } + + /** + * Called by init-method in spring bean instantiation. + * Will register and start all TargetHealthCheck services. + */ + public void init() { + LOGGER.debug("Initializing TargethostManager"); + + // Registering as Listener on DataManager + if(this.dataManager != null) { + this.dataManager.addListener(this); + } + + // Starts the list of HealthCheckServices + if (servicesToStart != null) { + for (ITargetHealthCheckService service : servicesToStart) { + registerHealthCheckService(service); + } + servicesToStart.clear(); + servicesToStart = null; + } + } + + /** + * Called by destroy-method of spring bean. + * Stops listening on API create/update/delete operations. + */ + public void destroy() { + LOGGER.debug("Destroying TargethostManager"); + + if(this.dataManager != null) { + this.dataManager.removeApiListener(this); + } + } + + /** + * Spring setter for DataManager + * @param dataManager The DataManager to set + */ + public void setDataManager(IDataManager dataManager) { + this.dataManager = dataManager; + } + + /** + * Spring setter for the list of ITargetHealthCheckService. + * + * @param services The list of ITargetHealthCheckService to register and start. + */ + public void setHealthCheckServices(List services) { + LOGGER.debug("Registering {} HealthCheck services", services.size()); + this.servicesToStart = services; + } + + /** + * Registers and starts a ITargetHealthCheckService. + * Internal method that put the service in it's internal map, mapped by service's name. + * The service is then started. + * + * @param service The ITargetHealthCheckService to register and start. + */ + protected void registerHealthCheckService(ITargetHealthCheckService service) { + if(service.getName() != null) { + LOGGER.debug("Registering HealthCheck service {} ({})", service.getName(), service.getClass().getName()); + + if(!this.targetHealthCheckServices.containsKey(service.getName())) { + this.targetHealthCheckServices.put(service.getName(), service); + service.start(); + } else { + LOGGER.warn("There is already a HealthCheck service for the name {}", service.getName()); + } + } else { + LOGGER.warn("HealthCheck service {} does not have a name, ignoring it.", service.getClass().getName()); + } + } + + /** + * Returns list of TargetReference objects for a given pair ApiID/ApiContextID. + * A TargetReference contains a TargetHost from E3's DataModel (to get url, site, ...) + a reference string. + * + * @param apiId The Api ID + * @param contextId The Api Context ID + * @return The list of TargetReference objects for a given pair ApiID/ApiContextID. + */ + @Override + public List getTargetReferences(String apiId, String contextId) { + List targetReferences = getContextList(apiId, contextId); + + return targetReferences; + } + + /** + * Internal getter for the map of Api Contexts. + * Creates the Map if it does not exists, returns the existing one otherwise. + * + * @param apiId The ApiId of Api Contexts to retrieve. + * @return The Map of APIContext for this Api + */ + protected synchronized Map> getApiMap(String apiId) { + Map> apis = targetReferencesMap.get(apiId); + if(apis == null) { + apis = Collections.synchronizedMap(new HashMap>()); + this.targetReferencesMap.put(apiId, apis); + } else { + LOGGER.debug("Apis already initialized for api id {}; nothing to do", apiId); + } + + return apis; + } + + /** + * Internal getter for the List of TargetReference, for a given ApiContext. + * Creates the List if it does not exist, returns the existing one otherwise. + * @param apiId The ApiId + * @param contextId The Api Context Id + * @return The List of TargetReference for the corresponding Api Context. + */ + protected synchronized List getContextList(String apiId, String contextId) { + Map> apis = getApiMap(apiId); + List contexts = apis.get(contextId); + + if(contexts == null) { + contexts = Collections.synchronizedList(new ArrayList()); + apis.put(apiId, contexts); + } else { + LOGGER.debug("Contexts already initialized for api id {} and context id {}; nothing to do", apiId, contextId); + } + + return contexts; + } + + + /** + * Registers an API on the TargetHostManager. + * + * For each API Contexts of the API, + * * For each TargetHost of the API Context, + * * Populate its ManagedTargetHost map + * * Prepare the list of TargetReference that will be requested by the HttpLoadBalancer later on + * + * This method is triggered by listeners on DataManager, when an API is created or updated. + * + * @param apiId The API Id to register. + */ + protected void registerAPI(String apiId) { + LOGGER.debug("Registering API {}", apiId); + + // Gets the API + Api api = dataManager.getApiById(apiId, true); + + // Get context Ids (because apis are incomplete on Gateway only machines) + List ids = api.getContextIds(); + LOGGER.debug("Browsing {} contexts for API #{}", ids.size(), apiId); + + // Get or create the Api Context map for this API + Map> map = getApiMap(apiId); + LOGGER.debug("Size of api context map for api id {}: {}", apiId, map.size()); + + // Browsing API Contexts + for(ApiIds id : ids) { + // Get the ApiContext by its ID (this map is populated on all gateways) + LOGGER.debug("Getting api context for api id {}", apiId); + APIContext context = dataManager.getApiContextById(id.getApiContextId()); + + // Shouldn't be null... + if(context != null) { + // Prepare the list of TargetReference + List targetReferences = new ArrayList(); + LOGGER.debug("Registering Context {} ({} TargetHosts)", context.getId(), context.getTargetHosts().size()); + + // Store requested HealthCheck service for later use + ITargetHealthCheckService healthCheckService = null; + String healthCheckServiceName = null; + + LoadBalancing lbConfig = context.getLoadBalancing(); + if(lbConfig.getTargetHealthCheck() != null) { + healthCheckServiceName = lbConfig.getTargetHealthCheck().getType(); + } + + if(healthCheckServiceName != null) { + LOGGER.debug("Will use HealthCheck service ", healthCheckServiceName); + + // Getting corresponding HealthCheck Service + healthCheckService = targetHealthCheckServices.get(healthCheckServiceName); + if(healthCheckService != null) { + LOGGER.debug("Found a HealthCheckService ({}) for this name: {}", healthCheckService.getClass().getName(), healthCheckServiceName); + } else { + LOGGER.debug("No HealthCheckService found for this name: {}", healthCheckServiceName); + } + } else { + LOGGER.debug("Will NOT use HealthCheck service for following targets"); + } + + + // For each TargetHost, check if there is already a corresponding ManagedTargetHost + for(TargetHost targetHost : context.getTargetHosts()) { + + // Using a "hash differentiation string": + // We need to take into account the HealthCheckService associated to a TargetHost + // Ex: API #1 (http://www.apple.com|Ping), API #2 (http://www.apple.com|Telnet), API #3 (http://www.apple.com|Ping) + // API #1 and #3 must have the same "Managed target" and #2 another one + // (One HealthCheck service may check for a specific functionality status) + String hashDifferentiationString = healthCheckServiceName == null ? "" : healthCheckServiceName; + String managedReference = ManagedTargetHost.computeTargetHostHash(targetHost, hashDifferentiationString); + + ManagedTargetHost target = targets.get(managedReference); + if(target == null) { + LOGGER.debug("No corresponding ManagedTarget, creating a new one"); + + // Instantiating and remembering managed target + target = new ManagedTargetHost(targetHost); + target.setReference(managedReference); + targets.put(managedReference, target); + + // Registering managed target on health check service + if(healthCheckService != null) { + LOGGER.debug("Target #{} registered on HealthCheck service {}", managedReference, healthCheckService.getName()); + + healthCheckService.registerTarget(target); + target.setHealthCheckService(healthCheckService); + } else { + LOGGER.debug("Target #{} not registered on HealthCheck service"); + } + } else { + // We already have a ManagedTarget for this protocol+host+port+healthcheck + LOGGER.debug("There is already a corresponding ManagedTarget: #{} ", managedReference); + } + + // Incrementing counter of use (used for unregister method) + target.getNumberOfUse().incrementAndGet(); + LOGGER.debug("New usage for target #{}: {}", managedReference, target.getNumberOfUse()); + + // Adding this reference to the list that will be returned to the LoadBalancer later on + TargetReference targetReference = new TargetReference(); + targetReference.setReference(managedReference); + targetReference.setTargetHost(targetHost); + targetReferences.add(targetReference); + } + + // Put the list of TargetReferences in the appropriate map for this Api Context. + map.put(context.getId(), targetReferences); + + } else { + // Context null + LOGGER.warn("No APIContext with that id {}, ignoring", id.getApiContextId()); + } + + } // End of for loop apiId / context + } + + /** + * Unregisters a TargetHost from the TargetHostManager. + * The ManagedTargetHost usage will be decremented, + * The object will be removed from the map only if it's not used by an API anymore and it will be unregistered from it's HealthCheck Service. + * + * @param targetHostReference The reference String of the ManagedTargetHost to unregister. + */ + protected void unregisterTargetHost(String targetHostReference) { + LOGGER.debug("Unregistering target with reference {}", targetHostReference); + ManagedTargetHost target = targets.get(targetHostReference); + if(target != null) { + int usage = target.getNumberOfUse().decrementAndGet(); + LOGGER.debug("Target #{} found, new usage: {}", targetHostReference, usage); + + // ManagedTarget is no longer used + if(usage == 0) { + LOGGER.debug("Usage == 0, removing target #{}", targetHostReference); + // Unregistering it from the HealthCheck service + ITargetHealthCheckService healthCheckService = target.getHealthCheckService(); + if(healthCheckService != null) { + LOGGER.debug("Unregistering target #{} from HealthCheckService {}", targetHostReference, healthCheckService.getName()); + healthCheckService.unregisterTarget(target); + target.setHealthCheckService(null); + } + + // Removing it from the local targets map + targets.remove(targetHostReference); + LOGGER.debug("Target #{} removed from TargetHostManager DB", targetHostReference); + } + } + } + + /** + * Marks a TargetHost as UNAVAILABLE (only if the target is monitored by a HealthCheck service, ignored otherwise). + * This method is called by the HttpLoadBalancer when sending a request to this targetHost has failed. + * + * The LoadBalancer will not try this target anymore, till the HealthCheck service restored it's state to AVAILABLE. + * + * @param targetHostReference The reference of ManagedTargetHost to mark as UNAVAILABLE. + */ + @Override + public void notifyFailed(String targetHostReference) { + ManagedTargetHost target = targets.get(targetHostReference); + if (target != null && target.getHealthCheckService() != null) { + LOGGER.debug("TargetHost {} has been notified as UNAVAILABLE, marking it"); + target.setStatus(TargetStatus.UNAVAILABLE); + } else { + LOGGER.debug("TargetHost {} has been notified as UNAVAILABLE, but is not healthChecked, so ignoring."); + } + } + + /** + * Returns if a ManagedTargetHost is AVAILABLE. + * Called by the LoadBalancer at each request. + * + * @param targetReference The reference of the TargetHost to retrieve. + * @return true if the ManagedTargetHost is considered as AVAILABLE, false otherwise. + */ + @Override + public boolean isAvailable(String targetReference) { + ManagedTargetHost target = targets.get(targetReference); + if(target != null) { + return target.isAvailable(); + } else { + LOGGER.warn("Asked invalid reference {}", targetReference); + return false; + } + } + + + /** + * Called when the DataManager is ready + */ + @Override + public void dataManagerReady() { + LOGGER.debug("Adding TargethostManager as listener on DataManager"); + if(this.dataManager != null) { + // Removing from DataManagerListener + this.dataManager.removeListener(this); + + // Adding as Listener on API Tables. + this.dataManager.addApiListener(this); + } + } + + /** + * Removes all TargetReference from the TargetHostManager for an API. + * @param apiId The Api ID of the API to clean. + */ + private void cleanApi(String apiId) { + Map> map = getApiMap(apiId); + + if (map != null) { + for(List references : map.values()) { + for(TargetReference reference : references) { + unregisterTargetHost(reference.getReference()); + } + } + map.remove(apiId); + } + } + + @Override + public void entryAdded(DataEntryEvent event) { + // populate the DB + registerAPI(event.getKey()); + } + + @Override + public void entryUpdated(DataEntryEvent event) { + // Update of an API + // clean the database... + cleanApi(event.getKey()); + + // ... and repopulate it + registerAPI(event.getKey()); + } + + @Override + public void entryRemoved(DataEntryEvent event) { + // Clean the DB + cleanApi(event.getKey()); + } + + + +} diff --git a/exposure-engine/gateway-common/src/main/java/com/alu/e3/gateway/loadbalancer/TargetReference.java b/exposure-engine/gateway-common/src/main/java/com/alu/e3/gateway/loadbalancer/TargetReference.java new file mode 100644 index 0000000..9104107 --- /dev/null +++ b/exposure-engine/gateway-common/src/main/java/com/alu/e3/gateway/loadbalancer/TargetReference.java @@ -0,0 +1,49 @@ +/** + * Copyright © 2012 Alcatel-Lucent. + * + * See the NOTICE file distributed with this work for additional + * information regarding copyright ownership. + * Licensed to you 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 com.alu.e3.gateway.loadbalancer; + +import com.alu.e3.data.model.sub.TargetHost; + +/** + * Class used by HttpLoadBalancer + * + */ +public class TargetReference { + + protected String reference; + protected TargetHost targetHost; + + public TargetHost getTargetHost() { + return targetHost; + } + + public String getReference() { + return reference; + } + + public void setReference(String reference) { + this.reference = reference; + } + + public void setTargetHost(TargetHost targetHost) { + this.targetHost = targetHost; + } + +} diff --git a/exposure-engine/gateway-common/src/main/java/com/alu/e3/gateway/security/CrlManager.java b/exposure-engine/gateway-common/src/main/java/com/alu/e3/gateway/security/CrlManager.java new file mode 100644 index 0000000..9873ea5 --- /dev/null +++ b/exposure-engine/gateway-common/src/main/java/com/alu/e3/gateway/security/CrlManager.java @@ -0,0 +1,49 @@ +/** + * Copyright © 2012 Alcatel-Lucent. + * + * See the NOTICE file distributed with this work for additional + * information regarding copyright ownership. + * Licensed to you 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 com.alu.e3.gateway.security; + +import java.security.cert.CRL; +import java.security.cert.Certificate; +import java.util.HashMap; + +public class CrlManager { + + private HashMap crlMap = new HashMap(); + + public CrlManager() {} + + public void addCRL(String id, CRL crl) { + crlMap.put(id, crl); + } + + public void removeCRL(String id) { + crlMap.remove(id); + } + + public boolean isCertificateRevoked(Certificate certificate) { + + for (CRL crl : crlMap.values()) { + if (crl.isRevoked(certificate)) { + return true; + } + } + + return false; + } +} diff --git a/exposure-engine/gateway-common/src/main/java/com/alu/e3/gateway/security/E3TrustManager.java b/exposure-engine/gateway-common/src/main/java/com/alu/e3/gateway/security/E3TrustManager.java new file mode 100644 index 0000000..8dff41a --- /dev/null +++ b/exposure-engine/gateway-common/src/main/java/com/alu/e3/gateway/security/E3TrustManager.java @@ -0,0 +1,184 @@ +/** + * Copyright © 2012 Alcatel-Lucent. + * + * See the NOTICE file distributed with this work for additional + * information regarding copyright ownership. + * Licensed to you 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 com.alu.e3.gateway.security; + +import java.security.InvalidAlgorithmParameterException; +import java.security.KeyStore; +import java.security.KeyStoreException; +import java.security.NoSuchAlgorithmException; +import java.security.Provider; +import java.security.cert.CRL; +import java.security.cert.CertPathValidator; +import java.security.cert.CertPathValidatorException; +import java.security.cert.CertStore; +import java.security.cert.CertStoreException; +import java.security.cert.Certificate; +import java.security.cert.CertificateException; +import java.security.cert.CertificateFactory; +import java.security.cert.CollectionCertStoreParameters; +import java.security.cert.PKIXParameters; +import java.security.cert.TrustAnchor; +import java.security.cert.X509Certificate; +import java.util.Arrays; +import java.util.Enumeration; +import java.util.HashMap; +import java.util.HashSet; +import java.util.Map; +import java.util.Set; + +import javax.net.ssl.X509TrustManager; + +import org.bouncycastle.jce.provider.BouncyCastleProvider; +import org.slf4j.Logger; +import org.slf4j.LoggerFactory; + +public class E3TrustManager implements X509TrustManager { + private static final Logger LOG = LoggerFactory.getLogger(E3TrustManager.class); + + private static final Provider PROVIDER = new BouncyCastleProvider(); + private static final Map CRL_MAP = new HashMap(); + private static volatile CertStore crlStore = null; + + private final CertificateFactory certFactory; + private final Set trustAnchors = new HashSet(); + private final CertStore certStore; + + public E3TrustManager(KeyStore trustStore) throws CertificateException, KeyStoreException, + InvalidAlgorithmParameterException, NoSuchAlgorithmException + { + certFactory = CertificateFactory.getInstance("X.509", PROVIDER); + + Set allX509Certs = new HashSet(); + Enumeration aliases = trustStore.aliases(); + while (aliases.hasMoreElements()) { + String alias = aliases.nextElement(); + if (!trustStore.isCertificateEntry(alias)) { + continue; + } + Certificate cert = trustStore.getCertificate(alias); + if (!(cert instanceof X509Certificate)) { + continue; + } + + X509Certificate x509Cert = (X509Certificate) cert; + allX509Certs.add(x509Cert); + trustAnchors.add(new TrustAnchor(x509Cert, null)); + } + + certStore = CertStore.getInstance("Collection", + new CollectionCertStoreParameters(allX509Certs), PROVIDER); + } + + @Override + public void checkClientTrusted(X509Certificate[] chain, String authType) throws CertificateException { + if ((chain == null) || (chain.length == 0)) { + // No certificate provided by the client, + // it will be handled later by ClientCertificateValidator + return; + } + + try { + // PKIXParameters is not thread-safe + final PKIXParameters params = new PKIXParameters(trustAnchors); + params.addCertStore(certStore); + + // Keep the local copy of crlStore, as the class attribute may change. + final CertStore crlStore = E3TrustManager.crlStore; + if (crlStore != null) { + params.addCertStore(crlStore); + params.setRevocationEnabled(true); + } else { + params.setRevocationEnabled(false); + } + + // CertPathValidator is not thread-safe + final CertPathValidator validator = CertPathValidator.getInstance("PKIX", PROVIDER); + validator.validate(certFactory.generateCertPath(Arrays.asList(chain)), params); + + } catch (InvalidAlgorithmParameterException e) { + logExcetpion(e, chain); + throw new CertificateException(e); + } catch (NoSuchAlgorithmException e) { + logExcetpion(e, chain); + throw new CertificateException(e); + } catch (CertPathValidatorException e) { + logExcetpion(e, chain); + throw new CertificateException(e); + } + } + + @Override + public void checkServerTrusted(X509Certificate[] chain, String authType) throws CertificateException { + // Not needed now + } + + @Override + public X509Certificate[] getAcceptedIssuers() { + try { + return certStore.getCertificates(null).toArray(new X509Certificate[0]); + } catch (CertStoreException e) { + LOG.error("Could not retrieve CA certificates", e); + return new X509Certificate[0]; + } + } + + public static void addCRL(String id, CRL crl) + throws NoSuchAlgorithmException, InvalidAlgorithmParameterException + { + synchronized (CRL_MAP) { + CRL_MAP.put(id, crl); + crlStore = CertStore.getInstance("Collection", + new CollectionCertStoreParameters(CRL_MAP.values()), PROVIDER); + } + } + + public static void removeCRL(String id) + throws NoSuchAlgorithmException, InvalidAlgorithmParameterException + { + synchronized (CRL_MAP) { + CRL_MAP.remove(id); + if (CRL_MAP.isEmpty()) { + crlStore = null; + } else { + crlStore = CertStore.getInstance("Collection", + new CollectionCertStoreParameters(CRL_MAP.values()), PROVIDER); + } + } + } + + private void logExcetpion(Exception e, X509Certificate[] chain) { + LOG.error("Certificate validation failed", e); + + if (LOG.isDebugEnabled()) { + LOG.debug("Provided chain:"); + for (X509Certificate x509Cert : chain) { + LOG.debug("Subject: " + x509Cert.getSubjectDN() + "\tIssuer: " + x509Cert.getIssuerDN()); + } + LOG.debug("Accepted issuers:"); + try { + for (Certificate cert : certStore.getCertificates(null)) { + X509Certificate x509Cert = (X509Certificate) cert; + LOG.debug("Issuer: " + x509Cert.getSubjectDN()); + } + } catch (CertStoreException e1) { + LOG.debug("Could not retrieve CA certificates", e); + } + } + } +} diff --git a/exposure-engine/gateway-common/src/main/java/com/alu/e3/gateway/security/SslJettyComponentReloader.java b/exposure-engine/gateway-common/src/main/java/com/alu/e3/gateway/security/SslJettyComponentReloader.java new file mode 100644 index 0000000..bbef2d3 --- /dev/null +++ b/exposure-engine/gateway-common/src/main/java/com/alu/e3/gateway/security/SslJettyComponentReloader.java @@ -0,0 +1,169 @@ +/** + * Copyright © 2012 Alcatel-Lucent. + * + * See the NOTICE file distributed with this work for additional + * information regarding copyright ownership. + * Licensed to you 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 com.alu.e3.gateway.security; + +import org.osgi.framework.BundleContext; +import org.osgi.framework.ServiceRegistration; +import org.slf4j.Logger; +import org.slf4j.LoggerFactory; +import org.springframework.beans.factory.annotation.Autowired; +import org.springframework.context.ApplicationContext; +import org.springframework.osgi.context.support.OsgiBundleXmlApplicationContext; + +import com.alu.e3.common.osgi.api.IKeyStoreService; +import com.alu.e3.common.osgi.api.IStoreChangedListener; +import com.alu.e3.common.osgi.api.ITrustStoreService; + +public class SslJettyComponentReloader implements IStoreChangedListener { + + private static final String SSLJETTY_REGISTRATION_BEAN_ID = "ssljettyRegistration"; + + private static final Logger LOG = LoggerFactory.getLogger(SslJettyComponentReloader.class); + + @Autowired + private BundleContext bundleContext; + @Autowired + private ApplicationContext parentApplicationContext; + private String contextXmlClasspath; + + private IKeyStoreService keyStoreService; + private ITrustStoreService trustStoreService; + + private ServiceRegistration sslJettyRegistration; + + private OsgiBundleXmlApplicationContext childApplicationContext; + + /** + * Needs the application context to init the SslJetty component in spring-dm context. + * @param applicationContext + */ + public void setApplicationContext(ApplicationContext applicationContext) { + this.parentApplicationContext = applicationContext; + } + + /** + * Needs the bundle context to init the SslJetty component in spring-dm context. + * @param bundleContext + */ + public void setBundleContext(BundleContext bundleContext) { + this.bundleContext = bundleContext; + } + + /** + * Sets the base xml classPath defining the SslJetty spring-dm'ized component. + * @param contextXmlClasspath + */ + public void setContextXmlClasspath(String contextXmlClasspath) { + this.contextXmlClasspath = contextXmlClasspath; + } + + /** + * Needs the {@link IKeyStoreService} to register on changed events. + * @param keyStoreService + */ + public void setKeyStoreService(IKeyStoreService keyStoreService) { + this.keyStoreService = keyStoreService; + } + + /** + * Needs the {@link ITrustStoreService} to register on changed events. + * @param trustStoreService + */ + public void setTrustStoreService(ITrustStoreService trustStoreService) { + this.trustStoreService = trustStoreService; + } + + /** + * Inits listeners and child application context. + */ + protected void init() { + LOG.debug("SslJettyComponentReloader initialization ..."); + + LOG.debug("Registering store changed listeners ..."); + keyStoreService.addStoreChangedListener(this); + trustStoreService.addStoreChangedListener(this); + + LOG.debug("Creating child context ..."); + String[] xmlConfigClassPathes = new String[]{contextXmlClasspath}; + childApplicationContext = new OsgiBundleXmlApplicationContext(xmlConfigClassPathes, parentApplicationContext); + childApplicationContext.setBundleContext(bundleContext); + + LOG.debug("Starting child context ..."); + childApplicationContext.refresh(); + + getOrUpdateServiceRegistration(); + + LOG.debug("SslJettyComponentReloader init done."); + } + + /** + * Cleans up listeners and child application context. + */ + protected void destroy() { + LOG.debug("SslJettyComponentReloader destroying ..."); + + LOG.debug("Closing child context ..."); + childApplicationContext.close(); + + LOG.debug("UNRegistering store changed listeners ..."); + keyStoreService.removeStoreChangedListener(this); + trustStoreService.removeStoreChangedListener(this); + + LOG.debug("SslJettyComponentReloader destroyed."); + } + + /** + * On key/cert stores changed, reloads the SslJetty spring-dm'ized component. + */ + @Override + public void onStoreChanged() { + LOG.debug("SslJettyComponent reloading ..."); + reload(); + LOG.debug("SslJettyComponent reloaded."); + } + + private void getOrUpdateServiceRegistration() { + LOG.debug("Getting service registration ..."); + sslJettyRegistration = childApplicationContext.getBean(SSLJETTY_REGISTRATION_BEAN_ID, ServiceRegistration.class); + + if (sslJettyRegistration==null) + throw new IllegalStateException("Unable to get back service registration with bean id: "+SSLJETTY_REGISTRATION_BEAN_ID); + } + + /** + * Reload the child application context, in other terms, the SslJetty spring-dm'ized component. + */ + private void reload() { + try { + LOG.debug("Trying sslJettyREgistration unregistering ..."); + sslJettyRegistration.unregister(); + } catch(Exception e) { + LOG.error("Bad luck, unable to unregister sslJettyREgistration", e); + } + + LOG.debug("childApplicationContext normal closing ..."); + childApplicationContext.destroy(); + + LOG.debug("childApplicationContext normal refreshing ..."); + childApplicationContext.refresh(); + + getOrUpdateServiceRegistration(); + } + +} diff --git a/exposure-engine/gateway-common/src/main/java/com/alu/e3/gateway/targethealthcheck/ITargetHealthCheckService.java b/exposure-engine/gateway-common/src/main/java/com/alu/e3/gateway/targethealthcheck/ITargetHealthCheckService.java new file mode 100644 index 0000000..7e72dba --- /dev/null +++ b/exposure-engine/gateway-common/src/main/java/com/alu/e3/gateway/targethealthcheck/ITargetHealthCheckService.java @@ -0,0 +1,76 @@ +/** + * Copyright © 2012 Alcatel-Lucent. + * + * See the NOTICE file distributed with this work for additional + * information regarding copyright ownership. + * Licensed to you 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 com.alu.e3.gateway.targethealthcheck; + +import com.alu.e3.gateway.loadbalancer.ManagedTargetHost; + +/** + * Interface that each TargetHealthCheck Service must implement. + * + * A TargetHealthCheck Service monitors a set of ManagedTargetHost and update their status. + * This status is used by the LoadBalancer to determine if a target can be used or not. + * + */ +public interface ITargetHealthCheckService { + + /** + * The name of the HealthCheck Service. Must be unique for all services. + * This is the name that must be used at API Provisioning time. + * + * @return The name of the HealthCheck Service. + */ + public String getName(); + + /** + * init-method of the bean, called by Spring. + */ + public void init(); + + /** + * Called by TargetHostManager when the HealthCheckService has been registered. + * This should start the target health check operation. + */ + public void start(); + + /** + * Stops the target health check operation. + */ + public void stop(); + + /** + * destroy-method of the bean, called by Spring. + * You should stop the health check operation in this method. + */ + public void destroy(); + + /** + * Registers a ManagedTargetHost to this health check service. + * This means that this health check service will now monitor this target. + * @param target The ManagedTargetHost to monitor + */ + public void registerTarget(ManagedTargetHost target); + + /** + * Removes a target from health check service + * @param target The ManagedTargetHost to remove from monitoring + */ + public void unregisterTarget(ManagedTargetHost target); + + +} \ No newline at end of file diff --git a/exposure-engine/gateway-common/src/main/java/com/alu/e3/gateway/valid/camel/component/ValidatorComponent.java b/exposure-engine/gateway-common/src/main/java/com/alu/e3/gateway/valid/camel/component/ValidatorComponent.java new file mode 100644 index 0000000..04045ba --- /dev/null +++ b/exposure-engine/gateway-common/src/main/java/com/alu/e3/gateway/valid/camel/component/ValidatorComponent.java @@ -0,0 +1,41 @@ +/** + * Copyright © 2012 Alcatel-Lucent. + * + * See the NOTICE file distributed with this work for additional + * information regarding copyright ownership. + * Licensed to you 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 com.alu.e3.gateway.valid.camel.component; + +import java.util.Map; + +import org.apache.camel.CamelContext; +import org.apache.camel.Endpoint; +import org.apache.camel.impl.DefaultComponent; + +public class ValidatorComponent extends DefaultComponent { + + public ValidatorComponent() {} + + public ValidatorComponent(CamelContext camelContext) { + super(camelContext); + } + + @Override + protected Endpoint createEndpoint(String uri, String remaining, Map parameters) throws Exception { + + return new ValidatorEndpoint(uri, this); + } + +} diff --git a/exposure-engine/gateway-common/src/main/java/com/alu/e3/gateway/valid/camel/component/ValidatorEndpoint.java b/exposure-engine/gateway-common/src/main/java/com/alu/e3/gateway/valid/camel/component/ValidatorEndpoint.java new file mode 100644 index 0000000..a073596 --- /dev/null +++ b/exposure-engine/gateway-common/src/main/java/com/alu/e3/gateway/valid/camel/component/ValidatorEndpoint.java @@ -0,0 +1,48 @@ +/** + * Copyright © 2012 Alcatel-Lucent. + * + * See the NOTICE file distributed with this work for additional + * information regarding copyright ownership. + * Licensed to you 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 com.alu.e3.gateway.valid.camel.component; + +import org.apache.camel.Component; +import org.apache.camel.Consumer; +import org.apache.camel.Processor; +import org.apache.camel.Producer; +import org.apache.camel.impl.DefaultEndpoint; + +public class ValidatorEndpoint extends DefaultEndpoint { + + public ValidatorEndpoint(String uri, Component component) { + super(uri, component); + } + + @Override + public Producer createProducer() throws Exception { + return new ValidatorProducer(this); + } + + @Override + public Consumer createConsumer(Processor processor) throws Exception { + //consumer is not needed in this case + throw new UnsupportedOperationException("createConsumer is not needed in this case"); + } + + @Override + public boolean isSingleton() { + return false; + } +} diff --git a/exposure-engine/gateway-common/src/main/java/com/alu/e3/gateway/valid/camel/component/ValidatorProducer.java b/exposure-engine/gateway-common/src/main/java/com/alu/e3/gateway/valid/camel/component/ValidatorProducer.java new file mode 100644 index 0000000..b2c2855 --- /dev/null +++ b/exposure-engine/gateway-common/src/main/java/com/alu/e3/gateway/valid/camel/component/ValidatorProducer.java @@ -0,0 +1,39 @@ +/** + * Copyright © 2012 Alcatel-Lucent. + * + * See the NOTICE file distributed with this work for additional + * information regarding copyright ownership. + * Licensed to you 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 com.alu.e3.gateway.valid.camel.component; + +import org.apache.camel.Endpoint; +import org.apache.camel.Exchange; +import org.apache.camel.impl.DefaultProducer; + +public class ValidatorProducer extends DefaultProducer { + + public ValidatorProducer(Endpoint endpoint) { + super(endpoint); + + if(!(endpoint instanceof ValidatorEndpoint)){ + throw new RuntimeException("ValidatorProducer does not support endpoint type:"+endpoint.getClass().getName()); + } + } + + @Override + public void process(Exchange exchange) throws Exception { + } + +} diff --git a/exposure-engine/gateway-common/src/main/java/com/alu/e3/tdr/TDRConstant.java b/exposure-engine/gateway-common/src/main/java/com/alu/e3/tdr/TDRConstant.java new file mode 100644 index 0000000..d04eec5 --- /dev/null +++ b/exposure-engine/gateway-common/src/main/java/com/alu/e3/tdr/TDRConstant.java @@ -0,0 +1,68 @@ +/** + * Copyright © 2012 Alcatel-Lucent. + * + * See the NOTICE file distributed with this work for additional + * information regarding copyright ownership. + * Licensed to you 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 com.alu.e3.tdr; + +public class TDRConstant { + + // TDR fields name + public static final String TIMESTAMP = "Timestamp"; + public static final String TRANSACTION = "TransactionID"; + public static final String SYSTEM = "SystemID"; + public static final String CLIENT = "ClientIP"; + public static final String ENDPOINT = "ClientEndpoint"; + public static final String ENDPOINT_ACTION = "APIAction"; + public static final String CLIENT_REQ_TIME = "ClientRequestTimestamp"; + public static final String TARGET_REQ_TIME = "APITargetRequestTimestamp"; + public static final String TARGET_RESP_TIME = "APITargetResponseTimestamp"; + public static final String CLIENT_RESP_TIME = "ClientResponseTimestamp"; + public static final String HTTP_CODE = "HTTPStatusCode"; + public static final String HTTP_METHOD = "HTTPMethod"; + public static final String RESP_SIZE = "PayloadSize"; + public static final String TARGET_URL = "TargetEndPoint"; + public static final String TARGET_IP = "TargetIP"; + public static final String AUTHENTICATION = "AuthMethod"; + public static final String SOAP_ACTION = "SOAPAction"; + + public static final String OVER_QUOTA = "OverQuota"; + public static final String OVER_QUOTA_SEC = "OverSecondRateLimit"; + public static final String OVER_QUOTA_MIN = "OverMinuteRateLimit"; + public static final String OVER_QUOTA_DAY = "OverDayQuota"; + public static final String OVER_QUOTA_WEEK = "OverWeekQuota"; + public static final String OVER_QUOTA_MONTH = "OverMonthQuota"; + public static final String OVER_QUOTA_ACTION = "QuotaAction"; + + // EventType TDR enum + public static final String EVENT_TYPE = "EventType"; + public static final String EVENT_TYPE_OK = "Response"; + public static final String EVENT_TYPE_INTERNALERROR = "Error"; + public static final String EVENT_TYPE_TARGETTIMEOUT = "APITargetTimeout"; + public static final String EVENT_TYPE_TARGETERROR = "APITargetError"; + + // Rate TDR fields name + public static final String RATE_TYPE = "Type"; + public static final String RATE_LIMIT = "Threshold"; + public static final String RATE_WARNING = "Warning"; + public static final String RATE_EXPIRATION = "Expiration"; + public static final String CALL_COUNT = "Count"; + public static final String USAGE_PERCENT = "UsagePercent"; + + // TDR Specific fields name + public static final String CORRELATION = "CorrelationID"; + +} diff --git a/exposure-engine/gateway-common/src/main/java/com/alu/e3/tdr/TDRDataService.java b/exposure-engine/gateway-common/src/main/java/com/alu/e3/tdr/TDRDataService.java new file mode 100644 index 0000000..73a0c5b --- /dev/null +++ b/exposure-engine/gateway-common/src/main/java/com/alu/e3/tdr/TDRDataService.java @@ -0,0 +1,352 @@ +/** + * Copyright © 2012 Alcatel-Lucent. + * + * See the NOTICE file distributed with this work for additional + * information regarding copyright ownership. + * Licensed to you 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 com.alu.e3.tdr; + +import java.util.ArrayList; +import java.util.Collections; +import java.util.HashMap; +import java.util.List; +import java.util.Map; +import java.util.Map.Entry; + +import org.apache.camel.Exchange; + +import com.alu.e3.data.model.sub.TdrDynamicRule; +import com.alu.e3.data.model.sub.TdrGenerationRule; +import com.alu.e3.data.model.sub.TdrStaticRule; + +/** + * Class TDRDataService A thin facade that will help read and write TDR specific + * properties on the Camel Exchange. + * + * + */ +public class TDRDataService { + + private static final String tdrDataKey = "__TDRDATA__"; + private static final String txTdrNameKey = "__TXTDRNAME__"; + + private static final Map emptyMap = Collections.emptyMap(); + + public static void setTxTDRName(String name, Exchange exchange) { + exchange.setProperty(txTdrNameKey, name); + } + + public static String getTxTDRName(Exchange exchange) { + String txTDRName = (String) exchange.getProperty(txTdrNameKey); + + // Make sure that the name has some value... default to txTDR + if (txTDRName == null || txTDRName.equals("")) { + txTDRName = "txTDR"; + } + + return txTDRName; + } + + /** + * Adds a new property (name/value pair) which will be shared by all the + * TDRs on this exchange. + * + * @param exchange + * @param name + * @param value + */ + public static void addCommonProperty(Exchange exchange, String name, + Object value) { + addToUniquelyNamedTdr(exchange, "common", name, value); + } + + /** + * Adds a new property (name/value pair) to the tx TDR on this exchange. + * + * @param exchange + * @param name + * @param value + */ + public static void addTxTDRProperty(Exchange exchange, String name, + Object value) { + String txTDRName = getTxTDRName(exchange); + addToUniquelyNamedTdr(exchange, txTDRName, name, value); + } + + /** + * Adds a new TDR (map of name/value pairs) of the specified tdrTypeName to + * this exchange. + * + * @param exchange + * @param tdr + * @param tdrTypeName + */ + public static void addNewTdrMap(Exchange exchange, Map tdr, + String tdrTypeName) { + Map>> tdrData = getTdrData(exchange); + synchronized (tdrData) { + List> list = tdrData.get(tdrTypeName); + if (list == null) { + list = new ArrayList>(); + tdrData.put(tdrTypeName, list); + } + list.add(tdr); + } + } + + /** + * Use this function to retrieve all TDR properties set on the exchange. + *

+ * This method was useful when there was only a single TDR for an exchange, + * but now that there can be multiple TDRs per exchange this method doesn't + * make much sense. For backwards compatibility, this method now returns the + * tx properties. + * + * @deprecated use getTxTDRProperties + * @param exchange + * @return Map + */ + @Deprecated + public static Map getProperties(Exchange exchange) { + return getTxTDRProperties(exchange); + } + + /** + * Use this function to retrieve all tx TDR properties set on the exchange. + *

+ * Note that the map returned by this method does not include the common + * properties. + * + * @param exchange + * @return Map + */ + public static Map getTxTDRProperties(Exchange exchange) { + String txTDRName = getTxTDRName(exchange); + Map map = getFirstNamedTdr(exchange, txTDRName); + return (map == null) ? emptyMap : map; + } + + /** + * Returns a value string for a given property name. Returns NULL if name + * not found. + *

+ * This method was useful when there was only a single TDR for an exchange, + * but now that there can be multiple TDRs per exchange this method doesn't + * make much sense. For backwards compatibility, this method now returns the + * tx property with the specified name. + * + * @deprecated use getTxTDRProperty + * @param name + * @param exchange + * @return String + */ + @Deprecated + public static Object getProperty(String name, Exchange exchange) { + return getTxTDRProperty(name, exchange); + } + + /** + * Returns a value string for a given tx property name. Returns NULL if name + * not found. + * + * @param name + * @param exchange + * @return String + */ + public static Object getTxTDRProperty(String name, Exchange exchange) { + return getTxTDRProperties(exchange).get(name); + } + + /** + * Will set a name value pair on the Camel Exchange. + * + * @deprecated use setTxTDRProperty + * @param String + * name + * @param Object + * value - this object should + * @param exchange + */ + @Deprecated + public static void setProperty(String name, Object value, Exchange exchange) { + setTxTDRProperty(name, value, exchange); + } + + public static void setPropertyForType(String tdrTypeName, String name, + String value, Exchange exchange) { + + if (tdrTypeName == null || tdrTypeName.equals("") || tdrTypeName.equals(getTxTDRName(exchange).toString())) { + setTxTDRProperty(name, value, exchange); + } else { + Map>> tdrData = getTdrData(exchange); + + if (tdrData != null) { + List> tdrList = tdrData.get(tdrTypeName); + if (tdrList != null) { + for (Map tdr : tdrList) { + // append this name-value to each tdr + tdr.put(name, value); + } + } + } + } + } + + /** + * Will set a name value pair on the Camel Exchange. + * + * @param String + * name + * @param Object + * value - this object should + * @param exchange + */ + public static void setTxTDRProperty(String name, Object value, + Exchange exchange) { + addTxTDRProperty(exchange, name, value); + } + + /** + * Returns all the TDRs from this exchange, with common values replicated in + * each. TDR specific values take precedence over any common values with the + * same name. + * + * @param exchange + * @return map (keyed on tdrTypeName) of list of TDR property maps + * (name/value pairs) + */ + public static Map>> getTdrs( + Exchange exchange) { + Map>> resolvedTdrs = new HashMap>>(); + Map>> tdrData = getTdrData(exchange); + + synchronized (tdrData) { + List> commonList = tdrData.get("common"); + Map commonMap = (commonList != null) ? commonList.get(0) : emptyMap; + + for (Entry>> tdrDataEntry: tdrData.entrySet()) { + if ("common".equals(tdrDataEntry.getKey())) { + continue; // not a real TDR + } + List> list = new ArrayList>(); + for (Map tdrMap : tdrDataEntry.getValue()) { + Map map = new HashMap(commonMap); + map.putAll(tdrMap); + list.add(map); + } + resolvedTdrs.put(tdrDataEntry.getKey(), list); + } + + return resolvedTdrs; + } + } + + /** + * Clean the given Exchange about tdr datas + * + * @param exchangeToClean + */ + public static void clean(Exchange exchangeToClean) { + exchangeToClean.getProperties().remove(tdrDataKey); + } + + /** + * Helper function to help do dynamic TDR value evaluation + * + * @param name + * @param header + * @param exchange + */ + public static void setDynamicTxTDRProperty(String name, String header, + Exchange exchange) { + String resolvedValue = evalDynamicProperty(header, exchange); + addTxTDRProperty(exchange, name, resolvedValue); + } + + public static String evalDynamicProperty(String header, Exchange exchange) { + String resolvedValue = exchange.getIn().getHeader(header, String.class); + + if (resolvedValue == null) { + resolvedValue = exchange.getProperty(header, String.class); + } + + if (resolvedValue == null) { + resolvedValue = ""; + } + + return resolvedValue; + } + + /** + * Helper function... simply converts the TdrGenerationRule into a + * Map and then calls the addNewTdrMap function above + * + * @param exchange + * @param genRule + * @param tdrTypeName + */ + public static void addNewTdrGenerationRule(Exchange exchange, + TdrGenerationRule genRule, String tdrTypeName) { + Map map = new HashMap(); + for (TdrDynamicRule rule : genRule.getDynamicRules()) { + map.put(rule.getTdrPropName(), + evalDynamicProperty(rule.getHttpHeaderName(), exchange)); + } + for (TdrStaticRule rule : genRule.getStaticRules()) { + map.put(rule.getTdrPropName(), rule.getValue()); + } + + addNewTdrMap(exchange, map, tdrTypeName); + } + + private static void addToUniquelyNamedTdr(Exchange exchange, + String tdrTypeName, String name, Object value) { + + Map>> tdrData = getTdrData(exchange); + synchronized (tdrData) { + List> list = tdrData.get(tdrTypeName); + if (list == null) { + list = new ArrayList>(); + list.add(new HashMap()); + tdrData.put(tdrTypeName, list); + } + Map map = list.get(0); + map.put(name, value); + } + } + + private static Map getFirstNamedTdr(Exchange exchange, + String tdrTypeName) { + Map>> tdrData = getTdrData(exchange); + synchronized (tdrData) { + List> list = tdrData.get(tdrTypeName); + return (list == null) ? null : list.get(0); + } + } + + @SuppressWarnings("unchecked") + private static Map>> getTdrData( + Exchange exchange) { + synchronized (exchange) { + Map>> tdrData = (Map>>) exchange + .getProperties().get(tdrDataKey); + if (tdrData == null) { + tdrData = new HashMap>>(); + exchange.setProperty(tdrDataKey, tdrData); + } + return tdrData; + } + } +} diff --git a/exposure-engine/gateway-common/src/main/resources/META-INF/services/org/apache/camel/component/validator b/exposure-engine/gateway-common/src/main/resources/META-INF/services/org/apache/camel/component/validator new file mode 100644 index 0000000..ef6951e --- /dev/null +++ b/exposure-engine/gateway-common/src/main/resources/META-INF/services/org/apache/camel/component/validator @@ -0,0 +1 @@ +class=com.alu.e3.gateway.valid.camel.component.ValidatorComponent \ No newline at end of file diff --git a/exposure-engine/gateway-common/src/main/resources/META-INF/spring-optional/gateway-common.beans-os.xml b/exposure-engine/gateway-common/src/main/resources/META-INF/spring-optional/gateway-common.beans-os.xml new file mode 100644 index 0000000..7bacfad --- /dev/null +++ b/exposure-engine/gateway-common/src/main/resources/META-INF/spring-optional/gateway-common.beans-os.xml @@ -0,0 +1,22 @@ + + + + + + + + + + + + + diff --git a/exposure-engine/gateway-common/src/main/resources/META-INF/spring-optional/gateway-common.beans.xml b/exposure-engine/gateway-common/src/main/resources/META-INF/spring-optional/gateway-common.beans.xml new file mode 100644 index 0000000..1b8b3b2 --- /dev/null +++ b/exposure-engine/gateway-common/src/main/resources/META-INF/spring-optional/gateway-common.beans.xml @@ -0,0 +1,67 @@ + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + diff --git a/exposure-engine/gateway-common/src/main/resources/META-INF/spring-optional/gateway-common.jetty-http-component-context.xml b/exposure-engine/gateway-common/src/main/resources/META-INF/spring-optional/gateway-common.jetty-http-component-context.xml new file mode 100644 index 0000000..b7b37ab --- /dev/null +++ b/exposure-engine/gateway-common/src/main/resources/META-INF/spring-optional/gateway-common.jetty-http-component-context.xml @@ -0,0 +1,67 @@ + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + diff --git a/exposure-engine/gateway-common/src/main/resources/META-INF/spring-optional/gateway-common.reloadable-jetty-https-component-context.xml b/exposure-engine/gateway-common/src/main/resources/META-INF/spring-optional/gateway-common.reloadable-jetty-https-component-context.xml new file mode 100644 index 0000000..4a62c72 --- /dev/null +++ b/exposure-engine/gateway-common/src/main/resources/META-INF/spring-optional/gateway-common.reloadable-jetty-https-component-context.xml @@ -0,0 +1,48 @@ + + + + + + + + + + + + + + + + + + + + + + + + diff --git a/exposure-engine/gateway-common/src/main/resources/META-INF/spring-optional/gateway-lb.beans.xml b/exposure-engine/gateway-common/src/main/resources/META-INF/spring-optional/gateway-lb.beans.xml new file mode 100644 index 0000000..8476c1a --- /dev/null +++ b/exposure-engine/gateway-common/src/main/resources/META-INF/spring-optional/gateway-lb.beans.xml @@ -0,0 +1,21 @@ + + + + + + + + + + + + diff --git a/exposure-engine/gateway-common/src/main/resources/soap/soap-1.1.xsd b/exposure-engine/gateway-common/src/main/resources/soap/soap-1.1.xsd new file mode 100644 index 0000000..bc3423e --- /dev/null +++ b/exposure-engine/gateway-common/src/main/resources/soap/soap-1.1.xsd @@ -0,0 +1,88 @@ + + + + + + + + + + + + + + + + + + + + + + + + + + + + Prose in the spec does not specify that attributes are allowed on the + Body element + + + + + + + + + + + + + + + + 'encodingStyle' indicates any canonicalization conventions followed in the contents + of the containing element. For example, the value + 'http://schemas.xmlsoap.org/soap/encoding/' indicates the pattern + described in SOAP specification + + + + + + + + + + + + + Fault reporting structure + + + + + + + + + + + + + + + + + + + + + + + + diff --git a/exposure-engine/gateway-common/src/main/resources/soap/soap-1.2.xsd b/exposure-engine/gateway-common/src/main/resources/soap/soap-1.2.xsd new file mode 100644 index 0000000..3dc9c66 --- /dev/null +++ b/exposure-engine/gateway-common/src/main/resources/soap/soap-1.2.xsd @@ -0,0 +1,109 @@ + + + + + + + + + + + + + + + + Elements replacing the wildcard MUST be namespace qualified, but can be in + the targetNamespace + + + + + + + + + + + + + + + + + + + + + + + Fault reporting structure + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + diff --git a/exposure-engine/gateway-common/src/main/resources/soap/xml.xsd b/exposure-engine/gateway-common/src/main/resources/soap/xml.xsd new file mode 100644 index 0000000..1c23e0b --- /dev/null +++ b/exposure-engine/gateway-common/src/main/resources/soap/xml.xsd @@ -0,0 +1,143 @@ + + + + + See http://www.w3.org/XML/1998/namespace.html and + http://www.w3.org/TR/REC-xml for information about this namespace. + + This schema document describes the XML namespace, in a form + suitable for import by other schema documents. + + Note that local names in this namespace are intended to be defined + only by the World Wide Web Consortium or its subgroups. The + following names are currently defined in this namespace and should + not be used with conflicting semantics by any Working Group, + specification, or document instance: + + base (as an attribute name): denotes an attribute whose value + provides a URI to be used as the base for interpreting any + relative URIs in the scope of the element on which it + appears; its value is inherited. This name is reserved + by virtue of its definition in the XML Base specification. + + id (as an attribute name): denotes an attribute whose value + should be interpreted as if declared to be of type ID. + This name is reserved by virtue of its definition in the + xml:id specification. + + lang (as an attribute name): denotes an attribute whose value + is a language code for the natural language of the content of + any element; its value is inherited. This name is reserved + by virtue of its definition in the XML specification. + + space (as an attribute name): denotes an attribute whose + value is a keyword indicating what whitespace processing + discipline is intended for the content of the element; its + value is inherited. This name is reserved by virtue of its + definition in the XML specification. + + Father (in any context at all): denotes Jon Bosak, the chair of + the original XML Working Group. This name is reserved by + the following decision of the W3C XML Plenary and + XML Coordination groups: + + In appreciation for his vision, leadership and dedication + the W3C XML Plenary on this 10th day of February, 2000 + reserves for Jon Bosak in perpetuity the XML name + xml:Father + + + + + This schema defines attributes and an attribute group + suitable for use by + schemas wishing to allow xml:base, xml:lang, xml:space or xml:id + attributes on elements they define. + + To enable this, such a schema must import this schema + for the XML namespace, e.g. as follows: + <schema . . .> + . . . + <import namespace="http://www.w3.org/XML/1998/namespace" + schemaLocation="http://www.w3.org/2001/xml.xsd"/> + + Subsequently, qualified reference to any of the attributes + or the group defined below will have the desired effect, e.g. + + <type . . .> + . . . + <attributeGroup ref="xml:specialAttrs"/> + + will define a type which will schema-validate an instance + element with any of those attributes + + + + In keeping with the XML Schema WG's standard versioning + policy, this schema document will persist at + http://www.w3.org/2007/08/xml.xsd. + At the date of issue it can also be found at + http://www.w3.org/2001/xml.xsd. + The schema document at that URI may however change in the future, + in order to remain compatible with the latest version of XML Schema + itself, or with the XML namespace itself. In other words, if the XML + Schema or XML namespaces change, the version of this document at + http://www.w3.org/2001/xml.xsd will change + accordingly; the version at + http://www.w3.org/2007/08/xml.xsd will not change. + + + + + + Attempting to install the relevant ISO 2- and 3-letter + codes as the enumerated possible values is probably never + going to be a realistic possibility. See + RFC 3066 at http://www.ietf.org/rfc/rfc3066.txt and the IANA registry + at http://www.iana.org/assignments/lang-tag-apps.htm for + further information. + + The union allows for the 'un-declaration' of xml:lang with + the empty string. + + + + + + + + + + + + + + + + + + + + + + See http://www.w3.org/TR/xmlbase/ for + information about this attribute. + + + + + See http://www.w3.org/TR/xml-id/ for + information about this attribute. + + + + + + + + + + diff --git a/exposure-engine/gateway-common/src/test/java/com/alu/e3/data/topology/DummyTopologyClient.java b/exposure-engine/gateway-common/src/test/java/com/alu/e3/data/topology/DummyTopologyClient.java new file mode 100644 index 0000000..fc47890 --- /dev/null +++ b/exposure-engine/gateway-common/src/test/java/com/alu/e3/data/topology/DummyTopologyClient.java @@ -0,0 +1,261 @@ +/** + * Copyright © 2012 Alcatel-Lucent. + * + * See the NOTICE file distributed with this work for additional + * information regarding copyright ownership. + * Licensed to you 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 com.alu.e3.data.topology; + +import java.util.ArrayList; +import java.util.HashSet; +import java.util.Iterator; +import java.util.LinkedList; +import java.util.List; +import java.util.Set; + +import com.alu.e3.common.E3Constant; +import com.alu.e3.common.caching.ICacheManager; +import com.alu.e3.common.caching.IEntryListener; +import com.alu.e3.common.osgi.api.ITopologyClient; +import com.alu.e3.data.DataEntryEvent; +import com.alu.e3.data.model.Instance; + +// This file is copied from the topology project where it was used +// to test TopologyWatcher +public class DummyTopologyClient implements ITopologyClient { + + private List gateways = new LinkedList(); + private List managers = new LinkedList(); + private List tdrCollectors = new LinkedList(); + + public void setGateways(List gateways) { + this.gateways = gateways; + } + + public void setManagers(List managers) { + this.managers = managers; + } + + public void setTdrCollectors(List tdrCollectors) { + this.tdrCollectors = tdrCollectors; + } + + @Override + public void addInstance(Instance inst) { + if (inst.getType().equals(E3Constant.E3GATEWAY)) { + gateways.add(inst); + } + else if (inst.getType().equals(E3Constant.E3MANAGER)) { + managers.add(inst); + } + else if (inst.getType().equals(E3Constant.TDR_COLLECTOR)) { + tdrCollectors.add(inst); + } + + fireInstanceAdded(new InstanceEvent(inst)); + + ArrayList instanceList = new ArrayList(1); + instanceList.add(inst); + fireInstanceTypeAdded(new DataEntryEvent>("", instanceList)); + + } + + @Override + public boolean deleteInstance(Instance inst) { + List list = null; + + if (inst.getType().equals(E3Constant.E3GATEWAY)) { + list = gateways; + } + else if (inst.getType().equals(E3Constant.E3MANAGER)) { + list = managers; + } + else if (inst.getType().equals(E3Constant.TDR_COLLECTOR)) { + list = tdrCollectors; + } + + if (list == null) + return false; + + Iterator itr = list.iterator(); + while (itr.hasNext()) { + if (itr.next().getInternalIP().equals(inst.getInternalIP())) { + itr.remove(); + fireInstanceRemoved(new InstanceEvent(inst)); + ArrayList instanceList = new ArrayList(1); + instanceList.add(inst); + fireInstanceTypeRemoved(new DataEntryEvent>("", instanceList)); + return true; + } + } + return false; + + } + + private LinkedList listeners = new LinkedList(); + private LinkedList>> entryListeners = new LinkedList>>(); + + @Override + public void addInstanceListener(IInstanceListener listener) { + listeners.add(listener); + } + + @Override + public void removeInstanceListener(IInstanceListener listener) { + listeners.remove(listener); + } + + private void fireInstanceAdded(InstanceEvent event) { + for (IInstanceListener listener : listeners) { + listener.instanceAdded(event); + } + } + + + private void fireInstanceTypeAdded(DataEntryEvent> event) { + for (IEntryListener> listener : entryListeners) { + listener.entryAdded(event); + } + } + + private void fireInstanceTypeRemoved(DataEntryEvent> event) { + for (IEntryListener> listener : entryListeners) { + listener.entryRemoved(event); + } + } + + private void fireInstanceRemoved(InstanceEvent event) { + for (IInstanceListener listener : listeners) { + listener.instanceRemoved(event); + } + } + + @Override + public Set getAllExternalIPsOfType(String type) { + List instances; + + if (type.equals(E3Constant.E3GATEWAY)) { + instances = gateways; + } + else if (type.equals(E3Constant.E3MANAGER)) { + instances = managers; + } + else if (type.equals(E3Constant.TDR_COLLECTOR)) { + instances = tdrCollectors; + } + else { + return null; + } + + Set ips = new HashSet(); + + for (Instance instance : instances) { + ips.add(instance.getExternalIP()); + } + + return ips; + } + + @Override + public List getAllInstancesOfType(String type) { + if (type.equals(E3Constant.E3GATEWAY)) { + return gateways; + } + else if (type.equals(E3Constant.E3MANAGER)) { + return managers; + } + else if (type.equals(E3Constant.TDR_COLLECTOR)) { + return tdrCollectors; + } + return null; + } + + @Override + public String getMyArea() { + return "myArea"; + } + + @Override + public void setCacheManager(ICacheManager cacheManager) { + // must not be called + throw new RuntimeException(); + } + + @Override + public void addInstanceTypeListener(IEntryListener> listener) { + entryListeners.add (listener); + } + + @Override + public void removeInstanceTypeListener(IEntryListener> listener) { + // must not be called + throw new RuntimeException(); + } + + + @Override + public Set getAllInternalIPsOfType(String type) { + // must not be called + throw new RuntimeException(); + } + + @Override + public Set getExternalIPsOfType(String type, String area) { + // must not be called + throw new RuntimeException(); + } + + @Override + public Set getInternalIPsOfType(String type, String area) { + // must not be called + throw new RuntimeException(); + } + + @Override + public List getInstancesOfType(String type, String area) { + // must not be called + throw new RuntimeException(); + } + + @Override + public Set getAllAreas() { + // must not be called + throw new RuntimeException(); + } + + @Override + public Set getAllOtherAreas() { + // must not be called + throw new RuntimeException(); + } + + @Override + public void addAreas(Set areas) { + // TODO Auto-generated method stub + throw new RuntimeException(); + } + + @Override + public void setMyArea(String area) { + // TODO Auto-generated method stub + throw new RuntimeException(); + } + + @Override + public Instance whoAmI(String type) { + // TODO Auto-generated method stub + return null; + } +} \ No newline at end of file diff --git a/exposure-engine/gateway-common/src/test/java/com/alu/e3/data/topology/TDRCollectorInstanceWatcherTest.java b/exposure-engine/gateway-common/src/test/java/com/alu/e3/data/topology/TDRCollectorInstanceWatcherTest.java new file mode 100644 index 0000000..34d76cf --- /dev/null +++ b/exposure-engine/gateway-common/src/test/java/com/alu/e3/data/topology/TDRCollectorInstanceWatcherTest.java @@ -0,0 +1,229 @@ +/** + * Copyright © 2012 Alcatel-Lucent. + * + * See the NOTICE file distributed with this work for additional + * information regarding copyright ownership. + * Licensed to you 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 com.alu.e3.data.topology; + +import static org.junit.Assert.assertTrue; + +import java.io.File; +import java.io.FileNotFoundException; +import java.util.HashMap; +import java.util.Scanner; + +import org.junit.After; +import org.junit.Test; + +import com.alu.e3.common.E3Constant; +import com.alu.e3.common.osgi.api.ITopologyClient; +import com.alu.e3.data.model.Instance; +import com.alu.e3.data.model.SSHKey; + +public class TDRCollectorInstanceWatcherTest { + + private static final byte[] PRIVATE_KEY = {45, 45, 45, 45, 45, 66, 69, 71, 73, 78, 32, 68, 83, 65, 32, 80, 82, 73, 86, 65, 84, 69, 32, 75, 69, 89, 45, 45, 45, 45, 45, 10, 77, 73, 73, 66, 118, 65, 73, 66, 65, 65, 75, 66, 103, 81, 67, 49, 122, 115, 54, 107, 50, 120, 66, 68, 104, 117, 57, 78, 76, 53, 104, 86, 84, 68, 118, 76, 80, 50, 108, 51, 112, 107, 105, 87, 109, 115, 113, 110, 67, 69, 69, 84, 89, 80, 43, 87, 119, 116, 70, 74, 67, 79, 97, 52, 10, 107, 113, 50, 87, 70, 120, 75, 75, 106, 98, 108, 87, 81, 107, 118, 77, 97, 109, 69, 97, 119, 72, 107, 103, 105, 55, 66, 87, 86, 105, 120, 119, 82, 113, 105, 70, 67, 102, 86, 56, 109, 54, 99, 117, 80, 51, 99, 108, 114, 89, 47, 117, 87, 81, 48, 66, 100, 113, 47, 70, 52, 82, 83, 80, 10, 83, 98, 116, 112, 76, 69, 79, 77, 86, 51, 74, 90, 119, 52, 116, 68, 122, 109, 108, 119, 120, 78, 78, 66, 118, 67, 55, 87, 101, 52, 104, 105, 48, 48, 83, 108, 70, 56, 90, 53, 110, 99, 43, 85, 70, 57, 53, 103, 117, 49, 77, 110, 65, 70, 71, 76, 103, 81, 73, 86, 65, 78, 54, 70, 10, 119, 48, 82, 82, 51, 112, 49, 66, 104, 113, 113, 83, 118, 48, 75, 98, 82, 75, 78, 102, 70, 57, 65, 76, 65, 111, 71, 65, 65, 106, 55, 112, 55, 83, 78, 122, 70, 110, 97, 117, 108, 80, 55, 103, 111, 100, 73, 55, 47, 54, 73, 120, 111, 56, 101, 73, 81, 71, 66, 74, 104, 47, 79, 85, 10, 85, 54, 107, 80, 99, 51, 104, 114, 47, 122, 82, 70, 100, 120, 52, 110, 100, 118, 120, 110, 75, 79, 84, 86, 104, 101, 113, 99, 74, 54, 84, 113, 111, 43, 57, 89, 77, 51, 104, 49, 105, 111, 90, 105, 100, 90, 121, 49, 98, 118, 71, 75, 107, 122, 81, 106, 118, 118, 119, 111, 117, 89, 76, 83, 10, 116, 55, 74, 76, 114, 75, 70, 69, 52, 111, 76, 90, 85, 115, 106, 78, 107, 98, 112, 114, 76, 77, 119, 53, 98, 111, 78, 109, 51, 51, 76, 90, 103, 90, 84, 102, 80, 118, 121, 113, 84, 112, 52, 101, 75, 51, 65, 97, 49, 98, 90, 50, 111, 99, 114, 50, 84, 103, 112, 98, 78, 110, 71, 112, 10, 122, 106, 89, 57, 87, 88, 115, 67, 103, 89, 69, 65, 106, 57, 73, 119, 74, 73, 90, 113, 56, 106, 103, 112, 102, 103, 52, 99, 81, 71, 82, 67, 111, 88, 103, 115, 111, 107, 85, 53, 116, 107, 80, 77, 51, 66, 73, 53, 105, 56, 80, 121, 118, 101, 114, 118, 70, 55, 80, 75, 105, 85, 108, 90, 10, 52, 80, 111, 103, 105, 55, 73, 102, 100, 111, 88, 97, 118, 73, 52, 67, 81, 78, 103, 99, 43, 72, 116, 54, 48, 50, 97, 110, 82, 57, 79, 117, 102, 81, 112, 66, 110, 51, 106, 98, 69, 120, 101, 86, 52, 78, 103, 111, 84, 117, 88, 119, 78, 101, 80, 68, 52, 77, 118, 111, 112, 108, 80, 111, 10, 78, 89, 82, 114, 82, 75, 56, 121, 67, 106, 88, 116, 79, 88, 83, 101, 87, 67, 52, 108, 74, 103, 67, 108, 74, 109, 55, 83, 72, 82, 111, 73, 51, 76, 111, 49, 47, 112, 109, 77, 88, 51, 120, 75, 119, 83, 71, 115, 111, 119, 99, 76, 71, 112, 107, 67, 70, 81, 67, 49, 121, 73, 116, 102, 10, 113, 84, 82, 84, 56, 104, 48, 51, 89, 105, 78, 74, 79, 109, 121, 51, 122, 73, 105, 105, 88, 119, 61, 61, 10, 45, 45, 45, 45, 45, 69, 78, 68, 32, 68, 83, 65, 32, 80, 82, 73, 86, 65, 84, 69, 32, 75, 69, 89, 45, 45, 45, 45, 45, 10, 9, 9}; + private static final byte[] PUBLIC_KEY = {115, 115, 104, 45, 100, 115, 115, 32, 65, 65, 65, 65, 66, 51, 78, 122, 97, 67, 49, 107, 99, 51, 77, 65, 65, 65, 67, 66, 65, 76, 88, 79, 122, 113, 84, 98, 69, 69, 79, 71, 55, 48, 48, 118, 109, 70, 86, 77, 79, 56, 115, 47, 97, 88, 101, 109, 83, 74, 97, 97, 121, 113, 99, 73, 81, 82, 78, 103, 47, 53, 98, 67, 48, 85, 107, 73, 53, 114, 105, 83, 114, 90, 89, 88, 69, 111, 113, 78, 117, 86, 90, 67, 83, 56, 120, 113, 89, 82, 114, 65, 101, 83, 67, 76, 115, 70, 90, 87, 76, 72, 66, 71, 113, 73, 85, 74, 57, 88, 121, 98, 112, 121, 52, 47, 100, 121, 87, 116, 106, 43, 53, 90, 68, 81, 70, 50, 114, 56, 88, 104, 70, 73, 57, 74, 117, 50, 107, 115, 81, 52, 120, 88, 99, 108, 110, 68, 105, 48, 80, 79, 97, 88, 68, 69, 48, 48, 71, 56, 76, 116, 90, 55, 105, 71, 76, 84, 82, 75, 85, 88, 120, 110, 109, 100, 122, 53, 81, 88, 51, 109, 67, 55, 85, 121, 99, 65, 85, 89, 117, 66, 65, 65, 65, 65, 70, 81, 68, 101, 104, 99, 78, 69, 85, 100, 54, 100, 81, 89, 97, 113, 107, 114, 57, 67, 109, 48, 83, 106, 88, 120, 102, 81, 67, 119, 65, 65, 65, 73, 65, 67, 80, 117, 110, 116, 73, 51, 77, 87, 100, 113, 54, 85, 47, 117, 67, 104, 48, 106, 118, 47, 111, 106, 71, 106, 120, 52, 104, 65, 89, 69, 109, 72, 56, 53, 82, 84, 113, 81, 57, 122, 101, 71, 118, 47, 78, 69, 86, 51, 72, 105, 100, 50, 47, 71, 99, 111, 53, 78, 87, 70, 54, 112, 119, 110, 112, 79, 113, 106, 55, 49, 103, 122, 101, 72, 87, 75, 104, 109, 74, 49, 110, 76, 86, 117, 56, 89, 113, 84, 78, 67, 79, 43, 47, 67, 105, 53, 103, 116, 75, 51, 115, 107, 117, 115, 111, 85, 84, 105, 103, 116, 108, 83, 121, 77, 50, 82, 117, 109, 115, 115, 122, 68, 108, 117, 103, 50, 98, 102, 99, 116, 109, 66, 108, 78, 56, 43, 47, 75, 112, 79, 110, 104, 52, 114, 99, 66, 114, 86, 116, 110, 97, 104, 121, 118, 90, 79, 67, 108, 115, 50, 99, 97, 110, 79, 78, 106, 49, 90, 101, 119, 65, 65, 65, 73, 69, 65, 106, 57, 73, 119, 74, 73, 90, 113, 56, 106, 103, 112, 102, 103, 52, 99, 81, 71, 82, 67, 111, 88, 103, 115, 111, 107, 85, 53, 116, 107, 80, 77, 51, 66, 73, 53, 105, 56, 80, 121, 118, 101, 114, 118, 70, 55, 80, 75, 105, 85, 108, 90, 52, 80, 111, 103, 105, 55, 73, 102, 100, 111, 88, 97, 118, 73, 52, 67, 81, 78, 103, 99, 43, 72, 116, 54, 48, 50, 97, 110, 82, 57, 79, 117, 102, 81, 112, 66, 110, 51, 106, 98, 69, 120, 101, 86, 52, 78, 103, 111, 84, 117, 88, 119, 78, 101, 80, 68, 52, 77, 118, 111, 112, 108, 80, 111, 78, 89, 82, 114, 82, 75, 56, 121, 67, 106, 88, 116, 79, 88, 83, 101, 87, 67, 52, 108, 74, 103, 67, 108, 74, 109, 55, 83, 72, 82, 111, 73, 51, 76, 111, 49, 47, 112, 109, 77, 88, 51, 120, 75, 119, 83, 71, 115, 111, 119, 99, 76, 71, 112, 107, 61, 32, 114, 111, 111, 116, 64, 118, 109, 45, 111, 97, 112, 45, 48}; + private static final String USER_NAME = "root"; + private static final String KEY_NAME = "test_key_name"; + private static final String CONFIG_NAME = "test_tdr_config"; + private static final String WRITE_LOCATION = "."; + + + private TDRCollectorInstanceWatcher tdrCollectorInstanceWatcher; + private ITopologyClient topologyClient; + + private Instance createInstance(String type, String intIP, String extIP, SSHKey key) { + Instance instance = new Instance(); + + instance.setType(type); + instance.setArea("myArea"); + instance.setInternalIP(intIP); + instance.setExternalIP(extIP); + instance.setSSHKey(key); + instance.setUser(USER_NAME); + + return instance; + } + + private void addInstance(Instance instance) { + topologyClient.addInstance(instance); + } + + private void deleteInstance(Instance instance) { + topologyClient.deleteInstance(instance); + } + + private void initializeTestSetup(int gatewayCount, int managerCount, int tdrCollectorCount, boolean useKey) { + + File oldConfig = new File(new File(WRITE_LOCATION), CONFIG_NAME); + File oldKey = new File(new File(WRITE_LOCATION), KEY_NAME); + if (oldConfig.exists()) oldConfig.delete(); + if (oldKey.exists()) oldKey.delete(); + + tdrCollectorInstanceWatcher = new TDRCollectorInstanceWatcher(); + tdrCollectorInstanceWatcher.setConfigName(CONFIG_NAME); + tdrCollectorInstanceWatcher.setKeyName(KEY_NAME); + tdrCollectorInstanceWatcher.setWriteLocation(WRITE_LOCATION); + + SSHKey key = null; + if (useKey) { + key = new SSHKey(KEY_NAME, PRIVATE_KEY, PUBLIC_KEY); + } + + topologyClient = new DummyTopologyClient(); + tdrCollectorInstanceWatcher.setTopologyClient(topologyClient); + + for (int i = 0; i < gatewayCount; i++) { + addInstance(createInstance(E3Constant.E3GATEWAY, "1.1.1." + i, "2.1.1." + i, null)); + } + for (int i = 0; i < managerCount; i++) { + addInstance(createInstance(E3Constant.E3MANAGER, "1.1.2." + i, "2.1.2." + i, key)); + } + for (int i = 0; i < tdrCollectorCount; i++) { + addInstance(createInstance(E3Constant.TDR_COLLECTOR, "1.1.3." + i, "2.1.3." + i, null)); + } + } + + private boolean verifyKeyExists() { + return new File(new File(WRITE_LOCATION), KEY_NAME).exists(); + } + + private boolean verifyConfigExists() { + return new File(new File(WRITE_LOCATION), CONFIG_NAME).exists(); + } + + // when verifying the correct collectors, it must be so that the current + // ips go from 0 to (correctCollectorCount-1) + private boolean verifyValidConfig(int correctCollectorCount) { + File configFile = new File(new File(WRITE_LOCATION), CONFIG_NAME); + if (!configFile.exists()) return false; + Scanner scan; + try { + scan = new Scanner(configFile); + } catch (FileNotFoundException e) { + return false; + } + try { + boolean hasKey = false; + boolean hasUser = false; + boolean hasCollectorCount = false; + HashMap collectorIndices = new HashMap(); + int collectorCount = 0; + + while (scan.hasNext()) { + String line = scan.nextLine(); + if (line.equals(TDRCollectorInstanceWatcher.KEY_CFG + + TDRCollectorInstanceWatcher.CONFIG_KEYVAL_CHAR + WRITE_LOCATION + "/" + KEY_NAME)) { + hasKey = true; + } else if (line.equals(TDRCollectorInstanceWatcher.USER_CFG + + TDRCollectorInstanceWatcher.CONFIG_KEYVAL_CHAR + USER_NAME)) { + hasUser = true; + } else if (line.startsWith(TDRCollectorInstanceWatcher.HOST_CFG + + TDRCollectorInstanceWatcher.CONFIG_KEYVAL_CHAR + "1.1.3.")) { + collectorCount++; + hasCollectorCount = collectorCount == correctCollectorCount; + collectorIndices.put( + line.replace(TDRCollectorInstanceWatcher.HOST_CFG + + TDRCollectorInstanceWatcher.CONFIG_KEYVAL_CHAR + "1.1.3.", ""), + true); + } + } + if (!hasKey || !hasUser || !hasCollectorCount) return false; + + for (int i = 0; i < correctCollectorCount; i++) { + if (!collectorIndices.get("" + i)) return false; + } + } finally { + scan.close(); + } + + return true; + } + + @Test + public void testInitialCreation() { + initializeTestSetup(1, 1, 1, true); + tdrCollectorInstanceWatcher.init(); + assertTrue("Key file was not created.", verifyKeyExists()); + assertTrue("Config file was not created.", verifyConfigExists()); + assertTrue("Config file was not correctly built.", verifyValidConfig(1)); + } + + + @Test + public void testInitialCreationWithNoTdrCollectors() { + initializeTestSetup(1, 1, 0, false); + tdrCollectorInstanceWatcher.init(); + assertTrue("Key file was created.", !verifyKeyExists()); + assertTrue("Config file was created.", !verifyConfigExists()); + } + + @Test + public void testNonTdrCollectorInstances() { + initializeTestSetup(1, 1, 1, true); + tdrCollectorInstanceWatcher.init(); + assertTrue("Key file was not created.", verifyKeyExists()); + assertTrue("Config file was not created.", verifyConfigExists()); + assertTrue("Config file was not correctly built.", verifyValidConfig(1)); + Instance gate = createInstance(E3Constant.E3GATEWAY, "1.1.1.1", "2.1.1.1", null); + Instance manager = createInstance(E3Constant.E3MANAGER, "1.1.2.1", "2.1.2.1", null); + addInstance(gate); + addInstance(manager); + assertTrue("Key file did not remain after adding non-collection instances.", verifyKeyExists()); + assertTrue("Config file did not remain after adding non-collection instances.", verifyConfigExists()); + assertTrue("Config file did not remain correctly built after adding non-collection instances.", verifyValidConfig(1)); + deleteInstance(gate); + deleteInstance(manager); + assertTrue("Key file did not remain after removing non-collection instances.", verifyKeyExists()); + assertTrue("Config file did not remain after removing non-collection instances.", verifyConfigExists()); + assertTrue("Config file did not remain correctly built after removing non-collection instances.", verifyValidConfig(1)); + } + + @Test + public void testTdrCollectorInstances() { + initializeTestSetup(1, 1, 2, true); + tdrCollectorInstanceWatcher.init(); + + assertTrue("Key file was not created.", verifyKeyExists()); + assertTrue("Config file was not created.", verifyConfigExists()); + assertTrue("Config file was not correctly built.", verifyValidConfig(2)); + Instance inst1 = createInstance(E3Constant.TDR_COLLECTOR, "1.1.3.2", "2.1.3.2", null); + Instance inst2 = createInstance(E3Constant.TDR_COLLECTOR, "1.1.3.3", "2.1.3.3", null); + addInstance(inst1); + addInstance(inst2); + assertTrue("Key file did not remain after adding collection instances.", verifyKeyExists()); + assertTrue("Config file did not remain after adding collection instances.", verifyConfigExists()); + assertTrue("Config file did not remain correctly built after adding collection instances.", verifyValidConfig(4)); + deleteInstance(inst2); + assertTrue("Key file did not remain after removing collection instance.", verifyKeyExists()); + assertTrue("Config file did not remain after removing collection instance.", verifyConfigExists()); + assertTrue("Config file did not remain correctly built after removing collection instance.", verifyValidConfig(3)); + } + + @After + public void tearDown() { + File oldKey = new File(new File(WRITE_LOCATION), KEY_NAME); + File oldConfig = new File(new File(WRITE_LOCATION), CONFIG_NAME); + if (oldKey.exists()) { + oldKey.delete(); + } + if (oldConfig.exists()) { + oldConfig.delete(); + } + } + +} diff --git a/exposure-engine/gateway-common/src/test/java/com/alu/e3/gateway/camel/MockExchange.java b/exposure-engine/gateway-common/src/test/java/com/alu/e3/gateway/camel/MockExchange.java new file mode 100644 index 0000000..e65e9c5 --- /dev/null +++ b/exposure-engine/gateway-common/src/test/java/com/alu/e3/gateway/camel/MockExchange.java @@ -0,0 +1,480 @@ +/** + * Copyright © 2012 Alcatel-Lucent. + * + * See the NOTICE file distributed with this work for additional + * information regarding copyright ownership. + * Licensed to you 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 com.alu.e3.gateway.camel; + +import java.util.HashMap; +import java.util.List; +import java.util.Map; +import java.util.Set; + +import javax.activation.DataHandler; + +import org.apache.camel.CamelContext; +import org.apache.camel.Endpoint; +import org.apache.camel.Exchange; +import org.apache.camel.ExchangePattern; +import org.apache.camel.InvalidPayloadException; +import org.apache.camel.Message; +import org.apache.camel.spi.Synchronization; +import org.apache.camel.spi.UnitOfWork; + +/** + * Built to support the properties management stuff to test the TDRDataService + * + */ +public class MockExchange implements Exchange { + private Map properties = new HashMap(); + + private Message in = new Message(){ + private Map headers = new HashMap(); + @Override + public String getMessageId() { + // TODO Auto-generated method stub + return null; + } + + @Override + public void setMessageId(String messageId) { + // TODO Auto-generated method stub + + } + + @Override + public Exchange getExchange() { + // TODO Auto-generated method stub + return null; + } + + @Override + public boolean isFault() { + // TODO Auto-generated method stub + return false; + } + + @Override + public void setFault(boolean fault) { + // TODO Auto-generated method stub + + } + + @Override + public Object getHeader(String name) { + return headers.get(name); + } + + @Override + public Object getHeader(String name, Object defaultValue) { + // TODO Auto-generated method stub + return null; + } + + @SuppressWarnings("unchecked") + @Override + public T getHeader(String name, Class type) { + return (T) headers.get(name); + } + + @SuppressWarnings("unchecked") + @Override + public T getHeader(String name, Object defaultValue, Class type) { + T value = getHeader(name, type); + if(value == null) + value = (T) defaultValue; + + return value; + } + + @Override + public void setHeader(String name, Object value) { + headers.put(name, value); + } + + @Override + public Object removeHeader(String name) { + Object result = headers.remove(name); + return result; + } + + @Override + public boolean removeHeaders(String pattern) { + // TODO Auto-generated method stub + return false; + } + + @Override + public boolean removeHeaders(String pattern, + String... excludePatterns) { + // TODO Auto-generated method stub + return false; + } + + @Override + public Map getHeaders() { + // TODO Auto-generated method stub + return null; + } + + @Override + public void setHeaders(Map headers) { + // TODO Auto-generated method stub + + } + + @Override + public boolean hasHeaders() { + // TODO Auto-generated method stub + return false; + } + + @Override + public Object getBody() { + // TODO Auto-generated method stub + return null; + } + + @Override + public Object getMandatoryBody() throws InvalidPayloadException { + // TODO Auto-generated method stub + return null; + } + + @Override + public T getBody(Class type) { + // TODO Auto-generated method stub + return null; + } + + @Override + public T getMandatoryBody(Class type) + throws InvalidPayloadException { + // TODO Auto-generated method stub + return null; + } + + @Override + public void setBody(Object body) { + // TODO Auto-generated method stub + + } + + @Override + public void setBody(Object body, Class type) { + // TODO Auto-generated method stub + + } + + @Override + public Message copy() { + // TODO Auto-generated method stub + return null; + } + + @Override + public void copyFrom(Message message) { + // TODO Auto-generated method stub + + } + + @Override + public DataHandler getAttachment(String id) { + // TODO Auto-generated method stub + return null; + } + + @Override + public Set getAttachmentNames() { + // TODO Auto-generated method stub + return null; + } + + @Override + public void removeAttachment(String id) { + // TODO Auto-generated method stub + + } + + @Override + public void addAttachment(String id, DataHandler content) { + // TODO Auto-generated method stub + + } + + @Override + public Map getAttachments() { + // TODO Auto-generated method stub + return null; + } + + @Override + public void setAttachments(Map attachments) { + // TODO Auto-generated method stub + + } + + @Override + public boolean hasAttachments() { + // TODO Auto-generated method stub + return false; + } + + @Override + public String createExchangeId() { + // TODO Auto-generated method stub + return null; + } + + }; + + @Override + public ExchangePattern getPattern() { + // TODO Auto-generated method stub + return null; + } + + @Override + public void setPattern(ExchangePattern pattern) { + // TODO Auto-generated method stub + + } + + @Override + public Object getProperty(String name) { + return properties.get(name); + } + + @Override + public Object getProperty(String name, Object defaultValue) { + Object ob = properties.get(name); + if(ob == null){ + ob = defaultValue; + } + return ob; + } + + @SuppressWarnings("unchecked") + @Override + public T getProperty(String name, Class type) { + return (T) properties.get(name); + } + + @SuppressWarnings("unchecked") + @Override + public T getProperty(String name, Object defaultValue, Class type) { + T ob = (T) properties.get(name); + if(ob == null){ + ob = (T) defaultValue; + } + return ob; + } + + @Override + public void setProperty(String name, Object value) { + properties.put(name, value); + } + + @Override + public Object removeProperty(String name) { + // TODO Auto-generated method stub + return null; + } + + @Override + public Map getProperties() { + return properties; + } + + @Override + public boolean hasProperties() { + // TODO Auto-generated method stub + return false; + } + + @Override + public Message getIn() { + return in; + } + + @Override + public T getIn(Class type) { + // TODO Auto-generated method stub + return null; + } + + @Override + public void setIn(Message in) { + // TODO Auto-generated method stub + + } + + @Override + public Message getOut() { + // TODO Auto-generated method stub + return null; + } + + @Override + public T getOut(Class type) { + // TODO Auto-generated method stub + return null; + } + + @Override + public boolean hasOut() { + // TODO Auto-generated method stub + return false; + } + + @Override + public void setOut(Message out) { + // TODO Auto-generated method stub + + } + + @Override + public Exception getException() { + // TODO Auto-generated method stub + return null; + } + + @Override + public T getException(Class type) { + // TODO Auto-generated method stub + return null; + } + + + @Override + public void setException(Throwable t) { + // TODO Auto-generated method stub + + } + + + @Override + public boolean isFailed() { + // TODO Auto-generated method stub + return false; + } + + + @Override + public boolean isTransacted() { + // TODO Auto-generated method stub + return false; + } + + + @Override + public boolean isRollbackOnly() { + // TODO Auto-generated method stub + return false; + } + + + @Override + public CamelContext getContext() { + // TODO Auto-generated method stub + return null; + } + + + @Override + public Exchange copy() { + // TODO Auto-generated method stub + return null; + } + + + @Override + public Endpoint getFromEndpoint() { + // TODO Auto-generated method stub + return null; + } + + + @Override + public void setFromEndpoint(Endpoint fromEndpoint) { + // TODO Auto-generated method stub + + } + + + @Override + public String getFromRouteId() { + // TODO Auto-generated method stub + return null; + } + + + @Override + public void setFromRouteId(String fromRouteId) { + // TODO Auto-generated method stub + + } + + + @Override + public UnitOfWork getUnitOfWork() { + // TODO Auto-generated method stub + return null; + } + + + @Override + public void setUnitOfWork(UnitOfWork unitOfWork) { + // TODO Auto-generated method stub + + } + + + @Override + public String getExchangeId() { + // TODO Auto-generated method stub + return null; + } + + + @Override + public void setExchangeId(String id) { + // TODO Auto-generated method stub + + } + + + @Override + public void addOnCompletion(Synchronization onCompletion) { + // TODO Auto-generated method stub + + } + + + @Override + public void handoverCompletions(Exchange target) { + // TODO Auto-generated method stub + + } + + + @Override + public List handoverCompletions() { + // TODO Auto-generated method stub + return null; + } + +} diff --git a/exposure-engine/gateway-common/src/test/java/com/alu/e3/gateway/camel/processor/HeaderTransProcessorsTest.java b/exposure-engine/gateway-common/src/test/java/com/alu/e3/gateway/camel/processor/HeaderTransProcessorsTest.java new file mode 100644 index 0000000..c79b69c --- /dev/null +++ b/exposure-engine/gateway-common/src/test/java/com/alu/e3/gateway/camel/processor/HeaderTransProcessorsTest.java @@ -0,0 +1,284 @@ +/** + * Copyright © 2012 Alcatel-Lucent. + * + * See the NOTICE file distributed with this work for additional + * information regarding copyright ownership. + * Licensed to you 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 com.alu.e3.gateway.camel.processor; + +import static org.junit.Assert.assertEquals; +import static org.junit.Assert.assertNotNull; +import static org.junit.Assert.assertNull; + +import java.util.ArrayList; +import java.util.HashMap; +import java.util.List; +import java.util.Map; + +import org.apache.camel.Exchange; +import org.apache.camel.Processor; +import org.junit.Before; +import org.junit.Test; + +import com.alu.e3.common.camel.AuthIdentity; +import com.alu.e3.common.camel.ExchangeConstantKeys; +import com.alu.e3.data.model.Api; +import com.alu.e3.data.model.Auth; +import com.alu.e3.data.model.Policy; +import com.alu.e3.data.model.enumeration.HeaderTransformationAction; +import com.alu.e3.data.model.enumeration.HeaderTransformationType; +import com.alu.e3.data.model.sub.HeaderTransformation; +import com.alu.e3.gateway.common.camel.processor.HeaderTransRequestProcessor; +import com.alu.e3.gateway.common.camel.processor.HeaderTransResponseProcessor; + +public class HeaderTransProcessorsTest { + + Exchange exchange; + Auth auth; + Api api; + Policy policy1; + Processor requestProcessor; + Processor responseProcessor; + + /** + * Basic test to make sure that all types of header transformations are applied + * correctly from an Api. + * @throws Exception + */ + @Test + public void testHeaderTransApi() throws Exception{ + api.setHeaderTransformation(getBasicTrans()); + + testPrerequisites(); + requestProcessor.process(exchange); + testPostRequestProcessor(); + responseProcessor.process(exchange); + testPostResponseProcessor(); + } + + @Test + public void testHeaderTransAuth() throws Exception{ + auth.setHeaderTransformation(getBasicTrans()); + + testPrerequisites(); + requestProcessor.process(exchange); + testPostRequestProcessor(); + responseProcessor.process(exchange); + testPostResponseProcessor(); + } + + @Test + public void testHeaderTransPolicy() throws Exception{ + policy1.setHeaderTransformation(getBasicTrans()); + + testPrerequisites(); + requestProcessor.process(exchange); + testPostRequestProcessor(); + responseProcessor.process(exchange); + testPostResponseProcessor(); + } + + + /** + * Helper method + */ + private void testPostResponseProcessor() { + assertNotNull(exchange.getIn().getHeader("HEADER-VALUE")); + assertEquals("RESPONSE-VALUE", exchange.getIn().getHeader("HEADER-VALUE")); + assertNotNull(exchange.getIn().getHeader("HEADER-PROP")); + assertEquals("5678", exchange.getIn().getHeader("HEADER-PROP")); + + // REMOVE1 and REMOVE2 should be gone + assertNull(exchange.getIn().getHeader("HEADER-REMOVE1")); + assertNull(exchange.getIn().getHeader("HEADER-REMOVE2")); + + // Should always be null + assertNull(exchange.getIn().getHeader("HEADER-PROP-NULL")); + assertNotNull(exchange.getIn().getHeader("HEADER-PREEXIST")); + assertEquals("BLARG", exchange.getIn().getHeader("HEADER-PREEXIST")); + + assertNull(exchange.getIn().getHeader("HEADER-EMPTY")); + assertNull(exchange.getIn().getHeader("HEADER-EMPTY2")); + + assertNull(exchange.getIn().getHeader("HEADER-REMOVE-NULL")); + assertNull(exchange.getIn().getHeader("HEADER-REMOVE-NULL2")); + } + + + /** + * Helper method + */ + private void testPostRequestProcessor() { + assertNotNull(exchange.getIn().getHeader("HEADER-VALUE")); + assertEquals("REQUEST-VALUE", exchange.getIn().getHeader("HEADER-VALUE")); + assertNotNull(exchange.getIn().getHeader("HEADER-PROP")); + assertEquals("1234", exchange.getIn().getHeader("HEADER-PROP")); + + // REMOVE1 should be gone but REMOVE2 should still be there + assertNull(exchange.getIn().getHeader("HEADER-REMOVE1")); + assertNotNull(exchange.getIn().getHeader("HEADER-REMOVE2")); + + // Should always be null + assertNull(exchange.getIn().getHeader("HEADER-PROP-NULL")); + assertNotNull(exchange.getIn().getHeader("HEADER-PREEXIST")); + assertEquals("BLARG", exchange.getIn().getHeader("HEADER-PREEXIST")); + + assertNull(exchange.getIn().getHeader("HEADER-EMPTY")); + assertNull(exchange.getIn().getHeader("HEADER-EMPTY2")); + + assertNull(exchange.getIn().getHeader("HEADER-REMOVE-NULL")); + assertNull(exchange.getIn().getHeader("HEADER-REMOVE-NULL2")); + + } + + + /** + * Helper method + */ + private void testPrerequisites() { + // Make sure the added headers are not there to start with + assertNull(exchange.getIn().getHeader("HEADER-VALUE")); + assertNull(exchange.getIn().getHeader("HEADER-PROP")); + assertNull(exchange.getIn().getHeader("HEADER-PROP-NULL")); + // Make sure these headers are there to start + assertNotNull(exchange.getIn().getHeader("HEADER-REMOVE1")); + assertNotNull(exchange.getIn().getHeader("HEADER-REMOVE2")); + assertNull(exchange.getIn().getHeader("HEADER-EMPTY")); + assertNull(exchange.getIn().getHeader("HEADER-EMPTY2")); + assertNull(exchange.getIn().getHeader("HEADER-REMOVE-NULL")); + assertNull(exchange.getIn().getHeader("HEADER-REMOVE-NULL2")); + } + + + + /** + * Setup some properties, headers, exchange and the processors + */ + @Before + public void setup(){ + exchange = TestHelper.setupExchange(); + requestProcessor = new HeaderTransRequestProcessor(); + responseProcessor = new HeaderTransResponseProcessor(); + + AuthIdentity id = (AuthIdentity) exchange.getProperty(ExchangeConstantKeys.E3_AUTH_IDENTITY.toString()); + auth = id.getAuth(); + api = id.getApi(); + policy1 = id.getCallDescriptors().get(0).getPolicy(); + + // Setup some properties to reference + Map properties = new HashMap(); + properties.put("PROPERTY1","1234"); + properties.put("PROPERTY2","5678"); + exchange.setProperty(ExchangeConstantKeys.E3_MODEL_PROPERTIES.toString(), properties); + + // Add some pre built headers to mess with + exchange.getIn().setHeader("HEADER-REMOVE1", "BLARG"); + exchange.getIn().setHeader("HEADER-REMOVE2", "BLARG"); + exchange.getIn().setHeader("HEADER-PREEXIST", "BLARG"); + + + } + + /** + * Setup a bunch of header transformations for use. + * @return + */ + private List getBasicTrans(){ + List list = new ArrayList(); + + // Create a value, property and remove transformation for request + HeaderTransformation ht = new HeaderTransformation(); + ht.setAction(HeaderTransformationAction.ADD); + ht.setName("HEADER-VALUE"); + ht.setValue("REQUEST-VALUE"); + ht.setType(HeaderTransformationType.REQUEST); + list.add(ht); + + ht = new HeaderTransformation(); + ht.setAction(HeaderTransformationAction.ADD); + ht.setName("HEADER-PROP"); + ht.setProperty("PROPERTY1"); + ht.setType(HeaderTransformationType.REQUEST); + list.add(ht); + + ht = new HeaderTransformation(); + ht.setAction(HeaderTransformationAction.ADD); + ht.setName("HEADER-PROP-NULL"); + ht.setProperty("PROPERTY3"); + ht.setType(HeaderTransformationType.REQUEST); + list.add(ht); + + ht = new HeaderTransformation(); + ht.setAction(HeaderTransformationAction.ADD); + ht.setName("HEADER-EMPTY"); + ht.setType(HeaderTransformationType.REQUEST); + list.add(ht); + + ht = new HeaderTransformation(); + ht.setAction(HeaderTransformationAction.REMOVE); + ht.setName("HEADER-REMOVE1"); + ht.setType(HeaderTransformationType.REQUEST); + list.add(ht); + + ht = new HeaderTransformation(); + ht.setAction(HeaderTransformationAction.REMOVE); + ht.setName("HEADER-REMOVE-NULL"); + ht.setType(HeaderTransformationType.REQUEST); + list.add(ht); + + // Create a value, property and remove transformation for the response + ht = new HeaderTransformation(); + ht.setAction(HeaderTransformationAction.ADD); + ht.setName("HEADER-VALUE"); + ht.setValue("RESPONSE-VALUE"); + ht.setType(HeaderTransformationType.RESPONSE); + list.add(ht); + + ht = new HeaderTransformation(); + ht.setAction(HeaderTransformationAction.ADD); + ht.setName("HEADER-PROP"); + ht.setProperty("PROPERTY2"); + ht.setType(HeaderTransformationType.RESPONSE); + list.add(ht); + + ht = new HeaderTransformation(); + ht.setAction(HeaderTransformationAction.REMOVE); + ht.setName("HEADER-REMOVE2"); + ht.setType(HeaderTransformationType.RESPONSE); + list.add(ht); + + ht = new HeaderTransformation(); + ht.setAction(HeaderTransformationAction.REMOVE); + ht.setName("HEADER-REMOVE-NULL2"); + ht.setType(HeaderTransformationType.RESPONSE); + list.add(ht); + + ht = new HeaderTransformation(); + ht.setAction(HeaderTransformationAction.ADD); + ht.setName("HEADER-PROP-NULL"); + ht.setProperty("PROPERTY3"); + ht.setType(HeaderTransformationType.RESPONSE); + list.add(ht); + + ht = new HeaderTransformation(); + ht.setAction(HeaderTransformationAction.ADD); + ht.setName("HEADER-EMPTY2"); + ht.setType(HeaderTransformationType.RESPONSE); + list.add(ht); + + return list; + } + +} diff --git a/exposure-engine/gateway-common/src/test/java/com/alu/e3/gateway/camel/processor/HttpMethodProcessorTest.java b/exposure-engine/gateway-common/src/test/java/com/alu/e3/gateway/camel/processor/HttpMethodProcessorTest.java new file mode 100644 index 0000000..6d4a3df --- /dev/null +++ b/exposure-engine/gateway-common/src/test/java/com/alu/e3/gateway/camel/processor/HttpMethodProcessorTest.java @@ -0,0 +1,118 @@ +/** + * Copyright © 2012 Alcatel-Lucent. + * + * See the NOTICE file distributed with this work for additional + * information regarding copyright ownership. + * Licensed to you 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 com.alu.e3.gateway.camel.processor; + +import static org.junit.Assert.assertEquals; +import static org.junit.Assert.fail; + +import java.util.ArrayList; +import java.util.Arrays; +import java.util.Collection; +import java.util.List; + +import org.apache.camel.Exchange; +import org.apache.commons.lang.StringUtils; +import org.junit.Before; +import org.junit.Test; + +import com.alu.e3.data.model.Api; +import com.alu.e3.gateway.common.camel.exception.GatewayException; +import com.alu.e3.gateway.common.camel.exception.GatewayExceptionCode; +import com.alu.e3.gateway.common.camel.processor.HttpMethodProcessor; + +public class HttpMethodProcessorTest { + + static String[] ALLOWED_ARR = {"yes","good","POSITIVE","SuperSweet","All","gOOd","1234"}; + static String[] NOTALLOWED_ARR = {"no","NotAllowed","BAD","terrible","CRAZY","paTHEtic","6789"}; + + static List ALLOWED; + static List NOTALLOWED; + + Exchange exchange; + + HttpMethodProcessor proc; + + Api api; + + @Before + public void setup(){ + proc = new HttpMethodProcessor(); + + ALLOWED = Arrays.asList(ALLOWED_ARR); + NOTALLOWED = Arrays.asList(NOTALLOWED_ARR); + } + + @Test + public void testPermutations() throws Exception{ + proc.setAllowedHttpMethods(StringUtils.join(ALLOWED.iterator(), ",")); + + checkAllowedMethods(ALLOWED); + + checkNotAllowedMethods(NOTALLOWED); + } + + @Test + public void testNullEdgeCases() throws Exception { + //empty list implies all are allowed + proc.setAllowedHttpMethods(""); + checkAllowedMethods(ALLOWED); + checkAllowedMethods(NOTALLOWED); + + //empty list implies all are allowed + proc.setAllowedHttpMethods(null); + checkAllowedMethods(ALLOWED); + checkAllowedMethods(NOTALLOWED); + + //check that when too many commas are added, they are ignored + List extracommas = new ArrayList(); + extracommas.addAll(ALLOWED); + extracommas.add(0, ","); + extracommas.add(2,",,"); + extracommas.add(",,"); + proc.setAllowedHttpMethods(StringUtils.join(extracommas.iterator(), ",")); + checkAllowedMethods(ALLOWED); + checkNotAllowedMethods(NOTALLOWED); + checkNotAllowedMethods(Arrays.asList("", ",", ",,", null)); + + + } + + private void checkAllowedMethods(Collection methods) throws Exception { + for(String method : methods){ + exchange = TestHelper.setupExchange(); + exchange.getIn().setHeader(Exchange.HTTP_METHOD, method); + proc.process(exchange); + //no exception means OK + } + } + + private void checkNotAllowedMethods(Collection methods) throws Exception { + for(String method : methods){ + exchange = TestHelper.setupExchange(); + exchange.getIn().setHeader(Exchange.HTTP_METHOD, method); + try{ + proc.process(exchange); + fail("Should not succeed"); + }catch(GatewayException e){ + assertEquals("Exception should be an HttpMethod error", GatewayExceptionCode.HTTP_METHOD, e.getCode()); + } + } + } + +} diff --git a/exposure-engine/gateway-common/src/test/java/com/alu/e3/gateway/camel/processor/PropertyExtractProcessorTest.java b/exposure-engine/gateway-common/src/test/java/com/alu/e3/gateway/camel/processor/PropertyExtractProcessorTest.java new file mode 100644 index 0000000..9680955 --- /dev/null +++ b/exposure-engine/gateway-common/src/test/java/com/alu/e3/gateway/camel/processor/PropertyExtractProcessorTest.java @@ -0,0 +1,150 @@ +/** + * Copyright © 2012 Alcatel-Lucent. + * + * See the NOTICE file distributed with this work for additional + * information regarding copyright ownership. + * Licensed to you 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 com.alu.e3.gateway.camel.processor; + +import static org.junit.Assert.assertEquals; +import static org.junit.Assert.assertTrue; + +import java.util.HashMap; +import java.util.Map; + +import org.apache.camel.Exchange; +import org.apache.camel.Processor; +import org.apache.camel.impl.DefaultCamelContext; +import org.apache.camel.impl.DefaultExchange; +import org.junit.Before; +import org.junit.Test; + +import com.alu.e3.common.camel.AuthIdentity; +import com.alu.e3.common.camel.ExchangeConstantKeys; +import com.alu.e3.data.model.Api; +import com.alu.e3.data.model.Auth; +import com.alu.e3.data.model.CallDescriptor; +import com.alu.e3.data.model.Policy; +import com.alu.e3.gateway.common.camel.processor.PropertyExtractionProcessor; + +public class PropertyExtractProcessorTest { + + Exchange exchange; + Auth auth; + Api api; + Policy policy1; + AuthIdentity id; + Processor processor; + + @Test + public void testAllEmpty() throws Exception{ + processor.process(exchange); + } + + @Test + public void testNullAuth() throws Exception{ + id.setAuth(null); + processor.process(exchange); + } + + @SuppressWarnings("unchecked") + @Test + public void testBasic() throws Exception{ + Map authProps = new HashMap(); + authProps.put("auth_1", "auth_1_val"); + auth.setProperties(authProps); + + Map apiProps = new HashMap(); + apiProps.put("api_1", "api_1_val"); + api.setProperties(apiProps); + + Map policyProps = new HashMap(); + policyProps.put("policy_1", "policy_1_val"); + policy1.setProperties(policyProps); + + processor.process(exchange); + + // get the properties out of the exchange + Map props = (Map) exchange.getProperty(ExchangeConstantKeys.E3_MODEL_PROPERTIES.toString()); + + assertTrue(props.containsKey("auth_1")); + assertEquals("auth_1_val", props.get("auth_1")); + + assertTrue(props.containsKey("api_1")); + assertEquals("api_1_val", props.get("api_1")); + + assertTrue(props.containsKey("policy_1")); + assertEquals("policy_1_val", props.get("policy_1")); + + } + + /** + * Testing that conflicts are resolved appropriately + * auth > policy > api + * policy >= policy // Conflicts are resolved in an undefined way + * @throws Exception + */ + @SuppressWarnings("unchecked") + @Test + public void testConflicts() throws Exception{ + Map authProps = new HashMap(); + authProps.put("a", "auth"); + auth.setProperties(authProps); + + Map apiProps = new HashMap(); + apiProps.put("a", "api"); + apiProps.put("b", "api"); + api.setProperties(apiProps); + + Map policyProps = new HashMap(); + policyProps.put("a", "policy"); + policyProps.put("b", "policy"); + policy1.setProperties(policyProps); + + processor.process(exchange); + + // get the properties out of the exchange + Map props = (Map) exchange.getProperty(ExchangeConstantKeys.E3_MODEL_PROPERTIES.toString()); + + assertTrue(props.containsKey("a")); + assertEquals("auth", props.get("a")); + + assertTrue(props.containsKey("b")); + assertEquals("policy", props.get("b")); + + } + + + + + + @Before + public void setup(){ + exchange = new DefaultExchange(new DefaultCamelContext()); + processor = new PropertyExtractionProcessor(); + + id = new AuthIdentity(); + api = new Api(); + policy1 = new Policy(); + auth = new Auth(); + CallDescriptor cd = new CallDescriptor(policy1, 0, 0); + + id.setApi(api); + id.setAuth(auth); + id.getCallDescriptors().add(cd); + + exchange.setProperty(ExchangeConstantKeys.E3_AUTH_IDENTITY.toString(), id); + } +} diff --git a/exposure-engine/gateway-common/src/test/java/com/alu/e3/gateway/camel/processor/ProvisionedTDRProcessorTest.java b/exposure-engine/gateway-common/src/test/java/com/alu/e3/gateway/camel/processor/ProvisionedTDRProcessorTest.java new file mode 100644 index 0000000..7cf5b35 --- /dev/null +++ b/exposure-engine/gateway-common/src/test/java/com/alu/e3/gateway/camel/processor/ProvisionedTDRProcessorTest.java @@ -0,0 +1,423 @@ +/** + * Copyright © 2012 Alcatel-Lucent. + * + * See the NOTICE file distributed with this work for additional + * information regarding copyright ownership. + * Licensed to you 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 com.alu.e3.gateway.camel.processor; + +import static org.junit.Assert.assertEquals; +import static org.junit.Assert.assertNotNull; +import static org.junit.Assert.assertTrue; + +import java.util.HashMap; +import java.util.List; +import java.util.Map; + +import org.apache.camel.Exchange; +import org.apache.camel.Processor; +import org.junit.Before; +import org.junit.Test; + +import com.alu.e3.common.camel.AuthIdentity; +import com.alu.e3.common.camel.ExchangeConstantKeys; +import com.alu.e3.data.model.Api; +import com.alu.e3.data.model.Auth; +import com.alu.e3.data.model.ExtractFromType; +import com.alu.e3.data.model.Policy; +import com.alu.e3.data.model.sub.TdrGenerationRule; +import com.alu.e3.gateway.common.camel.processor.TDRRequestProcessor; +import com.alu.e3.gateway.common.camel.processor.TDRResponseProcessor; +import com.alu.e3.gateway.common.camel.processor.TDRStaticProcessor; +import com.alu.e3.tdr.TDRDataService; + +public class ProvisionedTDRProcessorTest { + + private Exchange exchange; + private Api api; + private Auth auth; + private Policy policy1; + private Processor responseProcessor; + private Processor requestProcessor; + private Processor staticProcessor; + + /** + * Very basic test to make sure that static and dynamic tdr rules on an Auth + * Make it into the expected TDR + * @throws Exception + */ + @Test + public void testAuthTDRs() throws Exception{ + // Add some tdr rules to the Auth and make sure they make it into the billing tdr + TdrGenerationRule genRule = getBasicTestRule(); + auth.setTdrGenerationRule(genRule); + + requestProcessor.process(exchange); + + exchange.setProperty(ExchangeConstantKeys.E3_GOT_SB_RESPONSE.toString(), Boolean.TRUE); + testPostRequest(); + + responseProcessor.process(exchange); + + testPostResponse(); + + staticProcessor.process(exchange); + + testPostStatic(); + } + + /** + * Very basic test to make sure that static and dynamic tdr rules on an Api + * make it into the expected TDR + * @throws Exception + */ + @Test + public void testApiTDRs() throws Exception{ + // Add some tdr rules to the Api and make sure they make it into the billing tdr + TdrGenerationRule genRule = getBasicTestRule(); + api.setTdrGenerationRule(genRule); + + requestProcessor.process(exchange); + exchange.setProperty(ExchangeConstantKeys.E3_GOT_SB_RESPONSE.toString(), Boolean.TRUE); + + testPostRequest(); + + responseProcessor.process(exchange); + + testPostResponse(); + + staticProcessor.process(exchange); + + + testPostStatic(); + } + + /** + * Very basic test to make sure that static and dynamic tdr rules on a Policy + * make it into the expected TDR + * @throws Exception + */ + @Test + public void testPolicyTDRs() throws Exception{ + // Add some tdr rules to a Policy and make sure they make it into the billing tdr + TdrGenerationRule genRule = getBasicTestRule(); + policy1.setTdrGenerationRule(genRule); + + requestProcessor.process(exchange); + exchange.setProperty(ExchangeConstantKeys.E3_GOT_SB_RESPONSE.toString(), Boolean.TRUE); + + testPostRequest(); + + responseProcessor.process(exchange); + + testPostResponse(); + + staticProcessor.process(exchange); + + + testPostStatic(); + } + + /** + * Test that a rule that has NO types will be applied to ALL TDRs for that + * transaction. + * @throws Exception + */ + @Test + public void testCommonTdrRules() throws Exception{ + // Add some tdr rules to a Policy and make sure they make it into the billing tdr + TdrGenerationRule genRule = getBasicTestRule(); + // Add another kind of tdr + TdrGenerationRule quotaRule = new TdrGenerationRule(); + TDRDataService.addNewTdrGenerationRule(exchange, quotaRule, "apiRateLimit"); + + // Add some rule that will apply to all TDRs + genRule.getStaticRules().add(TestHelper.getStaticRule("COMMON-STATIC", "COMMON-STATIC-VALUE", null)); + exchange.getIn().setHeader("COMMON-DYN-HEAD", "COMMON-DYN-HEAD-VALUE"); + genRule.getDynamicRules().add(TestHelper.getDynamicRule("COMMON-DYN", "COMMON-DYN-HEAD", ExtractFromType.Response)); + auth.setTdrGenerationRule(genRule); + + requestProcessor.process(exchange); + exchange.setProperty(ExchangeConstantKeys.E3_GOT_SB_RESPONSE.toString(), Boolean.TRUE); + + testPostRequest(); + + responseProcessor.process(exchange); + + testPostResponse(); + + staticProcessor.process(exchange); + + testPostStatic(); + + // Make sure our new values are in the billing tdr + Map>> tdrData = TDRDataService.getTdrs(exchange); + Map billing = tdrData.get("Billing").get(0); + assertTrue(billing.containsKey("COMMON-STATIC")); + assertEquals("COMMON-STATIC-VALUE", billing.get("COMMON-STATIC")); + assertTrue(billing.containsKey("COMMON-DYN")); + assertEquals("COMMON-DYN-HEAD-VALUE", billing.get("COMMON-DYN")); + + // Make sure that the rateLimit tdr exists + assertTrue(tdrData.containsKey("apiRateLimit")); + assertEquals(1, tdrData.get("apiRateLimit").size()); + + // Make sure that our new values are in the rateLimit tdr + Map rateLimit = tdrData.get("apiRateLimit").get(0); + assertTrue(rateLimit.containsKey("COMMON-STATIC")); + assertEquals("COMMON-STATIC-VALUE", rateLimit.get("COMMON-STATIC")); + assertTrue(rateLimit.containsKey("COMMON-DYN")); + assertEquals("COMMON-DYN-HEAD-VALUE", rateLimit.get("COMMON-DYN")); + + // Make sure that the old values are NOT in the rateLimit tdr + assertTrue(!rateLimit.containsKey("AUTH-DYN")); + assertTrue(!rateLimit.containsKey("AUTH-STAT-VAL")); + + } + + /** + * Test to make sure that if a static rule is added without either a value or + * a property name then it is not used. + * @throws Exception + */ + @Test + public void testMissingStaticValueAndProperty() throws Exception{ + // Add some tdr rules to a Policy and make sure they make it into the billing tdr + TdrGenerationRule genRule = getBasicTestRule(); + genRule.getStaticRules().add(TestHelper.getStaticRule("STATIC-NAME", null, null, "Billing")); + api.setTdrGenerationRule(genRule); + + requestProcessor.process(exchange); + exchange.setProperty(ExchangeConstantKeys.E3_GOT_SB_RESPONSE.toString(), Boolean.TRUE); + + testPostRequest(); + responseProcessor.process(exchange); + testPostResponse(); + + staticProcessor.process(exchange); + + + testPostStatic(); + + Map>> tdrData = TDRDataService.getTdrs(exchange); + Map billing = tdrData.get("Billing").get(0); + assertTrue(!billing.containsKey("STATIC-NAME")); + + } + + /** + * Tests that if the request Processor gets called twice that it will only run once. + * @throws Exception + */ + @Test + public void testDuplicateRunRequest() throws Exception{ + // Add some tdr rules to a Policy and make sure they make it into the billing tdr + TdrGenerationRule genRule = getBasicTestRule(); + genRule.getStaticRules().add(TestHelper.getStaticRule("STATIC-NAME", null, null, "Billing")); + api.setTdrGenerationRule(genRule); + + requestProcessor.process(exchange); + testPostRequest(); + TDRDataService.clean(exchange); + + // This sets up the Billing TDR + TDRDataService.setTxTDRName("Billing", exchange); + TDRDataService.setTxTDRProperty("PROP-1", "VALUE-1", exchange); + + requestProcessor.process(exchange); + + testRequestNotRun(); + + } + + /** + * This test should make sure that no request rules are activated on if it is a response + */ + @Test + public void testRunRequestProcOnResponse() throws Exception{ + // Add some tdr rules to a Policy and make sure they make it into the billing tdr + TdrGenerationRule genRule = getBasicTestRule(); + genRule.getStaticRules().add(TestHelper.getStaticRule("STATIC-NAME", null, null, "Billing")); + api.setTdrGenerationRule(genRule); + exchange.setProperty(ExchangeConstantKeys.E3_GOT_SB_RESPONSE.toString(), Boolean.TRUE); + + requestProcessor.process(exchange); + testRequestNotRun(); + } + + /** + * This test should make sure that no response rules are activated on if it is a request + */ + @Test + public void testRunResponseProcOnRequest()throws Exception{ + // Add some tdr rules to a Policy and make sure they make it into the billing tdr + TdrGenerationRule genRule = getBasicTestRule(); + genRule.getStaticRules().add(TestHelper.getStaticRule("STATIC-NAME", null, null, "Billing")); + api.setTdrGenerationRule(genRule); + + responseProcessor.process(exchange); + + testResponseNotRun(); + } + + private void testRequestNotRun() { + Map>> tdrData = TDRDataService.getTdrs(exchange); + assertNotNull(tdrData); + assertTrue(tdrData.containsKey("Billing")); + assertEquals(1, tdrData.get("Billing").size()); + + Map billing = tdrData.get("Billing").get(0); + + // Make sure the request ones are not in there + assertTrue(!billing.containsKey("DYN-REQUEST")); + } + + /** + * Test that if the response processor gets called twice that it will only run once + * @throws Exception + */ + @Test + public void testDuplicateRunResponse() throws Exception{ + // Add some tdr rules to a Policy and make sure they make it into the billing tdr + TdrGenerationRule genRule = getBasicTestRule(); + genRule.getStaticRules().add(TestHelper.getStaticRule("STATIC-NAME", null, null, "Billing")); + api.setTdrGenerationRule(genRule); + + exchange.setProperty(ExchangeConstantKeys.E3_GOT_SB_RESPONSE.toString(), Boolean.TRUE); + responseProcessor.process(exchange); + TDRDataService.clean(exchange); + + // This sets up the Billing TDR + TDRDataService.setTxTDRName("Billing", exchange); + TDRDataService.setTxTDRProperty("PROP-1", "VALUE-1", exchange); + + responseProcessor.process(exchange); + + testResponseNotRun(); + } + + private void testResponseNotRun() { + Map>> tdrData = TDRDataService.getTdrs(exchange); + assertNotNull(tdrData); + assertTrue(tdrData.containsKey("Billing")); + assertEquals(1, tdrData.get("Billing").size()); + + Map billing = tdrData.get("Billing").get(0); + assertTrue(!billing.containsKey("AUTH-DYN")); + } + + /** + * Helper function to setup the basic tests above + * @return + */ + private TdrGenerationRule getBasicTestRule(){ + // Add a header to the exchange for use by the dynamic header + exchange.getIn().setHeader("AUTH_HEAD", "AUTH_HEAD_VALUE"); + exchange.getIn().setHeader("REQUEST-HEAD", "REQUEST-HEAD-VAL"); + Map props = new HashMap(); + props.put("appId", "1234"); + exchange.setProperty(ExchangeConstantKeys.E3_MODEL_PROPERTIES.toString(), props); + + TdrGenerationRule genRule = new TdrGenerationRule(); + genRule.getDynamicRules().add(TestHelper.getDynamicRule("AUTH-DYN", "AUTH_HEAD", ExtractFromType.Response, "Billing")); + genRule.getDynamicRules().add(TestHelper.getDynamicRule("DYN-REQUEST", "REQUEST-HEAD", ExtractFromType.Request, "Billing")); + genRule.getStaticRules().add(TestHelper.getStaticRule("AUTH-STAT-VAL", "1234", null, "Billing")); + genRule.getStaticRules().add(TestHelper.getStaticRule("AUTH-PROP-VAL", null, "appId", "Billing")); + return genRule; + } + + /** + * Helper function to test the functionality of the basic tests + */ + private void testPostStatic(){ + Map>> tdrData = TDRDataService.getTdrs(exchange); + assertNotNull(tdrData); + assertTrue(tdrData.containsKey("Billing")); + assertEquals(1, tdrData.get("Billing").size()); + + Map billing = tdrData.get("Billing").get(0); + assertTrue(billing.containsKey("AUTH-DYN")); + assertEquals("AUTH_HEAD_VALUE", billing.get("AUTH-DYN")); + assertTrue(billing.containsKey("AUTH-STAT-VAL")); + assertEquals("1234", billing.get("AUTH-STAT-VAL")); + assertTrue(billing.containsKey("AUTH-PROP-VAL")); + assertEquals("1234", billing.get("AUTH-PROP-VAL")); + + assertTrue(billing.containsKey("DYN-REQUEST")); + assertEquals("REQUEST-HEAD-VAL", billing.get("DYN-REQUEST")); + } + + /** + * Helper function to test the functionality of the basic tests + */ + private void testPostResponse(){ + Map>> tdrData = TDRDataService.getTdrs(exchange); + assertNotNull(tdrData); + assertTrue(tdrData.containsKey("Billing")); + assertEquals(1, tdrData.get("Billing").size()); + + Map billing = tdrData.get("Billing").get(0); + assertTrue(billing.containsKey("AUTH-DYN")); + assertTrue(!billing.containsKey("AUTH-STAT-VAL")); + assertTrue(!billing.containsKey("AUTH-PROP-VAL")); + + assertTrue(billing.containsKey("DYN-REQUEST")); + assertEquals("REQUEST-HEAD-VAL", billing.get("DYN-REQUEST")); + } + + /** + * Helper function to test the functionality of the basic tests + */ + private void testPostRequest(){ + Map>> tdrData = TDRDataService.getTdrs(exchange); + assertNotNull(tdrData); + assertTrue(tdrData.containsKey("Billing")); + assertEquals(1, tdrData.get("Billing").size()); + + Map billing = tdrData.get("Billing").get(0); + + // Make sure the response ones are not in there + assertTrue(!billing.containsKey("AUTH-DYN")); + assertTrue(!billing.containsKey("AUTH-STAT-VAL")); + assertTrue(!billing.containsKey("AUTH-PROP-VAL")); + + assertTrue(billing.containsKey("DYN-REQUEST")); + assertEquals("REQUEST-HEAD-VAL", billing.get("DYN-REQUEST")); + } + + + /** + * General setup function. Build up the model and handle the + * prerequisite TDR stuff. + */ + @Before + public void setup(){ + exchange = TestHelper.setupExchange(); + AuthIdentity id = (AuthIdentity) exchange.getProperty(ExchangeConstantKeys.E3_AUTH_IDENTITY.toString()); + auth = id.getAuth(); + api = id.getApi(); + policy1 = id.getCallDescriptors().get(0).getPolicy(); + + responseProcessor = new TDRResponseProcessor(); + requestProcessor = new TDRRequestProcessor(); + staticProcessor = new TDRStaticProcessor(); + + TDRDataService.setTxTDRName("Billing", exchange); + TDRDataService.setTxTDRProperty("PROP-1", "VALUE-1", exchange); + + } + + +} diff --git a/exposure-engine/gateway-common/src/test/java/com/alu/e3/gateway/camel/processor/TestHelper.java b/exposure-engine/gateway-common/src/test/java/com/alu/e3/gateway/camel/processor/TestHelper.java new file mode 100644 index 0000000..e1b0697 --- /dev/null +++ b/exposure-engine/gateway-common/src/test/java/com/alu/e3/gateway/camel/processor/TestHelper.java @@ -0,0 +1,96 @@ +/** + * Copyright © 2012 Alcatel-Lucent. + * + * See the NOTICE file distributed with this work for additional + * information regarding copyright ownership. + * Licensed to you 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 com.alu.e3.gateway.camel.processor; + +import org.apache.camel.Exchange; + +import com.alu.e3.common.camel.AuthIdentity; +import com.alu.e3.common.camel.ExchangeConstantKeys; +import com.alu.e3.data.model.Api; +import com.alu.e3.data.model.Auth; +import com.alu.e3.data.model.CallDescriptor; +import com.alu.e3.data.model.ExtractFromType; +import com.alu.e3.data.model.Policy; +import com.alu.e3.data.model.sub.TdrDynamicRule; +import com.alu.e3.data.model.sub.TdrStaticRule; +import com.alu.e3.gateway.camel.MockExchange; + +public class TestHelper { + + public static Exchange setupExchange(){ + Exchange exchange = new MockExchange(); + + AuthIdentity id = new AuthIdentity(); + Api api = new Api(); + Policy policy1 = new Policy(); + Auth auth = new Auth(); + CallDescriptor cd = new CallDescriptor(policy1, 0, 0); + + id.setApi(api); + id.setAuth(auth); + id.getCallDescriptors().add(cd); + + exchange.setProperty(ExchangeConstantKeys.E3_AUTH_IDENTITY.toString(), id); + + return exchange; + } + + /** + * Helper function for building static tdr rules + * @param name + * @param value + * @param propName + * @param types + * @return + */ + public static TdrStaticRule getStaticRule(String name, String value, String propName, String...types){ + TdrStaticRule rule = new TdrStaticRule(); + rule.setTdrPropName(name); + if(value != null && !value.equals("")){ + rule.setValue(value); + } + else if(propName != null && !propName.equals("")){ + rule.setPropertyName(propName); + } + + for(String type : types) + rule.getTypes().add(type); + + return rule; + } + + /** + * Helper function for building dynamic tdr rules + * @param name + * @param headerName + * @param types + * @return + */ + public static TdrDynamicRule getDynamicRule(String name, String headerName, ExtractFromType efType, String...types){ + TdrDynamicRule rule = new TdrDynamicRule(); + rule.setTdrPropName(name); + rule.setHttpHeaderName(headerName); + rule.setExtractFrom(efType); + + for(String type : types) + rule.getTypes().add(type); + + return rule; + } +} diff --git a/exposure-engine/gateway-common/src/test/java/com/alu/e3/gateway/connection/TestTargetHost2HttpRoute.java b/exposure-engine/gateway-common/src/test/java/com/alu/e3/gateway/connection/TestTargetHost2HttpRoute.java new file mode 100644 index 0000000..f4b43cd --- /dev/null +++ b/exposure-engine/gateway-common/src/test/java/com/alu/e3/gateway/connection/TestTargetHost2HttpRoute.java @@ -0,0 +1,155 @@ +/** + * Copyright © 2012 Alcatel-Lucent. + * + * See the NOTICE file distributed with this work for additional + * information regarding copyright ownership. + * Licensed to you 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 com.alu.e3.gateway.connection; + +import junit.framework.Assert; + +import org.apache.http.HttpHost; +import org.apache.http.conn.routing.HttpRoute; +import org.apache.http.impl.conn.tsccm.ThreadSafeClientConnManager; +import org.junit.Test; + +import com.alu.e3.data.model.sub.ForwardProxy; +import com.alu.e3.data.model.sub.TargetHost; +import com.alu.e3.gateway.TargetHost2HttpRouteUtil; + +public class TestTargetHost2HttpRoute { + + /** + * Tests the basline functionality that we need to confirm: + * That given two "equal" routes they will return the same maxConnections value + */ + @Test + public void testBaseline(){ + HttpRoute route = new HttpRoute(new HttpHost("google.com")); + HttpRoute route2 = new HttpRoute(new HttpHost("google.com")); + doMaxConnTests(route, route2); + } + + @Test + public void testNonSecureRoutes(){ + String url = "http://google.com"; + TargetHost th1 = new TargetHost(); + th1.setUrl(url); + TargetHost th2 = new TargetHost(); + th2.setUrl(url); + + HttpRoute route1 = TargetHost2HttpRouteUtil.fromTargetHost(th1); + HttpRoute route2 = TargetHost2HttpRouteUtil.fromTargetHost(th2); + + Assert.assertFalse(route1.isSecure()); + Assert.assertNull(route1.getProxyHost()); + + doMaxConnTests(route1, route2); + } + + @Test + public void testSecureRoutes(){ + String url = "https://google.com"; + TargetHost th1 = new TargetHost(); + th1.setUrl(url); + TargetHost th2 = new TargetHost(); + th2.setUrl(url); + + HttpRoute route1 = TargetHost2HttpRouteUtil.fromTargetHost(th1); + HttpRoute route2 = TargetHost2HttpRouteUtil.fromTargetHost(th2); + + Assert.assertTrue(route1.isSecure()); + Assert.assertNull(route1.getProxyHost()); + + doMaxConnTests(route1, route2); + } + + @Test + public void testProxiedRoutes(){ + String url = "http://google.com"; + + ForwardProxy fp = new ForwardProxy(); + fp.setProxyHost("alu-proxy.com"); + fp.setProxyPort("1234"); + + TargetHost th1 = new TargetHost(); + th1.setUrl(url); + th1.setForwardProxy(fp); + + TargetHost th2 = new TargetHost(); + th2.setUrl(url); + th2.setForwardProxy(fp); + + HttpRoute route1 = TargetHost2HttpRouteUtil.fromTargetHost(th1); + HttpRoute route2 = TargetHost2HttpRouteUtil.fromTargetHost(th2); + + Assert.assertFalse(route1.isSecure()); + Assert.assertNotNull(route1.getProxyHost()); + + doMaxConnTests(route1, route2); + } + + @Test + public void testSecuredProxied(){ + String url = "https://google.com"; + + ForwardProxy fp = new ForwardProxy(); + fp.setProxyHost("alu-proxy.com"); + fp.setProxyPort("1234"); + + TargetHost th1 = new TargetHost(); + th1.setUrl(url); + th1.setForwardProxy(fp); + + TargetHost th2 = new TargetHost(); + th2.setUrl(url); + th2.setForwardProxy(fp); + + HttpRoute route1 = TargetHost2HttpRouteUtil.fromTargetHost(th1); + HttpRoute route2 = TargetHost2HttpRouteUtil.fromTargetHost(th2); + + Assert.assertTrue(route1.isSecure()); + Assert.assertNotNull(route1.getProxyHost()); + + doMaxConnTests(route1, route2); + } + + + + + /** + * Private helper function + * @param route1 + * @param route2 + */ + private void doMaxConnTests(HttpRoute route1, HttpRoute route2){ + ThreadSafeClientConnManager manager = new ThreadSafeClientConnManager(); + + int originalMax = manager.getMaxForRoute(route1); + + int originalMax2 = manager.getMaxForRoute(route2); + + Assert.assertEquals(originalMax, originalMax2); + + int newMax = originalMax+1; + + manager.setMaxForRoute(route1, newMax); + + int newMax2 = manager.getMaxForRoute(route2); + + Assert.assertEquals(newMax, newMax2); + } + +} diff --git a/exposure-engine/gateway-common/src/test/java/com/alu/e3/gateway/loadbalancer/DataManagerMock.java b/exposure-engine/gateway-common/src/test/java/com/alu/e3/gateway/loadbalancer/DataManagerMock.java new file mode 100644 index 0000000..7213a6d --- /dev/null +++ b/exposure-engine/gateway-common/src/test/java/com/alu/e3/gateway/loadbalancer/DataManagerMock.java @@ -0,0 +1,860 @@ +/** + * Copyright © 2012 Alcatel-Lucent. + * + * See the NOTICE file distributed with this work for additional + * information regarding copyright ownership. + * Licensed to you 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 com.alu.e3.gateway.loadbalancer; + +import java.security.InvalidParameterException; +import java.util.Collection; +import java.util.HashMap; +import java.util.List; +import java.util.Map; +import java.util.Random; +import java.util.Set; + +import com.alu.e3.common.caching.ICacheManager; +import com.alu.e3.common.caching.IEntryListener; +import com.alu.e3.common.logging.Category; +import com.alu.e3.common.osgi.api.IDataManager; +import com.alu.e3.data.CacheAck; +import com.alu.e3.data.IAuthMatcher; +import com.alu.e3.data.IDataManagerListener; +import com.alu.e3.data.IDataManagerUsedBucketIdsListener; +import com.alu.e3.data.model.Api; +import com.alu.e3.data.model.ApiJar; +import com.alu.e3.data.model.Auth; +import com.alu.e3.data.model.CallDescriptor; +import com.alu.e3.data.model.Certificate; +import com.alu.e3.data.model.CertificateRequest; +import com.alu.e3.data.model.Key; +import com.alu.e3.data.model.Limit; +import com.alu.e3.data.model.LogLevel; +import com.alu.e3.data.model.Policy; +import com.alu.e3.data.model.SSLCRL; +import com.alu.e3.data.model.sub.APIContext; +import com.alu.e3.data.model.sub.ApiIds; +import com.alu.e3.data.model.sub.Context; +import com.alu.e3.data.model.sub.QuotaRLBucket; + + +public class DataManagerMock implements IDataManager { + + protected Map apis; + protected Map contexts; + + public DataManagerMock() { + apis = new HashMap(); + contexts = new HashMap(); + } + + @Override + public void addListener(IDataManagerListener listener) { + } + + + + @Override + public void removeListener(IDataManagerListener listener) { + throw new RuntimeException("Not implemented"); + + } + + + + @Override + public Set getAllApiIds() { + throw new RuntimeException("Not implemented"); + + } + + + @Override + public void addApi(Api api) { + apis.put(api.getId(), api); + + for(APIContext context : api.getApiDetail().getContexts()) { + Random r = new Random(); + + Integer id = new Integer(r.nextInt()); + context.setContextId(id); + contexts.put(id, context); + ApiIds ids = new ApiIds(context.getId(), context.getContextId(), 0, true); + api.getContextIds().add(ids); + } + } + + + + @Override + public boolean endpointExists(String endpoint) { + throw new RuntimeException("Not implemented"); + + } + + + + @Override + public void updateApi(Api api) { + throw new RuntimeException("Not implemented"); + + } + + + + @Override + public void removeApi(String id) { + throw new RuntimeException("Not implemented"); + + } + + + + @Override + public Api getApiById(String id) { + return apis.get(id); + } + + + + @Override + public Api getApiById(String id, boolean getFullDetails) { + return apis.get(id); + } + + + + @Override + public Set getAllAuthIds() { + throw new RuntimeException("Not implemented"); + + } + + + + @Override + public void addAuth(Auth auth) { + throw new RuntimeException("Not implemented"); + + } + + + + @Override + public void updateAuth(Auth auth) { + throw new RuntimeException("Not implemented"); + + } + + + + @Override + public void removeAuth(String id) { + throw new RuntimeException("Not implemented"); + + } + + + + @Override + public Auth getAuthById(String id) { + throw new RuntimeException("Not implemented"); + + } + + + + @Override + public Auth getAuthById(String id, boolean getFullDetails) { + throw new RuntimeException("Not implemented"); + + } + + + + @Override + public Auth getAuthByAuthKey(String authKey) { + throw new RuntimeException("Not implemented"); + + } + + + + @Override + public Auth getAuthByOAuth(String clientId, String clientSecret) { + throw new RuntimeException("Not implemented"); + + } + + + + @Override + public Auth getAuthByUserPass(String username, String password) { + throw new RuntimeException("Not implemented"); + + } + + + + @Override + public Auth getAuthByIP(String IP) { + throw new RuntimeException("Not implemented"); + + } + + + + @Override + public Auth getAuthMatching(IAuthMatcher authMatcher) { + throw new RuntimeException("Not implemented"); + + } + + + + @Override + public Set getAllPolicy() { + throw new RuntimeException("Not implemented"); + + } + + + + @Override + public void addPolicy(Policy policy) { + throw new RuntimeException("Not implemented"); + + } + + + + @Override + public void updatePolicy(Policy policy) { + throw new RuntimeException("Not implemented"); + + } + + + + @Override + public void removePolicy(String id) { + throw new RuntimeException("Not implemented"); + + } + + + + @Override + public Policy getPolicyById(String id) { + throw new RuntimeException("Not implemented"); + + } + + + + @Override + public Policy getPolicyById(String id, boolean getFullDetails) { + throw new RuntimeException("Not implemented"); + + } + + + + @Override + public void addAuthsToBucket(String policyId, String bucketId, + QuotaRLBucket authIds) throws InvalidParameterException { + throw new RuntimeException("Not implemented"); + + } + + + + @Override + public void addAuthsToBucket(List policyId, String bucketId, + QuotaRLBucket authIds) throws InvalidParameterException { + throw new RuntimeException("Not implemented"); + + } + + + + @Override + public void appendAuthsToBucket(List policyIds, String bucketId, + QuotaRLBucket authIds) throws IllegalArgumentException { + throw new RuntimeException("Not implemented"); + + } + + + + @Override + public void removeAuthFromBucket(String policyId, String bucketId, + String authId) throws InvalidParameterException { + throw new RuntimeException("Not implemented"); + + } + + + + @Override + public void createBucket(String policyId, QuotaRLBucket authIds) + throws InvalidParameterException { + throw new RuntimeException("Not implemented"); + + } + + + + @Override + public void removeBucket(String policyId, String bucketId) + throws InvalidParameterException { + throw new RuntimeException("Not implemented"); + + } + + + + @Override + public void removeBucket(List policyIds, String bucketId) + throws InvalidParameterException { + throw new RuntimeException("Not implemented"); + + } + + + + @Override + public List getMatchingPolicies(Api api) { + throw new RuntimeException("Not implemented"); + + } + + + + @Override + public List getMatchingPolicies(Api api, Auth auth) { + throw new RuntimeException("Not implemented"); + + } + + + + @Override + public void fillLimitsById(Integer contextId, Limit limit) { + throw new RuntimeException("Not implemented"); + + } + + + + @Override + public Context getPolicyContextById(Integer id) { + throw new RuntimeException("Not implemented"); + + } + + + + @Override + public APIContext getApiContextById(Integer id) { + APIContext context = contexts.get(id); + return context; + } + + + + @Override + public void putSettingString(String key, String value) { + throw new RuntimeException("Not implemented"); + + } + + + + @Override + public void clearSettingString(String key) { + throw new RuntimeException("Not implemented"); + + } + + + + @Override + public String getSettingString(String key) { + throw new RuntimeException("Not implemented"); + + } + + + + @Override + public void addKey(Key key) { + throw new RuntimeException("Not implemented"); + + } + + + + @Override + public Set getAllKeyIds() { + throw new RuntimeException("Not implemented"); + + } + + + + @Override + public Key getKeyById(String id) { + throw new RuntimeException("Not implemented"); + + } + + + + @Override + public Key getKeyById(String id, boolean getFullDetails) { + throw new RuntimeException("Not implemented"); + + } + + + + @Override + public void updateKey(Key key) { + throw new RuntimeException("Not implemented"); + + } + + + + @Override + public void removeKey(String id) { + throw new RuntimeException("Not implemented"); + + } + + + + @Override + public void addCert(Certificate cert) { + throw new RuntimeException("Not implemented"); + + } + + + + @Override + public Set getAllCertIds() { + throw new RuntimeException("Not implemented"); + + } + + + + @Override + public Set getAllCertIdsForKeyId(String keyId) { + throw new RuntimeException("Not implemented"); + + } + + + + @Override + public Certificate getCertById(String id) { + throw new RuntimeException("Not implemented"); + + } + + + + @Override + public Certificate getCertById(String id, boolean getFullDetails) { + throw new RuntimeException("Not implemented"); + + } + + + + @Override + public void updateCert(Certificate certificate) { + throw new RuntimeException("Not implemented"); + + } + + + + @Override + public void removeCert(String id) { + throw new RuntimeException("Not implemented"); + + } + + + + @Override + public Key generateKey(String id) { + throw new RuntimeException("Not implemented"); + + } + + + + @Override + public CertificateRequest getCSR(String keyId) { + throw new RuntimeException("Not implemented"); + + } + + + + @Override + public Certificate selfSignKey(String keyId, CertificateRequest csr) { + throw new RuntimeException("Not implemented"); + + } + + + + @Override + public void removeKeyListener(IEntryListener listener) { + throw new RuntimeException("Not implemented"); + + } + + + + @Override + public void addKeyListener(IEntryListener listener) { + throw new RuntimeException("Not implemented"); + + } + + + + @Override + public void setCacheManager(ICacheManager cacheManager) { + throw new RuntimeException("Not implemented"); + + } + + + + @Override + public boolean deployApi(String apiId, byte[] jarData) { + throw new RuntimeException("Not implemented"); + + } + + + + @Override + public boolean undeployApi(String apiId) { + throw new RuntimeException("Not implemented"); + + } + + + + @Override + public void addApiDeploymentListener(IEntryListener listener) { + throw new RuntimeException("Not implemented"); + + } + + + + @Override + public void removeApiDeploymentListener( + IEntryListener listener) { + throw new RuntimeException("Not implemented"); + + } + + + + @Override + public void postAcknowledgment(String localQueueName, CacheAck ack) + throws InterruptedException { + throw new RuntimeException("Not implemented"); + + } + + + + @Override + public void addLogLevelListener(IEntryListener listener) { + throw new RuntimeException("Not implemented"); + + } + + + + @Override + public void removeLogLevelListener(IEntryListener listener) { + throw new RuntimeException("Not implemented"); + + } + + + + @Override + public void setLogLevel(LogLevel logLevel) { + throw new RuntimeException("Not implemented"); + + } + + + + @Override + public LogLevel getLogLevel() { + throw new RuntimeException("Not implemented"); + + } + + + + @Override + public void setSMXLogLevel(LogLevel logLevel) { + throw new RuntimeException("Not implemented"); + + } + + + + @Override + public LogLevel getSMXLogLevel() { + throw new RuntimeException("Not implemented"); + + } + + + + @Override + public void setSyslogLevel(LogLevel logLevel) { + throw new RuntimeException("Not implemented"); + + } + + + @Override + public LogLevel getSyslogLevel() { + throw new RuntimeException("Not implemented"); + + } + + + + @Override + public void reloadGateway(String ip) { + throw new RuntimeException("Not implemented"); + + } + + + + @Override + public void addCA(Certificate cert) { + throw new RuntimeException("Not implemented"); + + } + + + + @Override + public Set getAllCA() { + throw new RuntimeException("Not implemented"); + + } + + + + @Override + public Certificate getCAById(String id) { + throw new RuntimeException("Not implemented"); + + } + + + + @Override + public void updateCA(Certificate cert) { + throw new RuntimeException("Not implemented"); + + } + + + + @Override + public void removeCA(String id) { + throw new RuntimeException("Not implemented"); + + } + + + + @Override + public void addCAListener(IEntryListener listener) { + throw new RuntimeException("Not implemented"); + + } + + + + @Override + public void removeCAListener(IEntryListener listener) { + throw new RuntimeException("Not implemented"); + + } + + + + @Override + public void addCRL(SSLCRL clr) { + throw new RuntimeException("Not implemented"); + + } + + + + @Override + public SSLCRL getCRLById(String id) { + throw new RuntimeException("Not implemented"); + + } + + + + @Override + public void updateCRL(SSLCRL crl) { + throw new RuntimeException("Not implemented"); + + } + + + @Override + public void removeCRL(String id) { + throw new RuntimeException("Not implemented"); + + } + + + + @Override + public Set getAllCRL() { + throw new RuntimeException("Not implemented"); + + } + + + + @Override + public Collection getAllCRLValues() { + throw new RuntimeException("Not implemented"); + + } + + + + @Override + public void addCrlListener(IEntryListener listener) { + throw new RuntimeException("Not implemented"); + + } + + + + @Override + public void removeCrlListener(IEntryListener listener) { + throw new RuntimeException("Not implemented"); + + } + + + @Override + public boolean isApiExist(String apiId) { + throw new RuntimeException("Not implemented"); + + } + + + @Override + public ApiJar getApiJar(String apiId) { + throw new RuntimeException("Not implemented"); + + } + + + @Override + public void addApiListener(IEntryListener listener) { + throw new RuntimeException("Not implemented"); + + } + + @Override + public void removeApiListener(IEntryListener listener) { + // throw new RuntimeException("Not implemented"); + // Commented because called by tearDown method + + } + + @Override + public Auth getWsseAuth(String username, String passwordDigest, boolean isPasswordText, String nonce, String created) { + throw new RuntimeException("Not implemented"); + + } + + /* (non-Javadoc) + * @see com.alu.e3.common.osgi.api.IDataManager#addListener(com.alu.e3.data.IDataManagerUsedBucketIdsListener) + */ + @Override + public void addListener(IDataManagerUsedBucketIdsListener listener) { + throw new RuntimeException("Not implemented"); + + } + + /* (non-Javadoc) + * @see com.alu.e3.common.osgi.api.IDataManager#removeListener(com.alu.e3.data.IDataManagerUsedBucketIdsListener) + */ + @Override + public void removeListener(IDataManagerUsedBucketIdsListener listener) { + throw new RuntimeException("Not implemented"); + + } + + /* (non-Javadoc) + * @see com.alu.e3.common.osgi.api.IDataManager#removeAuthsFromBucket(java.util.List, java.lang.String, java.util.List) + */ + @Override + public void removeAuthsFromBucket(List policyIds, String bucketId, + List authIds) throws IllegalArgumentException { + throw new RuntimeException("Not implemented"); + + } + + @Override + public void setLoggingCategory(Category category, boolean enabled) { + // TODO Auto-generated method stub + + } + + @Override + public boolean getLoggingCategory(Category category) { + // TODO Auto-generated method stub + return false; + } + +} diff --git a/exposure-engine/gateway-common/src/test/java/com/alu/e3/gateway/loadbalancer/HttpComponentMock.java b/exposure-engine/gateway-common/src/test/java/com/alu/e3/gateway/loadbalancer/HttpComponentMock.java new file mode 100644 index 0000000..586d23b --- /dev/null +++ b/exposure-engine/gateway-common/src/test/java/com/alu/e3/gateway/loadbalancer/HttpComponentMock.java @@ -0,0 +1,33 @@ +/** + * Copyright © 2012 Alcatel-Lucent. + * + * See the NOTICE file distributed with this work for additional + * information regarding copyright ownership. + * Licensed to you 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 com.alu.e3.gateway.loadbalancer; + +import java.util.Map; + +import org.apache.camel.component.http4.HttpEndpoint; +import org.apache.camel.impl.DefaultComponent; + +public class HttpComponentMock extends DefaultComponent { + + @Override + protected HttpEndpoint createEndpoint(String uri, String remaining, Map parameters) throws Exception { + return new HttpEndpointMock(); + } + +} diff --git a/exposure-engine/gateway-common/src/test/java/com/alu/e3/gateway/loadbalancer/HttpEndpointMock.java b/exposure-engine/gateway-common/src/test/java/com/alu/e3/gateway/loadbalancer/HttpEndpointMock.java new file mode 100644 index 0000000..cdc673c --- /dev/null +++ b/exposure-engine/gateway-common/src/test/java/com/alu/e3/gateway/loadbalancer/HttpEndpointMock.java @@ -0,0 +1,45 @@ +/** + * Copyright © 2012 Alcatel-Lucent. + * + * See the NOTICE file distributed with this work for additional + * information regarding copyright ownership. + * Licensed to you 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 com.alu.e3.gateway.loadbalancer; + +import org.apache.camel.Consumer; +import org.apache.camel.Processor; +import org.apache.camel.Producer; +import org.apache.camel.component.http4.HttpEndpoint; + +public class HttpEndpointMock extends HttpEndpoint { + + @Override + public Producer createProducer() throws Exception { + return new HttpProducerMock(this); + } + + @Override + public Consumer createConsumer(Processor processor) throws Exception { + // TODO Auto-generated method stub + return null; + } + + @Override + public boolean isSingleton() { + // TODO Auto-generated method stub + return false; + } + +} diff --git a/exposure-engine/gateway-common/src/test/java/com/alu/e3/gateway/loadbalancer/HttpLoadBalancerProcessorMock.java b/exposure-engine/gateway-common/src/test/java/com/alu/e3/gateway/loadbalancer/HttpLoadBalancerProcessorMock.java new file mode 100644 index 0000000..d7135cf --- /dev/null +++ b/exposure-engine/gateway-common/src/test/java/com/alu/e3/gateway/loadbalancer/HttpLoadBalancerProcessorMock.java @@ -0,0 +1,31 @@ +/** + * Copyright © 2012 Alcatel-Lucent. + * + * See the NOTICE file distributed with this work for additional + * information regarding copyright ownership. + * Licensed to you 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 com.alu.e3.gateway.loadbalancer; + +import org.apache.camel.Exchange; + +public class HttpLoadBalancerProcessorMock extends HttpLoadBalancerProcessor { + + void initHttpEndpoint(Exchange exchange) throws Exception { + HttpComponentMock component = new HttpComponentMock(); + super.httpEndpoint = component.createEndpoint(null, null, null); + + + } +} diff --git a/exposure-engine/gateway-common/src/test/java/com/alu/e3/gateway/loadbalancer/HttpLoadBalancerProcessorTest.java b/exposure-engine/gateway-common/src/test/java/com/alu/e3/gateway/loadbalancer/HttpLoadBalancerProcessorTest.java new file mode 100644 index 0000000..1805128 --- /dev/null +++ b/exposure-engine/gateway-common/src/test/java/com/alu/e3/gateway/loadbalancer/HttpLoadBalancerProcessorTest.java @@ -0,0 +1,27 @@ +/** + * Copyright © 2012 Alcatel-Lucent. + * + * See the NOTICE file distributed with this work for additional + * information regarding copyright ownership. + * Licensed to you 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 com.alu.e3.gateway.loadbalancer; + +public class HttpLoadBalancerProcessorTest { + + + + + +} diff --git a/exposure-engine/gateway-common/src/test/java/com/alu/e3/gateway/loadbalancer/HttpProducerMock.java b/exposure-engine/gateway-common/src/test/java/com/alu/e3/gateway/loadbalancer/HttpProducerMock.java new file mode 100644 index 0000000..ffc050c --- /dev/null +++ b/exposure-engine/gateway-common/src/test/java/com/alu/e3/gateway/loadbalancer/HttpProducerMock.java @@ -0,0 +1,49 @@ +/** + * Copyright © 2012 Alcatel-Lucent. + * + * See the NOTICE file distributed with this work for additional + * information regarding copyright ownership. + * Licensed to you 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 com.alu.e3.gateway.loadbalancer; + +import org.apache.camel.Endpoint; +import org.apache.camel.Exchange; +import org.apache.camel.impl.DefaultProducer; + + +public class HttpProducerMock extends DefaultProducer { + + public HttpProducerMock(Endpoint endpoint) { + super(endpoint); + } + + @Override + public void process(Exchange exchange) throws Exception { + + String body = (String) exchange.getIn().getBody(); + + Integer httpResponse = Integer.parseInt(body); + + if(httpResponse.intValue() == 200) { + exchange.getOut().setBody("OK"); + } else { + exchange.getOut().setBody("KO"); + } + + exchange.getOut().setHeader(Exchange.HTTP_RESPONSE_CODE, httpResponse); + + } + +} diff --git a/exposure-engine/gateway-common/src/test/java/com/alu/e3/gateway/loadbalancer/LoadBalancerProcessorTest.java b/exposure-engine/gateway-common/src/test/java/com/alu/e3/gateway/loadbalancer/LoadBalancerProcessorTest.java new file mode 100644 index 0000000..1c63835 --- /dev/null +++ b/exposure-engine/gateway-common/src/test/java/com/alu/e3/gateway/loadbalancer/LoadBalancerProcessorTest.java @@ -0,0 +1,114 @@ +/** + * Copyright © 2012 Alcatel-Lucent. + * + * See the NOTICE file distributed with this work for additional + * information regarding copyright ownership. + * Licensed to you 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 com.alu.e3.gateway.loadbalancer; + +import java.util.HashMap; +import java.util.Map; +import java.util.Properties; + +import org.apache.camel.CamelContext; +import org.apache.camel.EndpointInject; +import org.apache.camel.Exchange; +import org.apache.camel.Produce; +import org.apache.camel.ProducerTemplate; +import org.apache.camel.component.mock.MockEndpoint; +import org.junit.Ignore; +import org.junit.Test; +import org.junit.runner.RunWith; +import org.springframework.beans.factory.annotation.Autowired; +import org.springframework.test.annotation.DirtiesContext; +import org.springframework.test.context.ContextConfiguration; +import org.springframework.test.context.junit4.SpringJUnit4ClassRunner; + +import org.apache.log4j.PropertyConfigurator; + + +@RunWith(SpringJUnit4ClassRunner.class) +@ContextConfiguration(locations = { "classpath:gateway-common.test-lb-context.xml"} ) +@Ignore +public class LoadBalancerProcessorTest { + + static { + Properties props = new Properties(); + + props.setProperty("log4j.rootLogger","DEBUG, myConsoleAppender"); + props.setProperty("log4j.appender.myConsoleAppender","org.apache.log4j.ConsoleAppender"); + props.setProperty("log4j.appender.myConsoleAppender.layout","org.apache.log4j.PatternLayout"); + props.setProperty("log4j.appender.myConsoleAppender.layout.ConversionPattern","%-4r [%t] %-5p %c %x - %m%n"); + + PropertyConfigurator.configure(props); + } + + + @Autowired + protected CamelContext camelContext; + + @EndpointInject(uri = "mock:result") + protected MockEndpoint resultEndpoint; + + @EndpointInject(uri = "mock:resultError") + protected MockEndpoint resultErrorEndpoint; + + @Produce(uri = "direct:testCallApi") + protected ProducerTemplate producerTemplate; + + @Test + @DirtiesContext + @Ignore + public void testCallApiSuccess() throws InterruptedException { + + String body = "200"; + Map headers = new HashMap(); + headers.put("MyHeader", "true"); + + producerTemplate.sendBodyAndHeaders(body, headers); + resultEndpoint.message(0).header(Exchange.HTTP_RESPONSE_CODE).isEqualTo(200); + resultEndpoint.assertIsSatisfied(); + + + } + + @Test + @DirtiesContext + @Ignore + public void testCallApiFails() throws InterruptedException { + + String body = "503"; + Map headers = new HashMap(); + headers.put("MyHeader", "true"); + + producerTemplate.sendBodyAndHeaders(body, headers); + resultErrorEndpoint.message(0).header(Exchange.HTTP_RESPONSE_CODE).isEqualTo(500); + resultErrorEndpoint.assertIsSatisfied(); + } + + @Test + @DirtiesContext + @Ignore + public void testCallApiNotFound() throws InterruptedException { + + String body = "404"; + Map headers = new HashMap(); + headers.put("MyHeader", "true"); + + producerTemplate.sendBodyAndHeaders(body, headers); + resultEndpoint.message(0).header(Exchange.HTTP_RESPONSE_CODE).isEqualTo(404); + resultEndpoint.assertIsSatisfied(); + } +} diff --git a/exposure-engine/gateway-common/src/test/java/com/alu/e3/gateway/loadbalancer/TargetHostManagerBase.java b/exposure-engine/gateway-common/src/test/java/com/alu/e3/gateway/loadbalancer/TargetHostManagerBase.java new file mode 100644 index 0000000..e71008c --- /dev/null +++ b/exposure-engine/gateway-common/src/test/java/com/alu/e3/gateway/loadbalancer/TargetHostManagerBase.java @@ -0,0 +1,105 @@ +/** + * Copyright © 2012 Alcatel-Lucent. + * + * See the NOTICE file distributed with this work for additional + * information regarding copyright ownership. + * Licensed to you 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 com.alu.e3.gateway.loadbalancer; + + +import org.junit.After; +import org.junit.Before; + +import com.alu.e3.common.osgi.api.IDataManager; +import com.alu.e3.data.model.Api; +import com.alu.e3.data.model.ApiDetail; +import com.alu.e3.data.model.sub.APIContext; +import com.alu.e3.data.model.sub.TargetHealthCheck; +import com.alu.e3.data.model.sub.TargetHost; +import com.alu.e3.gateway.targethealthcheck.ITargetHealthCheckService; + +public class TargetHostManagerBase { + + protected IDataManager dataManager; + protected TargetHostManager targetHostManager; + + public TargetHostManagerBase() { + } + + @Before + public void setUp() throws Exception { + dataManager = new DataManagerMock(); + + targetHostManager = new TargetHostManager(); + targetHostManager.setDataManager(dataManager); + targetHostManager.init(); + + } + + @After + public void tearDown() throws Exception { + targetHostManager.destroy(); + } + + + public Api newApi(ITargetHealthCheckService healthCheckService) { + TargetHealthCheck targetHealthCheck = null; + if(healthCheckService != null) { + targetHealthCheck = new TargetHealthCheck(); + targetHealthCheck.setType(healthCheckService.getName()); + } + + APIContext context1 = new APIContext(); + context1.setId("test"); + context1.setDefaultContext(true); + context1.getTargetHosts().add(targetHostWithUrlAndSite("http://www.google.fr", "LOCAL")); + context1.getTargetHosts().add(targetHostWithUrlAndSite("http://www.google.com", "US")); + context1.getTargetHosts().add(targetHostWithUrlAndSite("http://www.google.co.uk", "UK")); + + if(targetHealthCheck != null) + context1.getLoadBalancing().setTargetHealthCheck(targetHealthCheck); + + + + APIContext context2 = new APIContext(); + context2.setId("production"); + context2.setDefaultContext(false); + context2.getTargetHosts().add(targetHostWithUrlAndSite("http://www.apple.fr", "LOCAL")); + context2.getTargetHosts().add(targetHostWithUrlAndSite("http://www.apple.com", "US")); + context2.getTargetHosts().add(targetHostWithUrlAndSite("http://www.apple.co.uk", "UK")); + + if(targetHealthCheck != null) + context2.getLoadBalancing().setTargetHealthCheck(targetHealthCheck); + + Api api = new Api(); + api.setApiDetail(new ApiDetail()); + api.getApiDetail().setEndpoint("/endpoint"); + api.getApiDetail().getContexts().add(context1); + api.getApiDetail().getContexts().add(context2); + return api; + } + + protected TargetHost targetHostWithUrlAndSite(String url, String site) { + TargetHost target = new TargetHost(); + target.setUrl(url); + target.setSite(site); + + return target; + } + +} diff --git a/exposure-engine/gateway-common/src/test/java/com/alu/e3/gateway/loadbalancer/TargetHostManagerMock.java b/exposure-engine/gateway-common/src/test/java/com/alu/e3/gateway/loadbalancer/TargetHostManagerMock.java new file mode 100644 index 0000000..f2ef5f8 --- /dev/null +++ b/exposure-engine/gateway-common/src/test/java/com/alu/e3/gateway/loadbalancer/TargetHostManagerMock.java @@ -0,0 +1,81 @@ +/** + * Copyright © 2012 Alcatel-Lucent. + * + * See the NOTICE file distributed with this work for additional + * information regarding copyright ownership. + * Licensed to you 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 com.alu.e3.gateway.loadbalancer; + +import java.util.HashMap; +import java.util.List; +import java.util.Map; + +import com.alu.e3.data.model.sub.TargetHost; + +public class TargetHostManagerMock implements ITargetHostManager { + + private Map targets; + private int index; + + public TargetHostManagerMock() { + targets = new HashMap(); + index = 0; + } + + @Override + public void notifyFailed(String targetHostReference) { + // TODO Auto-generated method stub + } + + @Override + public boolean isAvailable(String targetReference) { + + TargetReference targetRef = targets.get(targetReference); + boolean available = true; + if(targetRef != null) { + String url = targetRef.getTargetHost().getUrl(); + if(url.contains("not_available")) { + available = false; // simulate not available + } + } + + return available; + } + + public String registerTargetHost(TargetHost targetHost) { + + String reference = Integer.toString(index); + index++; + + TargetReference targetRef = new TargetReference(); + targetRef.setReference(reference); + targetRef.setTargetHost(targetHost); + + targets.put(reference, targetRef); + + return reference; + } + + + @Override + public List getTargetReferences(String apiId, + String contextId) { + // TODO Auto-generated method stub + return null; + } + + + +} diff --git a/exposure-engine/gateway-common/src/test/java/com/alu/e3/gateway/loadbalancer/TargetHostManagerTest.java b/exposure-engine/gateway-common/src/test/java/com/alu/e3/gateway/loadbalancer/TargetHostManagerTest.java new file mode 100644 index 0000000..8062324 --- /dev/null +++ b/exposure-engine/gateway-common/src/test/java/com/alu/e3/gateway/loadbalancer/TargetHostManagerTest.java @@ -0,0 +1,175 @@ +/** + * Copyright © 2012 Alcatel-Lucent. + * + * See the NOTICE file distributed with this work for additional + * information regarding copyright ownership. + * Licensed to you 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 com.alu.e3.gateway.loadbalancer; + + +import static org.junit.Assert.*; +import java.util.HashMap; +import java.util.List; +import java.util.Map; + +import org.junit.Test; + +import com.alu.e3.data.model.Api; +import com.alu.e3.data.model.sub.APIContext; +import com.alu.e3.gateway.loadbalancer.TargetHostManager.TargetStatus; +import com.alu.e3.gateway.targethealthcheck.ITargetHealthCheckService; + +public class TargetHostManagerTest extends TargetHostManagerBase { + + @Test + public void simpleNoHealthCheck() { + Api api = newApi(null); + + dataManager.addApi(api); + targetHostManager.registerAPI(api.getId()); + + for(APIContext context : api.getApiDetail().getContexts()) { + List references = targetHostManager.getTargetReferences(api.getId(), context.getId()); + + // We have same as many targetreference as targethost in the context + assertTrue("Number of target references == than number of target hosts", references.size() == context.getTargetHosts().size()); + + for(TargetReference target : references) { + // Assert that all targets are Available (their default status) + assertTrue(targetHostManager.isAvailable(target.getReference())); + + // Assert that the TargetHost referenced by the TargetReference obejct returned by TargetHostManager is really part of API Context's TargetHost + assertTrue("TargetHost in TargetReference is part of API Context's TargetHosts", context.getTargetHosts().contains(target.getTargetHost())); + } + + // Testing that notifying a failed target to targetHostManager does not change its status as this target is not healthchecked + targetHostManager.notifyFailed(references.get(0).getReference()); + assertTrue(targetHostManager.isAvailable(references.get(0).getReference())); + } + } + + @Test + /** + * Will test that an API with a HealthCheckService is correctly added to the Service. + */ + public void simpleHealthCheck() { + + // Mimic Spring instantiation of HealthCheckService + HealthCheckServiceMock healthCheckService = new HealthCheckServiceMock(); + healthCheckService.init(); + + // imic Spring instantiation of THManager + targetHostManager.registerHealthCheckService(healthCheckService); + + Api api = newApi(healthCheckService); + + // Provision the API + dataManager.addApi(api); + + // Register the APi on the THMgr: all targets should be monitored by the healthcheck service too + targetHostManager.registerAPI(api.getId()); + + for(APIContext context : api.getApiDetail().getContexts()) { + // These are targetReferences returned by the THMgr to the LoadBalancer + List references = targetHostManager.getTargetReferences(api.getId(), context.getId()); + + // We have same as many targetreference as targethost in the context + assertTrue("Number of target references == than number of target hosts", references.size() == context.getTargetHosts().size()); + + for(TargetReference target : references) { + // Assert that all targets are Available (their default status) + assertTrue(targetHostManager.isAvailable(target.getReference())); + + // Assert that the TargetHost referenced by the TargetReference obejct returned by TargetHostManager is really part of API Context's TargetHost + assertTrue("TargetHost in TargetReference is part of API Context's TargetHosts", context.getTargetHosts().contains(target.getTargetHost())); + + // Assert that the target has been added to the HealthCheckServiceMock + assertTrue("TargetReference is monitored by HealthCheckService", healthCheckService.isMonitored(target.getReference())); + } + + // Testing that notifying a failed target to targetHostManager CHANGES its status as this target IS healthchecked + targetHostManager.notifyFailed(references.get(0).getReference()); + assertFalse(targetHostManager.isAvailable(references.get(0).getReference())); + + // Reset target0 + healthCheckService.setStatus(references.get(0).getReference(), TargetStatus.AVAILABLE); + assertTrue(targetHostManager.isAvailable(references.get(0).getReference())); + + // Check that THMgr returns false for isAvailable(UNAVAILABLE) + healthCheckService.setStatus(references.get(1).getReference(), TargetStatus.UNAVAILABLE); + assertFalse(targetHostManager.isAvailable(references.get(1).getReference())); + + // Check that THMgr returns false for isAvailable(OVERLOADED) + healthCheckService.setStatus(references.get(2).getReference(), TargetStatus.OVERLOADED); + assertFalse(targetHostManager.isAvailable(references.get(2).getReference())); + } + + } + + class HealthCheckServiceMock implements ITargetHealthCheckService { + + public static final String NAME = "HealthCheckMock"; + protected Map targets; + + @Override + public String getName() { + return NAME; + } + + @Override + public void init() { + targets = new HashMap(); + } + + @Override + public void start() { + // Do nothing here + } + + @Override + public void stop() { + // Do nothing here + } + + @Override + public void destroy() { + // TODO Auto-generated method stub + + } + + @Override + public void registerTarget(ManagedTargetHost target) { + targets.put(target.getReference(), target); + } + + @Override + public void unregisterTarget(ManagedTargetHost target) { + targets.remove(target.getReference()); + } + + + public void setStatus(String reference, TargetStatus status) { + ManagedTargetHost target = targets.get(reference); + target.setStatus(status); + } + + public boolean isMonitored(String reference) { + return targets.containsKey(reference); + } + } +} diff --git a/exposure-engine/gateway-common/src/test/java/com/alu/e3/gateway/loadbalancer/TopologyClientMock.java b/exposure-engine/gateway-common/src/test/java/com/alu/e3/gateway/loadbalancer/TopologyClientMock.java new file mode 100644 index 0000000..b4107bf --- /dev/null +++ b/exposure-engine/gateway-common/src/test/java/com/alu/e3/gateway/loadbalancer/TopologyClientMock.java @@ -0,0 +1,155 @@ +/** + * Copyright © 2012 Alcatel-Lucent. + * + * See the NOTICE file distributed with this work for additional + * information regarding copyright ownership. + * Licensed to you 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 com.alu.e3.gateway.loadbalancer; + +import java.util.ArrayList; +import java.util.List; +import java.util.Set; + +import com.alu.e3.common.caching.ICacheManager; +import com.alu.e3.common.caching.IEntryListener; +import com.alu.e3.common.osgi.api.ITopologyClient; +import com.alu.e3.data.model.Instance; +import com.alu.e3.data.topology.IInstanceListener; + +public class TopologyClientMock implements ITopologyClient { + + + private String myArea; + + + @Override + public void setCacheManager(ICacheManager cacheManager) { + // TODO Auto-generated method stub + + } + + @Override + public void addInstance(Instance inst) { + // TODO Auto-generated method stub + + } + + @Override + public boolean deleteInstance(Instance inst) { + // TODO Auto-generated method stub + return false; + } + + @Override + public Set getAllExternalIPsOfType(String type) { + // TODO Auto-generated method stub + return null; + } + + @Override + public Set getAllInternalIPsOfType(String type) { + // TODO Auto-generated method stub + return null; + } + + @Override + public List getAllInstancesOfType(String type) { + // TODO Auto-generated method stub + return null; + } + + @Override + public Set getExternalIPsOfType(String type, String area) { + // TODO Auto-generated method stub + return null; + } + + @Override + public Set getInternalIPsOfType(String type, String area) { + // TODO Auto-generated method stub + return null; + } + + @Override + public List getInstancesOfType(String type, String area) { + // TODO Auto-generated method stub + return null; + } + + @Override + public void addAreas(Set areas) { + // TODO Auto-generated method stub + + } + + @Override + public void setMyArea(String area) { + this.myArea = area; + } + + @Override + public String getMyArea() { + return myArea; + } + + @Override + public Set getAllAreas() { + // TODO Auto-generated method stub + return null; + } + + @Override + public Set getAllOtherAreas() { + // TODO Auto-generated method stub + return null; + } + + @Override + public void addInstanceTypeListener( + IEntryListener> listener) { + // TODO Auto-generated method stub + + } + + @Override + public void removeInstanceTypeListener( + IEntryListener> listener) { + // TODO Auto-generated method stub + + } + + @Override + public void addInstanceListener(IInstanceListener listener) { + // TODO Auto-generated method stub + + } + + @Override + public void removeInstanceListener(IInstanceListener listener) { + // TODO Auto-generated method stub + + } + + /* (non-Javadoc) + * @see com.alu.e3.common.osgi.api.ITopologyClient#whoAmI(java.lang.String) + */ + @Override + public Instance whoAmI(String type) { + // TODO Auto-generated method stub + return null; + } + + +} diff --git a/exposure-engine/gateway-common/src/test/resources/gateway-common.test-lb-context.xml b/exposure-engine/gateway-common/src/test/resources/gateway-common.test-lb-context.xml new file mode 100644 index 0000000..2198ad9 --- /dev/null +++ b/exposure-engine/gateway-common/src/test/resources/gateway-common.test-lb-context.xml @@ -0,0 +1,82 @@ + + + + + + + + SiteA + + + + + + http://host.one.available + SiteA + 1000 + 10 + + + + http://host.two.not_available + SiteA + 1000 + 10 + + + + http://host.three.available + SiteB + 1000 + 10 + + + + + + true + 503 + + + + + + + + + + + + + java.lang.Exception + + true + + + + + + + + + + + + + + diff --git a/exposure-engine/gateway-rate-limits-manager/pom.xml b/exposure-engine/gateway-rate-limits-manager/pom.xml new file mode 100644 index 0000000..5083a4f --- /dev/null +++ b/exposure-engine/gateway-rate-limits-manager/pom.xml @@ -0,0 +1,91 @@ + + + 4.0.0 + + + exposure-engine + com.alu.e3 + 1.0.1 + .. + + + gateway-rate-limits-manager + E3 Gateway Rate Limit Manager + http://www.alcatel-lucent.com + + + jar + + + + org.apache.camel + camel-http + 2.6.0-fuse-01-09 + provided + + + tools + com.sun + + + + + org.apache.camel + camel-test + 2.0.0 + test + + + + org.apache.felix + org.apache.felix.framework + 3.0.9-fuse-03-11 + test + + + + org.springframework + spring-core + ${org.springframework.version} + provided + + + org.springframework + spring-test + 3.0.5.RELEASE + test + + + + com.alu.e3 + common + ${project.version} + jar + provided + + + org.springframework + spring-beans + 3.0.5.RELEASE + provided + + + + com.alu.e3 + gateway-common + ${project.version} + jar + provided + + + com.alu.e3 + auth-manager + ${project.version} + jar + provided + + + + + \ No newline at end of file diff --git a/exposure-engine/gateway-rate-limits-manager/src/main/java/com/alu/e3/rate/camel/RateLimitProcessor.java b/exposure-engine/gateway-rate-limits-manager/src/main/java/com/alu/e3/rate/camel/RateLimitProcessor.java new file mode 100644 index 0000000..1aeea05 --- /dev/null +++ b/exposure-engine/gateway-rate-limits-manager/src/main/java/com/alu/e3/rate/camel/RateLimitProcessor.java @@ -0,0 +1,107 @@ +/** + * Copyright © 2012 Alcatel-Lucent. + * + * See the NOTICE file distributed with this work for additional + * information regarding copyright ownership. + * Licensed to you 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 com.alu.e3.rate.camel; + +import java.util.List; + +import org.apache.camel.Exchange; +import org.apache.camel.Processor; +import org.slf4j.Logger; +import org.slf4j.LoggerFactory; + +import com.alu.e3.common.camel.AuthIdentity; +import com.alu.e3.common.camel.ExchangeConstantKeys; +import com.alu.e3.data.model.sub.TdrGenerationRule; +import com.alu.e3.gateway.common.camel.exception.GatewayException; +import com.alu.e3.gateway.common.camel.exception.GatewayExceptionCode; +import com.alu.e3.rate.manager.IGatewayRateManager; +import com.alu.e3.rate.model.LimitCheckResult; +import com.alu.e3.tdr.TDRConstant; +import com.alu.e3.tdr.TDRDataService; + +public class RateLimitProcessor implements Processor { + protected IGatewayRateManager rateManager; + + private final static Logger log = LoggerFactory.getLogger(RateLimitProcessor.class); + + public IGatewayRateManager getGtwRateMger() { + return rateManager; + } + + public void setGatewayRateMger(IGatewayRateManager gtwRateMger) { + log.debug("GatewayRateManager set in RateLimit processor"); + this.rateManager = gtwRateMger; + } + + @Override + public void process(Exchange exchange) throws Exception { + + if (rateManager == null) { + throw new GatewayException(GatewayExceptionCode.RATEORQUOTA, "Rate Manager is null"); + } + + /* + * TODO extract data required by the rate manager to compute the rate limits from the parameters inside exchange + */ + Object property = exchange.getProperty(ExchangeConstantKeys.E3_AUTH_IDENTITY.toString()); + if (property == null || ! (property instanceof AuthIdentity)) { + throw new GatewayException(GatewayExceptionCode.RATEORQUOTA, "The property " + ExchangeConstantKeys.E3_AUTH_IDENTITY.toString() + " is required to check the rate limits."); + } + + boolean isTDREnabled = exchange.getProperty(ExchangeConstantKeys.E3_TDR_ENABLED.toString(), boolean.class); + AuthIdentity authIdentity = (AuthIdentity) property; + LimitCheckResult limitCheckResult = rateManager.isAllowed(authIdentity, isTDREnabled); + + if(isTDREnabled){ + /** + * Put some TDR data into into service + */ + TDRDataService.addTxTDRProperty(exchange, TDRConstant.OVER_QUOTA, limitCheckResult.isOverQuota()); + TDRDataService.addTxTDRProperty(exchange, TDRConstant.OVER_QUOTA_SEC, limitCheckResult.isOverSecond()); + TDRDataService.addTxTDRProperty(exchange, TDRConstant.OVER_QUOTA_MIN, limitCheckResult.isOverMinute()); + TDRDataService.addTxTDRProperty(exchange, TDRConstant.OVER_QUOTA_DAY, limitCheckResult.isOverDay()); + TDRDataService.addTxTDRProperty(exchange, TDRConstant.OVER_QUOTA_WEEK, limitCheckResult.isOverWeek()); + TDRDataService.addTxTDRProperty(exchange, TDRConstant.OVER_QUOTA_MONTH, limitCheckResult.isOverMonth()); + + for(String tdrName : limitCheckResult.getTdrValues().keySet()){ + List genRules = limitCheckResult.getTdrValues().get(tdrName); + for(TdrGenerationRule genRule : genRules){ + TDRDataService.addNewTdrGenerationRule(exchange, genRule, tdrName); + } + } + } + + + // Route allowed if null - no action error defined + if (limitCheckResult != null && limitCheckResult.getActionType() != null) { + if(isTDREnabled) + exchange.setProperty(ExchangeConstantKeys.E3_RATELIMIT_ACTION.toString(), limitCheckResult.getActionType().toString()); + TDRDataService.addTxTDRProperty(exchange, TDRConstant.OVER_QUOTA_ACTION, limitCheckResult.getActionType().toString()); + + // Log - Will be based on the Logging Framework developed internally + //log.debug("Route rate limit for API " + (authIdentity.getApi()==null ? "(no API)" : authIdentity.getApi().getId()) + " exeeded" + ((authIdentity.getAuth()==null) ? "": "by " + authIdentity.getAuth().getId())); + // TDR Notification - not yet implemented + // HTTP Status Code 429 - to be return by the error processor of the route + + throw new GatewayException(GatewayExceptionCode.RATEORQUOTA, "Rate limit exceeded. " + limitCheckResult.getActionTypeMessage(), limitCheckResult.getActionType().toString()); + } + + } + +} diff --git a/exposure-engine/gateway-rate-limits-manager/src/main/java/com/alu/e3/rate/manager/GatewayDataManager.java b/exposure-engine/gateway-rate-limits-manager/src/main/java/com/alu/e3/rate/manager/GatewayDataManager.java new file mode 100644 index 0000000..fe509c3 --- /dev/null +++ b/exposure-engine/gateway-rate-limits-manager/src/main/java/com/alu/e3/rate/manager/GatewayDataManager.java @@ -0,0 +1,187 @@ +/** + * Copyright © 2012 Alcatel-Lucent. + * + * See the NOTICE file distributed with this work for additional + * information regarding copyright ownership. + * Licensed to you 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 com.alu.e3.rate.manager; + +import java.util.HashMap; +import java.util.Iterator; +import java.util.Queue; +import java.util.concurrent.ConcurrentHashMap; +import java.util.concurrent.ConcurrentLinkedQueue; + +import com.alu.e3.data.IDataManagerUsedBucketIdsListener; +import com.alu.e3.rate.model.ApiCall; +import com.alu.e3.rate.model.GatewayRate; +import com.alu.e3.rate.model.GatewayQueueRate; + +public class GatewayDataManager implements IDataManagerUsedBucketIdsListener { + + private static final int FREE_LOCK_COUNTER_MAX_SIZE = 100; + + private Queue apiCallsPerMinuteQueue = new ConcurrentLinkedQueue(); + private Queue apiCallsPerSecondQueue = new ConcurrentLinkedQueue(); + + private ConcurrentHashMap gatewayRateMap = new ConcurrentHashMap(); + + private ConcurrentHashMap gatewayQueueRateMap = new ConcurrentHashMap(); + + private ConcurrentLinkedQueue lockPool = new ConcurrentLinkedQueue(); + private HashMap bucketMapLock = new HashMap(); + + public class LockCounter { + int count; + + public LockCounter() { + count = 0; + } + } + + private LockCounter getLock() { + LockCounter lock; + + lock = lockPool.poll(); + + if (lock == null) { + lock = new LockCounter(); + } + + return lock; + } + + private void releaseLock(LockCounter lock) { + if (lockPool.size() < FREE_LOCK_COUNTER_MAX_SIZE) { + lockPool.add(lock); + } + } + + public LockCounter getLockForBucket(Integer bucketId) { + LockCounter lock; + + synchronized (bucketMapLock) { + lock = bucketMapLock.get(bucketId); + + if (lock == null) { + lock = getLock(); + bucketMapLock.put(bucketId, lock); + } + + lock.count++; + } + + return lock; + } + + public void releaseLockForBucket(Integer bucketId) { + releaseLockForBucket(bucketId, bucketMapLock.get(bucketId)); + } + + public void releaseLockForBucket(Integer bucketId, LockCounter lock) { + synchronized (bucketMapLock) { + lock.count--; + + if (lock.count == 0) { + bucketMapLock.remove(bucketId); + releaseLock(lock); + } + } + } + + public void addCallToMinuteQueue(ApiCall call) { + apiCallsPerMinuteQueue.add(call); + } + + public boolean removeCallFromMinuteQueue(ApiCall call) { + return apiCallsPerMinuteQueue.remove(call); + } + + /** + * Retrieves, but does not remove, the head of this queue, or returns null if this queue is empty. + * @param call + * @return + */ + public ApiCall peekCallFromMinuteQueue() { + return this.apiCallsPerMinuteQueue.peek(); + } + + public Iterator getIteratorFromMinuteQueue() { + return this.apiCallsPerMinuteQueue.iterator(); + } + + public void addCallToSecondQueue(ApiCall call) { + apiCallsPerSecondQueue.add(call); + } + + public boolean removeCallFromSecondQueue(ApiCall call) { + return apiCallsPerSecondQueue.remove(call); + } + + /** + * Retrieves, but does not remove, the head of this queue, or returns null if this queue is empty. + * @param call + * @return + */ + public ApiCall peekCallFromSecondQueue() { + return this.apiCallsPerSecondQueue.peek(); + } + + public Iterator getIteratorFromSecondQueue() { + return this.apiCallsPerSecondQueue.iterator(); + } + + + @Override + public void usedBucketIdsRemoved(Integer id) { + removeFromRateMap(id); + + } + /******************************************************************************************************************/ + + public void putInRateMap(Integer key, GatewayRate rate) { + gatewayRateMap.put(key,rate); + } + + public GatewayRate getFromRateMap(Integer key) { + return gatewayRateMap.get(key); + } + + public GatewayRate removeFromRateMap(Integer key) { + return this.gatewayRateMap.remove(key); + } + + public Iterator getIteratorFromRateMapApiCallsKeys() { + return this.gatewayRateMap.keySet().iterator(); + } + + public void putInQueueRateMap(Integer key, GatewayQueueRate rate) { + gatewayQueueRateMap.put(key,rate); + } + + public GatewayQueueRate getFromQueueRateMap(Integer key) { + return gatewayQueueRateMap.get(key); + } + + public GatewayQueueRate removeFromQueueRateMap(Integer key) { + return this.gatewayQueueRateMap.remove(key); + } + + public Iterator getIteratorFromQueueRateMapApiCallsKeys() { + return this.gatewayQueueRateMap.keySet().iterator(); + } + + +} diff --git a/exposure-engine/gateway-rate-limits-manager/src/main/java/com/alu/e3/rate/manager/GatewayRateManager.java b/exposure-engine/gateway-rate-limits-manager/src/main/java/com/alu/e3/rate/manager/GatewayRateManager.java new file mode 100644 index 0000000..34a959c --- /dev/null +++ b/exposure-engine/gateway-rate-limits-manager/src/main/java/com/alu/e3/rate/manager/GatewayRateManager.java @@ -0,0 +1,255 @@ +/** + * Copyright © 2012 Alcatel-Lucent. + * + * See the NOTICE file distributed with this work for additional + * information regarding copyright ownership. + * Licensed to you 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 com.alu.e3.rate.manager; + +import java.util.HashSet; +import java.util.Iterator; + +import org.slf4j.Logger; +import org.slf4j.LoggerFactory; + +import com.alu.e3.common.E3Constant; +import com.alu.e3.common.camel.AuthIdentity; +import com.alu.e3.common.osgi.api.IDataManager; +import com.alu.e3.data.IDataManagerUsedBucketIdsListener; +import com.alu.e3.data.model.CallDescriptor; +import com.alu.e3.data.model.Limit; +import com.alu.e3.rate.manager.GatewayDataManager.LockCounter; +import com.alu.e3.rate.manager.IGatewayRateValidator.ApiCallStatus; +import com.alu.e3.rate.manager.IGatewayRateValidator.RateLimitParams; +import com.alu.e3.rate.model.ApiCall; +import com.alu.e3.rate.model.GatewayQueueRate; +import com.alu.e3.rate.model.GatewayRate; +import com.alu.e3.rate.model.LimitCheckResult; + +public class GatewayRateManager implements IGatewayRateManager { + + private static final Logger logger = LoggerFactory.getLogger(GatewayRateManager.class); + + private IDataManager dataManager; + private IGatewayRateValidator gatewayRateValidator; + + private GatewayDataManager gdm; + + private Object lockUpdateSecondQueues = new Object(); + private Object lockUpdateMinuteQueues = new Object(); + + public void init() { + this.dataManager.addListener(this.gdm); + } + + public void destroy(){ + this.dataManager.removeListener(this.gdm); + } + + public void setDataManager(IDataManager dataManager) { + this.dataManager = dataManager; + } + + public void setGdm(GatewayDataManager gdm) { + this.gdm = gdm; + } + + public void setGatewayRateValidator(IGatewayRateValidator gatewayRateValidator) { + this.gatewayRateValidator = gatewayRateValidator; + } + + public void updateQueues(long currentTime) { + ApiCall oldestCall = null; + + // update this.apiCallsPerMinuteQueue to remove call older than 1 minute + boolean removed = true; + while (removed) { + removed = false; + synchronized(lockUpdateMinuteQueues) { + oldestCall = this.gdm.peekCallFromMinuteQueue(); + if ((oldestCall!=null) && (currentTime - oldestCall.callTime > 60000)) { + removed = this.gdm.removeCallFromMinuteQueue(oldestCall); + } + } + + // if the call was failed then it was not counted so no need to decrease the counter + if (removed && oldestCall.callSuccess) { + LockCounter lock = this.gdm.getLockForBucket(oldestCall.bucketID); + + synchronized (lock) { + GatewayRate gr = gatewayRateValidator.getRateForBucket(oldestCall.bucketID); + gr.localApiCallsSinceOneMinute--; + if (!oldestCall.countedInLastPeriodMinute) { + // if the call was after the last collect and older than 1 minute + // then we must count it + GatewayQueueRate gqr = gatewayRateValidator.getQueueRateForBucket(oldestCall.bucketID); + gqr.localApiCallsInLastPeriodMinute++; + } + this.gdm.releaseLockForBucket(oldestCall.bucketID, lock); + } + } + } + + // update this.apiCallsPerSecondQueue to remove call older than 1s + removed = true; + while (removed) { + removed = false; + synchronized(lockUpdateSecondQueues) { + oldestCall = this.gdm.peekCallFromSecondQueue(); + if ((oldestCall!=null) && (currentTime - oldestCall.callTime > 1000)) { + removed = this.gdm.removeCallFromSecondQueue(oldestCall); + } + } + if (removed && oldestCall.callSuccess) { + LockCounter lock = this.gdm.getLockForBucket(oldestCall.bucketID); + + synchronized (lock) { + GatewayRate gr = gatewayRateValidator.getRateForBucket(oldestCall.bucketID); + gr.localApiCallsSinceOneSecond--; + if (!oldestCall.countedInLastPeriodSecond) { + // if the call was after the last collect and older than 1 second + // then we must count it + GatewayQueueRate gqr = gatewayRateValidator.getQueueRateForBucket(oldestCall.bucketID); + gqr.localApiCallsInLastPeriodSecond++; + } + this.gdm.releaseLockForBucket(oldestCall.bucketID, lock); + } + } + } + } + + + + + + @Override + public LimitCheckResult isAllowed(AuthIdentity authIdentity, boolean isTDREnabled) { + long currentTime = System.currentTimeMillis(); + + updateQueues(currentTime); + + ApiCallStatus apiCallStatus = new ApiCallStatus(); + apiCallStatus.apiCallIsSuccess = true; + apiCallStatus.apiCallAction = null; + + RateLimitParams params = new RateLimitParams(); + params.isTDREnabled = isTDREnabled; + params.result = new LimitCheckResult(); + params.authIdentity = authIdentity; + + boolean mustResetRateLimit = gatewayRateValidator.isRateLimitInvalid(currentTime); + + // contain the id of the lock to unlocks locks in case of throw exception + HashSet lockedSet = new HashSet(); + + try { + // step1 : test if call is success + Iterator it = authIdentity.getCallDescriptors().iterator(); + Limit limit = new Limit(); + + while (it.hasNext()) { + CallDescriptor callDescriptor = it.next(); + Integer bucketID = callDescriptor.getBucketId(); + Integer contextId = callDescriptor.getContextId(); + + this.dataManager.fillLimitsById(contextId, limit); + + if ((limit.getQuotaPerDay()!=null) || (limit.getQuotaPerWeek()!=null) || (limit.getQuotaPerMonth()!=null) + || (limit.getRateLimitPerMinute()!=null) || (limit.getRateLimitPerSecond()!=null)) { + + LockCounter lock = this.gdm.getLockForBucket(bucketID); + + synchronized (lock) { + + lockedSet.add(bucketID); + + GatewayRate gr = gatewayRateValidator.getRateForBucket(bucketID, limit, mustResetRateLimit); + + gatewayRateValidator.updateRateLimitAndQuotaValues(gr, limit, currentTime); + + params.gr = gr; + params.limit = limit; + params.callDescriptor = callDescriptor; + + gatewayRateValidator.checkRateLimitAndQuota(apiCallStatus, params); + + this.gdm.releaseLockForBucket(bucketID, lock); + lockedSet.remove(bucketID); + } + } + } + + // TODO: maybe increment always in previous loop and decrement all gr only if call was failed + // step2: save data for call success or fail + it = authIdentity.getCallDescriptors().iterator(); + while (it.hasNext()) + { + CallDescriptor callDescriptor = it.next(); + Integer bucketID = callDescriptor.getBucketId(); + Integer contextId = callDescriptor.getContextId(); + this.dataManager.fillLimitsById(contextId, limit); + + if ((limit.getQuotaPerDay()!=null) || (limit.getQuotaPerWeek()!=null) || (limit.getQuotaPerMonth()!=null) + || (limit.getRateLimitPerMinute()!=null) || (limit.getRateLimitPerSecond()!=null)) + { + LockCounter lock = this.gdm.getLockForBucket(bucketID); + + synchronized (lock) { + + GatewayRate gr = gatewayRateValidator.getRateForBucket(bucketID); + GatewayQueueRate gqr = gatewayRateValidator.getQueueRateForBucket(bucketID); + + if (apiCallStatus.apiCallIsSuccess) + { + gr.localApiCallsSinceOneMinute++; + gr.localApiCallsSinceOneSecond++; + gr.localApiCallsSinceOneDay++; + gr.localApiCallsSinceOneWeek++; + gr.localApiCallsSinceOneMonth++; + gqr.localApiCallsInFirstPeriod++; + } + + gatewayRateValidator.updateRateWithStatus(gr, apiCallStatus); + + gqr.localApiSpeedInFirstPeriod++; + ApiCall call = new ApiCall(gr.bucketID, currentTime); + call.callSuccess = apiCallStatus.apiCallIsSuccess; + this.gdm.addCallToMinuteQueue(call); + this.gdm.addCallToSecondQueue(call); + + this.gdm.releaseLockForBucket(bucketID, lock); + lockedSet.remove(bucketID); + } + } + } + } + catch (Exception e) { + logger.error("Error checking if a route isAllowed in GatewayRateManager due to an exception", e); + apiCallStatus.apiCallAction = E3Constant.DEFAULT_ERROR_ACTION; + apiCallStatus.apiCallIsSuccess = false; + params.result.setActionTypeMessage(e.toString()); + Iterator it = lockedSet.iterator(); + while (it.hasNext()) + { + Integer id = it.next(); + this.gdm.releaseLockForBucket(id); + } + } + + params.result.setActionType(apiCallStatus.apiCallAction); + + return params.result; + } +} \ No newline at end of file diff --git a/exposure-engine/gateway-rate-limits-manager/src/main/java/com/alu/e3/rate/manager/GatewayRateValidator.java b/exposure-engine/gateway-rate-limits-manager/src/main/java/com/alu/e3/rate/manager/GatewayRateValidator.java new file mode 100644 index 0000000..2cc9dcd --- /dev/null +++ b/exposure-engine/gateway-rate-limits-manager/src/main/java/com/alu/e3/rate/manager/GatewayRateValidator.java @@ -0,0 +1,219 @@ +/** + * Copyright © 2012 Alcatel-Lucent. + * + * See the NOTICE file distributed with this work for additional + * information regarding copyright ownership. + * Licensed to you 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 com.alu.e3.rate.manager; + +import java.util.ArrayList; +import java.util.List; + +import org.slf4j.Logger; +import org.slf4j.LoggerFactory; + +import com.alu.e3.common.E3Constant; +import com.alu.e3.common.caching.IEntryListener; +import com.alu.e3.common.osgi.api.ITopologyClient; +import com.alu.e3.data.DataEntryEvent; +import com.alu.e3.data.model.Instance; +import com.alu.e3.data.model.Limit; +import com.alu.e3.rate.model.GatewayQueueRate; +import com.alu.e3.rate.model.GatewayRate; + +public class GatewayRateValidator implements IGatewayRateValidator, IEntryListener> { + + private static final Logger logger = LoggerFactory.getLogger(GatewayRateValidator.class); + + private GatewayDataManager gdm; + private ITopologyClient topologyClient; + + private int gatewaysCount = 1; + + public void setTopologyClient(ITopologyClient topologyClient) { + this.topologyClient = topologyClient; + } + + public void setGatewayDataManager(GatewayDataManager gdm) { + this.gdm = gdm; + } + + public void init() { + updateGatewaysCount(); + topologyClient.addInstanceTypeListener(this); + } + + public void destroy() { + topologyClient.removeInstanceTypeListener(this); + } + + @Override + public GatewayRate getRateForBucket(Integer bucketID) { + GatewayRate gr = this.gdm.getFromRateMap(bucketID); + + if (gr == null) { + gr = new GatewayRate(bucketID); + this.gdm.putInRateMap(gr.bucketID, gr); + } + + return gr; + } + + @Override + public GatewayRate getRateForBucket(Integer bucketID, Limit limit, boolean mustResetRateLimit) { + GatewayRate gr = this.gdm.getFromRateMap(bucketID); + + if (gr == null) { + gr = new GatewayRate(bucketID, limit.getCreatedDate()); + this.gdm.putInRateMap(gr.bucketID, gr); + } + + if (mustResetRateLimit) { + logger.debug("rate limit is reset"); + gr.initialized = false; // force a reset of the rate limit + } + + return gr; + } + + @Override + public GatewayQueueRate getQueueRateForBucket(Integer bucketID) { + GatewayQueueRate gqr = this.gdm.getFromQueueRateMap(bucketID); + + if (gqr == null) { + gqr = new GatewayQueueRate(bucketID); + this.gdm.putInQueueRateMap(gqr.bucketID, gqr); + } + + return gqr; + } + + @Override + public boolean isRateLimitInvalid(long currentTime) { + // don't handle any expiration time + return false; + } + + private int resetRateLimit(long threshold) { + int rateLimit; + + if (threshold == -1) { + rateLimit = -1; + } + else { + rateLimit = (int)(threshold / this.gatewaysCount); + } + + return rateLimit; + } + + @Override + public void updateRateLimitAndQuotaValues(GatewayRate gatewayRate, Limit limit, long currentTime) { + if (!gatewayRate.initialized) { + + if (limit.getRateLimitPerSecond() != null) { + gatewayRate.localRateLimitSecond = resetRateLimit(limit.getRateLimitPerSecond().getThreshold()); + } + + if (limit.getRateLimitPerMinute() != null) { + gatewayRate.localRateLimitMinute = resetRateLimit(limit.getRateLimitPerMinute().getThreshold()); + } + + if (limit.getQuotaPerDay() != null) { + gatewayRate.localQuotaLimitDay = resetRateLimit(limit.getQuotaPerDay().getThreshold()); + } + + if (limit.getQuotaPerWeek() != null) { + gatewayRate.localQuotaLimitWeek = resetRateLimit(limit.getQuotaPerWeek().getThreshold()); + } + + if (limit.getQuotaPerMonth() != null) { + gatewayRate.localQuotaLimitMonth = resetRateLimit(limit.getQuotaPerMonth().getThreshold()); + } + + gatewayRate.initialized = true; + } + } + + private boolean isValueOverLimit(long value, long limit) { + return (limit != -1) && (value >= limit); + } + + @Override + public void checkRateLimitAndQuota(ApiCallStatus apiCallStatus, RateLimitParams params) { + GatewayRate gr = params.gr; + Limit limit = params.limit; + + if (isValueOverLimit(gr.localApiCallsSinceOneSecond, gr.localRateLimitSecond)) { + apiCallStatus.apiCallIsSuccess = false; + apiCallStatus.apiCallAction = (limit.getRateLimitPerSecond().getAction() != null) ? limit.getRateLimitPerSecond().getAction() : E3Constant.DEFAULT_ERROR_ACTION; + } + else if (isValueOverLimit(gr.localApiCallsSinceOneMinute, gr.localRateLimitMinute)) { + apiCallStatus.apiCallIsSuccess = false; + apiCallStatus.apiCallAction = (limit.getRateLimitPerMinute().getAction() != null) ? limit.getRateLimitPerMinute().getAction() : E3Constant.DEFAULT_ERROR_ACTION; + } + else if (isValueOverLimit(gr.localApiCallsSinceOneDay, gr.localQuotaLimitDay)) { + apiCallStatus.apiCallIsSuccess = false; + apiCallStatus.apiCallAction = (limit.getQuotaPerDay().getAction() != null) ? limit.getQuotaPerDay().getAction() : E3Constant.DEFAULT_ERROR_ACTION; + } + else if (isValueOverLimit(gr.localApiCallsSinceOneWeek, gr.localQuotaLimitWeek)) { + apiCallStatus.apiCallIsSuccess = false; + apiCallStatus.apiCallAction = (limit.getQuotaPerWeek().getAction() != null) ? limit.getQuotaPerWeek().getAction() : E3Constant.DEFAULT_ERROR_ACTION; + } + else if (isValueOverLimit(gr.localApiCallsSinceOneMonth, gr.localQuotaLimitMonth)) { + apiCallStatus.apiCallIsSuccess = false; + apiCallStatus.apiCallAction = (limit.getQuotaPerMonth().getAction() != null) ? limit.getQuotaPerMonth().getAction() : E3Constant.DEFAULT_ERROR_ACTION; + } + } + + @Override + public void updateRateWithStatus(GatewayRate gatewayRate, ApiCallStatus apiCallStatus) { + // nothing to do + } + + @Override + public void entryAdded(DataEntryEvent> event) { + if (E3Constant.E3GATEWAY_ACTIVE.equals(event.getKey())) { + updateGatewaysCount(); + } + } + + @Override + public void entryUpdated(DataEntryEvent> event) { + if (E3Constant.E3GATEWAY_ACTIVE.equals(event.getKey())) { + updateGatewaysCount(); + } + } + + @Override + public void entryRemoved(DataEntryEvent> event) { + if (E3Constant.E3GATEWAY_ACTIVE.equals(event.getKey())) { + updateGatewaysCount(); + } + } + + private void updateGatewaysCount() { + List l = this.topologyClient.getAllInstancesOfType(E3Constant.E3GATEWAY_ACTIVE); + if ((l!=null) ) + { + this.gatewaysCount = l.size(); + + if (this.gatewaysCount == 0) { + logger.error("updateGatewaysCount: gateway count is 0"); + this.gatewaysCount = 1; + } + } + } +} diff --git a/exposure-engine/gateway-rate-limits-manager/src/main/java/com/alu/e3/rate/manager/IGatewayRateManager.java b/exposure-engine/gateway-rate-limits-manager/src/main/java/com/alu/e3/rate/manager/IGatewayRateManager.java new file mode 100644 index 0000000..8fb5974 --- /dev/null +++ b/exposure-engine/gateway-rate-limits-manager/src/main/java/com/alu/e3/rate/manager/IGatewayRateManager.java @@ -0,0 +1,28 @@ +/** + * Copyright © 2012 Alcatel-Lucent. + * + * See the NOTICE file distributed with this work for additional + * information regarding copyright ownership. + * Licensed to you 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 com.alu.e3.rate.manager; + +import com.alu.e3.common.camel.AuthIdentity; +import com.alu.e3.rate.model.LimitCheckResult; + + +public interface IGatewayRateManager { + + LimitCheckResult isAllowed (AuthIdentity authIdentity, boolean isTDREnabled); +} diff --git a/exposure-engine/gateway-rate-limits-manager/src/main/java/com/alu/e3/rate/manager/IGatewayRateValidator.java b/exposure-engine/gateway-rate-limits-manager/src/main/java/com/alu/e3/rate/manager/IGatewayRateValidator.java new file mode 100644 index 0000000..d74d580 --- /dev/null +++ b/exposure-engine/gateway-rate-limits-manager/src/main/java/com/alu/e3/rate/manager/IGatewayRateValidator.java @@ -0,0 +1,52 @@ +/** + * Copyright © 2012 Alcatel-Lucent. + * + * See the NOTICE file distributed with this work for additional + * information regarding copyright ownership. + * Licensed to you 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 com.alu.e3.rate.manager; + +import com.alu.e3.common.camel.AuthIdentity; +import com.alu.e3.data.model.CallDescriptor; +import com.alu.e3.data.model.Limit; +import com.alu.e3.data.model.enumeration.ActionType; +import com.alu.e3.rate.model.GatewayQueueRate; +import com.alu.e3.rate.model.GatewayRate; +import com.alu.e3.rate.model.LimitCheckResult; + +public interface IGatewayRateValidator { + + class ApiCallStatus { + public boolean apiCallIsSuccess; + public ActionType apiCallAction; + } + + class RateLimitParams { + public GatewayRate gr; + public Limit limit; + public boolean isTDREnabled; + public LimitCheckResult result; + public AuthIdentity authIdentity; + public CallDescriptor callDescriptor; + } + + GatewayRate getRateForBucket(Integer bucketID); + GatewayRate getRateForBucket(Integer bucketID, Limit limit, boolean mustResetRateLimit); + GatewayQueueRate getQueueRateForBucket(Integer bucketID); + boolean isRateLimitInvalid(long currentTime); + void updateRateLimitAndQuotaValues(GatewayRate gatewayRate, Limit limit, long currentTime); + void checkRateLimitAndQuota(ApiCallStatus apiCallStatus, RateLimitParams params); + void updateRateWithStatus(GatewayRate gatewayRate, ApiCallStatus apiCallStatus); +} diff --git a/exposure-engine/gateway-rate-limits-manager/src/main/java/com/alu/e3/rate/manager/IRateManager.java b/exposure-engine/gateway-rate-limits-manager/src/main/java/com/alu/e3/rate/manager/IRateManager.java new file mode 100644 index 0000000..f1ee23d --- /dev/null +++ b/exposure-engine/gateway-rate-limits-manager/src/main/java/com/alu/e3/rate/manager/IRateManager.java @@ -0,0 +1,26 @@ +/** + * Copyright © 2012 Alcatel-Lucent. + * + * See the NOTICE file distributed with this work for additional + * information regarding copyright ownership. + * Licensed to you 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 com.alu.e3.rate.manager; + +import com.alu.e3.common.camel.AuthIdentity; + +public interface IRateManager { + + boolean isAllowed (AuthIdentity authIdentity); +} diff --git a/exposure-engine/gateway-rate-limits-manager/src/main/java/com/alu/e3/rate/model/LimitCheckResult.java b/exposure-engine/gateway-rate-limits-manager/src/main/java/com/alu/e3/rate/model/LimitCheckResult.java new file mode 100644 index 0000000..ff63a4b --- /dev/null +++ b/exposure-engine/gateway-rate-limits-manager/src/main/java/com/alu/e3/rate/model/LimitCheckResult.java @@ -0,0 +1,154 @@ +/** + * Copyright © 2012 Alcatel-Lucent. + * + * See the NOTICE file distributed with this work for additional + * information regarding copyright ownership. + * Licensed to you 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 com.alu.e3.rate.model; + +import java.util.ArrayList; +import java.util.HashMap; +import java.util.List; +import java.util.Map; + +import com.alu.e3.data.model.enumeration.ActionType; +import com.alu.e3.data.model.sub.TdrGenerationRule; + +/** + * This class is used as the result to the IGatewayRateManager::isAllowed function. This enables us to get more data for TDRs + * than simply returning the ActionType enum. + * + * + */ +public class LimitCheckResult { + /** + * The Action to be taken by the gateway + */ + private ActionType actionType; + + /** + * The messace linked to the ActionType + */ + private String actionTypeMessage = ""; + + /** + * Whether or not a second ratelimit has been breached + */ + private boolean overSecond = false; + + /** + * Whether or not a minute ratelimit has been breached + */ + private boolean overMinute = false; + + /** + * Whether or not a daily quota has been breached + */ + private boolean overDay = false; + + /** + * whether or not a weekly quota has been breached + */ + private boolean overWeek = false; + + /** + * Whether or not a monthly quota has been breached + */ + private boolean overMonth = false; + + /** + * The tdrValues that should be inserted into the TDR + */ + private Map> tdrValues = new HashMap>(); + + public void addTdrValue(String tdrTypeName, TdrGenerationRule rule){ + if(!tdrValues.containsKey(tdrTypeName)){ + tdrValues.put(tdrTypeName, new ArrayList()); + } + + tdrValues.get(tdrTypeName).add(rule); + } + + public Map> getTdrValues(){ + return this.tdrValues; + } + + + public boolean isOverQuota(){ + return overSecond || overMinute || overDay || overWeek || overMonth; + } + + public ActionType getActionType() { + return actionType; + } + + public void setActionType(ActionType actionType) { + this.actionType = actionType; + } + + /** + * @return the actionTypeMessage + */ + public String getActionTypeMessage() { + return actionTypeMessage; + } + + /** + * @param actionTypeMessage the actionTypeMessage to set + */ + public void setActionTypeMessage(String actionTypeMessage) { + this.actionTypeMessage = actionTypeMessage; + } + + public boolean isOverSecond() { + return overSecond; + } + + public void setOverSecond(boolean overSecond) { + this.overSecond = overSecond; + } + + public boolean isOverMinute() { + return overMinute; + } + + public void setOverMinute(boolean overMinute) { + this.overMinute = overMinute; + } + + public boolean isOverDay() { + return overDay; + } + + public void setOverDay(boolean overDay) { + this.overDay = overDay; + } + + public boolean isOverWeek() { + return overWeek; + } + + public void setOverWeek(boolean overWeek) { + this.overWeek = overWeek; + } + + public boolean isOverMonth() { + return overMonth; + } + + public void setOverMonth(boolean overMonth) { + this.overMonth = overMonth; + } +} diff --git a/exposure-engine/gateway-rate-limits-manager/src/main/resources/META-INF/services/org/apache/camel/rate b/exposure-engine/gateway-rate-limits-manager/src/main/resources/META-INF/services/org/apache/camel/rate new file mode 100644 index 0000000..afc1e84 --- /dev/null +++ b/exposure-engine/gateway-rate-limits-manager/src/main/resources/META-INF/services/org/apache/camel/rate @@ -0,0 +1 @@ +class=com.alu.e3.auth.camel.component.RateComponent \ No newline at end of file diff --git a/exposure-engine/gateway-rate-limits-manager/src/main/resources/META-INF/spring-optional/gateway-rate.beans-os.xml b/exposure-engine/gateway-rate-limits-manager/src/main/resources/META-INF/spring-optional/gateway-rate.beans-os.xml new file mode 100644 index 0000000..3267dd7 --- /dev/null +++ b/exposure-engine/gateway-rate-limits-manager/src/main/resources/META-INF/spring-optional/gateway-rate.beans-os.xml @@ -0,0 +1,25 @@ + + + + + + + + + + + + diff --git a/exposure-engine/gateway-rate-limits-manager/src/main/resources/META-INF/spring-optional/gateway-rate.beans.xml b/exposure-engine/gateway-rate-limits-manager/src/main/resources/META-INF/spring-optional/gateway-rate.beans.xml new file mode 100644 index 0000000..d3dcbf6 --- /dev/null +++ b/exposure-engine/gateway-rate-limits-manager/src/main/resources/META-INF/spring-optional/gateway-rate.beans.xml @@ -0,0 +1,39 @@ + + + + + + + + + + + + + + + + + + + + + + + + + + \ No newline at end of file diff --git a/exposure-engine/gateway-rate-limits-manager/src/test/java/com/alu/e3/rate/camel/RateLimitProcessorTest.java b/exposure-engine/gateway-rate-limits-manager/src/test/java/com/alu/e3/rate/camel/RateLimitProcessorTest.java new file mode 100644 index 0000000..fc738b7 --- /dev/null +++ b/exposure-engine/gateway-rate-limits-manager/src/test/java/com/alu/e3/rate/camel/RateLimitProcessorTest.java @@ -0,0 +1,227 @@ +/** + * Copyright © 2012 Alcatel-Lucent. + * + * See the NOTICE file distributed with this work for additional + * information regarding copyright ownership. + * Licensed to you 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 com.alu.e3.rate.camel; + +import org.apache.camel.CamelContext; +import org.apache.camel.EndpointInject; +import org.apache.camel.Exchange; +import org.apache.camel.Processor; +import org.apache.camel.Produce; +import org.apache.camel.ProducerTemplate; +import org.apache.camel.component.mock.MockEndpoint; +import org.junit.Test; +import org.junit.runner.RunWith; +import org.springframework.beans.factory.annotation.Autowired; +import org.springframework.test.annotation.DirtiesContext; +import org.springframework.test.context.ContextConfiguration; +import org.springframework.test.context.junit4.SpringJUnit4ClassRunner; + +import com.alu.e3.common.camel.AuthIdentity; +import com.alu.e3.common.camel.ExchangeConstantKeys; +import com.alu.e3.data.model.Auth; +import com.alu.e3.data.model.enumeration.ActionType; +import com.alu.e3.rate.manager.IGatewayRateManager; +import com.alu.e3.rate.model.LimitCheckResult; + +@RunWith(SpringJUnit4ClassRunner.class) +@ContextConfiguration(locations = { "classpath:/spring/gateway-rate.rate-limit-test.xml" }) +public class RateLimitProcessorTest { + + @Autowired + protected CamelContext camelContext; + + @EndpointInject(uri = "mock:checkAuth") + protected MockEndpoint checkAuth; + + @EndpointInject(uri = "mock:checkRate") + protected MockEndpoint checkRate; + + @EndpointInject(uri = "mock:testMessage") + protected MockEndpoint testMessage; + + @EndpointInject(uri = "mock:handleException") + protected MockEndpoint handleException; + + @Produce(uri = "direct:test") + protected ProducerTemplate producerTemplate; + + @Test + @DirtiesContext + public void testRateOK() throws Exception { + AuthIdentity authIdentity = new AuthIdentity(); + Auth auth = new Auth(); + auth.setId("abc"); + authIdentity.setAuth(auth); + + AuthProcessorMock authProcessor = new AuthProcessorMock(authIdentity); + + checkAuth.whenAnyExchangeReceived(authProcessor); + + RateLimitProcessor rateProcessor = new RateLimitProcessor(); + rateProcessor.setGatewayRateMger(new IGatewayRateManager() { + + @Override + public LimitCheckResult isAllowed(AuthIdentity authIdentity, boolean isTDREnabled) { + LimitCheckResult result = new LimitCheckResult(); + return result; + } + + }); + + checkRate.whenAnyExchangeReceived(rateProcessor); + + testMessage.setExpectedMessageCount(1); + + producerTemplate.requestBody(String.class); + + testMessage.assertIsSatisfied(); + } + + @Test + @DirtiesContext + public void testRateKO() throws Exception { + AuthIdentity authIdentity = new AuthIdentity(); + Auth auth = new Auth(); + auth.setId("ko"); + authIdentity.setAuth(auth); + + AuthProcessorMock authProcessor = new AuthProcessorMock(authIdentity); + + checkAuth.whenAnyExchangeReceived(authProcessor); + + RateLimitProcessor rateProcessor = new RateLimitProcessor(); + rateProcessor.setGatewayRateMger(new IGatewayRateManager() { + + @Override + public LimitCheckResult isAllowed(AuthIdentity authIdentity, boolean isTDREnabled) { + LimitCheckResult result = new LimitCheckResult(); + result.setActionType(ActionType.REJECT); + return result; + } + }); + + checkRate.whenAnyExchangeReceived(rateProcessor); + + testMessage.setExpectedMessageCount(0); + testMessage.allMessages().body().isNull(); + + handleException.setExpectedMessageCount(1); + handleException.message(0).property("CamelExceptionCaught").equals("com.alu.e3.rate.RatePolicyRuntimeException: Rate limit exceeded"); + + producerTemplate.requestBody(String.class); + + testMessage.assertIsSatisfied(); + } + + @Test + @DirtiesContext + public void testAuthIdentityRequired() throws Exception { + RateLimitProcessor rateProcessor = new RateLimitProcessor(); + rateProcessor.setGatewayRateMger(new NeverAllowed()); + + checkRate.whenAnyExchangeReceived(rateProcessor); + + testMessage.setExpectedMessageCount(0); + testMessage.allMessages().body().isNull(); + + handleException.setExpectedMessageCount(1); + handleException.message(0).property("CamelExceptionCaught").equals("The property " + ExchangeConstantKeys.E3_AUTH_IDENTITY.toString() + " is required to check the rate limits."); + + producerTemplate.requestBody(String.class); + + testMessage.assertIsSatisfied(); + handleException.assertIsSatisfied(); + } + + @Test + @DirtiesContext + public void testRateLimitExeeded() throws Exception { + RateLimitProcessor rateProcessor = new RateLimitProcessor(); + rateProcessor.setGatewayRateMger(new NeverAllowed()); + + checkRate.whenAnyExchangeReceived(rateProcessor); + + testMessage.setExpectedMessageCount(0); + testMessage.allMessages().body().isNull(); + + handleException.setExpectedMessageCount(1); + handleException.message(0).property("CamelExceptionCaught").equals("com.alu.e3.rate.RatePolicyRuntimeException: Rate limit exceeded"); + + producerTemplate.requestBody(String.class); + + testMessage.assertIsSatisfied(); + handleException.assertIsSatisfied(); + } + + @Test + @DirtiesContext + public void testRateLimitNotExeeded() throws Exception { + AuthProcessorMock authProcessor = new AuthProcessorMock(new AuthIdentity()); + + checkAuth.whenAnyExchangeReceived(authProcessor); + + RateLimitProcessor rateProcessor = new RateLimitProcessor(); + rateProcessor.setGatewayRateMger(new AlwaysAllowed()); + + checkRate.whenAnyExchangeReceived(rateProcessor); + + testMessage.setExpectedMessageCount(1); + + producerTemplate.requestBody(String.class); + + testMessage.assertIsSatisfied(); + } + + class AlwaysAllowed implements IGatewayRateManager { + + @Override + public LimitCheckResult isAllowed(AuthIdentity authIdentity, boolean isTDREnabled) { + LimitCheckResult result = new LimitCheckResult(); + return result; + } + + } + class NeverAllowed implements IGatewayRateManager { + + @Override + + public LimitCheckResult isAllowed(AuthIdentity authIdentity, boolean isTDREnabled) { + LimitCheckResult result = new LimitCheckResult(); + result.setActionType(ActionType.REJECT); + return result; + } + + } + + class AuthProcessorMock implements Processor { + + protected AuthIdentity authIdentity; + + public AuthProcessorMock(AuthIdentity authIdentity) { + super(); + this.authIdentity = authIdentity; + } + + @Override + public void process(Exchange exchange) throws Exception { + exchange.setProperty(ExchangeConstantKeys.E3_AUTH_IDENTITY.toString(), authIdentity); + } + + } +} diff --git a/exposure-engine/gateway-rate-limits-manager/src/test/resources/spring/gateway-rate.rate-limit-test.xml b/exposure-engine/gateway-rate-limits-manager/src/test/resources/spring/gateway-rate.rate-limit-test.xml new file mode 100644 index 0000000..6087b9b --- /dev/null +++ b/exposure-engine/gateway-rate-limits-manager/src/test/resources/spring/gateway-rate.rate-limit-test.xml @@ -0,0 +1,33 @@ + + + + + + java.lang.Exception + + true + + + + + + + + + + + + + \ No newline at end of file diff --git a/exposure-engine/pom.xml b/exposure-engine/pom.xml new file mode 100644 index 0000000..d86e399 --- /dev/null +++ b/exposure-engine/pom.xml @@ -0,0 +1,204 @@ + + 4.0.0 + + com.alu.e3 + exposure-engine + E3 Exposure Engine + http://www.alcatel-lucent.com + 1.0.1 + + pom + + + 4.3.1-fuse-01-09 + 2.6.0-fuse-01-09 + 7.3.1.v20110307 + 2.2 + 1.7.0 + 3.1_5 + 2.3.3 + 3.0.5.RELEASE + UTF-8 + + + + common + topology + system-manager + auth-manager + provisioning + tdr-lib + gateway-common + gateway-rate-limits-manager + + + + + + org.apache.maven.plugins + maven-compiler-plugin + 2.4 + + 1.6 + 1.6 + UTF-8 + true + + + + + + + + + + + + + + org.apache.camel + camel-core + ${camel.version} + provided + + + com.sun + tools + + + + + org.apache.camel + camel-spring + ${camel.version} + provided + + + com.sun + tools + + + + + org.ops4j.pax.logging + pax-logging-api + 1.5.3 + provided + + + + org.apache.servicemix.specs + org.apache.servicemix.specs.jsr311-api-1.1 + 1.7.0 + provided + + + + org.apache.cxf + cxf-rt-frontend-jaxrs + ${cxf.version} + provided + + + + ${servicemix.specs.version} + org.apache.servicemix.specs + org.apache.servicemix.specs.jaxb-api-${jaxb.api.version} + provided + + + ${commons-httpclient.bundle.version} + org.apache.servicemix.bundles + org.apache.servicemix.bundles.commons-httpclient + provided + + + junit + junit + 4.8.2 + test + + + + org.springframework + spring-test + ${org.springframework.version} + test + + + + org.springframework + spring-core + ${org.springframework.version} + provided + + + + + org.springframework + spring-beans + ${org.springframework.version} + provided + + + + org.apache.cxf + cxf-bundle + 2.3.3 + test + + + + + org.eclipse.jetty + jetty-http + ${jetty.version} + provided + + + org.eclipse.jetty + jetty-io + ${jetty.version} + provided + + + org.eclipse.jetty + jetty-security + ${jetty.version} + provided + + + org.eclipse.jetty + jetty-server + ${jetty.version} + provided + + + org.eclipse.jetty + jetty-servlet + ${jetty.version} + provided + + + org.eclipse.jetty + jetty-servlets + ${jetty.version} + provided + + + org.eclipse.jetty + jetty-util + ${jetty.version} + provided + + + org.eclipse.jetty + jetty-xml + ${jetty.version} + provided + + + + \ No newline at end of file diff --git a/exposure-engine/provisioning/pom.xml b/exposure-engine/provisioning/pom.xml new file mode 100644 index 0000000..4c5b5a7 --- /dev/null +++ b/exposure-engine/provisioning/pom.xml @@ -0,0 +1,244 @@ + + + 4.0.0 + + + exposure-engine + com.alu.e3 + 1.0.1 + .. + + + provisioning + E3 Provisioning + http://www.alcatel-lucent.com + + + jar + + + 1.2.0 + + + + + com.alu.e3 + common + ${project.version} + jar + provided + + + com.alu.e3 + system-manager + ${project.version} + jar + provided + + + com.alu.e3 + topology + ${project.version} + jar + provided + + + + org.apache.camel + camel-cxf + ${camel.version} + provided + + + tools + com.sun + + + + + org.springframework + spring-core + ${org.springframework.version} + provided + + + + + org.springframework + spring-expression + ${org.springframework.version} + provided + + + + + org.springframework + spring-beans + ${org.springframework.version} + provided + + + + + org.springframework + spring-aop + ${org.springframework.version} + provided + + + + + org.springframework + spring-context + ${org.springframework.version} + provided + + + + + org.springframework + spring-context-support + ${org.springframework.version} + provided + + + + com.jayway.restassured + rest-assured + 1.6 + test + + + + org.apache.felix + org.apache.felix.framework + 3.0.9-fuse-03-11 + test + + + + + org.apache.camel + camel-freemarker + ${camel.version} + provided + + + tools + com.sun + + + + + commons-codec + commons-codec + 1.4 + provided + + + org.apache.camel + camel-test + ${camel.version} + test + + + tools + com.sun + + + + + org.apache.aries.jmx + org.apache.aries.jmx + 0.2-incubating + provided + + + org.springframework.osgi + spring-osgi-core + ${spring.osgi.version} + provided + + + org.springframework.aop + org.springframework + + + org.springframework.beans + org.springframework + + + org.springframework.context + org.springframework + + + org.springframework.core + org.springframework + + + + + org.springframework.osgi + spring-osgi-extender + ${spring.osgi.version} + provided + + + org.springframework.osgi + spring-osgi-io + ${spring.osgi.version} + provided + + + org.apache.servicemix.specs + org.apache.servicemix.specs.java-persistence-api-1.1.1 + 1.7.0 + provided + + + org.apache.servicemix.bundles + org.apache.servicemix.bundles.commons-dbcp + 1.2.2_6 + provided + + + org.springframework + spring-orm + 3.0.5.RELEASE + provided + + + org.apache.servicemix.bundles + org.apache.servicemix.bundles.openjpa + 1.2.1_3 + provided + + + org.hsqldb + com.springsource.org.hsqldb + 1.8.0.10 + provided + + + + org.apache.servicemix.bundles + org.apache.servicemix.bundles.commons-io + 1.4_1 + provided + + + + + \ No newline at end of file diff --git a/exposure-engine/provisioning/src/main/java/com/alu/e3/data/wrapper/BeanConverterUtil.java b/exposure-engine/provisioning/src/main/java/com/alu/e3/data/wrapper/BeanConverterUtil.java new file mode 100644 index 0000000..ee0e7b2 --- /dev/null +++ b/exposure-engine/provisioning/src/main/java/com/alu/e3/data/wrapper/BeanConverterUtil.java @@ -0,0 +1,1150 @@ +/** + * Copyright © 2012 Alcatel-Lucent. + * + * See the NOTICE file distributed with this work for additional + * information regarding copyright ownership. + * Licensed to you 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 com.alu.e3.data.wrapper; + +import java.util.ArrayList; +import java.util.List; +import java.util.Map; + +import com.alu.e3.data.model.Api; +import com.alu.e3.data.model.ApiDetail; +import com.alu.e3.data.model.Auth; +import com.alu.e3.data.model.AuthDetail; +import com.alu.e3.data.model.Certificate; +import com.alu.e3.data.model.CertificateDetail; +import com.alu.e3.data.model.KeyDetail; +import com.alu.e3.data.model.Policy; +import com.alu.e3.data.model.SSLCRL; +import com.alu.e3.data.model.enumeration.ActionType; +import com.alu.e3.data.model.enumeration.ApiNotificationFormat; +import com.alu.e3.data.model.enumeration.ApiSubscriptionStep; +import com.alu.e3.data.model.enumeration.ApiType; +import com.alu.e3.data.model.enumeration.HeaderTransformationAction; +import com.alu.e3.data.model.enumeration.HeaderTransformationType; +import com.alu.e3.data.model.enumeration.LoadBalancingType; +import com.alu.e3.data.model.enumeration.NBAuthType; +import com.alu.e3.data.model.enumeration.SchemaValidationEnum; +import com.alu.e3.data.model.enumeration.SoapVersionEnum; +import com.alu.e3.data.model.enumeration.StatusType; +import com.alu.e3.data.model.enumeration.TLSMode; +import com.alu.e3.data.model.sub.APIContext; +import com.alu.e3.data.model.sub.ConnectionParameters; +import com.alu.e3.data.model.sub.Context; +import com.alu.e3.data.model.sub.Counter; +import com.alu.e3.data.model.sub.FailOver; +import com.alu.e3.data.model.sub.ForwardProxy; +import com.alu.e3.data.model.sub.HTTPSType; +import com.alu.e3.data.model.sub.HeaderTransformation; +import com.alu.e3.data.model.sub.LoadBalancing; +import com.alu.e3.data.model.sub.QuotaRLBucket; +import com.alu.e3.data.model.sub.SBAuthentication; +import com.alu.e3.data.model.sub.TargetHealthCheck; +import com.alu.e3.data.model.sub.TargetHost; +import com.alu.e3.data.model.sub.TdrDynamicRule; +import com.alu.e3.data.model.sub.TdrGenerationRule; +import com.alu.e3.data.model.sub.TdrStaticRule; +import com.alu.e3.prov.restapi.model.ApiProxySettings; +import com.alu.e3.prov.restapi.model.AuthKeyAuth; +import com.alu.e3.prov.restapi.model.AuthType; +import com.alu.e3.prov.restapi.model.Authentication; +import com.alu.e3.prov.restapi.model.Authkey; +import com.alu.e3.prov.restapi.model.BasicAuth; +import com.alu.e3.prov.restapi.model.Data; +import com.alu.e3.prov.restapi.model.DynamicTdr; +import com.alu.e3.prov.restapi.model.IpWhiteListAuth; +import com.alu.e3.prov.restapi.model.Key; +import com.alu.e3.prov.restapi.model.NotificationFormat; +import com.alu.e3.prov.restapi.model.OAuth; +import com.alu.e3.prov.restapi.model.ProvisionAuthentication; +import com.alu.e3.prov.restapi.model.ResourceItem; +import com.alu.e3.prov.restapi.model.SSLCert; +import com.alu.e3.prov.restapi.model.SSLKey; +import com.alu.e3.prov.restapi.model.StaticTdr; +import com.alu.e3.prov.restapi.model.SubscriptionStep; +import com.alu.e3.prov.restapi.model.TdrData; +import com.alu.e3.prov.restapi.model.TdrEnabled; +import com.alu.e3.prov.restapi.model.TdrType; +import com.alu.e3.prov.restapi.model.Validation; +import com.alu.e3.prov.restapi.model.Validation.Schema; +import com.alu.e3.prov.restapi.model.WSSEAuth; + +public final class BeanConverterUtil { + + public static final com.alu.e3.prov.restapi.model.Api fromDataModel(Api api) { + if (api==null) throw new IllegalArgumentException("apiData must not be null"); + if (api.getApiDetail()==null) throw new IllegalArgumentException("apiData.detail must not be null"); + + com.alu.e3.prov.restapi.model.Api provisionData = new com.alu.e3.prov.restapi.model.Api(); + + provisionData.setId (api.getId()); + provisionData.setEndpoint (api.getApiDetail().getEndpoint()); + provisionData.setDisplayName (api.getApiDetail().getDisplayName()); + provisionData.setVersion (api.getApiDetail().getVersion()); + provisionData.setTdrEnabled (fromDataModelToTdr(api.getApiDetail().getTdrEnabled())); + provisionData.setType (fromDataModel(api.getApiDetail().getType())); + provisionData.setSubscriptionStep (fromDataModel(api.getApiDetail().getSubscriptionStep())); + provisionData.setNotificationFormat (fromDataModel(api.getApiDetail().getNotificationFormat())); + provisionData.getContexts().addAll (BeanConverterUtil.fromDataModels(api.getApiDetail().getContexts())); + provisionData.setAuthentication (fromDataModelToProvisionAuthentication(api.getApiDetail())); + provisionData.setTdr (fromDataModel(api.getTdrGenerationRule())); + provisionData.setTdrOnUse (api.getTdrOnUse()); + provisionData.setTdrOnLimitReached (api.getTdrOnLimitReached()); + provisionData.setStatus (fromDataModel(api.getApiDetail().getStatus())); + provisionData.setHttps (fromDataModel(api.getApiDetail().getHttps())); + + for(String keyname : api.getProperties().keySet()){ + Key k = new Key(); + k.setName(keyname); + k.setValue(api.getProperties().get(keyname)); + provisionData.getProperties().add(k); + } + + provisionData.setHeaderTransformations (BeanConverterUtil.fromDataModels(api.getHeaderTransformations())); + + provisionData.setAllowedHttpMethodsAsString(api.getApiDetail().getAllowedMethods()); + + provisionData.setValidation(fromDataModel(api.getValidation())); + provisionData.setHeaderTransEnabled(api.getHeaderTransEnabled()); + provisionData.setInternal(api.getInternal()); + + ApiProxySettings proxySettings = null; + + if(api.isUseGlobalProxy()){ + proxySettings = new ApiProxySettings(); + proxySettings.setGlobalProxy(new ApiProxySettings.GlobalProxy()); + }else if(api.getLocalProxy() != null){ + proxySettings = new ApiProxySettings(); + proxySettings.setLocalProxy(fromDataModel(api.getLocalProxy())); + } + provisionData.setProxySettings(proxySettings); + + return provisionData; + } + + public static final Api toDataModel(com.alu.e3.prov.restapi.model.Api provisionData) { + if (provisionData==null) throw new IllegalArgumentException("provisionData must not be null"); + + Api api = new Api(); + + api.setId (provisionData.getId()); + api.setTdrGenerationRule (toDataModel(provisionData.getTdr())); + //Not populated to WS + //api.setPolicyIds (null); + api.setTdrOnUse(provisionData.getTdrOnUse()); + api.setTdrOnLimitReached(provisionData.getTdrOnLimitReached()); + + for(Key prop : provisionData.getProperties()){ + api.getProperties().put(prop.getName(), prop.getValue()); + } + + api.setHeaderTransformation (BeanConverterUtil.toDataModels(provisionData.getHeaderTransformations())); + + ApiDetail apiDetail = new ApiDetail(); + api.setApiDetail (apiDetail); + + apiDetail.setDisplayName (provisionData.getDisplayName()); + apiDetail.setEndpoint (provisionData.getEndpoint()); + apiDetail.setHttps (toDataModel(provisionData.getHttps())); + apiDetail.setType (toDataModel(provisionData.getType())); + apiDetail.setSubscriptionStep (toDataModel(provisionData.getSubscriptionStep())); + apiDetail.setNotificationFormat (toDataModel(provisionData.getNotificationFormat())); + apiDetail.setVersion (provisionData.getVersion()); + apiDetail.getContexts().addAll (BeanConverterUtil.toDataModels(provisionData.getContexts())); + apiDetail.setTdrEnabled (toDataModel(provisionData.getTdrEnabled())); + if (provisionData.getAuthentication() != null && provisionData.getAuthentication().getAuthKey() != null) { + apiDetail.setAuthKeyName (provisionData.getAuthentication().getAuthKey().getKeyName()); + apiDetail.setAuthHeaderName (provisionData.getAuthentication().getAuthKey().getHeaderName()); + } + if (provisionData.getAuthentication() != null) + apiDetail.getEnabledAuthType().addAll (BeanConverterUtil.toDataModels(provisionData.getAuthentication().getAuths())); + + apiDetail.setStatus (toDataModel(provisionData.getStatus())); + + // FIXME: The current WS API model does not support notification (true|false) attributes. + apiDetail.setNotification (null); + + apiDetail.setAllowedMethods(provisionData.getAllowedHttpMethodsAsString()); + + api.setValidation(toDataModel(provisionData.getValidation())); + api.setHeaderTransEnabled(provisionData.getHeaderTransEnabled()); + api.setInternal(provisionData.getInternal()); + + if(provisionData.getProxySettings() != null){ + if(provisionData.getProxySettings().getGlobalProxy() != null){ + api.setUseGlobalProxy(true); + }else if (provisionData.getProxySettings().getLocalProxy() != null){ + api.setLocalProxy( toDataModel(provisionData.getProxySettings().getLocalProxy()) ); + }// else no proxy + } + + + return api; + } + + private static final com.alu.e3.prov.restapi.model.HeaderTransformation fromDataModel(HeaderTransformation ht){ + com.alu.e3.prov.restapi.model.HeaderTransformation xmlht = new com.alu.e3.prov.restapi.model.HeaderTransformation(); + + xmlht.setAction(com.alu.e3.prov.restapi.model.HeaderTransformationAction.valueOf(ht.getAction().toString())); + xmlht.setName(ht.getName()); + xmlht.setProperty(ht.getProperty()); + xmlht.setType(com.alu.e3.prov.restapi.model.HeaderTransformationType.valueOf(ht.getType().toString())); + xmlht.setValue(ht.getValue()); + + return xmlht; + } + + private static final HeaderTransformation toDataModel(com.alu.e3.prov.restapi.model.HeaderTransformation xmlht){ + HeaderTransformation ht = new HeaderTransformation(); + + ht.setAction(HeaderTransformationAction.valueOf(xmlht.getAction().toString())); + ht.setName(xmlht.getName()); + ht.setProperty(xmlht.getProperty()); + ht.setType(HeaderTransformationType.valueOf(xmlht.getType().toString())); + ht.setValue(xmlht.getValue()); + + return ht; + } + + + public static final com.alu.e3.prov.restapi.model.Auth fromDataModel(Auth auth) { + if (auth==null) throw new IllegalArgumentException("auth must not be null"); + + com.alu.e3.prov.restapi.model.Auth a = new com.alu.e3.prov.restapi.model.Auth(); + a.setId (auth.getId()); + a.setStatus (fromDataModel(auth.getAuthDetail().getStatus())); + a.setApiContext (auth.getApiContext()); + a.setPolicyContext (auth.getPolicyContext()); + a.setType (fromDataModel(auth.getAuthDetail().getType())); + a.setTdr (fromDataModel(auth.getTdrGenerationRule())); + a.setHeaderTransformations (BeanConverterUtil.fromDataModels(auth.getHeaderTransformations())); + + for(String keyname : auth.getProperties().keySet()){ + Key k = new Key(); + k.setName(keyname); + k.setValue(auth.getProperties().get(keyname)); + a.getProperties().add(k); + } + + switch(auth.getAuthDetail().getType()) { + case AUTHKEY: + a.setAuthKeyAuth (fromDataModelToAuthKeyAuth(auth.getAuthDetail())); + break; + case BASIC: + a.setBasicAuth (fromDataModelToBasicAuth(auth.getAuthDetail())); + break; + case IP_WHITE_LIST: + a.setIpWhiteListAuth (fromDataModelToIpWhiteListAuth(auth.getAuthDetail())); + break; + case NO_AUTH: + break; + case OAUTH: + a.setOAuth(fromDataModelToOAuth(auth.getAuthDetail())); + break; + case WSSE: + a.setWsseAuth(fromDataModelToWsseAuth(auth)); + break; + default: + throw new IllegalArgumentException("Unknown authType specified"); + } + + return a; + } + + public static final Auth toDataModel(com.alu.e3.prov.restapi.model.Auth authData) { + if (authData==null) throw new IllegalArgumentException("authData must not be null"); + + Auth auth = new Auth(); + auth.setId (authData.getId()); + auth.setTdrGenerationRule (toDataModel(authData.getTdr())); + auth.setApiContext (authData.getApiContext()); + auth.setPolicyContext (authData.getPolicyContext()); + auth.setHeaderTransformation (BeanConverterUtil.toDataModels(authData.getHeaderTransformations())); + + for(Key prop : authData.getProperties()){ + auth.getProperties().put(prop.getName(), prop.getValue()); + } + + AuthDetail authDetail = new AuthDetail(); + auth.setAuthDetail (authDetail); + + authDetail.setType (toDataModel(authData.getType())); + authDetail.setStatus (toDataModel(authData.getStatus())); + + switch(authData.getType()) { + case AUTHKEY: + authDetail.setAuthKeyValue(authData.getAuthKeyAuth().getKeyValue()); + break; + case BASIC: + authDetail.setUsername(authData.getBasicAuth().getUsername()); + authDetail.setPassword(authData.getBasicAuth().getPassword()); + break; + case IP_WHITE_LIST: + authDetail.getWhiteListedIps().addAll(authData.getIpWhiteListAuth().getIp()); + break; + case NO_AUTH: + break; + case OAUTH: + authDetail.setClientId(authData.getOAuth().getClientId()); + authDetail.setClientSecret(authData.getOAuth().getClientSecret()); + break; + case WSSE: + authDetail.setUsername(authData.getWsseAuth().getUsername()); + auth.setPasswordType(authData.getWsseAuth().getPasswordType()); + auth.setWssePassword(authData.getWsseAuth().getPassword()); + break; + default: + throw new IllegalArgumentException("Unknown authType specified"); + } + + return auth; + } + + public static final com.alu.e3.prov.restapi.model.Policy fromDataModel(Policy policy) { + if (policy==null) throw new IllegalArgumentException("policy must not be null"); + + com.alu.e3.prov.restapi.model.Policy p = new com.alu.e3.prov.restapi.model.Policy(); + p.setId (policy.getId()); + p.getApiIds().addAll (policy.getApiIds()); + p.getAuthIds().addAll (BeanConverterUtil.fromDataModels(policy.getAuthIds())); + p.getContexts().addAll (BeanConverterUtil.fromDataModels(policy.getContexts())); + + p.setTdr (fromDataModel(policy.getTdrGenerationRule())); + + p.setTdrOnLimitReached (policy.getTdrOnLimitReached()); + p.setHeaderTransformations (BeanConverterUtil.fromDataModels(policy.getHeaderTransformations())); + + + for(String keyname : policy.getProperties().keySet()){ + Key k = new Key(); + k.setName(keyname); + k.setValue(policy.getProperties().get(keyname)); + p.getProperties().add(k); + } + + return p; + } + + public static final Policy toDataModel(com.alu.e3.prov.restapi.model.Policy policy) { + if (policy==null) throw new IllegalArgumentException("policy must not be null"); + + Policy p = new Policy(); + p.setId (policy.getId()); + p.getApiIds().addAll (policy.getApiIds()); + p.getAuthIds().addAll (BeanConverterUtil.toDataModels(policy.getAuthIds())); + p.getContexts().addAll (BeanConverterUtil.toDataModels(policy.getContexts())); + + p.setTdrGenerationRule (toDataModel(policy.getTdr())); + + p.setTdrOnLimitReached (policy.getTdrOnLimitReached()); + + p.setHeaderTransformation (BeanConverterUtil.toDataModels(policy.getHeaderTransformations())); + + for(Key prop : policy.getProperties()){ + p.getProperties().put(prop.getName(), prop.getValue()); + } + + return p; + + } + + public static final QuotaRLBucket toDataModel(com.alu.e3.prov.restapi.model.AuthIdsNoIdType authIds) { + if (authIds==null) throw new IllegalArgumentException("authIds must not be null"); + + QuotaRLBucket ids = new QuotaRLBucket(); + ids.getAuthIds().addAll(authIds.getAuthIds()); + ids.setId(authIds.getId()); + + return ids; + } + + + + + private static final TdrGenerationRule toDataModel(TdrData tdr) { + if (tdr==null) return null;// throw new IllegalArgumentException("tdr must not be null"); + TdrGenerationRule t = new TdrGenerationRule(); + t.getStaticRules().addAll (BeanConverterUtil.toDataModels(tdr.getStatic())); + t.getDynamicRules().addAll (BeanConverterUtil.toDataModels(tdr.getDynamic())); + return t; + } + + /************************************************************************* + ************************************************************************* + * PRIVATE SUB CONVERTERS + ************************************************************************* + *************************************************************************/ + + private static final TdrEnabled fromDataModelToTdr(Boolean tdrEnabled) { + if (tdrEnabled==null) throw new IllegalArgumentException("tdrEnabled must not be null"); + + com.alu.e3.prov.restapi.model.TdrEnabled tdr = new com.alu.e3.prov.restapi.model.TdrEnabled(); + tdr.setEnabled(tdrEnabled?"true":"false"); + + return tdr; + } + + private static final Boolean toDataModel(TdrEnabled tdr) { + if (tdr==null) throw new IllegalArgumentException("tdr must not be null"); + // FIXME: false value of tdr.getEnabled() is implicitly and badly determined + if ("true".equals(tdr.getEnabled())) + return true; + if ("false".equals(tdr.getEnabled())) + return false; + throw new IllegalArgumentException("tdr.enabled must be one of 'true' or 'false' value"); + } + + private static final Validation fromDataModel(com.alu.e3.data.model.sub.Validation val) { + if (val == null) + return null; + + Validation rVal = new Validation(); + + if (val.getXml() != null) { + rVal.setXml(new Validation.Xml()); + } + if (val.getSchema() != null) { + rVal.setSchema(fromDataModel(val.getSchema())); + } + + if (val.getSoap() != null) { + rVal.setSoap(new Validation.Soap(com.alu.e3.prov.restapi.model.SoapVersionEnum.fromValue(val.getSoap().getVersion().value()))); + } + + return rVal; + } + + private static final com.alu.e3.prov.restapi.model.Validation.Schema fromDataModel(com.alu.e3.data.model.sub.Validation.Schema schema) { + Schema ret = new Schema(); + ret.setType(com.alu.e3.prov.restapi.model.SchemaValidationEnum.fromValue(schema.getType().value())); + + ret.setResourcesList(BeanConverterUtil. fromDataModels(schema.getResourcesList())); + + return ret; + } + + private static final com.alu.e3.data.model.sub.Validation.Schema toDataModel(com.alu.e3.prov.restapi.model.Validation.Schema schema) { + + com.alu.e3.data.model.sub.Validation.Schema mSchema = new com.alu.e3.data.model.sub.Validation.Schema(); + mSchema.setType(SchemaValidationEnum.fromValue(schema.getType().value())); + + mSchema.setResourcesList(BeanConverterUtil. toDataModels(schema.getResourcesList())); + + return mSchema; + } + + private static final com.alu.e3.prov.restapi.model.ResourceItem fromDataModel(com.alu.e3.data.model.sub.ResourceItem item) { + + ResourceItem wsItem = new ResourceItem(); + wsItem.setName(item.getName()); + wsItem.setGrammar(item.getGrammar()); + wsItem.setIsMain(item.isIsMain()); + + return wsItem; + } + + private static final com.alu.e3.data.model.sub.ResourceItem toDataModel(com.alu.e3.prov.restapi.model.ResourceItem item) { + com.alu.e3.data.model.sub.ResourceItem ret = new com.alu.e3.data.model.sub.ResourceItem(); + ret.setName(item.getName()); + ret.setGrammar(item.getGrammar()); + ret.setIsMain(item.isIsMain()); + + return ret; + } + + private static final com.alu.e3.data.model.sub.Validation toDataModel(Validation val) { + if (val == null) + return null; + + com.alu.e3.data.model.sub.Validation mVal = new com.alu.e3.data.model.sub.Validation(); + + if (val.getXml() != null) { + mVal.setXml(new com.alu.e3.data.model.sub.Validation.Xml()); + } + if (val.getSchema() != null) { + mVal.setSchema(toDataModel(val.getSchema())); + } + + if (val.getSoap() != null) { + mVal.setSoap(new com.alu.e3.data.model.sub.Validation.Soap(SoapVersionEnum.fromValue(val.getSoap().getVersion().value()))); + } + + return mVal; + } + + private static final TdrData fromDataModel(TdrGenerationRule tdrGenerationRule) { + if (tdrGenerationRule==null) return null; //throw new IllegalArgumentException("tdrGenerationRules must not be null"); + TdrData t = new TdrData(); + t.getStatic().addAll (BeanConverterUtil.fromDataModels(tdrGenerationRule.getStaticRules())); + t.getDynamic().addAll (BeanConverterUtil.fromDataModels(tdrGenerationRule.getDynamicRules())); + return t; + } + + private static final StaticTdr fromDataModel(TdrStaticRule tdrStaticRule) { + if (tdrStaticRule==null) throw new IllegalArgumentException("tdrStaticRule must not be null"); + + StaticTdr s = new StaticTdr(); + s.setValue (tdrStaticRule.getValue()); + s.setTdrPropName (tdrStaticRule.getTdrPropName()); + s.setPropertyName (tdrStaticRule.getPropertyName()); + + TdrType tdrType = new TdrType(); + s.setTypes (tdrType); + tdrType.getType().addAll (tdrStaticRule.getTypes()); + + return s; + } + + private static final DynamicTdr fromDataModel(TdrDynamicRule tdrDynamicRule) { + if (tdrDynamicRule==null) throw new IllegalArgumentException("tdrDynamicRule must not be null"); + + DynamicTdr s = new DynamicTdr(); + s.setHttpHeaderName (tdrDynamicRule.getHttpHeaderName()); + s.setTdrPropName (tdrDynamicRule.getTdrPropName()); + s.setExtractFrom (tdrDynamicRule.getExtractFrom()); + + TdrType tdrType = new TdrType(); + s.setTypes (tdrType); + tdrType.getType().addAll (tdrDynamicRule.getTypes()); + + return s; + } + + private static TdrDynamicRule toDataModel(DynamicTdr dynamicTdr) { + if (dynamicTdr==null) throw new IllegalArgumentException("dynamicTdr must not be null"); + TdrDynamicRule t = new TdrDynamicRule(); + t.setHttpHeaderName (dynamicTdr.getHttpHeaderName()); + t.setTdrPropName (dynamicTdr.getTdrPropName()); + t.setExtractFrom (dynamicTdr.getExtractFrom()); + + if(dynamicTdr.getTypes() != null) t.getTypes().addAll(dynamicTdr.getTypes().getType()); + + return t; + } + + private static TdrStaticRule toDataModel(StaticTdr staticTdr) { + if (staticTdr==null) throw new IllegalArgumentException("staticTdr must not be null"); + TdrStaticRule t = new TdrStaticRule(); + t.setTdrPropName (staticTdr.getTdrPropName()); + t.setValue (staticTdr.getValue()); + t.setPropertyName (staticTdr.getPropertyName()); + + if(staticTdr.getTypes() != null) t.getTypes().addAll (staticTdr.getTypes().getType()); + + return t; + } + + private static final com.alu.e3.prov.restapi.model.LoadBalancingType fromDataModel(LoadBalancingType type) { + return com.alu.e3.prov.restapi.model.LoadBalancingType.valueOf(type.name()); + } + private static final LoadBalancingType toDataModel(com.alu.e3.prov.restapi.model.LoadBalancingType type) { + if (type==null) throw new IllegalArgumentException("type must not be null"); + return LoadBalancingType.valueOf(type.name()); + } + + private static final com.alu.e3.prov.restapi.model.ApiType fromDataModel(ApiType type) { + return com.alu.e3.prov.restapi.model.ApiType.valueOf(type.name()); + } + private static final ApiType toDataModel(com.alu.e3.prov.restapi.model.ApiType type) { + if (type==null) throw new IllegalArgumentException("type must not be null"); + return ApiType.valueOf(type.name()); + } + + private static SubscriptionStep fromDataModel(ApiSubscriptionStep subscriptionStep) { + // This value can be null + if (subscriptionStep == null) return null; + return SubscriptionStep.valueOf(subscriptionStep.name()); + } + + private static NotificationFormat fromDataModel(ApiNotificationFormat notificationFormat) { + // This value can be null + if (notificationFormat == null) return null; + return NotificationFormat.valueOf(notificationFormat.name()); + } + + private static ApiSubscriptionStep toDataModel(SubscriptionStep subscriptionStep) { + if (subscriptionStep==null) return null; + return ApiSubscriptionStep.valueOf(subscriptionStep.name()); + } + + private static ApiNotificationFormat toDataModel(NotificationFormat notificationFormat) { + if (notificationFormat==null) return null; + return ApiNotificationFormat.valueOf(notificationFormat.name()); + } + + private static AuthType fromDataModel(NBAuthType type) { + if (type==null) throw new IllegalArgumentException("type must not be null"); + return AuthType.valueOf(type.name()); + } + private static final NBAuthType toDataModel(AuthType type) { + return NBAuthType.valueOf(type.name()); + } + + private static final com.alu.e3.prov.restapi.model.ApiContext fromDataModel(APIContext apiContext) { + if (apiContext==null) throw new IllegalArgumentException("apiContext must not be null"); + com.alu.e3.prov.restapi.model.ApiContext context = new com.alu.e3.prov.restapi.model.ApiContext(); + + context.setId (apiContext.getId()); + context.setDefaultContext (apiContext.isDefaultContext()); + context.setStatus (fromDataModel(apiContext.getStatus())); + context.setMaxRateLimitTPMThreshold (apiContext.getMaxRateLimitTPMThreshold()); + context.setMaxRateLimitTPMWarning (apiContext.getMaxRateLimitTPMWarning()); + context.setMaxRateLimitTPSThreshold (apiContext.getMaxRateLimitTPSThreshold()); + context.setMaxRateLimitTPSWarning (apiContext.getMaxRateLimitTPSWarning()); + + if (apiContext.getLoadBalancing() != null) + context.setLoadBalancing (fromDataModel(apiContext.getLoadBalancing())); + // Since the addition of MO call support + // we can have no target hosts + if (apiContext.getTargetHosts() != null) + context.setTargetHosts (BeanConverterUtil.fromDataModels(apiContext.getTargetHosts())); + + return context; + } + + private static final com.alu.e3.prov.restapi.model.ConnectionParameters fromDataModel(ConnectionParameters connectionParameters) { + if (connectionParameters==null) throw new IllegalArgumentException("failOver must not be null"); + + com.alu.e3.prov.restapi.model.ConnectionParameters cp = new com.alu.e3.prov.restapi.model.ConnectionParameters(); + cp.setConnectionTimeout (connectionParameters.getConnectionTimeout()); + cp.setSocketTimeout(connectionParameters.getSocketTimeout()); + cp.setMaxConnections(connectionParameters.getMaxConnections()); + + return cp; + } + + private static final ConnectionParameters toDataModel(com.alu.e3.prov.restapi.model.ConnectionParameters connectionParametersType) { + if (connectionParametersType==null) throw new IllegalArgumentException("failOver must not be null"); + + ConnectionParameters cp = new ConnectionParameters(); + cp.setConnectionTimeout (connectionParametersType.getConnectionTimeout()); + cp.setSocketTimeout(connectionParametersType.getSocketTimeout()); + cp.setMaxConnections(connectionParametersType.getMaxConnections()); + + return cp; + } + + private static final com.alu.e3.prov.restapi.model.TargetHost fromDataModel(TargetHost targetHost) { + if (targetHost==null) throw new IllegalArgumentException("targetHost must not be null"); + com.alu.e3.prov.restapi.model.TargetHost th = new com.alu.e3.prov.restapi.model.TargetHost(); + th.setUrl (targetHost.getUrl()); + th.setSite (targetHost.getSite()); + th.setAuthentication (fromDataModel(targetHost.getAuthentication())); + if (targetHost.getConnectionParameters() != null) + th.setConnectionParameters(fromDataModel(targetHost.getConnectionParameters())); + + return th; + } + + private static final Authentication fromDataModel(SBAuthentication authentication) { + if (authentication==null) return null; // throw new IllegalArgumentException("authentication must not be null"); + Authentication a = new Authentication(); + a.setType (authentication.getType()); + a.setData (fromDataModelToData(authentication.getKeys())); + return a; + } + + private static final Data fromDataModelToData(Map keys) { + if (keys==null) throw new IllegalArgumentException("keys must not be null"); + Data d = new Data(); + for(Map.Entry entry : keys.entrySet()) { + Key k = new Key(); + k.setName (entry.getKey()); + k.setValue (entry.getValue()); + d.getKey().add(k); + } + return d; + } + + private static final ProvisionAuthentication fromDataModelToProvisionAuthentication(ApiDetail apiDetail) { + if (apiDetail==null) throw new IllegalArgumentException("apiDetail must not be null"); + + Authkey ak = new Authkey(); + ak.setKeyName (apiDetail.getAuthKeyName()); + ak.setHeaderName (apiDetail.getAuthHeaderName()); + + ProvisionAuthentication p = new ProvisionAuthentication(); + p.setAuthKey (ak); + p.getAuths().addAll (BeanConverterUtil.fromDataModels(apiDetail.getEnabledAuthType())); + + return p; + } + + + private static final APIContext toDataModel(com.alu.e3.prov.restapi.model.ApiContext context) { + if (context==null) throw new IllegalArgumentException("environment must not be null"); + APIContext apiContext = new APIContext(); + + apiContext.setId (context.getId()); + apiContext.setDefaultContext (context.isDefaultContext()); + apiContext.setStatus (toDataModel(context.getStatus())); + apiContext.setMaxRateLimitTPMThreshold (context.getMaxRateLimitTPMThreshold()); + apiContext.setMaxRateLimitTPMWarning (context.getMaxRateLimitTPMWarning()); + apiContext.setMaxRateLimitTPSThreshold (context.getMaxRateLimitTPSThreshold()); + apiContext.setMaxRateLimitTPSWarning (context.getMaxRateLimitTPSWarning()); + if (context.getLoadBalancing() != null) + apiContext.setLoadBalancing (toDataModel(context.getLoadBalancing())); + + // Since the addition of MO call support + // We can have no TargetHosts + if (context.getTargetHosts()!=null) + apiContext.getTargetHosts().addAll (BeanConverterUtil.toDataModels(context.getTargetHosts())); + + return apiContext; + } + + private static final TargetHost toDataModel(com.alu.e3.prov.restapi.model.TargetHost targetHost) { + if (targetHost==null) throw new IllegalArgumentException("targetHost must not be null"); + TargetHost t = new TargetHost(); + t.setUrl (targetHost.getUrl()); + t.setSite (targetHost.getSite()); + t.setAuthentication (toDataModel(targetHost.getAuthentication())); + if (targetHost.getConnectionParameters() != null) + t.setConnectionParameters(toDataModel(targetHost.getConnectionParameters())); + + return t; + } + + private static final SBAuthentication toDataModel(Authentication authentication) { + if (authentication==null) return null; // throw new IllegalArgumentException("authentication must not be null"); + SBAuthentication s = new SBAuthentication(); + s.setType(authentication.getType()); + for (Key k : authentication.getData().getKey()) + s.getKeys().put(k.getName(), k.getValue()); + return s; + } + + private static final AuthKeyAuth fromDataModelToAuthKeyAuth(AuthDetail authDetail) { + if (authDetail==null) throw new IllegalArgumentException("authDetail must not be null"); + AuthKeyAuth a = new AuthKeyAuth(); + a.setKeyValue (authDetail.getAuthKeyValue()); + return a; + } + + private static BasicAuth fromDataModelToBasicAuth(AuthDetail authDetail) { + if (authDetail==null) throw new IllegalArgumentException("authDetail must not be null"); + BasicAuth b = new BasicAuth(); + b.setUsername (authDetail.getUsername()); + b.setPassword (authDetail.getPassword()); + return b; + } + + private static OAuth fromDataModelToOAuth(AuthDetail authDetail) { + if (authDetail==null) throw new IllegalArgumentException("authDetail must not be null"); + OAuth b = new OAuth(); + b.setClientId(authDetail.getClientId()); + b.setClientSecret(authDetail.getClientSecret()); + return b; + } + + private static IpWhiteListAuth fromDataModelToIpWhiteListAuth(AuthDetail authDetail) { + if (authDetail==null) throw new IllegalArgumentException("authDetail must not be null"); + IpWhiteListAuth i = new IpWhiteListAuth(); + i.getIp().addAll (authDetail.getWhiteListedIps()); + return i; + } + + private static WSSEAuth fromDataModelToWsseAuth(Auth auth){ + if (auth==null) throw new IllegalArgumentException("authDetail must not be null"); + WSSEAuth wsseAuth = new WSSEAuth(); + wsseAuth.setPasswordType(auth.getPasswordType()); + wsseAuth.setPassword(auth.getWssePassword()); + wsseAuth.setUsername(auth.getAuthDetail().getUsername()); + + return wsseAuth; + } + + private static final com.alu.e3.prov.restapi.model.Context fromDataModel(Context context) { + if (context==null) throw new IllegalArgumentException("context must not be null"); + + com.alu.e3.prov.restapi.model.Context e = new com.alu.e3.prov.restapi.model.Context(); + e.setId (context.getId()); + e.setStatus (fromDataModel(context.getStatus())); + + // Following are optional + if(context.getQuotaPerDay() != null) e.setQuotaPerDay (fromDataModel(context.getQuotaPerDay())); + if(context.getQuotaPerMonth() != null) e.setQuotaPerMonth (fromDataModel(context.getQuotaPerMonth())); + if(context.getQuotaPerWeek() != null) e.setQuotaPerWeek (fromDataModel(context.getQuotaPerWeek())); + if(context.getRateLimitPerMinute() != null) e.setRateLimitPerMinute (fromDataModel(context.getRateLimitPerMinute())); + if(context.getRateLimitPerSecond() != null) e.setRateLimitPerSecond (fromDataModel(context.getRateLimitPerSecond())); + + return e; + } + + private static final Context toDataModel(com.alu.e3.prov.restapi.model.Context contextData) { + if (contextData==null) throw new IllegalArgumentException("contextData must not be null"); + + Context e = new Context(); + e.setId (contextData.getId()); + e.setStatus (toDataModel(contextData.getStatus())); + + // Following are optional + if(contextData.getQuotaPerDay() != null) e.setQuotaPerDay (toDataModel(contextData.getQuotaPerDay())); + if(contextData.getQuotaPerMonth() != null) e.setQuotaPerMonth (toDataModel(contextData.getQuotaPerMonth())); + if(contextData.getQuotaPerWeek() != null) e.setQuotaPerWeek (toDataModel(contextData.getQuotaPerWeek())); + if(contextData.getRateLimitPerMinute() != null) e.setRateLimitPerMinute (toDataModel(contextData.getRateLimitPerMinute())); + if(contextData.getRateLimitPerSecond() != null) e.setRateLimitPerSecond (toDataModel(contextData.getRateLimitPerSecond())); + + return e; + } + + private static final com.alu.e3.prov.restapi.model.Counter fromDataModel(Counter counter) { + if (counter==null) throw new IllegalArgumentException("counter must not be null"); + + com.alu.e3.prov.restapi.model.Counter c = new com.alu.e3.prov.restapi.model.Counter(); + c.setAction (fromDataModel(counter.getAction())); + c.setStatus (fromDataModel(counter.getStatus())); + c.setThreshold (counter.getThreshold()); + c.setWarning (counter.getWarning()); + + return c; + } + + private static final Counter toDataModel(com.alu.e3.prov.restapi.model.Counter counterType) { + if (counterType==null) throw new IllegalArgumentException("counterType must not be null"); + + Counter c = new Counter(); + c.setAction (toDataModel(counterType.getAction())); + c.setStatus (toDataModel(counterType.getStatus())); + c.setThreshold (counterType.getThreshold()); + c.setWarning (counterType.getWarning()); + + return c; + } + + private static final com.alu.e3.prov.restapi.model.AuthIdsType fromDataModel(QuotaRLBucket authIds) { + if (authIds==null) throw new IllegalArgumentException("authIds must not be null"); + + com.alu.e3.prov.restapi.model.AuthIdsType ids = new com.alu.e3.prov.restapi.model.AuthIdsType(); + ids.getAuthIds().addAll(authIds.getAuthIds()); + ids.setId(authIds.getId()); + + return ids; + } + + private static final QuotaRLBucket toDataModel(com.alu.e3.prov.restapi.model.AuthIdsType authIds) { + if (authIds==null) throw new IllegalArgumentException("authIds must not be null"); + if (authIds.getId()==null) throw new IllegalArgumentException("id must not be null"); + + QuotaRLBucket ids = new QuotaRLBucket(); + ids.getAuthIds().addAll(authIds.getAuthIds()); + ids.setId(authIds.getId()); + + return ids; + } + + private static final com.alu.e3.prov.restapi.model.Action fromDataModel(ActionType action) { + if (action==null) throw new IllegalArgumentException("action must not be null"); + return com.alu.e3.prov.restapi.model.Action.valueOf(action.name()); + } + + private static final ActionType toDataModel(com.alu.e3.prov.restapi.model.Action action) { + if (action==null) throw new IllegalArgumentException("action must not be null"); + return ActionType.valueOf(action.name()); + } + + private static final com.alu.e3.prov.restapi.model.Status fromDataModel(StatusType status) { + if (status==null) return null; //throw new IllegalArgumentException("status must not be null"); + return com.alu.e3.prov.restapi.model.Status.valueOf(status.name()); + } + + private static final StatusType toDataModel(com.alu.e3.prov.restapi.model.Status status) { + if (status==null) return null; //throw new IllegalArgumentException("status must not be null"); + return StatusType.valueOf(status.name()); + } + + private static final com.alu.e3.prov.restapi.model.TargetHealthCheck fromDataModel(TargetHealthCheck targetHealthCheck) { + if (targetHealthCheck==null) throw new IllegalArgumentException("targetHealthCheck must not be null"); + + com.alu.e3.prov.restapi.model.TargetHealthCheck thc = new com.alu.e3.prov.restapi.model.TargetHealthCheck(); + thc.setType(targetHealthCheck.getType()); + + return thc; + } + + private static final TargetHealthCheck toDataModel(com.alu.e3.prov.restapi.model.TargetHealthCheck targetHealthCheckType) { + if (targetHealthCheckType==null) throw new IllegalArgumentException("targetHealthCheckType must not be null"); + + TargetHealthCheck thc = new TargetHealthCheck(); + thc.setType(targetHealthCheckType.getType()); + + return thc; + } + + private static final com.alu.e3.prov.restapi.model.FailOver fromDataModel(FailOver failOver) { + if (failOver==null) throw new IllegalArgumentException("failOver must not be null"); + + com.alu.e3.prov.restapi.model.FailOver fo = new com.alu.e3.prov.restapi.model.FailOver(); + fo.setOnResponseCode(failOver.getOnResponseCode()); + + return fo; + } + + private static final FailOver toDataModel(com.alu.e3.prov.restapi.model.FailOver failOverType) { + if (failOverType==null) throw new IllegalArgumentException("failOver must not be null"); + + FailOver fo = new FailOver(); + fo.setOnResponseCode(failOverType.getOnResponseCode()); + + return fo; + } + + private static final com.alu.e3.prov.restapi.model.LoadBalancing fromDataModel(LoadBalancing loadBalancing) { + if (loadBalancing==null) throw new IllegalArgumentException("loadBalancing must not be null"); + + com.alu.e3.prov.restapi.model.LoadBalancing lb = new com.alu.e3.prov.restapi.model.LoadBalancing(); + lb.setLoadBalancingType(fromDataModel(loadBalancing.getLoadBalancingType())); + + if(loadBalancing.getTargetHealthCheck() != null) + lb.setTargetHealthCheck(fromDataModel(loadBalancing.getTargetHealthCheck())); + + if(loadBalancing.getFailOver() != null) + lb.setFailOver(fromDataModel(loadBalancing.getFailOver())); + + return lb; + } + + private static final LoadBalancing toDataModel(com.alu.e3.prov.restapi.model.LoadBalancing loadBalancing) { + if (loadBalancing==null) throw new IllegalArgumentException("loadBalancing must not be null"); + + LoadBalancing lb = new LoadBalancing(); + lb.setLoadBalancingType(toDataModel(loadBalancing.getLoadBalancingType())); + + if(loadBalancing.getTargetHealthCheck() != null) + lb.setTargetHealthCheck(toDataModel(loadBalancing.getTargetHealthCheck())); + + if(loadBalancing.getFailOver() != null) + lb.setFailOver(toDataModel(loadBalancing.getFailOver())); + + return lb; + } + + public static final SSLKey fromDataModel(com.alu.e3.data.model.Key key) { + if (key==null) return null; //throw new IllegalArgumentException("status must not be null"); + + SSLKey ret = new SSLKey(); + + ret.setActiveCertId(key.getActiveCertId()); + ret.setDisplayName(key.getKeyDetail().getName()); + // do NOT set SSLKey.content and SSLKey.keyPassphrase + // key data should not be accessible through the provisioning api. + ret.setId(key.getId()); + ret.setType(key.getKeyDetail().getType()); + + return ret; + } + + + public static final com.alu.e3.data.model.Key toDataModel(SSLKey key) { + if (key==null) return null; //throw new IllegalArgumentException("status must not be null"); + com.alu.e3.data.model.Key ret = new com.alu.e3.data.model.Key(); + + KeyDetail kd = new KeyDetail(); + kd.setId(key.getId()); + kd.setName(key.getDisplayName()); + kd.setType(key.getType()); + + ret.setId(key.getId()); + ret.setKeyDetail(kd); + ret.setData(key.getContent()); + + ret.setActiveCertId(key.getActiveCertId()); + ret.setKeyPassphrase(key.getKeyPassphrase()); + + return ret; + } + + public static final SSLCert fromDataModel(Certificate cert){ + if(cert == null) throw new IllegalArgumentException("cert must not be null"); + + SSLCert sslCert = new SSLCert(); + sslCert.setDisplayName(cert.getCertDetail().getName()); + sslCert.setContent(cert.getData()); + sslCert.setId(cert.getId()); + sslCert.setKeyId(cert.getCertDetail().getKeyId()); + + return sslCert; + } + + + + public static final Certificate toDataModel(SSLCert sslCert){ + if(sslCert == null) throw new IllegalArgumentException("cert must not be null"); + + Certificate cert = new Certificate(); + cert.setData(sslCert.getContent()); + cert.setId(sslCert.getId()); + cert.setPassword(sslCert.getKeyId()); + + CertificateDetail cd = new CertificateDetail(); + cd.setId(sslCert.getId()); + cd.setKeyId(sslCert.getKeyId()); + cd.setName(sslCert.getDisplayName()); + + cert.setCertDetail(cd); + + return cert; + } + + /************************************************************************* + ************************************************************************* + * GENERICS PRIVATE TOOLS + ************************************************************************* + *************************************************************************/ + + @SuppressWarnings("unchecked") + private static final List fromDataModels(List dataModels) { + if (dataModels==null) throw new IllegalArgumentException("dataModels must not be null"); + List us = new ArrayList(); + for(V v : dataModels) { + // Very very dumb generic limitation: + // solve compilation and IDE ambiguity + if (v instanceof APIContext) + us.add((U)fromDataModel((APIContext)v)); + else if (v instanceof TargetHost) + us.add((U)fromDataModel((TargetHost)v)); + else if (v instanceof Context) + us.add((U)fromDataModel((Context)v)); + else if (v instanceof QuotaRLBucket) + us.add((U)fromDataModel((QuotaRLBucket)v)); + else if (v instanceof NBAuthType) + us.add((U)fromDataModel((NBAuthType)v)); + else if (v instanceof TdrStaticRule) + us.add((U)fromDataModel((TdrStaticRule)v)); + else if (v instanceof TdrDynamicRule) + us.add((U)fromDataModel((TdrDynamicRule)v)); + else if (v instanceof com.alu.e3.data.model.sub.ResourceItem) + us.add((U) fromDataModel((com.alu.e3.data.model.sub.ResourceItem) v)); + else if (v instanceof HeaderTransformation) + us.add((U) fromDataModel((HeaderTransformation) v)); + else + throw new IllegalArgumentException("List type:"+v.getClass().getName()+" conversion not supported"); + } + return us; + } + + @SuppressWarnings("unchecked") + private static final List toDataModels(List wsModels) { + if (wsModels==null) throw new IllegalArgumentException("wsModels must not be null"); + List us = new ArrayList(); + for(V v : wsModels) { + // Very very dumb generic limitation: + // solve compilation and IDE ambiguity + if (v instanceof com.alu.e3.prov.restapi.model.ApiContext) + us.add((U)toDataModel((com.alu.e3.prov.restapi.model.ApiContext)v)); + else if (v instanceof com.alu.e3.prov.restapi.model.TargetHost) + us.add((U)toDataModel((com.alu.e3.prov.restapi.model.TargetHost)v)); + else if (v instanceof com.alu.e3.prov.restapi.model.Context) + us.add((U)toDataModel((com.alu.e3.prov.restapi.model.Context)v)); + else if (v instanceof com.alu.e3.prov.restapi.model.AuthIdsType) + us.add((U)toDataModel((com.alu.e3.prov.restapi.model.AuthIdsType)v)); + else if (v instanceof AuthType) + us.add((U)toDataModel((AuthType)v)); + else if (v instanceof StaticTdr) + us.add((U)toDataModel((StaticTdr)v)); + else if (v instanceof DynamicTdr) + us.add((U)toDataModel((DynamicTdr)v)); + else if (v instanceof ResourceItem) + us.add((U) toDataModel((ResourceItem) v)); + else if (v instanceof com.alu.e3.prov.restapi.model.HeaderTransformation) + us.add((U) toDataModel((com.alu.e3.prov.restapi.model.HeaderTransformation) v)); + else + throw new IllegalArgumentException("List type:"+v.getClass().getName()+" conversion not supported"); + } + return us; + } + + private static final com.alu.e3.prov.restapi.model.HTTPSType fromDataModel(HTTPSType httpsType) { + if (httpsType==null) throw new IllegalArgumentException("httpsType must not be null"); + + com.alu.e3.prov.restapi.model.HTTPSType r = new com.alu.e3.prov.restapi.model.HTTPSType(); + r.setEnabled(httpsType.isEnabled()); + + if(httpsType.getTlsMode() != null) r.setTlsMode(fromDataModel(httpsType.getTlsMode())); + + return r; + } + + public static final HTTPSType toDataModel(com.alu.e3.prov.restapi.model.HTTPSType httpsType) { + if (httpsType==null) throw new IllegalArgumentException("httpsType must not be null"); + + HTTPSType r = new HTTPSType(); + r.setEnabled(httpsType.isEnabled()); + + if(httpsType.getTlsMode() != null) r.setTlsMode(toDataModel(httpsType.getTlsMode())); + + return r; + } + + public static final com.alu.e3.prov.restapi.model.ForwardProxy fromDataModel(ForwardProxy forwardProxy) { + if (forwardProxy==null) return null; + + com.alu.e3.prov.restapi.model.ForwardProxy fp = new com.alu.e3.prov.restapi.model.ForwardProxy(); + fp.setProxyHost(forwardProxy.getProxyHost()); + fp.setProxyPass(forwardProxy.getProxyPass()); + fp.setProxyPort(forwardProxy.getProxyPort()); + fp.setProxyUser(forwardProxy.getProxyUser()); + + return fp; + } + + public static final ForwardProxy toDataModel(com.alu.e3.prov.restapi.model.ForwardProxy forwardProxy) { + if (forwardProxy==null) return null; + + ForwardProxy fp = new ForwardProxy(); + fp.setProxyHost(forwardProxy.getProxyHost()); + fp.setProxyPass(forwardProxy.getProxyPass()); + fp.setProxyPort(forwardProxy.getProxyPort()); + fp.setProxyUser(forwardProxy.getProxyUser()); + + return fp; + } + + private static final com.alu.e3.prov.restapi.model.TLSMode fromDataModel(TLSMode tlsMode) { + if (tlsMode==null) throw new IllegalArgumentException("tlsMode must not be null"); + + return com.alu.e3.prov.restapi.model.TLSMode.valueOf(tlsMode.name()); + } + + public static final TLSMode toDataModel(com.alu.e3.prov.restapi.model.TLSMode tlsMode) { + if (tlsMode==null) throw new IllegalArgumentException("tlsMode must not be null"); + + return TLSMode.valueOf(tlsMode.name()); + } + + public static final com.alu.e3.prov.restapi.model.SSLCRL fromDataModel(SSLCRL crl) { + if (crl==null) throw new IllegalArgumentException("crl must not be null"); + + com.alu.e3.prov.restapi.model.SSLCRL r = new com.alu.e3.prov.restapi.model.SSLCRL(); + r.setId(crl.getId()); + r.setContent(crl.getContent()); + r.setDisplayName(crl.getDisplayName()); + return r; + } + + public static final SSLCRL toDataModel(com.alu.e3.prov.restapi.model.SSLCRL crl) { + if (crl==null) throw new IllegalArgumentException("crl must not be null"); + + SSLCRL r = new SSLCRL(); + r.setId(crl.getId()); + r.setContent(crl.getContent()); + r.setDisplayName(crl.getDisplayName()); + return r; + } + +} diff --git a/exposure-engine/provisioning/src/main/java/com/alu/e3/prov/ApplicationCodeConstants.java b/exposure-engine/provisioning/src/main/java/com/alu/e3/prov/ApplicationCodeConstants.java new file mode 100644 index 0000000..fc94ce9 --- /dev/null +++ b/exposure-engine/provisioning/src/main/java/com/alu/e3/prov/ApplicationCodeConstants.java @@ -0,0 +1,55 @@ +/** + * Copyright © 2012 Alcatel-Lucent. + * + * See the NOTICE file distributed with this work for additional + * information regarding copyright ownership. + * Licensed to you 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 com.alu.e3.prov; + +/** + * Application specific return codes. + * + * For Http return codes, @see org.springframework.http.HttpStatus + */ +public class ApplicationCodeConstants { + + public static final int RESPONSE_OK = 100; + + public static final int BODY_NOT_PROVIDED = 101; + public static final int INVALID_XML = 102; + public static final int API_ID_NOT_PROVIDED = 103; + public static final int OPERATION_FAILED = 104; + public static final int API_ID_NOT_FOUND = 105; + public static final int ROLLBACK_FAILED = 106; + public static final int API_ID_MISMATCH = 107; + public static final int NOTHING_TO_DELETE = 108; + public static final int ROUTE_CREATION_FAILED_ROLLBACK_KO = 109; + public static final int ROUTE_CREATION_FAILED_ROLLBACK_OK = 110; + public static final int DEPLOYMENT_FAILED = 111; + public static final int UNDEPLOYMENT_FAILED = 112; + public static final int NOTHING_TO_ROLLBACK = 113; + public static final int ID_NOT_FOUND = 114; + + public static final int API_ID_ALREADY_EXIST = 115; + + public static final int AUTHENTICATION_ENABLED_AND_FAILED = 403; + + public static final int UNAUTHORIZED = 401; + + public static final int INTERNAL_APPLICATION_ERROR = 500; + + public static final int NOT_IMPLEMENTED = 501; + +} diff --git a/exposure-engine/provisioning/src/main/java/com/alu/e3/prov/Constants.java b/exposure-engine/provisioning/src/main/java/com/alu/e3/prov/Constants.java new file mode 100644 index 0000000..f0ac19b --- /dev/null +++ b/exposure-engine/provisioning/src/main/java/com/alu/e3/prov/Constants.java @@ -0,0 +1,40 @@ +/** + * Copyright © 2012 Alcatel-Lucent. + * + * See the NOTICE file distributed with this work for additional + * information regarding copyright ownership. + * Licensed to you 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 com.alu.e3.prov; + +/** + * !!! Please do not use these Constants !!! + * The Exchange constants are now part of the common project. + * + * !!! Please use com.alu.e3.common.camel.ExchangeConstantKeys <> !!! + */ +@Deprecated +public class Constants { + public static final String E3_PROVISION_ID = "E3_PROVISION_ID"; + public static final String E3_PROVISION_ID_ENCODED = "E3_PROVISION_ID_ENCODED"; + public static final String E3_API_ID = "E3_API_ID"; + public static final String E3_API_ID_ENCODED = "E3_API_ID_ENCODED"; + public static final String E3_OPERATION_NAME = "E3_OPERATION_NAME"; + public static final String E3_REQUEST_PAYLOAD = "E3_REQUEST_PAYLOAD"; + public static final String E3_API_ID_CREATION_MODE = "E3_API_ID_CREATION_MODE"; + + // values + public static final String E3_API_ID_CREATION_MODE_GENERATED = "GENERATED"; + public static final String E3_API_ID_CREATION_MODE_PROVIDED = "PROVIDED"; +} diff --git a/exposure-engine/provisioning/src/main/java/com/alu/e3/prov/E3ExceptionMapper.java b/exposure-engine/provisioning/src/main/java/com/alu/e3/prov/E3ExceptionMapper.java new file mode 100644 index 0000000..27f4641 --- /dev/null +++ b/exposure-engine/provisioning/src/main/java/com/alu/e3/prov/E3ExceptionMapper.java @@ -0,0 +1,154 @@ +/** + * Copyright © 2012 Alcatel-Lucent. + * + * See the NOTICE file distributed with this work for additional + * information regarding copyright ownership. + * Licensed to you 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 com.alu.e3.prov; + +import java.util.ArrayList; + +import javax.ws.rs.WebApplicationException; +import javax.ws.rs.core.MediaType; +import javax.ws.rs.core.Response; +import javax.ws.rs.core.Response.ResponseBuilder; +import javax.ws.rs.ext.ExceptionMapper; + +import org.apache.cxf.interceptor.security.AccessDeniedException; +import org.apache.cxf.interceptor.security.AuthenticationException; +import org.xml.sax.SAXParseException; + +import com.alu.e3.common.InvalidIDException; +import com.alu.e3.common.NotImplementedException; +import com.alu.e3.common.logging.Category; +import com.alu.e3.common.logging.CategoryLogger; +import com.alu.e3.common.logging.CategoryLoggerFactory; +import com.alu.e3.prov.restapi.model.Error; +import com.alu.e3.prov.restapi.model.BasicResponse; + +public class E3ExceptionMapper implements ExceptionMapper { + private static final CategoryLogger logger = CategoryLoggerFactory.getLogger(E3ExceptionMapper.class, Category.PROV); + + public Response toResponse(Exception ex) { + String message = ""; + int applicationErrorCode = 0; + int status; + Throwable cause = ex; + + BasicResponse resp = new BasicResponse(BasicResponse.FAILURE); + resp.setError(new Error()); + + if (ex instanceof AccessDeniedException) { + // 403 FORBIDDEN + status = 403; + + applicationErrorCode = ApplicationCodeConstants.AUTHENTICATION_ENABLED_AND_FAILED; + resp.getError().setErrorText("Access Denied"); + + + } else if (ex instanceof AuthenticationException) { + // UNAUTHORIZED + status = 401; + + applicationErrorCode = ApplicationCodeConstants.UNAUTHORIZED; + resp.getError().setErrorText("Unauthorized access"); + + } else if (ex instanceof WebApplicationException) { // CXF raises this + // kind of exception + // 500 INTERNAL_SERVER_ERROR + status = 500; + applicationErrorCode = ApplicationCodeConstants.INTERNAL_APPLICATION_ERROR; + + if (ex.getCause() == null) { + message = ex.toString(); + } else { + cause = ex.getCause(); + if (cause instanceof SAXParseException) { + applicationErrorCode = ApplicationCodeConstants.INVALID_XML; + resp.getError().setErrorText("XML Validation Error: " + ex.getCause().getMessage()); + + } else if (cause instanceof ProvisionException) { + ProvisionException provEx = (ProvisionException) ex.getCause(); + applicationErrorCode = provEx.getErrorCode(); + resp.getError().setErrorText(ex.getCause().getMessage()); + + } else if (cause instanceof InvalidIDException) { + // This block is called in API WebService + // Should do the same as other InvalidIDException catch + // 404 NOT_FOUND + status = 404; + applicationErrorCode = ApplicationCodeConstants.ID_NOT_FOUND; + resp.getError().setErrorText(ex.getCause().getMessage()); + } else { + message = cause.getMessage(); + if (message == null) { + message = ex.getCause().toString(); + } + applicationErrorCode = ApplicationCodeConstants.INTERNAL_APPLICATION_ERROR; + resp.getError().setErrorText(message); + } + } + + } else if (ex instanceof InvalidIDException) { + // Should do the same as other InvalidIDException catch + // 404 NOT_FOUND + status = 404; + applicationErrorCode = ApplicationCodeConstants.ID_NOT_FOUND; + resp.getError().setErrorText(ex.getMessage()); + + } else if (ex instanceof NotImplementedException) { + // 501 NOT_IMPLEMENTED + status = 501; + applicationErrorCode = ApplicationCodeConstants.NOT_IMPLEMENTED; + resp.getError().setErrorText(ex.getMessage()); + + } else if (ex instanceof ProvisionException) { + // 500 INTERNAL_SERVER_ERROR + status = 500; + ProvisionException provEx = (ProvisionException) ex.getCause(); + applicationErrorCode = provEx.getErrorCode(); + resp.getError().setErrorText(ex.getCause().getMessage()); + + } else { + // 500 INTERNAL_SERVER_ERROR + status = 500; + message = ex.toString(); + + applicationErrorCode = ApplicationCodeConstants.INTERNAL_APPLICATION_ERROR; + resp.getError().setErrorText("Provisioning Server Error: "+message); + + } + StackTraceElement[] stack = cause.getStackTrace(); + ArrayList e3Stack = new ArrayList(); + for (StackTraceElement elem : stack) { + if (elem.getClassName().indexOf("com.alu.e3") != -1) { + e3Stack.add(elem); + } + } + + cause.setStackTrace(e3Stack.toArray(new StackTraceElement[e3Stack.size()])); + logger.error("E3 Runtime exception (HTTP status:" + status + ")", cause); + + resp.getError().setErrorCode(String.valueOf(applicationErrorCode)); + ResponseBuilder builder = Response.status(status).type(MediaType.APPLICATION_XML).header("X-Application-Error-Code", applicationErrorCode).entity(resp); + if(status == 401){ + builder.header("WWW-Authenticate", "Basic"); + } + + return builder.build(); + + } + +} diff --git a/exposure-engine/provisioning/src/main/java/com/alu/e3/prov/LogUtil.java b/exposure-engine/provisioning/src/main/java/com/alu/e3/prov/LogUtil.java new file mode 100644 index 0000000..dc0b2cc --- /dev/null +++ b/exposure-engine/provisioning/src/main/java/com/alu/e3/prov/LogUtil.java @@ -0,0 +1,141 @@ +/** + * Copyright © 2012 Alcatel-Lucent. + * + * See the NOTICE file distributed with this work for additional + * information regarding copyright ownership. + * Licensed to you 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 com.alu.e3.prov; + +import org.slf4j.Logger; + +import com.alu.e3.common.camel.ExchangeConstantKeys; +import com.alu.e3.common.logging.Category; +import com.alu.e3.common.logging.CategoryLogger; +import com.alu.e3.common.logging.CategoryLoggerFactory; +import com.alu.e3.prov.restapi.ExchangeData; + +/** + *

+ * A utility class for formatting and standardizing the log messages for provisioning events.

+ *

+ * The original version of this class provided variants on a log function with + * an org.slf4j.Logger as the first parameter. This logger parameter + * was ignored, however, and instead this class's static Logger instance (named + * “e3provLogger”) was used to output all messages.

+ *

+ * To make this class more compatible with the idea of logging categories introduced + * by com.alu.e3.common.logging.CategoryLogger, the internal static + * Logger has been changed to a CategoryLogger (with + * category PROV), and the logger parameter is no longer ignored. + * If the logger is not null, then that logger will + * be used to output (and categorize) the formatted message. If logger is null, + * this class's logger will be used instead, which is the equivalent of the + * original operation.

+ */ +public class LogUtil { + public static final String LOG_PATTERN_MODEL = "[ExchangeID: {}];[Action: {}];[API_ID: {}];[Mode: {}];[Encoded: {}];[ProvID: {}];[Phase: {}];[State: {}]"; + public static final String LOG_PATTERN = "{};{};{};{};{};{};{};{}"; + + // Keep original (non-class) name for logger? + private static final CategoryLogger LOG = CategoryLoggerFactory.getLogger("e3provLogger", Category.PROV); + + public static final void log(Logger logger, ExchangeData exchange, Phase phase, State status) + { + log(logger, exchange, phase.getLabel(), status.getLabel()); + } + + public static final void log(Logger logger, ExchangeData exchange, Phase phase, String status) + { + log(logger, exchange, phase.getLabel(), status); + } + + public static final void log(Logger logger, ExchangeData exchange, String phase, String status) + { + String action = (String)exchange.getProperty(ExchangeConstantKeys.E3_OPERATION_NAME.toString()); + String apiID = (String)exchange.getProperty(ExchangeConstantKeys.E3_API_ID.toString()); + String creationMode = (String)exchange.getProperty(ExchangeConstantKeys.E3_API_ID_CREATION_MODE.toString()); + String encodedApiID = (String)exchange.getProperty(ExchangeConstantKeys.E3_API_ID_ENCODED.toString()); + String provID = (String)exchange.getProperty(ExchangeConstantKeys.E3_PROVISION_ID.toString()); + + if (phase == null) + phase = ""; + if (status == null) + status = ""; + + if (logger != null) { + logger.debug(LOG_PATTERN, new Object[] { provID, action, apiID, creationMode, encodedApiID, provID, phase, status }); + } else { + LOG.debug(LOG_PATTERN, new Object[] { provID, action, apiID, creationMode, encodedApiID, provID, phase, status }); + } + } + + public enum Phase { + + PREPROCESS("PREPROCESS"), + + POSTPROCESS("POSTPROCESS"), + + PROCESS("PROCESS"), + + DEPLOY("DEPLOY"), + + UNDEPLOY("UNDEPLOY"), + + GET("GET"), + + GETALL("GETALL"), + + UNKNOWN("-"); + + private String label; + + Phase(String label) { + + this.label = label; + } + + public String getLabel() { + return label; + } + + } + + public enum State { + + RECEIVED("RECEIVED"), + + START("START"), + + INPROGRESS("INPROGRESS"), + + DONE("DONE"), + + FAILED("FAILED"), + + UNKNOWN("-"); + + private String label; + + State(String label) { + + this.label = label; + } + + public String getLabel() { + return label; + } + + } +} diff --git a/exposure-engine/provisioning/src/main/java/com/alu/e3/prov/ProvisionException.java b/exposure-engine/provisioning/src/main/java/com/alu/e3/prov/ProvisionException.java new file mode 100644 index 0000000..59e4cb8 --- /dev/null +++ b/exposure-engine/provisioning/src/main/java/com/alu/e3/prov/ProvisionException.java @@ -0,0 +1,56 @@ +/** + * Copyright © 2012 Alcatel-Lucent. + * + * See the NOTICE file distributed with this work for additional + * information regarding copyright ownership. + * Licensed to you 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 com.alu.e3.prov; + +public class ProvisionException extends Exception { + + /** + * Generated serial version UID + */ + private static final long serialVersionUID = 1495836926660177572L; + + int functionalErrorCode; + + public ProvisionException() { + super(); + } + + public ProvisionException(int code, String message) { + super(message); + functionalErrorCode = code; + } + + public ProvisionException(int code, String message, Throwable cause) { + super(message, cause); + functionalErrorCode = code; + } + + public ProvisionException(int code, Throwable cause) { + super(cause); + functionalErrorCode = code; + } + + public int getErrorCode() { + return functionalErrorCode; + } + + public void setErrorCode(int functionalErrorCode) { + this.functionalErrorCode = functionalErrorCode; + } +} diff --git a/exposure-engine/provisioning/src/main/java/com/alu/e3/prov/deployment/DeploymentException.java b/exposure-engine/provisioning/src/main/java/com/alu/e3/prov/deployment/DeploymentException.java new file mode 100644 index 0000000..d47823c --- /dev/null +++ b/exposure-engine/provisioning/src/main/java/com/alu/e3/prov/deployment/DeploymentException.java @@ -0,0 +1,58 @@ +/** + * Copyright © 2012 Alcatel-Lucent. + * + * See the NOTICE file distributed with this work for additional + * information regarding copyright ownership. + * Licensed to you 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 com.alu.e3.prov.deployment; + +import java.util.ArrayList; +import java.util.List; + +import com.alu.e3.data.model.Instance; +import com.alu.e3.prov.ProvisionException; + +public class DeploymentException extends ProvisionException { + + private static final long serialVersionUID = -6054594686753373061L; + + protected List toRollBack; + + public DeploymentException(int code, String message, Throwable cause) { + super(code, message, cause); + toRollBack = new ArrayList(); + } + + public DeploymentException(int code, String message) { + super(code, message); + toRollBack = new ArrayList(); + + } + + public DeploymentException(int code, Throwable cause) { + super(code, cause); + toRollBack = new ArrayList(); + + } + + public List getToRollBack() { + return toRollBack; + } + + public void setToRollBack(List toRollBack) { + this.toRollBack = toRollBack; + } + +} diff --git a/exposure-engine/provisioning/src/main/java/com/alu/e3/prov/deployment/DeploymentManager.java b/exposure-engine/provisioning/src/main/java/com/alu/e3/prov/deployment/DeploymentManager.java new file mode 100644 index 0000000..41e3cec --- /dev/null +++ b/exposure-engine/provisioning/src/main/java/com/alu/e3/prov/deployment/DeploymentManager.java @@ -0,0 +1,89 @@ +/** + * Copyright © 2012 Alcatel-Lucent. + * + * See the NOTICE file distributed with this work for additional + * information regarding copyright ownership. + * Licensed to you 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 com.alu.e3.prov.deployment; + +import org.springframework.beans.factory.annotation.Autowired; + +import com.alu.e3.common.camel.ExchangeConstantKeys; +import com.alu.e3.common.logging.CategoryLogger; +import com.alu.e3.common.logging.CategoryLoggerFactory; +import com.alu.e3.common.osgi.api.IDataManager; +import com.alu.e3.prov.ApplicationCodeConstants; +import com.alu.e3.prov.LogUtil; +import com.alu.e3.prov.restapi.ExchangeData; + +public class DeploymentManager implements IDeploymentManager { + private static final CategoryLogger logger = CategoryLoggerFactory.getLogger(DeploymentManager.class); + + @Autowired + protected IDataManager dataManager; + + public DeploymentManager() {} + + + + /* (non-Javadoc) + * @see com.alu.e3.prov.deployment.IDeploymentManager#deployApi(com.alu.e3.prov.restapi.ExchangeData, byte[]) + */ + @Override + public void deployApi(ExchangeData exchange, byte[] jarData) throws DeploymentException { + + LogUtil.log(logger, exchange, LogUtil.Phase.DEPLOY, "Deploy Jar Data procedure started"); + + + String apiId = (String) exchange.getProperty(ExchangeConstantKeys.E3_API_ID.toString()); + if(apiId == null) + throw new DeploymentException(ApplicationCodeConstants.DEPLOYMENT_FAILED, "No API ID in exchange"); + + boolean result = false; + + if(jarData != null) { + result = dataManager.deployApi(apiId, jarData); + } + + if(!result) { + logger.error("Deployment failed"); + throw new DeploymentException(ApplicationCodeConstants.DEPLOYMENT_FAILED, "Deployment failed"); + } + + LogUtil.log(logger, exchange, LogUtil.Phase.DEPLOY, "Deploy Jar Data procedure finished"); + + } + + /* (non-Javadoc) + * @see com.alu.e3.prov.deployment.IDeploymentManager#undeployApi(com.alu.e3.prov.restapi.ExchangeData, java.lang.String) + */ + @Override + public void undeployApi(ExchangeData exchange, String apiId) throws DeploymentException { + LogUtil.log(logger, exchange, LogUtil.Phase.UNDEPLOY, "Undeploy Jar Data procedure started"); + + if (logger.isDebugEnabled()) + logger.debug("Undeploy start for API with Id: " + apiId); + + boolean result = dataManager.undeployApi(apiId); + + if(!result) { + logger.error("UnDeployment failed"); + throw new DeploymentException(ApplicationCodeConstants.DEPLOYMENT_FAILED, "Undeployment failed"); + } + + LogUtil.log(logger, exchange, LogUtil.Phase.UNDEPLOY, "Undeploy Jar Data procedure finished"); + } + +} diff --git a/exposure-engine/provisioning/src/main/java/com/alu/e3/prov/deployment/IDeploymentManager.java b/exposure-engine/provisioning/src/main/java/com/alu/e3/prov/deployment/IDeploymentManager.java new file mode 100644 index 0000000..5f9c120 --- /dev/null +++ b/exposure-engine/provisioning/src/main/java/com/alu/e3/prov/deployment/IDeploymentManager.java @@ -0,0 +1,34 @@ +/** + * Copyright © 2012 Alcatel-Lucent. + * + * See the NOTICE file distributed with this work for additional + * information regarding copyright ownership. + * Licensed to you 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 com.alu.e3.prov.deployment; + +import com.alu.e3.prov.restapi.ExchangeData; + +public interface IDeploymentManager { + + public abstract void deployApi(ExchangeData exchange, byte[] jarData) throws DeploymentException; + + /** + * Undeploys APIs through DataManager + * @param apiId the apiId to undeploy + * @throws DeploymentException If an error occured during undeployment. + */ + public abstract void undeployApi(ExchangeData exchange, String apiId) throws DeploymentException; + +} \ No newline at end of file diff --git a/exposure-engine/provisioning/src/main/java/com/alu/e3/prov/deployment/NothingToRollbackException.java b/exposure-engine/provisioning/src/main/java/com/alu/e3/prov/deployment/NothingToRollbackException.java new file mode 100644 index 0000000..6404880 --- /dev/null +++ b/exposure-engine/provisioning/src/main/java/com/alu/e3/prov/deployment/NothingToRollbackException.java @@ -0,0 +1,39 @@ +/** + * Copyright © 2012 Alcatel-Lucent. + * + * See the NOTICE file distributed with this work for additional + * information regarding copyright ownership. + * Licensed to you 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 com.alu.e3.prov.deployment; + +import com.alu.e3.prov.ProvisionException; + +public class NothingToRollbackException extends ProvisionException { + + private static final long serialVersionUID = -7862928566449313500L; + + public NothingToRollbackException(int code, String message, Throwable cause) { + super(code, message, cause); + } + + public NothingToRollbackException(int code, String message) { + super(code, message); + } + + public NothingToRollbackException(int code, Throwable cause) { + super(code, cause); + } + +} diff --git a/exposure-engine/provisioning/src/main/java/com/alu/e3/prov/deployment/RollbackException.java b/exposure-engine/provisioning/src/main/java/com/alu/e3/prov/deployment/RollbackException.java new file mode 100644 index 0000000..fe056dc --- /dev/null +++ b/exposure-engine/provisioning/src/main/java/com/alu/e3/prov/deployment/RollbackException.java @@ -0,0 +1,40 @@ +/** + * Copyright © 2012 Alcatel-Lucent. + * + * See the NOTICE file distributed with this work for additional + * information regarding copyright ownership. + * Licensed to you 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 com.alu.e3.prov.deployment; + +import com.alu.e3.prov.ProvisionException; + + +public class RollbackException extends ProvisionException { + + private static final long serialVersionUID = -6054594686753373061L; + + public RollbackException(int code, String message, Throwable cause) { + super(code, message, cause); + } + + public RollbackException(int code, String message) { + super(code, message); + } + + public RollbackException(int code, Throwable cause) { + super(code, cause); + } + +} diff --git a/exposure-engine/provisioning/src/main/java/com/alu/e3/prov/lifecycle/IDHelper.java b/exposure-engine/provisioning/src/main/java/com/alu/e3/prov/lifecycle/IDHelper.java new file mode 100644 index 0000000..2a242bc --- /dev/null +++ b/exposure-engine/provisioning/src/main/java/com/alu/e3/prov/lifecycle/IDHelper.java @@ -0,0 +1,90 @@ +/** + * Copyright © 2012 Alcatel-Lucent. + * + * See the NOTICE file distributed with this work for additional + * information regarding copyright ownership. + * Licensed to you 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 com.alu.e3.prov.lifecycle; + +import java.util.UUID; +import java.util.regex.Matcher; +import java.util.regex.Pattern; + +import org.apache.commons.codec.DecoderException; +import org.apache.commons.codec.binary.Hex; +import org.slf4j.Logger; +import org.slf4j.LoggerFactory; + +public class IDHelper { + + private static final Logger logger = LoggerFactory.getLogger(IDHelper.class); + + /** + * Extract the apiID from the given filename. + * @param fileName + * @return the API ID + */ + public static String extractApiIdFromFileName(String fileName) { + String [] datas = extractAllFromFileName(fileName); + return datas == null ? null : datas[1]; + } + + /** + * Extract datas from the given filename. + * @param fileName + * @return a String[] containing respectively: { apiIDEncoded, apiID, provID } + */ + public static String[] extractAllFromFileName(String fileName) { + Pattern p = Pattern.compile("([a-f0-9]+)-([a-f0-9]+)\\.[a-z]{3}"); + Matcher m = p.matcher(fileName); + if (!m.matches()) return null; + + String apiIDEncoded = m.group(1); + String apiID = null; + try { + apiID = IDHelper.decode(apiIDEncoded); + } catch (RuntimeException e) { + e.printStackTrace(); + logger.error("Undecodable apiId:{}", apiIDEncoded); + } + String provID = m.group(2); + + String[] datas = new String[] { + apiIDEncoded, + apiID, + provID + }; + + return datas; + } + + // Generate a unique ID to be used as apiID or provID + public static String generateUID() { + return UUID.randomUUID().toString().replace("-", ""); + } + + public static String encode(String original) { + return Hex.encodeHexString(original.getBytes()); + } + + public static String decode(String encoded) { + try { + return new String(Hex.decodeHex(encoded.toCharArray())); + } catch (DecoderException e) { + throw new RuntimeException(e); + } + } + +} diff --git a/exposure-engine/provisioning/src/main/java/com/alu/e3/prov/restapi/ApiManager.java b/exposure-engine/provisioning/src/main/java/com/alu/e3/prov/restapi/ApiManager.java new file mode 100644 index 0000000..9ca063e --- /dev/null +++ b/exposure-engine/provisioning/src/main/java/com/alu/e3/prov/restapi/ApiManager.java @@ -0,0 +1,272 @@ +/** + * Copyright © 2012 Alcatel-Lucent. + * + * See the NOTICE file distributed with this work for additional + * information regarding copyright ownership. + * Licensed to you 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 com.alu.e3.prov.restapi; + +import java.util.List; + +import javax.ws.rs.Consumes; +import javax.ws.rs.DELETE; +import javax.ws.rs.GET; +import javax.ws.rs.POST; +import javax.ws.rs.PUT; +import javax.ws.rs.Path; +import javax.ws.rs.PathParam; +import javax.ws.rs.Produces; +import javax.ws.rs.WebApplicationException; +import javax.ws.rs.core.MediaType; +import javax.ws.rs.core.Response; + +import org.apache.cxf.jaxrs.ext.Description; +import org.springframework.stereotype.Controller; + +import com.alu.e3.common.logging.Category; +import com.alu.e3.common.logging.CategoryLogger; +import com.alu.e3.common.logging.CategoryLoggerFactory; +import com.alu.e3.prov.ApplicationCodeConstants; +import com.alu.e3.prov.ProvisionException; +import com.alu.e3.prov.restapi.model.Api; +import com.alu.e3.prov.restapi.model.ApiResponse; +import com.alu.e3.prov.service.IApiService; + +/** + * This class exposes the REST API to create, update or delete an API on E3 + * system. + */ +@Controller +@Path("/apis") +@Description(value = " E3 REST API to create, update or delete an API") +public class ApiManager extends BasicManager { + private static final CategoryLogger LOG = CategoryLoggerFactory.getLogger(ApiManager.class, Category.PROV); + + private IApiService apiService; + + /** + * + * @param dataManager + */ + public void setApiService(IApiService apiService) { + this.apiService = apiService; + } + + public ApiManager() { + + } + + /** + * This REST API is used to create an API. + * + * @param request + * @return Response + * + * @inputWrapped com.alu.e3.prov.restapi.model.Api + * + * @returnWrapped com.alu.e3.prov.restapi.model.ApiResponse + * + * @HTTP 200 for success + * + * @HTTP 500 for E3 internal errors + * + * @RequestHeader N/A No specific request header needed + * + * @ResponseHeader X-E3-Application-Error-Code 10x E3 Application Error Code + */ + @POST + @Path("") + @Produces({ MediaType.APPLICATION_XML /* , MediaType.APPLICATION_JSON */}) + @Consumes({ MediaType.APPLICATION_XML /* , MediaType.APPLICATION_JSON */}) + @Description(value = "This REST API is used to create an API.") + public Response create(final Api api) { + + if (LOG.isDebugEnabled()) + LOG.debug("Create API ID: {}", api.getId()); + + Action action = new Action() { + protected Object doAction(Object... params) { + try { + apiService.create(api); + } catch (ProvisionException e) { + throw new WebApplicationException(e); + } + return new ApiResponse(ApiResponse.SUCCESS, api.getId()); + } + }; + + return execute(action, (Object) null); + + } + + /** + * This REST API is used to update an API. + * + * @param request + * @param apiID + * the API ID + * @return + * + * @inputWrapped com.alu.e3.prov.restapi.model.Api + * + * @returnWrapped com.alu.e3.prov.restapi.model.ApiResponse + * + * @HTTP 200 for success + * + * @HTTP 500 for E3 internal errors + * + * @RequestHeader N/A No specific request header needed + * + * @ResponseHeader X-E3-Application-Error-Code 10x E3 Application Error Code + */ + @PUT + @Path("/{API_ID}") + @Produces({ MediaType.APPLICATION_XML /* , MediaType.APPLICATION_JSON */}) + @Consumes({ MediaType.APPLICATION_XML }) + @Description(value = "This REST API is used to update an API.") + public Response update(final Api api, final @PathParam("API_ID") String apiId) { + + if (LOG.isDebugEnabled()) + LOG.debug("Update API ID: {}", apiId); + + // check API ID same in Pay-load/URL + if (api == null || api.getId() == null) + throw new WebApplicationException(new ProvisionException(ApplicationCodeConstants.API_ID_NOT_PROVIDED, "API ID missing in the body for Update operation")); + + if (!api.getId().equals(apiId)) + throw new WebApplicationException(new ProvisionException(ApplicationCodeConstants.API_ID_MISMATCH, "API ID not the same in URL vs Body for Update operation: +" + apiId + "/" + apiId)); + + Action action = new Action() { + protected Object doAction(Object... params) { + try { + apiService.update(api); + return new ApiResponse(ApiResponse.SUCCESS, apiId); + + } catch (ProvisionException e) { + throw new WebApplicationException(e); + } + } + }; + return execute(action, (Object) null); + + } + + /** + * This REST API is used to delete an API. + * + * @param apiID + * @return + * @returnWrapped com.alu.e3.prov.restapi.model.ApiResponse + * + * @HTTP 200 for success + * + * @HTTP 500 for E3 internal errors + * + * @RequestHeader N/A No specific request header needed + * + * @ResponseHeader X-E3-Application-Error-Code 10x E3 Application Error Code + */ + @DELETE + @Path("/{API_ID}") + @Produces({ MediaType.APPLICATION_XML }) + @Consumes({ MediaType.WILDCARD }) + @Description(value = "This REST API is used to delete an API.") + public Response delete(final @PathParam("API_ID") String apiId) throws Exception { + + if (LOG.isDebugEnabled()) + LOG.debug("Delete API ID: {}", apiId); + + Action action = new Action() { + + protected Object doAction(Object... params) { + try { + apiService.delete(apiId); + } catch (ProvisionException e) { + throw new WebApplicationException(e); + } + return new ApiResponse(ApiResponse.SUCCESS, apiId); + } + }; + return execute(action, (Object) null); + + } + + /** + * Gets an API by it's ID from E3 system. + * + * @param apiId + * @return + * @throws ProvisionException + */ + @GET + @Path("/{API_ID}") + @Produces({ MediaType.APPLICATION_XML }) + @Consumes({ MediaType.WILDCARD }) + @Description(value = "Used to get an API by this ID.") + public Response get(final @PathParam("API_ID") String apiId) { + + if (LOG.isDebugEnabled()) + LOG.debug("Get API ID: {}", apiId); + + Action action = new Action() { + + protected Object doAction(Object... params) { + try { + Api api = apiService.get(apiId); + return new ApiResponse(ApiResponse.SUCCESS, api); + + } catch (ProvisionException e) { + throw new WebApplicationException(e); + } + } + }; + return execute(action, (Object) null); + + } + + /** + * Get all APIs created on E3 system + * + * @return + * @throws ProvisionException + */ + @GET + @Path("") + @Produces({ MediaType.APPLICATION_XML }) + @Consumes({ MediaType.WILDCARD }) + @Description(value = "Used to get all API IDs.") + public Response getAll() { + + if (LOG.isDebugEnabled()) + LOG.debug("GetAll APIs"); + + Action action = new Action() { + + protected Object doAction(Object... params) { + try { + List apiIdsList = apiService.getAll(); + return new ApiResponse(ApiResponse.SUCCESS, apiIdsList); + + } catch (ProvisionException e) { + throw new WebApplicationException(e); + } + } + + }; + + return execute(action, (Object) null); + } + +} diff --git a/exposure-engine/provisioning/src/main/java/com/alu/e3/prov/restapi/AuthManager.java b/exposure-engine/provisioning/src/main/java/com/alu/e3/prov/restapi/AuthManager.java new file mode 100644 index 0000000..7ba3a8d --- /dev/null +++ b/exposure-engine/provisioning/src/main/java/com/alu/e3/prov/restapi/AuthManager.java @@ -0,0 +1,468 @@ +/** + * Copyright © 2012 Alcatel-Lucent. + * + * See the NOTICE file distributed with this work for additional + * information regarding copyright ownership. + * Licensed to you 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 com.alu.e3.prov.restapi; + +import java.security.InvalidParameterException; +import java.util.HashSet; +import java.util.List; +import java.util.Set; +import java.util.UUID; + +import javax.ws.rs.Consumes; +import javax.ws.rs.DELETE; +import javax.ws.rs.GET; +import javax.ws.rs.POST; +import javax.ws.rs.PUT; +import javax.ws.rs.Path; +import javax.ws.rs.PathParam; +import javax.ws.rs.Produces; +import javax.ws.rs.core.MediaType; +import javax.ws.rs.core.Response; + +import org.apache.cxf.jaxrs.ext.Description; +import org.springframework.stereotype.Controller; + +import com.alu.e3.common.logging.Category; +import com.alu.e3.common.logging.CategoryLogger; +import com.alu.e3.common.logging.CategoryLoggerFactory; +import com.alu.e3.common.osgi.api.IDataManager; +import com.alu.e3.data.wrapper.BeanConverterUtil; +import com.alu.e3.prov.restapi.model.Auth; +import com.alu.e3.prov.restapi.model.AuthKeyAuth; +import com.alu.e3.prov.restapi.model.AuthResponse; +import com.alu.e3.prov.restapi.model.AuthType; +import com.alu.e3.prov.restapi.model.BasicAuth; +import com.alu.e3.prov.restapi.model.Error; +import com.alu.e3.prov.restapi.model.IpWhiteListAuth; +import com.alu.e3.prov.restapi.model.Key; +import com.alu.e3.prov.restapi.model.WSSEAuth; + +/** + * REST API to provision authentications on E3 subsystem. + */ +@Controller +@Path("/auths") +@Description(value = " E3 REST API provision authentications on E3 subsystem") +public class AuthManager extends BasicManager{ + + private static final CategoryLogger LOG = CategoryLoggerFactory.getLogger(AuthManager.class, Category.PROV); + + // business service + private IDataManager dataManager; + + private final Action getAll; + private final Action get; + private final Action delete; + private final Action create; + private final Action update; + + public AuthManager() { + getAll = newGetAllAction(); + get = newGetAction(); + delete = newDeleteAction(); + create = newCreateAction(); + update = newUpdateAction(); + } + + /** + * + * @param dataManager + */ + public void setDataManager(IDataManager dataManager) { + this.dataManager = dataManager; + } + + /** + * This REST API is used to create an authentication element on E3 subsystem. + * + * @param request the Auth structure to create + * @return Response the E3 response + * + * @inputWrapped com.alu.e3.prov.restapi.model.Auth + * + * @returnWrapped com.alu.e3.prov.restapi.model.AuthResponse + * + * @HTTP 200 for success + * + * @HTTP 500 for E3 internal errors + * + * @RequestHeader N/A No specific request header needed + * + * @ResponseHeader X-E3-Application-Error-Code 10x E3 Application Error Code + */ + @POST + @Path("") + @Produces({ MediaType.APPLICATION_XML }) + @Consumes({ MediaType.APPLICATION_XML }) + @Description(value = "This REST API is used to create an authentication element on E3 subsystem.") + public Response create(final Auth auth) { + + if(LOG.isDebugEnabled()) + LOG.debug("Create authentication "); + + return this.execute(create, auth); + } + + /** + * This REST API is used to update the API authentication data. + * + * @param request + * @param id + * the authentication ID + * @return + * + * @inputWrapped com.alu.e3.prov.restapi.model.AuthType + * + * @returnWrapped com.alu.e3.prov.restapi.model.AuthResponse + * + * @HTTP 200 for success + * + * @HTTP 500 for E3 internal errors + * + * @RequestHeader N/A No specific request header needed + * + * @ResponseHeader X-E3-Application-Error-Code 10x E3 Application Error Code + */ + @PUT + @Path("/{AUTH_ID}") + @Produces({ MediaType.APPLICATION_XML }) + @Consumes({ MediaType.APPLICATION_XML }) + @Description(value = "This REST API is used to update an authentication.") + public Response update(final Auth auth, @PathParam("AUTH_ID") final String id) { + + if(LOG.isDebugEnabled()) + LOG.debug("Update Auth ID: {}", id); + + return this.execute(update, auth, id); + } + + /** + * This REST API is used to delete an authentication from E3 subsystem. + * + * @param id + * the auth ID to delete + * @return + * + * + * @returnWrapped com.alu.e3.prov.restapi.model.AuthResponse + * + * @HTTP 200 for success + * + * @HTTP 500 for E3 internal errors + * + * @RequestHeader N/A No specific request header needed + * + * @ResponseHeader X-E3-Application-Error-Code 10x E3 Application Error Code + */ + + @DELETE + @Path("/{AUTH_ID}") + @Produces({ MediaType.APPLICATION_XML }) + @Consumes({ MediaType.WILDCARD }) + @Description(value = "This REST API is used to delete an Auth.") + public Response delete(@PathParam("AUTH_ID") final String id) { + + if(LOG.isDebugEnabled()) + LOG.debug("Delete Auth ID: {}", id); + + return this.execute(delete, id); + + } + + /** + * This REST API is used to get an authentication from E3 subsystem. + * + * @param id + * the auth ID to get + * @return + * + * + * @returnWrapped com.alu.e3.prov.restapi.model.AuthResponse + * + * @HTTP 200 for success + * + * @HTTP 500 for E3 internal errors + * + * @RequestHeader N/A No specific request header needed + * + * @ResponseHeader X-E3-Application-Error-Code 10x E3 Application Error Code + */ + + + @GET + @Path("/{AUTH_ID}") + @Produces({ MediaType.APPLICATION_XML }) + @Consumes({ MediaType.WILDCARD }) + @Description(value = "This REST API is used to get an authentication by ID from E3 subsystem.") + public Response get(@PathParam("AUTH_ID") final String id) { + + if(LOG.isDebugEnabled()) + LOG.debug("Get Auth ID: {}", id); + + return this.execute(get, id); + } + + /** + * This REST API is used to get all authentications from E3 subsystem. + * + * @return all the authentications from E3 subsystem + * + * + * @returnWrapped com.alu.e3.prov.restapi.model.AuthResponse + * + * @HTTP 200 for success + * + * @HTTP 500 for E3 internal errors + * + * @RequestHeader N/A No specific request header needed + * + * @ResponseHeader X-E3-Application-Error-Code 10x E3 Application Error Code + */ + + @GET + @Path("") + @Produces({ MediaType.APPLICATION_XML }) + @Consumes({ MediaType.WILDCARD }) + @Description(value = "This REST API is used to get all authentications from E3 subsystem.") + public Response getAll() { + + if(LOG.isDebugEnabled()) + LOG.debug("GetAll Auths"); + + return execute(getAll); + } + + + protected final Action newCreateAction() { + return new Action("create") { + @Override + protected Object doAction(Object... params) { + + Auth auth = (Auth) params[0]; + + if ((auth.getId() == null) || (auth.getId().equals(""))) { + auth.setId(UUID.randomUUID().toString()); + } + + com.alu.e3.prov.restapi.model.Error error = validate(auth); + + if(LOG.isDebugEnabled()) + LOG.debug("Creating Auth ID:", auth.getId()); + + AuthResponse response = new AuthResponse(AuthResponse.SUCCESS); + if(error == null){ + com.alu.e3.data.model.Auth authDataModel = BeanConverterUtil.toDataModel(auth); + dataManager.addAuth(authDataModel); + response.setId(auth.getId()); + } + else{ + error.setErrorCode("400"); + response.setStatus(AuthResponse.FAILURE); + response.setError(error); + } + + return response; + } + }; + } + + protected final Action newUpdateAction() { + return new Action("update") { + @Override + protected Object doAction(Object... params) { + Auth auth = (Auth) params[0]; + String id = (String) params[1]; + + if(LOG.isDebugEnabled()) + LOG.debug("Updating Auth ID: {}", id); + + com.alu.e3.prov.restapi.model.Error error = validate(auth); + + if(auth.getId() == null || auth.getId().equals("")) + auth.setId(id); + else if(auth.getId().equals(id) == false) + throw new InvalidParameterException("Auth ID mismatch"); + + AuthResponse response = new AuthResponse(AuthResponse.SUCCESS); + + if(error == null){ + com.alu.e3.data.model.Auth authDataModel = BeanConverterUtil.toDataModel(auth); + dataManager.updateAuth(authDataModel); + response.setId(auth.getId()); + } + else{ + error.setErrorCode("400"); + response.setStatus(AuthResponse.FAILURE); + response.setError(error); + } + return response; + } + }; + } + + protected final Action newDeleteAction() { + return new Action("delete") { + @Override + protected Object doAction(Object... params) { + String id = (String) params[0]; + + if(LOG.isDebugEnabled()) + LOG.debug("Deleting Auth ID: {}", id); + + dataManager.removeAuth(id); + + AuthResponse response = new AuthResponse(AuthResponse.SUCCESS); + return response; + } + }; + } + + protected final Action newGetAction() { + return new Action("get") { + @Override + protected Object doAction(Object... params) { + String id = (String) params[0]; + + if(LOG.isDebugEnabled()) + LOG.debug("Getting Auth ID: {}", id); + + com.alu.e3.data.model.Auth authDataModel = dataManager.getAuthById(id, true); + Auth auth = BeanConverterUtil.fromDataModel(authDataModel); + + AuthResponse response = new AuthResponse(AuthResponse.SUCCESS); + response.setAuth(auth); + return response; + + } + }; + } + + protected final Action newGetAllAction() { + return new Action("getAll") { + @Override + protected Object doAction(Object... params) { + if(LOG.isDebugEnabled()) + LOG.debug("Getting All Auths"); + + AuthResponse response = new AuthResponse(AuthResponse.SUCCESS); + + Set auths = dataManager.getAllAuthIds(); + response.getIds().addAll(auths); + + return response; + } + }; + } + + private Error validate(Auth auth) { + com.alu.e3.prov.restapi.model.Error error = new Error(); + error.setErrorText(""); + boolean inError = false; + + // Do some validation + AuthType authType = auth.getType(); + if(authType == null){ + inError = true; + error.setErrorText("Could not determine auth-type from request."); + } else { + if(authType.equals(AuthType.BASIC)){ + BasicAuth basicAuth = auth.getBasicAuth(); + if(basicAuth == null){ + inError = true; + error.setErrorText("Request did not contain BasicAuth info."); + } else { + if(basicAuth.getUsername() == null || basicAuth.getUsername().isEmpty()){ + inError = true; + error.setErrorText("Username must not be empty for Basic authentication type."); + } + if(basicAuth.getPassword() == null || basicAuth.getPassword().length <= 0){ + inError = true; + error.setErrorText(error.getErrorText()+" Password must not be empty for Basic authentication type."); + } + } + } + else if(authType.equals(AuthType.WSSE)){ + WSSEAuth basicAuth = auth.getWsseAuth(); + if(basicAuth == null){ + inError = true; + error.setErrorText("Request did not contain WsseAuth info."); + } else { + if(basicAuth.getUsername() == null || basicAuth.getUsername().isEmpty()){ + inError = true; + error.setErrorText("Username must not be empty for WSSE authentication type."); + } + if(basicAuth.getPassword() == null || basicAuth.getPassword().length <= 0){ + inError = true; + error.setErrorText(error.getErrorText()+" Passowrd must not be empty for WSSE authentication type."); + } + if(basicAuth.getPasswordType() == null){ + inError = true; + error.setErrorText(error.getErrorText()+" PasswordType must not be empty for WSSE authentication type."); + } + } + } + else if(authType.equals(AuthType.AUTHKEY)){ + AuthKeyAuth authKeyAuth = auth.getAuthKeyAuth(); + if(authKeyAuth == null) { + inError = true; + error.setErrorText("Request did not contain AuthKeyAuth info."); + } else { + if(authKeyAuth.getKeyValue()== null || authKeyAuth.getKeyValue().isEmpty()){ + inError = true; + error.setErrorText("authKey must not be empty for AuthKey authentication type."); + } + } + } + else if(authType.equals(AuthType.IP_WHITE_LIST)){ + IpWhiteListAuth ipWhiteListAuth = auth.getIpWhiteListAuth(); + if(ipWhiteListAuth == null) { + inError = true; + error.setErrorText("Request did not contain ipWhiteListAuth info."); + } else { + // We don't check for null ipList here, but could .... + List ipList = ipWhiteListAuth.getIp(); + // Check for duplicate white-list ips by adding all members of list to a Set + Set testSet = new HashSet(); + for (String ip : ipList) { + if (testSet.contains(ip)) { + LOG.debug("Found duplicate whitelist ip: {}", ip); + inError = true; + error.setErrorText("Duplicate ip in white-list: " + ip); + break; + } + testSet.add(ip); + } + } + } + + for(Key key : auth.getProperties()){ + if(key.getName() == null || key.getName().isEmpty()) + throw new IllegalArgumentException("All properties must have a name"); + } + } + + if(inError) + return error; + else + return null; + } + + + +} diff --git a/exposure-engine/provisioning/src/main/java/com/alu/e3/prov/restapi/BasicManager.java b/exposure-engine/provisioning/src/main/java/com/alu/e3/prov/restapi/BasicManager.java new file mode 100644 index 0000000..f8e0f7b --- /dev/null +++ b/exposure-engine/provisioning/src/main/java/com/alu/e3/prov/restapi/BasicManager.java @@ -0,0 +1,79 @@ +/** + * Copyright © 2012 Alcatel-Lucent. + * + * See the NOTICE file distributed with this work for additional + * information regarding copyright ownership. + * Licensed to you 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 com.alu.e3.prov.restapi; + +import javax.ws.rs.core.Response; +import javax.ws.rs.core.Response.ResponseBuilder; + +import com.alu.e3.prov.restapi.model.BasicResponse; + +public class BasicManager { + + + /** + * Generic method to handle REST response and status. + * + * @param params + * @return + */ + protected final Response execute(Action action, final Object... params) { + + BasicResponse response = (BasicResponse) action.doAction(params); + ResponseBuilder builder = Response.ok(response); + if(response.getError() != null){ + builder.status(new Integer(response.getError().getErrorCode())); + } + + return builder.build(); + } + + + /** + * Utility method to re-factor some REST code and introduce a generic method + * doAction to implement business logic. + * + */ + protected static class Action { + String name; + + protected Action() { + } + + protected Action(String name) { + this.name = name; + } + + protected String getName() { + return this.name; + } + + /** + * Business action to implement + * + * @param params + * @return + */ + protected Object doAction(final Object... params) { + return null; + } + + } + + +} diff --git a/exposure-engine/provisioning/src/main/java/com/alu/e3/prov/restapi/BulkPolicyQuotaRLBucketsManager.java b/exposure-engine/provisioning/src/main/java/com/alu/e3/prov/restapi/BulkPolicyQuotaRLBucketsManager.java new file mode 100644 index 0000000..10dd66f --- /dev/null +++ b/exposure-engine/provisioning/src/main/java/com/alu/e3/prov/restapi/BulkPolicyQuotaRLBucketsManager.java @@ -0,0 +1,295 @@ +/** + * Copyright © 2012 Alcatel-Lucent. + * + * See the NOTICE file distributed with this work for additional + * information regarding copyright ownership. + * Licensed to you 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 com.alu.e3.prov.restapi; + +import java.util.List; +import java.util.UUID; + +import javax.ws.rs.Consumes; +import javax.ws.rs.POST; +import javax.ws.rs.PUT; +import javax.ws.rs.Path; +import javax.ws.rs.PathParam; +import javax.ws.rs.Produces; +import javax.ws.rs.WebApplicationException; +import javax.ws.rs.core.MediaType; +import javax.ws.rs.core.Response; + +import org.apache.cxf.jaxrs.ext.Description; +import org.springframework.stereotype.Controller; + +import com.alu.e3.common.logging.Category; +import com.alu.e3.common.logging.CategoryLogger; +import com.alu.e3.common.logging.CategoryLoggerFactory; +import com.alu.e3.common.osgi.api.IDataManager; +import com.alu.e3.data.wrapper.BeanConverterUtil; +import com.alu.e3.prov.ApplicationCodeConstants; +import com.alu.e3.prov.ProvisionException; +import com.alu.e3.prov.restapi.model.AuthIdsNoIdType; +import com.alu.e3.prov.restapi.model.BulkPolicyQuotaRLBucketType; +import com.alu.e3.prov.restapi.model.PolicyIdsType; +import com.alu.e3.prov.restapi.model.PolicyResponse; + +/** + * The web service to create or delete a bucket of auths associated to a list of + * policies. + */ +@Controller +@Path("/bulk/policies/quotaRLBuckets") +@Description(value = " E3 REST API to create or delete a bucket of auths associated to a list of policies") +public class BulkPolicyQuotaRLBucketsManager extends BasicManager { + + private static final CategoryLogger LOG = CategoryLoggerFactory.getLogger(BulkPolicyQuotaRLBucketsManager.class, Category.PROV); + + private IDataManager dataManager; + + public BulkPolicyQuotaRLBucketsManager() { + } + + /** + * + * @param dataManager + */ + public void setDataManager(IDataManager dataManager) { + this.dataManager = dataManager; + } + + /** + * This REST API is used to create a bulk to associate auths to policies + * @param request + * @return Response + * @throws ProvisionException + * + * @inputWrapped com.alu.e3.prov.restapi.model.BulkPolicyQuotaRLBucketType + * + * @returnWrapped com.alu.e3.prov.restapi.model.PolicyResponse + * + * @HTTP 200 for success + * + * @HTTP 500 for E3 internal errors + * + * @RequestHeader N/A No specific request header needed + * + * @ResponseHeader N/A No specific response header needed + */ + @POST + @Path("") + @Produces({ MediaType.APPLICATION_XML }) + @Consumes({ MediaType.APPLICATION_XML }) + @Description(value = "This REST API is used to create a bucket linked to a list of policies.") + public Response createBucket(final BulkPolicyQuotaRLBucketType request) throws ProvisionException { + + checkCreate(request); + + Action addBucket = new Action() { + + protected Object doAction(Object... params) { + PolicyIdsType policies = request.getPolicies(); + AuthIdsNoIdType authIds = request.getQuotaRLBucket(); + + if (authIds.getId() == null || authIds.getId().equals("")) { + // create the id + authIds.setId(UUID.randomUUID().toString()); + } + + LOG.debug("Add auths to policies:" + policies + " on bucket:" + authIds); + + com.alu.e3.data.model.sub.QuotaRLBucket authIdsDataModel = BeanConverterUtil.toDataModel(authIds); + dataManager.addAuthsToBucket(policies.getId(), authIds.getId(), authIdsDataModel); + + return new PolicyResponse(PolicyResponse.SUCCESS, authIds.getId()); + } + }; + + return execute(addBucket, request); + } + + + /** + * This REST API is used to append auths to a bucket for several policies + * @param request + * @return Response + * @throws ProvisionException + * + * @inputWrapped com.alu.e3.prov.restapi.model.BulkPolicyQuotaRLBucketType + * + * @returnWrapped com.alu.e3.prov.restapi.model.PolicyResponse + * + * @HTTP 200 for success + * + * @HTTP 500 for E3 internal errors + * + * @RequestHeader N/A No specific request header needed + * + * @ResponseHeader N/A No specific response header needed + */ + @PUT + @Path("/{BUCKET_ID}") + @Produces({ MediaType.APPLICATION_XML }) + @Consumes({ MediaType.APPLICATION_XML }) + @Description(value = "This REST API is used to append auths to a bucket for several policies.") + public Response appendBucket(final BulkPolicyQuotaRLBucketType request, final @PathParam("BUCKET_ID") String bucketID) throws ProvisionException { + + checkCreate(request); + + AuthIdsNoIdType authIds = request.getQuotaRLBucket(); + + if (authIds.getId() != null) { + if(!authIds.getId().equals(bucketID)){ + throw new WebApplicationException(new ProvisionException(ApplicationCodeConstants.INVALID_XML, "Bucket ID not the same in payload as in URL:" + authIds.getId() +" >> " + bucketID)); + } + + } + + Action appendBucket = new Action() { + + protected Object doAction(Object... params) { + PolicyIdsType policies = request.getPolicies(); + + AuthIdsNoIdType authIds = request.getQuotaRLBucket(); + + LOG.debug("Add auths to policies:" + policies + " on bucket:" + authIds); + + com.alu.e3.data.model.sub.QuotaRLBucket authIdsDataModel = BeanConverterUtil.toDataModel(authIds); + dataManager.appendAuthsToBucket(policies.getId(), authIds.getId(), authIdsDataModel); + + return new PolicyResponse(PolicyResponse.SUCCESS, authIds.getId()); + } + }; + + return execute(appendBucket, request); + } + + /** + * Deletes a QuotaRLBucket from a list of policies. + * + * @inputWrapped com.alu.e3.prov.restapi.model.BulkPolicyQuotaRLBucketType + * + * @returnWrapped com.alu.e3.prov.restapi.model.PolicyResponse + * + * @HTTP 200 for success + * + * @HTTP 500 for E3 internal errors + * + * @RequestHeader N/A No specific request header needed + * + * @ResponseHeader N/A No specific response header needed + */ + @PUT + @Path("/{BUCKET_ID}/deleteBucket") + @Produces({ MediaType.APPLICATION_XML }) + @Consumes({ MediaType.APPLICATION_XML }) + @Description(value = "This REST API is used to remove a bucket from a list of policies.") + public Response deleteBucket(final BulkPolicyQuotaRLBucketType request, final @PathParam("BUCKET_ID") String bucketID) throws ProvisionException { + + checkDelete(request); + + Action deleteBucket = new Action() { + + protected Object doAction(Object... params) { + PolicyIdsType policies = request.getPolicies(); + + LOG.debug("Remove bucket ID:[" + bucketID + "] on policy:"+ policies.getId()); + + dataManager.removeBucket(policies.getId(), bucketID); + + return new PolicyResponse(PolicyResponse.SUCCESS); + } + }; + return execute(deleteBucket, bucketID); + } + + + /** + * This REST API is used to remove auths from a bucket for several policies + * @param request + * @return Response + * @throws ProvisionException + * + * @inputWrapped com.alu.e3.prov.restapi.model.BulkPolicyQuotaRLBucketType + * + * @returnWrapped com.alu.e3.prov.restapi.model.PolicyResponse + * + * @HTTP 200 for success + * + * @HTTP 500 for E3 internal errors + * + * @RequestHeader N/A No specific request header needed + * + * @ResponseHeader N/A No specific response header needed + */ + @PUT + @Path("/{BUCKET_ID}/deleteAuth") + @Produces({ MediaType.APPLICATION_XML }) + @Consumes({ MediaType.APPLICATION_XML }) + @Description(value = "This REST API is used to remove auths from a bucket for several policies.") + public Response deleteAuth(final BulkPolicyQuotaRLBucketType request, final @PathParam("BUCKET_ID") String bucketID) throws ProvisionException { + + checkCreate(request); + + AuthIdsNoIdType authIds = request.getQuotaRLBucket(); + + if (authIds.getId() != null) { + if(!authIds.getId().equals(bucketID)){ + throw new WebApplicationException(new ProvisionException(ApplicationCodeConstants.INVALID_XML, "Bucket ID not the same in payload as in URL:" + authIds.getId() +" >> " + bucketID)); + } + } + + Action removeAuths = new Action() { + protected Object doAction(Object... params) { + PolicyIdsType policies = request.getPolicies(); + AuthIdsNoIdType authIds = request.getQuotaRLBucket(); + dataManager.removeAuthsFromBucket(policies.getId(), bucketID, authIds.getAuthIds()); + LOG.debug("Remove auths from policies:" + policies + " on bucket:" + authIds); + return new PolicyResponse(PolicyResponse.SUCCESS); + } + }; + + return execute(removeAuths, request); + } + + + private boolean checkCreate(BulkPolicyQuotaRLBucketType request) throws ProvisionException { + boolean result = check(request); + + if(request.getQuotaRLBucket() == null){ + throw new WebApplicationException(new ProvisionException(ApplicationCodeConstants.INVALID_XML, "Bulk validation failure: bucket of auths missing -> tag ")); + } + + return result; + } + + private boolean checkDelete(BulkPolicyQuotaRLBucketType request) throws ProvisionException { + boolean result = check(request); + + return result; + + } + + private boolean check(BulkPolicyQuotaRLBucketType request) throws ProvisionException { + boolean restult = (request != null); + + if (!restult) { + throw new WebApplicationException(new ProvisionException(ApplicationCodeConstants.INVALID_XML, "Bulk validation failure: request empty")); + } + + return restult; + + } +} diff --git a/exposure-engine/provisioning/src/main/java/com/alu/e3/prov/restapi/ExchangeData.java b/exposure-engine/provisioning/src/main/java/com/alu/e3/prov/restapi/ExchangeData.java new file mode 100644 index 0000000..eb768c0 --- /dev/null +++ b/exposure-engine/provisioning/src/main/java/com/alu/e3/prov/restapi/ExchangeData.java @@ -0,0 +1,47 @@ +/** + * Copyright © 2012 Alcatel-Lucent. + * + * See the NOTICE file distributed with this work for additional + * information regarding copyright ownership. + * Licensed to you 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 com.alu.e3.prov.restapi; + +import java.util.HashMap; +import java.util.Map; + +public class ExchangeData { + private Map properties; + + public ExchangeData(){ + + } + + public Map getProperties(){ + if (properties == null) { + properties = new HashMap(); + } + return properties; + } + + public void setProperties(Map properties) { + this.properties = properties; + } + + public Object getProperty(String name){ + return getProperties().get(name); + } + + +} diff --git a/exposure-engine/provisioning/src/main/java/com/alu/e3/prov/restapi/KeyCertManager.java b/exposure-engine/provisioning/src/main/java/com/alu/e3/prov/restapi/KeyCertManager.java new file mode 100644 index 0000000..460bf02 --- /dev/null +++ b/exposure-engine/provisioning/src/main/java/com/alu/e3/prov/restapi/KeyCertManager.java @@ -0,0 +1,775 @@ +/** + * Copyright © 2012 Alcatel-Lucent. + * + * See the NOTICE file distributed with this work for additional + * information regarding copyright ownership. + * Licensed to you 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 com.alu.e3.prov.restapi; + +import java.security.InvalidParameterException; +import java.util.Set; +import java.util.UUID; + +import javax.ws.rs.Consumes; +import javax.ws.rs.DELETE; +import javax.ws.rs.GET; +import javax.ws.rs.POST; +import javax.ws.rs.PUT; +import javax.ws.rs.Path; +import javax.ws.rs.PathParam; +import javax.ws.rs.Produces; +import javax.ws.rs.core.MediaType; +import javax.ws.rs.core.Response; + +import org.apache.cxf.jaxrs.ext.Description; +import org.springframework.stereotype.Controller; + +import com.alu.e3.common.logging.Category; +import com.alu.e3.common.logging.CategoryLogger; +import com.alu.e3.common.logging.CategoryLoggerFactory; +import com.alu.e3.common.osgi.api.IDataManager; +import com.alu.e3.data.model.Certificate; +import com.alu.e3.data.wrapper.BeanConverterUtil; +import com.alu.e3.prov.restapi.model.SSLCert; +import com.alu.e3.prov.restapi.model.SSLCertResponse; +import com.alu.e3.prov.restapi.model.SSLKey; +import com.alu.e3.prov.restapi.model.SSLKeyResponse; + +/** + * REST API to provision SSLKeys and SSLCerts on E3 subsystem. + */ +@Controller +@Path("/keys") +@Description(value = " E3 REST API provision SSLKeys and SSLCerts on E3 subsystem") +public class KeyCertManager extends BasicManager{ + + private static final CategoryLogger LOG = CategoryLoggerFactory.getLogger(KeyCertManager.class, Category.PROV); + + // business service + private IDataManager dataManager; + + private final Action getAllKeys; + private final Action getKey; + private final Action deleteKey; + private final Action createKey; + private final Action updateKey; + + private final Action getAllCerts; + private final Action getCert; + private final Action deleteCert; + private final Action createCert; + private final Action updateCert; + + private final Action getCSR; + private final Action getSelfSigned; + + public KeyCertManager() { + getAllKeys = newGetAllKeysAction(); + getKey = newGetKeyAction(); + deleteKey = newDeleteKeyAction(); + createKey = newCreateKeyAction(); + updateKey = newUpdateKeyAction(); + + getAllCerts = newGetAllCertsAction(); + getCert = newGetCertAction(); + deleteCert = newDeleteCertAction(); + createCert = newCreateCertAction(); + updateCert = newUpdateCertAction(); + + getCSR = newGetCSRAction(); + getSelfSigned = newGetSelfSignedAction(); + } + + + + /** + * + * @param dataManager + */ + public void setDataManager(IDataManager dataManager) { + this.dataManager = dataManager; + } + + /** + * This REST API is used to create a a SSLKey element on E3 subsystem. + * + * @param request the SSLKey structure to create + * @return Response the E3 response + * + * @inputWrapped com.alu.e3.prov.restapi.model.SSLKey + * + * @returnWrapped com.alu.e3.prov.restapi.model.SSLKeyResponse + * + * @HTTP 200 for success + * + * @HTTP 500 for E3 internal errors + * + * @RequestHeader N/A No specific request header needed + * + * @ResponseHeader X-E3-Application-Error-Code 10x E3 Application Error Code + */ + @POST + @Path("") + @Produces({ MediaType.APPLICATION_XML }) + @Consumes({ MediaType.APPLICATION_XML }) + @Description(value = "This REST API is used to create an SSLKey element on E3 subsystem.") + public Response create(final SSLKey key) { + + if(LOG.isDebugEnabled()) + LOG.debug("Create SSLKey "); + + return this.execute(createKey, key); + } + + /** + * This REST API is used to update the SSLKey data. + * + * @param request + * @param id + * the SSLKey ID + * @return + * + * @inputWrapped com.alu.e3.prov.restapi.model.SSLKey + * + * @returnWrapped com.alu.e3.prov.restapi.model.SSLKeyResponse + * + * @HTTP 200 for success + * + * @HTTP 500 for E3 internal errors + * + * @RequestHeader N/A No specific request header needed + * + * @ResponseHeader X-E3-Application-Error-Code 10x E3 Application Error Code + */ + @PUT + @Path("/{KEY_ID}") + @Produces({ MediaType.APPLICATION_XML }) + @Consumes({ MediaType.APPLICATION_XML }) + @Description(value = "This REST API is used to update an SSLKey.") + public Response update(final SSLKey key, @PathParam("KEY_ID") final String id) { + + if(LOG.isDebugEnabled()) + LOG.debug("Update SSLKey ID: {}", id); + + return this.execute(updateKey, key, id); + } + + /** + * This REST API is used to delete an SSLKey from E3 subsystem. + * + * @param id + * the SSLkey ID to delete + * @return + * + * + * @returnWrapped com.alu.e3.prov.restapi.model.SSLKeyResponse + * + * @HTTP 200 for success + * + * @HTTP 500 for E3 internal errors + * + * @RequestHeader N/A No specific request header needed + * + * @ResponseHeader X-E3-Application-Error-Code 10x E3 Application Error Code + */ + + @DELETE + @Path("/{KEY_ID}") + @Produces({ MediaType.APPLICATION_XML }) + @Consumes({ MediaType.WILDCARD }) + @Description(value = "This REST API is used to delete an SSLKey.") + public Response delete(@PathParam("KEY_ID") final String id) { + + if(LOG.isDebugEnabled()) + LOG.debug("Delete SSLKey ID: {}", id); + + return this.execute(deleteKey, id); + + } + + /** + * This REST API is used to get an SSLKey from E3 subsystem. + * + * @param id + * the SSLkey ID to get + * @return + * + * + * @returnWrapped com.alu.e3.prov.restapi.model.SSLKeyResponse + * + * @HTTP 200 for success + * + * @HTTP 500 for E3 internal errors + * + * @RequestHeader N/A No specific request header needed + * + * @ResponseHeader X-E3-Application-Error-Code 10x E3 Application Error Code + */ + + + @GET + @Path("/{KEY_ID}") + @Produces({ MediaType.APPLICATION_XML }) + @Consumes({ MediaType.WILDCARD }) + @Description(value = "This REST API is used to get an SSLKey by ID from E3 subsystem.") + public Response get(@PathParam("KEY_ID") final String id) { + + if(LOG.isDebugEnabled()) + LOG.debug("Get SSLKey ID: {}", id); + + return this.execute(getKey, id); + } + + /** + * This REST API is used to get all SSLKeys from E3 subsystem. + * + * @return all the SSLKeys from E3 subsystem + * + * + * @returnWrapped com.alu.e3.prov.restapi.model.SSLKeyResponse + * + * @HTTP 200 for success + * + * @HTTP 500 for E3 internal errors + * + * @RequestHeader N/A No specific request header needed + * + * @ResponseHeader X-E3-Application-Error-Code 10x E3 Application Error Code + */ + + @GET + @Path("") + @Produces({ MediaType.APPLICATION_XML }) + @Consumes({ MediaType.WILDCARD }) + @Description(value = "This REST API is used to get all SSLKeys from E3 subsystem.") + public Response getAll() { + + if(LOG.isDebugEnabled()) + LOG.debug("GetAll SSLKeys"); + + return execute(getAllKeys); + } + + /** + * This REST API is used to create a a SSLCert element on E3 subsystem. + * + * @param request the SSLCert structure to create + * @return Response the E3 response + * + * @inputWrapped com.alu.e3.prov.restapi.model.SSLCert + * + * @returnWrapped com.alu.e3.prov.restapi.model.SSLCertResponse + * + * @HTTP 200 for success + * + * @HTTP 500 for E3 internal errors + * + * @RequestHeader N/A No specific request header needed + * + * @ResponseHeader X-E3-Application-Error-Code 10x E3 Application Error Code + */ + @POST + @Path("/{KEY_ID}/certs") + @Produces({ MediaType.APPLICATION_XML }) + @Consumes({ MediaType.APPLICATION_XML }) + @Description(value = "This REST API is used to create an SSLCert element on E3 subsystem.") + public Response createCert(final SSLCert cert, @PathParam("KEY_ID") final String keyId) { + + if(LOG.isDebugEnabled()) + LOG.debug("Create SSLCert "); + + return this.execute(createCert, keyId, cert); + } + + /** + * This REST API is used to update the SSLKey data. + * + * @param request + * @param keyId + * the SSLKey ID + * @param certId + * the SSLCert ID to get + * @return + * + * @inputWrapped com.alu.e3.prov.restapi.model.SSLCert + * + * @returnWrapped com.alu.e3.prov.restapi.model.SSLCertResponse + * + * @HTTP 200 for success + * + * @HTTP 500 for E3 internal errors + * + * @RequestHeader N/A No specific request header needed + * + * @ResponseHeader X-E3-Application-Error-Code 10x E3 Application Error Code + */ + @PUT + @Path("/{KEY_ID}/certs/{CERT_ID}") + @Produces({ MediaType.APPLICATION_XML }) + @Consumes({ MediaType.APPLICATION_XML }) + @Description(value = "This REST API is used to update an SSLKey.") + public Response updateCert(final SSLCert cert, @PathParam("KEY_ID") final String keyId, @PathParam("CERT_ID") final String certId) { + + if(LOG.isDebugEnabled()) + LOG.debug("Update SSLCert ID: {}", certId); + + return this.execute(updateCert, cert, keyId, certId); + } + + /** + * This REST API is used to delete an SSLCert from E3 subsystem. + * + * @param certId + * the SSLkey ID to delete + * @param certId + * the SSLCert ID to delete + * @return + * + * + * @returnWrapped com.alu.e3.prov.restapi.model.SSLCertResponse + * + * @HTTP 200 for success + * + * @HTTP 500 for E3 internal errors + * + * @RequestHeader N/A No specific request header needed + * + * @ResponseHeader X-E3-Application-Error-Code 10x E3 Application Error Code + */ + + @DELETE + @Path("/{KEY_ID}/certs/{CERT_ID}") + @Produces({ MediaType.APPLICATION_XML }) + @Consumes({ MediaType.WILDCARD }) + @Description(value = "This REST API is used to delete an SSLCert.") + public Response deleteCert(@PathParam("KEY_ID") final String keyId, @PathParam("CERT_ID") final String certId) { + + if(LOG.isDebugEnabled()) + LOG.debug("Delete SSLCert ID: {}", certId); + + return this.execute(deleteCert, keyId, certId); + + } + + /** + * This REST API is used to get an SSLCert from E3 subsystem. + * + * @param keyId + * the SSLkey ID to get + * @param certId + * the SSLCert ID to get + * @return + * + * + * @returnWrapped com.alu.e3.prov.restapi.model.SSLCertResponse + * + * @HTTP 200 for success + * + * @HTTP 500 for E3 internal errors + * + * @RequestHeader N/A No specific request header needed + * + * @ResponseHeader X-E3-Application-Error-Code 10x E3 Application Error Code + */ + + + @GET + @Path("/{KEY_ID}/certs/{CERT_ID}") + @Produces({ MediaType.APPLICATION_XML }) + @Consumes({ MediaType.WILDCARD }) + @Description(value = "This REST API is used to get an SSLKey by ID from E3 subsystem.") + public Response getCert(@PathParam("KEY_ID") final String keyId, @PathParam("CERT_ID") final String certId) { + + if(LOG.isDebugEnabled()) + LOG.debug("Get SSLCert ID: {}", certId); + + return this.execute(getCert, keyId, certId); + } + + /** + * This REST API is used to get all SSLCerts for a key + * + * @return all the SSLCerts for a key + * + * + * @returnWrapped com.alu.e3.prov.restapi.model.SSLCertResponse + * + * @HTTP 200 for success + * + * @HTTP 500 for E3 internal errors + * + * @RequestHeader N/A No specific request header needed + * + * @ResponseHeader X-E3-Application-Error-Code 10x E3 Application Error Code + */ + + @GET + @Path("/{KEY_ID}/certs") + @Produces({ MediaType.APPLICATION_XML }) + @Consumes({ MediaType.WILDCARD }) + @Description(value = "This REST API is used to get all SSLCerts for a key.") + public Response getAllCerts(@PathParam("KEY_ID") final String keyId) { + + if(LOG.isDebugEnabled()) + LOG.debug("GetAll SSLKeys"); + + return execute(getAllCerts, keyId); + } + + /** + * This REST API is used to get a CSR for the given SSLKey ID from E3 subsystem. + * + * @param id + * the SSLkey ID to get + * @return + * + * + * @returnWrapped com.alu.e3.prov.restapi.model.SSLCertResponse + * + * @HTTP 200 for success + * + * @HTTP 500 for E3 internal errors + * + * @RequestHeader N/A No specific request header needed + * + * @ResponseHeader X-E3-Application-Error-Code 10x E3 Application Error Code + */ + + + @GET + @Path("/{KEY_ID}/csr") + @Produces({ MediaType.APPLICATION_XML }) + @Consumes({ MediaType.WILDCARD }) + @Description(value = "This REST API is used to get a CSR for the given SSLKey ID from E3 subsystem.") + public Response getCSR(@PathParam("KEY_ID") final String id) { + + if(LOG.isDebugEnabled()) + LOG.debug("Get CSR for SSLKey ID: {}", id); + + return this.execute(getCSR, id); + } + + /** + * This REST API is used to create a self-signed cert for an existing Key + * + * @param id + * the SSLkey ID to sign + * @return + * + * + * @returnWrapped com.alu.e3.prov.restapi.model.SSLCertResponse + * + * @HTTP 200 for success + * + * @HTTP 500 for E3 internal errors + * + * @RequestHeader N/A No specific request header needed + * + * @ResponseHeader X-E3-Application-Error-Code 10x E3 Application Error Code + */ + + + @GET + @Path("/{KEY_ID}/selfsign") + @Produces({ MediaType.APPLICATION_XML }) + @Consumes({ MediaType.WILDCARD }) + @Description(value = "This REST API is used to create a self-signed cert for an existing Key") + public Response getSelfSigned(@PathParam("KEY_ID") final String id) { + + if(LOG.isDebugEnabled()) + LOG.debug("Create SelfSign for SSLKey ID: {}", id); + + return this.execute(getSelfSigned, id); + } + + + protected final Action newCreateKeyAction() { + return new Action("create") { + protected Object doAction(Object... params) { + SSLKey key = (SSLKey) params[0]; + + if ((key.getId() == null) || (key.getId().equals(""))) { + key.setId(UUID.randomUUID().toString()); + } + + if (key.getContent() == null || key.getContent().isEmpty()) { + throw new IllegalArgumentException("Must include content when creating a key"); + } + if(key.getDisplayName() == null || key.getDisplayName().isEmpty()) { + throw new IllegalArgumentException("Must include a display name when creating a key"); + } + + if(LOG.isDebugEnabled()) + LOG.debug("Creating SSLKey ID:", key.getId()); + + // Convert the provisioning object to the true model object + com.alu.e3.data.model.Key modelKey = BeanConverterUtil.toDataModel(key); + dataManager.addKey(modelKey); + + SSLKeyResponse response = new SSLKeyResponse(SSLKeyResponse.SUCCESS); + + response.setId(key.getId()); + return response; + } + }; + } + + protected final Action newUpdateKeyAction() { + return new Action("update") { + protected Object doAction(Object... params) { + SSLKey key = (SSLKey) params[0]; + String id = (String) params[1]; + + if(LOG.isDebugEnabled()) + LOG.debug("Updating SSLKey ID: {}", id); + + if(key.getId() == null || key.getId().isEmpty()) + key.setId(id); + else if(key.getId().equals(id) == false) + throw new InvalidParameterException("SSLKey ID mismatch"); + + com.alu.e3.data.model.Key modelKey = BeanConverterUtil.toDataModel(key); + dataManager.updateKey(modelKey); + + SSLKeyResponse response = new SSLKeyResponse(SSLKeyResponse.SUCCESS); + response.setId(key.getId()); + return response; + } + }; + } + + protected final Action newDeleteKeyAction() { + return new Action("delete") { + protected Object doAction(Object... params) { + String id = (String) params[0]; + + if(LOG.isDebugEnabled()) + LOG.debug("Deleting Auth ID: {}", id); + + dataManager.removeKey(id); + + SSLKeyResponse response = new SSLKeyResponse(SSLKeyResponse.SUCCESS); + return response; + } + }; + } + + protected final Action newGetKeyAction() { + return new Action("get") { + protected Object doAction(Object... params) { + String id = (String) params[0]; + + if(LOG.isDebugEnabled()) + LOG.debug("Getting Auth ID: {}", id); + + com.alu.e3.data.model.Key modelKey = dataManager.getKeyById(id, true); + SSLKey key = null; + if(modelKey != null) + key = BeanConverterUtil.fromDataModel(modelKey); + + + SSLKeyResponse response = new SSLKeyResponse(SSLKeyResponse.SUCCESS); + response.setKey(key); + return response; + + } + }; + } + + protected final Action newGetAllKeysAction() { + return new Action("getAll") { + protected Object doAction(Object... params) { + if(LOG.isDebugEnabled()) + LOG.debug("Getting All Auths"); + + SSLKeyResponse response = new SSLKeyResponse(SSLKeyResponse.SUCCESS); + + Set keyIds = dataManager.getAllKeyIds(); + + response.getIds().addAll(keyIds); + + return response; + } + }; + } + + protected final Action newCreateCertAction() { + return new Action("create") { + protected Object doAction(Object... params) { + String keyId = (String) params[0]; + SSLCert cert = (SSLCert) params[1]; + + if (cert.getId() == null || cert.getId().isEmpty()) { + cert.setId(UUID.randomUUID().toString()); + } + + if(cert.getDisplayName() == null || cert.getDisplayName().isEmpty()) { + throw new IllegalArgumentException("Must include a display name when creating a cert"); + } + + if(LOG.isDebugEnabled()) + LOG.debug("Creating SSLCert ID:", cert.getId()); + + cert.setKeyId(keyId); + + Certificate certificate = BeanConverterUtil.toDataModel(cert); + dataManager.addCert(certificate); + + SSLCertResponse response = new SSLCertResponse(SSLCertResponse.SUCCESS); + + response.setId(cert.getId()); + return response; + } + }; + } + + protected final Action newUpdateCertAction() { + return new Action("update") { + protected Object doAction(Object... params) { + SSLCert cert = (SSLCert) params[0]; + String keyId = (String) params[1]; + String certId = (String) params[2]; + + if(LOG.isDebugEnabled()) + LOG.debug("Updating SSLCert ID: {}", keyId); + + if(cert.getId() == null || cert.getId().equals("")) + cert.setId(certId); + else if(cert.getId().equals(certId) == false) + throw new InvalidParameterException("SSLCert ID mismatch"); + + cert.setKeyId(keyId); + + Certificate certificate = BeanConverterUtil.toDataModel(cert); + dataManager.updateCert(certificate); + + SSLCertResponse response = new SSLCertResponse(SSLCertResponse.SUCCESS); + response.setId(cert.getId()); + return response; + } + }; + } + + protected final Action newDeleteCertAction() { + return new Action("delete") { + protected Object doAction(Object... params) { + String keyId = (String) params[0]; + String certId = (String) params[1]; + + if(LOG.isDebugEnabled()) + LOG.debug("Deleting Auth ID: {}", keyId); + + dataManager.removeCert(certId); + + SSLCertResponse response = new SSLCertResponse(SSLCertResponse.SUCCESS); + return response; + } + }; + } + + protected final Action newGetCertAction() { + return new Action("get") { + protected Object doAction(Object... params) { + + String id = (String) params[1]; + + if(LOG.isDebugEnabled()) + LOG.debug("Getting Cert ID: {}", id); + + Certificate c = dataManager.getCertById(id, true); + SSLCert cert = BeanConverterUtil.fromDataModel(c); + + SSLCertResponse response = new SSLCertResponse(SSLCertResponse.SUCCESS); + response.setCert(cert); + return response; + } + }; + } + + protected final Action newGetAllCertsAction() { + return new Action("getAll") { + protected Object doAction(Object... params) { + String keyId = (String) params[0]; + + if(LOG.isDebugEnabled()) + LOG.debug("Getting All Auths"); + + SSLCertResponse response = new SSLCertResponse(SSLCertResponse.SUCCESS); + + + Set certIds = dataManager.getAllCertIdsForKeyId(keyId); + response.getIds().addAll(certIds); + + return response; + } + }; + } + + protected final Action newGetCSRAction() { + return new Action("get") { + protected Object doAction(Object... params) { + String keyId = (String) params[0]; + + if(LOG.isDebugEnabled()) + LOG.debug("Getting CSR for Key ID: {}", keyId); + + /** + * TODO: implement + */ + //dataManager.generateCSR(keyId); + + // Create a mock object to return until the above logic is implemented + // If the Cert already exists then throw illegal argument exception. This logic should go into the datamanager + if(keyId == null || keyId.isEmpty()){ + throw new IllegalArgumentException("SSLKey with that id does not exist"); + } + + SSLCertResponse response = new SSLCertResponse(SSLCertResponse.FAILURE); + com.alu.e3.prov.restapi.model.Error e = new com.alu.e3.prov.restapi.model.Error(); + e.setErrorText("Not Implemented"); + response.setError(e); + return response; + } + }; + } + protected final Action newGetSelfSignedAction() { + return new Action("get") { + protected Object doAction(Object... params) { + String keyId = (String) params[0]; + + if(LOG.isDebugEnabled()) + LOG.debug("Getting CSR for Key ID: {}", keyId); + + /** + * TODO: implement + */ + //dataManager.generateCSR(keyId); + + // Create a mock object to return until the above logic is implemented + // If the Cert already exists then throw illegal argument exception. This logic should go into the datamanager + if(keyId == null || keyId.isEmpty()){ + throw new IllegalArgumentException("SSLKey with that id does not exist"); + } + + SSLCertResponse response = new SSLCertResponse(SSLCertResponse.FAILURE); + com.alu.e3.prov.restapi.model.Error e = new com.alu.e3.prov.restapi.model.Error(); + e.setErrorText("Not Implemented"); + response.setError(e); + return response; + } + }; + } + +} diff --git a/exposure-engine/provisioning/src/main/java/com/alu/e3/prov/restapi/PolicyManager.java b/exposure-engine/provisioning/src/main/java/com/alu/e3/prov/restapi/PolicyManager.java new file mode 100644 index 0000000..aa3f2e3 --- /dev/null +++ b/exposure-engine/provisioning/src/main/java/com/alu/e3/prov/restapi/PolicyManager.java @@ -0,0 +1,507 @@ +/** + * Copyright © 2012 Alcatel-Lucent. + * + * See the NOTICE file distributed with this work for additional + * information regarding copyright ownership. + * Licensed to you 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 com.alu.e3.prov.restapi; + +import java.security.InvalidParameterException; +import java.util.UUID; + +import javax.ws.rs.Consumes; +import javax.ws.rs.DELETE; +import javax.ws.rs.GET; +import javax.ws.rs.POST; +import javax.ws.rs.PUT; +import javax.ws.rs.Path; +import javax.ws.rs.PathParam; +import javax.ws.rs.Produces; +import javax.ws.rs.core.MediaType; +import javax.ws.rs.core.Response; + +import org.apache.cxf.jaxrs.ext.Description; +import org.springframework.stereotype.Controller; + +import com.alu.e3.common.InvalidIDException; +import com.alu.e3.common.logging.Category; +import com.alu.e3.common.logging.CategoryLogger; +import com.alu.e3.common.logging.CategoryLoggerFactory; +import com.alu.e3.common.osgi.api.IDataManager; +import com.alu.e3.data.wrapper.BeanConverterUtil; +import com.alu.e3.prov.restapi.model.AuthIdsNoIdType; +import com.alu.e3.prov.restapi.model.Key; +import com.alu.e3.prov.restapi.model.Policy; +import com.alu.e3.prov.restapi.model.PolicyResponse; + +/** + * The web service to create, update or delete a policy. + */ +@Controller +@Path("/policies") +@Description(value = " E3 REST API to create, update or delete a policy") +public class PolicyManager extends BasicManager{ + + private static final CategoryLogger LOG = CategoryLoggerFactory.getLogger(PolicyManager.class, Category.PROV); + + private final Action create; + private final Action update; + private final Action delete; + private final Action get; + private final Action getAll; + + private final Action createBucket; + private final Action deleteBucket; + private final Action putAuthsToBucket; + private final Action deleteAuthFromBucket; + private final Action deleteAuthsFromBucket; + + private IDataManager dataManager; + + public PolicyManager() { + create = newCreateAction(); + update = newUpdateAction(); + delete = newDeleteAction(); + get = newGetAction(); + getAll = newGetAllAction(); + createBucket = newCreateBucketAction(); + deleteBucket = newDeleteBucketAction(); + putAuthsToBucket = newPutAuthsToBucketAction(); + deleteAuthFromBucket = newDeleteAuthFromBucketAction(); + deleteAuthsFromBucket = newdeleteAuthsFromBucketAction(); + } + + /** + * + * @param dataManager + */ + public void setDataManager(IDataManager dataManager) { + this.dataManager = dataManager; + } + + /** + * Gets all policies. + * + * @returnWrapped com.alu.e3.prov.restapi.model.PolicyResponse + */ + @GET + @Path("") + @Produces({ MediaType.APPLICATION_XML }) + @Consumes({ MediaType.WILDCARD }) + @Description(value = "This REST API is used to fetch all policy ids.") + public Response getAll() { + return execute(getAll); + } + + /** + * Creates a policy. + * + * @inputWrapped com.alu.e3.prov.restapi.model.PolicyDataType + * + * @returnWrapped com.alu.e3.prov.restapi.model.PolicyResponse + */ + @POST + @Path("") + @Produces({ MediaType.APPLICATION_XML }) + @Consumes({ MediaType.APPLICATION_XML }) + @Description(value = "This REST API is used to create a policy.") + public Response create(Policy request) { + return execute(create, request); + } + + /** + * Deletes a policy. + * + * @returnWrapped com.alu.e3.prov.restapi.model.PolicyResponse + */ + @DELETE + @Path("/{POLICY_ID}") + @Produces({ MediaType.APPLICATION_XML }) + @Consumes({ MediaType.WILDCARD }) + @Description(value = "This REST API is used to delete a policy.") + public Response delete(@PathParam("POLICY_ID") String policyID) { + return execute(delete, policyID); + } + + + /** + * Gets a policy. + * + * @returnWrapped com.alu.e3.prov.restapi.model.PolicyResponse + */ + @GET + @Path("/{POLICY_ID}") + @Produces({ MediaType.APPLICATION_XML }) + @Consumes({ MediaType.WILDCARD }) + @Description(value = "This REST API is used to fetch policy data.") + public Response get(@PathParam("POLICY_ID") String policyID) { + return execute(get, policyID); + } + + /** + * Updates a policy. + * + * @inputWrapped com.alu.e3.prov.restapi.model.PolicyDataType + * + * @returnWrapped com.alu.e3.prov.restapi.model.PolicyResponse + */ + @PUT + @Path("/{POLICY_ID}") + @Produces({ MediaType.APPLICATION_XML }) + @Consumes({ MediaType.APPLICATION_XML }) + @Description(value = "This REST API is used to update a policy.") + public Response put(Policy request, @PathParam("POLICY_ID") String policyID) { + return execute(update, request, policyID); + } + + /** + * Creates a QuotaRLBucket in a policy. + * + * @inputWrapped com.alu.e3.prov.restapi.model.QuotaRLBucket + * + * @returnWrapped com.alu.e3.prov.restapi.model.PolicyResponse + */ + @POST + @Path("/{POLICY_ID}/quotaRLBuckets") + @Produces({ MediaType.APPLICATION_XML }) + @Consumes({ MediaType.APPLICATION_XML }) + @Description(value = "This REST API is used to create a QuotaRLBucket in a policy.") + public Response add(AuthIdsNoIdType request, @PathParam("POLICY_ID") String policyID) { + return execute(createBucket, policyID, request); + } + + /** + * Appends Auths to a QuotaRLBucket. + * + * @inputWrapped com.alu.e3.prov.restapi.model.QuotaRLBucket + * + * @returnWrapped com.alu.e3.prov.restapi.model.PolicyResponse + */ + @PUT + @Path("/{POLICY_ID}/quotaRLBuckets/{BUCKET_ID}") + @Produces({ MediaType.APPLICATION_XML }) + @Consumes({ MediaType.APPLICATION_XML }) + @Description(value = "This REST API is used to append auths to a bucket.") + public Response addAuthsToBucket(AuthIdsNoIdType request, @PathParam("POLICY_ID") String policyID, @PathParam("BUCKET_ID") String bucketID) { + return execute(putAuthsToBucket, policyID, bucketID, request); + } + + /** + * Deletes a QuotaRLBucket from a policy. + * + * @returnWrapped com.alu.e3.prov.restapi.model.PolicyResponse + */ + @DELETE + @Path("/{POLICY_ID}/quotaRLBuckets/{BUCKET_ID}") + @Produces({ MediaType.APPLICATION_XML }) + @Consumes({ MediaType.WILDCARD }) + @Description(value = "This REST API is used to remove a bucket from a policy.") + public Response removeBucket(@PathParam("POLICY_ID") String policyID, @PathParam("BUCKET_ID") String bucketID) { + return execute(deleteBucket, policyID, bucketID); + } + + /** + * Deletes a Auth from a QuotaRLBucket. + * + * @returnWrapped com.alu.e3.prov.restapi.model.PolicyResponse + */ + @DELETE + @Path("/{POLICY_ID}/quotaRLBuckets/{BUCKET_ID}/auths/{AUTH_ID}") + @Produces({ MediaType.APPLICATION_XML }) + @Consumes({ MediaType.WILDCARD }) + @Description(value = "This REST API is used to remove an auth from a bucket.") + public Response removeAuthFromBucket(@PathParam("POLICY_ID") String policyID, @PathParam("BUCKET_ID") String bucketID, @PathParam("AUTH_ID") String authID) { + return execute(deleteAuthFromBucket, policyID, bucketID, authID); + } + + /** + * Deletes Auths from a QuotaRLBucket. + * + * @inputWrapped com.alu.e3.prov.restapi.model.QuotaRLBucket + * + * @returnWrapped com.alu.e3.prov.restapi.model.PolicyResponse + */ + @PUT + @Path("/{POLICY_ID}/quotaRLBuckets/{BUCKET_ID}/delete") + @Produces({ MediaType.APPLICATION_XML }) + @Consumes({ MediaType.APPLICATION_XML }) + @Description(value = "This REST API is used to remove Auths from a QuotaRLBucket.") + public Response removeAuthsFromBucket(AuthIdsNoIdType request, @PathParam("POLICY_ID") String policyID, @PathParam("BUCKET_ID") String bucketID) { + return execute(deleteAuthsFromBucket, policyID, bucketID, request); + } + + /** + * Action to create a Policy + * @return + */ + protected final Action newCreateAction() { + return new Action() { + + @Override + protected Object doAction(Object... params) { + Policy policy = (Policy) params[0]; + + if ((policy.getId() == null) || (policy.getId().equals(""))) + { + // create the id + policy.setId(UUID.randomUUID().toString()); + } + + /** + * Some validation + */ + for(Key key : policy.getProperties()){ + if(key.getName() == null || key.getName().isEmpty()) + throw new IllegalArgumentException("All properties must have a name"); + } + + LOG.debug("Creating Policy:", policy.getId()); + + com.alu.e3.data.model.Policy policyDataModel = BeanConverterUtil.toDataModel(policy); + dataManager.addPolicy(policyDataModel); + + PolicyResponse response = new PolicyResponse(PolicyResponse.SUCCESS); + response.setId(policy.getId()); + + return response; + } + }; + } + + /** + * Action to update a Policy + * @return + */ + protected final Action newUpdateAction() { + return new Action() { + + @Override + protected Object doAction(Object... params) { + Policy policy = (Policy) params[0]; + String policyId = (String) params[1]; + + /** + * Some validation + */ + for(Key key : policy.getProperties()){ + if(key.getName() == null || key.getName().isEmpty()) + throw new IllegalArgumentException("All properties must have a name"); + } + + LOG.debug("Updating Policy:", policyId); + + if(policy.getId() == null || policy.getId().equals("")) + policy.setId(policyId); + else if(policy.getId().equals(policyId) == false) + throw new InvalidParameterException("Policy ID mismatch"); + + com.alu.e3.data.model.Policy policyDataModel = BeanConverterUtil.toDataModel(policy); + dataManager.updatePolicy(policyDataModel); + + return new PolicyResponse(PolicyResponse.SUCCESS); + } + }; + } + + /** + * + * @return + */ + protected final Action newDeleteAction() { + return new Action() { + + @Override + protected Object doAction(Object... params) { + String policyId = (String) params[0]; + + LOG.debug("Deleting Policy:", policyId); + + dataManager.removePolicy(policyId); + + return new PolicyResponse(PolicyResponse.SUCCESS); + } + }; + } + + /** + * + * @return + */ + protected final Action newGetAction() { + return new Action() { + + @Override + protected Object doAction(Object... params) { + String policyId = (String) params[0]; + + LOG.debug("Getting Policy:", policyId); + + com.alu.e3.data.model.Policy policyDataModel = dataManager.getPolicyById(policyId); + if(policyDataModel == null) + throw new InvalidIDException("A Policy with that ID does not exist"); + + Policy policy = BeanConverterUtil.fromDataModel(policyDataModel); + + PolicyResponse response = new PolicyResponse(PolicyResponse.SUCCESS); + response.setPolicy(policy); + + return response; + } + }; + } + + /** + * + * @return + */ + protected final Action newGetAllAction() { + return new Action() { + + @Override + protected Object doAction(Object... params) { + + LOG.debug("Get all policies"); + + PolicyResponse response = new PolicyResponse(PolicyResponse.SUCCESS); + + // Get all policies from the store + response.getIds().addAll(dataManager.getAllPolicy()); + + return response; + } + }; + } + + /** + * + * @return + */ + protected final Action newCreateBucketAction() { + return new Action() { + + @Override + protected Object doAction(Object... params) { + String policyId = (String) params[0]; + AuthIdsNoIdType authIds = (AuthIdsNoIdType) params[1]; + + if(authIds.getId() == null || authIds.getId().equals("")) { + // create the id + authIds.setId(UUID.randomUUID().toString()); + } + + LOG.debug("Create bucket:", authIds.getId()); + + com.alu.e3.data.model.sub.QuotaRLBucket authIdsDataModel = BeanConverterUtil.toDataModel(authIds); + dataManager.createBucket(policyId, authIdsDataModel); + + PolicyResponse response = new PolicyResponse(PolicyResponse.SUCCESS); + response.setId(authIds.getId()); + + return response; + } + }; + } + + /** + * + * @return + */ + protected final Action newDeleteBucketAction() { + return new Action() { + + @Override + protected Object doAction(Object... params) { + String policyId = (String) params[0]; + String bucketId = (String) params[1]; + + LOG.debug("Remove bucket:" + bucketId + " on policy:", policyId); + + dataManager.removeBucket(policyId, bucketId); + + return new PolicyResponse(PolicyResponse.SUCCESS); + } + }; + } + + /** + * + * @return + */ + protected final Action newPutAuthsToBucketAction() { + return new Action() { + + @Override + protected Object doAction(Object... params) { + String policyId = (String) params[0]; + String bucketId = (String) params[1]; + AuthIdsNoIdType authIds = (AuthIdsNoIdType) params[2]; + + LOG.debug("Add auths to policy:" + policyId + " on bucket:", bucketId); + + com.alu.e3.data.model.sub.QuotaRLBucket authIdsDataModel = BeanConverterUtil.toDataModel(authIds); + dataManager.addAuthsToBucket(policyId, bucketId, authIdsDataModel); + + return new PolicyResponse(PolicyResponse.SUCCESS); + } + }; + } + + /** + * + * @return + */ + protected final Action newDeleteAuthFromBucketAction() { + return new Action() { + + @Override + protected Object doAction(Object... params) { + String policyId = (String) params[0]; + String bucketId = (String) params[1]; + String authId = (String) params[2]; + + LOG.debug("Remove auth:" + authId + " from policy:" + policyId + "/bucket:" + bucketId); + dataManager.removeAuthFromBucket(policyId, bucketId, authId); + + return new PolicyResponse(PolicyResponse.SUCCESS); + } + }; + } + /** + * + * @return + */ + + protected final Action newdeleteAuthsFromBucketAction() { + return new Action() { + + @Override + protected Object doAction(Object... params) { + String policyId = (String) params[0]; + String bucketId = (String) params[1]; + AuthIdsNoIdType authIds = (AuthIdsNoIdType) params[2]; + + LOG.debug("Remove auths fromo policy:" + policyId + " on bucket:", bucketId); + + for (String authId : authIds.getAuthIds()) + { + dataManager.removeAuthFromBucket(policyId, bucketId, authId); + } + + return new PolicyResponse(PolicyResponse.SUCCESS); + } + }; + } + +} diff --git a/exposure-engine/provisioning/src/main/java/com/alu/e3/prov/restapi/ProxySettingsManager.java b/exposure-engine/provisioning/src/main/java/com/alu/e3/prov/restapi/ProxySettingsManager.java new file mode 100644 index 0000000..ff5f422 --- /dev/null +++ b/exposure-engine/provisioning/src/main/java/com/alu/e3/prov/restapi/ProxySettingsManager.java @@ -0,0 +1,171 @@ +/** + * Copyright © 2012 Alcatel-Lucent. + * + * See the NOTICE file distributed with this work for additional + * information regarding copyright ownership. + * Licensed to you 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 com.alu.e3.prov.restapi; + +import javax.ws.rs.Consumes; +import javax.ws.rs.DELETE; +import javax.ws.rs.GET; +import javax.ws.rs.POST; +import javax.ws.rs.Path; +import javax.ws.rs.Produces; +import javax.ws.rs.core.MediaType; +import javax.ws.rs.core.Response; + +import org.apache.cxf.jaxrs.ext.Description; +import org.springframework.stereotype.Controller; + +import com.alu.e3.common.E3Constant; +import com.alu.e3.common.logging.Category; +import com.alu.e3.common.logging.CategoryLogger; +import com.alu.e3.common.logging.CategoryLoggerFactory; +import com.alu.e3.common.osgi.api.IDataManager; +import com.alu.e3.data.wrapper.BeanConverterUtil; +import com.alu.e3.prov.restapi.model.BasicResponse; +import com.alu.e3.prov.restapi.model.ForwardProxy; +import com.alu.e3.prov.restapi.model.ProxyResponse; + +/** + * This class exposes the REST API to set/get the global proxy settings on the provisioning system. + */ +@Controller +@Path("/proxy") +@Description(value = " E3 REST API to set and get the global proxy settings.") +public class ProxySettingsManager extends BasicManager{ + private static final CategoryLogger LOG = CategoryLoggerFactory.getLogger(ProxySettingsManager.class, Category.PROV); + + private IDataManager dataManager; + + Action set = newSetAction(); + Action get = newGetAction(); + Action delete = newDeleteAction(); + + /** + * + * @param dataManager + */ + public void setDataManager(IDataManager dataManager) { + this.dataManager = dataManager; + } + + public ProxySettingsManager() { + + } + + + /** + * Sets the global proxy settings. + * + * @inputWrapped com.alu.e3.prov.restapi.model.ForwardProxy + * + * @returnWrapped com.alu.e3.prov.restapi.model.ProxyResponse + */ + @POST + @Path("") + @Produces({ MediaType.APPLICATION_XML }) + @Consumes({ MediaType.APPLICATION_XML }) + @Description(value = "This REST API is used to set the global proxy settings.") + public Response set(ForwardProxy request) { + + + return this.execute(set, request); + } + + /** + * Gets the global proxy settings. + * + * @returnWrapped com.alu.e3.prov.restapi.model.ProxyResponse + */ + @GET + @Path("") + @Produces({ MediaType.APPLICATION_XML }) + @Consumes({ MediaType.WILDCARD }) + @Description(value = "This REST API is used to fetch the global proxy settings.") + public Response get() { + return this.execute(get); + } + + /** + * Gets the global proxy settings. + * + * @returnWrapped com.alu.e3.prov.restapi.model.ProxyResponse + */ + @DELETE + @Path("") + @Produces({ MediaType.APPLICATION_XML }) + @Consumes({ MediaType.WILDCARD }) + @Description(value = "This REST API is used to delete the global proxy settings.") + public Response delete() { + return this.execute(delete); + } + + protected final Action newSetAction() { + return new Action() { + + @Override + protected Object doAction(Object... params) { + ForwardProxy proxy = (ForwardProxy) params[0]; + + if(proxy == null) { + } + + dataManager.putSettingString(E3Constant.GLOBAL_PROXY_SETTINGS, BeanConverterUtil.toDataModel(proxy).serialize()); + + BasicResponse response = new BasicResponse(ProxyResponse.SUCCESS); + + return response; + } + }; + } + + protected final Action newGetAction() { + return new Action() { + + @Override + protected Object doAction(Object... params) { + + ProxyResponse response = new ProxyResponse(BasicResponse.SUCCESS); + String serializedProxy = dataManager.getSettingString(E3Constant.GLOBAL_PROXY_SETTINGS); + ForwardProxy proxy = null; + if (serializedProxy != null) { + proxy = BeanConverterUtil.fromDataModel(com.alu.e3.data.model.sub.ForwardProxy.deserialize(serializedProxy)); + } + if (proxy == null) { + proxy = new ForwardProxy(); + } + response.setProxy(proxy); + return response; + } + }; + } + + protected final Action newDeleteAction() { + return new Action() { + + @Override + protected Object doAction(Object... params) { + + dataManager.clearSettingString(E3Constant.GLOBAL_PROXY_SETTINGS); + + BasicResponse response = new BasicResponse(ProxyResponse.SUCCESS); + + return response; + } + }; + } +} diff --git a/exposure-engine/provisioning/src/main/java/com/alu/e3/prov/restapi/TrustStoreManager.java b/exposure-engine/provisioning/src/main/java/com/alu/e3/prov/restapi/TrustStoreManager.java new file mode 100644 index 0000000..43fb520 --- /dev/null +++ b/exposure-engine/provisioning/src/main/java/com/alu/e3/prov/restapi/TrustStoreManager.java @@ -0,0 +1,438 @@ +/** + * Copyright © 2012 Alcatel-Lucent. + * + * See the NOTICE file distributed with this work for additional + * information regarding copyright ownership. + * Licensed to you 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 com.alu.e3.prov.restapi; + +import java.security.InvalidParameterException; +import java.util.UUID; + +import javax.ws.rs.Consumes; +import javax.ws.rs.DELETE; +import javax.ws.rs.GET; +import javax.ws.rs.POST; +import javax.ws.rs.PUT; +import javax.ws.rs.Path; +import javax.ws.rs.PathParam; +import javax.ws.rs.Produces; +import javax.ws.rs.core.MediaType; +import javax.ws.rs.core.Response; + +import org.apache.cxf.jaxrs.ext.Description; +import org.springframework.stereotype.Controller; + +import com.alu.e3.common.logging.Category; +import com.alu.e3.common.logging.CategoryLogger; +import com.alu.e3.common.logging.CategoryLoggerFactory; +import com.alu.e3.common.osgi.api.IDataManager; +import com.alu.e3.data.wrapper.BeanConverterUtil; +import com.alu.e3.prov.restapi.model.SSLCRL; +import com.alu.e3.prov.restapi.model.SSLCRLResponse; +import com.alu.e3.prov.restapi.model.SSLCert; +import com.alu.e3.prov.restapi.model.SSLCertResponse; + +/** + * The web service to create, update or delete a policy. + */ +@Controller +@Path("/truststore") +@Description(value = " E3 REST API to add/update/delete trusted CAs and CRLs") +public class TrustStoreManager extends BasicManager{ + + private static final CategoryLogger LOG = CategoryLoggerFactory.getLogger(TrustStoreManager.class, Category.PROV); + + private final Action getAllCA; + private final Action createCA; + private final Action getCA; + private final Action updateCA; + private final Action deleteCA; + private final Action getAllCRL; + private final Action createCRL; + private final Action getCRL; + private final Action updateCRL; + private final Action deleteCRL; + + private IDataManager dataManager; + + public TrustStoreManager() { + getAllCA = newGetAllCAAction(); + createCA = newCreateCAAction(); + getCA = newGetCAAction(); + updateCA = newUpdateCAAction(); + deleteCA = newDeleteCAAction(); + getAllCRL = newGetAllCRLAction(); + createCRL = newCreateCRLAction(); + getCRL = newGetCRLAction(); + updateCRL = newUpdateCRLAction(); + deleteCRL = newDeleteCRLAction(); + } + + /** + * + * @param dataManager + */ + public void setDataManager(IDataManager dataManager) { + this.dataManager = dataManager; + } + + /** + * Gets all policies. + * + * @returnWrapped com.alu.e3.prov.restapi.model.SSLCertResponse + */ + @GET + @Path("/certs") + @Produces({ MediaType.APPLICATION_XML }) + @Consumes({ MediaType.WILDCARD }) + @Description(value = "This REST API is used to fetch all trusted certificates authorithies.") + public Response getAllCAs() { + return execute(getAllCA); + } + + /** + * Add a new trusted Certificate Authority. + * + * @inputWrapped com.alu.e3.prov.restapi.model.SSLCert + * + * @returnWrapped com.alu.e3.prov.restapi.model.SSLCertResponse + */ + @POST + @Path("/certs") + @Produces({ MediaType.APPLICATION_XML }) + @Consumes({ MediaType.APPLICATION_XML }) + @Description(value = "This REST API is used to add a trusted Certificate Authority.") + public Response addCA(SSLCert request) { + return execute(createCA, request); + } + + /** + * Gets a trusted Certificate Authority. + * + * @returnWrapped com.alu.e3.prov.restapi.model.SSLCertResponse + */ + @GET + @Path("/certs/{CA_ID}") + @Produces({ MediaType.APPLICATION_XML }) + @Consumes({ MediaType.WILDCARD }) + @Description(value = "This REST API is used to fetch trusted Certificate Authority.") + public Response getCA(@PathParam("CA_ID") String caID) { + return execute(getCA, caID); + } + + /** + * Updates a trusted Certificate Authority. + * + * @inputWrapped com.alu.e3.prov.restapi.model.SSLCert + * + * @returnWrapped com.alu.e3.prov.restapi.model.SSLCertResponse + */ + @PUT + @Path("/certs/{CA_ID}") + @Produces({ MediaType.APPLICATION_XML }) + @Consumes({ MediaType.APPLICATION_XML }) + @Description(value = "This REST API is used to update a trusted Certificate Authority.") + public Response updateCA(SSLCert request, @PathParam("CA_ID") String caID) { + return execute(updateCA, request, caID); + } + + /** + * Deletes a trusted Certificate Authority. + * + * @returnWrapped com.alu.e3.prov.restapi.model.SSLCertResponse + */ + @DELETE + @Path("/certs/{CA_ID}") + @Produces({ MediaType.APPLICATION_XML }) + @Consumes({ MediaType.WILDCARD }) + @Description(value = "This REST API is used to remove a trusted Certificate Authority.") + public Response removeCA(@PathParam("CA_ID") String caID) { + return execute(deleteCA, caID); + } + + /** + * Gets all Certificate Revocation List for a Certificate Authority + * + * @returnWrapped com.alu.e3.prov.restapi.model.SSLCRLResponse + */ + @GET + @Path("/crls") + @Produces({ MediaType.APPLICATION_XML }) + @Consumes({ MediaType.WILDCARD }) + @Description(value = "This REST API is used to fetch trusted Certificate Authority.") + public Response getAllCRLs() { + return execute(getAllCRL); + } + + /** + * Adds a Certificate Revocation List for this Certificate Authority + * + * @inputWrapped com.alu.e3.prov.restapi.model.SSLCRL + * + * @returnWrapped com.alu.e3.prov.restapi.model.SSLCRLResponse + */ + @POST + @Path("/crls") + @Produces({ MediaType.APPLICATION_XML }) + @Consumes({ MediaType.APPLICATION_XML }) + @Description(value = "This REST API is used to add a Certificate Revocation List for this Certificate Authority.") + public Response addCRL(SSLCRL request) { + return execute(createCRL, request); + } + + /** + * Gets a Certificate Revocation List. + * + * @returnWrapped com.alu.e3.prov.restapi.model.SSLCRLResponse + */ + @GET + @Path("/crls/{CRL_ID}") + @Produces({ MediaType.APPLICATION_XML }) + @Consumes({ MediaType.WILDCARD }) + @Description(value = "This REST API is used to fetch Certificate Revocation List.") + public Response getCRL(@PathParam("CRL_ID") String crlID) { + return execute(getCRL, crlID); + } + + /** + * Updates a Certificate Revocation List. + * + * @inputWrapped com.alu.e3.prov.restapi.model.SSLCRL + * + * @returnWrapped com.alu.e3.prov.restapi.model.SSLCRLResponse + */ + @PUT + @Path("/crls/{CRL_ID}") + @Produces({ MediaType.APPLICATION_XML }) + @Consumes({ MediaType.APPLICATION_XML }) + @Description(value = "This REST API is used to update a certificate revocation list.") + public Response updateCRL(SSLCRL request, @PathParam("CRL_ID") String crlID) { + return execute(updateCRL, request, crlID); + } + + /** + * Deletes a Certificate Revocation List from a Certificate Authority. + * + * @returnWrapped com.alu.e3.prov.restapi.model.SSLCRLResponse + */ + @DELETE + @Path("/crls/{CRL_ID}") + @Produces({ MediaType.APPLICATION_XML }) + @Consumes({ MediaType.WILDCARD }) + @Description(value = "This REST API is used to remove a certificate revocation list from a certificate authority.") + public Response removeCRL(@PathParam("CRL_ID") String crlID) { + return execute(deleteCRL, crlID); + } + + protected final Action newGetAllCAAction() { + return new Action() { + + protected Object doAction(Object... params) { + + LOG.debug("Get all CA"); + + SSLCertResponse response = new SSLCertResponse(SSLCertResponse.SUCCESS); + + // Get all CA from the store + response.getIds().addAll(dataManager.getAllCA()); + + return response; + } + }; + } + + protected final Action newCreateCAAction() { + return new Action() { + + protected Object doAction(Object... params) { + SSLCert cert = (SSLCert) params[0]; + + if ((cert.getId() == null) || (cert.getId().equals(""))) + { + // create the id + cert.setId(UUID.randomUUID().toString()); + } + + LOG.debug("Creating CA:", cert.getId()); + + com.alu.e3.data.model.Certificate certDataModel = BeanConverterUtil.toDataModel(cert); + dataManager.addCA(certDataModel); + + SSLCertResponse response = new SSLCertResponse(SSLCertResponse.SUCCESS); + response.setId(cert.getId()); + + return response; + } + }; + } + + protected final Action newGetCAAction() { + return new Action() { + + protected Object doAction(Object... params) { + String caId = (String) params[0]; + + LOG.debug("Getting CA:", caId); + + com.alu.e3.data.model.Certificate caDataModel = dataManager.getCAById(caId); + + SSLCert cert = BeanConverterUtil.fromDataModel(caDataModel); + + SSLCertResponse response = new SSLCertResponse(SSLCertResponse.SUCCESS); + response.setCert(cert); + + return response; + } + }; + } + + protected final Action newUpdateCAAction() { + return new Action() { + + protected Object doAction(Object... params) { + SSLCert cert = (SSLCert) params[0]; + String caId = (String) params[1]; + + LOG.debug("Updating CA:", caId); + + if(cert.getId() == null || cert.getId().equals("")) + cert.setId(caId); + else if(cert.getId().equals(caId) == false) + throw new InvalidParameterException("CA ID mismatch"); + + com.alu.e3.data.model.Certificate certDataModel = BeanConverterUtil.toDataModel(cert); + dataManager.updateCA(certDataModel); + + return new SSLCertResponse(SSLCertResponse.SUCCESS); + } + }; + } + + protected final Action newDeleteCAAction() { + return new Action() { + + protected Object doAction(Object... params) { + String caId = (String) params[0]; + + LOG.debug("Deleting CA:", caId); + + dataManager.removeCA(caId); + + return new SSLCertResponse(SSLCertResponse.SUCCESS); + } + }; + } + + protected final Action newGetAllCRLAction() { + return new Action() { + + protected Object doAction(Object... params) { + + LOG.debug("Get all CRL"); + + SSLCRLResponse response = new SSLCRLResponse(SSLCRLResponse.SUCCESS); + + // Get all CRL from the store + response.getIds().addAll(dataManager.getAllCRL()); + + return response; + } + }; + } + + protected final Action newCreateCRLAction() { + return new Action() { + + protected Object doAction(Object... params) { + SSLCRL crl = (SSLCRL) params[0]; + + if ((crl.getId() == null) || (crl.getId().equals(""))) + { + // create the id + crl.setId(UUID.randomUUID().toString()); + } + + LOG.debug("Creating CLR:", crl.getId()); + + com.alu.e3.data.model.SSLCRL clrDataModel = BeanConverterUtil.toDataModel(crl); + dataManager.addCRL(clrDataModel); + + SSLCRLResponse response = new SSLCRLResponse(SSLCRLResponse.SUCCESS); + response.setId(crl.getId()); + + return response; + } + }; + } + + protected final Action newGetCRLAction() { + return new Action() { + + protected Object doAction(Object... params) { + String crlID = (String) params[0]; + + LOG.debug("Getting CRL:", crlID); + + com.alu.e3.data.model.SSLCRL crlDataModel = dataManager.getCRLById(crlID); + + SSLCRL crl = BeanConverterUtil.fromDataModel(crlDataModel); + + SSLCRLResponse response = new SSLCRLResponse(SSLCRLResponse.SUCCESS); + response.setCRL(crl); + + return response; + } + }; + } + + protected final Action newUpdateCRLAction() { + return new Action() { + + protected Object doAction(Object... params) { + SSLCRL crl = (SSLCRL) params[0]; + String crlID = (String) params[1]; + + LOG.debug("Updating CRL:", crlID); + + if(crl.getId() == null || crl.getId().equals("")) + crl.setId(crlID); + else if(crl.getId().equals(crlID) == false) + throw new InvalidParameterException("CRL ID mismatch"); + + com.alu.e3.data.model.SSLCRL crlDataModel = BeanConverterUtil.toDataModel(crl); + dataManager.updateCRL(crlDataModel); + + return new SSLCRLResponse(SSLCRLResponse.SUCCESS); + } + }; + } + + protected final Action newDeleteCRLAction() { + return new Action() { + + protected Object doAction(Object... params) { + String crlId = (String) params[0]; + + LOG.debug("Deleting CRL:", crlId); + + dataManager.removeCRL(crlId); + + return new SSLCRLResponse(SSLCRLResponse.SUCCESS); + } + }; + } +} + diff --git a/exposure-engine/provisioning/src/main/java/com/alu/e3/prov/restapi/model/Action.java b/exposure-engine/provisioning/src/main/java/com/alu/e3/prov/restapi/model/Action.java new file mode 100644 index 0000000..23d0da6 --- /dev/null +++ b/exposure-engine/provisioning/src/main/java/com/alu/e3/prov/restapi/model/Action.java @@ -0,0 +1,60 @@ +/** + * Copyright © 2012 Alcatel-Lucent. + * + * See the NOTICE file distributed with this work for additional + * information regarding copyright ownership. + * Licensed to you 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 com.alu.e3.prov.restapi.model; + +import javax.xml.bind.annotation.XmlEnum; +import javax.xml.bind.annotation.XmlEnumValue; +import javax.xml.bind.annotation.XmlType; + + +/** + * Defines an action. It can be either 'ignore' or 'reject'. + */ +@XmlType(name = "ActionType") +@XmlEnum +public enum Action { + + @XmlEnumValue("ignore") + IGNORE("ignore"), + @XmlEnumValue("reject") + REJECT("reject"); + private final String value; + + public String toString() { + return value; + } + + Action(String v) { + value = v; + } + + public String value() { + return value; + } + + public static Action fromValue(String v) { + for (Action c: Action.values()) { + if (c.value.equals(v)) { + return c; + } + } + throw new IllegalArgumentException(v); + } + +} diff --git a/exposure-engine/provisioning/src/main/java/com/alu/e3/prov/restapi/model/Api.java b/exposure-engine/provisioning/src/main/java/com/alu/e3/prov/restapi/model/Api.java new file mode 100644 index 0000000..10f5cdd --- /dev/null +++ b/exposure-engine/provisioning/src/main/java/com/alu/e3/prov/restapi/model/Api.java @@ -0,0 +1,618 @@ +/** + * Copyright © 2012 Alcatel-Lucent. + * + * See the NOTICE file distributed with this work for additional + * information regarding copyright ownership. + * Licensed to you 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. + */ +// +// This file was generated by the JavaTM Architecture for XML Binding(JAXB) Reference Implementation, vhudson-jaxb-ri-2.2-27 +// See http://java.sun.com/xml/jaxb +// Any modifications to this file will be lost upon recompilation of the source schema. +// Generated on: 2012.03.19 at 02:26:27 PM CET +// + + +package com.alu.e3.prov.restapi.model; + +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.XmlElementWrapper; +import javax.xml.bind.annotation.XmlRootElement; +import javax.xml.bind.annotation.XmlTransient; +import javax.xml.bind.annotation.XmlType; + +/** + * The model to create an API on E3. + * + */ +@XmlRootElement +@XmlAccessorType(XmlAccessType.FIELD) +@XmlType(name = "api", propOrder = { + "id", + "displayName", + "version", + "validation", + "type", + "subscriptionStep", + "notificationFormat", + "endpoint", + "https", + "authentication", + "tdrEnabled", + "status", + "contexts", + "tdrOnUse", + "tdrOnLimitReached", + "tdr", + "properties", + "headerTransEnabled", + "headerTransformations", + "allowedHttpMethods", + "proxySettings" +}) +public class Api { + + /** + * The id of the API that could be provided. + */ + protected String id; + /** + * The API name used for the display + */ + protected String displayName; + /** + * The API version + */ + protected String version; + + /** + * Validation types + */ + protected Validation validation; + + /** + * The API Type: PassThrough or Composite + */ + @XmlElement(name="type", required = true) + protected ApiType type; + + /** + * If present, defines the subscription step + * for this API. + * Subscription: generates X-SubscriberID header. + * Notification: extracts X-SubscriberID. + */ + @XmlElement(name="subscriptionStep", required=false) + protected SubscriptionStep subscriptionStep; + + /** + * If present, defines the notification format for this API. + * HEADER: notifyUrl header is extracted. + * WS_ADDRESSIING: <To> tag element content is extracted. + */ + @XmlElement(name="notificationFormat", required=false) + protected NotificationFormat notificationFormat; + + /** + * The API endpoint URL + */ + @XmlElement(required = true) + protected String endpoint; + + /** + * Whether the API should be exposed over HTTPS + */ + @XmlElement(required = true) + protected HTTPSType https; + + /** + * The supported authentication associated to an API. E3 will use only these types to authenticate the API calls. + */ + @XmlElement(required = true) + protected ProvisionAuthentication authentication; + + /** + * The type of TDR to emit when the API is called. + */ + protected TypeAttribute tdrOnUse; + + /** + * The type of TDR to emit when the limit on the API is reached. + */ + protected TypeAttribute tdrOnLimitReached; + + /** + * Flag to enable or disable at provisioning time the TDR generation. + * Default is true + */ + protected TdrEnabled tdrEnabled = new TdrEnabled(); + + /** + * The API status: active, inactive, pending + */ + @XmlElement(required = true) + protected Status status; + + /** + * The contexts definition for the API. + *

Could be: production, sandbox, test + */ + @XmlElementWrapper(name="contexts", required = true) + @XmlElement(name="context", required = true) + protected List contexts; + + /** + * properties data that will be used by header transforms and/or tdr outputs. + */ + @XmlElementWrapper(name="properties") + @XmlElement(name="property") + protected List properties; + + /** + * The header transformations for the API. + */ + @XmlElementWrapper(name="headerTransformations", required = false) + @XmlElement(name="headerTransformation", required = false) + protected List headerTransformations; + + @XmlElement(name="headerTransEnabled", required=false) + protected Boolean headerTransEnabled = true; + + /** + * The header transformations for the API. + */ + @XmlElementWrapper(name="allowedHttpMethods", required = false) + @XmlElement(name="httpMethod", required = false) + protected List allowedHttpMethods; + + protected ApiProxySettings proxySettings; + + + + /** + * Tells if the api is internal or not. + */ + @XmlTransient + private Boolean internal = false; + + /** + * TDR data for static or dynamic TDR data + */ + protected TdrData tdr; + + /** + * Gets the value of the id property. + * + * @return + * possible object is + * {@link String } + * + */ + public String getId() { + return id; + } + + /** + * Sets the value of the id property. + * + * @param value + * allowed object is + * {@link String } + * + */ + public void setId(String value) { + this.id = value; + } + + /** + * Gets the value of the displayName property. + * + * @return + * possible object is + * {@link String } + * + */ + public String getDisplayName() { + return displayName; + } + + /** + * Sets the value of the displayName property. + * + * @param value + * allowed object is + * {@link String } + * + */ + public void setDisplayName(String value) { + this.displayName = value; + } + + /** + * Gets the value of the version property. + * + * @return + * possible object is + * {@link String } + * + */ + public String getVersion() { + return version; + } + + /** + * Sets the value of the version property. + * + * @param value + * allowed object is + * {@link String } + * + */ + public void setVersion(String value) { + this.version = value; + } + + /** + * Gets the value of the type property. + * + * @return + * possible object is + * {@link ApiType } + * + */ + public ApiType getType() { + return type; + } + + /** + * Sets the value of the type property. + * + * @param value + * allowed object is + * {@link ApiType } + * + */ + public void setType(ApiType value) { + this.type = value; + } + + /** + * Gets the value of the subscription property. + * + * @return value + * allowed object is + * {@link SubscriptionStep } + */ + public SubscriptionStep getSubscriptionStep() { + return subscriptionStep; + } + + /** + * Sets the value of the subscriptionStep property. + * + * @param value + * allowed object is + * {@link SubscriptionStep } + */ + public void setSubscriptionStep(SubscriptionStep subscriptionStep) { + this.subscriptionStep = subscriptionStep; + } + + + /** + * Gets the value of the notificationFormat property. + * + * @return value + * allowed object is + * {@link NotificationFormat } + */ + public NotificationFormat getNotificationFormat() { + return notificationFormat; + } + + + /** + * Sets the value of the notificationFormat property. + * + * @param value + * allowed object is + * {@link NotificationFormat } + */ + public void setNotificationFormat(NotificationFormat notificationFormat) { + this.notificationFormat = notificationFormat; + } + + /** + * Gets the value of the endpoint property. + * + * @return + * possible object is + * {@link String } + * + */ + public String getEndpoint() { + return endpoint; + } + + /** + * Sets the value of the endpoint property. + * + * @param value + * allowed object is + * {@link String } + * + */ + public void setEndpoint(String value) { + this.endpoint = value; + } + + + /** + * Gets the value of the authentication property. + * + * @return + * possible object is + * {@link ProvisionAuthentication } + * + */ + public ProvisionAuthentication getAuthentication() { + return authentication; + } + + /** + * Sets the value of the authentication property. + * + * @param value + * allowed object is + * {@link ProvisionAuthentication } + * + */ + public void setAuthentication(ProvisionAuthentication value) { + this.authentication = value; + } + + /** + * Gets the value of the tdrOnUse property. + * + * @return + * possible object is + * {@link String } + * + */ + public String getTdrOnUse() { + if (tdrOnUse == null) + return ""; + return tdrOnUse.getType(); + } + + /** + * Sets the value of the tdrOnUse property. + * + * @param value + * allowed object is + * {@link String } + * + */ + public void setTdrOnUse(String value) { + if (tdrOnUse == null) + tdrOnUse = new TypeAttribute(); + tdrOnUse.setType(value); + } + + /** + * Gets the value of the tdrOnLimitReached property. + * + * @return + * possible object is + * {@link String } + * + */ + public String getTdrOnLimitReached() { + if (tdrOnLimitReached == null) + return ""; + return tdrOnLimitReached.getType(); + } + + /** + * Sets the value of the tdrOnLimitReached property. + * + * @param value + * allowed object is + * {@link String } + * + */ + public void setTdrOnLimitReached(String value) { + if (tdrOnLimitReached == null) + tdrOnLimitReached = new TypeAttribute(); + tdrOnLimitReached.setType(value); + } + + /** + * Gets the value of the tdrEnabled property. + * + * @return + * possible object is + * {@link TdrEnabled } + * + */ + public TdrEnabled getTdrEnabled() { + return tdrEnabled; + } + + /** + * Sets the value of the tdrEnabled property. + * + * @param value + * allowed object is + * {@link TdrEnabled } + * + */ + public void setTdrEnabled(TdrEnabled value) { + this.tdrEnabled = value; + } + + /** + * Gets the value of the status property. + * + * @return + * possible object is + * {@link Status } + * + */ + public Status getStatus() { + return status; + } + + /** + * Sets the value of the status property. + * + * @param value + * allowed object is + * {@link Status } + * + */ + public void setStatus(Status value) { + this.status = value; + } + + /** + * Gets the value of the contexts property. + * + * @return + * possible object is + * {@link ApiContext } + * + */ + public List getContexts() { + if (contexts == null) { + contexts = new ArrayList(); + } + return contexts; + } + + /** + * Sets the value of the contexts property. + * + * @param value + * allowed object is + * {@link ApiContext } + * + */ + public void setContexts(List value) { + this.contexts = value; + } + + public TdrData getTdr() { + return tdr; + } + + public void setTdr(TdrData tdr) { + this.tdr = tdr; + } + public HTTPSType getHttps() { + return https; + } + + public void setHttps(HTTPSType https) { + this.https = https; + } + + public Validation getValidation() { + return validation; + } + + public void setValidation(Validation validation) { + this.validation = validation; + } + + public List getProperties(){ + if(this.properties == null) + this.properties = new ArrayList(); + return this.properties; + } + + public void setProperties(List value){ + this.properties = value; + } + + public List getHeaderTransformations(){ + if(this.headerTransformations == null) + this.headerTransformations = new ArrayList(); + return this.headerTransformations; + } + + public void setHeaderTransformations(List value){ + this.headerTransformations = value; + } + + public Boolean getHeaderTransEnabled() { + return headerTransEnabled; + } + + public void setHeaderTransEnabled(boolean headerTransEnabled) { + this.headerTransEnabled = headerTransEnabled; + } + + public List getAllowedHttpMethods(){ + if(this.allowedHttpMethods == null) + this.allowedHttpMethods = new ArrayList(); + return this.allowedHttpMethods; + } + + public void setAllowedHttpMethods(List value){ + this.allowedHttpMethods = value; + } + + public String getAllowedHttpMethodsAsString() { + final String comma = ","; + StringBuilder httpMethods = null; + for(com.alu.e3.prov.restapi.model.HttpMethod m : this.getAllowedHttpMethods()) { + if (httpMethods == null) { + httpMethods = new StringBuilder (m.toString()); + } else { + httpMethods.append(comma).append(m.toString()); + } + } + return httpMethods == null ? null : httpMethods.toString(); + } + + public void setAllowedHttpMethodsAsString(String in) { + List methods = new ArrayList(); + if(in!=null) + for(String m : in.split(",")) + methods.add(HttpMethod.valueOf(m)); + this.allowedHttpMethods = methods; + } + + public Boolean getInternal(){ + return this.internal; + } + + public void setInternal(boolean internal){ + this.internal = internal; + } + + public ApiProxySettings getProxySettings() { + return proxySettings; + } + + public void setProxySettings(ApiProxySettings proxySettings) { + this.proxySettings = proxySettings; + } +} diff --git a/exposure-engine/provisioning/src/main/java/com/alu/e3/prov/restapi/model/ApiContext.java b/exposure-engine/provisioning/src/main/java/com/alu/e3/prov/restapi/model/ApiContext.java new file mode 100644 index 0000000..e257c84 --- /dev/null +++ b/exposure-engine/provisioning/src/main/java/com/alu/e3/prov/restapi/model/ApiContext.java @@ -0,0 +1,315 @@ +/** + * Copyright © 2012 Alcatel-Lucent. + * + * See the NOTICE file distributed with this work for additional + * information regarding copyright ownership. + * Licensed to you 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. + */ +// +// This file was generated by the JavaTM Architecture for XML Binding(JAXB) Reference Implementation, vhudson-jaxb-ri-2.2-27 +// See http://java.sun.com/xml/jaxb +// Any modifications to this file will be lost upon recompilation of the source schema. +// Generated on: 2012.03.19 at 02:26:27 PM CET +// + + +package com.alu.e3.prov.restapi.model; + +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.XmlAttribute; +import javax.xml.bind.annotation.XmlElement; +import javax.xml.bind.annotation.XmlElementWrapper; +import javax.xml.bind.annotation.XmlType; + + +/** + * Defines an environment data model. + * + */ +@XmlAccessorType(XmlAccessType.FIELD) +@XmlType(name = "context", propOrder = { + "status", + "loadBalancing", + "targetHosts", + "maxRateLimitTPSThreshold", + "maxRateLimitTPSWarning", + "maxRateLimitTPMThreshold", + "maxRateLimitTPMWarning" +}) +public class ApiContext { + + /** + * The context id. + */ + @XmlAttribute(required = true) + protected String id; + + /** + * Specifies if this context is the default context. + */ + @XmlAttribute(required = true, name = "default") + protected boolean defaultContext; + + /** + * The environment status: active, inactive, pending + */ + @XmlElement(required = true) + protected Status status; + + /** + * The strategy to load balance on multiple target hosts: unmanaged, heartbeatedAffinity + */ + @XmlElement(required = false) + protected LoadBalancing loadBalancing; + + /** + * The target hosts defined for the environment. + */ + @XmlElementWrapper(name="targetHosts", required = true) + @XmlElement(name="targetHost", required = true) + protected List targetHosts; + + /** + * Max Rate Limit Transaction Per Second (TPS) Threshold + */ + @XmlElement(required = true) + protected int maxRateLimitTPSThreshold; + + /** + * Max Rate Limit Transaction Per Second (TPS) Warning + */ + @XmlElement(required = true) + protected float maxRateLimitTPSWarning; + + /** + * Max Rate Limit Transaction per Minute (TPM) Threshold + */ + @XmlElement(required = true) + protected int maxRateLimitTPMThreshold; + + /** + * Max Rate Limit TPM Warning + */ + @XmlElement(required = true) + protected float maxRateLimitTPMWarning; + + /** + * Gets the value of the id attribute. + * + * @return + * possible object is + * {@link String } + * + */ + public String getId() { + return id; + } + + /** + * Sets the value of the id property. + * + * @param id + * allowed object is + * {@link EnvType } + * + */ + public void setId(String id) { + this.id = id; + } + + /** + * Sets the value of the defaultContext property. + * @param defaultContext the defaultContext to set + */ + public void setDefaultContext(boolean defaultContext) { + this.defaultContext = defaultContext; + } + + /** + * Gets the value of the defaultContext property. + * @return the defaultContext + */ + public boolean isDefaultContext() { + return defaultContext; + } + + /** + * Gets the value of the status property. + * + * @return + * possible object is + * {@link Status } + * + */ + public Status getStatus() { + return status; + } + + /** + * Sets the value of the status property. + * + * @param value + * allowed object is + * {@link Status } + * + */ + public void setStatus(Status value) { + this.status = value; + } + + /** + * Gets the value of the Load Balancing property. + * + * @return + * possible object is + * {@link LoadBalancing } + * + */ + public LoadBalancing getLoadBalancing() { + return loadBalancing; + } + + /** + * Sets the value of the Load Balancing property. + * + * @param value + * allowed object is + * {@link LoadBalancing } + * + */ + public void setLoadBalancing(LoadBalancing value) { + this.loadBalancing = value; + } + + public List getTargetHosts() { + if (targetHosts == null) { + targetHosts = new ArrayList(); + } + return this.targetHosts; + } + + /** + * Sets the value of the targetHosts property. + * + * @param value + * allowed object is + * {@link TargetHosts } + * + */ + public void setTargetHosts(List value) { + this.targetHosts = value; + } + + /** + * Gets the value of the maxRateLimitTPSThreshold property. + * + * @return + * possible object is + * {@link String } + * + */ + public int getMaxRateLimitTPSThreshold() { + return maxRateLimitTPSThreshold; + } + + /** + * Sets the value of the maxRateLimitTPSThreshold property. + * + * @param value + * allowed object is + * {@link String } + * + */ + public void setMaxRateLimitTPSThreshold(int value) { + this.maxRateLimitTPSThreshold = value; + } + + /** + * Gets the value of the maxRateLimitTPSWarning property. + * + * @return + * possible object is + * {@link String } + * + */ + public float getMaxRateLimitTPSWarning() { + return maxRateLimitTPSWarning; + } + + /** + * Sets the value of the maxRateLimitTPSWarning property. + * + * @param value + * allowed object is + * {@link String } + * + */ + public void setMaxRateLimitTPSWarning(float value) { + this.maxRateLimitTPSWarning = value; + } + + /** + * Gets the value of the maxRateLimitTPMThreshold property. + * + * @return + * possible object is + * {@link String } + * + */ + public int getMaxRateLimitTPMThreshold() { + return maxRateLimitTPMThreshold; + } + + /** + * Sets the value of the maxRateLimitTPMThreshold property. + * + * @param value + * allowed object is + * {@link String } + * + */ + public void setMaxRateLimitTPMThreshold(int value) { + this.maxRateLimitTPMThreshold = value; + } + + /** + * Gets the value of the maxRateLimitTPMWarning property. + * + * @return + * possible object is + * {@link String } + * + */ + public float getMaxRateLimitTPMWarning() { + return maxRateLimitTPMWarning; + } + + /** + * Sets the value of the maxRateLimitTPMWarning property. + * + * @param value + * allowed object is + * {@link String } + * + */ + public void setMaxRateLimitTPMWarning(float value) { + this.maxRateLimitTPMWarning = value; + } + + +} diff --git a/exposure-engine/provisioning/src/main/java/com/alu/e3/prov/restapi/model/ApiProxySettings.java b/exposure-engine/provisioning/src/main/java/com/alu/e3/prov/restapi/model/ApiProxySettings.java new file mode 100644 index 0000000..2fb0d62 --- /dev/null +++ b/exposure-engine/provisioning/src/main/java/com/alu/e3/prov/restapi/model/ApiProxySettings.java @@ -0,0 +1,123 @@ +/** + * Copyright © 2012 Alcatel-Lucent. + * + * See the NOTICE file distributed with this work for additional + * information regarding copyright ownership. + * Licensed to you 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. + */ +// +// This file was generated by the JavaTM Architecture for XML Binding(JAXB) Reference Implementation, vhudson-jaxb-ri-2.2-27 +// See http://java.sun.com/xml/jaxb +// Any modifications to this file will be lost upon recompilation of the source schema. +// Generated on: 2012.08.20 at 03:08:31 PM CEST +// + + +package com.alu.e3.prov.restapi.model; + +import javax.xml.bind.annotation.XmlAccessType; +import javax.xml.bind.annotation.XmlAccessorType; +import javax.xml.bind.annotation.XmlType; + + +/** + * The Proxy settings on an API to use when calling the south-bound target hosts by a E3 on-boarded API. + * If local settings are provided they will be used. + * else if global settings are provided, they will be get from E3 system settings. + * Otherwise no Proxy settings will be used. + * + * Note: Only one setting is allowed, global xor local. + * + */ +@XmlAccessorType(XmlAccessType.FIELD) +@XmlType(name = "ApiProxySettingsType", propOrder = { + "globalProxy", + "localProxy" +}) +public class ApiProxySettings { + + protected ApiProxySettings.GlobalProxy globalProxy; + protected ForwardProxy localProxy; + + /** + * Gets the value of the globalProxy property. + * + * @return + * possible object is + * {@link ApiProxySettings.GlobalProxy } + * + */ + public ApiProxySettings.GlobalProxy getGlobalProxy() { + return globalProxy; + } + + /** + * Sets the value of the globalProxy property. + * + * @param value + * allowed object is + * {@link ApiProxySettings.GlobalProxy } + * + */ + public void setGlobalProxy(ApiProxySettings.GlobalProxy value) { + this.globalProxy = value; + } + + /** + * Gets the value of the localProxy property. + * + * @return + * possible object is + * {@link ForwardProxyType } + * + */ + public ForwardProxy getLocalProxy() { + return localProxy; + } + + /** + * Sets the value of the localProxy property. + * + * @param value + * allowed object is + * {@link ForwardProxyType } + * + */ + public void setLocalProxy(ForwardProxy value) { + this.localProxy = value; + } + + /** + *

Java class for anonymous complex type. + * + *

The following schema fragment specifies the expected content contained within this class. + * + *

+     * <complexType>
+     *   <complexContent>
+     *     <restriction base="{http://www.w3.org/2001/XMLSchema}anyType">
+     *     </restriction>
+     *   </complexContent>
+     * </complexType>
+     * 
+ * + * + */ + @XmlAccessorType(XmlAccessType.FIELD) + @XmlType(name = "") + public static class GlobalProxy { + + + } +} diff --git a/exposure-engine/provisioning/src/main/java/com/alu/e3/prov/restapi/model/ApiResponse.java b/exposure-engine/provisioning/src/main/java/com/alu/e3/prov/restapi/model/ApiResponse.java new file mode 100644 index 0000000..950aab3 --- /dev/null +++ b/exposure-engine/provisioning/src/main/java/com/alu/e3/prov/restapi/model/ApiResponse.java @@ -0,0 +1,64 @@ +/** + * Copyright © 2012 Alcatel-Lucent. + * + * See the NOTICE file distributed with this work for additional + * information regarding copyright ownership. + * Licensed to you 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 com.alu.e3.prov.restapi.model; + +import java.util.List; + +import javax.xml.bind.annotation.XmlRootElement; + +/** + * The Api REST service response model + * + */ +@XmlRootElement(name = "response") +public class ApiResponse extends BasicResponse { + protected Api api; + + public ApiResponse() { + super(); + } + + public ApiResponse(String status) { + super(status); + } + + public ApiResponse(String status, Api api) { + this(status); + setApi(api); + } + + public ApiResponse(String status, String apiId) { + this(status); + setId(apiId); + } + + public ApiResponse(String status, List apiIdsList) { + this(status); + setIds(apiIdsList); + } + + public Api getApi() { + return api; + } + + public void setApi(Api api) { + this.api = api; + } + +} diff --git a/exposure-engine/provisioning/src/main/java/com/alu/e3/prov/restapi/model/ApiType.java b/exposure-engine/provisioning/src/main/java/com/alu/e3/prov/restapi/model/ApiType.java new file mode 100644 index 0000000..a9e548f --- /dev/null +++ b/exposure-engine/provisioning/src/main/java/com/alu/e3/prov/restapi/model/ApiType.java @@ -0,0 +1,64 @@ +/** + * Copyright © 2012 Alcatel-Lucent. + * + * See the NOTICE file distributed with this work for additional + * information regarding copyright ownership. + * Licensed to you 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. + */ +// +// This file was generated by the JavaTM Architecture for XML Binding(JAXB) Reference Implementation, vhudson-jaxb-ri-2.2-27 +// See http://java.sun.com/xml/jaxb +// Any modifications to this file will be lost upon recompilation of the source schema. +// Generated on: 2012.03.19 at 05:41:58 PM CET +// + + +package com.alu.e3.prov.restapi.model; + +import javax.xml.bind.annotation.XmlEnum; +import javax.xml.bind.annotation.XmlEnumValue; +import javax.xml.bind.annotation.XmlType; + + +/** + * The API type, it can either be PassThrough or Composite + */ +@XmlType(name = "apiType") +@XmlEnum +public enum ApiType { + + @XmlEnumValue("PassThrough") + PASS_THROUGH("PassThrough"), + @XmlEnumValue("Composite") + COMPOSITE("Composite"); + private final String value; + + ApiType(String v) { + value = v; + } + + public String value() { + return value; + } + + public static ApiType fromValue(String v) { + for (ApiType c: ApiType.values()) { + if (c.value.equals(v)) { + return c; + } + } + throw new IllegalArgumentException(v); + } + +} diff --git a/exposure-engine/provisioning/src/main/java/com/alu/e3/prov/restapi/model/Auth.java b/exposure-engine/provisioning/src/main/java/com/alu/e3/prov/restapi/model/Auth.java new file mode 100644 index 0000000..1826c9a --- /dev/null +++ b/exposure-engine/provisioning/src/main/java/com/alu/e3/prov/restapi/model/Auth.java @@ -0,0 +1,429 @@ +/** + * Copyright © 2012 Alcatel-Lucent. + * + * See the NOTICE file distributed with this work for additional + * information regarding copyright ownership. + * Licensed to you 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 com.alu.e3.prov.restapi.model; + +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.XmlAttribute; +import javax.xml.bind.annotation.XmlElement; +import javax.xml.bind.annotation.XmlElementWrapper; +import javax.xml.bind.annotation.XmlID; +import javax.xml.bind.annotation.XmlRootElement; +import javax.xml.bind.annotation.XmlSchemaType; +import javax.xml.bind.annotation.XmlType; +import javax.xml.bind.annotation.adapters.CollapsedStringAdapter; +import javax.xml.bind.annotation.adapters.XmlJavaTypeAdapter; + + +/** + * The Auth detail used for NB authentication in E3 subsystem. + *

Supported types are: Basic, AuthKey, IP White List + * + */ +@XmlRootElement +@XmlAccessorType(XmlAccessType.FIELD) +@XmlType(name = "auth", propOrder = { + "id", + "status", + "type", + "policyContext", + "apiContext", + "basicAuth", + "oAuth", + "authKeyAuth", + "ipWhiteListAuth", + "wsseAuth", + "tdr", + "properties", + "headerTransformations" +}) +public class Auth { + + /** + * The auth ID. Could be provided. + */ + @XmlJavaTypeAdapter(CollapsedStringAdapter.class) + @XmlID + @XmlSchemaType(name = "ID") + protected String id; + /** + * The auth status: active, inactive, pending + */ + @XmlElement(required = true) + protected Status status; + + /** + * The auth type: basic, authKey, IP white list + */ + @XmlElement(required = true) + protected AuthType type; + + /** + * The policy context for which this Auth is applicable. + */ + @XmlElement(required = true) + protected IdAttribute policyContext; + + /** + * The api context for which this Auth is applicable. + */ + @XmlElement(required = true) + protected IdAttribute apiContext; + + /** + * The Basic Auth details if basic is selected as a type. + */ + @XmlElement(required = true) + protected BasicAuth basicAuth; + + /** + * The OAuth details if oauth is selected as a type. + */ + @XmlElement(required = true) + protected OAuth oAuth; + + /** + * The authKey details if authKey selected as a type + */ + @XmlElement(required = true) + protected AuthKeyAuth authKeyAuth; + + /** + * The IP white list if this auth is selected as a type. + */ + @XmlElement(required = true) + protected IpWhiteListAuth ipWhiteListAuth; + + /** + * The IP white list if this auth is selected as a type. + */ + @XmlElement(required = true) + protected WSSEAuth wsseAuth; + + /** + * TDR data that will be appended at TDR generation time. + */ + protected TdrData tdr; + + /** + * properties data that will be used by header transforms and/or tdr outputs. + */ + @XmlElementWrapper(name="properties") + @XmlElement(name="property") + protected List properties; + + /** + * The header transformations for the API. + */ + @XmlElementWrapper(name="headerTransformations", required = false) + @XmlElement(name="headerTransformation", required = false) + protected List headerTransformations; + + /** + * Gets the value of the id property. + * + * @return + * possible object is + * {@link String } + * + */ + public String getId() { + return id; + } + + /** + * Sets the value of the id property. + * + * @param value + * allowed object is + * {@link String } + * + */ + public void setId(String value) { + this.id = value; + } + + /** + * Gets the value of the status property. + * + * @return + * possible object is + * {@link Object } + * + */ + public Status getStatus() { + return status; + } + + /** + * Sets the value of the status property. + * + * @param value + * allowed object is + * {@link Object } + * + */ + public void setStatus(Status value) { + this.status = value; + } + + /** + * Gets the value of the type property. + * + * @return + * possible object is + * {@link AuthType } + * + */ + public AuthType getType() { + return type; + } + + /** + * Sets the value of the type property. + * + * @param value + * allowed object is + * {@link AuthType } + * + */ + public void setType(AuthType value) { + this.type = value; + } + + /** + * Gets the value of the apiContext property. + * + * @return + * possible object is + * {@link String } + * + */ + public String getApiContext() { + if (apiContext == null) + return ""; + return apiContext.getId(); + } + + /** + * Sets the value of the apiContext property. + * + * @param value + * allowed object is + * {@link String } + * + */ + public void setApiContext(String value) { + if (apiContext == null) + apiContext = new IdAttribute(); + apiContext.setId(value); + } + + /** + * Gets the value of the policyContext property. + * + * @return + * possible object is + * {@link String } + * + */ + public String getPolicyContext() { + if (policyContext == null) + return ""; + return policyContext.getId(); + } + + /** + * Sets the value of the policyContext property. + * + * @param value + * allowed object is + * {@link String } + * + */ + public void setPolicyContext(String value) { + if (policyContext == null) + policyContext = new IdAttribute(); + policyContext.setId(value); + } + + /** + * Gets the value of the basicAuth property. + * + * @return + * possible object is + * {@link BasicAuth } + * + */ + public BasicAuth getBasicAuth() { + return basicAuth; + } + + /** + * Sets the value of the basicAuth property. + * + * @param value + * allowed object is + * {@link BasicAuth } + * + */ + public void setBasicAuth(BasicAuth value) { + this.basicAuth = value; + } + + /** + * Gets the value of the oAuth property. + * + * @return + * possible object is + * {@link OAuth } + * + */ + public OAuth getOAuth() { + return oAuth; + } + + /** + * Sets the value of the oAuth property. + * + * @param value + * allowed object is + * {@link OAuth } + * + */ + public void setOAuth(OAuth value) { + this.oAuth = value; + } + + /** + * Gets the value of the authKeyAuth property. + * + * @return + * possible object is + * {@link AuthKeyAuth } + * + */ + public AuthKeyAuth getAuthKeyAuth() { + return authKeyAuth; + } + + /** + * Sets the value of the authKeyAuth property. + * + * @param value + * allowed object is + * {@link AuthKeyAuth } + * + */ + public void setAuthKeyAuth(AuthKeyAuth value) { + this.authKeyAuth = value; + } + + /** + * Gets the value of the ipWhiteListAuth property. + * + * @return + * possible object is + * {@link IpWhiteListAuth } + * + */ + public IpWhiteListAuth getIpWhiteListAuth() { + return ipWhiteListAuth; + } + + /** + * Sets the value of the ipWhiteListAuth property. + * + * @param value + * allowed object is + * {@link IpWhiteListAuth } + * + */ + public void setIpWhiteListAuth(IpWhiteListAuth value) { + this.ipWhiteListAuth = value; + } + + /** + * Gets tdr property. + * @return + */ + public TdrData getTdr() { + return tdr; + } + + /** + * Sets the value of the tdr property. + * @param tdr + */ + public void setTdr(TdrData tdr) { + this.tdr = tdr; + } + + @XmlAccessorType(XmlAccessType.FIELD) + @XmlType(name = "idAttribute", propOrder = { + "id" + }) + public static class IdAttribute + { + @XmlAttribute(name="id", required = true) + protected String id; + + public void setId(String id) { + this.id = id; + } + + public String getId() { + return id; + } + } + + + public List getProperties(){ + if(this.properties == null) + this.properties = new ArrayList(); + return this.properties; + } + + public void setProperties(List value){ + this.properties = value; + } + + public List getHeaderTransformations(){ + if(this.headerTransformations == null) + this.headerTransformations = new ArrayList(); + return this.headerTransformations; + } + + public void setHeaderTransformations(List value){ + this.headerTransformations = value; + } + + public WSSEAuth getWsseAuth() { + return wsseAuth; + } + + public void setWsseAuth(WSSEAuth wsseAuth) { + this.wsseAuth = wsseAuth; + } + + +} diff --git a/exposure-engine/provisioning/src/main/java/com/alu/e3/prov/restapi/model/AuthIdsNoIdType.java b/exposure-engine/provisioning/src/main/java/com/alu/e3/prov/restapi/model/AuthIdsNoIdType.java new file mode 100644 index 0000000..d7a6bd5 --- /dev/null +++ b/exposure-engine/provisioning/src/main/java/com/alu/e3/prov/restapi/model/AuthIdsNoIdType.java @@ -0,0 +1,110 @@ +/** + * Copyright © 2012 Alcatel-Lucent. + * + * See the NOTICE file distributed with this work for additional + * information regarding copyright ownership. + * Licensed to you 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 com.alu.e3.prov.restapi.model; + +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.XmlAttribute; +import javax.xml.bind.annotation.XmlElement; +import javax.xml.bind.annotation.XmlRootElement; +import javax.xml.bind.annotation.XmlType; + +/** + * Defines a bucket of authIds. + */ +@XmlRootElement(name = "quotaRLBucket") +@XmlAccessorType(XmlAccessType.FIELD) +@XmlType(name = "AuthIdsNoIdType", propOrder = { + "authIds" +}) +public class AuthIdsNoIdType { + + @XmlElement(name = "authId", required = true) + protected List authIds; + @XmlAttribute(name = "id") + protected String id; + + /** + * Gets the value of the authId property. + * + *

+ * This accessor method returns a reference to the live list, + * not a snapshot. Therefore any modification you make to the + * returned list will be present inside the JAXB object. + * This is why there is not a set method for the authId property. + * + *

+ * For example, to add a new item, do as follows: + *

+     *    getAuthId().add(newItem);
+     * 
+ * + * + *

+ * Objects of the following type(s) are allowed in the list + * {@link String } + * + * + */ + public List getAuthIds() { + if (authIds == null) { + authIds = new ArrayList(); + } + return this.authIds; + } + + /** + * Gets the value of the id attribute. + * + * @return + * possible object is + * {@link String } + * + */ + public String getId() { + return id; + } + + /** + * Sets the value of the id attribute. + * + * @param value + * allowed object is + * {@link String } + * + */ + public void setId(String value) { + this.id = value; + } + + @Override + public String toString() { + StringBuilder builder = new StringBuilder(); + builder.append("AuthIdsNoIdType [authIds="); + builder.append(authIds); + builder.append(", id="); + builder.append(id); + builder.append("]"); + return builder.toString(); + } + +} diff --git a/exposure-engine/provisioning/src/main/java/com/alu/e3/prov/restapi/model/AuthIdsType.java b/exposure-engine/provisioning/src/main/java/com/alu/e3/prov/restapi/model/AuthIdsType.java new file mode 100644 index 0000000..eec03be --- /dev/null +++ b/exposure-engine/provisioning/src/main/java/com/alu/e3/prov/restapi/model/AuthIdsType.java @@ -0,0 +1,113 @@ +/** + * Copyright © 2012 Alcatel-Lucent. + * + * See the NOTICE file distributed with this work for additional + * information regarding copyright ownership. + * Licensed to you 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 com.alu.e3.prov.restapi.model; + +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.XmlAttribute; +import javax.xml.bind.annotation.XmlElement; +import javax.xml.bind.annotation.XmlRootElement; +import javax.xml.bind.annotation.XmlType; + +/** + * Defines a bucket of authIds. + */ +@XmlRootElement(name = "quotaRLBucket") +@XmlAccessorType(XmlAccessType.FIELD) +@XmlType(name = "AuthIdsNoIdType", propOrder = { + "authIds" +}) +public class AuthIdsType { + + @XmlElement(name = "authId", required = true) + protected List authIds; + @XmlAttribute(name = "id", required = true) + protected String id; + + public String toString() { + String v = "authIds = " + authIds; //["; +// +// if(authIds != null) +// { +// for (String id : authIds) { +// v += id + ", "; +// } +// } +// v += "]"; +// + return v; + } + + /** + * Gets the value of the authIds property. + * + *

+ * This accessor method returns a reference to the live list, + * not a snapshot. Therefore any modification you make to the + * returned list will be present inside the JAXB object. + * This is why there is not a set method for the authIds property. + * + *

+ * For example, to add a new item, do as follows: + *

+     *    getAuthIds().add(newItem);
+     * 
+ * + * + *

+ * Objects of the following type(s) are allowed in the list + * {@link String } + * + * + */ + public List getAuthIds() { + if (authIds == null) { + authIds = new ArrayList(); + } + return this.authIds; + } + + /** + * Gets the value of the id attribute. + * + * @return + * possible object is + * {@link String } + * + */ + public String getId() { + return this.id; + } + + /** + * Sets the value of the id attribute. + * + * @param value + * allowed object is + * {@link String } + * + */ + public void setId(String value) { + this.id = value; + } + +} diff --git a/exposure-engine/provisioning/src/main/java/com/alu/e3/prov/restapi/model/AuthKeyAuth.java b/exposure-engine/provisioning/src/main/java/com/alu/e3/prov/restapi/model/AuthKeyAuth.java new file mode 100644 index 0000000..85840a4 --- /dev/null +++ b/exposure-engine/provisioning/src/main/java/com/alu/e3/prov/restapi/model/AuthKeyAuth.java @@ -0,0 +1,73 @@ +/** + * Copyright © 2012 Alcatel-Lucent. + * + * See the NOTICE file distributed with this work for additional + * information regarding copyright ownership. + * Licensed to you 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. + */ +// +// This file was generated by the JavaTM Architecture for XML Binding(JAXB) Reference Implementation, vhudson-jaxb-ri-2.2-27 +// See http://java.sun.com/xml/jaxb +// Any modifications to this file will be lost upon recompilation of the source schema. +// Generated on: 2012.03.19 at 02:26:36 PM CET +// + + +package com.alu.e3.prov.restapi.model; + +import javax.xml.bind.annotation.XmlAccessType; +import javax.xml.bind.annotation.XmlAccessorType; +import javax.xml.bind.annotation.XmlElement; +import javax.xml.bind.annotation.XmlType; + + +/** + * a AuthKey model to provision the AuthKey value on E3. + * + */ +@XmlAccessorType(XmlAccessType.FIELD) +@XmlType(name = "authKeyAuth", propOrder = { + "keyValue" +}) +public class AuthKeyAuth { + + @XmlElement(required = true) + protected String keyValue; + + + /** + * Gets the value of the keyValue property. + * + * @return + * possible object is + * {@link String } + * + */ + public String getKeyValue() { + return keyValue; + } + + /** + * Sets the value of the keyValue property. + * + * @param value + * allowed object is + * {@link String } + * + */ + public void setKeyValue(String value) { + this.keyValue = value; + } + +} diff --git a/exposure-engine/provisioning/src/main/java/com/alu/e3/prov/restapi/model/AuthRef.java b/exposure-engine/provisioning/src/main/java/com/alu/e3/prov/restapi/model/AuthRef.java new file mode 100644 index 0000000..392a00e --- /dev/null +++ b/exposure-engine/provisioning/src/main/java/com/alu/e3/prov/restapi/model/AuthRef.java @@ -0,0 +1,61 @@ +/** + * Copyright © 2012 Alcatel-Lucent. + * + * See the NOTICE file distributed with this work for additional + * information regarding copyright ownership. + * Licensed to you 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 com.alu.e3.prov.restapi.model; + +import javax.xml.bind.annotation.XmlAccessType; +import javax.xml.bind.annotation.XmlAccessorType; +import javax.xml.bind.annotation.XmlRootElement; +import javax.xml.bind.annotation.XmlType; + +/** + * Defines a reference to an Auth object. + * + */ +@XmlRootElement(name = "auth") +@XmlAccessorType(XmlAccessType.FIELD) +@XmlType(name = "AuthData", propOrder = { + "id" + }) +public class AuthRef { + protected String id; + + /** + * Gets the value of the id property. + * + * @return + * possible object is + * {@link String } + * + */ + public String getId() { + return id; + } + + /** + * Sets the value of the id property. + * + * @param value + * allowed object is + * {@link String } + * + */ + public void setId(String value) { + this.id = value; + } +} diff --git a/exposure-engine/provisioning/src/main/java/com/alu/e3/prov/restapi/model/AuthResponse.java b/exposure-engine/provisioning/src/main/java/com/alu/e3/prov/restapi/model/AuthResponse.java new file mode 100644 index 0000000..d0c3669 --- /dev/null +++ b/exposure-engine/provisioning/src/main/java/com/alu/e3/prov/restapi/model/AuthResponse.java @@ -0,0 +1,47 @@ +/** + * Copyright © 2012 Alcatel-Lucent. + * + * See the NOTICE file distributed with this work for additional + * information regarding copyright ownership. + * Licensed to you 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 com.alu.e3.prov.restapi.model; + +import javax.xml.bind.annotation.XmlRootElement; + +/** + * Auth REST service response model. + * + */ +@XmlRootElement(name = "response") +public class AuthResponse extends BasicResponse { + + protected Auth auth; + + public AuthResponse() { + super(); + } + + public AuthResponse(String status) { + super(status); + } + + public Auth getAuth() { + return auth; + } + + public void setAuth(Auth auth) { + this.auth = auth; + } +} diff --git a/exposure-engine/provisioning/src/main/java/com/alu/e3/prov/restapi/model/AuthType.java b/exposure-engine/provisioning/src/main/java/com/alu/e3/prov/restapi/model/AuthType.java new file mode 100644 index 0000000..cf3b7e7 --- /dev/null +++ b/exposure-engine/provisioning/src/main/java/com/alu/e3/prov/restapi/model/AuthType.java @@ -0,0 +1,73 @@ +/** + * Copyright © 2012 Alcatel-Lucent. + * + * See the NOTICE file distributed with this work for additional + * information regarding copyright ownership. + * Licensed to you 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. + */ +// +// This file was generated by the JavaTM Architecture for XML Binding(JAXB) Reference Implementation, vhudson-jaxb-ri-2.2-27 +// See http://java.sun.com/xml/jaxb +// Any modifications to this file will be lost upon recompilation of the source schema. +// Generated on: 2012.03.19 at 02:26:36 PM CET +// + + +package com.alu.e3.prov.restapi.model; + +import javax.xml.bind.annotation.XmlEnum; +import javax.xml.bind.annotation.XmlEnumValue; +import javax.xml.bind.annotation.XmlType; + + +/** + * Enum for supported North Bound authentication types : basic, authKey, IP White List + */ +@XmlType(name = "authType") +@XmlEnum +public enum AuthType { + + @XmlEnumValue("basic") + BASIC("basic"), + @XmlEnumValue("authKey") + AUTHKEY("authKey"), + @XmlEnumValue("ipWhiteList") + IP_WHITE_LIST("ipWhiteList"), + @XmlEnumValue("noAuth") + NO_AUTH("noAuth"), + @XmlEnumValue("oAuth") + OAUTH("oAuth"), + @XmlEnumValue("wsse") + WSSE("wsse"); + + private final String value; + + AuthType(String v) { + value = v; + } + + public String value() { + return value; + } + + public static AuthType fromValue(String v) { + for (AuthType c: AuthType.values()) { + if (c.value.equals(v)) { + return c; + } + } + throw new IllegalArgumentException(v); + } + +} diff --git a/exposure-engine/provisioning/src/main/java/com/alu/e3/prov/restapi/model/Authentication.java b/exposure-engine/provisioning/src/main/java/com/alu/e3/prov/restapi/model/Authentication.java new file mode 100644 index 0000000..59200ae --- /dev/null +++ b/exposure-engine/provisioning/src/main/java/com/alu/e3/prov/restapi/model/Authentication.java @@ -0,0 +1,98 @@ +/** + * Copyright © 2012 Alcatel-Lucent. + * + * See the NOTICE file distributed with this work for additional + * information regarding copyright ownership. + * Licensed to you 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. + */ +// +// This file was generated by the JavaTM Architecture for XML Binding(JAXB) Reference Implementation, vhudson-jaxb-ri-2.2-27 +// See http://java.sun.com/xml/jaxb +// Any modifications to this file will be lost upon recompilation of the source schema. +// Generated on: 2012.03.19 at 02:26:27 PM CET +// + + +package com.alu.e3.prov.restapi.model; + +import javax.xml.bind.annotation.XmlAccessType; +import javax.xml.bind.annotation.XmlAccessorType; +import javax.xml.bind.annotation.XmlElement; +import javax.xml.bind.annotation.XmlType; + + +/** + * The authentication data on targets + */ +@XmlAccessorType(XmlAccessType.FIELD) +@XmlType(name = "authentication", propOrder = { + "type", + "data" +}) +public class Authentication { + + @XmlElement(required = true) + protected String type; + @XmlElement(required = true) + protected Data data; + + /** + * Gets the value of the type property. + * + * @return + * possible object is + * {@link String } + * + */ + public String getType() { + return type; + } + + /** + * Sets the value of the type property. + * + * @param value + * allowed object is + * {@link String } + * + */ + public void setType(String value) { + this.type = value; + } + + /** + * Gets the value of the data property. + * + * @return + * possible object is + * {@link Data } + * + */ + public Data getData() { + return data; + } + + /** + * Sets the value of the data property. + * + * @param value + * allowed object is + * {@link Data } + * + */ + public void setData(Data value) { + this.data = value; + } + +} diff --git a/exposure-engine/provisioning/src/main/java/com/alu/e3/prov/restapi/model/Authkey.java b/exposure-engine/provisioning/src/main/java/com/alu/e3/prov/restapi/model/Authkey.java new file mode 100644 index 0000000..5ad197d --- /dev/null +++ b/exposure-engine/provisioning/src/main/java/com/alu/e3/prov/restapi/model/Authkey.java @@ -0,0 +1,98 @@ +/** + * Copyright © 2012 Alcatel-Lucent. + * + * See the NOTICE file distributed with this work for additional + * information regarding copyright ownership. + * Licensed to you 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. + */ +// +// This file was generated by the JavaTM Architecture for XML Binding(JAXB) Reference Implementation, vhudson-jaxb-ri-2.2-27 +// See http://java.sun.com/xml/jaxb +// Any modifications to this file will be lost upon recompilation of the source schema. +// Generated on: 2012.03.19 at 02:26:27 PM CET +// + + +package com.alu.e3.prov.restapi.model; + +import javax.xml.bind.annotation.XmlAccessType; +import javax.xml.bind.annotation.XmlAccessorType; +import javax.xml.bind.annotation.XmlElement; +import javax.xml.bind.annotation.XmlType; + + +/** + * The model to provision the Auth key name related to an API. + */ +@XmlAccessorType(XmlAccessType.FIELD) +@XmlType(name = "authkey", propOrder = { + "keyName", + "headerName" +}) +public class Authkey { + + @XmlElement(required = true) + protected String keyName; + + @XmlElement(required = false) + protected String headerName; + + /** + * Gets the value of the authkeyname property. + * + * @return + * possible object is + * {@link String } + * + */ + public String getKeyName() { + return keyName; + } + + /** + * Sets the value of the authkeyname property. + * + * @param value + * allowed object is + * {@link String } + * + */ + public void setKeyName(String value) { + this.keyName = value; + } + + /** + * Gets the value of the headerName property. + * + * @return + * possible object is + * {@link String } + * + */ + public String getHeaderName() { + return headerName; + } + + /** + * Sets the value of the headerName property. + * + * @param value + * allowed object is + * {@link String } + * + */ + public void setHeaderName(String value) { + this.headerName = value; + } +} diff --git a/exposure-engine/provisioning/src/main/java/com/alu/e3/prov/restapi/model/BasicAuth.java b/exposure-engine/provisioning/src/main/java/com/alu/e3/prov/restapi/model/BasicAuth.java new file mode 100644 index 0000000..94e4588 --- /dev/null +++ b/exposure-engine/provisioning/src/main/java/com/alu/e3/prov/restapi/model/BasicAuth.java @@ -0,0 +1,97 @@ +/** + * Copyright © 2012 Alcatel-Lucent. + * + * See the NOTICE file distributed with this work for additional + * information regarding copyright ownership. + * Licensed to you 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. + */ +// +// This file was generated by the JavaTM Architecture for XML Binding(JAXB) Reference Implementation, vhudson-jaxb-ri-2.2-27 +// See http://java.sun.com/xml/jaxb +// Any modifications to this file will be lost upon recompilation of the source schema. +// Generated on: 2012.03.19 at 02:26:36 PM CET +// + + +package com.alu.e3.prov.restapi.model; + +import javax.xml.bind.annotation.XmlAccessType; +import javax.xml.bind.annotation.XmlAccessorType; +import javax.xml.bind.annotation.XmlElement; +import javax.xml.bind.annotation.XmlType; + + +/** + * The Basic Auth data model. + * + */ +@XmlAccessorType(XmlAccessType.FIELD) +@XmlType(name = "basicAuth", propOrder = { + "username", + "password" +}) +public class BasicAuth { + + @XmlElement(required = true) + protected String username; + @XmlElement(required = true) + protected byte[] password; + + /** + * Gets the value of the username property. + * + * @return + * possible object is + * {@link String } + * + */ + public String getUsername() { + return username; + } + + /** + * Sets the value of the username property. + * + * @param value + * allowed object is + * {@link String } + * + */ + public void setUsername(String value) { + this.username = value; + } + + /** + * Gets the value of the password property. + * + * @return + * possible object is + * byte[] + */ + public byte[] getPassword() { + return password; + } + + /** + * Sets the value of the password property. + * + * @param value + * allowed object is + * byte[] + */ + public void setPassword(byte[] value) { + this.password = value; + } + +} diff --git a/exposure-engine/provisioning/src/main/java/com/alu/e3/prov/restapi/model/BasicResponse.java b/exposure-engine/provisioning/src/main/java/com/alu/e3/prov/restapi/model/BasicResponse.java new file mode 100644 index 0000000..e9d3f03 --- /dev/null +++ b/exposure-engine/provisioning/src/main/java/com/alu/e3/prov/restapi/model/BasicResponse.java @@ -0,0 +1,152 @@ +/** + * Copyright © 2012 Alcatel-Lucent. + * + * See the NOTICE file distributed with this work for additional + * information regarding copyright ownership. + * Licensed to you 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. + */ +// +// This file was generated by the JavaTM Architecture for XML Binding(JAXB) Reference Implementation, vhudson-jaxb-ri-2.2-27 +// See http://java.sun.com/xml/jaxb +// Any modifications to this file will be lost upon recompilation of the source schema. +// Generated on: 2012.03.20 at 02:23:24 PM CET +// + +package com.alu.e3.prov.restapi.model; + +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.XmlElementWrapper; +import javax.xml.bind.annotation.XmlRootElement; +import javax.xml.bind.annotation.XmlType; + +/** + * Basic class for the REST services response. + * + */ +@XmlRootElement(name="response") +@XmlAccessorType(XmlAccessType.FIELD) +@XmlType(name = "basicResponse", propOrder = { "id", "ids", "error", "status" }) +public class BasicResponse { + + public final static String SUCCESS = "SUCCESS"; + public final static String FAILURE = "FAILURE"; + + protected String id; + @XmlElementWrapper(name = "ids") + @XmlElement(name = "id") + protected List ids; + protected Error error; + protected String status; + + public BasicResponse() { + + } + + public BasicResponse(String status) { + setStatus(status); + } + + public BasicResponse(String status, String id) { + setStatus(status); + setId(id); + } + + /** + * Gets the value of the id property. + * + * @return possible object is {@link String } + * + */ + public String getId() { + return id; + } + + /** + * Sets the value of the id property. + * + * @param value + * allowed object is {@link String } + * + */ + public void setId(String value) { + this.id = value; + } + + /** + * + * @return + */ + public List getIds() { + if (ids == null) { + ids = new ArrayList(); + } + return this.ids; + } + + /** + * + * @return + */ + public void setIds(List ids) { + this.ids = ids; + } + + /** + * Gets the value of the error property. + * + * @return possible object is {@link Error } + * + */ + public Error getError() { + return error; + } + + /** + * Sets the value of the error property. + * + * @param value + * allowed object is {@link Error } + * + */ + public void setError(Error value) { + this.error = value; + } + + /** + * Gets the value of the status property. + * + * @return possible object is {@link String } + * + */ + public String getStatus() { + return status; + } + + /** + * Sets the value of the status property. + * + * @param value + * allowed object is {@link String } + * + */ + public void setStatus(String value) { + this.status = value; + } + +} diff --git a/exposure-engine/provisioning/src/main/java/com/alu/e3/prov/restapi/model/BulkPolicyQuotaRLBucketType.java b/exposure-engine/provisioning/src/main/java/com/alu/e3/prov/restapi/model/BulkPolicyQuotaRLBucketType.java new file mode 100644 index 0000000..a5381d3 --- /dev/null +++ b/exposure-engine/provisioning/src/main/java/com/alu/e3/prov/restapi/model/BulkPolicyQuotaRLBucketType.java @@ -0,0 +1,101 @@ +/** + * Copyright © 2012 Alcatel-Lucent. + * + * See the NOTICE file distributed with this work for additional + * information regarding copyright ownership. + * Licensed to you 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. + */ +// +// This file was generated by the JavaTM Architecture for XML Binding(JAXB) Reference Implementation, vhudson-jaxb-ri-2.2-27 +// See http://java.sun.com/xml/jaxb +// Any modifications to this file will be lost upon recompilation of the source schema. +// Generated on: 2012.03.30 at 11:23:09 AM CEST +// + + +package com.alu.e3.prov.restapi.model; + +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.XmlType; + +import com.alu.e3.prov.restapi.model.AuthIdsNoIdType; + + +/** + * A bulk structure to associate a bucket of auths to several policies + */ +@XmlRootElement(name="bulk") +@XmlAccessorType(XmlAccessType.FIELD) +@XmlType(name = "bulkQuotaRLBucketType", propOrder = { + +}) +public class BulkPolicyQuotaRLBucketType { + + @XmlElement(required = true) + protected PolicyIdsType policies; + @XmlElement + protected AuthIdsNoIdType quotaRLBucket; + + /** + * Gets the value of the policies property. + * + * @return + * possible object is + * {@link PolicyIdsType } + * + */ + public PolicyIdsType getPolicies() { + return policies; + } + + /** + * Sets the value of the policies property. + * + * @param value + * allowed object is + * {@link PolicyIdsType } + * + */ + public void setPolicies(PolicyIdsType value) { + this.policies = value; + } + + /** + * Gets the value of the quotaRLBucket property. + * + * @return + * possible object is + * {@link AuthIdsNoIdType } + * + */ + public AuthIdsNoIdType getQuotaRLBucket() { + return quotaRLBucket; + } + + /** + * Sets the value of the quotaRLBucket property. + * + * @param value + * allowed object is + * {@link AuthIdsNoIdType } + * + */ + public void setQuotaRLBucket(AuthIdsNoIdType value) { + this.quotaRLBucket = value; + } + +} diff --git a/exposure-engine/provisioning/src/main/java/com/alu/e3/prov/restapi/model/ConnectionParameters.java b/exposure-engine/provisioning/src/main/java/com/alu/e3/prov/restapi/model/ConnectionParameters.java new file mode 100644 index 0000000..2b537e9 --- /dev/null +++ b/exposure-engine/provisioning/src/main/java/com/alu/e3/prov/restapi/model/ConnectionParameters.java @@ -0,0 +1,107 @@ +/** + * Copyright © 2012 Alcatel-Lucent. + * + * See the NOTICE file distributed with this work for additional + * information regarding copyright ownership. + * Licensed to you 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 com.alu.e3.prov.restapi.model; + +import javax.xml.bind.annotation.XmlAccessType; +import javax.xml.bind.annotation.XmlAccessorType; +import javax.xml.bind.annotation.XmlElement; +import javax.xml.bind.annotation.XmlType; + + +/** + * The connection parameters for API target hosts. + * + */ +@XmlAccessorType(XmlAccessType.FIELD) +@XmlType(name = "connectionParameters", propOrder = { + "maxConnections", + "connectionTimeout", + "socketTimeout" +}) +public class ConnectionParameters { + + /** + * The maximum number of connections for this target host. + */ + @XmlElement(required = false) + protected Integer maxConnections = null; + + + /** + * The connection timeout for this target host. + */ + @XmlElement(required = false) + protected Integer connectionTimeout = null; + + + /** + * The socket timeout for this target host. + */ + @XmlElement(required = false) + protected Integer socketTimeout = null; + + /** + * Get the maximum number of connections for this target host. + * @return the maximum number of connections + */ + public Integer getMaxConnections() { + return maxConnections; + } + + /** + * Set the maximum number of connections for this target host. + * @param maxConnections the maximum number of connections to set + */ + public void setMaxConnections(Integer maxConnections) { + this.maxConnections = maxConnections; + } + + /** + * Get the connection timeout for this target host. + * @return the connection Timeout + */ + public Integer getConnectionTimeout() { + return connectionTimeout; + } + + /** + * Set the connection timeout for this target host. + * @param connectionTimeout the connection Timeout to set + */ + public void setConnectionTimeout(Integer connectionTimeout) { + this.connectionTimeout = connectionTimeout; + } + + /** + * Get the socket timeout for this target host. + * @return the socket Timeout + */ + public Integer getSocketTimeout() { + return socketTimeout; + } + + /** + * Set the socket timeout for this target host. + * @param socketTimeout the socket Timeout to set + */ + public void setSocketTimeout(Integer socketTimeout) { + this.socketTimeout = socketTimeout; + } + +} diff --git a/exposure-engine/provisioning/src/main/java/com/alu/e3/prov/restapi/model/Context.java b/exposure-engine/provisioning/src/main/java/com/alu/e3/prov/restapi/model/Context.java new file mode 100644 index 0000000..0cbb2ea --- /dev/null +++ b/exposure-engine/provisioning/src/main/java/com/alu/e3/prov/restapi/model/Context.java @@ -0,0 +1,232 @@ +/** + * Copyright © 2012 Alcatel-Lucent. + * + * See the NOTICE file distributed with this work for additional + * information regarding copyright ownership. + * Licensed to you 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 com.alu.e3.prov.restapi.model; + +import javax.xml.bind.annotation.XmlAccessType; +import javax.xml.bind.annotation.XmlAccessorType; +import javax.xml.bind.annotation.XmlAttribute; +import javax.xml.bind.annotation.XmlElement; +import javax.xml.bind.annotation.XmlType; + + +/** + * Defines an environment. + */ +@XmlAccessorType(XmlAccessType.FIELD) +@XmlType(name = "ContextType", propOrder = { + "status", + "quotaPerDay", + "quotaPerWeek", + "quotaPerMonth", + "rateLimitPerSecond", + "rateLimitPerMinute" +}) +public class Context { + + @XmlAttribute(required = true) + protected String id; + @XmlElement(required = true) + protected Status status; + protected Counter quotaPerDay; + protected Counter quotaPerWeek; + protected Counter quotaPerMonth; + protected Counter rateLimitPerSecond; + protected Counter rateLimitPerMinute; + + public String toString() { + String v = "id = " + id; + v += ", status = " + status; + v += ", quotaPerDay = [" + quotaPerDay + "]"; + v += ", quotaPerWeek = [" + quotaPerWeek + "]"; + v += ", quotaPerMonth = [" + quotaPerMonth + "]"; + v += ", rateLimitPerSecond = [" + rateLimitPerSecond + "]"; + v += ", rateLimitPerMinute = [" + rateLimitPerMinute + "]"; + + return v; + } + + /** + * Gets the value of the id attribute. + * + * @return + * possible object is + * {@link String } + * + */ + public String getId() { + return id; + } + + /** + * Sets the value of the id attribute. + * + * @param value + * allowed object is + * {@link String } + * + */ + public void setId(String value) { + this.id = value; + } + + /** + * Gets the value of the status property. + * + * @return + * possible object is + * {@link Status } + * + */ + public Status getStatus() { + return status; + } + + /** + * Sets the value of the status property. + * + * @param value + * allowed object is + * {@link Status } + * + */ + public void setStatus(Status value) { + this.status = value; + } + + /** + * Gets the value of the quotaPerDay property. + * + * @return + * possible object is + * {@link Counter } + * + */ + public Counter getQuotaPerDay() { + return quotaPerDay; + } + + /** + * Sets the value of the quotaPerDay property. + * + * @param value + * allowed object is + * {@link Counter } + * + */ + public void setQuotaPerDay(Counter value) { + this.quotaPerDay = value; + } + + /** + * Gets the value of the quotaPerWeek property. + * + * @return + * possible object is + * {@link Counter } + * + */ + public Counter getQuotaPerWeek() { + return quotaPerWeek; + } + + /** + * Sets the value of the quotaPerWeek property. + * + * @param value + * allowed object is + * {@link Counter } + * + */ + public void setQuotaPerWeek(Counter value) { + this.quotaPerWeek = value; + } + + /** + * Gets the value of the quotaPerMonth property. + * + * @return + * possible object is + * {@link Counter } + * + */ + public Counter getQuotaPerMonth() { + return quotaPerMonth; + } + + /** + * Sets the value of the quotaPerMonth property. + * + * @param value + * allowed object is + * {@link Counter } + * + */ + public void setQuotaPerMonth(Counter value) { + this.quotaPerMonth = value; + } + + /** + * Gets the value of the rateLimitPerSecond property. + * + * @return + * possible object is + * {@link Counter } + * + */ + public Counter getRateLimitPerSecond() { + return rateLimitPerSecond; + } + + /** + * Sets the value of the rateLimitPerSecond property. + * + * @param value + * allowed object is + * {@link Counter } + * + */ + public void setRateLimitPerSecond(Counter value) { + this.rateLimitPerSecond = value; + } + + /** + * Gets the value of the rateLimitPerMinute property. + * + * @return + * possible object is + * {@link Counter } + * + */ + public Counter getRateLimitPerMinute() { + return rateLimitPerMinute; + } + + /** + * Sets the value of the rateLimitPerMinute property. + * + * @param value + * allowed object is + * {@link Counter } + * + */ + public void setRateLimitPerMinute(Counter value) { + this.rateLimitPerMinute = value; + } + +} diff --git a/exposure-engine/provisioning/src/main/java/com/alu/e3/prov/restapi/model/Counter.java b/exposure-engine/provisioning/src/main/java/com/alu/e3/prov/restapi/model/Counter.java new file mode 100644 index 0000000..8bcb895 --- /dev/null +++ b/exposure-engine/provisioning/src/main/java/com/alu/e3/prov/restapi/model/Counter.java @@ -0,0 +1,135 @@ +/** + * Copyright © 2012 Alcatel-Lucent. + * + * See the NOTICE file distributed with this work for additional + * information regarding copyright ownership. + * Licensed to you 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 com.alu.e3.prov.restapi.model; + +import javax.xml.bind.annotation.XmlAccessType; +import javax.xml.bind.annotation.XmlAccessorType; +import javax.xml.bind.annotation.XmlElement; +import javax.xml.bind.annotation.XmlType; + + +/** + * Defines a counter. + */ +@XmlAccessorType(XmlAccessType.FIELD) +@XmlType(name = "CounterType", propOrder = { + "status", + "action", + "warning", + "threshold" +}) +public class Counter { + + @XmlElement(required = true) + protected Status status; + @XmlElement(required = true) + protected Action action; + protected float warning; + protected long threshold; + + public String toString() { + String v = "status = " + status; + v += ", action = " + action; + v += ", warning = " + warning; + v += ", threshold = " + threshold; + + return v; + } + + /** + * Gets the value of the status property. + * + * @return + * possible object is + * {@link Status } + * + */ + public Status getStatus() { + return status; + } + + /** + * Sets the value of the status property. + * + * @param value + * allowed object is + * {@link Status } + * + */ + public void setStatus(Status value) { + this.status = value; + } + + /** + * Gets the value of the action property. + * + * @return + * possible object is + * {@link Action } + * + */ + public Action getAction() { + return action; + } + + /** + * Sets the value of the action property. + * + * @param value + * allowed object is + * {@link Action } + * + */ + public void setAction(Action value) { + this.action = value; + } + + /** + * Gets the value of the warning property. + * + */ + public float getWarning() { + return warning; + } + + /** + * Sets the value of the warning property. + * + */ + public void setWarning(float value) { + this.warning = value; + } + + /** + * Gets the value of the threshold property. + * + */ + public long getThreshold() { + return threshold; + } + + /** + * Sets the value of the threshold property. + * + */ + public void setThreshold(long value) { + this.threshold = value; + } + +} diff --git a/exposure-engine/provisioning/src/main/java/com/alu/e3/prov/restapi/model/Data.java b/exposure-engine/provisioning/src/main/java/com/alu/e3/prov/restapi/model/Data.java new file mode 100644 index 0000000..6406314 --- /dev/null +++ b/exposure-engine/provisioning/src/main/java/com/alu/e3/prov/restapi/model/Data.java @@ -0,0 +1,83 @@ +/** + * Copyright © 2012 Alcatel-Lucent. + * + * See the NOTICE file distributed with this work for additional + * information regarding copyright ownership. + * Licensed to you 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. + */ +// +// This file was generated by the JavaTM Architecture for XML Binding(JAXB) Reference Implementation, vhudson-jaxb-ri-2.2-27 +// See http://java.sun.com/xml/jaxb +// Any modifications to this file will be lost upon recompilation of the source schema. +// Generated on: 2012.03.19 at 02:26:27 PM CET +// + + +package com.alu.e3.prov.restapi.model; + +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.XmlType; + + +/** + * A Generic list for key/value model. + * + */ +@XmlAccessorType(XmlAccessType.FIELD) +@XmlType(name = "data", propOrder = { + "key" +}) +public class Data { + + @XmlElement(required = true) + protected List key; + + /** + * Gets the value of the key property. + * + *

+ * This accessor method returns a reference to the live list, + * not a snapshot. Therefore any modification you make to the + * returned list will be present inside the JAXB object. + * This is why there is not a set method for the key property. + * + *

+ * For example, to add a new item, do as follows: + *

+     *    getKey().add(newItem);
+     * 
+ * + * + *

+ * Objects of the following type(s) are allowed in the list + * {@link Key } + * + * + */ + public List getKey() { + if (key == null) { + key = new ArrayList(); + } + return this.key; + } + + public void setKey(List key) { + this.key = key; + } + +} diff --git a/exposure-engine/provisioning/src/main/java/com/alu/e3/prov/restapi/model/DynamicTdr.java b/exposure-engine/provisioning/src/main/java/com/alu/e3/prov/restapi/model/DynamicTdr.java new file mode 100644 index 0000000..6415fc8 --- /dev/null +++ b/exposure-engine/provisioning/src/main/java/com/alu/e3/prov/restapi/model/DynamicTdr.java @@ -0,0 +1,138 @@ +/** + * Copyright © 2012 Alcatel-Lucent. + * + * See the NOTICE file distributed with this work for additional + * information regarding copyright ownership. + * Licensed to you 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 com.alu.e3.prov.restapi.model; + +import javax.xml.bind.annotation.XmlAccessType; +import javax.xml.bind.annotation.XmlAccessorType; +import javax.xml.bind.annotation.XmlAttribute; +import javax.xml.bind.annotation.XmlType; + +import com.alu.e3.data.model.ExtractFromType; + + +/** + * + */ +@XmlAccessorType(XmlAccessType.FIELD) +@XmlType(name = "dynamicTDR", propOrder = { + "types" +}) +public class DynamicTdr { + + protected TdrType types; + @XmlAttribute(name = "tdrPropName", required = true) + protected String tdrPropName; + @XmlAttribute(name = "httpHeaderName", required = true) + protected String httpHeaderName; + + @XmlAttribute(name = "extractFrom", required = false) + protected ExtractFromType extractFrom = ExtractFromType.Either; + + @Override + public String toString() { + String v = "types = " + types + ", "; + + v += "tdrPropName = " + tdrPropName + ", "; + + v += "httpHeaderName = " + httpHeaderName + ", "; + + return v; + } + + /** + * Gets the value of the types property. + * + * @return + * possible object is + * {@link TdrType } + * + */ + public TdrType getTypes() { + return types; + } + + /** + * Sets the value of the types property. + * + * @param value + * allowed object is + * {@link TdrType } + * + */ + public void setTypes(TdrType value) { + this.types = value; + } + + /** + * Gets the value of the tdrPropName property. + * + * @return + * possible object is + * {@link String } + * + */ + public String getTdrPropName() { + return tdrPropName; + } + + /** + * Sets the value of the tdrPropName property. + * + * @param value + * allowed object is + * {@link String } + * + */ + public void setTdrPropName(String value) { + this.tdrPropName = value; + } + + /** + * Gets the value of the httpHeaderName property. + * + * @return + * possible object is + * {@link String } + * + */ + public String getHttpHeaderName() { + return httpHeaderName; + } + + /** + * Sets the value of the httpHeaderName property. + * + * @param value + * allowed object is + * {@link String } + * + */ + public void setHttpHeaderName(String value) { + this.httpHeaderName = value; + } + + public ExtractFromType getExtractFrom() { + return extractFrom; + } + + public void setExtractFrom(ExtractFromType extractFrom) { + this.extractFrom = extractFrom; + } + +} diff --git a/exposure-engine/provisioning/src/main/java/com/alu/e3/prov/restapi/model/Environment.java b/exposure-engine/provisioning/src/main/java/com/alu/e3/prov/restapi/model/Environment.java new file mode 100644 index 0000000..ca31993 --- /dev/null +++ b/exposure-engine/provisioning/src/main/java/com/alu/e3/prov/restapi/model/Environment.java @@ -0,0 +1,262 @@ +/** + * Copyright © 2012 Alcatel-Lucent. + * + * See the NOTICE file distributed with this work for additional + * information regarding copyright ownership. + * Licensed to you 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. + */ +// +// This file was generated by the JavaTM Architecture for XML Binding(JAXB) Reference Implementation, vhudson-jaxb-ri-2.2-27 +// See http://java.sun.com/xml/jaxb +// Any modifications to this file will be lost upon recompilation of the source schema. +// Generated on: 2012.03.19 at 02:26:27 PM CET +// + + +package com.alu.e3.prov.restapi.model; + +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.XmlElementWrapper; +import javax.xml.bind.annotation.XmlType; + + +/** + * Defines an environment data model. + * + */ +@XmlAccessorType(XmlAccessType.FIELD) +@XmlType(name = "environment", propOrder = { + "type", + "status", + "targetHosts", + "maxRateLimitTPSThreshold", + "maxRateLimitTPSWarning", + "maxRateLimitTPMThreshold", + "maxRateLimitTPMWarning" +}) +public class Environment { + + /** + * The environment type. + */ + @XmlElement(required = true) + protected EnvironmentType type; + + /** + * The environment status: active, inactive, pending + */ + @XmlElement(required = true) + protected Status status; + + /** + * The target hosts defined for the environment. + */ + @XmlElementWrapper(name="targetHosts", required = true) + @XmlElement(name="targetHost", required = true) + protected List targetHosts; + + /** + * Max Rate Limit Transaction Per Second (TPS) Threshold + */ + @XmlElement(required = true) + protected int maxRateLimitTPSThreshold; + + /** + * Max Rate Limit Transaction Per Second (TPS) Warning + */ + @XmlElement(required = true) + protected float maxRateLimitTPSWarning; + + /** + * Max Rate Limit Transaction per Minute (TPM) Threshold + */ + @XmlElement(required = true) + protected int maxRateLimitTPMThreshold; + + /** + * Max Rate Limit TPM Warning + */ + @XmlElement(required = true) + protected float maxRateLimitTPMWarning; + + /** + * Gets the value of the type property. + * + * @return + * possible object is + * {@link EnvType } + * + */ + public EnvironmentType getType() { + return type; + } + + /** + * Sets the value of the type property. + * + * @param value + * allowed object is + * {@link EnvType } + * + */ + public void setType(EnvironmentType value) { + this.type = value; + } + + /** + * Gets the value of the status property. + * + * @return + * possible object is + * {@link EnvStatus } + * + */ + public Status getStatus() { + return status; + } + + /** + * Sets the value of the status property. + * + * @param value + * allowed object is + * {@link EnvStatus } + * + */ + public void setStatus(Status value) { + this.status = value; + } + + public List getTargetHosts() { + if (targetHosts == null) { + targetHosts = new ArrayList(); + } + return this.targetHosts; + } + + /** + * Sets the value of the targetHosts property. + * + * @param value + * allowed object is + * {@link TargetHosts } + * + */ + public void setTargetHosts(List value) { + this.targetHosts = value; + } + + /** + * Gets the value of the maxRateLimitTPSThreshold property. + * + * @return + * possible object is + * {@link String } + * + */ + public int getMaxRateLimitTPSThreshold() { + return maxRateLimitTPSThreshold; + } + + /** + * Sets the value of the maxRateLimitTPSThreshold property. + * + * @param value + * allowed object is + * {@link String } + * + */ + public void setMaxRateLimitTPSThreshold(int value) { + this.maxRateLimitTPSThreshold = value; + } + + /** + * Gets the value of the maxRateLimitTPSWarning property. + * + * @return + * possible object is + * {@link String } + * + */ + public float getMaxRateLimitTPSWarning() { + return maxRateLimitTPSWarning; + } + + /** + * Sets the value of the maxRateLimitTPSWarning property. + * + * @param value + * allowed object is + * {@link String } + * + */ + public void setMaxRateLimitTPSWarning(float value) { + this.maxRateLimitTPSWarning = value; + } + + /** + * Gets the value of the maxRateLimitTPMThreshold property. + * + * @return + * possible object is + * {@link String } + * + */ + public int getMaxRateLimitTPMThreshold() { + return maxRateLimitTPMThreshold; + } + + /** + * Sets the value of the maxRateLimitTPMThreshold property. + * + * @param value + * allowed object is + * {@link String } + * + */ + public void setMaxRateLimitTPMThreshold(int value) { + this.maxRateLimitTPMThreshold = value; + } + + /** + * Gets the value of the maxRateLimitTPMWarning property. + * + * @return + * possible object is + * {@link String } + * + */ + public float getMaxRateLimitTPMWarning() { + return maxRateLimitTPMWarning; + } + + /** + * Sets the value of the maxRateLimitTPMWarning property. + * + * @param value + * allowed object is + * {@link String } + * + */ + public void setMaxRateLimitTPMWarning(float value) { + this.maxRateLimitTPMWarning = value; + } + + +} diff --git a/exposure-engine/provisioning/src/main/java/com/alu/e3/prov/restapi/model/EnvironmentData.java b/exposure-engine/provisioning/src/main/java/com/alu/e3/prov/restapi/model/EnvironmentData.java new file mode 100644 index 0000000..4cf1752 --- /dev/null +++ b/exposure-engine/provisioning/src/main/java/com/alu/e3/prov/restapi/model/EnvironmentData.java @@ -0,0 +1,232 @@ +/** + * Copyright © 2012 Alcatel-Lucent. + * + * See the NOTICE file distributed with this work for additional + * information regarding copyright ownership. + * Licensed to you 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 com.alu.e3.prov.restapi.model; + +import javax.xml.bind.annotation.XmlAccessType; +import javax.xml.bind.annotation.XmlAccessorType; +import javax.xml.bind.annotation.XmlElement; +import javax.xml.bind.annotation.XmlType; + + +/** + * Defines an environment. + */ +@XmlAccessorType(XmlAccessType.FIELD) +@XmlType(name = "EnvironmentDataType", propOrder = { + "name", + "status", + "quotaPerDay", + "quotaPerWeek", + "quotaPerMonth", + "rateLimitPerSecond", + "rateLimitPerMinute" +}) +public class EnvironmentData { + + @XmlElement(required = true) + protected EnvironmentType name; + @XmlElement(required = true) + protected Status status; + protected Counter quotaPerDay; + protected Counter quotaPerWeek; + protected Counter quotaPerMonth; + protected Counter rateLimitPerSecond; + protected Counter rateLimitPerMinute; + + public String toString() { + String v = "name = " + name; + v += ", status = " + status; + v += ", quotaPerDay = [" + quotaPerDay + "]"; + v += ", quotaPerWeek = [" + quotaPerWeek + "]"; + v += ", quotaPerMonth = [" + quotaPerMonth + "]"; + v += ", rateLimitPerSecond = [" + rateLimitPerSecond + "]"; + v += ", rateLimitPerMinute = [" + rateLimitPerMinute + "]"; + + return v; + } + + /** + * Gets the value of the name property. + * + * @return + * possible object is + * {@link EnvironmentType } + * + */ + public EnvironmentType getName() { + return name; + } + + /** + * Sets the value of the name property. + * + * @param value + * allowed object is + * {@link EnvironmentType } + * + */ + public void setName(EnvironmentType value) { + this.name = value; + } + + /** + * Gets the value of the status property. + * + * @return + * possible object is + * {@link Status } + * + */ + public Status getStatus() { + return status; + } + + /** + * Sets the value of the status property. + * + * @param value + * allowed object is + * {@link Status } + * + */ + public void setStatus(Status value) { + this.status = value; + } + + /** + * Gets the value of the quotaPerDay property. + * + * @return + * possible object is + * {@link Counter } + * + */ + public Counter getQuotaPerDay() { + return quotaPerDay; + } + + /** + * Sets the value of the quotaPerDay property. + * + * @param value + * allowed object is + * {@link Counter } + * + */ + public void setQuotaPerDay(Counter value) { + this.quotaPerDay = value; + } + + /** + * Gets the value of the quotaPerWeek property. + * + * @return + * possible object is + * {@link Counter } + * + */ + public Counter getQuotaPerWeek() { + return quotaPerWeek; + } + + /** + * Sets the value of the quotaPerWeek property. + * + * @param value + * allowed object is + * {@link Counter } + * + */ + public void setQuotaPerWeek(Counter value) { + this.quotaPerWeek = value; + } + + /** + * Gets the value of the quotaPerMonth property. + * + * @return + * possible object is + * {@link Counter } + * + */ + public Counter getQuotaPerMonth() { + return quotaPerMonth; + } + + /** + * Sets the value of the quotaPerMonth property. + * + * @param value + * allowed object is + * {@link Counter } + * + */ + public void setQuotaPerMonth(Counter value) { + this.quotaPerMonth = value; + } + + /** + * Gets the value of the rateLimitPerSecond property. + * + * @return + * possible object is + * {@link Counter } + * + */ + public Counter getRateLimitPerSecond() { + return rateLimitPerSecond; + } + + /** + * Sets the value of the rateLimitPerSecond property. + * + * @param value + * allowed object is + * {@link Counter } + * + */ + public void setRateLimitPerSecond(Counter value) { + this.rateLimitPerSecond = value; + } + + /** + * Gets the value of the rateLimitPerMinute property. + * + * @return + * possible object is + * {@link Counter } + * + */ + public Counter getRateLimitPerMinute() { + return rateLimitPerMinute; + } + + /** + * Sets the value of the rateLimitPerMinute property. + * + * @param value + * allowed object is + * {@link Counter } + * + */ + public void setRateLimitPerMinute(Counter value) { + this.rateLimitPerMinute = value; + } + +} diff --git a/exposure-engine/provisioning/src/main/java/com/alu/e3/prov/restapi/model/EnvironmentType.java b/exposure-engine/provisioning/src/main/java/com/alu/e3/prov/restapi/model/EnvironmentType.java new file mode 100644 index 0000000..9d16fb7 --- /dev/null +++ b/exposure-engine/provisioning/src/main/java/com/alu/e3/prov/restapi/model/EnvironmentType.java @@ -0,0 +1,58 @@ +/** + * Copyright © 2012 Alcatel-Lucent. + * + * See the NOTICE file distributed with this work for additional + * information regarding copyright ownership. + * Licensed to you 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 com.alu.e3.prov.restapi.model; + +import javax.xml.bind.annotation.XmlEnum; +import javax.xml.bind.annotation.XmlEnumValue; +import javax.xml.bind.annotation.XmlType; + + +/** + * Defines a type of environment. It can be "production", "sandbox" or "test". + */ +@XmlType(name = "environmentType", namespace = "") +@XmlEnum +public enum EnvironmentType { + + @XmlEnumValue("production") + PRODUCTION("production"), + @XmlEnumValue("sandbox") + SANDBOX("sandbox"), + @XmlEnumValue("test") + TEST("test"); + private final String value; + + EnvironmentType(String v) { + value = v; + } + + public String value() { + return value; + } + + public static EnvironmentType fromValue(String v) { + for (EnvironmentType c: EnvironmentType.values()) { + if (c.value.equals(v)) { + return c; + } + } + throw new IllegalArgumentException(v); + } + +} diff --git a/exposure-engine/provisioning/src/main/java/com/alu/e3/prov/restapi/model/Error.java b/exposure-engine/provisioning/src/main/java/com/alu/e3/prov/restapi/model/Error.java new file mode 100644 index 0000000..d0db483 --- /dev/null +++ b/exposure-engine/provisioning/src/main/java/com/alu/e3/prov/restapi/model/Error.java @@ -0,0 +1,122 @@ +/** + * Copyright © 2012 Alcatel-Lucent. + * + * See the NOTICE file distributed with this work for additional + * information regarding copyright ownership. + * Licensed to you 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. + */ +// +// This file was generated by the JavaTM Architecture for XML Binding(JAXB) Reference Implementation, vhudson-jaxb-ri-2.2-27 +// See http://java.sun.com/xml/jaxb +// Any modifications to this file will be lost upon recompilation of the source schema. +// Generated on: 2012.03.19 at 02:26:27 PM CET +// + + +package com.alu.e3.prov.restapi.model; + +import javax.xml.bind.annotation.XmlAccessType; +import javax.xml.bind.annotation.XmlAccessorType; +import javax.xml.bind.annotation.XmlType; + + +/** + * Error data model used in REST services response + * + */ +@XmlAccessorType(XmlAccessType.FIELD) +@XmlType(name = "error", propOrder = { + "errorText", + "errorCode", + "errorType" +}) +public class Error { + + protected String errorText; + protected String errorCode; + protected String errorType; + + /** + * Gets the value of the errorText property. + * + * @return + * possible object is + * {@link String } + * + */ + public String getErrorText() { + return errorText; + } + + /** + * Sets the value of the errorText property. + * + * @param value + * allowed object is + * {@link String } + * + */ + public void setErrorText(String value) { + this.errorText = value; + } + + /** + * Gets the value of the errorCode property. + * + * @return + * possible object is + * {@link String } + * + */ + public String getErrorCode() { + return errorCode; + } + + /** + * Sets the value of the errorCode property. + * + * @param value + * allowed object is + * {@link String } + * + */ + public void setErrorCode(String value) { + this.errorCode = value; + } + + /** + * Gets the value of the errorType property. + * + * @return + * possible object is + * {@link String } + * + */ + public String getErrorType() { + return errorType; + } + + /** + * Sets the value of the errorType property. + * + * @param value + * allowed object is + * {@link String } + * + */ + public void setErrorType(String value) { + this.errorType = value; + } + +} diff --git a/exposure-engine/provisioning/src/main/java/com/alu/e3/prov/restapi/model/FailOver.java b/exposure-engine/provisioning/src/main/java/com/alu/e3/prov/restapi/model/FailOver.java new file mode 100644 index 0000000..e18e703 --- /dev/null +++ b/exposure-engine/provisioning/src/main/java/com/alu/e3/prov/restapi/model/FailOver.java @@ -0,0 +1,57 @@ +/** + * Copyright © 2012 Alcatel-Lucent. + * + * See the NOTICE file distributed with this work for additional + * information regarding copyright ownership. + * Licensed to you 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 com.alu.e3.prov.restapi.model; + +import javax.xml.bind.annotation.XmlAccessType; +import javax.xml.bind.annotation.XmlAccessorType; +import javax.xml.bind.annotation.XmlElement; +import javax.xml.bind.annotation.XmlType; + + +/** + * The Fail over for this load balancing + */ +@XmlAccessorType(XmlAccessType.FIELD) +@XmlType(name = "failOver", propOrder = { + "onResponseCode" +}) +public class FailOver { + + @XmlElement(required = true) + protected String onResponseCode; + + + + /** + * Gets the value of the onResponseCode property. + */ + public String getOnResponseCode() { + return this.onResponseCode; + } + + /** + * Sets the value of the onResponseCode property. + * @param onResponseCode the onResponseCode to set + */ + public void setOnResponseCode(String onResponseCode) { + this.onResponseCode = onResponseCode; + } + + +} diff --git a/exposure-engine/provisioning/src/main/java/com/alu/e3/prov/restapi/model/ForwardProxy.java b/exposure-engine/provisioning/src/main/java/com/alu/e3/prov/restapi/model/ForwardProxy.java new file mode 100644 index 0000000..8361c9c --- /dev/null +++ b/exposure-engine/provisioning/src/main/java/com/alu/e3/prov/restapi/model/ForwardProxy.java @@ -0,0 +1,151 @@ +/** + * Copyright © 2012 Alcatel-Lucent. + * + * See the NOTICE file distributed with this work for additional + * information regarding copyright ownership. + * Licensed to you 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 com.alu.e3.prov.restapi.model; + +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.XmlType; + +/** + * The forwardProxy data model. + * + */ +@XmlRootElement +@XmlAccessorType(XmlAccessType.FIELD) +@XmlType(name = "forwardProxy", propOrder = { + "proxyHost", + "proxyPort", + "proxyUser", + "proxyPass" +}) +public class ForwardProxy { + + @XmlElement(required = true) + protected String proxyHost; + + @XmlElement(required = true) + protected String proxyPort; + + @XmlElement(required = true) + protected String proxyUser; + + @XmlElement(required = true) + protected String proxyPass; + + /** + * Gets the value of the proxyHost property. + * + * @return + * possible object is + * {@link String } + * + */ + public String getProxyHost() { + return proxyHost; + } + + /** + * Sets the value of the proxyHost property. + * + * @param value + * allowed object is + * {@link String } + * + */ + public void setProxyHost(String value) { + this.proxyHost = value; + } + + + /** + * Gets the value of the proxyPort property. + * + * @return + * possible object is + * {@link String } + * + */ + public String getProxyPort() { + return proxyPort; + } + + /** + * Sets the value of the proxyPort property. + * + * @param value + * allowed object is + * {@link String } + * + */ + public void setProxyPort(String value) { + this.proxyPort = value; + } + + + /** + * Gets the value of the proxyUser property. + * + * @return + * possible object is + * {@link String } + * + */ + public String getProxyUser() { + return proxyUser; + } + + /** + * Sets the value of the proxyUser property. + * + * @param value + * allowed object is + * {@link String } + * + */ + public void setProxyUser(String value) { + this.proxyUser = value; + } + + + /** + * Gets the value of the proxyPass property. + * + * @return + * possible object is + * {@link String } + * + */ + public String getProxyPass() { + return proxyPass; + } + + /** + * Sets the value of the proxyPass property. + * + * @param value + * allowed object is + * {@link String } + * + */ + public void setProxyPass(String value) { + this.proxyPass = value; + } +} diff --git a/exposure-engine/provisioning/src/main/java/com/alu/e3/prov/restapi/model/HTTPSType.java b/exposure-engine/provisioning/src/main/java/com/alu/e3/prov/restapi/model/HTTPSType.java new file mode 100644 index 0000000..626d179 --- /dev/null +++ b/exposure-engine/provisioning/src/main/java/com/alu/e3/prov/restapi/model/HTTPSType.java @@ -0,0 +1,64 @@ +/** + * Copyright © 2012 Alcatel-Lucent. + * + * See the NOTICE file distributed with this work for additional + * information regarding copyright ownership. + * Licensed to you 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 com.alu.e3.prov.restapi.model; + +import javax.xml.bind.annotation.XmlAccessType; +import javax.xml.bind.annotation.XmlAccessorType; +import javax.xml.bind.annotation.XmlAttribute; +import javax.xml.bind.annotation.XmlType; +import javax.xml.bind.annotation.XmlValue; + + +/** + * The API type, it can either be PassThrough or Composite + */ +@XmlAccessorType(XmlAccessType.FIELD) +@XmlType(name = "https", propOrder = { + "enabled" +}) +public class HTTPSType { + + @XmlValue + protected boolean enabled; + + @XmlAttribute(name = "tlsMode") + protected TLSMode tlsMode; + + + public boolean isEnabled() { + return enabled; + } + + + public void setEnabled(boolean enabled) { + this.enabled = enabled; + } + + + public TLSMode getTlsMode() { + return tlsMode; + } + + + public void setTlsMode(TLSMode tlsMode) { + this.tlsMode = tlsMode; + } + +} diff --git a/exposure-engine/provisioning/src/main/java/com/alu/e3/prov/restapi/model/HeaderTransformation.java b/exposure-engine/provisioning/src/main/java/com/alu/e3/prov/restapi/model/HeaderTransformation.java new file mode 100644 index 0000000..3023977 --- /dev/null +++ b/exposure-engine/provisioning/src/main/java/com/alu/e3/prov/restapi/model/HeaderTransformation.java @@ -0,0 +1,165 @@ +/** + * Copyright © 2012 Alcatel-Lucent. + * + * See the NOTICE file distributed with this work for additional + * information regarding copyright ownership. + * Licensed to you 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 com.alu.e3.prov.restapi.model; + +import javax.xml.bind.annotation.XmlAccessType; +import javax.xml.bind.annotation.XmlAccessorType; +import javax.xml.bind.annotation.XmlAttribute; +import javax.xml.bind.annotation.XmlType; + +/** + * Defines a Header Transformation. + */ +@XmlAccessorType(XmlAccessType.FIELD) +@XmlType(name = "HeaderTransformation") +public class HeaderTransformation { + + @XmlAttribute(required = true) + protected String name; + @XmlAttribute(required = false) + protected String property; + @XmlAttribute(required = false) + protected String value; + @XmlAttribute(required = true) + protected HeaderTransformationType type; + @XmlAttribute(required = true) + protected HeaderTransformationAction action; + + + /** + * Gets the value of the name attribute. + * + * @return + * possible object is + * {@link String } + * + */ + public String getName() { + return name; + } + + /** + * Sets the value of the name attribute. + * + * @param value + * allowed object is + * {@link String } + * + */ + public void setName(String value) { + this.name = value; + } + + /** + * Gets the value of the property property. + * + * @return + * possible object is + * {@link String } + * + */ + public String getProperty() { + return property; + } + + /** + * Sets the value of the property property. + * + * @param value + * allowed object is + * {@link Status } + * + */ + public void setProperty(String value) { + this.property = value; + } + + /** + * Gets the value of the value property. + * + * @return + * possible object is + * {@link String } + * + */ + public String getValue() { + return value; + } + + /** + * Sets the value of the value property. + * + * @param value + * allowed object is + * {@link Status } + * + */ + public void setValue(String value) { + this.value = value; + } + + /** + * Gets the value of the type property. + * + * @return + * possible object is + * {@link HeaderTransformationType } + * + */ + public HeaderTransformationType getType() { + return type; + } + + /** + * Sets the value of the type property. + * + * @param value + * allowed object is + * {@link HeaderTransformationType } + * + */ + public void setType(HeaderTransformationType value) { + this.type = value; + } + + /** + * Gets the value of the action property. + * + * @return + * possible object is + * {@link HeaderTransformationAction } + * + */ + public HeaderTransformationAction getAction() { + return action; + } + + /** + * Sets the value of the action property. + * + * @param value + * allowed object is + * {@link HeaderTransformationAction } + * + */ + public void setAction(HeaderTransformationAction value) { + this.action = value; + } + +} diff --git a/exposure-engine/provisioning/src/main/java/com/alu/e3/prov/restapi/model/HeaderTransformationAction.java b/exposure-engine/provisioning/src/main/java/com/alu/e3/prov/restapi/model/HeaderTransformationAction.java new file mode 100644 index 0000000..1eebdab --- /dev/null +++ b/exposure-engine/provisioning/src/main/java/com/alu/e3/prov/restapi/model/HeaderTransformationAction.java @@ -0,0 +1,54 @@ +/** + * Copyright © 2012 Alcatel-Lucent. + * + * See the NOTICE file distributed with this work for additional + * information regarding copyright ownership. + * Licensed to you 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 com.alu.e3.prov.restapi.model; + +import javax.xml.bind.annotation.XmlEnum; +import javax.xml.bind.annotation.XmlEnumValue; + + +/** + * The Header Transformation type, it can either be Request or Response + */ +//@XmlType(name = "apiType") +@XmlEnum +public enum HeaderTransformationAction { + @XmlEnumValue("Add") + ADD("Add"), + @XmlEnumValue("Remove") + REMOVE("Remove"); + private final String value; + + HeaderTransformationAction(String v) { + value = v; + } + + public String value() { + return value; + } + + public static HeaderTransformationAction fromValue(String v) { + for (HeaderTransformationAction c: HeaderTransformationAction.values()) { + if (c.value.equals(v)) { + return c; + } + } + throw new IllegalArgumentException(v); + } + +} diff --git a/exposure-engine/provisioning/src/main/java/com/alu/e3/prov/restapi/model/HeaderTransformationType.java b/exposure-engine/provisioning/src/main/java/com/alu/e3/prov/restapi/model/HeaderTransformationType.java new file mode 100644 index 0000000..d5990c2 --- /dev/null +++ b/exposure-engine/provisioning/src/main/java/com/alu/e3/prov/restapi/model/HeaderTransformationType.java @@ -0,0 +1,54 @@ +/** + * Copyright © 2012 Alcatel-Lucent. + * + * See the NOTICE file distributed with this work for additional + * information regarding copyright ownership. + * Licensed to you 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 com.alu.e3.prov.restapi.model; + +import javax.xml.bind.annotation.XmlEnum; +import javax.xml.bind.annotation.XmlEnumValue; + + +/** + * The Header Transformation type, it can either be Request or Response + */ +//@XmlType(name = "apiType") +@XmlEnum +public enum HeaderTransformationType { + @XmlEnumValue("Request") + REQUEST("Request"), + @XmlEnumValue("Response") + RESPONSE("Response"); + private final String value; + + HeaderTransformationType(String v) { + value = v; + } + + public String value() { + return value; + } + + public static HeaderTransformationType fromValue(String v) { + for (HeaderTransformationType c: HeaderTransformationType.values()) { + if (c.value.equals(v)) { + return c; + } + } + throw new IllegalArgumentException(v); + } + +} diff --git a/exposure-engine/provisioning/src/main/java/com/alu/e3/prov/restapi/model/HttpMethod.java b/exposure-engine/provisioning/src/main/java/com/alu/e3/prov/restapi/model/HttpMethod.java new file mode 100644 index 0000000..b429d53 --- /dev/null +++ b/exposure-engine/provisioning/src/main/java/com/alu/e3/prov/restapi/model/HttpMethod.java @@ -0,0 +1,37 @@ +/** + * Copyright © 2012 Alcatel-Lucent. + * + * See the NOTICE file distributed with this work for additional + * information regarding copyright ownership. + * Licensed to you 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 com.alu.e3.prov.restapi.model; + +/** + * If you change this enum, also change com.alu.e3.data.model.enumeration.HttpMethod + * + * + * + */ +public enum HttpMethod { + GET, + POST, + PUT, + DELETE, + HEAD, + TRACE, + OPTIONS, + CONNECT, + PATCH +} diff --git a/exposure-engine/provisioning/src/main/java/com/alu/e3/prov/restapi/model/IpWhiteListAuth.java b/exposure-engine/provisioning/src/main/java/com/alu/e3/prov/restapi/model/IpWhiteListAuth.java new file mode 100644 index 0000000..e410046 --- /dev/null +++ b/exposure-engine/provisioning/src/main/java/com/alu/e3/prov/restapi/model/IpWhiteListAuth.java @@ -0,0 +1,80 @@ +/** + * Copyright © 2012 Alcatel-Lucent. + * + * See the NOTICE file distributed with this work for additional + * information regarding copyright ownership. + * Licensed to you 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. + */ +// +// This file was generated by the JavaTM Architecture for XML Binding(JAXB) Reference Implementation, vhudson-jaxb-ri-2.2-27 +// See http://java.sun.com/xml/jaxb +// Any modifications to this file will be lost upon recompilation of the source schema. +// Generated on: 2012.03.19 at 02:26:36 PM CET +// + + +package com.alu.e3.prov.restapi.model; + +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.XmlType; + + +/** + * A Auth model based on a IP list considered as white list. + * + */ +@XmlAccessorType(XmlAccessType.FIELD) +@XmlType(name = "ipWhiteListAuth", propOrder = { + "ip" +}) +public class IpWhiteListAuth { + /** + * The list of authorized IPs + */ + protected List ip; + + /** + * Gets the value of the ip property. + * + *

+ * This accessor method returns a reference to the live list, + * not a snapshot. Therefore any modification you make to the + * returned list will be present inside the JAXB object. + * This is why there is not a set method for the ip property. + * + *

+ * For example, to add a new item, do as follows: + *

+     *    getIp().add(newItem);
+     * 
+ * + * + *

+ * Objects of the following type(s) are allowed in the list + * {@link String } + * + * + */ + public List getIp() { + if (ip == null) { + ip = new ArrayList(); + } + return this.ip; + } + +} diff --git a/exposure-engine/provisioning/src/main/java/com/alu/e3/prov/restapi/model/Key.java b/exposure-engine/provisioning/src/main/java/com/alu/e3/prov/restapi/model/Key.java new file mode 100644 index 0000000..2ab2124 --- /dev/null +++ b/exposure-engine/provisioning/src/main/java/com/alu/e3/prov/restapi/model/Key.java @@ -0,0 +1,99 @@ +/** + * Copyright © 2012 Alcatel-Lucent. + * + * See the NOTICE file distributed with this work for additional + * information regarding copyright ownership. + * Licensed to you 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. + */ +// +// This file was generated by the JavaTM Architecture for XML Binding(JAXB) Reference Implementation, vhudson-jaxb-ri-2.2-27 +// See http://java.sun.com/xml/jaxb +// Any modifications to this file will be lost upon recompilation of the source schema. +// Generated on: 2012.03.19 at 02:26:27 PM CET +// + + +package com.alu.e3.prov.restapi.model; + +import javax.xml.bind.annotation.XmlAccessType; +import javax.xml.bind.annotation.XmlAccessorType; +import javax.xml.bind.annotation.XmlAttribute; +import javax.xml.bind.annotation.XmlType; +import javax.xml.bind.annotation.XmlValue; + + +/** + * Key/value model + * + */ +@XmlAccessorType(XmlAccessType.FIELD) +@XmlType(name = "key", propOrder = { + "value" +}) +public class Key { + + @XmlValue + protected String value; + @XmlAttribute(name = "name", required = true) + protected String name; + + /** + * Gets the value of the value property. + * + * @return + * possible object is + * {@link String } + * + */ + public String getValue() { + return value; + } + + /** + * Sets the value of the value property. + * + * @param value + * allowed object is + * {@link String } + * + */ + public void setValue(String value) { + this.value = value; + } + + /** + * Gets the value of the name property. + * + * @return + * possible object is + * {@link String } + * + */ + public String getName() { + return name; + } + + /** + * Sets the value of the name property. + * + * @param value + * allowed object is + * {@link String } + * + */ + public void setName(String value) { + this.name = value; + } + +} diff --git a/exposure-engine/provisioning/src/main/java/com/alu/e3/prov/restapi/model/LoadBalancing.java b/exposure-engine/provisioning/src/main/java/com/alu/e3/prov/restapi/model/LoadBalancing.java new file mode 100644 index 0000000..2295ab2 --- /dev/null +++ b/exposure-engine/provisioning/src/main/java/com/alu/e3/prov/restapi/model/LoadBalancing.java @@ -0,0 +1,97 @@ +/** + * Copyright © 2012 Alcatel-Lucent. + * + * See the NOTICE file distributed with this work for additional + * information regarding copyright ownership. + * Licensed to you 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 com.alu.e3.prov.restapi.model; + +import javax.xml.bind.annotation.XmlAccessType; +import javax.xml.bind.annotation.XmlAccessorType; +import javax.xml.bind.annotation.XmlAttribute; +import javax.xml.bind.annotation.XmlElement; +import javax.xml.bind.annotation.XmlType; + +/** + * The connection parameters for API target hosts. + * + */ +@XmlAccessorType(XmlAccessType.FIELD) +@XmlType(name = "loadBalancing", propOrder = { + "targetHealthCheck", + "failOver" +}) +public class LoadBalancing { + + /** + * The type of load balancing. + */ + @XmlAttribute(name = "type", required = false) + protected LoadBalancingType loadBalancingType = LoadBalancingType.ROUND_ROBIN; + + /** + * The target health check for this load balancing. + */ + @XmlElement(required = false) + protected TargetHealthCheck targetHealthCheck; + + /** + * The fail over for this load balancing. + */ + @XmlElement(required = false) + protected FailOver failOver; + + /** + * @return the loadBalancingType + */ + public LoadBalancingType getLoadBalancingType() { + return loadBalancingType; + } + + /** + * @param loadBalancingType the loadBalancingType to set + */ + public void setLoadBalancingType(LoadBalancingType loadBalancingType) { + this.loadBalancingType = loadBalancingType; + } + + /** + * @return the target Health Check attribute for this load balancing. + */ + public TargetHealthCheck getTargetHealthCheck() { + return targetHealthCheck; + } + + /** + * @param targetHealthCheck the targetHealthCheck to set + */ + public void setTargetHealthCheck(TargetHealthCheck targetHealthCheck) { + this.targetHealthCheck = targetHealthCheck; + } + + /** + * @return the fail over for this load balancing + */ + public FailOver getFailOver() { + return failOver; + } + + /** + * @param failOver the failOver to set + */ + public void setFailOver(FailOver failOver) { + this.failOver = failOver; + } +} diff --git a/exposure-engine/provisioning/src/main/java/com/alu/e3/prov/restapi/model/LoadBalancingType.java b/exposure-engine/provisioning/src/main/java/com/alu/e3/prov/restapi/model/LoadBalancingType.java new file mode 100644 index 0000000..1376ca2 --- /dev/null +++ b/exposure-engine/provisioning/src/main/java/com/alu/e3/prov/restapi/model/LoadBalancingType.java @@ -0,0 +1,55 @@ +/** + * Copyright © 2012 Alcatel-Lucent. + * + * See the NOTICE file distributed with this work for additional + * information regarding copyright ownership. + * Licensed to you 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 com.alu.e3.prov.restapi.model; + +import javax.xml.bind.annotation.XmlEnum; +import javax.xml.bind.annotation.XmlEnumValue; +import javax.xml.bind.annotation.XmlType; + + +/** + * Enumeration for allowed loadBalancing values + */ +@XmlType(name = "loadBalancingType", namespace = "") +@XmlEnum +public enum LoadBalancingType { + + @XmlEnumValue("roundRobin") + ROUND_ROBIN("roundRobin"); + + private final String value; + + LoadBalancingType(String v) { + value = v; + } + + public String value() { + return value; + } + + public static LoadBalancingType fromValue(String v) { + for (LoadBalancingType c: LoadBalancingType.values()) { + if (c.value.equals(v)) { + return c; + } + } + throw new IllegalArgumentException(v); + } + +} diff --git a/exposure-engine/provisioning/src/main/java/com/alu/e3/prov/restapi/model/NotificationFormat.java b/exposure-engine/provisioning/src/main/java/com/alu/e3/prov/restapi/model/NotificationFormat.java new file mode 100644 index 0000000..9956697 --- /dev/null +++ b/exposure-engine/provisioning/src/main/java/com/alu/e3/prov/restapi/model/NotificationFormat.java @@ -0,0 +1,52 @@ +/** + * Copyright © 2012 Alcatel-Lucent. + * + * See the NOTICE file distributed with this work for additional + * information regarding copyright ownership. + * Licensed to you 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 com.alu.e3.prov.restapi.model; + +import javax.xml.bind.annotation.XmlEnum; +import javax.xml.bind.annotation.XmlEnumValue; +import javax.xml.bind.annotation.XmlType; + +@XmlType(name="notificationFormat") +@XmlEnum +public enum NotificationFormat { + @XmlEnumValue("Header") + HEADER("Header"), + @XmlEnumValue("WS-Addressing") + WS_ADDRESSING("WS-Addressing"); + + private final String value; + + NotificationFormat(String v) { + value = v; + } + + public String value() { + return value; + } + + public static NotificationFormat fromValue(String v) { + for (NotificationFormat c: NotificationFormat.values()) { + if (c.value.equals(v)) { + return c; + } + } + throw new IllegalArgumentException(v); + } + +} diff --git a/exposure-engine/provisioning/src/main/java/com/alu/e3/prov/restapi/model/OAuth.java b/exposure-engine/provisioning/src/main/java/com/alu/e3/prov/restapi/model/OAuth.java new file mode 100644 index 0000000..03b1e69 --- /dev/null +++ b/exposure-engine/provisioning/src/main/java/com/alu/e3/prov/restapi/model/OAuth.java @@ -0,0 +1,100 @@ +/** + * Copyright © 2012 Alcatel-Lucent. + * + * See the NOTICE file distributed with this work for additional + * information regarding copyright ownership. + * Licensed to you 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. + */ +// +// This file was generated by the JavaTM Architecture for XML Binding(JAXB) Reference Implementation, vhudson-jaxb-ri-2.2-27 +// See http://java.sun.com/xml/jaxb +// Any modifications to this file will be lost upon recompilation of the source schema. +// Generated on: 2012.03.19 at 02:26:36 PM CET +// + + +package com.alu.e3.prov.restapi.model; + +import javax.xml.bind.annotation.XmlAccessType; +import javax.xml.bind.annotation.XmlAccessorType; +import javax.xml.bind.annotation.XmlElement; +import javax.xml.bind.annotation.XmlType; + + +/** + * The OAuth data model. + * + */ +@XmlAccessorType(XmlAccessType.FIELD) +@XmlType(name = "oAuth", propOrder = { + "clientId", + "clientSecret" +}) +public class OAuth { + + @XmlElement(required = true) + protected String clientId; + + @XmlElement(required = true) + protected String clientSecret; + + /** + * Gets the value of the clientId property. + * + * @return + * possible object is + * {@link String } + * + */ + public String getClientId() { + return clientId; + } + + /** + * Sets the value of the clientId property. + * + * @param value + * allowed object is + * {@link String } + * + */ + public void setClientId(String value) { + this.clientId = value; + } + + /** + * Gets the value of the clientSecret property. + * + * @return + * possible object is + * {@link String } + * + */ + public String getClientSecret() { + return clientSecret; + } + + /** + * Sets the value of the clientSecret property. + * + * @param value + * allowed object is + * {@link String } + * + */ + public void setClientSecret(String value) { + this.clientSecret = value; + } + +} diff --git a/exposure-engine/provisioning/src/main/java/com/alu/e3/prov/restapi/model/Policy.java b/exposure-engine/provisioning/src/main/java/com/alu/e3/prov/restapi/model/Policy.java new file mode 100644 index 0000000..1988f6e --- /dev/null +++ b/exposure-engine/provisioning/src/main/java/com/alu/e3/prov/restapi/model/Policy.java @@ -0,0 +1,287 @@ +/** + * Copyright © 2012 Alcatel-Lucent. + * + * See the NOTICE file distributed with this work for additional + * information regarding copyright ownership. + * Licensed to you 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 com.alu.e3.prov.restapi.model; + +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.XmlElementWrapper; +import javax.xml.bind.annotation.XmlRootElement; +import javax.xml.bind.annotation.XmlType; + + +/** + * Defines a policy. + */ +@XmlRootElement(name = "policy") +@XmlAccessorType(XmlAccessType.FIELD) +@XmlType(name = "PolicyDataType", propOrder = { + "id", + "apiIds", + "authIds", + "contexts", + "tdrOnLimitReached", + "tdr", + "properties", + "headerTransformations" +}) +public class Policy { + + protected String id; + @XmlElementWrapper(name="apiIds") + @XmlElement(name="apiId") + protected List apiIds; + @XmlElementWrapper(name="authIds") + @XmlElement(name="quotaRLBucket", required = true) + protected List authIds; + @XmlElement(name="context", required = true) + @XmlElementWrapper(name="contexts") + protected List contexts; + protected TypeAttribute tdrOnLimitReached; + protected TdrData tdr; + @XmlElementWrapper(name="properties") + @XmlElement(name="property") + protected List properties; + @XmlElementWrapper(name="headerTransformations", required = false) + @XmlElement(name="headerTransformation", required = false) + protected List headerTransformations; + + public String toString() { + final String comma = ", "; + final String openingBracket = "["; + final String closingBracket = "], "; + + StringBuilder v = new StringBuilder ("id = " + id + ", apiIds = ["); + + if (apiIds != null) + { + for (String id : apiIds) { + v.append(id).append(", "); + } + } + + v.append("], quotaRLBuckets = ["); + + if (authIds != null) + { + for (AuthIdsType id : authIds) { + v.append(id).append(comma); + } + } + + v.append("], env = ["); + + if (contexts != null) + { + for (Context ctx : contexts) { + v.append(openingBracket).append(ctx).append(closingBracket); + } + } + + v.append("], tdr = ").append(tdr); + + return v.toString(); + } + + /** + * Gets the value of the id property. + * + * @return + * possible object is + * {@link String } + * + */ + public String getId() { + return id; + } + + /** + * Sets the value of the id property. + * + * @param value + * allowed object is + * {@link String } + * + */ + public void setId(String value) { + this.id = value; + } + + /** + * Gets the value of the apiIds property. + * + *

+ * This accessor method returns a reference to the live list, + * not a snapshot. Therefore any modification you make to the + * returned list will be present inside the JAXB object. + * This is why there is not a set method for the apiIds property. + * + *

+ * For example, to add a new item, do as follows: + *

+     *    getApiIds().add(newItem);
+     * 
+ * + * + *

+ * Objects of the following type(s) are allowed in the list + * {@link String } + * + * + */ + public List getApiIds() { + if (apiIds == null) { + apiIds = new ArrayList(); + } + return this.apiIds; + } + + /** + * Gets the value of the authIds property. + * + *

+ * This accessor method returns a reference to the live list, + * not a snapshot. Therefore any modification you make to the + * returned list will be present inside the JAXB object. + * This is why there is not a set method for the authIds property. + * + *

+ * For example, to add a new item, do as follows: + *

+     *    getAuthIds().add(newItem);
+     * 
+ * + * + *

+ * Objects of the following type(s) are allowed in the list + * {@link AuthIdsType } + * + * + */ + public List getAuthIds() { + if (authIds == null) { + authIds = new ArrayList(); + } + return this.authIds; + } + + /** + * Gets the value of the contexts property. + * + *

+ * This accessor method returns a reference to the live list, + * not a snapshot. Therefore any modification you make to the + * returned list will be present inside the JAXB object. + * This is why there is not a set method for the contexts property. + * + *

+ * For example, to add a new item, do as follows: + *

+     *    getContexts().add(newItem);
+     * 
+ * + * + *

+ * Objects of the following type(s) are allowed in the list + * {@link Context } + * + * + */ + public List getContexts() { + if (contexts == null) { + contexts = new ArrayList(); + } + return this.contexts; + } + + /** + * Gets the value of the tdrOnLimitReached property. + * + * @return + * possible object is + * {@link String } + * + */ + public String getTdrOnLimitReached() { + if (tdrOnLimitReached == null) + return ""; + return tdrOnLimitReached.getType(); + } + + /** + * Sets the value of the tdrOnLimitReached property. + * + * @param value + * allowed object is + * {@link String } + * + */ + public void setTdrOnLimitReached(String value) { + if (tdrOnLimitReached == null) + tdrOnLimitReached = new TypeAttribute(); + tdrOnLimitReached.setType(value); + } + + /** + * + * @return + */ + public TdrData getTdr() { + return tdr; + } + + /** + * + * @param tdrData + */ + public void setTdr(TdrData tdr) { + this.tdr = tdr; + } + + /** + * + * @return + */ + public List getProperties(){ + if(this.properties == null) + this.properties = new ArrayList(); + return this.properties; + } + + /** + * + * @param value + */ + public void setProperties(List value){ + this.properties = value; + } + + public List getHeaderTransformations(){ + if(this.headerTransformations == null) + this.headerTransformations = new ArrayList(); + return this.headerTransformations; + } + + public void setHeaderTransformations(List value){ + this.headerTransformations = value; + } +} diff --git a/exposure-engine/provisioning/src/main/java/com/alu/e3/prov/restapi/model/PolicyIdsType.java b/exposure-engine/provisioning/src/main/java/com/alu/e3/prov/restapi/model/PolicyIdsType.java new file mode 100644 index 0000000..85644ea --- /dev/null +++ b/exposure-engine/provisioning/src/main/java/com/alu/e3/prov/restapi/model/PolicyIdsType.java @@ -0,0 +1,88 @@ +/** + * Copyright © 2012 Alcatel-Lucent. + * + * See the NOTICE file distributed with this work for additional + * information regarding copyright ownership. + * Licensed to you 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. + */ +// +// This file was generated by the JavaTM Architecture for XML Binding(JAXB) Reference Implementation, vhudson-jaxb-ri-2.2-27 +// See http://java.sun.com/xml/jaxb +// Any modifications to this file will be lost upon recompilation of the source schema. +// Generated on: 2012.03.30 at 11:23:09 AM CEST +// + + +package com.alu.e3.prov.restapi.model; + +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.XmlType; + + +/** + * Holds a list of policies IDs + * + */ +@XmlAccessorType(XmlAccessType.FIELD) +@XmlType(name = "PolicyIdsType", propOrder = { + "id" +}) +public class PolicyIdsType { + + @XmlElement(required = true) + protected List id; + + /** + * Gets the value of the id property. + * + *

+ * This accessor method returns a reference to the live list, + * not a snapshot. Therefore any modification you make to the + * returned list will be present inside the JAXB object. + * This is why there is not a set method for the id property. + * + *

+ * For example, to add a new item, do as follows: + *

+     *    getId().add(newItem);
+     * 
+ * + * + *

+ * Objects of the following type(s) are allowed in the list + * {@link String } + * + * + */ + public List getId() { + if (id == null) { + id = new ArrayList(); + } + return this.id; + } + + @Override + public String toString() { + StringBuilder builder = new StringBuilder(); + builder.append("PolicyIdsType [id="); + builder.append(id); + builder.append("]"); + return builder.toString(); + } + +} diff --git a/exposure-engine/provisioning/src/main/java/com/alu/e3/prov/restapi/model/PolicyResponse.java b/exposure-engine/provisioning/src/main/java/com/alu/e3/prov/restapi/model/PolicyResponse.java new file mode 100644 index 0000000..62f7a53 --- /dev/null +++ b/exposure-engine/provisioning/src/main/java/com/alu/e3/prov/restapi/model/PolicyResponse.java @@ -0,0 +1,56 @@ +/** + * Copyright © 2012 Alcatel-Lucent. + * + * See the NOTICE file distributed with this work for additional + * information regarding copyright ownership. + * Licensed to you 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 com.alu.e3.prov.restapi.model; + +import javax.xml.bind.annotation.XmlRootElement; + +/** + * Policy REST service response model + * + */ +@XmlRootElement(name = "response") +public class PolicyResponse extends BasicResponse { + private Policy policy; + + public PolicyResponse() { + super(); + } + + public PolicyResponse(Policy policy) { + super(); + this.policy = policy; + } + + public PolicyResponse(String status) { + super(status); + } + + public Policy getPolicy() { + return policy; + } + + public void setPolicy(Policy policy) { + this.policy = policy; + } + + public PolicyResponse(String status, String id) { + super(status, id); + } + +} diff --git a/exposure-engine/provisioning/src/main/java/com/alu/e3/prov/restapi/model/ProvisionAuthentication.java b/exposure-engine/provisioning/src/main/java/com/alu/e3/prov/restapi/model/ProvisionAuthentication.java new file mode 100644 index 0000000..0df2ae7 --- /dev/null +++ b/exposure-engine/provisioning/src/main/java/com/alu/e3/prov/restapi/model/ProvisionAuthentication.java @@ -0,0 +1,131 @@ +/** + * Copyright © 2012 Alcatel-Lucent. + * + * See the NOTICE file distributed with this work for additional + * information regarding copyright ownership. + * Licensed to you 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. + */ +// +// This file was generated by the JavaTM Architecture for XML Binding(JAXB) Reference Implementation, vhudson-jaxb-ri-2.2-27 +// See http://java.sun.com/xml/jaxb +// Any modifications to this file will be lost upon recompilation of the source schema. +// Generated on: 2012.03.19 at 02:26:27 PM CET +// + +package com.alu.e3.prov.restapi.model; + +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.XmlElementWrapper; +import javax.xml.bind.annotation.XmlType; + +/** + * Types of supported North Bound authentications when provisioning an API. + * + */ +@XmlAccessorType(XmlAccessType.FIELD) +@XmlType(name = "provisionAuthentication", propOrder = { "auths", "authKey" }) +public class ProvisionAuthentication { + + /** + * List of supported auth types: basic, ipWhiteList, authKey + */ + @XmlElementWrapper(name = "supportedTypes") + @XmlElement(name = "type", required = true) + protected List auths; + + /** + * When authKey is selected this info should be put to provide the authkey key name related to the created API + */ + protected Authkey authKey; + + /** + * Gets the value of the auths property. + * + *

+ * This accessor method returns a reference to the live list, not a + * snapshot. Therefore any modification you make to the returned list will + * be present inside the JAXB object. This is why there is not a + * set method for the auths property. + * + *

+ * For example, to add a new item, do as follows: + * + *

+	 * getAuths().add(newItem);
+	 * 
+ * + * + *

+ * Objects of the following type(s) are allowed in the list {@link AuthType } + * + * + */ + public List getAuths() { + if (auths == null) { + auths = new ArrayList(); + } + return this.auths; + } + + /** + * Gets the value of the authKey property. + * + * @return possible object is {@link Authkey } + * + */ + public Authkey getAuthKey() { + return authKey; + } + + /** + * Sets the value of the authKey property. + * + * @param value + * allowed object is {@link Authkey } + * + */ + public void setAuthKey(Authkey value) { + this.authKey = value; + } + + public boolean getUseBasicAuth() { + return getAuths().contains(AuthType.BASIC); + } + + public boolean getUseAuthKey() { + return getAuths().contains(AuthType.AUTHKEY); + } + + public boolean getUseNoAuth() { + return getAuths().contains(AuthType.NO_AUTH); + } + + public boolean getUseIpWhiteListAuth() { + return getAuths().contains(AuthType.IP_WHITE_LIST); + } + + public boolean getUseOAuth() { + return getAuths().contains(AuthType.OAUTH); + } + public boolean getUseWsse() { + return getAuths().contains(AuthType.WSSE); + } + + +} diff --git a/exposure-engine/provisioning/src/main/java/com/alu/e3/prov/restapi/model/ProxyResponse.java b/exposure-engine/provisioning/src/main/java/com/alu/e3/prov/restapi/model/ProxyResponse.java new file mode 100644 index 0000000..fcbf3c3 --- /dev/null +++ b/exposure-engine/provisioning/src/main/java/com/alu/e3/prov/restapi/model/ProxyResponse.java @@ -0,0 +1,48 @@ +/** + * Copyright © 2012 Alcatel-Lucent. + * + * See the NOTICE file distributed with this work for additional + * information regarding copyright ownership. + * Licensed to you 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 com.alu.e3.prov.restapi.model; + +import javax.xml.bind.annotation.XmlRootElement; + +@XmlRootElement(name = "response") +public class ProxyResponse extends BasicResponse{ + private ForwardProxy proxy; + + public ForwardProxy getProxy() { + return proxy; + } + + public ProxyResponse() { + super(); + } + + public ProxyResponse(String status) { + super(status); + } + + public void setProxy(ForwardProxy proxy) { + this.proxy = proxy; + } + + public ProxyResponse(ForwardProxy proxy) { + super(); + this.proxy = proxy; + } + +} diff --git a/exposure-engine/provisioning/src/main/java/com/alu/e3/prov/restapi/model/ResourceItem.java b/exposure-engine/provisioning/src/main/java/com/alu/e3/prov/restapi/model/ResourceItem.java new file mode 100644 index 0000000..e34764d --- /dev/null +++ b/exposure-engine/provisioning/src/main/java/com/alu/e3/prov/restapi/model/ResourceItem.java @@ -0,0 +1,119 @@ +/** + * Copyright © 2012 Alcatel-Lucent. + * + * See the NOTICE file distributed with this work for additional + * information regarding copyright ownership. + * Licensed to you 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 com.alu.e3.prov.restapi.model; + +import javax.xml.bind.annotation.XmlAccessType; +import javax.xml.bind.annotation.XmlAccessorType; +import javax.xml.bind.annotation.XmlElement; +import javax.xml.bind.annotation.XmlType; +import javax.xml.bind.annotation.adapters.XmlJavaTypeAdapter; + +import com.alu.e3.prov.restapi.util.Base64Adapter; + + +/** +* This element holds the XSD/WSDL file meta-data: name, content, is main file. + * + */ +@XmlAccessorType(XmlAccessType.FIELD) +@XmlType(name = "ResourceItemType", propOrder = { + +}) +public class ResourceItem { + + /** + * The filename of the resource + */ + @XmlElement(required = true) + protected String name; + /** + * The content of the xsd/wsdl file + */ + @XmlElement(required = true) + @XmlJavaTypeAdapter(value=Base64Adapter.class) + protected String grammar; + /** + * Specifies if this resource is the main. This done for imports/includes. + * Only one main resource is allowed. + */ + protected boolean isMain; + + /** + * Gets the value of the name property. + * + * @return + * possible object is + * {@link String } + * + */ + public String getName() { + return name; + } + + /** + * Sets the value of the name property. + * + * @param value + * allowed object is + * {@link String } + * + */ + public void setName(String value) { + this.name = value; + } + + /** + * Gets the value of the grammar property. + * + * @return + * possible object is + * byte[] + */ + public String getGrammar() { + return grammar; + } + + /** + * Sets the value of the grammar property. + * + * @param value + * allowed object is + * byte[] + */ + public void setGrammar(String value) { + this.grammar = value; + } + + /** + * Gets the value of the isMain property. + * + */ + public boolean isIsMain() { + return isMain; + } + + /** + * Sets the value of the isMain property. + * + */ + public void setIsMain(boolean value) { + this.isMain = value; + } + +} diff --git a/exposure-engine/provisioning/src/main/java/com/alu/e3/prov/restapi/model/SSLCRL.java b/exposure-engine/provisioning/src/main/java/com/alu/e3/prov/restapi/model/SSLCRL.java new file mode 100644 index 0000000..60830a7 --- /dev/null +++ b/exposure-engine/provisioning/src/main/java/com/alu/e3/prov/restapi/model/SSLCRL.java @@ -0,0 +1,97 @@ +/** + * Copyright © 2012 Alcatel-Lucent. + * + * See the NOTICE file distributed with this work for additional + * information regarding copyright ownership. + * Licensed to you 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 com.alu.e3.prov.restapi.model; + + +import javax.xml.bind.annotation.XmlAccessType; +import javax.xml.bind.annotation.XmlAccessorType; +import javax.xml.bind.annotation.XmlAttribute; +import javax.xml.bind.annotation.XmlElement; +import javax.xml.bind.annotation.XmlID; +import javax.xml.bind.annotation.XmlRootElement; +import javax.xml.bind.annotation.XmlSchemaType; +import javax.xml.bind.annotation.XmlType; +import javax.xml.bind.annotation.adapters.CollapsedStringAdapter; +import javax.xml.bind.annotation.adapters.XmlJavaTypeAdapter; + + +/** + * The Auth detail used for NB authentication in E3 subsystem. + *

Supported types are: Basic, AuthKey, IP White List + * + */ +@XmlRootElement(name="crl") +@XmlAccessorType(XmlAccessType.FIELD) +@XmlType(name = "crl", propOrder = { + "id", + "content", + "displayName" +}) +public class SSLCRL { + + /** + * The key ID. Could be provided. + */ + @XmlJavaTypeAdapter(CollapsedStringAdapter.class) + @XmlID + @XmlSchemaType(name = "ID") + @XmlAttribute + protected String id; + + /** + * The crl content + */ + @XmlElement + protected String content; + + /** + * CRL display name for administration purpose. + * If not provided, will be set with CRL's Issuer. + */ + @XmlElement + protected String displayName; + + public String getId() { + return id; + } + + + public void setId(String id) { + this.id = id; + } + + + public String getContent() { + return content; + } + + + public void setContent(String certContent) { + this.content = certContent; + } + + public String getDisplayName() { + return displayName; + } + + public void setDisplayName(String displayName) { + this.displayName = displayName; + } + +} diff --git a/exposure-engine/provisioning/src/main/java/com/alu/e3/prov/restapi/model/SSLCRLResponse.java b/exposure-engine/provisioning/src/main/java/com/alu/e3/prov/restapi/model/SSLCRLResponse.java new file mode 100644 index 0000000..babde0f --- /dev/null +++ b/exposure-engine/provisioning/src/main/java/com/alu/e3/prov/restapi/model/SSLCRLResponse.java @@ -0,0 +1,46 @@ +/** + * Copyright © 2012 Alcatel-Lucent. + * + * See the NOTICE file distributed with this work for additional + * information regarding copyright ownership. + * Licensed to you 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 com.alu.e3.prov.restapi.model; + +import javax.xml.bind.annotation.XmlRootElement; + +/** + * Wrapper object to return SSLCerts in REST API + * + */ +@XmlRootElement(name = "response") +public class SSLCRLResponse extends BasicResponse { + protected SSLCRL crl; + + public SSLCRLResponse() { + super(); + } + + public SSLCRLResponse(String status) { + super(status); + } + + public SSLCRL getCRL() { + return crl; + } + + public void setCRL(SSLCRL k) { + this.crl = k; + } +} diff --git a/exposure-engine/provisioning/src/main/java/com/alu/e3/prov/restapi/model/SSLCSR.java b/exposure-engine/provisioning/src/main/java/com/alu/e3/prov/restapi/model/SSLCSR.java new file mode 100644 index 0000000..37b2f5e --- /dev/null +++ b/exposure-engine/provisioning/src/main/java/com/alu/e3/prov/restapi/model/SSLCSR.java @@ -0,0 +1,79 @@ +/** + * Copyright © 2012 Alcatel-Lucent. + * + * See the NOTICE file distributed with this work for additional + * information regarding copyright ownership. + * Licensed to you 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 com.alu.e3.prov.restapi.model; + +import javax.xml.bind.annotation.XmlAccessType; +import javax.xml.bind.annotation.XmlAccessorType; +import javax.xml.bind.annotation.XmlAttribute; +import javax.xml.bind.annotation.XmlElement; +import javax.xml.bind.annotation.XmlID; +import javax.xml.bind.annotation.XmlRootElement; +import javax.xml.bind.annotation.XmlSchemaType; +import javax.xml.bind.annotation.XmlType; +import javax.xml.bind.annotation.adapters.CollapsedStringAdapter; +import javax.xml.bind.annotation.adapters.XmlJavaTypeAdapter; + + +/** + * The Certificate Signing Request data (will be generated automatically) + * + */ +@XmlRootElement +@XmlAccessorType(XmlAccessType.FIELD) +@XmlType(name = "sslcsr", propOrder = { + "id", + "csrContent" +}) +public class SSLCSR { + + /** + * The key ID. Could be provided. + */ + @XmlJavaTypeAdapter(CollapsedStringAdapter.class) + @XmlID + @XmlSchemaType(name = "ID") + @XmlAttribute + protected String id; + + /** + * The CSR content + */ + @XmlElement(required = true) + protected String csrContent; + + + public String getId() { + return id; + } + + + public void setId(String id) { + this.id = id; + } + + public String getCertContent() { + return csrContent; + } + + + public void setCertContent(String certContent) { + this.csrContent = certContent; + } + +} diff --git a/exposure-engine/provisioning/src/main/java/com/alu/e3/prov/restapi/model/SSLCert.java b/exposure-engine/provisioning/src/main/java/com/alu/e3/prov/restapi/model/SSLCert.java new file mode 100644 index 0000000..bab7acb --- /dev/null +++ b/exposure-engine/provisioning/src/main/java/com/alu/e3/prov/restapi/model/SSLCert.java @@ -0,0 +1,125 @@ +/** + * Copyright © 2012 Alcatel-Lucent. + * + * See the NOTICE file distributed with this work for additional + * information regarding copyright ownership. + * Licensed to you 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 com.alu.e3.prov.restapi.model; + +import javax.xml.bind.JAXBContext; +import javax.xml.bind.Marshaller; +import javax.xml.bind.annotation.XmlAccessType; +import javax.xml.bind.annotation.XmlAccessorType; +import javax.xml.bind.annotation.XmlAttribute; +import javax.xml.bind.annotation.XmlElement; +import javax.xml.bind.annotation.XmlID; +import javax.xml.bind.annotation.XmlRootElement; +import javax.xml.bind.annotation.XmlSchemaType; +import javax.xml.bind.annotation.XmlTransient; +import javax.xml.bind.annotation.XmlType; +import javax.xml.bind.annotation.adapters.CollapsedStringAdapter; +import javax.xml.bind.annotation.adapters.XmlJavaTypeAdapter; + + +/** + * The Auth detail used for NB authentication in E3 subsystem. + *

Supported types are: Basic, AuthKey, IP White List + * + */ +@XmlRootElement(name="cert") +@XmlAccessorType(XmlAccessType.FIELD) +@XmlType(name = "cert", propOrder = { + "id", + "content", + "displayName" +}) +public class SSLCert { + + /** + * The key ID. Could be provided. + */ + @XmlJavaTypeAdapter(CollapsedStringAdapter.class) + @XmlID + @XmlSchemaType(name = "ID") + @XmlAttribute + protected String id; + + @XmlTransient + protected String keyId; + + /** + * The cert content + */ + @XmlElement + protected String content; + + /** + * The cert content + */ + @XmlElement + protected String displayName; + + public String getId() { + return id; + } + + + public void setId(String id) { + this.id = id; + } + + + public String getKeyId() { + return keyId; + } + + + public void setKeyId(String keyId) { + this.keyId = keyId; + } + + + public String getContent() { + return content; + } + + + public void setContent(String certContent) { + this.content = certContent; + } + + public String getDisplayName() { + return displayName; + } + + public void setDisplayName(String displayName) { + this.displayName = displayName; + } + + + public static void main(String[] args) throws Exception{ + JAXBContext context = JAXBContext.newInstance(SSLCert.class); + Marshaller marshaller = context.createMarshaller(); + marshaller.setProperty(Marshaller.JAXB_FORMATTED_OUTPUT, true); + SSLCert cert = new SSLCert(); + + cert.setContent("abcdefgjik;,mop"); + cert.setId("blah"); + cert.setKeyId("keyidkeyid"); + + marshaller.marshal(cert, System.out); + } + +} diff --git a/exposure-engine/provisioning/src/main/java/com/alu/e3/prov/restapi/model/SSLCertResponse.java b/exposure-engine/provisioning/src/main/java/com/alu/e3/prov/restapi/model/SSLCertResponse.java new file mode 100644 index 0000000..c5c6ebd --- /dev/null +++ b/exposure-engine/provisioning/src/main/java/com/alu/e3/prov/restapi/model/SSLCertResponse.java @@ -0,0 +1,46 @@ +/** + * Copyright © 2012 Alcatel-Lucent. + * + * See the NOTICE file distributed with this work for additional + * information regarding copyright ownership. + * Licensed to you 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 com.alu.e3.prov.restapi.model; + +import javax.xml.bind.annotation.XmlRootElement; + +/** + * Wrapper object to return SSLCerts in REST API + * + */ +@XmlRootElement(name = "response") +public class SSLCertResponse extends BasicResponse { + protected SSLCert cert; + + public SSLCertResponse() { + super(); + } + + public SSLCertResponse(String status) { + super(status); + } + + public SSLCert getCert() { + return cert; + } + + public void setCert(SSLCert k) { + this.cert = k; + } +} diff --git a/exposure-engine/provisioning/src/main/java/com/alu/e3/prov/restapi/model/SSLKey.java b/exposure-engine/provisioning/src/main/java/com/alu/e3/prov/restapi/model/SSLKey.java new file mode 100644 index 0000000..c9c061e --- /dev/null +++ b/exposure-engine/provisioning/src/main/java/com/alu/e3/prov/restapi/model/SSLKey.java @@ -0,0 +1,149 @@ +/** + * Copyright © 2012 Alcatel-Lucent. + * + * See the NOTICE file distributed with this work for additional + * information regarding copyright ownership. + * Licensed to you 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 com.alu.e3.prov.restapi.model; + +import javax.xml.bind.JAXBContext; +import javax.xml.bind.Marshaller; +import javax.xml.bind.annotation.XmlAccessType; +import javax.xml.bind.annotation.XmlAccessorType; +import javax.xml.bind.annotation.XmlAttribute; +import javax.xml.bind.annotation.XmlElement; +import javax.xml.bind.annotation.XmlID; +import javax.xml.bind.annotation.XmlRootElement; +import javax.xml.bind.annotation.XmlSchemaType; +import javax.xml.bind.annotation.XmlType; +import javax.xml.bind.annotation.adapters.CollapsedStringAdapter; +import javax.xml.bind.annotation.adapters.XmlJavaTypeAdapter; + + +/** + * The SSLKey object + * + */ +@XmlRootElement(name="key") +@XmlAccessorType(XmlAccessType.FIELD) +@XmlType(name = "key", propOrder = { + "id", + "activeCertId", + "keyPassphrase", + "content", + "displayName", + "type" + }) +public class SSLKey { + + /** + * The key ID. Could be provided. + */ + @XmlJavaTypeAdapter(CollapsedStringAdapter.class) + @XmlID + @XmlSchemaType(name = "ID") + @XmlAttribute + protected String id; + + /** + * The key's currently active certificate + */ + @XmlElement + protected String activeCertId; + + /** + * The key's passphrase + */ + @XmlElement + protected String keyPassphrase; + + /** + * The key content + */ + @XmlElement + protected String content; + + /** + * The key's display name + */ + @XmlElement + protected String displayName; + + /** + * The key type. This is essentially metadata and not really useful + */ + @XmlElement + protected String type; + + public String getId() { + return id; + } + + public void setId(String id) { + this.id = id; + } + + public String getContent() { + return content; + } + + public void setContent(String keyContent) { + this.content = keyContent; + } + + public static void main(String [] args) throws Exception{ + JAXBContext context = JAXBContext.newInstance(SSLKey.class); + Marshaller marshaller = context.createMarshaller(); + marshaller.setProperty(Marshaller.JAXB_FORMATTED_OUTPUT, true); + SSLKey key = new SSLKey(); + key.setId("1234"); + key.setContent("asdfasdfasdfasdfasdf"); + key.setActiveCertId("1234"); + + marshaller.marshal(key, System.out); + } + + public String getActiveCertId() { + return activeCertId; + } + + public void setActiveCertId(String activeCertId) { + this.activeCertId = activeCertId; + } + + public void setKeyPassphrase(String keyPassphrase) { + this.keyPassphrase = keyPassphrase; + } + + public String getKeyPassphrase() { + return keyPassphrase; + } + + public String getDisplayName() { + return displayName; + } + + public void setDisplayName(String displayname) { + this.displayName = displayname; + } + + public String getType() { + return type; + } + + public void setType(String type) { + this.type = type; + } +} diff --git a/exposure-engine/provisioning/src/main/java/com/alu/e3/prov/restapi/model/SSLKeyResponse.java b/exposure-engine/provisioning/src/main/java/com/alu/e3/prov/restapi/model/SSLKeyResponse.java new file mode 100644 index 0000000..1fecacc --- /dev/null +++ b/exposure-engine/provisioning/src/main/java/com/alu/e3/prov/restapi/model/SSLKeyResponse.java @@ -0,0 +1,46 @@ +/** + * Copyright © 2012 Alcatel-Lucent. + * + * See the NOTICE file distributed with this work for additional + * information regarding copyright ownership. + * Licensed to you 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 com.alu.e3.prov.restapi.model; + +import javax.xml.bind.annotation.XmlRootElement; + +/** + * Wrapper object to return SSLKeys in REST API + * + */ +@XmlRootElement(name = "response") +public class SSLKeyResponse extends BasicResponse { + protected SSLKey key; + + public SSLKeyResponse() { + super(); + } + + public SSLKeyResponse(String status) { + super(status); + } + + public SSLKey getKey() { + return key; + } + + public void setKey(SSLKey k) { + this.key = k; + } +} diff --git a/exposure-engine/provisioning/src/main/java/com/alu/e3/prov/restapi/model/SchemaValidationEnum.java b/exposure-engine/provisioning/src/main/java/com/alu/e3/prov/restapi/model/SchemaValidationEnum.java new file mode 100644 index 0000000..f3151e1 --- /dev/null +++ b/exposure-engine/provisioning/src/main/java/com/alu/e3/prov/restapi/model/SchemaValidationEnum.java @@ -0,0 +1,76 @@ +/** + * Copyright © 2012 Alcatel-Lucent. + * + * See the NOTICE file distributed with this work for additional + * information regarding copyright ownership. + * Licensed to you 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. + */ +// +// This file was generated by the JavaTM Architecture for XML Binding(JAXB) Reference Implementation, vhudson-jaxb-ri-2.2-27 +// See http://java.sun.com/xml/jaxb +// Any modifications to this file will be lost upon recompilation of the source schema. +// Generated on: 2012.05.24 at 03:06:32 PM CEST +// + + +package com.alu.e3.prov.restapi.model; + +import javax.xml.bind.annotation.XmlEnum; +import javax.xml.bind.annotation.XmlEnumValue; +import javax.xml.bind.annotation.XmlType; + + +/** + *

Java class for SchemaValidationTypeEnum. + * + *

The following schema fragment specifies the expected content contained within this class. + *

+ *

+ * <simpleType name="SchemaValidationTypeEnum">
+ *   <restriction base="{http://www.w3.org/2001/XMLSchema}string">
+ *     <enumeration value="wsdl"/>
+ *     <enumeration value="xsd"/>
+ *   </restriction>
+ * </simpleType>
+ * 
+ * + */ +@XmlType(name = "SchemaValidationTypeEnum") +@XmlEnum +public enum SchemaValidationEnum { + + @XmlEnumValue("wsdl") + WSDL("wsdl"), + @XmlEnumValue("xsd") + XSD("xsd"); + private final String value; + + SchemaValidationEnum(String v) { + value = v; + } + + public String value() { + return value; + } + + public static SchemaValidationEnum fromValue(String v) { + for (SchemaValidationEnum c: SchemaValidationEnum.values()) { + if (c.value.equals(v)) { + return c; + } + } + throw new IllegalArgumentException(v); + } + +} diff --git a/exposure-engine/provisioning/src/main/java/com/alu/e3/prov/restapi/model/SoapVersionEnum.java b/exposure-engine/provisioning/src/main/java/com/alu/e3/prov/restapi/model/SoapVersionEnum.java new file mode 100644 index 0000000..572b6d9 --- /dev/null +++ b/exposure-engine/provisioning/src/main/java/com/alu/e3/prov/restapi/model/SoapVersionEnum.java @@ -0,0 +1,51 @@ +/** + * Copyright © 2012 Alcatel-Lucent. + * + * See the NOTICE file distributed with this work for additional + * information regarding copyright ownership. + * Licensed to you 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 com.alu.e3.prov.restapi.model; + +import javax.xml.bind.annotation.XmlEnum; +import javax.xml.bind.annotation.XmlEnumValue; +import javax.xml.bind.annotation.XmlType; + +@XmlType(name = "SoapVersionEnum") +@XmlEnum +public enum SoapVersionEnum { + @XmlEnumValue("1.1") + SOAP11("1.1"), + @XmlEnumValue("1.2") + SOAP12("1.2"); + private final String value; + + SoapVersionEnum(String v) { + value = v; + } + + public String value() { + return value; + } + + public static SoapVersionEnum fromValue(String v) { + for (SoapVersionEnum c : SoapVersionEnum.values()) { + if (c.value.equals(v)) { + return c; + } + } + throw new IllegalArgumentException(v); + } + +} diff --git a/exposure-engine/provisioning/src/main/java/com/alu/e3/prov/restapi/model/StaticTdr.java b/exposure-engine/provisioning/src/main/java/com/alu/e3/prov/restapi/model/StaticTdr.java new file mode 100644 index 0000000..2180a69 --- /dev/null +++ b/exposure-engine/provisioning/src/main/java/com/alu/e3/prov/restapi/model/StaticTdr.java @@ -0,0 +1,136 @@ +/** + * Copyright © 2012 Alcatel-Lucent. + * + * See the NOTICE file distributed with this work for additional + * information regarding copyright ownership. + * Licensed to you 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 com.alu.e3.prov.restapi.model; + +import javax.xml.bind.annotation.XmlAccessType; +import javax.xml.bind.annotation.XmlAccessorType; +import javax.xml.bind.annotation.XmlAttribute; +import javax.xml.bind.annotation.XmlType; + + +/** + * + */ +@XmlAccessorType(XmlAccessType.FIELD) +@XmlType(name = "staticTDR", propOrder = { + "types" +}) +public class StaticTdr { + + protected TdrType types; + @XmlAttribute(name = "tdrPropName", required = true) + protected String tdrPropName; + @XmlAttribute(name = "value", required = false) + protected String value; + @XmlAttribute(name = "property", required = false) + protected String propertyName; + + @Override + public String toString() { + String v = "types = " + types + ", "; + + v += "tdrPropName = " + tdrPropName + ", "; + + v += "value = " + value + ", "; + v += "property = " + propertyName + ", "; + + return v; + } + + /** + * Gets the value of the types property. + * + * @return + * possible object is + * {@link TdrType } + * + */ + public TdrType getTypes() { + return types; + } + + /** + * Sets the value of the types property. + * + * @param value + * allowed object is + * {@link TdrType } + * + */ + public void setTypes(TdrType value) { + this.types = value; + } + + /** + * Gets the value of the tdrPropName property. + * + * @return + * possible object is + * {@link String } + * + */ + public String getTdrPropName() { + return tdrPropName; + } + + /** + * Sets the value of the tdrPropName property. + * + * @param value + * allowed object is + * {@link String } + * + */ + public void setTdrPropName(String value) { + this.tdrPropName = value; + } + + /** + * Gets the value of the value property. + * + * @return + * possible object is + * {@link String } + * + */ + public String getValue() { + return value; + } + + /** + * Sets the value of the value property. + * + * @param value + * allowed object is + * {@link String } + * + */ + public void setValue(String value) { + this.value = value; + } + + public String getPropertyName() { + return propertyName; + } + + public void setPropertyName(String property) { + this.propertyName = property; + } + +} diff --git a/exposure-engine/provisioning/src/main/java/com/alu/e3/prov/restapi/model/Status.java b/exposure-engine/provisioning/src/main/java/com/alu/e3/prov/restapi/model/Status.java new file mode 100644 index 0000000..0dd44b7 --- /dev/null +++ b/exposure-engine/provisioning/src/main/java/com/alu/e3/prov/restapi/model/Status.java @@ -0,0 +1,66 @@ +/** + * Copyright © 2012 Alcatel-Lucent. + * + * See the NOTICE file distributed with this work for additional + * information regarding copyright ownership. + * Licensed to you 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. + */ +// +// This file was generated by the JavaTM Architecture for XML Binding(JAXB) Reference Implementation, vhudson-jaxb-ri-2.2-27 +// See http://java.sun.com/xml/jaxb +// Any modifications to this file will be lost upon recompilation of the source schema. +// Generated on: 2012.03.19 at 04:04:47 PM CET +// + + +package com.alu.e3.prov.restapi.model; + +import javax.xml.bind.annotation.XmlEnum; +import javax.xml.bind.annotation.XmlEnumValue; +import javax.xml.bind.annotation.XmlType; + + +/** + * Enumeration for allowed status values + */ +@XmlType(name = "status", namespace = "") +@XmlEnum +public enum Status { + + @XmlEnumValue("active") + ACTIVE("active"), + @XmlEnumValue("inactive") + INACTIVE("inactive"), + @XmlEnumValue("pending") + PENDING("pending"); + private final String value; + + Status(String v) { + value = v; + } + + public String value() { + return value; + } + + public static Status fromValue(String v) { + for (Status c: Status.values()) { + if (c.value.equals(v)) { + return c; + } + } + throw new IllegalArgumentException(v); + } + +} diff --git a/exposure-engine/provisioning/src/main/java/com/alu/e3/prov/restapi/model/SubscriptionStep.java b/exposure-engine/provisioning/src/main/java/com/alu/e3/prov/restapi/model/SubscriptionStep.java new file mode 100644 index 0000000..4561035 --- /dev/null +++ b/exposure-engine/provisioning/src/main/java/com/alu/e3/prov/restapi/model/SubscriptionStep.java @@ -0,0 +1,52 @@ +/** + * Copyright © 2012 Alcatel-Lucent. + * + * See the NOTICE file distributed with this work for additional + * information regarding copyright ownership. + * Licensed to you 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 com.alu.e3.prov.restapi.model; + +import javax.xml.bind.annotation.XmlEnum; +import javax.xml.bind.annotation.XmlEnumValue; +import javax.xml.bind.annotation.XmlType; + +@XmlType(name = "subscriptionStep") +@XmlEnum +public enum SubscriptionStep { + + @XmlEnumValue("Subscription") + SUBSCRIPTION("Subscription"), + @XmlEnumValue("Notification") + NOTIFICATION("Notification"); + + private final String value; + + SubscriptionStep(String v) { + value = v; + } + + public String value() { + return value; + } + + public static SubscriptionStep fromValue(String v) { + for (SubscriptionStep c: SubscriptionStep.values()) { + if (c.value.equals(v)) { + return c; + } + } + throw new IllegalArgumentException(v); + } +} diff --git a/exposure-engine/provisioning/src/main/java/com/alu/e3/prov/restapi/model/TLSMode.java b/exposure-engine/provisioning/src/main/java/com/alu/e3/prov/restapi/model/TLSMode.java new file mode 100644 index 0000000..887332d --- /dev/null +++ b/exposure-engine/provisioning/src/main/java/com/alu/e3/prov/restapi/model/TLSMode.java @@ -0,0 +1,57 @@ +/** + * Copyright © 2012 Alcatel-Lucent. + * + * See the NOTICE file distributed with this work for additional + * information regarding copyright ownership. + * Licensed to you 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 com.alu.e3.prov.restapi.model; + +import javax.xml.bind.annotation.XmlEnum; +import javax.xml.bind.annotation.XmlEnumValue; +import javax.xml.bind.annotation.XmlType; + + +/** + * Enumeration for allowed TLS Mode values + */ +@XmlType(name = "tlsMode", namespace = "") +@XmlEnum +public enum TLSMode { + + @XmlEnumValue("1Way") + ONE_WAY("1Way"), + @XmlEnumValue("2Way") + TWO_WAY("2Way"); + private final String value; + + TLSMode(String v) { + value = v; + } + + public String value() { + return value; + } + + public static TLSMode fromValue(String v) { + for (TLSMode c: TLSMode.values()) { + if (c.value.equals(v)) { + return c; + } + } + throw new IllegalArgumentException(v); + } + +} diff --git a/exposure-engine/provisioning/src/main/java/com/alu/e3/prov/restapi/model/TargetHealthCheck.java b/exposure-engine/provisioning/src/main/java/com/alu/e3/prov/restapi/model/TargetHealthCheck.java new file mode 100644 index 0000000..1cfdfe2 --- /dev/null +++ b/exposure-engine/provisioning/src/main/java/com/alu/e3/prov/restapi/model/TargetHealthCheck.java @@ -0,0 +1,54 @@ +/** + * Copyright © 2012 Alcatel-Lucent. + * + * See the NOTICE file distributed with this work for additional + * information regarding copyright ownership. + * Licensed to you 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 com.alu.e3.prov.restapi.model; + +import javax.xml.bind.annotation.XmlAccessType; +import javax.xml.bind.annotation.XmlAccessorType; +import javax.xml.bind.annotation.XmlAttribute; +import javax.xml.bind.annotation.XmlType; + + +/** + * The API target host model + * + */ +@XmlAccessorType(XmlAccessType.FIELD) +@XmlType(name = "targetHealthCheck ", propOrder = {}) +public class TargetHealthCheck { + + @XmlAttribute(name = "type", required = false) + protected String type; + + /** + * @return the type of Target Heath Check + */ + public String getType() { + return type; + } + + /** + * @param type the type of Target Heath Check to set + */ + public void setType(String type) { + this.type = type; + } + + +} diff --git a/exposure-engine/provisioning/src/main/java/com/alu/e3/prov/restapi/model/TargetHost.java b/exposure-engine/provisioning/src/main/java/com/alu/e3/prov/restapi/model/TargetHost.java new file mode 100644 index 0000000..559a97b --- /dev/null +++ b/exposure-engine/provisioning/src/main/java/com/alu/e3/prov/restapi/model/TargetHost.java @@ -0,0 +1,224 @@ +/** + * Copyright © 2012 Alcatel-Lucent. + * + * See the NOTICE file distributed with this work for additional + * information regarding copyright ownership. + * Licensed to you 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. + */ +// +// This file was generated by the JavaTM Architecture for XML Binding(JAXB) Reference Implementation, vhudson-jaxb-ri-2.2-27 +// See http://java.sun.com/xml/jaxb +// Any modifications to this file will be lost upon recompilation of the source schema. +// Generated on: 2012.03.19 at 02:26:27 PM CET +// + + +package com.alu.e3.prov.restapi.model; + +import java.net.MalformedURLException; +import java.net.URL; + +import javax.xml.bind.annotation.XmlAccessType; +import javax.xml.bind.annotation.XmlAccessorType; +import javax.xml.bind.annotation.XmlElement; +import javax.xml.bind.annotation.XmlType; + + +/** + * The API target host model + * + */ +@XmlAccessorType(XmlAccessType.FIELD) +@XmlType(name = "targetHost", propOrder = { + "url", + "site", + "authentication", + "connectionParameters" +}) +public class TargetHost { + /** + * The URL to the target host + */ + @XmlElement(required = true) + protected String url; + + /** + * The site destination of this target host + */ + @XmlElement(required = false) + protected String site; + + /** + * The authentication (South Bound) data to access the target host + */ + protected Authentication authentication; + + /** + * The connection parameters for this target host. + */ + @XmlElement(required = false) + protected ConnectionParameters connectionParameters; + + + /** + * Gets the value of the url property. + * + * @return + * possible object is + * {@link String } + * + */ + public String getUrl() { + return url; + } + + /** + * Sets the value of the url property. + * + * @param value + * allowed object is + * {@link String } + * + */ + public void setUrl(String value) { + this.url = value; + } + + /** + * Gets the value of the site property. + * + * @return + * possible object is + * {@link String } + * + */ + public String getSite() { + return site; + } + + + /** + * Sets the value of the site property. + * + * @param value + * allowed object is + * {@link String } + * + */ + public void setSite(String site) { + this.site = site; + } + + /** + * Gets the value of the authentication property. + * + * @return + * possible object is + * {@link Authentication } + * + */ + public Authentication getAuthentication() { + return authentication; + } + + /** + * Sets the value of the authentication property. + * + * @param value + * allowed object is + * {@link Authentication } + * + */ + public void setAuthentication(Authentication value) { + this.authentication = value; + } + + /** + * Gets the value of the connectionParameters property. + * + * @return + * possible object is + * {@link ConnectionParameters } + * + */ + public ConnectionParameters getConnectionParameters() { + return connectionParameters; + } + + /** + * Sets the value of the connectionParameters property. + * + * @param value + * allowed object is + * {@link ConnectionParameters } + * + */ + public void setConnectionParameters(ConnectionParameters connectionParameters) { + this.connectionParameters = connectionParameters; + } + + + public String getUrlParams() { + String params = ""; + + if (url!=null && url.contains("?")) { + params = url.split("\\?")[1]; + // & => & conversion + if (params.contains("&") && !params.contains("&")) { + params = params.replaceAll("&", "&"); + } + } + + return params; + } + + /** + * Gets the url without all params + * + * @return possible object is {@link String } + * + */ + public String getCamelUrlWithoutParams() { + String urlWithoutParams; + urlWithoutParams = url.contains("?") ? url.substring(0, url.indexOf("?")) : url; + urlWithoutParams = urlWithoutParams.replace("://", "4:"); + return urlWithoutParams; + } + + /** + * Gets the url without all params + * + * @return possible object is {@link String } + * + */ + public String getHostPort() { + URL url; + try { + url = new URL(this.url); + } catch (MalformedURLException e) { + // TODO Auto-generated catch block + e.printStackTrace(); + throw new RuntimeException("URL target wrong formatted:"+this.url, e); + } + + String hostPort; + if (url.getPort() < 0) + hostPort = url.getHost(); + else + hostPort = url.getHost() + ":" + url.getPort(); + + return hostPort; + } + +} diff --git a/exposure-engine/provisioning/src/main/java/com/alu/e3/prov/restapi/model/TdrData.java b/exposure-engine/provisioning/src/main/java/com/alu/e3/prov/restapi/model/TdrData.java new file mode 100644 index 0000000..a6b28df --- /dev/null +++ b/exposure-engine/provisioning/src/main/java/com/alu/e3/prov/restapi/model/TdrData.java @@ -0,0 +1,120 @@ +/** + * Copyright © 2012 Alcatel-Lucent. + * + * See the NOTICE file distributed with this work for additional + * information regarding copyright ownership. + * Licensed to you 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 com.alu.e3.prov.restapi.model; + +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.XmlType; + +@XmlAccessorType(XmlAccessType.FIELD) +@XmlType(name = "tdr", propOrder = { + "_static", + "dynamic" +}) +public class TdrData { + + @XmlElement(name = "static") + protected List _static; + protected List dynamic; + + public String toString() { + final String comma = ", "; + + StringBuilder v = new StringBuilder("TDRstatic ["); + + for (StaticTdr stdr : _static) + { + v.append(stdr).append(comma); + } + + v.append("], TDRdynamic ["); + + for (DynamicTdr dtdr : dynamic) + { + v.append(dtdr).append(comma); + } + + v.append("]"); + + return v.toString(); + } + + /** + * Gets the value of the static property. + * + *

+ * This accessor method returns a reference to the live list, + * not a snapshot. Therefore any modification you make to the + * returned list will be present inside the JAXB object. + * This is why there is not a set method for the static property. + * + *

+ * For example, to add a new item, do as follows: + *

+     *    getStatic().add(newItem);
+     * 
+ * + * + *

+ * Objects of the following type(s) are allowed in the list + * {@link StaticTdr } + * + * + */ + public List getStatic() { + if (_static == null) { + _static = new ArrayList(); + } + return this._static; + } + + /** + * Gets the value of the dynamic property. + * + *

+ * This accessor method returns a reference to the live list, + * not a snapshot. Therefore any modification you make to the + * returned list will be present inside the JAXB object. + * This is why there is not a set method for the dynamic property. + * + *

+ * For example, to add a new item, do as follows: + *

+     *    getDynamic().add(newItem);
+     * 
+ * + * + *

+ * Objects of the following type(s) are allowed in the list + * {@link DynamicTdr } + * + * + */ + public List getDynamic() { + if (dynamic == null) { + dynamic = new ArrayList(); + } + return this.dynamic; + } + +} diff --git a/exposure-engine/provisioning/src/main/java/com/alu/e3/prov/restapi/model/TdrEnabled.java b/exposure-engine/provisioning/src/main/java/com/alu/e3/prov/restapi/model/TdrEnabled.java new file mode 100644 index 0000000..bf5d1f2 --- /dev/null +++ b/exposure-engine/provisioning/src/main/java/com/alu/e3/prov/restapi/model/TdrEnabled.java @@ -0,0 +1,71 @@ +/** + * Copyright © 2012 Alcatel-Lucent. + * + * See the NOTICE file distributed with this work for additional + * information regarding copyright ownership. + * Licensed to you 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. + */ +// +// This file was generated by the JavaTM Architecture for XML Binding(JAXB) Reference Implementation, vhudson-jaxb-ri-2.2-27 +// See http://java.sun.com/xml/jaxb +// Any modifications to this file will be lost upon recompilation of the source schema. +// Generated on: 2012.03.19 at 02:26:27 PM CET +// + + +package com.alu.e3.prov.restapi.model; + +import javax.xml.bind.annotation.XmlAccessType; +import javax.xml.bind.annotation.XmlAccessorType; +import javax.xml.bind.annotation.XmlElement; +import javax.xml.bind.annotation.XmlType; + + +/** + * TDR enabled flag. + */ +@XmlAccessorType(XmlAccessType.FIELD) +@XmlType(name = "tdrEnabled", propOrder = { + "enabled" +}) +public class TdrEnabled { + + @XmlElement(required = true) + protected String enabled = "true"; + + /** + * Gets the value of the enabled property. + * + * @return + * possible object is + * {@link String } + * + */ + public String getEnabled() { + return enabled; + } + + /** + * Sets the value of the enabled property. + * + * @param value + * allowed object is + * {@link String } + * + */ + public void setEnabled(String value) { + this.enabled = value; + } + +} diff --git a/exposure-engine/provisioning/src/main/java/com/alu/e3/prov/restapi/model/TdrType.java b/exposure-engine/provisioning/src/main/java/com/alu/e3/prov/restapi/model/TdrType.java new file mode 100644 index 0000000..af5ef8e --- /dev/null +++ b/exposure-engine/provisioning/src/main/java/com/alu/e3/prov/restapi/model/TdrType.java @@ -0,0 +1,82 @@ +/** + * Copyright © 2012 Alcatel-Lucent. + * + * See the NOTICE file distributed with this work for additional + * information regarding copyright ownership. + * Licensed to you 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 com.alu.e3.prov.restapi.model; + +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.XmlType; + + +/** + * + */ +@XmlAccessorType(XmlAccessType.FIELD) +@XmlType(name = "tdrType", propOrder = { + "type" +}) +public class TdrType { + + @XmlElement(required = true) + protected List type; + + @Override + public String toString() { + final String comma = ", "; + + StringBuilder v = new StringBuilder ("type = ["); + + for (String t : type) + { + v.append(t).append(comma); + } + + v.append("]"); + + return v.toString(); + } + + /** + * Gets the value of the type property. + * + *

+ * This accessor method returns a reference to the live list, + * not a snapshot. Therefore any modification you make to the + * returned list will be present inside the JAXB object. + * This is why there is not a set method for the type property. + * + *

+ * For example, to add a new item, do as follows: + *

+	 *    getType().add(newItem);
+	 * 
+ * + * + */ + public List getType() { + if (type == null) { + type = new ArrayList(); + } + return this.type; + } + +} diff --git a/exposure-engine/provisioning/src/main/java/com/alu/e3/prov/restapi/model/TypeAttribute.java b/exposure-engine/provisioning/src/main/java/com/alu/e3/prov/restapi/model/TypeAttribute.java new file mode 100644 index 0000000..b5a52c5 --- /dev/null +++ b/exposure-engine/provisioning/src/main/java/com/alu/e3/prov/restapi/model/TypeAttribute.java @@ -0,0 +1,41 @@ +/** + * Copyright © 2012 Alcatel-Lucent. + * + * See the NOTICE file distributed with this work for additional + * information regarding copyright ownership. + * Licensed to you 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 com.alu.e3.prov.restapi.model; + +import javax.xml.bind.annotation.XmlAccessType; +import javax.xml.bind.annotation.XmlAccessorType; +import javax.xml.bind.annotation.XmlAttribute; +import javax.xml.bind.annotation.XmlType; + +@XmlAccessorType(XmlAccessType.FIELD) +@XmlType(name = "typeAttribute", propOrder = { + "type" + }) +public class TypeAttribute { + @XmlAttribute(name="type", required = true) + protected String type; + + public void setType(String type) { + this.type = type; + } + + public String getType() { + return type; + } +} diff --git a/exposure-engine/provisioning/src/main/java/com/alu/e3/prov/restapi/model/Validation.java b/exposure-engine/provisioning/src/main/java/com/alu/e3/prov/restapi/model/Validation.java new file mode 100644 index 0000000..48392ff --- /dev/null +++ b/exposure-engine/provisioning/src/main/java/com/alu/e3/prov/restapi/model/Validation.java @@ -0,0 +1,236 @@ +/** + * Copyright © 2012 Alcatel-Lucent. + * + * See the NOTICE file distributed with this work for additional + * information regarding copyright ownership. + * Licensed to you 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 com.alu.e3.prov.restapi.model; + +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.XmlElementWrapper; +import javax.xml.bind.annotation.XmlType; + + +/** + *

+ * Validation types given at provision of an API. + * + * + */ +@XmlAccessorType(XmlAccessType.FIELD) +@XmlType(name = "ValidationType", propOrder = { + +}) +public class Validation { + + protected Validation.Schema schema; + protected Validation.Xml xml; + protected Validation.Soap soap; + + /** + * Gets the value of the schema property. + * + * @return possible object is {@link Validation.Schema } + * + */ + public Validation.Schema getSchema() { + return schema; + } + + /** + * Sets the value of the schema property. + * + * @param value + * allowed object is {@link Validation.Schema } + * + */ + public void setSchema(Validation.Schema value) { + this.schema = value; + } + + /** + * Gets the value of the xml property. + * + * @return possible object is {@link Validation.Xml } + * + */ + public Validation.Xml getXml() { + return xml; + } + + /** + * Sets the value of the xml property. + * + * @param value + * allowed object is {@link Validation.Xml } + * + */ + public void setXml(Validation.Xml value) { + this.xml = value; + } + + /** + * Gets the value of the soap property. + * + * @return possible object is {@link Validation.Soap } + * + */ + public Validation.Soap getSoap() { + return soap; + } + + /** + * Sets the value of the soap property. + * + * @param value + * allowed object is {@link Validation.Soap } + * + */ + public void setSoap(Validation.Soap value) { + this.soap = value; + } + + /** + * + */ + @XmlAccessorType(XmlAccessType.FIELD) + @XmlType(name = "", propOrder = { + + }) + /** + * Schema validation type for XSD or WSDL + */ + public static class Schema { + + public Schema(SchemaValidationEnum type) { + super(); + this.type = type; + } + + public Schema() { + super(); + } + + /** + * xsd or wsdl type + */ + @XmlElement(required = true) + protected SchemaValidationEnum type; + /** + * List of resources for the schema element. + */ + @XmlElementWrapper(name = "resources", required = true) + @XmlElement(name = "resource", required = true) + protected List resourcesList; + + /** + * Gets the value of the type property. + * + * @return possible object is {@link SchemaValidationEnum } + * + */ + public SchemaValidationEnum getType() { + return type; + } + + /** + * Sets the value of the type property. + * + * @param value + * allowed object is {@link SchemaValidationEnum } + * + */ + public void setType(SchemaValidationEnum value) { + this.type = value; + } + + public List getResourcesList() { + if (resourcesList == null) { + resourcesList = new ArrayList(); + } + return this.resourcesList; + } + + public void setResourcesList(List resourcesList) { + this.resourcesList = resourcesList; + } + + } + + /** + * Soap validation type + * + */ + @XmlAccessorType(XmlAccessType.FIELD) + @XmlType(name = "", propOrder = { + + }) + public static class Soap { + /** + * Soap version 1.1 or 1.2 + */ + @XmlElement(required = true) + protected SoapVersionEnum version; + + public Soap(SoapVersionEnum version) { + super(); + this.version = version; + } + + public Soap() { + super(); + } + + /** + * Gets the value of the version property. + * + * @return possible object is {@link String } + * + */ + public SoapVersionEnum getVersion() { + return version; + } + + /** + * Sets the value of the version property. + * + * @param value + * allowed object is {@link String } + * + */ + public void setVersion(SoapVersionEnum value) { + this.version = value; + } + + } + + /** + *

+ * Xml validation type. + * When specified, this element must be empty. + * + */ + @XmlAccessorType(XmlAccessType.FIELD) + @XmlType(name = "") + public static class Xml { + + } + +} diff --git a/exposure-engine/provisioning/src/main/java/com/alu/e3/prov/restapi/model/WSSEAuth.java b/exposure-engine/provisioning/src/main/java/com/alu/e3/prov/restapi/model/WSSEAuth.java new file mode 100644 index 0000000..f7db5ca --- /dev/null +++ b/exposure-engine/provisioning/src/main/java/com/alu/e3/prov/restapi/model/WSSEAuth.java @@ -0,0 +1,71 @@ +/** + * Copyright © 2012 Alcatel-Lucent. + * + * See the NOTICE file distributed with this work for additional + * information regarding copyright ownership. + * Licensed to you 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 com.alu.e3.prov.restapi.model; + +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.XmlType; + +import com.alu.e3.data.model.WSSEAuthPassType; + +@XmlRootElement +@XmlAccessorType(XmlAccessType.FIELD) +@XmlType(name = "wsseAuth", propOrder = { + "username", + "password", + "passwordType" +}) +public class WSSEAuth { + @XmlElement(required = true) + protected String username; + + @XmlElement(required = true) + protected byte[] password; + + @XmlElement(required = true) + protected WSSEAuthPassType passwordType; + + public String getUsername() { + return username; + } + + public void setUsername(String username) { + this.username = username; + } + + public byte[] getPassword() { + return password; + } + + public void setPassword(byte[] password) { + this.password = password; + } + + public WSSEAuthPassType getPasswordType() { + return passwordType; + } + + public void setPasswordType(WSSEAuthPassType passType) { + this.passwordType = passType; + } + + +} diff --git a/exposure-engine/provisioning/src/main/java/com/alu/e3/prov/restapi/util/Base64Adapter.java b/exposure-engine/provisioning/src/main/java/com/alu/e3/prov/restapi/util/Base64Adapter.java new file mode 100644 index 0000000..d6d1546 --- /dev/null +++ b/exposure-engine/provisioning/src/main/java/com/alu/e3/prov/restapi/util/Base64Adapter.java @@ -0,0 +1,38 @@ +/** + * Copyright © 2012 Alcatel-Lucent. + * + * See the NOTICE file distributed with this work for additional + * information regarding copyright ownership. + * Licensed to you 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 com.alu.e3.prov.restapi.util; + +import javax.xml.bind.annotation.adapters.XmlAdapter; + +import org.apache.commons.codec.binary.Base64; + +public final class Base64Adapter extends XmlAdapter { + public String unmarshal(String s) { + if (s == null) + return null; + + return new String(Base64.decodeBase64(s)); + } + + public String marshal(String s) { + if (s == null) + return null; + return Base64.encodeBase64String(s.getBytes()); + } +} diff --git a/exposure-engine/provisioning/src/main/java/com/alu/e3/prov/restapi/util/CDataWriterInterceptor.java b/exposure-engine/provisioning/src/main/java/com/alu/e3/prov/restapi/util/CDataWriterInterceptor.java new file mode 100644 index 0000000..a2638ac --- /dev/null +++ b/exposure-engine/provisioning/src/main/java/com/alu/e3/prov/restapi/util/CDataWriterInterceptor.java @@ -0,0 +1,43 @@ +/** + * Copyright © 2012 Alcatel-Lucent. + * + * See the NOTICE file distributed with this work for additional + * information regarding copyright ownership. + * Licensed to you 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 com.alu.e3.prov.restapi.util; + +import java.io.OutputStream; + +import javax.xml.stream.XMLStreamWriter; + +import org.apache.cxf.interceptor.AttachmentOutInterceptor; +import org.apache.cxf.message.Message; +import org.apache.cxf.phase.AbstractPhaseInterceptor; +import org.apache.cxf.phase.Phase; +import org.apache.cxf.staxutils.StaxUtils; + +public class CDataWriterInterceptor extends AbstractPhaseInterceptor { + public CDataWriterInterceptor() { + super(Phase.PRE_STREAM); + addAfter(AttachmentOutInterceptor.class.getName()); + } + + @Override + public void handleMessage(Message message) { + message.put("disable.outputstream.optimization", Boolean.TRUE); + XMLStreamWriter writer = StaxUtils.createXMLStreamWriter(message.getContent(OutputStream.class)); + message.setContent(XMLStreamWriter.class, new CDataXMLStreamWriter(writer)); + } +} diff --git a/exposure-engine/provisioning/src/main/java/com/alu/e3/prov/restapi/util/CDataXMLStreamWriter.java b/exposure-engine/provisioning/src/main/java/com/alu/e3/prov/restapi/util/CDataXMLStreamWriter.java new file mode 100644 index 0000000..c9e3664 --- /dev/null +++ b/exposure-engine/provisioning/src/main/java/com/alu/e3/prov/restapi/util/CDataXMLStreamWriter.java @@ -0,0 +1,54 @@ +/** + * Copyright © 2012 Alcatel-Lucent. + * + * See the NOTICE file distributed with this work for additional + * information regarding copyright ownership. + * Licensed to you 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 com.alu.e3.prov.restapi.util; + +import javax.xml.stream.XMLStreamException; +import javax.xml.stream.XMLStreamWriter; + +import org.apache.cxf.staxutils.DelegatingXMLStreamWriter; + +public class CDataXMLStreamWriter extends DelegatingXMLStreamWriter { + + private String currentElementName; + + public CDataXMLStreamWriter(XMLStreamWriter del) { + super(del); + } + + @Override + public void writeCharacters(String text) throws XMLStreamException { + boolean useCData = checkIfCDATAneededForCurrentElement(); + if (useCData) { + super.writeCData(text); + } else { + super.writeCharacters(text); + } + } + + private boolean checkIfCDATAneededForCurrentElement() { + if ("grammar".equals(currentElementName)) + return true; + return false; + } + + public void writeStartElement(String prefix, String local, String uri) throws XMLStreamException { + currentElementName = local; + super.writeStartElement(prefix, local, uri); + } +} \ No newline at end of file diff --git a/exposure-engine/provisioning/src/main/java/com/alu/e3/prov/security/Default1WayKeyCertDeployer.java b/exposure-engine/provisioning/src/main/java/com/alu/e3/prov/security/Default1WayKeyCertDeployer.java new file mode 100644 index 0000000..168122b --- /dev/null +++ b/exposure-engine/provisioning/src/main/java/com/alu/e3/prov/security/Default1WayKeyCertDeployer.java @@ -0,0 +1,222 @@ +/** + * Copyright © 2012 Alcatel-Lucent. + * + * See the NOTICE file distributed with this work for additional + * information regarding copyright ownership. + * Licensed to you 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 com.alu.e3.prov.security; + +import java.io.File; +import java.io.FileNotFoundException; +import java.io.FileReader; +import java.io.IOException; +import java.io.Reader; + +import org.apache.commons.io.IOUtils; +import org.slf4j.Logger; +import org.slf4j.LoggerFactory; + +import com.alu.e3.common.osgi.api.IDataManager; +import com.alu.e3.data.IDataManagerListener; +import com.alu.e3.data.model.Certificate; +import com.alu.e3.data.model.CertificateDetail; +import com.alu.e3.data.model.Key; +import com.alu.e3.data.model.KeyDetail; +import com.alu.e3.osgi.api.ITopology; +import com.alu.e3.topology.model.ITopologyListener; + +public class Default1WayKeyCertDeployer implements IDataManagerListener, ITopologyListener { + + private static final String KEY_FILE_NAME = "e3.default.key"; + private static final String CERT_FILE_NAME = "e3.default.crt"; + + private static final String DEFAULT_KEY_ID = "default"; + private static final String DEFAULT_KEY_NAME = "Default Key"; + private static final String DEFAULT_KEY_TYPE = "Defautl Type"; + + private static final String DEFAULT_CERT_ID = "default"; + private static final String DEFAULT_CERT_NAME = "Default Cert"; + + private static final Logger logger = LoggerFactory.getLogger(Default1WayKeyCertDeployer.class); + + private File defaultKeyCertDirectory; + private ITopology topology; + private IDataManager dataManager; + + private boolean topologyServiceReady = false; + private boolean dataManagerServiceReady = false; + + private String keyData = null; + private String certData = null; + + public Default1WayKeyCertDeployer() {} + + /** + * Sets the default key/cert location to where this 'Deployer' will search for key and cert at startup. + * @param defaultKeyCertDirectory + */ + public void setDefaultKeyCertDirectory(File defaultKeyCertDirectory) { + this.defaultKeyCertDirectory = defaultKeyCertDirectory; + if (this.defaultKeyCertDirectory==null) throw new IllegalArgumentException("defaultKeyCertDirectory must be not null"); + if (!this.defaultKeyCertDirectory.exists()) throw new IllegalArgumentException("defaultKeyCertDirectory:"+defaultKeyCertDirectory.getAbsolutePath()+" does not exist"); + if (!this.defaultKeyCertDirectory.isDirectory()) throw new IllegalArgumentException("defaultKeyCertDirectory:"+defaultKeyCertDirectory.getAbsolutePath()+" must be a directory"); + } + + /** + * Sets the data manager (Preferred by Spring). + * @param dataManager + */ + public void setDataManager(IDataManager dataManager) { + this.dataManager = dataManager; + } + + /** + * Sets the topology service (Preferred by Spring). + * @param topology + */ + public void setTopology(ITopology topology) { + this.topology = topology; + } + + /** + * Initializes listeners on this 'Deployer'. + */ + protected void init() { + logger.debug("Initializing Default1WayKeyCertDeployer ..."); + + logger.debug("Checking default key availabilty ..."); + File defaultKeyFile = new File(defaultKeyCertDirectory, KEY_FILE_NAME); + if (!defaultKeyFile.exists()) throw new IllegalArgumentException("Key file:"+defaultKeyFile.getAbsolutePath()+" does not exists"); + if (!defaultKeyFile.isFile()) throw new IllegalArgumentException("Key file:"+defaultKeyFile.getAbsolutePath()+" is not a regular file"); + + logger.debug("Checking default cert availabilty ..."); + File defaultCertFile = new File(defaultKeyCertDirectory, CERT_FILE_NAME); + if (!defaultCertFile.exists()) throw new IllegalArgumentException("Cert file:"+defaultCertFile.getAbsolutePath()+" does not exists"); + if (!defaultCertFile.isFile()) throw new IllegalArgumentException("Cert file:"+defaultCertFile.getAbsolutePath()+" is not a regular file"); + + logger.debug("Loading default key data ..."); + Reader readerKey = null; + try { + readerKey = new FileReader(defaultKeyFile); + keyData = IOUtils.toString(readerKey); + } catch (FileNotFoundException e) { + throw new IllegalArgumentException("Key file:"+defaultKeyFile.getAbsolutePath()+" does not exists", e); + } catch (IOException e) { + throw new IllegalArgumentException("Key file:"+defaultKeyFile.getAbsolutePath()+" reading error", e); + } finally { + IOUtils.closeQuietly(readerKey); + readerKey = null; + } + + logger.debug("Loading default cert data ..."); + Reader readerCert = null; + try { + readerCert = new FileReader(defaultCertFile); + certData = IOUtils.toString(readerCert); + } catch (FileNotFoundException e) { + throw new IllegalArgumentException("Cert file:"+defaultCertFile.getAbsolutePath()+" does not exists", e); + } catch (IOException e) { + throw new IllegalArgumentException("Cert file:"+defaultCertFile.getAbsolutePath()+" reading error", e); + } finally { + IOUtils.closeQuietly(readerCert); + readerCert = null; + } + + logger.debug("Listening some needed services ..."); + topology.addTopologyListener(this); + dataManager.addListener(this); + logger.debug("Initialization done."); + } + + /** + * Cleans listeners on this 'Deployer'. + */ + protected void destroy() { + logger.debug("Destroying Default1WayKeyCertDeployer ..."); + topology.removeTopologyListener(this); + dataManager.removeListener(this); + logger.debug("Destroy done."); + } + + /** + * Called when topology service is ready. + */ + @Override + public void onReady() { + topologyServiceReady = true; + installDefault1WayKeyCert(); + } + + /** + * Called when dataManager service is ready. + */ + @Override + public void dataManagerReady() { + dataManagerServiceReady = true; + installDefault1WayKeyCert(); + } + + /** + * Installs one default key, one default cert and one default key/cert association. + */ + private void installDefault1WayKeyCert() { + if (!topologyServiceReady || !dataManagerServiceReady) { + // One of topology or dataManager service is not ready + return; + } + logger.debug("Installing default 1Way Key/Cert couple ..."); + + logger.debug("Installing default 1Way Key ..."); + Key defaultKey = new Key(); + KeyDetail defaultKeyDetail = new KeyDetail(); + + defaultKey.setId(DEFAULT_KEY_ID); + defaultKey.setData(keyData); + defaultKey.setActiveCertId(null); + defaultKey.setKeyDetail(defaultKeyDetail); + + defaultKeyDetail.setId(DEFAULT_KEY_ID); + defaultKeyDetail.setName(DEFAULT_KEY_NAME); + defaultKeyDetail.setType(DEFAULT_KEY_TYPE); + + dataManager.addKey(defaultKey); + + + logger.debug("Installing default 1Way Cert ..."); + Certificate defaultCert = new Certificate(); + CertificateDetail defaultCertDetail = new CertificateDetail(); + + defaultCert.setId(DEFAULT_CERT_ID); + defaultCert.setCertDetail(defaultCertDetail); + defaultCert.setData(certData); + defaultCert.setPassword(DEFAULT_CERT_ID); + + defaultCertDetail.setId(DEFAULT_CERT_ID); + defaultCertDetail.setKeyId(DEFAULT_KEY_ID); + defaultCertDetail.setName(DEFAULT_CERT_NAME); + + dataManager.addCert(defaultCert); + + // Now, key is installed, cert is installer under the previous key,0 + // let's update the key to use the default cert + logger.debug("Updating default Key/Cert association ..."); + defaultKey.setData(null); + defaultKey.setActiveCertId(DEFAULT_CERT_ID); + dataManager.updateKey(defaultKey); + + logger.debug("Installation done."); + } + +} diff --git a/exposure-engine/provisioning/src/main/java/com/alu/e3/prov/security/InitSslProvider.java b/exposure-engine/provisioning/src/main/java/com/alu/e3/prov/security/InitSslProvider.java new file mode 100644 index 0000000..d09b193 --- /dev/null +++ b/exposure-engine/provisioning/src/main/java/com/alu/e3/prov/security/InitSslProvider.java @@ -0,0 +1,32 @@ +/** + * Copyright © 2012 Alcatel-Lucent. + * + * See the NOTICE file distributed with this work for additional + * information regarding copyright ownership. + * Licensed to you 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 com.alu.e3.prov.security; + +import java.security.Security; + +import org.bouncycastle.jce.provider.BouncyCastleProvider; + +public class InitSslProvider { + + public InitSslProvider() { + super(); + Security.addProvider(new BouncyCastleProvider()); + } + +} diff --git a/exposure-engine/provisioning/src/main/java/com/alu/e3/prov/service/ApiJarBuilder.java b/exposure-engine/provisioning/src/main/java/com/alu/e3/prov/service/ApiJarBuilder.java new file mode 100644 index 0000000..ce267ec --- /dev/null +++ b/exposure-engine/provisioning/src/main/java/com/alu/e3/prov/service/ApiJarBuilder.java @@ -0,0 +1,307 @@ +/** + * Copyright © 2012 Alcatel-Lucent. + * + * See the NOTICE file distributed with this work for additional + * information regarding copyright ownership. + * Licensed to you 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 com.alu.e3.prov.service; + +import java.io.ByteArrayOutputStream; +import java.io.File; +import java.io.IOException; +import java.io.InputStream; +import java.io.StringWriter; +import java.io.UnsupportedEncodingException; +import java.net.URL; +import java.util.ArrayList; +import java.util.HashMap; +import java.util.List; +import java.util.Map; +import java.util.jar.JarEntry; +import java.util.jar.JarOutputStream; + +import org.apache.commons.io.IOUtils; +import org.springframework.core.io.Resource; + +import com.alu.e3.common.camel.ExchangeConstantKeys; +import com.alu.e3.common.logging.Category; +import com.alu.e3.common.logging.CategoryLogger; +import com.alu.e3.common.logging.CategoryLoggerFactory; +import com.alu.e3.common.tools.BundleTools; +import com.alu.e3.prov.restapi.ExchangeData; +import com.alu.e3.prov.restapi.model.Api; +import com.alu.e3.prov.restapi.model.ResourceItem; +import com.alu.e3.prov.restapi.model.SchemaValidationEnum; +import com.alu.e3.prov.restapi.model.Validation; +import com.alu.e3.prov.restapi.model.Validation.Schema; + +import freemarker.cache.URLTemplateLoader; +import freemarker.template.Configuration; +import freemarker.template.Template; +import freemarker.template.TemplateException; + +public class ApiJarBuilder implements IApiJarBuilder { + private static final CategoryLogger LOG = CategoryLoggerFactory.getLogger(ApiJarBuilder.class, Category.PROV); + + private static final String MANIFEST_TEMPLATE_PATH = "ftl/META-INF/MANIFEST.MF.ftl"; + private static final String ROUTE_TEMPLATE_PATH = "ftl/META-INF/spring/route-context.xml.ftl"; + private static final String RESOURCES_FOLDER_PATH_IN_JAR = "resources"; + + private Configuration fmConfiguration = null; + + protected int bufferSize = 128 * 1024; + private Resource soap11; + private Resource soap12; + private Resource xml; + + // for Jar generation in disk + private boolean generateJarInFile = false; + private String workingDir; + private String archiveDir; + + public ApiJarBuilder(Resource soap11, Resource soap12, Resource xml) { + this(); + this.soap11 = soap11; + this.soap12 = soap12; + this.xml = xml; + } + + public ApiJarBuilder() { + fmConfiguration = new Configuration(); + // fmConfiguration.setCacheStorage(new NoCacheStorage()); + fmConfiguration.setLocalizedLookup(false); + fmConfiguration.setTemplateLoader(new URLTemplateLoader() { + @Override + protected URL getURL(String name) { + return ApiJarBuilder.class.getClassLoader().getResource(name); + } + }); + } + + + + /* + * (non-Javadoc) + * + * @see + * com.alu.e3.prov.restapi.IApiJarBuilder#build(com.alu.e3.prov.restapi. + * model.Api, java.util.Map) + */ + @Override + public byte[] build(Api api, ExchangeData exchange) { + final Map variablesMap = new HashMap(); + variablesMap.put("exchange", exchange); + + byte[] jarBytes = null; + ByteArrayOutputStream baos = null; + JarOutputStream jos = null; + try { + baos = new ByteArrayOutputStream(); + jos = new JarOutputStream(baos); + + List entries = new ArrayList(); + doGenXML(entries, api, variablesMap); + doGenManifest(entries, api, variablesMap); + doGenResources(entries, api, variablesMap); + + for (JarEntryData anEntry : entries) { + jos.putNextEntry(anEntry.jarEntry); + jos.write(anEntry.bytes); + + } + // the close is necessary before getting bytes + jos.close(); + jarBytes = baos.toByteArray(); + + if (this.generateJarInFile) { + // generate Jar in Disk for debug only + doGenJar(jarBytes, api, variablesMap); + } + + } catch (Exception e) { + LOG.error("Error building the jar for apiID:" + api.getId(), e); + } finally { + if (jos != null) + try { + jos.close(); + } catch (IOException e) { + LOG.error("Error closing stream", e); + } + + if (baos != null) + try { + baos.close(); + } catch (IOException e) { + LOG.error("Error closing stream", e); + } + } + + return jarBytes; + } + + protected void doGenManifest(List entries, Api api, Map variablesMap) throws IOException, TemplateException { + Template template = fmConfiguration.getTemplate(MANIFEST_TEMPLATE_PATH); + StringWriter buffer = new StringWriter(); + template.process(variablesMap, buffer); + buffer.flush(); + + if (LOG.isDebugEnabled()) + LOG.debug(buffer.getBuffer().toString()); + + addJarEntry(entries, buffer.getBuffer().toString().getBytes("UTF-8"), "META-INF/MANIFEST.MF"); + + } + + protected void doGenXML(List entries, Api api, Map variablesMap) throws IOException, TemplateException { + Template template = fmConfiguration.getTemplate(ROUTE_TEMPLATE_PATH); + StringWriter buffer = new StringWriter(); + template.process(variablesMap, buffer); + buffer.flush(); + + if (LOG.isDebugEnabled()) + LOG.debug(buffer.getBuffer().toString()); + + addJarEntry(entries, buffer.getBuffer().toString().getBytes("UTF-8"), "META-INF/spring/route-context.xml"); + } + + protected void doGenResources(List entries, Api api, Map variablesMap) throws UnsupportedEncodingException, IOException { + if (api.getValidation() != null) { + Validation val = api.getValidation(); + + Schema schema = val.getSchema(); + + if (schema != null) { + + // loop on schema resources and store them on files + StringBuffer buf = new StringBuffer(); + List resources = schema.getResourcesList(); + int resourcesCount = resources.size(); + for (int i = 0; i < resourcesCount; i++) { + ResourceItem item = resources.get(i); + + if (item != null) { + boolean isMain = item.isIsMain(); + String fileName = item.getName(); + if (isMain) { + fileName = "main." + fileName; + } + + // log file name + buf.append(fileName); + if ((i + 1) < resourcesCount) { + buf.append(";"); + } + + addJarEntry(entries, item.getGrammar().getBytes("UTF-8"), RESOURCES_FOLDER_PATH_IN_JAR + File.separator + fileName); + } + } + + // if the validation is WSDL, we need to add the schemas to + // validate the SOAP envelop + if (schema.getType() == SchemaValidationEnum.WSDL) { + addSOAPResources(entries, buf, RESOURCES_FOLDER_PATH_IN_JAR); + } + + // write resources.list file + addJarEntry(entries, buf.toString().getBytes("UTF-8"), RESOURCES_FOLDER_PATH_IN_JAR + File.separator + "resources.list"); + } + + } + } + + protected void doGenJar(byte[] jarBytes, Api api, Map variablesMap) throws Exception { + ExchangeData data = (ExchangeData) variablesMap.get("exchange"); + + String jarName = data.getProperties().get(ExchangeConstantKeys.E3_API_ID_ENCODED.toString()) + "-" + data.getProperties().get(ExchangeConstantKeys.E3_PROVISION_ID.toString()) + ".jar"; + + File file = new File(workingDir + File.separator + archiveDir + File.separator + jarName); + if (!file.getParentFile().exists()) { + file.getParentFile().mkdirs(); + } + + BundleTools.byteArray2File(jarBytes, file); + } + + protected void addJarEntry(List entries, byte[] bytes, String entryName) throws IOException { + + JarEntry anEntry = new JarEntry(entryName); + JarEntryData data = new JarEntryData(); + data.bytes = bytes; + data.jarEntry = anEntry; + + entries.add(data); + + } + + private void addSOAPResources(List entries, StringBuffer buf, String dirPath) throws IOException { + + // load xml schema + InputStream xmlIn = this.xml.getInputStream(); + String xmlName = this.xml.getFilename(); + addJarEntry(entries, IOUtils.toByteArray(xmlIn), dirPath + File.separator + xmlName); + // log filename + buf.append(";"); + buf.append(xmlName); + buf.append(";"); + + // load soap 1.1 schema + InputStream soap11In = this.soap11.getInputStream(); + String soap11Name = this.soap11.getFilename(); + addJarEntry(entries, IOUtils.toByteArray(soap11In), dirPath + File.separator + soap11Name); + + // log filename + buf.append(soap11Name); + buf.append(";"); + + // load soap 1.2 schema + InputStream soap12In = this.soap12.getInputStream(); + String soap12Name = this.soap12.getFilename(); + addJarEntry(entries, IOUtils.toByteArray(soap12In), dirPath + File.separator + soap12Name); + + // log filename + buf.append(soap12Name); + + } + + private class JarEntryData { + JarEntry jarEntry; + byte[] bytes; + } + + public String getWorkingDir() { + return workingDir; + } + + public void setWorkingDir(String workingDir) { + this.workingDir = workingDir; + } + + public String getArchiveDir() { + return archiveDir; + } + + public void setArchiveDir(String archiveDir) { + this.archiveDir = archiveDir; + } + + public boolean isGenerateJarInFile() { + return generateJarInFile; + } + + public void setGenerateJarInFile(boolean generateJarInFile) { + this.generateJarInFile = generateJarInFile; + } + +} diff --git a/exposure-engine/provisioning/src/main/java/com/alu/e3/prov/service/ApiService.java b/exposure-engine/provisioning/src/main/java/com/alu/e3/prov/service/ApiService.java new file mode 100644 index 0000000..d3d7f9c --- /dev/null +++ b/exposure-engine/provisioning/src/main/java/com/alu/e3/prov/service/ApiService.java @@ -0,0 +1,407 @@ +/** + * Copyright © 2012 Alcatel-Lucent. + * + * See the NOTICE file distributed with this work for additional + * information regarding copyright ownership. + * Licensed to you 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 com.alu.e3.prov.service; + +import java.util.ArrayList; +import java.util.List; +import java.util.Set; + +import com.alu.e3.common.InvalidIDException; +import com.alu.e3.common.camel.ExchangeConstantKeys; +import com.alu.e3.common.logging.CategoryLogger; +import com.alu.e3.common.logging.CategoryLoggerFactory; +import com.alu.e3.common.osgi.api.IDataManager; +import com.alu.e3.data.model.ApiJar; +import com.alu.e3.data.wrapper.BeanConverterUtil; +import com.alu.e3.prov.ApplicationCodeConstants; +import com.alu.e3.prov.LogUtil; +import com.alu.e3.prov.ProvisionException; +import com.alu.e3.prov.deployment.DeploymentException; +import com.alu.e3.prov.deployment.IDeploymentManager; +import com.alu.e3.prov.deployment.RollbackException; +import com.alu.e3.prov.lifecycle.IDHelper; +import com.alu.e3.prov.restapi.ExchangeData; +import com.alu.e3.prov.restapi.model.Api; +import com.alu.e3.prov.restapi.model.HTTPSType; +import com.alu.e3.prov.restapi.model.Key; +import com.alu.e3.prov.restapi.model.TLSMode; +import com.alu.e3.prov.restapi.model.TdrData; + +public class ApiService implements IApiService { + private static final CategoryLogger LOG = CategoryLoggerFactory.getLogger(ApiService.class); + + private IDataManager dataManager; + private IApiJarBuilder apiBuilder; + private IDeploymentManager deploymentManager; + private ICommonApiCheck apiChecker; + private IFeaturedApiCheck featureChecker; + + public void setCommonApiCheck(ICommonApiCheck apiChecker) { + this.apiChecker = apiChecker; + } + + public void setFeaturedApiCheck(IFeaturedApiCheck featureChecker) { + this.featureChecker = featureChecker; + } + + /** + * + * @param dataManager + */ + public void setDeploymentManager(IDeploymentManager deploymentManager) { + this.deploymentManager = deploymentManager; + } + + /** + * + * @param dataManager + */ + public void setApiJarBuilder(IApiJarBuilder apiBuilder) { + this.apiBuilder = apiBuilder; + } + + /** + * + * @param dataManager + */ + public void setDataManager(IDataManager dataManager) { + this.dataManager = dataManager; + } + + @Override + public void create(Api api) throws ProvisionException { + + boolean canCreateJar; + + // Checks before create + canCreateJar = this.checkCreate(api); + + // Setting default value of HTTPS + this.setDefaultHttpsValue(api); + + // Set default TdrData + this.setDefaultTdrValue(api); + + ExchangeData exchange = createExchange(api); + + if (canCreateJar) { + // Deploy the api + this.deployApi(api, exchange); + } + + // Store the model + com.alu.e3.data.model.Api model = BeanConverterUtil.toDataModel(api); + model.getApiDetail().setIsApiDeployed(canCreateJar); + dataManager.addApi(model); + + LogUtil.log(LOG, exchange, LogUtil.Phase.PROCESS, "Create Done"); + + return; + + } + + @Override + public void update(Api api) throws ProvisionException { + + boolean canCreateJar; + + // checks before create + canCreateJar = this.checkUpdate(api); + + // Setting default value of HTTPS + this.setDefaultHttpsValue(api); + + // Set default TdrData + this.setDefaultTdrValue(api); + + ExchangeData exchange = createExchange(api); + + if (canCreateJar) { + this.deployApi(api, exchange); + } + else { + // remove the previously deployed jar if needed + com.alu.e3.data.model.Api previousApi = dataManager.getApiById(api.getId(), true); + + if (previousApi.getApiDetail().isApiDeployed()) { + this.deploymentManager.undeployApi(exchange, api.getId()); + } + } + + // store the model + com.alu.e3.data.model.Api model = BeanConverterUtil.toDataModel(api); + model.getApiDetail().setIsApiDeployed(canCreateJar); + dataManager.updateApi(model); + + LogUtil.log(LOG, exchange, LogUtil.Phase.PROCESS, "Update Done"); + + return; + + } + + @Override + public void delete(String apiId) throws ProvisionException { + if (apiId == null) { + throw new ProvisionException(ApplicationCodeConstants.API_ID_NOT_PROVIDED, "Missing API ID in the delete request"); + } + + com.alu.e3.data.model.Api api = dataManager.getApiById(apiId, true); + + dataManager.removeApi(apiId); + + ExchangeData exchange = createExchange(apiId); + + if (api.getApiDetail().isApiDeployed()) { + this.deploymentManager.undeployApi(exchange, apiId); + } + + LogUtil.log(LOG, exchange, LogUtil.Phase.PROCESS, "Delete Done"); + + return; + + } + + @Override + public Api get(String apiId) throws ProvisionException { + + if (apiId == null) { + LOG.error("Missing API ID in the get request"); + throw new ProvisionException(ApplicationCodeConstants.API_ID_NOT_PROVIDED, "Missing API ID in the get request"); + } + + com.alu.e3.data.model.Api api = dataManager.getApiById(apiId, true); + + Api apiWs = BeanConverterUtil.fromDataModel(api); + + ExchangeData exchange = createExchange(apiId); + LogUtil.log(LOG, exchange, LogUtil.Phase.GET, "N/A"); + + return apiWs; + } + + @Override + public List getAll() throws ProvisionException { + List apiIdsList = new ArrayList(); + + Set apiIds = dataManager.getAllApiIds(); + if (apiIds != null) + apiIdsList.addAll(apiIds); + + ExchangeData exchange = new ExchangeData(); + LogUtil.log(LOG, exchange, LogUtil.Phase.GETALL, "N/A"); + + return apiIdsList; + } + + private boolean checkCreate(Api api) throws ProvisionException { + + boolean canCreateJarFile; + + featureChecker.assertIsAvailableFeature(api); + + // check api ID already exist + if (api.getId() != null && dataManager.isApiExist(api.getId())) { + throw new ProvisionException(ApplicationCodeConstants.API_ID_ALREADY_EXIST, "An API with that ID already exist"); + } + // Checking if the API has one default context, throw an exception + // otherwise. + apiChecker.assertHasDefaultContext(api); + + // Checking PassThrough/Composite/Notification/Subscription + // consistency + canCreateJarFile = apiChecker.assertCompositionApiConsistency(api); + + if(api.getEndpoint() == null || api.getEndpoint().isEmpty()){ + throw new IllegalArgumentException("The endpoint is required"); + } + else if(dataManager.endpointExists(api.getEndpoint())){ + throw new IllegalArgumentException("An API with that endpoint already exists"); + } + + for(Key key : api.getProperties()){ + if(key.getName() == null || key.getName().isEmpty()) + throw new IllegalArgumentException("All properties must have a name"); + } + + if(api.getAuthentication().getUseAuthKey() && + (api.getAuthentication().getAuthKey() == null || + api.getAuthentication().getAuthKey().getKeyName() == null || + api.getAuthentication().getAuthKey().getKeyName().isEmpty())){ + throw new IllegalArgumentException("APIs with AuthKey authentication require a keyName"); + } + + return canCreateJarFile; + } + + private boolean checkUpdate(Api api) { + + boolean canCreateJarFile; + + featureChecker.assertIsAvailableFeature(api); + + // check api ID already exist + if (api.getId() == null || !dataManager.isApiExist(api.getId())) { + throw new InvalidIDException("An API with that ID does not exist"); + } + + // Checking if the API has one default context, throw an exception + // otherwise. + apiChecker.assertHasDefaultContext(api); + + // Checking PassThrough/Composite/Notification/Subscription consistency + canCreateJarFile = apiChecker.assertCompositionApiConsistency(api); + + com.alu.e3.data.model.Api oldApi = dataManager.getApiById(api.getId(), true); + // If the endpoint already exists AND it belongs to another api + if(api.getEndpoint() == null || api.getEndpoint().isEmpty()){ + throw new IllegalArgumentException("The endpoint is required"); + } + else if(dataManager.endpointExists(api.getEndpoint()) && !oldApi.getApiDetail().getEndpoint().equals(api.getEndpoint())){ + throw new IllegalArgumentException("An API with that endpoint already exists"); + } + for(Key key : api.getProperties()){ + if(key.getName() == null || key.getName().isEmpty()) + throw new IllegalArgumentException("All properties must have a name"); + } + + if(api.getAuthentication().getUseAuthKey() && + (api.getAuthentication().getAuthKey() == null || + api.getAuthentication().getAuthKey().getKeyName() == null || + api.getAuthentication().getAuthKey().getKeyName().isEmpty())){ + throw new IllegalArgumentException("APIs with AuthKey authentication require a keyName"); + } + + return canCreateJarFile; + } + + private void setDefaultHttpsValue(Api api) { + // Setting default value of HTTPS + HTTPSType httpsType = api.getHttps(); + if (httpsType == null) { + httpsType = new HTTPSType(); + httpsType.setEnabled(false); + } else if (httpsType.isEnabled() && httpsType.getTlsMode() == null) { + httpsType.setTlsMode(TLSMode.ONE_WAY); + } + api.setHttps(httpsType); + } + + private void setDefaultTdrValue(Api api){ + if(api.getTdr() == null){ + api.setTdr(new TdrData()); + } + } + + protected void deployApi(Api api, ExchangeData exchange) throws RollbackException, ProvisionException { + ApiJar oldApiJar = null; + try { + oldApiJar = dataManager.getApiJar(api.getId()); + + byte[] apiNewJarBytes = apiBuilder.build(api, exchange); + + if (apiNewJarBytes != null) { + deploymentManager.deployApi(exchange, apiNewJarBytes); + } else { + LOG.error("No Jar data created for for Api ID: " + api.getId()); + } + } catch (DeploymentException e) { + LOG.error("Deployment failed for Api ID: " + api.getId(), e); + + deploymentManager.undeployApi(exchange, api.getId()); + + // Roll back old API + if (oldApiJar != null) { + try { + // Deploy N-1 jar + deploymentManager.deployApi(exchange, oldApiJar.getData()); + // throw this status for error mgmt + throw new RollbackException(ApplicationCodeConstants.ROUTE_CREATION_FAILED_ROLLBACK_OK, "Route edition failed, rollback ok."); + + } catch (DeploymentException e1) { + throw new RollbackException(ApplicationCodeConstants.ROLLBACK_FAILED, "Second try deployment, give up", e1); + } + } else { + // Nothing to roll-back + throw new RollbackException(ApplicationCodeConstants.ROUTE_CREATION_FAILED_ROLLBACK_KO, "Route creation failed, and no rollback could be done."); + } + + } + + } + + // + // Utility methods for logging + // + + protected static ExchangeData createExchange(String apiId) { + ExchangeData exchange = new ExchangeData(); + String provID = IDHelper.generateUID(); + String encodedApiID = IDHelper.encode(apiId); + + exchange.getProperties().put(ExchangeConstantKeys.E3_API_ID.toString(), apiId); + exchange.getProperties().put(ExchangeConstantKeys.E3_API_ID_ENCODED.toString(), encodedApiID); + exchange.getProperties().put(ExchangeConstantKeys.E3_PROVISION_ID.toString(), provID); + + return exchange; + } + + protected static ExchangeData createExchange(Api api) { + ExchangeData exchange = new ExchangeData(); + + String provID = IDHelper.generateUID(); + + String encodedApiID = null; + String apiID = api.getId(); + if (apiID != null) { + exchange.getProperties().put(ExchangeConstantKeys.E3_API_ID_CREATION_MODE.toString(), ExchangeConstantKeys.E3_API_ID_CREATION_MODE_PROVIDED.toString()); + encodedApiID = IDHelper.encode(apiID); + + if (LOG.isDebugEnabled()) + LOG.debug("Found API ID: {}", apiID); + + } else { + apiID = IDHelper.generateUID(); + encodedApiID = IDHelper.encode(apiID); + + api.setId(apiID); + + exchange.getProperties().put(ExchangeConstantKeys.E3_API_ID_CREATION_MODE.toString(), ExchangeConstantKeys.E3_API_ID_CREATION_MODE_GENERATED.toString()); + + if (LOG.isDebugEnabled()) + LOG.debug("Generating API ID is set to: {}", apiID); + + } + + exchange.getProperties().put(ExchangeConstantKeys.E3_API_ID.toString(), api.getId()); + exchange.getProperties().put(ExchangeConstantKeys.E3_API_ID_ENCODED.toString(), encodedApiID); + exchange.getProperties().put(ExchangeConstantKeys.E3_REQUEST_PAYLOAD.toString(), api); + exchange.getProperties().put(ExchangeConstantKeys.E3_PROVISION_ID.toString(), provID); + + return exchange; + } + + public IDeploymentManager getDeploymentManager() { + return deploymentManager; + } + + public IDataManager getDataManager() { + return dataManager; + } + +} diff --git a/exposure-engine/provisioning/src/main/java/com/alu/e3/prov/service/CommonApiCheck.java b/exposure-engine/provisioning/src/main/java/com/alu/e3/prov/service/CommonApiCheck.java new file mode 100644 index 0000000..2f69d5f --- /dev/null +++ b/exposure-engine/provisioning/src/main/java/com/alu/e3/prov/service/CommonApiCheck.java @@ -0,0 +1,125 @@ +/** + * Copyright © 2012 Alcatel-Lucent. + * + * See the NOTICE file distributed with this work for additional + * information regarding copyright ownership. + * Licensed to you 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 com.alu.e3.prov.service; + +import java.util.List; + +import com.alu.e3.prov.restapi.model.Api; +import com.alu.e3.prov.restapi.model.ApiContext; +import com.alu.e3.prov.restapi.model.Status; +import com.alu.e3.prov.restapi.model.SubscriptionStep; + +public class CommonApiCheck implements ICommonApiCheck { + + public CommonApiCheck(){ + + } + /* (non-Javadoc) + * @see com.alu.e3.prov.service.ICommonApiCheck#assertHasDefaultContext(com.alu.e3.prov.restapi.model.Api) + */ + @Override + public final void assertHasDefaultContext(Api provRequest) { + boolean hasDefault = false; + for(ApiContext context : provRequest.getContexts()) { + if(context.isDefaultContext()) { + if(hasDefault) + throw new IllegalArgumentException("An api must have one and only one default context."); + else + hasDefault = true; + } + + } + if(!hasDefault) { + throw new IllegalArgumentException("An api must have one and only one default context."); + } + } + + /* (non-Javadoc) + * @see com.alu.e3.prov.service.ICommonApiCheck#assertCompositionApiConsistency(com.alu.e3.prov.restapi.model.Api) + */ + @Override + public final boolean assertCompositionApiConsistency(Api provRequest) { + boolean canCreateJarFile = false; + + if (provRequest.getSubscriptionStep() != null) { + // This API is marked as Subscription or Notification + if (SubscriptionStep.SUBSCRIPTION == provRequest.getSubscriptionStep()) { + // Nothing special to test + // OPTIONAL: + // 1- We can't have Notification format + if (provRequest.getNotificationFormat() != null) + throw new IllegalArgumentException("An api can't have a NotificationFormat in Subscription step mode."); + // 2- We must have target hosts + canCreateJarFile = assertHasAtLeastOneTargetHost(provRequest, "An active context must have at least one target host."); + } + else if (SubscriptionStep.NOTIFICATION == provRequest.getSubscriptionStep()) { + // 1- We can't have target hosts + assertHasNOTAnyTargetHost(provRequest, "An api marked as Notification step can't have any target host."); + // 2- We must have a notification format + if (provRequest.getNotificationFormat() == null) + throw new IllegalArgumentException("An api marked as Notification must have a NotificationFormat."); + + // we can always create the JAR file in case of the provisioning of a notification API + canCreateJarFile = true; + } + } else { + // We are on MT standard call (either is a COMPOSITE or NOT api + // 1- We must have target hosts + canCreateJarFile = assertHasAtLeastOneTargetHost(provRequest, "An active context must have at least one target host."); + // 2- We can't have notification format + if (provRequest.getNotificationFormat() != null) + throw new IllegalArgumentException("An api without Notification step flag can't have NotificationFormat."); + } + + return canCreateJarFile; + } + + private final boolean assertHasAtLeastOneTargetHost(Api provRequest, String msg) { + boolean hasTargetHost = false; + if (provRequest.getContexts() != null) { + List apiCtxs = provRequest.getContexts(); + for (ApiContext apiCtx : apiCtxs) { + if (apiCtx.getStatus() == Status.ACTIVE) { + // we must have at least one target host for an active API context + if (apiCtx.getTargetHosts() == null || apiCtx.getTargetHosts().size() == 0) { + throw new IllegalArgumentException(msg); + } + else { + hasTargetHost = true; + } + } + } + } + + return hasTargetHost; + } + + private final void assertHasNOTAnyTargetHost(Api provRequest, String msg) { + if (provRequest.getContexts() != null) { + List apiCtxs = provRequest.getContexts(); + for (ApiContext apiCtx : apiCtxs) { + if (apiCtx.getTargetHosts() != null) { + if (apiCtx.getTargetHosts().size() > 0) { + throw new IllegalArgumentException(msg); + } + } + } + } + } +} diff --git a/exposure-engine/provisioning/src/main/java/com/alu/e3/prov/service/FeaturedApiCheck.java b/exposure-engine/provisioning/src/main/java/com/alu/e3/prov/service/FeaturedApiCheck.java new file mode 100644 index 0000000..d4c6e09 --- /dev/null +++ b/exposure-engine/provisioning/src/main/java/com/alu/e3/prov/service/FeaturedApiCheck.java @@ -0,0 +1,36 @@ +/** + * Copyright © 2012 Alcatel-Lucent. + * + * See the NOTICE file distributed with this work for additional + * information regarding copyright ownership. + * Licensed to you 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 com.alu.e3.prov.service; + +import com.alu.e3.common.NotImplementedException; +import com.alu.e3.prov.restapi.model.Api; + +public class FeaturedApiCheck implements IFeaturedApiCheck { + @Override + public final void assertIsAvailableFeature(Api api) { + if(api.getAuthentication().getUseOAuth()) { + throw new NotImplementedException("OAuth feature not supported"); + } + + if(api.getValidation() != null) { + throw new NotImplementedException("Schema validation feature not supported"); + } + } + +} diff --git a/exposure-engine/provisioning/src/main/java/com/alu/e3/prov/service/IApiJarBuilder.java b/exposure-engine/provisioning/src/main/java/com/alu/e3/prov/service/IApiJarBuilder.java new file mode 100644 index 0000000..d170b94 --- /dev/null +++ b/exposure-engine/provisioning/src/main/java/com/alu/e3/prov/service/IApiJarBuilder.java @@ -0,0 +1,28 @@ +/** + * Copyright © 2012 Alcatel-Lucent. + * + * See the NOTICE file distributed with this work for additional + * information regarding copyright ownership. + * Licensed to you 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 com.alu.e3.prov.service; + +import com.alu.e3.prov.restapi.ExchangeData; +import com.alu.e3.prov.restapi.model.Api; + +public interface IApiJarBuilder { + + public abstract byte[] build(Api api, ExchangeData variablesMap); + +} \ No newline at end of file diff --git a/exposure-engine/provisioning/src/main/java/com/alu/e3/prov/service/IApiService.java b/exposure-engine/provisioning/src/main/java/com/alu/e3/prov/service/IApiService.java new file mode 100644 index 0000000..b420a29 --- /dev/null +++ b/exposure-engine/provisioning/src/main/java/com/alu/e3/prov/service/IApiService.java @@ -0,0 +1,38 @@ +/** + * Copyright © 2012 Alcatel-Lucent. + * + * See the NOTICE file distributed with this work for additional + * information regarding copyright ownership. + * Licensed to you 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 com.alu.e3.prov.service; + +import java.util.List; + +import com.alu.e3.prov.ProvisionException; +import com.alu.e3.prov.restapi.model.Api; + +public interface IApiService { + + public void create(Api api) throws ProvisionException; + + public void update(Api api) throws ProvisionException; + + public void delete(String apiId) throws ProvisionException; + + public Api get(String apiId) throws ProvisionException; + + public List getAll() throws ProvisionException; + +} diff --git a/exposure-engine/provisioning/src/main/java/com/alu/e3/prov/service/ICommonApiCheck.java b/exposure-engine/provisioning/src/main/java/com/alu/e3/prov/service/ICommonApiCheck.java new file mode 100644 index 0000000..7f773d5 --- /dev/null +++ b/exposure-engine/provisioning/src/main/java/com/alu/e3/prov/service/ICommonApiCheck.java @@ -0,0 +1,29 @@ +/** + * Copyright © 2012 Alcatel-Lucent. + * + * See the NOTICE file distributed with this work for additional + * information regarding copyright ownership. + * Licensed to you 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 com.alu.e3.prov.service; + +import com.alu.e3.prov.restapi.model.Api; + +public interface ICommonApiCheck { + + public abstract void assertHasDefaultContext(Api provRequest); + + public abstract boolean assertCompositionApiConsistency(Api provRequest); + +} \ No newline at end of file diff --git a/exposure-engine/provisioning/src/main/java/com/alu/e3/prov/service/IFeaturedApiCheck.java b/exposure-engine/provisioning/src/main/java/com/alu/e3/prov/service/IFeaturedApiCheck.java new file mode 100644 index 0000000..d2e44a0 --- /dev/null +++ b/exposure-engine/provisioning/src/main/java/com/alu/e3/prov/service/IFeaturedApiCheck.java @@ -0,0 +1,25 @@ +/** + * Copyright © 2012 Alcatel-Lucent. + * + * See the NOTICE file distributed with this work for additional + * information regarding copyright ownership. + * Licensed to you 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 com.alu.e3.prov.service; + +import com.alu.e3.prov.restapi.model.Api; + +public interface IFeaturedApiCheck { + void assertIsAvailableFeature(Api api); +} diff --git a/exposure-engine/provisioning/src/main/resources/META-INF/spring-optional/provisioning.osgi-context.xml b/exposure-engine/provisioning/src/main/resources/META-INF/spring-optional/provisioning.osgi-context.xml new file mode 100644 index 0000000..6ba206c --- /dev/null +++ b/exposure-engine/provisioning/src/main/resources/META-INF/spring-optional/provisioning.osgi-context.xml @@ -0,0 +1,14 @@ + + + + \ No newline at end of file diff --git a/exposure-engine/provisioning/src/main/resources/META-INF/spring-optional/provisioning.provision-beans.xml b/exposure-engine/provisioning/src/main/resources/META-INF/spring-optional/provisioning.provision-beans.xml new file mode 100644 index 0000000..ac71297 --- /dev/null +++ b/exposure-engine/provisioning/src/main/resources/META-INF/spring-optional/provisioning.provision-beans.xml @@ -0,0 +1,104 @@ + + + + + + + + + + + + + + + + + + + + + + + classpath:/provisioning/prov.xsd + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + \ No newline at end of file diff --git a/exposure-engine/provisioning/src/main/resources/META-INF/spring-optional/provisioning.rest-declaration.xml b/exposure-engine/provisioning/src/main/resources/META-INF/spring-optional/provisioning.rest-declaration.xml new file mode 100644 index 0000000..5b39d28 --- /dev/null +++ b/exposure-engine/provisioning/src/main/resources/META-INF/spring-optional/provisioning.rest-declaration.xml @@ -0,0 +1,55 @@ + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + \ No newline at end of file diff --git a/exposure-engine/provisioning/src/main/resources/ftl/META-INF/MANIFEST.MF.ftl b/exposure-engine/provisioning/src/main/resources/ftl/META-INF/MANIFEST.MF.ftl new file mode 100644 index 0000000..f489618 --- /dev/null +++ b/exposure-engine/provisioning/src/main/resources/ftl/META-INF/MANIFEST.MF.ftl @@ -0,0 +1,13 @@ +Manifest-Version: 1.0 +Bundle-Version: 1.0 +Build-Jdk: 1.6.0_25 +Built-By: E3-ExposureEngine +Tool: E3-ExposureEngine +Bundle-Name: API ${exchange.properties.E3_API_ID} ${exchange.properties.E3_API_ID_ENCODED} +Bundle-ManifestVersion: 2 +Created-By: E3-ExposureEngine +Bundle-SymbolicName: API-${exchange.properties.E3_API_ID} +Import-Package: org.apache.camel,org.apache.camel.component.jetty,com. + alu.e3.rate.model,com.alu.e3.common.osgi.api,com.alu.e3.gateway.loadb + alancer +DynamicImport-Package: * diff --git a/exposure-engine/provisioning/src/main/resources/ftl/META-INF/spring/route-context.xml.ftl b/exposure-engine/provisioning/src/main/resources/ftl/META-INF/spring/route-context.xml.ftl new file mode 100644 index 0000000..ee99300 --- /dev/null +++ b/exposure-engine/provisioning/src/main/resources/ftl/META-INF/spring/route-context.xml.ftl @@ -0,0 +1,325 @@ + + + + + + + + + + + + + <#if exchange.properties.E3_REQUEST_PAYLOAD.allowedHttpMethodsAsString??> + + + + + + + + + + + + + + + + + + + + + + + + + <#list exchange.properties.E3_REQUEST_PAYLOAD.contexts as context> + + + + <#if context.loadBalancing??> + <#if context.loadBalancing.failOver??> + + true + + <#if context.loadBalancing.failOver.onResponseCode??> + + ${context.loadBalancing.failOver.onResponseCode} + + + + + + ${exchange.properties.E3_API_ID} + + + ${context.id} + + + + + <#if exchange.properties.E3_REQUEST_PAYLOAD.tdr??> + <#if "${exchange.properties.E3_REQUEST_PAYLOAD.tdrEnabled.enabled}" == "true"> + + + + + + + <#if exchange.properties.E3_REQUEST_PAYLOAD.https.enabled> + + + + + <#list exchange.properties.E3_REQUEST_PAYLOAD.contexts as context> + + + + + <#if exchange.properties.E3_REQUEST_PAYLOAD.https.tlsMode.value() == "2Way"> + + + + + + + + + <#assign tdrEnabled=false /> + <#if exchange.properties.E3_REQUEST_PAYLOAD.tdrEnabled??> + <#if "${exchange.properties.E3_REQUEST_PAYLOAD.tdrEnabled.enabled}" == "true"> + <#assign tdrEnabled=true /> + + + + + java.lang.Exception + true + <#if tdrEnabled> + + + + + + + + + + <#assign endpoint=exchange.properties.E3_REQUEST_PAYLOAD.endpoint?replace('^/*', '', 'fr') /> + <#if exchange.properties.E3_REQUEST_PAYLOAD.https.enabled> + + + <#if exchange.properties.E3_REQUEST_PAYLOAD.https.tlsMode.value() == "2Way"> + + + <#else> + + + + <#if tdrEnabled> + true + + + + <#else> + false + + + + <#assign authParams = "apiId="+exchange.properties.E3_API_ID> + <#if exchange.properties.E3_REQUEST_PAYLOAD.authentication??> + <#if exchange.properties.E3_REQUEST_PAYLOAD.authentication.useAuthKey> + <#assign authParams = authParams + "&authKey=true"> + <#if exchange.properties.E3_REQUEST_PAYLOAD.authentication.authKey??> + <#assign authParams = authParams + "&keyName=" + exchange.properties.E3_REQUEST_PAYLOAD.authentication.authKey.keyName> + <#if exchange.properties.E3_REQUEST_PAYLOAD.authentication.authKey.headerName??> + <#assign authParams = authParams + "&headerName=" + exchange.properties.E3_REQUEST_PAYLOAD.authentication.authKey.headerName> + + + + <#if exchange.properties.E3_REQUEST_PAYLOAD.authentication.useBasicAuth> + <#assign authParams = authParams + "&basic=true"> + + <#if exchange.properties.E3_REQUEST_PAYLOAD.authentication.useIpWhiteListAuth> + <#assign authParams = authParams + "&ipList=true"> + + <#if exchange.properties.E3_REQUEST_PAYLOAD.authentication.useNoAuth> + <#assign authParams = authParams + "&noAuth=true"> + + <#if exchange.properties.E3_REQUEST_PAYLOAD.authentication.useOAuth> + <#assign authParams = authParams + "&oAuth=true"> + + <#if exchange.properties.E3_REQUEST_PAYLOAD.authentication.useWsse> + <#assign authParams = authParams + "&wsse=true"> + + + + + <#if exchange.properties.E3_REQUEST_PAYLOAD.subscriptionStep??> + <#if "${exchange.properties.E3_REQUEST_PAYLOAD.subscriptionStep}" == "NOTIFICATION"> + + <#else> + + + + + + + <#if exchange.properties.E3_REQUEST_PAYLOAD.allowedHttpMethodsAsString??> + + + + <#if "${exchange.properties.E3_REQUEST_PAYLOAD.type}" == "COMPOSITE"> + <#if exchange.properties.E3_REQUEST_PAYLOAD.subscriptionStep??> + <#if "${exchange.properties.E3_REQUEST_PAYLOAD.subscriptionStep}" == "NOTIFICATION"> + + <#else> + + + <#else> + + + + + <#assign validParams = "apiId="+exchange.properties.E3_API_ID> + <#if exchange.properties.E3_REQUEST_PAYLOAD.validation??> + <#if exchange.properties.E3_REQUEST_PAYLOAD.validation.xml??> + <#assign validParams = validParams + "&xmlValid=true"> + + <#if exchange.properties.E3_REQUEST_PAYLOAD.validation.soap??> + <#assign validParams = validParams + "&soapValid=true"> + <#if exchange.properties.E3_REQUEST_PAYLOAD.validation.soap.version??> + <#assign validParams = validParams + "&soapVersion=" + exchange.properties.E3_REQUEST_PAYLOAD.validation.soap.version> + + + <#if exchange.properties.E3_REQUEST_PAYLOAD.validation.schema??> + <#assign validParams = validParams + "&baseURI=${endpoint}" + "&schemaValid=${exchange.properties.E3_REQUEST_PAYLOAD.validation.schema.type}"> + + + + + + + <#if tdrEnabled> + + + <#if exchange.properties.E3_REQUEST_PAYLOAD.headerTransEnabled> + + + + <#assign idCondition = "{property.E3_AUTH_IDENTITY.auth.apiContext}"> + + <#list exchange.properties.E3_REQUEST_PAYLOAD.contexts as context> + + $${idCondition} == '${context.id}' + <#if tdrEnabled> + + + + + <#if context.defaultContext> + <#assign defaultContext = context> + + + <#if defaultContext??> + + <#if tdrEnabled> + + + + + + + + true + + <#if tdrEnabled> + + + <#if exchange.properties.E3_REQUEST_PAYLOAD.headerTransEnabled > + + + <#if tdrEnabled> + + + + + + + <#list exchange.properties.E3_REQUEST_PAYLOAD.contexts as context> + + + + <#if context.targetHosts?size > 0> + + + <#if exchange.properties.E3_REQUEST_PAYLOAD.subscriptionStep??> + <#if "${exchange.properties.E3_REQUEST_PAYLOAD.subscriptionStep}" == "NOTIFICATION"> + + + + + + + <#list exchange.properties.E3_REQUEST_PAYLOAD.contexts as context> + + + + <#if tdrEnabled> + + + + + <#if tdrEnabled> + + + + <#if exchange.properties.E3_REQUEST_PAYLOAD.authentication??> + + + + + + + <#if exchange.properties.E3_REQUEST_PAYLOAD.subscriptionStep??> + <#if "${exchange.properties.E3_REQUEST_PAYLOAD.subscriptionStep}" == "NOTIFICATION"> + + + + + <#if "${exchange.properties.E3_REQUEST_PAYLOAD.notificationFormat}" == "HEADER"> + + + + <#elseif "${exchange.properties.E3_REQUEST_PAYLOAD.notificationFormat}" == "WS_ADDRESSING"> + + + + + + <#if tdrEnabled> + + + + + + <#if tdrEnabled> + + + + + + + + diff --git a/exposure-engine/provisioning/src/main/resources/provisioning.properties b/exposure-engine/provisioning/src/main/resources/provisioning.properties new file mode 100644 index 0000000..e69de29 diff --git a/exposure-engine/provisioning/src/main/resources/provisioning/prov.xsd b/exposure-engine/provisioning/src/main/resources/provisioning/prov.xsd new file mode 100644 index 0000000..ca97b6b --- /dev/null +++ b/exposure-engine/provisioning/src/main/resources/provisioning/prov.xsd @@ -0,0 +1,838 @@ + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + value value value + + + + + + + + + + + Optional ; If omitted, will use X-App-AuthKey + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + The corresponding site name for this target url. + If another site provide the same target service (redundancy, HA, + clustering, etc), it will be added as more targetHost elements. + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + true/false + + + + + + + + + + + + + xml/soap/wsdl/xsd validations + + + + + The basic API type can be PassThrough or + Composite. + The PassThrough type is the classic case. + In Composite + mode, a X-LogCorrelationID header is generated or + extracted on, + respectively, outgoing southBound message or + incoming southBound + notification. + + + + + + subscription determines if E3 should generate or + extract X-SubsriberID headers and make subscriber following. + If + subscriptionStep is Subscription, outgoing southBound messages + will contain a generated X-SubscriberID. + If subscriptionStep is + Notification, incoming southBound messages + must contain the good + X-SubscriberID (obtained after a preliminar + subscription). + If + subscriptionStep is not present, none of the above is done (means + Subscribers are not followed) + + + + + + notificationFormat is way how url to notify is + extracted from notifications. + Header extraction or WS-Addressing + extraction are supported. + Header extraction extracts the header + notifyUrl. + WS-Addressing extracts the xml tag To. + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + Only one resource must be designated as main + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + To use the global proxy setting. This element must be empty when defined. + + + + + + + + + + + + To use the the proxy setting specific for the current api. + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + diff --git a/exposure-engine/provisioning/src/main/resources/provisioning/provisioning.wadl b/exposure-engine/provisioning/src/main/resources/provisioning/provisioning.wadl new file mode 100644 index 0000000..bb1d2e9 --- /dev/null +++ b/exposure-engine/provisioning/src/main/resources/provisioning/provisioning.wadl @@ -0,0 +1,512 @@ + + + + + + + + + E3 REST API to get, create, update or delete an API + + This REST API is used to get the list of APIs. + + + + + + + This REST API is used to create an API. + + + + + + + + + + + This REST API is used to get the API. + + + + + + + This REST API is used to delete an API. + + + + + + + This REST API is used to update an API. + + + + + + + + + + + E3 REST API provision authentications on E3 subsystem + + This REST API is used to get all authentications from E3 + subsystem. + + + + + + This REST API is used to create an authentication element on E3 + subsystem. + + + + + + + + + + + This REST API is used to delete an Auth. + + + + + + + This REST API is used to fetch data model by ID. + + + + + + + This REST API is used to update an authentication. + + + + + + + + + + + E3 REST API provision SSLKeys and SSLCerts on E3 subsystem + + This REST API is used to create an SSLKey element on E3 subsystem. + + + + + + + + + This REST API is used to get all SSLKeys from E3 subsystem. + + + + + + + + This REST API is used to update an SSLKey. + + + + + + + + + This REST API is used to delete an SSLKey. + + + + + + + This REST API is used to get an SSLKey by ID from E3 subsystem. + + + + + + + + + This REST API is used to create an SSLCert element on E3 subsystem. + + + + + + + + + This REST API is used to get all SSLCerts for a key. + + + + + + + + + + This REST API is used to update an SSLKey. + + + + + + + + + This REST API is used to delete an SSLCert. + + + + + + + This REST API is used to get an SSLKey by ID from E3 subsystem. + + + + + + + + + + + This REST API is used to get a CSR for the given SSLKey ID from E3 subsystem. + + + + + + + + + + This REST API is used to create a self-signed cert for an existing Key. + + + + + + + + + + E3 REST API to create, update or delete a policy + + This REST API is used to fetch all policy ids. + + + + + + This REST API is used to create a policy. + + + + + + + + + + + This REST API is used to delete a policy. + + + + + + + This REST API is used to fetch policy data. + + + + + + + This REST API is used to update a policy. + + + + + + + + + + + This REST API is used to add a bucket of auths to a policy. + + + + + + + + + + + + + This REST API is used to add some auths to a bucket of auths + on a policy. + + + + + + + + + This REST API is used to remove a bucket of auths from a + policy. + + + + + + + + + + + This REST API is used to delete an auth from a bucket of + auths on a policy. + + + + + + + + + + + + + E3 REST API to create or delete a bucket of auths associated to + a list of policies + + This REST API is used to create a policy. + + + + + + + + + + + + This REST API is used to append auths to a bucket for several policies. + + + + + + + + + + + + + This REST API is used to remove a bucket from a list of + policies. + + + + + + + + + + + + + E3 REST API to add/update/delete trusted CAs and CRLs + + + + + This REST API is used to fetch all trusted certificates authorithies. + + + + + + + + This REST API is used to add a trusted Certificate Authority. + + + + + + + + + + + + + + This REST API is used to remove a trusted Certificate Authority. + + + + + + + + + This REST API is used to fetch trusted Certificate Authority. + + + + + + + + + This REST API is used to update a trusted Certificate Authority. + + + + + + + + + + + + + This REST API is used to fetch trusted Certificate Authority. + + + + + + + + This REST API is used to add a Certificate Revocation List for this + Certificate Authority. + + + + + + + + + + + + + + This REST API is used to remove a certificate revocation list from a + certificate authority. + + + + + + + + + This REST API is used to fetch Certificate Revocation List. + + + + + + + + + This REST API is used to update a certificate revocation list. + + + + + + + + + + + + + This REST API is used to fetch the global proxy settings. + + + + + + + + This REST API is used to set the global proxy settings. + + + + + + + + + + + + \ No newline at end of file diff --git a/exposure-engine/provisioning/src/main/resources/soap/soap-1.1.xsd b/exposure-engine/provisioning/src/main/resources/soap/soap-1.1.xsd new file mode 100644 index 0000000..bc3423e --- /dev/null +++ b/exposure-engine/provisioning/src/main/resources/soap/soap-1.1.xsd @@ -0,0 +1,88 @@ + + + + + + + + + + + + + + + + + + + + + + + + + + + + Prose in the spec does not specify that attributes are allowed on the + Body element + + + + + + + + + + + + + + + + 'encodingStyle' indicates any canonicalization conventions followed in the contents + of the containing element. For example, the value + 'http://schemas.xmlsoap.org/soap/encoding/' indicates the pattern + described in SOAP specification + + + + + + + + + + + + + Fault reporting structure + + + + + + + + + + + + + + + + + + + + + + + + diff --git a/exposure-engine/provisioning/src/main/resources/soap/soap-1.2.xsd b/exposure-engine/provisioning/src/main/resources/soap/soap-1.2.xsd new file mode 100644 index 0000000..3dc9c66 --- /dev/null +++ b/exposure-engine/provisioning/src/main/resources/soap/soap-1.2.xsd @@ -0,0 +1,109 @@ + + + + + + + + + + + + + + + + Elements replacing the wildcard MUST be namespace qualified, but can be in + the targetNamespace + + + + + + + + + + + + + + + + + + + + + + + Fault reporting structure + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + diff --git a/exposure-engine/provisioning/src/main/resources/soap/xml.xsd b/exposure-engine/provisioning/src/main/resources/soap/xml.xsd new file mode 100644 index 0000000..1c23e0b --- /dev/null +++ b/exposure-engine/provisioning/src/main/resources/soap/xml.xsd @@ -0,0 +1,143 @@ + + + + + See http://www.w3.org/XML/1998/namespace.html and + http://www.w3.org/TR/REC-xml for information about this namespace. + + This schema document describes the XML namespace, in a form + suitable for import by other schema documents. + + Note that local names in this namespace are intended to be defined + only by the World Wide Web Consortium or its subgroups. The + following names are currently defined in this namespace and should + not be used with conflicting semantics by any Working Group, + specification, or document instance: + + base (as an attribute name): denotes an attribute whose value + provides a URI to be used as the base for interpreting any + relative URIs in the scope of the element on which it + appears; its value is inherited. This name is reserved + by virtue of its definition in the XML Base specification. + + id (as an attribute name): denotes an attribute whose value + should be interpreted as if declared to be of type ID. + This name is reserved by virtue of its definition in the + xml:id specification. + + lang (as an attribute name): denotes an attribute whose value + is a language code for the natural language of the content of + any element; its value is inherited. This name is reserved + by virtue of its definition in the XML specification. + + space (as an attribute name): denotes an attribute whose + value is a keyword indicating what whitespace processing + discipline is intended for the content of the element; its + value is inherited. This name is reserved by virtue of its + definition in the XML specification. + + Father (in any context at all): denotes Jon Bosak, the chair of + the original XML Working Group. This name is reserved by + the following decision of the W3C XML Plenary and + XML Coordination groups: + + In appreciation for his vision, leadership and dedication + the W3C XML Plenary on this 10th day of February, 2000 + reserves for Jon Bosak in perpetuity the XML name + xml:Father + + + + + This schema defines attributes and an attribute group + suitable for use by + schemas wishing to allow xml:base, xml:lang, xml:space or xml:id + attributes on elements they define. + + To enable this, such a schema must import this schema + for the XML namespace, e.g. as follows: + <schema . . .> + . . . + <import namespace="http://www.w3.org/XML/1998/namespace" + schemaLocation="http://www.w3.org/2001/xml.xsd"/> + + Subsequently, qualified reference to any of the attributes + or the group defined below will have the desired effect, e.g. + + <type . . .> + . . . + <attributeGroup ref="xml:specialAttrs"/> + + will define a type which will schema-validate an instance + element with any of those attributes + + + + In keeping with the XML Schema WG's standard versioning + policy, this schema document will persist at + http://www.w3.org/2007/08/xml.xsd. + At the date of issue it can also be found at + http://www.w3.org/2001/xml.xsd. + The schema document at that URI may however change in the future, + in order to remain compatible with the latest version of XML Schema + itself, or with the XML namespace itself. In other words, if the XML + Schema or XML namespaces change, the version of this document at + http://www.w3.org/2001/xml.xsd will change + accordingly; the version at + http://www.w3.org/2007/08/xml.xsd will not change. + + + + + + Attempting to install the relevant ISO 2- and 3-letter + codes as the enumerated possible values is probably never + going to be a realistic possibility. See + RFC 3066 at http://www.ietf.org/rfc/rfc3066.txt and the IANA registry + at http://www.iana.org/assignments/lang-tag-apps.htm for + further information. + + The union allows for the 'un-declaration' of xml:lang with + the empty string. + + + + + + + + + + + + + + + + + + + + + + See http://www.w3.org/TR/xmlbase/ for + information about this attribute. + + + + + See http://www.w3.org/TR/xml-id/ for + information about this attribute. + + + + + + + + + + diff --git a/exposure-engine/provisioning/src/test/java/com/alu/e3/data/AllSerializableModelTest.java b/exposure-engine/provisioning/src/test/java/com/alu/e3/data/AllSerializableModelTest.java new file mode 100644 index 0000000..0256873 --- /dev/null +++ b/exposure-engine/provisioning/src/test/java/com/alu/e3/data/AllSerializableModelTest.java @@ -0,0 +1,121 @@ +/** + * Copyright © 2012 Alcatel-Lucent. + * + * See the NOTICE file distributed with this work for additional + * information regarding copyright ownership. + * Licensed to you 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 com.alu.e3.data; + + +import static org.junit.Assert.assertTrue; + +import java.io.Serializable; +import java.lang.reflect.Field; +import java.lang.reflect.ParameterizedType; +import java.util.Date; +import java.util.List; +import java.util.Map; + +import org.junit.Test; + +import com.alu.e3.data.model.Api; +import com.alu.e3.data.model.Auth; +import com.alu.e3.data.model.Policy; + +//@RunWith(SpringJUnit4ClassRunner.class) +//@ContextConfiguration(locations = { +// }) +public class AllSerializableModelTest { + + @Test + public void allSeriazableTest() throws InstantiationException, IllegalAccessException { + Class[] classesToTest = new Class[] { + Api.class, + Auth.class, + Policy.class + }; + + for(Class classToTest : classesToTest) { + log(0, "Testing of class: "+classToTest.getName()); + assertAllSerializable(classToTest, 1); + } + } + + private void assertAllSerializable(Class classToLoad, int level) throws InstantiationException, IllegalAccessException { + + assertTrue("Class:"+classToLoad.getSimpleName()+" must be serializable", interfaceOf(classToLoad.getInterfaces(),Serializable.class)); + + for(Field field : classToLoad.getDeclaredFields()) { + log(level, "Tested field: "+(field.isAccessible()?"public":"private")+" "+field.getName()); + + Class clazz = field.getType(); + if (clazz.isAssignableFrom(String.class)) + good(); + else if (clazz.isAssignableFrom(Boolean.class) || clazz.equals(boolean.class)) + good(); + else if (clazz.isAssignableFrom(Long.class) || clazz.equals(long.class)) + good(); + else if (clazz.isAssignableFrom(Integer.class) || clazz.equals(int.class)) + good(); + else if (clazz.isAssignableFrom(Float.class) || clazz.equals(float.class)) + good(); + else if (clazz.isAssignableFrom(Short.class) || clazz.equals(short.class)) + good(); + else if (clazz.isEnum()) + good(); + else if (clazz.isAssignableFrom(Date.class)) + good(); + else if (clazz.isAssignableFrom(List.class) || clazz.isAssignableFrom(Map.class)) { + ParameterizedType type = (ParameterizedType) field.getGenericType(); + Class clazzInList = (Class) type.getActualTypeArguments()[0]; + + if (clazzInList.isAssignableFrom(String.class)) + good(); + else if (clazzInList.isAssignableFrom(Integer.class)) + good(); + else if (clazzInList.isAssignableFrom(Boolean.class)) + good(); + else if (clazzInList.isAssignableFrom(Long.class)) + good(); + else if (clazzInList.isAssignableFrom(Float.class)) + good(); + else if (clazzInList.isAssignableFrom(Short.class)) + good(); + else if (clazzInList.isEnum()) + good(); + else + assertAllSerializable(clazzInList, level+1); + + } else if (clazz.isArray()) + good(); + else + assertAllSerializable(clazz, level+1); + } + } + + private boolean interfaceOf(Class[] interfaces, Class i) { + for(Class ii : interfaces) + if (ii.isAssignableFrom(i)) return true; + return false; + } + + private void good() {} + + private void log(int level, String s) { + for(int i=0; i[] classesToLoad = new Class[] { + com.alu.e3.prov.restapi.model.Api.class, + //com.alu.e3.prov.restapi.model.Auth.class, + //com.alu.e3.prov.restapi.model.Policy.class, + }; + + + + for(Class classToLoad : classesToLoad) { + JAXBContext context = JAXBContext.newInstance(classToLoad); + Marshaller marshaller = context.createMarshaller(); + marshaller.setProperty(Marshaller.JAXB_FORMATTED_OUTPUT, true); + + for(int testingNumber=0; testingNumber<10; testingNumber++) { + System.out.println("Testing of class: "+classToLoad.getName()); + Object filledObject = loadObjectClass(classToLoad, 2); + System.out.println("Generated randomly full filled object: "+filledObject); + + Object transformed = null; + Object reTransformed = null; + + if (filledObject instanceof com.alu.e3.prov.restapi.model.Api) { + + Random random = new Random(); + int intRandom = random.nextInt(); + if(intRandom > 100) + ((com.alu.e3.prov.restapi.model.Api)filledObject).getProxySettings().setGlobalProxy(null); + else + ((com.alu.e3.prov.restapi.model.Api)filledObject).getProxySettings().setLocalProxy(null); + + transformed = BeanConverterUtil.toDataModel((com.alu.e3.prov.restapi.model.Api)filledObject); + System.out.println("Transformed toDataModel object: "+transformed); + reTransformed = BeanConverterUtil.fromDataModel((Api)transformed); + System.out.println("ReTransformed back toWsModel object: "+reTransformed); + } + else if (filledObject instanceof com.alu.e3.prov.restapi.model.Auth) { + com.alu.e3.prov.restapi.model.Auth specialPrepared = (com.alu.e3.prov.restapi.model.Auth)filledObject; + // Only one of auth type + if (specialPrepared.getType() != AuthType.AUTHKEY) + specialPrepared.setAuthKeyAuth(null); + if (specialPrepared.getType() != AuthType.BASIC) + specialPrepared.setBasicAuth(null); + if (specialPrepared.getType() != AuthType.IP_WHITE_LIST) + specialPrepared.setIpWhiteListAuth(null); + + transformed = BeanConverterUtil.toDataModel(specialPrepared); + System.out.println("Transformed toDataModel object: "+transformed); + reTransformed = BeanConverterUtil.fromDataModel((Auth)transformed); + System.out.println("ReTransformed back toWsModel object: "+reTransformed); + } + else if (filledObject instanceof com.alu.e3.prov.restapi.model.Policy) { + transformed = BeanConverterUtil.toDataModel((com.alu.e3.prov.restapi.model.Policy)filledObject); + System.out.println("Transformed toDataModel object: "+transformed); + reTransformed = BeanConverterUtil.fromDataModel((Policy)transformed); + System.out.println("ReTransformed back toWsModel object: "+reTransformed); + } + else + throw new IllegalArgumentException("Unsupported test for type: "+filledObject.getClass().getName()); + + System.out.println("====================================================="); + System.out.println("Deep assert equals on: "+classToLoad.getSimpleName()); + deepAssertEquals(filledObject, reTransformed, classToLoad.getName()); + System.out.println("!! Double Conversion Success !!"); + + marshaller.marshal(filledObject, System.out); + + } + } + } + + private T loadObjectClass(Class classToLoad, int level) throws InstantiationException, IllegalAccessException { + T instance = classToLoad.newInstance(); + for(Field field : classToLoad.getDeclaredFields()) { + boolean wasAccessible = field.isAccessible(); + field.setAccessible(true); + + Class clazz = field.getType(); + Object randomValue = null; + if (clazz.isAssignableFrom(TdrEnabled.class)) + randomValue = randomTdrEnabledValue(); + else if (clazz.isAssignableFrom(String.class)) + randomValue = randomString(); + else if (clazz.isAssignableFrom(Integer.class) || clazz.equals(int.class)) + randomValue = randomInt(); + else if (clazz.isAssignableFrom(Float.class) || clazz.equals(float.class)) + randomValue = randomFloat(); + else if (clazz.isAssignableFrom(Long.class) || clazz.equals(long.class)) + randomValue = randomLong(); + else if (clazz.isAssignableFrom(Boolean.class) || clazz.equals(boolean.class)) + randomValue = randomBoolean(); + else if (clazz.isEnum()) + randomValue = randomEnumOf(clazz); + else if (clazz.isAssignableFrom(List.class)) + randomValue = randomListOf(field, level+1); + else if (clazz.isArray()) + randomValue = arrayOfBytes(); + else + randomValue = loadObjectClass(clazz, level+1); + field.set(instance, randomValue); + + field.setAccessible(wasAccessible); + } + return instance; + } + + + private TdrEnabled randomTdrEnabledValue() { + TdrEnabled tdr = new TdrEnabled(); + if (Math.random()>0.5) + tdr.setEnabled("true"); + else + tdr.setEnabled("false"); + return tdr; + } + + private String randomString() { + return UUID.randomUUID().toString(); + } + + private Integer randomInt() { + return new Random().nextInt(); + } + + private Float randomFloat() { + return Math.round((new Random()).nextFloat() * 100.0f) / 100.0f; + } + + private Long randomLong() { + return new Random().nextLong(); + } + + private Boolean randomBoolean() { + return randomInt() % 2 == 0; + } + + private Object randomEnumOf(Class enumClazz) throws InstantiationException, IllegalAccessException { + Object[] enumValues = enumClazz.getEnumConstants(); + return enumValues[new Random().nextInt(enumValues.length)]; + } + + private byte[] arrayOfBytes() { + return new byte[] { 0x01, 0x02, 0x03 }; + } + + private List randomListOf(Field field, int level) throws InstantiationException, IllegalAccessException { + ParameterizedType type = (ParameterizedType) field.getGenericType(); + Class clazz = (Class) type.getActualTypeArguments()[0]; + + List list = new ArrayList(); + for(int i=0; i<10; i++) { + Object randomValue = null; + if (clazz.isAssignableFrom(String.class)) + randomValue = randomString(); + else if (clazz.isEnum()) + randomValue = randomEnumOf(clazz); + else + randomValue = loadObjectClass(clazz, level+1); + list.add(randomValue); + } + return list; + } + + private void deepAssertEquals(Object filledObject, Object reTransformed, String pkg) throws IllegalArgumentException, IllegalAccessException { + if (filledObject == null) { + assertNull("null comparison failed :"+pkg, reTransformed); + return; + } + + Class testedClazz = filledObject.getClass(); + + assertNotNull("Transformation has not supported, it's null: "+pkg, reTransformed); + + for(Field field : testedClazz.getDeclaredFields()) { + //System.out.println("Tested field: "+pkg+"."+field.getName()); + + boolean wasAccessible = field.isAccessible(); + field.setAccessible(true); + + Class clazz = field.getType(); + Object a = field.get(filledObject); + Object b = field.get(reTransformed); + + field.setAccessible(wasAccessible); + + if (clazz.isAssignableFrom(String.class)) + assertEquals("String comparison failed: "+pkg+"."+field.getName(), a, b); + else if (clazz.isAssignableFrom(Integer.class) || clazz.equals(int.class)) + assertEquals("Integer comparison failed: "+pkg+"."+field.getName(), a, b); + else if (clazz.isAssignableFrom(Float.class) || clazz.equals(float.class)) + assertEquals("Float comparison failed: "+pkg+"."+field.getName(), a, b); + else if (clazz.isAssignableFrom(Long.class) || clazz.equals(long.class)) + assertEquals("Long comparison failed: "+pkg+"."+field.getName(), a, b); + else if (clazz.isAssignableFrom(Boolean.class) || clazz.equals(boolean.class)) + assertEquals("Boolean comparison failed: "+pkg+"."+field.getName(), a, b); + else if (clazz.isEnum()) + assertEquals("Enum comparison failed: "+pkg+"."+field.getName(), a, b); + else if (clazz.isAssignableFrom(List.class)) + deepAssertEqualsList((List)a, (List)b, pkg+"."+field.getName()); + else if (clazz.isArray()) + deepAssertEqualsByteArray((byte[])a, (byte[])b, pkg+"."+field.getName()); + else + deepAssertEquals(a, b, pkg+"."+field.getName()); + } + } + + + private void deepAssertEqualsByteArray(byte[] filledObject, byte[] reTransformed, String pkg) { + for(int i=0; i void deepAssertEqualsList(List filledObject, List reTransformed, String pkg) throws IllegalArgumentException, IllegalAccessException { + for(int i=0; i", reTransformed); + + Object b = reTransformed.get(i); + + Class clazz = a.getClass(); + if (clazz.isAssignableFrom(String.class)) + assertEquals("String comparison failed: "+pkg+"["+i+"]", a, b); + else if (clazz.isAssignableFrom(Integer.class) || clazz.equals(int.class)) + assertEquals("Integer comparison failed: "+pkg+"["+i+"]", a, b); + else if (clazz.isAssignableFrom(Float.class) || clazz.equals(float.class)) + assertEquals("Float comparison failed: "+pkg+"["+i+"]", a, b); + else if (clazz.isAssignableFrom(Long.class) || clazz.equals(long.class)) + assertEquals("Long comparison failed: "+pkg+"["+i+"]", a, b); + else if (clazz.isAssignableFrom(Boolean.class) || clazz.equals(boolean.class)) + assertEquals("Boolean comparison failed: "+pkg+"["+i+"]", a, b); + else if (clazz.isEnum()) + assertEquals("Enum comparison failed: "+pkg+"["+i+"]", a, b); + else if (clazz.isArray()) + deepAssertEqualsByteArray((byte[])a, (byte[])b, pkg+"["+i+"]"); + else + deepAssertEquals(a, b, pkg+"["+i+"]"); + } + } +} diff --git a/exposure-engine/provisioning/src/test/java/com/alu/e3/prov/ApiManagerTest.java b/exposure-engine/provisioning/src/test/java/com/alu/e3/prov/ApiManagerTest.java new file mode 100644 index 0000000..209a13f --- /dev/null +++ b/exposure-engine/provisioning/src/test/java/com/alu/e3/prov/ApiManagerTest.java @@ -0,0 +1,1081 @@ +/** + * Copyright © 2012 Alcatel-Lucent. + * + * See the NOTICE file distributed with this work for additional + * information regarding copyright ownership. + * Licensed to you 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 com.alu.e3.prov; + +import static com.jayway.restassured.RestAssured.given; +import static org.hamcrest.CoreMatchers.equalTo; +import static org.hamcrest.CoreMatchers.notNullValue; + +import java.io.File; +import java.util.ArrayList; +import java.util.Arrays; +import java.util.List; +import java.util.Random; + +import junit.framework.Assert; + +import org.junit.After; +import org.junit.AfterClass; +import org.junit.Before; +import org.junit.BeforeClass; +import org.junit.Ignore; +import org.junit.Test; +import org.junit.runner.RunWith; +import org.springframework.test.context.ContextConfiguration; +import org.springframework.test.context.junit4.SpringJUnit4ClassRunner; + +import com.alu.e3.common.E3Constant; +import com.alu.e3.prov.restapi.model.Api; +import com.alu.e3.prov.restapi.model.ApiContext; +import com.alu.e3.prov.restapi.model.ApiType; +import com.alu.e3.prov.restapi.model.AuthType; +import com.alu.e3.prov.restapi.model.Authentication; +import com.alu.e3.prov.restapi.model.Authkey; +import com.alu.e3.prov.restapi.model.BasicResponse; +import com.alu.e3.prov.restapi.model.Data; +import com.alu.e3.prov.restapi.model.DynamicTdr; +import com.alu.e3.prov.restapi.model.HTTPSType; +import com.alu.e3.prov.restapi.model.Key; +import com.alu.e3.prov.restapi.model.NotificationFormat; +import com.alu.e3.prov.restapi.model.ProvisionAuthentication; +import com.alu.e3.prov.restapi.model.StaticTdr; +import com.alu.e3.prov.restapi.model.Status; +import com.alu.e3.prov.restapi.model.SubscriptionStep; +import com.alu.e3.prov.restapi.model.TargetHost; +import com.alu.e3.prov.restapi.model.TdrData; +import com.alu.e3.prov.restapi.model.TdrEnabled; +import com.alu.e3.prov.restapi.model.TdrType; +import com.alu.e3.prov.restapi.model.Validation; +import com.jayway.restassured.RestAssured; +import com.jayway.restassured.mapper.ObjectMapper; +import com.jayway.restassured.response.Response; + +@RunWith(SpringJUnit4ClassRunner.class) +@ContextConfiguration(locations = { + "classpath:/spring/provisioning.osgi-context-test.xml", + "classpath:/spring/provisioning.provision-beans-test.xml", + "classpath:/spring/provisioning.rest-declaration-test.xml" +}) + +public class ApiManagerTest { + private String apiVersion = E3Constant.REST_API_VERSION; + + + /** + * @throws java.lang.Exception + */ + @BeforeClass + public static void setUpBeforeClass() throws Exception { + //RestAssured.baseURI = "http://192.168.84.51";RestAssured.port = 8181; + + //A little bit of cleanup + File archiveDir = new File("target/PROVISIONING_WORKING_DIR/DEPLOYED"); + if (archiveDir.exists()) { + for(File toDelete : archiveDir.listFiles()) + toDelete.delete(); + } + + } + + /** + * @throws java.lang.Exception + */ + @AfterClass + public static void tearDownAfterClass() throws Exception { + + } + + /** + * @throws java.lang.Exception + */ + @Before + public void setUp() throws Exception { + + RestAssured.baseURI = "http://localhost"; RestAssured.port = 2666; + RestAssured.basePath = "/cxf/e3/prov/"+apiVersion+"/apis"; + //RestAssured.authentication = basic("username", "password"); + RestAssured.rootPath = "response"; + } + + /** + * @throws java.lang.Exception + */ + @After + public void tearDown() throws Exception { + } + + /** + * Strangly does not succeed if this test is put at bottom + * of this test suite. + * TODO: Need to be check why. + */ + @Test + public void testCreateAndGetAllApi() { + // GetAll step + BasicResponse response = given() + .contentType("application/xml") + .expect() + .statusCode(200) + .rootPath("response") + .body("status", equalTo("SUCCESS")) + + .log().ifError() + .when() + .get("/") + .andReturn() + .as(BasicResponse.class, ObjectMapper.JAXB); + + Assert.assertNotNull(response); + Assert.assertNotNull(response.getIds()); + for(String idToDelete : response.getIds()) { + // Delete step + BasicResponse deleteResponse = given() + .contentType("application/xml") + .expect() + .statusCode(200) + .rootPath("response") + .body("status", equalTo("SUCCESS")) + + .log().ifError() + .when() + .delete("/" + idToDelete) + .andReturn() + .as(BasicResponse.class, ObjectMapper.JAXB); + + Assert.assertNotNull(deleteResponse); + Assert.assertEquals("SUCCESS", deleteResponse.getStatus()); + } + + List createdApis = new ArrayList(); + + Api data; + for(int i=0; i<2; i++) { + data = newApi(); + String apiID = ""+(new Random().nextLong()); + createdApis.add(apiID); + data.setId(apiID); + + // Create step + BasicResponse createResponse = given() + .contentType("application/xml") + .body(data, ObjectMapper.JAXB) + .expect() + .statusCode(200) + .rootPath("response") + .body("status", equalTo("SUCCESS")) + .body("id", notNullValue()) + .log().ifError() + .when() + .post("") + .andReturn() + .as(BasicResponse.class, ObjectMapper.JAXB); + + String apiIDReturned = createResponse.getId(); + + Assert.assertNotNull(createResponse); + Assert.assertNotNull(apiIDReturned); + Assert.assertEquals(apiID, apiIDReturned); + + Assert.assertEquals("SUCCESS", createResponse.getStatus()); + } + + + // GetAll step + BasicResponse getAllResponse = given() + .contentType("application/xml") + .expect() + .statusCode(200) + .rootPath("response") + .body("status", equalTo("SUCCESS")) + + .log().ifError() + .when() + .get("/") + .andReturn() + .as(BasicResponse.class, ObjectMapper.JAXB); + + Assert.assertNotNull(getAllResponse); + Assert.assertNotNull(getAllResponse.getIds()); + // sometimes other junits create apis + Assert.assertTrue(createdApis.size() <= getAllResponse.getIds().size()); + for(int i=0; i"+ + ".*\\z"); + + producerTemplate.requestBody(String.class); + + testMessage.assertIsSatisfied(); + } + + @Test + @DirtiesContext + public void testBasicSuccess() throws Exception { + setup.whenAnyExchangeReceived(new Processor() { + @Override + public void process(Exchange exchange) throws Exception { + ProvisionAuthentication auth = new ProvisionAuthentication(); + auth.getAuths().add(AuthType.BASIC); + + setupExchange(exchange, auth); + } + }); + + testMessage.setExpectedMessageCount(1); + testMessage.allMessages().body().isNotNull(); + testMessage.allMessages().body().regex( + // Turns on single-line mode + "(?s)\\A.*"+ + ""+ + ".*\\z"); + + producerTemplate.requestBody(String.class); + + testMessage.assertIsSatisfied(); + } + + @Test + @DirtiesContext + public void testIpListSuccess() throws Exception { + setup.whenAnyExchangeReceived(new Processor() { + @Override + public void process(Exchange exchange) throws Exception { + ProvisionAuthentication auth = new ProvisionAuthentication(); + auth.getAuths().add(AuthType.IP_WHITE_LIST); + + setupExchange(exchange, auth); + } + }); + + testMessage.setExpectedMessageCount(1); + testMessage.allMessages().body().isNotNull(); + testMessage.allMessages().body().regex( + // Turns on single-line mode + "(?s)\\A.*"+ + ""+ + ".*\\z"); + + producerTemplate.requestBody(String.class); + + testMessage.assertIsSatisfied(); + } + + @Test + @DirtiesContext + public void testAllSuccess() throws Exception { + setup.whenAnyExchangeReceived(new Processor() { + @Override + public void process(Exchange exchange) throws Exception { + ProvisionAuthentication auth = new ProvisionAuthentication(); + Authkey authKey = new Authkey(); + authKey.setKeyName("MyAuthkeyValue"); + auth.setAuthKey(authKey); + auth.getAuths().add(AuthType.IP_WHITE_LIST); + auth.getAuths().add(AuthType.BASIC); + auth.getAuths().add(AuthType.AUTHKEY); + + setupExchange(exchange, auth); + } + }); + + testMessage.setExpectedMessageCount(1); + testMessage.allMessages().body().isNotNull(); + testMessage.allMessages().body().regex( + // Turns on single-line mode + "(?s)\\A.*"+ + ""+ + ".*\\z"); + + producerTemplate.requestBody(String.class); + + testMessage.assertIsSatisfied(); + } + + @Test + @DirtiesContext + public void testNoAuthSuccess() throws Exception { + setup.whenAnyExchangeReceived(new Processor() { + @Override + public void process(Exchange exchange) throws Exception { + ProvisionAuthentication auth = new ProvisionAuthentication(); + auth.getAuths().add(AuthType.NO_AUTH); + setupExchange(exchange, auth); + } + }); + + testMessage.setExpectedMessageCount(1); + testMessage.allMessages().body().isNotNull(); + testMessage.allMessages().body().regex( + // Turns on single-line mode + "(?s)\\A.*"+ + ""+ + ".*\\z"); + + + producerTemplate.requestBody(String.class); + + testMessage.assertIsSatisfied(); + } + + private void setupExchange(Exchange exchange, ProvisionAuthentication auth){ + Api api = new Api(); + + ApiContext env = new ApiContext(); + env.setId("test"); + + api.setType(ApiType.PASS_THROUGH); + api.setContexts(Arrays.asList(env)); + + List targetList = new ArrayList(); + + api.setEndpoint("www.yahoo.fr"); + + TargetHost to1 = new TargetHost(); + to1.setUrl("http://www.google.com"); + targetList.add(to1); + + TargetHost to2 = new TargetHost(); + to2.setUrl("http://www.google.com?toto=tutu"); + targetList.add(to2); + + TargetHost to3 = new TargetHost(); + to3.setUrl("http://www.google.com?toto=tutu&tata=tete&titi=toto"); + targetList.add(to3); + + env.setTargetHosts(targetList); + + TdrEnabled tdr = new TdrEnabled(); + tdr.setEnabled("true"); + api.setTdrEnabled(tdr); + + api.setAuthentication(auth); + + TdrData tdrData = new TdrData(); + + TdrType tdrType = new TdrType(); + tdrType.getType().add("apiRateLimit"); + + DynamicTdr dt = new DynamicTdr(); + dt.setHttpHeaderName("HTTP_HEADER"); + dt.setTdrPropName("propname"); + dt.setTypes(tdrType); + + tdrData.getDynamic().add(dt); + + StaticTdr st = new StaticTdr(); + st.setValue("staticValue"); + st.setTdrPropName("staticName"); + + st.setTypes(tdrType); + + tdrData.getStatic().add(st); + + api.setTdr(tdrData); + + HTTPSType httpsType = new HTTPSType(); + httpsType.setEnabled(true); + httpsType.setTlsMode(TLSMode.ONE_WAY); + api.setHttps(httpsType); + + exchange.setProperty(ExchangeConstantKeys.E3_REQUEST_PAYLOAD.toString(), api); + exchange.setProperty(ExchangeConstantKeys.E3_API_ID.toString(), "MyApiID"); + exchange.setProperty(ExchangeConstantKeys.E3_API_ID_ENCODED.toString(), "MonApiIDEncoded"); + exchange.setProperty(ExchangeConstantKeys.E3_PROVISION_ID.toString(), "MyProvId"); + } + +} diff --git a/exposure-engine/provisioning/src/test/java/com/alu/e3/prov/BulkPolicyQuotaRLBucketsManagerTest.java b/exposure-engine/provisioning/src/test/java/com/alu/e3/prov/BulkPolicyQuotaRLBucketsManagerTest.java new file mode 100644 index 0000000..3642248 --- /dev/null +++ b/exposure-engine/provisioning/src/test/java/com/alu/e3/prov/BulkPolicyQuotaRLBucketsManagerTest.java @@ -0,0 +1,273 @@ +/** + * Copyright © 2012 Alcatel-Lucent. + * + * See the NOTICE file distributed with this work for additional + * information regarding copyright ownership. + * Licensed to you 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 com.alu.e3.prov; + +import static com.jayway.restassured.RestAssured.given; +import static org.hamcrest.CoreMatchers.equalTo; +import static org.junit.Assert.assertNotNull; +import static org.junit.Assert.assertEquals; + +import org.junit.After; +import org.junit.AfterClass; +import org.junit.Before; +import org.junit.BeforeClass; +import org.junit.Test; +import org.junit.runner.RunWith; +import org.springframework.test.context.ContextConfiguration; +import org.springframework.test.context.junit4.SpringJUnit4ClassRunner; + +import com.alu.e3.common.E3Constant; +import com.alu.e3.prov.restapi.model.Auth; +import com.alu.e3.prov.restapi.model.AuthIdsNoIdType; +import com.alu.e3.prov.restapi.model.AuthType; +import com.alu.e3.prov.restapi.model.BasicAuth; +import com.alu.e3.prov.restapi.model.BasicResponse; +import com.alu.e3.prov.restapi.model.BulkPolicyQuotaRLBucketType; +import com.alu.e3.prov.restapi.model.Context; +import com.alu.e3.prov.restapi.model.Policy; +import com.alu.e3.prov.restapi.model.PolicyIdsType; +import com.alu.e3.prov.restapi.model.Status; +import com.jayway.restassured.RestAssured; +import com.jayway.restassured.internal.mapping.ObjectMapping; +import com.jayway.restassured.mapper.ObjectMapper; + +@RunWith(SpringJUnit4ClassRunner.class) +@ContextConfiguration(locations = { + "classpath:/spring/provisioning.osgi-context-test.xml", + "classpath:/spring/provisioning.provision-beans-test.xml", + "classpath:/spring/provisioning.rest-declaration-test.xml" }) +public class BulkPolicyQuotaRLBucketsManagerTest { + + private String apiVersion = E3Constant.REST_API_VERSION; + + private String baseBulkPath = "/cxf/e3/prov/" + apiVersion + "/bulk/policies/quotaRLBuckets"; + + private String basePoliciesPath = "/cxf/e3/prov/" + apiVersion + "/policies"; + + private String baseAuthPath = "/cxf/e3/prov/" + apiVersion + "/auths"; + + /** + * @throws java.lang.Exception + */ + @BeforeClass + public static void setUpBeforeClass() throws Exception { + + // RestAssured.baseURI = "http://192.168.84.51";RestAssured.port = 8181; + + } + + /** + * @throws java.lang.Exception + */ + @AfterClass + public static void tearDownAfterClass() throws Exception { + } + + /** + * @throws java.lang.Exception + */ + @Before + public void setUp() throws Exception { + RestAssured.baseURI = "http://localhost"; + RestAssured.port = 2666; + RestAssured.rootPath = "response"; + + RestAssured.basePath = ""; + + baseBulkPath = "/cxf/e3/prov/" + apiVersion + "/bulk/policies/quotaRLBuckets"; + basePoliciesPath = "/cxf/e3/prov/" + apiVersion + "/policies"; + baseAuthPath = "/cxf/e3/prov/" + apiVersion + "/auths"; + + createPolicy("p_1"); + createPolicy("p_2"); + createPolicy("p_3"); + + createAuth("a_1"); + createAuth("a_2"); + createAuth("a_3"); + createAuth("a_4"); + + + } + + /** + * @throws java.lang.Exception + */ + @After + public void tearDown() throws Exception { + deletePolicy("p_1"); + deletePolicy("p_2"); + deletePolicy("p_3"); + + deleteAuth("a_1"); + deleteAuth("a_2"); + deleteAuth("a_3"); + deleteAuth("a_4"); + + } + + @Test + public void testCreateDeleteBulkBucket() throws Exception { + String bucketId = "bucket_1"; + + BulkPolicyQuotaRLBucketType bulk = newBulkProvision(bucketId); + + BasicResponse response = given().contentType("application/xml").body(bulk, ObjectMapper.JAXB).expect().statusCode(200).rootPath("response").body("status", equalTo("SUCCESS")).log().ifError() + .when().post(baseBulkPath).andReturn().as(BasicResponse.class, ObjectMapper.JAXB); + + assertNotNull(response); + assertEquals("SUCCESS", response.getStatus()); + + + bulk.getQuotaRLBucket().getAuthIds().add("a_3"); + bulk.getQuotaRLBucket().getAuthIds().add("a_4"); + + // append + + response = given().contentType("application/xml").body(bulk, ObjectMapper.JAXB).expect().statusCode(500).rootPath("response").body("status", equalTo("FAILURE")).log().ifError() + .when().put(baseBulkPath + "/" + "wrongBucketID").andReturn().as(BasicResponse.class, ObjectMapper.JAXB); + + response = given().contentType("application/xml").body(bulk, ObjectMapper.JAXB).expect().statusCode(200).rootPath("response").body("status", equalTo("SUCCESS")).log().ifError() + .when().put(baseBulkPath + "/" + bulk.getQuotaRLBucket().getId()).andReturn().as(BasicResponse.class, ObjectMapper.JAXB); + + assertNotNull(response); + assertEquals("SUCCESS", response.getStatus()); + + // Delete step + response = given().contentType("application/xml").body(bulk).expect().statusCode(200).rootPath("response").body("status", equalTo("SUCCESS")).log().ifError().when() + .put(baseBulkPath + "/" + bulk.getQuotaRLBucket().getId() +"/deleteBucket").andReturn().as(BasicResponse.class, ObjectMapper.JAXB); + + assertNotNull(response); + assertEquals("SUCCESS", response.getStatus()); + } + + private void createPolicy(String id) throws Exception { + // CREATE + Policy policy = new Policy(); + + policy.setId(id); + + Context context = new Context(); + + context.setId("anid"); + context.setStatus(Status.ACTIVE); + + policy.getContexts().add(context); + + BasicResponse response = given().contentType("application/xml").body(policy, ObjectMapper.JAXB).expect().statusCode(200).rootPath("response").body("status", equalTo("SUCCESS")).log() + .ifError().when().post(basePoliciesPath).andReturn().as(BasicResponse.class, ObjectMapper.JAXB); + + assertNotNull(response); + assertEquals("SUCCESS", response.getStatus()); + + if (id != null) { + assertEquals(id, response.getId()); + } else { + assertNotNull(response.getId()); + id = response.getId(); + } + + } + + private void deletePolicy(String id) { + BasicResponse response = given().contentType("application/xml").expect().statusCode(200).rootPath("response").body("status", equalTo("SUCCESS")).log().ifError().when() + .delete(basePoliciesPath + "/" + id).andReturn().as(BasicResponse.class, ObjectMapper.JAXB); + + assertNotNull(response); + assertEquals("SUCCESS", response.getStatus()); + } + + public void createAuth(String id) throws Exception { + + Auth data = newAuthProvision(id); + + BasicResponse response = given() + .contentType("application/xml") + .body(data, ObjectMapper.JAXB) + .expect() + .statusCode(200).rootPath("response").body("status", equalTo("SUCCESS")) + .log().ifError() + .when().post(baseAuthPath) + .andReturn().as(BasicResponse.class, ObjectMapper.JAXB); + + assertNotNull(response); + assertEquals("SUCCESS", response.getStatus()); + + } + + private void deleteAuth(String id) { + BasicResponse response = given().contentType("application/xml").expect().statusCode(200).rootPath("response").body("status", equalTo("SUCCESS")).log().ifError().when() + .delete(baseAuthPath + "/" + id).andReturn().as(BasicResponse.class, ObjectMapper.JAXB); + + assertNotNull(response); + assertEquals("SUCCESS", response.getStatus()); + + } + + private Auth newAuthProvision(String authId) { + + Auth data = new Auth(); + + data.setId(authId); + data.setType(AuthType.BASIC); + data.setStatus(Status.ACTIVE); + data.setApiContext("apiCtx"); + data.setPolicyContext("policyCtx"); + + data.setBasicAuth(new BasicAuth()); + data.getBasicAuth().setUsername("username0"); + data.getBasicAuth().setPassword(("password0" + authId).getBytes()); + + //data.setIpWhiteListAuth(new IpWhiteListAuth()); + //data.getIpWhiteListAuth().getIp().add("192.168.84.67"); + + //data.setAuthKeyAuth(new AuthKeyAuth()); + //data.getAuthKeyAuth().setKeyValue("keyvaluesgfhjzghjzeg"); + + System.out.println(ObjectMapping.serialize(data, "xml", ObjectMapper.JAXB)); + + return data; + } + + private BulkPolicyQuotaRLBucketType newBulkProvision(String bucketId) { + + BulkPolicyQuotaRLBucketType bulk = new BulkPolicyQuotaRLBucketType(); + PolicyIdsType policies = new PolicyIdsType(); + + bulk.setPolicies(policies); + + policies.getId().add("p_1"); + policies.getId().add("p_2"); + policies.getId().add("p_3"); + + AuthIdsNoIdType authBucket = new AuthIdsNoIdType(); + bulk.setQuotaRLBucket(authBucket); + + authBucket.getAuthIds().add("a_1"); + authBucket.getAuthIds().add("a_2"); + //authBucket.getAuthIds().add("a_3"); + //authBucket.getAuthIds().add("a_4"); + + authBucket.setId(bucketId); + + System.out.println(ObjectMapping.serialize(bulk, "xml", ObjectMapper.JAXB)); + + return bulk; + } +} diff --git a/exposure-engine/provisioning/src/test/java/com/alu/e3/prov/HttpsTemplateTest.java b/exposure-engine/provisioning/src/test/java/com/alu/e3/prov/HttpsTemplateTest.java new file mode 100644 index 0000000..60e19b8 --- /dev/null +++ b/exposure-engine/provisioning/src/test/java/com/alu/e3/prov/HttpsTemplateTest.java @@ -0,0 +1,188 @@ +/** + * Copyright © 2012 Alcatel-Lucent. + * + * See the NOTICE file distributed with this work for additional + * information regarding copyright ownership. + * Licensed to you 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 com.alu.e3.prov; + +import java.util.ArrayList; +import java.util.Arrays; +import java.util.List; + +import org.apache.camel.EndpointInject; +import org.apache.camel.Exchange; +import org.apache.camel.Processor; +import org.apache.camel.Produce; +import org.apache.camel.ProducerTemplate; +import org.apache.camel.component.mock.MockEndpoint; +import org.junit.Test; +import org.junit.runner.RunWith; +import org.springframework.test.annotation.DirtiesContext; +import org.springframework.test.context.ContextConfiguration; +import org.springframework.test.context.junit4.SpringJUnit4ClassRunner; + +import com.alu.e3.common.camel.ExchangeConstantKeys; +import com.alu.e3.prov.restapi.model.Api; +import com.alu.e3.prov.restapi.model.ApiContext; +import com.alu.e3.prov.restapi.model.ApiType; +import com.alu.e3.prov.restapi.model.AuthType; +import com.alu.e3.prov.restapi.model.Authkey; +import com.alu.e3.prov.restapi.model.DynamicTdr; +import com.alu.e3.prov.restapi.model.HTTPSType; +import com.alu.e3.prov.restapi.model.ProvisionAuthentication; +import com.alu.e3.prov.restapi.model.StaticTdr; +import com.alu.e3.prov.restapi.model.TLSMode; +import com.alu.e3.prov.restapi.model.TargetHost; +import com.alu.e3.prov.restapi.model.TdrData; +import com.alu.e3.prov.restapi.model.TdrEnabled; +import com.alu.e3.prov.restapi.model.TdrType; + +@RunWith(SpringJUnit4ClassRunner.class) +@ContextConfiguration(locations = { + "classpath:/spring/provisioning.auth-template-test.xml" + }) +public class HttpsTemplateTest { + + @EndpointInject(uri = "mock:setup") + protected MockEndpoint setup; + + @EndpointInject(uri = "mock:testMessage") + protected MockEndpoint testMessage; + + @Produce(uri = "direct:test") + protected ProducerTemplate producerTemplate; + + @Test + @DirtiesContext + public void testHttpsSuccess() throws Exception { + setup.whenAnyExchangeReceived(new Processor() { + @Override + public void process(Exchange exchange) throws Exception { + setupExchange(exchange, true); + } + }); + + testMessage.setExpectedMessageCount(1); + testMessage.allMessages().body().isNotNull(); + testMessage.allMessages().body().regex( + // Turns on single-line mode + "(?s)\\A.*"+ + ""+ + ".*\\z"); + + producerTemplate.requestBody(String.class); + + testMessage.assertIsSatisfied(); + } + + @Test + @DirtiesContext + public void testHttpSuccess() throws Exception { + setup.whenAnyExchangeReceived(new Processor() { + @Override + public void process(Exchange exchange) throws Exception { + setupExchange(exchange, false); + } + }); + + testMessage.setExpectedMessageCount(1); + testMessage.allMessages().body().isNotNull(); + testMessage.allMessages().body().regex( + // Turns on single-line mode + "(?s)\\A.*"+ + ""+ + ".*\\z"); + + producerTemplate.requestBody(String.class); + + testMessage.assertIsSatisfied(); + } + + private void setupExchange(Exchange exchange, boolean https){ + Api api = new Api(); + + api.setType(ApiType.PASS_THROUGH); + + ApiContext env = new ApiContext(); + env.setId("test"); + + api.setContexts(Arrays.asList(env)); + + List targetList = new ArrayList(); + + api.setEndpoint("www.yahoo.fr"); + + TargetHost to1 = new TargetHost(); + to1.setUrl("http://www.google.com"); + targetList.add(to1); + + TargetHost to2 = new TargetHost(); + to2.setUrl("http://www.google.com?toto=tutu"); + targetList.add(to2); + + TargetHost to3 = new TargetHost(); + to3.setUrl("http://www.google.com?toto=tutu&tata=tete&titi=toto"); + targetList.add(to3); + + env.setTargetHosts(targetList); + + TdrEnabled tdr = new TdrEnabled(); + tdr.setEnabled("true"); + api.setTdrEnabled(tdr); + + + exchange.setProperty(ExchangeConstantKeys.E3_REQUEST_PAYLOAD.toString(), api); + exchange.setProperty(ExchangeConstantKeys.E3_API_ID.toString(), "MyApiID"); + exchange.setProperty(ExchangeConstantKeys.E3_API_ID_ENCODED.toString(), "MonApiIDEncoded"); + exchange.setProperty(ExchangeConstantKeys.E3_PROVISION_ID.toString(), "MyProvId"); + + ProvisionAuthentication auth = new ProvisionAuthentication(); + Authkey authKey = new Authkey(); + authKey.setKeyName("MyAuthkeyValue"); + auth.getAuths().add(AuthType.AUTHKEY); + auth.setAuthKey(authKey); + + HTTPSType httpsType = new HTTPSType(); + httpsType.setEnabled(https); + httpsType.setTlsMode(TLSMode.ONE_WAY); + api.setHttps(httpsType); + + TdrData tdrData = new TdrData(); + + TdrType tdrType = new TdrType(); + tdrType.getType().add("apiRateLimit"); + + DynamicTdr dt = new DynamicTdr(); + dt.setHttpHeaderName("HTTP_HEADER"); + dt.setTdrPropName("propname"); + dt.setTypes(tdrType); + + tdrData.getDynamic().add(dt); + + StaticTdr st = new StaticTdr(); + st.setValue("staticValue"); + st.setTdrPropName("staticName"); + + st.setTypes(tdrType); + + tdrData.getStatic().add(st); + api.setTdr(tdrData); + + api.setAuthentication(auth); + + } + +} diff --git a/exposure-engine/provisioning/src/test/java/com/alu/e3/prov/IDHelperTest.java b/exposure-engine/provisioning/src/test/java/com/alu/e3/prov/IDHelperTest.java new file mode 100644 index 0000000..5999563 --- /dev/null +++ b/exposure-engine/provisioning/src/test/java/com/alu/e3/prov/IDHelperTest.java @@ -0,0 +1,86 @@ +/** + * Copyright © 2012 Alcatel-Lucent. + * + * See the NOTICE file distributed with this work for additional + * information regarding copyright ownership. + * Licensed to you 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 com.alu.e3.prov; + +import static org.junit.Assert.assertFalse; +import static org.junit.Assert.assertNotNull; +import static org.junit.Assert.assertTrue; + +import org.junit.Test; + +import com.alu.e3.prov.lifecycle.IDHelper; + +public class IDHelperTest { + + @Test + public void testExtractApiIdFromFileName() { + String fileName1 = "41504969443a31363634-41504969443a31363634.xml"; + + String apiId1 = IDHelper.extractApiIdFromFileName(fileName1); + assertNotNull("Extracted apiId must be not null", apiId1); + assertTrue("apiId must be 'APIiD:1664'", "APIiD:1664".equals(apiId1)); + + String fileName2 = "41504969443a31363634-41504969443a31363634.jar"; + + String apiId2 = IDHelper.extractApiIdFromFileName(fileName2); + assertNotNull("Extracted apiId must be not null", apiId1); + assertTrue("apiId must be 'APIiD:1664'", "APIiD:1664".equals(apiId2)); + + } + + @Test + public void testExtractAllFromFileName() { + String fileName1 = "41504969443a31363634-41504969443a31363634.xml"; + + String[] datas1 = IDHelper.extractAllFromFileName(fileName1); + assertNotNull("Extracted datas must be not null", datas1); + assertTrue("Extracted datas must contains 3 value", datas1.length == 3); + assertTrue("datas[0] must be '41504969443a31363634'", "41504969443a31363634".equals(datas1[0])); + assertTrue("datas[1] must be 'APIiD:1664'", "APIiD:1664".equals(datas1[1])); + assertTrue("datas[2] must be '41504969443a31363634'", "41504969443a31363634".equals(datas1[2])); + } + + @Test + public void testGenerateUID() { + String uid1 = IDHelper.generateUID(); + assertNotNull("Generated UID must not be null", uid1); + + String uid2 = IDHelper.generateUID(); + assertNotNull("Generated UID must not be null", uid1); + + assertFalse("Two generated UID must be different", uid1.equals(uid2)); + } + + @Test + public void testEncode() { + String uid = "APIiD:1664"; + String uidEncoded = IDHelper.encode(uid); + + assertTrue("Encoded UID must be '41504969443a31363634'", "41504969443a31363634".equals(uidEncoded)); + } + + @Test + public void testDecode() { + String uidEncoded = "41504969443a31363634"; + String uid = IDHelper.decode(uidEncoded); + + assertTrue("Decoded UID must be 'APIiD:1664'", "APIiD:1664".equals(uid)); + } + +} diff --git a/exposure-engine/provisioning/src/test/java/com/alu/e3/prov/MockCacheManager.java b/exposure-engine/provisioning/src/test/java/com/alu/e3/prov/MockCacheManager.java new file mode 100644 index 0000000..fff1328 --- /dev/null +++ b/exposure-engine/provisioning/src/test/java/com/alu/e3/prov/MockCacheManager.java @@ -0,0 +1,65 @@ +/** + * Copyright © 2012 Alcatel-Lucent. + * + * See the NOTICE file distributed with this work for additional + * information regarding copyright ownership. + * Licensed to you 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 com.alu.e3.prov; + +import java.util.Map; + +import com.alu.e3.common.caching.IAckData; +import com.alu.e3.common.caching.ICacheManager; +import com.alu.e3.common.caching.ICacheQueue; +import com.alu.e3.common.caching.ICacheTable; + +public class MockCacheManager implements ICacheManager{ + + private ICacheManager cacheManager; + + public MockCacheManager() { + } + + public ICacheTable createTable(String name, boolean isReplicated, Map properties) { + return cacheManager.createTable(name, isReplicated, properties); + } + + public ICacheTable createOrGetTable(String name, boolean isReplicated, Map properties) { + return cacheManager.createOrGetTable(name, isReplicated, properties); + + } + + @Override + public ICacheTable createAckTable(String name, boolean isReplicated, Map properties) { + return cacheManager.createTable(name, isReplicated, properties); + + } + + @Override + public ICacheQueue createQueue(String name, Map properties) { + return cacheManager.createQueue(name, properties); + } + + @Override + public ICacheQueue getOrCreateQueue(String name, Map properties) { + return cacheManager.getOrCreateQueue(name, properties); + + } + + public void setCacheManager(ICacheManager cacheManager) { + this.cacheManager = cacheManager; + } + +}; \ No newline at end of file diff --git a/exposure-engine/provisioning/src/test/java/com/alu/e3/prov/PolicyManagerTest.java b/exposure-engine/provisioning/src/test/java/com/alu/e3/prov/PolicyManagerTest.java new file mode 100644 index 0000000..7a70ada --- /dev/null +++ b/exposure-engine/provisioning/src/test/java/com/alu/e3/prov/PolicyManagerTest.java @@ -0,0 +1,177 @@ +/** + * Copyright © 2012 Alcatel-Lucent. + * + * See the NOTICE file distributed with this work for additional + * information regarding copyright ownership. + * Licensed to you 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 com.alu.e3.prov; + +import static com.jayway.restassured.RestAssured.given; +import static org.hamcrest.CoreMatchers.equalTo; +import static org.junit.Assert.assertNotNull; +import static org.junit.Assert.assertEquals; + +import org.junit.After; +import org.junit.AfterClass; +import org.junit.Before; +import org.junit.BeforeClass; +import org.junit.Test; +import org.junit.runner.RunWith; +import org.springframework.test.context.ContextConfiguration; +import org.springframework.test.context.junit4.SpringJUnit4ClassRunner; + +import com.alu.e3.common.E3Constant; +import com.alu.e3.prov.restapi.model.BasicResponse; +import com.alu.e3.prov.restapi.model.Context; +import com.alu.e3.prov.restapi.model.Policy; +import com.alu.e3.prov.restapi.model.Status; +import com.jayway.restassured.RestAssured; +import com.jayway.restassured.mapper.ObjectMapper; + +@RunWith(SpringJUnit4ClassRunner.class) +@ContextConfiguration(locations = { + "classpath:/spring/provisioning.osgi-context-test.xml", + "classpath:/spring/provisioning.provision-beans-test.xml", + "classpath:/spring/provisioning.rest-declaration-test.xml" + }) +public class PolicyManagerTest { + + private String apiVersion = E3Constant.REST_API_VERSION; + + /** + * @throws java.lang.Exception + */ + @BeforeClass + public static void setUpBeforeClass() throws Exception { + + + } + + /** + * @throws java.lang.Exception + */ + @AfterClass + public static void tearDownAfterClass() throws Exception { + } + + /** + * @throws java.lang.Exception + */ + @Before + public void setUp() throws Exception { + RestAssured.baseURI = "http://localhost"; RestAssured.port = 2666; + RestAssured.basePath = "/cxf/e3/prov/"+apiVersion+"/policies"; + + RestAssured.rootPath = "response"; + } + + /** + * @throws java.lang.Exception + */ + @After + public void tearDown() throws Exception { + } + + private void baseTestCreateUpdateDeletePolicy(String id) throws Exception { + // CREATE + Policy policy = new Policy(); + + policy.setId(id); + + Context context = new Context(); + + context.setId("anid"); + context.setStatus(Status.ACTIVE); + + policy.getContexts().add(context); + + BasicResponse response = given() + .contentType("application/xml") + .body(policy, ObjectMapper.JAXB) + .expect() + .statusCode(200) + .rootPath("response") + .body("status", equalTo("SUCCESS")) + .log().ifError() + .when() + .post("") + .andReturn() + .as(BasicResponse.class, ObjectMapper.JAXB); + + assertNotNull(response); + assertEquals("SUCCESS", response.getStatus()); + + if (id != null) + { + assertEquals(id, response.getId()); + } + else + { + assertNotNull(response.getId()); + id = response.getId(); + } + + // UPDATE + context = new Context(); + + context.setId("anotherid"); + context.setStatus(Status.ACTIVE); + policy.getContexts().add(context); + + response = given() + .contentType("application/xml") + .body(policy, ObjectMapper.JAXB) + .expect() + .statusCode(200) + .rootPath("response") + .body("status", equalTo("SUCCESS")) + .log().ifError() + .when() + .put("/" + id) + .andReturn() + .as(BasicResponse.class, ObjectMapper.JAXB); + + assertNotNull(response); + assertEquals("SUCCESS", response.getStatus()); + + // DELETE + response = given() + .contentType("application/xml") + .body(policy, ObjectMapper.JAXB) + .expect() + .statusCode(200) + .rootPath("response") + .body("status", equalTo("SUCCESS")) + .log().ifError() + .when() + .delete("/" + id) + .andReturn() + .as(BasicResponse.class, ObjectMapper.JAXB); + + assertNotNull(response); + assertEquals("SUCCESS", response.getStatus()); + } + + @Test + public void testCreateUpdateDeletePolicy() throws Exception { + baseTestCreateUpdateDeletePolicy("12345"); + } + + @Test + public void testCreatePolicyNoID() throws Exception { + baseTestCreateUpdateDeletePolicy(null); + } + +} diff --git a/exposure-engine/provisioning/src/test/java/com/alu/e3/prov/SecuredRestApiTest.java b/exposure-engine/provisioning/src/test/java/com/alu/e3/prov/SecuredRestApiTest.java new file mode 100644 index 0000000..3e2f676 --- /dev/null +++ b/exposure-engine/provisioning/src/test/java/com/alu/e3/prov/SecuredRestApiTest.java @@ -0,0 +1,107 @@ +/** + * Copyright © 2012 Alcatel-Lucent. + * + * See the NOTICE file distributed with this work for additional + * information regarding copyright ownership. + * Licensed to you 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 com.alu.e3.prov; + +import static com.jayway.restassured.RestAssured.given; +import junit.framework.TestCase; + +import org.apache.cxf.common.util.Base64Utility; +import org.junit.After; +import org.junit.AfterClass; +import org.junit.Before; +import org.junit.BeforeClass; +import org.junit.Test; +import org.junit.runner.RunWith; +import org.springframework.test.context.ContextConfiguration; +import org.springframework.test.context.junit4.SpringJUnit4ClassRunner; + +import com.alu.e3.common.E3Constant; +import com.jayway.restassured.RestAssured; + +@RunWith(SpringJUnit4ClassRunner.class) +@ContextConfiguration(locations = { "classpath:/spring/provisioning.osgi-context-test.xml", "classpath:/spring/provisioning.provision-beans-test.xml", + "classpath:/spring/provisioning.rest-declaration-test.xml" }) +public class SecuredRestApiTest extends TestCase { + + private String apiVersion = E3Constant.REST_API_VERSION; + + private String username = "changeit"; + private String password = "changeit"; + + private String basicAuthCredentials = null; + + @BeforeClass + public static void setUpBeforeClass() throws Exception { + } + + /** + * @throws java.lang.Exception + */ + @AfterClass + public static void tearDownAfterClass() throws Exception { + } + + /** + * @throws java.lang.Exception + */ + @Before + public void setUp() throws Exception { + + // Security.setProperty("keystore.type", "jks"); + // RestAssured.keystore(resources.getJksTrustStore().getFile(), + // truststorePassword); + + RestAssured.baseURI = "http://localhost"; + RestAssured.port = 2667; + RestAssured.basePath = "/cxf/e3/prov/" + apiVersion + "/apis"; + + basicAuthCredentials = Base64Utility.encode((username + ":" + password).getBytes()); + } + + /** + * @throws java.lang.Exception + */ + @After + public void tearDown() throws Exception { + } + + @Test + public void testRestassured() throws Exception { + try { + given().header("Authorization", "Basic " + basicAuthCredentials).get("/"); + } finally { + RestAssured.reset(); + } + } + + @Test + public void testRestassured_Failure() throws Exception { + try { + + given().header("Authorization", "Basic wrongBasicAuthCredentials").expect().statusCode(401).get("/"); + } + catch (Exception e) { + + } + finally { + RestAssured.reset(); + } + } + +} diff --git a/exposure-engine/provisioning/src/test/java/com/alu/e3/prov/TrustStoreManagerTest.java b/exposure-engine/provisioning/src/test/java/com/alu/e3/prov/TrustStoreManagerTest.java new file mode 100644 index 0000000..81f0e70 --- /dev/null +++ b/exposure-engine/provisioning/src/test/java/com/alu/e3/prov/TrustStoreManagerTest.java @@ -0,0 +1,248 @@ +/** + * Copyright © 2012 Alcatel-Lucent. + * + * See the NOTICE file distributed with this work for additional + * information regarding copyright ownership. + * Licensed to you 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 com.alu.e3.prov; + +import static com.jayway.restassured.RestAssured.given; +import static org.hamcrest.CoreMatchers.equalTo; +import static org.junit.Assert.assertNotNull; +import static org.junit.Assert.assertEquals; + +import org.junit.After; +import org.junit.AfterClass; +import org.junit.Before; +import org.junit.BeforeClass; +import org.junit.Test; +import org.junit.runner.RunWith; +import org.springframework.test.context.ContextConfiguration; +import org.springframework.test.context.junit4.SpringJUnit4ClassRunner; + +import com.alu.e3.common.E3Constant; +import com.alu.e3.prov.restapi.model.BasicResponse; +import com.alu.e3.prov.restapi.model.SSLCRL; +import com.alu.e3.prov.restapi.model.SSLCert; +import com.jayway.restassured.RestAssured; +import com.jayway.restassured.mapper.ObjectMapper; + +@RunWith(SpringJUnit4ClassRunner.class) +@ContextConfiguration(locations = { + "classpath:/spring/provisioning.osgi-context-test.xml", + "classpath:/spring/provisioning.provision-beans-test.xml", + "classpath:/spring/provisioning.rest-declaration-test.xml" + }) +public class TrustStoreManagerTest { + + private String apiVersion = E3Constant.REST_API_VERSION; + + /** + * @throws java.lang.Exception + */ + @BeforeClass + public static void setUpBeforeClass() throws Exception { + + + } + + /** + * @throws java.lang.Exception + */ + @AfterClass + public static void tearDownAfterClass() throws Exception { + } + + /** + * @throws java.lang.Exception + */ + @Before + public void setUp() throws Exception { + RestAssured.baseURI = "http://localhost"; RestAssured.port = 2666; + RestAssured.basePath = "/cxf/e3/prov/"+apiVersion+"/truststore"; + + RestAssured.rootPath = "response"; + } + + /** + * @throws java.lang.Exception + */ + @After + public void tearDown() throws Exception { + } + + private void baseTestCreateUpdateDeleteCA(String id) throws Exception { + // CREATE + SSLCert cert = new SSLCert(); + + cert.setId(id); + cert.setContent("iurezahfskdqhflk"); + + BasicResponse response = given() + .contentType("application/xml") + .body(cert, ObjectMapper.JAXB) + .expect() + .statusCode(200) + .rootPath("response") + .body("status", equalTo("SUCCESS")) + .log().ifError() + .when() + .post("/certs") + .andReturn() + .as(BasicResponse.class, ObjectMapper.JAXB); + + assertNotNull(response); + assertEquals("SUCCESS", response.getStatus()); + + if (id != null) + { + assertEquals(id, response.getId()); + } + else + { + assertNotNull(response.getId()); + id = response.getId(); + } + + // UPDATE + cert.setContent(null); + cert.setDisplayName("titi"); + + response = given() + .contentType("application/xml") + .body(cert, ObjectMapper.JAXB) + .expect() + .statusCode(200) + .rootPath("response") + .body("status", equalTo("SUCCESS")) + .log().ifError() + .when() + .put("/certs/" + id) + .andReturn() + .as(BasicResponse.class, ObjectMapper.JAXB); + + assertNotNull(response); + assertEquals("SUCCESS", response.getStatus()); + + // DELETE + response = given() + .contentType("application/xml") + .body(cert, ObjectMapper.JAXB) + .expect() + .statusCode(200) + .rootPath("response") + .body("status", equalTo("SUCCESS")) + .log().ifError() + .when() + .delete("/certs/" + id) + .andReturn() + .as(BasicResponse.class, ObjectMapper.JAXB); + + assertNotNull(response); + assertEquals("SUCCESS", response.getStatus()); + } + + @Test + public void testCreateUpdateDeleteCA() throws Exception { + baseTestCreateUpdateDeleteCA("12345"); + } + + @Test + public void testCreateCANoID() throws Exception { + baseTestCreateUpdateDeleteCA(null); + } + + private void baseTestCreateUpdateDeleteCRL(String id) throws Exception { + // CREATE + SSLCRL crl = new SSLCRL(); + + crl.setId(id); + String content = "abc"; + crl.setContent(content); + + BasicResponse response = given() + .contentType("application/xml") + .body(crl, ObjectMapper.JAXB) + .expect() + .statusCode(200) + .rootPath("response") + .body("status", equalTo("SUCCESS")) + .log().ifError() + .when() + .post("/crls") + .andReturn() + .as(BasicResponse.class, ObjectMapper.JAXB); + + assertNotNull(response); + assertEquals("SUCCESS", response.getStatus()); + + if (id != null) + { + assertEquals(id, response.getId()); + } + else + { + assertNotNull(response.getId()); + id = response.getId(); + } + + // UPDATE + crl.setContent(null); + crl.setDisplayName("toto"); + + response = given() + .contentType("application/xml") + .body(crl, ObjectMapper.JAXB) + .expect() + .statusCode(200) + .rootPath("response") + .body("status", equalTo("SUCCESS")) + .log().ifError() + .when() + .put("/crls/" + id) + .andReturn() + .as(BasicResponse.class, ObjectMapper.JAXB); + + assertNotNull(response); + assertEquals("SUCCESS", response.getStatus()); + + // DELETE + response = given() + .contentType("application/xml") + .body(crl, ObjectMapper.JAXB) + .expect() + .statusCode(200) + .rootPath("response") + .body("status", equalTo("SUCCESS")) + .log().ifError() + .when() + .delete("/crls/" + id) + .andReturn() + .as(BasicResponse.class, ObjectMapper.JAXB); + + assertNotNull(response); + assertEquals("SUCCESS", response.getStatus()); + } + + @Test + public void testCreateUpdateDeleteCRL() throws Exception { + baseTestCreateUpdateDeleteCRL("98765"); + } + + @Test + public void testCreateCRLNoID() throws Exception { + baseTestCreateUpdateDeleteCRL(null); + } +} diff --git a/exposure-engine/provisioning/src/test/java/com/alu/e3/prov/deployment/MockDeploymentManager.java b/exposure-engine/provisioning/src/test/java/com/alu/e3/prov/deployment/MockDeploymentManager.java new file mode 100644 index 0000000..30c37d3 --- /dev/null +++ b/exposure-engine/provisioning/src/test/java/com/alu/e3/prov/deployment/MockDeploymentManager.java @@ -0,0 +1,101 @@ +/** + * Copyright © 2012 Alcatel-Lucent. + * + * See the NOTICE file distributed with this work for additional + * information regarding copyright ownership. + * Licensed to you 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 com.alu.e3.prov.deployment; + +import com.alu.e3.prov.restapi.ExchangeData; + +public class MockDeploymentManager implements IDeploymentManager { + + public MockDeploymentManager() { + } + + @Override + public void deployApi(ExchangeData exchange, byte[] jarData) throws DeploymentException { + + } + + @Override + public void undeployApi(ExchangeData exchange, String apiId) throws DeploymentException { + + } + + public static class FirstDeployOkSecondDeployKoUndeployOk extends MockDeploymentManager { + boolean firstTime = true; + + @Override + public void deployApi(ExchangeData exchange, byte[] jarData) throws DeploymentException { + if (firstTime) { + firstTime = false; + // ok + } else { + throw new DeploymentException(1, "Deployment failure testing"); + } + + } + + } + + public static class FirstDeployKoSecondDeployOkUndeployKo extends MockDeploymentManager { + boolean firstTime = true; + + @Override + public void deployApi(ExchangeData exchange, byte[] jarData) throws DeploymentException { + if (firstTime) { + firstTime = false; + throw new DeploymentException(1, "Deployment failure testing"); + } else { + // Ok + } + + } + + @Override + public void undeployApi(ExchangeData exchange, String apiId) throws DeploymentException { + throw new DeploymentException(1, "UnDeployment failure testing"); + } + } + + public static class DeployOk extends MockDeploymentManager { + + } + + public static class DeployKO extends MockDeploymentManager { + @Override + public void deployApi(ExchangeData exchange, byte[] jarData) throws DeploymentException { + throw new DeploymentException(1, "Deployment failure testing"); + } + + } + + public static class DeployOkUndeployOk extends MockDeploymentManager { + + } + + public static class DeployKoUndeployKo extends MockDeploymentManager { + @Override + public void deployApi(ExchangeData exchange, byte[] jarData) throws DeploymentException { + throw new DeploymentException(1, "Deployment failure testing"); + } + + @Override + public void undeployApi(ExchangeData exchange, String apiId) throws DeploymentException { + throw new DeploymentException(1, "UnDeployment failure testing"); + } + } +} diff --git a/exposure-engine/provisioning/src/test/java/com/alu/e3/prov/service/ApiServiceTest.java b/exposure-engine/provisioning/src/test/java/com/alu/e3/prov/service/ApiServiceTest.java new file mode 100644 index 0000000..8fc6dd1 --- /dev/null +++ b/exposure-engine/provisioning/src/test/java/com/alu/e3/prov/service/ApiServiceTest.java @@ -0,0 +1,321 @@ +/** + * Copyright © 2012 Alcatel-Lucent. + * + * See the NOTICE file distributed with this work for additional + * information regarding copyright ownership. + * Licensed to you 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 com.alu.e3.prov.service; + +import java.util.Arrays; +import java.util.List; +import java.util.Random; + +import static org.junit.Assert.assertTrue; +import static org.junit.Assert.assertFalse; +import static org.junit.Assert.assertNotNull; +import static org.junit.Assert.assertEquals; +import static org.junit.Assert.fail; + +import org.junit.After; +import org.junit.AfterClass; +import org.junit.Before; +import org.junit.BeforeClass; +import org.junit.Test; +import org.junit.runner.RunWith; +import org.springframework.beans.factory.annotation.Autowired; +import org.springframework.test.context.ContextConfiguration; +import org.springframework.test.context.junit4.SpringJUnit4ClassRunner; + +import com.alu.e3.common.InvalidIDException; +import com.alu.e3.data.DataManager; +import com.alu.e3.prov.ApplicationCodeConstants; +import com.alu.e3.prov.ProvisionException; +import com.alu.e3.prov.deployment.MockDeploymentManager; +import com.alu.e3.prov.deployment.RollbackException; +import com.alu.e3.prov.restapi.ExchangeData; +import com.alu.e3.prov.restapi.model.Api; +import com.alu.e3.prov.restapi.model.ApiContext; +import com.alu.e3.prov.restapi.model.ApiType; +import com.alu.e3.prov.restapi.model.AuthType; +import com.alu.e3.prov.restapi.model.Authentication; +import com.alu.e3.prov.restapi.model.Authkey; +import com.alu.e3.prov.restapi.model.Data; +import com.alu.e3.prov.restapi.model.DynamicTdr; +import com.alu.e3.prov.restapi.model.HTTPSType; +import com.alu.e3.prov.restapi.model.Key; +import com.alu.e3.prov.restapi.model.ProvisionAuthentication; +import com.alu.e3.prov.restapi.model.StaticTdr; +import com.alu.e3.prov.restapi.model.Status; +import com.alu.e3.prov.restapi.model.TargetHost; +import com.alu.e3.prov.restapi.model.TdrData; +import com.alu.e3.prov.restapi.model.TdrEnabled; +import com.alu.e3.prov.restapi.model.TdrType; + +@RunWith(SpringJUnit4ClassRunner.class) +@ContextConfiguration(locations = { + "classpath:/spring/provisioning.osgi-context-test.xml", + "classpath:/spring/provisioning.provision-beans-test.xml" + }) +public class ApiServiceTest { + + private ApiService apiService; + + @BeforeClass + public static void setUpBeforeClass() throws Exception { + } + + @AfterClass + public static void tearDownAfterClass() throws Exception { + } + + @Before + public void setUp() throws Exception { + } + + @After + public void tearDown() throws Exception { + } + + + @Test + public void testApiService() throws Exception { + Api api = newApi(); + try { + apiService.create(api); + apiService.update(api); + Api getApi = apiService.get(api.getId()); + assertNotNull(getApi); + + List ids = apiService.getAll(); + assertNotNull(ids); + assertFalse(ids.isEmpty()); + + apiService.delete(api.getId()); + + boolean isInvalidID = false; + + try { + apiService.get(api.getId()); + } catch (InvalidIDException e) { + isInvalidID = true; + } + + assertTrue(isInvalidID); + + } catch (ProvisionException e) { + fail("Update Api failure"); + e.printStackTrace(); + + } + } + + + + + + @Test + public void testDeploy() throws Exception { + Api api = newApi(); + try { + apiService.setDeploymentManager(new MockDeploymentManager.DeployOk()); + + apiService.deployApi(api, ApiService.createExchange(api)); + + } catch (ProvisionException e) { + fail("Create Api failure"); + e.printStackTrace(); + + } + } + + @Test + public void testRollback_DeployKo() throws Exception { + Api api = newApi(); + try { + // setup old jar in dataManager + byte[] oldJar = new byte[] { 0, 1 }; + ((DataManager) apiService.getDataManager()).deployApi(api.getId(), oldJar); + + // mock deploymentManager scenario + apiService.setDeploymentManager(new MockDeploymentManager.DeployKO()); + + ExchangeData exchange = ApiService.createExchange(api); + apiService.deployApi(api, exchange); + + } catch (RollbackException e) { + assertEquals(ApplicationCodeConstants.ROLLBACK_FAILED, e.getErrorCode()); + + } catch (ProvisionException e) { + fail("Rollback Api failure"); + e.printStackTrace(); + + } + } + + + @Test + public void testRollback_UndeployKo() throws Exception { + Api api = newApi(); + try { + // setup + byte[] oldJar = new byte[] { 0, 1 }; + ((DataManager) apiService.getDataManager()).deployApi(api.getId(), oldJar); + + apiService.setDeploymentManager(new MockDeploymentManager.FirstDeployKoSecondDeployOkUndeployKo()); + + ExchangeData exchange = ApiService.createExchange(api); + apiService.deployApi(api, exchange); + + } catch (ProvisionException e) { + assertEquals(1, e.getErrorCode()); + + } catch (Exception e) { + fail("Rollback Api failure"); + e.printStackTrace(); + } + } + + @Test + public void testRollback_FirstDeployOkSecondDeployKoUndeployOk() throws Exception { + Api api = newApi(); + try { + // setup + byte[] oldJar = new byte[] { 0, 1 }; + ((DataManager) apiService.getDataManager()).deployApi(api.getId(), oldJar); + + apiService.setDeploymentManager(new MockDeploymentManager.FirstDeployOkSecondDeployKoUndeployOk()); + + ExchangeData exchange = ApiService.createExchange(api); + apiService.deployApi(api, exchange); + + } catch (ProvisionException e) { + assertEquals(1, e.getErrorCode()); + + } catch (Exception e) { + fail("Rollback Api failure"); + e.printStackTrace(); + } + } + + + + @Test + public void testRollback_FirstDeployKoUndeployOk_NoOldJar() throws Exception { + Api api = newApi(); + try { + + apiService.setDeploymentManager(new MockDeploymentManager.DeployKoUndeployKo()); + + ExchangeData exchange = ApiService.createExchange(api); + apiService.deployApi(api, exchange); + + } catch (ProvisionException e) { + assertEquals(1, e.getErrorCode()); + + } catch (Exception e) { + fail("Rollback Api failure"); + e.printStackTrace(); + } + } + + @Autowired + public void setApiService(ApiService apiService) { + this.apiService = apiService; + } + + private Api newApi() { + + Api api = new Api(); + + ApiContext env = new ApiContext(); + env.setDefaultContext(true); + env.setId("test"); + api.getContexts().add(env); + + env.setStatus(Status.ACTIVE); + /* + * env.setMaxRateLimitTPMThreshold(1); env.setMaxRateLimitTPMWarning(1); + * env.setMaxRateLimitTPSThreshold(1); env.setMaxRateLimitTPSWarning(1); + */ + + api.setId("getLocation" + (new Random().nextLong())); + api.setDisplayName("test"); + api.setType(ApiType.PASS_THROUGH); + api.setVersion("1.0"); + api.setEndpoint("AEndpointURL"); + + api.setStatus(Status.ACTIVE); + + ProvisionAuthentication pauth = new ProvisionAuthentication(); + Authkey authKey = new Authkey(); + authKey.setKeyName("key"); + pauth.setAuthKey(authKey); + + api.setAuthentication(pauth); + + pauth.getAuths().add(AuthType.AUTHKEY); + pauth.getAuths().add(AuthType.BASIC); + pauth.getAuths().add(AuthType.IP_WHITE_LIST); + + TargetHost th = new TargetHost(); + th.setUrl("http://www.yahoo.com"); + + TargetHost th2 = new TargetHost(); + th2.setUrl("http://www.google.com"); + + Authentication auth = new Authentication(); + auth.setType("NoAuth"); + Data d = new Data(); + Key k = new Key(); + k.setName("aKey00"); + k.setValue("key000Val"); + d.setKey(Arrays.asList(k)); + auth.setData(d); + th.setAuthentication(auth); + th2.setAuthentication(auth); + + env.setTargetHosts(Arrays.asList(th, th2)); + api.setTdrEnabled(new TdrEnabled()); + api.getTdrEnabled().setEnabled("true"); + + HTTPSType httpsType = new HTTPSType(); + httpsType.setEnabled(true); + httpsType.setTlsMode(com.alu.e3.prov.restapi.model.TLSMode.ONE_WAY); + api.setHttps(httpsType); + + TdrData tdrData = new TdrData(); + + TdrType tdrType = new TdrType(); + tdrType.getType().add("apiRateLimit"); + + DynamicTdr dt = new DynamicTdr(); + dt.setHttpHeaderName("HTTP_HEADER"); + dt.setTdrPropName("propname"); + dt.setTypes(tdrType); + + tdrData.getDynamic().add(dt); + + StaticTdr st = new StaticTdr(); + st.setValue("staticValue"); + st.setTdrPropName("staticName"); + + st.setTypes(tdrType); + + tdrData.getStatic().add(st); + api.setTdr(tdrData); + + return api; + } +} diff --git a/exposure-engine/provisioning/src/test/java/com/alu/e3/prov/service/FeaturedApiCheck.java b/exposure-engine/provisioning/src/test/java/com/alu/e3/prov/service/FeaturedApiCheck.java new file mode 100644 index 0000000..c02d745 --- /dev/null +++ b/exposure-engine/provisioning/src/test/java/com/alu/e3/prov/service/FeaturedApiCheck.java @@ -0,0 +1,30 @@ +/** + * Copyright © 2012 Alcatel-Lucent. + * + * See the NOTICE file distributed with this work for additional + * information regarding copyright ownership. + * Licensed to you 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 com.alu.e3.prov.service; + + +import com.alu.e3.prov.restapi.model.Api; +import com.alu.e3.prov.service.IFeaturedApiCheck; + +public class FeaturedApiCheck implements IFeaturedApiCheck { + @Override + public final void assertIsAvailableFeature(Api api) { + } + +} diff --git a/exposure-engine/provisioning/src/test/resources/configuration.properties b/exposure-engine/provisioning/src/test/resources/configuration.properties new file mode 100644 index 0000000..0cdd261 --- /dev/null +++ b/exposure-engine/provisioning/src/test/resources/configuration.properties @@ -0,0 +1,5 @@ +provisioning.working.dir=target/PROVISIONING_WORKING_DIR +provisioning.archive.dir=DEPLOYED +provisioning.generate.jar.in.file=false + +default.key.cert.directory=./target/test-classes/grove \ No newline at end of file diff --git a/exposure-engine/provisioning/src/test/resources/grove/README b/exposure-engine/provisioning/src/test/resources/grove/README new file mode 100644 index 0000000..e69de29 diff --git a/exposure-engine/provisioning/src/test/resources/grove/e3.default.crt b/exposure-engine/provisioning/src/test/resources/grove/e3.default.crt new file mode 100644 index 0000000..93f77af --- /dev/null +++ b/exposure-engine/provisioning/src/test/resources/grove/e3.default.crt @@ -0,0 +1,17 @@ +-----BEGIN CERTIFICATE----- +MIICuzCCAiQCCQDxj0dkEy3MLzANBgkqhkiG9w0BAQUFADCBoTELMAkGA1UEBhMC +VVMxEzARBgNVBAgTCkNhbGlmb3JuaWExEzARBgNVBAcTClNhbnRhIENydXoxEzAR +BgNVBAoTClByb2R1Y3RPcHMxFDASBgNVBAsTC2RldmVsb3BtZW50MRMwEQYDVQQD +EwpFcmljIEZ1bHR6MSgwJgYJKoZIhvcNAQkBFhllcmljLmZ1bHR6QHByb2R1Y3Rv +cHMuY29tMB4XDTEyMDUwNDIxMzYxNVoXDTEzMDUwNDIxMzYxNVowgaExCzAJBgNV +BAYTAlVTMRMwEQYDVQQIEwpDYWxpZm9ybmlhMRMwEQYDVQQHEwpTYW50YSBDcnV6 +MRMwEQYDVQQKEwpQcm9kdWN0T3BzMRQwEgYDVQQLEwtkZXZlbG9wbWVudDETMBEG +A1UEAxMKRXJpYyBGdWx0ejEoMCYGCSqGSIb3DQEJARYZZXJpYy5mdWx0ekBwcm9k +dWN0b3BzLmNvbTCBnzANBgkqhkiG9w0BAQEFAAOBjQAwgYkCgYEAxtJijhRJDMVJ +CrVmgMQaKT43+DUjdz28m1OS/wbGyRqZmwHWWXSgPHeuu30Opw/MxpgqlxfqAScZ +4nRfSq3kjENeoNAO8OPbKStT/5Y5HqEE6Ipfy8OU95Q4EbuGdSidrJDyHvWayNjc +GWBbvh7HnDwMkqiETFJZiP3y+ASunJcCAwEAATANBgkqhkiG9w0BAQUFAAOBgQAP +F9XVSlNSk6JJFzF3xA7FmAbB5Bf1kk0xmYt63Q3dsUHX++aVkC/TDnpAexvpA7sE +tKi20XthyjBWTB7KgfnQeoIz0tHJikbjTPo0yNZhv2p9DtApz12sGVIqtC7zR3rU +f1y9BHz8IM584dECmkd3lgBIbx2fClxvPX5zLbTYgw== +-----END CERTIFICATE----- \ No newline at end of file diff --git a/exposure-engine/provisioning/src/test/resources/grove/e3.default.key b/exposure-engine/provisioning/src/test/resources/grove/e3.default.key new file mode 100644 index 0000000..a6b8f05 --- /dev/null +++ b/exposure-engine/provisioning/src/test/resources/grove/e3.default.key @@ -0,0 +1,15 @@ +-----BEGIN RSA PRIVATE KEY----- +MIICXAIBAAKBgQDG0mKOFEkMxUkKtWaAxBopPjf4NSN3PbybU5L/BsbJGpmbAdZZ +dKA8d667fQ6nD8zGmCqXF+oBJxnidF9KreSMQ16g0A7w49spK1P/ljkeoQToil/L +w5T3lDgRu4Z1KJ2skPIe9ZrI2NwZYFu+HsecPAySqIRMUlmI/fL4BK6clwIDAQAB +AoGAMRtnokYaYOAdkVqKrcVB3Ov0MQcW8m26NvcmeHz4/lTmmaWThtbKeQTqkH5r +7xF095w/8L/EWXKJ7yflHXHj392J6TyDb3ejZBR88w+BFYY2Juu1JmKs5VM0yXyT +qr6KOlNJxyFZh1r+tdVtL/e5p9CXa4NTACofLezZfzahCuECQQDoIhU2heuT+C5g +YfVtw6zuB+HI1wurBcmcLXkIsvKAF+YvaC3D+r4rxDLxSAEgvwFTZlkkEiuE5OyE +NhBXZAxxAkEA20OF+ojpDJhqZvo1Gtbxs9DeTZOI62sa7QQ2RmkuE1at9Ek8WHDi +s/TC9VToAszInFZjWj4q6BEmIVceHFddhwJAU6xNZyzYoKqZ1OYaeGlLATXYHfPd +4dShOmltskQGg0OaFkaAEJ9mQxJipnQk6+/Ng4ll4kmmZC28T1/JfiazEQJBAMwk +NORKffg9G6uevryrbMPG7oJ5nxvYT2xm5IVvvfdBV5o+aVHKYDe95Zn2oECjGw/7 +mmrVwKrp9H9MFfu7F5cCQChLP1dOmBYoJpgPD4jrjmbDhMOR39joHuq1Gw8bASRv +7SONE40H7qWAgEtFo8KanhhImJ08lHmbyYefVvQ8M4M= +-----END RSA PRIVATE KEY----- \ No newline at end of file diff --git a/exposure-engine/provisioning/src/test/resources/log4j.properties b/exposure-engine/provisioning/src/test/resources/log4j.properties new file mode 100644 index 0000000..2fcb7bc --- /dev/null +++ b/exposure-engine/provisioning/src/test/resources/log4j.properties @@ -0,0 +1,7 @@ +log4j.rootLogger=ERROR, CA +log4j.logger.org.apache.camel=ERROR +log4j.logger.org.eclipse.jetty=ERROR +log4j.logger.com.alu=DEBUG +log4j.appender.CA=org.apache.log4j.ConsoleAppender +log4j.appender.CA.layout=org.apache.log4j.PatternLayout +log4j.appender.CA.layout.ConversionPattern=%-4r [%t] %-5p %c %x - %m%n \ No newline at end of file diff --git a/exposure-engine/provisioning/src/test/resources/spring/provisioning.auth-template-test.xml b/exposure-engine/provisioning/src/test/resources/spring/provisioning.auth-template-test.xml new file mode 100644 index 0000000..aee90ce --- /dev/null +++ b/exposure-engine/provisioning/src/test/resources/spring/provisioning.auth-template-test.xml @@ -0,0 +1,24 @@ + + + + + + + + + + + + + + \ No newline at end of file diff --git a/exposure-engine/provisioning/src/test/resources/spring/provisioning.osgi-context-test.xml b/exposure-engine/provisioning/src/test/resources/spring/provisioning.osgi-context-test.xml new file mode 100644 index 0000000..db7409e --- /dev/null +++ b/exposure-engine/provisioning/src/test/resources/spring/provisioning.osgi-context-test.xml @@ -0,0 +1,30 @@ + + + + + + + + + + + + + + + + + + + + \ No newline at end of file diff --git a/exposure-engine/provisioning/src/test/resources/spring/provisioning.provision-beans-test.xml b/exposure-engine/provisioning/src/test/resources/spring/provisioning.provision-beans-test.xml new file mode 100644 index 0000000..1a7e007 --- /dev/null +++ b/exposure-engine/provisioning/src/test/resources/spring/provisioning.provision-beans-test.xml @@ -0,0 +1,31 @@ + + + + + + + + + + + + \ No newline at end of file diff --git a/exposure-engine/provisioning/src/test/resources/spring/provisioning.rest-declaration-test.xml b/exposure-engine/provisioning/src/test/resources/spring/provisioning.rest-declaration-test.xml new file mode 100644 index 0000000..a460023 --- /dev/null +++ b/exposure-engine/provisioning/src/test/resources/spring/provisioning.rest-declaration-test.xml @@ -0,0 +1,96 @@ + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + \ No newline at end of file diff --git a/exposure-engine/system-manager/pom.xml b/exposure-engine/system-manager/pom.xml new file mode 100644 index 0000000..5b5c86d --- /dev/null +++ b/exposure-engine/system-manager/pom.xml @@ -0,0 +1,56 @@ + + + 4.0.0 + + + exposure-engine + com.alu.e3 + 1.0.1 + .. + + + system-manager + E3 System Manager + http://www.alcatel-lucent.com + + + jar + + + + com.jcraft + jsch + 0.1.45 + compile + + + com.alu.e3 + common + ${project.version} + jar + provided + + + com.alu.e3 + topology + ${project.version} + jar + provided + + + + org.apache.felix + org.apache.felix.framework + 3.0.9-fuse-03-11 + provided + + + commons-lang + commons-lang + 2.5 + provided + + + + diff --git a/exposure-engine/system-manager/src/main/java/com/alu/e3/BasicAuthFilterWrapper.java b/exposure-engine/system-manager/src/main/java/com/alu/e3/BasicAuthFilterWrapper.java new file mode 100644 index 0000000..e6f3881 --- /dev/null +++ b/exposure-engine/system-manager/src/main/java/com/alu/e3/BasicAuthFilterWrapper.java @@ -0,0 +1,54 @@ +/** + * Copyright © 2012 Alcatel-Lucent. + * + * See the NOTICE file distributed with this work for additional + * information regarding copyright ownership. + * Licensed to you 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 com.alu.e3; + +import javax.ws.rs.core.Response; + +import org.apache.cxf.interceptor.security.AuthenticationException; +import org.apache.cxf.jaxrs.ext.RequestHandler; +import org.apache.cxf.jaxrs.model.ClassResourceInfo; +import org.apache.cxf.message.Message; + +import com.alu.e3.security.BasicAuthenticationFilter; + +public class BasicAuthFilterWrapper implements RequestHandler{ + private BasicAuthenticationFilter basicAuthFilter; + public BasicAuthFilterWrapper(){ + + } + @Override + public Response handleRequest(Message m, ClassResourceInfo resourceClass) { + + Response response = null; + try { + response = basicAuthFilter.handleRequest(m, resourceClass); + } catch (AuthenticationException e) { + response = Response.status(Response.Status.UNAUTHORIZED).header("WWW-Authenticate", "Basic").build(); + } + + return response; + } + public void setBasicAuthFilter(BasicAuthenticationFilter basicAuthFilter) { + this.basicAuthFilter = basicAuthFilter; + } + + + + +} diff --git a/exposure-engine/system-manager/src/main/java/com/alu/e3/SystemManagerInfo.java b/exposure-engine/system-manager/src/main/java/com/alu/e3/SystemManagerInfo.java new file mode 100644 index 0000000..df6d671 --- /dev/null +++ b/exposure-engine/system-manager/src/main/java/com/alu/e3/SystemManagerInfo.java @@ -0,0 +1,44 @@ +/** + * Copyright © 2012 Alcatel-Lucent. + * + * See the NOTICE file distributed with this work for additional + * information regarding copyright ownership. + * Licensed to you 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 com.alu.e3; + +import com.alu.e3.common.logging.Category; +import com.alu.e3.common.logging.CategoryLogger; +import com.alu.e3.common.logging.CategoryLoggerFactory; +import com.alu.e3.common.osgi.api.IInstanceInfo; + +public class SystemManagerInfo { + private static final CategoryLogger logger = CategoryLoggerFactory.getLogger(SystemManagerInfo.class, Category.SYS); + protected IInstanceInfo instanceInfo; + + public void setInstanceInfo(IInstanceInfo instanceInfo) { + this.instanceInfo = instanceInfo; + } + + public SystemManagerInfo() {} + + public void init() { + logger.warn("Elected as manager"); + instanceInfo.setManager(true); + } + +} diff --git a/exposure-engine/system-manager/src/main/java/com/alu/e3/SystemManagerService.java b/exposure-engine/system-manager/src/main/java/com/alu/e3/SystemManagerService.java new file mode 100644 index 0000000..6ec9549 --- /dev/null +++ b/exposure-engine/system-manager/src/main/java/com/alu/e3/SystemManagerService.java @@ -0,0 +1,162 @@ +/** + * Copyright © 2012 Alcatel-Lucent. + * + * See the NOTICE file distributed with this work for additional + * information regarding copyright ownership. + * Licensed to you 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 com.alu.e3; + +import java.io.File; +import java.io.IOException; +import java.io.InputStream; +import java.net.URL; +import java.util.Enumeration; +import java.util.jar.Attributes; +import java.util.jar.JarFile; +import java.util.jar.Manifest; + +import javax.ws.rs.GET; +import javax.ws.rs.Path; +import javax.ws.rs.PathParam; +import javax.ws.rs.core.Response; + +import org.apache.cxf.jaxrs.ext.Description; +import org.osgi.framework.BundleContext; +import org.springframework.beans.factory.annotation.Autowired; + +import com.alu.e3.common.logging.Category; +import com.alu.e3.common.logging.CategoryLogger; +import com.alu.e3.common.logging.CategoryLoggerFactory; +import com.alu.e3.common.spring.SpringContextBootstrapper; +import com.alu.e3.installer.Installer; +import com.alu.e3.osgi.api.ITopology; +import com.alu.e3.topology.model.Topology; + + +@Path("/system-manager/") +public class SystemManagerService { + + private static final CategoryLogger logger = CategoryLoggerFactory.getLogger(SystemManagerService.class, Category.SYS); + + @Autowired + private BundleContext bundleContext; + + private ITopology topology; + + @Autowired + private SpringContextBootstrapper springContextBootstrapper; + + public SystemManagerService() {} + + public void setTopology(ITopology topology) { + this.topology = topology; + } + + /** + *

Ask the SystemManager to install E3 on the machines described in the topology configuration file. + *

The path specified should contain the configuration files installer-config.xml and topology.xml. + * + * @param pathToConfigFilesDirectory the path to configuration files directory (URL encoded) + * @returnWrapped java.lang.String A message for the execution status + * @HTTP 200 in case of success + * @HTTP 201 in case of errors + * @RequestHeader No specific request header needed + * @ResponseHeader No specific response header needed + */ + @GET + @Path("/install/{pathToConfigFilesDirectory}") + @Description(value = "Ask the SystemManager to install E3 on the machines described in the topology configuration file. The path specified should contain the configuration files installer-config.xml and topology.xml.") + public Response install(@PathParam("pathToConfigFilesDirectory") String pathToConfigFilesDirectory) { + + String configFilePath = System.getProperty("user.home") + File.separator + "installer-config.xml"; + String topologyFilePath = System.getProperty("user.home") + File.separator + "topology.xml"; + + File srcConfigFile = new File(pathToConfigFilesDirectory + "/installer-config.xml"); + File srcTopologyFile = new File(pathToConfigFilesDirectory + "/topology.xml"); + + File dstConfigFile = new File(configFilePath); + File dstTopologyFile = new File(topologyFilePath); + + + + try { + + Topology tmpTopology = topology.getTopologyFromFile(srcTopologyFile.getAbsolutePath()); + + logger.debug("Installing E3 on all topology targets ..."); + + Installer installer = new Installer(srcConfigFile.getAbsolutePath(), tmpTopology, springContextBootstrapper); + installer.deploy(); + + logger.debug("Installation of all topology targets done."); + + logger.debug("Copying configFile and topologyFile to home user ..."); + // The deploy has succeed, we can override manager topology + // Copying topology and configuration files + Utilities.copyFile(srcConfigFile, dstConfigFile, true); + Utilities.copyFile(srcTopologyFile, dstTopologyFile, true); + logger.debug("Copy done."); + + logger.debug("No listening on the topology."); + + return Response.ok("Install successful").build(); + + } catch (Exception e) { + + logger.error("An error occurs during the install",e); + + String result = "Path = " + pathToConfigFilesDirectory + "\n\n"; + result += e.getMessage(); + result += "\n\n"; + result += Utilities.getStackTrace(e); + + return Response.status(Response.Status.INTERNAL_SERVER_ERROR).entity(result).build(); + } + } + + + /** + *

Gets the current version.

+ */ + @GET + @Path("/version") + public String getVersion() { + + Enumeration resEnum; + try { + resEnum = bundleContext.getBundle().getResources(JarFile.MANIFEST_NAME); + while (resEnum.hasMoreElements()) { + try { + URL url = (URL)resEnum.nextElement(); + InputStream is = url.openStream(); + if (is != null) { + Manifest manifest = new Manifest(is); + Attributes mainAttribs = manifest.getMainAttributes(); + String version = mainAttribs.getValue("Bundle-Version"); + if(version != null) { + return version; + } + } + } + catch (Exception e) { + // Silently ignore wrong manifests on classpath? + } + } + } catch (IOException e1) { + // Silently ignore wrong manifests on classpath? + } + return null; + } +} diff --git a/exposure-engine/system-manager/src/main/java/com/alu/e3/Utilities.java b/exposure-engine/system-manager/src/main/java/com/alu/e3/Utilities.java new file mode 100644 index 0000000..05aed59 --- /dev/null +++ b/exposure-engine/system-manager/src/main/java/com/alu/e3/Utilities.java @@ -0,0 +1,119 @@ +/** + * Copyright © 2012 Alcatel-Lucent. + * + * See the NOTICE file distributed with this work for additional + * information regarding copyright ownership. + * Licensed to you 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 com.alu.e3; + +import java.io.File; +import java.io.FileInputStream; +import java.io.FileOutputStream; +import java.io.IOException; +import java.io.PrintWriter; +import java.io.StringWriter; +import java.io.Writer; +import java.nio.channels.FileChannel; +import java.util.Iterator; +import java.util.List; + +import com.alu.e3.common.E3Constant; +import com.alu.e3.common.logging.CategoryLogger; +import com.alu.e3.data.model.Instance; +import com.alu.e3.installer.NonExistingManagerException; + +public class Utilities { + + public static String getStackTrace(Throwable throwable) { + Writer writer = new StringWriter(); + PrintWriter printWriter = new PrintWriter(writer); + throwable.printStackTrace(printWriter); + return writer.toString(); + } + + public static void copyFile(File srcFile, File dstFile, boolean overwrite) throws IOException { + + // preconditions check + if(dstFile.isDirectory()) + throw new IOException("copyFile: destination is a directory: " + dstFile.getAbsolutePath()); + + if(dstFile.exists() && !overwrite) + throw new IOException("copyFile: destination file already exists: " + dstFile.getAbsolutePath()); + + FileChannel srcChannel = null; + FileChannel dstChannel = null; + + try { + srcChannel = new FileInputStream(srcFile).getChannel(); + dstChannel = new FileOutputStream(dstFile).getChannel(); + + long transfered = 0; + long size = srcChannel.size(); + + while ((transfered += srcChannel.transferTo(0, size-transfered, dstChannel)) < size); + + } finally { + if(srcChannel != null) + srcChannel.close(); + + if(dstChannel != null) + dstChannel.close(); + } + } + + + /** + * Method getManagerByIP + * @param managerHostName the manager's host name + * @param managerIP the manager's ip adress + * @param topology + * @param logger + * @return Instance the manager of that ip if existing + * @throws NonExistingManagerException thrown if parameter is no valid ip + */ + public static Instance getManagerByIP(String managerHostName, String managerIP, List instances, final CategoryLogger logger) throws NonExistingManagerException { + + boolean found = false; + Iterator iter = instances.iterator(); + + Instance manager = null; + + while (!found && iter.hasNext()) { + Instance currentInstance = iter.next(); + String currentIP = currentInstance.getInternalIP(); + if (currentIP == null) { + logger.warn("Encountered instance in topology with null internal IP: {}", currentInstance); + continue; + } + logger.debug("Comparing manager ip '" + managerIP + "' with current instance internal ip '" + currentIP + "'"); + //instance internal ip has to match manager ip or manager hostname (allows to work with both) + //for AIB install, the internalIP for the manager is "localhost", so for AIB allow match on "localhost" + if (currentIP.equals(managerIP) || currentIP.equals(managerHostName) || currentIP.equals(E3Constant.localhost)) { + found = true; + logger.debug("Found manager with ip '" + managerIP + "' found"); + manager = currentInstance; + } + } + + if (!found) { //this manager ip does not exist + logger.error("No manager with ip '" + managerIP + "' found"); + throw new NonExistingManagerException("No manager with ip '" + managerIP + "' found"); + } + + return manager; + } + + +} diff --git a/exposure-engine/system-manager/src/main/java/com/alu/e3/gateway/GatewayAddedListener.java b/exposure-engine/system-manager/src/main/java/com/alu/e3/gateway/GatewayAddedListener.java new file mode 100644 index 0000000..aa3bbe2 --- /dev/null +++ b/exposure-engine/system-manager/src/main/java/com/alu/e3/gateway/GatewayAddedListener.java @@ -0,0 +1,110 @@ +/** + * Copyright © 2012 Alcatel-Lucent. + * + * See the NOTICE file distributed with this work for additional + * information regarding copyright ownership. + * Licensed to you 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 com.alu.e3.gateway; + +import java.util.List; + +import com.alu.e3.common.E3Constant; +import com.alu.e3.common.osgi.api.IDataManager; +import com.alu.e3.common.osgi.api.ITopologyClient; +import com.alu.e3.data.IDataManagerListener; +import com.alu.e3.data.model.Instance; +import com.alu.e3.data.topology.IInstanceListener; +import com.alu.e3.data.topology.InstanceEvent; + +public class GatewayAddedListener implements IInstanceListener, IDataManagerListener{ + + protected ITopologyClient topologyClient; + protected IDataManager dataManager; + + public void setDataManager(IDataManager dataManager) { + this.dataManager = dataManager; + } + + public void setTopologyClient(ITopologyClient topologyClient) { + this.topologyClient = topologyClient; + } + + public GatewayAddedListener() {} + + public void init() { + dataManager.addListener(this); + } + + public void destroy() { + dataManager.removeListener(this); + } + + @Override + public void dataManagerReady() { + List gateways = topologyClient.getAllInstancesOfType(E3Constant.E3GATEWAY); + + if (gateways != null) { + for (Instance gateway : gateways) { + reloadGateway(gateway); + } + } + + topologyClient.addInstanceListener(this); + } + + @Override + public void instanceAdded(InstanceEvent event) { + if (dataManager == null) { + System.out.println("WARN: GatewayAddedListener was not able to deal with an InstanceEvent because the attribute dataManager of GatewayAddedListener is set to null"); + return; + } + if (event == null) { + System.out.println("ERROR: GatewayAddedListener was not able to deal with an InstanceEvent because the event null"); + return; + } + + // Instance type added need to be filtered + if(E3Constant.E3GATEWAY.equals(event.getType())) { + + Instance gateway = event.getInstance(); + + if (gateway == null) { + System.out.println("ERROR: GatewayAddedListener was not able to launch the provisioning of a gateway because the instance attribute of the event is null"); + return; + } + + reloadGateway(gateway); + } + } + + @Override + public void instanceRemoved(InstanceEvent event) { + // Nothing to be done here + } + + private void reloadGateway(Instance gateway) { + String myArea = topologyClient.getMyArea(); + String gatewayIP; + + if (myArea == null || myArea.equals(gateway.getArea())) { + gatewayIP = gateway.getInternalIP(); + } + else { + gatewayIP = gateway.getExternalIP(); + } + + dataManager.reloadGateway(gatewayIP); + } +} diff --git a/exposure-engine/system-manager/src/main/java/com/alu/e3/installer/Installer.java b/exposure-engine/system-manager/src/main/java/com/alu/e3/installer/Installer.java new file mode 100644 index 0000000..b39f8fb --- /dev/null +++ b/exposure-engine/system-manager/src/main/java/com/alu/e3/installer/Installer.java @@ -0,0 +1,321 @@ +/** + * Copyright © 2012 Alcatel-Lucent. + * + * See the NOTICE file distributed with this work for additional + * information regarding copyright ownership. + * Licensed to you 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 com.alu.e3.installer; + +import java.io.File; +import java.io.IOException; +import java.io.InputStream; +import java.net.URL; +import java.net.UnknownHostException; +import java.util.List; +import java.util.Map; + +import com.alu.e3.Utilities; +import com.alu.e3.common.E3Constant; +import com.alu.e3.common.logging.Category; +import com.alu.e3.common.logging.CategoryLogger; +import com.alu.e3.common.logging.CategoryLoggerFactory; +import com.alu.e3.common.spring.SpringContextBootstrapper; +import com.alu.e3.common.tools.CommonTools; +import com.alu.e3.data.model.Instance; +import com.alu.e3.data.model.SSHKey; +import com.alu.e3.installer.command.Command; +import com.alu.e3.installer.command.ICommand; +import com.alu.e3.installer.command.SSHCommand; +import com.alu.e3.installer.command.ShellCommandResult; +import com.alu.e3.installer.model.Configuration; +import com.alu.e3.installer.model.InstallerDeployException; +import com.alu.e3.installer.parsers.InstallerConfigurationParser; +import com.alu.e3.installer.parsers.InstallerParserException; +import com.alu.e3.topology.model.Topology; +import com.jcraft.jsch.JSchException; + +/** + * Class Installer + */ +public class Installer { + + /* Members */ + private Map> configurations; + + private static final CategoryLogger logger = CategoryLoggerFactory.getLogger(Installer.class, Category.SYS); + + private Topology topology; + + private SpringContextBootstrapper springContextBoostrapper; + + /** + * Constructor + * @param configFilePath + * @throws Exception + */ + public Installer(String configFilePath, Topology topology, SpringContextBootstrapper springCtxBootstrapper) throws Exception { + try { + this.topology = topology; + this.springContextBoostrapper = springCtxBootstrapper; + + /* Parsing Configuration File */ + logger.debug("new instance Installer"); + logger.debug("Parsing xml: " + configFilePath); + InstallerConfigurationParser configParser = new InstallerConfigurationParser(); + this.configurations = configParser.parse(configFilePath); + }catch (Exception e){ + logger.error("Exception: " + e.getMessage() + "\n" + Utilities.getStackTrace(e)); + e.printStackTrace(); + throw new Exception("Xml parsing failed", e); + } + } + + /** + * Constructor + * @param configInput + * @throws Exception + */ + public Installer(InputStream configInput) throws Exception { + try { + logger.debug("new instance Installer"); + + /* Parsing Configuration InputStream */ + logger.debug("Parsing xml: configInput stream"); + InstallerConfigurationParser configParser = new InstallerConfigurationParser(); + this.configurations = configParser.parse(configInput); + }catch (Exception e){ + logger.error("Exception: " + e.getMessage() + "\n" + Utilities.getStackTrace(e)); + e.printStackTrace(); + throw new Exception("Xml parsing failed", e); + } + } + + /** + * Deploy EE as specified in the configuration files. + * @throws UnknownHostException + * @throws IOException + * @throws JSchException + * @throws InstallerParserException + */ + public void deploy() throws Exception { + + /* Get local ip and host name. */ + String managerIP = CommonTools.getLocalAddress(); + logger.debug("call Installer.deploy() on machine " + CommonTools.getLocalHostname() + "(IP:" + managerIP + ")"); + + //retrieve manager area + String managerArea = getManagerAreaByIP(CommonTools.getLocalHostname(), managerIP); + + /* Loop on all the configurations to install */ + for (String configName : configurations.keySet()) + { + List instanceList = topology.getInstancesByType(configName); + + for(Instance instance : instanceList) + { + try { + String localizedGatewayIP = getLocalizedGatewayIP(instance, managerArea); + logger.debug("deploying: '" + instance.toString() + "' using ip '" + localizedGatewayIP + "'"); + + /* copy and launch installers */ + List instanceConfigurations = configurations.get(instance.getType()); + if(instanceConfigurations != null) { + for(Configuration config : instanceConfigurations) { + logger.debug("installing: " + config); + + /* copy and start installer setup script. */ + ICommand cmd = Command.getCommand(localizedGatewayIP); + + if (!CommonTools.isLocal(localizedGatewayIP)) + { + /* Get the ssh key. TODO: handle case without sshkey (eg. if user/password provided) */ + // return manager can not be null + Instance manager = Utilities.getManagerByIP(CommonTools.getLocalHostname(), CommonTools.getLocalAddress(), topology.getInstancesByType(E3Constant.E3MANAGER), logger); + SSHKey key = manager.getSSHKey(); + if (key != null) + logger.debug("using key: " + key.getName()); + + /* Connect via ssh. */ + SSHCommand sshCommand = (SSHCommand) cmd; + sshCommand.connect(key, localizedGatewayIP, 22, instance.getUser(), instance.getPassword()); + + if (!sshCommand.isConnected()) + { + String errorSshMsg = "Error: ssh connection to " + localizedGatewayIP+ " failed (sshkey="; + errorSshMsg += (key == null) ? "not defined " : key.getName(); + errorSshMsg += "user=" + instance.getUser() + ")"; + throw new InstallerDeployException(errorSshMsg); + } + + logger.debug("command type: " + cmd.getImplementationType()); + + /* check if the destination directory already exists. */ + ShellCommandResult dirExistResult = cmd.execShellCommand("ls "+ config.getRemotePath()); + if (dirExistResult.getExitStatus() != 0) + { + /* Create the destination directory */ + ShellCommandResult dirCreateResult = cmd.execShellCommand("mkdir -p -m 755 "+ config.getRemotePath()); + if (dirCreateResult.getExitStatus() != 0) + { + throw new InstallerDeployException("Unable to create remote destination directory "+ config.getRemotePath() + "."); + } + + /* Remote copy the package. */ + logger.debug("package url: " + config.getPackageUrl()); + URL urlPackage = new URL(config.getPackageUrl()); + String strFilename; + if (urlPackage.getProtocol().equals("file")) + { + strFilename = new File(urlPackage.getFile()).getName(); + cmd.copy(urlPackage.getFile(), config.getRemotePath() + "/" + strFilename); + + } else { + /* TODO: handle HTTP package URL ? */ + logger.debug("URL type " + urlPackage.getProtocol() + " is not supported yet."); + continue; + } + + /* Unzip TODO: instaler filename and install location in config */ + ShellCommandResult cmdRes = cmd.execShellCommand("tar xfz " + strFilename, config.getRemotePath()); + if (cmdRes.getExitStatus() != 0) + { + /* unzip has failed, display output. TODO: handle failure */ + throw new InstallerDeployException("Unzip archive" + strFilename + " failed (returned code: "+ cmdRes + ")"); + } + } + + String fullyQualifiedInstallerCmd = replaceManagerIPPattern(config.getInstallerCmd(), managerIP); + logger.debug("Executing shell command '" + fullyQualifiedInstallerCmd + "'"); + + /* Launch Install. */ + ShellCommandResult cmdResInstallation = cmd.execShellCommand(fullyQualifiedInstallerCmd, config.getRemotePath()); + if (cmdResInstallation.getExitStatus() != 0) + { + /* remote installation has failed, display output. */ + throw new InstallerDeployException("Installation has failed while executing command [" + fullyQualifiedInstallerCmd + "]\ndetails:"+ cmdResInstallation); + } + + /* Launch sanity check. */ + ShellCommandResult cmdResSanityCheck = cmd.execShellCommand(config.getSanityCheckCmd(), config.getRemotePath()); + if (cmdResSanityCheck.getExitStatus() != 0) + { + /* remote installation has failed, display output. TODO: handle failure */ + throw new InstallerDeployException("Sanity check has failed while executing command ["+ config.getSanityCheckCmd() + "] in the folder [" + config.getRemotePath() + "]\nDetails:"+ cmdResSanityCheck); + } + } + else { // Local + //if ("E3Gateway".equals(instance.getType())) { + + String generateNatureCmd = config.getGenerateNatureCmd(); + if (generateNatureCmd != null && !generateNatureCmd.isEmpty()) + { + + String fullyQualifiedGenerateNatureCmd = replaceManagerIPPattern(generateNatureCmd, managerIP); + logger.debug("Executing shell command '" + fullyQualifiedGenerateNatureCmd + "'"); + + /* Get the ssh key. TODO: handle case without sshkey (eg. if user/password provided) */ + SSHKey key = instance.getSSHKey(); + if (key != null) + logger.debug("using key: " + key.getName()); + + /* Connect via ssh. */ + SSHCommand sshCommand = (SSHCommand) cmd; + sshCommand.connect(key, localizedGatewayIP, 22, instance.getUser(), instance.getPassword()); + + if (!sshCommand.isConnected()) + { + String errorSshMsg = "Error: ssh connection to" + localizedGatewayIP+ " failed (sshkey="; + errorSshMsg += (key == null) ? "not defined " : key.getName(); + errorSshMsg += "user=" + instance.getUser() + ")"; + throw new InstallerDeployException(errorSshMsg); + } + + // And we need to update the configuration.properties file directly + ShellCommandResult cmdGenerateNature = cmd.execShellCommand(fullyQualifiedGenerateNatureCmd, config.getRemotePath()); + if (cmdGenerateNature.getExitStatus() != 0) + { + + /* Update nature failed */ + throw new InstallerDeployException("Update nature has failed while executing command ["+ fullyQualifiedGenerateNatureCmd + "] in the folder [" + config.getRemotePath() + "]\nDetails:"+ cmdGenerateNature); + } + + /* reload context. */ + springContextBoostrapper.reloadNatureProperties(); + } + } + } + } else { + logger.debug("Nothing to install for type " + instance.getType()); + } + + } + catch (Exception e) + { + logger.error("Exception: " + e.getMessage() + "\n" + Utilities.getStackTrace(e)); + e.printStackTrace(); + logger.debug("Install for type " + instance.getType() + " has failed. (" + e.getMessage() + ")"); + throw e; + } + + } + } + } + + /** + * Method: replaceManagerIPPattern + * Replaces the pattern for manager IP in template-installer-config with the computed manager ip + * Aug 7, 2012 - 11:52:01 AM + * @param originalCmd the original command line retrieved from the config file + * @param managerIP the manager ip replacement + * @return String the command line after replacement + */ + private String replaceManagerIPPattern(String originalCmd, String managerIP) { + return originalCmd.replace(E3Constant.MANAGER_IP_REPLACE_PATTERN, managerIP); + } + + + + /** + * Method getManagerAreaByIP + * @param managerHostName the manager's host name + * @param managerIP the manager's ip adress + * @return String the area of that ip if existing + * @throws NonExistingManagerException thrown if parameter is no valid ip + */ + private String getManagerAreaByIP(String managerHostName, String managerIP) throws NonExistingManagerException { + // getManagerByIP(..) either return the manager or throw an exception if not found => can not have a NPE + return Utilities.getManagerByIP(managerHostName, managerIP, topology.getInstancesByType(E3Constant.E3MANAGER), logger).getArea(); + } + + /** + * Method getLocalizedGatewayIP + * @param instance the gateway instance + * @param managerArea the manager's area + * @return String the localized ip to use for that gateway + */ + private String getLocalizedGatewayIP(Instance instance, String managerArea) { + String localizedGatewayIP = null; + if (managerArea.equals(instance.getArea())) { //gateway has same area than the manager -> use internal ip + logger.debug("Instance '" + instance.getName() + "' uses same area than the manager; using internal IP"); + localizedGatewayIP = instance.getInternalIP(); + } else { //gateway has different area than the manager -> use external ip + logger.debug("Instance '" + instance.getName() + "' uses different area than the manager; using external IP"); + localizedGatewayIP = instance.getExternalIP(); + } + + return localizedGatewayIP; + } + +} diff --git a/exposure-engine/system-manager/src/main/java/com/alu/e3/installer/NonExistingManagerException.java b/exposure-engine/system-manager/src/main/java/com/alu/e3/installer/NonExistingManagerException.java new file mode 100644 index 0000000..3172e80 --- /dev/null +++ b/exposure-engine/system-manager/src/main/java/com/alu/e3/installer/NonExistingManagerException.java @@ -0,0 +1,29 @@ +/** + * Copyright © 2012 Alcatel-Lucent. + * + * See the NOTICE file distributed with this work for additional + * information regarding copyright ownership. + * Licensed to you 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 com.alu.e3.installer; + + +public class NonExistingManagerException extends Exception { + + private static final long serialVersionUID = -738548187501672979L; + + public NonExistingManagerException(String message) { + super(message); + } +} diff --git a/exposure-engine/system-manager/src/main/java/com/alu/e3/installer/TopologyWatcher.java b/exposure-engine/system-manager/src/main/java/com/alu/e3/installer/TopologyWatcher.java new file mode 100644 index 0000000..b34c84f --- /dev/null +++ b/exposure-engine/system-manager/src/main/java/com/alu/e3/installer/TopologyWatcher.java @@ -0,0 +1,93 @@ +/** + * Copyright © 2012 Alcatel-Lucent. + * + * See the NOTICE file distributed with this work for additional + * information regarding copyright ownership. + * Licensed to you 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 com.alu.e3.installer; + +import org.apache.camel.Exchange; + +import com.alu.e3.common.logging.Category; +import com.alu.e3.common.logging.CategoryLogger; +import com.alu.e3.common.logging.CategoryLoggerFactory; +import com.alu.e3.osgi.api.ITopology; + +public class TopologyWatcher +{ + private static final CategoryLogger logger = CategoryLoggerFactory.getLogger(TopologyWatcher.class, Category.SYS); + + private ITopology topology; + boolean topologyProcessed = false; + boolean systemTopologyProcessed = false; + + public void setTopology(ITopology topology) { + this.topology = topology; + } + + public TopologyWatcher() {} + + public void processTopology(Exchange exchange) throws Exception + { + logger.debug("New topology.xml file detected"); + + if(topologyProcessed) { + logger.debug("Topology.xml already processed. Ignoring."); + return; + } + + topologyProcessed = true; + + if (topology != null) + { + logger.debug("Setting new topology.xml file on topology service."); + topology.setTopology("null"); + } + else + logger.warn("Topology file is null. Ignoring."); + } + + public void processSystemTopology(Exchange exchange) throws Exception + { + logger.debug("New system-topology.xml file detected"); + + if(systemTopologyProcessed) { + logger.debug("system-topology.xml already processed. Ignoring."); + return; + } + + systemTopologyProcessed = true; + + if (topology != null) + { + logger.debug("Setting new system-topology.xml file on topology service."); + topology.setSystemTopology("null"); + } + else + logger.warn("system-topology file is null. Ignoring."); + } + + /** + * General Setters + */ + public void setTopologyProcessed(boolean topologyProcessed) { + this.topologyProcessed = topologyProcessed; + } + + public void setSystemTopologyProcessed(boolean systemTopologyProcessed) { + this.systemTopologyProcessed = systemTopologyProcessed; + } + +} diff --git a/exposure-engine/system-manager/src/main/java/com/alu/e3/installer/command/Command.java b/exposure-engine/system-manager/src/main/java/com/alu/e3/installer/command/Command.java new file mode 100644 index 0000000..9a2d1dd --- /dev/null +++ b/exposure-engine/system-manager/src/main/java/com/alu/e3/installer/command/Command.java @@ -0,0 +1,85 @@ +/** + * Copyright © 2012 Alcatel-Lucent. + * + * See the NOTICE file distributed with this work for additional + * information regarding copyright ownership. + * Licensed to you 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 com.alu.e3.installer.command; + +import java.net.UnknownHostException; + +//import com.alu.e3.common.tools.CommonTools; +import com.alu.e3.data.model.SSHKey; + +public class Command { + + /** + * Returns either a LocalCommand or SSHCommand instance, depending on hosts to connect from/to. + * @param host + * @return A LocalCommand if remoteHost is the same machine as the one running the code, SSHCommand otherwise. + * @throws UnknownHostException + */ + public static ICommand getCommand(String host) throws UnknownHostException { + ICommand command = null; + + // We need to be root to add iptables rules... so only use SSH +// if(CommonTools.isLocal(host)) { +// command = new LocalCommand(); +// } else { + command = new SSHCommand(); +// } + + return command; + + } + + /** + * Returns either a LocalCommand or SSHCommand connected instance, depending on hosts to connect from/to. + * @param SSHKey + * @param host + * @param SSHPort + * @param user + * @param password + * @return + * @throws UnknownHostException + */ + public static ICommand getCommandAndConnect(SSHKey SSHKey, String host, int SSHPort, String user, String password) throws UnknownHostException{ + + ICommand command = null; + + // We need to be root to add iptables rules... so only use SSH +// if(CommonTools.isLocal(host)) { +// command = new LocalCommand(); +// } else { + command = new SSHCommand(); + try{ + ((SSHCommand) command).connect(SSHKey, host, SSHPort, user, password); + + if (!((SSHCommand) command).isConnected()) + { + throw new Exception("SSH connection to " + host + " failed"); + } + }catch(Exception e){ + + } +// } + + return command; + } + +} diff --git a/exposure-engine/system-manager/src/main/java/com/alu/e3/installer/command/ICommand.java b/exposure-engine/system-manager/src/main/java/com/alu/e3/installer/command/ICommand.java new file mode 100644 index 0000000..0c47e3c --- /dev/null +++ b/exposure-engine/system-manager/src/main/java/com/alu/e3/installer/command/ICommand.java @@ -0,0 +1,57 @@ +/** + * Copyright © 2012 Alcatel-Lucent. + * + * See the NOTICE file distributed with this work for additional + * information regarding copyright ownership. + * Licensed to you 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 com.alu.e3.installer.command; + + /** + * Interface ICommand + */ +public interface ICommand { + + /** + * Execute a shell command on the current system + * @param strCommand + * @return Exit status of the command executed on the remote host + */ + public ShellCommandResult execShellCommand(String strCommand) throws Exception; + + /** + * Execute a shell command on the current system + * @param strCommand + * @param workingDir + * @return Exit status of the command executed on the remote host + */ + public ShellCommandResult execShellCommand(String strCommand, String workingDir) throws Exception; + + /** + * Copy + * @param sourcePath + * @param targetPath + */ + public void copy(String sourcePath, String targetPath) throws Exception; + + + /** + * Get implementation type (eg. local, ssh...) + * @return + */ + public String getImplementationType(); + + public void disconnect(); + +} \ No newline at end of file diff --git a/exposure-engine/system-manager/src/main/java/com/alu/e3/installer/command/LocalCommand.java b/exposure-engine/system-manager/src/main/java/com/alu/e3/installer/command/LocalCommand.java new file mode 100644 index 0000000..65f7be8 --- /dev/null +++ b/exposure-engine/system-manager/src/main/java/com/alu/e3/installer/command/LocalCommand.java @@ -0,0 +1,152 @@ +/** + * Copyright © 2012 Alcatel-Lucent. + * + * See the NOTICE file distributed with this work for additional + * information regarding copyright ownership. + * Licensed to you 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 com.alu.e3.installer.command; + +import java.io.File; +import java.io.FileInputStream; +import java.io.FileOutputStream; +import java.io.IOException; +import java.io.InputStream; +import java.nio.channels.FileChannel; + +import org.slf4j.Logger; +import org.slf4j.LoggerFactory; + + /** + * Class LocalCommand + */ +public class LocalCommand implements ICommand { + + /* slf4j logger */ + private static final Logger logger = LoggerFactory.getLogger(LocalCommand.class); + + /** + * Constructor + */ + public LocalCommand() + { + } + + /** + * Execute a shell command on the current system + * @param strCommand + * @param strAnswer + * @return Exit status of the command executed on the remote host + * @throws IOException + * @throws InterruptedException + */ + @Override + public ShellCommandResult execShellCommand(String strCommand) throws IOException, InterruptedException { + return execShellCommand(strCommand, null); + } + + @Override + public ShellCommandResult execShellCommand(String strCommand, String workingDir) throws IOException, InterruptedException { + + /* Init answer. */ + logger.debug("local execShellCommand " + strCommand + "(dir:" + workingDir + ")"); + int nExitStatus = 0; + StringBuilder strAnswer = new StringBuilder(); + + InputStream inStream = null; + try { + /* Execute command */ + Process aProcess; + if(workingDir == null) + aProcess = Runtime.getRuntime().exec(strCommand); + else + aProcess = Runtime.getRuntime().exec(strCommand, null, new File(workingDir)); + + aProcess.waitFor(); + + /* Get output */ + inStream = aProcess.getInputStream(); + nExitStatus = aProcess.exitValue(); + + /* Read answer */ + byte buffer[] = new byte[1024]; + int nRead = inStream.read(buffer); + while (nRead >= 0) { + strAnswer.append(new String(buffer, 0, nRead)); + nRead = inStream.read(buffer); + } + } finally { + if (inStream != null) { + inStream.close(); + } + } + + String answer = strAnswer.toString(); + /* return answer. */ + logger.debug("local execShellCommand returned: exit status" + nExitStatus + "\n" + answer); + return new ShellCommandResult(answer, nExitStatus); + } + + /** + * Copy file + * + * @param sourcePath + * @param targetPath + * @throws IOException + */ + @Override + public void copy(String sourcePath, String targetPath) throws IOException { + + /* Fast java copy file */ + logger.debug("local copy from " + sourcePath + " to " + targetPath); + File tDestFile = new File(targetPath); + File tSourceFile = new File(sourcePath); + + if (!tDestFile.exists()) { + tDestFile.createNewFile(); + } + + FileChannel source = null; + FileChannel destination = null; + + try { + source = new FileInputStream(tSourceFile).getChannel(); + destination = new FileOutputStream(tDestFile).getChannel(); + destination.transferFrom(source, 0, source.size()); + } finally { + if (source != null) { + source.close(); + } + if (destination != null) { + destination.close(); + } + } + + logger.debug("local copy done "); + } + + /** + * + */ + @Override + public String getImplementationType() { + + return "local"; + } + + @Override + public void disconnect() { + + } +} \ No newline at end of file diff --git a/exposure-engine/system-manager/src/main/java/com/alu/e3/installer/command/SSHCommand.java b/exposure-engine/system-manager/src/main/java/com/alu/e3/installer/command/SSHCommand.java new file mode 100644 index 0000000..b1c63cf --- /dev/null +++ b/exposure-engine/system-manager/src/main/java/com/alu/e3/installer/command/SSHCommand.java @@ -0,0 +1,443 @@ +/** + * Copyright © 2012 Alcatel-Lucent. + * + * See the NOTICE file distributed with this work for additional + * information regarding copyright ownership. + * Licensed to you 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 com.alu.e3.installer.command; + +import java.io.File; +import java.io.FileInputStream; +import java.io.FileOutputStream; +import java.io.IOException; +import java.io.InputStream; +import java.io.OutputStream; + +import org.slf4j.Logger; +import org.slf4j.LoggerFactory; + +import com.alu.e3.data.model.SSHKey; +import com.jcraft.jsch.*; + +/** + * Class SSHCommand + */ +public class SSHCommand implements ICommand { + + /* slf4j logger */ + private static final Logger logger = LoggerFactory.getLogger(SSHCommand.class); + + /* members */ + private Session m_tSession; + + /** + * Constructor + */ + public SSHCommand() + { + m_tSession = null; + } + + /** + * Finalize + */ + protected void finalize() + { + /* Make sure to disconnect session. */ + //if (m_tSession != null && m_tSession.isConnected()) + // m_tSession.disconnect(); + } + + /** + * Connect via ssh + * @param strPrivateKeyPath + * @param strTargetHostName + * @param nPortNumber + * @param strUser + * @param strPassword + * @throws JSchException + */ + public void connect(SSHKey key, String strTargetHostName, int nPortNumber, String strUser, String strPassword) throws JSchException + { + connect(key, strTargetHostName, nPortNumber, strUser, strPassword, 0); + } + + /** + * Connect via ssh + * @param strPrivateKeyPath + * @param strTargetHostName + * @param nPortNumber + * @param strUser + * @param strPassword + * @throws JSchException + */ + public void connect(SSHKey key, String strTargetHostName, int nPortNumber, String strUser, String strPassword, int timeout) throws JSchException + { + /* Init ssh object with the private key. */ + JSch jsch = new JSch(); + if(key != null){ + jsch.addIdentity(key.getName(), key.getPrivateKey() == null ? null : key.getPrivateKey().clone(), key.getPublicKey(), null); + } + + /* Init session, set password if needed. */ + m_tSession = jsch.getSession(strUser, strTargetHostName, nPortNumber); + if (strPassword != null) { + m_tSession.setPassword(strPassword); + } + + /* Disable strict host checking. */ + java.util.Properties config = new java.util.Properties(); + config.put("StrictHostKeyChecking", "no"); + m_tSession.setConfig(config); + + /* Connect */ + if (timeout > 0) { + m_tSession.connect(timeout); + } else { + m_tSession.connect(); + } + } + + /** + * Disconnect the session. + */ + public void disconnect() + { + /* Disconnect session. */ + if (m_tSession != null) + m_tSession.disconnect(); + } + + /** + * Reconnect with the settings used previously to connect. + * @throws JSchException + */ + public void reconnect() throws JSchException + { + /* Sanity check. */ + if (m_tSession == null) + throw new JSchException("Session not initializad, use connect() first"); + + /* connect session. */ + m_tSession.connect(); + } + + /** + * Is connected + */ + public boolean isConnected() + { + return m_tSession != null && m_tSession.isConnected(); + } + + /** + * Execute a shell command on the remote location. + * @param strCommand + * @param strAnswer + * @return Exit status of the command executed on the remote host + * @throws JSchException + * @throws IOException + */ + + @Override + public ShellCommandResult execShellCommand(String strCommand) throws IOException, JSchException { + return execShellCommand(strCommand, null); + } + + @Override + public ShellCommandResult execShellCommand(String strCommand, String workingDir) + throws JSchException, IOException { + + /* Sanity check. */ + if (m_tSession == null || !m_tSession.isConnected()) + throw new JSchException("Session not initializad, use connect() first"); + + /* Change directory before executing the command. */ + if(workingDir != null) + strCommand = "cd " + workingDir + "; " + strCommand; + + /* execute command */ + logger.debug("remote execShellCommand " + strCommand); + Channel channel = m_tSession.openChannel("exec"); + ((ChannelExec) channel).setCommand(strCommand); + + InputStream in = channel.getInputStream(); // Data coming from remote host + ((ChannelExec) channel).setErrStream(System.err); + channel.connect(); + + /* Get answer. */ + int nExitStatus = 0; + StringBuilder strAnswer = new StringBuilder(); + byte[] buffer = new byte[1024]; + while (true) { + while (in.available() > 0) { + int i = in.read(buffer, 0, 1024); + if (i < 0) + break; + strAnswer.append(new String(buffer, 0, i)); + } + if (channel.isClosed()) { + nExitStatus = channel.getExitStatus(); + break; + } + try { + Thread.sleep(100); + } catch (Exception ee) { + } + } + channel.disconnect(); + + /* return answer. */ + logger.debug("remote execShellCommand returned:\nexit status" + nExitStatus + "\n" + strAnswer); + return new ShellCommandResult(strAnswer.toString(), nExitStatus); + } + + /** + * Secure remote copy file + * + * @param sourcePath + * @param targetPath + * @throws Exception + */ + public void copy(String sourcePath, String targetPath) throws JSchException, IOException { + + /* Sanity check. */ + if (m_tSession == null || !m_tSession.isConnected()) + throw new JSchException( + "Session not initializad, use connect() first"); + + logger.debug("remote copy from " + sourcePath + " to " + targetPath); + String command = "scp -p -t " + targetPath; + Channel channel = m_tSession.openChannel("exec"); + ((ChannelExec) channel).setCommand(command); + + // get I/O streams for remote scp + OutputStream out = channel.getOutputStream(); + FileInputStream fis = null; + try { + channel.connect(); + + // send "C0644 filesize filename", where filename should not include '/' + long filesize = (new File(sourcePath)).length(); + logger.debug("scp filesize = " + filesize); + command = "C0644 " + filesize + " "; + if (sourcePath.lastIndexOf('/') > 0) { + command += sourcePath.substring(sourcePath.lastIndexOf('/') + 1); + }else if (sourcePath.lastIndexOf('\\') > 0){ + command += sourcePath.substring(sourcePath.lastIndexOf('\\') + 1); + + } else { + command += sourcePath; + } + command += "\n"; + out.write(command.getBytes()); + out.flush(); + + fis = new FileInputStream(sourcePath); + byte[] buf = new byte[1024]; + + while (true) { + int len = fis.read(buf, 0, buf.length); + if (len <= 0) + break; + out.write(buf, 0, len); + } + fis = null; + buf[0] = 0; + out.write(buf, 0, 1); + out.flush(); + + } finally { + if (fis != null) + fis.close(); + out.close(); + } + + // Wait for the end of the actual copy + while (! channel.isEOF()) { + logger.trace("Finishing the copy of " + sourcePath + " to " + targetPath); + } + + channel.disconnect(); + + logger.debug("scp done"); + } + + // From: http://www.jcraft.com/jsch/examples/ScpFrom.java.html + public long copyFrom(String remotePath, String localPath) throws JSchException, IOException + { + /* Sanity check. */ + if ((m_tSession == null) || !m_tSession.isConnected()) { + throw new JSchException("Session not initializad, use connect() first"); + } + + logger.debug("remote copy from {} to {}", remotePath, localPath); + + long copiedByteCount = 0L; + FileOutputStream fos = null; + + String prefix = null; + if (new File(localPath).isDirectory()) { + prefix = localPath + File.separator; + } + + // exec 'scp -f rfile' remotely + String command="scp -f "+ remotePath; + Channel channel = m_tSession.openChannel("exec"); + ((ChannelExec)channel).setCommand(command); + + // get I/O streams for remote scp + OutputStream out = channel.getOutputStream(); + InputStream in = channel.getInputStream(); + + channel.connect(); + + byte[] buf = new byte[1024]; + + + try { + // send '\0' + buf[0] = 0; + out.write(buf, 0, 1); + out.flush(); + + while (true) { + int c = checkAck(in); + if (c != 'C') { + break; + } + + // read '0644 ' + in.read(buf, 0, 5); + + long filesize = 0L; + while (true) { + if (in.read(buf, 0, 1) < 0) { + // error + break; + } + if (buf[0] == ' ') break; + filesize = filesize*10L + (long)(buf[0] - '0'); + } + + String file = null; + for (int i = 0; ; i++) { + in.read(buf, i, 1); + if (buf[i] == (byte)0x0a) { + file = new String(buf, 0, i); + break; + } + } + + //System.out.println("filesize="+filesize+", file="+file); + + // send '\0' + buf[0] = 0; + out.write(buf, 0, 1); + out.flush(); + + // read a content of lfile + fos = new FileOutputStream(prefix == null ? localPath : prefix+file); + int foo; + while (true) { + if (buf.length < filesize) foo=buf.length; + else foo = (int)filesize; + foo = in.read(buf, 0, foo); + if (foo < 0) { + // error + break; + } + fos.write(buf, 0, foo); + filesize -= foo; + copiedByteCount += foo; + if (filesize == 0L) break; + } + fos.close(); + fos = null; + + if (checkAck(in) != 0) { + System.exit(0); + } + + // send '\0' + buf[0] = 0; + out.write(buf, 0, 1); + out.flush(); + } + + channel.disconnect(); + logger.debug("scp done"); + + } catch (Exception e) { + logger.error(e.getLocalizedMessage()); + try { if (fos != null) fos.close(); } catch(Exception ee){} + } + return copiedByteCount; + } + + // For symmetry ... + public void copyTo(String localPath, String remotePath) throws JSchException, IOException + { + copy(localPath, remotePath); + } + + static int checkAck(InputStream in) throws IOException{ + int b=in.read(); + // b may be 0 for success, + // 1 for error, + // 2 for fatal error, + // -1 + if(b==0) return b; + if(b==-1) return b; + + if(b==1 || b==2){ + StringBuffer sb=new StringBuffer(); + int c; + do { + c=in.read(); + sb.append((char)c); + } + while(c!='\n'); + if(b==1){ // error + System.out.print(sb.toString()); + } + if(b==2){ // fatal error + System.out.print(sb.toString()); + } + } + return b; + } + + @Override + public String getImplementationType() { + return "ssh"; + } + + public int getSessionTimeout() + { + return m_tSession.getTimeout(); + } + + public void setSessionTimeout(int timeout) throws JSchException + { + m_tSession.setTimeout(timeout); + } + + public String getSessionUsername() + { + return m_tSession.getUserName(); + } + +} \ No newline at end of file diff --git a/exposure-engine/system-manager/src/main/java/com/alu/e3/installer/command/ShellCommandResult.java b/exposure-engine/system-manager/src/main/java/com/alu/e3/installer/command/ShellCommandResult.java new file mode 100644 index 0000000..d497c6d --- /dev/null +++ b/exposure-engine/system-manager/src/main/java/com/alu/e3/installer/command/ShellCommandResult.java @@ -0,0 +1,62 @@ +/** + * Copyright © 2012 Alcatel-Lucent. + * + * See the NOTICE file distributed with this work for additional + * information regarding copyright ownership. + * Licensed to you 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 com.alu.e3.installer.command; + +/** + * Class ShellCommandResult + * + */ +public class ShellCommandResult { + + /* members */ + private String m_strResult; + private int m_nExitStatus; + + /** + * Constructor + * @param m_strResult + * @param m_nExitStatus + */ + public ShellCommandResult(String m_strResult, int m_nExitStatus) { + this.m_strResult = m_strResult; + this.m_nExitStatus = m_nExitStatus; + } + + /** + * Return a string of the output of the command + * @return output of the command + */ + public String getResult() { + return m_strResult; + } + + /** + * Return a string of the status of the command + * @return exit status of the command + */ + public int getExitStatus() { + return m_nExitStatus; + } + + @Override + public String toString() { + return "[Result=" + m_strResult + + ", ExitStatus=" + m_nExitStatus + "]"; + } + } \ No newline at end of file diff --git a/exposure-engine/system-manager/src/main/java/com/alu/e3/installer/model/Configuration.java b/exposure-engine/system-manager/src/main/java/com/alu/e3/installer/model/Configuration.java new file mode 100644 index 0000000..1eb0066 --- /dev/null +++ b/exposure-engine/system-manager/src/main/java/com/alu/e3/installer/model/Configuration.java @@ -0,0 +1,119 @@ +/** + * Copyright © 2012 Alcatel-Lucent. + * + * See the NOTICE file distributed with this work for additional + * information regarding copyright ownership. + * Licensed to you 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 com.alu.e3.installer.model; + +/** + * Class Configuration + */ +public class Configuration { + + private String name; + private String packageUrl; + private String installerCmd, sanityCheckCmd, generateNatureCmd; + private String type; + private String version; + private final String defaultRemotePath="/tmp"; + + + public String getName() { + return name; + } + + public void setName(String name) { + this.name = name; + } + + public String getPackageUrl() { + return packageUrl; + } + + public void setPackageUrl(String packageUrl) { + this.packageUrl = packageUrl; + } + + public String getInstallerCmd() { + return installerCmd; + } + + public void setInstallerCmd(String installerCmd) { + this.installerCmd = installerCmd; + } + + public String getSanityCheckCmd() { + return sanityCheckCmd; + } + + public void setSanityCheckCmd(String sanityCheckCmd) { + this.sanityCheckCmd = sanityCheckCmd; + } + + public String getType() { + return type; + } + + public void setType(String type) { + this.type = type; + } + + public String getGenerateNatureCmd() { + return generateNatureCmd; + } + + public void setGenerateNatureCmd(String generateNatureCmd) { + this.generateNatureCmd = generateNatureCmd; + } + + /** + * Get the remote path, built from the module name and version. + * @return + */ + public String getRemotePath() { + if (name == null || name.isEmpty()) + return defaultRemotePath; + return "/su/" + name + "-" + version; + } + + public String getVersion() { + return version; + } + + public void setVersion(String version) { + this.version = version; + } + + @Override + public String toString() { + return "configuration [" + name + " " + version + " " + type + " " + packageUrl + " " + getRemotePath() + " " + installerCmd + " " + sanityCheckCmd + "]"; + } + + /* + try { + URL urlPackage = new URL(packageUrl); + String strFile = new File(urlPackage.getFile()).getName(); + + remotePath = strFile.substring(0, strFile.lastIndexOf('_')); + version = strFile.substring(strFile.lastIndexOf('_')+1, strFile.indexOf(".tar.gz")); + + } catch (MalformedURLException e) { + + remotePath = "/su"; + version = "undefined"; + } + */ +} diff --git a/exposure-engine/system-manager/src/main/java/com/alu/e3/installer/model/InstallerDeployException.java b/exposure-engine/system-manager/src/main/java/com/alu/e3/installer/model/InstallerDeployException.java new file mode 100644 index 0000000..ab78925 --- /dev/null +++ b/exposure-engine/system-manager/src/main/java/com/alu/e3/installer/model/InstallerDeployException.java @@ -0,0 +1,36 @@ +/** + * Copyright © 2012 Alcatel-Lucent. + * + * See the NOTICE file distributed with this work for additional + * information regarding copyright ownership. + * Licensed to you 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 com.alu.e3.installer.model; + +/** + * class InstallerDeployException + * + */ +public class InstallerDeployException extends Exception { + + private static final long serialVersionUID = 8742574906582716518L; + + public InstallerDeployException(String message) { + super(message); + } + + public InstallerDeployException(Exception e) { + super(e.getMessage()); + } +} diff --git a/exposure-engine/system-manager/src/main/java/com/alu/e3/installer/parsers/InstallerConfigurationParser.java b/exposure-engine/system-manager/src/main/java/com/alu/e3/installer/parsers/InstallerConfigurationParser.java new file mode 100644 index 0000000..eaa7e53 --- /dev/null +++ b/exposure-engine/system-manager/src/main/java/com/alu/e3/installer/parsers/InstallerConfigurationParser.java @@ -0,0 +1,124 @@ +/** + * Copyright © 2012 Alcatel-Lucent. + * + * See the NOTICE file distributed with this work for additional + * information regarding copyright ownership. + * Licensed to you 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 com.alu.e3.installer.parsers; + +import java.io.FileInputStream; +import java.io.FileNotFoundException; +import java.io.InputStream; +import java.util.ArrayList; +import java.util.HashMap; +import java.util.List; +import java.util.Map; + +import javax.xml.parsers.DocumentBuilder; +import javax.xml.parsers.DocumentBuilderFactory; + +import org.w3c.dom.Document; +import org.w3c.dom.Element; +import org.w3c.dom.NodeList; + +import com.alu.e3.common.logging.Category; +import com.alu.e3.common.logging.CategoryLogger; +import com.alu.e3.common.logging.CategoryLoggerFactory; +import com.alu.e3.installer.model.Configuration; + +public class InstallerConfigurationParser { + + private static final CategoryLogger logger = CategoryLoggerFactory.getLogger(InstallerConfigurationParser.class, Category.SYS); + + public InstallerConfigurationParser() { + + } + + + public Map> parse(String configFilePath) throws InstallerParserException { + logger.debug("Parsing file at path: " + configFilePath); + + FileInputStream fin = null; + try { + fin = new FileInputStream(configFilePath); + } catch (FileNotFoundException e) { + logger.error(e.getMessage()); + throw new InstallerParserException(e); + } + return parse(fin); + } + + public Map> parse(InputStream inputStream) throws InstallerParserException { + if(inputStream == null) + throw new InstallerParserException("InputStream null"); + + Map> configurations = new HashMap>(); + try + { + // Parsing installers configuration inputstream + DocumentBuilderFactory factory = DocumentBuilderFactory.newInstance(); + DocumentBuilder builder = factory.newDocumentBuilder(); + + Document doc = builder.parse(inputStream); + Element rootElement = doc.getDocumentElement(); + + NodeList nodes = rootElement.getElementsByTagName("Configuration"); + logger.debug("Found " + nodes.getLength() + " configurations"); + for(int i = 0; i < nodes.getLength(); i++) + { + Element el = (Element) nodes.item(i); + + Configuration config = new Configuration(); + config.setPackageUrl(el.getAttribute("packageURL")); + config.setInstallerCmd(el.getAttribute("installerCmd")); + config.setSanityCheckCmd(el.getAttribute("sanityCheckCmd")); + config.setGenerateNatureCmd(el.getAttribute("generateNatureCmd")); + config.setType(el.getAttribute("type")); + config.setName(el.getAttribute("name")); + config.setVersion(el.getAttribute("version")); + + // stores this new configuration in the configuration map to be returned + storeConfiguration(configurations, config); + + logger.debug(config.toString()); + } + } + catch (Exception e) + { + logger.error(e.getMessage()); + throw new InstallerParserException(e); + } + + return configurations; + } + + + /** + * Store a configuration for a type. A given type can have several configurations. + */ + private void storeConfiguration(Map> configurationsMap, Configuration config) { + + List configurationsList = configurationsMap.get(config.getType()); + + if(configurationsList == null) { + configurationsList = new ArrayList(); + configurationsMap.put(config.getType(), configurationsList); + } + + configurationsList.add(config); + } + + +} diff --git a/exposure-engine/system-manager/src/main/java/com/alu/e3/installer/parsers/InstallerParserException.java b/exposure-engine/system-manager/src/main/java/com/alu/e3/installer/parsers/InstallerParserException.java new file mode 100644 index 0000000..d88e3c3 --- /dev/null +++ b/exposure-engine/system-manager/src/main/java/com/alu/e3/installer/parsers/InstallerParserException.java @@ -0,0 +1,37 @@ +/** + * Copyright © 2012 Alcatel-Lucent. + * + * See the NOTICE file distributed with this work for additional + * information regarding copyright ownership. + * Licensed to you 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 com.alu.e3.installer.parsers; + +/** + * class InstallerParserException + * + */ +public class InstallerParserException extends Exception { + + private static final long serialVersionUID = 2643389317278295881L; + + public InstallerParserException(String message) { + super(message); + } + + public InstallerParserException(Exception e) { + super(e.getMessage()); + e.printStackTrace(); + } +} diff --git a/exposure-engine/system-manager/src/main/java/com/alu/e3/logger/CategoryListWrapper.java b/exposure-engine/system-manager/src/main/java/com/alu/e3/logger/CategoryListWrapper.java new file mode 100644 index 0000000..49ebdac --- /dev/null +++ b/exposure-engine/system-manager/src/main/java/com/alu/e3/logger/CategoryListWrapper.java @@ -0,0 +1,77 @@ +/** + * Copyright © 2012 Alcatel-Lucent. + * + * See the NOTICE file distributed with this work for additional + * information regarding copyright ownership. + * Licensed to you 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 com.alu.e3.logger; + +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; +import javax.xml.bind.annotation.XmlType; + +import com.alu.e3.common.logging.Category; + +/** + * A JAXB wrapper class to encapsulate the Category list sent by + * requesters to the LoggingManager REST API. + */ +@XmlRootElement(name="loggingCategories") +@XmlAccessorType(XmlAccessType.FIELD) +@XmlType(name="loggingCategoryList", propOrder = {"categories"}) +public class CategoryListWrapper { + + @XmlElement(name = "loggingCategory", required = true) + protected List categories; + + public List getCategories() + { + return categories; + } + + public void setCategories(List categories) + { + this.categories = categories; + } + + public static final List toDataModel(CategoryListWrapper categoryListWrapper) + { + return toDataModel(categoryListWrapper.getCategories()); + } + + public static final List toDataModel(List wrappers) + { + List categoryList = new ArrayList(); + for (CategoryWrapper c : wrappers) { + categoryList.add(CategoryWrapper.toDataModel(c)); + } + return categoryList; + } + + public static final List fromDataModel(List categories) + { + List wrapperList = new ArrayList(); + for (Category c : categories) { + wrapperList.add(CategoryWrapper.fromDataModel(c)); + } + return wrapperList; + } + +} diff --git a/exposure-engine/system-manager/src/main/java/com/alu/e3/logger/CategoryResponse.java b/exposure-engine/system-manager/src/main/java/com/alu/e3/logger/CategoryResponse.java new file mode 100644 index 0000000..a203a07 --- /dev/null +++ b/exposure-engine/system-manager/src/main/java/com/alu/e3/logger/CategoryResponse.java @@ -0,0 +1,98 @@ +/** + * Copyright © 2012 Alcatel-Lucent. + * + * See the NOTICE file distributed with this work for additional + * information regarding copyright ownership. + * Licensed to you 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 com.alu.e3.logger; + +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.XmlElementWrapper; +import javax.xml.bind.annotation.XmlRootElement; +import javax.xml.bind.annotation.XmlType; + + +/** + * An XML/JAXB-wrapped response used by LoggingManager when responding + * to logging-category management REST calls. Based on the model + * used in Provisioning for Auths/Apis etc., except it doesn't + * currently provide an error member. + */ +@XmlRootElement(name="response") +@XmlAccessorType(XmlAccessType.FIELD) +@XmlType(name = "loggingCategoryResponse", propOrder = { "categories", "status" }) +public class CategoryResponse { + public final static String SUCCESS = "SUCCESS"; + public final static String FAILURE = "FAILURE"; + + @XmlElementWrapper(name = "loggingCategories") + @XmlElement(name = "loggingCategory") + protected List categories; + protected String status; + + public CategoryResponse() { + + } + + public CategoryResponse(String status) { + setStatus(status); + } + + /** + * + * @return + */ + public List getCategories() { + if (categories == null) { + categories = new ArrayList(); + } + return this.categories; + } + + /** + * + * @return + */ + public void setCategories(List categories) { + this.categories = categories; + } + + /** + * Gets the value of the status property. + * + * @return possible object is {@link String } + * + */ + public String getStatus() { + return status; + } + + /** + * Sets the value of the status property. + * + * @param value + * allowed object is {@link String } + * + */ + public void setStatus(String value) { + this.status = value; + } + +} diff --git a/exposure-engine/system-manager/src/main/java/com/alu/e3/logger/CategoryWrapper.java b/exposure-engine/system-manager/src/main/java/com/alu/e3/logger/CategoryWrapper.java new file mode 100644 index 0000000..84a81e8 --- /dev/null +++ b/exposure-engine/system-manager/src/main/java/com/alu/e3/logger/CategoryWrapper.java @@ -0,0 +1,118 @@ +/** + * Copyright © 2012 Alcatel-Lucent. + * + * See the NOTICE file distributed with this work for additional + * information regarding copyright ownership. + * Licensed to you 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 com.alu.e3.logger; + +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.XmlType; + +import com.alu.e3.common.logging.Category; + + +/** + * A Category wrapper class for use by the REST logging-management methods + * in LoggingManager. + */ +@XmlRootElement +@XmlAccessorType(XmlAccessType.FIELD) +@XmlType(name="loggingCategory", propOrder = { + "name", + "fullname", + "description", + "enabled"}) + +public class CategoryWrapper { + @XmlElement(name="name", required = true) + protected String name; + @XmlElement(name="fullname", required = false) + protected String fullname; + @XmlElement(name="description", required = false) + protected String description; + @XmlElement(name="enabled", required = true) + protected boolean enabled; + + public String getName() + { + return name; + } + + public void setName(String name) + { + this.name = name; + } + + public String getFullname() + { + return fullname; + } + + public void setFullname(String fullname) + { + this.fullname = fullname; + } + + public String getDescription() + { + return description; + } + + public void setDescription(String description) + { + this.description = description; + } + + public boolean getEnabled() + { + return enabled; + } + + public void setEnabled(boolean enabled) + { + this.enabled = enabled; + } + + public static final Category toDataModel(CategoryWrapper categoryXML) + { + if (categoryXML == null) { + throw new IllegalArgumentException("CategoryWrapper must not be null"); + } + Category category = Category.fromString(categoryXML.getName()); + if (category == null) { + throw new IllegalArgumentException("CategoryWrapper.name must be a valid Category value: " + Category.valuesList); + } + Category.enableCategory(category, categoryXML.getEnabled()); + return category; + } + + public static final CategoryWrapper fromDataModel(Category category) + { + if (category == null) { + throw new IllegalArgumentException("Category must not be null"); + } + CategoryWrapper c = new CategoryWrapper(); + c.setName(category.name()); + c.setFullname(category.fullname()); + c.setDescription(category.description()); + c.setEnabled(Category.isCategoryEnabled(category)); + return c; + } + +} diff --git a/exposure-engine/system-manager/src/main/java/com/alu/e3/logger/LogCollector.java b/exposure-engine/system-manager/src/main/java/com/alu/e3/logger/LogCollector.java new file mode 100644 index 0000000..655072e --- /dev/null +++ b/exposure-engine/system-manager/src/main/java/com/alu/e3/logger/LogCollector.java @@ -0,0 +1,1560 @@ +/** + * Copyright © 2012 Alcatel-Lucent. + * + * See the NOTICE file distributed with this work for additional + * information regarding copyright ownership. + * Licensed to you 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 com.alu.e3.logger; + +import java.io.BufferedReader; +import java.io.File; +import java.io.FileFilter; +import java.io.FileInputStream; +import java.io.FileNotFoundException; +import java.io.FileOutputStream; +import java.io.IOException; +import java.io.InputStream; +import java.io.InputStreamReader; +import java.nio.channels.FileChannel; +import java.text.DateFormat; +import java.text.SimpleDateFormat; +import java.util.Arrays; +import java.util.Comparator; +import java.util.Date; +import java.util.HashSet; +import java.util.LinkedList; +import java.util.List; +import java.util.Set; +import java.util.concurrent.Callable; +import java.util.concurrent.TimeUnit; +import java.util.concurrent.TimeoutException; +import java.util.concurrent.locks.Lock; +import java.util.concurrent.locks.ReentrantLock; + +import org.apache.commons.lang.StringEscapeUtils; + +import com.alu.e3.Utilities; +import com.alu.e3.common.E3Constant; +import com.alu.e3.common.logging.Category; +import com.alu.e3.common.logging.CategoryLogger; +import com.alu.e3.common.logging.CategoryLoggerFactory; +import com.alu.e3.common.logging.LoggingUtil; +import com.alu.e3.common.logging.LoggingUtil.LogFileSource; +import com.alu.e3.common.logging.NonJavaLogger; +import com.alu.e3.common.tools.CommonTools; +import com.alu.e3.data.model.Instance; +import com.alu.e3.installer.NonExistingManagerException; +import com.alu.e3.installer.command.SSHCommand; +import com.alu.e3.installer.command.ShellCommandResult; +import com.alu.e3.osgi.api.ITopology; +import com.jcraft.jsch.JSchException; + +/** + * The LogCollector class provides an object to traverse the topology + * and visit each instance, collecting log files to a repository on + * the system manager. + * + * There are still some unresolved issues in the design and/or + * implementation of the Log Collector. These include: + *
    + *
  • Throughout the code, instances are referred to by IP-Address. + * This is probably not right, and will have to be changed to some + * sort of (non-volatile) instance identifier. + *
  • If logging config files are moved or significantly edited + * (or not set up properly on install) the Collector may not be + * able to find remote log files. + *
+ */ + +public class LogCollector implements Callable { + + private static final String COLLECTION_PATH = System.getProperty("user.home") + "/apache-servicemix/data/logCollection"; + private static final CategoryLogger logger = CategoryLoggerFactory.getLogger(LogCollector.class, Category.LOG); + + // Should collected files be deleted on the source after collection? + private static final boolean deleteAfterCollect = true; + + // If a file already exists with the copied log-file name, append a ".1" etc to uniquify? + // Don't uniquify if we don't delete source logs, since this will lead to local duplicates + private static final boolean uniquifyCopiedFilenames = deleteAfterCollect; + private static final int uniquifyLimit = 100; // unique filename extension limit, after this overwrite + + // Should the collector only collect (and delete) files owned by the ssh user? + // This feature hasn't yet been tested ... + private static final boolean collectOnlyUserOwnedLogs = false; + + // Set a short ssh connect timeout since we assume all instances are close, + // and on timeout we can try again on next collection + private static final int sshSessionTimeout = 10000; // 10s + + /* + * Synchronization policy: allow only one writer to operate at a time. + * Allow concurrent readers and writer, except that readers must ignore + * any files the writer is currently writing, indicated by a specific suffix + */ + // For now: use a lock to allow only one writer (collector) to run at a time + private static final Lock writerLock = new ReentrantLock(); + // Reader should ignore these files - collector is currently writing + private static final String workingFileSuffix = "~"; + + // Each collector can have its own topology (we could split large + // topologies for collection by multiple collectors) + private final ITopology topology; + + /** + * Data structure to hold information about a (remote) file + * + */ + private static class FileInfo { + public String filePath; + public String fileSize; + public String fileModtime; + + FileInfo(String path, String size, String modtime) { + filePath = path; + fileSize = size; + fileModtime = modtime; + } + } + + /** + * File-name filter to check for log files (by extension) + * and to ignore "working files" (files being written by collector) + */ + private static class LogFileFilter implements FileFilter + { + private String basename; + public LogFileFilter(String basename) + { + this.basename = basename; + } + public boolean accept(File pathname) + { + String filename = pathname.getName(); + if (basename != null) { + return ((filename.matches(basename + LoggingUtil.rollingFileExtPatternString) || + filename.matches(basename + LoggingUtil.dailyRollingFileExtPatternString) && + !filename.endsWith(LogCollector.workingFileSuffix))); + } else { + return ((filename.matches(LoggingUtil.rollingFilePatternString) || + filename.matches(LoggingUtil.dailyRollingFilePatternString) && + !filename.endsWith(LogCollector.workingFileSuffix))); + } + } + } + + /** + * LogCollector constructor without parameters to satisfy spring-bean requirements. + */ + public LogCollector(ITopology topology) + { + this.topology = topology; + } + + /** + * Traverse the topology and collect logs from each instance found. + * + * @return The number of bytes collected in all logs + * @throws InterruptedException + * @throws TimeoutException + */ + @Override + public Long call() throws InterruptedException, TimeoutException, NonExistingManagerException + { + logger.debug("Call to LogCollector.call()"); + long bytesCollected = collectAllLogs(0, TimeUnit.SECONDS); + return Long.valueOf(bytesCollected); + } + + /** + * Traverse the topology and collect logs from each instance found. + * + * @param waitTimeout The time to wait if another collector is running + * @param unit The time unit for waitTimeout + * @return The number of bytes collected in all logs + * @throws InterruptedException + * @throws TimeoutException + * @throws NonExistingManagerException + */ + public long collectAllLogs(long waitTimeout, TimeUnit unit) throws InterruptedException, TimeoutException, NonExistingManagerException + { + logger.debug("Launching system-manager log-file collection ..."); + if (!LogCollector.writerLock.tryLock(waitTimeout, unit)) { + logger.warn("Attempt to run log collector but cannot acquire lock (another collection must be running)"); + throw new TimeoutException("Timeout waiting to acquire log collector write lock"); + } + long collectionCount = 0L; + + try { + Set visitedIPs = new HashSet(); + + // Create the top-level log collection directory, if this is the first time run + File collectionDir = new File(COLLECTION_PATH); + if (!collectionDir.exists() && !collectionDir.mkdirs()) { + logger.error("Unable to create log-collection directory: {}", COLLECTION_PATH); + return 0L; + } + + // Iterate through all instances in the current topology + + Instance logCollectorInstance = Utilities.getManagerByIP(CommonTools.getLocalHostname(), CommonTools.getLocalAddress(), topology.getInstancesByType(E3Constant.E3MANAGER), logger); + List instances = getInstanceList(this.topology); + logger.debug("There are {} instances in the current topology", instances.size()); + for (Instance logSource : instances) { + LogCollector.logInstance(logSource); // for debugging + + // Avoid visiting the same address twice + String ipAddress = logSource.getInternalIP(); + if (ipAddress == null) { + logger.warn("Encountered instance node with null ipAddress during log collection!"); + continue; + } + if (CommonTools.isLocal(ipAddress)) { + ipAddress = E3Constant.localhost; // stay consistent + } + if (visitedIPs.contains(ipAddress)) { + logger.debug("Skipping already-visited address: {}", ipAddress); + continue; + } + visitedIPs.add(ipAddress); + + // Create or verify the existence of a log-collection target directory + String sanitizedHost = ipToCollectionDirectory(ipAddress); + File instanceCollectionDir = new File(COLLECTION_PATH, sanitizedHost); + if (instanceCollectionDir.exists()) { + if (!instanceCollectionDir.isDirectory()) { + logger.error("Log-collection target exists but is not a directory: {}", instanceCollectionDir.getAbsolutePath()); + continue; + } + } else { + if (!instanceCollectionDir.mkdirs()) { + logger.error("Unable to create log-collection directory: {}", instanceCollectionDir.getAbsolutePath()); + continue; + } + } + + // Finally, perform log collection + // There may be a chance for parallelism here by farming the collection work for each instance + // out to a separate worker thread. At a minimum the local collection could occur in parallel with + // collection on a remote host. + if (ipAddress.equalsIgnoreCase(E3Constant.localhost)) { + try { + collectionCount += collectAllLocalLogs(instanceCollectionDir); + } catch (IOException ex) { + logger.warn("Error trying to copy local log files to {}", instanceCollectionDir.getAbsolutePath()); + } + } else { + try { + collectionCount += collectAllRemoteLogs(logSource, logCollectorInstance, instanceCollectionDir); + } catch (JSchException ex) { + logger.debug("Could not connect to host: {}", logSource.getInternalIP()); + logger.debug(ex.getLocalizedMessage()); + } catch (IOException ex) { + logger.debug("Got IOException while connecting to or transferring files from host: {}", logSource.getInternalIP()); + logger.debug(ex.getLocalizedMessage()); + } + } + + } + } finally { + LogCollector.writerLock.unlock(); + } + return collectionCount; + } + + /** + * Traverse the topology and collect a certain number of lines from the + * active logs on each instance found. + * + * @param numLines The number of lines to retrieve from each log file on each instance + * @return An XML-structured string with a single <logCollection> node and + * <log> node for each log-file found (including multiple instances). + * @throws InterruptedException + * @throws TimeoutException + */ + public String collectAllActiveLogs(int numLines) + { + StringBuilder sb = new StringBuilder(); + + Set visitedIPs = new HashSet(); + + // Iterate through all instances in the current topology + // (Note: use TRACE-level log statements so that our logging doesn't appear in returned log tails) + List instances = getInstanceList(this.topology); + logger.trace("There are {} instances in the current topology", instances.size()); + + Instance collectorInstance; + try { + collectorInstance = Utilities.getManagerByIP(CommonTools.getLocalHostname(), CommonTools.getLocalAddress(), topology.getInstancesByType(E3Constant.E3MANAGER), logger); + } catch (NonExistingManagerException e) { + String errMsg = "Cannot find manager at " + CommonTools.getLocalAddress() + " while collecting active logs."; + logger.error(errMsg); + return errMsg; + } + + for (Instance instance : instances) { + + // Avoid visiting the same address twice + String ipAddress = instance.getInternalIP(); + if (ipAddress == null) { + logger.warn("Encountered instance node with null ipAddress during log collection!"); + continue; + } + if (CommonTools.isLocal(ipAddress)) { + ipAddress = E3Constant.localhost; // stay consistent + } + if (visitedIPs.contains(ipAddress)) { + logger.trace("Skipping already-visited address: {}", ipAddress); + continue; + } + visitedIPs.add(ipAddress); + + // Finally, perform log collection (of active-log tails) + if (ipAddress.equalsIgnoreCase(E3Constant.localhost)) { + try { + String logs = getTailOfLocalActiveLogs(numLines); + if (logs != null) { + sb.append(logs); + } + } catch (IOException ex) { + logger.warn("Error trying to get tail of active log files from {}", ipAddress); + } + } else { + try { + String logs = getTailOfRemoteActiveLogs(instance, collectorInstance, numLines); + if (logs != null) { + sb.append(logs); + } + } catch (JSchException ex) { + logger.warn("Could not connect to host: {}", instance.getInternalIP()); + logger.warn(ex.getLocalizedMessage()); + } catch (IOException ex) { + logger.warn("Got IOException while connecting to or transferring files from host: {}", instance.getInternalIP()); + logger.warn(ex.getLocalizedMessage()); + } + } + + } + return LoggingResponseBuilder.logCollectionToXml(sb.toString()); + } + + /** + * A top-level method to return a certain number of most-recent log + * lines from previously-connected log files from all instances. + * + * @param numLines The requested number of log lines to retrieve. + * Fewer lines may be returned if sufficient log entries are not available. + * @return An XML-structured string with a single <logCollection> node and + * <log> node for each log-file found (including multiple instances). + */ + public String getCollectedLogLines(int numLines) + { + File collectionDir = new File(COLLECTION_PATH); + if (!collectionDir.exists() || !collectionDir.isDirectory()) { + return null; + } + + logger.debug("Attempting to get all collected logs ..."); + StringBuilder logLines = new StringBuilder(); + File[] files = collectionDir.listFiles(); // get a list of instance directories + for (File item : files) { + logger.debug("Collection directory entry: {}", item.getAbsolutePath()); + if (item.isDirectory()) { + String ipAddress = collectionDirectoryToIP(item.getName()); + logger.debug("Getting logs from: {}", ipAddress); + // First get the java logs + String contents = getCollectedLogLinesFromInstance(ipAddress, LogFileSource.JAVA, numLines); + if (contents != null) { + logLines.append(contents); + } + // Next get the servicemix logs + contents = getCollectedLogLinesFromInstance(ipAddress, LogFileSource.SMX, numLines); + if (contents != null) { + logLines.append(contents); + } + // Get the E3-facility syslog files + contents = getCollectedLogLinesFromInstance(ipAddress, LogFileSource.SYSLOG, numLines); + if (contents != null) { + logLines.append(contents); + } + } + } + + return LoggingResponseBuilder.logCollectionToXml(logLines.toString()); + } + + /** + * Returns the specified number of most-recent log lines from previously- + * collected log files for a particular instance and log source. + * + * @param ipAddress The ip-address of the instance + * @param logSource The source for the logs (JAVA, SMX, SYSLOG) + * @param numLines The number of lines to retrieve. Fewer lines may be returned if the + * requested number is not available. + * @return Log lines in XML structure, with a top-level <log> node. + */ + public String getCollectedLogLinesFromInstance(String ipAddress, LogFileSource logSource, int numLines) + { + StringBuilder logLines = null; + String logFilePath = null; + int lineCount = 0; + + File collectionDir = new File(COLLECTION_PATH, LogCollector.ipToCollectionDirectory(ipAddress)); + if (!collectionDir.exists() || !collectionDir.isDirectory()) { + logger.warn("No log collection directory for ipAddress: {}", ipAddress); + return null; + } + File logSourceSubdir = new File(collectionDir, logSource.toString()); + if (!logSourceSubdir.exists() || !logSourceSubdir.isDirectory()) { + logger.warn("No log-type '{}' collection subdirectory for ipAddress: {}", logSource.toString(), ipAddress); + return null; + } + + // Get the list of collected log files in date order + File[] files = logSourceSubdir.listFiles(new LogFileFilter(null)); // get all log files, regardless of basename and ext + Arrays.sort(files, new Comparator() { + public int compare(Object o1, Object o2) { + // Sort by decreasing date first, and then decreasing alphabetical + File f1 = (File)o1; File f2 = (File)o2; + int result = (Long.valueOf(f2.lastModified())).compareTo(Long.valueOf(f1.lastModified())); + if (result == 0) { + result = f2.getName().compareTo(f1.getName()); + } + return result; + } + }); + logger.trace("Sorted log-files:"); + for (File logFile : files) { + logger.trace("{}", logFile.getName()); + } + logLines = new StringBuilder(); + try { + for (File file : files) { + String fileName = file.getName(); + logger.debug("Consider file: {}", fileName); + logFilePath = file.getAbsolutePath(); + logger.debug("Retrieving {} log lines from file {}", String.valueOf(numLines-lineCount), logFilePath); + String logContent = LogCollector.getTailOfFile(file, numLines - lineCount); + logLines.insert(0, logContent); + int retrievedCount = lineCount(logContent); + logger.debug("Actually got {} lines", String.valueOf(retrievedCount)); + lineCount += retrievedCount; + if (lineCount >= numLines) { + break; + } + } + } catch (IOException ex) { + // Swallow exception from any one file read and hope to get lines from the next log + logger.warn("Couldn't read from log file {}", logFilePath == null ? "(null)" : logFilePath); + } + logger.debug("Got {} of {} requested lines", String.valueOf(lineCount), String.valueOf(numLines)); + + return LoggingResponseBuilder.logLinesToXml(logSource, ipAddress, + StringEscapeUtils.escapeXml(logLines.toString())); + } + + /** + * Collects logs from the localhost for all log sources. + * + * @param instanceCollectionDir Target directory to place collected logs (subdirectories for + * each log source will be created) + * @return The number of bytes in all files collected + * + * @throws IOException + */ + private long collectAllLocalLogs(File instanceCollectionDir) throws IOException + { + // First, get the E3Appender (java) logs + // Parse the log-config file to find path to logs + long bytesCollected = 0L; + String logFilePath = LoggingUtil.getLocalLogFilePath(LogFileSource.JAVA); + if ((logFilePath == null) || (logFilePath.length() == 0)) { + // If we can't determine the log-file path from the config file, + // look anyway in the usual servicemix log directory for any log files with the default name + logger.warn("Localhost is not using E3Appender, using default log-file path (check log-config file: {})", LoggingUtil.defaultConfigPath); + logFilePath = LoggingUtil.defaultLogPath; + } + logger.debug("java log file path {}", logFilePath); + File logFile = new File(logFilePath); + bytesCollected += collectLocalLogs(logFile.getParentFile(), instanceCollectionDir, logFile.getName(), LogFileSource.JAVA); + + // Next, get the serviceMix logs + logFilePath = LoggingUtil.getLocalLogFilePath(LogFileSource.SMX); + if ((logFilePath == null) || (logFilePath.length() == 0)) { + // Same situation as above + logger.warn("Localhost log-config file ({}) does not specify servicemix log location, using default", LoggingUtil.defaultConfigPath); + logFilePath = LoggingUtil.defaultSMXLogPath; + } + logger.debug("smx log file path {}", logFilePath); + File smxLogFile = new File(logFilePath); + bytesCollected += collectLocalLogs(smxLogFile.getParentFile(), instanceCollectionDir, smxLogFile.getName(), LogFileSource.SMX); + + // Collect the E3-specific syslog files + logFilePath = NonJavaLogger.getLogFilePath(); + if ((logFilePath == null) || (logFilePath.length() == 0)) { + // Same situation as above + logFilePath = NonJavaLogger.defaultLogFilePath; + logger.warn("Localhost syslog-config file ({}) does not specify log location, using default", logFilePath); + } + logger.debug("syslog file path: {}", logFilePath); + File syslogFile = new File(logFilePath); + bytesCollected += collectLocalLogs(syslogFile.getParentFile(), instanceCollectionDir, syslogFile.getName(), LogFileSource.SYSLOG); + return bytesCollected; + } + + /** + * Collects logs from the specified instance for all log sources. + * + * @param logSource The topology instance to collect logs from + * @param instanceCollectionDir Target directory to place collected logs (subdirectories for + * each log source will be created) + * @return The number of bytes in all files collected + * @throws JSchException, IOException + */ + private long collectAllRemoteLogs(Instance logSource, Instance logDestination, File instanceCollectionDir) throws JSchException, IOException + { + if (logSource == null) { + throw new NullPointerException("The instance than contains remote logs cannot be null"); + } + if (logDestination == null) { + throw new NullPointerException("The instance where to copy logs cannot be null"); + } + + // First, try to open a new SSH session to instance + long bytesCollected = 0L; + String ipAddress = logSource.getInternalIP(); + logger.debug("trying to connect to {} via ssh ...", ipAddress); + SSHCommand sshCommand = new SSHCommand(); + sshCommand.connect(logDestination.getSSHKey(), ipAddress, 22, logSource.getUser(), logSource.getPassword(), sshSessionTimeout); + + // Start with E3Appender Java logs first + // Get a local copy of the logging config file to determine log-file path + String remoteLogPath = null; + File localConfigFile = new File(instanceCollectionDir, "java-logging.cfg"); + String localConfigFilePath = localConfigFile.getAbsolutePath(); + if (copyRemoteConfigFile(sshCommand, localConfigFilePath, LogFileSource.JAVA)) { + remoteLogPath = LoggingUtil.getLogFilePathFromConfigFile(localConfigFilePath, LogFileSource.JAVA, false); + } else { + logger.warn("Couldn't retrieve E3 Java logging config file from host {}, will try default path", ipAddress); + } + if ((remoteLogPath == null) || (remoteLogPath.length() == 0)) { + // If we can't find a logging config file with an E3Appender section, + // look anyway in the usual servicemix log directory for any log files with the default name + logger.warn("Instance at {} is not using E3Appender (check log-config file: {})", ipAddress, LoggingUtil.defaultConfigPath); + remoteLogPath = LoggingUtil.defaultLogPath; + } + File localTargetDir = createLocalLogTargetDir(instanceCollectionDir, LogFileSource.JAVA); + if (localTargetDir == null) { + logger.warn("Couldn't create log-collection directory: {}", instanceCollectionDir + File.separator + LogFileSource.JAVA.toString()); + } else { + File remoteLog = new File(remoteLogPath); + List logList = getMatchingRemoteFileList(sshCommand, remoteLog.getParent(), remoteLog.getName()); + for (FileInfo remoteFileInfo : logList) { + File localCopy = new File(localTargetDir, targetNameForLogFile(remoteFileInfo, localTargetDir)); + try { + bytesCollected += copyRemoteFileWithWorkingTemp(sshCommand, remoteFileInfo, localCopy.getAbsolutePath(), deleteAfterCollect); + } catch (Exception ex) { + // Continue copy attempts if we experience an error + logger.warn("Failed to copy remote file: {} ({})", remoteFileInfo.filePath, ex.getLocalizedMessage()); + } + } + } + + // Now try to get the remote serviceMix log files + // We use the same log-config file as the java logs to parse the path + remoteLogPath = LoggingUtil.getLogFilePathFromConfigFile(localConfigFilePath, LogFileSource.SMX, false); + localConfigFile.delete(); // no longer needed + if ((remoteLogPath == null) || (remoteLogPath.length() == 0)) { + // If we can't find a logging config file with the proper appender section, + // look anyway in the usual servicemix log directory for any log files with the default name + logger.warn("Instance at {} is not using expected appender for servicemix rootLogger (check log-config file: {})", ipAddress, LoggingUtil.defaultConfigPath); + remoteLogPath = LoggingUtil.defaultSMXLogPath; + } + localTargetDir = createLocalLogTargetDir(instanceCollectionDir, LogFileSource.SMX); + if (localTargetDir == null) { + logger.warn("Couldn't create log-collection directory: {}", instanceCollectionDir + File.separator + LogFileSource.SMX.toString()); + } else { + File remoteLog = new File(remoteLogPath); + List logList = getMatchingRemoteFileList(sshCommand, remoteLog.getParent(), remoteLog.getName()); + for (FileInfo remoteFileInfo : logList) { + File localCopy = new File(localTargetDir, targetNameForLogFile(remoteFileInfo, localTargetDir)); + try { + bytesCollected += copyRemoteFileWithWorkingTemp(sshCommand, remoteFileInfo, localCopy.getAbsolutePath(), deleteAfterCollect); + } catch (Exception ex) { + // Continue copy attempts if we experience an error + logger.warn("Failed to copy remote file: {} ({})", remoteFileInfo.filePath, ex.getLocalizedMessage()); + } + } + } + + // Collect the E3-specific syslog files + // For syslog we parse the rsyslog config file for the log-file path + localConfigFile = new File(instanceCollectionDir, "syslog.cfg"); + localConfigFilePath = localConfigFile.getAbsolutePath(); + if (copyRemoteConfigFile(sshCommand, localConfigFilePath, LogFileSource.SYSLOG)) { + remoteLogPath = NonJavaLogger.getLogFilePathFromConfigFile(localConfigFilePath); + localConfigFile.delete(); + } else { + logger.warn("Couldn't retrieve E3 syslog config file from host {}", ipAddress); + } + if ((remoteLogPath == null) || (remoteLogPath.length() == 0)) { + // Try default path + remoteLogPath = NonJavaLogger.defaultLogFilePath; + logger.warn("Instance at {} does not specify an E3-specific syslog file, trying default: {}", ipAddress, remoteLogPath); + } + localTargetDir = createLocalLogTargetDir(instanceCollectionDir, LogFileSource.SYSLOG); + if (localTargetDir == null) { + logger.warn("Couldn't create log-collection directory: {}", instanceCollectionDir + File.separator + LogFileSource.SYSLOG.toString()); + } else { + File remoteLog = new File(remoteLogPath); + List logList = getMatchingRemoteFileList(sshCommand, remoteLog.getParent(), remoteLog.getName()); + for (FileInfo remoteFileInfo : logList) { + File localCopy = new File(localTargetDir, targetNameForLogFile(remoteFileInfo, localTargetDir)); + try { + bytesCollected += copyRemoteFileWithWorkingTemp(sshCommand, remoteFileInfo, localCopy.getAbsolutePath(), deleteAfterCollect); + } catch (Exception ex) { + // Continue copy attempts if we experience an error + logger.warn("Failed to copy remote file: {} ({})", remoteFileInfo.filePath, ex.getLocalizedMessage()); + } + } + } + + // We're done - disconnect and return number of bytes copied + sshCommand.disconnect(); + logger.debug("connected/disconnected!"); + return bytesCollected; + } + + /** + * Visit a particular local directory and collect all the log files that start with + * a particular base filename, copying them to the specified target directory. + * + * @param sourceDir The directory in which the log files are located + * @param targetDir The directory to put the copied files + * @param baseName The basename of the log files to collect (such as "e3.log", "servicemix.log", etc) + * @param logSource The type of logs to collect (JAVA, SMX, SYSLOG); the string form of the type will + * be used as a destination subdirectory under targetDir + * @return The number of bytes in all files collected + */ + private long collectLocalLogs(File sourceDir, File targetDir, final String baseName, LogFileSource logSource) + { + long bytesCollected = 0L; + + logger.debug("Collecting logs from localhost from {} with base {}", sourceDir, baseName); + // New: Get all log files with a matching basename, regardless of rotation type + File[] logFiles = sourceDir.listFiles(new LogFileFilter(baseName)); + + if (logFiles == null) { + logger.warn("Error retrieving file list from {} matching name {}", sourceDir, baseName); + return 0L; + } + + // Make or use a specific subdirectory for this log type + targetDir = new File(targetDir, logSource.toString()); + if (!targetDir.exists()) { + targetDir.mkdirs(); + } else if (!targetDir.isDirectory()) { + logger.error("Target for local log collection is not a directory: {}", targetDir.getAbsolutePath()); + return 0L; + } + + File logFile; + for (File log : logFiles) { + logFile = log; + logger.debug("Copying log file {} ...", logFile.getAbsolutePath()); + String destFileName = targetNameForLogFile(logFile, targetDir); + File destFile = new File(targetDir, destFileName); + try { + bytesCollected += LogCollector.copyLocalFileWithWorkingTemp(logFile, destFile, deleteAfterCollect); + } catch (IOException ex) { + // Continue copying despite single-file error + logger.error("Could not copy file {}: {}", logFile.getAbsolutePath() + " to " + targetDir.getAbsolutePath(), ex.getLocalizedMessage()); + } + } + return bytesCollected; + } + + /** + * Collects logs from the localhost for all log sources. + * + * @param numLines The requested number of log lines to retrieve. + * Fewer lines may be returned if sufficient log entries are not available. + * @return An XML-structured string with a <log> node for + * each log-file found.. + * @throws IOException + */ + private String getTailOfLocalActiveLogs(int numLines) throws IOException + { + // First, get the E3Appender (java) log + // Parse the log-config file to find path to log file + // Note: use TRACE-level logging here since our output may appear in retrieved log lines + StringBuilder sb = new StringBuilder(); + String logFilePath = LoggingUtil.getLocalLogFilePath(LogFileSource.JAVA); + if ((logFilePath == null) || (logFilePath.length() == 0)) { + // If we can't determine the log-file path from the config file, + // look anyway in the usual servicemix log directory for any log files with the default name + logger.warn("Localhost is not using E3Appender, using default log-file path (check log-config file: {})", LoggingUtil.defaultConfigPath); + logFilePath = LoggingUtil.defaultLogPath; + } + logger.trace("java log file path {}", logFilePath); + File logFile = new File(logFilePath); + String logLines = execTailOnFile(logFile, numLines); + if (logLines != null) { + sb.append(LoggingResponseBuilder.logLinesToXml(LogFileSource.JAVA, E3Constant.localhost, StringEscapeUtils.escapeXml(logLines.toString()))); + } + + // Next, get the serviceMix log + logFilePath = LoggingUtil.getLocalLogFilePath(LogFileSource.SMX); + if ((logFilePath == null) || (logFilePath.length() == 0)) { + // Same situation as above + logger.warn("Localhost log-config file ({}) does not specify servicemix log location, using default", LoggingUtil.defaultConfigPath); + logFilePath = LoggingUtil.defaultSMXLogPath; + } + logger.trace("smx log file path {}", logFilePath); + File smxLogFile = new File(logFilePath); + logLines = execTailOnFile(smxLogFile, numLines); + if (logLines != null) { + sb.append(LoggingResponseBuilder.logLinesToXml(LogFileSource.SMX, E3Constant.localhost, StringEscapeUtils.escapeXml(logLines.toString()))); + } + + // Collect the E3-specific syslog files + logFilePath = NonJavaLogger.getLogFilePath(); + if ((logFilePath == null) || (logFilePath.length() == 0)) { + // Same situation as above + logFilePath = NonJavaLogger.defaultLogFilePath; + logger.warn("Localhost syslog-config file does not specify an E3-specific log location, using default: {}", LoggingUtil.defaultLogPath); + } + logger.trace("syslog file path: {}", logFilePath); + logFile = new File(logFilePath); + logLines = execTailOnFile(logFile, numLines); + if (logLines != null) { + sb.append(LoggingResponseBuilder.logLinesToXml(LogFileSource.SYSLOG, E3Constant.localhost, StringEscapeUtils.escapeXml(logLines.toString()))); + } + return sb.toString(); + } + + /** + * Retrieves the last numLines lines from the remote machine's active logs. + * + * @param numLines The requested number of log lines to retrieve. + * Fewer lines may be returned if sufficient log entries are not available. + * @return An XML-structured string with a <log> node for + * each log-file found.. + * @throws JSchException, IOException + */ + private String getTailOfRemoteActiveLogs(Instance logSource, Instance logDestination, int numLines) throws JSchException, IOException + { + if (logSource == null) { + throw new NullPointerException ("Log source cannot be null"); + } + if (logDestination == null) { + throw new NullPointerException ("Log destination cannot be null"); + } + + StringBuilder sb = new StringBuilder(); + + // First, try to open a new SSH session to instance + // Note: use TRACE-level logging here since our output may appear in retrieved log lines + String ipAddress = logSource.getInternalIP(); + logger.trace("trying to connect to {} via ssh ...", ipAddress); + + SSHCommand sshCommand = new SSHCommand(); + sshCommand.connect(logDestination.getSSHKey(), ipAddress, 22, logSource.getUser(), logSource.getPassword(), sshSessionTimeout); + + // Start with E3Appender Java log first + // Get a local copy of the logging config file to determine log-file path + String remoteLogPath = null; + File localConfigFile = File.createTempFile("java-logging", ".cfg"); + boolean gotConfigFile = false; + String localConfigFilePath = localConfigFile.getAbsolutePath(); + if (copyRemoteConfigFile(sshCommand, localConfigFilePath, LogFileSource.JAVA)) { + gotConfigFile = true; + remoteLogPath = LoggingUtil.getLogFilePathFromConfigFile(localConfigFilePath, LogFileSource.JAVA, false); + } else { + logger.warn("Couldn't retrieve E3 Java logging config file from host {}, will try default path", ipAddress); + } + if ((remoteLogPath == null) || (remoteLogPath.length() == 0)) { + // If we can't find a logging config file with an E3Appender section, + // look anyway in the usual servicemix log directory for any log files with the default name + logger.warn("Instance at {} is not using E3Appender (check log-config file: {})", ipAddress, LoggingUtil.defaultConfigPath); + remoteLogPath = LoggingUtil.defaultLogPath; + } + logger.trace("java log file path for instance {}: {}", ipAddress, remoteLogPath); + String logLines = execTailOnRemoteFile(sshCommand, remoteLogPath, numLines); + if (logLines != null) { + sb.append(LoggingResponseBuilder.logLinesToXml(LogFileSource.JAVA, ipAddress, StringEscapeUtils.escapeXml(logLines.toString()))); + } + + // Next, get the serviceMix log + // We use the same logging config file to get the servicemix log-file path + remoteLogPath = null; + if (gotConfigFile) { + remoteLogPath = LoggingUtil.getLogFilePathFromConfigFile(localConfigFilePath, LogFileSource.SMX, false); + localConfigFile.delete(); // We're done with the local version of the java/smx config file + } + if ((remoteLogPath == null) || (remoteLogPath.length() == 0)) { + // Same situation as above + logger.warn("Could not parse servicemix log-file path from config file for instance at {}, using default", ipAddress); + remoteLogPath = LoggingUtil.defaultSMXLogPath; + } + logger.trace("smx log file path for instance {}: {}", ipAddress, remoteLogPath); + logLines = execTailOnRemoteFile(sshCommand, remoteLogPath, numLines); + if (logLines != null) { + sb.append(LoggingResponseBuilder.logLinesToXml(LogFileSource.SMX, ipAddress, StringEscapeUtils.escapeXml(logLines.toString()))); + } + + // Collect the E3-specific syslog files + // For syslog we parse the rsyslog config file for the log-file path + remoteLogPath = null; + localConfigFile = File.createTempFile("syslog", ".cfg"); + localConfigFilePath = localConfigFile.getAbsolutePath(); + if (copyRemoteConfigFile(sshCommand, localConfigFilePath, LogFileSource.SYSLOG)) { + remoteLogPath = NonJavaLogger.getLogFilePathFromConfigFile(localConfigFilePath); + localConfigFile.delete(); + } else { + logger.warn("Couldn't retrieve E3 syslog config file from host {}", ipAddress); + } + if ((remoteLogPath == null) || (remoteLogPath.length() == 0)) { + // Same situation as above + logger.warn("Could not parse E3-specific log-file path from syslog config file for instance at {}, using default", ipAddress); + remoteLogPath = NonJavaLogger.defaultLogFilePath; + } + logger.trace("syslog file path: {}", remoteLogPath); + logLines = execTailOnRemoteFile(sshCommand, remoteLogPath, numLines); + if (logLines != null) { + sb.append(LoggingResponseBuilder.logLinesToXml(LogFileSource.SYSLOG, ipAddress, StringEscapeUtils.escapeXml(logLines.toString()))); + } + return sb.toString(); + } + + // Code based on Stack Overflow suggestion: + // http://stackoverflow.com/questions/686231/java-quickly-read-the-last-line-of-a-text-file + // Pretty basic: byte-based (no Unicode) and relies on Unix-style EOL 0xA + private static String getTailOfFile(File file, int numLines) throws FileNotFoundException, IOException + { + if (numLines < 0) { + return null; + } else if (numLines == 0) { + return ""; + } + java.io.RandomAccessFile raFile = new java.io.RandomAccessFile(file, "r"); + long fileLength = file.length() - 1; + StringBuilder sb = new StringBuilder(); + int line = 0; + + for (long filePointer = fileLength; filePointer >= 0; filePointer--) { + raFile.seek(filePointer); + int readByte = raFile.readByte(); + + if (readByte == 0xA) { + if (filePointer < fileLength) { + line = line + 1; + if (line >= numLines) { + break; + } + } + } + sb.append((char)readByte); + } + + String lastLines = sb.reverse().toString(); + return lastLines; + } + + private static String execTailOnFile(File file, int numLines) throws IOException + { + String numLinesArg = String.valueOf(numLines); + if ((numLines < 0) || (numLinesArg == null) || (numLinesArg.length() == 0) || (file == null) || !file.exists()) { + return null; + } else if (numLines == 0) { + return ""; + } + Process p = new ProcessBuilder("/usr/bin/tail", "-n " + numLinesArg, file.getAbsolutePath()).start(); + try { + p.waitFor(); + } catch (InterruptedException ex) { + logger.warn("Tail on logfile {} interrupted!", file.getAbsoluteFile()); + } + logger.trace("Tail process exited with code {} ", String.valueOf(p.exitValue())); + // Get tail's output: its InputStream + InputStream is = p.getInputStream(); + BufferedReader reader = null; + + StringBuilder sb = new StringBuilder(); + try { + reader = new BufferedReader(new InputStreamReader(is)); + + String s; + while ((s = reader.readLine()) != null) { + sb.append(s + "\n"); + } + is.close(); + } finally { + if (reader != null) { + try { + reader.close(); + } catch (IOException ioe) { + // Nothing to do + } + } + } + + return sb.toString(); + } + + /** + * Count the number of newline characters in a string. + * + * @param logLines The string to parse (assumed to be log lines) + * @return The number of newlines found + */ + private static int lineCount(String logLines) + { + return logLines.split(System.getProperty("line.separator")).length; + } + + /** + * Traverse the specified topology and return a list of instances. + * Included instance types: + *
    + *
  • E3Gateway + *
  • E3GatewayA + *
  • E3Manager + *
  • E3ManagerA + *
+ * + * @param t The topology to traverse + * @return A List of instances found in the topology + */ + private List getInstanceList(ITopology t) + { + List instances = new LinkedList(); + if (t == null) { + logger.warn("topology is null when trying to retrieve instances!"); + } else { + instances.addAll(t.getInstancesByType("E3Gateway")); + instances.addAll(t.getInstancesByType("E3Manager")); + instances.addAll(t.getInstancesByType("E3GatewayA")); + instances.addAll(t.getInstancesByType("E3ManagerA")); + // add other types? + } + return instances; + } + + /* + * Local file operations + */ + + /** + * Copy a file from one location to another on the localhost, first moving + * (renaming) the source file out of the way of any rotator process, and + * then optionally deleting the source file after a successful copy. + * Will attempt to replicate the modification time from the original file. + * + * @param sourceFile File to copy + * @param destFile Destination file + * @param deleteSource If true, will delete original after copy + * @return The number of bytes copied + * @throws IOException + */ + public static long copyLocalFile(File sourceFile, File destFile, boolean deleteSource) throws IOException + { + long bytesCopied = 0L; + + if ((sourceFile == null) || (destFile == null)) { + throw new NullPointerException("Source or destination file is null (source: " + sourceFile + ", dest: " + destFile + ")"); + } + + if (!destFile.exists()) { + destFile.createNewFile(); + } + + String origSourcePath = sourceFile.getPath(); + File tempFile = new File(tempNameForSourceFile(sourceFile.getPath())); + FileChannel source = null; + FileChannel destination = null; + IOException cleanupException = null; + boolean success = false; + + // Copy and validate result + try { + // Rename source file to temporary name before copying + logger.debug("Renaming local file to: {}", tempFile.getPath()); + if (!sourceFile.renameTo(tempFile)) { + logger.error("Could not move file to new name: {}", tempFile.getAbsolutePath()); + } else { + source = new FileInputStream(tempFile).getChannel(); + destination = new FileOutputStream(destFile).getChannel(); + bytesCopied = destination.transferFrom(source, 0, source.size()); + copyModificationTime(tempFile, destFile); + + // Check integrity of copy + success = validateFileCopy(tempFile, destFile); + if (!success) { + logger.warn("Copy of file {} did not pass integrity check!", origSourcePath); + } + } + } catch (IOException ex) { + // If there's been an error copying the file, we may be left with a zero-length or incomplete file + if (!success) { + logger.debug("Deleting failed copy of local file: {}", destFile.getAbsolutePath()); + destFile.delete(); + } + } finally { + // Use a try-block during cleanup, but only throw exception if the + // main file-copy try-block doesn't + try { + if (source != null) { + source.close(); + } + if (destination != null) { + destination.close(); + } + if (deleteSource && success) { + logger.debug("Deleting local source file: {}", tempFile.getAbsolutePath()); + tempFile.delete(); + } else { + // Move source file back from temp name + if (tempFile == null || !tempFile.renameTo(new File(origSourcePath))) { + logger.error("Could not restore original filename: {}", origSourcePath); + } + } + } catch (IOException ex) { + logger.warn("IOException during local file-copy cleanup: {}", ex); + cleanupException = new IOException(ex); + } + } + + if (cleanupException != null) { + throw cleanupException; + } + return bytesCopied; + } + + /** + * Copy the modification time from one local file to another. + * + * @param sourceFile The file to copy the mod time from + * @param destFile The file to copy the mod time to + * @throws IOException + */ + public static void copyModificationTime(File sourceFile, File destFile) throws IOException + { + destFile.setLastModified(sourceFile.lastModified()); + } + + private static boolean validateFileCopy(File sourceFile, File destFile) throws IOException + { + boolean success; + long sourceLength = sourceFile.length(); + long destLength = destFile.length(); + if (sourceLength != destLength) { + logger.error("File-size difference after copy of file {}: {}", + sourceFile.getAbsolutePath(), "orig size: " + String.valueOf(sourceLength) + ", copy size: " + String.valueOf(destLength)); + success = false; + } else { + // Check if last lines of files are the same + String sourceTail = execTailOnFile(sourceFile, 1); + String destTail = execTailOnFile(destFile, 1); + success = sourceTail != null && sourceTail.equals(destTail); + if (!success) { + logger.error("Last lines of copied files are different: '{}' vs '{}'", sourceTail, destTail); + } + } + + return success; + } + + /** + * Make a copy of a local file, but write first to a "working" temporary file and then + * rename the temporary file to the destination name. + * + * @param sourceFile The file to copy + * @param destFile The final destination of the copy + * @param deleteSource If true, will delete original after copy + * @return The number of bytes copied + * @throws IOException + */ + public static long copyLocalFileWithWorkingTemp(File sourceFile, File destFile, boolean deleteSource) throws IOException + { + File tempLocalFile = new File(tempNameForWorkingFile(destFile.getPath())); + long bytesCopied = copyLocalFile(sourceFile, tempLocalFile, deleteSource); + tempLocalFile.renameTo(destFile); + return bytesCopied; + } + + /* + * Remote file operations + */ + + /** + * Copies the appropriate logging-config file for the logSource from the ssh remote host to + * the path specified by destFilePath. May search remote host at multiple locations for + * config file, or use a default path. + * + * @param sshCommand An connected SSHCommand session + * @param destFilePath The target path for the copy of the config file + * @param logSource The type of log-config file to look for + * @return
    + *
  • true if an appropriate log-config file was found and copied + *
  • false otherwise + *
+ */ + private static boolean copyRemoteConfigFile(SSHCommand sshCommand, String destFilePath, LogFileSource logSource) + { + boolean success = false; + if (logSource.equals(LogFileSource.JAVA)) { + try { + // We assume there is only one location for the java-logging config file + String remoteConfigPath = LoggingUtil.defaultConfigPath; + success = (sshCommand.copyFrom(remoteConfigPath, destFilePath) > 0); + } catch (Exception ex) { + // swallow exception since failure means we try default paths, etc + } + + } else if (logSource.equals(LogFileSource.SYSLOG)) { + + // There are a couple of pre-defined alternatives for syslog config file paths + // And NonJavaLogger.getConfigFilePath() could return a non-default value if setConfigFilePath() has been used + String [] altPaths = NonJavaLogger.getAltConfigFilePaths(); + List pathCandidates = new LinkedList(); + pathCandidates.add(NonJavaLogger.getConfigFilePath()); + pathCandidates.addAll(Arrays.asList(altPaths)); + //boolean foundConfigFile = false; + for (String pathCand : pathCandidates) { + String remoteConfigPath = pathCand; + try { + logger.debug("Trying syslog config path: {}", pathCand); + if (sshCommand.copyFrom(remoteConfigPath, destFilePath) > 0) { + success = true; + break; + } + } catch (Exception ex) { + logger.debug("Failed on path {}", remoteConfigPath); + } + } + } else { + logger.warn("Invalid log-file type passed to getRemoteLogPath: {}", logSource.toString()); + } + + return success; + } + + /** + * Creates a local directory to hold collected log files, specific to the log source (JAVA, SMX, SYSLOG) + * + * @param instanceCollectionDir The parent directory for the new directory + * @param logSource The log-file source (determines name of created directory) + * @return A File object representing the new directory, null on error + */ + private static File createLocalLogTargetDir(File instanceCollectionDir, LogFileSource logSource) + { + File logTargetDir = new File(instanceCollectionDir, logSource.toString()); + if (logTargetDir.exists()) { + if (!logTargetDir.isDirectory()) { + logger.error("Log collection target path is not a directory: {}", logTargetDir.getAbsolutePath()); + return null; + } + } else if (!logTargetDir.mkdirs()) { + logger.error("Could not create log collection target directory: {}", logTargetDir.getAbsolutePath()); + } + return logTargetDir; + } + + /** + * Searches the contents of the specified remote directory, and returns a list of FileInfo + * instances that represent remote files that match the specified basename. + * + * @param sshCommand An active (connected) SSHCommand + * @param remoteDirPath The path on the remote machine to search for matching files + * @param baseName A base filename to compare against each remote filename (no path) to determine a match + * @return A List of matching files in FileInfo form, empty if no matches were found + * @throws JSchException + * @throws IOException + */ + private static List getMatchingRemoteFileList(SSHCommand sshCommand, String remoteDirPath, String baseName) throws JSchException, IOException + { + if ((sshCommand == null) || !sshCommand.isConnected()) { + throw new JSchException("Not connected with a valid SSH session"); + } + String remoteUsername = null; + if (LogCollector.collectOnlyUserOwnedLogs) { + remoteUsername = sshCommand.getSessionUsername(); + if (remoteUsername == null) { + throw new JSchException("Username for SSH session is not valid"); + } + } + // First get a list of *all* files in the remote directory, and then + // parse the results for a match with the target basename + // (Prefer to do the matching work locally rather than remotely) + List matches = new LinkedList(); + String findCmd; + if (LogCollector.collectOnlyUserOwnedLogs) { + findCmd = "find " + remoteDirPath + " -maxdepth 1 -user " + remoteUsername + " -perm -664 -type f"; + } else { + findCmd = "find " + remoteDirPath + " -maxdepth 1 -type f"; + } + findCmd = findCmd + " -printf '%T@\t%s\t%p\n' 2> /dev/null"; + ShellCommandResult sshResult = sshCommand.execShellCommand(findCmd); + String[] allFiles = sshResult.getResult().split("\n"); + LogFileFilter baseFileFilter = new LogFileFilter(baseName); + + for (String remoteFileItem : allFiles) { + String[] remoteFileItems = remoteFileItem.split("\t"); + if (remoteFileItems.length != 3) { + logger.warn("Got remote file entry, but not formatted as expected: {}", remoteFileItem); + } else { + String remoteFilePath = remoteFileItems[2]; + File remoteLogFile = new File(remoteFilePath); + //logger.debug("Consider {} vs {}", remoteLogFile.getName(), filenameRegex); + if (baseFileFilter.accept(remoteLogFile)) { + matches.add(new FileInfo(remoteFilePath, remoteFileItems[1], remoteFileItems[0])); + //logger.debug("{} matches!", remoteLogFile.getName()); + } else { + logger.trace ("No match between regex '{}' and '{}'", baseName, remoteLogFile.getName()); + } + } + } + + return matches; + } + + /** + * Formats the filename for a copied log file to enable identification and sorting. + * Currently transforms rolling-appender style (".1") file suffixes to + * daily-rolling-appender style ("yyyy-MM-dd-HH-ss)". + * + * @param logFileInfo FileInfo structure for log file + * @param localTargetDir The directory where this file will be placed + * @return New filename (no path) for log file + */ + private static String targetNameForLogFile(FileInfo logFileInfo, File localTargetDir) + { + // Assume log files have either a rolling file extension (e.g. ".1") + // or a daily-rolling file extension ("2012-05-01-14-00") + // Convert log files with rolling extensions to dailyRolling for uniqueness + File logFile = new File(logFileInfo.filePath); + String localName = logFile.getName(); + if (localName.matches(LoggingUtil.rollingFilePatternString)) { + long modTime = (long) (Double.parseDouble(logFileInfo.fileModtime) * 1000.0); + Date modDate = new Date(modTime); + DateFormat format = new SimpleDateFormat(LoggingUtil.minRollingDatePattern); + String formattedDate = format.format(modDate); + localName = localName.replaceFirst(LoggingUtil.rollingFilePatternString, "$1." + formattedDate); + + // Uniquify in target directory + // Don't uniquify if we don't delete source logs, since this will result in local duplicates + if (uniquifyCopiedFilenames) { + int id = 0; + File targetFile = new File(localTargetDir, localName); + boolean uniquified = false; + while (targetFile.exists()) { + if (++id > uniquifyLimit) { + break; + } + uniquified = true; + targetFile = new File(localTargetDir, localName + "." + String.valueOf(id)); + } + if (uniquified) { + logger.debug("Uniquified filename {} to {}", logFile.getName(), targetFile.getName()); + } + localName = targetFile.getName(); + } + logger.debug("Changed target filename {} to {}", logFile.getName(), localName); + } + return localName; + } + + /** + * Formats the filename for a copied log file to enable identification and sorting. + * Currently transforms rolling-appender style (".1") file suffixes to + * daily-rolling-appender style ("yyyy-MM-dd-HH-ss)". + * + * @param logFile Log-file File object + * @param localTargetDir The directory where this file will be placed + * @return New filename (no path) for log file + */ + private static String targetNameForLogFile(File logFile, File localTargetDir) + { + // Assume log files have either a rolling file extension (e.g. ".1") + // or a daily-rolling file extension ("2012-05-01-14-00") + // Convert log files with rolling extensions to dailyRolling for uniqueness + String localName = logFile.getName(); + if (localName.matches(LoggingUtil.rollingFilePatternString)) { + long modTime = logFile.lastModified(); + Date modDate = new Date(modTime); + DateFormat format = new SimpleDateFormat(LoggingUtil.minRollingDatePattern); + String formattedDate = format.format(modDate); + localName = localName.replaceFirst(LoggingUtil.rollingFilePatternString, "$1." + formattedDate); + + // Uniquify in target directory, requested + // Don't uniquify if we don't delete the original (source) log file, + // since we'll end up with duplicates + if (uniquifyCopiedFilenames) { + int id = 0; + File targetFile = new File(localTargetDir, localName); + while (targetFile.exists()) { + if (++id > uniquifyLimit) { + break; + } + targetFile = new File(localTargetDir, localName + "." + String.valueOf(id)); + logger.debug("Uniquified filename {} to {}", logFile.getName(), targetFile.getName()); + } + localName = targetFile.getName(); + } + logger.debug("Changed target filename {} to {}", logFile.getName(), localName); + } + return localName; + } + + /** + * Copies a file on a remote host to a local path. Before copying, renames source file + * with a temporary name to move it out of the way of any rotator process. + * Optionally deletes the file from the remote host. + * + * @param sshCommand An active (connected) SSHCommand + * @param remoteFileInfo A FileInfo structure representing the remote file + * @param localFilePath The full path for the local file copy + * @param deleteSource If true and the copied succeeds, the remote file will be deleted + * @return The number of bytes copied. + * @throws JSchException + * @throws IOException + */ + private static long copyRemoteFile(SSHCommand sshCommand, FileInfo remoteFileInfo, String localFilePath, boolean deleteSource) throws JSchException, IOException + { + String remoteFilePath = remoteFileInfo.filePath; + String tempRemotePath = tempNameForSourceFile(remoteFilePath); + File localFile = null; + long bytesCopied = 0L; + IOException cleanupIOException = null; + JSchException cleanupJSchException = null; + boolean success = false; + + // Copy file and validate result + try { + // Rename the remote file with a temporary name before copying + logger.debug("Renaming remote file to: {}", tempRemotePath); + sshCommand.execShellCommand("mv " + remoteFilePath + " " + tempRemotePath); + + // Copy the (renamed) remote file to local destination + remoteFileInfo.filePath = tempRemotePath; // remote file name is needed during validation + bytesCopied = sshCommand.copyFrom(tempRemotePath, localFilePath); + localFile = new File(localFilePath); + long modTime = (long) (Double.parseDouble(remoteFileInfo.fileModtime) * 1000.0); + localFile.setLastModified(modTime); + + // Check integrity of copy + success = validateRemoteFileCopy(sshCommand, remoteFileInfo, localFilePath); + if (!success) { + logger.warn("Copy of file {} did not pass integrity check!", remoteFilePath); + } + } catch (IOException ex) { + // If there's been an error copying the file, we may be left with a zero-length or incomplete file + if ((localFile != null) && localFile.exists() && !success) { + logger.debug("Deleting failed local copy of remote file: {}", localFile.getAbsolutePath()); + localFile.delete(); + } + } finally { + // Use a try-block during cleanup, but only throw exception if the + // main file-copy try-block doesn't + try { + if (deleteSource && success) { + logger.debug("Deleting remote file: {}", tempRemotePath); + sshCommand.execShellCommand("rm " + tempRemotePath); + } else { + // Move source file back from temporary name + sshCommand.execShellCommand("mv " + tempRemotePath + " " + remoteFilePath); + } + } catch (JSchException ex) { + logger.warn("JSchException during remote file copy cleanup: {}", ex); + cleanupJSchException = new JSchException(ex.getMessage()); + } catch (IOException ex) { + logger.warn("IOException during remote file copy cleanup: {}", ex); + cleanupIOException = new IOException(ex); + } + remoteFileInfo.filePath = remoteFilePath; // restore original file name in argument + } + + if (cleanupJSchException != null) { + throw cleanupJSchException; + } else if (cleanupIOException != null) { + throw cleanupIOException; + } + return bytesCopied; + } + + private static boolean validateRemoteFileCopy(SSHCommand sshCommand, FileInfo remoteFileInfo, String localFilePath) throws JSchException, IOException + { + boolean success; + File localFile = new File(localFilePath); + String remoteFilePath = remoteFileInfo.filePath; + long remoteLength = Long.parseLong(remoteFileInfo.fileSize); + long localLength = localFile.length(); + if (localLength != remoteLength) { + logger.warn("File-size difference after copy of remote log file {}: {}", + remoteFilePath, "remote size: " + String.valueOf(remoteLength) + ", local size: " + String.valueOf(localLength)); + success = false; + } else { + // Check if last lines of files are the same + String remoteTail = execTailOnRemoteFile(sshCommand, remoteFilePath, 1); + String localTail = execTailOnFile(localFile, 1); + success = remoteTail != null && remoteTail.equals(localTail); + if (!success) { + logger.error("Last lines of copied files are different: '{}' vs '{}'", localTail, remoteTail); + } + } + + return success; + } + + /** + * Copies a file on a remote host to a local path, using a temporary local file intermediary. Optionally deletes the file from the remote host. + * + * @param sshCommand An active (connected) SSHCommand + * @param remoteFileInfo A FileInfo structure representing the remote file + * @param localFilePath The full path for the local file copy + * @param deleteSource If true and the copied succeeds, the remote file will be deleted + * @return The number of bytes copied. + * @throws JSchException + * @throws IOException + */ + private static long copyRemoteFileWithWorkingTemp(SSHCommand sshCommand, FileInfo remoteFileInfo, String localFilePath, boolean deleteSource) throws JSchException, IOException + { + String tempLocalPath = tempNameForWorkingFile(localFilePath); + long bytesCopied = copyRemoteFile(sshCommand, remoteFileInfo, tempLocalPath, deleteSource); + (new File(tempLocalPath)).renameTo(new File(localFilePath)); + return bytesCopied; + } + + private static String execTailOnRemoteFile(SSHCommand sshCommand, String remoteFilePath, int numLines) throws JSchException, IOException + { + if ((sshCommand == null) || !sshCommand.isConnected()) { + throw new JSchException("Not connected with a valid SSH session"); + } + String numLinesArg = String.valueOf(numLines); + if ((numLines < 0) || (numLinesArg == null) || (numLinesArg.length() == 0) || (remoteFilePath == null) || (remoteFilePath.length() == 0)) { + return null; + } else if (numLines == 0) { + return ""; + } + + String tailCmd = "/usr/bin/tail -n " + numLinesArg + " " + remoteFilePath; + ShellCommandResult sshResult = sshCommand.execShellCommand(tailCmd); + logger.debug("Remote tail process exited with code {}", String.valueOf(sshResult.getExitStatus())); + String logLines = sshResult.getResult(); + return logLines; + } + + /** + * Format an ip address string for use as a directory name. + * + * @param ipAddress The ip address in the usual IPv4 format + * @return + */ + private static String ipToCollectionDirectory(String ipAddress) + { + return ipAddress.replace(".", "_"); + } + + /** + * Reverses the formatting performed by the ipToCollectionDirectory function. + * + * @param dirName The collection directory name + * @return The name re-formatted as an IPv4 address + */ + private static String collectionDirectoryToIP(String dirName) + { + String ip = dirName.replaceAll("^(\\d{1,3})_(\\d{1,3})_(\\d{1,3})_(\\d{1,3})$", "$1\\.$2\\.$3\\.$4"); + return ip; + } + + private static String tempNameForWorkingFile(String fileNameOrPath) + { + return fileNameOrPath + workingFileSuffix; + } + + private static String tempNameForSourceFile(String fileNameOrPath) + { + Date modDate = new Date(); + DateFormat format = new SimpleDateFormat(LoggingUtil.minRollingDatePattern); + String formattedDate = format.format(modDate); + return fileNameOrPath + ".collected_" + formattedDate; + } + + /** + * Log an entire Instance structure. + * + * @param instance The Instance to send to the log + */ + public static void logInstance(Instance instance) + { + logger.debug("Got instance: {}", instance); + logger.trace("SSHKeyName: {}", instance.getSSHKeyName()); + logger.trace("User: {}", instance.getUser()); + logger.trace("Password: {}", instance.getPassword()); + logger.trace("Port: {}", instance.getPort()); + logger.trace("Area: {}", instance.getArea()); + logger.trace("SSHKey: {}", instance.getSSHKey()); + } + + /** + * Gets a specified number of most-recent log lines from the localhost's + * rotated logs. + * + * This method has been supplanted by the other log-collection methods in this class. + * + * @param numLines + * @return + * @throws IOException + */ + public static String getLocalLogLines(LogFileSource logSource, int numLines) throws IOException + { + if (!LogFileSource.JAVA.equals(logSource) && !LogFileSource.SMX.equals(logSource)) { + logger.warn("Unexpected log-source value: {}", logSource == null ? "(null)" : logSource); + return null; + } + + StringBuilder logLines = null; + String logFilePath = LoggingUtil.getLocalLogFilePath(logSource); + int lineCount = 0; + + File logDir = (new File(logFilePath)).getParentFile(); + if (!logDir.exists() || !logDir.isDirectory()) { + return null; + } + + // Try getting lines from the current log file(s) ... + logLines = new StringBuilder(); + int logGen = 1; + try { + while (lineCount < numLines) { + File logFile = new File(logFilePath + "." + String.valueOf(logGen)); + if (!logFile.exists()) { + break; + } + String logContent = getTailOfFile(logFile, numLines - lineCount); + logLines.insert(0, logContent); + lineCount += lineCount(logContent); + logGen++; + } + } catch (IOException ex) { + logger.warn("Couldn't read from log file {}", logFilePath); + } + + return LoggingResponseBuilder.logLinesToXml(LogFileSource.JAVA, E3Constant.localhost, logLines.toString()); + } + + +} diff --git a/exposure-engine/system-manager/src/main/java/com/alu/e3/logger/LoggingManager.java b/exposure-engine/system-manager/src/main/java/com/alu/e3/logger/LoggingManager.java new file mode 100644 index 0000000..22cc817 --- /dev/null +++ b/exposure-engine/system-manager/src/main/java/com/alu/e3/logger/LoggingManager.java @@ -0,0 +1,1134 @@ +/** + * Copyright © 2012 Alcatel-Lucent. + * + * See the NOTICE file distributed with this work for additional + * information regarding copyright ownership. + * Licensed to you 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 com.alu.e3.logger; + +import java.io.IOException; +import java.util.Arrays; +import java.util.List; +import java.util.concurrent.ExecutorService; +import java.util.concurrent.Executors; +import java.util.concurrent.Future; + +import javax.ws.rs.Consumes; +import javax.ws.rs.GET; +import javax.ws.rs.PUT; +import javax.ws.rs.Path; +import javax.ws.rs.PathParam; +import javax.ws.rs.Produces; +import javax.ws.rs.core.MediaType; +import javax.ws.rs.core.Response; +import javax.ws.rs.core.Response.ResponseBuilder; + +import org.apache.cxf.jaxrs.ext.Description; + +import com.alu.e3.Utilities; +import com.alu.e3.common.caching.IEntryListener; +import com.alu.e3.common.logging.LoggingUtil; +import com.alu.e3.common.logging.LoggingUtil.LogFileSource; +import com.alu.e3.common.osgi.api.IDataManager; +import com.alu.e3.common.logging.Category; +import com.alu.e3.common.logging.CategoryLogger; +import com.alu.e3.common.logging.CategoryLoggerFactory; +import com.alu.e3.common.logging.NonJavaLogger; +import com.alu.e3.logger.LogCollector; +import com.alu.e3.data.DataEntryEvent; +import com.alu.e3.data.IDataManagerListener; +import com.alu.e3.data.model.LogLevel; +import com.alu.e3.osgi.api.ITopology; + + +/** + * The LoggingManager class provides a REST-API interface for controlling log levels + * and retrieving collected log lines. It also provides functions for setting + * global log levels by broadcasting log-level updates via the DataManager. + * + * Important note: + * + * The Log Collector is currently not run either by a Timer or by a Spring + * scheduler. It is only run by a call to the "forceLogCollection" REST-API + * method. This will be changed shortly .... + * + */ + +@Path("/system-manager/logging") +public class LoggingManager implements IDataManagerListener, IEntryListener { + + /* Final Members. */ + private static final CategoryLogger logger = CategoryLoggerFactory.getLogger(LoggingManager.class, Category.LOG); + + + /* Members */ + private IDataManager dataManager; + private boolean dataManagerReady; + private ExecutorService collectionExecutor; + private Future collectionResult; + private ITopology topology; + + + /** + * Default Constructor + */ + private LoggingManager() + { + dataManagerReady = false; + } + + public void init() + { + dataManager.addListener(this); + } + + /* + * IEntryListener implementation + */ + + /** + * Property setter + * + * @param dataManager The new IDataManager reference + */ + public void setDataManager(IDataManager dataManager) + { + // set dataManager before adding as listener, otherwise, dataManagerReady might fail! + this.dataManager = dataManager; + dataManagerReady = false; + } + + /** + * Called by DataManager when it's ready (has loaded all its tables) + */ + @Override + public void dataManagerReady() + { + logger.debug("DataManager ready, registering as Log-Level Listener"); + dataManagerReady = true; + this.dataManager.addLogLevelListener(this); + } + + /** + * Called by Spring magic + */ + public void destroy() + { + logger.debug("Destroying, removing as listener"); + + dataManagerReady = false; + if (dataManager != null) { + dataManager.removeListener(this); + dataManager.removeLogLevelListener(this); + } + } + + /** + * Sets the static topology that represents the current system + * topology, assumed to be updated on changes. Set by spring. + * + * @param topology The current system topology. + */ + public void setTopology(ITopology topology) + { + this.topology = topology; + } + + /* + * IEntryListener implementation + */ + + /** + * The (single) log level value has been added. + */ + @Override + public void entryAdded(DataEntryEvent event) + { + // The manager does nothing here (except perhaps verify) + // The loggingClient does the actual work of changing log level + } + + + /** + * The log entry has been updated. + */ + @Override + public void entryUpdated(DataEntryEvent event) + { + // The manager does nothing here (except perhaps verify) + // The loggingClient does the actual work of changing log level + } + + + /** + * A log entry has been removed, this should probably not happen + */ + @Override + public void entryRemoved(DataEntryEvent event) + { + } + + /** + * Currently, we do not handle instanceId parameters as intended. + * (This is deferred until there is some mechanism for callers + * to get instanceIds from a Topology object or client.) + * We have left the instanceId-parameter + * form of the REST-API calls in for future use, but for now + * we interpret instanceIds only as ints where 0 means "all instances" + * and anything else means localhost. + * + * @param instanceId ID of instance to query + */ + private boolean isGlobalInstanceId(String instanceId) + { + boolean globalLevel = true; + if (instanceId != null) { + try { + int instanceInt = Integer.parseInt(instanceId); + globalLevel = (instanceInt == 0); + } catch (NumberFormatException ex){ + // ignore malformed instanceId, and assume globalLevel + logger.debug("Got exception when trying to convert: {}", instanceId); + } + } + return globalLevel; + } + + /** + * The REST method for getting the set of logging categories and the enabled status for each. + */ + @GET + @Path("/loggingCategories") + @Produces({ MediaType.APPLICATION_XML }) + @Consumes({ MediaType.WILDCARD }) + @Description(value = "REST API to retrieve the set of logging categories and the enable/disable status for each.") + public Response restGetLoggingCategories() + { + logger.debug("rest-api call to getLoggingCategories"); + CategoryResponse response = new CategoryResponse(CategoryResponse.SUCCESS); + List categoryList = CategoryListWrapper.fromDataModel(Arrays.asList(Category.values())); + response.setCategories(categoryList); + ResponseBuilder builder = Response.ok(response); + return builder.build(); + } + + /** + * The REST method for setting the set of logging categories and the enabled status for each. + */ + @PUT + @Path("/loggingCategories") + @Produces({ MediaType.APPLICATION_XML }) + @Consumes({ MediaType.APPLICATION_XML }) + @Description(value = "REST API to put the set of logging categories and the enable/disable status for each.") + public Response restPutLoggingCategories(CategoryListWrapper categoryListWrapper) + { + logger.debug("rest-api call to putLoggingCategories"); + // The only exception possible is an IllegalArgumentException when trying to convert an illegal Category (enum) name + try { + // Just calling toDataModel on the Category list will set values for this (manager) instance + List requestCategories = CategoryListWrapper.toDataModel(categoryListWrapper); + if ((this.dataManager == null) || !dataManagerReady) { + logger.error("call to put loggingCategories but DataManager is null or not ready!"); + } else { + for (Category c : requestCategories) { + // Set the shared values explicitly + logger.debug("Requested category: {}: {}", c.name(), c.fullname() + ", " + c.description() + ", " + c.enabled()); + this.dataManager.setLoggingCategory(c, c.enabled()); + } + } + + } catch (Exception ex) { + ex.printStackTrace(System.err); + String result = "PutLoggingCategories error: \n\n"; + result += ex.getMessage() + "\n"; + return Response.status(Response.Status.INTERNAL_SERVER_ERROR).entity(result).build(); + } + + CategoryResponse response = new CategoryResponse(CategoryResponse.SUCCESS); + List categoryList = CategoryListWrapper.fromDataModel(Arrays.asList(Category.values())); + response.setCategories(categoryList); + ResponseBuilder builder = Response.ok(response); + return builder.build(); + } + + /** + * The REST method for getting the global log level. + */ + @GET + @Path("/logLevel") + @Produces({ MediaType.APPLICATION_XML }) + @Consumes({ MediaType.WILDCARD }) + @Description(value = "REST API to retrieve the global java log level.") + public Response restGetLogLevel() + { + LogLevel logLevel = null; + logger.debug("rest-api call to getLogLevel"); + try { + // The parameterless (no instanceId) version could get either the + // local or the global log level. + // For now, it gets the global level. + logLevel = getGlobalLogLevel(); + } catch (Exception e) { + e.printStackTrace(System.err); + + String result = "getLogLevel\n\n"; + result += e.getMessage(); + result += "\n\n"; + result += Utilities.getStackTrace(e); + + return Response.status(Response.Status.INTERNAL_SERVER_ERROR).entity(result).build(); + } + + String content = LoggingResponseBuilder.createResponseContent(LoggingResponseBuilder.logLevelToXml(logLevel)); + logger.debug("LogLevel response: {}", content); + return Response.ok(content, MediaType.APPLICATION_XML_TYPE).build(); + } + + /** + * The REST method for getting the log level for a particular + * instance. + * + * Since callers do not currently have a way of retrieving instance-ids, + * this function only handles two cases: + *
    + *
  • instanceId == 0: return the global log level + *
  • instanceId != 0: return the log level for this instance (localhost) + *
+ * + * @param instanceId The ID for the instance to query (see note above) + */ + @GET + @Path("/instances/{instanceId}/logLevel") + @Produces({ MediaType.APPLICATION_XML }) + @Consumes({ MediaType.WILDCARD }) + @Description(value = "REST API to retrieve the java log level for an instance (1 for localhost, 0 for global).") + public Response restGetInstanceLogLevel(@PathParam("instanceId") String instanceId) + { + LogLevel logLevel = null; + logger.debug("rest-api call to getInstanceLogLevel with instanceId: {}", (instanceId == null ? "(null)" : instanceId)); + try { + logLevel = isGlobalInstanceId(instanceId) ? getGlobalLogLevel() : getLocalLogLevel(); + } catch (Exception e) { + e.printStackTrace(System.err); + + String result = "getLogLevel for instanceId: " + instanceId + "\n\n"; + result += e.getMessage(); + result += "\n\n"; + result += Utilities.getStackTrace(e); + + return Response.status(Response.Status.INTERNAL_SERVER_ERROR).entity(result).build(); + } + + String content = LoggingResponseBuilder.createResponseContent(LoggingResponseBuilder.logLevelToXml(logLevel)); + logger.debug("LogLevel response: {}", content); + return Response.ok(content, MediaType.APPLICATION_XML_TYPE).build(); + } + + /** + * The REST method for putting the global log level. This value is placed + * in the DataManager cache and distributed to all instances, where + * each LoggingClient will pick it up and set the local log level. + * (This is also true for this SystemManager instance.) + * + * @param level A valid log4j log level string (OFF, FATAL, ERROR, WARN, INFO, DEBUG, TRACE, ALL) + */ + @PUT + @Path("/logLevel") + @Produces({ MediaType.APPLICATION_XML }) + //@Consumes({ MediaType.TEXT_PLAIN }) + @Description(value = "REST API to set the global java log level.") + public Response restSetLogLevel(String level) + { + logger.debug("rest-api call to setLogLevel with level = {}", level != null ? level : "(null)"); + LogLevel logLevel = null; + try { + if (LogLevel.isValidLogLevel(level)) { + logLevel = new LogLevel(level); + // The parameterless (no instanceId) version could set either the + // local or the global log level. + // For now, it sets the global level. + setGlobalLogLevel(logLevel); + } else { + logger.debug("Call to REST setLogLevel with invalid log level string: {}", level); + String result = "Invalid logLevel '" + level + "' - must be one of " + LogLevel.Log4JLevel.valuesList; + return Response.status(Response.Status.NOT_ACCEPTABLE).entity(result).build(); + } + + } catch (Exception e) { + e.printStackTrace(System.err); + + String result = "setLogLevel " + logLevel + "\n\n"; + result += e.getMessage(); + result += "\n\n"; + result += Utilities.getStackTrace(e); + + return Response.status(Response.Status.INTERNAL_SERVER_ERROR).entity(result).build(); + } + + String content = LoggingResponseBuilder.createResponseContent(LoggingResponseBuilder.logLevelToXml(logLevel)); + logger.debug("LogLevel response: {}", content); + return Response.ok(content, MediaType.APPLICATION_XML_TYPE).build(); + } + + /** + * The REST method for setting the log level for a particular + * instance. + * + * Since callers do not currently have a way of retrieving instance-ids, + * this function only handles two cases: + *
    + *
  • instanceId == 0: set the global log level + *
  • instanceId != 0: set the log level for this instance (localhost) + *
+ * + * @param instanceId The ID of the instance for which to change the log level (see note above) + * @param level A valid log4j log level string (OFF, FATAL, ERROR, WARN, INFO, DEBUG, TRACE, ALL) + */ + @PUT + @Path("/instances/{instanceId}/logLevel") + @Produces({ MediaType.APPLICATION_XML }) + //@Consumes({ MediaType.TEXT_PLAIN }) + @Description(value = "REST API to set the java log level for an instance (1 for localhost, 0 for global).") + public Response restSetInstanceLogLevel(@PathParam("instanceId") String instanceId, String level) + { + logger.debug("rest-api call to setInstanceLogLevel with instanceId = {}, level = {}", + instanceId != null ? instanceId : "(null)", level != null ? level : "(null)"); + LogLevel logLevel = null; + try { + if (LogLevel.isValidLogLevel(level)) { + logLevel = new LogLevel(level); + if (isGlobalInstanceId(instanceId)) { + setGlobalLogLevel(logLevel); + } else { + setLocalLogLevel(logLevel); + } + } else { + logger.debug("Call to REST setLogLevel with invalid log level string: {}", level); + String result = "Invalid logLevel '" + level + "' - must be one of " + LogLevel.Log4JLevel.valuesList; + return Response.status(Response.Status.NOT_ACCEPTABLE).entity(result).build(); + } + + } catch (Exception e) { + e.printStackTrace(System.err); + + String result = "setLogLevel " + logLevel + "\n\n"; + result += e.getMessage(); + result += "\n\n"; + result += Utilities.getStackTrace(e); + + return Response.status(Response.Status.INTERNAL_SERVER_ERROR).entity(result).build(); + } + + String content = LoggingResponseBuilder.createResponseContent(LoggingResponseBuilder.logLevelToXml(logLevel)); + logger.debug("LogLevel response: {}", content); + return Response.ok(content, MediaType.APPLICATION_XML_TYPE).build(); + } + + /** + * The REST method for getting the global servicemix log level. + */ + @GET + @Path("/smxlogLevel") + @Produces({ MediaType.APPLICATION_XML }) + @Consumes({ MediaType.WILDCARD }) + @Description(value = "REST API to retrieve the global servicemix log level.") + public Response restGetSMXLogLevel() + { + LogLevel logLevel = null; + logger.debug("rest-api call to getLogLevel"); + try { + // The parameterless (no instanceId) version could get either the + // local or the global log level. + // For now, it gets the global level. + logLevel = getGlobalSMXLogLevel(); + } catch (Exception e) { + e.printStackTrace(System.err); + + String result = "getSMXLogLevel\n\n"; + result += e.getMessage(); + result += "\n\n"; + result += Utilities.getStackTrace(e); + + return Response.status(Response.Status.INTERNAL_SERVER_ERROR).entity(result).build(); + } + + String content = LoggingResponseBuilder.createResponseContent(LoggingResponseBuilder.logLevelToXml(logLevel)); + logger.debug("SMXLogLevel response: {}", content); + return Response.ok(content, MediaType.APPLICATION_XML_TYPE).build(); + } + + /** + * The REST method for getting the servicemix log level for a particular + * instance. + * + * Since callers do not currently have a way of retrieving instance-ids, + * this function only handles two cases: + *
    + *
  • instanceId == 0: return the global log level + *
  • instanceId != 0: return the log level for this instance (localhost) + *
+ * + * @param instanceId The ID for the instance to query (see note above) + */ + @GET + @Path("/instances/{instanceId}/smxlogLevel") + @Produces({ MediaType.APPLICATION_XML }) + @Consumes({ MediaType.WILDCARD }) + @Description(value = "REST API to retrieve the servicemix log level for an instance (1 for localhost, 0 for global).") + public Response restGetInstanceSMXLogLevel(@PathParam("instanceId") String instanceId) + { + LogLevel logLevel = null; + logger.debug("rest-api call to getInstanceSMXLogLevel with instanceId: {}", (instanceId == null ? "(null)" : instanceId)); + try { + logLevel = isGlobalInstanceId(instanceId) ? getGlobalSMXLogLevel() : getLocalSMXLogLevel(); + } catch (Exception e) { + e.printStackTrace(System.err); + + String result = "getSMXLogLevel for instanceId: " + instanceId + "\n\n"; + result += e.getMessage(); + result += "\n\n"; + result += Utilities.getStackTrace(e); + + return Response.status(Response.Status.INTERNAL_SERVER_ERROR).entity(result).build(); + } + + String content = LoggingResponseBuilder.createResponseContent(LoggingResponseBuilder.logLevelToXml(logLevel)); + logger.debug("SMXLogLevel response: {}", content); + return Response.ok(content, MediaType.APPLICATION_XML_TYPE).build(); + } + + /** + * The REST method for putting the global servicemix log level. This value is placed + * in the DataManager cache and distributed to all instances, where + * each LoggingClient will pick it up and set the local log level. + * (This is also true for this SystemManager instance.) + * + * @param level A valid log4j log level string (OFF, FATAL, ERROR, WARN, INFO, DEBUG, TRACE, ALL) + */ + @PUT + @Path("/smxlogLevel") + @Produces({ MediaType.APPLICATION_XML }) + //@Consumes({ MediaType.TEXT_PLAIN }) + @Description(value = "REST API to set the global servicemix log level.") + public Response restSetSMXLogLevel(String level) + { + logger.debug("rest-api call to setSMXLogLevel with level = {}", level != null ? level : "(null)"); + LogLevel logLevel = null; + try { + if (LogLevel.isValidLogLevel(level)) { + logLevel = new LogLevel(level); + // The parameterless (no instanceId) version could set either the + // local or the global log level. + // For now, it sets the global level. + setGlobalSMXLogLevel(logLevel); + } else { + logger.debug("Call to REST setSMXLogLevel with invalid log level string: {}", level); + String result = "Invalid logLevel '" + level + "' - must be one of " + LogLevel.Log4JLevel.valuesList; + return Response.status(Response.Status.NOT_ACCEPTABLE).entity(result).build(); + } + + } catch (Exception e) { + e.printStackTrace(System.err); + + String result = "setSMXLogLevel " + logLevel + "\n\n"; + result += e.getMessage(); + result += "\n\n"; + result += Utilities.getStackTrace(e); + + return Response.status(Response.Status.INTERNAL_SERVER_ERROR).entity(result).build(); + } + + String content = LoggingResponseBuilder.createResponseContent(LoggingResponseBuilder.logLevelToXml(logLevel)); + logger.debug("SMXLogLevel response: {}", content); + return Response.ok(content, MediaType.APPLICATION_XML_TYPE).build(); + } + + /** + * The REST method for setting the servicemix log level for a particular + * instance. + * + * Since callers do not currently have a way of retrieving instance-ids, + * this function only handles two cases: + *
    + *
  • instanceId == 0: set the global log level + *
  • instanceId != 0: set the log level for this instance (localhost) + *
+ * + * @param instanceId The ID of the instance for which to change the log level (see note above) + * @param level A valid log4j log level string (OFF, FATAL, ERROR, WARN, INFO, DEBUG, TRACE, ALL) + */ + @PUT + @Path("/instances/{instanceId}/smxlogLevel") + @Produces({ MediaType.APPLICATION_XML }) + //@Consumes({ MediaType.TEXT_PLAIN }) + @Description(value = "REST API to set the servicemix log level for an instance (1 for localhost, 0 for global).") + public Response restSetInstanceSMXLogLevel(@PathParam("instanceId") String instanceId, String level) + { + logger.debug("rest-api call to setInstanceSMXLogLevel with instanceId = {}, level = {}", + instanceId != null ? instanceId : "(null)", level != null ? level : "(null)"); + LogLevel logLevel = null; + try { + if (LogLevel.isValidLogLevel(level)) { + logLevel = new LogLevel(level); + if (isGlobalInstanceId(instanceId)) { + setGlobalSMXLogLevel(logLevel); + } else { + setLocalSMXLogLevel(logLevel); + } + } else { + logger.debug("Call to REST setSMXLogLevel with invalid log level string: {}", level); + String result = "Invalid logLevel '" + level + "' - must be one of " + LogLevel.Log4JLevel.valuesList; + return Response.status(Response.Status.NOT_ACCEPTABLE).entity(result).build(); + } + + } catch (Exception e) { + e.printStackTrace(System.err); + + String result = "setSMXLogLevel " + logLevel + "\n\n"; + result += e.getMessage(); + result += "\n\n"; + result += Utilities.getStackTrace(e); + + return Response.status(Response.Status.INTERNAL_SERVER_ERROR).entity(result).build(); + } + + String content = LoggingResponseBuilder.createResponseContent(LoggingResponseBuilder.logLevelToXml(logLevel)); + logger.debug("SMXLogLevel response: {}", content); + return Response.ok(content, MediaType.APPLICATION_XML_TYPE).build(); + } + + /** + * The REST method for getting the global syslog level. + */ + @GET + @Path("/syslogLevel") + @Produces({ MediaType.APPLICATION_XML }) + @Consumes({ MediaType.WILDCARD }) + @Description(value = "REST API to retrieve the global syslog level.") + public Response restGetSyslogLevel() + { + logger.debug("rest-api call to getSyslogLevel"); + String syslogLevel = null; + try { + syslogLevel = getGlobalSyslogLevel(); + } catch (Exception e) { + e.printStackTrace(System.err); + + String result = "getGlobalSyslogLevel\n\n"; + result += e.getMessage(); + result += "\n\n"; + result += Utilities.getStackTrace(e); + + return Response.status(Response.Status.INTERNAL_SERVER_ERROR).entity(result).build(); + } + + String content = LoggingResponseBuilder.createResponseContent(LoggingResponseBuilder.syslogLevelToXml(syslogLevel)); + logger.debug("LogLevel response: {}", content); + return Response.ok(content, MediaType.APPLICATION_XML_TYPE).build(); + } + + /** + * The REST method for getting the syslog level for a particular + * instance. + * + * Since callers do not currently have a way of retrieving instance-ids, + * this function only handles two cases: + *
    + *
  • instanceId == 0: return the global syslog level + *
  • instanceId != 0: return the syslog level for this instance (localhost) + *
+ * + * @param instanceId The ID for the instance to query (see note above) + */ + @GET + @Path("/instances/{instanceId}/syslogLevel") + @Produces({ MediaType.APPLICATION_XML }) + @Consumes({ MediaType.WILDCARD }) + @Description(value = "REST API to retrieve the syslog level for an instance (1 for localhost, 0 for global).") + public Response restGetInstanceSyslogLevel(@PathParam("instanceId") String instanceId) + { + String syslogLevel = null; + logger.debug("rest-api call to getInstanceSyslogLevel with instanceId: {}", (instanceId == null ? "(null)" : instanceId)); + try { + syslogLevel = isGlobalInstanceId(instanceId) ? getGlobalSyslogLevel() : getLocalSyslogLevel(); + } catch (Exception e) { + e.printStackTrace(System.err); + + String result = "getSyslogLevel for instanceId: " + instanceId + "\n\n"; + result += e.getMessage(); + result += "\n\n"; + result += Utilities.getStackTrace(e); + + return Response.status(Response.Status.INTERNAL_SERVER_ERROR).entity(result).build(); + } + + String content = LoggingResponseBuilder.createResponseContent(LoggingResponseBuilder.syslogLevelToXml(syslogLevel)); + logger.debug("SyslogLevel response: {}", content); + return Response.ok(content, MediaType.APPLICATION_XML_TYPE).build(); + } + + /** + * The REST method for setting the global syslog level. This value is placed + * in the DataManager cache and distributed to all instances, where + * each LoggingClient will pick it up and set the local syslog level. + * (This is also true for this SystemManager instance.) + * + * @param syslogLevel A valid syslog level string (EMERG, ALERT, CRIT, ERR, WARNING, NOTICE, INFO, DEBUG) + */ + @PUT + @Path("/syslogLevel") + @Produces({ MediaType.APPLICATION_XML }) + //@Consumes({ MediaType.TEXT_PLAIN }) + @Description(value = "REST API to set the global syslog level.") + public Response restSetSyslogLevel(String syslogLevel) + { + logger.debug("rest-api call to setGlobalSyslogLevel with level = {}", syslogLevel != null ? syslogLevel : "(null)"); + String validatedLevel = null; + if (LogLevel.isValidSyslogLevel(syslogLevel)) { + validatedLevel = syslogLevel; + } + if (validatedLevel == null) { + logger.debug("Call to REST setSyslogLevel with invalid syslog level string: {}", syslogLevel); + String result = "Invalid syslog level '" + syslogLevel + "' - must be one of " + LogLevel.SyslogLevel.valuesList; + return Response.status(Response.Status.NOT_ACCEPTABLE).entity(result).build(); + } + try { + setGlobalSyslogLevel(validatedLevel); + } catch (Exception e) { + e.printStackTrace(System.err); + + String result = "setGlobalSyslogLevel " + syslogLevel + "\n\n"; + result += e.getMessage(); + result += "\n\n"; + result += Utilities.getStackTrace(e); + + return Response.status(Response.Status.INTERNAL_SERVER_ERROR).entity(result).build(); + } + + String content = LoggingResponseBuilder.createResponseContent(LoggingResponseBuilder.syslogLevelToXml(validatedLevel)); + logger.debug("SyslogLevel response: {}", content); + return Response.ok(content, MediaType.APPLICATION_XML_TYPE).build(); + } + + /** + * The REST method for setting the syslog level for a particular + * instance. + * + * Since callers do not currently have a way of retrieving instance-ids, + * this function only handles two cases: + *
    + *
  • instanceId == 0: set the global syslog level + *
  • instanceId != 0: set the log syslevel for this instance (localhost) + *
+ * + * @param instanceId The ID of the instance for which to change the syslog level (see note above) + * @param level A valid syslog level string (EMERG, ALERT, CRIT, ERR, WARNING, NOTICE, INFO, DEBUG) + */ + @PUT + @Path("/instances/{instanceId}/syslogLevel") + @Produces({ MediaType.APPLICATION_XML }) + //@Consumes({ MediaType.TEXT_PLAIN }) + @Description(value = "REST API to set the syslog level for an instance (1 for localhost, 0 for global).") + public Response restSetInstanceSyslogLevel(@PathParam("instanceId") String instanceId, String syslogLevel) + { + logger.debug("rest-api call to setInstanceSysogLevel with instanceId = {}, level = {}", + instanceId != null ? instanceId : "(null)", syslogLevel != null ? syslogLevel : "(null)"); + String validatedLevel = null; + if (LogLevel.isValidSyslogLevel(syslogLevel)) { + validatedLevel = syslogLevel; + } + if (validatedLevel == null) { + logger.debug("Call to REST setSyslogLevel with invalid syslog level string: {}", syslogLevel); + String result = "Invalid syslog level '" + syslogLevel + "' - must be one of " + LogLevel.SyslogLevel.valuesList; + return Response.status(Response.Status.NOT_ACCEPTABLE).entity(result).build(); + } + try { + if (isGlobalInstanceId(instanceId)) { + setGlobalSyslogLevel(validatedLevel); + } else { + setLocalSyslogLevel(validatedLevel); + } + } catch (Exception e) { + e.printStackTrace(System.err); + + String result = "setSyslogLevel " + syslogLevel + "\n\n"; + result += e.getMessage(); + result += "\n\n"; + result += Utilities.getStackTrace(e); + + return Response.status(Response.Status.INTERNAL_SERVER_ERROR).entity(result).build(); + } + + String content = LoggingResponseBuilder.createResponseContent(LoggingResponseBuilder.syslogLevelToXml(validatedLevel)); + logger.debug("SyslogLevel response: {}", content); + return Response.ok(content, MediaType.APPLICATION_XML_TYPE).build(); + } + + /** + * A REST method for triggering a log collection operation. This method + * is provided for debugging and testing: the actual log collector will + * run on a periodic timer. + */ + @GET + @Path("/forceLogCollection") + @Consumes({MediaType.WILDCARD}) + @Produces({MediaType.APPLICATION_XML}) + @Description(value = "REST API to trigger log collection across all instances in the topology.") + public Response forceLogCollection() + { + logger.debug("rest-api call to forceLogCollection"); + try { + startLogCollection(); + } catch (Exception e) { + String result = "forceLogCollection\n\n"; + result += e.getMessage(); + result += "\n\n"; + result += Utilities.getStackTrace(e); + + return Response.status(Response.Status.INTERNAL_SERVER_ERROR).entity(result).build(); + } + String content = LoggingResponseBuilder.createResponseContent(null); + return Response.ok(content, MediaType.APPLICATION_XML_TYPE).build(); + } + + /** + * A REST method for retrieving the latest numLines lines from + * the collected logs. + * + * @param numLines A positive int in string form + */ + @GET + @Path("/collectedLogLines/{numLines}") + @Produces({ MediaType.APPLICATION_XML }) + @Consumes({ MediaType.WILDCARD }) + @Description(value = "REST API to retrieve a specified number of log lines from the collected (rotated) logs.") + public Response restGetLogLines(@PathParam("numLines") String numLines) + { + logger.debug("rest-api call to collectedLogLines/{numLines} with numLines = {}", + numLines == null ? "(null)" : numLines); + int linesRequested = 0; + try { + linesRequested = Integer.parseInt(numLines); + } catch (NumberFormatException ex){ + logger.debug("Got exception when trying to convert: {}", numLines); + String result = "Invalid {numLines} parameter: " + numLines; + return Response.status(Response.Status.NOT_ACCEPTABLE).entity(result).build(); + } + + // Reading already-collected log lines doesn't actually + // require a current topology (could be used for reading lines + // from specific instances, however) + LogCollector logCollector = new LogCollector(this.topology); + String logs = logCollector.getCollectedLogLines(linesRequested); + String content = LoggingResponseBuilder.createResponseContent(logs); + return Response.ok(content, MediaType.APPLICATION_XML_TYPE).build(); + } + + /** + * A REST method for retrieving the latest numLines lines from + * the collected logs. + * + * @param numLines A positive int in string form + */ + @GET + @Path("/activeLogLines/{numLines}") + @Produces({ MediaType.APPLICATION_XML }) + @Consumes({ MediaType.WILDCARD }) + @Description(value = "REST API to retrieve a specified number of log lines from the active log files.") + public Response restGetActiveLogLines(@PathParam("numLines") String numLines) + { + logger.debug("rest-api call to activeLogLines/{numLines} with numLines = {}", + numLines == null ? "(null)" : numLines); + int linesRequested = 0; + try { + linesRequested = Integer.parseInt(numLines); + } catch (NumberFormatException ex){ + logger.debug("Got exception when trying to convert: {}", numLines); + String result = "Invalid {numLines} parameter: " + numLines; + return Response.status(Response.Status.NOT_ACCEPTABLE).entity(result).build(); + } + + LogCollector logCollector = new LogCollector(this.topology); + String logs = logCollector.collectAllActiveLogs(linesRequested); + String content = LoggingResponseBuilder.createResponseContent(logs); + return Response.ok(content, MediaType.APPLICATION_XML_TYPE).build(); + } + + /** + * Returns the global log level from the DataManager's cache. + * + * @return A valid log4j LogLevel (OFF, FATAL, ERROR, WARN, INFO, DEBUG, TRACE, ALL) + * if a global log-level is found in the DataManager cache, + * or null if not. + */ + public LogLevel getGlobalLogLevel() + { + LogLevel logLevel = null; + // Get the system-wide log level value (in the cache) + if ((this.dataManager == null) || !dataManagerReady) { + logger.error("call to shared getLogLevel but DataManager is null or not ready!"); + } else { + logLevel = dataManager.getLogLevel(); + logger.debug("retrieved cached log-level value: {}", (logLevel == null ? "(null)" : logLevel.toString())); + } + return logLevel; + } + + /** + * Returns the local java log level (for localhost). + * + * @return A valid log4j LogLevel (OFF, FATAL, ERROR, WARN, INFO, DEBUG, TRACE, ALL) + * if an E3Appender specification is found in the local logging config file, + * or null if not. + */ + public LogLevel getLocalLogLevel() throws IOException + { + // Get the local log value (in the config file) + return LoggingUtil.getLocalLogLevel(LogFileSource.JAVA); + } + + /** + * Returns the global servicemix log level from the DataManager's cache. + * + * @return A valid log4j LogLevel (OFF, FATAL, ERROR, WARN, INFO, DEBUG, TRACE, ALL) + * if a global log-level is found in the DataManager cache, + * or null if not. + */ + public LogLevel getGlobalSMXLogLevel() + { + LogLevel logLevel = null; + // Get the system-wide log level value (in the cache) + if ((this.dataManager == null) || !dataManagerReady) { + logger.error("call to shared getSMXLogLevel but DataManager is null or not ready!"); + } else { + logLevel = dataManager.getSMXLogLevel(); + logger.debug("retrieved cached smxlog-level value: {}", (logLevel == null ? "(null)" : logLevel.toString())); + } + return logLevel; + } + + /** + * Returns the local servicemix log level (for localhost). + * + * @return A valid log4j LogLevel (OFF, FATAL, ERROR, WARN, INFO, DEBUG, TRACE, ALL) + * if a rootLogger appender specification is found in the local logging config file, + * or null if not. + */ + public LogLevel getLocalSMXLogLevel() throws IOException + { + // Get the local log value (in the config file) + return LoggingUtil.getLocalLogLevel(LogFileSource.SMX); + } + + /** + * Returns the global syslog level from the DataManager's cache. + * + * @return A valid syslog level string (EMERG, ALERT, CRIT, ERR, WARNING, NOTICE, INFO, DEBUG) + * if a global log-level is found in the DataManager cache, + * or null if not. + */ + public String getGlobalSyslogLevel() + { + String syslogLevel = null; + // Get the system-wide syslog level value (in the cache) + if ((this.dataManager == null) || !dataManagerReady) { + logger.error("call to shared getLogLevel but DataManager is null or not ready!"); + } else { + LogLevel logLevel = dataManager.getSyslogLevel(); + logger.debug("retrieved cached log-level value: {}", (logLevel == null ? "(null)" : logLevel.toString())); + if (logLevel != null) { + syslogLevel = logLevel.getSyslogLevel().name(); + } + } + return syslogLevel; + } + + /** + * Returns the local syslog level specific to the E3 facility, + * if one is set in the local syslog config file. + * + * @return A valid syslog level string (EMERG, ALERT, CRIT, ERR, WARNING, NOTICE, INFO, DEBUG), + * or null if no E3-specific level can be determined. + * @throws IOException + */ + public String getLocalSyslogLevel() throws IOException + { + return NonJavaLogger.getLogLevel(); + } + + /** + * Sets the global log level by putting new logLevel in shared + * (DataManager) cache and letting the LoggingClient for + * each instance pick up and set the new level. + * + * @param logLevel A valid log4j LogLevel (OFF, FATAL, ERROR, WARN, INFO, DEBUG, TRACE, ALL) + */ + public void setGlobalLogLevel(LogLevel logLevel) + { + if ((logLevel == null) || (logLevel.getLevel() == null)) { + logger.warn("setGlobalLogLevel called with null level!"); + return; + } + logger.debug("setGlobalLogLevel with level: {}", logLevel.toString()); + + // Set the system-wide log level (in the cache) + // We'll set our local log level when we pick up the cache change + if ((this.dataManager == null) || !dataManagerReady) { + logger.error("call to shared setLogLevel but DataManager is null or not ready!"); + } else { + logger.debug("setting cached log-level value to: {}", logLevel.toString()); + dataManager.setLogLevel(logLevel); + } + } + + /** + * Sets the log level for this instance. + * + * @param logLevel A valid log4j LogLevel (OFF, FATAL, ERROR, WARN, INFO, DEBUG, TRACE, ALL) + * @throws IOException + */ + public void setLocalLogLevel(LogLevel logLevel) throws IOException + { + if ((logLevel == null) || (logLevel.getLevel() == null)) { + logger.warn("setLocalLogLevel called with null level!"); + return; + } + logger.debug("setLocalLogLevel with level: {}", logLevel.toString()); + LoggingUtil.setLocalJavaLogLevel(logLevel); + } + + /** + * Sets the global servicemix log level by putting new smxlogLevel + * in the shared (DataManager) cache and letting the LoggingClient for + * each instance pick up and set the new level. + * + * @param logLevel A valid log4j LogLevel (OFF, FATAL, ERROR, WARN, INFO, DEBUG, TRACE, ALL) + */ + public void setGlobalSMXLogLevel(LogLevel logLevel) + { + if ((logLevel == null) || (logLevel.getLevel() == null)) { + logger.warn("setGlobalSMXLogLevel called with null level!"); + return; + } + logger.debug("setGlobalSMXLogLevel with level: {}", logLevel.toString()); + + // Set the system-wide log level (in the cache) + // We'll set our local log level when we pick up the cache change + if ((this.dataManager == null) || !dataManagerReady) { + logger.error("call to shared setSMXLogLevel but DataManager is null or not ready!"); + } else { + logger.debug("setting cached smxlog-level value to: {}", logLevel.toString()); + dataManager.setSMXLogLevel(logLevel); + } + } + + /** + * Sets the servicemix log level for this instance. + * + * @param logLevel A valid log4j LogLevel (OFF, FATAL, ERROR, WARN, INFO, DEBUG, TRACE, ALL) + * @throws IOException + */ + public void setLocalSMXLogLevel(LogLevel logLevel) throws IOException + { + if ((logLevel == null) || (logLevel.getLevel() == null)) { + logger.warn("setLocalSMXLogLevel called with null level!"); + return; + } + logger.debug("setLocalSMXLogLevel with level: {}", logLevel.toString()); + LoggingUtil.setLocalSMXLogLevel(logLevel); + } + + /** + * Sets the global syslog level by putting a new logLevel in shared + * (DataManager) cache and letting the LoggingClient for + * each instance pick up and set the new level. + * + * @param logLevel A valid syslog level string (EMERG, ALERT, CRIT, ERR, WARNING, NOTICE, INFO, DEBUG) + */ + public void setGlobalSyslogLevel(String syslogLevel) + { + if ((syslogLevel == null) || !LogLevel.isValidSyslogLevel(syslogLevel)) { + logger.warn("setGlobalSyslogLevel called with invalid syslog level: {}", syslogLevel == null ? "(null)" : syslogLevel); + return; + } + logger.debug("setGlobalSyslogLevel with level: {}", syslogLevel); + + // Set the system-wide syslog level (in the cache) + // LoggingClient will set our local syslog level when it picks up the cache change + if ((this.dataManager == null) || !dataManagerReady) { + logger.error("call to shared setSyslogLevel but DataManager is null or not ready!"); + } else { + LogLevel equivLevel = new LogLevel(syslogLevel); + dataManager.setSyslogLevel(equivLevel); + logger.debug("setting cached syslog-level value to: {} (requested {})", equivLevel.toString(), syslogLevel); + } + } + + /** + * Attempts to set the syslog level for the E3 facility on the localhost. + * Calls out to the local loggingClient to actually change the syslog settings. + * + * @param level A valid syslog level string (EMERG, ALERT, CRIT, ERR, WARNING, NOTICE, INFO, DEBUG) + * @throws IOException + */ + public void setLocalSyslogLevel(String level) throws IOException + { + if ((level == null) || !LogLevel.isValidSyslogLevel(level)) { + logger.warn("setLocalSyslogLevel called with invalid level string: {}", + level == null ? "(null)" : level); + return; + } + + // See note at top of NonJavaLogger.java about necessary permissions to change syslog level! + logger.debug("setLocalSylogLevel with level: {}", level); + NonJavaLogger.setLogLevel(level); + } + + /** + * Fire off a log-collection operation. This function is called both + * by the REST-API for asynchronous calls and by the spring task + * scheduler to run periodic log collection. + * + * If another log collection operation is currently running, the + * new collection execution will return (almost) immediately + * after handling a TimeoutException on trying to obtain the LogCollector write lock. + */ + public void startLogCollection() + { + logger.debug("Running log collector from LoggingManager ..."); + if ((collectionExecutor != null) && (collectionResult != null)) { + if (!collectionResult.isDone() && !collectionResult.isCancelled()) { + logger.debug("Log Collector is still active - delaying new collection ..."); + return; + } + } + + LogCollector logCollector = new LogCollector(this.topology); + collectionExecutor = Executors.newSingleThreadExecutor(); + collectionResult = collectionExecutor.submit(logCollector); + } + + /** + * General Setters + */ + public void setCollectionExecutor(ExecutorService collectionExecutor) { + this.collectionExecutor = collectionExecutor; + } + + public void setCollectionResult(Future collectionResult) { + this.collectionResult = collectionResult; + } + +} diff --git a/exposure-engine/system-manager/src/main/java/com/alu/e3/logger/LoggingResponseBuilder.java b/exposure-engine/system-manager/src/main/java/com/alu/e3/logger/LoggingResponseBuilder.java new file mode 100644 index 0000000..35e3c6e --- /dev/null +++ b/exposure-engine/system-manager/src/main/java/com/alu/e3/logger/LoggingResponseBuilder.java @@ -0,0 +1,104 @@ +/** + * Copyright © 2012 Alcatel-Lucent. + * + * See the NOTICE file distributed with this work for additional + * information regarding copyright ownership. + * Licensed to you 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 com.alu.e3.logger; + +import com.alu.e3.common.logging.LoggingUtil.LogFileSource; +import com.alu.e3.data.model.LogLevel; + +/** + * A utility class for building Response objects returned by + * LoggingManager to REST-API calls. + * + * This is intended as a simple equivalent for + * the BasicResponse family found in Provisioning. + * It will probably be replaced by something more + * real as SystemManager requires it .... + * + */ + +public class LoggingResponseBuilder { + + // Only for SUCCESS status responses + public static String createResponseContent(String result) + { + if (result != null) { + return "SUCCESS" + + result + ""; + } else { + return "SUCCESS"; + } + } + + public static String logLevelToXml(LogLevel logLevel) + { + if ((logLevel == null) || (logLevel.getLevel() == null)) { + return ""; + } else { + return "" + logLevel.toString() + ""; + } + } + + public static String syslogLevelToXml(LogLevel logLevel) + { + if ((logLevel == null) || (logLevel.getSyslogLevel() == null)) { + return ""; + } else { + return "" + logLevel.getSyslogLevel() + ""; + } + + } + + public static String syslogLevelToXml(String syslogLevel) + { + if (syslogLevel == null) { + return ""; + } else { + return "" + syslogLevel + ""; + } + + } + + public static String logLinesToXml(LogFileSource logType, String ipAddress, String logLines) + { + StringBuilder xml = new StringBuilder(); + xml.append(""); + xml.append("" + logType.toString() + ""); + if (ipAddress != null) { + xml.append("" + ipAddress + ""); + } else { + xml.append(""); + } + if ((logLines != null) && (logLines.length() > 0)) { + xml.append("
  • " + logLines.replaceFirst("\\n$", "").replaceAll("\\n", "
  • ") + "
  • "); + } + xml.append("
    "); + return xml.toString(); + } + + public static String logCollectionToXml(String xmlLogs) + { + StringBuilder collection = new StringBuilder(); + collection.append(""); + if (xmlLogs != null) { + collection.append(xmlLogs); + } + collection.append(""); + return collection.toString(); + } +} diff --git a/exposure-engine/system-manager/src/main/java/com/alu/e3/osgi/manager/api/IE3Config.java b/exposure-engine/system-manager/src/main/java/com/alu/e3/osgi/manager/api/IE3Config.java new file mode 100644 index 0000000..33ac09e --- /dev/null +++ b/exposure-engine/system-manager/src/main/java/com/alu/e3/osgi/manager/api/IE3Config.java @@ -0,0 +1,37 @@ +/** + * Copyright © 2012 Alcatel-Lucent. + * + * See the NOTICE file distributed with this work for additional + * information regarding copyright ownership. + * Licensed to you 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 com.alu.e3.osgi.manager.api; + +public interface IE3Config { + + public int getSshdPort(); + public int getSmxSshdPort(); + + public String getSmxUser(); + public String getSmxPassword(); + + public void setSshdPort(int sshdPort); + public void setSmxSshdPort(int smxSshdPort); + public void setSmxUser(String smxUser); + public void setSmxPassword(String smxPassword); + +} diff --git a/exposure-engine/system-manager/src/main/resources/META-INF/spring-optional/system-manager.beans.xml b/exposure-engine/system-manager/src/main/resources/META-INF/spring-optional/system-manager.beans.xml new file mode 100644 index 0000000..f7dec61 --- /dev/null +++ b/exposure-engine/system-manager/src/main/resources/META-INF/spring-optional/system-manager.beans.xml @@ -0,0 +1,81 @@ + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + diff --git a/exposure-engine/system-manager/src/main/resources/META-INF/spring-optional/system-manager.topology-watcher.xml b/exposure-engine/system-manager/src/main/resources/META-INF/spring-optional/system-manager.topology-watcher.xml new file mode 100644 index 0000000..550cda8 --- /dev/null +++ b/exposure-engine/system-manager/src/main/resources/META-INF/spring-optional/system-manager.topology-watcher.xml @@ -0,0 +1,41 @@ + + + + + + + + + + + + + + + + + + + + + + + + + + + \ No newline at end of file diff --git a/exposure-engine/system-manager/src/main/resources/system-manager-logging.wadl b/exposure-engine/system-manager/src/main/resources/system-manager-logging.wadl new file mode 100644 index 0000000..6d4db41 --- /dev/null +++ b/exposure-engine/system-manager/src/main/resources/system-manager-logging.wadl @@ -0,0 +1,163 @@ + + + + + + + + REST API to retrieve a specified number of log lines from the active log files. + + + + + + + + + + REST API to retrieve a specified number of log lines from the collected (rotated) logs. + + + + + + + + + REST API to trigger log collection across all instances in the topology. + + + + + + + + + REST API to retrieve the java log level for an instance (1 for localhost, 0 for global). + + + + + + + REST API to set the java log level for an instance (1 for localhost, 0 for global). + + + + + + + + + + + + + + REST API to retrieve the servicemix level for an instance (1 for localhost, 0 for global). + + + + + + + REST API to set the servicemix level for an instance (1 for localhost, 0 for global). + + + + + + + + + + + + + + REST API to retrieve the syslog level for an instance (1 for localhost, 0 for global). + + + + + + + REST API to set the syslog level for an instance (1 for localhost, 0 for global). + + + + + + + + + + + + + REST API to test the LoggingManager by logging a message at each log level. + + + + + + + + REST API to retrieve the global java log level. + + + + + + REST API to set the global java log level. + + + + + + + + + + + + + REST API to retrieve the global servicemix log level. + + + + + + REST API to set the global servicemix log level. + + + + + + + + + + + + + REST API to retrieve the global syslog level. + + + + + + REST API to set the global syslog level. + + + + + + + + + + + + + \ No newline at end of file diff --git a/exposure-engine/system-manager/src/main/resources/system-manager.wadl b/exposure-engine/system-manager/src/main/resources/system-manager.wadl new file mode 100644 index 0000000..b8387cb --- /dev/null +++ b/exposure-engine/system-manager/src/main/resources/system-manager.wadl @@ -0,0 +1,71 @@ + + + + + + + + + + + + + Ask the SystemManager to install E3 on the machines described in the topology configuration file. The path specified should contain the configuration files installer-config.xml and topology.xml. + + + + + + + + + + + + + + + + REST API to retrieve the log level for an instance (1 for localhost, 0 for global). + + + + + REST API to set the log level for an instance (1 for localhost, 0 for global). + + + + + + + + + REST API to retrieve the global log level. + + + + REST API to set the global log level. + + + + + + + + + + + + + + + + REST API to test the LoggingManager by logging a message at each log level. + + + + + + + \ No newline at end of file diff --git a/exposure-engine/system-manager/src/main/resources/system-manager.xsd b/exposure-engine/system-manager/src/main/resources/system-manager.xsd new file mode 100644 index 0000000..104b063 --- /dev/null +++ b/exposure-engine/system-manager/src/main/resources/system-manager.xsd @@ -0,0 +1,119 @@ + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + \ No newline at end of file diff --git a/exposure-engine/system-manager/src/test/java/com/alu/e3/installer/command/LocalCommandTest.java b/exposure-engine/system-manager/src/test/java/com/alu/e3/installer/command/LocalCommandTest.java new file mode 100644 index 0000000..01ecbe8 --- /dev/null +++ b/exposure-engine/system-manager/src/test/java/com/alu/e3/installer/command/LocalCommandTest.java @@ -0,0 +1,64 @@ +/** + * Copyright © 2012 Alcatel-Lucent. + * + * See the NOTICE file distributed with this work for additional + * information regarding copyright ownership. + * Licensed to you 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 com.alu.e3.installer.command; + +import static org.junit.Assert.assertEquals; +import static org.junit.Assert.assertNotNull; +import static org.junit.Assert.assertTrue; + +import java.io.File; + +import org.junit.Before; +import org.junit.Test; + + +public class LocalCommandTest { + + /* members */ + LocalCommand cmd = null; + + @Before + public void setUp() throws Exception { + cmd = new LocalCommand(); + } + + @Test + public void testExecShellCommand() throws Exception { + // Dev environment (under win32) should ignore this test + if (System.getProperty("os.name").toLowerCase().contains("win")) return; + // + assertNotNull(cmd); + ShellCommandResult res = cmd.execShellCommand("echo Test"); + assertEquals(0, res.getExitStatus()); + assertEquals("Test\n", res.getResult()); + } + + @Test + public void testCopy() throws Exception { + assertNotNull(cmd); + + File fTemp = File.createTempFile("test", ".tmp"); + File fTempDest = new File(fTemp.getAbsolutePath()+".bak"); + cmd.copy(fTemp.getAbsolutePath(), fTempDest.getAbsolutePath()); + + assertTrue(fTempDest.exists()); + fTempDest.delete(); + } + +} diff --git a/exposure-engine/system-manager/src/test/java/com/alu/e3/installer/parsers/InstallerConfigurationTest.java b/exposure-engine/system-manager/src/test/java/com/alu/e3/installer/parsers/InstallerConfigurationTest.java new file mode 100644 index 0000000..31256db --- /dev/null +++ b/exposure-engine/system-manager/src/test/java/com/alu/e3/installer/parsers/InstallerConfigurationTest.java @@ -0,0 +1,96 @@ +/** + * Copyright © 2012 Alcatel-Lucent. + * + * See the NOTICE file distributed with this work for additional + * information regarding copyright ownership. + * Licensed to you 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 com.alu.e3.installer.parsers; + +import static org.junit.Assert.assertEquals; +import static org.junit.Assert.assertNotNull; + +import java.net.URL; +import java.util.List; +import java.util.Map; + +import org.junit.Before; +import org.junit.Test; + +import com.alu.e3.installer.model.Configuration; + +/** + * Test for InstallerConfigurationParser. + * + */ +public class InstallerConfigurationTest { + + private static String CONFIG_PATH = "/installer/installer-config.xml"; + + private InstallerConfigurationParser parser; + + @Before + public void setUp() throws Exception { + parser = new InstallerConfigurationParser(); + } + + @Test + public void test() throws InstallerParserException { + URL fileURL = getClass().getResource(CONFIG_PATH); + + Map> configurations = parser.parse(fileURL.getPath()); + + // this configuration file should contain 3 types of machine + assertEquals(3, configurations.size()); + assertNotNull(configurations.get("E3ManagerMaster")); + assertNotNull(configurations.get("E3ManagerSlave")); + assertNotNull(configurations.get("E3Gateway")); + + Configuration cfg = null; + + // E3Manager Master dummy configurations + List e3MgrMstrConfigs = configurations.get("E3ManagerMaster"); + assertEquals(2, e3MgrMstrConfigs.size()); + + cfg = e3MgrMstrConfigs.get(0); + assertNotNull(null, cfg.getName()); + assertEquals("file:///tmp/E3.zip", cfg.getPackageUrl()); + assertEquals("bin/install.sh manager-master", cfg.getInstallerCmd()); + assertEquals("bin/sanitycheck.sh manager", cfg.getSanityCheckCmd()); + + cfg = e3MgrMstrConfigs.get(1); + assertNotNull(null, cfg.getName()); + assertEquals("file:///tmp/E3ManagerAddOn.zip", cfg.getPackageUrl()); + assertEquals("bin/install.sh", cfg.getInstallerCmd()); + assertEquals("bin/sanitycheck.sh", cfg.getSanityCheckCmd()); + + // E3Manager Slave dummy configurations + List e3MgrSlaveConfigs = configurations.get("E3ManagerSlave"); + cfg = e3MgrSlaveConfigs.get(0); + assertNotNull(null, cfg.getName()); + assertEquals("file:///tmp/E3.zip", cfg.getPackageUrl()); + assertEquals("bin/install.sh manager-slave", cfg.getInstallerCmd()); + assertEquals("bin/sanitycheck.sh manager", cfg.getSanityCheckCmd()); + + // E3Gateway dummy configurations + List e3GtwConfigs = configurations.get("E3Gateway"); + cfg = e3GtwConfigs.get(0); + assertNotNull(null, cfg.getName()); + assertEquals("file:///tmp/E3.zip", cfg.getPackageUrl()); + assertEquals("bin/install.sh gateway", cfg.getInstallerCmd()); + assertEquals("bin/sanitycheck.sh gateway", cfg.getSanityCheckCmd()); + + } + +} diff --git a/exposure-engine/system-manager/src/test/resources/installer/installer-config.xml b/exposure-engine/system-manager/src/test/resources/installer/installer-config.xml new file mode 100644 index 0000000..a3fa3cd --- /dev/null +++ b/exposure-engine/system-manager/src/test/resources/installer/installer-config.xml @@ -0,0 +1,38 @@ + + + + + + + + + + + + + + \ No newline at end of file diff --git a/exposure-engine/tdr-lib/pom.xml b/exposure-engine/tdr-lib/pom.xml new file mode 100644 index 0000000..1e903a8 --- /dev/null +++ b/exposure-engine/tdr-lib/pom.xml @@ -0,0 +1,49 @@ + + + 4.0.0 + + + exposure-engine + com.alu.e3 + 1.0.1 + .. + + + tdr-lib + E3 TDR Library + http://www.alcatel-lucent.com + All of the code to support saving TDR data on the exchange as well as two components for generating Tx Ids and writing out the TDRs. + + jar + + + + org.apache.camel + camel-test + 2.0.0 + test + + + log4j + log4j + 1.2.16 + provided + + + com.alu.e3 + gateway-common + ${project.version} + jar + provided + + + com.alu.e3 + common + ${project.version} + jar + provided + + + + \ No newline at end of file diff --git a/exposure-engine/tdr-lib/src/main/java/com/alu/e3/tdr/String2ListConverter.java b/exposure-engine/tdr-lib/src/main/java/com/alu/e3/tdr/String2ListConverter.java new file mode 100644 index 0000000..13b9d4f --- /dev/null +++ b/exposure-engine/tdr-lib/src/main/java/com/alu/e3/tdr/String2ListConverter.java @@ -0,0 +1,42 @@ +/** + * Copyright © 2012 Alcatel-Lucent. + * + * See the NOTICE file distributed with this work for additional + * information regarding copyright ownership. + * Licensed to you 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 com.alu.e3.tdr; + +import java.util.ArrayList; +import java.util.List; + +import org.apache.camel.Converter; + +@Converter +public class String2ListConverter { + /** + * Converts a String to List by spliting the string on ',' + * @param str + * @return + */ + @Converter + public static List toList(String str){ + List result = new ArrayList(); + String[] sArray = str.split(","); + for(String s : sArray){ + result.add(s); + } + return result; + } +} diff --git a/exposure-engine/tdr-lib/src/main/java/com/alu/e3/tdr/TDRComponent.java b/exposure-engine/tdr-lib/src/main/java/com/alu/e3/tdr/TDRComponent.java new file mode 100644 index 0000000..2ce697f --- /dev/null +++ b/exposure-engine/tdr-lib/src/main/java/com/alu/e3/tdr/TDRComponent.java @@ -0,0 +1,44 @@ +/** + * Copyright © 2012 Alcatel-Lucent. + * + * See the NOTICE file distributed with this work for additional + * information regarding copyright ownership. + * Licensed to you 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 com.alu.e3.tdr; + +import java.util.Map; + +import org.apache.camel.CamelContext; +import org.apache.camel.Endpoint; +import org.apache.camel.impl.DefaultComponent; + +public class TDRComponent extends DefaultComponent { + + public TDRComponent(){ + + } + + public TDRComponent(CamelContext context){ + super(context); + } + + @Override + protected Endpoint createEndpoint(String uri, String remaining, Map parameters) throws Exception { + Endpoint endpoint = new TDREndpoint(uri, this); + setProperties(endpoint, parameters); + return endpoint; + } + +} \ No newline at end of file diff --git a/exposure-engine/tdr-lib/src/main/java/com/alu/e3/tdr/TDREndpoint.java b/exposure-engine/tdr-lib/src/main/java/com/alu/e3/tdr/TDREndpoint.java new file mode 100644 index 0000000..9cca29c --- /dev/null +++ b/exposure-engine/tdr-lib/src/main/java/com/alu/e3/tdr/TDREndpoint.java @@ -0,0 +1,73 @@ +/** + * Copyright © 2012 Alcatel-Lucent. + * + * See the NOTICE file distributed with this work for additional + * information regarding copyright ownership. + * Licensed to you 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 com.alu.e3.tdr; + +import java.util.ArrayList; +import java.util.List; + +import org.apache.camel.Component; +import org.apache.camel.Consumer; +import org.apache.camel.Processor; +import org.apache.camel.Producer; +import org.apache.camel.impl.DefaultEndpoint; + +public class TDREndpoint extends DefaultEndpoint { + + private List headers = new ArrayList(); + + public TDREndpoint(String uri, Component component){ + super(uri, component); + } + + @Override + public Producer createProducer() throws Exception { + return new TDRProducer(this); + } + + @Override + public Consumer createConsumer(Processor processor) throws Exception { + throw new UnsupportedOperationException("TDR Endpoint can only be used as a producer"); + } + + @Override + public boolean isSingleton() { + // TODO Auto-generated method stub + return false; + } + + public List getHeaders() { + return headers; + } + + public void setHeaders(List headers) { + this.headers = headers; + } + + /** + * FIXME: Work around made to fix a camel context loading order problem. + * When restarting fuse, TypeConverters are loaded *after* Route contexts. + * The consequences is : on FUSE restart, Routes fails loading due to a 'false' missing type converter. + * + * @param headers + */ + public void setHeaders(String headers) { + this.headers = String2ListConverter.toList(headers); + } + +} diff --git a/exposure-engine/tdr-lib/src/main/java/com/alu/e3/tdr/TDRProducer.java b/exposure-engine/tdr-lib/src/main/java/com/alu/e3/tdr/TDRProducer.java new file mode 100644 index 0000000..d825d0e --- /dev/null +++ b/exposure-engine/tdr-lib/src/main/java/com/alu/e3/tdr/TDRProducer.java @@ -0,0 +1,150 @@ +/** + * Copyright © 2012 Alcatel-Lucent. + * + * See the NOTICE file distributed with this work for additional + * information regarding copyright ownership. + * Licensed to you 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 com.alu.e3.tdr; + +import java.io.StringWriter; +import java.util.Map; +import java.util.Map.Entry; + +import javax.xml.parsers.DocumentBuilder; +import javax.xml.parsers.DocumentBuilderFactory; +import javax.xml.parsers.ParserConfigurationException; +import javax.xml.transform.OutputKeys; +import javax.xml.transform.Result; +import javax.xml.transform.Source; +import javax.xml.transform.Transformer; +import javax.xml.transform.TransformerFactory; +import javax.xml.transform.dom.DOMSource; +import javax.xml.transform.stream.StreamResult; + +import org.apache.camel.Endpoint; +import org.apache.camel.Exchange; +import org.apache.camel.impl.DefaultProducer; +import org.slf4j.Logger; +import org.slf4j.LoggerFactory; +import org.w3c.dom.Document; +import org.w3c.dom.Element; + +public class TDRProducer extends DefaultProducer { + + private static Logger logger = LoggerFactory.getLogger(TDRProducer.class); + private TDREndpoint tdrEndpoint; + + DocumentBuilder docBuilder = null; + + public TDRProducer(Endpoint endpoint) { + super(endpoint); + + if(!(endpoint instanceof TDREndpoint)){ + throw new RuntimeException("Unsupported endpoint type:"+ endpoint.getClass().getName()); + } + + try { + docBuilder = DocumentBuilderFactory.newInstance().newDocumentBuilder(); + } catch (ParserConfigurationException e) { + throw new RuntimeException("DOM Builder error :", e); + } + + // Keep another reference so I don't have to cast everywhere to get the properties out + tdrEndpoint = (TDREndpoint) endpoint; + } + + @Override + public void process(Exchange exchange) throws Exception { + logger.debug("TDR Processor Hit"); + Map tdrProps = TDRDataService.getTxTDRProperties(exchange); + + Document doc = docBuilder.newDocument(); + + //create the root element and add it to the document + Element root = doc.createElement("tdr"); + root.setAttribute("id", exchange.getExchangeId()); + doc.appendChild(root); + + // Add the headers + for(String head : this.tdrEndpoint.getHeaders()){ + Object value = exchange.getIn().getHeader(head); + if(value == null){ + value = "null"; + } + + //create child element, add an attribute, and add to root + Element child = doc.createElement("nvp"); + child.setAttribute("name", head); + child.setAttribute("value", value.toString()); + root.appendChild(child); + } + + // Add the TDR properties that have been added along the way + for(Entry tdrProp : tdrProps.entrySet()){ + //create child element, add an attribute, and add to root + Element child = doc.createElement("nvp"); + child.setAttribute("name", tdrProp.getKey()); + child.setAttribute("value", tdrProp.getValue() == null ? "null" : tdrProp.getValue().toString()); + root.appendChild(child); + } + + TransformerFactory factory = TransformerFactory.newInstance(); + Transformer transformer = factory.newTransformer(); + transformer.setOutputProperty(OutputKeys.OMIT_XML_DECLARATION, "yes"); + StringWriter writer = new StringWriter(); + Result result = new StreamResult(writer); + Source source = new DOMSource(root); + transformer.transform(source, result); + writer.close(); + + String xml = writer.toString(); + //exchange.getIn().setBody(xml); + + exchange.getOut().setBody(xml); + + /* ************************************** + * This version is like a properties file + StringBuilder sb = new StringBuilder(); + + // Add the id + sb.append("txid: "+exchange.getExchangeId()+"\n"); + + // Add the headers + for(String head : this.headersToInclude){ + Object value = exchange.getIn().getHeader(head); + if(value == null){ + value = "null"; + } + sb.append(head+": "+value+"\n"); + } + + // Add the TDR properties that have been added along the way + for(String key : tdrProps.keySet()){ + Object value = tdrProps.get(key); + if(value == null){ + value = "null"; + } + sb.append(key+": "+(value.toString())+"\n"); + } + + exchange.getIn().setBody(sb.toString()); + */ + if(logger.isDebugEnabled()){ + logger.debug("TDR: \n"+xml); + //logger.debug(root.toString()); + } + } + +} diff --git a/exposure-engine/tdr-lib/src/main/java/com/alu/e3/tdr/TdrPreProcessor.java b/exposure-engine/tdr-lib/src/main/java/com/alu/e3/tdr/TdrPreProcessor.java new file mode 100644 index 0000000..b3fe57b --- /dev/null +++ b/exposure-engine/tdr-lib/src/main/java/com/alu/e3/tdr/TdrPreProcessor.java @@ -0,0 +1,34 @@ +/** + * Copyright © 2012 Alcatel-Lucent. + * + * See the NOTICE file distributed with this work for additional + * information regarding copyright ownership. + * Licensed to you 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 com.alu.e3.tdr; + +import org.apache.camel.Exchange; +import org.apache.camel.Processor; + +public class TdrPreProcessor implements Processor{ + + @Override + public void process(Exchange exchange) throws Exception { + + exchange.getIn().setBody(null); + exchange.getOut().setBody(null); + + } + +} diff --git a/exposure-engine/tdr-lib/src/main/java/com/alu/e3/tdr/camel/component/TdrRuleComponent.java b/exposure-engine/tdr-lib/src/main/java/com/alu/e3/tdr/camel/component/TdrRuleComponent.java new file mode 100644 index 0000000..ce198e3 --- /dev/null +++ b/exposure-engine/tdr-lib/src/main/java/com/alu/e3/tdr/camel/component/TdrRuleComponent.java @@ -0,0 +1,54 @@ +/** + * Copyright © 2012 Alcatel-Lucent. + * + * See the NOTICE file distributed with this work for additional + * information regarding copyright ownership. + * Licensed to you 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 com.alu.e3.tdr.camel.component; + +import java.util.Map; + +import org.apache.camel.Endpoint; +import org.apache.camel.impl.DefaultComponent; + +import com.alu.e3.tdr.camel.endpoint.TdrRuleEndpoint; +import com.alu.e3.tdr.service.ITdrQueueService; + +/** + * TDRRuleComponent is used to add extracted tdr data from exchange along a route + * to an internal TDR map. + */ +public class TdrRuleComponent extends DefaultComponent { + + private ITdrQueueService tdrQueueService; + + public TdrRuleComponent() {} + + @Override + protected Endpoint createEndpoint(String uri, String remaining, Map parameters) throws Exception { + TdrRuleEndpoint tdrre = new TdrRuleEndpoint(uri, this, remaining, tdrQueueService); + setProperties(tdrre, parameters); + return tdrre; + } + + public void setTdrQueueService(ITdrQueueService tdrQueueService) { + if(tdrQueueService == null){ + throw new RuntimeException("Cannot initialize TdrRuleComponent, tdrQueueService is null"); + } + + this.tdrQueueService = tdrQueueService; + } + +} diff --git a/exposure-engine/tdr-lib/src/main/java/com/alu/e3/tdr/camel/endpoint/TdrRuleEndpoint.java b/exposure-engine/tdr-lib/src/main/java/com/alu/e3/tdr/camel/endpoint/TdrRuleEndpoint.java new file mode 100644 index 0000000..0145176 --- /dev/null +++ b/exposure-engine/tdr-lib/src/main/java/com/alu/e3/tdr/camel/endpoint/TdrRuleEndpoint.java @@ -0,0 +1,103 @@ +/** + * Copyright © 2012 Alcatel-Lucent. + * + * See the NOTICE file distributed with this work for additional + * information regarding copyright ownership. + * Licensed to you 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 com.alu.e3.tdr.camel.endpoint; + +import org.apache.camel.Component; +import org.apache.camel.Consumer; +import org.apache.camel.Processor; +import org.apache.camel.Producer; +import org.apache.camel.impl.DefaultEndpoint; + +import com.alu.e3.tdr.camel.producer.TdrCommonRuleProducer; +import com.alu.e3.tdr.camel.producer.TdrDynamicRuleProducer; +import com.alu.e3.tdr.camel.producer.TdrEmitProducer; +import com.alu.e3.tdr.camel.producer.TdrStaticRuleProducer; +import com.alu.e3.tdr.service.ITdrQueueService; + +public class TdrRuleEndpoint extends DefaultEndpoint { + + public static enum Type { + COMMON, + STATIC, + DYNAMIC, + EMIT + } + + private Type type; + private String tdrTypeName; + private String propName; + private String staticValue; + private String headerName; + private String txTDRName; + private ITdrQueueService tdrQueueService; + + public TdrRuleEndpoint(String uri, Component component, String type, ITdrQueueService tdrQueueService) { + super(uri, component); + + if (type == null) throw new IllegalArgumentException("TdrRuleEndpoint(type) must not be null"); + if (tdrQueueService == null) throw new IllegalArgumentException("TdrQueueService must not be null"); + this.type = Type.valueOf(type); + + this.tdrQueueService = tdrQueueService; + } + + @Override + public Producer createProducer() throws Exception { + if (Type.COMMON == type) + return new TdrCommonRuleProducer(this, txTDRName); + else if (Type.STATIC == type) + return new TdrStaticRuleProducer(this, propName, staticValue, tdrTypeName); + else if (Type.DYNAMIC == type) + return new TdrDynamicRuleProducer(this, propName, headerName, tdrTypeName); + else if (Type.EMIT == type) + return new TdrEmitProducer(this, tdrQueueService); + else + throw new UnsupportedOperationException("No producer of type: "+type); + } + + @Override + public Consumer createConsumer(Processor processor) throws Exception { + throw new UnsupportedOperationException("TdrRuleComponent does not support instance as consumer"); + } + + @Override + public boolean isSingleton() { + return false; + } + + public void setPropName(String propName) { + this.propName = propName; + } + + public void setStaticValue(String staticValue) { + this.staticValue = staticValue; + } + + public void setHeaderName(String headerName) { + this.headerName = headerName; + } + + public void setTdrTypeName(String tdrTypeName){ + this.tdrTypeName = tdrTypeName; + } + + public void setTxTDRName(String name){ + this.txTDRName = name; + } +} diff --git a/exposure-engine/tdr-lib/src/main/java/com/alu/e3/tdr/camel/producer/TdrCommonRuleProducer.java b/exposure-engine/tdr-lib/src/main/java/com/alu/e3/tdr/camel/producer/TdrCommonRuleProducer.java new file mode 100644 index 0000000..0369077 --- /dev/null +++ b/exposure-engine/tdr-lib/src/main/java/com/alu/e3/tdr/camel/producer/TdrCommonRuleProducer.java @@ -0,0 +1,83 @@ +/** + * Copyright © 2012 Alcatel-Lucent. + * + * See the NOTICE file distributed with this work for additional + * information regarding copyright ownership. + * Licensed to you 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 com.alu.e3.tdr.camel.producer; + +import java.lang.reflect.Method; +import java.net.InetAddress; + +import org.apache.camel.Endpoint; +import org.apache.camel.Exchange; +import org.apache.camel.impl.DefaultProducer; +import org.apache.log4j.Logger; + +import com.alu.e3.tdr.TDRConstant; +import com.alu.e3.tdr.TDRDataService; + +public class TdrCommonRuleProducer extends DefaultProducer { + private static Logger logger = Logger.getLogger(TdrCommonRuleProducer.class); + private static String SYSTEM_ID = ""; + + // The name of the tdr that gets generated on every transaction. Default to txTDR + private String txTDRName = "txTDR"; + + static { + String hostname; + try { + hostname = ":"+InetAddress.getLocalHost().getHostName(); + } catch (Exception e) { + logger.error("Unable to initialize SYSTEM_ID", e); + hostname = ""; + } + SYSTEM_ID = new StringBuilder("E3:GATEWAY").append(hostname).toString(); + } + + + public TdrCommonRuleProducer(Endpoint endpoint, String txTDRName) { + super(endpoint); + this.txTDRName = txTDRName; + } + + @Override + public void process(Exchange exchange) throws Exception { + TDRDataService.setTxTDRName(txTDRName, exchange); + long firstInTimestamp = System.currentTimeMillis(); + TDRDataService.addCommonProperty(exchange, TDRConstant.TIMESTAMP, firstInTimestamp); + TDRDataService.addCommonProperty(exchange, TDRConstant.TRANSACTION, exchange.getExchangeId()); + TDRDataService.addTxTDRProperty(exchange, TDRConstant.HTTP_METHOD, exchange.getIn().getHeader(Exchange.HTTP_METHOD)); + TDRDataService.addTxTDRProperty(exchange, TDRConstant.CLIENT_REQ_TIME, firstInTimestamp); + + /** + * This done to avoid adding a dependency on the servlet spec + */ + try{ + Object request = exchange.getIn().getHeader(Exchange.HTTP_SERVLET_REQUEST); + Method method = request.getClass().getMethod("getRemoteAddr"); + String clientIp = (String) method.invoke(request); + TDRDataService.addCommonProperty(exchange, TDRConstant.CLIENT, clientIp); + } catch(Exception e){ + logger.debug("Could not obtain clientIP"); + } + + String endpoint = exchange.getIn().getHeader(Exchange.HTTP_URL, String.class); + TDRDataService.addTxTDRProperty(exchange, TDRConstant.ENDPOINT, endpoint); + TDRDataService.addTxTDRProperty(exchange, TDRConstant.ENDPOINT_ACTION, exchange.getIn().getHeader(Exchange.HTTP_URI)); + TDRDataService.addCommonProperty(exchange, TDRConstant.SYSTEM, SYSTEM_ID); + } + +} diff --git a/exposure-engine/tdr-lib/src/main/java/com/alu/e3/tdr/camel/producer/TdrDynamicRuleProducer.java b/exposure-engine/tdr-lib/src/main/java/com/alu/e3/tdr/camel/producer/TdrDynamicRuleProducer.java new file mode 100644 index 0000000..fda6a80 --- /dev/null +++ b/exposure-engine/tdr-lib/src/main/java/com/alu/e3/tdr/camel/producer/TdrDynamicRuleProducer.java @@ -0,0 +1,61 @@ +/** + * Copyright © 2012 Alcatel-Lucent. + * + * See the NOTICE file distributed with this work for additional + * information regarding copyright ownership. + * Licensed to you 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 com.alu.e3.tdr.camel.producer; + +import org.apache.camel.Endpoint; +import org.apache.camel.Exchange; +import org.apache.camel.impl.DefaultProducer; + +import com.alu.e3.tdr.TDRDataService; + +public class TdrDynamicRuleProducer extends DefaultProducer { + + private String propName; + private String headerName; + private String tdrTypeName; + + public TdrDynamicRuleProducer(Endpoint endpoint, String propName, String headerName, String tdrTypeName) { + super(endpoint); + + this.propName = propName; + this.headerName = headerName; + this.tdrTypeName = tdrTypeName; + } + + @Override + public void process(Exchange exchange) throws Exception { + String resolvedValue = exchange.getIn().getHeader(headerName, String.class); + + if(resolvedValue == null){ + resolvedValue = exchange.getProperty(headerName, String.class); + } + + if(resolvedValue == null){ + resolvedValue = ""; + } + + if(tdrTypeName == null || tdrTypeName.equals("")){ + TDRDataService.addCommonProperty(exchange, propName, resolvedValue); + } + else{ + TDRDataService.setPropertyForType(tdrTypeName, propName, resolvedValue, exchange); + } + } + +} diff --git a/exposure-engine/tdr-lib/src/main/java/com/alu/e3/tdr/camel/producer/TdrEmitProducer.java b/exposure-engine/tdr-lib/src/main/java/com/alu/e3/tdr/camel/producer/TdrEmitProducer.java new file mode 100644 index 0000000..be0f7dc --- /dev/null +++ b/exposure-engine/tdr-lib/src/main/java/com/alu/e3/tdr/camel/producer/TdrEmitProducer.java @@ -0,0 +1,60 @@ +/** + * Copyright © 2012 Alcatel-Lucent. + * + * See the NOTICE file distributed with this work for additional + * information regarding copyright ownership. + * Licensed to you 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 com.alu.e3.tdr.camel.producer; + +import org.apache.camel.Endpoint; +import org.apache.camel.Exchange; +import org.apache.camel.impl.DefaultProducer; +import org.apache.log4j.Logger; + +import com.alu.e3.tdr.TDRConstant; +import com.alu.e3.tdr.TDRDataService; +import com.alu.e3.tdr.service.ITdrQueueService; + +public class TdrEmitProducer extends DefaultProducer { + + private static Logger logger = Logger.getLogger(TdrEmitProducer.class); + private ITdrQueueService tdrQueueService; + + public TdrEmitProducer(Endpoint endpoint, ITdrQueueService tdrQueueService) { + super(endpoint); + if(tdrQueueService == null){ + throw new RuntimeException("Cannot initialize TdrEmitProducer, TdrQueueService is null"); + } + + this.tdrQueueService = tdrQueueService; + } + + @Override + public void process(Exchange exchange) throws Exception { + try{ + // Add the last timestamp + TDRDataService.addTxTDRProperty(exchange, TDRConstant.CLIENT_RESP_TIME, System.currentTimeMillis()); + + if(TDRDataService.getTxTDRProperty(TDRConstant.EVENT_TYPE, exchange) == null) + TDRDataService.setTxTDRProperty(TDRConstant.EVENT_TYPE, TDRConstant.EVENT_TYPE_INTERNALERROR, exchange); + + // Add the TDRs to the queue to be written to disk + tdrQueueService.putOrWait(TDRDataService.getTdrs(exchange)); + TDRDataService.clean(exchange); + } catch(Exception e){ + logger.error(e.getMessage(), e); + } + } +} diff --git a/exposure-engine/tdr-lib/src/main/java/com/alu/e3/tdr/camel/producer/TdrStaticRuleProducer.java b/exposure-engine/tdr-lib/src/main/java/com/alu/e3/tdr/camel/producer/TdrStaticRuleProducer.java new file mode 100644 index 0000000..a523ce9 --- /dev/null +++ b/exposure-engine/tdr-lib/src/main/java/com/alu/e3/tdr/camel/producer/TdrStaticRuleProducer.java @@ -0,0 +1,50 @@ +/** + * Copyright © 2012 Alcatel-Lucent. + * + * See the NOTICE file distributed with this work for additional + * information regarding copyright ownership. + * Licensed to you 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 com.alu.e3.tdr.camel.producer; + +import org.apache.camel.Endpoint; +import org.apache.camel.Exchange; +import org.apache.camel.impl.DefaultProducer; + +import com.alu.e3.tdr.TDRDataService; + +public class TdrStaticRuleProducer extends DefaultProducer { + + private String propName; + private String staticValue; + private String tdrTypeName; + + public TdrStaticRuleProducer(Endpoint endpoint, String propName, String staticValue, String tdrTypeName) { + super(endpoint); + this.propName = propName; + this.staticValue = staticValue; + this.tdrTypeName = tdrTypeName; + } + + @Override + public void process(Exchange exchange) throws Exception { + if(tdrTypeName == null || tdrTypeName.equals("")){ + TDRDataService.addCommonProperty(exchange, propName, staticValue); + } + else{ + TDRDataService.setPropertyForType(tdrTypeName, propName, staticValue, exchange); + } + } + +} diff --git a/exposure-engine/tdr-lib/src/main/java/com/alu/e3/tdr/rotator/RotatableFileWriterProvider.java b/exposure-engine/tdr-lib/src/main/java/com/alu/e3/tdr/rotator/RotatableFileWriterProvider.java new file mode 100644 index 0000000..3141e75 --- /dev/null +++ b/exposure-engine/tdr-lib/src/main/java/com/alu/e3/tdr/rotator/RotatableFileWriterProvider.java @@ -0,0 +1,70 @@ +/** + * Copyright © 2012 Alcatel-Lucent. + * + * See the NOTICE file distributed with this work for additional + * information regarding copyright ownership. + * Licensed to you 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 com.alu.e3.tdr.rotator; + +import java.io.BufferedWriter; +import java.io.File; +import java.io.FileWriter; +import java.io.IOException; +import java.io.Writer; + +/** + * Extends {@link RotatableWriterProvider} and encapsulates File specific functionality. + * A subclass may extend this to implement specific file names. + * + */ +public class RotatableFileWriterProvider extends RotatableWriterProvider { + + // directory in which the files are to be maintained + private final File dir; + + public RotatableFileWriterProvider(File dir, + long characterCountThreshold, long millisecondsThreshold) { + super(characterCountThreshold, millisecondsThreshold); + this.dir = dir; + } + + /** + * Creates a new file and {@link Writer}. + * + * @return the Writer for the new file + * @throws IOException + */ + public Writer newWriter() throws IOException { + return new BufferedWriter(new FileWriter(new File(dir, getTempFileName()))); + } + + /** + * Renames the current file. + */ + public void rotate() { + synchronized (getSynchroLock()) { + super.rotate(); + new File(dir, getTempFileName()).renameTo(new File(dir, getFileName())); + } + } + + protected String getTempFileName() { + return "temp"; + } + + protected String getFileName() { + return "log." + System.currentTimeMillis() + ".txt"; + } +} diff --git a/exposure-engine/tdr-lib/src/main/java/com/alu/e3/tdr/rotator/RotatableWriter.java b/exposure-engine/tdr-lib/src/main/java/com/alu/e3/tdr/rotator/RotatableWriter.java new file mode 100644 index 0000000..c8d89aa --- /dev/null +++ b/exposure-engine/tdr-lib/src/main/java/com/alu/e3/tdr/rotator/RotatableWriter.java @@ -0,0 +1,192 @@ +/** + * Copyright © 2012 Alcatel-Lucent. + * + * See the NOTICE file distributed with this work for additional + * information regarding copyright ownership. + * Licensed to you 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 com.alu.e3.tdr.rotator; + +import java.io.FilterWriter; +import java.io.IOException; +import java.io.Writer; +import java.util.Timer; +import java.util.TimerTask; + +/** + * A monitored {@link Writer} (character output stream). An associated {@link Rotator} + * is notified when the size or age of this RotatingWriter exceeds a specified threshold. + *

    + * A new RotatingWriter is created for each new log file. + *

    + * Everything is synchronized on a lock object provided by the Rotator. + * + */ +public class RotatableWriter extends FilterWriter { + + public interface Rotator { + public Object getSynchroLock(); + public void rotate(); // invoked when the size or age exceeds a threshold + } + + private final Rotator rotator; + private final long charCountThreshold; + private final long millisecondsThreshold; + + private boolean isClosed = false; + + private int currentCharCount = 0; + private TimerTask timerTask; + + // protects against FilterWriter that may implement write methods in terms of each other + private boolean reentered = false; + + public RotatableWriter(Rotator rotator, Writer writer, + long charCountThreshold, long millisecondsThreshold) { + super(writer); + this.rotator = rotator; + this.charCountThreshold = charCountThreshold; + this.millisecondsThreshold = millisecondsThreshold; + } + + /** + * Writes the specified array of characters to the output stream. + */ + @Override + public void write(char[] cbuf, int off, int len) throws IOException { + synchronized (rotator.getSynchroLock()) { + boolean wasReentered = reentered; + reentered = true; + try { + super.write(cbuf, off, len); + if (!wasReentered) { + countCharactersWritten(len); + } + } finally { + reentered = wasReentered; + } + } + } + + /** + * Writes the specified String to the output stream. + */ + @Override + public void write(String str, int off, int len) throws IOException { + synchronized (rotator.getSynchroLock()) { + boolean wasReentered = reentered; + reentered = true; + try { + super.write(str, off, len); + if (!wasReentered) { + countCharactersWritten(len); + } + } finally { + reentered = wasReentered; + } + } + } + + @Override + public void write(int c) throws IOException { + synchronized (rotator.getSynchroLock()) { + boolean wasReentered = reentered; + reentered = true; + try { + super.write(c); + if (!wasReentered) { + countCharactersWritten(1); + } + } finally { + reentered = wasReentered; + } + } + } + + /** + * Common code that is invoked after characters have been written. + * + * @param len number of characters just written + */ + private void countCharactersWritten(int len) { + if ((currentCharCount == 0) && (len > 0)) { + // first write to a new file: start the timer + startTimer(); + } + currentCharCount += len; + } + + /** + * Closes this output stream, stopping the timer and notifying the Rotator. + *

    + * Note that this implementation may invoke the Rotator's rotate() method, + * which in turn could invoke this close() method. Both methods protect + * themselves against runaway recursion. + */ + @Override + public void close() { + synchronized (rotator.getSynchroLock()) { + if (isClosed) { + return; // once is enough + } + isClosed = true; + rotator.rotate(); // end of the line for this RotatingWriter + stopTimer(); + try { + super.close(); + } catch (Exception e) { + // do nothing + } + } + } + + /** + * Checks the length (number of characters written) of the output stream. + * If it exceeds the threshold, closes the stream, which in turn causes + * the Rotator to be notified. + */ + public void checkLength() { + synchronized (rotator.getSynchroLock()) { + if (currentCharCount >= charCountThreshold) { + close(); + } + } + } + + /** + * Starts the one-shot timer associated with this Writer. When the timer + * expires this Writer will be closed and the Rotator will be notified. + */ + private void startTimer() { + timerTask = new TimerTask() { + @Override + public void run() { + synchronized (rotator.getSynchroLock()) { + close(); // time expired + } + } + }; + new Timer("RotatingWriter", true).schedule(timerTask, millisecondsThreshold); + } + + /** + * Stops (cancels) this timer. + */ + private void stopTimer() { + if (timerTask != null) { + timerTask.cancel(); // stop the timer + timerTask = null; + } + } +} diff --git a/exposure-engine/tdr-lib/src/main/java/com/alu/e3/tdr/rotator/RotatableWriterProvider.java b/exposure-engine/tdr-lib/src/main/java/com/alu/e3/tdr/rotator/RotatableWriterProvider.java new file mode 100644 index 0000000..13a9419 --- /dev/null +++ b/exposure-engine/tdr-lib/src/main/java/com/alu/e3/tdr/rotator/RotatableWriterProvider.java @@ -0,0 +1,129 @@ +/** + * Copyright © 2012 Alcatel-Lucent. + * + * See the NOTICE file distributed with this work for additional + * information regarding copyright ownership. + * Licensed to you 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 com.alu.e3.tdr.rotator; + +import java.io.IOException; +import java.io.Writer; + +/** + * Implements {@link WriterProvider}, providing a {@link Writer} (character output stream) + * associated with a file, which is created and rotated (renamed and replaced with a new one) + * over time. This class also implements RotatingWriter.Rotator, allowing it to be notified + * when it's time to rotate the output file. + *

    + * Note that file specific functionality is encapsulated in the {@link RotatableFileWriterProvider} + * subclass. + * + * @see {@link RotatableWriter} + */ +public abstract class RotatableWriterProvider implements WriterProvider, RotatableWriter.Rotator { + + /** + * Creates a new {@link Writer}, along with an underlying data store (such as a file). + * This method must be provided by a subclass. + * + * @return the Writer for the new file + * @throws IOException + */ + public abstract Writer newWriter() throws IOException; + + // single synchronization lock object used to protect both writing and rotation + private final Object synchroLock = new Object(); + + // the current Writer being used to output characters (changes with each rotate operation) + private RotatableWriter currentWriter = null; + + // number of characters written to this Writer that will trigger a rotate operation + private final long characterCountThreshold; + + // number of milliseconds from initial write to this Writer that will trigger a rotate operation + private final long millisecondsThreshold; + + public RotatableWriterProvider(long characterCountThreshold, long millisecondsThreshold) { + this.characterCountThreshold = characterCountThreshold; + this.millisecondsThreshold = millisecondsThreshold; + } + + /** + * Returns the synchronization lock for this OutputWriterProvider & RotatingWriter.Rotator. + */ + @Override + public Object getSynchroLock() { + return synchroLock; + } + + /** + * Returns the current Writer. + *

    + * Repeated invocations of this method may return the same Writer until such time + * as the Writer gets closed, at which time this method may obtain a new Writer. + *

    + * This implementation makes use of the subclass's newWriter() method to obtain + * a new Writer as needed, wrapping it in a RotatableWriter. + *

    + * This implementation also checks the length (number of characters written so far), + * which may precipitate a rotate operation. + */ + @Override + public Writer getWriter() throws IOException { + synchronized (getSynchroLock()) { + if (currentWriter != null) { + currentWriter.checkLength(); // may precipitate invocation of rotate() + } + if (currentWriter == null) { + // create a new Writer (character output stream) and wrap it + currentWriter = new RotatableWriter(this, newWriter(), + characterCountThreshold, millisecondsThreshold); + openWriter(currentWriter); + } + return currentWriter; + } + } + + @Override + public void stop() { + rotate(); // make sure any pending output/rename is done + } + + /** + * Invoked when the output file needs to be rotated (closed/renamed). A subclass + * should invoke this superclass method first, then do whatever is necessary to + * persist the data that got written by the Writer (such as rename files). + */ + public void rotate() { + synchronized (getSynchroLock()) { + Writer writer = currentWriter; + if (writer != null) { + currentWriter = null; + try { + closeWriter(writer); + writer.close(); // may already be closed, but let's be sure + } catch (IOException e) { + // do nothing + } + } + } + } + + protected void openWriter(Writer writer) throws IOException { + } + + protected void closeWriter(Writer writer) throws IOException { + } +} diff --git a/exposure-engine/tdr-lib/src/main/java/com/alu/e3/tdr/rotator/WriterProvider.java b/exposure-engine/tdr-lib/src/main/java/com/alu/e3/tdr/rotator/WriterProvider.java new file mode 100644 index 0000000..bae2e1c --- /dev/null +++ b/exposure-engine/tdr-lib/src/main/java/com/alu/e3/tdr/rotator/WriterProvider.java @@ -0,0 +1,49 @@ +/** + * Copyright © 2012 Alcatel-Lucent. + * + * See the NOTICE file distributed with this work for additional + * information regarding copyright ownership. + * Licensed to you 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 com.alu.e3.tdr.rotator; + +import java.io.IOException; +import java.io.Writer; + +/** + * Provides a {@link Writer} (character output stream), which may change over time. + * + */ +public interface WriterProvider { + + /** + * Returns the synchronization lock for this OutputWriterProvider. + * + * @return the synchronization lock + */ + public Object getSynchroLock(); + + /** + * Returns the current Writer (character output stream). + * + * @return the current Writer + * @throws IOException + */ + public Writer getWriter() throws IOException; + + /** + * Flushes any pending output. + */ + public void stop(); +} diff --git a/exposure-engine/tdr-lib/src/main/java/com/alu/e3/tdr/rotator/XmlStreamWriter.java b/exposure-engine/tdr-lib/src/main/java/com/alu/e3/tdr/rotator/XmlStreamWriter.java new file mode 100644 index 0000000..708729f --- /dev/null +++ b/exposure-engine/tdr-lib/src/main/java/com/alu/e3/tdr/rotator/XmlStreamWriter.java @@ -0,0 +1,100 @@ +/** + * Copyright © 2012 Alcatel-Lucent. + * + * See the NOTICE file distributed with this work for additional + * information regarding copyright ownership. + * Licensed to you 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 com.alu.e3.tdr.rotator; + +import java.io.IOException; +import java.io.Writer; + +import javax.xml.parsers.DocumentBuilder; +import javax.xml.parsers.DocumentBuilderFactory; +import javax.xml.parsers.ParserConfigurationException; +import javax.xml.transform.OutputKeys; +import javax.xml.transform.Result; +import javax.xml.transform.Source; +import javax.xml.transform.Transformer; +import javax.xml.transform.TransformerConfigurationException; +import javax.xml.transform.TransformerException; +import javax.xml.transform.TransformerFactory; +import javax.xml.transform.dom.DOMSource; +import javax.xml.transform.stream.StreamResult; + +import org.w3c.dom.Element; + +/** + * Writes arbitrary XML to a {@link Writer} (a character stream), which is obtained + * from a {@link WriterProvider}. + * + */ +public class XmlStreamWriter { + + private final DocumentBuilder docBuilder; + + // source of the current Writer + private final WriterProvider outputWriterProvider; + + public XmlStreamWriter(WriterProvider outputWriterProvider) { + this.outputWriterProvider = outputWriterProvider; + try { + docBuilder = DocumentBuilderFactory.newInstance().newDocumentBuilder(); + } catch (ParserConfigurationException e) { + throw new RuntimeException("DOM Builder error: ", e); + } + } + + public DocumentBuilder getDocBuilder() { + return docBuilder; + } + + /** + * Writes the specified DOM tree in XML format to the current character output stream. + * + * @param root top of the DOM tree to be written + * @throws TransformerException + * @throws IOException + */ + public void writeXml(Element root) throws TransformerException, IOException { + Transformer transformer = getTransformer(); + Source source = new DOMSource(root); + synchronized (outputWriterProvider.getSynchroLock()) { // ensure atomicity of the entire DOM write + Writer outputWriter = outputWriterProvider.getWriter(); // get current output stream + Result result = new StreamResult(outputWriter); + transformer.transform(source, result); // write out the XML + } + } + + public void stop() { + synchronized (outputWriterProvider.getSynchroLock()) { + outputWriterProvider.stop(); + } + } + + /** + * Returns the {@link Transformer}. May be overridden if necessary. + * + * @return the Transformer + * @throws TransformerConfigurationException + */ + protected Transformer getTransformer() throws TransformerConfigurationException { + TransformerFactory factory = TransformerFactory.newInstance(); + Transformer transformer = factory.newTransformer(); + transformer.setOutputProperty(OutputKeys.OMIT_XML_DECLARATION, "yes"); + transformer.setOutputProperty(OutputKeys.INDENT, "yes"); + return transformer; + } +} diff --git a/exposure-engine/tdr-lib/src/main/java/com/alu/e3/tdr/service/ITdrQueueService.java b/exposure-engine/tdr-lib/src/main/java/com/alu/e3/tdr/service/ITdrQueueService.java new file mode 100644 index 0000000..2f921a5 --- /dev/null +++ b/exposure-engine/tdr-lib/src/main/java/com/alu/e3/tdr/service/ITdrQueueService.java @@ -0,0 +1,36 @@ +/** + * Copyright © 2012 Alcatel-Lucent. + * + * See the NOTICE file distributed with this work for additional + * information regarding copyright ownership. + * Licensed to you 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 com.alu.e3.tdr.service; + +import java.util.List; +import java.util.Map; + +public interface ITdrQueueService { + + int getQueueSize(); + + public void putOrWait(Map>> elem) + throws InterruptedException; + + public Map>> getOrWait() + throws InterruptedException; + + public List>>> getMultiple(int size) + throws InterruptedException; +} \ No newline at end of file diff --git a/exposure-engine/tdr-lib/src/main/java/com/alu/e3/tdr/service/impl/TdrQueueService.java b/exposure-engine/tdr-lib/src/main/java/com/alu/e3/tdr/service/impl/TdrQueueService.java new file mode 100644 index 0000000..a6117f9 --- /dev/null +++ b/exposure-engine/tdr-lib/src/main/java/com/alu/e3/tdr/service/impl/TdrQueueService.java @@ -0,0 +1,96 @@ +/** + * Copyright © 2012 Alcatel-Lucent. + * + * See the NOTICE file distributed with this work for additional + * information regarding copyright ownership. + * Licensed to you 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 com.alu.e3.tdr.service.impl; + +import java.util.LinkedList; +import java.util.List; +import java.util.Map; +import java.util.concurrent.LinkedBlockingQueue; + +import com.alu.e3.tdr.service.ITdrQueueService; + +public class TdrQueueService implements ITdrQueueService { + + private LinkedBlockingQueue>>> queue; + + private int queueWaitingSize = 2000; // Only default + + public void setQueueWaitingSize(int size) { + this.queueWaitingSize = size; + init(); + } + + private void init() { + LinkedBlockingQueue>>> lastQueue = null; + + if (queue != null) + lastQueue = queue; + + queue = new LinkedBlockingQueue>>>( + queueWaitingSize); + // A consumer may still have a take in progress on lastQueue + // but at this point queue is now the queue where future lock will + // happen + + if (lastQueue != null) { + // Transfer queue contents + List>>> toTransfer = new LinkedList>>>(); + // Safe drainTo, 'cause queue reference has changed + + do { + lastQueue.drainTo(toTransfer); + // Safe addAll, 'cause toTransfer will not be modified during + // the call + queue.addAll(toTransfer); + // Notify possibly offerer + toTransfer.clear(); + // TODO: Check the good existing of this loop, and the + // concurrent-ness between + // queue.addAll and putOrWait of offerers. + } while (!lastQueue.isEmpty()); + + lastQueue.clear(); + } + } + + @Override + public void putOrWait(Map>> elem) + throws InterruptedException { + queue.put(elem); + } + + @Override + public Map>> getOrWait() + throws InterruptedException { + return queue.take(); + } + + @Override + public int getQueueSize() { + return queue.size(); + } + + @Override + public List>>> getMultiple(int capacity) + throws InterruptedException { + List>>> dataPack = new LinkedList>>>(); + queue.drainTo(dataPack, capacity); + return dataPack; + } +} \ No newline at end of file diff --git a/exposure-engine/tdr-lib/src/main/java/com/alu/e3/tdr/service/impl/TdrStreamWriter.java b/exposure-engine/tdr-lib/src/main/java/com/alu/e3/tdr/service/impl/TdrStreamWriter.java new file mode 100644 index 0000000..09db92e --- /dev/null +++ b/exposure-engine/tdr-lib/src/main/java/com/alu/e3/tdr/service/impl/TdrStreamWriter.java @@ -0,0 +1,99 @@ +/** + * Copyright © 2012 Alcatel-Lucent. + * + * See the NOTICE file distributed with this work for additional + * information regarding copyright ownership. + * Licensed to you 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 com.alu.e3.tdr.service.impl; + +import java.io.File; +import java.io.IOException; +import java.io.Writer; +import java.util.List; +import java.util.Map; +import java.util.Map.Entry; + +import javax.xml.transform.TransformerException; + +import org.w3c.dom.Document; +import org.w3c.dom.Element; + +import com.alu.e3.tdr.rotator.RotatableFileWriterProvider; +import com.alu.e3.tdr.rotator.RotatableWriterProvider; +import com.alu.e3.tdr.rotator.WriterProvider; +import com.alu.e3.tdr.rotator.XmlStreamWriter; + +/** + * Writes out TDRs in XML format. + *

    + * This class encapsulates TDR specific functionality. The XmlStreamWriter superclass + * (TDR independent) takes care of writing out the XML. + * + * @see {@link XmlStreamWriter} and {@link RotatableWriterProvider} + */ +public class TdrStreamWriter extends XmlStreamWriter { + + private static final int TDR_FILE_SIZE = 10 * 1024 * 1024; // TDR file size rotation trigger + private static final int TDR_FILE_AGE = 30 * 1000; // TDR file age rotation trigger + + public TdrStreamWriter(File dir) { + this(new RotatableFileWriterProvider(dir, TDR_FILE_SIZE, TDR_FILE_AGE) { + @Override + protected String getFileName() { + return "tdrs." + System.currentTimeMillis() + ".xml"; // TDR file name + } + + @Override + protected void openWriter(Writer writer) throws IOException { + writer.append("\n"); + } + + @Override + protected void closeWriter(Writer writer) throws IOException { + writer.append("\n"); + } + }); + } + + public TdrStreamWriter(WriterProvider outputWriterProvider) { + super(outputWriterProvider); + } + + public void writeTdrs(List> tdrDatas) throws TransformerException, IOException { + Document doc = getDocBuilder().newDocument(); + for (Map tdrProps : tdrDatas) { + writeXml(writerBulkTdrXml(doc, tdrProps)); + } + } + + private Element writerBulkTdrXml(Document doc, Map tdrProps) + throws TransformerException, IOException { + // create a root element and fill it up + Element tdrElem = doc.createElement("TDR"); + + if (tdrProps != null) { + // Add the TDR properties that have been added along the way + + for (Entry entry : tdrProps.entrySet()) { + // create child element, add an attribute, and add to root + Element child = doc.createElement(entry.getKey()); + child.setTextContent(entry.getValue() == null ? "null" : entry.getValue().toString()); + tdrElem.appendChild(child); + } + } + + return tdrElem; + } +} diff --git a/exposure-engine/tdr-lib/src/main/java/com/alu/e3/tdr/service/impl/TdrXMLWriter.java b/exposure-engine/tdr-lib/src/main/java/com/alu/e3/tdr/service/impl/TdrXMLWriter.java new file mode 100644 index 0000000..e2724d1 --- /dev/null +++ b/exposure-engine/tdr-lib/src/main/java/com/alu/e3/tdr/service/impl/TdrXMLWriter.java @@ -0,0 +1,157 @@ +/** + * Copyright © 2012 Alcatel-Lucent. + * + * See the NOTICE file distributed with this work for additional + * information regarding copyright ownership. + * Licensed to you 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 com.alu.e3.tdr.service.impl; + +import java.io.File; +import java.io.IOException; +import java.util.HashMap; +import java.util.List; +import java.util.Map; +import java.util.Map.Entry; +import java.util.TimerTask; + +import javax.xml.transform.TransformerException; + +import org.slf4j.Logger; +import org.slf4j.LoggerFactory; +import org.springframework.jmx.export.annotation.ManagedAttribute; +import org.springframework.jmx.export.annotation.ManagedOperation; + +import com.alu.e3.common.E3Constant; +import com.alu.e3.tdr.service.ITdrQueueService; + +public class TdrXMLWriter extends TimerTask { + + private static final Logger logger = LoggerFactory.getLogger(TdrXMLWriter.class); + + private static int INSTANCE_INDEX = 0; + + private static final Map tdrTypeNameToTdrStreamWriter = new HashMap(); + + private ITdrQueueService tdrQueueService; + + private boolean alive = true; + + private int bulkWriteSize = 500; + + private File outputDirectory; + + private TdrStreamWriter tdrStreamWriter; + + private int instanceIndex; + + public TdrXMLWriter() {} + + public void init() { + outputDirectory.mkdirs(); + } + + + public void setTdrQueueService(ITdrQueueService tdrQueueService) { + this.tdrQueueService = tdrQueueService; + } + + @ManagedAttribute + public int getBulkWriteSize() { + return bulkWriteSize; + } + + public void setBulkWriteSize(int bulkWriteSize) { + this.bulkWriteSize = bulkWriteSize; + } + + public void setOutputDirectory(String outputDirectory) { + setOutputDirectory(new File(outputDirectory)); + } + + public void setOutputDirectory(File outputDirectory) { + this.outputDirectory = outputDirectory; + } + + @ManagedOperation + public void kill() { + alive = false; + } + + + @Override + public void run() { + instanceIndex = INSTANCE_INDEX++; + logger.debug("TdrXMLWriter instance:"+instanceIndex+" Starting ..."); + processTdrQueue(); + } + + private void processTdrQueue() { + while (alive) { + try { + Map>> tdrData = tdrQueueService.getOrWait(); + writeTdrData(tdrData); + } catch (InterruptedException e) { + // ignore this + } + } + tdrStreamWriter.stop(); + } + + private void writeTdrData(Map>> tdrData) { + for (Entry>> entry : tdrData.entrySet()) { + try { + logger.debug("Writing TDR: " + entry.getKey()); + getTdrStreamWriter(entry.getKey()).writeTdrs(entry.getValue()); + } catch (TransformerException e) { + logger.error(e.getMessage(), e); + } catch (IOException e) { + logger.error(e.getMessage(), e); + } + } + } + + private TdrStreamWriter getTdrStreamWriter(String tdrTypeName) { + synchronized (tdrTypeNameToTdrStreamWriter) { + TdrStreamWriter tdrStreamWriter = tdrTypeNameToTdrStreamWriter.get(tdrTypeName); + if (tdrStreamWriter == null) { + tdrStreamWriter = newTdrStreamWriter(tdrTypeName); + tdrTypeNameToTdrStreamWriter.put(tdrTypeName, tdrStreamWriter); + } + return tdrStreamWriter; + } + } + + private static TdrStreamWriter newTdrStreamWriter(String subdirectoryName) { + File dir = new File(E3Constant.TDR_BASE_PATH, subdirectoryName); + dir.mkdirs(); + logger.debug("Creating new TDR writer: " + dir.getPath()); + return new TdrStreamWriter(dir); + } + + /** + * General Setters + */ + public void setAlive(boolean alive) { + this.alive = alive; + } + + public void setTdrStreamWriter(TdrStreamWriter tdrStreamWriter) { + this.tdrStreamWriter = tdrStreamWriter; + } + + public void setInstanceIndex(int instanceIndex) { + this.instanceIndex = instanceIndex; + } +} diff --git a/exposure-engine/tdr-lib/src/main/resources/META-INF/services/README b/exposure-engine/tdr-lib/src/main/resources/META-INF/services/README new file mode 100644 index 0000000..7992ae1 --- /dev/null +++ b/exposure-engine/tdr-lib/src/main/resources/META-INF/services/README @@ -0,0 +1,6 @@ +The following files are automatically loaded by FUSE ESB to contribute with new embedded component. + +'tdr' file declares a new endpoint uri scheme to be used in route xmls like : + + +It refers the implementation TDRComponent class. \ No newline at end of file diff --git a/exposure-engine/tdr-lib/src/main/resources/META-INF/services/org/apache/camel/TypeConverter b/exposure-engine/tdr-lib/src/main/resources/META-INF/services/org/apache/camel/TypeConverter new file mode 100644 index 0000000..bfedd20 --- /dev/null +++ b/exposure-engine/tdr-lib/src/main/resources/META-INF/services/org/apache/camel/TypeConverter @@ -0,0 +1 @@ +com.alu.e3.tdr \ No newline at end of file diff --git a/exposure-engine/tdr-lib/src/main/resources/META-INF/services/org/apache/camel/component/tdr b/exposure-engine/tdr-lib/src/main/resources/META-INF/services/org/apache/camel/component/tdr new file mode 100644 index 0000000..4fa9012 --- /dev/null +++ b/exposure-engine/tdr-lib/src/main/resources/META-INF/services/org/apache/camel/component/tdr @@ -0,0 +1 @@ +class=com.alu.e3.tdr.TDRComponent \ No newline at end of file diff --git a/exposure-engine/tdr-lib/src/main/resources/META-INF/services/org/apache/camel/component/tdrRule b/exposure-engine/tdr-lib/src/main/resources/META-INF/services/org/apache/camel/component/tdrRule new file mode 100644 index 0000000..aaa668a --- /dev/null +++ b/exposure-engine/tdr-lib/src/main/resources/META-INF/services/org/apache/camel/component/tdrRule @@ -0,0 +1 @@ +class=com.alu.e3.tdr.camel.component.TdrRuleComponent \ No newline at end of file diff --git a/exposure-engine/tdr-lib/src/main/resources/META-INF/spring-optional/tdr.osgi-context.xml b/exposure-engine/tdr-lib/src/main/resources/META-INF/spring-optional/tdr.osgi-context.xml new file mode 100644 index 0000000..f53886e --- /dev/null +++ b/exposure-engine/tdr-lib/src/main/resources/META-INF/spring-optional/tdr.osgi-context.xml @@ -0,0 +1,24 @@ + + + + + + + + + + + + + + + + diff --git a/exposure-engine/tdr-lib/src/main/resources/META-INF/spring-optional/tdr.tdr-writer-context.xml b/exposure-engine/tdr-lib/src/main/resources/META-INF/spring-optional/tdr.tdr-writer-context.xml new file mode 100644 index 0000000..1922ccc --- /dev/null +++ b/exposure-engine/tdr-lib/src/main/resources/META-INF/spring-optional/tdr.tdr-writer-context.xml @@ -0,0 +1,29 @@ + + + + + + + + + + + + + + + + + + + + + + + + + + \ No newline at end of file diff --git a/exposure-engine/tdr-lib/src/main/resources/limit_tdr_schema.xsd b/exposure-engine/tdr-lib/src/main/resources/limit_tdr_schema.xsd new file mode 100644 index 0000000..dcffcd2 --- /dev/null +++ b/exposure-engine/tdr-lib/src/main/resources/limit_tdr_schema.xsd @@ -0,0 +1,40 @@ + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + \ No newline at end of file diff --git a/exposure-engine/tdr-lib/src/main/resources/log4j.properties b/exposure-engine/tdr-lib/src/main/resources/log4j.properties new file mode 100644 index 0000000..2fcb7bc --- /dev/null +++ b/exposure-engine/tdr-lib/src/main/resources/log4j.properties @@ -0,0 +1,7 @@ +log4j.rootLogger=ERROR, CA +log4j.logger.org.apache.camel=ERROR +log4j.logger.org.eclipse.jetty=ERROR +log4j.logger.com.alu=DEBUG +log4j.appender.CA=org.apache.log4j.ConsoleAppender +log4j.appender.CA.layout=org.apache.log4j.PatternLayout +log4j.appender.CA.layout.ConversionPattern=%-4r [%t] %-5p %c %x - %m%n \ No newline at end of file diff --git a/exposure-engine/tdr-lib/src/main/resources/tx_tdr_schema.xsd b/exposure-engine/tdr-lib/src/main/resources/tx_tdr_schema.xsd new file mode 100644 index 0000000..e29277f --- /dev/null +++ b/exposure-engine/tdr-lib/src/main/resources/tx_tdr_schema.xsd @@ -0,0 +1,50 @@ + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + \ No newline at end of file diff --git a/exposure-engine/tdr-lib/src/test/java/com/alu/e3/tdr/MockExchange.java b/exposure-engine/tdr-lib/src/test/java/com/alu/e3/tdr/MockExchange.java new file mode 100644 index 0000000..bc2bb1b --- /dev/null +++ b/exposure-engine/tdr-lib/src/test/java/com/alu/e3/tdr/MockExchange.java @@ -0,0 +1,234 @@ +/** + * Copyright © 2012 Alcatel-Lucent. + * + * See the NOTICE file distributed with this work for additional + * information regarding copyright ownership. + * Licensed to you 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 com.alu.e3.tdr; + +import java.util.HashMap; +import java.util.List; +import java.util.Map; + +import org.apache.camel.CamelContext; +import org.apache.camel.Endpoint; +import org.apache.camel.Exchange; +import org.apache.camel.ExchangePattern; +import org.apache.camel.Message; +import org.apache.camel.spi.Synchronization; +import org.apache.camel.spi.UnitOfWork; + +/** + * Built to support the properties management stuff to test the TDRDataService + * + */ +public class MockExchange implements Exchange { + private Map properties = new HashMap(); + + public ExchangePattern getPattern() { + // TODO Auto-generated method stub + return null; + } + + public void setPattern(ExchangePattern pattern) { + // TODO Auto-generated method stub + + } + + public Object getProperty(String name) { + return properties.get(name); + } + + public Object getProperty(String name, Object defaultValue) { + // TODO Auto-generated method stub + return null; + } + + public T getProperty(String name, Class type) { + // TODO Auto-generated method stub + return null; + } + + public T getProperty(String name, Object defaultValue, Class type) { + // TODO Auto-generated method stub + return null; + } + + public void setProperty(String name, Object value) { + properties.put(name, value); + } + + public Object removeProperty(String name) { + // TODO Auto-generated method stub + return null; + } + + public Map getProperties() { + return properties; + } + + public boolean hasProperties() { + // TODO Auto-generated method stub + return false; + } + + public Message getIn() { + // TODO Auto-generated method stub + return null; + } + + public T getIn(Class type) { + // TODO Auto-generated method stub + return null; + } + + public void setIn(Message in) { + // TODO Auto-generated method stub + + } + + public Message getOut() { + // TODO Auto-generated method stub + return null; + } + + public T getOut(Class type) { + // TODO Auto-generated method stub + return null; + } + + public boolean hasOut() { + // TODO Auto-generated method stub + return false; + } + + public void setOut(Message out) { + // TODO Auto-generated method stub + + } + + public Exception getException() { + // TODO Auto-generated method stub + return null; + } + + public T getException(Class type) { + // TODO Auto-generated method stub + return null; + } + + + public void setException(Throwable t) { + // TODO Auto-generated method stub + + } + + + public boolean isFailed() { + // TODO Auto-generated method stub + return false; + } + + + public boolean isTransacted() { + // TODO Auto-generated method stub + return false; + } + + + public boolean isRollbackOnly() { + // TODO Auto-generated method stub + return false; + } + + + public CamelContext getContext() { + // TODO Auto-generated method stub + return null; + } + + + public Exchange copy() { + // TODO Auto-generated method stub + return null; + } + + + public Endpoint getFromEndpoint() { + // TODO Auto-generated method stub + return null; + } + + + public void setFromEndpoint(Endpoint fromEndpoint) { + // TODO Auto-generated method stub + + } + + + public String getFromRouteId() { + // TODO Auto-generated method stub + return null; + } + + + public void setFromRouteId(String fromRouteId) { + // TODO Auto-generated method stub + + } + + + public UnitOfWork getUnitOfWork() { + // TODO Auto-generated method stub + return null; + } + + + public void setUnitOfWork(UnitOfWork unitOfWork) { + // TODO Auto-generated method stub + + } + + + public String getExchangeId() { + // TODO Auto-generated method stub + return null; + } + + + public void setExchangeId(String id) { + // TODO Auto-generated method stub + + } + + + public void addOnCompletion(Synchronization onCompletion) { + // TODO Auto-generated method stub + + } + + + public void handoverCompletions(Exchange target) { + // TODO Auto-generated method stub + + } + + + public List handoverCompletions() { + // TODO Auto-generated method stub + return null; + } + +} diff --git a/exposure-engine/tdr-lib/src/test/java/com/alu/e3/tdr/PostProxyProcessor.java b/exposure-engine/tdr-lib/src/test/java/com/alu/e3/tdr/PostProxyProcessor.java new file mode 100644 index 0000000..9be4360 --- /dev/null +++ b/exposure-engine/tdr-lib/src/test/java/com/alu/e3/tdr/PostProxyProcessor.java @@ -0,0 +1,36 @@ +/** + * Copyright © 2012 Alcatel-Lucent. + * + * See the NOTICE file distributed with this work for additional + * information regarding copyright ownership. + * Licensed to you 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 com.alu.e3.tdr; + +import org.apache.camel.Exchange; +import org.apache.camel.Processor; +import org.apache.camel.util.ObjectHelper; + +public class PostProxyProcessor implements Processor { + + @Override + public void process(Exchange exchange) throws Exception { + String body = exchange.getIn().getBody(String.class); + String reply = ObjectHelper.after(body, "STATUS="); + exchange.getIn().setBody(reply); + TDRDataService.setTxTDRProperty("replyStatus", reply, exchange); + TDRDataService.setTxTDRProperty("A-NULL-VALUE", null, exchange); + } + +} diff --git a/exposure-engine/tdr-lib/src/test/java/com/alu/e3/tdr/PreProxyProcessor.java b/exposure-engine/tdr-lib/src/test/java/com/alu/e3/tdr/PreProxyProcessor.java new file mode 100644 index 0000000..c1203b3 --- /dev/null +++ b/exposure-engine/tdr-lib/src/test/java/com/alu/e3/tdr/PreProxyProcessor.java @@ -0,0 +1,36 @@ +/** + * Copyright © 2012 Alcatel-Lucent. + * + * See the NOTICE file distributed with this work for additional + * information regarding copyright ownership. + * Licensed to you 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 com.alu.e3.tdr; + +import org.apache.camel.Exchange; +import org.apache.camel.Processor; + +public class PreProxyProcessor implements Processor { + + @Override + public void process(Exchange exchange) throws Exception { + //String id = exchange.getIn().getHeader("id", String.class); + + // Store the exchangeId at the beginning so we can compare at the end to make sure it + // is persistant + exchange.getIn().setBody("ID=123"); + TDRDataService.setTxTDRProperty("paramId", "123", exchange); + } + +} diff --git a/exposure-engine/tdr-lib/src/test/java/com/alu/e3/tdr/TDRDataServiceTest.java b/exposure-engine/tdr-lib/src/test/java/com/alu/e3/tdr/TDRDataServiceTest.java new file mode 100644 index 0000000..6b21bdd --- /dev/null +++ b/exposure-engine/tdr-lib/src/test/java/com/alu/e3/tdr/TDRDataServiceTest.java @@ -0,0 +1,83 @@ +/** + * Copyright © 2012 Alcatel-Lucent. + * + * See the NOTICE file distributed with this work for additional + * information regarding copyright ownership. + * Licensed to you 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 com.alu.e3.tdr; + +import static org.junit.Assert.assertEquals; +import static org.junit.Assert.assertNotNull; +import static org.junit.Assert.assertTrue; + +import java.util.Map; + +import org.apache.camel.Exchange; +import org.junit.Test; + +public class TDRDataServiceTest { + + @Test + public void test() { + Exchange exchange = new MockExchange(); + + // Make sure that it starts empty + Map tdrProperties = TDRDataService.getTxTDRProperties(exchange); + assertTrue(tdrProperties==null || tdrProperties.size()==0); + + // Add something... + String key1 = "hello"; + String value1 = "world"; + TDRDataService.setTxTDRProperty(key1, value1, exchange); + // Make sure that our tdr props is now size 1 and has our new property + tdrProperties = TDRDataService.getTxTDRProperties(exchange); + assertEquals(1, tdrProperties.size()); + assertNotNull(TDRDataService.getTxTDRProperty(key1, exchange)); + assertNotNull(tdrProperties.get(key1)); + assertEquals(value1, TDRDataService.getTxTDRProperty(key1, exchange)); + assertEquals(value1, tdrProperties.get(key1)); + + // Add another one + String key2 = "foo"; + String value2 = "bar"; + TDRDataService.setTxTDRProperty(key2, value2, exchange); + // Make sure that our tdr props is now size 2 and has our new property + tdrProperties = TDRDataService.getTxTDRProperties(exchange); + assertEquals(2, tdrProperties.size()); + assertNotNull(TDRDataService.getTxTDRProperty(key2, exchange)); + assertNotNull(tdrProperties.get(key2)); + assertEquals(value2, TDRDataService.getTxTDRProperty(key2, exchange)); + assertEquals(value2, tdrProperties.get(key2)); + + // Make sure we can still get the first one + assertNotNull(TDRDataService.getTxTDRProperty(key1, exchange)); + assertNotNull(tdrProperties.get(key1)); + assertEquals(value1, TDRDataService.getTxTDRProperty(key1, exchange)); + assertEquals(value1, tdrProperties.get(key1)); + + // Overwrite value 1 with value 3 and make sure we still only have 2 + String value3 = "hoot"; + TDRDataService.setTxTDRProperty(key1, value3, exchange); + // Make sure that our tdr props is now size 2 and has our new property + tdrProperties = TDRDataService.getTxTDRProperties(exchange); + assertEquals(2, tdrProperties.size()); + assertNotNull(TDRDataService.getTxTDRProperty(key1, exchange)); + assertNotNull(tdrProperties.get(key1)); + assertEquals(value3, TDRDataService.getTxTDRProperty(key1, exchange)); + assertEquals(value3, tdrProperties.get(key1)); + + } + +} diff --git a/exposure-engine/tdr-lib/src/test/java/com/alu/e3/tdr/camel/TdrRuleTest.java b/exposure-engine/tdr-lib/src/test/java/com/alu/e3/tdr/camel/TdrRuleTest.java new file mode 100644 index 0000000..f4102af --- /dev/null +++ b/exposure-engine/tdr-lib/src/test/java/com/alu/e3/tdr/camel/TdrRuleTest.java @@ -0,0 +1,501 @@ +/** + * Copyright © 2012 Alcatel-Lucent. + * + * See the NOTICE file distributed with this work for additional + * information regarding copyright ownership. + * Licensed to you 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 com.alu.e3.tdr.camel; + +import static org.junit.Assert.assertEquals; +import static org.junit.Assert.assertNotNull; +import static org.junit.Assert.assertNotSame; +import static org.junit.Assert.assertTrue; + +import java.util.List; +import java.util.Map; + +import org.apache.camel.CamelContext; +import org.apache.camel.Exchange; +import org.apache.camel.ProducerTemplate; +import org.apache.camel.component.mock.MockEndpoint; +import org.apache.camel.impl.DefaultExchange; +import org.junit.Test; +import org.junit.runner.RunWith; +import org.springframework.beans.factory.annotation.Autowired; +import org.springframework.beans.factory.annotation.Qualifier; +import org.springframework.test.context.ContextConfiguration; +import org.springframework.test.context.junit4.SpringJUnit4ClassRunner; + +import com.alu.e3.tdr.TDRDataService; +import com.alu.e3.tdr.service.ITdrQueueService; +import com.alu.e3.tdr.service.impl.TdrQueueService; + +@RunWith(SpringJUnit4ClassRunner.class) +@ContextConfiguration(locations = { + "classpath:tdr.osgi-context-test.xml" +}) +public class TdrRuleTest { + + @Autowired + @Qualifier("tdrRuleContext") + CamelContext camelContext; + + @Autowired + ITdrQueueService tdrQueueService; + + + @Test + public void enableTestEnvironment() throws Exception { + MockEndpoint.assertIsSatisfied(camelContext); + } + + @Test + public void staticRuleTest() throws InterruptedException { + ProducerTemplate producer; + MockEndpoint mockEndpoint; + Exchange exchange; + Exchange receivedExchange; + Map tdrProperties; + + // + // Test route 1 + producer = camelContext.createProducerTemplate(); + assertNotNull("producer for test purpose is null", producer); + mockEndpoint = camelContext.getEndpoint("mock:tdrRuleResult1", MockEndpoint.class); + assertNotNull("mockEndpoint for test purpose is null", mockEndpoint); + + mockEndpoint.expectedMessageCount(1); + exchange = new DefaultExchange(camelContext); + + producer.send("direct:tdrRuleTest1", exchange); + + assertEquals("Wrong expected message count", 1, mockEndpoint.getReceivedCounter()); + + receivedExchange = mockEndpoint.getExchanges().get(0); + assertNotNull("receivedExchange is null", receivedExchange); + + tdrProperties = TDRDataService.getTxTDRProperties(receivedExchange); + assertNotNull("tdrProperties map is null", tdrProperties); + + assertTrue("PropertyOne missing", tdrProperties.containsKey("PropertyOne")); + assertEquals("PropertyOne wrong value", "Static", tdrProperties.get("PropertyOne")); + assertTrue("PropertyOneTwo missing", tdrProperties.containsKey("PropertyOneTwo")); + assertEquals("PropertyOneTwo wrong value", "OtherValue", tdrProperties.get("PropertyOneTwo")); + + mockEndpoint.reset(); + + + // + // Test route 1 - 10 messages + mockEndpoint.expectedMessageCount(10); + + for(int i=0; i<10; i++) { + exchange = new DefaultExchange(camelContext); + producer.send("direct:tdrRuleTest1", exchange); + } + + assertEquals("Wrong expected message count", 10, mockEndpoint.getReceivedCounter()); + + Exchange lastExchange = null; + for(int i=0; i<10; i++) { + receivedExchange = mockEndpoint.getExchanges().get(i); + assertNotSame("Exchanges are identics", receivedExchange, lastExchange); + assertNotNull("receivedExchange is null", receivedExchange); + + tdrProperties = TDRDataService.getTxTDRProperties(receivedExchange); + assertNotNull("tdrProperties map is null", tdrProperties); + + assertTrue("PropertyOne missing", tdrProperties.containsKey("PropertyOne")); + assertEquals("PropertyOne wrong value", "Static", tdrProperties.get("PropertyOne")); + assertTrue("PropertyOneTwo missing", tdrProperties.containsKey("PropertyOneTwo")); + assertEquals("PropertyOneTwo wrong value", "OtherValue", tdrProperties.get("PropertyOneTwo")); + + lastExchange = receivedExchange; + } + + mockEndpoint.reset(); + + + // + // Test route 2 - Complex static value + producer = camelContext.createProducerTemplate(); + assertNotNull("producer for test purpose is null", producer); + mockEndpoint = camelContext.getEndpoint("mock:tdrRuleResult2", MockEndpoint.class); + assertNotNull("mockEndpoint for test purpose is null", mockEndpoint); + + mockEndpoint.expectedMessageCount(1); + exchange = new DefaultExchange(camelContext); + + producer.send("direct:tdrRuleTest2", exchange); + + assertEquals("Wrong expected message count", 1, mockEndpoint.getReceivedCounter()); + + receivedExchange = mockEndpoint.getExchanges().get(0); + assertNotNull("receivedExchange is null", receivedExchange); + + tdrProperties = TDRDataService.getTxTDRProperties(receivedExchange); + assertNotNull("tdrProperties map is null", tdrProperties); + + assertTrue("PropertyTwo missing", tdrProperties.containsKey("PropertyTwo")); + assertEquals("PropertyTwo wrong value", "Static value with space", tdrProperties.get("PropertyTwo")); + assertTrue("PropertyTwoTwo missing", tdrProperties.containsKey("PropertyTwoTwo")); + assertEquals("PropertyTwoTwo wrong value", "OtherValue", tdrProperties.get("PropertyTwoTwo")); + + mockEndpoint.reset(); + + + // + // Test route 3 - Complex static value with special character + producer = camelContext.createProducerTemplate(); + assertNotNull("producer for test purpose is null", producer); + mockEndpoint = camelContext.getEndpoint("mock:tdrRuleResult3", MockEndpoint.class); + assertNotNull("mockEndpoint for test purpose is null", mockEndpoint); + + mockEndpoint.expectedMessageCount(1); + exchange = new DefaultExchange(camelContext); + + producer.send("direct:tdrRuleTest3", exchange); + + assertEquals("Wrong expected message count", 1, mockEndpoint.getReceivedCounter()); + + receivedExchange = mockEndpoint.getExchanges().get(0); + assertNotNull("receivedExchange is null", receivedExchange); + + tdrProperties = TDRDataService.getTxTDRProperties(receivedExchange); + assertNotNull("tdrProperties map is null", tdrProperties); + + assertTrue("PropertyThree missing", tdrProperties.containsKey("PropertyThree")); + assertEquals("PropertyThree wrong value", "What kind of complex value we should have ?", tdrProperties.get("PropertyThree")); + assertTrue("PropertyThreeTwo missing", tdrProperties.containsKey("PropertyThreeTwo")); + assertEquals("PropertyThreeTwo wrong value", "OtherValue", tdrProperties.get("PropertyThreeTwo")); + + mockEndpoint.reset(); + } + + public void dynamicRuleTest() { + ProducerTemplate producer; + MockEndpoint mockEndpoint; + Exchange exchange; + Exchange receivedExchange; + Map tdrProperties; + + + // + // Test route 4 - Dynamic tdr rule + producer = camelContext.createProducerTemplate(); + assertNotNull("producer for test purpose is null", producer); + mockEndpoint = camelContext.getEndpoint("mock:tdrRuleResult4", MockEndpoint.class); + assertNotNull("mockEndpoint for test purpose is null", mockEndpoint); + + mockEndpoint.expectedMessageCount(1); + exchange = new DefaultExchange(camelContext); + exchange.getIn().setHeader("Header1", "Value header 1"); + + producer.send("direct:tdrRuleTest4", exchange); + + assertEquals("Wrong expected message count", 1, mockEndpoint.getReceivedCounter()); + + receivedExchange = mockEndpoint.getExchanges().get(0); + assertNotNull("receivedExchange is null", receivedExchange); + + tdrProperties = TDRDataService.getTxTDRProperties(receivedExchange); + assertNotNull("tdrProperties map is null", tdrProperties); + + assertTrue("PropertyFour missing", tdrProperties.containsKey("PropertyFour")); + assertEquals("PropertyFour wrong value", "Value header 1", tdrProperties.get("PropertyFour")); + assertTrue("PropertyFourTwo missing", tdrProperties.containsKey("PropertyFourTwo")); + assertEquals("PropertyFourTwo wrong value", "OtherValue", tdrProperties.get("PropertyFourTwo")); + + + mockEndpoint.reset(); + } + + @Test + public void queueServiceTest() throws InterruptedException { + ProducerTemplate producer; + MockEndpoint mockEndpoint; + Exchange exchange; + Map>> tdrData; + + // + // Test route 5 - Queue Service + producer = camelContext.createProducerTemplate(); + assertNotNull("producer for test purpose is null", producer); + mockEndpoint = camelContext.getEndpoint("mock:tdrRuleResult5", MockEndpoint.class); + assertNotNull("mockEndpoint for test purpose is null", mockEndpoint); + assertNotNull("tdrQueueService for test purpose is null", tdrQueueService); + + mockEndpoint.expectedMessageCount(1); + exchange = new DefaultExchange(camelContext); + exchange.getIn().setHeader("DynamicHeader", "DynamicValue"); + + producer.send("direct:tdrRuleTest5", exchange); + assertEquals("Wrong expected message count", 1, mockEndpoint.getReceivedCounter()); + assertEquals("Wrong tdrQueueService size", 1, tdrQueueService.getQueueSize()); + + tdrData = tdrQueueService.getOrWait(); + // Now the queue is empty + assertEquals("Wrong tdrQueueService size", 0, tdrQueueService.getQueueSize()); + // Check tdrData values + assertNotNull("tdrDatas is null", tdrData); + assertTrue("tdrDatas does not have a txTDR", + tdrData.containsKey("txTDR")); + assertTrue("txTDR list has not members", + tdrData.get("txTDR").size() > 0); + Map txTdr = tdrData.get("txTDR").get(0); + assertTrue("PropertyFive missing", txTdr.containsKey("PropertyFive")); + assertEquals("PropertyFive wrong value", "OtherValue", + txTdr.get("PropertyFive")); + assertTrue("DynamicHeader missing", txTdr.containsKey("DynamicHeader")); + assertEquals("DynamicHeader wrong value", "DynamicValue", + txTdr.get("DynamicHeader")); + + // Reset + mockEndpoint.reset(); + + // Sends 10 message + for(int i=0; i<10; i++) { + exchange = new DefaultExchange(camelContext); + exchange.getIn().setHeader("DynamicHeader", "DynamicValue"+i); + + producer.send("direct:tdrRuleTest5", exchange); + } + assertEquals("Wrong expected message count", 10, + mockEndpoint.getReceivedCounter()); + tdrData = tdrQueueService.getOrWait(); + // Now the queue is 9 + assertEquals("Wrong tdrQueueService size", 9, tdrQueueService.getQueueSize()); + // Check tdrData values + assertNotNull("tdrDatas is null", tdrData); + assertNotNull("tdrDatas is null", tdrData); + assertTrue("tdrDatas does not have a txTDR", + tdrData.containsKey("txTDR")); + assertTrue("txTDR list has not members", + tdrData.get("txTDR").size() > 0); + txTdr = tdrData.get("txTDR").get(0); + assertTrue("PropertyFive missing", txTdr.containsKey("PropertyFive")); + assertEquals("PropertyFive wrong value", "OtherValue", txTdr.get("PropertyFive")); + assertTrue("DynamicHeader missing", txTdr.containsKey("DynamicHeader")); + assertEquals("DynamicHeader wrong value", "DynamicValue0", + txTdr.get("DynamicHeader")); + // Check others tdrData + for (int i = 1; i < 10; i++) { + tdrData = tdrQueueService.getOrWait(); + assertEquals("Wrong tdrQueueService size", 9 - i, + tdrQueueService.getQueueSize()); + // Check tdrData values + + assertNotNull("tdrDatas is null", tdrData); + assertTrue("tdrDatas does not have a txTDR", + tdrData.containsKey("txTDR")); + assertTrue("txTDR list has not members", tdrData.get("txTDR") + .size() > 0); + txTdr = tdrData.get("txTDR").get(0); + assertTrue("PropertyFive missing", + txTdr.containsKey("PropertyFive")); + assertEquals("PropertyFive wrong value", "OtherValue", + txTdr.get("PropertyFive")); + assertTrue("DynamicHeader missing", + txTdr.containsKey("DynamicHeader")); + assertEquals("DynamicHeader wrong value", "DynamicValue" + i, + txTdr.get("DynamicHeader")); + } + + // Reset + mockEndpoint.reset(); + + // Bulk tdrData get + // Sends 10 message + for (int i = 0; i < 10; i++) { + exchange = new DefaultExchange(camelContext); + exchange.getIn().setHeader("DynamicHeader", "DynamicValue" + i); + + producer.send("direct:tdrRuleTest5", exchange); + } + assertEquals("Wrong expected message count", 10, + mockEndpoint.getReceivedCounter()); + assertEquals("Wrong tdrQueueService size", 10, + tdrQueueService.getQueueSize()); + // Get 5 of them + List>>> tdrDatas = tdrQueueService + .getMultiple(5); + assertEquals("Wrong tdrQueueService size", 5, + tdrQueueService.getQueueSize()); + assertEquals("Wrong tdrDatas size", 5, tdrDatas.size()); + tdrDatas.clear(); + // Get 10 but there is only 5 in queue + tdrDatas = tdrQueueService.getMultiple(10); + assertEquals("Wrong tdrQueueService size", 0, + tdrQueueService.getQueueSize()); + // So we must have 5 + assertEquals("Wrong tdrDatas size", 5, tdrDatas.size()); + tdrDatas.clear(); + + + // Reset + mockEndpoint.reset(); + } + + @Test + public void blockingQueueServiceTest() throws InterruptedException { + final ProducerTemplate producer; + MockEndpoint mockEndpoint; + Exchange exchange; + Map>> tdrData; + + // Test - Blocking tdr queue service + producer = camelContext.createProducerTemplate(); + assertNotNull("producer for test purpose is null", producer); + mockEndpoint = camelContext.getEndpoint("mock:tdrRuleResult5", + MockEndpoint.class); + assertNotNull("mockEndpoint for test purpose is null", mockEndpoint); + assertNotNull("tdrQueueService for test purpose is null", + tdrQueueService); + + TdrQueueService tdrQueueServiceImpl = (TdrQueueService) tdrQueueService; + // Force the queue size to have only 5 slot. + // If a sixth exchange come, the thread will wait until someone + // consume at least one message from the queue. + tdrQueueServiceImpl.setQueueWaitingSize(5); + + // Each exchange are sent in a separate thread + for (int i = 0; i < 10; i++) { + exchange = new DefaultExchange(camelContext); + exchange.getIn().setHeader("DynamicHeader", "DynamicValue" + i); + + new Thread( + new Runnable() { + private Exchange exchange; + public Runnable setExchange(Exchange exchange) { + this.exchange = exchange; + return this; + } + @Override + public void run() { + producer.send("direct:tdrRuleTest5", exchange); + } + }.setExchange(exchange) + ).start(); + } + // Wait a bit to be sure + Thread.sleep(100); + // We had 10 thread sending exchange + // but the tdrData todo queue is 5 slot + // We have only received 5 message: + assertEquals("Wrong expected message count", 5, mockEndpoint.getReceivedCounter()); + + // Pop the first one from the queue + tdrData = tdrQueueService.getOrWait(); + assertNotNull("tdrDatas is null", tdrData); + assertTrue("tdrDatas does not have a txTDR", + tdrData.containsKey("txTDR")); + assertTrue("txTDR list has not members", + tdrData.get("txTDR").size() > 0); + Map txTdr = tdrData.get("txTDR").get(0); + assertTrue("PropertyFive missing", txTdr.containsKey("PropertyFive")); + assertEquals("PropertyFive wrong value", "OtherValue", + txTdr.get("PropertyFive")); + // Wait a bit to be sure + Thread.sleep(100); + // Now the queue is still 5, cause a route thread has been released + assertEquals("Wrong tdrQueueService size", 5, + tdrQueueService.getQueueSize()); + // Only one more route thread has finished + assertEquals("Wrong expected message count", 6, + mockEndpoint.getReceivedCounter()); + // Pop .=*=. 2 + tdrData = tdrQueueService.getOrWait(); + // Pop .=*=. 3 + tdrData = tdrQueueService.getOrWait(); + // Pop .=*=. 4 + tdrData = tdrQueueService.getOrWait(); + // Pop .=*=. 5 + tdrData = tdrQueueService.getOrWait(); + // Wait a bit to be sure + Thread.sleep(100); + // All route have finished + assertEquals("Wrong expected message count", 10, + mockEndpoint.getReceivedCounter()); + // But tdr data to treat are still 5 + assertEquals("Wrong tdrQueueService size", 5, + tdrQueueService.getQueueSize()); + // Pop them all + List>>> tdrDatas = tdrQueueService + .getMultiple(10); + // Queue size is empty + assertEquals("Wrong tdrQueueService size", 0, + tdrQueueService.getQueueSize()); + assertEquals("Wrong tdrDatas size", 5, tdrDatas.size()); + // No more data to treat + tdrDatas = tdrQueueService.getMultiple(10); + assertEquals("Wrong tdrDatas size", 0, tdrDatas.size()); + + + // Reset + mockEndpoint.reset(); + } + + @Test + public void commonTdrRuleTest() throws InterruptedException { + ProducerTemplate producer; + MockEndpoint mockEndpoint; + Exchange exchange; + Exchange receivedExchange; + Map>> tdrProperties; + + // + // Test route 6 - Common tdr rule + producer = camelContext.createProducerTemplate(); + assertNotNull("producer for test purpose is null", producer); + mockEndpoint = camelContext.getEndpoint("mock:tdrRuleResult6", + MockEndpoint.class); + assertNotNull("mockEndpoint for test purpose is null", mockEndpoint); + assertNotNull("tdrQueueService for test purpose is null", + tdrQueueService); + + mockEndpoint.expectedMessageCount(1); + exchange = new DefaultExchange(camelContext); + exchange.getIn().setHeader("DynamicHeader7", + "The value header 7, but will not be extracted"); + exchange.getIn().setHeader("DynamicHeader8", "The value header 8"); + + producer.send("direct:tdrRuleTest6", exchange); + + assertEquals("Wrong expected message count", 1, + mockEndpoint.getReceivedCounter()); + + receivedExchange = mockEndpoint.getExchanges().get(0); + assertNotNull("receivedExchange is null", receivedExchange); + + tdrProperties = tdrQueueService.getOrWait(); + assertTrue("tdr Properties doesn't have a txTDR", + tdrProperties.containsKey("txTDR")); + assertTrue("txTDR list has no elements", tdrProperties.get("txTDR") + .size() > 0); + + Map txTdr = tdrProperties.get("txTDR").get(0); + + assertTrue("PropertySeven missing", txTdr.containsKey("PropertySeven")); + assertEquals("PropertySeven wrong value", "SevenValue", + txTdr.get("PropertySeven")); + assertTrue("Property8 missing", txTdr.containsKey("Property8")); + assertEquals("Property8 wrong value", "The value header 8", + txTdr.get("Property8")); + assertTrue("id missing", txTdr.containsKey("TransactionID")); + assertNotNull("id is null", txTdr.get("TransactionID")); + + mockEndpoint.reset(); + } +} \ No newline at end of file diff --git a/exposure-engine/tdr-lib/src/test/java/com/alu/e3/tdr/camel/TdrRuleWithXMLWriterTest.java b/exposure-engine/tdr-lib/src/test/java/com/alu/e3/tdr/camel/TdrRuleWithXMLWriterTest.java new file mode 100644 index 0000000..5d12fdf --- /dev/null +++ b/exposure-engine/tdr-lib/src/test/java/com/alu/e3/tdr/camel/TdrRuleWithXMLWriterTest.java @@ -0,0 +1,136 @@ +/** + * Copyright © 2012 Alcatel-Lucent. + * + * See the NOTICE file distributed with this work for additional + * information regarding copyright ownership. + * Licensed to you 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 com.alu.e3.tdr.camel; + +import static org.junit.Assert.assertEquals; +import static org.junit.Assert.assertNotNull; + +import java.io.File; + +import org.apache.camel.CamelContext; +import org.apache.camel.Exchange; +import org.apache.camel.ProducerTemplate; +import org.apache.camel.component.mock.MockEndpoint; +import org.apache.camel.impl.DefaultExchange; +import org.junit.Assert; +import org.junit.BeforeClass; +import org.junit.Test; +import org.junit.runner.RunWith; +import org.springframework.beans.factory.annotation.Autowired; +import org.springframework.beans.factory.annotation.Qualifier; +import org.springframework.test.context.ContextConfiguration; +import org.springframework.test.context.junit4.SpringJUnit4ClassRunner; + +import com.alu.e3.tdr.service.ITdrQueueService; + +@RunWith(SpringJUnit4ClassRunner.class) +@ContextConfiguration(locations = { + "classpath:tdr.osgi-context-writer-test.xml" +}) +public class TdrRuleWithXMLWriterTest { + + @Autowired + @Qualifier("tdrWriterContext") + CamelContext camelContext; + + @Autowired + ITdrQueueService tdrQueueService; + + @BeforeClass + public static void cleanTdrs() { + File outputDir = new File("target/tdrs"); + outputDir.mkdirs(); + for(File f : outputDir.listFiles()) { + f.delete(); + } + } + + @Test + public void enableTestEnvironment() throws Exception { + MockEndpoint.assertIsSatisfied(camelContext); + } + + @Test + public void xmlWriterTest() throws InterruptedException { + // Waiting xmlWriter service launch + Thread.sleep(1010); + + // Ok, the writer should have been started + //TODO: Test it up + + + final ProducerTemplate producer; + MockEndpoint mockEndpoint; + + // + // Test - Blocking tdr queue service + producer = camelContext.createProducerTemplate(); + assertNotNull("producer for test purpose is null", producer); + mockEndpoint = camelContext.getEndpoint("mock:tdrWriter", MockEndpoint.class); + assertNotNull("mockEndpoint for test purpose is null", mockEndpoint); + assertNotNull("tdrQueueService for test purpose is null", tdrQueueService); + + long start = System.currentTimeMillis(); + + // Each thread sends 100 message + // There are 100 threads ... + // So : finally 10000 tdrs + for(int i=0; i<100; i++) { + + new Thread( + new Runnable() { + @Override + public void run() { + for(int i=0; i<100; i++) { + Exchange exchange = new DefaultExchange(camelContext); + exchange.getIn().setHeader("DynamicHeader", "The dynamic value message:"+i); + producer.send("direct:tdrWriterTest", exchange); + } + } + } + ).start(); + } + // Wait a bit to be sure + int attempt = 1000; // We're not going to wait indefinitely ... + do { + Thread.sleep(100); + System.out.println(" Remaining route to finish:"+mockEndpoint.getReceivedCounter()+"/10000"); + } while( mockEndpoint.getReceivedCounter()<10000 && --attempt > 0); + + assertEquals("Wrong expected message count", 10000, mockEndpoint.getReceivedCounter()); + + attempt = 1000; + do { + Thread.sleep(100); + System.out.println(" Remaining tdr to write:"+tdrQueueService.getQueueSize()); + } while(tdrQueueService.getQueueSize()>0 && --attempt > 0); + + assertEquals("Wrong queue size", 0, tdrQueueService.getQueueSize()); + + long stop = System.currentTimeMillis(); + + System.out.println("Writing 10000 tdr took: "+(stop-start)+"millis"); + + // The queue should be empty + Assert.assertTrue("Size should be 0", tdrQueueService.getQueueSize() == 0); + + // Reset + mockEndpoint.reset(); + } +} \ No newline at end of file diff --git a/exposure-engine/tdr-lib/src/test/java/com/alu/e3/tdr/rotator/RotatableWriterProviderTest.java b/exposure-engine/tdr-lib/src/test/java/com/alu/e3/tdr/rotator/RotatableWriterProviderTest.java new file mode 100644 index 0000000..b229c99 --- /dev/null +++ b/exposure-engine/tdr-lib/src/test/java/com/alu/e3/tdr/rotator/RotatableWriterProviderTest.java @@ -0,0 +1,101 @@ +/** + * Copyright © 2012 Alcatel-Lucent. + * + * See the NOTICE file distributed with this work for additional + * information regarding copyright ownership. + * Licensed to you 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 com.alu.e3.tdr.rotator; + +import java.io.CharArrayWriter; +import java.io.IOException; +import java.io.Writer; + +import static org.junit.Assert.assertNotNull; +import static org.junit.Assert.assertEquals; + +import org.junit.Test; + +/** + * Tests RotatableWriterProvider. + * + */ +public class RotatableWriterProviderTest { + + private static final int MILLISECOND_THRESHOLD = 1 * 1000; // short timeout, for testing + private static final int CHARACTER_COUNT_THRESHOLD = 3; // short length, for testing + + private static final String[] indexedTestStrings = { + "the first test string", + "the second test string", + "the third test string" + }; + + + // handy test class + private class RotateableCharArryWriterProvider extends RotatableWriterProvider { + + int rotateCount = 0; // to determine which test string is expected + private CharArrayWriter currentCharArrayWriter; // for verifying content + + public RotateableCharArryWriterProvider(long characterCountThreshold, long millisecondsThreshold) { + super(characterCountThreshold, millisecondsThreshold); + } + + @Override + public Writer newWriter() throws IOException { + return currentCharArrayWriter = new CharArrayWriter(); + } + + @Override + public void rotate() { + synchronized (getSynchroLock()) { + super.rotate(); + // with each rotate operation, we expect to find the corresponding test string + assertEquals(indexedTestStrings[rotateCount++], currentCharArrayWriter.toString()); + } + } + } + + @Test + public void testConstuctor() throws IOException, InterruptedException { + WriterProvider wp = new RotateableCharArryWriterProvider(1000, 3 * 1000); + assertNotNull(wp); + } + + @Test + public void testTimeout() throws IOException, InterruptedException { + // create a WriterProvider with a low timeout value + WriterProvider wp = new RotateableCharArryWriterProvider(1000, MILLISECOND_THRESHOLD); + assertNotNull(wp); + for (int i = 0; i < indexedTestStrings.length; i++) { + synchronized (wp.getSynchroLock()) { + wp.getWriter().write(indexedTestStrings[i]); + } + Thread.sleep(MILLISECOND_THRESHOLD * 2); // sleep long enough for a rotate to occur + } + } + + @Test + public void testLength() throws IOException, InterruptedException { + // create a WriterProvider with a low character count threshold + WriterProvider wp = new RotateableCharArryWriterProvider(CHARACTER_COUNT_THRESHOLD, 30 * 1000); + assertNotNull(wp); + for (int i = 0; i < indexedTestStrings.length; i++) { + synchronized (wp.getSynchroLock()) { + wp.getWriter().write(indexedTestStrings[i]); // write enough chars to trigger a rotate + } + } + } +} diff --git a/exposure-engine/tdr-lib/src/test/resources/tdr.osgi-context-test.xml b/exposure-engine/tdr-lib/src/test/resources/tdr.osgi-context-test.xml new file mode 100644 index 0000000..ef07193 --- /dev/null +++ b/exposure-engine/tdr-lib/src/test/resources/tdr.osgi-context-test.xml @@ -0,0 +1,64 @@ + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + diff --git a/exposure-engine/tdr-lib/src/test/resources/tdr.osgi-context-writer-test.xml b/exposure-engine/tdr-lib/src/test/resources/tdr.osgi-context-writer-test.xml new file mode 100644 index 0000000..f59b9a2 --- /dev/null +++ b/exposure-engine/tdr-lib/src/test/resources/tdr.osgi-context-writer-test.xml @@ -0,0 +1,49 @@ + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + \ No newline at end of file diff --git a/exposure-engine/tdr-lib/src/test/resources/tdr.spring-unit-test.xml b/exposure-engine/tdr-lib/src/test/resources/tdr.spring-unit-test.xml new file mode 100644 index 0000000..74184bf --- /dev/null +++ b/exposure-engine/tdr-lib/src/test/resources/tdr.spring-unit-test.xml @@ -0,0 +1,30 @@ + + + + + + + + + + + + + + + + + + + + + + + + + diff --git a/exposure-engine/topology/pom.xml b/exposure-engine/topology/pom.xml new file mode 100644 index 0000000..8a80660 --- /dev/null +++ b/exposure-engine/topology/pom.xml @@ -0,0 +1,30 @@ + + + 4.0.0 + + + exposure-engine + com.alu.e3 + 1.0.1 + .. + + + topology + E3 Topology + http://www.alcatel-lucent.com + + + jar + + + + com.alu.e3 + common + ${project.version} + jar + provided + + + + diff --git a/exposure-engine/topology/src/main/java/com/alu/e3/osgi/api/ITopology.java b/exposure-engine/topology/src/main/java/com/alu/e3/osgi/api/ITopology.java new file mode 100644 index 0000000..d2bd86f --- /dev/null +++ b/exposure-engine/topology/src/main/java/com/alu/e3/osgi/api/ITopology.java @@ -0,0 +1,82 @@ +/** + * Copyright © 2012 Alcatel-Lucent. + * + * See the NOTICE file distributed with this work for additional + * information regarding copyright ownership. + * Licensed to you 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 com.alu.e3.osgi.api; + +import java.util.List; + +import com.alu.e3.data.model.Instance; +import com.alu.e3.topology.model.ITopologyListener; +import com.alu.e3.topology.model.Topology; + +public interface ITopology { + + /** + * + * @param nodeType + * @return + */ + List getNodeAccessDescriptor(String nodeType); + + /** + * Get the instance list by type 'instanceType'. + * @param instanceType the instance type query + * @return a list of found instances + */ + List getInstancesByType(String instanceType); + + /** + * Override or set the topology. + * @param path, the fullpath string to the topology to set. + * @return true if success, false otherwise + */ + boolean setTopology(String path); + + /** + * Override or set the topology. + * @param tmpTopology, the Topology to set. + * @return true if success, false otherwise + */ + boolean setTopology(Topology tmpTopology); + + /** + * Override or set the system topology. + * @param path the fullpath string to the system topology to set. + * @return true if success, false otherwise + */ + boolean setSystemTopology(String path); + + /** + * Register a topology listener against the Topology service. + * @param listener the listener to register and notify + */ + void addTopologyListener(ITopologyListener listener); + + /** + * Unregister a topology listener against the Topology service. + * @param listener the listener to unregister + */ + void removeTopologyListener(ITopologyListener listener); + + /** + * Parse a topology file and return Topology object. + * @param absolutePath the fullpath string of the topology file to parse + * @return the constructed topology object + */ + Topology getTopologyFromFile(String absolutePath); +} diff --git a/exposure-engine/topology/src/main/java/com/alu/e3/topology/Topology.java b/exposure-engine/topology/src/main/java/com/alu/e3/topology/Topology.java new file mode 100644 index 0000000..a05ca0a --- /dev/null +++ b/exposure-engine/topology/src/main/java/com/alu/e3/topology/Topology.java @@ -0,0 +1,332 @@ +/** + * Copyright © 2012 Alcatel-Lucent. + * + * See the NOTICE file distributed with this work for additional + * information regarding copyright ownership. + * Licensed to you 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 com.alu.e3.topology; + +import java.io.File; +import java.util.ArrayList; +import java.util.HashSet; +import java.util.LinkedList; +import java.util.List; +import java.util.Set; + +import com.alu.e3.common.E3Constant; +import com.alu.e3.common.osgi.api.ITopologyClient; +import com.alu.e3.common.tools.CommonTools; +import com.alu.e3.data.model.Instance; +import com.alu.e3.osgi.api.ITopology; +import com.alu.e3.topology.model.ITopologyListener; +import com.alu.e3.topology.parsers.TopologyDescriptorParser; + +public class Topology implements ITopology +{ + private com.alu.e3.topology.model.Topology topology; + private com.alu.e3.topology.model.Topology systemTopology; + + private LinkedList listeners = new LinkedList(); + + private ITopologyClient topologyClient; + + /** + * setTopologyClient + */ + + public void setTopologyClient(ITopologyClient topologyClient) { + this.topologyClient = topologyClient; + + if (topology != null) { + saveTopologyInCache(topology.getInstances()); + } + + if (systemTopology != null) { + saveTopologyInCache(systemTopology.getInstances()); + } + + } + + @Override + public List getNodeAccessDescriptor(String nodeType) + { + if (nodeType == null) + { + return null; + } + + List result = null; + + if (systemTopology != null) + { + result = getNodeAccessDescriptor_internal(nodeType, systemTopology.getInstances()); + } + + if (result == null || result.isEmpty()) + { + if (topology != null) + { + result = getNodeAccessDescriptor_internal(nodeType, topology.getInstances()); + } + } + + return result; + } + + @Override + public List getInstancesByType(String instanceType) + { + List instances = new ArrayList(); + + if (systemTopology != null) { + instances.addAll(systemTopology.getInstancesByType(instanceType)); + } + if (topology != null) { + instances.addAll(topology.getInstancesByType(instanceType)); + } + + return instances; + } + + @Override + public boolean setTopology(String path) + { + if (path.contains("null")) + { + path = System.getProperty("user.home") + File.separator + "topology.xml"; + } + + com.alu.e3.topology.model.Topology tmpTopology = null; + TopologyDescriptorParser parser = new TopologyDescriptorParser(); + try + { + tmpTopology = parser.parse(path); + } + catch (Exception e) + { + e.printStackTrace(); + } + return setTopology(tmpTopology); + } + + @Override + public synchronized boolean setTopology(com.alu.e3.topology.model.Topology tmpTopology) { + if (tmpTopology == null) + { + return false; + } + + this.topology = tmpTopology; + + + if (systemTopology != null) + { + // Store in cache + saveTopologyInCache(); + + // both topology and systemTopology are set, notify listeners + notifyReady(); + } + + return true; + } + + @Override + public synchronized boolean setSystemTopology(String path) + { + if (systemTopology != null) + { + return false; + } + + if (path.contains("null")) + { + path = System.getProperty("user.home") + File.separator + "system_topology.xml"; + } + + TopologyDescriptorParser parser = new TopologyDescriptorParser(); + try + { + systemTopology = parser.parse(path); + } + catch (Exception e) + { + e.printStackTrace(); + } + + if (systemTopology == null) + { + return false; + } + + + if (topology != null) + { + // Store in cache + saveTopologyInCache(); + + // both topology and systemTopology are set, notify listeners + notifyReady(); + } + + return true; + } + + /** + * Save a topology in the cache of data manager. + */ + private void saveTopologyInCache() { + if (topologyClient == null) { + return; + } + + // my area + all areas + List instances = topology.getInstances(); + Set areas = new HashSet(); + + List gateways = new ArrayList(); + List others = new ArrayList(); + for (Instance instance : instances){ + areas.add(instance.getArea()); + if(E3Constant.E3GATEWAY.equals(instance.getType())){ + gateways.add(instance); + }else{ + others.add(instance); + } + } + topologyClient.addAreas(areas); + String myArea = initMyArea(instances); + topologyClient.setMyArea(myArea); + + // first gateways + saveTopologyInCache(gateways); + // machines inside E3 (managers, speakers ...) + saveTopologyInCache(others); + // machines outside of E3 (DataStorage ...) + saveTopologyInCache(systemTopology.getInstances()); + } + + /** + * Save a topology in the cache of data manager. + */ + private void saveTopologyInCache(List instances) { + + if (topologyClient == null) { + return; + } + + //topologyClient.addAreas(topology.getAreas()); + for (Instance instance : instances) + topologyClient.addInstance(instance); + } + + private List getNodeAccessDescriptor_internal(String nodeType, List instances) + { + ArrayList nodes = new ArrayList(); + + for (Instance instance : instances) + { + if (nodeType.equals(instance.getType())) + { + String nd = ""; + + if (instance.getExternalDNS() != null) + { + nd += "ip=" + instance.getExternalDNS(); + } + else + { + nd += "ip=" + instance.getExternalIP(); + } + + if (instance.getPort() != null) + { + nd += "&port=" + instance.getPort(); + } + + if (instance.getUser() != null) + { + nd += "&user=" + + org.apache.cxf.jaxrs.utils.HttpUtils + .urlEncode(instance.getUser()); + } + + if (instance.getPassword() != null) + { + nd += "&password=" + + org.apache.cxf.jaxrs.utils.HttpUtils + .urlEncode(instance.getPassword()); + } + + nodes.add(nd); + } + } + + return nodes; + } + + @Override + public void addTopologyListener(ITopologyListener listener) + { + listeners.add(listener); + + if (topology != null && systemTopology != null) + { + listener.onReady(); + } + } + + @Override + public void removeTopologyListener(ITopologyListener listener) + { + listeners.remove(listener); + } + + @Override + public com.alu.e3.topology.model.Topology getTopologyFromFile(String absolutePath) { + TopologyDescriptorParser parser = new TopologyDescriptorParser(); + try + { + return parser.parse(absolutePath); + } + catch (Exception e) + { + e.printStackTrace(); + throw new RuntimeException("Unable to parse the given topology file:"+absolutePath, e); + } + } + + private void notifyReady() + { + for (ITopologyListener listener : listeners) + { + listener.onReady(); + } + } + + private String initMyArea(List instances){ + String currentArea = null; + + for (Instance inst : instances) { + if (CommonTools.isLocal(inst.getExternalIP()) || CommonTools.isLocal(inst.getInternalIP())) { + currentArea = inst.getArea(); + return currentArea; + } + } + + return currentArea; + } + +} diff --git a/exposure-engine/topology/src/main/java/com/alu/e3/topology/TopologyWatcher.java b/exposure-engine/topology/src/main/java/com/alu/e3/topology/TopologyWatcher.java new file mode 100644 index 0000000..e80a968 --- /dev/null +++ b/exposure-engine/topology/src/main/java/com/alu/e3/topology/TopologyWatcher.java @@ -0,0 +1,413 @@ +/** + * Copyright © 2012 Alcatel-Lucent. + * + * See the NOTICE file distributed with this work for additional + * information regarding copyright ownership. + * Licensed to you 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 com.alu.e3.topology; + +import java.util.LinkedList; +import java.util.List; + +import org.slf4j.Logger; +import org.slf4j.LoggerFactory; + +import com.alu.e3.common.E3Constant; +import com.alu.e3.common.osgi.api.IHealthCheckFactory; +import com.alu.e3.common.osgi.api.ITopologyClient; +import com.alu.e3.data.IHealthCheckService; +import com.alu.e3.data.model.Instance; +import com.alu.e3.data.topology.IInstanceListener; +import com.alu.e3.data.topology.InstanceEvent; + +/** + * Keeps track of the topology using health check mechanism and update the TopologyClient accordingly. + */ +public class TopologyWatcher implements Runnable, IInstanceListener { + + private static final Logger logger = LoggerFactory.getLogger(TopologyWatcher.class); + + private ITopologyClient topologyClient; + private IHealthCheckFactory healthCheckFactory; + + private List upGateways = new LinkedList(); + private List upGatewaysActive = new LinkedList(); + private List downGateways = new LinkedList(); + + private List upSpeakers = new LinkedList(); + private List upSpeakersActive = new LinkedList(); + + private int pollingInterval = E3Constant.HEALTH_CHECK_POLLING_INTERVAL; + + private volatile boolean running; + + private Thread localThread; + + public TopologyWatcher() {} + + /** + * Sets the polling interval. + */ + public void setPollingInterval(int pollingInterval) { + this.pollingInterval = pollingInterval; + } + + /** + * Sets the healthCheckFactory object + */ + public void setHealthCheckFactory(IHealthCheckFactory healthCheckFactory) { + this.healthCheckFactory = healthCheckFactory; + } + + /** + * Set the topologyClient object + */ + public void setTopologyClient(ITopologyClient topologyClient) { + this.topologyClient = topologyClient; + } + + /** + * Starts watching of the nodes + */ + public void init() { + topologyClient.addInstanceListener(this); + + // get the list of gateways + speaker to monitor + List nodeList; + + synchronized (this) { + nodeList = topologyClient.getAllInstancesOfType(E3Constant.E3GATEWAY); + if (nodeList != null) { + upGateways.addAll(nodeList); + } + + nodeList = topologyClient.getAllInstancesOfType(E3Constant.E3GATEWAY_ACTIVE); + if (nodeList != null) { + upGatewaysActive.addAll(nodeList); + } + + nodeList = topologyClient.getAllInstancesOfType(E3Constant.E3SPEAKER); + if (nodeList != null) { + upSpeakers.addAll(nodeList); + } + + nodeList = topologyClient.getAllInstancesOfType(E3Constant.E3SPEAKER_ACTIVE); + if (nodeList != null) { + upSpeakersActive.addAll(nodeList); + } + } + + // start the watching of nodes + setRunning(true); + + // TODO what is doing the passive manager? watching only the active manager? how do we know active or passive? + localThread = new Thread(this); + localThread.start(); + } + + /** + * Stops watching the nodes + */ + public void destroy() { + logger.debug("Stopping TopologyWatcher ..."); + setRunning(false); + + logger.debug("Clearing TopologyWatcher list ..."); + synchronized (this) { + upGateways.clear(); + upGatewaysActive.clear(); + upSpeakers.clear(); + upSpeakersActive.clear(); + } + + logger.debug("Clearing TopologyWatcher listeners ..."); + topologyClient.removeInstanceListener(this); + + logger.debug("TopologyWatcher waiting for its local thread (join) ..."); + try { + localThread.join(); + } catch (InterruptedException e) { + logger.error("Unable to join TopologyWatcher local thread", e); + } + logger.debug("TopologyWatcher destroyed."); + } + + /** + * Runnable implementation + */ + @Override + public void run() { + do { + try { + synchronized (this) { + // check the active gateways which are up + // if an active gateways is down, it is removed from the list of E3GATEWAY_ACTIVE in the TopologyClient + checkUpNodes(upGatewaysActive, null, E3Constant.E3GATEWAY_ACTIVE); + + // check the gateways which are up + // if a gateway is down, it is removed from the list of E3GATEWAY in the TopologyClient + checkUpNodes(upGateways, downGateways, E3Constant.E3GATEWAY); + + // check the active speakers which are up + // if an active speaker is down, it is removed from the list of E3SPEAKER_ACTIVE in the TopologyClient + checkUpNodes(upSpeakersActive, null, E3Constant.E3SPEAKER_ACTIVE); + + // check the gateways which are down + // if a gateway becomes up, it is added to the list of E3GATEWAY in the TopologyClient + checkDownNodes(upGateways, downGateways, E3Constant.E3GATEWAY); + + // check the gateways that are becoming active + // if a gateway becomes active, it is added to the list of E3GATEWAY_ACTIVE in the TopologyClient + checkForActiveGateways(); + + // check if there's a new speaker + // if a speaker becomes active, it is added to the list of E3SPEAKER_ACTIVE in the TopologyClient + checkForNewSpeakers(); + } + Thread.sleep(pollingInterval); + } catch (InterruptedException e) { + logger.warn("TopologyWatcher thread interrupted", e); + running = false; + } + } while (running); + } + + /** + * Return the correct IP depending on the area + */ + private String getIPWithArea(Instance node) { + String myArea = topologyClient.getMyArea(); + + if (myArea == null || myArea.equals(node.getArea())) { + return node.getInternalIP(); + } + else { + return node.getExternalIP(); + } + } + + /** + * Check if a gateway is becoming active + */ + private void checkForActiveGateways() { + Instance[] nodes = new Instance[0]; + + synchronized (this) { + nodes = upGateways.toArray(nodes); + } + + for (int i = 0; i < nodes.length; i++) { + Instance node = nodes[i]; + + if (!upGatewaysActive.contains(node) && checkIfUp(getIPWithArea(node), E3Constant.E3GATEWAY_ACTIVE)) { + upGatewaysActive.add(node); // keep the node + Instance newNode = new Instance(node); + newNode.setType(E3Constant.E3GATEWAY_ACTIVE); + topologyClient.addInstance(newNode); + } + } + } + + /** + * Check if a new speaker is up + */ + private void checkForNewSpeakers() { + // iterate over the speakers and check if the Speaker heart beat is up + Instance[] nodes = new Instance[0]; + + nodes = upSpeakers.toArray(nodes); + + for (int i = 0; i < nodes.length; i++) { + Instance node = nodes[i]; + if (!upSpeakersActive.contains(node) && checkIfUp(getIPWithArea(node), E3Constant.E3SPEAKER_ACTIVE)) { + upSpeakersActive.add(node); // keep the node + Instance newNode = new Instance(node); + newNode.setType(E3Constant.E3SPEAKER_ACTIVE); + topologyClient.addInstance(newNode); + } + } + } + + /** + * Check if the upNodes are still up + */ + private void checkUpNodes(List upNodes, List downNodes, String type) { + Instance[] nodes = new Instance[0]; + + nodes = upNodes.toArray(nodes); + + for (int i = 0; i < nodes.length; i++) { + Instance node = nodes[i]; + if (!checkIfUp(getIPWithArea(node), type)) { + + upNodes.remove(node); + + if (downNodes != null) { + downNodes.add(node); + } + + Instance newNode = new Instance(node); + newNode.setType(type); + topologyClient.deleteInstance(newNode); + } + } + } + + /** + * Check if the downNodes are still down + */ + private void checkDownNodes(List upNodes, List downNodes, String type) { + Instance[] nodes = new Instance[0]; + + nodes = downNodes.toArray(nodes); + + for (int i = 0; i < nodes.length; i++) { + Instance node = nodes[i]; + if (checkIfUp(getIPWithArea(node), type)) { + + downNodes.remove(node); + upNodes.add(node); + + topologyClient.addInstance(node); + } + } + } + + /** + * Check if the node is up + */ + private boolean checkIfUp(String node, String type) { + + if (healthCheckFactory == null) { + // TODO log error + return false; + } + + String instanceType; + + if (E3Constant.E3GATEWAY.equals(type)) { + instanceType = IHealthCheckFactory.GATEWAY_INTERNAL_TYPE; + } + else if (E3Constant.E3GATEWAY_ACTIVE.equals(type)) { + instanceType = IHealthCheckFactory.GATEWAY_TYPE; + } + else if (E3Constant.E3SPEAKER_ACTIVE.equals(type)) { + instanceType = IHealthCheckFactory.SPEAKER_TYPE; + } + else { + // TODO log error + return false; + } + + IHealthCheckService healthCheckService; + + healthCheckService = healthCheckFactory.getHealthCheckService(instanceType); + + return healthCheckService.check(node); + } + + private boolean checkIfExist(Instance instance, List list) + { + for (Instance i : list) + { + if (i.getName().equals(instance.getName()) ) + { + return true; + } + } + return false; + } + + /** + * IInstanceListener implementation + */ + @Override + public synchronized void instanceAdded(InstanceEvent event) { + if (E3Constant.E3GATEWAY.equals(event.getType())) { + if (!checkIfExist(event.getInstance(), upGateways)) + { + upGateways.add(event.getInstance()); + } + logger.debug("E3GATEWAY added: {}", event.getInstance()); + } + + else if (E3Constant.E3SPEAKER.equals(event.getType())) { + if (!checkIfExist(event.getInstance(), upSpeakers)) + { + upSpeakers.add(event.getInstance()); + } + logger.debug("E3SPEAKER added: {}", event.getInstance()); + } + + else if (E3Constant.E3GATEWAY_ACTIVE.equals(event.getType())) { + logger.debug("E3GATEWAY_ACTIVE added: {}", event.getInstance()); + } + else if (E3Constant.E3SPEAKER_ACTIVE.equals(event.getType())) { + logger.debug("E3SPEAKER_ACTIVE added: {}", event.getInstance()); + } + } + + /** + * IInstanceListener implementation + */ + @Override + public synchronized void instanceRemoved(InstanceEvent event) { + if (E3Constant.E3GATEWAY.equals(event.getType())) { + upGateways.remove(event.getInstance()); + logger.debug("E3GATEWAY removed: {}", event.getInstance()); + } + else if (E3Constant.E3SPEAKER.equals(event.getType())) { + upSpeakers.remove(event.getInstance()); + logger.debug("E3SPEAKER removed: {}", event.getInstance()); + } + else if (E3Constant.E3GATEWAY_ACTIVE.equals(event.getType())) { + logger.debug("E3GATEWAY_ACTIVE removed: {}", event.getInstance()); + } + else if (E3Constant.E3SPEAKER_ACTIVE.equals(event.getType())) { + logger.debug("E3SPEAKER_ACTIVE removed: {}", event.getInstance()); + } + } + + /** + * General Setters + */ + public void setUpGateways(List upGateways) { + synchronized (this) { + this.upGateways = upGateways; + } + } + + public void setUpGatewaysActive(List upGatewaysActive) { + this.upGatewaysActive = upGatewaysActive; + } + + public void setDownGateways(List downGateways) { + this.downGateways = downGateways; + } + + public void setUpSpeakers(List upSpeakers) { + synchronized (this) { + this.upSpeakers = upSpeakers; + } + } + + public void setUpSpeakersActive(List upSpeakersActive) { + this.upSpeakersActive = upSpeakersActive; + } + + public void setRunning(boolean running) { + this.running = running; + } +} diff --git a/exposure-engine/topology/src/main/java/com/alu/e3/topology/model/ITopologyListener.java b/exposure-engine/topology/src/main/java/com/alu/e3/topology/model/ITopologyListener.java new file mode 100644 index 0000000..3a3c219 --- /dev/null +++ b/exposure-engine/topology/src/main/java/com/alu/e3/topology/model/ITopologyListener.java @@ -0,0 +1,24 @@ +/** + * Copyright © 2012 Alcatel-Lucent. + * + * See the NOTICE file distributed with this work for additional + * information regarding copyright ownership. + * Licensed to you 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 com.alu.e3.topology.model; + +public interface ITopologyListener +{ + void onReady(); +} diff --git a/exposure-engine/topology/src/main/java/com/alu/e3/topology/model/Topology.java b/exposure-engine/topology/src/main/java/com/alu/e3/topology/model/Topology.java new file mode 100644 index 0000000..5ebd103 --- /dev/null +++ b/exposure-engine/topology/src/main/java/com/alu/e3/topology/model/Topology.java @@ -0,0 +1,95 @@ +/** + * Copyright © 2012 Alcatel-Lucent. + * + * See the NOTICE file distributed with this work for additional + * information regarding copyright ownership. + * Licensed to you 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 com.alu.e3.topology.model; + +import java.util.ArrayList; +import java.util.HashMap; +import java.util.HashSet; +import java.util.List; +import java.util.Map; +import java.util.Set; + +import com.alu.e3.data.model.Instance; +import com.alu.e3.data.model.SSHKey; + + +/** + * Maintains a list of instances + * + */ +public class Topology { + + private List instances; + private Map sshKeys; + private Set areas = new HashSet(); + public Topology() { + instances = new ArrayList(); + sshKeys = new HashMap(); + } + + public List getInstances() { + return instances; + } + + public void addInstance(Instance instance) { + instances.add(instance); + } + + public Map getKeys() { + return sshKeys; + } + + public void addKey(SSHKey key) { + sshKeys.put(key.getName(), key); + } + + /** + * Extract the instance list by type 'instanceType'. + * @param instanceType the instance type query + * @return the list of found instances + */ + public List getInstancesByType(String instanceType) { + List tmpInstances = new ArrayList(); + + if (instanceType != null) + { + if (this.instances != null) + { + for (Instance instance : this.instances) + { + if (instanceType.equals(instance.getType())) + { + tmpInstances.add(instance); + } + } + } + } + + return tmpInstances; + } + + public Set getAreas() { + return areas; + } + + public void setAreas(Set areas) { + this.areas = areas; + } + +} diff --git a/exposure-engine/topology/src/main/java/com/alu/e3/topology/parsers/TopologyDescriptorParser.java b/exposure-engine/topology/src/main/java/com/alu/e3/topology/parsers/TopologyDescriptorParser.java new file mode 100644 index 0000000..f3b49df --- /dev/null +++ b/exposure-engine/topology/src/main/java/com/alu/e3/topology/parsers/TopologyDescriptorParser.java @@ -0,0 +1,245 @@ +/** + * Copyright © 2012 Alcatel-Lucent. + * + * See the NOTICE file distributed with this work for additional + * information regarding copyright ownership. + * Licensed to you 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 com.alu.e3.topology.parsers; + +import java.io.BufferedReader; +import java.io.File; +import java.io.FileInputStream; +import java.io.FileNotFoundException; +import java.io.FileReader; +import java.io.InputStream; +import java.io.UnsupportedEncodingException; +import java.util.HashSet; +import java.util.Set; + +import javax.xml.parsers.DocumentBuilder; +import javax.xml.parsers.DocumentBuilderFactory; + +import org.slf4j.Logger; +import org.slf4j.LoggerFactory; +import org.w3c.dom.Document; +import org.w3c.dom.Element; +import org.w3c.dom.Node; +import org.w3c.dom.NodeList; + +import com.alu.e3.data.model.Instance; +import com.alu.e3.data.model.SSHKey; +import com.alu.e3.topology.model.Topology; + +public class TopologyDescriptorParser { + + private static final Logger logger = LoggerFactory.getLogger(TopologyDescriptorParser.class); + + + public Topology parse(String topologyFilePath) throws TopologyParserException, UnsupportedEncodingException { + logger.debug("Parsing file at path: " + topologyFilePath); + + FileInputStream fin = null; + + try { + fin = new FileInputStream(topologyFilePath); + } catch (FileNotFoundException e) { + logger.error(e.getMessage()); + throw new TopologyParserException(e.getMessage()); + } + + return parse(fin); + } + + public Topology parse(InputStream topologyInputStream) throws TopologyParserException, UnsupportedEncodingException { + Topology topology = null; + Element rootElement = getRootElement(topologyInputStream); + + String type = rootElement.getAttribute("type"); + logger.debug("Topology type: " + type); + + TopologyParser parser = getParser(type); + + topology = parser.parseElement(rootElement); + + return topology; + } + + + private Element getRootElement(InputStream inputStream) throws TopologyParserException { + try { + DocumentBuilderFactory factory = DocumentBuilderFactory.newInstance(); + DocumentBuilder builder = factory.newDocumentBuilder(); + + Document labDoc = builder.parse(inputStream); + Element rootElement = labDoc.getDocumentElement(); + + return rootElement; + + } catch (Exception e) { + logger.error(e.getMessage()); + throw new TopologyParserException(e.getMessage()); + } + + } + + private TopologyParser getParser(String type) throws TopologyParserException { + TopologyParser parser = null; + + parser = new CommonTopologyParser(); + return parser; + } + + abstract class TopologyParser { + abstract Topology parseElement(Element rootElement) throws TopologyParserException, UnsupportedEncodingException; + } + + class CommonTopologyParser extends TopologyParser { + + @Override + Topology parseElement(Element rootElement) throws TopologyParserException, UnsupportedEncodingException { + Topology topology = new Topology(); + + // Finding keypair to use + NodeList keyNodes = rootElement.getElementsByTagName("Key"); + logger.debug("Found " + keyNodes.getLength() + " SSH keys"); + for(int i = 0; i < keyNodes.getLength(); i++) + { + Element keyElement = (Element) keyNodes.item(i); + if(keyElement == null) { + continue; + } + + String strPrivateKey = "", strPublicKey = ""; + String strKeyName = keyElement.getAttribute("name"); + String privateKeyPath = keyElement.getAttribute("privatekeypath"); + if (privateKeyPath != null && !privateKeyPath.isEmpty()) + { + String strKeyFormat = keyElement.getAttribute("format"); + privateKeyPath += File.separatorChar + strKeyName + "." + strKeyFormat; + + try { + StringBuffer fileContent = new StringBuffer(1000); + BufferedReader br = new BufferedReader(new FileReader(privateKeyPath)); + char[] buf = new char[1024]; + int nRead=0; + while((nRead=br.read(buf)) != -1){ + fileContent.append(buf, 0, nRead); + } + br.close(); + strPrivateKey = fileContent.toString(); + + + } catch (Exception e) { + logger.error(e.getMessage()); + throw new TopologyParserException(e.getMessage()); + } + } + else + { + NodeList privateKeyNode = keyElement.getElementsByTagName("PrivateKey"); + strPublicKey = keyElement.getElementsByTagName("PublicKey").item(0).getTextContent(); + strPrivateKey = (privateKeyNode == null || privateKeyNode.getLength() == 0) ? null : privateKeyNode.item(0).getTextContent(); + } + + SSHKey key = new SSHKey(strKeyName, strPrivateKey == null ? null : strPrivateKey.getBytes("UTF-8"), strPublicKey.getBytes("UTF-8")); + topology.addKey(key); + + logger.debug(key.toString()); + } + + + NodeList labNodes = rootElement.getElementsByTagName("Node"); + logger.debug("Found " + labNodes.getLength() + " nodes in this topology"); + + HashSet instancesNameAlreadyAdded = new HashSet(); + + for(int i = 0; i < labNodes.getLength(); i++) + { + Instance instance = new Instance(); + Node node = labNodes.item(i); + + instance.setName(node.getAttributes().getNamedItem("name").getTextContent()); + + if (instancesNameAlreadyAdded.contains(instance.getName())) + { + throw new TopologyParserException("Each node name in the topology configuration file must be unique. The name " + instance.getName() + "is set to more than one node"); + } + + for(int j = 0; j < node.getChildNodes().getLength(); j++) + { + Node child = node.getChildNodes().item(j); + if(child.getNodeName().equals("Type")) + { + instance.setType(child.getAttributes().getNamedItem("type").getTextContent()); + } + else if(child.getNodeName().equals("ExternalDNS")) + { + instance.setExternalDNS(child.getAttributes().getNamedItem("url").getTextContent()); + } + else if(child.getNodeName().equals("ExternalIP")) + { + instance.setExternalIP(child.getAttributes().getNamedItem("ip").getTextContent()); + } + else if(child.getNodeName().equals("InternalIP")) + { + instance.setInternalIP(child.getAttributes().getNamedItem("ip").getTextContent()); + } + else if(child.getNodeName().equals("Port")) + { + instance.setPort(child.getAttributes().getNamedItem("port").getTextContent()); + } + else if(child.getNodeName().equals("Area")) + { + instance.setArea(child.getAttributes().getNamedItem("name").getTextContent()); + topology.getAreas().add(child.getAttributes().getNamedItem("name").getTextContent()); + } + else if(child.getNodeName().equals("Credentials")) + { + if (child.getAttributes().getNamedItem("key") != null) { + instance.setSSHKeyName(child.getAttributes().getNamedItem("key").getTextContent()); + instance.setSSHKey(topology.getKeys().get(instance.getSSHKeyName())); + } + if (child.getAttributes().getNamedItem("user") != null) { + instance.setUser(child.getAttributes().getNamedItem("user").getTextContent()); + } + if (child.getAttributes().getNamedItem("password") != null) { + instance.setPassword(child.getAttributes().getNamedItem("password").getTextContent()); + } + } + else if(child.getNodeName().equals("KeyUsed")) + { + if (child.getAttributes().getNamedItem("key") != null) { + instance.setSSHKeyName(child.getAttributes().getNamedItem("key").getTextContent()); + instance.setSSHKey(topology.getKeys().get(instance.getSSHKeyName())); + } + if (child.getAttributes().getNamedItem("user") != null) { + instance.setUser(child.getAttributes().getNamedItem("user").getTextContent()); + } + if (child.getAttributes().getNamedItem("password") != null) { + instance.setPassword(child.getAttributes().getNamedItem("password").getTextContent()); + } + } + + } + + logger.debug(instance.toString()); + + topology.addInstance(instance); + } + + return topology; + } + } +} diff --git a/exposure-engine/topology/src/main/java/com/alu/e3/topology/parsers/TopologyParserException.java b/exposure-engine/topology/src/main/java/com/alu/e3/topology/parsers/TopologyParserException.java new file mode 100644 index 0000000..25dccb0 --- /dev/null +++ b/exposure-engine/topology/src/main/java/com/alu/e3/topology/parsers/TopologyParserException.java @@ -0,0 +1,37 @@ +/** + * Copyright © 2012 Alcatel-Lucent. + * + * See the NOTICE file distributed with this work for additional + * information regarding copyright ownership. + * Licensed to you 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 com.alu.e3.topology.parsers; + +/** + * class InstallerParserException + * + */ +public class TopologyParserException extends Exception { + + private static final long serialVersionUID = 2643389317278295881L; + + public TopologyParserException(String message) { + super(message); + } + + public TopologyParserException(Exception e) { + super(e.getMessage()); + e.printStackTrace(); + } +} diff --git a/exposure-engine/topology/src/main/resources/META-INF/spring-optional/topology.beans.xml b/exposure-engine/topology/src/main/resources/META-INF/spring-optional/topology.beans.xml new file mode 100644 index 0000000..1fe4ef4 --- /dev/null +++ b/exposure-engine/topology/src/main/resources/META-INF/spring-optional/topology.beans.xml @@ -0,0 +1,38 @@ + + + + + + + + + + + + + + diff --git a/exposure-engine/topology/src/test/java/com/alu/e3/tests/TopologyWatcherTest.java b/exposure-engine/topology/src/test/java/com/alu/e3/tests/TopologyWatcherTest.java new file mode 100644 index 0000000..cfe2d94 --- /dev/null +++ b/exposure-engine/topology/src/test/java/com/alu/e3/tests/TopologyWatcherTest.java @@ -0,0 +1,396 @@ +/** + * Copyright © 2012 Alcatel-Lucent. + * + * See the NOTICE file distributed with this work for additional + * information regarding copyright ownership. + * Licensed to you 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 com.alu.e3.tests; + +import static org.junit.Assert.assertTrue; + +import java.util.HashSet; +import java.util.Set; + +import org.junit.Test; + +import com.alu.e3.common.E3Constant; +import com.alu.e3.common.osgi.api.ITopologyClient; +import com.alu.e3.data.model.Instance; +import com.alu.e3.tests.topologywatcher.DummyHealthCheckFactory; +import com.alu.e3.tests.topologywatcher.DummyTopologyClient; +import com.alu.e3.topology.TopologyWatcher; + +public class TopologyWatcherTest { + + private static final int POLLING_INTERVAL = 10; + + private TopologyWatcher topologyWatcher; + private ITopologyClient topologyClient; + private DummyHealthCheckFactory healthCheckFactory; + + private void setHealthCheckGatewaysActive(String[] gatewayList) { + Set gateways = new HashSet(); + for (int i = 0; i < gatewayList.length; i++) { + gateways.add(gatewayList[i]); + } + + healthCheckFactory.setGatewaysActive(gateways); + } + + private void setHealthCheckGateways(String[] gatewayList) { + Set gateways = new HashSet(); + for (int i = 0; i < gatewayList.length; i++) { + gateways.add(gatewayList[i]); + } + + healthCheckFactory.setGateways(gateways); + } + + private void setHealthCheckSpeakers(String[] speakerList) { + Set speakers = new HashSet(); + for (int i = 0; i < speakerList.length; i++) { + speakers.add(speakerList[i]); + } + + healthCheckFactory.setSpeakers(speakers); + } + + private Instance createInstance(String type, String intIP, String extIP) { + Instance instance = new Instance(); + + instance.setType(type); + instance.setArea("myArea"); + instance.setInternalIP(intIP); + instance.setExternalIP(extIP); + + return instance; + } + + private void createTestResources(String[] gatewayList, String[] gatewayActiveList, String[] speakerList) { + topologyWatcher = new TopologyWatcher(); + + topologyWatcher.setPollingInterval(POLLING_INTERVAL); + + topologyClient = new DummyTopologyClient(); + + healthCheckFactory = new DummyHealthCheckFactory(); + + setHealthCheckGateways(gatewayList); + setHealthCheckGatewaysActive(gatewayActiveList); + setHealthCheckSpeakers(speakerList); + + topologyClient.addInstance(createInstance(E3Constant.E3GATEWAY, "1.1.1.1", "1.1.1.1")); + topologyClient.addInstance(createInstance(E3Constant.E3GATEWAY, "1.1.1.2", "1.1.1.2")); + topologyClient.addInstance(createInstance(E3Constant.E3GATEWAY, "1.1.1.3", "1.1.1.3")); + + topologyClient.addInstance(createInstance(E3Constant.E3SPEAKER, "1.1.1.4", "1.1.1.4")); + + topologyWatcher.setHealthCheckFactory(healthCheckFactory); + topologyWatcher.setTopologyClient(topologyClient); + } + + private boolean areEquals(Set v1, String[] v2) { + + if (v1 == null || v2 == null) return false; + + for (int i = 0; i < v2.length; i++) { + if (!v1.contains(v2[i])) return false; + } + + return v1.size() == v2.length; + } + + @Test + public void testTopologyNotChanged() { + String[] gatewayList = {"1.1.1.1", "1.1.1.2", "1.1.1.3"}; + String[] gatewayActiveList = {"1.1.1.1", "1.1.1.2", "1.1.1.3"}; + String[] speakerList = {"1.1.1.4"}; + + createTestResources(gatewayList, gatewayActiveList, speakerList); + + // run 2 cycles of topology watcher + topologyWatcher.init(); + + try { + Thread.sleep(POLLING_INTERVAL * 2 + POLLING_INTERVAL / 2); + + topologyWatcher.destroy(); + + // wait until it's stopped + Thread.sleep(POLLING_INTERVAL + POLLING_INTERVAL / 2); + } + catch (InterruptedException e) { + assertTrue("interrupted", false); + } + + // the list of gateways and speakers must not have changed + boolean check; + + Set outGateways = topologyClient.getAllExternalIPsOfType(E3Constant.E3GATEWAY); + check = areEquals(outGateways, gatewayList); + assertTrue("The list of gateways must not have changed", check); + + Set outGatewaysActive = topologyClient.getAllExternalIPsOfType(E3Constant.E3GATEWAY_ACTIVE); + check = areEquals(outGatewaysActive, gatewayActiveList); + assertTrue("The list of active gateways must not have changed", check); + + Set outSpeakers = topologyClient.getAllExternalIPsOfType(E3Constant.E3SPEAKER); + check = areEquals(outSpeakers, speakerList); + assertTrue("The list of speakers is not correct", check); + + Set outSpeakersActive = topologyClient.getAllExternalIPsOfType(E3Constant.E3SPEAKER_ACTIVE); + check = areEquals(outSpeakersActive, speakerList); + assertTrue("The list of active speakers must not have changed", check); + } + + @Test + public void testTopologyGatewayDownAndUp() { + // from the beginning there's one gateway down + String[] gatewayList = {"1.1.1.1", "1.1.1.3"}; + String[] gatewayActiveList = {"1.1.1.1", "1.1.1.3"}; + String[] speakerList = {"1.1.1.4"}; + + createTestResources(gatewayList, gatewayActiveList, speakerList); + + // run 2 cycles of topology watcher + topologyWatcher.init(); + + try { + Thread.sleep(POLLING_INTERVAL * 2 + POLLING_INTERVAL / 2); + + topologyWatcher.destroy(); + + // wait until it's stopped + Thread.sleep(POLLING_INTERVAL + POLLING_INTERVAL / 2); + } + catch (InterruptedException e) { + assertTrue("interrupted", false); + } + + // there must be one gateway down + boolean check; + + Set outGateways = topologyClient.getAllExternalIPsOfType(E3Constant.E3GATEWAY); + check = !outGateways.contains("1.1.1.2"); + assertTrue("The list of gateways must not contain the down gateway", check); + check = outGateways.contains("1.1.1.1") && outGateways.contains("1.1.1.3") && outGateways.size() == 2; + assertTrue("The list of gateways is not correct", check); + + Set outActiveGateways = topologyClient.getAllExternalIPsOfType(E3Constant.E3GATEWAY_ACTIVE); + check = !outActiveGateways.contains("1.1.1.2"); + assertTrue("The list of active gateways must not contain the down gateway", check); + check = outActiveGateways.contains("1.1.1.1") && outActiveGateways.contains("1.1.1.3") && outActiveGateways.size() == 2; + assertTrue("The list of active gateways is not correct", check); + + Set outSpeakers = topologyClient.getAllExternalIPsOfType(E3Constant.E3SPEAKER); + check = areEquals(outSpeakers, speakerList); + assertTrue("The list of speakers is not correct", check); + + Set outSpeakersActive = topologyClient.getAllExternalIPsOfType(E3Constant.E3SPEAKER_ACTIVE); + check = areEquals(outSpeakersActive, speakerList); + assertTrue("The list of active speakers must not have changed", check); + + // add one gateway + String[] newGatewayList = {"1.1.1.1", "1.1.1.2", "1.1.1.3"}; + setHealthCheckGateways(newGatewayList); + + // run 1 cycle of topology watcher + topologyWatcher.init(); + + try { + Thread.sleep(POLLING_INTERVAL * 2 + POLLING_INTERVAL / 2); + + topologyWatcher.destroy(); + + // wait until it's stopped + Thread.sleep(POLLING_INTERVAL + POLLING_INTERVAL / 2); + } + catch (InterruptedException e) { + assertTrue("interrupted", false); + } + + // all gateways must be up + outGateways = topologyClient.getAllExternalIPsOfType(E3Constant.E3GATEWAY); + check = areEquals(outGateways, newGatewayList); + assertTrue("The list of gateways is not correct", check); + + outActiveGateways = topologyClient.getAllExternalIPsOfType(E3Constant.E3GATEWAY_ACTIVE); + check = !outActiveGateways.contains("1.1.1.2"); + assertTrue("The list of active gateways must not contain the down gateway", check); + check = outActiveGateways.contains("1.1.1.1") && outActiveGateways.contains("1.1.1.3") && outActiveGateways.size() == 2; + assertTrue("The list of active gateways is not correct", check); + + outSpeakers = topologyClient.getAllExternalIPsOfType(E3Constant.E3SPEAKER); + check = areEquals(outSpeakers, speakerList); + assertTrue("The list of speakers is not correct", check); + + outSpeakersActive = topologyClient.getAllExternalIPsOfType(E3Constant.E3SPEAKER_ACTIVE); + check = areEquals(outSpeakersActive, speakerList); + assertTrue("The list of active speakers must not have changed", check); + + // make the gateway active + String[] newGatewayActiveList = {"1.1.1.1", "1.1.1.2", "1.1.1.3"}; + setHealthCheckGatewaysActive(newGatewayActiveList); + + // run 1 cycle of topology watcher + topologyWatcher.init(); + + try { + Thread.sleep(POLLING_INTERVAL * 2 + POLLING_INTERVAL / 2); + + topologyWatcher.destroy(); + + // wait until it's stopped + Thread.sleep(POLLING_INTERVAL + POLLING_INTERVAL / 2); + } + catch (InterruptedException e) { + assertTrue("interrupted", false); + } + + // all gateways must be up + outGateways = topologyClient.getAllExternalIPsOfType(E3Constant.E3GATEWAY); + check = areEquals(outGateways, newGatewayList); + assertTrue("The list of gateways is not correct", check); + + outActiveGateways = topologyClient.getAllExternalIPsOfType(E3Constant.E3GATEWAY_ACTIVE); + check = areEquals(outActiveGateways, newGatewayActiveList); + assertTrue("The list of gateways is not correct", check); + + outSpeakers = topologyClient.getAllExternalIPsOfType(E3Constant.E3SPEAKER); + check = areEquals(outSpeakers, speakerList); + assertTrue("The list of speakers is not correct", check); + + outSpeakersActive = topologyClient.getAllExternalIPsOfType(E3Constant.E3SPEAKER_ACTIVE); + check = areEquals(outSpeakersActive, speakerList); + assertTrue("The list of active speakers must not have changed", check); + } + + @Test + public void testTopologySpeakerDownAndUp() { + // from the beginning there's one speaker down + String[] gatewayList = {"1.1.1.1", "1.1.1.2", "1.1.1.3"}; + String[] gatewayActiveList = {"1.1.1.1", "1.1.1.2", "1.1.1.3"}; + String[] speakerBaseList = {"1.1.1.4"}; + String[] speakerList = {}; + + createTestResources(gatewayList, gatewayActiveList, speakerList); + + // run 1 cycle of topology watcher + topologyWatcher.init(); + + try { + Thread.sleep(POLLING_INTERVAL * 2 + POLLING_INTERVAL / 2); + + topologyWatcher.destroy(); + + // wait until it's stopped + Thread.sleep(POLLING_INTERVAL + POLLING_INTERVAL / 2); + } + catch (InterruptedException e) { + assertTrue("interrupted", false); + } + + // there must be one speaker down + boolean check; + + Set outGateways = topologyClient.getAllExternalIPsOfType(E3Constant.E3GATEWAY); + check = areEquals(outGateways, gatewayList); + assertTrue("The list of gateways is not correct", check); + + Set outActiveGateways = topologyClient.getAllExternalIPsOfType(E3Constant.E3GATEWAY_ACTIVE); + check = areEquals(outActiveGateways, gatewayActiveList); + assertTrue("The list of active gateways is not correct", check); + + Set outSpeakers = topologyClient.getAllExternalIPsOfType(E3Constant.E3SPEAKER); + check = areEquals(outSpeakers, speakerBaseList); + assertTrue("The list of speakers is not correct", check); + + Set outSpeakersActive = topologyClient.getAllExternalIPsOfType(E3Constant.E3SPEAKER_ACTIVE); + check = outSpeakersActive.size() == 0; + assertTrue("The list of active speakers must be empty", check); + + // add one speaker + String[] newSpeakerList = {"1.1.1.4"}; + setHealthCheckSpeakers(newSpeakerList); + + // run 1 cycle of topology watcher + topologyWatcher.init(); + + try { + Thread.sleep(POLLING_INTERVAL * 2 + POLLING_INTERVAL / 2); + + topologyWatcher.destroy(); + + // wait until it's stopped + Thread.sleep(POLLING_INTERVAL + POLLING_INTERVAL / 2); + } + catch (InterruptedException e) { + assertTrue("interrupted", false); + } + + // there must be one new speaker + outGateways = topologyClient.getAllExternalIPsOfType(E3Constant.E3GATEWAY); + check = areEquals(outGateways, gatewayList); + assertTrue("The list of gateways is not correct", check); + + outActiveGateways = topologyClient.getAllExternalIPsOfType(E3Constant.E3GATEWAY_ACTIVE); + check = areEquals(outActiveGateways, gatewayActiveList); + assertTrue("The list of active gateways is not correct", check); + + outSpeakers = topologyClient.getAllExternalIPsOfType(E3Constant.E3SPEAKER); + check = areEquals(outSpeakers, speakerBaseList); + assertTrue("The list of speakers is not correct", check); + + outSpeakers = topologyClient.getAllExternalIPsOfType(E3Constant.E3SPEAKER_ACTIVE); + check = areEquals(outSpeakers, newSpeakerList); + assertTrue("The list of speakers is not correct", check); + + // remove the speaker + setHealthCheckSpeakers(speakerList); + + // run 1 cycle of topology watcher + topologyWatcher.init(); + + try { + Thread.sleep(POLLING_INTERVAL * 2 + POLLING_INTERVAL / 2); + + topologyWatcher.destroy(); + + // wait until it's stopped + Thread.sleep(POLLING_INTERVAL + POLLING_INTERVAL / 2); + } + catch (InterruptedException e) { + assertTrue("interrupted", false); + } + + outGateways = topologyClient.getAllExternalIPsOfType(E3Constant.E3GATEWAY); + check = areEquals(outGateways, gatewayList); + assertTrue("The list of gateways is not correct", check); + + outActiveGateways = topologyClient.getAllExternalIPsOfType(E3Constant.E3GATEWAY_ACTIVE); + check = areEquals(outActiveGateways, gatewayActiveList); + assertTrue("The list of active gateways is not correct", check); + + outSpeakers = topologyClient.getAllExternalIPsOfType(E3Constant.E3SPEAKER); + check = areEquals(outSpeakers, speakerBaseList); + assertTrue("The list of speakers is not correct", check); + + outSpeakersActive = topologyClient.getAllExternalIPsOfType(E3Constant.E3SPEAKER_ACTIVE); + check = outSpeakersActive.size() == 0; + assertTrue("The list of active speakers must be empty", check); + } +} + + diff --git a/exposure-engine/topology/src/test/java/com/alu/e3/tests/topologywatcher/DummyHealCheckService.java b/exposure-engine/topology/src/test/java/com/alu/e3/tests/topologywatcher/DummyHealCheckService.java new file mode 100644 index 0000000..502525a --- /dev/null +++ b/exposure-engine/topology/src/test/java/com/alu/e3/tests/topologywatcher/DummyHealCheckService.java @@ -0,0 +1,50 @@ +/** + * Copyright © 2012 Alcatel-Lucent. + * + * See the NOTICE file distributed with this work for additional + * information regarding copyright ownership. + * Licensed to you 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 com.alu.e3.tests.topologywatcher; + +import com.alu.e3.data.IHealthCheckService; + +public class DummyHealCheckService implements IHealthCheckService { + + private String type; + private DummyHealthCheckFactory factory; + + public DummyHealCheckService(String type, DummyHealthCheckFactory factory) { + this.type = type; + this.factory = factory; + } + + @Override + public void start() { + // must not be called + throw new RuntimeException(); + } + + @Override + public void stop() { + // must not be called + throw new RuntimeException(); + } + + @Override + public boolean check(String ip) { + return factory.check(type, ip); + } + +} diff --git a/exposure-engine/topology/src/test/java/com/alu/e3/tests/topologywatcher/DummyHealthCheckFactory.java b/exposure-engine/topology/src/test/java/com/alu/e3/tests/topologywatcher/DummyHealthCheckFactory.java new file mode 100644 index 0000000..135fc10 --- /dev/null +++ b/exposure-engine/topology/src/test/java/com/alu/e3/tests/topologywatcher/DummyHealthCheckFactory.java @@ -0,0 +1,63 @@ +/** + * Copyright © 2012 Alcatel-Lucent. + * + * See the NOTICE file distributed with this work for additional + * information regarding copyright ownership. + * Licensed to you 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 com.alu.e3.tests.topologywatcher; + +import java.util.HashSet; +import java.util.Set; + +import com.alu.e3.common.osgi.api.IHealthCheckFactory; +import com.alu.e3.data.IHealthCheckService; + +public class DummyHealthCheckFactory implements IHealthCheckFactory { + + private Set gatewaysActive = new HashSet(); + private Set gateways = new HashSet(); + private Set speakers = new HashSet(); + + public void setGatewaysActive(Set gateways) { + this.gatewaysActive = gateways; + } + + public void setGateways(Set gateways) { + this.gateways = gateways; + } + + public void setSpeakers(Set speakers) { + this.speakers = speakers; + } + + @Override + public IHealthCheckService getHealthCheckService(String instanceType) { + return new DummyHealCheckService(instanceType, this); + } + + public boolean check(String instanceType, String ip) { + if (instanceType.equals(IHealthCheckFactory.GATEWAY_INTERNAL_TYPE)) { + return gateways.contains(ip); + } + else if (instanceType.equals(IHealthCheckFactory.GATEWAY_TYPE)) { + return gatewaysActive.contains(ip); + } + else if (instanceType.equals(IHealthCheckFactory.SPEAKER_TYPE)) { + return speakers.contains(ip); + } + + return false; + } +} diff --git a/exposure-engine/topology/src/test/java/com/alu/e3/tests/topologywatcher/DummyTopologyClient.java b/exposure-engine/topology/src/test/java/com/alu/e3/tests/topologywatcher/DummyTopologyClient.java new file mode 100644 index 0000000..8948e31 --- /dev/null +++ b/exposure-engine/topology/src/test/java/com/alu/e3/tests/topologywatcher/DummyTopologyClient.java @@ -0,0 +1,248 @@ +/** + * Copyright © 2012 Alcatel-Lucent. + * + * See the NOTICE file distributed with this work for additional + * information regarding copyright ownership. + * Licensed to you 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 com.alu.e3.tests.topologywatcher; + +import java.util.ArrayList; +import java.util.HashSet; +import java.util.Iterator; +import java.util.LinkedList; +import java.util.List; +import java.util.Set; + +import com.alu.e3.common.E3Constant; +import com.alu.e3.common.caching.ICacheManager; +import com.alu.e3.common.caching.IEntryListener; +import com.alu.e3.common.osgi.api.ITopologyClient; +import com.alu.e3.data.model.Instance; +import com.alu.e3.data.topology.IInstanceListener; +import com.alu.e3.data.topology.InstanceEvent; + +public class DummyTopologyClient implements ITopologyClient { + + private List gateways = new LinkedList(); + private List gatewaysActive = new LinkedList(); + private List speakers = new LinkedList(); + private List speakersActive = new LinkedList(); + + public void setGateways(List gateways) { + this.gateways = gateways; + } + + public void setSpeakers(List speakers) { + this.speakers = speakers; + } + + @Override + public void setCacheManager(ICacheManager cacheManager) { + // must not be called + throw new RuntimeException(); + } + + @Override + public void addInstance(Instance inst) { + if (inst.getType().equals(E3Constant.E3GATEWAY)) { + gateways.add(inst); + } + else if (inst.getType().equals(E3Constant.E3GATEWAY_ACTIVE)) { + gatewaysActive.add(inst); + } + else if (inst.getType().equals(E3Constant.E3SPEAKER)) { + speakers.add(inst); + } + else if (inst.getType().equals(E3Constant.E3SPEAKER_ACTIVE)) { + speakersActive.add(inst); + } + + fireInstanceAdded(new InstanceEvent(inst)); + } + + @Override + public boolean deleteInstance(Instance inst) { + List list = null; + + if (inst.getType().equals(E3Constant.E3GATEWAY)) { + list = gateways; + } + else if (inst.getType().equals(E3Constant.E3GATEWAY_ACTIVE)) { + list = gatewaysActive; + } + else if (inst.getType().equals(E3Constant.E3SPEAKER)) { + list = speakers; + } + else if (inst.getType().equals(E3Constant.E3SPEAKER_ACTIVE)) { + list = speakersActive; + } + + if (list == null) + return false; + + Iterator itr = list.iterator(); + while (itr.hasNext()) { + if (itr.next().getInternalIP().equals(inst.getInternalIP())) { + itr.remove(); + fireInstanceRemoved(new InstanceEvent(inst)); + return true; + } + } + return false; + + } + + @Override + public void addInstanceTypeListener(IEntryListener> listener) { + // must not be called + throw new RuntimeException(); + } + + @Override + public void removeInstanceTypeListener(IEntryListener> listener) { + // must not be called + throw new RuntimeException(); + } + + private LinkedList listeners = new LinkedList(); + + @Override + public void addInstanceListener(IInstanceListener listener) { + listeners.add(listener); + } + + @Override + public void removeInstanceListener(IInstanceListener listener) { + listeners.remove(listener); + } + + private void fireInstanceAdded(InstanceEvent event) { + for (IInstanceListener listener : listeners) { + listener.instanceAdded(event); + } + } + + private void fireInstanceRemoved(InstanceEvent event) { + for (IInstanceListener listener : listeners) { + listener.instanceRemoved(event); + } + } + + @Override + public Set getAllExternalIPsOfType(String type) { + List instances; + + if (type.equals(E3Constant.E3GATEWAY)) { + instances = gateways; + } + else if (type.equals(E3Constant.E3SPEAKER)) { + instances = speakers; + } + else if (type.equals(E3Constant.E3GATEWAY_ACTIVE)) { + instances = gatewaysActive; + } + else if (type.equals(E3Constant.E3SPEAKER_ACTIVE)) { + instances = speakersActive; + } + else { + return null; + } + + Set ips = new HashSet(); + + for (Instance instance : instances) { + ips.add(instance.getExternalIP()); + } + + return ips; + } + + @Override + public Set getAllInternalIPsOfType(String type) { + // must not be called + throw new RuntimeException(); + } + + @Override + public List getAllInstancesOfType(String type) { + if (type.equals(E3Constant.E3GATEWAY)) { + return gateways; + } + else if (type.equals(E3Constant.E3SPEAKER)) { + return speakers; + } + else if (type.equals(E3Constant.E3GATEWAY_ACTIVE)) { + return gatewaysActive; + } + else if (type.equals(E3Constant.E3SPEAKER_ACTIVE)) { + return speakersActive; + } + return null; + } + + @Override + public Set getExternalIPsOfType(String type, String area) { + // must not be called + throw new RuntimeException(); + } + + @Override + public Set getInternalIPsOfType(String type, String area) { + // must not be called + throw new RuntimeException(); + } + + @Override + public List getInstancesOfType(String type, String area) { + // must not be called + throw new RuntimeException(); + } + + @Override + public String getMyArea() { + return "myArea"; + } + + @Override + public Set getAllAreas() { + // must not be called + throw new RuntimeException(); + } + + @Override + public Set getAllOtherAreas() { + // must not be called + throw new RuntimeException(); + } + + @Override + public void addAreas(Set areas) { + // TODO Auto-generated method stub + throw new RuntimeException(); + } + + @Override + public void setMyArea(String area) { + // TODO Auto-generated method stub + throw new RuntimeException(); + } + + @Override + public Instance whoAmI(String type) { + // TODO Auto-generated method stub + return null; + } + +} \ No newline at end of file diff --git a/maven/settings.xml b/maven/settings.xml new file mode 100644 index 0000000..bdc37e9 --- /dev/null +++ b/maven/settings.xml @@ -0,0 +1,42 @@ + + + + + + + UK + UK Central + http://central.maven.org/maven2 + central, maven-central-repository + + + + + + e3-repository + + true + + + + + com.springsource.repository.bundles.external + SpringSource Enterprise Bundle Repository - External Bundle Releases + http://repository.springsource.com/maven/bundles/external + + + maven + maven Repository + http://repo2.maven.org/maven2 + + + Fuse Source + Fuse Source Repository + http://repo.fusesource.com/nexus/content/groups/public/ + + + + + diff --git a/packaging/src/main/assembly/main.xml b/packaging/src/main/assembly/main.xml new file mode 100644 index 0000000..aa3e79f --- /dev/null +++ b/packaging/src/main/assembly/main.xml @@ -0,0 +1,119 @@ + + main + + tar.gz + + false + + + + + + com.alu.e3:e3-bundle + + + false + bundles + false + + + + + + + ${basedir}/packaging/src/main/resources + bin + + *.sh + + + + + ${basedir}/packaging/src/main/resources/defaults + defaults + + e3.default.key + e3.default.crt + + + + thirdparty-dependencies + + + tools + + + + ${basedir}/Licenses + Licenses + + * + + + + + + + ${basedir}/LICENSE + / + + + ${basedir}/NOTICE + / + + + + ${basedir}/exposure-engine/common/src/main/java/com/alu/e3/common/tools/CanonicalizedIpAddress.java + Licenses/src/com/alu/e3/common/tools + + + ${basedir}/target/classes/Template_features.xml + features + features.xml + + + ${basedir}/packaging/src/main/resources/karaf-wrapper.conf + bin + + + ${basedir}/packaging/src/main/resources/config.properties + bin + + + ${basedir}/packaging/src/main/resources/aib_topology.xml + bin + + + ${basedir}/packaging/src/main/resources/aib_system_topology.xml + bin + + + ${basedir}/packaging/src/main/resources/configuration-defaults.properties + bin + + + ${basedir}/target/classes/template-installer-config.xml + templates + template-installer-config.xml + + + ${basedir}/packaging/src/main/resources/template-topology_cluster.xml + templates + + + ${basedir}/packaging/src/main/resources/template-system_topology_cluster.xml + templates + + + + + + org.bouncycastle:bcprov-jdk16 + + bundles + + + \ No newline at end of file diff --git a/packaging/src/main/resources/Template_features.xml b/packaging/src/main/resources/Template_features.xml new file mode 100644 index 0000000..5d77ecc --- /dev/null +++ b/packaging/src/main/resources/Template_features.xml @@ -0,0 +1,25 @@ + + + + camel-core + mvn:org.apache.httpcomponents/httpcore-osgi/4.1.2 + mvn:org.apache.httpcomponents/httpclient-osgi/4.1.2 + mvn:org.apache.geronimo.specs/geronimo-servlet_3.0_spec/1.0 + mvn:org.apache.camel/camel-http4/2.6.0-fuse-01-09 + + + camel-jetty + camel-cxf + camel-freemarker + camel-http4-patched + + + file:$$PATH$$/../bundles/bcprov-jdk16-1.46.jar + + + file:$$PATH$$/../bundles/e3-bundle-${e3.package.version}.jar + E3-std-deps + E3-JCE-provider + + + diff --git a/packaging/src/main/resources/aib_system_topology.xml b/packaging/src/main/resources/aib_system_topology.xml new file mode 100644 index 0000000..aa3e243 --- /dev/null +++ b/packaging/src/main/resources/aib_system_topology.xml @@ -0,0 +1,15 @@ + + + + + + + + + + + + + + + \ No newline at end of file diff --git a/packaging/src/main/resources/aib_topology.xml b/packaging/src/main/resources/aib_topology.xml new file mode 100644 index 0000000..c1c8651 --- /dev/null +++ b/packaging/src/main/resources/aib_topology.xml @@ -0,0 +1,29 @@ + + + + + + + + + + + + + + + + + + + + + + + + + + + + + \ No newline at end of file diff --git a/packaging/src/main/resources/config.properties b/packaging/src/main/resources/config.properties new file mode 100644 index 0000000..45a8049 --- /dev/null +++ b/packaging/src/main/resources/config.properties @@ -0,0 +1,92 @@ +################################################################################ +# +# Licensed to the Apache Software Foundation (ASF) under one or more +# contributor license agreements. See the NOTICE file distributed with +# this work for additional information regarding copyright ownership. +# The ASF licenses this file to You 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. +# +################################################################################ + +# +# Properties file inclusions (as a space separated list of relative paths) +# Included files will override the values specified in this file +# +${includes} = jre.properties custom.properties + +# +# Framework selection properties +# +karaf.framework=felix + +# +# Location of the OSGi frameworks +# +karaf.framework.equinox=${karaf.default.repository}/org/eclipse/osgi/3.6.0.v20100517/osgi-3.6.0.v20100517.jar +karaf.framework.felix=${karaf.default.repository}/org/apache/felix/org.apache.felix.framework/3.0.2/org.apache.felix.framework-3.0.2.jar + +# +# Framework config properties. +# +org.osgi.framework.system.packages=org.osgi.framework; version=1.5.0, \ + org.osgi.framework.launch; version=1.0.0, \ + org.osgi.framework.hooks.service; version=1.0.0, \ + org.osgi.service.packageadmin; version=1.2.0, \ + org.osgi.service.startlevel; version=1.1.0, \ + org.osgi.service.url; version=1.0.0, \ + org.osgi.util.tracker; version=1.4.0, \ + org.apache.karaf.jaas.boot; version=2.1.4.fuse-00-09, \ + org.apache.karaf.version; version=2.1.4.fuse-00-09, \ + ${jre-${java.specification.version}} + +org.osgi.framework.system.packages.extra=org.bouncycastle.math.ec; version=1.46, \ +org.bouncycastle.jce.provider; version=1.46 + +org.apache.felix.karaf.security.providers=org.bouncycastle.jce.provider.BouncyCastleProvider + +# javax.transaction is needed to avoid class loader constraint violation when using javax.sql +org.osgi.framework.bootdelegation=org.apache.karaf.jaas.boot,sun.*,com.sun.*,javax.transaction,javax.transaction.*,org.bouncycastle.* + +# OSGi Execution Environment +org.osgi.framework.executionenvironment=JavaSE-1.6,J2SE-1.5,J2SE-1.4,J2SE-1.3,J2SE-1.2 + +# Set the parent classloader for the bundle to the classloader that loads the Framework (i.e. everything in lib/*.jar) +org.osgi.framework.bundle.parent=framework + +# To enable the use of the startup.properties file to control the start level: +karaf.auto.start=startup.properties + +org.osgi.framework.startlevel.beginning=100 +karaf.startlevel.bundle=60 + +karaf.shutdown.port.file=${karaf.data}/port + +# +# FileMonitor properties +# +felix.fileinstall.dir = ${karaf.base}/etc +felix.fileinstall.filter = .*\\.cfg +felix.fileinstall.poll = 1000 +felix.fileinstall.noInitialDelay = true + +# +# Delay for writing the framework state to disk in equinox +# must be >= 1000 and <= 1800000 +# +eclipse.stateSaveDelayInterval = 1000 + +# +# OBR Repository list +# This property will be modified by the obr:addUrl and obr:removeUrl commands. +# +obr.repository.url = + diff --git a/packaging/src/main/resources/configSystem.sh b/packaging/src/main/resources/configSystem.sh new file mode 100644 index 0000000..c3eaedb --- /dev/null +++ b/packaging/src/main/resources/configSystem.sh @@ -0,0 +1,274 @@ +#!/bin/bash + +ABS_PATH_NAME=$(readlink -f $0) +DIR=`dirname $ABS_PATH_NAME` + +source $DIR/variables.sh +export JAVA_HOME=/usr/java/default + +# Non-Java (syslog) Logging: +# Setup initial syslog configuration, and give the e3 user permissions to change things +function e3_syslog_setup { + + E3_SYSLOG_FACILITY="local3" + SYSLOG_FILE="/var/log/e3syslog.log" + TMP_DIR="$E3_HOME/tmp" + E3_SECTION_START_LINE="# E3 NON-JAVA LOGGING BEGIN" + E3_SECTION_END_LINE="# E3 NON-JAVA LOGGING END" + + # Determine if syslog config is at /etc/syslog.conf or /etc/rsyslog.conf + echo "Setting up E3-specific syslog logging" + SYSLOG="UNDETERMINED" + if [ -f /etc/rsyslog.conf ] + then + SYSLOG="rsyslog" + elif [ -f /etc/syslog.conf ] + then + SYSLOG="syslog" + else + echo "Could not find syslog configuration!" + return + fi + + # Modify sudoers so e3 can adjust log level settings + # If our changes from a previous install are present, delete them + cp /etc/sudoers /etc/sudoers.e3save + chown --reference=/etc/sudoers /etc/sudoers.e3save + START_LINE_NO=`grep -n "$E3_SECTION_START_LINE" /etc/sudoers | cut -d ":" -f1` + END_LINE_NO=`grep -n "$E3_SECTION_END_LINE" /etc/sudoers | cut -d ":" -f1` + if [ ! -z $START_LINE_NO ] && [ ! -z $END_LINE_NO ] && [ $START_LINE_NO -lt $END_LINE_NO ] + then + echo "Deleting previous E3-specific rules from /etc/sudoers (lines $START_LINE_NO to $END_LINE_NO)" + sed -i "/$E3_SECTION_START_LINE/,/$E3_SECTION_END_LINE/d" /etc/sudoers + else + # On a new install, make a little space + echo "" >> /etc/sudoers + fi + + echo "Writing changes to /etc/sudoers" + cat >> /etc/sudoers <<-EOF + $E3_SECTION_START_LINE + Defaults:e3 !requiretty + e3 ALL=(ALL) NOPASSWD:/bin/cp $TMP_DIR/e3syslog.conf /etc/${SYSLOG}.conf + e3 ALL=(ALL) NOPASSWD:/etc/init.d/$SYSLOG restart + e3 ALL=(ALL) NOPASSWD:/bin/cp $TMP_DIR/e3logrotate.conf /etc/logrotate.d/e3 + $E3_SECTION_END_LINE + EOF + + # Create an e3-specific logrotate file + echo "Initializing logrotate config at /etc/logrotate.d/e3" + cat > /etc/logrotate.d/e3 <<-EOF + $SYSLOG_FILE { + missingok + notifempty + daily + create 0660 e3 root + dateext + dateformat .%Y%m%d + } + EOF + + # Make the logrotate file writable by user e3 + chown e3:root /etc/logrotate.d/e3 + chmod 0660 /etc/logrotate.d/e3 + + # Modify syslog config to write to an e3-specific logfile + # If our changes from a previous install are present, delete them + cp /etc/${SYSLOG}.conf /etc/${SYSLOG}.conf.e3save + chown --reference=/etc/${SYSLOG}.conf /etc/${SYSLOG}.conf.e3save + START_LINE_NO=`grep -n "$E3_SECTION_START_LINE" /etc/${SYSLOG}.conf | cut -d ":" -f1` + END_LINE_NO=`grep -n "$E3_SECTION_END_LINE" /etc/${SYSLOG}.conf | cut -d ":" -f1` + if [ ! -z $START_LINE_NO ] && [ ! -z $END_LINE_NO ] && [ $START_LINE_NO -lt $END_LINE_NO ] + then + echo "Deleting previous E3-specific rules from /etc/${SYSLOG}.conf (lines $START_LINE_NO to $END_LINE_NO)" + sed -i "/$E3_SECTION_START_LINE/,/$E3_SECTION_END_LINE/d" /etc/${SYSLOG}.conf + else + # On a new install, make a little space + echo "" >>/etc/${SYSLOG}.conf + fi + + echo "Writing changes to /etc/${SYSLOG}.conf" + cat >> /etc/${SYSLOG}.conf <<-EOF + $E3_SECTION_START_LINE + # E3-specific rule: do not change the facility ($E3_SYSLOG_FACILITY) or log-file path without reading logging documentation + ${E3_SYSLOG_FACILITY}.DEBUG $SYSLOG_FILE + $E3_SECTION_END_LINE + EOF + + # Initialize syslog file so that the e3 user can read + touch $SYSLOG_FILE + chown e3:root $SYSLOG_FILE + chmod 0660 $SYSLOG_FILE + + # Restart syslog daemon to activate new settings, and log one line to test the setup + echo "Restarting syslog daemon" + /etc/init.d/$SYSLOG restart + sleep 2 + logger -p ${E3_SYSLOG_FACILITY}.debug -t "E3" "E3-specific syslog logging configured for facility: $E3_SYSLOG_FACILITY" + +} # end e3_syslog_setup + +# Set up E3 (com.alu.e3) Java logging +function e3_paxlogging_setup { + + # Modify servicemix's config to log E3 java output (from com.alu.e3) + # to a specific location and with specific settings + SMX_DIR="$E3_HOME/$SMX_LINK_DIRNAME" + SMX_CFG="$SMX_DIR/etc/org.ops4j.pax.logging.cfg" + E3_SECTION_START_LINE="# E3 appender start" + E3_SECTION_END_LINE="# E3 appender end" + + if [ ! -f $SMX_CFG ] + then + echo "Could not find ServiceMix logging configuration where expected: $SMX_CFG" + return + fi + + # Save a version of config file before our modifications + cp $SMX_CFG ${SMX_CFG}.e3save + chown --reference=$SMX_CFG ${SMX_CFG}.e3save + + # If our changes from a previous install are present, delete them + START_LINE_NO=`grep -n "$E3_SECTION_START_LINE" $SMX_CFG | cut -d ":" -f1` + END_LINE_NO=`grep -n "$E3_SECTION_END_LINE" $SMX_CFG | cut -d ":" -f1` + if [ ! -z $START_LINE_NO ] && [ ! -z $END_LINE_NO ] && [ $START_LINE_NO -lt $END_LINE_NO ] + then + echo "Deleting previous E3-specific rules from $SMX_CFG (lines $START_LINE_NO to $END_LINE_NO)" + sed -i "/$E3_SECTION_START_LINE/,/$E3_SECTION_END_LINE/d" $SMX_CFG + else + # On a new install, make a little space + echo "" >>$SMX_CFG + fi + + # Make sure SMX appender uses daily-rolling + echo "Writing changes to $SMX_CFG" + sed -i "s/^log4j.appender.out=org.apache.log4j.RollingFileAppender/log4j.appender.out=org.apache.log4j.DailyRollingFileAppender\nlog4j.appender.out.DatePattern='.'yyyy-MM-dd-HH/ + /^log4j.appender.out.maxFileSize=/d + /^log4j.appender.out.maxBackupIndex=/d" $SMX_CFG + + # Add new E3Appender section + cat >> $SMX_CFG <<-EOF + $E3_SECTION_START_LINE + log4j.appender.E3Appender=org.apache.log4j.DailyRollingFileAppender + log4j.appender.E3Appender.layout=org.apache.log4j.PatternLayout + log4j.appender.E3Appender.layout.ConversionPattern= %-5p %d %-20c [%L] - %m%n + log4j.appender.E3Appender.file=$SMX_DIR/data/log/e3.log + log4j.appender.E3Appender.append=true + log4j.appender.E3Appender.DatePattern='.'yyyy-MM-dd-HH + log4j.appender.E3Appender.threshold=INFO + log4j.logger.com.alu.e3=INFO, E3Appender + log4j.additivity.com.alu.e3=false + $E3_SECTION_END_LINE + EOF + +} # end e3_paxlogging_setup + + +# Beginning of the script + +if [[ $# < 1 ]] +then + echo "Missing input parameter." + exit 1 +fi + +serviceMixOk=0 +for n in `seq 1 2` +do + $E3_HOME/$SMX_LINK_DIRNAME/bin/client -p $SMX_PWD -u $SMX_USER " " + if [[ ${?} != 0 ]] + then + # unable to connect: wait and retry + sleep 3 + else + serviceMixOk=1 + break + fi + +done + +if [[ $serviceMixOk == 0 ]] +then + echo "Servicemix not started -- trying to start " + service karaf-service start + sleep 5 +fi + +eval '$E3_HOME/$SMX_LINK_DIRNAME/bin/client -p $SMX_PWD -u $SMX_USER "features:addurl file:$FEATURES"' 2>&1 +if [[ ${?} != 0 ]] +then + echo "Unable to add the feature url" + exit 1 +fi + +sleep 2 +eval '$E3_HOME/$SMX_LINK_DIRNAME/bin/client -p $SMX_PWD -u $SMX_USER "features:uninstall E3"' 2>&1 +if [[ ${?} != 0 ]] +then + echo "Unable to uninstall the feature: E3" + exit 1 +fi +sleep 2 +eval '$E3_HOME/$SMX_LINK_DIRNAME/bin/client -p $SMX_PWD -u $SMX_USER "features:install E3"' 2>&1 +if [[ ${?} != 0 ]] +then + echo "Unable to install the feature: E3" + exit 1 +fi + +# refreshing fuse feature urls +eval '$E3_HOME/$SMX_LINK_DIRNAME/bin/client -p $SMX_PWD -u $SMX_USER "features:refreshurl"' 2>&1 +if [[ ${?} != 0 ]] +then + echo "Unable to fresh feature urls" + exit 1 +fi + +# Affect hostname manually if respond on 127.0.0.1 for RMI connections +if ! grep -lir "Binding external IP version 1.0" /etc/rc.local +then + cat >> /etc/rc.local <<'HEREDOC' +# Affect hostname manually if respond on 127.0.0.1 for RMI connections +# Binding external IP version 1.0 +if [ `hostname -i` = "127.0.0.1" ] +then + if [ ! -f /root/e3ipaddresshistory ] + then + oldipaddress=`ifconfig eth0 | sed -n 's/.*inet *addr:\([0-9\.]*\).*/\1/p'` + else + oldipaddress=`cat /root/e3ipaddresshistory` + fi + + echo `ifconfig eth0 | sed -n 's/.*inet *addr:\([0-9\.]*\).*/\1/p'` > /root/e3ipaddresshistory + + hostnameline=`sed -n "s/$oldipaddress\(.*\)/\1/p" /etc/hosts` + hostnameline=`echo $hostnameline` + if [ "$hostnameline" = "e3hostname" ] + then + sed -i '/e3hostname/d' /etc/hosts + else + sed -i 's/e3hostname//' /etc/hosts + fi + + ipaddress=`ifconfig eth0 | sed -n 's/.*inet *addr:\([0-9\.]*\).*/\1/p'` + + ipline=`sed -n "s/\($ipaddress\)/\1/p" /etc/hosts` + if [ "$ipline" = "" ] + then + echo "$ipaddress e3hostname" >> /etc/hosts + else + sed -i "/$ipaddress/ s/\(.*[a-zA-Z0-9]\)\( *$\)/\1 e3hostname/g" /etc/hosts + fi + + hostname e3hostname + /etc/init.d/karaf-service restart +fi +HEREDOC + /etc/rc.local +fi + +# Logging setup for both E3-specific syslog and Java logging +e3_syslog_setup +e3_paxlogging_setup + +exit 0 diff --git a/packaging/src/main/resources/configuration-defaults.properties b/packaging/src/main/resources/configuration-defaults.properties new file mode 100644 index 0000000..9bf22ee --- /dev/null +++ b/packaging/src/main/resources/configuration-defaults.properties @@ -0,0 +1,22 @@ +e3.manager=false +e3.gateway=false + +e3.keystore.path=data/keystore.bks +e3.keystore.password=PASSWORD + +# This password (used to encrypt keys in the keystore) must not be longer than 7 characters!!! +e3.keystore.keypassword=PASSWRD + +e3.truststore.path=data/truststore.bks +e3.truststore.password=PASSWORD + +# Basic Auth security. Values are true or false +e3.provisioning.restapi.security.basicauth.enable=false +e3.provisioning.restapi.security.basicauth.username=USERNAME +e3.provisioning.restapi.security.basicauth.password=PASSWORD + +provisioning.working.dir=data/PROVISIONING_WORKING_DIR +provisioning.archive.dir=DEPLOYED +provisioning.generate.jar.in.file=false + +default.key.cert.directory=${user.home}/.grove \ No newline at end of file diff --git a/packaging/src/main/resources/configureSecurity.sh b/packaging/src/main/resources/configureSecurity.sh new file mode 100644 index 0000000..2639923 --- /dev/null +++ b/packaging/src/main/resources/configureSecurity.sh @@ -0,0 +1,41 @@ +#!/bin/bash + +ABS_PATH_NAME=$(readlink -f $0) +DIR=`dirname $ABS_PATH_NAME` + + +# Clean iptables + +iptables -F +iptables -t nat -F + +# Create custom firewall rule + +iptables -N 'E3-Firewall-INPUT' + +iptables -A INPUT -j E3-Firewall-INPUT +iptables -A FORWARD -j E3-Firewall-INPUT + +# Add standard rules + +iptables -A E3-Firewall-INPUT -i lo -j ACCEPT +iptables -A E3-Firewall-INPUT -p tcp -m state --state NEW -m tcp --dport 22 -j ACCEPT +iptables -A E3-Firewall-INPUT -m state --state RELATED,ESTABLISHED -j ACCEPT + +# SNMP +if [ -e $DIR/install_snmp.sh ] ; then + iptables -A E3-Firewall-INPUT -p udp --dport 161 -j ACCEPT +fi + +# NetBIOS +iptables -A E3-Firewall-INPUT -p udp --dport 137 -j ACCEPT + +# Block all other requests +iptables -A E3-Firewall-INPUT -j REJECT --reject-with icmp-host-prohibited + +# Manager/Gateway specific rules are added in "generateNature.sh" + +service iptables save +service iptables restart + +exit 0 diff --git a/packaging/src/main/resources/copyFiles.sh b/packaging/src/main/resources/copyFiles.sh new file mode 100644 index 0000000..7f69ea3 --- /dev/null +++ b/packaging/src/main/resources/copyFiles.sh @@ -0,0 +1,45 @@ +#!/bin/bash + +ABS_PATH_NAME=$(readlink -f $0) +DIR=`dirname $ABS_PATH_NAME` + +source $DIR/variables.sh + +if [ ! -n "$BUNDLES" ] +then + echo "Unable to find the directory BUNDLES_SRC in zip " $BUNDLES_SRC +exit 1 +fi + +if [ ! -n "$FEATURES" ] +then + echo "Unable to find FEATURE_SRC in zip " $FEATURE_SRC +exit 1 +fi + +# replace PATH in the feature file +SEARCH_STRING="\\$\\\$PATH\\$\\$" + +REPLACE_STRING=$DIR + +FILE=$FEATURES + +EXPR="s#${SEARCH_STRING}#${REPLACE_STRING}#g" + +sed -i -e $EXPR $FILE + +# Default Key/Cert file installation ... +DEFAULT_KEY_CERT_LOCATION=$E3_HOME/.grove +echo "Installing default Key/Cert in $DEFAULT_KEY_CERT_LOCATION ..." + +mkdir -p $DEFAULT_KEY_CERT_LOCATION +cp -f $DIR/../defaults/e3.default.crt $DIR/../defaults/e3.default.key $DEFAULT_KEY_CERT_LOCATION +# Let the owner be the root user +chown -R root:$USER $DEFAULT_KEY_CERT_LOCATION + +# Root keep all access +# Grove user only have execute (intering the directory) +chmod 710 $DEFAULT_KEY_CERT_LOCATION +chmod 640 $DEFAULT_KEY_CERT_LOCATION/e3.default.crt $DEFAULT_KEY_CERT_LOCATION/e3.default.key + +exit 0 diff --git a/packaging/src/main/resources/defaults/e3.default.crt b/packaging/src/main/resources/defaults/e3.default.crt new file mode 100644 index 0000000..93f77af --- /dev/null +++ b/packaging/src/main/resources/defaults/e3.default.crt @@ -0,0 +1,17 @@ +-----BEGIN CERTIFICATE----- +MIICuzCCAiQCCQDxj0dkEy3MLzANBgkqhkiG9w0BAQUFADCBoTELMAkGA1UEBhMC +VVMxEzARBgNVBAgTCkNhbGlmb3JuaWExEzARBgNVBAcTClNhbnRhIENydXoxEzAR +BgNVBAoTClByb2R1Y3RPcHMxFDASBgNVBAsTC2RldmVsb3BtZW50MRMwEQYDVQQD +EwpFcmljIEZ1bHR6MSgwJgYJKoZIhvcNAQkBFhllcmljLmZ1bHR6QHByb2R1Y3Rv +cHMuY29tMB4XDTEyMDUwNDIxMzYxNVoXDTEzMDUwNDIxMzYxNVowgaExCzAJBgNV +BAYTAlVTMRMwEQYDVQQIEwpDYWxpZm9ybmlhMRMwEQYDVQQHEwpTYW50YSBDcnV6 +MRMwEQYDVQQKEwpQcm9kdWN0T3BzMRQwEgYDVQQLEwtkZXZlbG9wbWVudDETMBEG +A1UEAxMKRXJpYyBGdWx0ejEoMCYGCSqGSIb3DQEJARYZZXJpYy5mdWx0ekBwcm9k +dWN0b3BzLmNvbTCBnzANBgkqhkiG9w0BAQEFAAOBjQAwgYkCgYEAxtJijhRJDMVJ +CrVmgMQaKT43+DUjdz28m1OS/wbGyRqZmwHWWXSgPHeuu30Opw/MxpgqlxfqAScZ +4nRfSq3kjENeoNAO8OPbKStT/5Y5HqEE6Ipfy8OU95Q4EbuGdSidrJDyHvWayNjc +GWBbvh7HnDwMkqiETFJZiP3y+ASunJcCAwEAATANBgkqhkiG9w0BAQUFAAOBgQAP +F9XVSlNSk6JJFzF3xA7FmAbB5Bf1kk0xmYt63Q3dsUHX++aVkC/TDnpAexvpA7sE +tKi20XthyjBWTB7KgfnQeoIz0tHJikbjTPo0yNZhv2p9DtApz12sGVIqtC7zR3rU +f1y9BHz8IM584dECmkd3lgBIbx2fClxvPX5zLbTYgw== +-----END CERTIFICATE----- \ No newline at end of file diff --git a/packaging/src/main/resources/defaults/e3.default.key b/packaging/src/main/resources/defaults/e3.default.key new file mode 100644 index 0000000..a6b8f05 --- /dev/null +++ b/packaging/src/main/resources/defaults/e3.default.key @@ -0,0 +1,15 @@ +-----BEGIN RSA PRIVATE KEY----- +MIICXAIBAAKBgQDG0mKOFEkMxUkKtWaAxBopPjf4NSN3PbybU5L/BsbJGpmbAdZZ +dKA8d667fQ6nD8zGmCqXF+oBJxnidF9KreSMQ16g0A7w49spK1P/ljkeoQToil/L +w5T3lDgRu4Z1KJ2skPIe9ZrI2NwZYFu+HsecPAySqIRMUlmI/fL4BK6clwIDAQAB +AoGAMRtnokYaYOAdkVqKrcVB3Ov0MQcW8m26NvcmeHz4/lTmmaWThtbKeQTqkH5r +7xF095w/8L/EWXKJ7yflHXHj392J6TyDb3ejZBR88w+BFYY2Juu1JmKs5VM0yXyT +qr6KOlNJxyFZh1r+tdVtL/e5p9CXa4NTACofLezZfzahCuECQQDoIhU2heuT+C5g +YfVtw6zuB+HI1wurBcmcLXkIsvKAF+YvaC3D+r4rxDLxSAEgvwFTZlkkEiuE5OyE +NhBXZAxxAkEA20OF+ojpDJhqZvo1Gtbxs9DeTZOI62sa7QQ2RmkuE1at9Ek8WHDi +s/TC9VToAszInFZjWj4q6BEmIVceHFddhwJAU6xNZyzYoKqZ1OYaeGlLATXYHfPd +4dShOmltskQGg0OaFkaAEJ9mQxJipnQk6+/Ng4ll4kmmZC28T1/JfiazEQJBAMwk +NORKffg9G6uevryrbMPG7oJ5nxvYT2xm5IVvvfdBV5o+aVHKYDe95Zn2oECjGw/7 +mmrVwKrp9H9MFfu7F5cCQChLP1dOmBYoJpgPD4jrjmbDhMOR39joHuq1Gw8bASRv +7SONE40H7qWAgEtFo8KanhhImJ08lHmbyYefVvQ8M4M= +-----END RSA PRIVATE KEY----- \ No newline at end of file diff --git a/packaging/src/main/resources/dependencies.sh b/packaging/src/main/resources/dependencies.sh new file mode 100644 index 0000000..77ca806 --- /dev/null +++ b/packaging/src/main/resources/dependencies.sh @@ -0,0 +1,444 @@ +#!/bin/bash + +ABS_PATH_NAME=$(readlink -f $0) +DIR=`dirname $ABS_PATH_NAME` + +source $DIR/variables.sh + +# this function installs java if java is not present in OS +function redhat_java { + # Get input parameters + JAVA_BIN="$1" + JAVA_MD5="$2" + + # Check if java is already installed + if which java ; then + VER=`java -version 2>&1 | head -1 | awk '{print $3}' | tr -d \"` + MAINVER="${VER%_*}" + MAINVER="${MAINVER%.*}" + MAINVER="${MAINVER#*.}" + SUBVER="${VER#*_}" + + + J_MAINVER="${JAVA_VER%_*}" + J_MAINVER="${J_MAINVER%.*}" + J_MAINVER="${J_MAINVER#*.}" + J_SUBVER="${JAVA_VER#*_}" + + # if [[ $MAINVER -gt $J_MAINVER ]] ; then return 0 ; fi + # if [ $MAINVER = $J_MAINVER ] ; then + # if [[ $SUBVER -ge $J_SUBVER ]] ; then return 0 ; fi + # fi + + if [ "$VER"x != "$JAVA_VER"x ] ; then + Reinstall='yes' + fi + + JDKVendor=`java -version 2>&1 | awk 'NR==2 {print $1}'` + if [ "$JDKVendor"x != "Java(TM)"x ] ; then + Reinstall='yes' + fi + else + Reinstall='yes' + fi + + if [ "$Reinstall" == "yes" ] ; then + ( + # Compute and check MD5 sum + #md5=`md5sum $JAVA_BIN` + #md5check=`cat $JAVA_MD5` + + #set -- $md5 + + #if [[ $1 != $md5check ]]; then + # echo " bad JAVA md5 checksum" + # exit 1 + #fi + + # Create directory if not exists + if [ ! -e "/usr/java" ] ; then + mkdir /usr/java + fi + + # Copy the bin + cp $JAVA_BIN /usr/java + cd /usr/java + JAVA_NAME=`basename $JAVA_BIN` + chmod +x $JAVA_NAME + test ! -z "$JAVA_NAME" || exit 1 + + # do not remove any old java + #rm -f /usr/bin/java + + # Install with auto answer + echo "yes" | ./$JAVA_NAME &>/dev/null + + rm -f $JAVA_NAME + + # Set the environment variable + JAVA_HOME=/usr/java/default + export JAVA_HOME=/usr/java/default + echo "export JAVA_HOME=/usr/java/default" > /etc/profile.d/java.sh + export PATH=$PATH:$JAVA_HOME/bin + echo "export PATH=$JAVA_HOME/bin:$PATH" >> /etc/profile.d/java.sh + . /etc/profile.d/java.sh + source /etc/profile.d/java.sh + ) + if ! [ $? = 0 ] ; then + echo "Failed to install java" >&2 + exit 1 + fi + fi +} # end redhat_java + + +function patch_karaf_wrapper { + KARAF_WRAPPER_PATH=$E3_HOME/$SMX_LINK_DIRNAME/etc/karaf-wrapper.conf + + cp $KARAF_WRAPPER_PATH $KARAF_WRAPPER_PATH.bak + cp $KARAF_WRAPPER_TEMPLATE $KARAF_WRAPPER_PATH + + EXPR="s#E3_HOME_DIR#$E3_HOME#g" + sed -i -e $EXPR $KARAF_WRAPPER_PATH + +} # end patch_karaf_wrapper + +function patch_karaf_config { + + # patch karaf configuration file to use felix as osgi implementation + KARAF_CONFIG_FILE_PATH=$E3_HOME/$SMX_LINK_DIRNAME/etc/config.properties + + echo "Overriding karaf config file $KARAF_CONFIG_FILE_PATH with custom version" + cp $KARAF_CONFIG_FILE_PATH $KARAF_CONFIG_FILE_PATH.bak + cp $KARAF_CONFIG_FILE $KARAF_CONFIG_FILE_PATH +} + +function update_smx_ssh_pwd { + smxPwdFile=$E3_HOME/$ESB_NAME/etc/users.properties + echo "Updading servicemix password user:$SMX_USER $smxPwdFile" + sed -i -e "s/^.*,admin/$SMX_USER=$SMX_PWD,admin/" $smxPwdFile + echo "$smxPwdFile updated." +} + +function universal_esb { + export JAVA_HOME=/usr/java/default + # Get input parameters + FUSE_GZ="$1" + FUSE_MD5="$2" + + ESB_DIR="${FUSE_GZ%.tar.gz}" + ESB_NAME=`basename $ESB_DIR` + + # Update smx ssh pwd + + + if [ -e "$E3_HOME/$ESB_NAME" ] ; then + # Fuse already installed + echo $E3_HOME/$ESB_NAME + service karaf-service stop + rm -rf $E3_HOME/$SMX_LINK_DIRNAME + rm -rf $E3_HOME/$ESB_NAME + rm -f $MODE_CONF_PATH + rm -f $E3_HOME/topology.xml + rm -f $E3_HOME/system_topology.xml + rm -f $E3_HOME/installer-config.xml + rm -rf $E3_HOME/TDR_ProcessScript + rm -f /etc/init.d/karaf-service + rm -f /root/.ssh/known_hosts + fi + + # Compute and check MD5 sum + #md5=`md5sum $FUSE_GZ` + #md5check=`cat $FUSE_MD5` + + #set -- $md5 + + #if [[ $1 != $md5check ]]; then + # echo " bad fuse md5 checksum" + # exit 1 + #fi + + # Install fuse + tar xzf $FUSE_GZ -C $E3_HOME + + chown -R $USER:$GROUP $E3_HOME/$ESB_NAME + + su - $USER -c "cd $E3_HOME ; \ + ln -s $ESB_NAME $SMX_LINK_DIRNAME ; \ + exit 0 " + + if ! [ $? = 0 ] ; then + echo "Failed to unpack apache-servicemix" >&2 + exit 1 + fi + + update_smx_ssh_pwd + + # Replacing variable org.ops4j.pax.url.mvn.repositories with empty value => removes any external maven repository servicemix might want to use + # Have values for variable org.ops4j.pax.url.mvn.repositories be on one single line (remove new lines) and replace that line + echo "Patching Servicemix external maven repo file ..." + cd $E3_HOME + cd $SMX_LINK_DIRNAME/etc + cp $SERVICE_MIX_MVN_REPO_FILE $SERVICE_MIX_MVN_REPO_FILE.bak + sed -i -e 's/^[ \t]*//' $SERVICE_MIX_MVN_REPO_FILE + sed -i -e :a -e '/\\$/N; s/\\\n//; ta' $SERVICE_MIX_MVN_REPO_FILE + sed -i -e 's/org.ops4j.pax.url.mvn.repositories=.*$/org.ops4j.pax.url.mvn.repositories=/' $SERVICE_MIX_MVN_REPO_FILE + if ! [ $? = 0 ] ; then + echo "Failed to patch external maven repo file" >&2 + exit 1 + fi + + # patching karaf config file + echo 'Patching karaf config.properties file to use Felix ...' + patch_karaf_config + + if ! [ $? = 0 ] ; then + echo "Failed to patch karaf config.properties file to use Felix" >&2 + exit 1 + fi + + # Unzip external dependencies into system folder (default karaf repository) + # Allows to get rid of any internet repository dependecy + echo "Adding external dependencies to default karaf repository ..." + tar xvfz $DEP_ARCHIVE -C $E3_HOME/$ESB_NAME/system --strip-components=1 + chown -R $USER:$GROUP $E3_HOME/$ESB_NAME/system + chmod a+rwx $E3_HOME/$ESB_NAME/system + if ! [ $? = 0 ] ; then + echo "Failed to add external maven dependencies for Servicemix" >&2 + exit 1 + fi + + # starting karaf under $USER user + su - $USER -c "echo 'Starting karaf...' ; \ + $E3_HOME/$SMX_LINK_DIRNAME/bin/start ; \ + if ! [ $? = 0 ] ; then \ + echo 'Karaf startup seems to have failed' ; \ + exit 1 ; \ + fi ; \ + exit 0" + + # waiting for karaf + echo "Waiting for karaf..." + sh $DIR/wait-karaf.sh + + echo 'Wait for ServiceMix normal to properly init...' + test_servicemix_ok + + # installing karaf-wrapper + echo 'Installing wrapper feature...' + $E3_HOME/$SMX_LINK_DIRNAME/bin/client -p $SMX_PWD -u $SMX_USER 'features:install wrapper' + if ! [ $? = 0 ] ; then + echo 'Failed to install wrapper feature' + exit 1 + fi + + # generating wrapper service stuff + echo 'Generating wrapper service stuff...' + $E3_HOME/$SMX_LINK_DIRNAME/bin/client -p $SMX_PWD -u $SMX_USER 'wrapper:install -n karaf -d karaf -D KarafFuseESBService' + if ! [ $? = 0 ] ; then + echo 'Failed to generate wrapper service stuff' + exit 1 + fi + + # stopping karaf + echo 'Stopping karaf...' + $E3_HOME/$SMX_LINK_DIRNAME/bin/stop + echo "Waiting for karaf be down..." + sh $DIR/wait-karaf-down.sh + if [ $? != 0 ] + then + echo "Unable to stop karaf, kill all servicemix instances and try again, exiting..." + exit 1 + fi + + # patching karaf-wrapper.conf + echo 'Patching karaf-wrapper.conf...' + patch_karaf_wrapper + + if ! [ $? = 0 ] ; then + echo "Failed to install and configure karaf-wrapper" >&2 + exit 1 + fi + + echo "Installing karaf as service" + ln -s $E3_HOME/$SMX_LINK_DIRNAME/bin/karaf-service /etc/init.d/ + + if grep -qE '#RUN_AS_USER=' $E3_HOME/$SMX_LINK_DIRNAME/bin/karaf-service ; then + echo "Updating init.d script to set RUN_AS_USER=$USER..." + EXPR="s/#RUN_AS_USER=/RUN_AS_USER=$USER/" + sed -i -e $EXPR $E3_HOME/$SMX_LINK_DIRNAME/bin/karaf-service + echo "Updating the start priority of the service" + sed -i -e 's/# chkconfig: 2345 20 80/# chkconfig: 2345 99 80/' $E3_HOME/$SMX_LINK_DIRNAME/bin/karaf-service + fi +} # end universal_esb + +function redhat_initd { + echo "Enabling karaf-service..." + chkconfig karaf-service --add + chkconfig karaf-service on + + echo "Starting karaf-service..." + /etc/init.d/karaf-service start + +} # end redhat_initd + + +function redhat_filelimits { + if ! grep -qE 'fs.file-max' /etc/sysctl.conf ; then + echo "Updating file-limits configuration..." + echo "Patching /etc/sysctl.conf" + echo "fs.file-max = $FILE_MAX" >> /etc/sysctl.conf + fi + + if ! grep -qE "hard nofile $FILE_LIMITS" /etc/security/limits.conf ; then + echo "Patching /etc/security/limits.conf (hard limit)" + sed -i -e "/# End of file/ i \* hard nofile $FILE_LIMITS" /etc/security/limits.conf + fi + + if ! grep -qE "soft nofile $FILE_LIMITS" /etc/security/limits.conf ; then + echo "Patching /etc/security/limits.conf (soft limit)" + sed -i -e "/# End of file/ i \* soft nofile $FILE_LIMITS" /etc/security/limits.conf + fi + + # set file max + if [ `cat /proc/sys/fs/file-max` -ne $FILE_MAX ] ; then + echo "Patching /proc/sys/fs/file-max" + echo $FILE_MAX > /proc/sys/fs/file-max + fi + +} # end redhat_filelimits + +function test_servicemix_ok { + for n in `seq 1 20` + do + result=`$E3_HOME/$SMX_LINK_DIRNAME/bin/client -p $SMX_PWD -u $SMX_USER list | grep "camel" | grep Active` + if [[ $result = *[Active* ]] + then + echo 'ServiceMix init done' + break + else + echo 'ServiceMix still initializing: wait 5s and retry ('$n' of 20)' + sleep 5 + fi + done +} # end test_servicemix_ok + +function disable_xinetd { + echo "Disabling xinetd daemon ..." + if [ -e /etc/init.d/xinetd ] + then + echo " Stopping xinetd daemon ..." + /etc/init.d/xinetd stop + echo " xinetd stopped." + chkconfig --del xinetd + # The following call to --list must fail + # 'cause we have unregistered it + chkconfig --list xinetd 2> /dev/null + if [ $? = 0 ] ; then + echo " unabled to unregister xinetd daemon." + exit 1 + else + echo " xinetd daemon unregistered." + fi + else + echo " xinetd does not appear to be present." + fi + + echo "xinetd daemon disabled." +} # end disable_xinetd + +function disable_xdmcp { + echo "Disabling xdmcp protocol ..." + if [ -e /etc/gdm/custom.conf ] + then + echo " Stopping gdm daemon ..." + gdm-stop > /dev/null 2>&1 + echo " gdm stopped." + + echo " Changing /etc/gdm/custom.conf if necessary ..." + if [ -z "`grep -i 'Enable=true' /etc/gdm/custom.conf`" ] + then + echo " No change to apply." + else + sed -i 's/enable=true/Enable=false/Ig' /etc/gdm/custom.conf + echo " /etc/gdm/custom.conf patched." + fi + else + echo " xdmcp does not appear to be present." + fi + + echo "xdmcp protocol disabled." +} # end disable_xinetd + +function check_tftp_daemon { + echo "Checking tftp daemon configuration ..." + if [ -e /etc/xinetd.d/tftp ] + then + if [ -z "`grep 'server_args' /etc/xinetd.d/tftp`" ] + then + echo " Configuration file not conform." + exit 1 + fi + # Applying patch + sed -i 's/\(server_args.*=\).*/\1 -s\ \/tftpboot/g' /etc/xinetd.d/tftp + if [ $? = 0 ] + then + echo " Configuration file patched." + else + echo " Error while patching /etc/xinetd.d/tftp file." + exit 1 + fi + else + echo " tftp configuration does not appear to be present." + fi + + echo "tftp daemon configuration checked." +} # end disable_xinetd + +# Begginning of the script + +if [ -e "/etc/redhat-release" ] ; then + if [ "$(uname -m)" = "x86_64" ] ; then + redhat_java $E3_JAVA_64_BIN $E3_JAVA_64_MD5 + else + redhat_java $E3_JAVA_32_BIN $E3_JAVA_32_MD5 + fi + + # file-limits patch + redhat_filelimits + + if [ -e $DIR/install_snmp.sh ] ; then + sh $DIR/install_snmp.sh + if [ $? != 0 ] + then + exit 1 + fi + fi + + # installing fuse esb + universal_esb $E3_FUSE_GZ $E3_FUSE_MD5 + + # set fuse esb as service + redhat_initd + + # + # Applying TMO Security items: + # 4- checking tftp daemon configuration + check_tftp_daemon + + # 6- xinetd daemon disabling + disable_xinetd + + # 8- xdmcp protocol disabling + disable_xdmcp + + + + +elif [ -e "/etc/debian_version" ] ; then + echo "Debian is not yet supported!" >&2 + exit 1 +else + echo "Unknown Linux Distro" >&2 + exit 1 +fi diff --git a/packaging/src/main/resources/generateNature.sh b/packaging/src/main/resources/generateNature.sh new file mode 100644 index 0000000..a1dba55 --- /dev/null +++ b/packaging/src/main/resources/generateNature.sh @@ -0,0 +1,274 @@ +#!/bin/bash + +ABS_PATH_NAME=$(readlink -f $0) +DIR=`dirname $ABS_PATH_NAME` + +source $DIR/variables.sh + +if [[ $# < 1 ]] +then + echo "Missing input parameter." + exit 1 +fi + +# build firewall restriction if manager ip is passed +if [ "$1" = "-ip" ] +then + SOURCE_RESTICT="-s $2" + echo "Will apply source restriction $SOURCE_RESTICT on all rules concerning manager-gateway communication" + # ignore the first two parameters (-ip option and ip itself) for the rest of the script + shift 2 +fi + +# create configuration file indicating mode (manager, gateway or both) +if [ ! -f $MODE_CONF_PATH ] +then + echo "E3 mode configuration file does not exist. Creating it in $MODE_CONF_PATH" + + if [ -f $DIR/configuration-defaults.properties ] + then + cp $DIR/configuration-defaults.properties $MODE_CONF_PATH + fi + + if [ -f $DIR/configuration.properties ] + then + cp $DIR/configuration.properties $MODE_CONF_PATH + fi + + if [ ! -f $MODE_CONF_PATH ] + then + echo "Unable to create $MODE_CONF_PATH. Exiting ..." + exit 1 + fi +fi +chown $USER:$GROUP $MODE_CONF_PATH +chmod 600 $MODE_CONF_PATH + +# change configuration file values according to parameters +for ARG in "$@" +do + if [ "$ARG" == "gateway" ] + then + sed -i -e 's/^\(e3.gateway=.*\)$/e3.gateway=true/' $MODE_CONF_PATH + fi + + if [ "$ARG" == "manager" ] + then + sed -i -e 's/^\(e3.manager=.*\)$/e3.manager=true/' $MODE_CONF_PATH + if [ $PROV_REST_API_BASICAUTH_ENABLE = 1 ] + then + sed -i -e 's/^\(e3.provisioning.restapi.security.basicauth.enable=.*\)$/e3.provisioning.restapi.security.basicauth.enable=true/' $MODE_CONF_PATH + sed -i -e "s/^\(e3.provisioning.restapi.security.basicauth.username=.*\)$/e3.provisioning.restapi.security.basicauth.username=$PROV_REST_API_BASICAUTH_USERNAME/" $MODE_CONF_PATH + sed -i -e "s/^\(e3.provisioning.restapi.security.basicauth.password=.*\)$/e3.provisioning.restapi.security.basicauth.password=$PROV_REST_API_BASICAUTH_PASSWORD/" $MODE_CONF_PATH + else + sed -i -e 's/^\(e3.provisioning.restapi.security.basicauth.enable=.*\)$/e3.provisioning.restapi.security.basicauth.enable=false/' $MODE_CONF_PATH + sed -i -e "s/^\(e3.provisioning.restapi.security.basicauth.username=.*\)$/e3.provisioning.restapi.security.basicauth.username=/" $MODE_CONF_PATH + sed -i -e "s/^\(e3.provisioning.restapi.security.basicauth.password=.*\)$/e3.provisioning.restapi.security.basicauth.password=/" $MODE_CONF_PATH + fi + + fi +done + +# Install the transfer of the TDRs for gateway +if [ -e $DIR/installTdrTransfer.sh ] ; then + for ARG in "$@" + do + if [ "$ARG" == "gateway" ] + then + sh $DIR/installTdrTransfer.sh + if [ $? != 0 ] + then + echo "Unable to install the TDR transfer" + exit 1 + fi + fi + done +fi + + +# Set up pax-web settings +function e3_paxweb_setup { + + + SMX_DIR="$E3_HOME/$SMX_LINK_DIRNAME" + SMX_CFG="$SMX_DIR/etc/$SERVICE_MIX_PAX_WEB_CFG_FILE" + + E3_SECTION_START_LINE="# E3 setup start" + E3_SECTION_END_LINE="# E3 setup end" + + if [ ! -f $SMX_CFG ] + then + echo "Could not find ServiceMix logging configuration where expected: $SMX_CFG" + return + fi + + + # If our changes from a previous install are present, delete them + cp $SMX_CFG ${SMX_CFG}.bak + chown --reference=$SMX_CFG ${SMX_CFG}.bak + START_LINE_NO=`grep -n "$E3_SECTION_START_LINE" $SMX_CFG | cut -d ":" -f1` + END_LINE_NO=`grep -n "$E3_SECTION_END_LINE" $SMX_CFG | cut -d ":" -f1` + if [ ! -z $START_LINE_NO ] && [ ! -z $END_LINE_NO ] && [ $START_LINE_NO -lt $END_LINE_NO ] + then + echo "Deleting previous E3-specific rules from $SMX_CFG (lines $START_LINE_NO to $END_LINE_NO)" + sed -i "/$E3_SECTION_START_LINE/,/$E3_SECTION_END_LINE/d" $SMX_CFG + else + # On a new install, make a little space + echo "" >>$SMX_CFG + fi + + echo "Writing changes to $SMX_CFG" + if [ $PROV_REST_API_HTTP_ENABLE = 1 ] && [ $PROV_REST_API_HTTPS_ENABLE = 1 ] + then + cat >> $SMX_CFG <<-EOF + $E3_SECTION_START_LINE + org.osgi.service.http.enabled=true + org.osgi.service.http.secure.enabled=true + org.ops4j.pax.web.ssl.keystore=$PROV_REST_API_KEYSTORE_PATH + org.ops4j.pax.web.ssl.password=$PROV_REST_API_KEYSTORE_PASSWORD + org.ops4j.pax.web.ssl.keypassword=$PROV_REST_API_KEYSTORE_KEYPASSWORD + org.ops4j.pax.web.ssl.clientauthwanted=false + org.ops4j.pax.web.ssl.clientauthneeded=false + $E3_SECTION_END_LINE + EOF + fi + if [ $PROV_REST_API_HTTP_ENABLE = 0 ] && [ $PROV_REST_API_HTTPS_ENABLE = 1 ] + then + cat >> $SMX_CFG <<-EOF + $E3_SECTION_START_LINE + org.osgi.service.http.enabled=false + org.osgi.service.http.secure.enabled=true + org.ops4j.pax.web.ssl.keystore=$PROV_REST_API_KEYSTORE_PATH + org.ops4j.pax.web.ssl.password=$PROV_REST_API_KEYSTORE_PASSWORD + org.ops4j.pax.web.ssl.keypassword=$PROV_REST_API_KEYSTORE_KEYPASSWORD + org.ops4j.pax.web.ssl.clientauthwanted=false + org.ops4j.pax.web.ssl.clientauthneeded=false + $E3_SECTION_END_LINE + EOF + fi + if [ $PROV_REST_API_HTTP_ENABLE = 1 ] && [ $PROV_REST_API_HTTPS_ENABLE = 0 ] + then + cat >> $SMX_CFG <<-EOF + $E3_SECTION_START_LINE + org.osgi.service.http.enabled=true + org.osgi.service.http.secure.enabled=false + $E3_SECTION_END_LINE + EOF + fi + if [ $PROV_REST_API_HTTP_ENABLE = 0 ] && [ $PROV_REST_API_HTTPS_ENABLE = 0 ] + then + echo "WARNING: both http and https are disabled to access REST API !!!" + fi + +} # end e3_paxweb_setup + +IS_GATEWAY=0 +IS_MANAGER=0 +IS_SPEAKER=0 + +# change configuration file values according to parameters +for ARG in "$@" +do + if [ "$ARG" = "gateway" ] + then + IS_GATEWAY=1 + IS_SPEAKER=1 + fi + + if [ "$ARG" = "manager" ] + then + IS_MANAGER=1 + fi +done + +iptables -D E3-Firewall-INPUT -j REJECT --reject-with icmp-host-prohibited + +if [ $IS_GATEWAY = 1 ] ; then + if [ ! $IS_E3_AIB ] ; then + iptables -A E3-Firewall-INPUT -p tcp --dport 15701 -j ACCEPT $SOURCE_RESTICT + fi + + iptables -A E3-Firewall-INPUT -p tcp --dport 25100 -j ACCEPT + iptables -A E3-Firewall-INPUT -p tcp --dport 25101 -j ACCEPT + iptables -t nat -A PREROUTING -p tcp --dport 80 -j REDIRECT --to-port 25100 + iptables -t nat -A PREROUTING -p tcp --dport 443 -j REDIRECT --to-port 25101 + iptables -A OUTPUT -t nat -p TCP --dport 25100 -j REDIRECT --to-ports 80 + iptables -A OUTPUT -t nat -p TCP --dport 25101 -j REDIRECT --to-ports 443 +fi + +if [ $IS_SPEAKER = 1 ] ; then + if [ ! $IS_E3_AIB ] ; then + iptables -A E3-Firewall-INPUT -p tcp --dport 15701 -j ACCEPT $SOURCE_RESTICT + fi +fi + +ipList= +nbElem=0 +if [ $PROV_REST_API_IPWHITELIST_ENABLE = 1 ] ; then + echo "ip whitelist for $PROV_REST_API_IPWHITELIST" + ipList=($PROV_REST_API_IPWHITELIST) + nbElem=${#ipList[*]} + + if [ $nbElem = 0 ] ; then + echo "ERROR: PROV_REST_API_IPWHITELIST_ENABLE=1 but no ip list provided in PROV_REST_API_IPWHITELIST see varibales.sh." + exit 1 + fi +fi + +if [ $IS_MANAGER = 1 ] ; then + e3_paxweb_setup + if [ $PROV_REST_API_HTTP_ENABLE = 1 ] ; then + echo "HTTP port 8181 enabled" + if [ $nbElem = 0 ] + then + iptables -A E3-Firewall-INPUT -p tcp --dport 8181 -j ACCEPT + else + for i in `seq 0 $(($nbElem - 1))`; + do + echo "HTTP port 8181 enabled for ip ${ipList[$i]}" + iptables -A E3-Firewall-INPUT -p tcp --dport 8181 -j ACCEPT -s ${ipList[$i]} + done + fi + fi + if [ $PROV_REST_API_HTTPS_ENABLE = 1 ] ; then + echo "HTTPS port 8443 enabled" + if [ $nbElem = 0 ] + then + iptables -A E3-Firewall-INPUT -p tcp --dport 8443 -j ACCEPT + else + for i in `seq 0 $(($nbElem - 1))`; + do + echo "HTTP port 8443 enabled for ip ${ipList[$i]}" + iptables -A E3-Firewall-INPUT -p tcp --dport 8443 -j ACCEPT -s ${ipList[$i]} + done + fi + fi +fi + +iptables -A E3-Firewall-INPUT -p tcp --dport 8888 -j ACCEPT $SOURCE_RESTICT +iptables -A E3-Firewall-INPUT -p tcp --dport 8889 -j ACCEPT $SOURCE_RESTICT +iptables -A E3-Firewall-INPUT -p tcp --dport 8988 -j ACCEPT $SOURCE_RESTICT + +if [ ! $IS_E3_AIB ] ; then + iptables -A E3-Firewall-INPUT -p tcp --dport 8082 -j ACCEPT $SOURCE_RESTICT + + if [ $IS_GATEWAY = 1 ] ; then + iptables -A E3-Firewall-INPUT -p tcp --dport 8083 -j ACCEPT $SOURCE_RESTICT + fi + + if [ $IS_SPEAKER = 1 ] ; then + iptables -A E3-Firewall-INPUT -p tcp --dport 8084 -j ACCEPT $SOURCE_RESTICT + fi + + if [ $IS_MANAGER = 1 ] ; then + iptables -A E3-Firewall-INPUT -p tcp --dport 8085 -j ACCEPT $SOURCE_RESTICT + fi +fi + +# Block all other requests +iptables -A E3-Firewall-INPUT -j REJECT --reject-with icmp-host-prohibited + +service iptables save +service iptables restart + +exit 0 diff --git a/packaging/src/main/resources/install.sh b/packaging/src/main/resources/install.sh new file mode 100644 index 0000000..5a75546 --- /dev/null +++ b/packaging/src/main/resources/install.sh @@ -0,0 +1,77 @@ +#!/bin/sh + +ABS_PATH_NAME=$(readlink -f $0) +DIR=`dirname $ABS_PATH_NAME` + +source $DIR/variables.sh + +if [[ $# < 1 ]] +then + echo "Missing input parameter : manager AND/OR gateway" + exit 1 +fi + +# treat the manager ip parameter passed through the option -ip +if [ "$1" = "-ip" ] +then + IP_MANAGER="$1 $2" + echo "Capturing the manager ip and option $IP_MANAGER" + # ignore the first two parameters (-ip option and ip itself) + shift 2 +fi + +# create the user $USER +useradd $USER -d "$E3_HOME" -m -s "/bin/bash" + +if [ -e $DIR/dependencies.sh ] ; then + sh $DIR/dependencies.sh + if [ $? != 0 ] + then + echo "Unable to assume the dependencies" + exit 1 + fi +fi + +sh $DIR/copyFiles.sh +if [ $? != 0 ] +then + echo "Unable to copy files" + exit 1 +fi + + +sh $DIR/configureSecurity.sh $* +if [ $? != 0 ] +then + echo "Unable to configure the security" + exit 1 +fi + +echo "Calling generateNature.sh $IP_MANAGER $*" +sh $DIR/generateNature.sh $IP_MANAGER $* +if [ $? != 0 ] +then + echo "Unable to generate the nature" + exit 1 +fi + + +sh $DIR/configSystem.sh $* +if [ $? != 0 ] +then + echo "Unable to configure the system" + exit 1 +fi + + +sh $DIR/sanityCheck.sh $* +if [ $? != 0 ] +then + echo "Unable to execute the sanity check" + exit 1 +fi + +echo "Install success" +exit 0 + + \ No newline at end of file diff --git a/packaging/src/main/resources/install_e3_aib.sh b/packaging/src/main/resources/install_e3_aib.sh new file mode 100644 index 0000000..fe242b1 --- /dev/null +++ b/packaging/src/main/resources/install_e3_aib.sh @@ -0,0 +1,57 @@ +#!/bin/bash + +ABS_PATH_NAME=$(readlink -f $0) +DIR=`dirname $ABS_PATH_NAME` + +source $DIR/variables.sh + +export IS_E3_AIB=1 + +sh $DIR/install.sh manager gateway +if [ $? != 0 ] +then + echo "E3 manager/gateway installation failed, exiting" + exit 1 +fi + +cp $DIR/aib_topology.xml $E3_HOME/topology.xml +if [ $? != 0 ] +then + echo "unable to copy the topology, exiting" + exit 1 +fi + +chown $USER:$GROUP $E3_HOME/topology.xml +if [ $? != 0 ] +then + echo "unable to chowm the topology, exiting" + exit 1 +fi + +cp $DIR/aib_system_topology.xml $E3_HOME/system_topology.xml +if [ $? != 0 ] +then + echo "unable to copy the system topology, exiting" + exit 1 +fi + +chown $USER:$GROUP $E3_HOME/system_topology.xml +if [ $? != 0 ] +then + echo "unable to chowm the system topology, exiting" + exit 1 +fi + +chmod 600 $E3_HOME/topology.xml +if [ $? != 0 ] +then + echo "unable to chmod the topology, exiting" + exit 1 +fi + +chmod 600 $E3_HOME/system_topology.xml +if [ $? != 0 ] +then + echo "unable to chmod the system topology, exiting" + exit 1 +fi diff --git a/packaging/src/main/resources/install_e3_cluster.sh b/packaging/src/main/resources/install_e3_cluster.sh new file mode 100644 index 0000000..39a3bb3 --- /dev/null +++ b/packaging/src/main/resources/install_e3_cluster.sh @@ -0,0 +1,120 @@ +#!/bin/sh + +ABS_PATH_NAME=$(readlink -f $0) +DIR=`dirname $ABS_PATH_NAME` + +source $DIR/variables.sh + +if [[ $# < 1 ]] +then + echo "Missing input parameter : Absolute path to installer.tar.zg" + exit 1 +fi + +PATH_TO_TAR_GZ=$1 + +if [ ! -e $PATH_TO_TAR_GZ ] ; then + echo "File $PATH_TO_TAR_GZ does not exist" + exit 1 +fi + +# Install manager +sh $DIR/install.sh manager +if [ $? != 0 ] +then + echo "E3 manager installation failed, exiting" + exit 1 +fi + +# copy the config files +chown $USER:$GROUP $DIR/../topology.xml +if [ $? != 0 ] +then + echo "unable to chown the topology, you need to have a topology.xml file in $DIR/.." + exit 1 +fi + +chmod 600 $DIR/../topology.xml +if [ $? != 0 ] +then + echo "unable to chmod the topology." + exit 1 +fi + +chmod 400 $DIR/../system_topology.xml +if [ $? != 0 ] +then + echo "unable to chmod the system topology." + exit 1 +fi + +cp $DIR/../system_topology.xml $E3_HOME/system_topology.xml +if [ $? != 0 ] +then + echo "unable to copy the system topology, you need to have a system_topology.xml file in $DIR/.." + exit 1 +fi + +chown $USER:$GROUP $E3_HOME/system_topology.xml +if [ $? != 0 ] +then + echo "unable to chown the system topology, exiting" + exit 1 +fi + +if [ ! -e $DIR/../installer-config.xml ] +then + cp $DIR/../templates/template-installer-config.xml $DIR/../installer-config.xml + if [ $? != 0 ] + then + echo "unable to copy the installer-config, exiting" + exit 1 + fi +fi + +chown $USER:$GROUP $DIR/../installer-config.xml +if [ $? != 0 ] +then + echo "unable to chown the installer-config, exiting" + exit 1 +fi + +echo "Calling system manager" +HTTP_CODE_RETURN=0 +rm -f result.log + +# replace / with a space +TAR_MODULE_PATH=`dirname $PATH_TO_TAR_GZ` +TAR_MODULE_PATH=$(echo $TAR_MODULE_PATH|sed 's/\//%2F/g') + +HTTP_SCHEME="http" +PORT="8181" +if [ $PROV_REST_API_HTTPS_ENABLE = 1 ] ; then + HTTP_SCHEME="https" + PORT="8443" +fi + +credentials="$PROV_REST_API_BASICAUTH_USERNAME:$PROV_REST_API_BASICAUTH_PASSWORD" +credentials64=`printf "$credentials"|base64` + +curl -k --header "Authorization: Basic $credentials64" -s -o result.log -w "%{http_code}" $HTTP_SCHEME://localhost:$PORT/cxf/e3/system-manager/install/$TAR_MODULE_PATH > log.log + +result=`cat log.log` +if [[ $result != *200* ]]; then + HTTP_CODE_RETURN=1 +fi + +echo " WebService response begin " +cat result.log +echo " WebService response end " + +if ! [ $HTTP_CODE_RETURN = 0 ] ; then + exit $HTTP_CODE_RETURN +fi + +chmod 600 $E3_HOME/topology.xml +if [ $? != 0 ] +then + echo "unable to chmod the topology in E3 home." + exit 1 +fi diff --git a/packaging/src/main/resources/karaf-wrapper.conf b/packaging/src/main/resources/karaf-wrapper.conf new file mode 100644 index 0000000..9ca4aab --- /dev/null +++ b/packaging/src/main/resources/karaf-wrapper.conf @@ -0,0 +1,143 @@ +# ------------------------------------------------------------------------ +# Licensed to the Apache Software Foundation (ASF) under one or more +# contributor license agreements. See the NOTICE file distributed with +# this work for additional information regarding copyright ownership. +# The ASF licenses this file to You 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. +# ------------------------------------------------------------------------ + +#******************************************************************** +# Wrapper Properties +#******************************************************************** +set.default.KARAF_HOME=E3_HOME_DIR/apache-servicemix +set.default.KARAF_BASE=E3_HOME_DIR/apache-servicemix +set.default.KARAF_DATA=E3_HOME_DIR/apache-servicemix/data + +set.default.JAVA_HOME=/usr/java/default +set.default.JAVA_MIN_MEM=128M +set.default.JAVA_MAX_MEM=2048M +set.default.JAVA_PERM_MEM=512M +set.default.JAVA_MAX_PERM_MEM=512M + +# Java Application +wrapper.working.dir=%KARAF_BASE% +wrapper.java.command=%JAVA_HOME%/bin/java +wrapper.java.mainclass=org.apache.karaf.shell.wrapper.Main +wrapper.java.classpath.1=%KARAF_BASE%/lib/karaf-wrapper.jar +wrapper.java.classpath.2=%KARAF_HOME%/lib/karaf.jar +wrapper.java.classpath.3=%KARAF_HOME%/lib/karaf-jaas-boot.jar +wrapper.java.classpath.4=%KARAF_BASE%/lib/karaf-wrapper-main.jar +wrapper.java.library.path.1=%KARAF_BASE%/lib/ + +# Application Parameters. Add parameters as needed starting from 1 +#wrapper.app.parameter.1= + +# JVM Parameters +# note that n is the parameter number starting from 1. +wrapper.java.additional.1=-Dkaraf.home=%KARAF_HOME% +wrapper.java.additional.2=-Dkaraf.base=%KARAF_BASE% +wrapper.java.additional.3=-Dkaraf.data=%KARAF_DATA% +wrapper.java.additional.4=-Dcom.sun.management.jmxremote +wrapper.java.additional.5=-Dkaraf.startLocalConsole=false +wrapper.java.additional.6=-Dkaraf.startRemoteShell=true +wrapper.java.additional.7=-Djava.endorsed.dirs=%JAVA_HOME%/jre/lib/endorsed:%JAVA_HOME%/lib/endorsed:%KARAF_HOME%/lib/endorsed +wrapper.java.additional.8=-Djava.ext.dirs=%JAVA_HOME%/jre/lib/ext:%JAVA_HOME%/lib/ext:%KARAF_HOME%/lib/ext + +wrapper.java.additional.9=-Xmx%JAVA_MAX_MEM% +wrapper.java.additional.10=-Xms%JAVA_MIN_MEM% +wrapper.java.additional.11=-XX:PermSize=%JAVA_PERM_MEM% +wrapper.java.additional.12=-XX:MaxPermSize=%JAVA_MAX_PERM_MEM% + +# Allow to customize Karaf options in the .bashrc file +#wrapper.java.additional.13=%CUSTOM_KARAF_OPTIONS% + +# Uncomment to enable jmx +#wrapper.java.additional.n=-Dcom.sun.management.jmxremote.port=1616 +#wrapper.java.additional.n=-Dcom.sun.management.jmxremote.authenticate=false +#wrapper.java.additional.n=-Dcom.sun.management.jmxremote.ssl=false + +# Uncomment to enable YourKit profiling +#wrapper.java.additional.n=-Xrunyjpagent + +# Uncomment to enable remote debugging +#wrapper.java.additional.n=-Xdebug -Xnoagent -Djava.compiler=NONE +#wrapper.java.additional.n=-Xrunjdwp:transport=dt_socket,server=y,suspend=n,address=5005 + +# Initial Java Heap Size (in MB) +#wrapper.java.initmemory=24576 + +# Maximum Java Heap Size (in MB) +#wrapper.java.maxmemory=24576 + + +#******************************************************************** +# Wrapper Logging Properties +#******************************************************************** +# Format of output for the console. (See docs for formats) +wrapper.console.format=PM + +# Log Level for console output. (See docs for log levels) +wrapper.console.loglevel=INFO + +# Log file to use for wrapper output logging. +wrapper.logfile=%KARAF_DATA%/log/wrapper.log + +# Format of output for the log file. (See docs for formats) +wrapper.logfile.format=LPTM + +# Log Level for log file output. (See docs for log levels) +wrapper.logfile.loglevel=INFO + +# Maximum size that the log file will be allowed to grow to before +# the log is rolled. Size is specified in bytes. The default value +# of 0, disables log rolling. May abbreviate with the 'k' (kb) or +# 'm' (mb) suffix. For example: 10m = 10 megabytes. +wrapper.logfile.maxsize=10m + +# Maximum number of rolled log files which will be allowed before old +# files are deleted. The default value of 0 implies no limit. +wrapper.logfile.maxfiles=5 + +# Log Level for sys/event log output. (See docs for log levels) +wrapper.syslog.loglevel=NONE + +#******************************************************************** +# Wrapper Windows Properties +#******************************************************************** +# Title to use when running as a console +wrapper.console.title=karaf + +#******************************************************************** +# Wrapper Windows NT/2000/XP Service Properties +#******************************************************************** +# WARNING - Do not modify any of these properties when an application +# using this configuration file has been installed as a service. +# Please uninstall the service before modifying this section. The +# service can then be reinstalled. + +# Name of the service +wrapper.ntservice.name=karaf + +# Display name of the service +wrapper.ntservice.displayname=karaf + +# Description of the service +wrapper.ntservice.description=KarafFuseESBService + +# Service dependencies. Add dependencies as needed starting from 1 +wrapper.ntservice.dependency.1= + +# Mode in which the service is installed. AUTO_START or DEMAND_START +wrapper.ntservice.starttype=AUTO_START + +# Allow the service to interact with the desktop. +wrapper.ntservice.interactive=false diff --git a/packaging/src/main/resources/sanityCheck.sh b/packaging/src/main/resources/sanityCheck.sh new file mode 100644 index 0000000..935c6a8 --- /dev/null +++ b/packaging/src/main/resources/sanityCheck.sh @@ -0,0 +1,55 @@ +#!/bin/bash +echo "Test if components are up and running..." + +ABS_PATH_NAME=$(readlink -f $0) +DIR=`dirname $ABS_PATH_NAME` + +source $DIR/variables.sh + +JAVA_HOME=/usr/java/default +export JAVA_HOME=/usr/java/default + +$JAVA_HOME/bin/java -version 2> /tmp/tmp.ver +VERSION=`cat /tmp/tmp.ver | grep "java version" | awk '{ print substr($3, 2, length($3)-2); }'` +rm -f /tmp/tmp.ver + +if [[ $VERSION != $JAVA_VER ]] +then +echo "warning: java version doesn't match: $VERSION != $JAVA_VER" +fi + +# check property file exists +if [ ! -f $MODE_CONF_PATH ] +then + echo "error: no property file found at $MODE_CONF_PATH" + exit 1 +fi + +nbWait=24 +numero=0 +while [ $numero != $nbWait ] +do + # Check if component is running + result=`$E3_HOME/$SMX_LINK_DIRNAME/bin/client -p $SMX_PWD -u $SMX_USER list | grep "E3 Bundle" | grep Active` + if [[ $result = *Failed* ]]; then + echo "E3 Bundle component failed start" + exit 1 + fi + if [[ $result = *Waiting* ]]; then + result="In Wait" + fi + if [[ $result = *Active* ]]; then + echo "E3 Bundle component up and running" + exit 0 + else + numero=`expr $numero + 1` + if [ $numero = $nbWait ] ; then + echo "E3 Bundle component not started" + exit 1 + fi + sleep 5 + fi +done + +echo "Sanity Check script error" +exit 1 diff --git a/packaging/src/main/resources/template-installer-config.xml b/packaging/src/main/resources/template-installer-config.xml new file mode 100644 index 0000000..51c8408 --- /dev/null +++ b/packaging/src/main/resources/template-installer-config.xml @@ -0,0 +1,26 @@ + + + + + + + + + \ No newline at end of file diff --git a/packaging/src/main/resources/template-system_topology_cluster.xml b/packaging/src/main/resources/template-system_topology_cluster.xml new file mode 100644 index 0000000..0c5cc87 --- /dev/null +++ b/packaging/src/main/resources/template-system_topology_cluster.xml @@ -0,0 +1,30 @@ + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + diff --git a/packaging/src/main/resources/template-topology_cluster.xml b/packaging/src/main/resources/template-topology_cluster.xml new file mode 100644 index 0000000..e17eea9 --- /dev/null +++ b/packaging/src/main/resources/template-topology_cluster.xml @@ -0,0 +1,51 @@ + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + diff --git a/packaging/src/main/resources/upgrade_e3_aib.sh b/packaging/src/main/resources/upgrade_e3_aib.sh new file mode 100644 index 0000000..af61d2d --- /dev/null +++ b/packaging/src/main/resources/upgrade_e3_aib.sh @@ -0,0 +1,11 @@ +#!/bin/sh + + +sh install_e3_aib.sh + +if [ $? != 0 ] +then + echo "Upgrade failed, exiting" + exit 1 +fi + diff --git a/packaging/src/main/resources/upgrade_e3_cluster.sh b/packaging/src/main/resources/upgrade_e3_cluster.sh new file mode 100644 index 0000000..0b40582 --- /dev/null +++ b/packaging/src/main/resources/upgrade_e3_cluster.sh @@ -0,0 +1,27 @@ +#!/bin/sh + +ABS_PATH_NAME=$(readlink -f $0) +DIR=`dirname $ABS_PATH_NAME` + +source $DIR/variables.sh + +PATH_TO_TAR_GZ=$1 + +# backup config files +cp $E3_HOME/topology.xml $DIR/../ +if [ $? != 0 ] +then + echo "unable to backup the topology, exiting" + exit 1 +fi + +cp $E3_HOME/system_topology.xml $DIR/../ +if [ $? != 0 ] +then + echo "unable to backup the system_topology, exiting" + exit 1 +fi + +# Call install +sh $DIR/install_e3_cluster.sh $PATH_TO_TAR_GZ + diff --git a/packaging/src/main/resources/variables.sh b/packaging/src/main/resources/variables.sh new file mode 100644 index 0000000..296f77d --- /dev/null +++ b/packaging/src/main/resources/variables.sh @@ -0,0 +1,86 @@ +#!/bin/bash + +ABS_PATH_NAME=$(readlink -f $0) +DIR=`dirname $ABS_PATH_NAME` + + +JAVA_VER=1.6.0_32 + +E3_JAVA_64_BIN=$DIR/../tools/x64-6u32-linux-x64-rpm.bin +E3_JAVA_32_BIN=$DIR/../tools/i586-6u32-linux-i586-rpm.bin +E3_FUSE_NAME=apache-servicemix-4.3.1-fuse-01-09 +E3_FUSE_GZ=$DIR/../tools/$E3_FUSE_NAME.tar.gz + +INSTALLER_HOME=$DIR/.. + +BUNDLES=$DIR/../bundles/ + +FEATURES=$DIR/../features/features.xml + +JCE_PROVIDER_LIB=$BUNDLES/bcprov-jdk16-1.46.jar + +# dependency archive path +DEP_ARCHIVE=$DIR/../thirdparty-dependencies/thirdparty-dependencies.tar.gz + +# file containing service mix external maven repositories +SERVICE_MIX_MVN_REPO_FILE=org.ops4j.pax.url.mvn.cfg + +# username/group, owner of E3 +USER=e3 +GROUP=e3 + +# installation directories +# base directory where fuse will be installed +E3_HOME=/home/$USER +# name of the symbolic link to fuse installation, located in E3_HOME directory +SMX_LINK_DIRNAME=apache-servicemix + +# ssh fuse user/pwd +SMX_USER=smx +SMX_PWD=smx + +# ESB full path (a link will be created in $E3_HOME/$SMX_LINK_DIRNAME +ESB_FULL_PATH=$E3_HOME/apache-servicemix-4.3.1-fuse-01-09 + +# configuration parameters +# template file use for karaf wrapper configuration (update java memory params in this file) +KARAF_WRAPPER_TEMPLATE=$DIR/karaf-wrapper.conf + +# karaf main configuration file: configured to use felix by default +KARAF_CONFIG_FILE=$DIR/config.properties + +# file max/limits configuration +FILE_MAX=1048576 +FILE_LIMITS=1048500 + +# path to configuration file indicating mode (manager or gateway) +MODE_CONF_PATH=$E3_HOME/configuration.properties + +# file containing jetty http/https config through pax-web +SERVICE_MIX_PAX_WEB_CFG_FILE=org.ops4j.pax.web.cfg + +# enable/disable https access to provisioning rest api +# possible values are 1 or 0. Default port is 8443 +PROV_REST_API_HTTPS_ENABLE=0 +# Path to E3 Rest server keystore. ex: $E3_HOME/rest-keystore.jks +PROV_REST_API_KEYSTORE_PATH=$E3_HOME/rest-keystore.jks +# E3 Rest server keystore password +PROV_REST_API_KEYSTORE_PASSWORD= +# E3 Rest server key password +PROV_REST_API_KEYSTORE_KEYPASSWORD= + +# enable/disable http access to provisioning rest api +# possible values are 1 or 0. Default port is 8181. +PROV_REST_API_HTTP_ENABLE=1 + +# enable/disable basic authentication to access provisioning rest api +# possible values are 1 or 0 +PROV_REST_API_BASICAUTH_ENABLE=0 +PROV_REST_API_BASICAUTH_USERNAME=changeit +PROV_REST_API_BASICAUTH_PASSWORD=changeit + +# Activate IP whitelist. +PROV_REST_API_IPWHITELIST_ENABLE=0 +# ip list 192.168.84.135 192.168.84.135 192.168.84.135 +PROV_REST_API_IPWHITELIST= + diff --git a/packaging/src/main/resources/wait-karaf-down.sh b/packaging/src/main/resources/wait-karaf-down.sh new file mode 100644 index 0000000..7bc8886 --- /dev/null +++ b/packaging/src/main/resources/wait-karaf-down.sh @@ -0,0 +1,30 @@ +#!/bin/bash + +ABS_PATH_NAME=$(readlink -f $0) +DIR=`dirname $ABS_PATH_NAME` + +source $DIR/variables.sh + +serviceMixDown=0 +retry=20 +for n in `seq 1 $retry` +do + $E3_HOME/$SMX_LINK_DIRNAME/bin/client -p $SMX_PWD -u $SMX_USER ' ' + if [[ ${?} = 0 ]] + then + echo "Karaf is still up, retrying in 5 seconds..." + sleep 5 + else + echo "OK, Karaf is down" + serviceMixDown=1 + break + fi +done + +if [[ $serviceMixDown == 1 ]] +then + exit 0 +else + echo 'Failed to stop karaf' + exit 1 +fi diff --git a/packaging/src/main/resources/wait-karaf.sh b/packaging/src/main/resources/wait-karaf.sh new file mode 100644 index 0000000..4dcd279 --- /dev/null +++ b/packaging/src/main/resources/wait-karaf.sh @@ -0,0 +1,31 @@ +#!/bin/bash + +ABS_PATH_NAME=$(readlink -f $0) +DIR=`dirname $ABS_PATH_NAME` + +source $DIR/variables.sh + +serviceMixOk=0 +retry=3 +for n in `seq 1 $retry` +do + $E3_HOME/$SMX_LINK_DIRNAME/bin/client -p $SMX_PWD -u $SMX_USER ' ' + if [[ ${?} != 0 ]] + then + # unable to connect: wait and retry + echo "retrying in 3 seconds..." + sleep 3 + else + echo "OK, Karaf is started" + serviceMixOk=1 + break + fi +done + +if [[ $serviceMixOk == 0 ]] +then + exit 0 +else + exit 1 +fi + diff --git a/pom-assembly.xml b/pom-assembly.xml new file mode 100644 index 0000000..bb4195e --- /dev/null +++ b/pom-assembly.xml @@ -0,0 +1,166 @@ + + 4.0.0 + + com.alu.opensource + e3 + 1.0.1 + pom + e3 + + + ${project.name}-${project.version} + + + 1.46 + + file:///su/${e3.module.name}/${e3.module.name}.tar.gz + ${project.version} + ${project.name} + apigrove-installer-front-end-module_${project.version} + UTF-8 + + + + + + + org.apache.maven.plugins + maven-assembly-plugin + 2.2.2 + + + + + + + + build-modules + + ./pom.xml + + + + build-front-end-module + + front-end + + + + + + assembly + + + + + packaging/src/main/resources + true + + + + + org.apache.maven.plugins + maven-assembly-plugin + + false + ${e3.module.name} + target/server-side + + packaging/src/main/assembly/main.xml + + + + + package + + single + + + + + + + + org.apache.maven.plugins + maven-resources-plugin + 2.5 + + + gen-resources + process-resources + + resources + + + + + + + + + + + + assembly-front-end + + + + org.apache.maven.plugins + maven-assembly-plugin + + false + ${e3.install.front.end.module.name} + target/front-end + + packaging-front-end/src/main/assembly/main.xml + + + + + Front End packaging PHP and Installer + package + + single + + + + + + + org.apache.maven.plugins + maven-install-plugin + + + default-install + none + + true + + + + + + + + + com.alu.opensource + front-end + + [0.0.1-SNAPSHOT,) + zip + + + + + + + + + org.bouncycastle + bcprov-jdk16 + ${version.bouncycastle} + jar + + + \ No newline at end of file diff --git a/pom.xml b/pom.xml new file mode 100644 index 0000000..459fca9 --- /dev/null +++ b/pom.xml @@ -0,0 +1,22 @@ + + + 4.0.0 + + com.alu.e3 + root + E3 Root + 1.0.1 + + pom + + + exposure-engine + bundle + + + + UTF-8 + + + \ No newline at end of file diff --git a/tests/HOW_TO_RUN_TESTS b/tests/HOW_TO_RUN_TESTS new file mode 100644 index 0000000..a1c5665 --- /dev/null +++ b/tests/HOW_TO_RUN_TESTS @@ -0,0 +1,14 @@ +In order to run the tests, you will need to download SoapUI 4.x from http://www.soapui.org/ + +In each SoapUI project, there are several variables to modify: +- IP_ADDRESS_OF_MANAGER: Should be the IP address of the E3 Manager. +- IP_ADDRESS_OF_GATEWAY: Should be the IP address of the E3 Gateway (can be the same as the Manager, which is the default when installing with install_e3_aib.sh). +- IP_ADDRESS_OF_FIRST_TARGET: Should be the IP address of a mock endpoint, simulating a target service. +- IP_ADDRESS_OF_SECOND_TARGET: Should be the IP address of a mock endpoint, simulating a target service (can be the same). +- IP_ADDRESS_OF_THIRD_TARGET: Should be the IP address of a mock endpoint, simulating a target service (can be the same). + +Each of the simulated services should be running a PHP Web Server on port 8080, with the scripts compositeEndpoint.php, parametersEndpoint.php and proxySize.php (see tests\src\site). +Those "target" services should be accessible with an URL such as: + + http://aaa.bbb.ccc.ddd:8080/proxySize + diff --git a/tests/functional-tests/functional-test-auth-basic/pom.xml b/tests/functional-tests/functional-test-auth-basic/pom.xml new file mode 100644 index 0000000..5d2df06 --- /dev/null +++ b/tests/functional-tests/functional-test-auth-basic/pom.xml @@ -0,0 +1,48 @@ + + 4.0.0 + com.alu.e3.functional-tests.samples + functional-test-auth-basic + pom + + + + eviware + maven-soapui-plugin + 4.0.1 + + + mysql + mysql-connector-java + 5.1.6 + + + junit + junit + 4.8.1 + + + + + test + + test + + + ${basedir}/soapui-project.xml + ${basedir}/target/surefire-reports + true + ${basedir}/soapui-project-properties.xml + + + + + + + + com.alu.e3.functional-tests + functional-tests + 0.0.1-SNAPSHOT + .. + + Functional test auth basic + \ No newline at end of file diff --git a/tests/functional-tests/functional-test-auth-basic/soapui-project.xml b/tests/functional-tests/functional-test-auth-basic/soapui-project.xml new file mode 100644 index 0000000..e76d141 --- /dev/null +++ b/tests/functional-tests/functional-test-auth-basic/soapui-project.xml @@ -0,0 +1,7890 @@ + + +http://${#Project#E3Gateway}/api-parameters-endpoint1?param1=value1&key=api-parameters-key1&param2=value2http://${#Project#E3Gateway}/api-parameters-endpoint2/five?key=api-parameters-key2http://${#Project#E3Gateway}/api-parameters-endpoint2/three/five?key=api-parameters-key2apiauthTEMPLATEkeymykeyQUERYmykeyparam1QUERYtext/plain403 500 429data200data200data0data0data0data200data200data200data200data200data200data0datatext/html200<xml-fragment/>http://${#Project#E3Gateway}keymykeyQUERYmykeyparam1value1QUERYvalue1param2value2QUERYvalue2text/plain403data200data200data0data0data0data200data200data200data200data200data200data200datatext/html2000data<xml-fragment/>http://${#Project#E3Gateway}param1value1QUERYvalue1keymykeyQUERYxs:stringmykeyparam2value2QUERYvalue2text/plain403data200data200data0data0data0data200data200data200data200data200data200datatext/html200<xml-fragment/>http://${#Project#E3Gateway}param1value1QUERYvalue1param2value2QUERYvalue2keymykeyQUERYxs:stringmykeytext/plain403data200data200data0data0data0data200data200data200data200data200data200datatext/html200<xml-fragment/>http://${#Project#E3Gateway}text/plain403data200data200data0data0data0data200data200data200data200data200data200datatext/html200text/html;charset=ISO-8859-1404htmltext/html404html<xml-fragment/>http://${#Project#E3Gateway}param1QUERYtext/plain403 500 429data200data200data0data0data0data200data200data200data200data200data200data0datatext/html200text/html404html<xml-fragment/>http://${#Project#E3Gateway}keyQUERYtext/plain403 500 429data200data200data0data0data0data200data200data200data200data200data200data0datatext/html200text/html;charset=ISO-8859-1404html<xml-fragment/>http://${#Project#E3Gateway}text/plain403data200data200data0data0data0data200data200data200data200data200data200datatext/html200text/html;charset=ISO-8859-1404html0data<xml-fragment/>http://${#Project#E3Gateway}text/plain403data200data200data0data0data0data200data200data200data200data200data200datatext/html200text/html;charset=ISO-8859-1404html<xml-fragment/>http://${#Project#E3Gateway}text/plain403data200data200data0data0data0data200data200data200data200data200data200datatext/html200text/html;charset=ISO-8859-1404html0data0data0data0data<xml-fragment/>http://${#Project#E3Gateway}param1QUERYtext/plain403data200data200data0data0data0data200data200data200data200data200data200datatext/html200text/html;charset=ISO-8859-1404html0data<xml-fragment/>http://${#Project#E3Gateway}param1QUERYkeyQUERYtext/plain403data200data200data0data0data0data200data200data200data200data200data200datatext/html200text/html;charset=ISO-8859-1404html0data<xml-fragment/>http://${#Project#E3Gateway}keyQUERYtext/plain403data200data200data0data0data0data200data200data200data200data200data200datatext/html200text/html;charset=ISO-8859-1404html0data<xml-fragment/>http://${#Project#E3Gateway}text/plain403data200data200data0data0data0data200data200data200data200data200data200datatext/html200text/html;charset=ISO-8859-1404html0data0data<xml-fragment/>http://${#Project#E3Gateway}param1QUERYtext/plain403data200data200data0data0data0data200data200data200data200data200data200datatext/html200text/html;charset=ISO-8859-1404html0data<xml-fragment/>http://${#Project#E3Gateway}param1QUERYkeyQUERYtext/plain403data200data200data0data0data0data200data200data200data200data200data200datatext/html200text/html;charset=ISO-8859-1404html0data<xml-fragment/>http://${#Project#E3Gateway}text/plain403data200data200data0data0data0data200data200data200data200data200data200datatext/html200text/html;charset=ISO-8859-1404html<xml-fragment/>http://${#Project#E3Gateway}text/plain403 500data200data200data0data0data0data200data200data200data200data200data200datatext/html200text/html;charset=ISO-8859-1404html0datatext/html; charset=iso-8859-1404html<xml-fragment/>http://${#Project#E3Gateway}text/plain403data200data200data0data0data0data200data200data200data200data200data200datatext/html200text/html;charset=ISO-8859-1404html<xml-fragment/>http://${#Project#E3Gateway}text/html200text/plain403 500datatext/html404htmlhttp://${#Project#E3Gateway} + + + http://${#Project#E3Gateway}/auth-extended-endpoint1?key=auth-extended-key1http://${#Project#E3Gateway}/auth-extended-endpoint1http://${#Project#E3Gateway}/auth-key-endpoint2http://${#Project#E3Gateway}/api-header-transform-endpoint1?key=api-header-transform-key1http://${#Project#E3Gateway}/api-header-transform-endpoint2?key=api-header-transform-key2http://${#Project#E3Gateway}/api-header-transform-endpoint3?key=api-header-transform-key3http://${#Project#E3Gateway}/provision-api-ext-endpoint1http://${#Project#E3Gateway}/provision-api-ext-endpoint3?key=provision-api-ext-key3https://${#Project#E3Gateway}/tls2ways-call-expired-endpoint1https://${#Project#E3Gateway}/tls2ways-call-ko-endpoint1https://${#Project#E3Gateway}/tls2ways-call-no-cert-endpoint1https://${#Project#E3Gateway}/tls2ways-call-ok-endpoint1https://${#Project#E3Gateway}:25101/provision-sslkey-endpoint3https://${#Project#E3Gateway}:25101/provision-sslkey-endpoint4?key=provision-sslkey-key4http://${#Project#E3Gateway}/tdr-smoke-endpoint1?key=tdr-smoke-key1http://${#Project#E3Gateway}/tdr-endpoint1?key=tdr-key1http://${#Project#E3Gateway}/rate-limit-aib-and-cluster-endpoint2?key=rate-limit-aib-and-cluster-key2http://${#Project#E3Gateway}/rate-limit-aib-and-cluster-endpoint3?key=rate-limit-aib-and-cluster-key3http://${#Project#E3Gateway}/rate-limit-aib-endpoint2http://${#Project#E3Gateway}/rate-limit-aib-endpoint3?key=rate-limit-aib-key3http://${#Project#E3Gateway}/api-provision-endpoint5?key=api-provision-key5http://${#Project#E3Gateway}/api-provision-endpoint5_2?key=api-provision-key5http://${#Project#E3Gateway}/api-provision-endpoint6?key=api-provision-key6http://${#Project#E3Gateway}/api-provision-endpoint6_2?key=api-provision-key6http://${#Project#E3Gateway}/api-provision-endpoint7?key=api-provision-key7http://${#Project#E3Gateway}/api-provision-endpoint8_2?key=api-provision-key8http://${#Project#E3Gateway}/api-provision-endpoint8http://${#Project#E3Gateway}/api-provision-endpoint9http://${#Project#E3Gateway}/api-provision-endpoint9_2http://${#Project#E3Gateway}/api-provision-endpoint9_2?key=api-provision-key9http://${#Project#E3Gateway}/api-provision-endpoint10http://${#Project#E3Gateway}/api-provision-endpoint10_2http://${#Project#E3Gateway}/api-provision-endpoint10_2?key=api-provision-key10http://${#Project#E3Gateway}/api-provision-endpoint11http://${#Project#E3Gateway}/api-provision-endpoint11_2http://${#Project#E3Gateway}/api-provision-endpoint11_2?key=api-provision-key11http://${#Project#E3Gateway}/api-provision-endpoint12http://${#Project#E3Gateway}/api-provision-endpoint12_2http://${#Project#E3Gateway}/api-provision-endpoint12_2?key=api-provision-key12http://${#Project#E3Gateway}/api-provision-endpoint13http://${#Project#E3Gateway}/api-provision-endpoint13_2http://${#Project#E3Gateway}/api-provision-endpoint13_2?key=api-provision-key13http://${#Project#E3Gateway}/api-provision-endpoint18?key=api-provision-key18http://${#Project#E3Gateway}/api-provision-endpoint18_2?key=api-provision-key18http://${#Project#E3Gateway}/api-provision-endpoint19?key=api-provision-key19http://${#Project#E3Gateway}/api-provision-endpoint19_2?key=api-provision-key19http://${#Project#E3Gateway}/auth-type-ip-white-list-endpoint2http://${#Project#E3Gateway}/auth-type-ip-white-list-endpoint3http://${#Project#E3Gateway}/auth-type-ip-white-list-endpoint4http://${#Project#E3Gateway}/auth-type-ip-white-list-endpoint5http://${#Project#E3Gateway}/auth-type-ip-white-list-endpoint9http://${#Project#E3Gateway}/auth-basic-endpoint4http://${#Project#E3Gateway}/provision-api-loadbalancing-endpoint1?uniqueId=${#TestCase#uniqueId}http://${#Project#E3Gateway}/provision-api-loadbalancing-endpoint2?uniqueId=${#TestCase#uniqueId}http://${#Project#E3Gateway}/provision-api-loadbalancing-endpoint3?uniqueId=${#TestCase#uniqueId} + + + + + + keyQUERY + + text/html + 200 + + html + + + + 0 + + data + + + text/plain + 500 403 401 429 + + data + + + + 200 + + data + + + + 200 + + data + + + text/html + 404 + + html + + 0data0data0data0data0data + 0data0datatext/xml200data0data<xml-fragment xmlns:con="http://eviware.com/soapui/config"> + <con:entry key="WAIT" value="0"/> + <con:entry key="SIZE" value="100"/> +</xml-fragment>http://${#Project#E3Gateway}/endpoint1<xml-fragment xmlns:con="http://eviware.com/soapui/config"> + <con:entry key="WAIT" value="0"/> + <con:entry key="SIZE" value="100"/> +</xml-fragment>http://${#Project#E3Gateway}/endpoint1 + text/plain401 403 429 500datatext/html200html0data0data0data0datatext/html404htmltext/xml200data0data0data0data0data0data0data0data0data0data0data0data<xml-fragment xmlns:con="http://eviware.com/soapui/config"> + <con:entry key="WAIT" value="0"/> + <con:entry key="SIZE" value="100"/> +</xml-fragment>http://${#Project#E3Gateway}/endpoint1text/plain401 500 429 403data0data0data0data0data0data0data0data0data0data0datatext/xml200datatext/html404htmltext/html200data<xml-fragment xmlns:con="http://eviware.com/soapui/config"> + <con:entry key="Authorization" value="Basic dGVzdGVyOnRlc3RlcnBhc3N3b3Jk"/> + <con:entry key="WAIT" value="0"/> + <con:entry key="SIZE" value="100"/> +</xml-fragment>http://${#Project#E3Gateway}/endpoint1<xml-fragment xmlns:con="http://eviware.com/soapui/config"> + <con:entry key="Authorization" value="Basic invalidbasic"/> + <con:entry key="WAIT" value="0"/> + <con:entry key="SIZE" value="100"/> +</xml-fragment>http://${#Project#E3Gateway}/endpoint1text/xml200datatext/html200data<xml-fragment xmlns:con="http://eviware.com/soapui/config"> + <con:entry key="WAIT" value="0"/> + <con:entry key="SIZE" value="100"/> +</xml-fragment>http://${#Project#E3Gateway}/endpoint1?key=e88ba0c1e4c34f25bf95733eebd8574f + http://${#Project#E3Gateway}:8181/cxf/e3/prov/v1?_wadl&_type=xml + + + + E3 REST API to create, update or delete an API + + Used to get all API IDs. + + + + + + This REST API is used to create an API. + + + + + + + + + + + This REST API is used to delete an API. + + + + + + + Used to get an API by this ID. + + + + + + + This REST API is used to update an API. + + + + + + + + + + + E3 REST API to create, update or delete a policy + + This REST API is used to fetch all policy ids. + + + + + + This REST API is used to create a policy. + + + + + + + + + + + This REST API is used to delete a policy. + + + + + + + This REST API is used to fetch policy data. + + + + + + + This REST API is used to update a policy. + + + + + + + + + + + + This REST API is used to create a QuotaRLBucket in a policy. + + + + + + + + + + + + + This REST API is used to remove a bucket from a policy. + + + + + + + This REST API is used to append auths to a bucket. + + + + + + + + + + + + + + This REST API is used to remove an auth from a bucket. + + + + + + + + + E3 REST API provision authentications on E3 subsystem + + This REST API is used to get all authentications from E3 subsystem. + + + + + + This REST API is used to create an authentication element on E3 subsystem. + + + + + + + + + + + This REST API is used to delete an Auth. + + + + + + + This REST API is used to get an authentication by ID from E3 subsystem. + + + + + + + This REST API is used to update an authentication. + + + + + + + + + + + E3 REST API to create or delete a bucket of auths associated to a list of policies + + This REST API is used to create a bucket linked to a list of policies. + + + + + + + + + + + This REST API is used to append auths to a bucket for several policies. + + + + + + + + + + + + This REST API is used to remove a bucket from a list of policies. + + + + + + + + + + + E3 REST API provision SSLKeys and SSLCerts on E3 subsystem + + This REST API is used to get all SSLKeys from E3 subsystem. + + + + + + This REST API is used to create an SSLKey element on E3 subsystem. + + + + + + + + + + + This REST API is used to delete an SSLKey. + + + + + + + This REST API is used to get an SSLKey by ID from E3 subsystem. + + + + + + + This REST API is used to update an SSLKey. + + + + + + + + + + + + This REST API is used to get all SSLCerts for a key. + + + + + + + This REST API is used to create an SSLCert element on E3 subsystem. + + + + + + + + + + + + + This REST API is used to delete an SSLCert. + + + + + + + This REST API is used to get an SSLKey by ID from E3 subsystem. + + + + + + + This REST API is used to update an SSLKey. + + + + + + + + + + + + This REST API is used to get a CSR for the given SSLKey ID from E3 subsystem. + + + + + + + + + + This REST API is used to create a self-signed cert for an existing Key + + + + + + + + + E3 REST API to add/update/delete trusted CAs and CRLs + + + This REST API is used to fetch all trusted certificates authorithies. + + + + + + This REST API is used to add a trusted Certificate Authority. + + + + + + + + + + + + This REST API is used to remove a trusted Certificate Authority. + + + + + + + This REST API is used to fetch trusted Certificate Authority. + + + + + + + This REST API is used to update a trusted Certificate Authority. + + + + + + + + + + + This REST API is used to fetch trusted Certificate Authority. + + + + + + This REST API is used to add a Certificate Revocation List for this Certificate Authority. + + + + + + + + + + + + This REST API is used to remove a certificate revocation list from a certificate authority. + + + + + + + This REST API is used to fetch Certificate Revocation List. + + + + + + + This REST API is used to update a certificate revocation list. + + + + + + + + + + +]]>http://wadl.dev.java.net/2009/02http://${#Project#E3Manager}:8181API_IDTEMPLATExs:stringapplication/xmlhttp://${#Project#E3Gateway}:8181application/xmlhttp://${#Project#E3Gateway}:8181application/xmlapplication/xmlhttp://${#Project#E3Gateway}:8181application/xmlhttp://${#Project#E3Gateway}:8181application/xmlapplication/xmlhttp://${#Project#E3Gateway}:8181POLICY_IDTEMPLATExs:stringapplication/xmlhttp://${#Project#E3Gateway}:8181application/xmlhttp://${#Project#E3Gateway}:8181application/xmlapplication/xmlhttp://${#Project#E3Gateway}:8181POLICY_IDTEMPLATExs:stringapplication/xmlapplication/xmlhttp://${#Project#E3Gateway}:8181POLICY_IDTEMPLATExs:stringBUCKET_IDTEMPLATExs:stringapplication/xmlhttp://${#Project#E3Gateway}:8181application/xmlapplication/xmlhttp://${#Project#E3Gateway}:8181POLICY_IDTEMPLATExs:stringBUCKET_IDTEMPLATExs:stringAUTH_IDTEMPLATExs:stringapplication/xmlhttp://${#Project#E3Gateway}:8181application/xmlhttp://${#Project#E3Gateway}:8181application/xmlapplication/xmlhttp://${#Project#E3Gateway}:8181AUTH_IDTEMPLATExs:stringapplication/xmlhttp://${#Project#E3Gateway}:8181application/xmlhttp://${#Project#E3Gateway}:8181application/xmlapplication/xmlhttp://${#Project#E3Gateway}:8181application/xmlhttp://${#Project#E3Gateway}:8181application/xmlapplication/xmlhttp://${#Project#E3Gateway}:8181BUCKET_IDTEMPLATExs:stringapplication/xmlapplication/xmlhttp://${#Project#E3Gateway}:8181BUCKET_IDTEMPLATExs:stringapplication/xmlapplication/xmlhttp://${#Project#E3Gateway}:8181application/xmlapplication/xmlhttp://${#Project#E3Gateway}:8181KEY_IDTEMPLATExs:stringapplication/xmlhttp://${#Project#E3Gateway}:8181application/xmlhttp://${#Project#E3Gateway}:8181application/xmlapplication/xmlhttp://${#Project#E3Gateway}:8181KEY_IDTEMPLATExs:stringapplication/xmlhttp://${#Project#E3Gateway}:8181application/xmlapplication/xmlhttp://${#Project#E3Gateway}:8181KEY_IDTEMPLATExs:stringCERT_IDTEMPLATExs:stringapplication/xmlhttp://${#Project#E3Gateway}:8181application/xmlhttp://${#Project#E3Gateway}:8181application/xmlapplication/xmlhttp://${#Project#E3Gateway}:8181KEY_IDTEMPLATExs:stringapplication/xmlhttp://${#Project#E3Gateway}:8181KEY_IDTEMPLATExs:stringapplication/xmlhttp://${#Project#E3Gateway}:8181application/xml<xml-fragment/>http://${#Project#E3Gateway}:8181application/xmlapplication/xmlhttp://${#Project#E3Gateway}:8181application/xml<xml-fragment/>http://${#Project#E3Gateway}:8181application/xmlapplication/xmlhttp://${#Project#E3Gateway}:8181CA_IDTEMPLATExs:stringapplication/xmlhttp://${#Project#E3Gateway}:8181application/xmlhttp://${#Project#E3Gateway}:8181application/xmlapplication/xmlhttp://${#Project#E3Gateway}:8181application/xmlhttp://${#Project#E3Gateway}:8181application/xmlapplication/xmlhttp://${#Project#E3Gateway}:8181CRL_IDTEMPLATExs:stringapplication/xmlhttp://${#Project#E3Gateway}:8181application/xmlhttp://${#Project#E3Gateway}:8181application/xmlapplication/xmlhttp://${#Project#E3Gateway}:8181file:/D:/Documents%20and%20Settings/mtobiasz/Desktop/targertest_1.wadl + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + +]]>http://wadl.dev.java.net/2009/02http://${#Project#E3Gateway}http://${#Project#E3Gateway}/api-http-method-endpoint1?key=api-http-method-key1http://${#Project#E3Gateway}/api-http-method-endpoint2?key=api-http-method-key2http://${#Project#E3Gateway}/api-http-method-endpoint3?key=api-http-method-key3http://${#Project#E3Gateway}/api-http-method-endpoint4?key=api-http-method-key40text/html200http://${#Project#E3Gateway}application/xml0application/xmltext/plain403 405 429text/xml200ns:responsehttp://${#Project#E3Gateway}application/xmlapplication/xmltext/plain405 429text/xml200ns:responsehttp://${#Project#E3Gateway}text/plain405 429text/xml200ns:responsehttp://${#Project#E3Gateway}0text/plain405text/xml200http://${#Project#E3Gateway}http://135.248.213.24:8181pathToConfigFilesDirectoryTEMPLATExs:stringapplication/octet-streamhttp://135.248.213.24:8181application/octet-streamhttp://135.248.213.24:8181numLinesTEMPLATExs:stringapplication/xmlhttp://135.248.213.24:8181numLinesTEMPLATExs:stringapplication/xmlhttp://135.248.213.24:8181application/xmlhttp://135.248.213.24:8181instanceIdTEMPLATExs:stringapplication/xml<xml-fragment/>http://135.248.213.36:8181application/octet-streamapplication/xmlhttp://135.248.213.24:8181instanceIdTEMPLATExs:stringapplication/xmlhttp://135.248.213.24:8181application/octet-streamapplication/xmlhttp://135.248.213.24:8181instanceIdTEMPLATExs:stringapplication/xmlhttp://135.248.213.24:8181application/octet-streamapplication/xmlhttp://135.248.213.24:8181application/octet-streamhttp://135.248.213.24:8181application/octet-streamhttp://135.248.213.24:8181application/xml<xml-fragment/>http://135.248.213.24:8181application/octet-streamapplication/xml<xml-fragment/>http://135.248.213.24:8181application/xmlhttp://135.248.213.24:8181application/xmlapplication/xmlhttp://135.248.213.24:8181application/xmlhttp://135.248.213.24:8181application/octet-streamapplication/xmlhttp://135.248.213.24:8181application/xml<xml-fragment/>http://135.248.213.24:8181application/octet-streamapplication/xmlhttp://135.248.213.24:8181 + TestSuite generated for REST Service + [functional-test-provision-api] + + SEQUENTIAL + + + + + + + + + + + + TestCase generated for REST Resource [/apis] located + at [/apis] + + + <xml-fragment/>http://${#Project#E3Manager}:8181 + + + + + + + + + + +]]> + + + http://${#Project#E3Manager}:8181 + + + + + + + + + + + + + + + + +]]> + + http://${#Project#E3Manager}:8181 + + auth-key-api1 + test_route_1 + active + PassThrough + auth-key-endpoint1 + false + + + authKey + + + key + + + + false + + + + + + http://${#Project#Target1}:8080/proxySize.php + + NoAuth + + key000Val + + + + + active + 10 + 0.0 + 10 + 0.0 + + + + + + + CompanyQuota + Billing + + + + + + CompanyQuota + Billing + + + +]]> + + 200 + + + + /response/status + SUCCESS + false + false + false + + + + /response/idauth-key-api1falsefalsefalse + + + + + + + + + + <xml-fragment/>http://${#Project#E3Manager}:8181 + auth-key-auth1 + active + authKey + + + + + + + + + + CompanyQuota + Billing + + + + + + CompanyQuota + Billing + + + +]]>400/response + + authKey must not be empty for AuthKey authentication type. + 400 + + FAILURE +]]>falsefalsefalse + + <xml-fragment/>http://${#Project#E3Manager}:8181 + + + + + + + + + +]]> + + + http://${#Project#E3Manager}:8181 + + + + + + + + + TestCase generated for REST Resource [/apis] located + at [/apis] + + <xml-fragment/>http://${#Project#E3Manager}:8181 + <xml-fragment/>http://${#Project#E3Manager}:8181 + + + + + + + + + + +]]> + + + http://${#Project#E3Manager}:8181 + + + + + + + + + + + + + + + + +]]> + + http://${#Project#E3Manager}:8181 + + auth-key-api2 + test_route_1 + active + PassThrough + auth-key-endpoint2 + false + + + authKey + + + key + + + + false + + + + + + http://${#Project#Target1}:8080/proxySize.php + + NoAuth + + key000Val + + + + + active + 10 + 0.0 + 10 + 0.0 + + + + + + + CompanyQuota + Billing + + + + + + CompanyQuota + Billing + + + +]]> + + 200 + + + + /response/status + SUCCESS + false + false + false + + + + /response/idauth-key-api2falsefalsefalse + + + + + + + + + + <xml-fragment/>http://${#Project#E3Manager}:8181 + auth-key-auth2 + active + authKey + + + + auth-key-key2 + + + + + + CompanyQuota + Billing + + + + + + CompanyQuota + Billing + + + +]]>200/response/idauth-key-auth2falsefalsefalse/response/statusSUCCESSfalsefalsefalse + + + + + + + + + + + +]]> + + http://${#Project#E3Manager}:8181 + + auth-key-auth2 + active + authKey + + + + auth-key-key2 + + + + + + CompanyQuota + Billing + + + + + + CompanyQuota + Billing + + + +]]> + + + /response/error/errorCode500falsefalsefalse + + + Provisioning Server Error: java.lang.IllegalArgumentException: Auth already exists with that IDfalsefalsefinal String EXPECTED_STATUS = "HTTP/1.1 500 Internal Server Error" +final String RESPONSE_STATUS = messageExchange.getResponseHeaders().get("#status#")[0] +//Verify response code status. Should be HTTP/1.1 500 Internal Server Error +assert EXPECTED_STATUS.equals(RESPONSE_STATUS) : "Expected status is \"${EXPECTED_STATUS}\" but was \"${RESPONSE_STATUS}\""/response/statusFAILUREfalsefalsefalse + + + + + <xml-fragment/>http://${#Project#E3Manager}:8181 + auth-key-p2 + + auth-key-api2 + + + + auth-key-auth2 + + + + + active + + active + reject + 98 + 1000 + + + + active + + +]]>200/response/idauth-key-p2falsefalsefalse/response/statusSUCCESSfalsefalsefalse1000 + + + + + <xml-fragment/> + + http://${#Project#E3Gateway}/auth-key-endpoint2 + + + 200 + + + + + + + <xml-fragment xmlns:con="http://eviware.com/soapui/config"> + <con:entry key="X-App-AuthKey" value="auth-key-key2"/> + <con:entry key="SIZE" value="10"/> +</xml-fragment>http://${#Project#E3Gateway}/auth-key-endpoint29876543210falsefalse200<xml-fragment/>http://${#Project#E3Gateway}/auth-key-endpoint2401<xml-fragment/>http://${#Project#E3Manager}:8181<xml-fragment/>http://${#Project#E3Manager}:8181 + + + + + + + + + +]]> + + + http://${#Project#E3Manager}:8181 + + + + + + + + + TestCase generated for REST Resource [/apis] located + at [/apis] + + + + + + + + + <xml-fragment/>http://${#Project#E3Manager}:8181<xml-fragment/>http://${#Project#E3Manager}:8181 + + + + + + + + + +]]> + + + http://${#Project#E3Manager}:8181 + + + + + + + + + + + + + + + + +]]> + + http://${#Project#E3Manager}:8181 + + auth-key-api3 + test_route_1 + active + PassThrough + auth-key-endpoint3 + false + + + authKey + + + key + + + + false + + + + + + http://${#Project#Target1}:8080/proxySize.php + + NoAuth + + key000Val + + + + + active + 10 + 0.0 + 10 + 0.0 + + + + + + + CompanyQuota + Billing + + + + + + CompanyQuota + Billing + + + +]]> + + 200 + + + + /response/status + SUCCESS + false + false + false + + + + /response/idauth-key-api3falsefalsefalse + + + + + + + <xml-fragment/>http://${#Project#E3Manager}:8181 + auth-key-auth3 + active + authKey + + + + auth-key-key3 + + + + + + CompanyQuota + Billing + + + + + + CompanyQuota + Billing + + + +]]>200/response/idauth-key-auth3falsefalsefalse/response/statusSUCCESSfalsefalsefalse<xml-fragment/>http://${#Project#E3Manager}:8181 + auth-key-p3 + + auth-key-api3 + + + + auth-key-auth3 + + + + + active + + active + reject + 98 + 1000 + + + + active + + +]]>200/response/idauth-key-p3falsefalsefalse/response/statusSUCCESSfalsefalsefalse<xml-fragment/>http://${#Project#E3Manager}:8181 + auth-key-auth3 + active + authKey + + + + auth-key-key3_new + + + + + + CompanyQuota + Billing + + + + + + CompanyQuota + Billing + + + +]]>final String EXPECTED_STATUS = "HTTP/1.1 200 OK" +final String RESPONSE_STATUS = messageExchange.getResponseHeaders().get("#status#")[0] +//Verify response code status. Should be HTTP/1.1 200 OK +assert EXPECTED_STATUS.equals(RESPONSE_STATUS) : "Expected status is \"${EXPECTED_STATUS}\" but was \"${RESPONSE_STATUS}\""//response + auth-key-auth3 + SUCCESS +]]>falsefalsefalse + + + + + <xml-fragment/> + + http://${#Project#E3Gateway}/auth-key-endpoint3 + + + final String EXPECTED_STATUS = "HTTP/1.1 401 Unauthorized" +final String RESPONSE_STATUS = messageExchange.getResponseHeaders().get("#status#")[0] +//Verify response code status. Should be HTTP/1.1 401 Unauthorized +assert EXPECTED_STATUS.equals(RESPONSE_STATUS) : "Expected status is \"${EXPECTED_STATUS}\" but was \"${RESPONSE_STATUS}\""Issue: Not Authorizedfalsefalse + + + + + + + + + + <entry key="SIZE" value="10" xmlns="http://eviware.com/soapui/config"/> + + http://${#Project#E3Gateway}/auth-key-endpoint3 + + + final String EXPECTED_STATUS = "HTTP/1.1 200 OK" +final String RESPONSE_STATUS = messageExchange.getResponseHeaders().get("#status#")[0] +//Verify response code status. Should be HTTP/1.1 200 OK +assert EXPECTED_STATUS.equals(RESPONSE_STATUS) : "Expected status is \"${EXPECTED_STATUS}\" but was \"${RESPONSE_STATUS}\""9876543210falsefalse + + + + + <xml-fragment/>http://${#Project#E3Manager}:8181<xml-fragment/>http://${#Project#E3Manager}:8181 + + + + + + + + + +]]> + + + http://${#Project#E3Manager}:8181 + + + + + + + + + TestCase generated for REST Resource [/apis] located + at [/apis] + + + + + + + + + <xml-fragment/>http://${#Project#E3Manager}:8181<xml-fragment/>http://${#Project#E3Manager}:8181 + + + + + + + + + +]]> + + + http://${#Project#E3Manager}:8181 + + + + + + + + + + + + + + + + +]]> + + http://${#Project#E3Manager}:8181 + + auth-key-api4 + test_route_1 + active + PassThrough + auth-key-endpoint4 + false + + + authKey + + + key + + + + false + + + + + + http://${#Project#Target1}/proxySize.php + + NoAuth + + key000Val + + + + + active + 10 + 0.0 + 10 + 0.0 + + + + + + + CompanyQuota + Billing + + + + + + CompanyQuota + Billing + + + +]]> + + 200 + + + + /response/status + SUCCESS + false + false + false + + + + /response/idauth-key-api4falsefalsefalse + + + + + + + <xml-fragment/>http://${#Project#E3Manager}:8181 + auth-key-auth4 + active + authKey + + + + auth-key-key4 + + + + + + CompanyQuota + Billing + + + + + + CompanyQuota + Billing + + + +]]>200/response/idauth-key-auth4falsefalsefalse/response/statusSUCCESSfalsefalsefalse<xml-fragment/>http://${#Project#E3Manager}:8181 + auth-key-p4 + + auth-key-api4 + + + + auth-key-auth4 + + + + + active + + active + reject + 98 + 1000 + + + + active + + +]]>200/response/idauth-key-p4falsefalsefalse/response/statusSUCCESSfalsefalsefalse<xml-fragment/>http://${#Project#E3Manager}:8181 + auth-key-auth4 + inactive + authKey + + + + auth-key-key4 + + + + + + CompanyQuota + Billing + + + + + + CompanyQuota + Billing + + + +]]>final String EXPECTED_STATUS = "HTTP/1.1 200 OK" +final String RESPONSE_STATUS = messageExchange.getResponseHeaders().get("#status#")[0] +//Verify response code status. Should be HTTP/1.1 200 OK +assert EXPECTED_STATUS.equals(RESPONSE_STATUS) : "Expected status is \"${EXPECTED_STATUS}\" but was \"${RESPONSE_STATUS}\""//response + auth-key-auth4 + SUCCESS +]]>falsefalsefalse + + + + + <xml-fragment/> + + http://${#Project#E3Gateway}/auth-key-endpoint4 + + + final String EXPECTED_STATUS = "HTTP/1.1 401 Unauthorized" +final String RESPONSE_STATUS = messageExchange.getResponseHeaders().get("#status#")[0] +//Verify response code status. Should be HTTP/1.1 401 Unauthorized +assert EXPECTED_STATUS.equals(RESPONSE_STATUS) : "Expected status is \"${EXPECTED_STATUS}\" but was \"${RESPONSE_STATUS}\""Issue: Not Authorizedfalsefalse + + + + + <xml-fragment/>http://${#Project#E3Manager}:8181<xml-fragment/>http://${#Project#E3Manager}:8181 + + + + + + + + + +]]> + + + http://${#Project#E3Manager}:8181 + + + + + + + + + TestCase generated for REST Resource [/apis] located + at [/apis] + + + + + + + + + <xml-fragment/>http://${#Project#E3Manager}:8181<xml-fragment/>http://${#Project#E3Manager}:8181 + + + + + + + + + +]]> + + + http://${#Project#E3Manager}:8181 + + + + + + + + + + + + + + + + +]]> + + http://${#Project#E3Manager}:8181 + + auth-key-api5 + test_route_1 + active + PassThrough + auth-key-endpoint5 + false + + + authKey + + + key + + + + false + + + + + + http://${#Project#Target1}:8080/proxySize.php + + NoAuth + + key000Val + + + + + active + 10 + 0.0 + 10 + 0.0 + + + + + + + CompanyQuota + Billing + + + + + + CompanyQuota + Billing + + + +]]> + + 200 + + + + /response/status + SUCCESS + false + false + false + + + + /response/idauth-key-api5falsefalsefalse + + + + + + + <xml-fragment/>http://${#Project#E3Manager}:8181 + auth-key-auth5 + active + authKey + + + + auth-key-key5 + + + + + + CompanyQuota + Billing + + + + + + CompanyQuota + Billing + + + +]]>200/response/idauth-key-auth5falsefalsefalse/response/statusSUCCESSfalsefalsefalse<xml-fragment/>http://${#Project#E3Manager}:8181 + auth-key-p5 + + auth-key-api5 + + + + auth-key-auth5 + + + + + active + + active + reject + 98 + 1000 + + + + active + + +]]>200/response/idauth-key-p5falsefalsefalse/response/statusSUCCESSfalsefalsefalse<xml-fragment/>http://${#Project#E3Manager}:8181200/response/statusSUCCESSfalsefalsefalse<xml-fragment/>http://${#Project#E3Manager}:8181200/response/statusSUCCESSfalsefalsefalse + + + + + <xml-fragment/> + + http://${#Project#E3Gateway}/auth-key-endpoint5 + + + final String EXPECTED_STATUS = "HTTP/1.1 401 Unauthorized" +final String RESPONSE_STATUS = messageExchange.getResponseHeaders().get("#status#")[0] +//Verify response code status. Should be HTTP/1.1 401 Unauthorized +assert EXPECTED_STATUS.equals(RESPONSE_STATUS) : "Expected status is \"${EXPECTED_STATUS}\" but was \"${RESPONSE_STATUS}\""Issue: Not Authorizedfalsefalse + + + + + + + + + + + + + + +]]> + + http://${#Project#E3Manager}:8181 + + + 200 + + + + + /response/status + SUCCESS + false + false + false + + + + + + + + + + TestCase generated for REST Resource [/apis] located + at [/apis] + + <xml-fragment/>http://${#Project#E3Manager}:8181 + <xml-fragment/>http://${#Project#E3Manager}:8181 + + + + + + + + + + +]]> + + + http://${#Project#E3Manager}:8181 + + + + + + + + + + + + + + + + +]]> + + http://${#Project#E3Manager}:8181 + + auth-key-api6 + test_route_1 + active + PassThrough + auth-key-endpoint6 + false + + + authKey + + + key + + + + false + + + + + + http://${#Project#Target1}:8080/proxySize.php + + NoAuth + + key000Val + + + + + active + 10 + 0.0 + 10 + 0.0 + + + + + + + CompanyQuota + Billing + + + + + + CompanyQuota + Billing + + + +]]> + + 200 + + + + /response/status + SUCCESS + false + false + false + + + + /response/idauth-key-api6falsefalsefalse + + + + + + + + + + <xml-fragment/>http://${#Project#E3Manager}:8181 + auth-key-auth6 + active + authKey + + + + auth-key-key6 + + + + + + CompanyQuota + Billing + + + + + + CompanyQuota + Billing + + + +]]>200/response/idauth-key-auth6falsefalsefalse/response/statusSUCCESSfalsefalsefalse + + <xml-fragment/>http://${#Project#E3Manager}:8181 + auth-key-p6 + + auth-key-api6 + + + + auth-key-auth6 + + + + + active + + active + reject + 98 + 1000 + + + + active + + +]]>200/response/idauth-key-p6falsefalsefalse/response/statusSUCCESSfalsefalsefalse1000 + + + + + <xml-fragment/> + + http://${#Project#E3Gateway}/auth-key-endpoint6 + + + 4xx + + Valid messagefalsefalse + + + + + <xml-fragment/>http://${#Project#E3Manager}:8181<xml-fragment/>http://${#Project#E3Manager}:8181 + + + + + + + + + +]]> + + + http://${#Project#E3Manager}:8181 + + + + + + + + + TestCase generated for REST Resource [/apis] located + at [/apis] + + <xml-fragment/>http://${#Project#E3Manager}:8181 + <xml-fragment/>http://${#Project#E3Manager}:8181 + + + + + + + + + + +]]> + + + http://${#Project#E3Manager}:8181 + + + + + + + + + + + + + + + + +]]> + + http://${#Project#E3Manager}:8181 + + auth-key-api7 + test_route_1 + active + PassThrough + auth-key-endpoint7 + false + + + authKey + + + key + + + + false + + + + + + http://${#Project#Target1}:8080/proxySize.php + + NoAuth + + key000Val + + + + + active + 10 + 0.0 + 10 + 0.0 + + + + + + + CompanyQuota + Billing + + + + + + CompanyQuota + Billing + + + +]]> + + 200 + + + + /response/status + SUCCESS + false + false + false + + + + /response/idauth-key-api7falsefalsefalse + + + + + + + + + + <xml-fragment/>http://${#Project#E3Manager}:8181 + auth-key-auth7 + active + authKey + + + + auth-key-key7 + + + + + + CompanyQuota + Billing + + + + + + CompanyQuota + Billing + + + +]]>200/response/idauth-key-auth7falsefalsefalse/response/statusSUCCESSfalsefalsefalse + + <xml-fragment/>http://${#Project#E3Manager}:8181 + auth-key-p7 + + auth-key-api7 + + + + auth-key-auth7 + + + + + active + + active + reject + 98 + 1000 + + + + active + + +]]>200/response/idauth-key-p7falsefalsefalse/response/statusSUCCESSfalsefalsefalse1000 + + + + + <xml-fragment/> + + http://${#Project#E3Gateway}/auth-key-endpoint7 + + + 4xx + + Valid messagefalsefalse + + + + + <xml-fragment/>http://${#Project#E3Manager}:8181<xml-fragment/>http://${#Project#E3Manager}:8181 + + + + + + + + + +]]> + + + http://${#Project#E3Manager}:8181 + + + + + + + + + + TestSuite generated for REST Service + [functional-test-provision-api] + + SEQUENTIAL + + + + + + + + + + + + TestCase generated for REST Resource [/apis] located + at [/apis] + + + + <xml-fragment/>http://${#Project#E3Manager}:8181 + + + <xml-fragment/>http://${#Project#E3Manager}:8181 + + + + + + + + + +]]> + + + http://${#Project#E3Manager}:8181 + + + + + + + + + + + + + + + + + + +]]> + + http://${#Project#E3Manager}:8181 + + auth-basic-api1 + test_route_1 + PassThrough + active + auth-basic-endpoint1 + false + + + basic + + + + false + + + + + + http://${#Project#Target1}/proxySize + + NoAuth + + key000Val + + + + + active + 100 + 50.0 + 100 + 50.0 + + + + + + + CompanyQuota + Billing + + + + + + CompanyQuota + Billing + + + +]]> + + + 200 + + + + + /response/status + SUCCESS + false + false + false + + + + /response/idauth-basic-api1falsefalsefalse + + + + + + + <xml-fragment/>http://${#Project#E3Manager}:8181 + auth-basic-auth1 + active + basic + + + + + dGVzdGVycGFzc3dvcmQy + + + + + + + CompanyQuota + Billing + + + + + + CompanyQuota + Billing + + + +]]>200/response/idauth0falsefalsefalse/response/statusSUCCESSfalsefalsefalse<xml-fragment/>http://${#Project#E3Manager}:8181 + auth-basic-auth1 + active + basic + + + + + + + + + + + + CompanyQuota + Billing + + + + + + CompanyQuota + Billing + + + +]]>200/response/idauth0falsefalsefalse/response/statusSUCCESSfalsefalsefalse<xml-fragment/>http://${#Project#E3Manager}:8181 + auth-basic-auth1 + active + basic + + + + tester + + + + + + + + CompanyQuota + Billing + + + + + + CompanyQuota + Billing + + + +]]>200/response/idauth0falsefalsefalse/response/statusSUCCESSfalsefalsefalse<xml-fragment/>http://${#Project#E3Manager}:8181<xml-fragment/>http://${#Project#E3Manager}:8181 + + + + + + + + + +]]> + + + http://${#Project#E3Manager}:8181 + + + + + + + + + TestCase generated for REST Resource [/apis] located + at [/apis] + + <xml-fragment/>http://${#Project#E3Manager}:8181 + <xml-fragment/>http://${#Project#E3Manager}:8181 + + + + + + + + + + +]]> + + + http://${#Project#E3Manager}:8181 + + + + + + + + + + + + + + + + +]]> + + http://${#Project#E3Manager}:8181 + + auth-basic-api2 + test_route_1 + PassThrough + active + auth-basic-endpoint2 + false + + + basic + + + + false + + + + + + http://${#Project#Target1}:8080/proxySize + + NoAuth + + key000Val + + + + + active + 100 + 50.0 + 100 + 50.0 + + + + + + + CompanyQuota + Billing + + + + + + CompanyQuota + Billing + + + +]]> + + + 200 + + + + + /response/status + SUCCESS + false + false + false + + + + /response/idauth-basic-api2falsefalsefalse + + + + + + + + + + <xml-fragment/>http://${#Project#E3Manager}:8181 + auth-basic-auth2 + active + basic + + + + auth-basic-username2 + YXV0aC1iYXNpYy1wYXNzd29yZDI= + + + + + + + CompanyQuota + Billing + + + + + + CompanyQuota + Billing + + + +]]>200/response/idauth-basic-auth2falsefalsefalse/response/statusSUCCESSfalsefalsefalse + + + + + + + + + +]]> + + http://${#Project#E3Manager}:8181 + + auth-basic-auth2 + active + basic + + + + auth-basic-username2 + YXV0aC1iYXNpYy1wYXNzd29yZDI= + + + + + + + CompanyQuota + Billing + + + + + + CompanyQuota + Billing + + + +]]> + + + /response/error/errorCode500falsefalsefalse + + + Provisioning Server Error: java.lang.IllegalArgumentException: Auth already exists with that IDfalsefalsefinal String EXPECTED_STATUS = "HTTP/1.1 500 Internal Server Error" +final String RESPONSE_STATUS = messageExchange.getResponseHeaders().get("#status#")[0] +//Verify response code status. Should be HTTP/1.1 500 Internal Server Error +assert EXPECTED_STATUS.equals(RESPONSE_STATUS) : "Expected status is \"${EXPECTED_STATUS}\" but was \"${RESPONSE_STATUS}\""/response/statusFAILUREfalsefalsefalse + + + + + <xml-fragment/>http://${#Project#E3Manager}:8181 + auth-basic-p2 + + auth-basic-api2 + + + + auth-basic-auth2 + + + + + active + + active + reject + 3 + 3 + + + + active + + +]]>200/response/idauth-basic-p2falsefalsefalse/response/statusSUCCESSfalsefalsefalse1000 + + <entry key="Authorization" value="Basic invalidbasic" xmlns="http://eviware.com/soapui/config"/>http://${#Project#E3Gateway}/auth-basic-endpoint2403<entry key="Authorization" value="Basic YXV0aC1iYXNpYy11c2VybmFtZTI6YXV0aC1iYXNpYy1wYXNzd29yZDI=" xmlns="http://eviware.com/soapui/config"/>http://${#Project#E3Gateway}/auth-basic-endpoint2200<entry key="Authorization" value="Basic YXV0aC1iYXNpYy11c2VybmFtZTI6YXV0aC1iYXNpYy1wYXNzd29yZDI=" xmlns="http://eviware.com/soapui/config"/>http://${#Project#E3Gateway}/auth-basic-endpoint2200<entry key="Authorization" value="Basic YXV0aC1iYXNpYy11c2VybmFtZTI6YXV0aC1iYXNpYy1wYXNzd29yZDI=" xmlns="http://eviware.com/soapui/config"/>http://${#Project#E3Gateway}/auth-basic-endpoint2200<entry key="Authorization" value="Basic YXV0aC1iYXNpYy11c2VybmFtZTI6YXV0aC1iYXNpYy1wYXNzd29yZDI=" xmlns="http://eviware.com/soapui/config"/>http://${#Project#E3Gateway}/auth-basic-endpoint2final String EXPECTED_STATUS = "HTTP/1.1 429" +final String RESPONSE_STATUS = messageExchange.getResponseHeaders().get("#status#")[0] +//Verify response code status. Should be HTTP/1.1 429 +assert EXPECTED_STATUS.equals(RESPONSE_STATUS) : "Expected status is \"${EXPECTED_STATUS}\" but was \"${RESPONSE_STATUS}\""<xml-fragment/>http://${#Project#E3Manager}:8181<xml-fragment/>http://${#Project#E3Manager}:8181 + + + + + + + + + +]]> + + + http://${#Project#E3Manager}:8181 + + + + + + + + + TestCase generated for REST Resource [/apis] located + at [/apis] + + <xml-fragment/>http://${#Project#E3Manager}:8181 + <xml-fragment/>http://${#Project#E3Manager}:8181 + + + + + + + + + + +]]> + + + http://${#Project#E3Manager}:8181 + + + + + + + + + + + + + + + + +]]> + + http://${#Project#E3Manager}:8181 + + auth-basic-api3 + test_route_1 + PassThrough + active + auth-basic-endpoint3 + false + + + basic + + + + false + + + + + + http://${#Project#Target1}:8080/proxySize + + NoAuth + + key000Val + + + + + active + 10 + 50.0 + 10 + 50.0 + + + + + + + CompanyQuota + Billing + + + + + + CompanyQuota + Billing + + + +]]> + + 200 + + + /response/statusSUCCESSfalsefalsefalse + + + + + + + + + + + <xml-fragment/>http://${#Project#E3Manager}:8181 + auth-basic-auth3 + active + basic + + + + auth-basic-username3 + YXV0aC1iYXNpYy1wYXNzd29yZDM= + + + + + + + CompanyQuota + Billing + + + + + + CompanyQuota + Billing + + + +]]>200/response/idauth-basic-auth3falsefalsefalse/response/statusSUCCESSfalsefalsefalse<xml-fragment/>http://${#Project#E3Manager}:8181 + auth-basic-p3 + + auth-basic-api3 + + + + auth-basic-auth3 + + + + + active + + active + reject + 98 + 1000 + + + + active + + +]]>200/response/idauth-basic-p3falsefalsefalse/response/statusSUCCESSfalsefalsefalse + + <xml-fragment/>http://${#Project#E3Manager}:8181 + auth-basic-auth3 + active + basic + + + + auth-basic-username3_new + YXV0aC1iYXNpYy1wYXNzd29yZDM= + + + + + + + CompanyQuota + Billing + + + + + + CompanyQuota + Billing + + + +]]>//response/idauth-basic-auth3falsefalsefalse//response/statusSUCCESSfalsefalsefalse200<entry key="Authorization" value="Basic dGVzdGVyOnRlc3RlcnBhc3N3b3JkMg==" xmlns="http://eviware.com/soapui/config"/>http://${#Project#E3Gateway}/auth-basic-endpoint3final String EXPECTED_STATUS = "HTTP/1.1 401 Unauthorized" +final String RESPONSE_STATUS = messageExchange.getResponseHeaders().get("#status#")[0] +//Verify response code status. Should be HTTP/1.1 401 Unauthorized +assert EXPECTED_STATUS.equals(RESPONSE_STATUS) : "Expected status is \"${EXPECTED_STATUS}\" but was \"${RESPONSE_STATUS}\""Issue: Authorization requiredfalsefalse<xml-fragment xmlns:con="http://eviware.com/soapui/config"> + <con:entry key="Authorization" value="basic YXV0aC1iYXNpYy11c2VybmFtZTNfbmV3OmF1dGgtYmFzaWMtcGFzc3dvcmQz"/> + <con:entry key="SIZE" value="10"/> +</xml-fragment>http://${#Project#E3Gateway}/auth-basic-endpoint3final String EXPECTED_STATUS = "HTTP/1.1 200 OK" +final String RESPONSE_STATUS = messageExchange.getResponseHeaders().get("#status#")[0] +//Verify response code status. Should be HTTP/1.1 200 OK +assert EXPECTED_STATUS.equals(RESPONSE_STATUS) : "Expected status is \"${EXPECTED_STATUS}\" but was \"${RESPONSE_STATUS}\""9876543210falsefalse<xml-fragment/>http://${#Project#E3Manager}:8181 + auth-basic-auth3 + active + basic + + + + auth-basic-username3_new + YXV0aC1iYXNpYy1wYXNzd29yZDNfbmV3 + + + + + + + CompanyQuota + Billing + + + + + + CompanyQuota + Billing + + + +]]>//response/idauth-basic-auth3falsefalsefalse//response/statusSUCCESSfalsefalsefalse200<entry key="Authorization" value="Basic bmV3dGVzdGVyOnRlc3RlcnBhc3N3b3JkMg==" xmlns="http://eviware.com/soapui/config"/>http://${#Project#E3Gateway}/auth-basic-endpoint3final String EXPECTED_STATUS = "HTTP/1.1 401 Unauthorized" +final String RESPONSE_STATUS = messageExchange.getResponseHeaders().get("#status#")[0] +//Verify response code status. Should be HTTP/1.1 401 Unauthorized +assert EXPECTED_STATUS.equals(RESPONSE_STATUS) : "Expected status is \"${EXPECTED_STATUS}\" but was \"${RESPONSE_STATUS}\""Issue: Authorization requiredfalsefalse<xml-fragment xmlns:con="http://eviware.com/soapui/config"> + <con:entry key="Authorization" value="Basic YXV0aC1iYXNpYy11c2VybmFtZTNfbmV3OmF1dGgtYmFzaWMtcGFzc3dvcmQzX25ldw=="/> + <con:entry key="SIZE" value="10"/> +</xml-fragment>http://${#Project#E3Gateway}/auth-basic-endpoint3final String EXPECTED_STATUS = "HTTP/1.1 200 OK" +final String RESPONSE_STATUS = messageExchange.getResponseHeaders().get("#status#")[0] +//Verify response code status. Should be HTTP/1.1 200 OK +assert EXPECTED_STATUS.equals(RESPONSE_STATUS) : "Expected status is \"${EXPECTED_STATUS}\" but was \"${RESPONSE_STATUS}\""9876543210falsefalse<xml-fragment/>http://${#Project#E3Manager}:8181<xml-fragment/>http://${#Project#E3Manager}:8181 + + + + + + + + + +]]> + + + http://${#Project#E3Manager}:8181 + + + + + + + + + TestCase generated for REST Resource [/apis] located + at [/apis] + + <xml-fragment/>http://${#Project#E3Manager}:8181 + <xml-fragment/>http://${#Project#E3Manager}:8181 + + + + + + + + + + +]]> + + + http://${#Project#E3Manager}:8181 + + + + + + + + + + + + + + + + +]]> + + http://${#Project#E3Manager}:8181 + + auth-basic-api4 + test_route_1 + PassThrough + active + auth-basic-endpoint4 + false + + + basic + + + + false + + + + + + http://${#Project#Target1}:8080/proxySize + + NoAuth + + key000Val + + + + + active + 100 + 50.0 + 100 + 50.0 + + + + + + + CompanyQuota + Billing + + + + + + CompanyQuota + Billing + + + +]]> + + + 200 + + + + + /response/status + SUCCESS + false + false + false + + + + /response/idauth-basic-api4falsefalsefalse + + + + + + + + + + <xml-fragment/>http://${#Project#E3Manager}:8181 + auth-basic-auth4 + active + basic + + + + auth-basic-username4 + YXV0aC1iYXNpYy1wYXNzd29yZDQ= + + + + + + + CompanyQuota + Billing + + + + + + CompanyQuota + Billing + + + +]]>200/response/idauth-basic-auth4falsefalsefalse/response/statusSUCCESSfalsefalsefalse<xml-fragment/>http://${#Project#E3Manager}:8181 + auth-basic-p4 + + auth-basic-api4 + + + + auth-basic-auth4 + + + + + active + + active + reject + 98 + 1000 + + + + active + + +]]>200/response/idauth-basic-p4falsefalsefalse/response/statusSUCCESSfalsefalsefalse + + <xml-fragment/>http://${#Project#E3Manager}:8181 + auth-basic-auth4 + inactive + basic + + + + auth-basic-username4 + YXV0aC1iYXNpYy1wYXNzd29yZDQ= + + + + + + + CompanyQuota + Billing + + + + + + CompanyQuota + Billing + + + +]]>//response/idauth-basic-auth4falsefalsefalse//response/statusSUCCESSfalsefalsefalsefinal String EXPECTED_STATUS = "HTTP/1.1 200 OK" +final String RESPONSE_STATUS = messageExchange.getResponseHeaders().get("#status#")[0] +//Verify response code status. Should be HTTP/1.1 200 OK +assert EXPECTED_STATUS.equals(RESPONSE_STATUS) : "Expected status is \"${EXPECTED_STATUS}\" but was \"${RESPONSE_STATUS}\""<entry key="Authorization" value="Basic YXV0aC1iYXNpYy11c2VybmFtZTQ6YXV0aC1iYXNpYy1wYXNzd29yZDQ=" xmlns="http://eviware.com/soapui/config"/>http://${#Project#E3Gateway}/auth-basic-endpoint4final String EXPECTED_STATUS = "HTTP/1.1 401 Unauthorized" +final String RESPONSE_STATUS = messageExchange.getResponseHeaders().get("#status#")[0] +//Verify response code status. Should be HTTP/1.1 401 Unauthorized +assert EXPECTED_STATUS.equals(RESPONSE_STATUS) : "Expected status is \"${EXPECTED_STATUS}\" but was \"${RESPONSE_STATUS}\""Issue: Authorization requiredfalsefalse<entry key="Authorization" value="Basic invalidbasic" xmlns="http://eviware.com/soapui/config"/>http://${#Project#E3Gateway}/auth-basic-endpoint4final String EXPECTED_STATUS = "HTTP/1.1 401 Unauthorized" +final String RESPONSE_STATUS = messageExchange.getResponseHeaders().get("#status#")[0] +//Verify response code status. Should be HTTP/1.1 401 Unauthorized +assert EXPECTED_STATUS.equals(RESPONSE_STATUS) : "Expected status is \"${EXPECTED_STATUS}\" but was \"${RESPONSE_STATUS}\""Issue: Not Authorizedfalsefalse<xml-fragment/>http://${#Project#E3Manager}:8181 + auth-basic-auth4 + active + basic + + + + auth-basic-username4 + YXV0aC1iYXNpYy1wYXNzd29yZDQ= + + + + + + + CompanyQuota + Billing + + + + + + CompanyQuota + Billing + + + +]]>//response/idauth-basic-auth4falsefalsefalse//response/statusSUCCESSfalsefalsefalsefinal String EXPECTED_STATUS = "HTTP/1.1 200 OK" +final String RESPONSE_STATUS = messageExchange.getResponseHeaders().get("#status#")[0] +//Verify response code status. Should be HTTP/1.1 200 OK +assert EXPECTED_STATUS.equals(RESPONSE_STATUS) : "Expected status is \"${EXPECTED_STATUS}\" but was \"${RESPONSE_STATUS}\""<entry key="Authorization" value="Basic YXV0aC1iYXNpYy11c2VybmFtZTQ6YXV0aC1iYXNpYy1wYXNzd29yZDQ=" xmlns="http://eviware.com/soapui/config"/>http://${#Project#E3Gateway}/auth-basic-endpoint4final String EXPECTED_STATUS = "HTTP/1.1 200 OK" +final String RESPONSE_STATUS = messageExchange.getResponseHeaders().get("#status#")[0] +//Verify response code status. Should be HTTP/1.1 200 OK +assert EXPECTED_STATUS.equals(RESPONSE_STATUS) : "Expected status is \"${EXPECTED_STATUS}\" but was \"${RESPONSE_STATUS}\""<entry key="Authorization" value="Basic invalidbasic" xmlns="http://eviware.com/soapui/config"/>http://${#Project#E3Gateway}/auth-basic-endpoint4final String EXPECTED_STATUS = "HTTP/1.1 401 Unauthorized" +final String RESPONSE_STATUS = messageExchange.getResponseHeaders().get("#status#")[0] +//Verify response code status. Should be HTTP/1.1 401 Unauthorized +assert EXPECTED_STATUS.equals(RESPONSE_STATUS) : "Expected status is \"${EXPECTED_STATUS}\" but was \"${RESPONSE_STATUS}\""Issue: Not Authorizedfalsefalse<xml-fragment/>http://${#Project#E3Manager}:8181<xml-fragment/>http://${#Project#E3Manager}:8181 + + + + + + + + + +]]> + + + http://${#Project#E3Manager}:8181 + + + + + + + + + TestCase generated for REST Resource [/apis] located + at [/apis] + + + + + + + + + <xml-fragment/>http://${#Project#E3Manager}:8181<xml-fragment/>http://${#Project#E3Manager}:8181 + + + + + + + + + +]]> + + + http://${#Project#E3Manager}:8181 + + + + + + + + + + + + + + + + +]]> + + http://${#Project#E3Manager}:8181 + + auth-basic-api5 + test_route_1 + PassThrough + active + auth-basic-endpoint5 + false + + + basic + + + + false + + + + + + http://${#Project#Target1}:8080/proxySize + + NoAuth + + key000Val + + + + + active + 100 + 50.0 + 100 + 50.0 + + + + + + + CompanyQuota + Billing + + + + + + CompanyQuota + Billing + + + +]]> + + + 200 + + + + + /response/status + SUCCESS + false + false + false + + + + /response/idauth-basic-api5falsefalsefalse + + + + + + + <xml-fragment/>http://${#Project#E3Manager}:8181 + auth-basic-auth5 + active + basic + + + + auth-basic-username5 + YXV0aC1iYXNpYy1wYXNzd29yZDU= + + + + + + + CompanyQuota + Billing + + + + + + CompanyQuota + Billing + + + +]]>200/response/idauth-basic-auth5falsefalsefalse/response/statusSUCCESSfalsefalsefalse<xml-fragment/>http://${#Project#E3Manager}:8181 + auth-basic-p5 + + auth-basic-api5 + + + + auth-basic-auth5 + + + + + active + + active + reject + 98 + 1000 + + + + active + + +]]>200/response/idauth-basic-p5falsefalsefalse/response/statusSUCCESSfalsefalsefalse<xml-fragment/>http://${#Project#E3Manager}:8181200/response/statusSUCCESSfalsefalsefalse<xml-fragment/>http://${#Project#E3Manager}:8181200/response/statusSUCCESSfalsefalsefalse<entry key="Authorization" value="Basic YXV0aC1iYXNpYy11c2VybmFtZTU6YXV0aC1iYXNpYy1wYXNzd29yZDU=" xmlns="http://eviware.com/soapui/config"/>http://${#Project#E3Gateway}/auth-basic-endpoint5final String EXPECTED_STATUS = "HTTP/1.1 401 Unauthorized" +final String RESPONSE_STATUS = messageExchange.getResponseHeaders().get("#status#")[0] +//Verify response code status. Should be HTTP/1.1 401 Unauthorized +assert EXPECTED_STATUS.equals(RESPONSE_STATUS) : "Expected status is \"${EXPECTED_STATUS}\" but was \"${RESPONSE_STATUS}\""Issue: Authorization requiredfalsefalse + + + + + + + + + +]]> + + http://${#Project#E3Manager}:8181 + + + 200 + + + + + /response/status + SUCCESS + false + false + false + + + + + + + + + + TestCase generated for REST Resource [/apis] located + at [/apis] + + + + + + + + + <xml-fragment/>http://${#Project#E3Manager}:8181 + auth-basic-auth6 + active + authKey + + + + keyValue1 + +]]>200/response/statusSUCCESSfalsefalsefalse<xml-fragment/>http://${#Project#E3Manager}:8181//response/statusSUCCESSfalsefalsefalse200 + + + TestSuite generated for REST Service + [functional-test-provision-auth] + + SEQUENTIAL + + + + + + + + <xml-fragment/> + + http://${#Project#E3Manager}:8181 + + auth0 + active + basic + + + + + keyvaluesgfhjzghjzeg + + + + username0 + cGFzc3dvcmQw + + + + + + + CompanyQuota + Billing + + + + + + CompanyQuota + Billing + + + +]]> + final String EXPECTED_STATUS = "HTTP/1.1 500 Internal Server Error" +final String RESPONSE_STATUS = messageExchange.getResponseHeaders().get("#status#")[0] +//Verify response code status. Should be HTTP/1.1 500 Internal Server Error +assert EXPECTED_STATUS.equals(RESPONSE_STATUS) : "Expected status is \"${EXPECTED_STATUS}\" but was \"${RESPONSE_STATUS}\""//response/statusFAILUREfalsefalsefalse//response/error/errorTextXML Validation Error: cvc-complex-type.2.4.a: Invalid content was found starting with element 'basicAuth'. One of '{tdr, properties, headerTransformations}' is expected.falsefalsefalse//response/error/errorCode102falsefalsefalse + + + + + + + + + + + + + + + <xml-fragment/> + + http://${#Project#E3Manager}:8181 + + auth0 + active + authKey + + + + + keyvaluesgfhjzghjzeg + + + + username0 + cGFzc3dvcmQw + + + + + + + CompanyQuota + Billing + + + + + + CompanyQuota + Billing + + + +]]> + final String EXPECTED_STATUS = "HTTP/1.1 500 Internal Server Error" +final String RESPONSE_STATUS = messageExchange.getResponseHeaders().get("#status#")[0] +//Verify response code status. Should be HTTP/1.1 500 Internal Server Error +assert EXPECTED_STATUS.equals(RESPONSE_STATUS) : "Expected status is \"${EXPECTED_STATUS}\" but was \"${RESPONSE_STATUS}\""//response/statusFAILUREfalsefalsefalse//response/error/errorTextXML Validation Error: cvc-complex-type.2.4.a: Invalid content was found starting with element 'basicAuth'. One of '{tdr, properties, headerTransformations}' is expected.falsefalsefalse//response/error/errorCode102falsefalsefalse + + + + + + + + + + <xml-fragment/> + + http://${#Project#E3Manager}:8181 + + auth0 + active + ipWhiteList + + + + + keyvaluesgfhjzghjzeg + + + + username0 + cGFzc3dvcmQw + + + + + + + CompanyQuota + Billing + + + + + + CompanyQuota + Billing + + + +]]> + final String EXPECTED_STATUS = "HTTP/1.1 500 Internal Server Error" +final String RESPONSE_STATUS = messageExchange.getResponseHeaders().get("#status#")[0] +//Verify response code status. Should be HTTP/1.1 500 Internal Server Error +assert EXPECTED_STATUS.equals(RESPONSE_STATUS) : "Expected status is \"${EXPECTED_STATUS}\" but was \"${RESPONSE_STATUS}\""//response/statusFAILUREfalsefalsefalse//response/error/errorTextXML Validation Error: cvc-complex-type.2.4.a: Invalid content was found starting with element 'basicAuth'. One of '{tdr, properties, headerTransformations}' is expected.falsefalsefalse//response/error/errorCode102falsefalsefalse + + + + + + + + + + <xml-fragment/> + + http://${#Project#E3Manager}:8181 + + auth0 + active + basic + + + + + keyvaluesgfhjzghjzeg + + + username0 + cGFzc3dvcmQw + + + + + + + CompanyQuota + Billing + + + + + + CompanyQuota + Billing + + + +]]> + final String EXPECTED_STATUS = "HTTP/1.1 500 Internal Server Error" +final String RESPONSE_STATUS = messageExchange.getResponseHeaders().get("#status#")[0] +//Verify response code status. Should be HTTP/1.1 500 Internal Server Error +assert EXPECTED_STATUS.equals(RESPONSE_STATUS) : "Expected status is \"${EXPECTED_STATUS}\" but was \"${RESPONSE_STATUS}\""//response/statusFAILUREfalsefalsefalse//response/error/errorTextXML Validation Error: cvc-complex-type.2.4.a: Invalid content was found starting with element 'basicAuth'. One of '{tdr, properties, headerTransformations}' is expected.falsefalsefalse//response/error/errorCode102falsefalsefalse + + + + + + + + + + <xml-fragment/> + + http://${#Project#E3Manager}:8181 + + auth0 + active + basic + + + + + username0 + cGFzc3dvcmQw + + + 192.168.84.67 + 192.168.84.68 + + + + + + CompanyQuota + Billing + + + + + + CompanyQuota + Billing + + + +]]> + final String EXPECTED_STATUS = "HTTP/1.1 500 Internal Server Error" +final String RESPONSE_STATUS = messageExchange.getResponseHeaders().get("#status#")[0] +//Verify response code status. Should be HTTP/1.1 500 Internal Server Error +assert EXPECTED_STATUS.equals(RESPONSE_STATUS) : "Expected status is \"${EXPECTED_STATUS}\" but was \"${RESPONSE_STATUS}\""//response/statusFAILUREfalsefalsefalse//response/error/errorTextXML Validation Error: cvc-complex-type.2.4.a: Invalid content was found starting with element 'ipWhiteListAuth'. One of '{tdr, properties, headerTransformations}' is expected.falsefalsefalse//response/error/errorCode102falsefalsefalse + + + + + + + + + + <xml-fragment/> + + http://${#Project#E3Manager}:8181 + + auth0 + active + basic + + + + + keyvaluesgfhjzghjzeg + + + + 192.168.84.67 + 192.168.84.68 + + + + + + CompanyQuota + Billing + + + + + + CompanyQuota + Billing + + + +]]> + final String EXPECTED_STATUS = "HTTP/1.1 500 Internal Server Error" +final String RESPONSE_STATUS = messageExchange.getResponseHeaders().get("#status#")[0] +//Verify response code status. Should be HTTP/1.1 500 Internal Server Error +assert EXPECTED_STATUS.equals(RESPONSE_STATUS) : "Expected status is \"${EXPECTED_STATUS}\" but was \"${RESPONSE_STATUS}\""//response/statusFAILUREfalsefalsefalse//response/error/errorTextXML Validation Error: cvc-complex-type.2.4.a: Invalid content was found starting with element 'ipWhiteListAuth'. One of '{tdr, properties, headerTransformations}' is expected.falsefalsefalse//response/error/errorCode102falsefalsefalse + + + + + + + + + + <xml-fragment/> + + http://${#Project#E3Manager}:8181 + + auth0 + active + basic + + + + + username0 + cGFzc3dvcmQw + + + + username1 + cGFzc3dvcmQw + + + + + + + CompanyQuota + Billing + + + + + + CompanyQuota + Billing + + + +]]> + final String EXPECTED_STATUS = "HTTP/1.1 500 Internal Server Error" +final String RESPONSE_STATUS = messageExchange.getResponseHeaders().get("#status#")[0] +//Verify response code status. Should be HTTP/1.1 500 Internal Server Error +assert EXPECTED_STATUS.equals(RESPONSE_STATUS) : "Expected status is \"${EXPECTED_STATUS}\" but was \"${RESPONSE_STATUS}\""//response/statusFAILUREfalsefalsefalse//response/error/errorTextXML Validation Error: cvc-complex-type.2.4.a: Invalid content was found starting with element 'basicAuth'. One of '{tdr, properties, headerTransformations}' is expected.falsefalsefalse//response/error/errorCode102falsefalsefalse + + + + + + + + + + <xml-fragment/> + + http://${#Project#E3Manager}:8181 + + auth0 + active + authKey + + + + + keyvaluesgfhjzghjzeg + + + username0 + cGFzc3dvcmQw + + + + + + + CompanyQuota + Billing + + + + + + CompanyQuota + Billing + + + +]]> + final String EXPECTED_STATUS = "HTTP/1.1 500 Internal Server Error" +final String RESPONSE_STATUS = messageExchange.getResponseHeaders().get("#status#")[0] +//Verify response code status. Should be HTTP/1.1 500 Internal Server Error +assert EXPECTED_STATUS.equals(RESPONSE_STATUS) : "Expected status is \"${EXPECTED_STATUS}\" but was \"${RESPONSE_STATUS}\""//response/statusFAILUREfalsefalsefalse//response/error/errorTextXML Validation Error: cvc-complex-type.2.4.a: Invalid content was found starting with element 'basicAuth'. One of '{tdr, properties, headerTransformations}' is expected.falsefalsefalse//response/error/errorCode102falsefalsefalse + + + + + + + + + + <xml-fragment/> + + http://${#Project#E3Manager}:8181 + + auth0 + active + authKey + + + + + username0 + cGFzc3dvcmQw + + + 192.168.84.67 + 192.168.84.68 + + + + + + CompanyQuota + Billing + + + + + + CompanyQuota + Billing + + + +]]> + final String EXPECTED_STATUS = "HTTP/1.1 500 Internal Server Error" +final String RESPONSE_STATUS = messageExchange.getResponseHeaders().get("#status#")[0] +//Verify response code status. Should be HTTP/1.1 500 Internal Server Error +assert EXPECTED_STATUS.equals(RESPONSE_STATUS) : "Expected status is \"${EXPECTED_STATUS}\" but was \"${RESPONSE_STATUS}\""//response/statusFAILUREfalsefalsefalse//response/error/errorTextXML Validation Error: cvc-complex-type.2.4.a: Invalid content was found starting with element 'ipWhiteListAuth'. One of '{tdr, properties, headerTransformations}' is expected.falsefalsefalse//response/error/errorCode102falsefalsefalse + + + + + + + + + + <xml-fragment/> + + http://${#Project#E3Manager}:8181 + + auth0 + active + authKey + + + + + keyvaluesgfhjzghjzeg + + + + 192.168.84.67 + 192.168.84.68 + + + + + + CompanyQuota + Billing + + + + + + CompanyQuota + Billing + + + +]]> + final String EXPECTED_STATUS = "HTTP/1.1 500 Internal Server Error" +final String RESPONSE_STATUS = messageExchange.getResponseHeaders().get("#status#")[0] +//Verify response code status. Should be HTTP/1.1 500 Internal Server Error +assert EXPECTED_STATUS.equals(RESPONSE_STATUS) : "Expected status is \"${EXPECTED_STATUS}\" but was \"${RESPONSE_STATUS}\""//response/statusFAILUREfalsefalsefalse//response/error/errorTextXML Validation Error: cvc-complex-type.2.4.a: Invalid content was found starting with element 'ipWhiteListAuth'. One of '{tdr, properties, headerTransformations}' is expected.falsefalsefalse//response/error/errorCode102falsefalsefalse + + + + + + + + + + <xml-fragment/> + + http://${#Project#E3Manager}:8181 + + auth0 + active + authKey + + + + + keyvaluesgfhjzghjzeg + + + + keyvaluesgfhjzghjzeg + + + + + + CompanyQuota + Billing + + + + + + CompanyQuota + Billing + + + +]]> + final String EXPECTED_STATUS = "HTTP/1.1 500 Internal Server Error" +final String RESPONSE_STATUS = messageExchange.getResponseHeaders().get("#status#")[0] +//Verify response code status. Should be HTTP/1.1 500 Internal Server Error +assert EXPECTED_STATUS.equals(RESPONSE_STATUS) : "Expected status is \"${EXPECTED_STATUS}\" but was \"${RESPONSE_STATUS}\""//response/statusFAILUREfalsefalsefalse//response/error/errorTextXML Validation Error: cvc-complex-type.2.4.a: Invalid content was found starting with element 'authKeyAuth'. One of '{tdr, properties, headerTransformations}' is expected.falsefalsefalse//response/error/errorCode102falsefalsefalse + + + + + + + + + + <xml-fragment/> + + http://${#Project#E3Manager}:8181 + + auth0 + active + ipWhiteList + + + + + keyvaluesgfhjzghjzeg + + + username0 + cGFzc3dvcmQw + + + + + + + CompanyQuota + Billing + + + + + + CompanyQuota + Billing + + + +]]> + final String EXPECTED_STATUS = "HTTP/1.1 500 Internal Server Error" +final String RESPONSE_STATUS = messageExchange.getResponseHeaders().get("#status#")[0] +//Verify response code status. Should be HTTP/1.1 500 Internal Server Error +assert EXPECTED_STATUS.equals(RESPONSE_STATUS) : "Expected status is \"${EXPECTED_STATUS}\" but was \"${RESPONSE_STATUS}\""//response/statusFAILUREfalsefalsefalse//response/error/errorTextXML Validation Error: cvc-complex-type.2.4.a: Invalid content was found starting with element 'basicAuth'. One of '{tdr, properties, headerTransformations}' is expected.falsefalsefalse//response/error/errorCode102falsefalsefalse + + + + + + + + + + <xml-fragment/> + + http://${#Project#E3Manager}:8181 + + auth0 + active + ipWhiteList + + + + + username0 + cGFzc3dvcmQw + + + 192.168.84.67 + 192.168.84.68 + + + + + + CompanyQuota + Billing + + + + + + CompanyQuota + Billing + + + +]]> + final String EXPECTED_STATUS = "HTTP/1.1 500 Internal Server Error" +final String RESPONSE_STATUS = messageExchange.getResponseHeaders().get("#status#")[0] +//Verify response code status. Should be HTTP/1.1 500 Internal Server Error +assert EXPECTED_STATUS.equals(RESPONSE_STATUS) : "Expected status is \"${EXPECTED_STATUS}\" but was \"${RESPONSE_STATUS}\""//response/statusFAILUREfalsefalsefalse//response/error/errorTextXML Validation Error: cvc-complex-type.2.4.a: Invalid content was found starting with element 'ipWhiteListAuth'. One of '{tdr, properties, headerTransformations}' is expected.falsefalsefalse//response/error/errorCode102falsefalsefalse + + + + + + + + + + <xml-fragment/> + + http://${#Project#E3Manager}:8181 + + auth0 + active + ipWhiteList + + + + + keyvaluesgfhjzghjzeg + + + + 192.168.84.67 + 192.168.84.68 + + + + + + CompanyQuota + Billing + + + + + + CompanyQuota + Billing + + + +]]> + final String EXPECTED_STATUS = "HTTP/1.1 500 Internal Server Error" +final String RESPONSE_STATUS = messageExchange.getResponseHeaders().get("#status#")[0] +//Verify response code status. Should be HTTP/1.1 500 Internal Server Error +assert EXPECTED_STATUS.equals(RESPONSE_STATUS) : "Expected status is \"${EXPECTED_STATUS}\" but was \"${RESPONSE_STATUS}\""//response/statusFAILUREfalsefalsefalse//response/error/errorTextXML Validation Error: cvc-complex-type.2.4.a: Invalid content was found starting with element 'ipWhiteListAuth'. One of '{tdr, properties, headerTransformations}' is expected.falsefalsefalse//response/error/errorCode102falsefalsefalse + + + + + + + + + + <xml-fragment/> + + http://${#Project#E3Manager}:8181 + + auth0 + active + ipWhiteList + + + + + 192.168.84.65 + 192.168.84.66 + + + + 192.168.84.67 + 192.168.84.68 + + + + + + CompanyQuota + Billing + + + + + + CompanyQuota + Billing + + + +]]> + final String EXPECTED_STATUS = "HTTP/1.1 500 Internal Server Error" +final String RESPONSE_STATUS = messageExchange.getResponseHeaders().get("#status#")[0] +//Verify response code status. Should be HTTP/1.1 500 Internal Server Error +assert EXPECTED_STATUS.equals(RESPONSE_STATUS) : "Expected status is \"${EXPECTED_STATUS}\" but was \"${RESPONSE_STATUS}\""//response/statusFAILUREfalsefalsefalse//response/error/errorTextXML Validation Error: cvc-complex-type.2.4.a: Invalid content was found starting with element 'ipWhiteListAuth'. One of '{tdr, properties, headerTransformations}' is expected.falsefalsefalse//response/error/errorCode102falsefalsefalse + + + + + + + + + + + + + + <xml-fragment/> + + http://${#Project#E3Manager}:8181 + + + + + + + + + + + + + <xml-fragment/> + + http://${#Project#E3Manager}:8181 + + auth-all-types-auth2 + active + basic + + + + + keyvaluesgfhjzghjzeg + + + + + + + CompanyQuota + Billing + + + + + + CompanyQuota + Billing + + + +]]> + 400/response + + Request did not contain BasicAuth info. + 400 + + FAILURE +]]>falsefalsefalse + + + + + + + + + + + <xml-fragment/> + + http://${#Project#E3Manager}:8181 + + auth-all-types-auth2 + active + basic + + + + + 192.168.84.67 + 192.168.84.68 + + + + + + CompanyQuota + Billing + + + + + + CompanyQuota + Billing + + + + +]]> + 400/response + + Request did not contain BasicAuth info. + 400 + + FAILURE +]]>falsefalsefalse + + + + + + + + + + + <xml-fragment/> + + http://${#Project#E3Manager}:8181 + + auth-all-types-auth2 + active + authKey + + + + + username0 + cGFzc3dvcmQw + + + + + + + CompanyQuota + Billing + + + + + + CompanyQuota + Billing + + + + +]]> + 400/response + + Request did not contain AuthKeyAuth info. + 400 + + FAILURE +]]>falsefalsefalse + + + + + + + + + + + <xml-fragment/> + + http://${#Project#E3Manager}:8181 + + auth-all-types-auth2 + active + authKey + + + + + 192.168.84.67 + 192.168.84.68 + + + + + + CompanyQuota + Billing + + + + + + CompanyQuota + Billing + + + + +]]> + 400/response + + Request did not contain AuthKeyAuth info. + 400 + + FAILURE +]]>falsefalsefalse + + + + + + + + + + + <xml-fragment/> + + http://${#Project#E3Manager}:8181 + + auth-all-types-auth2 + active + ipWhiteList + + + + + keyvaluesgfhjzghjzeg + + + + + + + CompanyQuota + Billing + + + + + + CompanyQuota + Billing + + + + +]]> + + + + + + + + + + + <xml-fragment/> + + http://${#Project#E3Manager}:8181 + + auth-all-types-auth2 + active + ipWhiteList + + + + + username0 + cGFzc3dvcmQw + + + + + + + CompanyQuota + Billing + + + + + + CompanyQuota + Billing + + + + +]]> + + + + + + + + + + + <xml-fragment/> + + http://${#Project#E3Manager}:8181 + + + + + + + + + + + + + + + <xml-fragment/>http://${#Project#E3Manager}:8181<xml-fragment/>http://${#Project#E3Manager}:8181 + change-types-auth3 + active + authKey + + + + change-types-key3 + + + + + + CompanyQuota + Billing + + + + + + CompanyQuota + Billing + + + +]]>200/response/idchange-types-auth3falsefalsefalse/response/statusSUCCESSfalsefalsefalse<xml-fragment/>http://${#Project#E3Manager}:8181 + change-types-auth3 + active + basic + + + + newtester + dGVzdGVycGFzc3dvcmQy + + + + + + + CompanyQuota + Billing + + + + + + CompanyQuota + Billing + + + +]]>//response/idchange-types-auth3falsefalsefalse//response/statusSUCCESSfalsefalsefalse200<xml-fragment/>http://${#Project#E3Manager}:8181 + change-types-auth3 + active + ipWhiteList + + + + ${= InetAddress.getLocalHost().getHostAddress()} + + + + + + CompanyQuota + Billing + + + + + + CompanyQuota + Billing + + + +]]>//response/idchange-types-auth3falsefalsefalse//response/statusSUCCESSfalsefalsefalse200<xml-fragment/>http://${#Project#E3Manager}:8181 + + + + + + + + <xml-fragment/>http://${#Project#E3Manager}:8181<xml-fragment/>http://${#Project#E3Manager}:8181 + + + + + + + + + +]]> + + + http://${#Project#E3Manager}:8181 + + + + + + + + + + + + + + + + +]]> + + http://${#Project#E3Manager}:8181 + + change-types-api4 + test_route_1 + PassThrough + active + change-types-endpoint4 + false + + + authKey + + + key + + + + false + + + + + + http://${#Project#Target1}:8080/proxySize.php + + NoAuth + + key000Val + + + + + active + 10 + 50.0 + 10 + 50.0 + + + + + + + CompanyQuota + Billing + + + + + + CompanyQuota + Billing + + + +]]> + + + 200 + + + + + /response/status + SUCCESS + false + false + false + + + + /response/idchange-types-api4falsefalsefalse + + + + + + + <xml-fragment/>http://${#Project#E3Manager}:8181 + change-types-auth4 + active + authKey + + + + change-types-key4 + + + + + + CompanyQuota + Billing + + + + + + CompanyQuota + Billing + + + +]]>200/response/idchange-types-auth4falsefalsefalse/response/statusSUCCESSfalsefalsefalse<xml-fragment/>http://${#Project#E3Manager}:8181 + change-types-p4 + + change-types-api4 + + + + change-types-auth4 + + + + + active + + active + reject + 98 + 1000 + + + + active + + +]]>200/response/idchange-types-p4falsefalsefalse/response/statusSUCCESSfalsefalsefalse + + + + + <entry key="SIZE" value="10" xmlns="http://eviware.com/soapui/config"/> + + http://${#Project#E3Gateway}/change-types-endpoint4 + + + final String EXPECTED_STATUS = "HTTP/1.1 200 OK" +final String RESPONSE_STATUS = messageExchange.getResponseHeaders().get("#status#")[0] +//Verify response code status. Should be HTTP/1.1 200 OK +assert EXPECTED_STATUS.equals(RESPONSE_STATUS) : "Expected status is \"${EXPECTED_STATUS}\" but was \"${RESPONSE_STATUS}\"" + + + + + <xml-fragment/>http://${#Project#E3Manager}:8181 + change-types-auth4 + active + basic + + + + types1 + dGVzdGVycGFzc3dvcmQy + + + + + + + CompanyQuota + Billing + + + + + + CompanyQuota + Billing + + + +]]>//response/idchange-types-auth4falsefalsefalse//response/statusSUCCESSfalsefalsefalse200<entry key="Authorization" value="Basic dHlwZXMxOnRlc3RlcnBhc3N3b3JkMg==" xmlns="http://eviware.com/soapui/config"/>http://${#Project#E3Gateway}/change-types-endpoint4final String EXPECTED_STATUS = "HTTP/1.1 401 Unauthorized" +final String RESPONSE_STATUS = messageExchange.getResponseHeaders().get("#status#")[0] +//Verify response code status. Should be HTTP/1.1 401 Unauthorized +assert EXPECTED_STATUS.equals(RESPONSE_STATUS) : "Expected status is \"${EXPECTED_STATUS}\" but was \"${RESPONSE_STATUS}\""Issue: Not Authorizedfalsefalse<xml-fragment/>http://${#Project#E3Manager}:8181 + change-types-auth4 + active + ipWhiteList + + + + ${= InetAddress.getLocalHost().getHostAddress()} + 1.1.3.4 + + + + + + CompanyQuota + Billing + + + + + + CompanyQuota + Billing + + + +]]>//response/idchange-types-auth4falsefalsefalse//response/statusSUCCESSfalsefalsefalse200<xml-fragment/>http://${#Project#E3Gateway}/change-types-endpoint4401Issue: Not Authorizedfalsefalse<xml-fragment/>http://${#Project#E3Manager}:8181 + change-types-auth4 + active + authKey + + + + change-types-key4 + + + + + + CompanyQuota + Billing + + + + + + CompanyQuota + Billing + + + +]]>//response/idchange-types-auth4falsefalsefalse//response/statusSUCCESSfalsefalsefalse200 + + + + + <xml-fragment/> + + http://${#Project#E3Gateway}/change-types-endpoint4 + + + final String EXPECTED_STATUS = "HTTP/1.1 200 OK" +final String RESPONSE_STATUS = messageExchange.getResponseHeaders().get("#status#")[0] +//Verify response code status. Should be HTTP/1.1 200 OK +assert EXPECTED_STATUS.equals(RESPONSE_STATUS) : "Expected status is \"${EXPECTED_STATUS}\" but was \"${RESPONSE_STATUS}\"" + + + + + <xml-fragment/>http://${#Project#E3Manager}:8181<xml-fragment/>http://${#Project#E3Manager}:8181 + + + + + + + + + +]]> + + + http://${#Project#E3Manager}:8181 + + + + + + + + + + + + + + + <xml-fragment/> + + http://${#Project#E3Manager}:8181 + + + + + + + + + + + + + + + <xml-fragment/> + + http://${#Project#E3Manager}:8181 + + + + + + + + + + + + + <xml-fragment/> + + http://${#Project#E3Manager}:8181 + + + + + + + + <xml-fragment/>http://${#Project#E3Manager}:8181 + change-types-auth5-k + active + authKey + + + + change-types-key5 + + + + + + CompanyQuota + Billing + + + + + + CompanyQuota + Billing + + + +]]>200/response/idchange-types-auth5-kfalsefalsefalse/response/statusSUCCESSfalsefalsefalse<xml-fragment/>http://${#Project#E3Manager}:8181//response/statusSUCCESSfalsefalsefalsechange-types-auth5-kfalsefalse<xml-fragment/>http://${#Project#E3Manager}:8181 + change-types-auth5-b + active + basic + + + + change-types-auth5-b + dGVzdGVycGFzc3dvcmQy + + + + + + + CompanyQuota + Billing + + + + + + CompanyQuota + Billing + + + +]]>200/response/idchange-types-auth5-bfalsefalsefalse/response/statusSUCCESSfalsefalsefalse<xml-fragment/>http://${#Project#E3Manager}:8181//response/statusSUCCESSfalsefalsefalsechange-types-auth5-kfalsefalsechange-types-auth5-bfalsefalse<xml-fragment/>http://${#Project#E3Manager}:8181 + change-types-auth5-w + active + ipWhiteList + + + + 255.2.2.1 + + + + + + CompanyQuota + Billing + + + + + + CompanyQuota + Billing + + + +]]>200/response/idchange-types-auth5-wfalsefalsefalse/response/statusSUCCESSfalsefalsefalse<xml-fragment/>http://${#Project#E3Manager}:8181//response/statusSUCCESSfalsefalsefalsechange-types-auth5-kfalsefalsechange-types-auth5-bfalsefalsechange-types-auth5-wfalsefalse + + + + + <xml-fragment/> + + http://${#Project#E3Manager}:8181 + + + + + + + <xml-fragment/>http://${#Project#E3Manager}:8181//response/statusSUCCESSfalsefalsefalsechange-types-auth5-kfalsefalse + + + + + <xml-fragment/> + + http://${#Project#E3Manager}:8181 + + + + + + + <xml-fragment/>http://${#Project#E3Manager}:8181//response/statusSUCCESSfalsefalsefalsechange-types-auth5-wfalsefalse + + + + + <xml-fragment/> + + http://${#Project#E3Manager}:8181 + + + + + + + <xml-fragment/>http://${#Project#E3Manager}:8181//response/statusSUCCESSfalsefalsefalsechange-types-auth5-bfalsefalse + + TestCase generated for REST Resource [/apis] located + at [/apis] + + <xml-fragment/>http://${#Project#E3Manager}:8181 + + + + + + + + + + +]]> + + http://${#Project#E3Manager}:8181 + + + + + + + + + + + + + + + + + + + +]]> + + + http://${#Project#E3Manager}:8181 + + + + + + + + + + + + + + + + + + + + + +]]> + + http://${#Project#E3Manager}:8181 + + change-types-api6 + test_route_1 + PassThrough + active + change-types-endpoint6 + false + + + noAuth + + + + false + + + + + + http://${#Project#Target1}:8080/proxySize + + NoAuth + + key000Val + + + + + active + 10 + 0.0 + 10 + 0.0 + + + + + + + CompanyQuota + Billing + + + + + + CompanyQuota + Billing + + + +]]> + + + 200 + + + + + /response/status + SUCCESS + false + false + false + + + + /response/idchange-types-api6falsefalsefalse + + + + + + + <entry key="SIZE" value="10" xmlns="http://eviware.com/soapui/config"/>http://${#Project#E3Gateway}/change-types-endpoint62009876543210falsefalse + + + + + + + + + +]]> + + http://${#Project#E3Manager}:8181 + + + 200 + + + + + /response/status + SUCCESS + false + false + false + + + + + + + + + <xml-fragment/>http://${#Project#E3Manager}:8181<xml-fragment/>http://${#Project#E3Manager}:8181 + change-types-auth7 + active + authKey + + + + + + + + + + CompanyQuota + Billing + + + + + + CompanyQuota + Billing + + + +]]>400/response/statusFAILUREfalsefalsefalse<xml-fragment/>http://${#Project#E3Manager}:8181 + change-types-auth7 + active + basic + + + + + dGVzdGVycGFzc3dvcmQy + + + + + + + CompanyQuota + Billing + + + + + + CompanyQuota + Billing + + + +]]>400/response/statusFAILUREfalsefalsefalse<xml-fragment/>http://${#Project#E3Manager}:8181 + change-types-auth7 + active + basic + + + + asdfasdf + + + + + + + + CompanyQuota + Billing + + + + + + CompanyQuota + Billing + + + +]]>400/response/statusFAILUREfalsefalsefalse<xml-fragment/>http://${#Project#E3Manager}:8181 + + TestSuite generated for REST Service + [functional-test-provision-api] + + SEQUENTIAL + + + + + + + + + + + + TestCase generated for REST Resource [/apis] located + at [/apis] + + <xml-fragment/>http://${#Project#E3Manager}:8181 + + <xml-fragment/>http://${#Project#E3Manager}:8181 + + + + + + + + + +]]> + + + http://${#Project#E3Manager}:8181 + + + + + + + + + + + + + + + + + + + +]]> + + http://${#Project#E3Manager}:8181 + + auth-type-ip-white-list-api1 + test_route_1 + PassThrough + active + auth-type-ip-white-list-endpoint1 + false + + + ipWhiteList + + + + false + + + + + + http://${#Project#Target1}/proxySize + + NoAuth + + key000Val + + + + + active + 100 + 0.0 + 100 + 0.0 + + + + + + + CompanyQuota + Billing + + + + + + CompanyQuota + Billing + + + +]]> + + + 200 + + + + + /response/status + SUCCESS + false + false + false + + + + /response/idauth-type-ip-white-list-api1falsefalsefalse + + + + + + + <xml-fragment/>http://${#Project#E3Manager}:8181 + auth-type-ip-white-list-auth1 + active + ipWhiteList + + + + 256.2.2.1 + + + + + + CompanyQuota + Billing + + + + + + CompanyQuota + Billing + + + +]]>500/response/error/errorCode102falsefalsefalse/response/statusFAILUREfalsefalsefalse + + <xml-fragment/>http://${#Project#E3Manager}:8181 + auth-type-ip-white-list-auth1 + active + ipWhiteList + + + + + + + + + + CompanyQuota + Billing + + + + + + CompanyQuota + Billing + + + +]]>500/response/error/errorCode102falsefalsefalse/response/statusFAILUREfalsefalsefalse<xml-fragment/>http://${#Project#E3Manager}:8181<xml-fragment/>http://${#Project#E3Manager}:8181 + + + + + + + + + +]]> + + + http://${#Project#E3Manager}:8181 + + + + + + + + + TestCase generated for REST Resource [/apis] located + at [/apis] + + + + <xml-fragment/>http://${#Project#E3Manager}:8181<xml-fragment/>http://${#Project#E3Manager}:8181 + + + + + + + + + + + + +]]> + + + http://${#Project#E3Manager}:8181 + + + + + + + + + + + + + + + + +]]> + + http://${#Project#E3Manager}:8181 + + auth-type-ip-white-list-api2 + test_route_1 + PassThrough + active + auth-type-ip-white-list-endpoint2 + false + + + ipWhiteList + + + + false + + + + + + http://${#Project#Target1}:8080/proxySize + + NoAuth + + key000Val + + + + + active + 100 + 0.0 + 100 + 0.0 + + + + + + + CompanyQuota + Billing + + + + + + CompanyQuota + Billing + + + +]]> + + + 200 + + + + + /response/status + SUCCESS + false + false + false + + + + /response/idauth-type-ip-white-list-api2falsefalsefalse + + + + + + + + + <xml-fragment/>http://${#Project#E3Manager}:8181 + auth-type-ip-white-list-auth2 + active + ipWhiteList + + + + ${= InetAddress.getLocalHost().getHostAddress()} + + + + + + CompanyQuota + Billing + + + + + + CompanyQuota + Billing + + + +]]>200/response/idauth-type-ip-white-list-auth2falsefalsefalse/response/statusSUCCESSfalsefalsefalse<xml-fragment/>http://${#Project#E3Manager}:8181 + auth-type-ip-white-list-auth2 + active + ipWhiteList + + + + ${= InetAddress.getLocalHost().getHostAddress()} + + + + + + CompanyQuota + Billing + + + + + + CompanyQuota + Billing + + + +]]>500/response/error/errorTextProvisioning Server Error: java.lang.IllegalArgumentException: Auth already exists with that ID [auth-type-ip-white-list-auth2]falsefalsefalse/response/statusFAILUREfalsefalsefalse//response/error/errorCode500falsetruefalse<xml-fragment/>http://${#Project#E3Manager}:8181 + auth-type-ip-white-list-p2 + + auth-type-ip-white-list-api2 + + + + auth-type-ip-white-list-auth2 + + + + + active + + active + reject + 98 + 1000 + + + + active + + +]]>200/response/idauth-type-ip-white-list-p2falsefalsefalse/response/statusSUCCESSfalsefalsefalse<xml-fragment/>http://${#Project#E3Gateway}/auth-type-ip-white-list-endpoint2200<xml-fragment/>http://${#Project#E3Manager}:8181<xml-fragment/>http://${#Project#E3Manager}:8181 + + + + + + + + + +]]> + + + http://${#Project#E3Manager}:8181 + + + + + + + + + TestCase generated for REST Resource [/apis] located + at [/apis] + + <xml-fragment/>http://${#Project#E3Manager}:8181 + + <xml-fragment/>http://${#Project#E3Manager}:8181 + + + + + + + + + +]]> + + + http://${#Project#E3Manager}:8181 + + + + + + + + + + + + + + + + + + + +]]> + + http://${#Project#E3Manager}:8181 + + auth-type-ip-white-list-api3 + test_route_1 + PassThrough + active + auth-type-ip-white-list-endpoint3 + false + + + ipWhiteList + + + + false + + + + + + http://${#Project#Target1}/proxySize + + NoAuth + + key000Val + + + + + active + 100 + 0.0 + 100 + 0.0 + + + + + + + CompanyQuota + Billing + + + + + + CompanyQuota + Billing + + + +]]> + + + 200 + + + + + /response/status + SUCCESS + false + false + false + + + + /response/idauth-type-ip-white-list-api3falsefalsefalse + + + + + + + <xml-fragment/>http://${#Project#E3Manager}:8181 + auth-type-ip-white-list-auth3 + active + ipWhiteList + + + + 1.1.4.3 + + + + + + CompanyQuota + Billing + + + + + + CompanyQuota + Billing + + + +]]>200/response/idauth-type-ip-white-list-auth3falsefalsefalse/response/statusSUCCESSfalsefalsefalse + + <xml-fragment/>http://${#Project#E3Manager}:8181 + auth-type-ip-white-list-auth3 + active + ipWhiteList + + + + ${= InetAddress.getLocalHost().getHostAddress()} + + + + + + CompanyQuota + Billing + + + + + + CompanyQuota + Billing + + + +]]>500/response/error/errorTextProvisioning Server Error: java.lang.IllegalArgumentException: Auth already exists with that ID [auth-type-ip-white-list-auth3]falsefalsefalse/response/statusFAILUREfalsefalsefalse//response/error/errorCode500falsetruefalse<xml-fragment/>http://${#Project#E3Manager}:8181 + auth-type-ip-white-list-p3 + + auth-type-ip-white-list-api3 + + + + auth-type-ip-white-list-auth3 + + + + + active + + active + reject + 98 + 1000 + + + + active + + +]]>200/response/idauth-type-ip-white-list-p3falsefalsefalse/response/statusSUCCESSfalsefalsefalse<xml-fragment/>http://${#Project#E3Gateway}/auth-type-ip-white-list-endpoint3final String EXPECTED_STATUS = "HTTP/1.1 401 Unauthorized" +final String RESPONSE_STATUS = messageExchange.getResponseHeaders().get("#status#")[0] +//Verify response code status. Should be HTTP/1.1 401 Unauthorized +assert EXPECTED_STATUS.equals(RESPONSE_STATUS) : "Expected status is \"${EXPECTED_STATUS}\" but was \"${RESPONSE_STATUS}\""Issue: Not Authorizedfalsefalse<xml-fragment/>http://${#Project#E3Manager}:8181<xml-fragment/>http://${#Project#E3Manager}:8181 + + + + + + + + + +]]> + + + http://${#Project#E3Manager}:8181 + + + + + + + + + TestCase generated for REST Resource [/apis] located + at [/apis] + + <xml-fragment/>http://${#Project#E3Manager}:8181 + + <xml-fragment/>http://${#Project#E3Manager}:8181 + + + + + + + + + +]]> + + + http://${#Project#E3Manager}:8181 + + + + + + + + + + + + + + + + + + + +]]> + + http://${#Project#E3Manager}:8181 + + auth-type-ip-white-list-api4 + test_route_1 + PassThrough + active + auth-type-ip-white-list-endpoint4 + false + + + ipWhiteList + + + + false + + + + + + http://${#Project#Target1}/proxySize + + NoAuth + + key000Val + + + + + active + 100 + 0.0 + 100 + 0.0 + + + + + + + CompanyQuota + Billing + + + + + + CompanyQuota + Billing + + + +]]> + + + 200 + + + + + /response/status + SUCCESS + false + false + false + + + + /response/idauth-type-ip-white-list-api4falsefalsefalse + + + + + + + <xml-fragment/>http://${#Project#E3Manager}:8181 + auth-type-ip-white-list-auth4 + active + ipWhiteList + + + + 1.1.1.1 + + + + + + CompanyQuota + Billing + + + + + + CompanyQuota + Billing + + + +]]>200/response/idauth-type-ip-white-list-auth4falsefalsefalse/response/statusSUCCESSfalsefalsefalse + + <xml-fragment/>http://${#Project#E3Manager}:8181 + auth-type-ip-white-list-p4 + + auth-type-ip-white-list-api4 + + + + auth-type-ip-white-list-auth4 + + + + + active + + active + reject + 98 + 1000 + + + + active + + +]]>200/response/idauth-type-ip-white-list-p4falsefalsefalse/response/statusSUCCESSfalsefalsefalse<xml-fragment/>http://${#Project#E3Manager}:8181 + auth-type-ip-white-list-auth4 + inactive + ipWhiteList + + + + ${= InetAddress.getLocalHost().getHostAddress()} + + + + + + CompanyQuota + Billing + + + + + + CompanyQuota + Billing + + + +]]>//response/idauth-type-ip-white-list-auth4falsefalsefalse//response/statusSUCCESSfalsefalsefalse200<xml-fragment/>http://${#Project#E3Gateway}/auth-type-ip-white-list-endpoint4401Issue: Not Authorizedfalsefalse<xml-fragment/>http://${#Project#E3Gateway}/auth-type-ip-white-list-endpoint4final String EXPECTED_STATUS = "HTTP/1.1 401 Unauthorized" +final String RESPONSE_STATUS = messageExchange.getResponseHeaders().get("#status#")[0] +//Verify response code status. Should be HTTP/1.1 401 Unauthorized +assert EXPECTED_STATUS.equals(RESPONSE_STATUS) : "Expected status is \"${EXPECTED_STATUS}\" but was \"${RESPONSE_STATUS}\""Issue: Not Authorizedfalsefalse<xml-fragment/>http://${#Project#E3Manager}:8181<xml-fragment/>http://${#Project#E3Manager}:8181 + + + + + + + + + +]]> + + + http://${#Project#E3Manager}:8181 + + + + + + + + + TestCase generated for REST Resource [/apis] located + at [/apis] + + <xml-fragment/>http://${#Project#E3Manager}:8181 + + <xml-fragment/>http://${#Project#E3Manager}:8181 + + + + + + + + + +]]> + + + http://${#Project#E3Manager}:8181 + + + + + + + + + + + + + + + + + + + +]]> + + http://${#Project#E3Manager}:8181 + + auth-type-ip-white-list-api5 + test_route_1 + PassThrough + active + auth-type-ip-white-list-endpoint5 + false + + + ipWhiteList + + + + false + + + + + + http://${#Project#Target1}/proxySize + + NoAuth + + key000Val + + + + + active + 100 + 0.0 + 100 + 0.0 + + + + + + + CompanyQuota + Billing + + + + + + CompanyQuota + Billing + + + +]]> + + + 200 + + + + + /response/status + SUCCESS + false + false + false + + + + /response/idauth-type-ip-white-list-api5falsefalsefalse + + + + + + + <xml-fragment/>http://${#Project#E3Manager}:8181 + auth-type-ip-white-list-auth5 + active + ipWhiteList + + + + 1.1.4.5 + + + + + + CompanyQuota + Billing + + + + + + CompanyQuota + Billing + + + +]]>200/response/idauth-type-ip-white-list-auth5falsefalsefalse/response/statusSUCCESSfalsefalsefalse + + <xml-fragment/>http://${#Project#E3Manager}:8181 + auth-type-ip-white-list-p5 + + auth-type-ip-white-list-api5 + + + + auth-type-ip-white-list-auth5 + + + + + active + + active + reject + 98 + 1000 + + + + active + + +]]>200/response/idauth-type-ip-white-list-p5falsefalsefalse/response/statusSUCCESSfalsefalsefalse<xml-fragment/>http://${#Project#E3Gateway}/auth-type-ip-white-list-endpoint5final String EXPECTED_STATUS = "HTTP/1.1 401 Unauthorized" +final String RESPONSE_STATUS = messageExchange.getResponseHeaders().get("#status#")[0] +//Verify response code status. Should be HTTP/1.1 401 Unauthorized +assert EXPECTED_STATUS.equals(RESPONSE_STATUS) : "Expected status is \"${EXPECTED_STATUS}\" but was \"${RESPONSE_STATUS}\""Issue: Not Authorizedfalsefalse<xml-fragment/>http://${#Project#E3Manager}:8181 + auth-type-ip-white-list-auth5 + active + ipWhiteList + + + + ${= InetAddress.getLocalHost().getHostAddress()} + + + + + + CompanyQuota + Billing + + + + + + CompanyQuota + Billing + + + +]]>//response/idauth-type-ip-white-list-auth5falsefalsefalse//response/statusSUCCESSfalsefalsefalse200<xml-fragment/>http://${#Project#E3Manager}:8181<xml-fragment/>http://${#Project#E3Manager}:8181 + + + + + + + + + +]]> + + + http://${#Project#E3Manager}:8181 + + + + + + + + + TestCase generated for REST Resource [/apis] located + at [/apis] + + <xml-fragment/>http://${#Project#E3Manager}:8181 + <xml-fragment/>http://${#Project#E3Manager}:8181 + + + + + + + + + + +]]> + + + http://${#Project#E3Manager}:8181 + + + + + + + + + + + + + + + + +]]> + + http://${#Project#E3Manager}:8181 + + auth-type-ip-white-list-api6 + test_route_1 + PassThrough + active + auth-type-ip-white-list-endpoint6 + false + + + ipWhiteList + + + + false + + + + + + http://${#Project#Target1}:8080/proxySize + + NoAuth + + key000Val + + + + + active + 100 + 0.0 + 100 + 0.0 + + + + + + + CompanyQuota + Billing + + + + + + CompanyQuota + Billing + + + +]]> + + + 200 + + + + + /response/status + SUCCESS + false + false + false + + + + /response/idauth-type-ip-white-list-api6falsefalsefalse + + + + + + + + + + <xml-fragment/>http://${#Project#E3Manager}:8181 + auth-type-ip-white-list-auth6 + active + ipWhiteList + + + + ${= InetAddress.getLocalHost().getHostAddress()} + + + + + + CompanyQuota + Billing + + + + + + CompanyQuota + Billing + + + +]]>200/response/idauth-type-ip-white-list-auth6falsefalsefalse/response/statusSUCCESSfalsefalsefalse<xml-fragment/>http://${#Project#E3Manager}:8181 + auth-type-ip-white-list-p6 + + auth-type-ip-white-list-api6 + + + + auth-type-ip-white-list-auth6 + + + + + active + + active + reject + 98 + 1000 + + + + active + + +]]>200/response/idauth-type-ip-white-list-p6falsefalsefalse/response/statusSUCCESSfalsefalsefalse + + <xml-fragment/>http://${#Project#E3Manager}:8181200/response/statusSUCCESSfalsefalsefalse<xml-fragment/>http://${#Project#E3Manager}:8181200/response/statusSUCCESSfalsefalsefalse + + + + + + + + + +]]> + + http://${#Project#E3Manager}:8181 + + + 200 + + + + + /response/status + SUCCESS + false + false + false + + + + + + + + + + TestCase generated for REST Resource [/apis] located + at [/apis] + + + + <xml-fragment/>http://${#Project#E3Manager}:8181 + + + + + <xml-fragment/>http://${#Project#E3Manager}:8181 + auth-type-ip-white-list-auth7 + active + ipWhiteList + + + + ${= InetAddress.getLocalHost().getHostAddress()} + ${= InetAddress.getLocalHost().getHostAddress()} + ${= InetAddress.getLocalHost().getHostAddress()} + + + + + + CompanyQuota + Billing + + + + + + CompanyQuota + Billing + + + +]]>400/response + + Duplicate ip in white-list: ${= InetAddress.getLocalHost().getHostAddress()} + 400 + + FAILURE +]]>falsefalsefalse + + TestCase generated for REST Resource [/apis] located + at [/apis] + + + + <xml-fragment/>http://${#Project#E3Manager}:8181 + + + + + <xml-fragment/>http://${#Project#E3Manager}:8181 + auth-type-ip-white-list-auth8 + active + ipWhiteList + + + + 1.1.4.81 + 1.1.4.82 + 1.1.4.83 + + + + + + CompanyQuota + Billing + + + + + + CompanyQuota + Billing + + + +]]>200/response/idauth-type-ip-white-list-auth8falsefalsefalse/response/statusSUCCESSfalsefalsefalse<xml-fragment/>http://${#Project#E3Manager}:8181 + auth-type-ip-white-list-auth8_2 + active + ipWhiteList + + + + 1.1.4.83 + 1.1.4.81 + 1.1.4.82 + + + + + + CompanyQuota + Billing + + + + + + CompanyQuota + Billing + + + +]]>500/response/statusFAILUREfalsefalsefalse<xml-fragment/>http://${#Project#E3Manager}:8181 + auth-type-ip-white-list-auth8_3 + active + ipWhiteList + + + + 1.1.4.83 + + + + + + CompanyQuota + Billing + + + + + + CompanyQuota + Billing + + + +]]>500/response/statusFAILUREfalsefalsefalse<xml-fragment/>http://${#Project#E3Manager}:8181 + + TestCase generated for REST Resource [/apis] located + at [/apis] + + <xml-fragment/>http://${#Project#E3Manager}:8181 + <xml-fragment/>http://${#Project#E3Manager}:8181 + + + + + + + + + + +]]> + + + http://${#Project#E3Manager}:8181 + + + + + + + + + + + + + + + + + + + +]]> + + http://${#Project#E3Manager}:8181 + + auth-type-ip-white-list-api9 + test_route_1 + PassThrough + active + auth-type-ip-white-list-endpoint9 + false + + + ipWhiteList + + + + false + + + + + + http://${#Project#Target1}:8080/proxySize + + NoAuth + + key000Val + + + + + active + 100 + 0.0 + 100 + 0.0 + + + + + + + CompanyQuota + Billing + + + + + + CompanyQuota + Billing + + + +]]> + + + 200 + + + + + /response/status + SUCCESS + false + false + false + + + + /response/idauth-type-ip-white-list-api9falsefalsefalse + + + + + + + <xml-fragment/>http://${#Project#E3Manager}:8181 + auth-type-ip-white-list-auth9 + active + ipWhiteList + + + + ${= InetAddress.getLocalHost().getHostAddress()} + + + + + + CompanyQuota + Billing + + + + + + CompanyQuota + Billing + + + +]]>200/response/idauth-type-ip-white-list-auth9falsefalsefalse/response/statusSUCCESSfalsefalsefalse + + <xml-fragment/>http://${#Project#E3Manager}:8181 + auth-type-ip-white-list-p9 + + auth-type-ip-white-list-api9 + + + + auth-type-ip-white-list-auth9 + + + + + active + + active + reject + 98 + 1000 + + + + active + + +]]>200/response/idauth-type-ip-white-list-p9falsefalsefalse/response/statusSUCCESSfalsefalsefalse<xml-fragment/>http://${#Project#E3Gateway}/auth-type-ip-white-list-endpoint9200<xml-fragment/>http://${#Project#E3Manager}:8181200/response/statusSUCCESSfalsefalsefalse<xml-fragment/>http://${#Project#E3Manager}:8181 + auth-type-ip-white-list-auth9 + active + ipWhiteList + + + + 94.156.99.150 + + + + + + CompanyQuota + Billing + + + + + + CompanyQuota + Billing + + + +]]>200/response/idauth-type-ip-white-list-auth9falsefalsefalse/response/statusSUCCESSfalsefalsefalse<xml-fragment/>http://${#Project#E3Manager}:8181<quotaRLBucket> + <authId>auth-type-ip-white-list-auth9</authId> +</quotaRLBucket>200/response/statusSUCCESSfalsefalsefalse + + +<xml-fragment/>http://${#Project#E3Gateway}/auth-type-ip-white-list-endpoint9401<xml-fragment/>http://${#Project#E3Manager}:8181200/response/statusSUCCESSfalsefalsefalse<xml-fragment/>http://${#Project#E3Manager}:8181200/response/statusSUCCESSfalsefalsefalse + + + + + + + + + +]]> + + http://${#Project#E3Manager}:8181 + + + 200 + + + + + /response/status + SUCCESS + false + false + false + + + + + + + + + + TestCase generated for REST Resource [/apis] located + at [/apis] + + <xml-fragment/>http://${#Project#E3Manager}:8181 + + <xml-fragment/>http://${#Project#E3Manager}:8181<xml-fragment/>http://${#Project#E3Manager}:8181 + + + + + + + + + + + + +]]> + + + http://${#Project#E3Manager}:8181 + + + + + + + + + + + + + + + + + + +]]> + + http://${#Project#E3Manager}:8181 + + auth-type-ip-white-list-api10 + test_route_1 + PassThrough + active + auth-type-ip-white-list-endpoint10 + false + + + ipWhiteList + + + + false + + + + + + http://${#Project#Target1}/proxySize + + NoAuth + + key000Val + + + + + active + 100 + 0.0 + 100 + 0.0 + + + + + + + CompanyQuota + Billing + + + + + + CompanyQuota + Billing + + + +]]> + + + 200 + + + + + /response/status + SUCCESS + false + false + false + + + + /response/idauth-type-ip-white-list-api10falsefalsefalse + + + + + + + <xml-fragment/>http://${#Project#E3Manager}:8181 + auth-type-ip-white-list-auth10_1 + active + ipWhiteList + + + + 1.1.4.101 + + + + + + CompanyQuota + Billing + + + + + + CompanyQuota + Billing + + + +]]>200/response/idauth-type-ip-white-list-auth10_1falsefalsefalse/response/statusSUCCESSfalsefalsefalse<xml-fragment/>http://${#Project#E3Manager}:8181 + auth-type-ip-white-list-auth10_2 + active + ipWhiteList + + + + 1.1.4.102 + + + + + + CompanyQuota + Billing + + + + + + CompanyQuota + Billing + + + +]]>200/response/idauth-type-ip-white-list-auth10_2falsefalsefalse/response/statusSUCCESSfalsefalsefalse<xml-fragment/>http://${#Project#E3Manager}:8181 + auth-type-ip-white-list-auth10_2 + active + ipWhiteList + + + + 1.1.4.101 + + + + + + CompanyQuota + Billing + + + + + + CompanyQuota + Billing + + + +]]>//response/error/errorCode500falsefalsefalse//response/statusFAILUREfalsefalsefalse500//response/error/errorTextProvisioning Server Error: java.lang.IllegalArgumentException: An authorization with the same IP address already existfalsefalsefalse<xml-fragment/>http://${#Project#E3Manager}:8181<xml-fragment/>http://${#Project#E3Manager}:8181<xml-fragment/>http://${#Project#E3Manager}:8181 + + + + + + + + + +]]> + + + http://${#Project#E3Manager}:8181 + + + + + + + + + + TestSuite generated for REST Service + [functional-test-provision-api] + + SEQUENTIAL + + + + + + + + + + + + TestCase generated for REST Resource [/apis] located + at [/apis] + + + + <xml-fragment/>http://${#Project#E3Manager}:8181 + + + <xml-fragment/>http://${#Project#E3Manager}:8181 + + + + + + + + + +]]> + + + http://${#Project#E3Manager}:8181 + + + + + + + + + + + + + + + + + + +]]> + + http://${#Project#E3Manager}:8181 + + auth-type-wsse-api1 + test_route_1 + PassThrough + active + auth-type-wsse-endpoint1 + false + + + wsse + + + + false + + + + + + http://${#Project#Target1}:8080/proxySize + + NoAuth + + key000Val + + + + + active + 100 + 50.0 + 100 + 50.0 + + + + + + + CompanyQuota + Billing + + + + + + CompanyQuota + Billing + + + +]]> + + + 200 + + + + + /response/status + SUCCESS + false + false + false + + + + /response/idauth-type-wsse-api1falsefalsefalse + + + + + + + <xml-fragment/>http://${#Project#E3Manager}:8181 + auth-type-wsse-auth1 + active + wsse + + + + + dGVzdGVycGFzc3dvcmQy + PlainText + + + + + + CompanyQuota + Billing + + + + + + CompanyQuota + Billing + + + +]]>200/response/idauth0falsefalsefalse/response/statusSUCCESSfalsefalsefalse<xml-fragment/>http://${#Project#E3Manager}:8181 + auth-type-wsse-auth1 + active + wsse + + + + + + PlainText + + + + + + CompanyQuota + Billing + + + + + + CompanyQuota + Billing + + + +]]>200/response/idauth0falsefalsefalse/response/statusSUCCESSfalsefalsefalse<xml-fragment/>http://${#Project#E3Manager}:8181 + auth-type-wsse-auth1 + active + wsse + + + + username1 + + PlainText + + + + + + CompanyQuota + Billing + + + + + + CompanyQuota + Billing + + + +]]>200/response/idauth0falsefalsefalse/response/statusSUCCESSfalsefalsefalse<xml-fragment/>http://${#Project#E3Manager}:8181 + auth-type-wsse-auth1 + active + wsse + + + + auth-type-wsse-username1 + YXV0aC10eXBlLXdzc2UtcGFzc3dvcmQx + + PlainText + + + + + + CompanyQuota + Billing + + + + + + CompanyQuota + Billing + + + +]]>200/response/idauth0falsefalsefalse/response/statusSUCCESSfalsefalsefalse<xml-fragment/>http://${#Project#E3Manager}:8181 + auth-type-wsse-p1 + + auth-type-wsse-api1 + + + + auth-type-wsse-auth1 + + + + + active + + active + reject + 50 + 100 + + + +]]>200/response/idauth-type-wsse-p1falsefalsefalse/response/statusSUCCESSfalsefalsefalseGlobal HTTP Settings<xml-fragment/>http://${#Project#E3Gateway}/auth-type-wsse-endpoint1 + + + + + ${#TestCase#wsseUsername} + ${#TestCase#wsseDigest} + ${#TestCase#wsseNonce} + ${#TestCase#wssePastCreated} + + + + + + My Simple Service Request + + + +]]>401Global HTTP Settings<xml-fragment/>http://${#Project#E3Gateway}/auth-type-wsse-endpoint1 + + + + + ${#TestCase#wsseUsername} + ${#TestCase#wsseDigest} + ${#TestCase#wsseNonce} + ${#TestCase#wsseFutureCreated} + + + + + + My Simple Service Request + + + +]]>401Global HTTP Settings<xml-fragment/>http://${#Project#E3Gateway}/auth-type-wsse-endpoint1 + + + + + ${#TestCase#wsseUsername} + ${#TestCase#wsseBadDigest} + ${#TestCase#wsseNonce} + ${#TestCase#wsseCreated} + + + + + + My Simple Service Request + + + +]]>401Global HTTP Settings<xml-fragment/>http://${#Project#E3Gateway}/auth-type-wsse-endpoint1 + + + + + ${#TestCase#wsseUsername} + ${#TestCase#wsseBadDigest} + ${#TestCase#wsseNonce} + ${#TestCase#wsseCreated} + + + + + + My Simple Service Request + + + +]]>401Global HTTP Settings<xml-fragment/>http://${#Project#E3Gateway}/auth-type-wsse-endpoint1 + + + + + ${#TestCase#wsseUsername} + ${#TestCase#wsseDigest} + ${#TestCase#wsseNonce} + ${#TestCase#wsseCreated} + + + + + + My Simple Service Request + + + +]]>200Global HTTP Settings<xml-fragment/>http://${#Project#E3Gateway}/auth-type-wsse-endpoint1 + + + + + ${#TestCase#wsseUsername} + ${#TestCase#wsseDigest} + ${#TestCase#wsseNonce} + ${#TestCase#wsseCreated} + + + + + + My Simple Service Request + + + +]]>401Global HTTP Settings<xml-fragment/>http://${#Project#E3Gateway}/auth-type-wsse-endpoint1 + + + + + ${#TestCase#wsseUsername} + ${#TestCase#wsseDigest} + + + + + + My Simple Service Request + + + +]]>200Global HTTP Settings<xml-fragment/>http://${#Project#E3Manager}:8181<xml-fragment/>http://${#Project#E3Manager}:8181 + + + + + + + + + +]]> + + + http://${#Project#E3Manager}:8181 + + + + + + + wsseUsernameauth-type-wsse-username1wsseDigestrSums10OsGJlIZ01fc9OZXMHWWE=wsseNoncewsseCreatedwssePastCreated2012-03-27T01:23:45ZwsseFutureCreated2037-03-27T01:23:45ZwsseBadDigesteDjxgPNb2a+Lq6Wt9PjEs1ImoRQ= + + TestCase generated for REST Resource [/apis] located + at [/apis] + + + + <xml-fragment/>http://${#Project#E3Manager}:8181 + + + <xml-fragment/>http://${#Project#E3Manager}:8181 + + + + + + + + + +]]> + + + http://${#Project#E3Manager}:8181 + + + + + + + + + + + + + + + + + + +]]> + + http://${#Project#E3Manager}:8181 + + auth-type-wsse-api2 + test_route_1 + PassThrough + active + auth-type-wsse-endpoint2 + false + + + wsse + + + + false + + + + + + http://${#Project#Target1}:8080/displayBody + + NoAuth + + key000Val + + + + + active + 100 + 50.0 + 100 + 50.0 + + + + + + + CompanyQuota + Billing + + + + + + CompanyQuota + Billing + + + +]]> + + + 200 + + + + + /response/status + SUCCESS + false + false + false + + + + /response/idauth-type-wsse-api2falsefalsefalse + + + + + + + <xml-fragment/>http://${#Project#E3Manager}:8181 + auth-type-wsse-auth2 + active + wsse + + + + auth-type-wsse-username2 + YXV0aC10eXBlLXdzc2UtcGFzc3dvcmQy + PlainText + + + + + + CompanyQuota + Billing + + + + + + CompanyQuota + Billing + + + +]]>200/response/idauth-type-wsse-auth2falsefalsefalse/response/statusSUCCESSfalsefalsefalse<xml-fragment/>http://${#Project#E3Manager}:8181 + auth-type-wsse-p2 + + auth-type-wsse-api2 + + + + auth-type-wsse-auth2 + + + + + active + + active + reject + 50 + 100 + + + +]]>200/response/idauth-type-wsse-p2falsefalsefalse/response/statusSUCCESSfalsefalsefalseGlobal HTTP Settings<xml-fragment/>http://${#Project#E3Gateway}/auth-type-wsse-endpoint2 + + + + + ${#TestCase#wsseUsername} + ${#TestCase#wsseBadPassword} + + + + + + My Simple Service Request + + + +]]>401Global HTTP Settings<xml-fragment/>http://${#Project#E3Gateway}/auth-type-wsse-endpoint2 + + + + + ${#TestCase#wsseUsername} + ${#TestCase#wssePassword} + + + + + + My Simple Service Request + + + +]]>401Global HTTP Settings<xml-fragment/>http://${#Project#E3Gateway}/auth-type-wsse-endpoint2 + + + + + ${#TestCase#wsseUsername} + ${#TestCase#wssePassword} + + + + + + My Simple Service Request + + + +]]>200My Simple Service Requestfalsefalse<soapenv:EnvelopefalsefalseGlobal HTTP Settings<xml-fragment/>http://${#Project#E3Gateway}/auth-type-wsse-endpoint2 + + + + + ${#TestCase#wsseUsername} + ${#TestCase#wssePassword} + + + + + + My Simple Service Request + + + +]]>200My Simple Service Requestfalsefalse<soapenv:EnvelopefalsefalseGlobal HTTP Settings<xml-fragment/>http://${#Project#E3Manager}:8181<xml-fragment/>http://${#Project#E3Manager}:8181 + + + + + + + + + +]]> + + + http://${#Project#E3Manager}:8181 + + + + + + + wsseUsernameauth-type-wsse-username2wssePasswordauth-type-wsse-password2wsseBadPasswordthis-is-a-bad-password + + E3Managere3-dev-59E3Gatewaye3-dev-59Target1192.168.84.90Target2192.168.84.103Target3192.168.84.184uniqdeleteLOG4J_LEVEL_VALUES(ALL|TRACE|DEBUG|INFO|WARN|ERROR|FATAL|OFF)STATUS_SUCCESSSUCCESSSYSLOG_LEVEL_VALUES(DEBUG|INFO|NOTICE|WARNING|ERR|CRIT|ALERT|EMERG)ResponseCodeDown500 \ No newline at end of file diff --git a/tests/functional-tests/functional-test-ca-prov/pom.xml b/tests/functional-tests/functional-test-ca-prov/pom.xml new file mode 100644 index 0000000..efce41f --- /dev/null +++ b/tests/functional-tests/functional-test-ca-prov/pom.xml @@ -0,0 +1,48 @@ + + 4.0.0 + com.alu.e3.functional-tests.samples + functional-test-ca-prov + pom + + + + eviware + maven-soapui-plugin + 4.0.1 + + + mysql + mysql-connector-java + 5.1.6 + + + junit + junit + 4.8.1 + + + + + test + + test + + + ${basedir}/soapui-project.xml + ${basedir}/target/surefire-reports + true + ${basedir}/soapui-project-properties.xml + + + + + + + + com.alu.e3.functional-tests + functional-tests + 0.0.1-SNAPSHOT + .. + + Functional test certificate authority - Provisioning + \ No newline at end of file diff --git a/tests/functional-tests/functional-test-ca-prov/soapui-project.xml b/tests/functional-tests/functional-test-ca-prov/soapui-project.xml new file mode 100644 index 0000000..d35c595 --- /dev/null +++ b/tests/functional-tests/functional-test-ca-prov/soapui-project.xml @@ -0,0 +1,675 @@ + + +http://${#Project#E3Gateway}/api-parameters-endpoint1?param1=value1&key=api-parameters-key1&param2=value2http://${#Project#E3Gateway}/api-parameters-endpoint2/five?key=api-parameters-key2http://${#Project#E3Gateway}/api-parameters-endpoint2/three/five?key=api-parameters-key2apiauthTEMPLATEkeymykeyQUERYmykeyparam1QUERYtext/plain403 500 429data200data200data0data0data0data200data200data200data200data200data200data0datatext/html200<xml-fragment/>http://${#Project#E3Gateway}keymykeyQUERYmykeyparam1value1QUERYvalue1param2value2QUERYvalue2text/plain403data200data200data0data0data0data200data200data200data200data200data200data200datatext/html2000data<xml-fragment/>http://${#Project#E3Gateway}param1value1QUERYvalue1keymykeyQUERYxs:stringmykeyparam2value2QUERYvalue2text/plain403data200data200data0data0data0data200data200data200data200data200data200datatext/html200<xml-fragment/>http://${#Project#E3Gateway}param1value1QUERYvalue1param2value2QUERYvalue2keymykeyQUERYxs:stringmykeytext/plain403data200data200data0data0data0data200data200data200data200data200data200datatext/html200<xml-fragment/>http://${#Project#E3Gateway}text/plain403data200data200data0data0data0data200data200data200data200data200data200datatext/html200text/html;charset=ISO-8859-1404htmltext/html404html<xml-fragment/>http://${#Project#E3Gateway}param1QUERYtext/plain403 500 429data200data200data0data0data0data200data200data200data200data200data200data0datatext/html200text/html404html<xml-fragment/>http://${#Project#E3Gateway}keyQUERYtext/plain403 500 429data200data200data0data0data0data200data200data200data200data200data200data0datatext/html200text/html;charset=ISO-8859-1404html<xml-fragment/>http://${#Project#E3Gateway}text/plain403data200data200data0data0data0data200data200data200data200data200data200datatext/html200text/html;charset=ISO-8859-1404html0data<xml-fragment/>http://${#Project#E3Gateway}text/plain403data200data200data0data0data0data200data200data200data200data200data200datatext/html200text/html;charset=ISO-8859-1404html<xml-fragment/>http://${#Project#E3Gateway}text/plain403data200data200data0data0data0data200data200data200data200data200data200datatext/html200text/html;charset=ISO-8859-1404html0data0data0data0data<xml-fragment/>http://${#Project#E3Gateway}param1QUERYtext/plain403data200data200data0data0data0data200data200data200data200data200data200datatext/html200text/html;charset=ISO-8859-1404html0data<xml-fragment/>http://${#Project#E3Gateway}param1QUERYkeyQUERYtext/plain403data200data200data0data0data0data200data200data200data200data200data200datatext/html200text/html;charset=ISO-8859-1404html0data<xml-fragment/>http://${#Project#E3Gateway}keyQUERYtext/plain403data200data200data0data0data0data200data200data200data200data200data200datatext/html200text/html;charset=ISO-8859-1404html0data<xml-fragment/>http://${#Project#E3Gateway}text/plain403data200data200data0data0data0data200data200data200data200data200data200datatext/html200text/html;charset=ISO-8859-1404html0data0data<xml-fragment/>http://${#Project#E3Gateway}param1QUERYtext/plain403data200data200data0data0data0data200data200data200data200data200data200datatext/html200text/html;charset=ISO-8859-1404html0data<xml-fragment/>http://${#Project#E3Gateway}param1QUERYkeyQUERYtext/plain403data200data200data0data0data0data200data200data200data200data200data200datatext/html200text/html;charset=ISO-8859-1404html0data<xml-fragment/>http://${#Project#E3Gateway}text/plain403data200data200data0data0data0data200data200data200data200data200data200datatext/html200text/html;charset=ISO-8859-1404html<xml-fragment/>http://${#Project#E3Gateway}text/plain403 500data200data200data0data0data0data200data200data200data200data200data200datatext/html200text/html;charset=ISO-8859-1404html0datatext/html; charset=iso-8859-1404html<xml-fragment/>http://${#Project#E3Gateway}text/plain403data200data200data0data0data0data200data200data200data200data200data200datatext/html200text/html;charset=ISO-8859-1404html<xml-fragment/>http://${#Project#E3Gateway}text/html200text/plain403 500datatext/html404htmlhttp://${#Project#E3Gateway} + + + http://${#Project#E3Gateway}/auth-extended-endpoint1?key=auth-extended-key1http://${#Project#E3Gateway}/auth-extended-endpoint1http://${#Project#E3Gateway}/auth-extended-endpoint2http://${#Project#E3Gateway}/api-header-transform-endpoint1?key=api-header-transform-key1http://${#Project#E3Gateway}/api-header-transform-endpoint2?key=api-header-transform-key2http://${#Project#E3Gateway}/api-header-transform-endpoint3?key=api-header-transform-key3http://${#Project#E3Gateway}/provision-api-ext-endpoint1http://${#Project#E3Gateway}/provision-api-ext-endpoint3?key=provision-api-ext-key3 + + + + + + keyQUERY + + text/html + 200 + + html + + + + 0 + + data + + + text/plain + 500 403 401 429 + + data + + + + 200 + + data + + + + 200 + + data + + + text/html + 404 + + html + + 0data0data0data0data0data + 0data0datatext/xml200data<xml-fragment xmlns:con="http://eviware.com/soapui/config"> + <con:entry key="WAIT" value="0"/> + <con:entry key="SIZE" value="100"/> +</xml-fragment>http://${#Project#E3Gateway}/endpoint1<xml-fragment xmlns:con="http://eviware.com/soapui/config"> + <con:entry key="WAIT" value="0"/> + <con:entry key="SIZE" value="100"/> +</xml-fragment>http://${#Project#E3Gateway}/endpoint1 + text/plain401 403 429 500datatext/html200html0data0data0data0datatext/html404htmltext/xml200data<xml-fragment xmlns:con="http://eviware.com/soapui/config"> + <con:entry key="WAIT" value="0"/> + <con:entry key="SIZE" value="100"/> +</xml-fragment>http://${#Project#E3Gateway}/endpoint1text/plain401 500 429data0data0data0data0data0data0data0data0data0data0datatext/xml200datatext/html404html<xml-fragment xmlns:con="http://eviware.com/soapui/config"> + <con:entry key="Authorization" value="Basic dGVzdGVyOnRlc3RlcnBhc3N3b3Jk"/> + <con:entry key="WAIT" value="0"/> + <con:entry key="SIZE" value="100"/> +</xml-fragment>http://${#Project#E3Gateway}/endpoint1<xml-fragment xmlns:con="http://eviware.com/soapui/config"> + <con:entry key="Authorization" value="Basic invalidbasic"/> + <con:entry key="WAIT" value="0"/> + <con:entry key="SIZE" value="100"/> +</xml-fragment>http://${#Project#E3Gateway}/endpoint1text/xml200datatext/html200data<xml-fragment xmlns:con="http://eviware.com/soapui/config"> + <con:entry key="WAIT" value="0"/> + <con:entry key="SIZE" value="100"/> +</xml-fragment>http://${#Project#E3Gateway}/endpoint1?key=e88ba0c1e4c34f25bf95733eebd8574f + http://${#Project#E3Gateway}:8181/cxf/e3/prov/v1?_wadl&_type=xml + + + + E3 REST API to create, update or delete an API + + Used to get all API IDs. + + + + + + This REST API is used to create an API. + + + + + + + + + + + This REST API is used to delete an API. + + + + + + + Used to get an API by this ID. + + + + + + + This REST API is used to update an API. + + + + + + + + + + + E3 REST API to create, update or delete a policy + + This REST API is used to fetch all policy ids. + + + + + + This REST API is used to create a policy. + + + + + + + + + + + This REST API is used to delete a policy. + + + + + + + This REST API is used to fetch policy data. + + + + + + + This REST API is used to update a policy. + + + + + + + + + + + + This REST API is used to create a QuotaRLBucket in a policy. + + + + + + + + + + + + + This REST API is used to remove a bucket from a policy. + + + + + + + This REST API is used to append auths to a bucket. + + + + + + + + + + + + + + This REST API is used to remove an auth from a bucket. + + + + + + + + + E3 REST API provision authentications on E3 subsystem + + This REST API is used to get all authentications from E3 subsystem. + + + + + + This REST API is used to create an authentication element on E3 subsystem. + + + + + + + + + + + This REST API is used to delete an Auth. + + + + + + + This REST API is used to get an authentication by ID from E3 subsystem. + + + + + + + This REST API is used to update an authentication. + + + + + + + + + + + E3 REST API to create or delete a bucket of auths associated to a list of policies + + This REST API is used to create a bucket linked to a list of policies. + + + + + + + + + + + This REST API is used to append auths to a bucket for several policies. + + + + + + + + + + + + This REST API is used to remove a bucket from a list of policies. + + + + + + + + + + + E3 REST API provision SSLKeys and SSLCerts on E3 subsystem + + This REST API is used to get all SSLKeys from E3 subsystem. + + + + + + This REST API is used to create an SSLKey element on E3 subsystem. + + + + + + + + + + + This REST API is used to delete an SSLKey. + + + + + + + This REST API is used to get an SSLKey by ID from E3 subsystem. + + + + + + + This REST API is used to update an SSLKey. + + + + + + + + + + + + This REST API is used to get all SSLCerts for a key. + + + + + + + This REST API is used to create an SSLCert element on E3 subsystem. + + + + + + + + + + + + + This REST API is used to delete an SSLCert. + + + + + + + This REST API is used to get an SSLKey by ID from E3 subsystem. + + + + + + + This REST API is used to update an SSLKey. + + + + + + + + + + + + This REST API is used to get a CSR for the given SSLKey ID from E3 subsystem. + + + + + + + + + + This REST API is used to create a self-signed cert for an existing Key + + + + + + + + + E3 REST API to add/update/delete trusted CAs and CRLs + + + This REST API is used to fetch all trusted certificates authorithies. + + + + + + This REST API is used to add a trusted Certificate Authority. + + + + + + + + + + + + This REST API is used to remove a trusted Certificate Authority. + + + + + + + This REST API is used to fetch trusted Certificate Authority. + + + + + + + This REST API is used to update a trusted Certificate Authority. + + + + + + + + + + + This REST API is used to fetch trusted Certificate Authority. + + + + + + This REST API is used to add a Certificate Revocation List for this Certificate Authority. + + + + + + + + + + + + This REST API is used to remove a certificate revocation list from a certificate authority. + + + + + + + This REST API is used to fetch Certificate Revocation List. + + + + + + + This REST API is used to update a certificate revocation list. + + + + + + + + + + +]]>http://wadl.dev.java.net/2009/02http://${#Project#E3Gateway}:8181API_IDTEMPLATExs:stringapplication/xmlhttp://${#Project#E3Gateway}:8181application/xmlhttp://${#Project#E3Gateway}:8181application/xmlapplication/xmlhttp://${#Project#E3Gateway}:8181application/xmlhttp://${#Project#E3Gateway}:8181application/xmlapplication/xmlhttp://${#Project#E3Gateway}:8181POLICY_IDTEMPLATExs:stringapplication/xmlhttp://${#Project#E3Gateway}:8181application/xmlhttp://${#Project#E3Gateway}:8181application/xmlapplication/xmlhttp://${#Project#E3Gateway}:8181POLICY_IDTEMPLATExs:stringapplication/xmlapplication/xmlhttp://${#Project#E3Gateway}:8181POLICY_IDTEMPLATExs:stringBUCKET_IDTEMPLATExs:stringapplication/xmlhttp://${#Project#E3Gateway}:8181application/xmlapplication/xmlhttp://${#Project#E3Gateway}:8181POLICY_IDTEMPLATExs:stringBUCKET_IDTEMPLATExs:stringAUTH_IDTEMPLATExs:stringapplication/xmlhttp://${#Project#E3Gateway}:8181application/xmlhttp://${#Project#E3Gateway}:8181application/xmlapplication/xmlhttp://${#Project#E3Gateway}:8181AUTH_IDTEMPLATExs:stringapplication/xmlhttp://${#Project#E3Gateway}:8181application/xmlhttp://${#Project#E3Gateway}:8181application/xmlapplication/xmlhttp://${#Project#E3Gateway}:8181application/xmlhttp://${#Project#E3Gateway}:8181application/xmlapplication/xmlhttp://${#Project#E3Gateway}:8181BUCKET_IDTEMPLATExs:stringapplication/xmlapplication/xmlhttp://${#Project#E3Gateway}:8181BUCKET_IDTEMPLATExs:stringapplication/xmlapplication/xmlhttp://${#Project#E3Gateway}:8181application/xmlapplication/xmlhttp://${#Project#E3Gateway}:8181KEY_IDTEMPLATExs:stringapplication/xmlhttp://${#Project#E3Gateway}:8181application/xmlhttp://${#Project#E3Gateway}:8181application/xmlapplication/xmlhttp://${#Project#E3Gateway}:8181KEY_IDTEMPLATExs:stringapplication/xmlhttp://${#Project#E3Gateway}:8181application/xmlapplication/xmlhttp://${#Project#E3Gateway}:8181KEY_IDTEMPLATExs:stringCERT_IDTEMPLATExs:stringapplication/xmlhttp://${#Project#E3Gateway}:8181application/xmlhttp://${#Project#E3Gateway}:8181application/xmlapplication/xmlhttp://${#Project#E3Gateway}:8181KEY_IDTEMPLATExs:stringapplication/xmlhttp://${#Project#E3Gateway}:8181KEY_IDTEMPLATExs:stringapplication/xmlhttp://${#Project#E3Gateway}:8181application/xmlhttp://${#Project#E3Gateway}:8181application/xmlapplication/xmlhttp://${#Project#E3Gateway}:8181application/xmlhttp://${#Project#E3Gateway}:8181application/xmlapplication/xmlhttp://${#Project#E3Gateway}:8181CA_IDTEMPLATExs:stringapplication/xmlhttp://${#Project#E3Gateway}:8181application/xmlhttp://${#Project#E3Gateway}:8181application/xmlapplication/xmlhttp://${#Project#E3Gateway}:8181application/xmlhttp://${#Project#E3Gateway}:8181application/xmlapplication/xmlhttp://${#Project#E3Gateway}:8181CRL_IDTEMPLATExs:stringapplication/xmlhttp://${#Project#E3Gateway}:8181application/xmlhttp://${#Project#E3Gateway}:8181application/xmlapplication/xmlhttp://${#Project#E3Gateway}:8181file:/D:/Documents%20and%20Settings/mtobiasz/Desktop/targertest_1.wadl + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + +]]>http://wadl.dev.java.net/2009/02http://${#Project#E3Gateway}http://${#Project#E3Gateway}/api-http-method-endpoint1?key=api-http-method-key1http://${#Project#E3Gateway}/api-http-method-endpoint2?key=api-http-method-key2http://${#Project#E3Gateway}/api-http-method-endpoint3?key=api-http-method-key3http://${#Project#E3Gateway}/api-http-method-endpoint4?key=api-http-method-key40text/html200http://${#Project#E3Gateway}application/xml0application/xmltext/plain403 405 429text/xml200ns:responsehttp://${#Project#E3Gateway}application/xmlapplication/xmltext/plain405 429text/xml200ns:responsehttp://${#Project#E3Gateway}text/plain405 429text/xml200ns:responsehttp://${#Project#E3Gateway}0text/plain405text/xml200http://${#Project#E3Gateway}SEQUENTIAL<xml-fragment/>http://${#Project#E3Manager}:8181<xml-fragment/>http://${#Project#E3Manager}:8181 + + +<xml-fragment/>http://${#Project#E3Manager}:8181 + > + auth-ca-prov-ca1_1 + +]]>200/response/idauth-ca-prov-ca1_1falsefalsefalse/response/statusSUCCESSfalsefalsefalse<xml-fragment/>http://${#Project#E3Manager}:8181200/response/statusSUCCESSfalsefalsefalse/response/cert/displayNameauth-ca-prov-ca1_1falsefalsefalse/response/cert/content-----BEGIN CERTIFICATE----- +MIIBpjCCAVACCQC7WQANxgAjaDANBgkqhkiG9w0BAQUFADBaMQswCQYDVQQGEwJH +QjESMBAGA1UECBMJQmVya3NoaXJlMRAwDgYDVQQHEwdOZXdidXJ5MRcwFQYDVQQK +Ew5NeSBDb21wYW55IEx0ZDEMMAoGA1UEAxMDQ0ExMB4XDTEyMDUzMDA4MjAyOVoX +DTEzMDUzMDA4MjAyOVowWjELMAkGA1UEBhMCR0IxEjAQBgNVBAgTCUJlcmtzaGly +ZTEQMA4GA1UEBxMHTmV3YnVyeTEXMBUGA1UEChMOTXkgQ29tcGFueSBMdGQxDDAK +BgNVBAMTA0NBMTBcMA0GCSqGSIb3DQEBAQUAA0sAMEgCQQDprqtFm1ecyxFR69wU +FZdUnhKJriQO/J89TqD9+xMbW0KZfpk6N+EsH1x6tIxguF7ketdJxdYP37IfHrEk +Uc2jAgMBAAEwDQYJKoZIhvcNAQEFBQADQQB25EXtF8PBPm8lRJ0Y0n/BmYkp4k8F +mZrknQf2fVaOHW7VH5Y2Cg6awXpuAm3tijuPiJMt56tZHiTOh1MgemSc +-----END CERTIFICATE-----falsefalsefalse<cert id="auth-ca-prov-ca1_1">falsefalse<xml-fragment/>http://${#Project#E3Manager}:8181 + > + auth-ca-prov-ca1_2 + +]]>200/response/idauth-ca-prov-ca1_2falsefalsefalse/response/statusSUCCESSfalsefalsefalse<xml-fragment/>http://${#Project#E3Manager}:8181200/response/statusSUCCESSfalsefalsefalse/response/cert/content-----BEGIN CERTIFICATE----- +MIIBnjCCAUgCAQIwDQYJKoZIhvcNAQEFBQAwWjELMAkGA1UEBhMCR0IxEjAQBgNV +BAgTCUJlcmtzaGlyZTEQMA4GA1UEBxMHTmV3YnVyeTEXMBUGA1UEChMOTXkgQ29t +cGFueSBMdGQxDDAKBgNVBAMTA0NBMTAeFw0xMjA2MDUxNDA4MDFaFw0xMzA2MDUx +NDA4MDFaMFoxCzAJBgNVBAYTAkdCMRIwEAYDVQQIEwlCZXJrc2hpcmUxEDAOBgNV +BAcTB05ld2J1cnkxFzAVBgNVBAoTDk15IENvbXBhbnkgTHRkMQwwCgYDVQQDEwND +QTIwXDANBgkqhkiG9w0BAQEFAANLADBIAkEA0a3UhJIHBe55EbbmvqUAtYv+lG6h +IFv9LQV/jmOR7unoZchlCCXaIzhBMVJ2lF9q5XD2UfiIwTQoFYMUt0wRKwIDAQAB +MA0GCSqGSIb3DQEBBQUAA0EA4oJsNy6bMV7LB4ecwI7lOgTtoFff0pkC3VIaiMQH +t/WY/K806hvWym01uyfxLkzkIkJ4cVEFtXLyUYEaiip0rg== +-----END CERTIFICATE-----falsefalsefalse/response/cert/displayNameauth-ca-prov-ca1_2falsefalsefalse<cert id="auth-ca-prov-ca1_2">falsefalse + + +<xml-fragment/>http://${#Project#E3Manager}:8181200/response/statusSUCCESSfalsefalsefalse<id>auth-ca-prov-ca1_1</id>falsefalse<id>auth-ca-prov-ca1_2</id>falsefalse<xml-fragment/>http://${#Project#E3Manager}:8181200/response/statusSUCCESSfalsefalsefalse + + +<xml-fragment/>http://${#Project#E3Manager}:8181200/response/statusSUCCESSfalsefalsefalse<id>auth-ca-prov-ca1_1</id>falsefalse<xml-fragment/>http://${#Project#E3Manager}:8181<cert id="auth-ca-prov-ca1_1"> + <displayName>new cert auth 1</displayName> +</cert> +200/response/statusSUCCESSfalsefalsefalse<xml-fragment/>http://${#Project#E3Manager}:8181200/response/statusSUCCESSfalsefalsefalse/response/cert/displayNamenew cert auth 1falsefalsefalse/response/cert/content-----BEGIN CERTIFICATE----- +MIIBpjCCAVACCQC7WQANxgAjaDANBgkqhkiG9w0BAQUFADBaMQswCQYDVQQGEwJH +QjESMBAGA1UECBMJQmVya3NoaXJlMRAwDgYDVQQHEwdOZXdidXJ5MRcwFQYDVQQK +Ew5NeSBDb21wYW55IEx0ZDEMMAoGA1UEAxMDQ0ExMB4XDTEyMDUzMDA4MjAyOVoX +DTEzMDUzMDA4MjAyOVowWjELMAkGA1UEBhMCR0IxEjAQBgNVBAgTCUJlcmtzaGly +ZTEQMA4GA1UEBxMHTmV3YnVyeTEXMBUGA1UEChMOTXkgQ29tcGFueSBMdGQxDDAK +BgNVBAMTA0NBMTBcMA0GCSqGSIb3DQEBAQUAA0sAMEgCQQDprqtFm1ecyxFR69wU +FZdUnhKJriQO/J89TqD9+xMbW0KZfpk6N+EsH1x6tIxguF7ketdJxdYP37IfHrEk +Uc2jAgMBAAEwDQYJKoZIhvcNAQEFBQADQQB25EXtF8PBPm8lRJ0Y0n/BmYkp4k8F +mZrknQf2fVaOHW7VH5Y2Cg6awXpuAm3tijuPiJMt56tZHiTOh1MgemSc +-----END CERTIFICATE-----falsefalsefalse<cert id="auth-ca-prov-ca1_1">falsefalse<xml-fragment/>http://${#Project#E3Manager}:8181200/response/statusSUCCESSfalsefalsefalse<xml-fragment/>http://${#Project#E3Manager}:8181404/response/statusFAILUREfalsefalsefalse/response/error/errorTextA CA with that ID [auth-ca-prov-ca1_1] doesn't existfalsefalsefalse/response/error/errorCode114falsefalsefalse<xml-fragment/>http://${#Project#E3Manager}:8181200/response/statusSUCCESSfalsefalsefalse<id>auth-ca-prov-ca1_1</id>falsefalse<id>auth-ca-prov-ca1_2</id>falsefalseSEQUENTIAL<xml-fragment/>http://${#Project#E3Manager}:8181404/response/statusFAILUREfalsefalsefalse/response/error/errorCode114falsefalsefalse/response/error/errorTextA CA with that ID [ca-prov-ext-ca1] doesn't existfalsefalsefalse + + +<xml-fragment/>http://${#Project#E3Manager}:8181 + > + ca-prov-ext-ca1 + +]]>404/response/statusFAILUREfalsefalsefalse/response/error/errorCode114falsefalsefalse/response/error/errorTextA CA with that ID [ca-prov-ext-ca1] doesn't existfalsefalsefalse + + +<xml-fragment/>http://${#Project#E3Manager}:8181404/response/error/errorCode114falsefalsefalse/response/error/errorTextA CA with that ID [ca-prov-ext-ca1] doesn't existfalsefalsefalse + + +E3Managere3-int-aib-1E3Gatewaye3-int-aib-1Target1192.168.84.90uniqdelete \ No newline at end of file diff --git a/tests/functional-tests/functional-test-header-transform/pom.xml b/tests/functional-tests/functional-test-header-transform/pom.xml new file mode 100644 index 0000000..5fe9ca6 --- /dev/null +++ b/tests/functional-tests/functional-test-header-transform/pom.xml @@ -0,0 +1,48 @@ + + 4.0.0 + com.alu.e3.functional-tests.samples + functional-test-header-transform + pom + + + + eviware + maven-soapui-plugin + 4.0.1 + + + mysql + mysql-connector-java + 5.1.6 + + + junit + junit + 4.8.1 + + + + + test + + test + + + ${basedir}/soapui-project.xml + ${basedir}/target/surefire-reports + true + ${basedir}/soapui-project-properties.xml + + + + + + + + com.alu.e3.functional-tests + functional-tests + 0.0.1-SNAPSHOT + .. + + Functional test Header Transformation + \ No newline at end of file diff --git a/tests/functional-tests/functional-test-header-transform/soapui-project.xml b/tests/functional-tests/functional-test-header-transform/soapui-project.xml new file mode 100644 index 0000000..52c79fe --- /dev/null +++ b/tests/functional-tests/functional-test-header-transform/soapui-project.xml @@ -0,0 +1,1730 @@ + + +http://${#Project#E3Gateway}/api-parameters-endpoint1?param1=value1&key=api-parameters-key1&param2=value2http://${#Project#E3Gateway}/api-parameters-endpoint2/five?key=api-parameters-key2http://${#Project#E3Gateway}/api-parameters-endpoint2/three/five?key=api-parameters-key2apiauthTEMPLATEkeymykeyQUERYmykeyparam1QUERYtext/plain403 500 429data200data200data0data0data0data200data200data200data200data200data200data0datatext/html200<xml-fragment/>http://${#Project#E3Gateway}keymykeyQUERYmykeyparam1value1QUERYvalue1param2value2QUERYvalue2text/plain403data200data200data0data0data0data200data200data200data200data200data200data200datatext/html2000data<xml-fragment/>http://${#Project#E3Gateway}param1value1QUERYvalue1keymykeyQUERYxs:stringmykeyparam2value2QUERYvalue2text/plain403data200data200data0data0data0data200data200data200data200data200data200datatext/html200<xml-fragment/>http://${#Project#E3Gateway}param1value1QUERYvalue1param2value2QUERYvalue2keymykeyQUERYxs:stringmykeytext/plain403data200data200data0data0data0data200data200data200data200data200data200datatext/html200<xml-fragment/>http://${#Project#E3Gateway}text/plain403data200data200data0data0data0data200data200data200data200data200data200datatext/html200text/html;charset=ISO-8859-1404htmltext/html404html<xml-fragment/>http://${#Project#E3Gateway}param1QUERYtext/plain403 500 429data200data200data0data0data0data200data200data200data200data200data200data0datatext/html200text/html404html<xml-fragment/>http://${#Project#E3Gateway}keyQUERYtext/plain403 500 429data200data200data0data0data0data200data200data200data200data200data200data0datatext/html200text/html;charset=ISO-8859-1404html<xml-fragment/>http://${#Project#E3Gateway}text/plain403data200data200data0data0data0data200data200data200data200data200data200datatext/html200text/html;charset=ISO-8859-1404html0data<xml-fragment/>http://${#Project#E3Gateway}text/plain403data200data200data0data0data0data200data200data200data200data200data200datatext/html200text/html;charset=ISO-8859-1404html<xml-fragment/>http://${#Project#E3Gateway}text/plain403data200data200data0data0data0data200data200data200data200data200data200datatext/html200text/html;charset=ISO-8859-1404html0data0data0data0data<xml-fragment/>http://${#Project#E3Gateway}param1QUERYtext/plain403data200data200data0data0data0data200data200data200data200data200data200datatext/html200text/html;charset=ISO-8859-1404html0data<xml-fragment/>http://${#Project#E3Gateway}param1QUERYkeyQUERYtext/plain403data200data200data0data0data0data200data200data200data200data200data200datatext/html200text/html;charset=ISO-8859-1404html0data<xml-fragment/>http://${#Project#E3Gateway}keyQUERYtext/plain403data200data200data0data0data0data200data200data200data200data200data200datatext/html200text/html;charset=ISO-8859-1404html0data<xml-fragment/>http://${#Project#E3Gateway}text/plain403data200data200data0data0data0data200data200data200data200data200data200datatext/html200text/html;charset=ISO-8859-1404html0data0data<xml-fragment/>http://${#Project#E3Gateway}param1QUERYtext/plain403data200data200data0data0data0data200data200data200data200data200data200datatext/html200text/html;charset=ISO-8859-1404html0data<xml-fragment/>http://${#Project#E3Gateway}param1QUERYkeyQUERYtext/plain403data200data200data0data0data0data200data200data200data200data200data200datatext/html200text/html;charset=ISO-8859-1404html0data<xml-fragment/>http://${#Project#E3Gateway}text/plain403data200data200data0data0data0data200data200data200data200data200data200datatext/html200text/html;charset=ISO-8859-1404html<xml-fragment/>http://${#Project#E3Gateway}text/plain403 500data200data200data0data0data0data200data200data200data200data200data200datatext/html200text/html;charset=ISO-8859-1404html0datatext/html; charset=iso-8859-1404html<xml-fragment/>http://${#Project#E3Gateway}text/plain403data200data200data0data0data0data200data200data200data200data200data200datatext/html200text/html;charset=ISO-8859-1404html<xml-fragment/>http://${#Project#E3Gateway}text/html200text/plain403 500datatext/html404htmlhttp://${#Project#E3Gateway} + + + http://${#Project#E3Gateway}/auth-extended-endpoint1?key=auth-extended-key1http://${#Project#E3Gateway}/auth-extended-endpoint1http://${#Project#E3Gateway}/auth-extended-endpoint2http://${#Project#E3Gateway}/api-header-transform-endpoint1?key=api-header-transform-key1http://${#Project#E3Gateway}/api-header-transform-endpoint2?key=api-header-transform-key2http://${#Project#E3Gateway}/api-header-transform-endpoint3?key=api-header-transform-key3http://${#Project#E3Gateway}/provision-api-ext-endpoint1http://${#Project#E3Gateway}/provision-api-ext-endpoint3?key=provision-api-ext-key3 + + + + + + keyQUERY + + text/html + 200 + + html + + + + 0 + + data + + + text/plain + 500 403 401 429 + + data + + + + 200 + + data + + + + 200 + + data + + + text/html + 404 + + html + + 0data0data0data0data0data + 0data0datatext/xml200data<xml-fragment xmlns:con="http://eviware.com/soapui/config"> + <con:entry key="WAIT" value="0"/> + <con:entry key="SIZE" value="100"/> +</xml-fragment>http://${#Project#E3Gateway}/endpoint1<xml-fragment xmlns:con="http://eviware.com/soapui/config"> + <con:entry key="WAIT" value="0"/> + <con:entry key="SIZE" value="100"/> +</xml-fragment>http://${#Project#E3Gateway}/endpoint1 + text/plain401 403 429 500datatext/html200html0data0data0data0datatext/html404htmltext/xml200data<xml-fragment xmlns:con="http://eviware.com/soapui/config"> + <con:entry key="WAIT" value="0"/> + <con:entry key="SIZE" value="100"/> +</xml-fragment>http://${#Project#E3Gateway}/endpoint1text/plain401 500 429data0data0data0data0data0data0data0data0data0data0datatext/xml200datatext/html404html<xml-fragment xmlns:con="http://eviware.com/soapui/config"> + <con:entry key="Authorization" value="Basic dGVzdGVyOnRlc3RlcnBhc3N3b3Jk"/> + <con:entry key="WAIT" value="0"/> + <con:entry key="SIZE" value="100"/> +</xml-fragment>http://${#Project#E3Gateway}/endpoint1<xml-fragment xmlns:con="http://eviware.com/soapui/config"> + <con:entry key="Authorization" value="Basic invalidbasic"/> + <con:entry key="WAIT" value="0"/> + <con:entry key="SIZE" value="100"/> +</xml-fragment>http://${#Project#E3Gateway}/endpoint1text/xml200datatext/html200data<xml-fragment xmlns:con="http://eviware.com/soapui/config"> + <con:entry key="WAIT" value="0"/> + <con:entry key="SIZE" value="100"/> +</xml-fragment>http://${#Project#E3Gateway}/endpoint1?key=e88ba0c1e4c34f25bf95733eebd8574f + http://${#Project#E3Gateway}:8181/cxf/e3/prov/v1?_wadl&_type=xml + + + + E3 REST API to create, update or delete an API + + Used to get all API IDs. + + + + + + This REST API is used to create an API. + + + + + + + + + + + This REST API is used to delete an API. + + + + + + + Used to get an API by this ID. + + + + + + + This REST API is used to update an API. + + + + + + + + + + + E3 REST API to create, update or delete a policy + + This REST API is used to fetch all policy ids. + + + + + + This REST API is used to create a policy. + + + + + + + + + + + This REST API is used to delete a policy. + + + + + + + This REST API is used to fetch policy data. + + + + + + + This REST API is used to update a policy. + + + + + + + + + + + + This REST API is used to create a QuotaRLBucket in a policy. + + + + + + + + + + + + + This REST API is used to remove a bucket from a policy. + + + + + + + This REST API is used to append auths to a bucket. + + + + + + + + + + + + + + This REST API is used to remove an auth from a bucket. + + + + + + + + + E3 REST API provision authentications on E3 subsystem + + This REST API is used to get all authentications from E3 subsystem. + + + + + + This REST API is used to create an authentication element on E3 subsystem. + + + + + + + + + + + This REST API is used to delete an Auth. + + + + + + + This REST API is used to get an authentication by ID from E3 subsystem. + + + + + + + This REST API is used to update an authentication. + + + + + + + + + + + E3 REST API to create or delete a bucket of auths associated to a list of policies + + This REST API is used to create a bucket linked to a list of policies. + + + + + + + + + + + This REST API is used to append auths to a bucket for several policies. + + + + + + + + + + + + This REST API is used to remove a bucket from a list of policies. + + + + + + + + + + + E3 REST API provision SSLKeys and SSLCerts on E3 subsystem + + This REST API is used to get all SSLKeys from E3 subsystem. + + + + + + This REST API is used to create an SSLKey element on E3 subsystem. + + + + + + + + + + + This REST API is used to delete an SSLKey. + + + + + + + This REST API is used to get an SSLKey by ID from E3 subsystem. + + + + + + + This REST API is used to update an SSLKey. + + + + + + + + + + + + This REST API is used to get all SSLCerts for a key. + + + + + + + This REST API is used to create an SSLCert element on E3 subsystem. + + + + + + + + + + + + + This REST API is used to delete an SSLCert. + + + + + + + This REST API is used to get an SSLKey by ID from E3 subsystem. + + + + + + + This REST API is used to update an SSLKey. + + + + + + + + + + + + This REST API is used to get a CSR for the given SSLKey ID from E3 subsystem. + + + + + + + + + + This REST API is used to create a self-signed cert for an existing Key + + + + + + + + + E3 REST API to add/update/delete trusted CAs and CRLs + + + This REST API is used to fetch all trusted certificates authorithies. + + + + + + This REST API is used to add a trusted Certificate Authority. + + + + + + + + + + + + This REST API is used to remove a trusted Certificate Authority. + + + + + + + This REST API is used to fetch trusted Certificate Authority. + + + + + + + This REST API is used to update a trusted Certificate Authority. + + + + + + + + + + + This REST API is used to fetch trusted Certificate Authority. + + + + + + This REST API is used to add a Certificate Revocation List for this Certificate Authority. + + + + + + + + + + + + This REST API is used to remove a certificate revocation list from a certificate authority. + + + + + + + This REST API is used to fetch Certificate Revocation List. + + + + + + + This REST API is used to update a certificate revocation list. + + + + + + + + + + +]]>http://wadl.dev.java.net/2009/02http://${#Project#E3Gateway}:8181API_IDTEMPLATExs:stringapplication/xmlhttp://${#Project#E3Gateway}:8181application/xmlhttp://${#Project#E3Gateway}:8181application/xmlapplication/xmlhttp://${#Project#E3Gateway}:8181application/xmlhttp://${#Project#E3Gateway}:8181application/xmlapplication/xmlhttp://${#Project#E3Gateway}:8181POLICY_IDTEMPLATExs:stringapplication/xmlhttp://${#Project#E3Gateway}:8181application/xmlhttp://${#Project#E3Gateway}:8181application/xmlapplication/xmlhttp://${#Project#E3Gateway}:8181POLICY_IDTEMPLATExs:stringapplication/xmlapplication/xmlhttp://${#Project#E3Gateway}:8181POLICY_IDTEMPLATExs:stringBUCKET_IDTEMPLATExs:stringapplication/xmlhttp://${#Project#E3Gateway}:8181application/xmlapplication/xmlhttp://${#Project#E3Gateway}:8181POLICY_IDTEMPLATExs:stringBUCKET_IDTEMPLATExs:stringAUTH_IDTEMPLATExs:stringapplication/xmlhttp://${#Project#E3Gateway}:8181application/xmlhttp://${#Project#E3Gateway}:8181application/xmlapplication/xmlhttp://${#Project#E3Gateway}:8181AUTH_IDTEMPLATExs:stringapplication/xmlhttp://${#Project#E3Gateway}:8181application/xmlhttp://${#Project#E3Gateway}:8181application/xmlapplication/xmlhttp://${#Project#E3Gateway}:8181application/xmlhttp://${#Project#E3Gateway}:8181application/xmlapplication/xmlhttp://${#Project#E3Gateway}:8181BUCKET_IDTEMPLATExs:stringapplication/xmlapplication/xmlhttp://${#Project#E3Gateway}:8181BUCKET_IDTEMPLATExs:stringapplication/xmlapplication/xmlhttp://${#Project#E3Gateway}:8181application/xmlapplication/xmlhttp://${#Project#E3Gateway}:8181KEY_IDTEMPLATExs:stringapplication/xmlhttp://${#Project#E3Gateway}:8181application/xmlhttp://${#Project#E3Gateway}:8181application/xmlapplication/xmlhttp://${#Project#E3Gateway}:8181KEY_IDTEMPLATExs:stringapplication/xmlhttp://${#Project#E3Gateway}:8181application/xmlapplication/xmlhttp://${#Project#E3Gateway}:8181KEY_IDTEMPLATExs:stringCERT_IDTEMPLATExs:stringapplication/xmlhttp://${#Project#E3Gateway}:8181application/xmlhttp://${#Project#E3Gateway}:8181application/xmlapplication/xmlhttp://${#Project#E3Gateway}:8181KEY_IDTEMPLATExs:stringapplication/xmlhttp://${#Project#E3Gateway}:8181KEY_IDTEMPLATExs:stringapplication/xmlhttp://${#Project#E3Gateway}:8181application/xmlhttp://${#Project#E3Gateway}:8181application/xmlapplication/xmlhttp://${#Project#E3Gateway}:8181application/xmlhttp://${#Project#E3Gateway}:8181application/xmlapplication/xmlhttp://${#Project#E3Gateway}:8181CA_IDTEMPLATExs:stringapplication/xmlhttp://${#Project#E3Gateway}:8181application/xmlhttp://${#Project#E3Gateway}:8181application/xmlapplication/xmlhttp://${#Project#E3Gateway}:8181application/xmlhttp://${#Project#E3Gateway}:8181application/xmlapplication/xmlhttp://${#Project#E3Gateway}:8181CRL_IDTEMPLATExs:stringapplication/xmlhttp://${#Project#E3Gateway}:8181application/xmlhttp://${#Project#E3Gateway}:8181application/xmlapplication/xmlhttp://${#Project#E3Gateway}:8181file:/D:/Documents%20and%20Settings/mtobiasz/Desktop/targertest_1.wadl + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + +]]>http://wadl.dev.java.net/2009/02http://${#Project#E3Gateway}http://${#Project#E3Gateway}/api-http-method-endpoint1?key=api-http-method-key1http://${#Project#E3Gateway}/api-http-method-endpoint2?key=api-http-method-key2http://${#Project#E3Gateway}/api-http-method-endpoint3?key=api-http-method-key3http://${#Project#E3Gateway}/api-http-method-endpoint4?key=api-http-method-key40text/html200http://${#Project#E3Gateway}application/xml0application/xmltext/plain403 405 429text/xml200ns:responsehttp://${#Project#E3Gateway}application/xmlapplication/xmltext/plain405 429text/xml200ns:responsehttp://${#Project#E3Gateway}text/plain405 429text/xml200ns:responsehttp://${#Project#E3Gateway}0text/plain405text/xml200http://${#Project#E3Gateway} + TestSuite generated for REST Service + [functional-test-provision-api] + + SEQUENTIAL + + + + + TestCase generated for REST Resource [/apis] located + at [/apis] + + + + + + + + + + + +]]> + + http://${#Project#E3Manager}:8181 + + + + + + + + + + + <xml-fragment/>http://${#Project#E3Manager}:8181 + <xml-fragment/>http://${#Project#E3Manager}:8181 + + + + + + + + + + +]]> + + http://${#Project#E3Manager}:8181 + + api-header-transform-api1 + test_route_1 + PassThrough + active + api-header-transform-endpoint1 + false + + + authKey + + + key + + + + true + + + + active + + + http://${#Project#Target1}:8080/parametersEndpoint + + NoAuth + + key000Val + + + + + 10000 + -1 + 600000 + -1 + + + + + + + + CompanyQuota + Billing + + + + + + CompanyQuota + Billing + + + + + + CompanyQuota + Billing + + + + + request + response + + true + + + + + + + + +]]> + + + 200 + + + + + /response/status + SUCCESS + false + false + false + + + + /response/idapi-header-transform-api1falsefalsefalse + + + + + + + + <xml-fragment/>http://${#Project#E3Manager}:8181 + api-header-transform-auth1 + active + authKey + + + + api-header-transform-key1 + + + + + + CompanyQuota + Billing + + + + + + CompanyQuota + Billing + + + +]]>200/response/idapi-header-transform-auth1falsefalsefalse/response/statusSUCCESSfalsefalsefalse + <xml-fragment/>http://${#Project#E3Manager}:8181 + api-header-transform-p1 + + api-header-transform-api1 + + + + api-header-transform-auth1 + + + + + active + + active + reject + 1000 + 30 + + + + active + + + +]]>200/response/idapi-header-transform-p1falsefalsefalse/response/statusSUCCESSfalsefalsefalse + + + + + + <xml-fragment xmlns:con="http://eviware.com/soapui/config"> + <con:entry key="CUST" value="blarg"/> + <con:entry key="HEAD_TO_REMOVE" value="1234"/> + <con:entry key="SIZE" value="10"/> +</xml-fragment> + + http://${#Project#E3Gateway}/api-header-transform-endpoint1?key=api-header-transform-key1 + + + 200 + + /response/parameters/parameter[@key='CUST']1234falsefalsefalse//log(messageExchange.responseHeaders["APPID"][0]) +assert messageExchange.responseHeaders["APPID"][0] == "response" +assert messageExchange.responseHeaders["CUST3"][0] == "1234" +/response/parameters/parameter[@key='APPID']requestfalsefalsefalsekey="HEAD_TO_REMOVE"falsefalse + + + + + + + + + + + + + + +]]> + + + http://${#Project#E3Manager}:8181 + + api-header-transform-api1 + test_route_1 + PassThrough + active + api-header-transform-endpoint1 + false + + + authKey + + + key + + + + true + + + + active + + + http://${#Project#Target1}:8080/proxySize + + NoAuth + + key000Val + + + + + 10000 + -1 + 600000 + -1 + + + + + + + + CompanyQuota + Billing + + + + + + CompanyQuota + Billing + + + + + + CompanyQuota + Billing + + + + + request + response + + false + + + + + + + + +]]> + + + /response/status + SUCCESS + false + false + false + + + + + 200 + + + + /response/idapi-header-transform-api1falsefalsefalse + + + + + + + + + + + + <entry key="SIZE" value="10" xmlns="http://eviware.com/soapui/config"/> + + http://${#Project#E3Gateway}/api-header-transform-endpoint1?key=api-header-transform-key1 + + + 200 + + /data9876543210falsefalsefalse//log(messageExchange.responseHeaders["APPID"][0]) +assert messageExchange.responseHeaders["APPID"] == null +assert messageExchange.responseHeaders["CUST3"] == null + + + + + + + + + + + + + + + +]]> + + http://${#Project#E3Manager}:8181 + + + + 200 + + + + + + /response/status + SUCCESS + false + false + false + + + + + + + + <xml-fragment/>http://${#Project#E3Manager}:8181200/response/statusSUCCESSfalsefalsefalse<xml-fragment/>http://${#Project#E3Manager}:8181200/response/statusSUCCESSfalsefalsefalse + + + + + + + + + + + + + TestCase generated for REST Resource [/apis] located + at [/apis] + + + + + + + + + + + +]]> + + http://${#Project#E3Manager}:8181 + + + + + + + + + + + <xml-fragment/>http://${#Project#E3Manager}:8181 + <xml-fragment/>http://${#Project#E3Manager}:8181 + + + + + + + + + + +]]> + + http://${#Project#E3Manager}:8181 + + api-header-transform-api2 + api-header-transform-api2 + PassThrough + active + api-header-transform-endpoint2 + false + + + authKey + + + key + + + + true + + + + active + + + http://${#Project#Target1}:8080/parametersEndpoint + + NoAuth + + key000Val + + + + + 10000 + -1 + 600000 + -1 + + + + + + + + CompanyQuota + Billing + + + + + + CompanyQuota + Billing + + + + + + CompanyQuota + Billing + + + + true +]]> + + + 200 + + + + + /response/status + SUCCESS + false + false + false + + + + /response/idapi-header-transform-api2falsefalsefalse + + + + + + + + <xml-fragment/>http://${#Project#E3Manager}:8181 + api-header-transform-auth2 + active + authKey + + + + api-header-transform-key2 + + + + + + CompanyQuota + Billing + + + + + + CompanyQuota + Billing + + + + + request + response + + + + + + + + + +]]>200/response/idapi-header-transform-auth2falsefalsefalse/response/statusSUCCESSfalsefalsefalse + <xml-fragment/>http://${#Project#E3Manager}:8181 + api-header-transform-p2 + + api-header-transform-api2 + + + + api-header-transform-auth2 + + + + + active + + active + reject + 1000 + 30 + + + + active + + + +]]>200/response/idapi-header-transform-p2falsefalsefalse/response/statusSUCCESSfalsefalsefalse + + + + + + <xml-fragment xmlns:con="http://eviware.com/soapui/config"> + <con:entry key="CUST" value="blarg"/> + <con:entry key="HEAD_TO_REMOVE" value="1234"/> + <con:entry key="SIZE" value="10"/> +</xml-fragment> + + http://${#Project#E3Gateway}/api-header-transform-endpoint2?key=api-header-transform-key2 + + + 200 + + /response/parameters/parameter[@key='CUST']1234falsefalsefalse//log(messageExchange.responseHeaders["APPID"][0]) +assert messageExchange.responseHeaders["APPID"][0] == "response" +assert messageExchange.responseHeaders["CUST3"][0] == "1234" +/response/parameters/parameter[@key='APPID']requestfalsefalsefalsekey="HEAD_TO_REMOVE"falsefalse + + + + + + + + + + + + + + +]]> + + + http://${#Project#E3Manager}:8181 + + api-header-transform-api2 + api-header-transform-api2 + PassThrough + active + api-header-transform-endpoint2 + false + + + authKey + + + key + + + + true + + + + active + + + http://${#Project#Target1}:8080/proxySize + + NoAuth + + key000Val + + + + + 10000 + -1 + 600000 + -1 + + + + + + + + CompanyQuota + Billing + + + + + + CompanyQuota + Billing + + + + + + CompanyQuota + Billing + + + + + woohoo + + false +]]> + + + /response/status + SUCCESS + false + false + false + + + + + 200 + + + + /response/idapi-header-transform-api2falsefalsefalse + + + + + + + + + + + + <entry key="SIZE" value="10" xmlns="http://eviware.com/soapui/config"/> + + http://${#Project#E3Gateway}/api-header-transform-endpoint2?key=api-header-transform-key2 + + + 200 + + /data9876543210falsefalsefalse//log(messageExchange.responseHeaders["APPID"][0]) +assert messageExchange.responseHeaders["APPID"] == null +assert messageExchange.responseHeaders["CUST3"] == null + + + + + + + + + + + + + + + +]]> + + http://${#Project#E3Manager}:8181 + + + + 200 + + + + + + /response/status + SUCCESS + false + false + false + + + + + + + + <xml-fragment/>http://${#Project#E3Manager}:8181200/response/statusSUCCESSfalsefalsefalse<xml-fragment/>http://${#Project#E3Manager}:8181200/response/statusSUCCESSfalsefalsefalse + + TestCase generated for REST Resource [/apis] located + at [/apis] + + + + + + + + + + + +]]> + + http://${#Project#E3Manager}:8181 + + + + + + + + + + + <xml-fragment/>http://${#Project#E3Manager}:8181 + <xml-fragment/>http://${#Project#E3Manager}:8181 + + + + + + + + + + +]]> + + http://${#Project#E3Manager}:8181 + + api-header-transform-api3 + api-header-transform-api3 + PassThrough + active + api-header-transform-endpoint3 + false + + + authKey + + + key + + + + true + + + + active + + + http://${#Project#Target1}:8080/parametersEndpoint + + NoAuth + + key000Val + + + + + 10000 + -1 + 600000 + -1 + + + + + + + + CompanyQuota + Billing + + + + + + CompanyQuota + Billing + + + + + + CompanyQuota + Billing + + + + true +]]> + + + 200 + + + + + /response/status + SUCCESS + false + false + false + + + + /response/idapi-header-transform-api3falsefalsefalse + + + + + + + + <xml-fragment/>http://${#Project#E3Manager}:8181 + api-header-transform-auth3 + active + authKey + + + + api-header-transform-key3 + + + + + + CompanyQuota + Billing + + + + + + CompanyQuota + Billing + + + +]]>200/response/idapi-header-transform-auth3falsefalsefalse/response/statusSUCCESSfalsefalsefalse + <xml-fragment/>http://${#Project#E3Manager}:8181 + api-header-transform-p3 + + api-header-transform-api3 + + + + api-header-transform-auth3 + + + + + active + + active + reject + 1000 + 30 + + + + active + + + + + request + response + + + + + + + + + +]]>200/response/idapi-header-transform-p3falsefalsefalse/response/statusSUCCESSfalsefalsefalse + + + + + + <xml-fragment xmlns:con="http://eviware.com/soapui/config"> + <con:entry key="CUST" value="blarg"/> + <con:entry key="HEAD_TO_REMOVE" value="1234"/> + <con:entry key="SIZE" value="10"/> +</xml-fragment> + + http://${#Project#E3Gateway}/api-header-transform-endpoint3?key=api-header-transform-key3 + + + 200 + + /response/parameters/parameter[@key='CUST']1234falsefalsefalse//log(messageExchange.responseHeaders["APPID"][0]) +assert messageExchange.responseHeaders["APPID"][0] == "response" +assert messageExchange.responseHeaders["CUST3"][0] == "1234" +/response/parameters/parameter[@key='APPID']requestfalsefalsefalsekey="HEAD_TO_REMOVE"falsefalse + + + + + + + + + + + + + + +]]> + + + http://${#Project#E3Manager}:8181 + + api-header-transform-api3 + api-header-transform-api3 + PassThrough + active + api-header-transform-endpoint3 + false + + + authKey + + + key + + + + true + + + + active + + + http://${#Project#Target1}:8080/proxySize + + NoAuth + + key000Val + + + + + 10000 + -1 + 600000 + -1 + + + + + + + + CompanyQuota + Billing + + + + + + CompanyQuota + Billing + + + + + + CompanyQuota + Billing + + + + false +]]> + + + /response/status + SUCCESS + false + false + false + + + + + 200 + + + + /response/idapi-header-transform-api3falsefalsefalse + + + + + + + + + + + + <entry key="SIZE" value="10" xmlns="http://eviware.com/soapui/config"/> + + http://${#Project#E3Gateway}/api-header-transform-endpoint3?key=api-header-transform-key3 + + + 200 + + /data9876543210falsefalsefalse//log(messageExchange.responseHeaders["APPID"][0]) +assert messageExchange.responseHeaders["APPID"] == null +assert messageExchange.responseHeaders["CUST3"] == null + + + + + + + + + + + + + + + +]]> + + http://${#Project#E3Manager}:8181 + + + + 200 + + + + + + /response/status + SUCCESS + false + false + false + + + + + + + + <xml-fragment/>http://${#Project#E3Manager}:8181200/response/statusSUCCESSfalsefalsefalse<xml-fragment/>http://${#Project#E3Manager}:8181200/response/statusSUCCESSfalsefalsefalse + + E3Manager135.248.213.24E3Gateway135.248.213.24Target110.168.168.49uniqdelete \ No newline at end of file diff --git a/tests/functional-tests/functional-test-http-method/pom.xml b/tests/functional-tests/functional-test-http-method/pom.xml new file mode 100644 index 0000000..52b9ecc --- /dev/null +++ b/tests/functional-tests/functional-test-http-method/pom.xml @@ -0,0 +1,48 @@ + + 4.0.0 + com.alu.e3.functional-tests.samples + functional-test-http-method + pom + + + + eviware + maven-soapui-plugin + 4.0.1 + + + mysql + mysql-connector-java + 5.1.6 + + + junit + junit + 4.8.1 + + + + + test + + test + + + ${basedir}/soapui-project.xml + ${basedir}/target/surefire-reports + true + ${basedir}/soapui-project-properties.xml + + + + + + + + com.alu.e3.functional-tests + functional-tests + 0.0.1-SNAPSHOT + .. + + Functional test Header Transformation + \ No newline at end of file diff --git a/tests/functional-tests/functional-test-http-method/soapui-project.xml b/tests/functional-tests/functional-test-http-method/soapui-project.xml new file mode 100644 index 0000000..ae7eebd --- /dev/null +++ b/tests/functional-tests/functional-test-http-method/soapui-project.xml @@ -0,0 +1,1894 @@ + + +http://${#Project#E3Gateway}/api-parameters-endpoint1?param1=value1&key=api-parameters-key1&param2=value2http://${#Project#E3Gateway}/api-parameters-endpoint2/five?key=api-parameters-key2http://${#Project#E3Gateway}/api-parameters-endpoint2/three/five?key=api-parameters-key2apiauthTEMPLATEkeymykeyQUERYmykeyparam1QUERYtext/plain403 500 429data200data200data0data0data0data200data200data200data200data200data200data0datatext/html200<xml-fragment/>http://${#Project#E3Gateway}keymykeyQUERYmykeyparam1value1QUERYvalue1param2value2QUERYvalue2text/plain403data200data200data0data0data0data200data200data200data200data200data200data200datatext/html2000data<xml-fragment/>http://${#Project#E3Gateway}param1value1QUERYvalue1keymykeyQUERYxs:stringmykeyparam2value2QUERYvalue2text/plain403data200data200data0data0data0data200data200data200data200data200data200datatext/html200<xml-fragment/>http://${#Project#E3Gateway}param1value1QUERYvalue1param2value2QUERYvalue2keymykeyQUERYxs:stringmykeytext/plain403data200data200data0data0data0data200data200data200data200data200data200datatext/html200<xml-fragment/>http://${#Project#E3Gateway}text/plain403data200data200data0data0data0data200data200data200data200data200data200datatext/html200text/html;charset=ISO-8859-1404htmltext/html404html<xml-fragment/>http://${#Project#E3Gateway}param1QUERYtext/plain403 500 429data200data200data0data0data0data200data200data200data200data200data200data0datatext/html200text/html404html<xml-fragment/>http://${#Project#E3Gateway}keyQUERYtext/plain403 500 429data200data200data0data0data0data200data200data200data200data200data200data0datatext/html200text/html;charset=ISO-8859-1404html<xml-fragment/>http://${#Project#E3Gateway}text/plain403data200data200data0data0data0data200data200data200data200data200data200datatext/html200text/html;charset=ISO-8859-1404html0data<xml-fragment/>http://${#Project#E3Gateway}text/plain403data200data200data0data0data0data200data200data200data200data200data200datatext/html200text/html;charset=ISO-8859-1404html<xml-fragment/>http://${#Project#E3Gateway}text/plain403data200data200data0data0data0data200data200data200data200data200data200datatext/html200text/html;charset=ISO-8859-1404html0data0data0data0data<xml-fragment/>http://${#Project#E3Gateway}param1QUERYtext/plain403data200data200data0data0data0data200data200data200data200data200data200datatext/html200text/html;charset=ISO-8859-1404html0data<xml-fragment/>http://${#Project#E3Gateway}param1QUERYkeyQUERYtext/plain403data200data200data0data0data0data200data200data200data200data200data200datatext/html200text/html;charset=ISO-8859-1404html0data<xml-fragment/>http://${#Project#E3Gateway}keyQUERYtext/plain403data200data200data0data0data0data200data200data200data200data200data200datatext/html200text/html;charset=ISO-8859-1404html0data<xml-fragment/>http://${#Project#E3Gateway}text/plain403data200data200data0data0data0data200data200data200data200data200data200datatext/html200text/html;charset=ISO-8859-1404html0data0data<xml-fragment/>http://${#Project#E3Gateway}param1QUERYtext/plain403data200data200data0data0data0data200data200data200data200data200data200datatext/html200text/html;charset=ISO-8859-1404html0data<xml-fragment/>http://${#Project#E3Gateway}param1QUERYkeyQUERYtext/plain403data200data200data0data0data0data200data200data200data200data200data200datatext/html200text/html;charset=ISO-8859-1404html0data<xml-fragment/>http://${#Project#E3Gateway}text/plain403data200data200data0data0data0data200data200data200data200data200data200datatext/html200text/html;charset=ISO-8859-1404html<xml-fragment/>http://${#Project#E3Gateway}text/plain403 500data200data200data0data0data0data200data200data200data200data200data200datatext/html200text/html;charset=ISO-8859-1404html0datatext/html; charset=iso-8859-1404html<xml-fragment/>http://${#Project#E3Gateway}text/plain403data200data200data0data0data0data200data200data200data200data200data200datatext/html200text/html;charset=ISO-8859-1404html<xml-fragment/>http://${#Project#E3Gateway}text/html200text/plain403 500datatext/html404htmlhttp://${#Project#E3Gateway} + + + http://${#Project#E3Gateway}/auth-extended-endpoint1?key=auth-extended-key1http://${#Project#E3Gateway}/auth-extended-endpoint1http://${#Project#E3Gateway}/auth-extended-endpoint2http://${#Project#E3Gateway}/api-header-transform-endpoint1?key=api-header-transform-key1http://${#Project#E3Gateway}/api-header-transform-endpoint2?key=api-header-transform-key2http://${#Project#E3Gateway}/api-header-transform-endpoint3?key=api-header-transform-key3http://${#Project#E3Gateway}/provision-api-ext-endpoint1http://${#Project#E3Gateway}/provision-api-ext-endpoint3?key=provision-api-ext-key3 + + + + + + keyQUERY + + text/html + 200 + + html + + + + 0 + + data + + + text/plain + 500 403 401 429 + + data + + + + 200 + + data + + + + 200 + + data + + + text/html + 404 + + html + + 0data0data0data0data0data + 0data0datatext/xml200data<xml-fragment xmlns:con="http://eviware.com/soapui/config"> + <con:entry key="WAIT" value="0"/> + <con:entry key="SIZE" value="100"/> +</xml-fragment>http://${#Project#E3Gateway}/endpoint1<xml-fragment xmlns:con="http://eviware.com/soapui/config"> + <con:entry key="WAIT" value="0"/> + <con:entry key="SIZE" value="100"/> +</xml-fragment>http://${#Project#E3Gateway}/endpoint1 + text/plain401 403 429 500datatext/html200html0data0data0data0datatext/html404htmltext/xml200data<xml-fragment xmlns:con="http://eviware.com/soapui/config"> + <con:entry key="WAIT" value="0"/> + <con:entry key="SIZE" value="100"/> +</xml-fragment>http://${#Project#E3Gateway}/endpoint1text/plain401 500 429data0data0data0data0data0data0data0data0data0data0datatext/xml200datatext/html404html<xml-fragment xmlns:con="http://eviware.com/soapui/config"> + <con:entry key="Authorization" value="Basic dGVzdGVyOnRlc3RlcnBhc3N3b3Jk"/> + <con:entry key="WAIT" value="0"/> + <con:entry key="SIZE" value="100"/> +</xml-fragment>http://${#Project#E3Gateway}/endpoint1<xml-fragment xmlns:con="http://eviware.com/soapui/config"> + <con:entry key="Authorization" value="Basic invalidbasic"/> + <con:entry key="WAIT" value="0"/> + <con:entry key="SIZE" value="100"/> +</xml-fragment>http://${#Project#E3Gateway}/endpoint1text/xml200datatext/html200data<xml-fragment xmlns:con="http://eviware.com/soapui/config"> + <con:entry key="WAIT" value="0"/> + <con:entry key="SIZE" value="100"/> +</xml-fragment>http://${#Project#E3Gateway}/endpoint1?key=e88ba0c1e4c34f25bf95733eebd8574f + http://${#Project#E3Gateway}:8181/cxf/e3/prov/v1?_wadl&_type=xml + + + + E3 REST API to create, update or delete an API + + Used to get all API IDs. + + + + + + This REST API is used to create an API. + + + + + + + + + + + This REST API is used to delete an API. + + + + + + + Used to get an API by this ID. + + + + + + + This REST API is used to update an API. + + + + + + + + + + + E3 REST API to create, update or delete a policy + + This REST API is used to fetch all policy ids. + + + + + + This REST API is used to create a policy. + + + + + + + + + + + This REST API is used to delete a policy. + + + + + + + This REST API is used to fetch policy data. + + + + + + + This REST API is used to update a policy. + + + + + + + + + + + + This REST API is used to create a QuotaRLBucket in a policy. + + + + + + + + + + + + + This REST API is used to remove a bucket from a policy. + + + + + + + This REST API is used to append auths to a bucket. + + + + + + + + + + + + + + This REST API is used to remove an auth from a bucket. + + + + + + + + + E3 REST API provision authentications on E3 subsystem + + This REST API is used to get all authentications from E3 subsystem. + + + + + + This REST API is used to create an authentication element on E3 subsystem. + + + + + + + + + + + This REST API is used to delete an Auth. + + + + + + + This REST API is used to get an authentication by ID from E3 subsystem. + + + + + + + This REST API is used to update an authentication. + + + + + + + + + + + E3 REST API to create or delete a bucket of auths associated to a list of policies + + This REST API is used to create a bucket linked to a list of policies. + + + + + + + + + + + This REST API is used to append auths to a bucket for several policies. + + + + + + + + + + + + This REST API is used to remove a bucket from a list of policies. + + + + + + + + + + + E3 REST API provision SSLKeys and SSLCerts on E3 subsystem + + This REST API is used to get all SSLKeys from E3 subsystem. + + + + + + This REST API is used to create an SSLKey element on E3 subsystem. + + + + + + + + + + + This REST API is used to delete an SSLKey. + + + + + + + This REST API is used to get an SSLKey by ID from E3 subsystem. + + + + + + + This REST API is used to update an SSLKey. + + + + + + + + + + + + This REST API is used to get all SSLCerts for a key. + + + + + + + This REST API is used to create an SSLCert element on E3 subsystem. + + + + + + + + + + + + + This REST API is used to delete an SSLCert. + + + + + + + This REST API is used to get an SSLKey by ID from E3 subsystem. + + + + + + + This REST API is used to update an SSLKey. + + + + + + + + + + + + This REST API is used to get a CSR for the given SSLKey ID from E3 subsystem. + + + + + + + + + + This REST API is used to create a self-signed cert for an existing Key + + + + + + + + + E3 REST API to add/update/delete trusted CAs and CRLs + + + This REST API is used to fetch all trusted certificates authorithies. + + + + + + This REST API is used to add a trusted Certificate Authority. + + + + + + + + + + + + This REST API is used to remove a trusted Certificate Authority. + + + + + + + This REST API is used to fetch trusted Certificate Authority. + + + + + + + This REST API is used to update a trusted Certificate Authority. + + + + + + + + + + + This REST API is used to fetch trusted Certificate Authority. + + + + + + This REST API is used to add a Certificate Revocation List for this Certificate Authority. + + + + + + + + + + + + This REST API is used to remove a certificate revocation list from a certificate authority. + + + + + + + This REST API is used to fetch Certificate Revocation List. + + + + + + + This REST API is used to update a certificate revocation list. + + + + + + + + + + +]]>http://wadl.dev.java.net/2009/02http://${#Project#E3Gateway}:8181API_IDTEMPLATExs:stringapplication/xmlhttp://${#Project#E3Gateway}:8181application/xmlhttp://${#Project#E3Gateway}:8181application/xmlapplication/xmlhttp://${#Project#E3Gateway}:8181application/xmlhttp://${#Project#E3Gateway}:8181application/xmlapplication/xmlhttp://${#Project#E3Gateway}:8181POLICY_IDTEMPLATExs:stringapplication/xmlhttp://${#Project#E3Gateway}:8181application/xmlhttp://${#Project#E3Gateway}:8181application/xmlapplication/xmlhttp://${#Project#E3Gateway}:8181POLICY_IDTEMPLATExs:stringapplication/xmlapplication/xmlhttp://${#Project#E3Gateway}:8181POLICY_IDTEMPLATExs:stringBUCKET_IDTEMPLATExs:stringapplication/xmlhttp://${#Project#E3Gateway}:8181application/xmlapplication/xmlhttp://${#Project#E3Gateway}:8181POLICY_IDTEMPLATExs:stringBUCKET_IDTEMPLATExs:stringAUTH_IDTEMPLATExs:stringapplication/xmlhttp://${#Project#E3Gateway}:8181application/xmlhttp://${#Project#E3Gateway}:8181application/xmlapplication/xmlhttp://${#Project#E3Gateway}:8181AUTH_IDTEMPLATExs:stringapplication/xmlhttp://${#Project#E3Gateway}:8181application/xmlhttp://${#Project#E3Gateway}:8181application/xmlapplication/xmlhttp://${#Project#E3Gateway}:8181application/xmlhttp://${#Project#E3Gateway}:8181application/xmlapplication/xmlhttp://${#Project#E3Gateway}:8181BUCKET_IDTEMPLATExs:stringapplication/xmlapplication/xmlhttp://${#Project#E3Gateway}:8181BUCKET_IDTEMPLATExs:stringapplication/xmlapplication/xmlhttp://${#Project#E3Gateway}:8181application/xmlapplication/xmlhttp://${#Project#E3Gateway}:8181KEY_IDTEMPLATExs:stringapplication/xmlhttp://${#Project#E3Gateway}:8181application/xmlhttp://${#Project#E3Gateway}:8181application/xmlapplication/xmlhttp://${#Project#E3Gateway}:8181KEY_IDTEMPLATExs:stringapplication/xmlhttp://${#Project#E3Gateway}:8181application/xmlapplication/xmlhttp://${#Project#E3Gateway}:8181KEY_IDTEMPLATExs:stringCERT_IDTEMPLATExs:stringapplication/xmlhttp://${#Project#E3Gateway}:8181application/xmlhttp://${#Project#E3Gateway}:8181application/xmlapplication/xmlhttp://${#Project#E3Gateway}:8181KEY_IDTEMPLATExs:stringapplication/xmlhttp://${#Project#E3Gateway}:8181KEY_IDTEMPLATExs:stringapplication/xmlhttp://${#Project#E3Gateway}:8181application/xmlhttp://${#Project#E3Gateway}:8181application/xmlapplication/xmlhttp://${#Project#E3Gateway}:8181application/xmlhttp://${#Project#E3Gateway}:8181application/xmlapplication/xmlhttp://${#Project#E3Gateway}:8181CA_IDTEMPLATExs:stringapplication/xmlhttp://${#Project#E3Gateway}:8181application/xmlhttp://${#Project#E3Gateway}:8181application/xmlapplication/xmlhttp://${#Project#E3Gateway}:8181application/xmlhttp://${#Project#E3Gateway}:8181application/xmlapplication/xmlhttp://${#Project#E3Gateway}:8181CRL_IDTEMPLATExs:stringapplication/xmlhttp://${#Project#E3Gateway}:8181application/xmlhttp://${#Project#E3Gateway}:8181application/xmlapplication/xmlhttp://${#Project#E3Gateway}:8181file:/D:/Documents%20and%20Settings/mtobiasz/Desktop/targertest_1.wadl + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + +]]>http://wadl.dev.java.net/2009/02http://${#Project#E3Gateway}http://${#Project#E3Gateway}/api-http-method-endpoint1?key=api-http-method-key1http://${#Project#E3Gateway}/api-http-method-endpoint2?key=api-http-method-key2http://${#Project#E3Gateway}/api-http-method-endpoint3?key=api-http-method-key3http://${#Project#E3Gateway}/api-http-method-endpoint4?key=api-http-method-key40text/html200http://${#Project#E3Gateway}application/xml0application/xmltext/plain403 405 429text/xml200ns:responsehttp://${#Project#E3Gateway}application/xmlapplication/xmltext/plain405 429text/xml200ns:responsehttp://${#Project#E3Gateway}text/plain405 429text/xml200ns:responsehttp://${#Project#E3Gateway}0text/plain405text/xml200http://${#Project#E3Gateway} + TestSuite generated for REST Service + [functional-test-provision-api] + + SEQUENTIAL + + + + + TestCase generated for REST Resource [/apis] located + at [/apis] + + + + + + + + + + + +]]> + + http://${#Project#E3Manager}:8181 + + + + + + + + + + + <xml-fragment/>http://${#Project#E3Manager}:8181 + <xml-fragment/>http://${#Project#E3Manager}:8181 + + + + + + + + + + +]]> + + http://${#Project#E3Manager}:8181 + + api-http-method-api1 + api-http-method-api1 + PassThrough + active + api-http-method-endpoint1 + false + + + authKey + + + key + + + + false + + + + active + + + http://${#Project#Target1}:8080/parametersEndpoint + + NoAuth + + key000Val + + + + + 100 + 90 + 6000 + 5000 + + + + + GET + POST + +]]> + + + 200 + + + + + /response/status + SUCCESS + false + false + false + + + + /response/idapi-http-method-api1falsefalsefalse + + + + + + + + <xml-fragment/>http://${#Project#E3Manager}:8181 + api-http-method-auth1 + active + authKey + + + + api-http-method-key1 + + + + + + CompanyQuota + Billing + + + + + + CompanyQuota + Billing + + + +]]>200/response/idapi-http-method-auth1falsefalsefalse/response/statusSUCCESSfalsefalsefalse + <xml-fragment/>http://${#Project#E3Manager}:8181 + api-http-method-p1 + + api-http-method-api1 + + + + api-http-method-auth1 + + + + + active + + active + reject + 1000 + 100 + + + + active + + + +]]>200/response/idapi-http-method-p1falsefalsefalse/response/statusSUCCESSfalsefalsefalse + <entry key="SIZE" value="10" xmlns="http://eviware.com/soapui/config"/>http://${#Project#E3Gateway}/api-http-method-endpoint1?key=api-http-method-key1200/response/data9876543210falsefalsefalse<entry key="SIZE" value="10" xmlns="http://eviware.com/soapui/config"/>http://${#Project#E3Gateway}/api-http-method-endpoint1?key=api-http-method-key1200/response/data9876543210falsefalsefalse<entry key="SIZE" value="10" xmlns="http://eviware.com/soapui/config"/>http://${#Project#E3Gateway}/api-http-method-endpoint1?key=api-http-method-key1405Method PUT not allowedfalsefalse<entry key="SIZE" value="10" xmlns="http://eviware.com/soapui/config"/>http://${#Project#E3Gateway}/api-http-method-endpoint1?key=api-http-method-key1405Method DELETE not allowedfalsefalse<entry key="SIZE" value="10" xmlns="http://eviware.com/soapui/config"/>http://${#Project#E3Gateway}/api-http-method-endpoint1?key=api-http-method-key1405 + + + + + + + + + +]]> + + + http://${#Project#E3Manager}:8181 + + api-http-method-api1 + api-http-method-api1 + PassThrough + active + api-http-method-endpoint1 + false + + + authKey + + + key + + + + true + + + + active + + + http://${#Project#Target1}:8080/parametersEndpoint + + NoAuth + + key000Val + + + + + 10000 + 9000 + 600000 + 500000 + + + + + + + CompanyQuota + Billing + + + + + + CompanyQuota + Billing + + + + + woohoo + + + GET + PUT + DELETE + +]]> + + + /response/status + SUCCESS + false + false + false + + + + + 200 + + + + /response/idapi-http-method-api1falsefalsefalse + + + + + + + <entry key="SIZE" value="10" xmlns="http://eviware.com/soapui/config"/>http://${#Project#E3Gateway}/api-http-method-endpoint1?key=api-http-method-key1200/response/data9876543210falsefalsefalse<entry key="SIZE" value="10" xmlns="http://eviware.com/soapui/config"/>http://${#Project#E3Gateway}/api-http-method-endpoint1?key=api-http-method-key1405Method POST not allowedfalsefalse<entry key="SIZE" value="10" xmlns="http://eviware.com/soapui/config"/>http://${#Project#E3Gateway}/api-http-method-endpoint1?key=api-http-method-key1200/response/data9876543210falsefalsefalse<entry key="SIZE" value="10" xmlns="http://eviware.com/soapui/config"/>http://${#Project#E3Gateway}/api-http-method-endpoint1?key=api-http-method-key1200/response/data9876543210falsefalsefalse<entry key="SIZE" value="10" xmlns="http://eviware.com/soapui/config"/>http://${#Project#E3Gateway}/api-http-method-endpoint1?key=api-http-method-key1405 + + + + + + + + + +]]> + + http://${#Project#E3Manager}:8181 + + + + 200 + + + + + + /response/status + SUCCESS + false + false + false + + + + + + + + <xml-fragment/>http://${#Project#E3Manager}:8181200/response/statusSUCCESSfalsefalsefalse<xml-fragment/>http://${#Project#E3Manager}:8181200/response/statusSUCCESSfalsefalsefalse + + + + + + + + + + + + + TestCase generated for REST Resource [/apis] located + at [/apis] + + + + + + + + + + + +]]> + + http://${#Project#E3Manager}:8181 + + + + + + + + + + + <xml-fragment/>http://${#Project#E3Manager}:8181 + <xml-fragment/>http://${#Project#E3Manager}:8181 + + + + + + + + + + +]]> + + http://${#Project#E3Manager}:8181 + + api-http-method-api2 + api-http-method-api2 + PassThrough + active + api-http-method-endpoint2 + false + + + authKey + + + key + + + + false + + + + active + + + http://${#Project#Target1}:8080/parametersEndpoint + + NoAuth + + key000Val + + + + + 10000 + 9000 + 600000 + 500000 + + + + + GET + POST + +]]> + + + 200 + + + + + /response/status + SUCCESS + false + false + false + + + + /response/idapi-http-method-api2falsefalsefalse + + + + + + + + <xml-fragment/>http://${#Project#E3Manager}:8181 + api-http-method-auth2 + active + authKey + + + + api-http-method-key2 + + + + + + CompanyQuota + Billing + + + + + + CompanyQuota + Billing + + + +]]>200/response/idapi-http-method-auth2falsefalsefalse/response/statusSUCCESSfalsefalsefalse + <xml-fragment/>http://${#Project#E3Manager}:8181 + api-http-method-p2 + + api-http-method-api2 + + + + api-http-method-auth2 + + + + + active + + active + reject + 1000 + 100 + + + + active + + + +]]>200/response/idapi-http-method-p2falsefalsefalse/response/statusSUCCESSfalsefalsefalse + <entry key="SIZE" value="10" xmlns="http://eviware.com/soapui/config"/>http://${#Project#E3Gateway}/api-http-method-endpoint2?key=api-http-method-key2200/response/data9876543210falsefalsefalse<entry key="SIZE" value="10" xmlns="http://eviware.com/soapui/config"/>http://${#Project#E3Gateway}/api-http-method-endpoint2?key=api-http-method-key2200/response/data9876543210falsefalsefalse + + + + + + + + + +]]> + + + http://${#Project#E3Manager}:8181 + + api-http-method-api2 + api-http-method-api2 + PassThrough + active + api-http-method-endpoint2 + false + + + authKey + + + key + + + + false + + + + active + + + http://${#Project#Target1}:8080/parametersEndpoint + + NoAuth + + key000Val + + + + + 10000 + 9000 + 600000 + 500000 + + + + + woohoo + + + GET + +]]> + + + /response/status + SUCCESS + false + false + false + + + + + 200 + + + + /response/idapi-http-method-api2falsefalsefalse + + + + + + + <entry key="SIZE" value="10" xmlns="http://eviware.com/soapui/config"/>http://${#Project#E3Gateway}/api-http-method-endpoint2?key=api-http-method-key2200/response/data9876543210falsefalsefalse<entry key="SIZE" value="10" xmlns="http://eviware.com/soapui/config"/>http://${#Project#E3Gateway}/api-http-method-endpoint2?key=api-http-method-key2405Method POST not allowedfalsefalse + + + + + + + + + +]]> + + + http://${#Project#E3Manager}:8181 + + api-http-method-api2 + api-http-method-api2 + PassThrough + active + api-http-method-endpoint2 + false + + + authKey + + + key + + + + false + + + + active + + + http://${#Project#Target1}:8080/parametersEndpoint + + NoAuth + + key000Val + + + + + 10000 + 9000 + 600000 + 500000 + + + + + woohoo + + + POST + +]]> + + + /response/status + SUCCESS + false + false + false + + + + + 200 + + + + /response/idapi-http-method-api2falsefalsefalse + + + + + + + <entry key="SIZE" value="10" xmlns="http://eviware.com/soapui/config"/>http://${#Project#E3Gateway}/api-http-method-endpoint2?key=api-http-method-key2405Method GET not allowedfalsefalse<entry key="SIZE" value="10" xmlns="http://eviware.com/soapui/config"/>http://${#Project#E3Gateway}/api-http-method-endpoint2?key=api-http-method-key2200/response/data9876543210falsefalsefalse + + + + + + + + + +]]> + + + http://${#Project#E3Manager}:8181 + + api-http-method-api2 + api-http-method-api2 + PassThrough + active + api-http-method-endpoint2 + false + + + authKey + + + key + + + + false + + + + active + + + http://${#Project#Target1}:8080/parametersEndpoint + + NoAuth + + key000Val + + + + + 10000 + 9000 + 600000 + 500000 + + + + + woohoo + + + PUT + +]]> + + + /response/status + SUCCESS + false + false + false + + + + + 200 + + + + /response/idapi-http-method-api2falsefalsefalse + + + + + + + <entry key="SIZE" value="10" xmlns="http://eviware.com/soapui/config"/>http://${#Project#E3Gateway}/api-http-method-endpoint2?key=api-http-method-key2405Method GET not allowedfalsefalse<entry key="SIZE" value="10" xmlns="http://eviware.com/soapui/config"/>http://${#Project#E3Gateway}/api-http-method-endpoint2?key=api-http-method-key2405Method POST not allowedfalsefalse + + + + + + + + + +]]> + + http://${#Project#E3Manager}:8181 + + + + 200 + + + + + + /response/status + SUCCESS + false + false + false + + + + + + + + <xml-fragment/>http://${#Project#E3Manager}:8181200/response/statusSUCCESSfalsefalsefalse<xml-fragment/>http://${#Project#E3Manager}:8181200/response/statusSUCCESSfalsefalsefalse + + TestCase generated for REST Resource [/apis] located + at [/apis] + + + + + + + + + + + +]]> + + http://${#Project#E3Manager}:8181 + + + + + + + + + + + <xml-fragment/>http://${#Project#E3Manager}:8181 + <xml-fragment/>http://${#Project#E3Manager}:8181 + + + + + + + + + + +]]> + + http://${#Project#E3Manager}:8181 + + api-http-method-api3 + api-http-method-api3 + PassThrough + active + api-http-method-endpoint3 + false + + + authKey + + + key + + + + false + + + + active + + + http://${#Project#Target1}:8080/parametersEndpoint + + NoAuth + + key000Val + + + + + 10000 + 9000 + 600000 + 500000 + + + + + GET + POST + PUT + DELETE + HEAD + TRACE + OPTIONS + CONNECT + PATCH + +]]> + + + 200 + + + + + /response/status + SUCCESS + false + false + false + + + + /response/idapi-http-method-api3falsefalsefalse + + + + + + + + <xml-fragment/>http://${#Project#E3Manager}:8181 + api-http-method-auth3 + active + authKey + + + + api-http-method-key3 + + + + + + CompanyQuota + Billing + + + + + + CompanyQuota + Billing + + + +]]>200/response/idapi-http-method-auth3falsefalsefalse/response/statusSUCCESSfalsefalsefalse + <xml-fragment/>http://${#Project#E3Manager}:8181 + api-http-method-p3 + + api-http-method-api3 + + + + api-http-method-auth3 + + + + + active + + active + reject + 1000 + 100 + + + + active + + + +]]>200/response/idapi-http-method-p3falsefalsefalse/response/statusSUCCESSfalsefalsefalse + <entry key="SIZE" value="10" xmlns="http://eviware.com/soapui/config"/>http://${#Project#E3Gateway}/api-http-method-endpoint3?key=api-http-method-key3200/response/data9876543210falsefalsefalse<entry key="SIZE" value="10" xmlns="http://eviware.com/soapui/config"/>http://${#Project#E3Gateway}/api-http-method-endpoint3?key=api-http-method-key3200/response/data9876543210falsefalsefalse<entry key="SIZE" value="10" xmlns="http://eviware.com/soapui/config"/>http://${#Project#E3Gateway}/api-http-method-endpoint3?key=api-http-method-key3200/response/data9876543210falsefalsefalse<entry key="SIZE" value="10" xmlns="http://eviware.com/soapui/config"/>http://${#Project#E3Gateway}/api-http-method-endpoint3?key=api-http-method-key3200/response/data9876543210falsefalsefalse<entry key="SIZE" value="10" xmlns="http://eviware.com/soapui/config"/>http://${#Project#E3Gateway}/api-http-method-endpoint3?key=api-http-method-key3200 + + + + + + + + + +]]> + + + http://${#Project#E3Manager}:8181 + + api-http-method-api3 + api-http-method-api3 + PassThrough + active + api-http-method-endpoint3 + false + + + authKey + + + key + + + + false + + + + active + + + http://${#Project#Target1}:8080/parametersEndpoint + + NoAuth + + key000Val + + + + + 10000 + 9000 + 600000 + 500000 + + + + + woohoo + + + +]]> + + + /response/status + SUCCESS + false + false + false + + + + + 200 + + + + /response/idapi-http-method-api3falsefalsefalse + + + + + + + <entry key="SIZE" value="10" xmlns="http://eviware.com/soapui/config"/>http://${#Project#E3Gateway}/api-http-method-endpoint3?key=api-http-method-key3200/response/data9876543210falsefalsefalse<entry key="SIZE" value="10" xmlns="http://eviware.com/soapui/config"/>http://${#Project#E3Gateway}/api-http-method-endpoint3?key=api-http-method-key3200/response/data9876543210falsefalsefalse<entry key="SIZE" value="10" xmlns="http://eviware.com/soapui/config"/>http://${#Project#E3Gateway}/api-http-method-endpoint3?key=api-http-method-key3200/response/data9876543210falsefalsefalse<entry key="SIZE" value="10" xmlns="http://eviware.com/soapui/config"/>http://${#Project#E3Gateway}/api-http-method-endpoint3?key=api-http-method-key3200/response/data9876543210falsefalsefalse<entry key="SIZE" value="10" xmlns="http://eviware.com/soapui/config"/>http://${#Project#E3Gateway}/api-http-method-endpoint3?key=api-http-method-key3200 + + + + + + + + + +]]> + + http://${#Project#E3Manager}:8181 + + + + 200 + + + + + + /response/status + SUCCESS + false + false + false + + + + + + + + <xml-fragment/>http://${#Project#E3Manager}:8181200/response/statusSUCCESSfalsefalsefalse<xml-fragment/>http://${#Project#E3Manager}:8181200/response/statusSUCCESSfalsefalsefalse + + TestCase generated for REST Resource [/apis] located + at [/apis] + + + + + + + + + + + +]]> + + http://${#Project#E3Manager}:8181 + + + + + + + + + + + <xml-fragment/>http://${#Project#E3Manager}:8181 + <xml-fragment/>http://${#Project#E3Manager}:8181 + + + + + + + + + + +]]> + + http://${#Project#E3Manager}:8181 + + api-http-method-api4 + api-http-method-api4 + PassThrough + active + api-http-method-endpoint4 + false + + + authKey + + + key + + + + false + + + + active + + + http://${#Project#Target1}:8080/parametersEndpoint + + NoAuth + + key000Val + + + + + 10000 + 9000 + 600000 + 500000 + + + + + GET + POST + PUT + DELETE + HEAD + TRACE + OPTIONS + CONNECT + PATCH + +]]> + + + 200 + + + + + /response/status + SUCCESS + false + false + false + + + + /response/idapi-http-method-api4falsefalsefalse + + + + + + + + <xml-fragment/>http://${#Project#E3Manager}:8181 + api-http-method-auth4 + active + authKey + + + + api-http-method-key4 + + + + + + CompanyQuota + Billing + + + + + + CompanyQuota + Billing + + + +]]>200/response/idapi-http-method-auth4falsefalsefalse/response/statusSUCCESSfalsefalsefalse + <xml-fragment/>http://${#Project#E3Manager}:8181 + api-http-method-p4 + + api-http-method-api4 + + + + api-http-method-auth4 + + + + + active + + active + reject + 1000 + 10 + + + + active + + + +]]>200/response/idapi-http-method-p4falsefalsefalse/response/statusSUCCESSfalsefalsefalse + <entry key="SIZE" value="10" xmlns="http://eviware.com/soapui/config"/>http://${#Project#E3Gateway}/api-http-method-endpoint4?key=api-http-method-key4200/response/data9876543210falsefalsefalse + + + + + + + + + +]]> + + + http://${#Project#E3Manager}:8181 + + api-http-method-api4 + api-http-method-api4 + PassThrough + active + api-http-method-endpoint4 + false + + + authKey + + + key + + + + false + + + + active + + + http://${#Project#Target1}:8080/parametersEndpoint + + NoAuth + + key000Val + + + + + 10000 + 9000 + 600000 + 500000 + + + + + woohoo + + + GET + BOGUS + +]]> + + /response/statusFAILUREfalsefalsefalse + + + + 200,201BOGUSfalsefalse + + + + + + + + + + + + + + +]]> + + http://${#Project#E3Manager}:8181 + + + + 200 + + + + + + /response/status + SUCCESS + false + false + false + + + + + + + + <xml-fragment/>http://${#Project#E3Manager}:8181200/response/statusSUCCESSfalsefalsefalse<xml-fragment/>http://${#Project#E3Manager}:8181200/response/statusSUCCESSfalsefalsefalse + + E3Manager192.168.84.109E3Gateway192.168.84.109Target1192.168.84.90uniqdelete \ No newline at end of file diff --git a/tests/functional-tests/functional-test-provision-api-ext/pom.xml b/tests/functional-tests/functional-test-provision-api-ext/pom.xml new file mode 100644 index 0000000..76f598f --- /dev/null +++ b/tests/functional-tests/functional-test-provision-api-ext/pom.xml @@ -0,0 +1,48 @@ + + 4.0.0 + com.alu.e3.functional-tests.samples + functional-test-provision-api-ext + pom + + + + eviware + maven-soapui-plugin + 4.0.1 + + + mysql + mysql-connector-java + 5.1.6 + + + junit + junit + 4.8.1 + + + + + test + + test + + + ${basedir}/soapui-project.xml + ${basedir}/target/surefire-reports + true + ${basedir}/soapui-project-properties.xml + + + + + + + + com.alu.e3.functional-tests + functional-tests + 0.0.1-SNAPSHOT + .. + + Functional test provision api extended + \ No newline at end of file diff --git a/tests/functional-tests/functional-test-provision-api-ext/soapui-project.xml b/tests/functional-tests/functional-test-provision-api-ext/soapui-project.xml new file mode 100644 index 0000000..d6b9150 --- /dev/null +++ b/tests/functional-tests/functional-test-provision-api-ext/soapui-project.xml @@ -0,0 +1,2529 @@ + + +http://${#Project#E3Gateway}/api-parameters-endpoint1?param1=value1&key=api-parameters-key1&param2=value2http://${#Project#E3Gateway}/api-parameters-endpoint2/five?key=api-parameters-key2http://${#Project#E3Gateway}/api-parameters-endpoint2/three/five?key=api-parameters-key2apiauthTEMPLATEkeymykeyQUERYmykeyparam1QUERYtext/plain403 500 429data200data200data0data0data0data200data200data200data200data200data200data0datatext/html200<xml-fragment/>http://${#Project#E3Gateway}keymykeyQUERYmykeyparam1value1QUERYvalue1param2value2QUERYvalue2text/plain403data200data200data0data0data0data200data200data200data200data200data200data200datatext/html2000data<xml-fragment/>http://${#Project#E3Gateway}param1value1QUERYvalue1keymykeyQUERYxs:stringmykeyparam2value2QUERYvalue2text/plain403data200data200data0data0data0data200data200data200data200data200data200datatext/html200<xml-fragment/>http://${#Project#E3Gateway}param1value1QUERYvalue1param2value2QUERYvalue2keymykeyQUERYxs:stringmykeytext/plain403data200data200data0data0data0data200data200data200data200data200data200datatext/html200<xml-fragment/>http://${#Project#E3Gateway}text/plain403data200data200data0data0data0data200data200data200data200data200data200datatext/html200text/html;charset=ISO-8859-1404htmltext/html404html<xml-fragment/>http://${#Project#E3Gateway}param1QUERYtext/plain403 500 429data200data200data0data0data0data200data200data200data200data200data200data0datatext/html200text/html404html<xml-fragment/>http://${#Project#E3Gateway}keyQUERYtext/plain403 500 429data200data200data0data0data0data200data200data200data200data200data200data0datatext/html200text/html;charset=ISO-8859-1404html<xml-fragment/>http://${#Project#E3Gateway}text/plain403data200data200data0data0data0data200data200data200data200data200data200datatext/html200text/html;charset=ISO-8859-1404html0data<xml-fragment/>http://${#Project#E3Gateway}text/plain403data200data200data0data0data0data200data200data200data200data200data200datatext/html200text/html;charset=ISO-8859-1404html<xml-fragment/>http://${#Project#E3Gateway}text/plain403data200data200data0data0data0data200data200data200data200data200data200datatext/html200text/html;charset=ISO-8859-1404html0data0data0data0data<xml-fragment/>http://${#Project#E3Gateway}param1QUERYtext/plain403data200data200data0data0data0data200data200data200data200data200data200datatext/html200text/html;charset=ISO-8859-1404html0data<xml-fragment/>http://${#Project#E3Gateway}param1QUERYkeyQUERYtext/plain403data200data200data0data0data0data200data200data200data200data200data200datatext/html200text/html;charset=ISO-8859-1404html0data<xml-fragment/>http://${#Project#E3Gateway}keyQUERYtext/plain403data200data200data0data0data0data200data200data200data200data200data200datatext/html200text/html;charset=ISO-8859-1404html0data<xml-fragment/>http://${#Project#E3Gateway}text/plain403data200data200data0data0data0data200data200data200data200data200data200datatext/html200text/html;charset=ISO-8859-1404html0data0data<xml-fragment/>http://${#Project#E3Gateway}param1QUERYtext/plain403data200data200data0data0data0data200data200data200data200data200data200datatext/html200text/html;charset=ISO-8859-1404html0data<xml-fragment/>http://${#Project#E3Gateway}param1QUERYkeyQUERYtext/plain403data200data200data0data0data0data200data200data200data200data200data200datatext/html200text/html;charset=ISO-8859-1404html0data<xml-fragment/>http://${#Project#E3Gateway}text/plain403data200data200data0data0data0data200data200data200data200data200data200datatext/html200text/html;charset=ISO-8859-1404html<xml-fragment/>http://${#Project#E3Gateway}text/plain403 500data200data200data0data0data0data200data200data200data200data200data200datatext/html200text/html;charset=ISO-8859-1404html0datatext/html; charset=iso-8859-1404html<xml-fragment/>http://${#Project#E3Gateway}text/plain403data200data200data0data0data0data200data200data200data200data200data200datatext/html200text/html;charset=ISO-8859-1404html<xml-fragment/>http://${#Project#E3Gateway}text/html200text/plain403 500datatext/html404htmlhttp://${#Project#E3Gateway} + + + http://${#Project#E3Gateway}/auth-extended-endpoint1?key=auth-extended-key1http://${#Project#E3Gateway}/auth-extended-endpoint1http://${#Project#E3Gateway}/auth-extended-endpoint2http://${#Project#E3Gateway}/api-header-transform-endpoint1?key=api-header-transform-key1http://${#Project#E3Gateway}/api-header-transform-endpoint2?key=api-header-transform-key2http://${#Project#E3Gateway}/api-header-transform-endpoint3?key=api-header-transform-key3http://${#Project#E3Gateway}/provision-api-ext-endpoint1http://${#Project#E3Gateway}/provision-api-ext-endpoint3?key=provision-api-ext-key3https://${#Project#E3Gateway}/tls2ways-call-expired-endpoint1https://${#Project#E3Gateway}/tls2ways-call-ko-endpoint1https://${#Project#E3Gateway}/tls2ways-call-no-cert-endpoint1https://${#Project#E3Gateway}/tls2ways-call-ok-endpoint1https://${#Project#E3Gateway}:25101/provision-sslkey-endpoint3https://${#Project#E3Gateway}:25101/provision-sslkey-endpoint4?key=provision-sslkey-key4http://${#Project#E3Gateway}/tdr-smoke-endpoint1?key=tdr-smoke-key1http://${#Project#E3Gateway}/tdr-endpoint1?key=tdr-key1http://${#Project#E3Gateway}/rate-limit-aib-and-cluster-endpoint2?key=rate-limit-aib-and-cluster-key2http://${#Project#E3Gateway}/rate-limit-aib-and-cluster-endpoint3?key=rate-limit-aib-and-cluster-key3http://${#Project#E3Gateway}/rate-limit-aib-endpoint2http://${#Project#E3Gateway}/rate-limit-aib-endpoint3?key=rate-limit-aib-key3http://${#Project#E3Gateway}/api-provision-endpoint5?key=api-provision-key5http://${#Project#E3Gateway}/api-provision-endpoint5_2?key=api-provision-key5http://${#Project#E3Gateway}/api-provision-endpoint6?key=api-provision-key6http://${#Project#E3Gateway}/api-provision-endpoint6_2?key=api-provision-key6http://${#Project#E3Gateway}/api-provision-endpoint7?key=api-provision-key7http://${#Project#E3Gateway}/api-provision-endpoint8_2?key=api-provision-key8http://${#Project#E3Gateway}/api-provision-endpoint8http://${#Project#E3Gateway}/api-provision-endpoint9http://${#Project#E3Gateway}/api-provision-endpoint9_2http://${#Project#E3Gateway}/api-provision-endpoint9_2?key=api-provision-key9http://${#Project#E3Gateway}/api-provision-endpoint10http://${#Project#E3Gateway}/api-provision-endpoint10_2http://${#Project#E3Gateway}/api-provision-endpoint10_2?key=api-provision-key10http://${#Project#E3Gateway}/api-provision-endpoint11http://${#Project#E3Gateway}/api-provision-endpoint11_2http://${#Project#E3Gateway}/api-provision-endpoint11_2?key=api-provision-key11http://${#Project#E3Gateway}/api-provision-endpoint12http://${#Project#E3Gateway}/api-provision-endpoint12_2http://${#Project#E3Gateway}/api-provision-endpoint12_2?key=api-provision-key12http://${#Project#E3Gateway}/api-provision-endpoint13http://${#Project#E3Gateway}/api-provision-endpoint13_2http://${#Project#E3Gateway}/api-provision-endpoint13_2?key=api-provision-key13http://${#Project#E3Gateway}/api-provision-endpoint18?key=api-provision-key18http://${#Project#E3Gateway}/api-provision-endpoint18_2?key=api-provision-key18http://${#Project#E3Gateway}/api-provision-endpoint19?key=api-provision-key19http://${#Project#E3Gateway}/api-provision-endpoint19_2?key=api-provision-key19http://${#Project#E3Gateway}/auth-type-ip-white-list-endpoint2http://${#Project#E3Gateway}/auth-type-ip-white-list-endpoint3http://${#Project#E3Gateway}/auth-type-ip-white-list-endpoint4http://${#Project#E3Gateway}/auth-type-ip-white-list-endpoint5http://${#Project#E3Gateway}/auth-type-ip-white-list-endpoint9http://${#Project#E3Gateway}/auth-basic-endpoint4http://${#Project#E3Gateway}/provision-api-loadbalancing-endpoint1?uniqueId=${#TestCase#uniqueId}http://${#Project#E3Gateway}/provision-api-loadbalancing-endpoint2?uniqueId=${#TestCase#uniqueId}http://${#Project#E3Gateway}/provision-api-loadbalancing-endpoint3?uniqueId=${#TestCase#uniqueId} + + + + + + keyQUERY + + text/html + 200 + + html + + + + 0 + + data + + + text/plain + 500 403 401 429 + + data + + + + 200 + + data + + + + 200 + + data + + + text/html + 404 + + html + + 0data0data0data0data0data + 0data0datatext/xml200data<xml-fragment xmlns:con="http://eviware.com/soapui/config"> + <con:entry key="WAIT" value="0"/> + <con:entry key="SIZE" value="100"/> +</xml-fragment>http://${#Project#E3Gateway}/endpoint1<xml-fragment xmlns:con="http://eviware.com/soapui/config"> + <con:entry key="WAIT" value="0"/> + <con:entry key="SIZE" value="100"/> +</xml-fragment>http://${#Project#E3Gateway}/endpoint1 + text/plain401 403 429 500datatext/html200html0data0data0data0datatext/html404htmltext/xml200data0data0data0data0data0data0data0data0data0data0data0data<xml-fragment xmlns:con="http://eviware.com/soapui/config"> + <con:entry key="WAIT" value="0"/> + <con:entry key="SIZE" value="100"/> +</xml-fragment>http://${#Project#E3Gateway}/endpoint1text/plain401 500 429 403data0data0data0data0data0data0data0data0data0data0datatext/xml200datatext/html404htmltext/html200data<xml-fragment xmlns:con="http://eviware.com/soapui/config"> + <con:entry key="Authorization" value="Basic dGVzdGVyOnRlc3RlcnBhc3N3b3Jk"/> + <con:entry key="WAIT" value="0"/> + <con:entry key="SIZE" value="100"/> +</xml-fragment>http://${#Project#E3Gateway}/endpoint1<xml-fragment xmlns:con="http://eviware.com/soapui/config"> + <con:entry key="Authorization" value="Basic invalidbasic"/> + <con:entry key="WAIT" value="0"/> + <con:entry key="SIZE" value="100"/> +</xml-fragment>http://${#Project#E3Gateway}/endpoint1text/xml200datatext/html200data<xml-fragment xmlns:con="http://eviware.com/soapui/config"> + <con:entry key="WAIT" value="0"/> + <con:entry key="SIZE" value="100"/> +</xml-fragment>http://${#Project#E3Gateway}/endpoint1?key=e88ba0c1e4c34f25bf95733eebd8574f + http://${#Project#E3Gateway}:8181/cxf/e3/prov/v1?_wadl&_type=xml + + + + E3 REST API to create, update or delete an API + + Used to get all API IDs. + + + + + + This REST API is used to create an API. + + + + + + + + + + + This REST API is used to delete an API. + + + + + + + Used to get an API by this ID. + + + + + + + This REST API is used to update an API. + + + + + + + + + + + E3 REST API to create, update or delete a policy + + This REST API is used to fetch all policy ids. + + + + + + This REST API is used to create a policy. + + + + + + + + + + + This REST API is used to delete a policy. + + + + + + + This REST API is used to fetch policy data. + + + + + + + This REST API is used to update a policy. + + + + + + + + + + + + This REST API is used to create a QuotaRLBucket in a policy. + + + + + + + + + + + + + This REST API is used to remove a bucket from a policy. + + + + + + + This REST API is used to append auths to a bucket. + + + + + + + + + + + + + + This REST API is used to remove an auth from a bucket. + + + + + + + + + E3 REST API provision authentications on E3 subsystem + + This REST API is used to get all authentications from E3 subsystem. + + + + + + This REST API is used to create an authentication element on E3 subsystem. + + + + + + + + + + + This REST API is used to delete an Auth. + + + + + + + This REST API is used to get an authentication by ID from E3 subsystem. + + + + + + + This REST API is used to update an authentication. + + + + + + + + + + + E3 REST API to create or delete a bucket of auths associated to a list of policies + + This REST API is used to create a bucket linked to a list of policies. + + + + + + + + + + + This REST API is used to append auths to a bucket for several policies. + + + + + + + + + + + + This REST API is used to remove a bucket from a list of policies. + + + + + + + + + + + E3 REST API provision SSLKeys and SSLCerts on E3 subsystem + + This REST API is used to get all SSLKeys from E3 subsystem. + + + + + + This REST API is used to create an SSLKey element on E3 subsystem. + + + + + + + + + + + This REST API is used to delete an SSLKey. + + + + + + + This REST API is used to get an SSLKey by ID from E3 subsystem. + + + + + + + This REST API is used to update an SSLKey. + + + + + + + + + + + + This REST API is used to get all SSLCerts for a key. + + + + + + + This REST API is used to create an SSLCert element on E3 subsystem. + + + + + + + + + + + + + This REST API is used to delete an SSLCert. + + + + + + + This REST API is used to get an SSLKey by ID from E3 subsystem. + + + + + + + This REST API is used to update an SSLKey. + + + + + + + + + + + + This REST API is used to get a CSR for the given SSLKey ID from E3 subsystem. + + + + + + + + + + This REST API is used to create a self-signed cert for an existing Key + + + + + + + + + E3 REST API to add/update/delete trusted CAs and CRLs + + + This REST API is used to fetch all trusted certificates authorithies. + + + + + + This REST API is used to add a trusted Certificate Authority. + + + + + + + + + + + + This REST API is used to remove a trusted Certificate Authority. + + + + + + + This REST API is used to fetch trusted Certificate Authority. + + + + + + + This REST API is used to update a trusted Certificate Authority. + + + + + + + + + + + This REST API is used to fetch trusted Certificate Authority. + + + + + + This REST API is used to add a Certificate Revocation List for this Certificate Authority. + + + + + + + + + + + + This REST API is used to remove a certificate revocation list from a certificate authority. + + + + + + + This REST API is used to fetch Certificate Revocation List. + + + + + + + This REST API is used to update a certificate revocation list. + + + + + + + + + + +]]>http://wadl.dev.java.net/2009/02http://${#Project#E3Gateway}:8181API_IDTEMPLATExs:stringapplication/xmlhttp://${#Project#E3Gateway}:8181application/xmlhttp://${#Project#E3Gateway}:8181application/xmlapplication/xmlhttp://${#Project#E3Gateway}:8181application/xmlhttp://${#Project#E3Gateway}:8181application/xmlapplication/xmlhttp://${#Project#E3Gateway}:8181POLICY_IDTEMPLATExs:stringapplication/xmlhttp://${#Project#E3Gateway}:8181application/xmlhttp://${#Project#E3Gateway}:8181application/xmlapplication/xmlhttp://${#Project#E3Gateway}:8181POLICY_IDTEMPLATExs:stringapplication/xmlapplication/xmlhttp://${#Project#E3Gateway}:8181POLICY_IDTEMPLATExs:stringBUCKET_IDTEMPLATExs:stringapplication/xmlhttp://${#Project#E3Gateway}:8181application/xmlapplication/xmlhttp://${#Project#E3Gateway}:8181POLICY_IDTEMPLATExs:stringBUCKET_IDTEMPLATExs:stringAUTH_IDTEMPLATExs:stringapplication/xmlhttp://${#Project#E3Gateway}:8181application/xmlhttp://${#Project#E3Gateway}:8181application/xmlapplication/xmlhttp://${#Project#E3Gateway}:8181AUTH_IDTEMPLATExs:stringapplication/xmlhttp://${#Project#E3Gateway}:8181application/xmlhttp://${#Project#E3Gateway}:8181application/xmlapplication/xmlhttp://${#Project#E3Gateway}:8181application/xmlhttp://${#Project#E3Gateway}:8181application/xmlapplication/xmlhttp://${#Project#E3Gateway}:8181BUCKET_IDTEMPLATExs:stringapplication/xmlapplication/xmlhttp://${#Project#E3Gateway}:8181BUCKET_IDTEMPLATExs:stringapplication/xmlapplication/xmlhttp://${#Project#E3Gateway}:8181application/xmlapplication/xmlhttp://${#Project#E3Gateway}:8181KEY_IDTEMPLATExs:stringapplication/xmlhttp://${#Project#E3Gateway}:8181application/xmlhttp://${#Project#E3Gateway}:8181application/xmlapplication/xmlhttp://${#Project#E3Gateway}:8181KEY_IDTEMPLATExs:stringapplication/xmlhttp://${#Project#E3Gateway}:8181application/xmlapplication/xmlhttp://${#Project#E3Gateway}:8181KEY_IDTEMPLATExs:stringCERT_IDTEMPLATExs:stringapplication/xmlhttp://${#Project#E3Gateway}:8181application/xmlhttp://${#Project#E3Gateway}:8181application/xmlapplication/xmlhttp://${#Project#E3Gateway}:8181KEY_IDTEMPLATExs:stringapplication/xmlhttp://${#Project#E3Gateway}:8181KEY_IDTEMPLATExs:stringapplication/xmlhttp://${#Project#E3Gateway}:8181application/xml<xml-fragment/>http://${#Project#E3Gateway}:8181application/xmlapplication/xmlhttp://${#Project#E3Gateway}:8181application/xml<xml-fragment/>http://${#Project#E3Gateway}:8181application/xmlapplication/xmlhttp://${#Project#E3Gateway}:8181CA_IDTEMPLATExs:stringapplication/xmlhttp://${#Project#E3Gateway}:8181application/xmlhttp://${#Project#E3Gateway}:8181application/xmlapplication/xmlhttp://${#Project#E3Gateway}:8181application/xmlhttp://${#Project#E3Gateway}:8181application/xmlapplication/xmlhttp://${#Project#E3Gateway}:8181CRL_IDTEMPLATExs:stringapplication/xmlhttp://${#Project#E3Gateway}:8181application/xmlhttp://${#Project#E3Gateway}:8181application/xmlapplication/xmlhttp://${#Project#E3Gateway}:8181file:/D:/Documents%20and%20Settings/mtobiasz/Desktop/targertest_1.wadl + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + +]]>http://wadl.dev.java.net/2009/02http://${#Project#E3Gateway}http://${#Project#E3Gateway}/api-http-method-endpoint1?key=api-http-method-key1http://${#Project#E3Gateway}/api-http-method-endpoint2?key=api-http-method-key2http://${#Project#E3Gateway}/api-http-method-endpoint3?key=api-http-method-key3http://${#Project#E3Gateway}/api-http-method-endpoint4?key=api-http-method-key40text/html200http://${#Project#E3Gateway}application/xml0application/xmltext/plain403 405 429text/xml200ns:responsehttp://${#Project#E3Gateway}application/xmlapplication/xmltext/plain405 429text/xml200ns:responsehttp://${#Project#E3Gateway}text/plain405 429text/xml200ns:responsehttp://${#Project#E3Gateway}0text/plain405text/xml200http://${#Project#E3Gateway}http://135.248.213.24:8181pathToConfigFilesDirectoryTEMPLATExs:stringapplication/octet-streamhttp://135.248.213.24:8181application/octet-streamhttp://135.248.213.24:8181numLinesTEMPLATExs:stringapplication/xmlhttp://135.248.213.24:8181numLinesTEMPLATExs:stringapplication/xmlhttp://135.248.213.24:8181application/xmlhttp://135.248.213.24:8181instanceIdTEMPLATExs:stringapplication/xml<xml-fragment/>http://135.248.213.36:8181application/octet-streamapplication/xmlhttp://135.248.213.24:8181instanceIdTEMPLATExs:stringapplication/xmlhttp://135.248.213.24:8181application/octet-streamapplication/xmlhttp://135.248.213.24:8181instanceIdTEMPLATExs:stringapplication/xmlhttp://135.248.213.24:8181application/octet-streamapplication/xmlhttp://135.248.213.24:8181application/octet-streamhttp://135.248.213.24:8181application/octet-streamhttp://135.248.213.24:8181application/xml<xml-fragment/>http://135.248.213.24:8181application/octet-streamapplication/xml<xml-fragment/>http://135.248.213.24:8181application/xmlhttp://135.248.213.24:8181application/xmlapplication/xmlhttp://135.248.213.24:8181application/xmlhttp://135.248.213.24:8181application/octet-streamapplication/xmlhttp://135.248.213.24:8181application/xml<xml-fragment/>http://135.248.213.24:8181application/octet-streamapplication/xmlhttp://135.248.213.24:8181 + TestSuite generated for REST Service + [functional-test-provision-api] + + SEQUENTIAL + + + + + + + + + TestCase generated for REST Resource [/apis] located + at [/apis] + + + + + + + + + + + +]]> + + + http://${#Project#E3Manager}:8181 + + + + + + + + + + + + + + + + + +]]> + + http://${#Project#E3Manager}:8181 + + provision-api-ext-api1 + PassThrough + provision-api-ext-endpoint1 + + + noAuth + + + active + + + active + 0 + 0.0 + 0 + 0.0 + + +]]> + + 500 + + + /response/statusFAILUREfalsefalsefalse + + + /response/error/errorTextProvisioning Server Error: java.lang.IllegalArgumentException: An active context must have at least one target host.falsefalsefalse/response/error/errorCode500falsefalsefalse + + + + + + + + + + + + + + + +]]> + + http://${#Project#E3Manager}:8181 + + provision-api-ext-api1 + PassThrough + provision-api-ext-endpoint1 + + + noAuth + + + active + + + inactive + 0 + 0.0 + 0 + 0.0 + + +]]> + + 200 + + + + /response/status + SUCCESS + false + false + false + + + + /response/idprovision-api-ext-api1falsefalsefalse + + + + + + + + + + + + + + + + + +]]> + + http://${#Project#E3Manager}:8181 + + + + 200 + + + + + + /response/status + SUCCESS + false + false + false + + + + + + + + + + + + + + + + + + +]]> + + http://${#Project#E3Manager}:8181 + + provision-api-ext-api1 + PassThrough + provision-api-ext-endpoint1 + + + noAuth + + + active + + + inactive + 0 + 0.0 + 0 + 0.0 + + +]]> + + 200 + + + + /response/status + SUCCESS + false + false + false + + + + /response/idprovision-api-ext-api1falsefalsefalse + + + + + + + + + + + + + + +]]> + + http://${#Project#E3Manager}:8181 + + provision-api-ext-api1 + PassThrough + provision-api-ext-endpoint1 + + + noAuth + + + active + + + active + 0 + 0.0 + 0 + 0.0 + + +]]> + 500/response/statusFAILUREfalsefalsefalse/response/error/errorCode500falsefalsefalse/response/error/errorTextProvisioning Server Error: java.lang.IllegalArgumentException: An active context must have at least one target host.falsefalsefalse + + + + + + + + + + + +]]> + + http://${#Project#E3Manager}:8181 + + provision-api-ext-api1 + PassThrough + provision-api-ext-endpoint1 + + + noAuth + + + active + + + active + + + http://${#Project#Target1}:8080/proxySize + + NoAuth + + key000Val + + + + + 10 + 0.0 + 10 + 0.0 + + + + + + + CompanyQuota + Billing + + + + + + CompanyQuota + Billing + + + +]]> + 200/response/idprovision-api-ext-api1falsefalsefalse/response/statusSUCCESSfalsefalsefalse + + + + + + + + <entry key="SIZE" value="10" xmlns="http://eviware.com/soapui/config"/> + + http://${#Project#E3Gateway}/provision-api-ext-endpoint1 + + + + 200 + + + /data9876543210falsefalsefalse + + + + + + + + + + + +]]> + + http://${#Project#E3Manager}:8181 + + provision-api-ext-api1 + PassThrough + provision-api-ext-endpoint1 + + + noAuth + + + active + + + inactive + 0 + 0.0 + 0 + 0.0 + + +]]> + 200/response/statusSUCCESSfalsefalsefalse/response/idprovision-api-ext-api1falsefalsefalse + + + + + + + + <entry key="SIZE" value="10" xmlns="http://eviware.com/soapui/config"/> + + http://${#Project#E3Gateway}/provision-api-ext-endpoint1 + + + 404 + + + + + + + + + + + + + + + + +]]> + + http://${#Project#E3Manager}:8181 + + + + 200 + + + + + + /response/status + SUCCESS + false + false + false + + + + + + + + + + + + + + + + <xml-fragment/>http://${#Project#E3Manager}:8181404/response/statusFAILUREfalsefalsefalse/response/error/errorCode114falsefalsefalse/response/error/errorTextAn API with that ID [provision-api-ext-api2] doesn't existfalsefalsefalse + + + + + + +]]> + + http://${#Project#E3Manager}:8181 + + provision-api-ext-api2 + PassThrough + provision-api-ext-endpoint2 + + + noAuth + + + active + + + active + + + http://${#Project#Target1}:8080/proxySize + + NoAuth + + key000Val + + + + + 0 + 0.0 + 0 + 0.0 + + +]]> + 404/response/statusFAILUREfalsefalsefalse/response/error/errorCode114falsefalsefalse/response/error/errorTextAn API with that ID does not existfalsefalsefalse + + + + + + + + + +]]> + + http://${#Project#E3Manager}:8181 + + 404/response/statusFAILUREfalsefalsefalse/response/error/errorCode114falsefalsefalse/response/error/errorTextAn API with that ID [provision-api-ext-api2] doesn't existfalsefalsefalse + + + + + + + + + + + + +]]> + + + http://${#Project#E3Manager}:8181 + + + + + + + <xml-fragment/>http://${#Project#Target2}:8080/mockSCFTarget2404actionsetStatusQUERYxs:stringclient_credentialsstatusCode200QUERYxs:string497df8c47ea64d8db8fa412964a070ffuniqueId${#TestCase#uniqueId}QUERY + + + + + + + + + +]]> + + http://${#Project#E3Manager}:8181 + + provision-api-loadbalancing-api1 + test_route_1 + PassThrough + active + provision-api-loadbalancing-endpoint1 + false + + + noAuth + + + + false + + + + active + + + http://${#Project#Target2}:8080/mockSCFTarget2 + + + 10000 + 0.0 + 600000 + 0.0 + + +]]> + + 200 + + + + /response/status + SUCCESS + false + false + false + + + + /response/idprovision-api-loadbalancing-api1falsefalsefalse + + + + + + + + + + + + <entry key="SIZE" value="10" xmlns="http://eviware.com/soapui/config"/> + + http://${#Project#E3Gateway}/provision-api-loadbalancing-endpoint1?uniqueId=${#TestCase#uniqueId} + + + 404 + + + + + + + + + + + + + + + + +]]> + + + http://${#Project#E3Manager}:8181 + + + + + + + uniqueId${#Project#E3Gateway} + + + + + + + + + +]]> + + + http://${#Project#E3Manager}:8181 + + + + + + + <xml-fragment/>http://${#Project#Target2}:8080/mockSCFTarget202Global HTTP SettingsactionsetStatusQUERYxs:stringclient_credentialsstatusCode503QUERYxs:string497df8c47ea64d8db8fa412964a070ffuniqueId${#TestCase#uniqueId}QUERY<xml-fragment/>http://${#Project#Target2}:8080/mockSCFTarget503<ipAddress>${#Project#Target2}</ipAddress>falsefalseuniqueId${#TestCase#uniqueId}QUERY + + + + + + + + + +]]> + + http://${#Project#E3Manager}:8181 + + provision-api-loadbalancing-api1 + test_route_1 + PassThrough + active + provision-api-loadbalancing-endpoint1 + false + + + noAuth + + + + false + + + + active + + + http://${#Project#Target2}:8080/mockSCFTarget + + + 10000 + 0.0 + 600000 + 0.0 + + +]]> + + 200 + + + + /response/status + SUCCESS + false + false + false + + + + /response/idprovision-api-loadbalancing-api1falsefalsefalse + + + + + + + + + + + + <entry key="SIZE" value="10" xmlns="http://eviware.com/soapui/config"/> + + http://${#Project#E3Gateway}/provision-api-loadbalancing-endpoint1?uniqueId=${#TestCase#uniqueId} + + + 503 + + <ipAddress>${#Project#Target2}</ipAddress>falsefalseGlobal HTTP Settings + + + + + + + + + + + + + + +]]> + + + http://${#Project#E3Manager}:8181 + + + + + + + uniqueId${#Project#E3Gateway} + TestCase generated for REST Resource [/apis] located + at [/apis] + + <xml-fragment/>http://${#Project#E3Manager}:8181<xml-fragment/>http://${#Project#E3Manager}:8181 + + + + + + + + + +]]> + + + http://${#Project#E3Manager}:8181 + + + + + + + <xml-fragment/>http://${#Project#E3Manager}:8181 + provision-api-ext-auth3 + active + authKey + + + + provision-api-ext-key3 + + + + + + CompanyQuota + Billing + + + + + + CompanyQuota + Billing + + + + + +]]>200/response/idprovision-api-ext-auth3falsefalsefalse/response/statusSUCCESSfalsefalsefalse + + + + + + + + + +]]> + + http://${#Project#E3Manager}:8181 + + provision-api-ext-api3 + provision-api-ext-api3 + PassThrough + active + provision-api-ext-endpoint3 + false + + + authKey + + + key + + + + true + + + + active + + + http://${#Project#Target1}:8080/proxySize + + NoAuth + + key000Val + + + + + 10000 + 0.0 + 600000 + 0.0 + + + + + + + CompanyQuota + Billing + + + + + + CompanyQuota + Billing + + + +]]> + + 200 + + + + /response/status + SUCCESS + false + false + false + + + + /response/idprovision-api-ext-api3falsefalsefalse + + + + + + + + + + + + + + <xml-fragment/>http://${#Project#E3Manager}:8181 + provision-api-ext-p3 + + provision-api-ext-api3 + + + + provision-api-ext-auth3 + + + + + active + + active + reject + 98 + 1000 + + + + active + + + +]]>200/response/idprovision-api-ext-p3falsefalsefalse/response/statusSUCCESSfalsefalsefalse + + + + + <entry key="SIZE" value="10" xmlns="http://eviware.com/soapui/config"/> + + http://${#Project#E3Gateway}/provision-api-ext-endpoint3?key=provision-api-ext-key3 + + + + 200 + + + /data9876543210falsefalsefalse + + + + + + + + + + + + + + +]]> + + + http://${#Project#E3Manager}:8181 + + provision-api-ext-api3 + provision-api-ext-api3 + PassThrough + inactive + provision-api-ext-endpoint3 + false + + + authKey + + + key + + + + true + + + + active + + + http://${#Project#Target1}:8080/proxySize + + NoAuth + + key000Val + + + + + 10000 + 0.0 + 600000 + 0.0 + + + + + + + CompanyQuota + Billing + + + + + + CompanyQuota + Billing + + + +]]> + + + /response/status + SUCCESS + false + false + false + + + + + 200 + + + + /response/idprovision-api-ext-api3falsefalsefalse + + + + + + + + + + + + <entry key="SIZE" value="10" xmlns="http://eviware.com/soapui/config"/> + + http://${#Project#E3Gateway}/provision-api-ext-endpoint3?key=provision-api-ext-key3 + + + 403 + + + + + + + + + + + + + + + + +]]> + + + http://${#Project#E3Manager}:8181 + + + + + + + <xml-fragment/>http://${#Project#E3Manager}:8181<xml-fragment/>http://${#Project#E3Manager}:8181 + + SEQUENTIAL<xml-fragment/>http://${#Project#E3Manager}:8181/cxf/e3/system-manager/logging/instances/0/logLevelDEBUG + + + + + + + + + +]]> + + + http://${#Project#E3Manager}:8181 + + + + + + + <xml-fragment/>http://${#Project#Target1}:8080/mockSCFTarget200actionlogQUERYxs:stringclient_credentialstextStarting testcase3 LB no failOverQUERYxs:string497df8c47ea64d8db8fa412964a070ffuniqueId${#TestCase#uniqueId}QUERY<xml-fragment/>http://${#Project#Target1}:8080/mockSCFTarget202actionsetStatusQUERYxs:stringclient_credentialsstatusCode200QUERYxs:string497df8c47ea64d8db8fa412964a070ffuniqueId${#TestCase#uniqueId}QUERY<xml-fragment/>http://${#Project#Target2}:8080/mockSCFTarget202actionsetStatusQUERYxs:stringclient_credentialsstatusCode200QUERYxs:string497df8c47ea64d8db8fa412964a070ffuniqueId${#TestCase#uniqueId}QUERY<xml-fragment/>http://${#Project#Target3}:8080/mockSCFTarget202actionsetStatusQUERYxs:stringclient_credentialsstatusCode200QUERYxs:string497df8c47ea64d8db8fa412964a070ffuniqueId${#TestCase#uniqueId}QUERY + + + + + + + + + +]]> + + http://${#Project#E3Manager}:8181 + + provision-api-loadbalancing-api1 + test_route_1 + PassThrough + active + provision-api-loadbalancing-endpoint1 + false + + + noAuth + + + + false + + + + active + + + + + http://${#Project#Target1}:8080/mockSCFTarget + + + http://${#Project#Target2}:8080/mockSCFTarget + + + http://${#Project#Target3}:8080/mockSCFTarget + + + 10000 + 0.0 + 600000 + 0.0 + + +]]> + + 200 + + + + /response/status + SUCCESS + false + false + false + + + + /response/idprovision-api-loadbalancing-api1falsefalsefalse + + + + + + + + + + + + <entry key="SIZE" value="10" xmlns="http://eviware.com/soapui/config"/> + + http://${#Project#E3Gateway}/provision-api-loadbalancing-endpoint1?uniqueId=${#TestCase#uniqueId} + + + 200 + + <ipAddress>${#Project#Target1}</ipAddress>falsefalse + + + + + + + + + + <entry key="SIZE" value="10" xmlns="http://eviware.com/soapui/config"/> + + http://${#Project#E3Gateway}/provision-api-loadbalancing-endpoint1?uniqueId=${#TestCase#uniqueId} + + + 200 + + <ipAddress>${#Project#Target2}</ipAddress>falsefalse + + + + + + + + + + <entry key="SIZE" value="10" xmlns="http://eviware.com/soapui/config"/> + + http://${#Project#E3Gateway}/provision-api-loadbalancing-endpoint1?uniqueId=${#TestCase#uniqueId} + + + 200 + + <ipAddress>${#Project#Target3}</ipAddress>falsefalseGlobal HTTP Settings + + + + + <xml-fragment/>http://${#Project#Target1}:8080/mockSCFTarget202Global HTTP SettingsactionsetStatusQUERYxs:stringclient_credentialsstatusCode503QUERYxs:string497df8c47ea64d8db8fa412964a070ffuniqueId${#TestCase#uniqueId}QUERY + + + + + <entry key="SIZE" value="10" xmlns="http://eviware.com/soapui/config"/> + + http://${#Project#E3Gateway}/provision-api-loadbalancing-endpoint1?uniqueId=${#TestCase#uniqueId} + + + 503 + + Global HTTP Settings + + + + + + + + + + <entry key="SIZE" value="10" xmlns="http://eviware.com/soapui/config"/> + + http://${#Project#E3Gateway}/provision-api-loadbalancing-endpoint1?uniqueId=${#TestCase#uniqueId} + + + 200 + + <ipAddress>${#Project#Target2}</ipAddress>falsefalseGlobal HTTP Settings + + + + + + + + + + <entry key="SIZE" value="10" xmlns="http://eviware.com/soapui/config"/> + + http://${#Project#E3Gateway}/provision-api-loadbalancing-endpoint1?uniqueId=${#TestCase#uniqueId} + + + 200 + + <ipAddress>${#Project#Target3}</ipAddress>falsefalse + + + + + + + + + + <entry key="SIZE" value="10" xmlns="http://eviware.com/soapui/config"/> + + http://${#Project#E3Gateway}/provision-api-loadbalancing-endpoint1?uniqueId=${#TestCase#uniqueId} + + + 503 + + Global HTTP Settings + + + + + <xml-fragment/>http://${#Project#Target1}:8080/mockSCFTarget202actionsetStatusQUERYxs:stringclient_credentialsstatusCode200QUERYxs:string497df8c47ea64d8db8fa412964a070ffuniqueId${#TestCase#uniqueId}QUERY + + + + + <entry key="SIZE" value="10" xmlns="http://eviware.com/soapui/config"/> + + http://${#Project#E3Gateway}/provision-api-loadbalancing-endpoint1?uniqueId=${#TestCase#uniqueId} + + + 200 + + <ipAddress>${#Project#Target2}</ipAddress>falsefalse + + + + + + + + + + <entry key="SIZE" value="10" xmlns="http://eviware.com/soapui/config"/> + + http://${#Project#E3Gateway}/provision-api-loadbalancing-endpoint1?uniqueId=${#TestCase#uniqueId} + + + 200 + + <ipAddress>${#Project#Target3}</ipAddress>falsefalse + + + + + + + + + + <entry key="SIZE" value="10" xmlns="http://eviware.com/soapui/config"/> + + http://${#Project#E3Gateway}/provision-api-loadbalancing-endpoint1?uniqueId=${#TestCase#uniqueId} + + + 200 + + <ipAddress>${#Project#Target1}</ipAddress>falsefalseGlobal HTTP Settings + + + + + + + + + + + + + + +]]> + + + http://${#Project#E3Manager}:8181 + + + + + + + <xml-fragment/>http://${#Project#Target1}:8080/mockSCFTarget200actionlogQUERYxs:stringclient_credentialstextEnding testcase3 LB no failOverQUERYxs:string497df8c47ea64d8db8fa412964a070ffuniqueId${#TestCase#uniqueId}QUERYuniqueId${#Project#E3Gateway} + + + + + + + + + +]]> + + + http://${#Project#E3Manager}:8181 + + + + + + + <xml-fragment/>http://${#Project#Target1}:8080/mockSCFTarget200actionlogQUERYxs:stringclient_credentialstextStarting testcase2 LB/FO no HAQUERYxs:string497df8c47ea64d8db8fa412964a070ffuniqueId${#TestCase#uniqueId}QUERY<xml-fragment/>http://${#Project#Target1}:8080/mockSCFTarget202actionsetStatusQUERYxs:stringclient_credentialsstatusCode200QUERYxs:string497df8c47ea64d8db8fa412964a070ffuniqueId${#TestCase#uniqueId}QUERY<xml-fragment/>http://${#Project#Target2}:8080/mockSCFTarget202actionsetStatusQUERYxs:stringclient_credentialsstatusCode200QUERYxs:string497df8c47ea64d8db8fa412964a070ffuniqueId${#TestCase#uniqueId}QUERY<xml-fragment/>http://${#Project#Target3}:8080/mockSCFTarget202actionsetStatusQUERYxs:stringclient_credentialsstatusCode200QUERYxs:string497df8c47ea64d8db8fa412964a070ffuniqueId${#TestCase#uniqueId}QUERY + + + + + + + + + +]]> + + http://${#Project#E3Manager}:8181 + + provision-api-loadbalancing-api2 + test_route_1 + PassThrough + active + provision-api-loadbalancing-endpoint2 + false + + + noAuth + + + + false + + + + active + + + 503 + + + + + http://${#Project#Target1}:8080/mockSCFTarget + + + http://${#Project#Target2}:8080/mockSCFTarget + + + http://${#Project#Target3}:8080/mockSCFTarget + + + 10000 + 0.0 + 600000 + 0.0 + + +]]> + + 200 + + + + /response/status + SUCCESS + false + false + false + + + + /response/idprovision-api-loadbalancing-api2falsefalsefalse + + + + + + + + + + + + <entry key="SIZE" value="10" xmlns="http://eviware.com/soapui/config"/> + + http://${#Project#E3Gateway}/provision-api-loadbalancing-endpoint2?uniqueId=${#TestCase#uniqueId} + + + 200 + + <ipAddress>${#Project#Target1}</ipAddress>falsefalse + + + + + + + + + + <entry key="SIZE" value="10" xmlns="http://eviware.com/soapui/config"/> + + http://${#Project#E3Gateway}/provision-api-loadbalancing-endpoint2?uniqueId=${#TestCase#uniqueId} + + + 200 + + <ipAddress>${#Project#Target2}</ipAddress>falsefalse + + + + + + + + + + <entry key="SIZE" value="10" xmlns="http://eviware.com/soapui/config"/> + + http://${#Project#E3Gateway}/provision-api-loadbalancing-endpoint2?uniqueId=${#TestCase#uniqueId} + + + 200 + + <ipAddress>${#Project#Target3}</ipAddress>falsefalse + + + + + <xml-fragment/>http://${#Project#Target1}:8080/mockSCFTarget202Global HTTP SettingsactionsetStatusQUERYxs:stringclient_credentialsstatusCode503QUERYxs:string497df8c47ea64d8db8fa412964a070ffuniqueId${#TestCase#uniqueId}QUERY + + + + + <entry key="SIZE" value="10" xmlns="http://eviware.com/soapui/config"/> + + http://${#Project#E3Gateway}/provision-api-loadbalancing-endpoint2?uniqueId=${#TestCase#uniqueId} + + + 200 + + <ipAddress>${#Project#Target2}</ipAddress>falsefalseGlobal HTTP Settings + + + + + + + + + + <entry key="SIZE" value="10" xmlns="http://eviware.com/soapui/config"/> + + http://${#Project#E3Gateway}/provision-api-loadbalancing-endpoint2?uniqueId=${#TestCase#uniqueId} + + + 200 + + <ipAddress>${#Project#Target2}</ipAddress>falsefalse + + + + + + + + + + <entry key="SIZE" value="10" xmlns="http://eviware.com/soapui/config"/> + + http://${#Project#E3Gateway}/provision-api-loadbalancing-endpoint2?uniqueId=${#TestCase#uniqueId} + + + 200 + + <ipAddress>${#Project#Target3}</ipAddress>falsefalse + + + + + + + + + + <entry key="SIZE" value="10" xmlns="http://eviware.com/soapui/config"/> + + http://${#Project#E3Gateway}/provision-api-loadbalancing-endpoint2?uniqueId=${#TestCase#uniqueId} + + + 200 + + <ipAddress>${#Project#Target2}</ipAddress>falsefalse + + + + + + + + + + <entry key="SIZE" value="10" xmlns="http://eviware.com/soapui/config"/> + + http://${#Project#E3Gateway}/provision-api-loadbalancing-endpoint2?uniqueId=${#TestCase#uniqueId} + + + 200 + + <ipAddress>${#Project#Target2}</ipAddress>falsefalse + + + + + + + + + + <entry key="SIZE" value="10" xmlns="http://eviware.com/soapui/config"/> + + http://${#Project#E3Gateway}/provision-api-loadbalancing-endpoint2?uniqueId=${#TestCase#uniqueId} + + + 200 + + <ipAddress>${#Project#Target3}</ipAddress>falsefalse + + + + + <xml-fragment/>http://${#Project#Target1}:8080/mockSCFTarget202actionsetStatusQUERYxs:stringclient_credentialsstatusCode200QUERYxs:string497df8c47ea64d8db8fa412964a070ffuniqueId${#TestCase#uniqueId}QUERY + + + + + <entry key="SIZE" value="10" xmlns="http://eviware.com/soapui/config"/> + + http://${#Project#E3Gateway}/provision-api-loadbalancing-endpoint2?uniqueId=${#TestCase#uniqueId} + + + 200 + + <ipAddress>${#Project#Target1}</ipAddress>falsefalse + + + + + + + + + + <entry key="SIZE" value="10" xmlns="http://eviware.com/soapui/config"/> + + http://${#Project#E3Gateway}/provision-api-loadbalancing-endpoint2?uniqueId=${#TestCase#uniqueId} + + + 200 + + <ipAddress>${#Project#Target2}</ipAddress>falsefalse + + + + + + + + + + <entry key="SIZE" value="10" xmlns="http://eviware.com/soapui/config"/> + + http://${#Project#E3Gateway}/provision-api-loadbalancing-endpoint2?uniqueId=${#TestCase#uniqueId} + + + 200 + + <ipAddress>${#Project#Target3}</ipAddress>falsefalse + + + + + + + + + + + + + + +]]> + + + http://${#Project#E3Manager}:8181 + + + + + + + <xml-fragment/>http://${#Project#Target1}:8080/mockSCFTarget200actionlogQUERYxs:stringclient_credentialstextEnding testcase2 LB/FO no HAQUERYxs:string497df8c47ea64d8db8fa412964a070ffuniqueId${#TestCase#uniqueId}QUERYuniqueId${#Project#E3Gateway} + + + + + + + + + +]]> + + + http://${#Project#E3Manager}:8181 + + + + + + + <xml-fragment/>http://${#Project#Target1}:8080/mockSCFTarget200actionlogQUERYxs:stringclient_credentialstextStarting testcase4 LB/FO no HB all downQUERYxs:string497df8c47ea64d8db8fa412964a070ffuniqueId${#TestCase#uniqueId}QUERY<xml-fragment/>http://${#Project#Target1}:8080/mockSCFTarget202actionsetStatusQUERYxs:stringclient_credentialsstatusCode200QUERYxs:string497df8c47ea64d8db8fa412964a070ffuniqueId${#TestCase#uniqueId}QUERY<xml-fragment/>http://${#Project#Target2}:8080/mockSCFTarget202actionsetStatusQUERYxs:stringclient_credentialsstatusCode200QUERYxs:string497df8c47ea64d8db8fa412964a070ffuniqueId${#TestCase#uniqueId}QUERY<xml-fragment/>http://${#Project#Target3}:8080/mockSCFTarget202actionsetStatusQUERYxs:stringclient_credentialsstatusCode200QUERYxs:string497df8c47ea64d8db8fa412964a070ffuniqueId${#TestCase#uniqueId}QUERY + + + + + + + + + +]]> + + http://${#Project#E3Manager}:8181 + + provision-api-loadbalancing-api3 + test_route_1 + PassThrough + active + provision-api-loadbalancing-endpoint3 + false + + + noAuth + + + + false + + + + active + + + 503 + + + + + http://${#Project#Target1}:8080/mockSCFTarget + + + http://${#Project#Target2}:8080/mockSCFTarget + + + http://${#Project#Target3}:8080/mockSCFTarget + + + 10000 + 0.0 + 600000 + 0.0 + + +]]> + + 200 + + + + /response/status + SUCCESS + false + false + false + + + + /response/idprovision-api-loadbalancing-api3falsefalsefalse + + + + + + + + + + + + <entry key="SIZE" value="10" xmlns="http://eviware.com/soapui/config"/> + + http://${#Project#E3Gateway}/provision-api-loadbalancing-endpoint3?uniqueId=${#TestCase#uniqueId} + + + 200 + + <ipAddress>${#Project#Target1}</ipAddress>falsefalse + + + + + + + + + + <entry key="SIZE" value="10" xmlns="http://eviware.com/soapui/config"/> + + http://${#Project#E3Gateway}/provision-api-loadbalancing-endpoint3?uniqueId=${#TestCase#uniqueId} + + + 200 + + <ipAddress>${#Project#Target2}</ipAddress>falsefalse + + + + + + + + + + <entry key="SIZE" value="10" xmlns="http://eviware.com/soapui/config"/> + + http://${#Project#E3Gateway}/provision-api-loadbalancing-endpoint3?uniqueId=${#TestCase#uniqueId} + + + 200 + + <ipAddress>${#Project#Target3}</ipAddress>falsefalse + + + + + <xml-fragment/>http://${#Project#Target1}:8080/mockSCFTarget202actionsetStatusQUERYxs:stringclient_credentialsstatusCode503QUERYxs:string497df8c47ea64d8db8fa412964a070ffuniqueId${#TestCase#uniqueId}QUERY<xml-fragment/>http://${#Project#Target2}:8080/mockSCFTarget202actionsetStatusQUERYxs:stringclient_credentialsstatusCode503QUERYxs:string497df8c47ea64d8db8fa412964a070ffuniqueId${#TestCase#uniqueId}QUERY<xml-fragment/>http://${#Project#Target3}:8080/mockSCFTarget202actionsetStatusQUERYxs:stringclient_credentialsstatusCode503QUERYxs:string497df8c47ea64d8db8fa412964a070ffuniqueId${#TestCase#uniqueId}QUERY + + + + + <entry key="SIZE" value="10" xmlns="http://eviware.com/soapui/config"/> + + http://${#Project#E3Gateway}/provision-api-loadbalancing-endpoint3?uniqueId=${#TestCase#uniqueId} + + + ${#Project#ResponseCodeDown} + + + + + + + + + + + + <entry key="SIZE" value="10" xmlns="http://eviware.com/soapui/config"/> + + http://${#Project#E3Gateway}/provision-api-loadbalancing-endpoint3?uniqueId=${#TestCase#uniqueId} + + + ${#Project#ResponseCodeDown} + + + + + + + + + + + + <entry key="SIZE" value="10" xmlns="http://eviware.com/soapui/config"/> + + http://${#Project#E3Gateway}/provision-api-loadbalancing-endpoint3?uniqueId=${#TestCase#uniqueId} + + + ${#Project#ResponseCodeDown} + + + + + + + + + + + + <entry key="SIZE" value="10" xmlns="http://eviware.com/soapui/config"/> + + http://${#Project#E3Gateway}/provision-api-loadbalancing-endpoint3?uniqueId=${#TestCase#uniqueId} + + + ${#Project#ResponseCodeDown} + + + + + + + <xml-fragment/>http://${#Project#Target1}:8080/mockSCFTarget202actionsetStatusQUERYxs:stringclient_credentialsstatusCode200QUERYxs:string497df8c47ea64d8db8fa412964a070ffuniqueId${#TestCase#uniqueId}QUERY + + + + + <entry key="SIZE" value="10" xmlns="http://eviware.com/soapui/config"/> + + http://${#Project#E3Gateway}/provision-api-loadbalancing-endpoint3?uniqueId=${#TestCase#uniqueId} + + + 200 + + <ipAddress>${#Project#Target1}</ipAddress>falsefalse + + + + + + + + + + <entry key="SIZE" value="10" xmlns="http://eviware.com/soapui/config"/> + + http://${#Project#E3Gateway}/provision-api-loadbalancing-endpoint3?uniqueId=${#TestCase#uniqueId} + + + 200 + + + + + + + + + + + + <entry key="SIZE" value="10" xmlns="http://eviware.com/soapui/config"/> + + http://${#Project#E3Gateway}/provision-api-loadbalancing-endpoint3?uniqueId=${#TestCase#uniqueId} + + + 200 + + + + + + + + + + + + <entry key="SIZE" value="10" xmlns="http://eviware.com/soapui/config"/> + + http://${#Project#E3Gateway}/provision-api-loadbalancing-endpoint3?uniqueId=${#TestCase#uniqueId} + + + 200 + + + + + + + + + + + + + + + + +]]> + + + http://${#Project#E3Manager}:8181 + + + + + + + <xml-fragment/>http://${#Project#Target1}:8080/mockSCFTarget200actionlogQUERYxs:stringclient_credentialstextEnding testcase4 LB/FO no HB all downQUERYxs:string497df8c47ea64d8db8fa412964a070ffuniqueId${#TestCase#uniqueId}QUERYuniqueId${#Project#E3Gateway}<xml-fragment/>http://${#Project#E3Manager}:8181/cxf/e3/system-manager/logging/instances/0/logLevelINFOuniqueId${#Project#E3Gateway}E3Manager192.168.84.162E3Gateway192.168.84.162Target1192.168.84.90Target2192.168.84.103Target3192.168.84.184uniqdeleteLOG4J_LEVEL_VALUES(ALL|TRACE|DEBUG|INFO|WARN|ERROR|FATAL|OFF)STATUS_SUCCESSSUCCESSSYSLOG_LEVEL_VALUES(DEBUG|INFO|NOTICE|WARNING|ERR|CRIT|ALERT|EMERG)ResponseCodeDown500 \ No newline at end of file diff --git a/tests/functional-tests/functional-test-provision-api/pom.xml b/tests/functional-tests/functional-test-provision-api/pom.xml new file mode 100644 index 0000000..25a307a --- /dev/null +++ b/tests/functional-tests/functional-test-provision-api/pom.xml @@ -0,0 +1,48 @@ + + 4.0.0 + com.alu.e3.functional-tests.samples + functional-test-provision-api + pom + + + + eviware + maven-soapui-plugin + 4.0.1 + + + mysql + mysql-connector-java + 5.1.6 + + + junit + junit + 4.8.1 + + + + + test + + test + + + ${basedir}/soapui-project.xml + ${basedir}/target/surefire-reports + true + ${basedir}/soapui-project-properties.xml + + + + + + + + com.alu.e3.functional-tests + functional-tests + 0.0.1-SNAPSHOT + .. + + Functional test provision api + \ No newline at end of file diff --git a/tests/functional-tests/functional-test-provision-api/soapui-project.xml b/tests/functional-tests/functional-test-provision-api/soapui-project.xml new file mode 100644 index 0000000..5a2d0da --- /dev/null +++ b/tests/functional-tests/functional-test-provision-api/soapui-project.xml @@ -0,0 +1,9664 @@ + + +http://${#Project#E3Gateway}/api-parameters-endpoint1?param1=value1&key=api-parameters-key1&param2=value2http://${#Project#E3Gateway}/api-parameters-endpoint2/five?key=api-parameters-key2http://${#Project#E3Gateway}/api-parameters-endpoint2/three/five?key=api-parameters-key2apiauthTEMPLATEkeymykeyQUERYmykeyparam1QUERYtext/plain403 500 429data200data200data0data0data0data200data200data200data200data200data200data0datatext/html200<xml-fragment/>http://${#Project#E3Gateway}keymykeyQUERYmykeyparam1value1QUERYvalue1param2value2QUERYvalue2text/plain403data200data200data0data0data0data200data200data200data200data200data200data200datatext/html2000data<xml-fragment/>http://${#Project#E3Gateway}param1value1QUERYvalue1keymykeyQUERYxs:stringmykeyparam2value2QUERYvalue2text/plain403data200data200data0data0data0data200data200data200data200data200data200datatext/html200<xml-fragment/>http://${#Project#E3Gateway}param1value1QUERYvalue1param2value2QUERYvalue2keymykeyQUERYxs:stringmykeytext/plain403data200data200data0data0data0data200data200data200data200data200data200datatext/html200<xml-fragment/>http://${#Project#E3Gateway}text/plain403data200data200data0data0data0data200data200data200data200data200data200datatext/html200text/html;charset=ISO-8859-1404htmltext/html404html<xml-fragment/>http://${#Project#E3Gateway}param1QUERYtext/plain403 500 429data200data200data0data0data0data200data200data200data200data200data200data0datatext/html200text/html404html<xml-fragment/>http://${#Project#E3Gateway}keyQUERYtext/plain403 500 429data200data200data0data0data0data200data200data200data200data200data200data0datatext/html200text/html;charset=ISO-8859-1404html<xml-fragment/>http://${#Project#E3Gateway}text/plain403data200data200data0data0data0data200data200data200data200data200data200datatext/html200text/html;charset=ISO-8859-1404html0data<xml-fragment/>http://${#Project#E3Gateway}text/plain403data200data200data0data0data0data200data200data200data200data200data200datatext/html200text/html;charset=ISO-8859-1404html<xml-fragment/>http://${#Project#E3Gateway}text/plain403data200data200data0data0data0data200data200data200data200data200data200datatext/html200text/html;charset=ISO-8859-1404html0data0data0data0data<xml-fragment/>http://${#Project#E3Gateway}param1QUERYtext/plain403data200data200data0data0data0data200data200data200data200data200data200datatext/html200text/html;charset=ISO-8859-1404html0data<xml-fragment/>http://${#Project#E3Gateway}param1QUERYkeyQUERYtext/plain403data200data200data0data0data0data200data200data200data200data200data200datatext/html200text/html;charset=ISO-8859-1404html0data<xml-fragment/>http://${#Project#E3Gateway}keyQUERYtext/plain403data200data200data0data0data0data200data200data200data200data200data200datatext/html200text/html;charset=ISO-8859-1404html0data<xml-fragment/>http://${#Project#E3Gateway}text/plain403data200data200data0data0data0data200data200data200data200data200data200datatext/html200text/html;charset=ISO-8859-1404html0data0data<xml-fragment/>http://${#Project#E3Gateway}param1QUERYtext/plain403data200data200data0data0data0data200data200data200data200data200data200datatext/html200text/html;charset=ISO-8859-1404html0data<xml-fragment/>http://${#Project#E3Gateway}param1QUERYkeyQUERYtext/plain403data200data200data0data0data0data200data200data200data200data200data200datatext/html200text/html;charset=ISO-8859-1404html0data<xml-fragment/>http://${#Project#E3Gateway}text/plain403data200data200data0data0data0data200data200data200data200data200data200datatext/html200text/html;charset=ISO-8859-1404html<xml-fragment/>http://${#Project#E3Gateway}text/plain403 500data200data200data0data0data0data200data200data200data200data200data200datatext/html200text/html;charset=ISO-8859-1404html0datatext/html; charset=iso-8859-1404html<xml-fragment/>http://${#Project#E3Gateway}text/plain403data200data200data0data0data0data200data200data200data200data200data200datatext/html200text/html;charset=ISO-8859-1404html<xml-fragment/>http://${#Project#E3Gateway}text/html200text/plain403 500datatext/html404htmlhttp://${#Project#E3Gateway} + + + http://${#Project#E3Gateway}/auth-extended-endpoint1?key=auth-extended-key1http://${#Project#E3Gateway}/auth-extended-endpoint1http://${#Project#E3Gateway}/auth-extended-endpoint2http://${#Project#E3Gateway}/api-header-transform-endpoint1?key=api-header-transform-key1http://${#Project#E3Gateway}/api-header-transform-endpoint2?key=api-header-transform-key2http://${#Project#E3Gateway}/api-header-transform-endpoint3?key=api-header-transform-key3http://${#Project#E3Gateway}/provision-api-ext-endpoint1http://${#Project#E3Gateway}/provision-api-ext-endpoint3?key=provision-api-ext-key3https://${#Project#E3Gateway}/tls2ways-call-expired-endpoint1https://${#Project#E3Gateway}/tls2ways-call-ko-endpoint1https://${#Project#E3Gateway}/tls2ways-call-no-cert-endpoint1https://${#Project#E3Gateway}/tls2ways-call-ok-endpoint1https://${#Project#E3Gateway}:25101/provision-sslkey-endpoint3https://${#Project#E3Gateway}:25101/provision-sslkey-endpoint4?key=provision-sslkey-key4http://${#Project#E3Gateway}/tdr-smoke-endpoint1?key=tdr-smoke-key1http://${#Project#E3Gateway}/tdr-endpoint1?key=tdr-key1http://${#Project#E3Gateway}/rate-limit-aib-and-cluster-endpoint2?key=rate-limit-aib-and-cluster-key2http://${#Project#E3Gateway}/rate-limit-aib-and-cluster-endpoint3?key=rate-limit-aib-and-cluster-key3http://${#Project#E3Gateway}/rate-limit-aib-endpoint2http://${#Project#E3Gateway}/rate-limit-aib-endpoint3?key=rate-limit-aib-key3http://${#Project#E3Gateway}/end3?key=789456http://${#Project#E3Gateway}/end3?key=789456http://${#Project#E3Gateway}/api-provision-endpoint6http://${#Project#E3Gateway}/api-provision-endpoint6_2http://${#Project#E3Gateway}/api-provision-endpoint7?key=api-provision-key7http://${#Project#E3Gateway}/api-provision-endpoint8_2?key=api-provision-key8http://${#Project#E3Gateway}/api-provision-endpoint8http://${#Project#E3Gateway}/api-provision-endpoint9http://${#Project#E3Gateway}/api-provision-endpoint9_2http://${#Project#E3Gateway}/api-provision-endpoint9_2?key=api-provision-key9http://${#Project#E3Gateway}/api-provision-endpoint10http://${#Project#E3Gateway}/api-provision-endpoint10_2http://${#Project#E3Gateway}/api-provision-endpoint10_2?key=api-provision-key10http://${#Project#E3Gateway}/api-provision-endpoint11http://${#Project#E3Gateway}/api-provision-endpoint11_2http://${#Project#E3Gateway}/api-provision-endpoint11_2?key=api-provision-key11http://${#Project#E3Gateway}/api-provision-endpoint12http://${#Project#E3Gateway}/api-provision-endpoint12_2http://${#Project#E3Gateway}/api-provision-endpoint12_2?key=api-provision-key12http://${#Project#E3Gateway}/api-provision-endpoint13http://${#Project#E3Gateway}/api-provision-endpoint13_2http://${#Project#E3Gateway}/api-provision-endpoint13_2?key=api-provision-key13http://${#Project#E3Gateway}/api-provision-endpoint18?key=api-provision-key18http://${#Project#E3Gateway}/api-provision-endpoint18_2?key=api-provision-key18http://${#Project#E3Gateway}/api-provision-endpoint19?key=api-provision-key19http://${#Project#E3Gateway}/api-provision-endpoint19_2?key=api-provision-key19http://${#Project#E3Gateway}/auth-type-ip-white-list-endpoint2http://${#Project#E3Gateway}/auth-type-ip-white-list-endpoint3http://${#Project#E3Gateway}/auth-type-ip-white-list-endpoint4http://${#Project#E3Gateway}/auth-type-ip-white-list-endpoint5 + + + + + + keyQUERY + + text/html + 200 + + html + + + + 0 + + data + + + text/plain + 500 403 401 429 + + data + + + + 200 + + data + + + + 200 + + data + + + text/html + 404 + + html + + 0data0data0data0data0data + 0data0datatext/xml200data<xml-fragment xmlns:con="http://eviware.com/soapui/config"> + <con:entry key="WAIT" value="0"/> + <con:entry key="SIZE" value="100"/> +</xml-fragment>http://${#Project#E3Gateway}/endpoint1<xml-fragment xmlns:con="http://eviware.com/soapui/config"> + <con:entry key="WAIT" value="0"/> + <con:entry key="SIZE" value="100"/> +</xml-fragment>http://${#Project#E3Gateway}/endpoint1 + text/plain401 403 429 500datatext/html200html0data0data0data0datatext/html404htmltext/xml200data0data0data0data0data0data0data0data0data0data0data0data0data0data<xml-fragment xmlns:con="http://eviware.com/soapui/config"> + <con:entry key="WAIT" value="0"/> + <con:entry key="SIZE" value="100"/> +</xml-fragment>http://${#Project#E3Gateway}/endpoint1text/plain401 500 429data0data0data0data0data0data0data0data0data0data0datatext/xml200datatext/html404html<xml-fragment xmlns:con="http://eviware.com/soapui/config"> + <con:entry key="Authorization" value="Basic dGVzdGVyOnRlc3RlcnBhc3N3b3Jk"/> + <con:entry key="WAIT" value="0"/> + <con:entry key="SIZE" value="100"/> +</xml-fragment>http://${#Project#E3Gateway}/endpoint1<xml-fragment xmlns:con="http://eviware.com/soapui/config"> + <con:entry key="Authorization" value="Basic invalidbasic"/> + <con:entry key="WAIT" value="0"/> + <con:entry key="SIZE" value="100"/> +</xml-fragment>http://${#Project#E3Gateway}/endpoint1text/xml200datatext/html200data<xml-fragment xmlns:con="http://eviware.com/soapui/config"> + <con:entry key="WAIT" value="0"/> + <con:entry key="SIZE" value="100"/> +</xml-fragment>http://${#Project#E3Gateway}/endpoint1?key=e88ba0c1e4c34f25bf95733eebd8574f + http://${#Project#E3Gateway}:8181/cxf/e3/prov/v1?_wadl&_type=xml + + + + E3 REST API to create, update or delete an API + + Used to get all API IDs. + + + + + + This REST API is used to create an API. + + + + + + + + + + + This REST API is used to delete an API. + + + + + + + Used to get an API by this ID. + + + + + + + This REST API is used to update an API. + + + + + + + + + + + E3 REST API to create, update or delete a policy + + This REST API is used to fetch all policy ids. + + + + + + This REST API is used to create a policy. + + + + + + + + + + + This REST API is used to delete a policy. + + + + + + + This REST API is used to fetch policy data. + + + + + + + This REST API is used to update a policy. + + + + + + + + + + + + This REST API is used to create a QuotaRLBucket in a policy. + + + + + + + + + + + + + This REST API is used to remove a bucket from a policy. + + + + + + + This REST API is used to append auths to a bucket. + + + + + + + + + + + + + + This REST API is used to remove an auth from a bucket. + + + + + + + + + E3 REST API provision authentications on E3 subsystem + + This REST API is used to get all authentications from E3 subsystem. + + + + + + This REST API is used to create an authentication element on E3 subsystem. + + + + + + + + + + + This REST API is used to delete an Auth. + + + + + + + This REST API is used to get an authentication by ID from E3 subsystem. + + + + + + + This REST API is used to update an authentication. + + + + + + + + + + + E3 REST API to create or delete a bucket of auths associated to a list of policies + + This REST API is used to create a bucket linked to a list of policies. + + + + + + + + + + + This REST API is used to append auths to a bucket for several policies. + + + + + + + + + + + + This REST API is used to remove a bucket from a list of policies. + + + + + + + + + + + E3 REST API provision SSLKeys and SSLCerts on E3 subsystem + + This REST API is used to get all SSLKeys from E3 subsystem. + + + + + + This REST API is used to create an SSLKey element on E3 subsystem. + + + + + + + + + + + This REST API is used to delete an SSLKey. + + + + + + + This REST API is used to get an SSLKey by ID from E3 subsystem. + + + + + + + This REST API is used to update an SSLKey. + + + + + + + + + + + + This REST API is used to get all SSLCerts for a key. + + + + + + + This REST API is used to create an SSLCert element on E3 subsystem. + + + + + + + + + + + + + This REST API is used to delete an SSLCert. + + + + + + + This REST API is used to get an SSLKey by ID from E3 subsystem. + + + + + + + This REST API is used to update an SSLKey. + + + + + + + + + + + + This REST API is used to get a CSR for the given SSLKey ID from E3 subsystem. + + + + + + + + + + This REST API is used to create a self-signed cert for an existing Key + + + + + + + + + E3 REST API to add/update/delete trusted CAs and CRLs + + + This REST API is used to fetch all trusted certificates authorithies. + + + + + + This REST API is used to add a trusted Certificate Authority. + + + + + + + + + + + + This REST API is used to remove a trusted Certificate Authority. + + + + + + + This REST API is used to fetch trusted Certificate Authority. + + + + + + + This REST API is used to update a trusted Certificate Authority. + + + + + + + + + + + This REST API is used to fetch trusted Certificate Authority. + + + + + + This REST API is used to add a Certificate Revocation List for this Certificate Authority. + + + + + + + + + + + + This REST API is used to remove a certificate revocation list from a certificate authority. + + + + + + + This REST API is used to fetch Certificate Revocation List. + + + + + + + This REST API is used to update a certificate revocation list. + + + + + + + + + + +]]>http://wadl.dev.java.net/2009/02http://${#Project#E3Gateway}:8181API_IDTEMPLATExs:stringapplication/xmlhttp://${#Project#E3Gateway}:8181application/xmlhttp://${#Project#E3Gateway}:8181application/xmlapplication/xmlhttp://${#Project#E3Gateway}:8181application/xmlhttp://${#Project#E3Gateway}:8181application/xmlapplication/xmlhttp://${#Project#E3Gateway}:8181POLICY_IDTEMPLATExs:stringapplication/xmlhttp://${#Project#E3Gateway}:8181application/xmlhttp://${#Project#E3Gateway}:8181application/xmlapplication/xmlhttp://${#Project#E3Gateway}:8181POLICY_IDTEMPLATExs:stringapplication/xmlapplication/xmlhttp://${#Project#E3Gateway}:8181POLICY_IDTEMPLATExs:stringBUCKET_IDTEMPLATExs:stringapplication/xmlhttp://${#Project#E3Gateway}:8181application/xmlapplication/xmlhttp://${#Project#E3Gateway}:8181POLICY_IDTEMPLATExs:stringBUCKET_IDTEMPLATExs:stringAUTH_IDTEMPLATExs:stringapplication/xmlhttp://${#Project#E3Gateway}:8181application/xmlhttp://${#Project#E3Gateway}:8181application/xmlapplication/xmlhttp://${#Project#E3Gateway}:8181AUTH_IDTEMPLATExs:stringapplication/xmlhttp://${#Project#E3Gateway}:8181application/xmlhttp://${#Project#E3Gateway}:8181application/xmlapplication/xmlhttp://${#Project#E3Gateway}:8181application/xmlhttp://${#Project#E3Gateway}:8181application/xmlapplication/xmlhttp://${#Project#E3Gateway}:8181BUCKET_IDTEMPLATExs:stringapplication/xmlapplication/xmlhttp://${#Project#E3Gateway}:8181BUCKET_IDTEMPLATExs:stringapplication/xmlapplication/xmlhttp://${#Project#E3Gateway}:8181application/xmlapplication/xmlhttp://${#Project#E3Gateway}:8181KEY_IDTEMPLATExs:stringapplication/xmlhttp://${#Project#E3Gateway}:8181application/xmlhttp://${#Project#E3Gateway}:8181application/xmlapplication/xmlhttp://${#Project#E3Gateway}:8181KEY_IDTEMPLATExs:stringapplication/xmlhttp://${#Project#E3Gateway}:8181application/xmlapplication/xmlhttp://${#Project#E3Gateway}:8181KEY_IDTEMPLATExs:stringCERT_IDTEMPLATExs:stringapplication/xmlhttp://${#Project#E3Gateway}:8181application/xmlhttp://${#Project#E3Gateway}:8181application/xmlapplication/xmlhttp://${#Project#E3Gateway}:8181KEY_IDTEMPLATExs:stringapplication/xmlhttp://${#Project#E3Gateway}:8181KEY_IDTEMPLATExs:stringapplication/xmlhttp://${#Project#E3Gateway}:8181application/xml<xml-fragment/>http://${#Project#E3Gateway}:8181application/xmlapplication/xmlhttp://${#Project#E3Gateway}:8181application/xml<xml-fragment/>http://${#Project#E3Gateway}:8181application/xmlapplication/xmlhttp://${#Project#E3Gateway}:8181CA_IDTEMPLATExs:stringapplication/xmlhttp://${#Project#E3Gateway}:8181application/xmlhttp://${#Project#E3Gateway}:8181application/xmlapplication/xmlhttp://${#Project#E3Gateway}:8181application/xmlhttp://${#Project#E3Gateway}:8181application/xmlapplication/xmlhttp://${#Project#E3Gateway}:8181CRL_IDTEMPLATExs:stringapplication/xmlhttp://${#Project#E3Gateway}:8181application/xmlhttp://${#Project#E3Gateway}:8181application/xmlapplication/xmlhttp://${#Project#E3Gateway}:8181file:/D:/Documents%20and%20Settings/mtobiasz/Desktop/targertest_1.wadl + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + +]]>http://wadl.dev.java.net/2009/02http://${#Project#E3Gateway}http://${#Project#E3Gateway}/api-http-method-endpoint1?key=api-http-method-key1http://${#Project#E3Gateway}/api-http-method-endpoint2?key=api-http-method-key2http://${#Project#E3Gateway}/api-http-method-endpoint3?key=api-http-method-key3http://${#Project#E3Gateway}/api-http-method-endpoint4?key=api-http-method-key40text/html200http://${#Project#E3Gateway}application/xml0application/xmltext/plain403 405 429text/xml200ns:responsehttp://${#Project#E3Gateway}application/xmlapplication/xmltext/plain405 429text/xml200ns:responsehttp://${#Project#E3Gateway}text/plain405 429text/xml200ns:responsehttp://${#Project#E3Gateway}0text/plain405text/xml200http://${#Project#E3Gateway}http://135.248.213.24:8181pathToConfigFilesDirectoryTEMPLATExs:stringapplication/octet-streamhttp://135.248.213.24:8181application/octet-streamhttp://135.248.213.24:8181numLinesTEMPLATExs:stringapplication/xmlhttp://135.248.213.24:8181numLinesTEMPLATExs:stringapplication/xmlhttp://135.248.213.24:8181application/xmlhttp://135.248.213.24:8181instanceIdTEMPLATExs:stringapplication/xml<xml-fragment/>http://135.248.213.36:8181application/octet-streamapplication/xmlhttp://135.248.213.24:8181instanceIdTEMPLATExs:stringapplication/xmlhttp://135.248.213.24:8181application/octet-streamapplication/xmlhttp://135.248.213.24:8181instanceIdTEMPLATExs:stringapplication/xmlhttp://135.248.213.24:8181application/octet-streamapplication/xmlhttp://135.248.213.24:8181application/octet-streamhttp://135.248.213.24:8181application/octet-streamhttp://135.248.213.24:8181application/xml<xml-fragment/>http://135.248.213.24:8181application/octet-streamapplication/xml<xml-fragment/>http://135.248.213.24:8181application/xmlhttp://135.248.213.24:8181application/xmlapplication/xmlhttp://135.248.213.24:8181application/xmlhttp://135.248.213.24:8181application/octet-streamapplication/xmlhttp://135.248.213.24:8181application/xml<xml-fragment/>http://135.248.213.24:8181application/octet-streamapplication/xmlhttp://135.248.213.24:8181 + TestSuite generated for REST Service + [functional-test-provision-api] + + SEQUENTIAL + + TestCase generated for REST Resource [/apis] located + at [/apis] + + + + + + + + + + + +]]> + + http://${#Project#E3Manager}:8181 + + + + + + + + + + + + + + + + + +]]> + + http://${#Project#E3Manager}:8181 + + api-provision-api1_fake + test_route_1 + PassThrough + active + api-provision-endpoint1_fake + false + + + authKey + + + key + + + + false + + + + active + + + http://${#Project#Target1}:8080/proxySize + + NoAuth + + key000Val + + + + + http://${#Project#Target2}:8080/proxySize + + NoAuth + + key000Val + + + + + 10000 + 0.0 + 600000 + 0.0 + + + active + + + http://${#Project#Target1}:8080/proxySize + + NoAuth + + key000Val + + + + + http://${#Project#Target2}:8080/proxySize + + NoAuth + + key000Val + + + + + 10000 + 0.0 + 600000 + 0.0 + + + + + + + CompanyQuota + Billing + + + + + + CompanyQuota + Billing + + + + true + + + + + + + + +]]> + + + 200 + + + + + /response/status + SUCCESS + false + false + false + + + + /response/idapi-provision-api1_fakefalsefalsefalse + + + + + + + + + + + + + + + + + +]]> + + http://${#Project#E3Manager}:8181 + + + + + + + + + + + + + + + + + +]]> + + http://${#Project#E3Manager}:8181 + + api-provision-api1_2 + test_route_1 + PassThrough + active + api-provision-endpoint1_2 + false + + + authKey + + + key + + + + true + + + + active + + + http://${#Project#Target1}:8080/proxySize + + NoAuth + + key000Val + + + + + 10000 + 0.0 + 600000 + 0.0 + + + + + + + CompanyQuota + Billing + + + + + + CompanyQuota + Billing + + + +]]> + + + 200 + + + + + /response/status + SUCCESS + false + false + false + + + + /response/idapi-provision-api1_2falsefalsefalse + + + + + + + + + + + + + + + + + +]]> + + http://${#Project#E3Manager}:8181 + + api-provision-api1_2 + test_route_1 + PassThrough + active + api-provision-endpoint1_2 + false + + + authKey + + + key + + + + false + + + + active + + + http://${#Project#Target1}:8080/proxySize + + NoAuth + + key000Val + + + + + 10000 + 0.0 + 600000 + 0.0 + + + + + + + CompanyQuota + Billing + + + + + + CompanyQuota + Billing + + + +]]> + + + /response/status + SUCCESS + false + false + false + + + + + 200 + + + + /response/idapi-provision-api1_2falsefalsefalse + + + + + + + + + + + + + + + + + +]]> + + http://${#Project#E3Manager}:8181 + + getLocation + test_route_1 + PassThrough + active + endpoint1 + false + + + authKey + + + key + + + + false + + + + active + + + http://${#Project#Target1}:8080/proxySize + + NoAuth + + key000Val + + + + + 10000 + 0.0 + 600000 + 0.0 + + + + + + + CompanyQuota + Billing + + + + + + CompanyQuota + Billing + + + +]]> + + /response/statusFAILUREfalsefalsefalse + + + 500 + + + + + + + + + + + + + + + + + + +]]> + + http://${#Project#E3Manager}:8181 + + + + 200 + + + + + + /response/status + SUCCESS + false + false + false + + + + + + + + + + + TestCase generated for REST Resource [/apis] located + at [/apis] + + + + + + + + + + + +]]> + + http://${#Project#E3Manager}:8181 + + + + + + + + + + + + + + + + + +]]> + + http://${#Project#E3Manager}:8181 + + api-provision-api2 + test_route_1 + PassThrough + active + api-provision-endpoint2 + false + + + authKey + + + key + + + + true + + + + active + + + http://${#Project#Target1}:8080/proxySize + + NoAuth + + key000Val + + + + + 10000 + 0.0 + 600000 + 0.0 + + + + + + + CompanyQuota + Billing + + + + + + CompanyQuota + Billing + + + +]]> + + + 200 + + + + + /response/status + SUCCESS + false + false + false + + + + /response/idapi-provision-api2falsefalsefalse + + + + + + + + + + + + + + + + + +]]> + + http://${#Project#E3Manager}:8181 + + + + 200 + + + + + + /response/status + SUCCESS + false + false + false + + + + + + + + + + + + + + + + + + +]]> + + http://${#Project#E3Manager}:8181 + + api-provision-api2 + test_route_1 + PassThrough + active + api-provision-endpoint2 + false + + + authKey + + + key + + + + true + + + + active + + + http://${#Project#Target1}:8080/proxySize + + NoAuth + + key000Val + + + + + 10000 + 0.0 + 600000 + 0.0 + + + + + + + CompanyQuota + Billing + + + + + + CompanyQuota + Billing + + + +]]> + + + /response/status + FAILURE + false + false + false + + + + 404 + + + + + + + + + + + + + + + + + + + + +]]> + + http://${#Project#E3Manager}:8181 + + + + + + + + + + + + + + + + + +]]> + + http://${#Project#E3Manager}:8181 + + api-provision-api3 + test_route_1 + PassThrough + active + api-provision-endpoint3 + false + + + authKey + + + key + + + + true + + + + active + + + http://${#Project#Target1}:8080/proxySize + + NoAuth + + key000Val + + + + + 10000 + 0.0 + 600000 + 0.0 + + + + + + + CompanyQuota + Billing + + + + + + CompanyQuota + Billing + + + +]]> + + + 200 + + + + + /response/status + SUCCESS + false + false + false + + + + /response/idapi-provision-api3falsefalsefalse + + + + + + + + + + + + + + + + + +]]> + + http://${#Project#E3Manager}:8181 + + api-provision-api3 + test_route_1 + PassThrough + active + api-provision-endpoint3 + false + + + authKey + + + key + + + + true + + + + active + + + http://${#Project#Target1}:8080/proxySize + + NoAuth + + key000Val + + + + + 10000 + 0.0 + 600000 + 0.0 + + + + + + + CompanyQuota + Billing + + + + + + CompanyQuota + Billing + + + +]]> + + + 500 + + + + + /response/status + FAILURE + false + false + false + + + + + + + + + + + + + + + + + + +]]> + + http://${#Project#E3Manager}:8181 + + + + 200 + + + + + + /response/status + SUCCESS + false + false + false + + + + + + + + + + + + TestCase generated for REST Resource [/apis] located + at [/apis] + + + + + + + + + + + +]]> + + http://${#Project#E3Manager}:8181 + + + + + + + + + + + + + + + + + +]]> + + http://${#Project#E3Manager}:8181 + + api-provision-api4 + test_route_1 + PassThrough + active + api-provision-endpoint4 + false + + + authKey + + + key + + + + true + + + + active + + + http://${#Project#Target1}:8080/proxySize + + NoAuth + + key000Val + + + + + 10000 + 0.0 + 600000 + 0.0 + + + + + + + CompanyQuota + Billing + + + + + + CompanyQuota + Billing + + + +]]> + + + 200 + + + + + /response/status + SUCCESS + false + false + false + + + + /response/idapi-provision-api4falsefalsefalse + + + + + + + + + + + + + + + + + +]]> + + http://${#Project#E3Manager}:8181 + + + + 200 + + + + + + /response/status + SUCCESS + false + false + false + + + + + + + + + + + + + + + + + + +]]> + + http://${#Project#E3Manager}:8181 + + + 404 + + + /response/statusFAILUREfalsefalsefalse + + + + + + + + + TestCase generated for REST Resource [/apis] located + at [/apis] + + + + + + + + + + + +]]> + + http://${#Project#E3Manager}:8181 + + + + + + + + + + + <xml-fragment/>http://${#Project#E3Manager}:8181 + <xml-fragment/>http://${#Project#E3Manager}:8181 + + + + + + + + + + +]]> + + http://${#Project#E3Manager}:8181 + + api-provision-api5 + test_route_1 + PassThrough + active + api-provision-endpoint5 + false + + + authKey + + + key + + + + true + + + + active + + + http://${#Project#Target1}:8080/proxySize + + NoAuth + + key000Val + + + + + 10000 + -1 + 600000 + -1 + + + + + + + + CompanyQuota + Billing + + + + + + CompanyQuota + Billing + + + + + + CompanyQuota + Billing + + + + + request + response + + + + + + + + + +]]> + + + 200 + + + + + /response/status + SUCCESS + false + false + false + + + + /response/idapi-provision-api5falsefalsefalse + + + + + + + + <xml-fragment/>http://${#Project#E3Manager}:8181 + api-provision-auth5 + active + authKey + + + + api-provision-key5 + + + + + + CompanyQuota + Billing + + + + + + CompanyQuota + Billing + + + +]]>200/response/idapi-provision-auth5falsefalsefalse/response/statusSUCCESSfalsefalsefalse + <xml-fragment/>http://${#Project#E3Manager}:8181 + api-provision-p5 + + api-provision-api5 + + + + api-provision-auth5 + + + + + active + + active + reject + 98 + 1000 + + + + active + + + +]]>200/response/idapi-provision-p5falsefalsefalse/response/statusSUCCESSfalsefalsefalse + + + + + + <entry key="SIZE" value="10" xmlns="http://eviware.com/soapui/config"/> + + http://${#Project#E3Gateway}/api-provision-endpoint5?key=api-provision-key5 + + + 200 + + /data9876543210falsefalsefalse + + + + + + + + + + + + + + +]]> + + + http://${#Project#E3Manager}:8181 + + api-provision-api5 + test_route_1 + PassThrough + active + api-provision-endpoint5_2 + false + + + authKey + + + key + + + + true + + + + active + + + http://${#Project#Target1}:8080/proxySize + + NoAuth + + key000Val + + + + + 10000 + 0.0 + 600000 + 0.0 + + + + + + + CompanyQuota + Billing + + + + + + CompanyQuota + Billing + + + +]]> + + + /response/status + SUCCESS + false + false + false + + + + + 200 + + + + /response/idapi-provision-api5falsefalsefalse + + + + + + + + + + + + <entry key="SIZE" value="10" xmlns="http://eviware.com/soapui/config"/> + + http://${#Project#E3Gateway}/api-provision-endpoint5_2?key=api-provision-key5 + + + + 200 + + + /data9876543210falsefalsefalse + + + + + + + + + + + + + + +]]> + + http://${#Project#E3Manager}:8181 + + + + 200 + + + + + + /response/status + SUCCESS + false + false + false + + + + + + + + + + + + + <xml-fragment/> + + http://${#Project#E3Gateway}/api-provision-endpoint5_2?key=api-provision-key5 + + + 404 + + + + + + + <xml-fragment/>http://${#Project#E3Manager}:8181200/response/statusSUCCESSfalsefalsefalse<xml-fragment/>http://${#Project#E3Manager}:8181200/response/statusSUCCESSfalsefalsefalse + + + TestCase generated for REST Resource [/apis] located + at [/apis] + + + + + + + + + + + +]]> + + + http://${#Project#E3Manager}:8181 + + + + + + + + <xml-fragment/>http://${#Project#E3Manager}:8181 + <xml-fragment/>http://${#Project#E3Manager}:8181 + + + + + + + + + +]]> + + http://${#Project#E3Manager}:8181 + + api-provision-api6 + test_route_1 + PassThrough + active + api-provision-endpoint6 + false + + + authKey + + + key + + + + false + + + + active + + + http://${#Project#Target1}:8080/proxySize + + NoAuth + + key000Val + + + + + 10000 + 0.0 + 600000 + 0.0 + + + + + + + CompanyQuota + Billing + + + + + + CompanyQuota + Billing + + + +]]> + + + 200 + + + + + /response/status + SUCCESS + false + false + false + + + + /response/idapi-provision-api6falsefalsefalse + + + + + + + <xml-fragment/>http://${#Project#E3Manager}:8181 + api-provision-auth6 + active + authKey + + + + + api-provision-key6 + + + + + + CompanyQuota + Billing + + + + + + CompanyQuota + Billing + + + + + +]]>200/response/idapi-provision-auth6falsefalsefalse/response/statusSUCCESSfalsefalsefalse + <xml-fragment/>http://${#Project#E3Manager}:8181 + api-provision-p6 + + api-provision-api6 + + + + api-provision-auth6 + + + + + active + + active + reject + 98 + 1000 + + + + active + + + +]]>200/response/idapi-provision-p6falsefalsefalse/response/statusSUCCESSfalsefalsefalse + + + + + + <entry key="SIZE" value="10" xmlns="http://eviware.com/soapui/config"/> + + http://${#Project#E3Gateway}/api-provision-endpoint6?key=api-provision-key6 + + + + 200 + + + /data9876543210falsefalsefalse + + + + + + + + + + + <xml-fragment xmlns:con="http://eviware.com/soapui/config"> + <con:entry key="X-App-AuthKey" value="api-provision-key6"/> + <con:entry key="SIZE" value="10"/> +</xml-fragment> + + http://${#Project#E3Gateway}/api-provision-endpoint6 + + + + 200 + + + /data9876543210falsefalsefalse + + + + + + + + + + + + + + + +]]> + + + http://${#Project#E3Manager}:8181 + + api-provision-api6 + test_route_1 + PassThrough + active + api-provision-endpoint6_2 + false + + + authKey + + + key + + + + false + + + + active + + + http://${#Project#Target1}:8080/proxySize + + NoAuth + + key000Val + + + + + 10000 + 0.0 + 600000 + 0.0 + + + + + + + CompanyQuota + Billing + + + + + + CompanyQuota + Billing + + + +]]> + + + /response/status + SUCCESS + false + false + false + + + + + 200 + + + + /response/idapi-provision-api6falsefalsefalse + + + + + + + + + + + + + <entry key="SIZE" value="10" xmlns="http://eviware.com/soapui/config"/> + + http://${#Project#E3Gateway}/api-provision-endpoint6_2?key=api-provision-key6 + + + 200 + + /data9876543210falsefalsefalse + + + + + + + + + + + + + + +]]> + + + http://${#Project#E3Manager}:8181 + + api-provision-api6 + test_route_1 + PassThrough + active + api-provision-endpoint6_2 + false + + + authKey + + + key + header + + + + false + + + + active + + + http://${#Project#Target1}:8080/proxySize + + NoAuth + + key000Val + + + + + 10000 + 0.0 + 600000 + 0.0 + + + + + + + CompanyQuota + Billing + + + + + + CompanyQuota + Billing + + + +]]> + + + /response/status + SUCCESS + false + false + false + + + + + 200 + + + + /response/idapi-provision-api6falsefalsefalse + + + + + + + + + + + + <entry key="SIZE" value="10" xmlns="http://eviware.com/soapui/config"/> + + http://${#Project#E3Gateway}/api-provision-endpoint6_2?key=api-provision-key6 + + + 200 + + /data9876543210falsefalsefalse + + + + + + + + + + <xml-fragment xmlns:con="http://eviware.com/soapui/config"> + <con:entry key="SIZE" value="10"/> + <con:entry key="header" value="api-provision-key6"/> +</xml-fragment> + + http://${#Project#E3Gateway}/api-provision-endpoint6_2 + + + 200 + + /data9876543210falsefalsefalse + + + + + + + + + + <entry key="SIZE" value="10" xmlns="http://eviware.com/soapui/config"/> + + http://${#Project#E3Gateway}/api-provision-endpoint6_2 + + + 401 + + + + + + + + + + + + + + + + +]]> + + http://${#Project#E3Manager}:8181 + + + 200 + + + + + /response/status + SUCCESS + false + false + false + + + + + + + + + + + + + <xml-fragment/> + + http://${#Project#E3Gateway}/api-provision-api6_2?key=api-provision-key6 + + + 404 + + + + + + + <xml-fragment/>http://${#Project#E3Manager}:8181200/response/statusSUCCESSfalsefalsefalse<xml-fragment/>http://${#Project#E3Manager}:8181200/response/statusSUCCESSfalsefalsefalse + + + TestCase generated for REST Resource [/apis] located + at [/apis] + + + + + + + + + + + +]]> + + + http://${#Project#E3Manager}:8181 + + + + + + + + <xml-fragment/>http://${#Project#E3Manager}:8181 + <xml-fragment/>http://${#Project#E3Manager}:8181<xml-fragment/>http://${#Project#E3Manager}:8181 + + + + + + + + + +]]> + + http://${#Project#E3Manager}:8181 + + api-provision-api7 + test_route_1 + PassThrough + active + api-provision-endpoint7 + false + + + authKey + + + key + + + + false + + + + active + + + http://${#Project#Target1}:8080/proxySize + + NoAuth + + key000Val + + + + + 10000 + 0.0 + 600000 + 0.0 + + + + + + + CompanyQuota + Billing + + + + + + CompanyQuota + Billing + + + +]]> + + + 200 + + + + + /response/status + SUCCESS + false + false + false + + + + /response/idapi-provision-api7falsefalsefalse + + + + + + + <xml-fragment/>http://${#Project#E3Manager}:8181 + api-provision-auth7 + active + authKey + + + + + api-provision-key7 + + + + + + CompanyQuota + Billing + + + + + + CompanyQuota + Billing + + + + + +]]>200/response/idapi-provision-auth7falsefalsefalse/response/statusSUCCESSfalsefalsefalse + <xml-fragment/>http://${#Project#E3Manager}:8181 + api-provision-p7 + + api-provision-api7 + + + + + active + + active + reject + 98 + 1000 + + + + active + + + +]]>200/response/idapi-provision-p7falsefalsefalse/response/statusSUCCESSfalsefalsefalse + <xml-fragment/>http://${#Project#E3Manager}:8181 + api-provision-p7_2 + + api-provision-api7 + + + + + + + active + + active + reject + 98 + 1000 + + + + active + + +]]>/response + api-provision-p7_2 + SUCCESS +]]>falsefalsefalse200 + + + + + <entry key="SIZE" value="10" xmlns="http://eviware.com/soapui/config"/> + + http://${#Project#E3Gateway}/api-provision-endpoint7?key=api-provision-key7 + + + 403 + + /data9876543210falsefalsefalse + + + + + + + + + + + + + + + +]]> + + + http://${#Project#E3Manager}:8181 + + api-provision-api7 + test_route_1 + PassThrough + active + api-provision-endpoint7_2 + false + + + authKey + + + key + + + + false + + + + active + + + http://${#Project#Target1}:8080/proxySize + + NoAuth + + key000Val + + + + + 10000 + 0.0 + 600000 + 0.0 + + + + + + + CompanyQuota + Billing + + + + + + CompanyQuota + Billing + + + +]]> + + + /response/status + SUCCESS + false + false + false + + + + + 200 + + + + /response/idapi-provision-api7falsefalsefalse + + + + + + + + + + + + + <entry key="SIZE" value="10" xmlns="http://eviware.com/soapui/config"/> + + http://${#Project#E3Gateway}/api-provision-endpoint7_2?key=api-provision-key7 + + + 403 + + + + + + + + + + + + + + + + + +]]> + + http://${#Project#E3Manager}:8181 + + + 200 + + + + + /response/status + SUCCESS + false + false + false + + + + + + + + <xml-fragment/>http://${#Project#E3Manager}:8181200/response/statusSUCCESSfalsefalsefalse<xml-fragment/>http://${#Project#E3Manager}:8181200/response/statusSUCCESSfalsefalsefalse<xml-fragment/>http://${#Project#E3Manager}:8181 + + + TestCase generated for REST Resource [/apis] located + at [/apis] + + + + + + + + + + + +]]> + + + http://${#Project#E3Manager}:8181 + + + + + + + + + + + + + + + + + +]]> + + http://${#Project#E3Manager}:8181 + + api-provision-api8 + test_route_1 + PassThrough + active + api-provision-endpoint8 + false + + + noAuth + + + + true + + + + active + + + http://${#Project#Target1}:8080/proxySize + + NoAuth + + key000Val + + + + + 10000 + 0.0 + 600000 + 0.0 + + + + + + + CompanyQuota + Billing + + + + + + CompanyQuota + Billing + + + +]]> + + + 200 + + + + + /response/status + SUCCESS + false + false + false + + + + /response/idapi-provision-api8falsefalsefalse + + + + + + + + + + + + + <entry key="SIZE" value="10" xmlns="http://eviware.com/soapui/config"/> + + http://${#Project#E3Gateway}/api-provision-endpoint8 + + + + 200 + + + /data9876543210falsefalsefalse + + + + + + + + + + + + + + + +]]> + + + http://${#Project#E3Manager}:8181 + + api-provision-api8 + test_route_1 + PassThrough + active + api-provision-endpoint8_2 + false + + + noAuth + + + + true + + + + active + + + http://${#Project#Target1}:8080/proxySize + + NoAuth + + key000Val + + + + + 10000 + 0.0 + 600000 + 0.0 + + + + + + + CompanyQuota + Billing + + + + + + CompanyQuota + Billing + + + +]]> + + + /response/status + SUCCESS + false + false + false + + + + + 200 + + + + /response/idapi-provision-api8falsefalsefalse + + + + + + + + + + + + + <entry key="SIZE" value="10" xmlns="http://eviware.com/soapui/config"/> + + http://${#Project#E3Gateway}/api-provision-endpoint8_2?key=api-provision-key8 + + + + 200 + + + /data9876543210falsefalsefalse + + + + + + + + + + + + + + + +]]> + + http://${#Project#E3Manager}:8181 + + + + 200 + + + + + + /response/status + SUCCESS + false + false + false + + + + + + + + + + + + + + <xml-fragment/> + + http://${#Project#E3Gateway}/api-provision-endpoint8_2?key=api-provision-key8 + + + + 404 + + + + + + + + + + + + TestCase generated for REST Resource [/apis] located + at [/apis] + + + + + + + + + + + +]]> + + + http://${#Project#E3Manager}:8181 + + + + + + + + + + + + + + + + + +]]> + + http://${#Project#E3Manager}:8181 + + api-provision-api9 + test_route_1 + PassThrough + active + api-provision-endpoint9 + false + + + noAuth + + + + false + + + + active + + + http://${#Project#Target1}:8080/proxySize + + NoAuth + + key000Val + + + + + 10000 + 0.0 + 600000 + 0.0 + + + + + + + CompanyQuota + Billing + + + + + + CompanyQuota + Billing + + + +]]> + + 200 + + + + /response/status + SUCCESS + false + false + false + + + + /response/idapi-provision-api9falsefalsefalse + + + + + + + + + + + + + <entry key="SIZE" value="10" xmlns="http://eviware.com/soapui/config"/> + + http://${#Project#E3Gateway}/api-provision-endpoint9 + + + + 200 + + + /data9876543210falsefalsefalse + + + + + + + + + + + + + + + +]]> + + + http://${#Project#E3Manager}:8181 + + api-provision-api9 + test_route_1 + PassThrough + active + api-provision-endpoint9_2 + false + + + noAuth + + + + false + + + + active + + + http://${#Project#Target1}:8080/proxySize + + NoAuth + + key000Val + + + + + 10000 + 0.0 + 600000 + 0.0 + + + + + + + CompanyQuota + Billing + + + + + + CompanyQuota + Billing + + + +]]> + + + /response/status + SUCCESS + false + false + false + + + + 200 + + + /response/idapi-provision-api9falsefalsefalse + + + + + + + + + + + + + <entry key="SIZE" value="10" xmlns="http://eviware.com/soapui/config"/> + + http://${#Project#E3Gateway}/api-provision-endpoint9_2 + + + + 200 + + + /data9876543210falsefalsefalse + + + + + + + + + + + + + + + +]]> + + http://${#Project#E3Manager}:8181 + + + + 200 + + + + + + /response/status + SUCCESS + false + false + false + + + + + + + + + + + + + + <xml-fragment/> + + http://${#Project#E3Gateway}/api-provision-endpoint9_2?key=api-provision-key9 + + + + 404 + + + + + + + + + + + + TestCase generated for REST Resource [/apis] located + at [/apis] + + + + + + + + + + + +]]> + + + http://${#Project#E3Manager}:8181 + + + + + + + + + + + + + + + + + +]]> + + http://${#Project#E3Manager}:8181 + + api-provision-api10 + test_route_1 + PassThrough + active + api-provision-endpoint10 + false + + + noAuth + + + + false + + + + active + + + http://${#Project#Target1}:8080/proxySize + + NoAuth + + key000Val + + + + + 10000 + 0.0 + 600000 + 0.0 + + + + + + + CompanyQuota + Billing + + + + + + CompanyQuota + Billing + + + + + apipropvalue1 + apipropvalue2 + +]]> + + 200 + + + + /response/status + SUCCESS + false + false + false + + + + /response/idapi-provision-api10falsefalsefalse + + + + + + + + + + + + + + + + + +]]> + + http://${#Project#E3Manager}:8181 + + + 200 + + + + /response/status + SUCCESS + false + false + false + + + + /response/api/idapi-provision-api10falsefalsefalse + + /response/api/properties/propertyapipropvalue1falsefalsefalse/response/api/properties/propertyapipropvalue2falsefalsefalse + + + + + + + + + + + <entry key="SIZE" value="10" xmlns="http://eviware.com/soapui/config"/> + + http://${#Project#E3Gateway}/api-provision-endpoint10 + + + + 200 + + + /data9876543210falsefalsefalse + + + + + + + + + + + + + + + +]]> + + + http://${#Project#E3Manager}:8181 + + api-provision-api10 + test_route_1 + PassThrough + active + api-provision-endpoint10_2 + false + + + noAuth + + + + false + + + + active + + + http://${#Project#Target1}:8080/proxySize + + NoAuth + + key000Val + + + + + 10000 + 0.0 + 600000 + 0.0 + + + + + + + CompanyQuota + Billing + + + + + + CompanyQuota + Billing + + + + + apipropvalue3 + apipropvalue4 + +]]> + + + /response/status + SUCCESS + false + false + false + + + + + 200 + + + + /response/idapi-provision-api10falsefalsefalse + + + + + + + + + + + + + + + + + +]]> + + http://${#Project#E3Manager}:8181 + + + 200 + + + + /response/status + SUCCESS + false + false + false + + + + /response/api/idapi-provision-api10falsefalsefalse + + /response/api/properties/propertyapipropvalue3falsefalsefalse/response/api/properties/propertyapipropvalue4falsefalsefalse + + + + + + + + + + + <entry key="SIZE" value="10" xmlns="http://eviware.com/soapui/config"/> + + http://${#Project#E3Gateway}/api-provision-endpoint10_2 + + + + 200 + + + /data9876543210falsefalsefalse + + + + + + + + + + + + + + + +]]> + + http://${#Project#E3Manager}:8181 + + + + 200 + + + + + + /response/status + SUCCESS + false + false + false + + + + + + + + + + + + + <xml-fragment/> + + http://${#Project#E3Gateway}/api-provision-endpoint10_2?key=api-provision-key10 + + + 404 + + + + + + + + + + + TestCase generated for REST Resource [/apis] located + at [/apis] + + + + + + + + + + + +]]> + + + http://${#Project#E3Manager}:8181 + + + + + + + + + + + + + + + + + +]]> + + http://${#Project#E3Manager}:8181 + + api-provision-api11 + test_route_1 + PassThrough + active + api-provision-endpoint11 + false + + + noAuth + + + + false + + + + active + + + http://${#Project#Target1}:8080/proxySize + + NoAuth + + key000Val + + + + + 10000 + 0.0 + 600000 + 0.0 + + + + + + + CompanyQuota + Billing + + + + + + CompanyQuota + Billing + + + + + + + + + + + +]]> + + 200 + + + + /response/status + SUCCESS + false + false + false + + + + /response/idapi-provision-api11falsefalsefalse + + + + + + + + + + + + + + + + + +]]> + + http://${#Project#E3Manager}:8181 + + + 200 + + + + /response/status + SUCCESS + false + false + false + + + + /response/api/idapi-provision-api11falsefalsefalse + + /response/api/headerTransformations/headerTransformation<headerTransformation name="apitransfname1" value="apitransfvalue1" type="Request" action="Add"/>falsefalsefalse/response/api/headerTransformations/headerTransformation <headerTransformation name="apitransfname2" property="apitransfprop2" type="Request" action="Add"/>falsefalsefalse/response/api/headerTransformations/headerTransformation <headerTransformation name="apitransfname3" property="apitransfprop3" type="Response" action="Add"/>falsefalsefalse/response/api/headerTransformations/headerTransformation <headerTransformation name="apitransfname4" value="apitransfvalue4" type="Response" action="Add"/>falsefalsefalse/response/api/headerTransformations/headerTransformation <headerTransformation name="apitransfname5" type="Request" action="Remove"/>falsefalsefalse/response/api/headerTransformations/headerTransformation <headerTransformation name="apitransfname6" type="Response" action="Remove"/>falsefalsefalse + + + + + + + + + + + <entry key="SIZE" value="10" xmlns="http://eviware.com/soapui/config"/> + + http://${#Project#E3Gateway}/api-provision-endpoint11 + + + + 200 + + + /data9876543210falsefalsefalse + + + + + + + + + + + + + + + +]]> + + + http://${#Project#E3Manager}:8181 + + api-provision-api11 + test_route_1 + PassThrough + active + api-provision-endpoint11_2 + false + + + noAuth + + + + false + + + + active + + + http://${#Project#Target1}:8080/proxySize + + NoAuth + + key000Val + + + + + 10000 + 0.0 + 600000 + 0.0 + + + + + + + CompanyQuota + Billing + + + + + + CompanyQuota + Billing + + + + + + + + + + + +]]> + + + /response/status + SUCCESS + false + false + false + + + + + 200 + + + + /response/idapi-provision-api11falsefalsefalse + + + + + + + + + + + + + + + + + + +]]> + + http://${#Project#E3Manager}:8181 + + + 200 + + + + /response/status + SUCCESS + false + false + false + + + + /response/api/idapi-provision-api11falsefalsefalse + + /response/api/headerTransformations/headerTransformation<headerTransformation name="apitransfname7" value="apitransfvalue7" type="Request" action="Add"/>falsefalsefalse/response/api/headerTransformations/headerTransformation <headerTransformation name="apitransfname8" property="apitransfprop8" type="Request" action="Add"/>falsefalsefalse/response/api/headerTransformations/headerTransformation <headerTransformation name="apitransfname9" property="apitransfprop9" type="Response" action="Add"/>falsefalsefalse/response/api/headerTransformations/headerTransformation <headerTransformation name="apitransfname10" value="apitransfvalue10" type="Response" action="Add"/>falsefalsefalse/response/api/headerTransformations/headerTransformation <headerTransformation name="apitransfname11" type="Request" action="Remove"/>falsefalsefalse/response/api/headerTransformations/headerTransformation <headerTransformation name="apitransfname12" type="Response" action="Remove"/>falsefalsefalse + + + + + + + + + + + <entry key="SIZE" value="10" xmlns="http://eviware.com/soapui/config"/> + + http://${#Project#E3Gateway}/api-provision-endpoint11_2 + + + 200 + + /data9876543210falsefalsefalse + + + + + + + + + + + + + + +]]> + + http://${#Project#E3Manager}:8181 + + + + 200 + + + + + + /response/status + SUCCESS + false + false + false + + + + + + + + + + + + + <xml-fragment/> + + http://${#Project#E3Gateway}/api-provision-endpoint11_2?key=api-provision-key11 + + + 404 + + + + + + + + + TestCase generated for REST Resource [/apis] located + at [/apis] + + + + + + + + + + + +]]> + + + http://${#Project#E3Manager}:8181 + + + + + + + + + + + + + + + + + +]]> + + http://${#Project#E3Manager}:8181 + + api-provision-api12 + test_route_1 + PassThrough + active + api-provision-endpoint12 + false + + + noAuth + + + + false + + + + active + + + http://${#Project#Target1}:8080/proxySize + + NoAuth + + key000Val + + + + + 10000 + 0.0 + 600000 + 0.0 + + + + + + + CompanyQuota + Billing + + + + + + CompanyQuota + Billing + + + + + + + + + + + + + GET + POST + PUT + DELETE + +]]> + + 200 + + + + /response/status + SUCCESS + false + false + false + + + + /response/idapi-provision-api12falsefalsefalse + + + + + + + + + + + + + + + + + +]]> + + http://${#Project#E3Manager}:8181 + + + 200 + + + + /response/status + SUCCESS + false + false + false + + + + /response/api/idapi-provision-api12falsefalsefalse + + /response/api/allowedHttpMethods/httpMethodGETfalsefalsefalse/response/api/allowedHttpMethods/httpMethodPOSTfalsefalsefalse/response/api/allowedHttpMethods/httpMethodPUTfalsefalsefalse/response/api/allowedHttpMethods/httpMethodDELETEfalsefalsefalse<httpMethod>HEAD</httpMethod>falsefalse + + + + + + + + + + + <entry key="SIZE" value="10" xmlns="http://eviware.com/soapui/config"/> + + http://${#Project#E3Gateway}/api-provision-endpoint12 + + + + 200 + + + /data9876543210falsefalsefalse + + + + + + + + + + + + + + + +]]> + + + http://${#Project#E3Manager}:8181 + + api-provision-api12 + test_route_1 + PassThrough + active + api-provision-endpoint12_2 + false + + + noAuth + + + + false + + + + active + + + http://${#Project#Target1}:8080/proxySize + + NoAuth + + key000Val + + + + + 10000 + 0.0 + 600000 + 0.0 + + + + + + + CompanyQuota + Billing + + + + + + CompanyQuota + Billing + + + + + + + + + + + + + GET + HEAD + TRACE + OPTIONS + CONNECT + PATCH + +]]> + + + /response/status + SUCCESS + false + false + false + + + + + 200 + + + + /response/idapi-provision-api12falsefalsefalse + + + + + + + + + + + + + + + + + + +]]> + + http://${#Project#E3Manager}:8181 + + + 200 + + + + /response/status + SUCCESS + false + false + false + + + + /response/api/idapi-provision-api12falsefalsefalse + + /response/api/allowedHttpMethods/httpMethodGETfalsefalsefalse/response/api/allowedHttpMethods/httpMethodHEADfalsefalsefalse/response/api/allowedHttpMethods/httpMethodTRACEfalsefalsefalse/response/api/allowedHttpMethods/httpMethodOPTIONSfalsefalsefalse/response/api/allowedHttpMethods/httpMethodCONNECTfalsefalsefalse/response/api/allowedHttpMethods/httpMethodPATCHfalsefalsefalse<httpMethod>POST</httpMethod>falsefalse + + + + + + + + + + <entry key="SIZE" value="10" xmlns="http://eviware.com/soapui/config"/> + + http://${#Project#E3Gateway}/api-provision-endpoint12_2 + + + + 200 + + + /data9876543210falsefalsefalse + + + + + + + + + + + + + + +]]> + + http://${#Project#E3Manager}:8181 + + + + 200 + + + + + + /response/status + SUCCESS + false + false + false + + + + + + + + + + + + + <xml-fragment/> + + http://${#Project#E3Gateway}/api-provision-endpoint12_2?key=api-provision-key12 + + + 404 + + + + + + + + + + + TestCase generated for REST Resource [/apis] located + at [/apis] + + + + + + + + + + + +]]> + + http://${#Project#E3Manager}:8181 + + test_route_1 + PassThrough + api-provision-endpoint13 + active + false + + + noAuth + + + + false + + + + active + + + http://${#Project#Target1}:8080/proxySize + + NoAuth + + key000Val + + + + + 10000 + 0.0 + 600000 + 0.0 + + + + + + + CompanyQuota + Billing + + + + + + CompanyQuota + Billing + + + +]]> + + 200 + + + + /response/status + SUCCESS + false + false + false + + + + + + + + + + + + + + <entry key="SIZE" value="10" xmlns="http://eviware.com/soapui/config"/> + + http://${#Project#E3Gateway}/api-provision-endpoint13 + + + + 200 + + + /data9876543210falsefalsefalse + + + + + + + + + + apiID + ResponseAsXml + Request - Create API + /response/id + API_ID + Request - Update API + + + + + + + + + apiID + ResponseAsXml + Request - Create API + /response/id + Request + Request - Update API + /api/id + + + + + + + + apiID + ResponseAsXml + Request - Create API + /response/id + API_ID + Request - Delete API + + + + + + + + + + + + + +]]> + + + http://${#Project#E3Manager}:8181 + + 525984b0787348a0a842ec62d9696da4 + test_route_1 + PassThrough + active + api-provision-endpoint13_2 + false + + + noAuth + + + + false + + + + active + + + http://${#Project#Target1}:8080/proxySize + + NoAuth + + key000Val + + + + + 10000 + 0.0 + 600000 + 0.0 + + + + + + + CompanyQuota + Billing + + + + + + CompanyQuota + Billing + + + +]]> + + + /response/status + SUCCESS + false + false + false + + + + + 200 + + + + + + + + + + + + + + <entry key="SIZE" value="10" xmlns="http://eviware.com/soapui/config"/> + + http://${#Project#E3Gateway}/api-provision-endpoint13_2 + + + + 200 + + + /data9876543210falsefalsefalse + + + + + + + + + + + + + + + +]]> + + http://${#Project#E3Manager}:8181 + + + + 200 + + + + + /response/status + SUCCESS + false + false + false + + + + + + + + + + + + + + <xml-fragment/> + + http://${#Project#E3Gateway}/api-provision-endpoint13_2?key=api-provision-key13 + + + + 404 + + + + + + + + + + + + + TestCase generated for REST Resource [/apis] located + at [/apis] + + + + + + + + +]]> + + http://${#Project#E3Manager}:8181 + + + + + + + + + + + + + + + + + + + + + + + +]]> + + http://${#Project#E3Manager}:8181 + + api-provision-api14 + test_route_1 + PassThrough + active + api-provision-endpoint14 + false + + + noAuth + + + + false + + + + active + + + http://${#Project#Target1}:8080/proxySize + + NoAuth + + key000Val + + + + + 10000 + 0.0 + 600000 + 0.0 + + + active + + + http://${#Project#Target1}:8080/proxySize + + NoAuth + + key000Val + + + + + 10000 + 0.0 + 600000 + 0.0 + + + + + + + CompanyQuota + Billing + + + + + + CompanyQuota + Billing + + + +]]> + + 500 + + + /response/statusFAILUREfalsefalsefalse + + + + + + + + + + + + + + + + +]]> + + http://${#Project#E3Manager}:8181 + + api-provision-api14 + test_route_1 + PassThrough + active + api-provision-endpoint14 + false + + + noAuth + + + + false + + + + active + + + http://${#Project#Target1}:8080/proxySize + + NoAuth + + key000Val + + + + + 10000 + 0.0 + 600000 + 0.0 + + + active + + + http://${#Project#Target1}:8080/proxySize + + NoAuth + + key000Val + + + + + 10000 + 0.0 + 600000 + 0.0 + + + + + + + CompanyQuota + Billing + + + + + + CompanyQuota + Billing + + + +]]> + + 500 + + + /response/statusFAILUREfalsefalsefalse + + + + + + + + + TestCase generated for REST Resource [/apis] located + at [/apis] + + + + + + + + + + + +]]> + + + http://${#Project#E3Manager}:8181 + + + + + + + + + + + + + + + + + +]]> + + http://${#Project#E3Manager}:8181 + + api-provision-api15 + test_composite_route + Composite + active + api-provision-endpoint15 + false + + + noAuth + + + + false + + + + active + + + http://${#Project#Target1}:8080/compositeEndpoint + + NoAuth + + key000Val + + + + + 10000 + 0.0 + 600000 + 0.0 + + + + + + + CompanyQuota + Billing + + + + + + CompanyQuota + Billing + + + + + + + +]]> + + 200 + + + + /response/status + SUCCESS + false + false + false + + + + /response/idapi-provision-api15falsefalsefalse + + + + + + + + + + + 1000<xml-fragment/>http://${#Project#E3Gateway}/api-provision-endpoint15200// check that OAP_StatusCode header is not present +// it must be removed by E3 +assert messageExchange.responseHeaders["OAP_StatusCode"] == nullexists(/data/correlationId)truefalsefalsefalseE3Test-InjectOAPStatusCodeHeadertrueHEADERxs:string + + + + + + + + + + + +]]> + + http://${#Project#E3Manager}:8181 + + + + 200 + + + + + + /response/status + SUCCESS + false + false + false + + + + + + + + + + TestCase to create API using minimal xml [/apis] located + at [/apis] + + + + + + + + + + + + + + +]]> + + http://${#Project#E3Manager}:8181 + + PassThrough + api-provision-api16 + + + noAuth + + + active + + + active + + + http://${#Project#Target1}:8080/proxySize + + + http://${#Project#Target2}:8080/proxySize + + + 214748364 + 0 + 214748364 + 0 + + + active + + + http://${#Project#Target1}:8080/proxySize + + + http://${#Project#Target2}:8080/proxySize + + + 214748364 + 0 + 214748364 + 0 + + +]]> + + 200 + + + + /response/status + SUCCESS + false + false + false + + + + + + + + + + + + + + + + apiID + ResponseAsXml + Request - Create API minimal + /response/id + API_ID + Delete API + + + + + + + + + + + + +]]> + + http://${#Project#E3Manager}:8181 + + + + 200 + + + + + /response/status + SUCCESS + false + false + false + + + + + + + + + + TestCase generated for REST Resource [/apis] located + at [/apis] + + + + + + + + + + + +]]> + + + http://${#Project#E3Manager}:8181 + + + + + + + + + + + + + + + + + +]]> + + http://${#Project#E3Manager}:8181 + + api-provision-api17 + test_composite_route + PassThrough + Notification + Header + active + api-provision-endpoint17 + false + + + noAuth + + + + false + + + + active + 10000 + 0.0 + 600000 + 0.0 + + + + + + + CompanyQuota + Billing + + + + + + CompanyQuota + Billing + + + +]]> + + 200 + + + + /response/status + SUCCESS + false + false + false + + + + /response/idapi-provision-api17falsefalsefalse + + + + + + + + + + + <xml-fragment xmlns:con="http://eviware.com/soapui/config"> + <con:entry key="SIZE" value="9"/> + <con:entry key="notifyUrl" value="http://${#Project#Target1}:8080/parametersEndpoint.php?param=test1"/> +</xml-fragment>http://${#Project#E3Gateway}/api-provision-endpoint17200// check that OAP_StatusCode header is not present +// it must be removed by E3 +assert messageExchange.responseHeaders["OAP_StatusCode"] == null/response/data876543210falsefalsefalse/response/parameters/parameter[@key='param' and @type='get']test1falsefalsefalse + + + + + + + + + + + +]]> + + http://${#Project#E3Manager}:8181 + + api-provision-api17 + test_composite_route + PassThrough + Notification + WS-Addressing + active + api-provision-endpoint17 + false + + + noAuth + + + + false + + + + active + 10000 + 0.0 + 600000 + 0.0 + + + + + + + CompanyQuota + Billing + + + + + + CompanyQuota + Billing + + + +]]> + + 200 + + + + /response/status + SUCCESS + false + false + false + + + + /response/idapi-provision-api17falsefalsefalse + + + + + + + <entry key="SIZE" value="7" xmlns="http://eviware.com/soapui/config"/>http://${#Project#E3Gateway}/api-provision-endpoint17 +

    +http://${#Project#Target1}:8080/parametersEndpoint.php?param=test2 +http://wso2.org/wsf/c/addr/order + +
    http://localhost:9090/axis2/services/billing_service
    +
    + +
    http://localhost:9090/axis2/services/reorder_service
    +
    +a4dfb94a-593b-1dc1-36d2-000000000000 +
    + + +paper +100 + + +]]>200// check that OAP_StatusCode header is not present +// it must be removed by E3 +assert messageExchange.responseHeaders["OAP_StatusCode"] == null/response/data6543210falsefalsefalse/response/parameters/parameter[@key='param' and @type='get']test2falsefalsefalse<entry key="SIZE" value="6" xmlns="http://eviware.com/soapui/config"/>http://${#Project#E3Gateway}/api-provision-endpoint17 + +http://${#Project#Target1}:8080/parametersEndpoint.php?param=test3 + + + +paper +100 + + +]]>200// check that OAP_StatusCode header is not present +// it must be removed by E3 +assert messageExchange.responseHeaders["OAP_StatusCode"] == null/response/data543210falsefalsefalse/response/parameters/parameter[@key='param' and @type='get']test3falsefalsefalse<entry key="SIZE" value="5" xmlns="http://eviware.com/soapui/config"/>http://${#Project#E3Gateway}/api-provision-endpoint17 + +http://${#Project#Target1}:8080/parametersEndpoint.php?param=test4 + + + +paper +100 + + +]]>200// check that OAP_StatusCode header is not present +// it must be removed by E3 +assert messageExchange.responseHeaders["OAP_StatusCode"] == null/response/data43210falsefalsefalse/response/parameters/parameter[@key='param' and @type='get']test4falsefalsefalse + + + + + + + + + +]]> + + http://${#Project#E3Manager}:8181 + + + + 200 + + + + + + /response/status + SUCCESS + false + false + false + + + + + + + + + + TestCase generated for REST Resource [/apis] located + at [/apis] + + + + + + + + + + + +]]> + + http://${#Project#E3Manager}:8181 + + + + + + + + + + + <xml-fragment/>http://${#Project#E3Manager}:8181 + <xml-fragment/>http://${#Project#E3Manager}:8181 + + + + + + + + + + +]]> + + http://${#Project#E3Manager}:8181 + + api-provision-api18 + test_route_1 + PassThrough + active + api-provision-endpoint18 + false + + + authKey + + + key + + + + true + + + + active + + + http://${#Project#Target1}:8080/proxySize + + NoAuth + + key000Val + + + + + + 10000 + -1 + 600000 + -1 + + + + + + + + CompanyQuota + Billing + + + + + + CompanyQuota + Billing + + + + + + CompanyQuota + Billing + + + + + request + response + + + + + + + + + + + + + localhost + 12345 + hoopla + blargblarg + + +]]> + + + 200 + + + + + /response/status + SUCCESS + false + false + false + + + + /response/idapi-provision-api18falsefalsefalse + + + + + + + + <xml-fragment/>http://${#Project#E3Manager}:8181 + api-provision-auth18 + active + authKey + + + + api-provision-key18 + + + + + + CompanyQuota + Billing + + + + + + CompanyQuota + Billing + + + +]]>200/response/idapi-provision-auth18falsefalsefalse/response/statusSUCCESSfalsefalsefalse + <xml-fragment/>http://${#Project#E3Manager}:8181 + api-provision-p18 + + api-provision-api18 + + + + api-provision-auth18 + + + + + active + + active + reject + 98 + 1000 + + + + active + + + +]]>200/response/idapi-provision-p18falsefalsefalse/response/statusSUCCESSfalsefalsefalse + + + + + + <entry key="SIZE" value="10" xmlns="http://eviware.com/soapui/config"/> + + http://${#Project#E3Gateway}/api-provision-endpoint18?key=api-provision-key18 + + + 200 + + /data9876543210falsefalsefalse + + + + + + + + + + + + + + +]]> + + + http://${#Project#E3Manager}:8181 + + api-provision-api18 + test_route_1 + PassThrough + active + api-provision-endpoint18_2 + false + + + authKey + + + key + + + + true + + + + active + + + http://${#Project#Target1}:8080/proxySize + + NoAuth + + key000Val + + + + + + 10000 + 0.0 + 600000 + 0.0 + + + + + + + CompanyQuota + Billing + + + + + + CompanyQuota + Billing + + + + + + + localhost123 + 12345 + hoopla + blargblarg + + + +]]> + + + /response/status + SUCCESS + false + false + false + + + + + 200 + + + + /response/idapi-provision-api18falsefalsefalse + + + + + + + + + + + + <entry key="SIZE" value="10" xmlns="http://eviware.com/soapui/config"/> + + http://${#Project#E3Gateway}/api-provision-endpoint18_2?key=api-provision-key18 + + + + 200 + + + /data9876543210falsefalsefalse + + + + + + + + + + + + + + +]]> + + http://${#Project#E3Manager}:8181 + + + + 200 + + + + + + /response/status + SUCCESS + false + false + false + + + + + + + + <xml-fragment/>http://${#Project#E3Manager}:8181200/response/statusSUCCESSfalsefalsefalse<xml-fragment/>http://${#Project#E3Manager}:8181200/response/statusSUCCESSfalsefalsefalse + + TestCase generated for REST Resource [/apis] located + at [/apis] + + + + + + + + + + + +]]> + + http://${#Project#E3Manager}:8181 + + + + + + + + + + + <xml-fragment/>http://${#Project#E3Manager}:8181 + <xml-fragment/>http://${#Project#E3Manager}:8181 + + + + + + + + + + +]]> + + http://${#Project#E3Manager}:8181 + + api-provision-api19 + test_route_1 + PassThrough + active + api-provision-endpoint19 + false + + + authKey + + + key + + + + true + + + + active + + + http://${#Project#Target1}:8080/proxySize + + NoAuth + + key000Val + + + + 10 + 1000 + 1000 + + + + 10000 + -1 + 600000 + -1 + + + + + + + + CompanyQuota + Billing + + + + + + CompanyQuota + Billing + + + + + + CompanyQuota + Billing + + + + + request + response + + + + + + + + + +]]> + + + 200 + + + + + /response/status + SUCCESS + false + false + false + + + + /response/idapi-provision-api19falsefalsefalse + + + + + + + + <xml-fragment/>http://${#Project#E3Manager}:8181 + api-provision-auth19 + active + authKey + + + + api-provision-key19 + + + + + + CompanyQuota + Billing + + + + + + CompanyQuota + Billing + + + +]]>200/response/idapi-provision-auth19falsefalsefalse/response/statusSUCCESSfalsefalsefalse + <xml-fragment/>http://${#Project#E3Manager}:8181 + api-provision-p19 + + api-provision-api19 + + + + api-provision-auth19 + + + + + active + + active + reject + 98 + 1000 + + + + active + + + +]]>200/response/idapi-provision-p19falsefalsefalse/response/statusSUCCESSfalsefalsefalse + + + + + + <entry key="SIZE" value="10" xmlns="http://eviware.com/soapui/config"/> + + http://${#Project#E3Gateway}/api-provision-endpoint19?key=api-provision-key19 + + + 200 + + /data9876543210falsefalsefalse + + + + + + + + + + + + + + +]]> + + + http://${#Project#E3Manager}:8181 + + api-provision-api19 + test_route_1 + PassThrough + active + api-provision-endpoint19_2 + false + + + authKey + + + key + + + + true + + + + active + + + http://${#Project#Target1}:8080/proxySize + + NoAuth + + key000Val + + + + 20 + 2000 + 2000 + + + + 10000 + 0.0 + 600000 + 0.0 + + + + + + + CompanyQuota + Billing + + + + + + CompanyQuota + Billing + + + +]]> + + + /response/status + SUCCESS + false + false + false + + + + + 200 + + + + /response/idapi-provision-api19falsefalsefalse + + + + + + + + + + + + <entry key="SIZE" value="10" xmlns="http://eviware.com/soapui/config"/> + + http://${#Project#E3Gateway}/api-provision-endpoint19_2?key=api-provision-key19 + + + + 200 + + + /data9876543210falsefalsefalse + + + + + + + + + + + + + + +]]> + + http://${#Project#E3Manager}:8181 + + + + 200 + + + + + + /response/status + SUCCESS + false + false + false + + + + + + + + <xml-fragment/>http://${#Project#E3Manager}:8181200/response/statusSUCCESSfalsefalsefalse<xml-fragment/>http://${#Project#E3Manager}:8181200/response/statusSUCCESSfalsefalsefalse + + + + + + + + + + + + + +]]> + + + http://${#Project#E3Manager}:8181 + + Global HTTP Settings + + + + + + + + + + + + + + + + + +]]> + + + http://${#Project#E3Manager}:8181 + + Global HTTP Settings + + + + + + + + + + + + + + + + + +]]> + + + http://${#Project#E3Manager}:8181 + + Global HTTP Settings + + + + + + + + + + + + + + + + + +]]> + + + http://${#Project#E3Manager}:8181 + + + + + + + + + + + + + + + + + + + +]]> + + + http://${#Project#E3Manager}:8181 + + + + + + + + + + + + + + + + + +]]> + + + http://${#Project#E3Manager}:8181 + + + + + + + + + + + + + + + + + +]]> + + + http://${#Project#E3Manager}:8181 + + + + + + + + + + + + + + + + + + +]]> + + + http://${#Project#E3Manager}:8181 + + + + + + + + + + + + + + + + +]]> + + + http://${#Project#E3Manager}:8181 + + + + + + + + + + + + + + + + + +]]> + + + http://${#Project#E3Manager}:8181 + + Global HTTP Settings + + + + + + + + + + + + + + +]]> + + + http://${#Project#E3Manager}:8181 + + Global HTTP Settings + + + + + + + + + + + + + + +]]> + + + http://${#Project#E3Manager}:8181 + + Global HTTP Settings + + + + + + + + + + + + + + +]]> + + + http://${#Project#E3Manager}:8181 + + Global HTTP Settings + + + + + + + + + + + + + + +]]> + + + http://${#Project#E3Manager}:8181 + + Global HTTP Settings + + + + + http://${#Project#E3Manager}:8181http://${#Project#E3Manager}:8181<xml-fragment/>http://${#Project#E3Manager}:8181<xml-fragment/>http://${#Project#E3Manager}:8181http://${#Project#E3Manager}:8181http://${#Project#E3Manager}:8181<xml-fragment/>http://${#Project#E3Manager}:8181<xml-fragment/>http://${#Project#E3Manager}:8181http://${#Project#E3Manager}:8181 + + + + + + + + + +]]> + + + http://${#Project#E3Manager}:8181 + + + + + + + + + + + + + +]]> + + http://${#Project#E3Manager}:8181 + + + + + + + + + + + + + + +]]> + + + http://${#Project#E3Manager}:8181 + + + + + + + + + + + + + + + + +]]> + + + http://${#Project#E3Manager}:8181 + + + + + + + <xml-fragment/>http://${#Project#E3Manager}:8181<xml-fragment/>http://${#Project#E3Manager}:8181 + + + + + + + + + +]]> + + + http://${#Project#E3Manager}:8181 + + + + + + + + + http://${#Project#E3Manager}:8181 + + + <xml-fragment/> + http://${#Project#E3Manager}:8181 + + > + PerfTestKey +]]>/response/statusSUCCESSfalsefalsefalse200 + + <xml-fragment/> + http://${#Project#E3Manager}:8181 + + > + Self-Signed Cert +]]>/response/statusSUCCESSfalsefalsefalse200 + <xml-fragment/>http://${#Project#E3Manager}:8181<xml-fragment/>http://${#Project#E3Manager}:8181 + > + cert auth 1 + +]]>200/response/idca1falsefalsefalse/response/statusSUCCESSfalsefalsefalse<xml-fragment/>http://${#Project#E3Manager}:8181<key id="key1"> + <activeCertId>cert1</activeCertId> +</key>/response/statusSUCCESSfalsefalsefalse200<xml-fragment/>http://${#Project#E3Manager}:8181 + auth1 + active + authKey + + + + 288ba0c1e4c34f25bf95733eebd8574f + + + + + + CompanyQuota + Billing + + + + + + CompanyQuota + Billing + + + +]]>200/response/idauth1falsefalsefalse/response/statusSUCCESSfalsefalsefalseGlobal HTTP Settings<xml-fragment/>http://${#Project#E3Manager}:8181 + auth2 + active + authKey + + + + 488ba0c1e4c34f25bf95733eebd8574f + + + + + + CompanyQuota + Billing + + + + + + CompanyQuota + Billing + + + +]]>200/response/idauth2falsefalsefalse/response/statusSUCCESSfalsefalsefalse<xml-fragment/>http://${#Project#E3Manager}:8181 + authBasic + active + basic + + + + tester + + dGVzdGVycGFzc3dvcmQ= + + + + + + CompanyQuota + Billing + + + + + + CompanyQuota + Billing + + + +]]>200/response/statusSUCCESSfalsefalsefalseGlobal HTTP Settings<xml-fragment/>http://${#Project#E3Manager}:8181 + authPerfIp + active + ipWhiteList + + + + 192.168.84.179 + 192.168.84.198 + + + + + + CompanyQuota + Billing + + + + + + CompanyQuota + Billing + + + +]]>200/response/statusSUCCESSfalsefalsefalse + + + + + + + + + +]]> + + http://${#Project#E3Manager}:8181 + + getLocation + test_route_1 + PassThrough + active + endpoint1 + false + + + noAuth + + + + false + + + + active + + + http://${#Project#Target1}:8080/proxySize + + NoAuth + + key000Val + + + + + http://${#Project#Target2}:8080/proxySize + + NoAuth + + key000Val + + + + + http://${#Project#Target3}:8080/proxySize + + NoAuth + + key000Val + + + + + 10000 + 0.0 + 600000 + 0.0 + + + + + + + CompanyQuota + Billing + + + + + + CompanyQuota + Billing + + + +]]> + + + 200 + + + + + /response/status + SUCCESS + false + false + false + + + + + /response/id + getLocation + false + false + false + + + Global HTTP Settings + + + + + + + + + + + + + + +]]> + + http://${#Project#E3Manager}:8181 + + getLocation2 + test_route_2 + PassThrough + active + endpoint2 + false + + + authKey + + + key + + + + false + + + + active + + + http://${#Project#Target1}:8080/proxySize + + + http://${#Project#Target2}:8080/proxySize + + + http://${#Project#Target3}:8080/proxySize + + + 10000 + 0.0 + 600000 + 0.0 + + + + + + + CompanyQuota + Billing + + + + + + CompanyQuota + Billing + + + +]]> + + + 200 + + + + + /response/status + SUCCESS + false + false + false + + + + + /response/id + getLocation2 + false + false + false + + + + + + + + + + + + + + + + + +]]> + + http://${#Project#E3Manager}:8181 + + getLocation3 + test_route_3 + PassThrough + active + endpoint3 + false + + + noAuth + + + + true + + + + active + + + http://${#Project#Target1}:8080/proxySize + + + http://${#Project#Target2}:8080/proxySize + + + http://${#Project#Target3}:8080/proxySize + + + 10000 + 0.0 + 600000 + 0.0 + + + + + + + CompanyQuota + Billing + + + + + + CompanyQuota + Billing + + + +]]> + + + 200 + + + + + /response/status + SUCCESS + false + false + false + + + + + /response/id + getLocation3 + false + false + false + + + Global HTTP Settings + + + + + + + + + + + + + + +]]> + + http://${#Project#E3Manager}:8181 + + getLocation4 + test_route_4 + PassThrough + active + endpoint4 + false + + + authKey + + + key + + + + true + + + + active + + + http://${#Project#Target1}:8080/proxySize + + + http://${#Project#Target2}:8080/proxySize + + + http://${#Project#Target3}:8080/proxySize + + + 10000 + 0.0 + 600000 + 0.0 + + + + + + + CompanyQuota + Billing + + + + + + CompanyQuota + Billing + + + +]]> + + + 200 + + + + + /response/status + SUCCESS + false + false + false + + + + + /response/id + getLocation4 + false + false + false + + + + + + + + + + + + + + + + + +]]> + + http://${#Project#E3Manager}:8181 + + getLocation5 + test_route_5 + PassThrough + active + endpoint5 + false + + + noAuth + + + + false + + + + active + + + http://${#Project#Target1}:8080/proxySize + + NoAuth + + key000Val + + + + + http://${#Project#Target2}:8080/proxySize + + NoAuth + + key000Val + + + + + http://${#Project#Target3}:8080/proxySize + + NoAuth + + key000Val + + + + + 100 + 0.0 + 80000 + 0.0 + + + + + + + CompanyQuota + Billing + + + + + + CompanyQuota + Billing + + + +]]> + + + 200 + + + + + /response/status + SUCCESS + false + false + false + + + + /response/idgetLocation5falsefalsefalse + + + + + + + + + + + + + + + + +]]> + + http://${#Project#E3Manager}:8181 + + getLocation6 + test_route_authbasic + PassThrough + active + endpointauthbasic + false + + + basic + + + + false + + + + active + + + http://${#Project#Target1}:8080/proxySize.php + + + http://${#Project#Target2}:8080/proxySize.php + + + http://${#Project#Target3}:8080/proxySize.php + + + 10000 + 0.0 + 600000 + 0.0 + + + + + + + CompanyQuota + Billing + + + + + + CompanyQuota + Billing + + + +]]> + + 200 + + + + /response/status + SUCCESS + false + false + false + + + + + + + + + + + + + + + + + + +]]> + + http://${#Project#E3Manager}:8181 + + getLocation7 + test_route_authip + PassThrough + active + endpointauthip + false + + + ipWhiteList + + + + false + + + + active + + + http://${#Project#Target1}:8080/proxySize + + + http://${#Project#Target2}:8080/proxySize + + + http://${#Project#Target3}:8080/proxySize + + + 10000 + 0.0 + 600000 + 0.0 + + + + + + + CompanyQuota + Billing + + + + + + CompanyQuota + Billing + + + +]]> + + 200 + + + + /response/status + SUCCESS + false + false + false + + + + Global HTTP Settings + + + + + + + + + + + + + + +]]> + + http://${#Project#E3Manager}:8181 + + getLocation8 + test_route_8 + PassThrough + active + endpoint8 + false + + + noAuth + + + + false + + + + active + + + http://${#Project#Target1}:8080/proxySize + + NoAuth + + key000Val + + + + + http://${#Project#Target2}:8080/proxySize + + NoAuth + + key000Val + + + + + http://${#Project#Target3}:8080/proxySize + + NoAuth + + key000Val + + + + + 50 + 0.0 + 3000 + 0.0 + + + + + + + CompanyQuota + Billing + + + + + + CompanyQuota + Billing + + + +]]> + + 200 + + + /response/statusSUCCESSfalsefalsefalse + + + /response/idgetLocation8falsefalsefalse + + + + + + + + + + + + + + + + +]]> + + http://${#Project#E3Manager}:8181 + + getLocation9 + test_route_9 + PassThrough + active + endpoint9 + false + + + noAuth + + + + false + + + + active + + + http://${#Project#Target1}:8080/proxySize + + NoAuth + + key000Val + + + + + http://${#Project#Target2}:8080/proxySize + + NoAuth + + key000Val + + + + + http://${#Project#Target3}:8080/proxySize + + NoAuth + + key000Val + + + + + 5 + 0.0 + 300 + 0.0 + + + + + + + CompanyQuota + Billing + + + + + + CompanyQuota + Billing + + + +]]> + + + 200 + + + + + /response/status + SUCCESS + false + false + false + + + + /response/idgetLocation9falsefalsefalse + + + + + + + + + + + + + +]]> + + http://${#Project#E3Manager}:8181 + + getLocation10 + test_route_10 + PassThrough + active + endpoint10 + true + + + noAuth + + + + true + + + + active + + + http://${#Project#Target1}:8080/proxySize + + + http://${#Project#Target2}:8080/proxySize + + + http://${#Project#Target3}:8080/proxySize + + + 10000 + 0.0 + 600000 + 0.0 + + + + + + + CompanyQuota + Billing + + + + + + CompanyQuota + Billing + + + +]]> + /response/statusSUCCESSfalsefalsefalse/response/idgetLocation10falsefalsefalseGlobal HTTP Settings + + + + + + + + + +]]> + + http://${#Project#E3Manager}:8181 + + getLocation11 + test_route_11 + PassThrough + active + endpoint11 + true + + + authKey + + + key + + + + true + + + + active + + + http://${#Project#Target1}:8080/proxySize + + + http://${#Project#Target2}:8080/proxySize + + + http://${#Project#Target3}:8080/proxySize + + + 10000 + 0.0 + 600000 + 0.0 + + + + + + + CompanyQuota + Billing + + + + + + CompanyQuota + Billing + + + +]]> + /response/statusSUCCESSfalsefalsefalse/response/idgetLocation11falsefalsefalseGlobal HTTP Settings + + + + + + + + + + + + +]]> + + http://${#Project#E3Manager}:8181 + + getLocation12 + test_route_1 + PassThrough + active + endpointHeaderTransformation + false + + + noAuth + + + + false + + + + active + + + http://${#Project#Target1}:8080/parametersEndpoint + + NoAuth + + key000Val + + + + + 10000 + -1 + 600000 + -1 + + + + + + + + CompanyQuota + Billing + + + + + + CompanyQuota + Billing + + + + + + CompanyQuota + Billing + + + + + request + response + + true + + + + + + + + +]]> + + 200 + + + /response/statusSUCCESSfalsefalsefalse + + + /response/idgetLocation12falsefalsefalse + + Global HTTP Settings + + + + + <xml-fragment/>http://${#Project#E3Manager}:8181 + p1 + + getLocation2 + + + + auth1 + + + + + active + + active + reject + 98 + 1000 + + + + active + + +]]>200/response/idp1falsefalsefalse/response/statusSUCCESSfalsefalsefalseGlobal HTTP Settings + + <xml-fragment/>http://${#Project#E3Manager}:8181 + p2 + + getLocation4 + + + + auth2 + + + + + active + + active + reject + 98 + 1000 + + + + active + + +]]>200/response/idp2falsefalsefalse/response/statusSUCCESSfalsefalsefalseGlobal HTTP Settings + + <xml-fragment/>http://${#Project#E3Manager}:8181 + pAuthBasic + + getLocation6 + + + + authBasic + + + + + active + + active + reject + 98 + 1000 + + + + active + + +]]>200/response/statusSUCCESSfalsefalsefalseGlobal HTTP Settings<xml-fragment/>http://${#Project#E3Manager}:8181 + pAuthIp + + getLocation7 + + + + authPerfIp + + + + + active + + active + reject + 98 + 1000 + + + + active + + +]]>200/response/statusSUCCESSfalsefalsefalse<xml-fragment/>http://${#Project#E3Manager}:8181 + phttpsauthkey + + getLocation11 + + + + auth2 + + + + + active + + active + reject + 98 + 1000 + + + + active + + +]]>200/response/idphttpsauthkeyfalsefalsefalse/response/statusSUCCESSfalsefalsefalse + + + + + + + + + +]]> + + http://${#Project#E3Manager}:8181 + + + + + + + + + + + + + + + +]]> + + http://${#Project#E3Manager}:8181 + + getLocationNoVal + test_route_1 + PassThrough + active + endpointNoVal + false + + + noAuth + + + + false + + + + active + + + http://${#Project#Target1}:8080/proxySize + + NoAuth + + key000Val + + + + + 10000 + 0.0 + 600000 + 0.0 + + + + + + + CompanyQuota + Billing + + + + + + CompanyQuota + Billing + + + +]]> + /response/statusSUCCESSfalsefalsefalse/response/idgetLocationNoValfalsefalsefalse + + + + + + + + + +]]> + + http://${#Project#E3Manager}:8181 + + getLocationHttps2ways + test_route_10 + PassThrough + active + endpointHttps2ways + true + + + noAuth + + + + true + + + + active + + + http://${#Project#Target1}:8080/proxySize + + NoAuth + + key000Val + + + + + http://${#Project#Target2}:8080/proxySize + + NoAuth + + key000Val + + + + + http://${#Project#Target3}:8080/proxySize + + NoAuth + + key000Val + + + + + 10000 + 0.0 + 600000 + 0.0 + + + + + + + CompanyQuota + Billing + + + + + + CompanyQuota + Billing + + + +]]> + /response/statusSUCCESSfalsefalsefalse/response/idgetLocationHttps2waysfalsefalsefalse + + + + + + + + + +]]> + + http://${#Project#E3Manager}:8181 + + perfComposite + test_composite_route + Composite + active + endpointComposite + false + + + noAuth + + + + false + + + + active + + + http://${#Project#Target1}:8080/compositeEndpoint + + NoAuth + + key000Val + + + + + 10000 + 0.0 + 600000 + 0.0 + + + + + + + CompanyQuota + Billing + + + + + + CompanyQuota + Billing + + + + + + +]]> + /response/statusSUCCESSfalsefalsefalse/response/idperfCompositefalsefalsefalse + + + + + + + + + + + + +]]> + + http://${#Project#E3Manager}:8181 + + getLocationHttpMethodFilter + test_route_http_method_filter + PassThrough + active + endpointHttpMethodFilter + false + + + noAuth + + + + false + + + + active + + + http://${#Project#Target1}:8080/proxySize + + NoAuth + + key000Val + + + + + http://${#Project#Target2}:8080/proxySize + + NoAuth + + key000Val + + + + + http://${#Project#Target3}:8080/proxySize + + NoAuth + + key000Val + + + + + 10000 + 0.0 + 600000 + 0.0 + + + + + + + CompanyQuota + Billing + + + + + + CompanyQuota + Billing + + + + + GET + POST + PUT + +]]> + + + 200 + + + + + /response/status + SUCCESS + false + false + false + + + + /response/idgetLocationHttpMethodFilterfalsefalsefalse + + + + + + + + + + + + + + + + +]]> + + http://${#Project#E3Manager}:8181 + + auth-type-wsse-api1 + test_route_1 + PassThrough + active + auth-type-wsse-endpoint1 + false + + + wsse + + + + false + + + + + + http://${#Project#Target1}:8080/proxySize + + + http://${#Project#Target2}:8080/proxySize + + + http://${#Project#Target3}:8080/proxySize + + + active + 10000 + 0.0 + 600000 + 0.0 + + +]]> + + + 200 + + + + + /response/status + SUCCESS + false + false + false + + + + /response/idauth-type-wsse-api1falsefalsefalse + + Global HTTP Settings + + + + + <xml-fragment/>http://${#Project#E3Manager}:8181 + auth-type-wsse-auth1 + active + wsse + + + + auth-type-wsse-username1 + YXV0aC10eXBlLXdzc2UtcGFzc3dvcmQx + + PlainText + +]]>200/response/idauth0falsefalsefalse/response/statusSUCCESSfalsefalsefalseGlobal HTTP Settings<xml-fragment/>http://${#Project#E3Manager}:8181 + auth-type-wsse-p1 + + auth-type-wsse-api1 + + + + auth-type-wsse-auth1 + + + + + active + + +]]>200/response/idauth-type-wsse-p1falsefalsefalse/response/statusSUCCESSfalsefalsefalseGlobal HTTP Settings + + + + + + + + + +]]> + + http://${#Project#E3Manager}:8181 + + getLocationConn10 + getLocationConn10 + PassThrough + active + endpointConn10 + false + + + noAuth + + + + false + + + + active + + + http://${#Project#Target1}:8080/proxyWait + + 10 + + + + http://${#Project#Target2}:8080/proxyWait + + 10 + + + + http://${#Project#Target3}:8080/proxyWait + + 10 + + + + 10000 + 0.0 + 600000 + 0.0 + + +]]> + + + 200 + + + + + /response/status + SUCCESS + false + false + false + + + + Global HTTP Settings + + + + + + + + + + + + + + +]]> + + http://${#Project#E3Manager}:8181 + + getLocationConn50 + getLocationConn50 + PassThrough + active + endpointConn50 + false + + + noAuth + + + + false + + + + active + + + http://${#Project#Target1}:8080/proxyWait + + 50 + + + + http://${#Project#Target2}:8080/proxyWait + + 50 + + + + http://${#Project#Target3}:8080/proxyWait + + 50 + + + + 10000 + 0.0 + 600000 + 0.0 + + +]]> + + + 200 + + + + + /response/status + SUCCESS + false + false + false + + + + Global HTTP Settings + + + + + + <xml-fragment/>http://${#Project#E3Manager}:8181404,200<xml-fragment/>http://${#Project#E3Manager}:8181 + > + Default Key +]]>200<xml-fragment/>http://${#Project#E3Manager}:8181 + > + Default Cert +]]>200<xml-fragment/>http://${#Project#E3Manager}:8181<?xml version="1.0" encoding="UTF-8" standalone="yes"?> +<key id="default"> + <activeCertId>default</activeCertId> +</key>200 + TestCase generated for REST Resource [/apis] located + at [/apis] + + + + + + + + + + + +]]> + + http://${#Project#E3Manager}:8181 + + + + + + + + + + + <xml-fragment/>http://${#Project#E3Manager}:8181 + <xml-fragment/>http://${#Project#E3Manager}:8181 + + + + + + + + + + +]]> + + http://${#Project#E3Manager}:8181 + + seb_test1 + seb_test1 + seb_test1 + PassThrough + endTest + false + + + authKey + + + key + + + + false + + active + + + active + + + + http://www.google.fr + www.google.fr + + + + value + + + + + 10 + 0.0 + 10 + 0.0 + + + + + + false + + +]]> + + + 200 + + + + + /response/status + SUCCESS + false + false + false + + + + /response/idseb_test1falsefalsefalse + + + + + + + + <xml-fragment/>http://${#Project#E3Manager}:8181 + auth1 + active + authKey + + + + 123456 + + + +]]>200/response/idauth1falsefalsefalse/response/statusSUCCESSfalsefalsefalse + <xml-fragment/>http://${#Project#E3Manager}:8181 + policy1 + + seb_test1 + + + + auth1 + + + + + active + + active + reject + 0.0 + 2 + + + + + + +]]>200/response/idpolicy1falsefalsefalse/response/statusSUCCESSfalsefalsefalse + + + + + + <entry key="SIZE" value="10" xmlns="http://eviware.com/soapui/config"/> + + http://${#Project#E3Gateway}/endTest?key=123456 + + + 200 + + //titleGooglefalsefalsefalse + + + + + + + + + + <entry key="SIZE" value="10" xmlns="http://eviware.com/soapui/config"/> + + http://${#Project#E3Gateway}/endTest?key=123456 + + + 200 + + //titleGooglefalsefalsefalse + + + + + + + + + + <entry key="SIZE" value="10" xmlns="http://eviware.com/soapui/config"/> + + http://${#Project#E3Gateway}/endTest?key=123456 + + + 429 + + Rate limit exceededfalsefalse + + + + + + + + + + + + + + +]]> + + http://${#Project#E3Manager}:8181 + + + + 200 + + + + + + /response/status + SUCCESS + false + false + false + + + + + + + + + + + + + <xml-fragment/> + + http://${#Project#E3Gateway}/endTest?key=123456 + + + 404 + + + + + + + <xml-fragment/>http://${#Project#E3Manager}:8181200/response/statusSUCCESSfalsefalsefalse<xml-fragment/>http://${#Project#E3Manager}:8181200/response/statusSUCCESSfalsefalsefalse + + TestCase generated for REST Resource [/apis] located + at [/apis] + + + + + + + + + + + +]]> + + http://${#Project#E3Manager}:8181 + + + + + + + + + + + <xml-fragment/>http://${#Project#E3Manager}:8181 + <xml-fragment/>http://${#Project#E3Manager}:8181 + + + + + + + + + + +]]> + + http://${#Project#E3Manager}:8181 + + test2 + test2 + test2 + PassThrough + end2 + false + + + authKey + + + key + + + + false + + active + + + active + + + + http://www.google.fr + www.google.fr + + + + value + + + + + 2 + 0.0 + 2 + 0.0 + + + + + + false + + +]]> + + + 200 + + + + + /response/status + SUCCESS + false + false + false + + + + /response/idtest2falsefalsefalse + + + + + + + + <xml-fragment/>http://${#Project#E3Manager}:8181 + auth2 + active + authKey + + + + 012346 + + + +]]>200/response/idauth2falsefalsefalse/response/statusSUCCESSfalsefalsefalse + <xml-fragment/>http://${#Project#E3Manager}:8181 + policy2 + + + auth2 + + + + + active + + active + reject + 0.0 + 5 + + + + + + +]]>200/response/idpolicy2falsefalsefalse/response/statusSUCCESSfalsefalsefalse + + + + + + <entry key="SIZE" value="10" xmlns="http://eviware.com/soapui/config"/> + + http://${#Project#E3Gateway}/end2?key=012346 + + + 200 + + //titleGooglefalsefalsefalse + + + + + + + + + + <entry key="SIZE" value="10" xmlns="http://eviware.com/soapui/config"/> + + http://${#Project#E3Gateway}/end2?key=012346 + + + 200 + + //titleGooglefalsefalsefalse + + + + + + + + + + <entry key="SIZE" value="10" xmlns="http://eviware.com/soapui/config"/> + + http://${#Project#E3Gateway}/end2?key=012346 + + + 429 + + Rate limit exceededfalsefalse + + + + + + + + + + + + + + +]]> + + http://${#Project#E3Manager}:8181 + + + + 200 + + + + + + /response/status + SUCCESS + false + false + false + + + + + + + + + + + + + <xml-fragment/> + + http://${#Project#E3Gateway}/end2?key=012346 + + + 404 + + + + + + + <xml-fragment/>http://${#Project#E3Manager}:8181200/response/statusSUCCESSfalsefalsefalse<xml-fragment/>http://${#Project#E3Manager}:8181200/response/statusSUCCESSfalsefalsefalse + + TestCase generated for REST Resource [/apis] located + at [/apis] + + + + + + + + + + + +]]> + + http://${#Project#E3Manager}:8181 + + + + + + + + + + + <xml-fragment/>http://${#Project#E3Manager}:8181 + <xml-fragment/>http://${#Project#E3Manager}:8181 + + + + + + + + + + +]]> + + http://${#Project#E3Manager}:8181 + + test3 + test3 + test3 + PassThrough + end3 + false + + + authKey + + + key + + + + false + + active + + + active + + + + http://www.google.fr + www.google.fr + + + + value + + + + + + 2 + 0.0 + 2 + 0.0 + + + + + + false + + +]]> + + + 200 + + + + + /response/status + SUCCESS + false + false + false + + + + /response/idtest3falsefalsefalse + + + + + + + + <xml-fragment/>http://${#Project#E3Manager}:8181 + auth3 + active + authKey + + + + 789456 + + + +]]>200/response/idauth3falsefalsefalse/response/statusSUCCESSfalsefalsefalse + <xml-fragment/>http://${#Project#E3Manager}:8181 + policy3 + + + auth3 + + + + + active + + active + reject + 0.0 + 5 + + + + + + +]]>200/response/idpolicy3falsefalsefalse/response/statusSUCCESSfalsefalsefalse + + + + + + <entry key="SIZE" value="10" xmlns="http://eviware.com/soapui/config"/> + + http://${#Project#E3Gateway}/end3?key=789456 + + + 429 + + Rate limit exceededfalsefalse + + + + + + + + + + + + + + +]]> + + http://${#Project#E3Manager}:8181 + + + + 200 + + + + + + /response/status + SUCCESS + false + false + false + + + + + + + + + + + + + <xml-fragment/> + + http://${#Project#E3Gateway}/end3?key=789456 + + + 404 + + + + + + + <xml-fragment/>http://${#Project#E3Manager}:8181200/response/statusSUCCESSfalsefalsefalse<xml-fragment/>http://${#Project#E3Manager}:8181200/response/statusSUCCESSfalsefalsefalse + + E3Manager192.168.84.176E3Gateway192.168.84.176Target1192.168.84.90Target2192.168.84.103Target3192.168.84.184uniqdeleteLOG4J_LEVEL_VALUES(ALL|TRACE|DEBUG|INFO|WARN|ERROR|FATAL|OFF)STATUS_SUCCESSSUCCESSSYSLOG_LEVEL_VALUES(DEBUG|INFO|NOTICE|WARNING|ERR|CRIT|ALERT|EMERG) \ No newline at end of file diff --git a/tests/functional-tests/functional-test-provision-auth/pom.xml b/tests/functional-tests/functional-test-provision-auth/pom.xml new file mode 100644 index 0000000..478e222 --- /dev/null +++ b/tests/functional-tests/functional-test-provision-auth/pom.xml @@ -0,0 +1,48 @@ + + 4.0.0 + com.alu.e3.functional-tests.provision-auth + functional-test-provision-auth + pom + + + + eviware + maven-soapui-plugin + 4.0.1 + + + mysql + mysql-connector-java + 5.1.6 + + + junit + junit + 4.8.1 + + + + + test + + test + + + ${basedir}/soapui-project.xml + ${basedir}/target/surefire-reports + true + ${basedir}/soapui-project-properties.xml + + + + + + + + com.alu.e3.functional-tests + functional-tests + 0.0.1-SNAPSHOT + .. + + Functional test provision auths + \ No newline at end of file diff --git a/tests/functional-tests/functional-test-provision-auth/soapui-project.xml b/tests/functional-tests/functional-test-provision-auth/soapui-project.xml new file mode 100644 index 0000000..b8a86a5 --- /dev/null +++ b/tests/functional-tests/functional-test-provision-auth/soapui-project.xml @@ -0,0 +1,1107 @@ + + +http://${#Project#E3Gateway}/api-parameters-endpoint1?param1=value1&key=api-parameters-key1&param2=value2http://${#Project#E3Gateway}/api-parameters-endpoint2/five?key=api-parameters-key2http://${#Project#E3Gateway}/api-parameters-endpoint2/three/five?key=api-parameters-key2apiauthTEMPLATEkeymykeyQUERYmykeyparam1QUERYtext/plain403 500 429data200data200data0data0data0data200data200data200data200data200data200data0datatext/html200<xml-fragment/>http://${#Project#E3Gateway}keymykeyQUERYmykeyparam1value1QUERYvalue1param2value2QUERYvalue2text/plain403data200data200data0data0data0data200data200data200data200data200data200data200datatext/html2000data<xml-fragment/>http://${#Project#E3Gateway}param1value1QUERYvalue1keymykeyQUERYxs:stringmykeyparam2value2QUERYvalue2text/plain403data200data200data0data0data0data200data200data200data200data200data200datatext/html200<xml-fragment/>http://${#Project#E3Gateway}param1value1QUERYvalue1param2value2QUERYvalue2keymykeyQUERYxs:stringmykeytext/plain403data200data200data0data0data0data200data200data200data200data200data200datatext/html200<xml-fragment/>http://${#Project#E3Gateway}text/plain403data200data200data0data0data0data200data200data200data200data200data200datatext/html200text/html;charset=ISO-8859-1404htmltext/html404html<xml-fragment/>http://${#Project#E3Gateway}param1QUERYtext/plain403 500 429data200data200data0data0data0data200data200data200data200data200data200data0datatext/html200text/html404html<xml-fragment/>http://${#Project#E3Gateway}keyQUERYtext/plain403 500 429data200data200data0data0data0data200data200data200data200data200data200data0datatext/html200text/html;charset=ISO-8859-1404html<xml-fragment/>http://${#Project#E3Gateway}text/plain403data200data200data0data0data0data200data200data200data200data200data200datatext/html200text/html;charset=ISO-8859-1404html0data<xml-fragment/>http://${#Project#E3Gateway}text/plain403data200data200data0data0data0data200data200data200data200data200data200datatext/html200text/html;charset=ISO-8859-1404html<xml-fragment/>http://${#Project#E3Gateway}text/plain403data200data200data0data0data0data200data200data200data200data200data200datatext/html200text/html;charset=ISO-8859-1404html0data0data0data0data<xml-fragment/>http://${#Project#E3Gateway}param1QUERYtext/plain403data200data200data0data0data0data200data200data200data200data200data200datatext/html200text/html;charset=ISO-8859-1404html0data<xml-fragment/>http://${#Project#E3Gateway}param1QUERYkeyQUERYtext/plain403data200data200data0data0data0data200data200data200data200data200data200datatext/html200text/html;charset=ISO-8859-1404html0data<xml-fragment/>http://${#Project#E3Gateway}keyQUERYtext/plain403data200data200data0data0data0data200data200data200data200data200data200datatext/html200text/html;charset=ISO-8859-1404html0data<xml-fragment/>http://${#Project#E3Gateway}text/plain403data200data200data0data0data0data200data200data200data200data200data200datatext/html200text/html;charset=ISO-8859-1404html0data0data<xml-fragment/>http://${#Project#E3Gateway}param1QUERYtext/plain403data200data200data0data0data0data200data200data200data200data200data200datatext/html200text/html;charset=ISO-8859-1404html0data<xml-fragment/>http://${#Project#E3Gateway}param1QUERYkeyQUERYtext/plain403data200data200data0data0data0data200data200data200data200data200data200datatext/html200text/html;charset=ISO-8859-1404html0data<xml-fragment/>http://${#Project#E3Gateway}text/plain403data200data200data0data0data0data200data200data200data200data200data200datatext/html200text/html;charset=ISO-8859-1404html<xml-fragment/>http://${#Project#E3Gateway}text/plain403 500data200data200data0data0data0data200data200data200data200data200data200datatext/html200text/html;charset=ISO-8859-1404html0datatext/html; charset=iso-8859-1404html<xml-fragment/>http://${#Project#E3Gateway}text/plain403data200data200data0data0data0data200data200data200data200data200data200datatext/html200text/html;charset=ISO-8859-1404html<xml-fragment/>http://${#Project#E3Gateway}text/html200text/plain403 500datatext/html404htmlhttp://${#Project#E3Gateway} + + + http://${#Project#E3Gateway}/auth-extended-endpoint1?key=auth-extended-key1http://${#Project#E3Gateway}/auth-extended-endpoint1http://${#Project#E3Gateway}/auth-extended-endpoint2http://${#Project#E3Gateway}/api-header-transform-endpoint1?key=api-header-transform-key1http://${#Project#E3Gateway}/api-header-transform-endpoint2?key=api-header-transform-key2http://${#Project#E3Gateway}/api-header-transform-endpoint3?key=api-header-transform-key3http://${#Project#E3Gateway}/provision-api-ext-endpoint1http://${#Project#E3Gateway}/provision-api-ext-endpoint3?key=provision-api-ext-key3 + + + + + + keyQUERY + + text/html + 200 + + html + + + + 0 + + data + + + text/plain + 500 403 401 429 + + data + + + + 200 + + data + + + + 200 + + data + + + text/html + 404 + + html + + 0data0data0data0data0data + 0data0datatext/xml200data<xml-fragment xmlns:con="http://eviware.com/soapui/config"> + <con:entry key="WAIT" value="0"/> + <con:entry key="SIZE" value="100"/> +</xml-fragment>http://${#Project#E3Gateway}/endpoint1<xml-fragment xmlns:con="http://eviware.com/soapui/config"> + <con:entry key="WAIT" value="0"/> + <con:entry key="SIZE" value="100"/> +</xml-fragment>http://${#Project#E3Gateway}/endpoint1 + text/plain401 403 429 500datatext/html200html0data0data0data0datatext/html404htmltext/xml200data<xml-fragment xmlns:con="http://eviware.com/soapui/config"> + <con:entry key="WAIT" value="0"/> + <con:entry key="SIZE" value="100"/> +</xml-fragment>http://${#Project#E3Gateway}/endpoint1text/plain401 500 429data0data0data0data0data0data0data0data0data0data0datatext/xml200datatext/html404html<xml-fragment xmlns:con="http://eviware.com/soapui/config"> + <con:entry key="Authorization" value="Basic dGVzdGVyOnRlc3RlcnBhc3N3b3Jk"/> + <con:entry key="WAIT" value="0"/> + <con:entry key="SIZE" value="100"/> +</xml-fragment>http://${#Project#E3Gateway}/endpoint1<xml-fragment xmlns:con="http://eviware.com/soapui/config"> + <con:entry key="Authorization" value="Basic invalidbasic"/> + <con:entry key="WAIT" value="0"/> + <con:entry key="SIZE" value="100"/> +</xml-fragment>http://${#Project#E3Gateway}/endpoint1text/xml200datatext/html200data<xml-fragment xmlns:con="http://eviware.com/soapui/config"> + <con:entry key="WAIT" value="0"/> + <con:entry key="SIZE" value="100"/> +</xml-fragment>http://${#Project#E3Gateway}/endpoint1?key=e88ba0c1e4c34f25bf95733eebd8574f + http://${#Project#E3Gateway}:8181/cxf/e3/prov/v1?_wadl&_type=xml + + + + E3 REST API to create, update or delete an API + + Used to get all API IDs. + + + + + + This REST API is used to create an API. + + + + + + + + + + + This REST API is used to delete an API. + + + + + + + Used to get an API by this ID. + + + + + + + This REST API is used to update an API. + + + + + + + + + + + E3 REST API to create, update or delete a policy + + This REST API is used to fetch all policy ids. + + + + + + This REST API is used to create a policy. + + + + + + + + + + + This REST API is used to delete a policy. + + + + + + + This REST API is used to fetch policy data. + + + + + + + This REST API is used to update a policy. + + + + + + + + + + + + This REST API is used to create a QuotaRLBucket in a policy. + + + + + + + + + + + + + This REST API is used to remove a bucket from a policy. + + + + + + + This REST API is used to append auths to a bucket. + + + + + + + + + + + + + + This REST API is used to remove an auth from a bucket. + + + + + + + + + E3 REST API provision authentications on E3 subsystem + + This REST API is used to get all authentications from E3 subsystem. + + + + + + This REST API is used to create an authentication element on E3 subsystem. + + + + + + + + + + + This REST API is used to delete an Auth. + + + + + + + This REST API is used to get an authentication by ID from E3 subsystem. + + + + + + + This REST API is used to update an authentication. + + + + + + + + + + + E3 REST API to create or delete a bucket of auths associated to a list of policies + + This REST API is used to create a bucket linked to a list of policies. + + + + + + + + + + + This REST API is used to append auths to a bucket for several policies. + + + + + + + + + + + + This REST API is used to remove a bucket from a list of policies. + + + + + + + + + + + E3 REST API provision SSLKeys and SSLCerts on E3 subsystem + + This REST API is used to get all SSLKeys from E3 subsystem. + + + + + + This REST API is used to create an SSLKey element on E3 subsystem. + + + + + + + + + + + This REST API is used to delete an SSLKey. + + + + + + + This REST API is used to get an SSLKey by ID from E3 subsystem. + + + + + + + This REST API is used to update an SSLKey. + + + + + + + + + + + + This REST API is used to get all SSLCerts for a key. + + + + + + + This REST API is used to create an SSLCert element on E3 subsystem. + + + + + + + + + + + + + This REST API is used to delete an SSLCert. + + + + + + + This REST API is used to get an SSLKey by ID from E3 subsystem. + + + + + + + This REST API is used to update an SSLKey. + + + + + + + + + + + + This REST API is used to get a CSR for the given SSLKey ID from E3 subsystem. + + + + + + + + + + This REST API is used to create a self-signed cert for an existing Key + + + + + + + + + E3 REST API to add/update/delete trusted CAs and CRLs + + + This REST API is used to fetch all trusted certificates authorithies. + + + + + + This REST API is used to add a trusted Certificate Authority. + + + + + + + + + + + + This REST API is used to remove a trusted Certificate Authority. + + + + + + + This REST API is used to fetch trusted Certificate Authority. + + + + + + + This REST API is used to update a trusted Certificate Authority. + + + + + + + + + + + This REST API is used to fetch trusted Certificate Authority. + + + + + + This REST API is used to add a Certificate Revocation List for this Certificate Authority. + + + + + + + + + + + + This REST API is used to remove a certificate revocation list from a certificate authority. + + + + + + + This REST API is used to fetch Certificate Revocation List. + + + + + + + This REST API is used to update a certificate revocation list. + + + + + + + + + + +]]>http://wadl.dev.java.net/2009/02http://${#Project#E3Gateway}:8181API_IDTEMPLATExs:stringapplication/xmlhttp://${#Project#E3Gateway}:8181application/xmlhttp://${#Project#E3Gateway}:8181application/xmlapplication/xmlhttp://${#Project#E3Gateway}:8181application/xmlhttp://${#Project#E3Gateway}:8181application/xmlapplication/xmlhttp://${#Project#E3Gateway}:8181POLICY_IDTEMPLATExs:stringapplication/xmlhttp://${#Project#E3Gateway}:8181application/xmlhttp://${#Project#E3Gateway}:8181application/xmlapplication/xmlhttp://${#Project#E3Gateway}:8181POLICY_IDTEMPLATExs:stringapplication/xmlapplication/xmlhttp://${#Project#E3Gateway}:8181POLICY_IDTEMPLATExs:stringBUCKET_IDTEMPLATExs:stringapplication/xmlhttp://${#Project#E3Gateway}:8181application/xmlapplication/xmlhttp://${#Project#E3Gateway}:8181POLICY_IDTEMPLATExs:stringBUCKET_IDTEMPLATExs:stringAUTH_IDTEMPLATExs:stringapplication/xmlhttp://${#Project#E3Gateway}:8181application/xmlhttp://${#Project#E3Gateway}:8181application/xmlapplication/xmlhttp://${#Project#E3Gateway}:8181AUTH_IDTEMPLATExs:stringapplication/xmlhttp://${#Project#E3Gateway}:8181application/xmlhttp://${#Project#E3Gateway}:8181application/xmlapplication/xmlhttp://${#Project#E3Gateway}:8181application/xmlhttp://${#Project#E3Gateway}:8181application/xmlapplication/xmlhttp://${#Project#E3Gateway}:8181BUCKET_IDTEMPLATExs:stringapplication/xmlapplication/xmlhttp://${#Project#E3Gateway}:8181BUCKET_IDTEMPLATExs:stringapplication/xmlapplication/xmlhttp://${#Project#E3Gateway}:8181application/xmlapplication/xmlhttp://${#Project#E3Gateway}:8181KEY_IDTEMPLATExs:stringapplication/xmlhttp://${#Project#E3Gateway}:8181application/xmlhttp://${#Project#E3Gateway}:8181application/xmlapplication/xmlhttp://${#Project#E3Gateway}:8181KEY_IDTEMPLATExs:stringapplication/xmlhttp://${#Project#E3Gateway}:8181application/xmlapplication/xmlhttp://${#Project#E3Gateway}:8181KEY_IDTEMPLATExs:stringCERT_IDTEMPLATExs:stringapplication/xmlhttp://${#Project#E3Gateway}:8181application/xmlhttp://${#Project#E3Gateway}:8181application/xmlapplication/xmlhttp://${#Project#E3Gateway}:8181KEY_IDTEMPLATExs:stringapplication/xmlhttp://${#Project#E3Gateway}:8181KEY_IDTEMPLATExs:stringapplication/xmlhttp://${#Project#E3Gateway}:8181application/xmlhttp://${#Project#E3Gateway}:8181application/xmlapplication/xmlhttp://${#Project#E3Gateway}:8181application/xmlhttp://${#Project#E3Gateway}:8181application/xmlapplication/xmlhttp://${#Project#E3Gateway}:8181CA_IDTEMPLATExs:stringapplication/xmlhttp://${#Project#E3Gateway}:8181application/xmlhttp://${#Project#E3Gateway}:8181application/xmlapplication/xmlhttp://${#Project#E3Gateway}:8181application/xmlhttp://${#Project#E3Gateway}:8181application/xmlapplication/xmlhttp://${#Project#E3Gateway}:8181CRL_IDTEMPLATExs:stringapplication/xmlhttp://${#Project#E3Gateway}:8181application/xmlhttp://${#Project#E3Gateway}:8181application/xmlapplication/xmlhttp://${#Project#E3Gateway}:8181file:/D:/Documents%20and%20Settings/mtobiasz/Desktop/targertest_1.wadl + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + +]]>http://wadl.dev.java.net/2009/02http://${#Project#E3Gateway}http://${#Project#E3Gateway}/api-http-method-endpoint1?key=api-http-method-key1http://${#Project#E3Gateway}/api-http-method-endpoint2?key=api-http-method-key2http://${#Project#E3Gateway}/api-http-method-endpoint3?key=api-http-method-key3http://${#Project#E3Gateway}/api-http-method-endpoint4?key=api-http-method-key40text/html200http://${#Project#E3Gateway}application/xml0application/xmltext/plain403 405 429text/xml200ns:responsehttp://${#Project#E3Gateway}application/xmlapplication/xmltext/plain405 429text/xml200ns:responsehttp://${#Project#E3Gateway}text/plain405 429text/xml200ns:responsehttp://${#Project#E3Gateway}0text/plain405text/xml200http://${#Project#E3Gateway} + TestSuite generated for REST Service + [functional-test-provision-auth] + + SEQUENTIAL + + + + + + + + <xml-fragment/> + + http://${#Project#E3Manager}:8181 + + + + + + + + + + + + + <xml-fragment/> + + http://${#Project#E3Manager}:8181 + + auth-provision-auth1 + active + basic + + + + auth-provision-username1 + YXV0aC1wcm92aXNpb24tcGFzc3dvcmQx + + + + + + + CompanyQuota + Billing + + + + + + CompanyQuota + Billing + + + + + + CompanyQuota + Billing + + + + + +]]> + /response/statusSUCCESSfalsefalsefalse + + + + + + + + + + + <xml-fragment/> + + http://${#Project#E3Manager}:8181 + + + + + + + + + + + + + <xml-fragment/> + + http://${#Project#E3Manager}:8181 + + + + + + + + + + + + + <xml-fragment/> + + http://${#Project#E3Manager}:8181 + + auth-provision-auth1 + active + authKey + + + + + auth-provision-key1 + + + + + + CompanyQuota + Billing + + + + + + CompanyQuota + Billing + + + +]]> + /response/statusSUCCESSfalsefalsefalse + + + + + + + + + + + <xml-fragment/> + + http://${#Project#E3Manager}:8181 + + + + + + + + + + + + + + + + <xml-fragment/> + + http://${#Project#E3Manager}:8181 + + + + + + + + + + + + + <xml-fragment/> + + http://${#Project#E3Manager}:8181 + + auth-provision-auth2 + active + authKey + + + + + auth-provision-key2 + + + + + + CompanyQuota + Billing + + + + + + CompanyQuota + Billing + + + + + authpropvalue1 + authpropvalue2 + +]]> + 200/response/idauth-provision-auth2falsefalsefalse + + + + + + + + + + + <xml-fragment/> + + http://${#Project#E3Manager}:8181 + + /response/ids/idauth-provision-auth2falsefalsefalse200 + + + + + + + + + + + <xml-fragment/> + + http://${#Project#E3Manager}:8181 + + 200/response/auth/properties/propertyauthpropvalue1falsefalsefalse/response/auth/properties/propertyauthpropvalue2falsefalsefalse/response/auth/idauth-provision-auth2falsefalsefalse + + + + + + + + + + + <xml-fragment/> + + http://${#Project#E3Manager}:8181 + + auth-provision-auth2 + active + authKey + + + + + auth-provision-key2 + + + + + + CompanyQuota + Billing + + + + + + CompanyQuota + Billing + + + + + authpropvalue3 + authpropvalue4 + +]]> + 200/response/idauth-provision-auth2falsefalsefalse + + + + + + + + + + + <xml-fragment/> + + http://${#Project#E3Manager}:8181 + + 200/response/auth/properties/propertyauthpropvalue3falsefalsefalse/response/auth/properties/propertyauthpropvalue4falsefalsefalse/response/auth/idauth-provision-auth2falsefalsefalse + + + + + + + + + + <xml-fragment/> + + http://${#Project#E3Manager}:8181 + + 200 + + + + + + + + + + + + + <xml-fragment/> + + http://${#Project#E3Manager}:8181 + + + + + + + + + + + + + <xml-fragment/> + + http://${#Project#E3Manager}:8181 + + auth-provision-auth3 + active + authKey + + + + + auth-provision-key3 + + + + + + CompanyQuota + Billing + + + + + + CompanyQuota + Billing + + + + + + + + + + + +]]> + 200/response/idauth-provision-auth3falsefalsefalse + + + + + + + + + + + <xml-fragment/> + + http://${#Project#E3Manager}:8181 + + /response/ids/idauth-provision-auth3falsefalsefalse200 + + + + + + + + + + + <xml-fragment/> + + http://${#Project#E3Manager}:8181 + + 200/response/auth/idauth-provision-auth3falsefalsefalse/response/auth/headerTransformations/headerTransformation<headerTransformation name="authtransfname1" type="Request" action="Add" value="authtransfvalue1"/>falsefalsefalse/response/auth/headerTransformations/headerTransformation<headerTransformation name="authtransfname2" type="Request" action="Add" property="authtransfprop2"/>falsefalsefalse/response/auth/headerTransformations/headerTransformation<headerTransformation name="authtransfname3" type="Response" action="Add" property="authtransfprop3"/>falsefalsefalse/response/auth/headerTransformations/headerTransformation<headerTransformation name="authtransfname4" type="Response" action="Add" value="authtransfvalue4"/>falsefalsefalse/response/auth/headerTransformations/headerTransformation<headerTransformation name="authtransfname5" type="Request" action="Remove" />falsefalsefalse/response/auth/headerTransformations/headerTransformation<headerTransformation name="authtransfname6" type="Response" action="Remove" />falsefalsefalse + + + + + + + + + + + <xml-fragment/> + + http://${#Project#E3Manager}:8181 + + auth-provision-auth3 + active + authKey + + + + + auth-provision-key3 + + + + + + CompanyQuota + Billing + + + + + + CompanyQuota + Billing + + + + + + + + + + + +]]> + 200/response/idauth-provision-auth3falsefalsefalse + + + + + + + + + + + <xml-fragment/> + + http://${#Project#E3Manager}:8181 + + 200/response/auth/idauth-provision-auth3falsefalsefalse/response/auth/headerTransformations/headerTransformation<headerTransformation name="authtransfname7" value="authtransfvalue7" type="Request" action="Add" />falsefalsefalse/response/auth/headerTransformations/headerTransformation<headerTransformation name="authtransfname8" type="Request" action="Add" property="authtransfprop8"/>falsefalsefalse/response/auth/headerTransformations/headerTransformation<headerTransformation name="authtransfname9" type="Response" action="Add" property="authtransfprop9"/>falsefalsefalse/response/auth/headerTransformations/headerTransformation<headerTransformation name="authtransfname10" type="Response" action="Add" value="authtransfvalue10"/>falsefalsefalse/response/auth/headerTransformations/headerTransformation<headerTransformation name="authtransfname11" type="Request" action="Remove" />falsefalsefalse/response/auth/headerTransformations/headerTransformation<headerTransformation name="authtransfname12" type="Response" action="Remove" />falsefalsefalse + + + + + + + + TestSuite generated for REST Service + [functional-test-provision-api] + + SEQUENTIAL + + + + + + + + + + + <xml-fragment/>http://${#Project#E3Manager}:8181404/response/statusFAILUREfalsefalsefalse/response/error/errorCode114falsefalsefalse/response/error/errorTextAn Authorization with that ID [nonExistent] doesn't existfalsefalsefalse<xml-fragment/>http://${#Project#E3Manager}:8181 + nonExistent + active + authKey + + + + e88ba0c1e4c34f25bf95733eebd8574f + + + + + + CompanyQuota + Billing + + + + + + CompanyQuota + Billing + + + +]]>404/response/statusFAILUREfalsefalsefalse/response/error/errorCode114falsefalsefalse/response/error/errorTextAn authorization with that ID [nonExistent] doesn't existfalsefalsefalse<xml-fragment/>http://${#Project#E3Manager}:8181404/response/statusFAILUREfalsefalsefalse/response/error/errorCode114falsefalsefalse/response/error/errorTextAn Authorization with that ID [nonExistent] doesn't existfalsefalsefalse + E3Manager192.168.84.157E3Gateway192.168.84.157Target1192.168.84.90uniqdelete \ No newline at end of file diff --git a/tests/functional-tests/functional-test-provision-policy/pom.xml b/tests/functional-tests/functional-test-provision-policy/pom.xml new file mode 100644 index 0000000..a320be0 --- /dev/null +++ b/tests/functional-tests/functional-test-provision-policy/pom.xml @@ -0,0 +1,48 @@ + + 4.0.0 + com.alu.e3.functional-tests.samples + functional-test-provision-policy + pom + + + + eviware + maven-soapui-plugin + 4.0.1 + + + mysql + mysql-connector-java + 5.1.6 + + + junit + junit + 4.8.1 + + + + + test + + test + + + ${basedir}/soapui-project.xml + ${basedir}/target/surefire-reports + true + ${basedir}/soapui-project-properties.xml + + + + + + + + com.alu.e3.functional-tests + functional-tests + 0.0.1-SNAPSHOT + .. + + Functional test provision policy + \ No newline at end of file diff --git a/tests/functional-tests/functional-test-provision-policy/soapui-project.xml b/tests/functional-tests/functional-test-provision-policy/soapui-project.xml new file mode 100644 index 0000000..e4156f0 --- /dev/null +++ b/tests/functional-tests/functional-test-provision-policy/soapui-project.xml @@ -0,0 +1,3572 @@ + + +http://${#Project#E3Gateway}/api-parameters-endpoint1?param1=value1&key=api-parameters-key1&param2=value2http://${#Project#E3Gateway}/api-parameters-endpoint2/five?key=api-parameters-key2http://${#Project#E3Gateway}/api-parameters-endpoint2/three/five?key=api-parameters-key2apiauthTEMPLATEkeymykeyQUERYmykeyparam1QUERYtext/plain403 500 429data200data200data0data0data0data200data200data200data200data200data200data0datatext/html200<xml-fragment/>http://${#Project#E3Gateway}keymykeyQUERYmykeyparam1value1QUERYvalue1param2value2QUERYvalue2text/plain403data200data200data0data0data0data200data200data200data200data200data200data200datatext/html2000data<xml-fragment/>http://${#Project#E3Gateway}param1value1QUERYvalue1keymykeyQUERYxs:stringmykeyparam2value2QUERYvalue2text/plain403data200data200data0data0data0data200data200data200data200data200data200datatext/html200<xml-fragment/>http://${#Project#E3Gateway}param1value1QUERYvalue1param2value2QUERYvalue2keymykeyQUERYxs:stringmykeytext/plain403data200data200data0data0data0data200data200data200data200data200data200datatext/html200<xml-fragment/>http://${#Project#E3Gateway}text/plain403data200data200data0data0data0data200data200data200data200data200data200datatext/html200text/html;charset=ISO-8859-1404htmltext/html404html<xml-fragment/>http://${#Project#E3Gateway}param1QUERYtext/plain403 500 429data200data200data0data0data0data200data200data200data200data200data200data0datatext/html200text/html404html<xml-fragment/>http://${#Project#E3Gateway}keyQUERYtext/plain403 500 429data200data200data0data0data0data200data200data200data200data200data200data0datatext/html200text/html;charset=ISO-8859-1404html<xml-fragment/>http://${#Project#E3Gateway}text/plain403data200data200data0data0data0data200data200data200data200data200data200datatext/html200text/html;charset=ISO-8859-1404html0data<xml-fragment/>http://${#Project#E3Gateway}text/plain403data200data200data0data0data0data200data200data200data200data200data200datatext/html200text/html;charset=ISO-8859-1404html<xml-fragment/>http://${#Project#E3Gateway}text/plain403data200data200data0data0data0data200data200data200data200data200data200datatext/html200text/html;charset=ISO-8859-1404html0data0data0data0data<xml-fragment/>http://${#Project#E3Gateway}param1QUERYtext/plain403data200data200data0data0data0data200data200data200data200data200data200datatext/html200text/html;charset=ISO-8859-1404html0data<xml-fragment/>http://${#Project#E3Gateway}param1QUERYkeyQUERYtext/plain403data200data200data0data0data0data200data200data200data200data200data200datatext/html200text/html;charset=ISO-8859-1404html0data<xml-fragment/>http://${#Project#E3Gateway}keyQUERYtext/plain403data200data200data0data0data0data200data200data200data200data200data200datatext/html200text/html;charset=ISO-8859-1404html0data<xml-fragment/>http://${#Project#E3Gateway}text/plain403data200data200data0data0data0data200data200data200data200data200data200datatext/html200text/html;charset=ISO-8859-1404html0data0data<xml-fragment/>http://${#Project#E3Gateway}param1QUERYtext/plain403data200data200data0data0data0data200data200data200data200data200data200datatext/html200text/html;charset=ISO-8859-1404html0data<xml-fragment/>http://${#Project#E3Gateway}param1QUERYkeyQUERYtext/plain403data200data200data0data0data0data200data200data200data200data200data200datatext/html200text/html;charset=ISO-8859-1404html0data<xml-fragment/>http://${#Project#E3Gateway}text/plain403data200data200data0data0data0data200data200data200data200data200data200datatext/html200text/html;charset=ISO-8859-1404html<xml-fragment/>http://${#Project#E3Gateway}text/plain403 500data200data200data0data0data0data200data200data200data200data200data200datatext/html200text/html;charset=ISO-8859-1404html0datatext/html; charset=iso-8859-1404html<xml-fragment/>http://${#Project#E3Gateway}text/plain403data200data200data0data0data0data200data200data200data200data200data200datatext/html200text/html;charset=ISO-8859-1404html<xml-fragment/>http://${#Project#E3Gateway}text/html200text/plain403 500datatext/html404htmlhttp://${#Project#E3Gateway} + + + http://${#Project#E3Gateway}/auth-extended-endpoint1?key=auth-extended-key1http://${#Project#E3Gateway}/auth-extended-endpoint1http://${#Project#E3Gateway}/auth-extended-endpoint2http://${#Project#E3Gateway}/api-header-transform-endpoint1?key=api-header-transform-key1http://${#Project#E3Gateway}/api-header-transform-endpoint2?key=api-header-transform-key2http://${#Project#E3Gateway}/api-header-transform-endpoint3?key=api-header-transform-key3http://${#Project#E3Gateway}/provision-api-ext-endpoint1http://${#Project#E3Gateway}/provision-api-ext-endpoint3?key=provision-api-ext-key3 + + + + + + keyQUERY + + text/html + 200 + + html + + + + 0 + + data + + + text/plain + 500 403 401 429 + + data + + + + 200 + + data + + + + 200 + + data + + + text/html + 404 + + html + + 0data0data0data0data0data + 0data0datatext/xml200data<xml-fragment xmlns:con="http://eviware.com/soapui/config"> + <con:entry key="WAIT" value="0"/> + <con:entry key="SIZE" value="100"/> +</xml-fragment>http://${#Project#E3Gateway}/endpoint1<xml-fragment xmlns:con="http://eviware.com/soapui/config"> + <con:entry key="WAIT" value="0"/> + <con:entry key="SIZE" value="100"/> +</xml-fragment>http://${#Project#E3Gateway}/endpoint1 + text/plain401 403 429 500datatext/html200html0data0data0data0datatext/html404htmltext/xml200data<xml-fragment xmlns:con="http://eviware.com/soapui/config"> + <con:entry key="WAIT" value="0"/> + <con:entry key="SIZE" value="100"/> +</xml-fragment>http://${#Project#E3Gateway}/endpoint1text/plain401 500 429data0data0data0data0data0data0data0data0data0data0datatext/xml200datatext/html404html<xml-fragment xmlns:con="http://eviware.com/soapui/config"> + <con:entry key="Authorization" value="Basic dGVzdGVyOnRlc3RlcnBhc3N3b3Jk"/> + <con:entry key="WAIT" value="0"/> + <con:entry key="SIZE" value="100"/> +</xml-fragment>http://${#Project#E3Gateway}/endpoint1<xml-fragment xmlns:con="http://eviware.com/soapui/config"> + <con:entry key="Authorization" value="Basic invalidbasic"/> + <con:entry key="WAIT" value="0"/> + <con:entry key="SIZE" value="100"/> +</xml-fragment>http://${#Project#E3Gateway}/endpoint1text/xml200datatext/html200data<xml-fragment xmlns:con="http://eviware.com/soapui/config"> + <con:entry key="WAIT" value="0"/> + <con:entry key="SIZE" value="100"/> +</xml-fragment>http://${#Project#E3Gateway}/endpoint1?key=e88ba0c1e4c34f25bf95733eebd8574f + http://${#Project#E3Gateway}:8181/cxf/e3/prov/v1?_wadl&_type=xml + + + + E3 REST API to create, update or delete an API + + Used to get all API IDs. + + + + + + This REST API is used to create an API. + + + + + + + + + + + This REST API is used to delete an API. + + + + + + + Used to get an API by this ID. + + + + + + + This REST API is used to update an API. + + + + + + + + + + + E3 REST API to create, update or delete a policy + + This REST API is used to fetch all policy ids. + + + + + + This REST API is used to create a policy. + + + + + + + + + + + This REST API is used to delete a policy. + + + + + + + This REST API is used to fetch policy data. + + + + + + + This REST API is used to update a policy. + + + + + + + + + + + + This REST API is used to create a QuotaRLBucket in a policy. + + + + + + + + + + + + + This REST API is used to remove a bucket from a policy. + + + + + + + This REST API is used to append auths to a bucket. + + + + + + + + + + + + + + This REST API is used to remove an auth from a bucket. + + + + + + + + + E3 REST API provision authentications on E3 subsystem + + This REST API is used to get all authentications from E3 subsystem. + + + + + + This REST API is used to create an authentication element on E3 subsystem. + + + + + + + + + + + This REST API is used to delete an Auth. + + + + + + + This REST API is used to get an authentication by ID from E3 subsystem. + + + + + + + This REST API is used to update an authentication. + + + + + + + + + + + E3 REST API to create or delete a bucket of auths associated to a list of policies + + This REST API is used to create a bucket linked to a list of policies. + + + + + + + + + + + This REST API is used to append auths to a bucket for several policies. + + + + + + + + + + + + This REST API is used to remove a bucket from a list of policies. + + + + + + + + + + + E3 REST API provision SSLKeys and SSLCerts on E3 subsystem + + This REST API is used to get all SSLKeys from E3 subsystem. + + + + + + This REST API is used to create an SSLKey element on E3 subsystem. + + + + + + + + + + + This REST API is used to delete an SSLKey. + + + + + + + This REST API is used to get an SSLKey by ID from E3 subsystem. + + + + + + + This REST API is used to update an SSLKey. + + + + + + + + + + + + This REST API is used to get all SSLCerts for a key. + + + + + + + This REST API is used to create an SSLCert element on E3 subsystem. + + + + + + + + + + + + + This REST API is used to delete an SSLCert. + + + + + + + This REST API is used to get an SSLKey by ID from E3 subsystem. + + + + + + + This REST API is used to update an SSLKey. + + + + + + + + + + + + This REST API is used to get a CSR for the given SSLKey ID from E3 subsystem. + + + + + + + + + + This REST API is used to create a self-signed cert for an existing Key + + + + + + + + + E3 REST API to add/update/delete trusted CAs and CRLs + + + This REST API is used to fetch all trusted certificates authorithies. + + + + + + This REST API is used to add a trusted Certificate Authority. + + + + + + + + + + + + This REST API is used to remove a trusted Certificate Authority. + + + + + + + This REST API is used to fetch trusted Certificate Authority. + + + + + + + This REST API is used to update a trusted Certificate Authority. + + + + + + + + + + + This REST API is used to fetch trusted Certificate Authority. + + + + + + This REST API is used to add a Certificate Revocation List for this Certificate Authority. + + + + + + + + + + + + This REST API is used to remove a certificate revocation list from a certificate authority. + + + + + + + This REST API is used to fetch Certificate Revocation List. + + + + + + + This REST API is used to update a certificate revocation list. + + + + + + + + + + +]]>http://wadl.dev.java.net/2009/02http://${#Project#E3Gateway}:8181API_IDTEMPLATExs:stringapplication/xmlhttp://${#Project#E3Gateway}:8181application/xmlhttp://${#Project#E3Gateway}:8181application/xmlapplication/xmlhttp://${#Project#E3Gateway}:8181application/xmlhttp://${#Project#E3Gateway}:8181application/xmlapplication/xmlhttp://${#Project#E3Gateway}:8181POLICY_IDTEMPLATExs:stringapplication/xmlhttp://${#Project#E3Gateway}:8181application/xmlhttp://${#Project#E3Gateway}:8181application/xmlapplication/xmlhttp://${#Project#E3Gateway}:8181POLICY_IDTEMPLATExs:stringapplication/xmlapplication/xmlhttp://${#Project#E3Gateway}:8181POLICY_IDTEMPLATExs:stringBUCKET_IDTEMPLATExs:stringapplication/xmlhttp://${#Project#E3Gateway}:8181application/xmlapplication/xmlhttp://${#Project#E3Gateway}:8181POLICY_IDTEMPLATExs:stringBUCKET_IDTEMPLATExs:stringAUTH_IDTEMPLATExs:stringapplication/xmlhttp://${#Project#E3Gateway}:8181application/xmlhttp://${#Project#E3Gateway}:8181application/xmlapplication/xmlhttp://${#Project#E3Gateway}:8181AUTH_IDTEMPLATExs:stringapplication/xmlhttp://${#Project#E3Gateway}:8181application/xmlhttp://${#Project#E3Gateway}:8181application/xmlapplication/xmlhttp://${#Project#E3Gateway}:8181application/xmlhttp://${#Project#E3Gateway}:8181application/xmlapplication/xmlhttp://${#Project#E3Gateway}:8181BUCKET_IDTEMPLATExs:stringapplication/xmlapplication/xmlhttp://${#Project#E3Gateway}:8181BUCKET_IDTEMPLATExs:stringapplication/xmlapplication/xmlhttp://${#Project#E3Gateway}:8181BUCKET_IDTEMPLATExs:stringapplication/xmlapplication/xmlhttp://${#Project#E3Gateway}:8181application/xmlapplication/xmlhttp://${#Project#E3Gateway}:8181KEY_IDTEMPLATExs:stringapplication/xmlhttp://${#Project#E3Gateway}:8181application/xmlhttp://${#Project#E3Gateway}:8181application/xmlapplication/xmlhttp://${#Project#E3Gateway}:8181KEY_IDTEMPLATExs:stringapplication/xmlhttp://${#Project#E3Gateway}:8181application/xmlapplication/xmlhttp://${#Project#E3Gateway}:8181KEY_IDTEMPLATExs:stringCERT_IDTEMPLATExs:stringapplication/xmlhttp://${#Project#E3Gateway}:8181application/xmlhttp://${#Project#E3Gateway}:8181application/xmlapplication/xmlhttp://${#Project#E3Gateway}:8181KEY_IDTEMPLATExs:stringapplication/xmlhttp://${#Project#E3Gateway}:8181KEY_IDTEMPLATExs:stringapplication/xmlhttp://${#Project#E3Gateway}:8181application/xmlhttp://${#Project#E3Gateway}:8181application/xmlapplication/xmlhttp://${#Project#E3Gateway}:8181application/xmlhttp://${#Project#E3Gateway}:8181application/xmlapplication/xmlhttp://${#Project#E3Gateway}:8181CA_IDTEMPLATExs:stringapplication/xmlhttp://${#Project#E3Gateway}:8181application/xmlhttp://${#Project#E3Gateway}:8181application/xmlapplication/xmlhttp://${#Project#E3Gateway}:8181application/xmlhttp://${#Project#E3Gateway}:8181application/xmlapplication/xmlhttp://${#Project#E3Gateway}:8181CRL_IDTEMPLATExs:stringapplication/xmlhttp://${#Project#E3Gateway}:8181application/xmlhttp://${#Project#E3Gateway}:8181application/xmlapplication/xmlhttp://${#Project#E3Gateway}:8181file:/D:/Documents%20and%20Settings/mtobiasz/Desktop/targertest_1.wadl + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + +]]>http://wadl.dev.java.net/2009/02http://${#Project#E3Gateway}http://${#Project#E3Gateway}/api-http-method-endpoint1?key=api-http-method-key1http://${#Project#E3Gateway}/api-http-method-endpoint2?key=api-http-method-key2http://${#Project#E3Gateway}/api-http-method-endpoint3?key=api-http-method-key3http://${#Project#E3Gateway}/api-http-method-endpoint4?key=api-http-method-key40text/html200http://${#Project#E3Gateway}application/xml0application/xmltext/plain403 405 429text/xml200ns:responsehttp://${#Project#E3Gateway}application/xmlapplication/xmltext/plain405 429text/xml200ns:responsehttp://${#Project#E3Gateway}text/plain405 429text/xml200ns:responsehttp://${#Project#E3Gateway}0text/plain405text/xml200http://${#Project#E3Gateway} + + SEQUENTIAL + + <xml-fragment/> + http://${#Project#E3Manager}:8181 + + + <xml-fragment/> + http://${#Project#E3Manager}:8181 + + policy-provision-p1 + + + inactive + + +]]>200/response/statusSUCCESSfalsefalsefalse + + <xml-fragment/> + http://${#Project#E3Manager}:8181 + 200/response/statusSUCCESSfalsefalsefalse/response/policy/contexts/context/@idpolicy-provision-policy-context1falsefalsefalse + + <xml-fragment/> + http://${#Project#E3Manager}:8181 + + policy-provision-p1 + + + inactive + + +]]>200/response/statusSUCCESSfalsefalsefalse + + <xml-fragment/> + http://${#Project#E3Manager}:8181 + 200/response/statusSUCCESSfalsefalsefalse/response/policy/contexts/context/@idpolicy-provision-p1falsefalsefalse + + <xml-fragment/> + http://${#Project#E3Manager}:8181 + 200/response/statusSUCCESSfalsefalsefalse + + + + http://${#Project#E3Manager}:8181 + + + <xml-fragment/> + http://${#Project#E3Manager}:8181 + + policy-provision-p2 + + + inactive + + + + policypropvalue1 + policypropvalue2 + +]]>200/response/statusSUCCESSfalsefalsefalse + + <xml-fragment/> + http://${#Project#E3Manager}:8181 + 200/response/statusSUCCESSfalsefalsefalse/response/policy/contexts/context/@idpolicy-provision-policy-context2falsefalsefalse/response/policy/properties/propertypolicypropvalue1falsefalsefalse/response/policy/properties/propertypolicypropvalue2falsefalsefalse + + <xml-fragment/> + http://${#Project#E3Manager}:8181 + + policy-provision-p2 + + + inactive + + + + policypropvalue3 + policypropvalue4 + +]]>200/response/statusSUCCESSfalsefalsefalse + + <xml-fragment/> + http://${#Project#E3Manager}:8181 + 200/response/statusSUCCESSfalsefalsefalse/response/policy/contexts/context/@idpolicy-provision-policy-context2falsefalsefalse/response/policy/properties/propertypolicypropvalue3falsefalsefalse/response/policy/properties/propertypolicypropvalue4falsefalsefalse + + <xml-fragment/> + http://${#Project#E3Manager}:8181 + 200/response/statusSUCCESSfalsefalsefalse + + <xml-fragment/> + http://${#Project#E3Manager}:8181 + + + <xml-fragment/> + http://${#Project#E3Manager}:8181 + + policy-provision-p3 + + + inactive + + + + + + + + + + +]]>200/response/statusSUCCESSfalsefalsefalse + + <xml-fragment/> + http://${#Project#E3Manager}:8181 + 200/response/statusSUCCESSfalsefalsefalse/response/policy/contexts/context/@idpolicy-provision-policy-context3falsefalsefalse/response/policy/headerTransformations/headerTransformation<headerTransformation name="policytransfname1" value="policytransfvalue1" type="Request" action="Add"/>falsefalsefalse/response/policy/headerTransformations/headerTransformation<headerTransformation name="policytransfname2" property="policytransfprop2" type="Request" action="Add"/>falsefalsefalse/response/policy/headerTransformations/headerTransformation<headerTransformation name="policytransfname3" property="policytransfprop3" type="Response" action="Add"/>falsefalsefalse/response/policy/headerTransformations/headerTransformation<headerTransformation name="policytransfname4" value="policytransfvalue4" type="Response" action="Add"/>falsefalsefalse/response/policy/headerTransformations/headerTransformation<headerTransformation name="policytransfname5" type="Request" action="Remove"/>falsefalsefalse/response/policy/headerTransformations/headerTransformation<headerTransformation name="policytransfname6" type="Response" action="Remove"/>falsefalsefalse + + <xml-fragment/> + http://${#Project#E3Manager}:8181 + + policy-provision-p3 + + + inactive + + + + + + + + + + +]]>200/response/statusSUCCESSfalsefalsefalse + + <xml-fragment/> + http://${#Project#E3Manager}:8181 + 200/response/statusSUCCESSfalsefalsefalse/response/policy/contexts/context/@idpolicy-provision-policy-context3falsefalsefalse/response/policy/headerTransformations/headerTransformation<headerTransformation name="policytransfname7" value="policytransfvalue7" type="Request" action="Add"/>falsefalsefalse/response/policy/headerTransformations/headerTransformation<headerTransformation name="policytransfname8" property="policytransfprop8" type="Request" action="Add"/>falsefalsefalse/response/policy/headerTransformations/headerTransformation<headerTransformation name="policytransfname9" property="policytransfprop9" type="Response" action="Add"/>falsefalsefalse/response/policy/headerTransformations/headerTransformation<headerTransformation name="policytransfname10" value="policytransfvalue10" type="Response" action="Add"/>falsefalsefalse/response/policy/headerTransformations/headerTransformation<headerTransformation name="policytransfname11" type="Request" action="Remove"/>falsefalsefalse/response/policy/headerTransformations/headerTransformation<headerTransformation name="policytransfname12" type="Response" action="Remove"/>falsefalsefalse + + <xml-fragment/> + http://${#Project#E3Manager}:8181 + 200/response/statusSUCCESSfalsefalsefalse + + + + + + + + <xml-fragment/> + + http://${#Project#E3Manager}:8181 + + + + + + + + + + + + + http://${#Project#E3Manager}:8181 + + + + + + + + <xml-fragment/> + + http://${#Project#E3Manager}:8181 + + + + + + + + + + + + + <xml-fragment/> + + http://${#Project#E3Manager}:8181 + + + + + + + + + + + + + + <xml-fragment/> + + http://${#Project#E3Manager}:8181 + + + + + + + + <xml-fragment/> + http://${#Project#E3Manager}:8181 + + policy-provision-api4 + PassThrough + policy-provision-endpoint4 + active + false + + + noAuth + + + + + active + + + http://${#Project#Target1}:8080/proxySize + + + 1 + 0.0 + 1 + 0.0 + + +]]>200/response/statusSUCCESSfalsefalsefalse + + + + + + + <xml-fragment/> + + http://${#Project#E3Manager}:8181 + + policy-provision-auth4_1 + active + basic + + + + + + username + cGFzc3dvcmQw + + + + + + + CompanyQuota + Billing + + + + + + CompanyQuota + Billing + + + + +]]> + + + 200 + + + + + /response/status + SUCCESS + false + false + false + + + + /response/idpolicy-provision-auth4_1falsefalsefalse + + + + + + + + + + + + + <xml-fragment/> + + http://${#Project#E3Manager}:8181 + + policy-provision-p4 + + policy-provision-api4 + + + + policy-provision-auth4_1 + + + + + active + + active + reject + 98 + 1000 + + + + active + + + + + + + CompanyQuota + Billing + + + + + + CompanyQuota + Billing + + + + + + CompanyQuota + Billing + + + + +]]> + + + 200 + + + + + /response/status + SUCCESS + false + false + false + + + + /response/idpolicy-provision-p4falsefalsefalse + + + + + + + + + + + + + <xml-fragment/> + + http://${#Project#E3Manager}:8181 + + + policy-provision-api4 + + + + policy-provision-auth4_1 + + + + + active + + active + reject + 98 + 1000 + + + + active + + +]]> + + + 200 + + + + + /response/status + SUCCESS + false + false + false + + + + + + + + + + + + + policyNoId + ResponseAsXml + create policy without id - should add with generated one + /response/id + policyNoId + no id property + + + + + + + + + policyNoId + 72968eba-9643-45dd-9ab6-f48e092471a0 + + + + + + + + + policyId + ResponseAsXml + create policy without id - should add with generated one + /response/id + POLICY_ID + delete policy with id generated by E3 + + + + + + + + + <xml-fragment/> + + http://${#Project#E3Manager}:8181 + + policy-provision-p4 + + policy-provision-api4 + + + + policy-provision-auth4_1 + + + + + active + + active + reject + 98 + 1000 + + + + active + + + +]]> + + + 200 + + + + + /response/status + SUCCESS + false + false + false + + + + + + + + + + + + + + + + + <xml-fragment/> + + http://${#Project#E3Manager}:8181 + + + + 200 + + + + + /response/status + SUCCESS + false + false + false + + + + + <id>policy-provision-p4</id>falsefalse + + + + + + + + + + + + <xml-fragment/> + + http://${#Project#E3Manager}:8181 + + + + 200 + + + + + /response/status + SUCCESS + false + false + false + + + + + + + + + + + + + + + + + <xml-fragment/> + + http://${#Project#E3Manager}:8181 + + + + 200 + + + + + /response/status + SUCCESS + false + false + false + + + + /response/ids/idpolicy-provision-p4falsefalsefalse + + + ${#policyNoId}falsefalse + + + + + + + + + + + + + <xml-fragment/> + + http://${#Project#E3Manager}:8181 + + + 200 + + + + /response/status + SUCCESS + false + false + false + + + + + + + + + + + + + + + + + + + + + + + + + + + + <xml-fragment/> + + http://${#Project#E3Manager}:8181 + + + + 200 + + + + + /response/status + SUCCESS + false + false + false + + + + + + + + + + + + + + + + + <xml-fragment/> + + http://${#Project#E3Manager}:8181 + + + + 200 + + + + + /response/status + SUCCESS + false + false + false + + + + + + + + + <xml-fragment/> + http://${#Project#E3Manager}:8181 + 200 + + + + + + + + + <xml-fragment/> + + http://${#Project#E3Manager}:8181 + + + + + + + + + + + + <xml-fragment/> + http://${#Project#E3Manager}:8181 + + + + + + + + <xml-fragment/> + + http://${#Project#E3Manager}:8181 + + + + + + + + + + + + + <xml-fragment/> + + http://${#Project#E3Manager}:8181 + + + + + + + + + + + + + + <xml-fragment/> + + http://${#Project#E3Manager}:8181 + + + + + + + + <xml-fragment/> + http://${#Project#E3Manager}:8181 + + policy-provision-api5 + PassThrough + policy-provision-endpoint5 + active + false + + + noAuth + + + + + active + + + http://${#Project#Target1}:8080/proxySize + + + 1 + 0.0 + 1 + 0.0 + + +]]>200/response/statusSUCCESSfalsefalsefalse + + + + + + + <xml-fragment/> + + http://${#Project#E3Manager}:8181 + + policy-provision-auth5_1 + active + basic + + + + + + policy-provision-username5_1 + cHJvdmlzaW9uLXBvbGljeS1wYXNzd29yZDVfMQ== + + + + + + + + CompanyQuota + Billing + + + + + + CompanyQuota + Billing + + + + +]]> + + + 200 + + + + + /response/status + SUCCESS + false + false + false + + + + /response/idpolicy-provision-auth5_1falsefalsefalse + + + + + + + + + + + + + <xml-fragment/> + + http://${#Project#E3Manager}:8181 + + policy-provision-p5 + + policy-provision-api5 + + + + policy-provision-auth5_1 + + + + + active + + active + reject + 98 + 1000 + + + + active + + + +]]> + + + 200 + + + + + /response/status + SUCCESS + false + false + false + + + + /response/idpolicy-provision-p5falsefalsefalse + + + + + + + + + + + + + + + + + + + + + + + <xml-fragment/> + + http://${#Project#E3Manager}:8181 + + policy-provision-auth5_2 + active + basic + + + + + + policy-provision-username5_2 + cHJvdmlzaW9uLXBvbGljeS1wYXNzd29yZDVfMg== + + + + + + + + CompanyQuota + Billing + + + + + + CompanyQuota + Billing + + + + +]]> + + + 200 + + + + + /response/status + SUCCESS + false + false + false + + + + /response/idpolicy-provision-auth5_2falsefalsefalse + + + + + + + + + + + + + <xml-fragment/> + + http://${#Project#E3Manager}:8181 + <quotaRLBucket id="bucket1"> + <authId>policy-provision-auth5_2</authId> +</quotaRLBucket> + + + 200 + + + + + /response/status + SUCCESS + false + false + false + + + + + + + + + <xml-fragment/>UTF-8http://${#Project#E3Manager}:8181<quotaRLBucket id="bucket2_n_auth"> +</quotaRLBucket>200/response/statusSUCCESSfalsefalsefalse + + + + + <xml-fragment/> + + http://${#Project#E3Manager}:8181 + + + + 200 + + + + + /response/status + SUCCESS + false + false + false + + + + /response/policy/authIds/quotaRLBucket[@id="bucket0"]/authIdpolicy-provision-auth5_1falsefalsefalse + + + /response/policy/authIds/quotaRLBucket[@id="bucket1"]/authIdpolicy-provision-auth5_2falsefalsefalse + + + /response/policy/authIds/quotaRLBucket[@id="bucket2_n_auth"]<quotaRLBucket id="bucket2_n_auth"/>falsefalsefalse + bucket2_n_authfalsefalse + + + + + + + + + + + <xml-fragment/> + + http://${#Project#E3Manager}:8181 + + policy-provision-auth5_3 + active + basic + + + + + + policy-provision-username5_3 + cHJvdmlzaW9uLXBvbGljeS1wYXNzd29yZDVfMw== + + + + + + + + CompanyQuota + Billing + + + + + + CompanyQuota + Billing + + + + +]]> + + + 200 + + + + + /response/status + SUCCESS + false + false + false + + + + /response/idpolicy-provision-auth5_3falsefalsefalse + + + + + + + + + + + + + <xml-fragment/> + + http://${#Project#E3Manager}:8181 + <quotaRLBucket> + <authId>policy-provision-auth5_3</authId> +</quotaRLBucket> + + 200 + + + + /response/status + SUCCESS + false + false + false + + + + + + + + + + + + + + + + + <xml-fragment/> + + http://${#Project#E3Manager}:8181 + <quotaRLBucket id="bucket2"> + <authId>policy-provision-auth5_3</authId> +</quotaRLBucket> + + 500 + + + + /response/status + FAILURE + false + false + false + + + + + + + + + + + + + + + + + <xml-fragment/> + + http://${#Project#E3Manager}:8181 + + + + 200 + + + + + /response/status + SUCCESS + false + false + false + + + + + + + + + + + + + + + + + + <xml-fragment/> + + http://${#Project#E3Manager}:8181 + + + + 200 + + + + + /response/status + SUCCESS + false + false + false + + + + /response/policy/authIds/quotaRLBucket[@id="bucket0"]/authIdpolicy-provision-auth5_1falsefalsefalse + + + /response/policy/authIds/quotaRLBucket[@id="bucket1"]/authIdpolicy-provision-auth5_2falsefalsefalse + + + + auth2 + false + false + + + + + + + + + + + + + + <xml-fragment/> + + http://${#Project#E3Manager}:8181 + + + + 200 + + + + + /response/status + SUCCESS + false + false + false + + + + + + + + + + + + + + + + + <xml-fragment/> + + http://${#Project#E3Manager}:8181 + + + + 200 + + + + + /response/status + SUCCESS + false + false + false + + + + /response/policy/authIds/quotaRLBucket[@id="bucket1"]/authIdpolicy-provision-auth5_2falsefalsefalse + + + + bucket0 + false + false + + + + + auth0 + false + false + + + + + + + + + + + + + + <xml-fragment/> + + http://${#Project#E3Manager}:8181 + + + + 200 + + + + + /response/status + SUCCESS + false + false + false + + + + + + + + + + + + + + + + + <xml-fragment/> + + http://${#Project#E3Manager}:8181 + + + + 200 + + + + + /response/status + SUCCESS + false + false + false + + + + + + + + + + + + + <xml-fragment/> + + http://${#Project#E3Manager}:8181 + + + + 200 + + + + + /response/status + SUCCESS + false + false + false + + + + + + + + + + + + + <xml-fragment/> + + http://${#Project#E3Manager}:8181 + + + + 200 + + + + + /response/status + SUCCESS + false + false + false + + + + + + + + + <xml-fragment/> + http://${#Project#E3Manager}:8181 + 200 + + + + + + <xml-fragment/> + http://${#Project#E3Manager}:8181 + + + + + + + <xml-fragment/> + + http://${#Project#E3Manager}:8181 + + + + + + + + + + + + + <xml-fragment/> + + http://${#Project#E3Manager}:8181 + + + + + + + + + + + + + <xml-fragment/> + + http://${#Project#E3Manager}:8181 + + + + + + + + + + + + + + <xml-fragment/> + + http://${#Project#E3Manager}:8181 + + + + + + + + + + + + + <xml-fragment/> + + http://${#Project#E3Manager}:8181 + + + + + + + + + + + + + + + + + + <xml-fragment/> + + http://${#Project#E3Manager}:8181 + + + + + + + + + + + + + + + + + + + + + + + <xml-fragment/>http://${#Project#E3Manager}:8181 + + policy-provision-p6_1 + +]]> + + + + + + + + + + + + <xml-fragment/> + http://${#Project#E3Manager}:8181 + + policy-provision-api6 + PassThrough + policy-provision-endpoint6 + false + active + + + noAuth + + + + + active + + + http://${#Project#Target1}:8080/proxySize + + + 1 + 0.0 + 1 + 0.0 + + +]]>200/response/statusSUCCESSfalsefalsefalse + + + + + + <xml-fragment/> + + http://${#Project#E3Manager}:8181 + + policy-provision-auth6_1 + active + basic + + + + + + policy-provision-username6_1 + cHJvdmlzaW9uLXBvbGljeS1wYXNzd29yZDZfMQ== + + + + + + + + CompanyQuota + Billing + + + + + + CompanyQuota + Billing + + + + +]]> + + + 200 + + + + + /response/status + SUCCESS + false + false + false + + + + /response/idpolicy-provision-auth6_1falsefalsefalse + + + + + + + + + + + + <xml-fragment/> + + http://${#Project#E3Manager}:8181 + + policy-provision-auth6_4 + active + basic + + + + + + policy-provision-username6_4 + cG9saWN5LXByb3Zpc2lvbi1wYXNzd29yZDZfNA== + + + + + + + + CompanyQuota + Billing + + + + + + CompanyQuota + Billing + + + + +]]> + + + 200 + + + + + /response/status + SUCCESS + false + false + false + + + + /response/idpolicy-provision-auth6_4falsefalsefalse + + + + + + + + + + + + <xml-fragment/> + + http://${#Project#E3Manager}:8181 + + policy-provision-p6_1 + + policy-provision-api6 + + + + policy-provision-auth6_4 + + + + + active + + active + reject + 98 + 1000 + + + + active + + + +]]> + + + 200 + + + + + /response/status + SUCCESS + false + false + false + + + + /response/idpolicy-provision-p6_1falsefalsefalse + + + + + + + + + + + + <xml-fragment/> + + http://${#Project#E3Manager}:8181 + + policy-provision-p6_2 + + policy-provision-api6 + + + + policy-provision-auth6_4 + + + + + active + + active + reject + 98 + 1000 + + + + active + + + +]]> + + + 200 + + + + + /response/status + SUCCESS + false + false + false + + + + /response/idpolicy-provision-p6_2falsefalsefalse + + + + + + + + + + + + <xml-fragment/> + + http://${#Project#E3Manager}:8181 + + policy-provision-auth6_2 + active + basic + + + + + + policy-provision-username6_2 + cHJvdmlzaW9uLXBvbGljeS1wYXNzd29yZDZfMg== + + + + + + + + CompanyQuota + Billing + + + + + + CompanyQuota + Billing + + + + +]]> + + + 200 + + + + + /response/status + SUCCESS + false + false + false + + + + /response/idpolicy-provision-auth6_2falsefalsefalse + + + + + + + + + + + + <xml-fragment/> + + http://${#Project#E3Manager}:8181 + + policy-provision-auth6_3 + active + basic + + + + + + policy-provision-username6_3 + cHJvdmlzaW9uLXBvbGljeS1wYXNzd29yZDZfMw== + + + + + + + + CompanyQuota + Billing + + + + + + CompanyQuota + Billing + + + + +]]> + + + 200 + + + + + /response/status + SUCCESS + false + false + false + + + + /response/idpolicy-provision-auth6_3falsefalsefalse + + + + + + + <xml-fragment/>http://${#Project#E3Manager}:8181 + + policy-provision-p6_1 + policy-provision-p6_2 + + + policy-provision-auth6_1 + policy-provision-auth6_2 + +]]>200/response/statusSUCCESSfalsefalsefalse<xml-fragment/>http://${#Project#E3Manager}:8181 + + policy-provision-p6_1 + policy-provision-p6_2 + + + policy-provision-auth6_3 + policy-provision-auth6_2 + +]]>200/response/statusSUCCESSfalsefalsefalse<xml-fragment/>http://${#Project#E3Manager}:8181 + + policy-provision-p6_1 + policy-provision-p6_2 + + + policy-provision-auth6_3 + policy-provision-auth6_2 + +]]>200/response/statusSUCCESSfalsefalsefalse<xml-fragment/>http://${#Project#E3Manager}:8181 + + policy-provision-p6_1 + policy-provision-p6_2 + + + policy-provision-auth6_3 + policy-provision-auth6_2 + +]]>200/response/statusSUCCESSfalsefalsefalse<xml-fragment/>http://${#Project#E3Manager}:8181 + + policy-provision-p6_1 + +]]>200/response/statusSUCCESSfalsefalsefalse<xml-fragment/>http://${#Project#E3Manager}:8181 + + policy-provision-p6_2 + + + policy-provision-auth6_3 + policy-provision-auth6_2 + +]]>200/response/statusSUCCESSfalsefalsefalse + + + + + <xml-fragment/> + + http://${#Project#E3Manager}:8181 + + + + 200 + + + + + /response/status + SUCCESS + false + false + false + + + + + + + + + + + <xml-fragment/>http://${#Project#E3Manager}:8181 + + policy-provision-p6_2 + +]]>200/response/statusSUCCESSfalsefalsefalse + + + + + <xml-fragment/> + + http://${#Project#E3Manager}:8181 + + + + 200 + + + + + /response/status + SUCCESS + false + false + false + + + + + + + + + + + + + <xml-fragment/> + + http://${#Project#E3Manager}:8181 + + + + 200 + + + + + /response/status + SUCCESS + false + false + false + + + + + + + + + + + + + <xml-fragment/> + + http://${#Project#E3Manager}:8181 + + + + 200 + + + + + /response/status + SUCCESS + false + false + false + + + + + + + + + + + + + <xml-fragment/> + + http://${#Project#E3Manager}:8181 + + + + 200 + + + + + /response/status + SUCCESS + false + false + false + + + + + + + + + + + + <xml-fragment/> + http://${#Project#E3Manager}:8181 + 200 + + + <xml-fragment/> + http://${#Project#E3Manager}:8181 + + + <xml-fragment/> + http://${#Project#E3Manager}:8181 + + policy-provision-p7 + + policy-provision-api7 + + + + inactive + + +]]>404/response/error/errorTextAn API with that ID [policy-provision-api7] doesn't existfalsefalsefalse + + <xml-fragment/> + http://${#Project#E3Manager}:8181 + 404/response/error/errorTextA Policy with that ID [policy-provision-p7] doesn't existfalsefalsefalse + + + + + + <xml-fragment/> + + http://${#Project#E3Manager}:8181 + + + + + + + + + + + + + + + <xml-fragment/> + + http://${#Project#E3Manager}:8181 + + + + + + + + <xml-fragment/> + http://${#Project#E3Manager}:8181 + + <xml-fragment/>http://${#Project#E3Manager}:8181 + + policy-provision-p8 + +]]> + <xml-fragment/> + http://${#Project#E3Manager}:8181 + + policy-provision-api8 + PassThrough + policy-provision-endpoint8 + false + active + + + noAuth + + + + + active + + + http://${#Project#Target1}:8080/proxySize + + + 1 + 0.0 + 1 + 0.0 + + +]]>200/response/statusSUCCESSfalsefalsefalse + + + + + + <xml-fragment/> + + http://${#Project#E3Manager}:8181 + + policy-provision-auth8 + active + basic + + + + + + policy-provision-username8 + cG9saWN5LXByb3Zpc2lvbi1wYXNzd29yZDg= + + + + + + + + CompanyQuota + Billing + + + + + + CompanyQuota + Billing + + + + +]]> + + + 200 + + + + + /response/status + SUCCESS + false + false + false + + + + /response/idpolicy-provision-auth8falsefalsefalse + + + + + + + + + + + + <xml-fragment/> + + http://${#Project#E3Manager}:8181 + + policy-provision-p8 + + policy-provision-api8 + + + + policy-provision-auth8 + + + + + active + + active + reject + 98 + 1000 + + + + active + + + +]]> + + + 200 + + + + + /response/status + SUCCESS + false + false + false + + + + /response/idpolicy-provision-p8falsefalsefalse + + + + + + + <xml-fragment/>http://${#Project#E3Manager}:8181 + + policy-provision-p8 + + + policy-provision-auth8 + +]]>500/response/statusFAILUREfalsefalsefalsealready usedfalsefalse + + + + + <xml-fragment/> + + http://${#Project#E3Manager}:8181 + + + + 200 + + + + + /response/status + SUCCESS + false + false + false + + + + + + + + + + + + + + + + <xml-fragment/> + + http://${#Project#E3Manager}:8181 + + + + 200 + + + + + /response/status + SUCCESS + false + false + false + + + + + + + + + <xml-fragment/> + http://${#Project#E3Manager}:8181 + 200 + + TestCase generated for REST Resource [/apis] located + at [/apis] + + + + + + + + + + + +]]> + + http://${#Project#E3Manager}:8181 + + + + + + + + + + + <xml-fragment/>http://${#Project#E3Manager}:8181 + <xml-fragment/>http://${#Project#E3Manager}:8181 + + + + + + + + + + +]]> + + http://${#Project#E3Manager}:8181 + + policy-provision-ApiBadContext + policy-provision-ApiBadContext + 1 + PassThrough + end5 + false + + + authKey + + + key + + + + false + + active + + + active + + + + http://${#Project#Target1}:8080/proxySize + + + + value + + + + + + 10000 + -1 + 600000 + -1 + + + + + + false + + +]]> + + + 200 + + + + + /response/status + SUCCESS + false + false + false + + + + /response/idpolicy-provision-ApiBadContextfalsefalsefalse + + + + + + + + <xml-fragment/>http://${#Project#E3Manager}:8181 + policy-provision-AuthBadContext + active + authKey + + + + policy-provision-BadContextKey + + + +]]>200/response/idpolicy-provision-AuthBadContextfalsefalsefalse/response/statusSUCCESSfalsefalsefalse + <xml-fragment/>http://${#Project#E3Manager}:8181 + policy-provision-PolicyBadContext + + policy-provision-ApiBadContext + + + + policy-provision-AuthBadContext + + + + + active + + active + reject + 0.0 + 10000 + + + + + + +]]>200/response/idpolicy-provision-PolicyBadContextfalsefalsefalse/response/statusSUCCESSfalsefalsefalse + + + + + + <entry key="SIZE" value="10" xmlns="http://eviware.com/soapui/config"/> + + http://${#Project#E3Gateway}/end5?key=policy-provision-BadContextKey + + + 429 + + /data<data contentType="text/plain" contentLength="104">Issue: Rate limit exceeded. java.lang.IllegalArgumentException: There is no limit available with that ID</data>falsefalsefalse + + + + + + <xml-fragment/> + http://${#Project#E3Manager}:8181 + + policy-provision-PolicyBadContext + + policy-provision-ApiBadContext + + + + policy-provision-AuthBadContext + + + + + active + + active + reject + 0.0 + 10000 + + + + + + +]]>200/response/statusSUCCESSfalsefalsefalse + + + + + + <entry key="SIZE" value="10" xmlns="http://eviware.com/soapui/config"/> + + http://${#Project#E3Gateway}/end5?key=policy-provision-BadContextKey + + + 200 + + /data9876543210falsefalsefalse + + + + + + + + + + + + + + +]]> + + http://${#Project#E3Manager}:8181 + + + + 200 + + + + + + /response/status + SUCCESS + false + false + false + + + + + + + + <xml-fragment/>http://${#Project#E3Manager}:8181200/response/statusSUCCESSfalsefalsefalse<xml-fragment/>http://${#Project#E3Manager}:8181200/response/statusSUCCESSfalsefalsefalse + + TestCase generated for REST Resource [/apis] located + at [/apis] + + + + + + + + + + + +]]> + + http://${#Project#E3Manager}:8181 + + + + + + + + + + + <xml-fragment/>http://${#Project#E3Manager}:8181 + <xml-fragment/>http://${#Project#E3Manager}:8181 + + + + + + + + + + +]]> + + http://${#Project#E3Manager}:8181 + + policy-provision-ApiBadContext + policy-provision-ApiBadContext + 1 + PassThrough + end5 + false + + + authKey + + + key + + + + false + + active + + + active + + + + http://${#Project#Target1}:8080/proxySize + + + + value + + + + + + 10000 + -1 + 600000 + -1 + + + + + + false + + +]]> + + + 200 + + + + + /response/status + SUCCESS + false + false + false + + + + /response/idpolicy-provision-ApiBadContextfalsefalsefalse + + + + + + + + <xml-fragment/>http://${#Project#E3Manager}:8181 + policy-provision-AuthBadContext + active + authKey + + + + policy-provision-BadContextKey + + + +]]>200/response/idpolicy-provision-AuthBadContextfalsefalsefalse/response/statusSUCCESSfalsefalsefalse + <xml-fragment/>http://${#Project#E3Manager}:8181 + policy-provision-PolicyBadContext + + policy-provision-ApiBadContext + + + + policy-provision-AuthBadContext + + + + + active + + active + reject + 0.0 + 10000 + + + + + + +]]>200/response/idpolicy-provision-PolicyBadContextfalsefalsefalse/response/statusSUCCESSfalsefalsefalse + + + + + + <entry key="SIZE" value="10" xmlns="http://eviware.com/soapui/config"/> + + http://${#Project#E3Gateway}/end5?key=policy-provision-BadContextKey + + + 429 + + /data<data contentType="text/plain" contentLength="104">Issue: Rate limit exceeded. java.lang.IllegalArgumentException: There is no limit available with that ID</data>falsefalsefalse + + + + + + + + + + <xml-fragment/> + + http://${#Project#E3Manager}:8181 + + policy-provision-AuthBadContext + active + authKey + + + + policy-provision-BadContextKey + + + +]]> + /response/statusSUCCESSfalsefalsefalse + + + + + + + + + + <entry key="SIZE" value="10" xmlns="http://eviware.com/soapui/config"/> + + http://${#Project#E3Gateway}/end5?key=policy-provision-BadContextKey + + + 200 + + /data9876543210falsefalsefalse + + + + + + + + + + + + + + +]]> + + http://${#Project#E3Manager}:8181 + + + + 200 + + + + + + /response/status + SUCCESS + false + false + false + + + + + + + + <xml-fragment/>http://${#Project#E3Manager}:8181200/response/statusSUCCESSfalsefalsefalse<xml-fragment/>http://${#Project#E3Manager}:8181200/response/statusSUCCESSfalsefalsefalse + + E3Manager192.168.84.105E3Gateway192.168.84.105Target1192.168.84.90uniqdelete \ No newline at end of file diff --git a/tests/functional-tests/functional-test-rate-limit/pom.xml b/tests/functional-tests/functional-test-rate-limit/pom.xml new file mode 100644 index 0000000..e0edffd --- /dev/null +++ b/tests/functional-tests/functional-test-rate-limit/pom.xml @@ -0,0 +1,48 @@ + + 4.0.0 + com.alu.e3.functional-tests.samples + functional-test-rate-limit + pom + + + + eviware + maven-soapui-plugin + 4.0.1 + + + mysql + mysql-connector-java + 5.1.6 + + + junit + junit + 4.8.1 + + + + + test + + test + + + ${basedir}/soapui-project.xml + ${basedir}/target/surefire-reports + true + ${basedir}/soapui-project-properties.xml + + + + + + + + com.alu.e3.functional-tests + functional-tests + 0.0.1-SNAPSHOT + .. + + Functional Test Rate Limit + \ No newline at end of file diff --git a/tests/functional-tests/functional-test-rate-limit/soapui-project.xml b/tests/functional-tests/functional-test-rate-limit/soapui-project.xml new file mode 100644 index 0000000..e1172d0 --- /dev/null +++ b/tests/functional-tests/functional-test-rate-limit/soapui-project.xml @@ -0,0 +1,4076 @@ + + +http://${#Project#E3Gateway}/api-parameters-endpoint1?param1=value1&key=api-parameters-key1&param2=value2http://${#Project#E3Gateway}/api-parameters-endpoint2/five?key=api-parameters-key2http://${#Project#E3Gateway}/api-parameters-endpoint2/three/five?key=api-parameters-key2apiauthTEMPLATEkeymykeyQUERYmykeyparam1QUERYtext/plain403 500 429data200data200data0data0data0data200data200data200data200data200data200data0datatext/html200<xml-fragment/>http://${#Project#E3Gateway}keymykeyQUERYmykeyparam1value1QUERYvalue1param2value2QUERYvalue2text/plain403data200data200data0data0data0data200data200data200data200data200data200data200datatext/html2000data<xml-fragment/>http://${#Project#E3Gateway}param1value1QUERYvalue1keymykeyQUERYxs:stringmykeyparam2value2QUERYvalue2text/plain403data200data200data0data0data0data200data200data200data200data200data200datatext/html200<xml-fragment/>http://${#Project#E3Gateway}param1value1QUERYvalue1param2value2QUERYvalue2keymykeyQUERYxs:stringmykeytext/plain403data200data200data0data0data0data200data200data200data200data200data200datatext/html200<xml-fragment/>http://${#Project#E3Gateway}text/plain403data200data200data0data0data0data200data200data200data200data200data200datatext/html200text/html;charset=ISO-8859-1404htmltext/html404html<xml-fragment/>http://${#Project#E3Gateway}param1QUERYtext/plain403 500 429data200data200data0data0data0data200data200data200data200data200data200data0datatext/html200text/html404html<xml-fragment/>http://${#Project#E3Gateway}keyQUERYtext/plain403 500 429data200data200data0data0data0data200data200data200data200data200data200data0datatext/html200text/html;charset=ISO-8859-1404html<xml-fragment/>http://${#Project#E3Gateway}text/plain403data200data200data0data0data0data200data200data200data200data200data200datatext/html200text/html;charset=ISO-8859-1404html0data<xml-fragment/>http://${#Project#E3Gateway}text/plain403data200data200data0data0data0data200data200data200data200data200data200datatext/html200text/html;charset=ISO-8859-1404html<xml-fragment/>http://${#Project#E3Gateway}text/plain403data200data200data0data0data0data200data200data200data200data200data200datatext/html200text/html;charset=ISO-8859-1404html0data0data0data0data<xml-fragment/>http://${#Project#E3Gateway}param1QUERYtext/plain403data200data200data0data0data0data200data200data200data200data200data200datatext/html200text/html;charset=ISO-8859-1404html0data<xml-fragment/>http://${#Project#E3Gateway}param1QUERYkeyQUERYtext/plain403data200data200data0data0data0data200data200data200data200data200data200datatext/html200text/html;charset=ISO-8859-1404html0data<xml-fragment/>http://${#Project#E3Gateway}keyQUERYtext/plain403data200data200data0data0data0data200data200data200data200data200data200datatext/html200text/html;charset=ISO-8859-1404html0data<xml-fragment/>http://${#Project#E3Gateway}text/plain403data200data200data0data0data0data200data200data200data200data200data200datatext/html200text/html;charset=ISO-8859-1404html0data0data<xml-fragment/>http://${#Project#E3Gateway}param1QUERYtext/plain403data200data200data0data0data0data200data200data200data200data200data200datatext/html200text/html;charset=ISO-8859-1404html0data<xml-fragment/>http://${#Project#E3Gateway}param1QUERYkeyQUERYtext/plain403data200data200data0data0data0data200data200data200data200data200data200datatext/html200text/html;charset=ISO-8859-1404html0data<xml-fragment/>http://${#Project#E3Gateway}text/plain403data200data200data0data0data0data200data200data200data200data200data200datatext/html200text/html;charset=ISO-8859-1404html<xml-fragment/>http://${#Project#E3Gateway}text/plain403 500data200data200data0data0data0data200data200data200data200data200data200datatext/html200text/html;charset=ISO-8859-1404html0datatext/html; charset=iso-8859-1404html<xml-fragment/>http://${#Project#E3Gateway}text/plain403data200data200data0data0data0data200data200data200data200data200data200datatext/html200text/html;charset=ISO-8859-1404html<xml-fragment/>http://${#Project#E3Gateway}text/html200text/plain403 500datatext/html404htmlhttp://${#Project#E3Gateway} + + + http://${#Project#E3Gateway}/auth-extended-endpoint1?key=auth-extended-key1http://${#Project#E3Gateway}/auth-extended-endpoint1http://${#Project#E3Gateway}/auth-extended-endpoint2http://${#Project#E3Gateway}/api-header-transform-endpoint1?key=api-header-transform-key1http://${#Project#E3Gateway}/api-header-transform-endpoint2?key=api-header-transform-key2http://${#Project#E3Gateway}/api-header-transform-endpoint3?key=api-header-transform-key3http://${#Project#E3Gateway}/provision-api-ext-endpoint1http://${#Project#E3Gateway}/provision-api-ext-endpoint3?key=provision-api-ext-key3https://${#Project#E3Gateway}/tls2ways-call-expired-endpoint1https://${#Project#E3Gateway}/tls2ways-call-ko-endpoint1https://${#Project#E3Gateway}/tls2ways-call-no-cert-endpoint1https://${#Project#E3Gateway}/tls2ways-call-ok-endpoint1https://${#Project#E3Gateway}:25101/provision-sslkey-endpoint3https://${#Project#E3Gateway}:25101/provision-sslkey-endpoint4?key=provision-sslkey-key4http://${#Project#E3Gateway}/tdr-smoke-endpoint1?key=tdr-smoke-key1http://${#Project#E3Gateway}/tdr-endpoint1?key=tdr-key1http://${#Project#E3Gateway}/rate-limit-aib-and-cluster-endpoint2?key=rate-limit-aib-and-cluster-key2http://${#Project#E3Gateway}/rate-limit-aib-and-cluster-endpoint3?key=rate-limit-aib-and-cluster-key3http://${#Project#E3Gateway}/rate-limit-aib-endpoint2http://${#Project#E3Gateway}/rate-limit-aib-endpoint3?key=rate-limit-aib-key3 + + + + + + keyQUERY + + text/html + 200 + + html + + + + 0 + + data + + + text/plain + 500 403 401 429 + + data + + + + 200 + + data + + + + 200 + + data + + + text/html + 404 + + html + + 0data0data0data0data0data + 0data0datatext/xml200data<xml-fragment xmlns:con="http://eviware.com/soapui/config"> + <con:entry key="WAIT" value="0"/> + <con:entry key="SIZE" value="100"/> +</xml-fragment>http://${#Project#E3Gateway}/endpoint1<xml-fragment xmlns:con="http://eviware.com/soapui/config"> + <con:entry key="WAIT" value="0"/> + <con:entry key="SIZE" value="100"/> +</xml-fragment>http://${#Project#E3Gateway}/endpoint1 + text/plain401 403 429 500datatext/html200html0data0data0data0datatext/html404htmltext/xml200data0data0data0data0data0data0data0data0data0data0data0data0data0data0data0data0data0data0data<xml-fragment xmlns:con="http://eviware.com/soapui/config"> + <con:entry key="WAIT" value="0"/> + <con:entry key="SIZE" value="100"/> +</xml-fragment>http://${#Project#E3Gateway}/endpoint1text/plain401 500 429data0data0data0data0data0data0data0data0data0data0datatext/xml200datatext/html404html<xml-fragment xmlns:con="http://eviware.com/soapui/config"> + <con:entry key="Authorization" value="Basic dGVzdGVyOnRlc3RlcnBhc3N3b3Jk"/> + <con:entry key="WAIT" value="0"/> + <con:entry key="SIZE" value="100"/> +</xml-fragment>http://${#Project#E3Gateway}/endpoint1<xml-fragment xmlns:con="http://eviware.com/soapui/config"> + <con:entry key="Authorization" value="Basic invalidbasic"/> + <con:entry key="WAIT" value="0"/> + <con:entry key="SIZE" value="100"/> +</xml-fragment>http://${#Project#E3Gateway}/endpoint1text/xml200datatext/html200data<xml-fragment xmlns:con="http://eviware.com/soapui/config"> + <con:entry key="WAIT" value="0"/> + <con:entry key="SIZE" value="100"/> +</xml-fragment>http://${#Project#E3Gateway}/endpoint1?key=e88ba0c1e4c34f25bf95733eebd8574f + http://${#Project#E3Gateway}:8181/cxf/e3/prov/v1?_wadl&_type=xml + + + + E3 REST API to create, update or delete an API + + Used to get all API IDs. + + + + + + This REST API is used to create an API. + + + + + + + + + + + This REST API is used to delete an API. + + + + + + + Used to get an API by this ID. + + + + + + + This REST API is used to update an API. + + + + + + + + + + + E3 REST API to create, update or delete a policy + + This REST API is used to fetch all policy ids. + + + + + + This REST API is used to create a policy. + + + + + + + + + + + This REST API is used to delete a policy. + + + + + + + This REST API is used to fetch policy data. + + + + + + + This REST API is used to update a policy. + + + + + + + + + + + + This REST API is used to create a QuotaRLBucket in a policy. + + + + + + + + + + + + + This REST API is used to remove a bucket from a policy. + + + + + + + This REST API is used to append auths to a bucket. + + + + + + + + + + + + + + This REST API is used to remove an auth from a bucket. + + + + + + + + + E3 REST API provision authentications on E3 subsystem + + This REST API is used to get all authentications from E3 subsystem. + + + + + + This REST API is used to create an authentication element on E3 subsystem. + + + + + + + + + + + This REST API is used to delete an Auth. + + + + + + + This REST API is used to get an authentication by ID from E3 subsystem. + + + + + + + This REST API is used to update an authentication. + + + + + + + + + + + E3 REST API to create or delete a bucket of auths associated to a list of policies + + This REST API is used to create a bucket linked to a list of policies. + + + + + + + + + + + This REST API is used to append auths to a bucket for several policies. + + + + + + + + + + + + This REST API is used to remove a bucket from a list of policies. + + + + + + + + + + + E3 REST API provision SSLKeys and SSLCerts on E3 subsystem + + This REST API is used to get all SSLKeys from E3 subsystem. + + + + + + This REST API is used to create an SSLKey element on E3 subsystem. + + + + + + + + + + + This REST API is used to delete an SSLKey. + + + + + + + This REST API is used to get an SSLKey by ID from E3 subsystem. + + + + + + + This REST API is used to update an SSLKey. + + + + + + + + + + + + This REST API is used to get all SSLCerts for a key. + + + + + + + This REST API is used to create an SSLCert element on E3 subsystem. + + + + + + + + + + + + + This REST API is used to delete an SSLCert. + + + + + + + This REST API is used to get an SSLKey by ID from E3 subsystem. + + + + + + + This REST API is used to update an SSLKey. + + + + + + + + + + + + This REST API is used to get a CSR for the given SSLKey ID from E3 subsystem. + + + + + + + + + + This REST API is used to create a self-signed cert for an existing Key + + + + + + + + + E3 REST API to add/update/delete trusted CAs and CRLs + + + This REST API is used to fetch all trusted certificates authorithies. + + + + + + This REST API is used to add a trusted Certificate Authority. + + + + + + + + + + + + This REST API is used to remove a trusted Certificate Authority. + + + + + + + This REST API is used to fetch trusted Certificate Authority. + + + + + + + This REST API is used to update a trusted Certificate Authority. + + + + + + + + + + + This REST API is used to fetch trusted Certificate Authority. + + + + + + This REST API is used to add a Certificate Revocation List for this Certificate Authority. + + + + + + + + + + + + This REST API is used to remove a certificate revocation list from a certificate authority. + + + + + + + This REST API is used to fetch Certificate Revocation List. + + + + + + + This REST API is used to update a certificate revocation list. + + + + + + + + + + +]]>http://wadl.dev.java.net/2009/02http://${#Project#E3Gateway}:8181API_IDTEMPLATExs:stringapplication/xmlhttp://${#Project#E3Gateway}:8181application/xmlhttp://${#Project#E3Gateway}:8181application/xmlapplication/xmlhttp://${#Project#E3Gateway}:8181application/xmlhttp://${#Project#E3Gateway}:8181application/xmlapplication/xmlhttp://${#Project#E3Gateway}:8181POLICY_IDTEMPLATExs:stringapplication/xmlhttp://${#Project#E3Gateway}:8181application/xmlhttp://${#Project#E3Gateway}:8181application/xmlapplication/xmlhttp://${#Project#E3Gateway}:8181POLICY_IDTEMPLATExs:stringapplication/xmlapplication/xmlhttp://${#Project#E3Gateway}:8181POLICY_IDTEMPLATExs:stringBUCKET_IDTEMPLATExs:stringapplication/xmlhttp://${#Project#E3Gateway}:8181application/xmlapplication/xmlhttp://${#Project#E3Gateway}:8181POLICY_IDTEMPLATExs:stringBUCKET_IDTEMPLATExs:stringAUTH_IDTEMPLATExs:stringapplication/xmlhttp://${#Project#E3Gateway}:8181application/xmlhttp://${#Project#E3Gateway}:8181application/xmlapplication/xmlhttp://${#Project#E3Gateway}:8181AUTH_IDTEMPLATExs:stringapplication/xmlhttp://${#Project#E3Gateway}:8181application/xmlhttp://${#Project#E3Gateway}:8181application/xmlapplication/xmlhttp://${#Project#E3Gateway}:8181application/xmlhttp://${#Project#E3Gateway}:8181application/xmlapplication/xmlhttp://${#Project#E3Gateway}:8181BUCKET_IDTEMPLATExs:stringapplication/xmlapplication/xmlhttp://${#Project#E3Gateway}:8181BUCKET_IDTEMPLATExs:stringapplication/xmlapplication/xmlhttp://${#Project#E3Gateway}:8181application/xmlapplication/xmlhttp://${#Project#E3Gateway}:8181KEY_IDTEMPLATExs:stringapplication/xmlhttp://${#Project#E3Gateway}:8181application/xmlhttp://${#Project#E3Gateway}:8181application/xmlapplication/xmlhttp://${#Project#E3Gateway}:8181KEY_IDTEMPLATExs:stringapplication/xmlhttp://${#Project#E3Gateway}:8181application/xmlapplication/xmlhttp://${#Project#E3Gateway}:8181KEY_IDTEMPLATExs:stringCERT_IDTEMPLATExs:stringapplication/xmlhttp://${#Project#E3Gateway}:8181application/xmlhttp://${#Project#E3Gateway}:8181application/xmlapplication/xmlhttp://${#Project#E3Gateway}:8181KEY_IDTEMPLATExs:stringapplication/xmlhttp://${#Project#E3Gateway}:8181KEY_IDTEMPLATExs:stringapplication/xmlhttp://${#Project#E3Gateway}:8181application/xml<xml-fragment/>http://${#Project#E3Gateway}:8181application/xmlapplication/xmlhttp://${#Project#E3Gateway}:8181application/xml<xml-fragment/>http://${#Project#E3Gateway}:8181application/xmlapplication/xmlhttp://${#Project#E3Gateway}:8181CA_IDTEMPLATExs:stringapplication/xmlhttp://${#Project#E3Gateway}:8181application/xmlhttp://${#Project#E3Gateway}:8181application/xmlapplication/xmlhttp://${#Project#E3Gateway}:8181application/xmlhttp://${#Project#E3Gateway}:8181application/xmlapplication/xmlhttp://${#Project#E3Gateway}:8181CRL_IDTEMPLATExs:stringapplication/xmlhttp://${#Project#E3Gateway}:8181application/xmlhttp://${#Project#E3Gateway}:8181application/xmlapplication/xmlhttp://${#Project#E3Gateway}:8181file:/D:/Documents%20and%20Settings/mtobiasz/Desktop/targertest_1.wadl + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + +]]>http://wadl.dev.java.net/2009/02http://${#Project#E3Gateway}http://${#Project#E3Gateway}/api-http-method-endpoint1?key=api-http-method-key1http://${#Project#E3Gateway}/api-http-method-endpoint2?key=api-http-method-key2http://${#Project#E3Gateway}/api-http-method-endpoint3?key=api-http-method-key3http://${#Project#E3Gateway}/api-http-method-endpoint4?key=api-http-method-key40text/html200http://${#Project#E3Gateway}application/xml0application/xmltext/plain403 405 429text/xml200ns:responsehttp://${#Project#E3Gateway}application/xmlapplication/xmltext/plain405 429text/xml200ns:responsehttp://${#Project#E3Gateway}text/plain405 429text/xml200ns:responsehttp://${#Project#E3Gateway}0text/plain405text/xml200http://${#Project#E3Gateway}http://135.248.213.24:8181pathToConfigFilesDirectoryTEMPLATExs:stringapplication/octet-streamhttp://135.248.213.24:8181application/octet-streamhttp://135.248.213.24:8181numLinesTEMPLATExs:stringapplication/xmlhttp://135.248.213.24:8181numLinesTEMPLATExs:stringapplication/xmlhttp://135.248.213.24:8181application/xmlhttp://135.248.213.24:8181instanceIdTEMPLATExs:stringapplication/xmlhttp://135.248.213.24:8181application/octet-streamapplication/xmlhttp://135.248.213.24:8181instanceIdTEMPLATExs:stringapplication/xmlhttp://135.248.213.24:8181application/octet-streamapplication/xmlhttp://135.248.213.24:8181instanceIdTEMPLATExs:stringapplication/xmlhttp://135.248.213.24:8181application/octet-streamapplication/xmlhttp://135.248.213.24:8181application/octet-streamhttp://135.248.213.24:8181application/octet-streamhttp://135.248.213.24:8181application/xmlhttp://135.248.213.24:8181application/octet-streamapplication/xmlhttp://135.248.213.24:8181application/xmlhttp://135.248.213.24:8181application/xmlapplication/xmlhttp://135.248.213.24:8181application/xmlhttp://135.248.213.24:8181application/octet-streamapplication/xmlhttp://135.248.213.24:8181application/xmlhttp://135.248.213.24:8181application/octet-streamapplication/xmlhttp://135.248.213.24:8181 + TestSuite generated for REST Service + [functional-test-rate-limit] + + SEQUENTIAL + + + + + + + Provision rate limits for an API, and check that expected value were actually provisioned. + + + + + + + + + + + +]]> + + + http://${#Project#E3Manager}:8181 + + + + + + + + <xml-fragment/>http://${#Project#E3Manager}:8181 + <xml-fragment/>http://${#Project#E3Manager}:8181 + + + + + + + + + +]]> + + http://${#Project#E3Manager}:8181 + + rate-limit-aib-and-cluster-api1 + rate-limit-aib-and-cluster-api1 + PassThrough + active + rate-limit-aib-and-cluster-endpoint1 + false + + + authKey + + + key + + + + false + + + + active + + + http://${#Project#Target1}:8080/proxySize + + NoAuth + + key000Val + + + + + 100 + 50 + 150 + 10 + + + + + + + CompanyQuota + Billing + + + + + + CompanyQuota + Billing + + + +]]> + + 200 + + + + /response/status + SUCCESS + false + false + false + + + + /response/idrate-limit-aib-and-cluster-api1falsefalsefalse + + + + + + + <xml-fragment/>http://${#Project#E3Manager}:8181 + rate-limit-aib-and-cluster-auth1 + active + authKey + + + + rate-limit-aib-and-cluster-key1 + + + + + + CompanyQuota + Billing + + + + + + CompanyQuota + Billing + + + +]]>200/response/idrate-limit-aib-and-cluster-auth1falsefalsefalse/response/statusSUCCESSfalsefalsefalse + <xml-fragment/>http://${#Project#E3Manager}:8181 + rate-limit-aib-and-cluster-p1 + + rate-limit-aib-and-cluster-api1 + + + + rate-limit-aib-and-cluster-auth1 + + + + + active + + active + reject + 98 + 1000 + + + + active + + +]]>200/response/idrate-limit-aib-and-cluster-p1falsefalsefalse/response/statusSUCCESSfalsefalsefalse + + + + <xml-fragment/>http://${#Project#E3Manager}:8181/response/api/contexts/context/maxRateLimitTPSThreshold100falsefalsefalse/response/api/contexts/context/maxRateLimitTPSWarning50.0falsefalsefalse/response/api/contexts/context/maxRateLimitTPMThreshold150falsefalsefalse/response/api/contexts/context/maxRateLimitTPMWarning10.0falsefalsefalse<xml-fragment/>http://${#Project#E3Manager}:8181200/response/statusSUCCESSfalsefalsefalse<xml-fragment/>http://${#Project#E3Manager}:8181200/response/statusSUCCESSfalsefalsefalse + + + + + + + + + +]]> + + + http://${#Project#E3Manager}:8181 + + 200 + + + + + + + + + + + + Provision rate limits for an API, and check that expected value were actually provisioned. + + + + + + + + + + + +]]> + + + http://${#Project#E3Manager}:8181 + + + + + + + + <xml-fragment/>http://${#Project#E3Manager}:8181 + <xml-fragment/>http://${#Project#E3Manager}:8181 + + + + + + + + + +]]> + + http://${#Project#E3Manager}:8181 + + rate-limit-aib-and-cluster-api2 + rate-limit-aib-and-cluster-api2 + PassThrough + active + rate-limit-aib-and-cluster-endpoint2 + false + + + authKey + + + key + + + + false + + + + active + + + http://${#Project#Target1}:8080/proxySize + + NoAuth + + key000Val + + + + + -1 + -1.0 + -1 + -1.0 + + + + + + + CompanyQuota + Billing + + + + + + CompanyQuota + Billing + + + +]]> + + 200 + + + + /response/status + SUCCESS + false + false + false + + + + /response/idrate-limit-aib-and-cluster-api2falsefalsefalse + + + + + + + <xml-fragment/>http://${#Project#E3Manager}:8181 + rate-limit-aib-and-cluster-auth2 + active + authKey + + + + rate-limit-aib-and-cluster-key2 + + + + + + CompanyQuota + Billing + + + + + + CompanyQuota + Billing + + + +]]>200/response/idrate-limit-aib-and-cluster-auth2falsefalsefalse/response/statusSUCCESSfalsefalsefalse + <xml-fragment/>http://${#Project#E3Manager}:8181 + rate-limit-aib-and-cluster-p2 + + rate-limit-aib-and-cluster-api2 + + + + rate-limit-aib-and-cluster-auth2 + + + + + active + + active + reject + -1.0 + -1 + + + + active + + +]]>200/response/idrate-limit-aib-and-cluster-p2falsefalsefalse/response/statusSUCCESSfalsefalsefalse + + + + + + + + + <xml-fragment/> + + http://${#Project#E3Gateway}/rate-limit-aib-and-cluster-endpoint2?key=rate-limit-aib-and-cluster-key2 + + + 200 + + + + + + + + + + + + <xml-fragment/> + + http://${#Project#E3Gateway}/rate-limit-aib-and-cluster-endpoint2?key=rate-limit-aib-and-cluster-key2 + + + + 200 + + + + + + + + + + + + + <xml-fragment/> + + http://${#Project#E3Gateway}/rate-limit-aib-and-cluster-endpoint2?key=rate-limit-aib-and-cluster-key2 + + + + 200 + + + + + + + + <xml-fragment/>http://${#Project#E3Manager}:8181/response/api/contexts/context/maxRateLimitTPSThreshold-1falsefalsefalse/response/api/contexts/context/maxRateLimitTPSWarning-1.0falsefalsefalse/response/api/contexts/context/maxRateLimitTPMThreshold-1falsefalsefalse/response/api/contexts/context/maxRateLimitTPMWarning-1.0falsefalsefalse<xml-fragment/>http://${#Project#E3Manager}:8181200/response/statusSUCCESSfalsefalsefalse<xml-fragment/>http://${#Project#E3Manager}:8181200/response/statusSUCCESSfalsefalsefalse + + + + + + + + + +]]> + + + http://${#Project#E3Manager}:8181 + + 200 + + + + + + + Provision rate limits for an API, and check that expected value were actually provisioned. + + + + + + + + + + + +]]> + + + http://${#Project#E3Manager}:8181 + + + + + + + + <xml-fragment/>http://${#Project#E3Manager}:8181 + <xml-fragment/>http://${#Project#E3Manager}:8181 + + + + + + + + + +]]> + + http://${#Project#E3Manager}:8181 + + rate-limit-aib-and-cluster-api3 + rate-limit-aib-and-cluster-api3 + PassThrough + active + rate-limit-aib-and-cluster-endpoint3 + false + + + authKey + + + key + + + + false + + + + active + + + http://${#Project#Target1}:8080/proxySize + + NoAuth + + key000Val + + + + + 0 + 0.0 + 0 + 0.0 + + + + + + + CompanyQuota + Billing + + + + + + CompanyQuota + Billing + + + +]]> + + 200 + + + + /response/status + SUCCESS + false + false + false + + + + /response/idrate-limit-aib-and-cluster-api3falsefalsefalse + + + + + + + <xml-fragment/>http://${#Project#E3Manager}:8181 + rate-limit-aib-and-cluster-auth3 + active + authKey + + + + rate-limit-aib-and-cluster-key3 + + + + + + CompanyQuota + Billing + + + + + + CompanyQuota + Billing + + + +]]>200/response/idrate-limit-aib-and-cluster-auth3falsefalsefalse/response/statusSUCCESSfalsefalsefalse + <xml-fragment/>http://${#Project#E3Manager}:8181 + rate-limit-aib-and-cluster-p3 + + rate-limit-aib-and-cluster-api3 + + + + rate-limit-aib-and-cluster-auth3 + + + + + active + + active + reject + 0.0 + 0 + + + + active + + +]]>200/response/idrate-limit-aib-and-cluster-p3falsefalsefalse/response/statusSUCCESSfalsefalsefalse + + + + + + + + + <xml-fragment/> + + http://${#Project#E3Gateway}/rate-limit-aib-and-cluster-endpoint3?key=rate-limit-aib-and-cluster-key3 + + + 429 + + + + + + + <xml-fragment/>http://${#Project#E3Manager}:8181/response/api/contexts/context/maxRateLimitTPSThreshold0falsefalsefalse/response/api/contexts/context/maxRateLimitTPSWarning0.0falsefalsefalse/response/api/contexts/context/maxRateLimitTPMThreshold0falsefalsefalse/response/api/contexts/context/maxRateLimitTPMWarning0.0falsefalsefalse<xml-fragment/>http://${#Project#E3Manager}:8181200/response/statusSUCCESSfalsefalsefalse<xml-fragment/>http://${#Project#E3Manager}:8181200/response/statusSUCCESSfalsefalsefalse + + + + + + + + + +]]> + + + http://${#Project#E3Manager}:8181 + + 200 + + + + + + + SEQUENTIAL + Provision rate limits for an API, then call that API. + + + + + + + + + + + +]]> + + + http://${#Project#E3Manager}:8181 + + + + + + + + + + + + + + + + + + +]]> + + http://${#Project#E3Manager}:8181 + + rate-limit-aib-api2 + rate-limit-aib-api2 + PassThrough + active + rate-limit-aib-endpoint2 + false + + + noAuth + + + + false + + + + active + + + http://${#Project#Target1}:8080/proxySize + + NoAuth + + key000Val + + + + + 100 + 1 + 3 + 1 + + + + + + + CompanyQuota + Billing + + + + + + CompanyQuota + Billing + + + +]]> + + 200 + + + + /response/status + SUCCESS + false + false + false + + + + /response/idrate-limit-aib-api2falsefalsefalse + + + + + + + + + + + + + + <xml-fragment/> + + http://${#Project#E3Gateway}/rate-limit-aib-endpoint2 + + 200 + + + + + <xml-fragment/> + + http://${#Project#E3Gateway}/rate-limit-aib-endpoint2 + + 200 + + + + + <xml-fragment/> + + http://${#Project#E3Gateway}/rate-limit-aib-endpoint2 + + 200 + + + + + <xml-fragment/> + + http://${#Project#E3Gateway}/rate-limit-aib-endpoint2 + + 429 + + + + + <xml-fragment/> + + http://${#Project#E3Gateway}/rate-limit-aib-endpoint2 + + 429 + + + + + + + + + + + + +]]> + + + http://${#Project#E3Manager}:8181 + + 200 + + + + + + + Provision rate limits for an API, and check that expected value were actually provisioned. + + + + + + + + + + + +]]> + + + http://${#Project#E3Manager}:8181 + + + + + + + + <xml-fragment/>http://${#Project#E3Manager}:8181 + <xml-fragment/>http://${#Project#E3Manager}:8181<xml-fragment/>http://${#Project#E3Manager}:8181 + + + + + + + + + +]]> + + http://${#Project#E3Manager}:8181 + + rate-limit-aib-api3 + rate-limit-aib-auth3 + PassThrough + active + rate-limit-aib-endpoint3 + false + + + authKey + + + key + + + + true + + + + active + + + http://${#Project#Target1}:8080/proxySize + + NoAuth + + key000Val + + + + + 100 + 90 + 6000 + 90 + + + + + + + CompanyQuota + Billing + + + + + + CompanyQuota + Billing + + + +]]> + + 200 + + + + /response/status + SUCCESS + false + false + false + + + + /response/idrate-limit-aib-api3falsefalsefalse + + + + + + + + <xml-fragment/>http://${#Project#E3Manager}:8181 + rate-limit-aib-auth3 + active + authKey + + + + rate-limit-aib-key3 + + + + + + CompanyQuota + Billing + + + + + + CompanyQuota + Billing + + + +]]>200/response/idrate-limit-aib-auth3falsefalsefalse/response/statusSUCCESSfalsefalsefalse + + + + <xml-fragment/>http://${#Project#E3Manager}:8181 + rate-limit-aib-p3_1 + + rate-limit-aib-api3 + + + + rate-limit-aib-auth3 + + + + + active + + active + reject + 98 + 5 + + + + active + + active + reject + 98 + 10 + + + +]]>200/response/idrate-limit-aib-p3_1falsefalsefalse/response/statusSUCCESSfalsefalsefalse<xml-fragment/>http://${#Project#E3Manager}:8181<xml-fragment/>http://${#Project#E3Manager}:8181 + rate-limit-aib-p3_1 + + rate-limit-aib-api3 + + + + rate-limit-aib-auth3 + + + + + active + + active + reject + 98 + 10 + + + + active + + active + reject + 98 + 5 + + + +]]>200/response/idrate-limit-aib-p3_1falsefalsefalse/response/statusSUCCESSfalsefalsefalse<xml-fragment/>http://${#Project#E3Manager}:8181<xml-fragment/>http://${#Project#E3Manager}:8181 + rate-limit-aib-p3_1 + + rate-limit-aib-api3 + + + + rate-limit-aib-auth3 + + + + + active + + active + reject + 98 + 50 + + + + active + + active + reject + 98 + 5 + + + +]]>200/response/idrate-limit-aib-p3_1falsefalsefalse/response/statusSUCCESSfalsefalsefalse<xml-fragment/>http://${#Project#E3Manager}:8181 + rate-limit-aib-p3_2 + + + rate-limit-aib-auth3 + + + + + active + + active + reject + 98 + 10 + + + + active + + active + reject + 98 + 5 + + + +]]>200/response/idrate-limit-aib-p3_2falsefalsefalse/response/statusSUCCESSfalsefalsefalse<xml-fragment/>http://${#Project#E3Manager}:8181200/response/statusSUCCESSfalsefalsefalse<xml-fragment/>http://${#Project#E3Manager}:8181200/response/statusSUCCESSfalsefalsefalse<xml-fragment/>http://${#Project#E3Manager}:8181200/response/statusSUCCESSfalsefalsefalse + + + + + + + + + +]]> + + + http://${#Project#E3Manager}:8181 + + + + + + + + + <xml-fragment/> + + http://${#Project#E3Gateway}/rate-limit-aib-endpoint3?key=rate-limit-aib-key3 + + 200 + + + + + <xml-fragment/> + + http://${#Project#E3Gateway}/rate-limit-aib-endpoint3?key=rate-limit-aib-key3 + + 429 + + + + + TestCase generated for REST Resource [/apis] located + at [/apis] + + + + + + + + + + + +]]> + + + http://${#Project#E3Manager}:8181 + + + + + + + + + + + + + + + + + +]]> + + + http://${#Project#E3Manager}:8181 + + + + + + + + + + + http://${#Project#E3Manager}:8181http://${#Project#E3Manager}:8181 + + + + + + + + + + + +]]> + + http://${#Project#E3Manager}:8181 + + rate-limit-aib-api4_1 + test_subscription_route + PassThrough + Subscription + active + rate-limit-aib-endpoint4 + false + + + authKey + + + key + + + + false + + + + active + + + http://${#Project#Target1}:8080/compositeEndpoint + + NoAuth + + key000Val + + + + + 100 + 0.0 + 600 + 0.0 + + + + + + + CompanyQuota + Billing + + + + + + CompanyQuota + Billing + + + +]]> + + 200 + + + + /response/status + SUCCESS + false + false + false + + + + /response/idrate-limit-aib-api4_1falsefalsefalse + + + + + + + + + + + + + + + + +]]> + + http://${#Project#E3Manager}:8181 + + rate-limit-aib-api4_2 + test_notification_route + PassThrough + Notification + Header + active + rate-limit-aib-endpoint4_2 + false + + + noAuth + + + + false + + + + active + 100 + 0.0 + 600 + 0.0 + + + + + + + CompanyQuota + Billing + + + + + + CompanyQuota + Billing + + + +]]> + + 200 + + + + /response/status + SUCCESS + false + false + false + + + + /response/idrate-limit-aib-api4_2falsefalsefalse + + + + + + + <xml-fragment/>http://${#Project#E3Manager}:8181 + rate-limit-aib-auth4 + active + authKey + + + + + rate-limit-aib-key4 + + + + + + CompanyQuota + Billing + + + + + + CompanyQuota + Billing + + + + +]]>200/response/statusSUCCESSfalsefalsefalse<xml-fragment/>http://${#Project#E3Manager}:8181 + rate-limit-aib-p4 + + rate-limit-aib-api4_1 + + + + rate-limit-aib-auth4 + + + + + active + + active + reject + 98 + 2 + + + + +]]>200/response/statusSUCCESSfalsefalsefalse<xml-fragment xmlns:con="http://eviware.com/soapui/config"> + <con:entry key="SIZE" value="9"/> + <con:entry key="notifyUrl" value="http://${#Project#Target1}:8080/parametersEndpoint.php?param=test1"/> +</xml-fragment>http://${#Project#E3Gateway}/rate-limit-aib-endpoint4?key=rate-limit-aib-key4200// check that OAP_StatusCode header is not present +// it must be removed by E3 +assert messageExchange.responseHeaders["OAP_StatusCode"] == nullexists(/data/subscriberId)truefalsefalsefalse<xml-fragment xmlns:con="http://eviware.com/soapui/config"> + <con:entry key="SIZE" value="9"/> + <con:entry key="notifyUrl" value="http://${#Project#Target1}:8080/parametersEndpoint.php?param=test1"/> +</xml-fragment>http://${#Project#E3Gateway}/rate-limit-aib-endpoint4?key=rate-limit-aib-key4200// check that OAP_StatusCode header is not present +// it must be removed by E3 +assert messageExchange.responseHeaders["OAP_StatusCode"] == nullexists(/data/subscriberId)truefalsefalsefalsesubscriberIdResponseAsXmlRequest - Test Subscription API #1/data/subscriberIdsubscriberId#TestCase#<xml-fragment xmlns:con="http://eviware.com/soapui/config"> + <con:entry key="SIZE" value="9"/> + <con:entry key="notifyUrl" value="http://${#Project#Target1}:8080/parametersEndpoint.php?param=test1"/> +</xml-fragment>http://${#Project#E3Gateway}/rate-limit-aib-endpoint4?key=rate-limit-aib-key4429<xml-fragment xmlns:con="http://eviware.com/soapui/config"> + <con:entry key="X-SubscriberID" value="${#TestCase#subscriberId}"/> + <con:entry key="SIZE" value="9"/> + <con:entry key="notifyUrl" value="http://${#Project#Target1}:8080/parametersEndpoint.php?param=test1"/> +</xml-fragment>http://${#Project#E3Gateway}/rate-limit-aib-endpoint4_2200// check that OAP_StatusCode header is not present +// it must be removed by E3 +assert messageExchange.responseHeaders["OAP_StatusCode"] == null/response/data876543210falsefalsefalse/response/parameters/parameter[@key='param' and @type='get']test1falsefalsefalse<xml-fragment xmlns:con="http://eviware.com/soapui/config"> + <con:entry key="X-SubscriberID" value="${#TestCase#subscriberId}"/> + <con:entry key="notifyUrl" value="http://${#Project#Target1}:8080/parametersEndpoint.php?param=test1"/> + <con:entry key="SIZE" value="9"/> +</xml-fragment>http://${#Project#E3Gateway}/rate-limit-aib-endpoint4_2200// check that OAP_StatusCode header is not present +// it must be removed by E3 +assert messageExchange.responseHeaders["OAP_StatusCode"] == null/response/data876543210falsefalsefalse/response/parameters/parameter[@key='param' and @type='get']test1falsefalsefalse<xml-fragment xmlns:con="http://eviware.com/soapui/config"> + <con:entry key="X-SubscriberID" value="${#TestCase#subscriberId}"/> + <con:entry key="notifyUrl" value="http://${#Project#Target1}:8080/parametersEndpoint.php?param=test1"/> + <con:entry key="SIZE" value="9"/> +</xml-fragment>http://${#Project#E3Gateway}/rate-limit-aib-endpoint4_2200// check that OAP_StatusCode header is not present +// it must be removed by E3 +assert messageExchange.responseHeaders["OAP_StatusCode"] == null/response/data876543210falsefalsefalse/response/parameters/parameter[@key='param' and @type='get']test1falsefalsefalse + + + + + + + + + +]]> + + http://${#Project#E3Manager}:8181 + + + + 200 + + + + + + /response/status + SUCCESS + false + false + false + + + + + + + + + + + + + + + + + +]]> + + http://${#Project#E3Manager}:8181 + + + + 200 + + + + + + /response/status + SUCCESS + false + false + false + + + + + + + + <xml-fragment/>http://${#Project#E3Manager}:8181200/response/statusSUCCESSfalsefalsefalse<xml-fragment/>http://${#Project#E3Manager}:8181200/response/statusSUCCESSfalsefalsefalsesubscriberIdrate-limit-aib-api4_1|rate-limit-aib-auth4 + + TestCase generated for REST Resource [/apis] located + at [/apis] + + + + + + + + + + + +]]> + + + http://${#Project#E3Manager}:8181 + + + + + + + + + + + + + + + + + +]]> + + + http://${#Project#E3Manager}:8181 + + + + + + + + + + + <xml-fragment/>http://${#Project#E3Manager}:8181<xml-fragment/>http://${#Project#E3Manager}:8181 + + + + + + + + + + + +]]> + + http://${#Project#E3Manager}:8181 + + rate-limit-aib-api5_1 + test_subscription_route + PassThrough + Subscription + active + rate-limit-aib-endpoint5 + false + + + authKey + + + key + + + + false + + + + active + + + http://${#Project#Target1}:8080/compositeEndpoint + + NoAuth + + key000Val + + + + + 100 + 0.0 + 600 + 0.0 + + + + + + + CompanyQuota + Billing + + + + + + CompanyQuota + Billing + + + +]]> + + 200 + + + + /response/status + SUCCESS + false + false + false + + + + /response/idrate-limit-aib-api5_1falsefalsefalse + + + + + + + + + + + + + + + + +]]> + + http://${#Project#E3Manager}:8181 + + rate-limit-aib-api5_2 + test_notification_route + PassThrough + Notification + Header + active + rate-limit-aib-endpoint5_2 + false + + + noAuth + + + + false + + + + active + 100 + 0.0 + 600 + 0.0 + + + + + + + CompanyQuota + Billing + + + + + + CompanyQuota + Billing + + + +]]> + + 200 + + + + /response/status + SUCCESS + false + false + false + + + + /response/idrate-limit-aib-api5_2falsefalsefalse + + + + + + + <xml-fragment/>http://${#Project#E3Manager}:8181 + rate-limit-aib-auth5 + active + authKey + + + + + rate-limit-aib-key5 + + + + + + CompanyQuota + Billing + + + + + + CompanyQuota + Billing + + + + +]]>200/response/statusSUCCESSfalsefalsefalse<xml-fragment/>http://${#Project#E3Manager}:8181 + rate-limit-aib-p5 + + rate-limit-aib-api5_1 + rate-limit-aib-api5_2 + + + + rate-limit-aib-auth5 + + + + + active + + active + reject + 98 + 3 + + + + +]]>200/response/statusSUCCESSfalsefalsefalse<xml-fragment xmlns:con="http://eviware.com/soapui/config"> + <con:entry key="notifyUrl" value="http://${#Project#Target1}:8080/parametersEndpoint.php?param=test1"/> + <con:entry key="SIZE" value="9"/> +</xml-fragment>http://${#Project#E3Gateway}/rate-limit-aib-endpoint5?key=rate-limit-aib-key5200// check that OAP_StatusCode header is not present +// it must be removed by E3 +assert messageExchange.responseHeaders["OAP_StatusCode"] == nullexists(/data/subscriberId)truefalsefalsefalsesubscriberIdResponseAsXmlRequest - Test Subscription API #1/data/subscriberIdsubscriberId#TestCase#<xml-fragment xmlns:con="http://eviware.com/soapui/config"> + <con:entry key="X-SubscriberID" value="${#TestCase#subscriberId}"/> + <con:entry key="SIZE" value="9"/> + <con:entry key="notifyUrl" value="http://${#Project#Target1}:8080/parametersEndpoint.php?param=test1"/> +</xml-fragment>http://${#Project#E3Gateway}/rate-limit-aib-endpoint5_2200// check that OAP_StatusCode header is not present +// it must be removed by E3 +assert messageExchange.responseHeaders["OAP_StatusCode"] == null/response/data876543210falsefalsefalse/response/parameters/parameter[@key='param' and @type='get']test1falsefalsefalse<xml-fragment xmlns:con="http://eviware.com/soapui/config"> + <con:entry key="X-SubscriberID" value="${#TestCase#subscriberId}"/> + <con:entry key="SIZE" value="9"/> + <con:entry key="notifyUrl" value="http://${#Project#Target1}:8080/parametersEndpoint.php?param=test1"/> +</xml-fragment>http://${#Project#E3Gateway}/rate-limit-aib-endpoint5_2200// check that OAP_StatusCode header is not present +// it must be removed by E3 +assert messageExchange.responseHeaders["OAP_StatusCode"] == null/response/data876543210falsefalsefalse/response/parameters/parameter[@key='param' and @type='get']test1falsefalsefalse<xml-fragment xmlns:con="http://eviware.com/soapui/config"> + <con:entry key="X-SubscriberID" value="${#TestCase#subscriberId}"/> + <con:entry key="notifyUrl" value="http://${#Project#Target1}:8080/parametersEndpoint.php?param=test1"/> + <con:entry key="SIZE" value="9"/> +</xml-fragment>http://${#Project#E3Gateway}/rate-limit-aib-endpoint5_2429<xml-fragment xmlns:con="http://eviware.com/soapui/config"> + <con:entry key="notifyUrl" value="http://${#Project#Target1}:8080/parametersEndpoint.php?param=test1"/> + <con:entry key="SIZE" value="9"/> +</xml-fragment>http://${#Project#E3Gateway}/rate-limit-aib-endpoint5?key=rate-limit-aib-key5429 + + + + + + + + + +]]> + + http://${#Project#E3Manager}:8181 + + + + 200 + + + + + + /response/status + SUCCESS + false + false + false + + + + + + + + + + + + + + + + + +]]> + + http://${#Project#E3Manager}:8181 + + + + 200 + + + + + + /response/status + SUCCESS + false + false + false + + + + + + + + <xml-fragment/>http://${#Project#E3Manager}:8181200/response/statusSUCCESSfalsefalsefalse<xml-fragment/>http://${#Project#E3Manager}:8181200/response/statusSUCCESSfalsefalsefalsesubscriberIdrate-limit-aib-api5_1|rate-limit-aib-auth5 + + TestCase generated for REST Resource [/apis] located + at [/apis] + + + + + + + + + + + +]]> + + + http://${#Project#E3Manager}:8181 + + + + + + + + + + + + + + + + + +]]> + + + http://${#Project#E3Manager}:8181 + + + + + + + + + + + <xml-fragment/>http://${#Project#E3Manager}:8181<xml-fragment/>http://${#Project#E3Manager}:8181 + + + + + + + + + + + +]]> + + http://${#Project#E3Manager}:8181 + + rate-limit-aib-api6_1 + test_subscription_route + PassThrough + Subscription + active + rate-limit-aib-endpoint6 + false + + + authKey + + + key + + + + false + + + + active + + + http://${#Project#Target1}:8080/compositeEndpoint + + NoAuth + + key000Val + + + + + 100 + 0.0 + 600 + 0.0 + + + + + + + CompanyQuota + Billing + + + + + + CompanyQuota + Billing + + + +]]> + + 200 + + + + /response/status + SUCCESS + false + false + false + + + + /response/idrate-limit-aib-api6_1falsefalsefalse + + + + + + + + + + + + + + + + +]]> + + http://${#Project#E3Manager}:8181 + + rate-limit-aib-api6_2 + test_notification_route + PassThrough + Notification + Header + active + rate-limit-aib-endpoint6_2 + false + + + noAuth + + + + false + + + + active + 100 + 0.0 + 2 + 0.0 + + + + + + + CompanyQuota + Billing + + + + + + CompanyQuota + Billing + + + +]]> + + 200 + + + + /response/status + SUCCESS + false + false + false + + + + /response/idrate-limit-aib-api6_2falsefalsefalse + + + + + + + <xml-fragment/>http://${#Project#E3Manager}:8181 + rate-limit-aib-auth6 + active + authKey + + + + + rate-limit-aib-key6 + + + + + + CompanyQuota + Billing + + + + + + CompanyQuota + Billing + + + + +]]>200/response/statusSUCCESSfalsefalsefalse<xml-fragment/>http://${#Project#E3Manager}:8181 + rate-limit-aib-p6 + + rate-limit-aib-api6_1 + + + + rate-limit-aib-auth6 + + + + + active + + active + reject + 98 + 1000 + + + + +]]>200/response/statusSUCCESSfalsefalsefalse<xml-fragment xmlns:con="http://eviware.com/soapui/config"> + <con:entry key="SIZE" value="9"/> + <con:entry key="notifyUrl" value="http://${#Project#Target1}:8080/parametersEndpoint.php?param=test1"/> +</xml-fragment>http://${#Project#E3Gateway}/rate-limit-aib-endpoint6?key=rate-limit-aib-key6200// check that OAP_StatusCode header is not present +// it must be removed by E3 +assert messageExchange.responseHeaders["OAP_StatusCode"] == nullexists(/data/subscriberId)truefalsefalsefalse<xml-fragment xmlns:con="http://eviware.com/soapui/config"> + <con:entry key="notifyUrl" value="http://${#Project#Target1}:8080/parametersEndpoint.php?param=test1"/> + <con:entry key="SIZE" value="9"/> +</xml-fragment>http://${#Project#E3Gateway}/rate-limit-aib-endpoint6?key=rate-limit-aib-key6200// check that OAP_StatusCode header is not present +// it must be removed by E3 +assert messageExchange.responseHeaders["OAP_StatusCode"] == nullexists(/data/subscriberId)truefalsefalsefalsesubscriberIdResponseAsXmlRequest - Test Subscription API #1/data/subscriberIdsubscriberId#TestCase#<xml-fragment xmlns:con="http://eviware.com/soapui/config"> + <con:entry key="X-SubscriberID" value="${#TestCase#subscriberId}"/> + <con:entry key="SIZE" value="9"/> + <con:entry key="notifyUrl" value="http://${#Project#Target1}:8080/parametersEndpoint.php?param=test1"/> +</xml-fragment>http://${#Project#E3Gateway}/rate-limit-aib-endpoint6_2200// check that OAP_StatusCode header is not present +// it must be removed by E3 +assert messageExchange.responseHeaders["OAP_StatusCode"] == null/response/data876543210falsefalsefalse/response/parameters/parameter[@key='param' and @type='get']test1falsefalsefalse<xml-fragment xmlns:con="http://eviware.com/soapui/config"> + <con:entry key="subscriberId" value="${#TestCase#subscriberId}"/> + <con:entry key="notifyUrl" value="http://${#Project#Target1}:8080/parametersEndpoint.php?param=test2"/> + <con:entry key="SIZE" value="9"/> +</xml-fragment>http://${#Project#E3Gateway}/rate-limit-aib-endpoint6_2200// check that OAP_StatusCode header is not present +// it must be removed by E3 +assert messageExchange.responseHeaders["OAP_StatusCode"] == null/response/data876543210falsefalsefalse/response/parameters/parameter[@key='param' and @type='get']test2falsefalsefalse<xml-fragment xmlns:con="http://eviware.com/soapui/config"> + <con:entry key="X-SubscriberID" value="${#TestCase#subscriberId}"/> + <con:entry key="notifyUrl" value="http://${#Project#Target1}:8080/parametersEndpoint.php?param=test1"/> + <con:entry key="SIZE" value="9"/> +</xml-fragment>http://${#Project#E3Gateway}/rate-limit-aib-endpoint6_2429 + + + + + + + + + +]]> + + http://${#Project#E3Manager}:8181 + + + + 200 + + + + + + /response/status + SUCCESS + false + false + false + + + + + + + + + + + + + + + + + +]]> + + http://${#Project#E3Manager}:8181 + + + + 200 + + + + + + /response/status + SUCCESS + false + false + false + + + + + + + + <xml-fragment/>http://${#Project#E3Manager}:8181200/response/statusSUCCESSfalsefalsefalse<xml-fragment/>http://${#Project#E3Manager}:8181200/response/statusSUCCESSfalsefalsefalsesubscriberIdrate-limit-aib-api6_1|rate-limit-aib-auth6 + + TestCase generated for REST Resource [/apis] located + at [/apis] + + + + + + + + + + + +]]> + + + http://${#Project#E3Manager}:8181 + + + + + + + + + + + + + + + + + +]]> + + + http://${#Project#E3Manager}:8181 + + + + + + + + + + + <xml-fragment/>http://${#Project#E3Manager}:8181<xml-fragment/>http://${#Project#E3Manager}:8181 + + <xml-fragment/>http://${#Project#E3Manager}:8181<xml-fragment/>http://${#Project#E3Manager}:8181 + + + + + + + + + +]]> + + http://${#Project#E3Manager}:8181 + + rate-limit-aib-api7_1 + test_subscription_route + PassThrough + Subscription + active + rate-limit-aib-endpoint7 + false + + + authKey + + + key + + + + false + + + + active + + + http://${#Project#Target1}:8080/compositeEndpoint + + NoAuth + + key000Val + + + + + 100 + 0.0 + 600 + 0.0 + + + + + + + CompanyQuota + Billing + + + + + + CompanyQuota + Billing + + + +]]> + + 200 + + + + /response/status + SUCCESS + false + false + false + + + + /response/idrate-limit-aib-api7_1falsefalsefalse + + + + + + + + + + + + + + + + +]]> + + http://${#Project#E3Manager}:8181 + + rate-limit-aib-api7_2 + test_notification_route + PassThrough + Notification + Header + active + rate-limit-aib-endpoint7_2 + false + + + authKey + + + key + + + + false + + + + active + 100 + 0.0 + 600 + 0.0 + + + + + + + CompanyQuota + Billing + + + + + + CompanyQuota + Billing + + + +]]> + + 200 + + + + /response/status + SUCCESS + false + false + false + + + + /response/idrate-limit-aib-api7_2falsefalsefalse + + + + + + + <xml-fragment/>http://${#Project#E3Manager}:8181 + rate-limit-aib-auth7_1 + active + authKey + + + + + rate-limit-aib-key7_1 + + + + + + CompanyQuota + Billing + + + + + + CompanyQuota + Billing + + + + +]]>200/response/statusSUCCESSfalsefalsefalse<xml-fragment/>http://${#Project#E3Manager}:8181 + rate-limit-aib-auth7_2 + active + authKey + + + + + rate-limit-aib-key7_2 + + + + + + CompanyQuota + Billing + + + + + + CompanyQuota + Billing + + + + +]]>200/response/statusSUCCESSfalsefalsefalse<xml-fragment/>http://${#Project#E3Manager}:8181 + rate-limit-aib-p7_1 + + rate-limit-aib-api7_1 + + + + rate-limit-aib-auth7_1 + + + + + active + + active + reject + 98 + 2 + + + + +]]>200/response/statusSUCCESSfalsefalsefalse<xml-fragment/>http://${#Project#E3Manager}:8181 + rate-limit-aib-p7_2 + + rate-limit-aib-api7_2 + + + + rate-limit-aib-auth7_2 + + + + + active + + active + reject + 98 + 5 + + + + +]]>200/response/statusSUCCESSfalsefalsefalse<xml-fragment xmlns:con="http://eviware.com/soapui/config"> + <con:entry key="notifyUrl" value="http://${#Project#Target1}:8080/parametersEndpoint.php?param=test1"/> + <con:entry key="SIZE" value="9"/> +</xml-fragment>http://${#Project#E3Gateway}/rate-limit-aib-endpoint7?key=rate-limit-aib-key7_1200// check that OAP_StatusCode header is not present +// it must be removed by E3 +assert messageExchange.responseHeaders["OAP_StatusCode"] == nullexists(/data/subscriberId)truefalsefalsefalse<xml-fragment xmlns:con="http://eviware.com/soapui/config"> + <con:entry key="SIZE" value="9"/> + <con:entry key="notifyUrl" value="http://${#Project#Target1}:8080/parametersEndpoint.php?param=test1"/> +</xml-fragment>http://${#Project#E3Gateway}/rate-limit-aib-endpoint7?key=rate-limit-aib-key7_1200// check that OAP_StatusCode header is not present +// it must be removed by E3 +assert messageExchange.responseHeaders["OAP_StatusCode"] == nullexists(/data/subscriberId)truefalsefalsefalsesubscriberIdResponseAsXmlRequest - Test Subscription API #1/data/subscriberIdsubscriberId#TestCase#<xml-fragment xmlns:con="http://eviware.com/soapui/config"> + <con:entry key="notifyUrl" value="http://${#Project#Target1}:8080/parametersEndpoint.php?param=test1"/> + <con:entry key="SIZE" value="9"/> +</xml-fragment>http://${#Project#E3Gateway}/rate-limit-aib-endpoint7?key=rate-limit-aib-key7_1429<xml-fragment xmlns:con="http://eviware.com/soapui/config"> + <con:entry key="X-SubscriberID" value="${#TestCase#subscriberId}"/> + <con:entry key="notifyUrl" value="http://${#Project#Target1}:8080/parametersEndpoint.php?param=test1"/> + <con:entry key="SIZE" value="9"/> +</xml-fragment>http://${#Project#E3Gateway}/rate-limit-aib-endpoint7_2?key=rate-limit-aib-key7_2200// check that OAP_StatusCode header is not present +// it must be removed by E3 +assert messageExchange.responseHeaders["OAP_StatusCode"] == null/response/data876543210falsefalsefalse/response/parameters/parameter[@key='param' and @type='get']test1falsefalsefalse<xml-fragment xmlns:con="http://eviware.com/soapui/config"> + <con:entry key="X-SubscriberID" value="${#TestCase#subscriberId}"/> + <con:entry key="SIZE" value="9"/> + <con:entry key="notifyUrl" value="http://${#Project#Target1}:8080/parametersEndpoint.php?param=test2"/> +</xml-fragment>http://${#Project#E3Gateway}/rate-limit-aib-endpoint7_2?key=rate-limit-aib-key7_2200// check that OAP_StatusCode header is not present +// it must be removed by E3 +assert messageExchange.responseHeaders["OAP_StatusCode"] == null/response/data876543210falsefalsefalse/response/parameters/parameter[@key='param' and @type='get']test2falsefalsefalse<xml-fragment xmlns:con="http://eviware.com/soapui/config"> + <con:entry key="X-SubscriberID" value="${#TestCase#subscriberId}"/> + <con:entry key="notifyUrl" value="http://${#Project#Target1}:8080/parametersEndpoint.php?param=test2"/> + <con:entry key="SIZE" value="9"/> +</xml-fragment>http://${#Project#E3Gateway}/rate-limit-aib-endpoint7_2?key=rate-limit-aib-key7_2200// check that OAP_StatusCode header is not present +// it must be removed by E3 +assert messageExchange.responseHeaders["OAP_StatusCode"] == null/response/data876543210falsefalsefalse/response/parameters/parameter[@key='param' and @type='get']test2falsefalsefalse<xml-fragment xmlns:con="http://eviware.com/soapui/config"> + <con:entry key="X-SubscriberID" value="${#TestCase#subscriberId}"/> + <con:entry key="notifyUrl" value="http://${#Project#Target1}:8080/parametersEndpoint.php?param=test2"/> + <con:entry key="SIZE" value="9"/> +</xml-fragment>http://${#Project#E3Gateway}/rate-limit-aib-endpoint7_2?key=rate-limit-aib-key7_2200// check that OAP_StatusCode header is not present +// it must be removed by E3 +assert messageExchange.responseHeaders["OAP_StatusCode"] == null/response/data876543210falsefalsefalse/response/parameters/parameter[@key='param' and @type='get']test2falsefalsefalse<xml-fragment xmlns:con="http://eviware.com/soapui/config"> + <con:entry key="X-SubscriberID" value="${#TestCase#subscriberId}"/> + <con:entry key="notifyUrl" value="http://${#Project#Target1}:8080/parametersEndpoint.php?param=test2"/> + <con:entry key="SIZE" value="9"/> +</xml-fragment>http://${#Project#E3Gateway}/rate-limit-aib-endpoint7_2?key=rate-limit-aib-key7_2200// check that OAP_StatusCode header is not present +// it must be removed by E3 +assert messageExchange.responseHeaders["OAP_StatusCode"] == null/response/data876543210falsefalsefalse/response/parameters/parameter[@key='param' and @type='get']test2falsefalsefalse<xml-fragment xmlns:con="http://eviware.com/soapui/config"> + <con:entry key="X-SubscriberID" value="${#TestCase#subscriberId}"/> + <con:entry key="SIZE" value="9"/> + <con:entry key="notifyUrl" value="http://${#Project#Target1}:8080/parametersEndpoint.php?param=test1"/> +</xml-fragment>http://${#Project#E3Gateway}/rate-limit-aib-endpoint7_2?key=rate-limit-aib-key7_2429 + + + + + + + + + +]]> + + http://${#Project#E3Manager}:8181 + + + + 200 + + + + + + /response/status + SUCCESS + false + false + false + + + + + + + + + + + + + + + + + +]]> + + http://${#Project#E3Manager}:8181 + + + + 200 + + + + + + /response/status + SUCCESS + false + false + false + + + + + + + + <xml-fragment/>http://${#Project#E3Manager}:8181200/response/statusSUCCESSfalsefalsefalse<xml-fragment/>http://${#Project#E3Manager}:8181200/response/statusSUCCESSfalsefalsefalse<xml-fragment/>http://${#Project#E3Manager}:8181200/response/statusSUCCESSfalsefalsefalse<xml-fragment/>http://${#Project#E3Manager}:8181200/response/statusSUCCESSfalsefalsefalsesubscriberIdrate-limit-aib-api7_1|rate-limit-aib-auth7_1 + + + + + + + + + + +]]> + + http://${#Project#E3Manager}:8181 + + + + + + + + + + <xml-fragment/>http://${#Project#E3Manager}:8181<xml-fragment/>http://${#Project#E3Manager}:8181 + + + + + + + + + +]]> + + http://${#Project#E3Manager}:8181 + + ratelimit_no_auth_api + ratelimit_no_auth_api + ratelimit_no_auth_api + PassThrough + endTest + false + + + authKey + + + key + + + + false + + active + + + active + + + + http://${#Project#Target1}:8080/proxySize + + + + value + + + + + 10 + 0.0 + 10 + 0.0 + + + + + + false + + +]]> + + + 200 + + + + + /response/status + SUCCESS + false + false + false + + + + /response/idratelimit_no_auth_apifalsefalsefalse + + + + + + + <xml-fragment/>http://${#Project#E3Manager}:8181 + ratelimit_no_auth_auth + active + authKey + + + + 123456 + + + +]]>200/response/idratelimit_no_auth_authfalsefalsefalse/response/statusSUCCESSfalsefalsefalse<xml-fragment/>http://${#Project#E3Manager}:8181 + ratelimit_no_auth_policy + + ratelimit_no_auth_api + + + + ratelimit_no_auth_auth + + + + + active + + active + reject + 0.0 + 2 + + + + + + +]]>200/response/idratelimit_no_auth_policyfalsefalsefalse/response/statusSUCCESSfalsefalsefalse + + + + + <entry key="SIZE" value="10" xmlns="http://eviware.com/soapui/config"/> + + http://${#Project#E3Gateway}/endTest?key=123456 + + + 200 + + + + + + + + + + + + <entry key="SIZE" value="10" xmlns="http://eviware.com/soapui/config"/> + + http://${#Project#E3Gateway}/endTest?key=123456 + + + 200 + + + + + + + + + + + + <entry key="SIZE" value="10" xmlns="http://eviware.com/soapui/config"/> + + http://${#Project#E3Gateway}/endTest?key=123456 + + + 429 + + + + + + + + + + + + + + + + +]]> + + http://${#Project#E3Manager}:8181 + + + + 200 + + + + + + /response/status + SUCCESS + false + false + false + + + + + + + + <xml-fragment/>http://${#Project#E3Manager}:8181200/response/statusSUCCESSfalsefalsefalse<xml-fragment/>http://${#Project#E3Manager}:8181200/response/statusSUCCESSfalsefalsefalse + + + + + + + + + +]]> + + http://${#Project#E3Manager}:8181 + + + + + + + + + + <xml-fragment/>http://${#Project#E3Manager}:8181<xml-fragment/>http://${#Project#E3Manager}:8181 + + + + + + + + + +]]> + + http://${#Project#E3Manager}:8181 + + ratelimit_no_api_api + ratelimit_no_api_api + ratelimit_no_api_api + PassThrough + end2 + false + + + authKey + + + key + + + + false + + active + + + active + + + + http://${#Project#Target1}:8080/proxySize + + + + value + + + + + 2 + 0.0 + 2 + 0.0 + + + + + + false + + +]]> + + + 200 + + + + + /response/status + SUCCESS + false + false + false + + + + /response/idratelimit_no_api_apifalsefalsefalse + + + + + + + <xml-fragment/>http://${#Project#E3Manager}:8181 + ratelimit_no_api_auth + active + authKey + + + + 012346 + + + +]]>200/response/idratelimit_no_api_authfalsefalsefalse/response/statusSUCCESSfalsefalsefalse<xml-fragment/>http://${#Project#E3Manager}:8181 + ratelimit_no_api_api_policy + + + ratelimit_no_api_auth + + + + + active + + active + reject + 0.0 + 5 + + + + + + +]]>200/response/idratelimit_no_api_api_policyfalsefalsefalse/response/statusSUCCESSfalsefalsefalse + + + + + <entry key="SIZE" value="10" xmlns="http://eviware.com/soapui/config"/> + + http://${#Project#E3Gateway}/end2?key=012346 + + + 200 + + + + + + + + + + + + <entry key="SIZE" value="10" xmlns="http://eviware.com/soapui/config"/> + + http://${#Project#E3Gateway}/end2?key=012346 + + + 200 + + + + + + + + + + + + <entry key="SIZE" value="10" xmlns="http://eviware.com/soapui/config"/> + + http://${#Project#E3Gateway}/end2?key=012346 + + + 429 + + + + + + + + + + + + + + + + +]]> + + http://${#Project#E3Manager}:8181 + + + + 200 + + + + + + /response/status + SUCCESS + false + false + false + + + + + + + + <xml-fragment/>http://${#Project#E3Manager}:8181200/response/statusSUCCESSfalsefalsefalse<xml-fragment/>http://${#Project#E3Manager}:8181200/response/statusSUCCESSfalsefalsefalse + + + + + + + + + +]]> + + http://${#Project#E3Manager}:8181 + + + + + + + + + + <xml-fragment/>http://${#Project#E3Manager}:8181<xml-fragment/>http://${#Project#E3Manager}:8181 + + + + + + + + + +]]> + + http://${#Project#E3Manager}:8181 + + ratelimit_no_policy_api + ratelimit_no_policy_api + ratelimit_no_policy_api + PassThrough + end3 + false + + + authKey + + + key + + + + false + + active + + + active + + + + http://${#Project#Target1}:8080/proxySize + + + + value + + + + + + 2 + 0.0 + 2 + 0.0 + + + + + + false + + +]]> + + + 200 + + + + + /response/status + SUCCESS + false + false + false + + + + /response/idratelimit_no_policy_apifalsefalsefalse + + + + + + + <xml-fragment/>http://${#Project#E3Manager}:8181 + ratelimit_no_policy_auth + active + authKey + + + + 789456 + + + +]]>200/response/idratelimit_no_policy_authfalsefalsefalse/response/statusSUCCESSfalsefalsefalse<xml-fragment/>http://${#Project#E3Manager}:8181 + ratelimit_no_policy_policy + + + ratelimit_no_policy_auth + + + + + active + + active + reject + 0.0 + 5 + + + + + + +]]>200/response/idratelimit_no_policy_policyfalsefalsefalse/response/statusSUCCESSfalsefalsefalse + + + + + <entry key="SIZE" value="10" xmlns="http://eviware.com/soapui/config"/> + + http://${#Project#E3Gateway}/end3?key=789456 + + + 429 + + + + + + + + + + + + + + + + +]]> + + http://${#Project#E3Manager}:8181 + + + + + 200 + + + + + <xml-fragment/>http://${#Project#E3Manager}:8181200/response/statusSUCCESSfalsefalsefalse<xml-fragment/>http://${#Project#E3Manager}:8181200/response/statusSUCCESSfalsefalsefalseSEQUENTIAL + Provision rate limits for an API, then call that API. + + + + + + + + + + + +]]> + + + http://${#Project#E3Manager}:8181 + + + + + + + + + + + + + + + + + + +]]> + + http://${#Project#E3Manager}:8181 + + rate-limit-cluster-api1 + rate-limit-cluster-api12 + PassThrough + active + rate-limit-aib-endpoint2 + false + + + noAuth + + + + false + + + + active + + + http://${#Project#Target1}:8080/proxySize + + NoAuth + + key000Val + + + + + 30 + 1 + 30 + 1 + + + + + + + CompanyQuota + Billing + + + + + + CompanyQuota + Billing + + + +]]> + + 200 + + + + /response/status + SUCCESS + false + false + false + + + + /response/idrate-limit-cluster-api1falsefalsefalse + + + + + + + + + + + + + + <xml-fragment/> + + http://${#Project#E3Gateway}/rate-limit-aib-endpoint2 + + if ( messageExchange.getResponseStatusCode() == 200) +{ + context.testCase.getTestStepByName("PropertiesLoop").setPropertyValue( "success", "1" ) +} +else +{ + if ( messageExchange.getResponseStatusCode() == 429) + { + context.testCase.getTestStepByName("PropertiesLoop").setPropertyValue( "success", "0" ) + } + else + { + assert false + } +} + + + + + + + + + + + + +]]> + + + http://${#Project#E3Manager}:8181 + + 200 + + + + + successCount0success0successCount0XXXXXXXXXXX + E3Manager192.168.84.53E3Gateway192.168.84.53Target1192.168.84.90uniqdeleteLOG4J_LEVEL_VALUES(ALL|TRACE|DEBUG|INFO|WARN|ERROR|FATAL|OFF)STATUS_SUCCESSSUCCESSSYSLOG_LEVEL_VALUES(DEBUG|INFO|NOTICE|WARNING|ERR|CRIT|ALERT|EMERG) \ No newline at end of file diff --git a/tests/functional-tests/functional-test-tdr-smoke/pom.xml b/tests/functional-tests/functional-test-tdr-smoke/pom.xml new file mode 100644 index 0000000..0cc553a --- /dev/null +++ b/tests/functional-tests/functional-test-tdr-smoke/pom.xml @@ -0,0 +1,48 @@ + + 4.0.0 + com.alu.e3.functional-tests.samples + functional-test-tdr-smoke + pom + + + + eviware + maven-soapui-plugin + 4.0.1 + + + mysql + mysql-connector-java + 5.1.6 + + + junit + junit + 4.8.1 + + + + + test + + test + + + ${basedir}/soapui-project.xml + ${basedir}/target/surefire-reports + true + ${basedir}/soapui-project-properties.xml + + + + + + + + com.alu.e3.functional-tests + functional-tests + 0.0.1-SNAPSHOT + .. + + Functional test TDR generation + \ No newline at end of file diff --git a/tests/functional-tests/functional-test-tdr-smoke/soapui-project.xml b/tests/functional-tests/functional-test-tdr-smoke/soapui-project.xml new file mode 100644 index 0000000..b84fba3 --- /dev/null +++ b/tests/functional-tests/functional-test-tdr-smoke/soapui-project.xml @@ -0,0 +1,927 @@ + + +http://${#Project#E3Gateway}/api-parameters-endpoint1?param1=value1&key=api-parameters-key1&param2=value2http://${#Project#E3Gateway}/api-parameters-endpoint2/five?key=api-parameters-key2http://${#Project#E3Gateway}/api-parameters-endpoint2/three/five?key=api-parameters-key2apiauthTEMPLATEkeymykeyQUERYmykeyparam1QUERYtext/plain403 500 429data200data200data0data0data0data200data200data200data200data200data200data0datatext/html200<xml-fragment/>http://${#Project#E3Gateway}keymykeyQUERYmykeyparam1value1QUERYvalue1param2value2QUERYvalue2text/plain403data200data200data0data0data0data200data200data200data200data200data200data200datatext/html2000data<xml-fragment/>http://${#Project#E3Gateway}param1value1QUERYvalue1keymykeyQUERYxs:stringmykeyparam2value2QUERYvalue2text/plain403data200data200data0data0data0data200data200data200data200data200data200datatext/html200<xml-fragment/>http://${#Project#E3Gateway}param1value1QUERYvalue1param2value2QUERYvalue2keymykeyQUERYxs:stringmykeytext/plain403data200data200data0data0data0data200data200data200data200data200data200datatext/html200<xml-fragment/>http://${#Project#E3Gateway}text/plain403data200data200data0data0data0data200data200data200data200data200data200datatext/html200text/html;charset=ISO-8859-1404htmltext/html404html<xml-fragment/>http://${#Project#E3Gateway}param1QUERYtext/plain403 500 429data200data200data0data0data0data200data200data200data200data200data200data0datatext/html200text/html404html<xml-fragment/>http://${#Project#E3Gateway}keyQUERYtext/plain403 500 429data200data200data0data0data0data200data200data200data200data200data200data0datatext/html200text/html;charset=ISO-8859-1404html<xml-fragment/>http://${#Project#E3Gateway}text/plain403data200data200data0data0data0data200data200data200data200data200data200datatext/html200text/html;charset=ISO-8859-1404html0data<xml-fragment/>http://${#Project#E3Gateway}text/plain403data200data200data0data0data0data200data200data200data200data200data200datatext/html200text/html;charset=ISO-8859-1404html<xml-fragment/>http://${#Project#E3Gateway}text/plain403data200data200data0data0data0data200data200data200data200data200data200datatext/html200text/html;charset=ISO-8859-1404html0data0data0data0data<xml-fragment/>http://${#Project#E3Gateway}param1QUERYtext/plain403data200data200data0data0data0data200data200data200data200data200data200datatext/html200text/html;charset=ISO-8859-1404html0data<xml-fragment/>http://${#Project#E3Gateway}param1QUERYkeyQUERYtext/plain403data200data200data0data0data0data200data200data200data200data200data200datatext/html200text/html;charset=ISO-8859-1404html0data<xml-fragment/>http://${#Project#E3Gateway}keyQUERYtext/plain403data200data200data0data0data0data200data200data200data200data200data200datatext/html200text/html;charset=ISO-8859-1404html0data<xml-fragment/>http://${#Project#E3Gateway}text/plain403data200data200data0data0data0data200data200data200data200data200data200datatext/html200text/html;charset=ISO-8859-1404html0data0data<xml-fragment/>http://${#Project#E3Gateway}param1QUERYtext/plain403data200data200data0data0data0data200data200data200data200data200data200datatext/html200text/html;charset=ISO-8859-1404html0data<xml-fragment/>http://${#Project#E3Gateway}param1QUERYkeyQUERYtext/plain403data200data200data0data0data0data200data200data200data200data200data200datatext/html200text/html;charset=ISO-8859-1404html0data<xml-fragment/>http://${#Project#E3Gateway}text/plain403data200data200data0data0data0data200data200data200data200data200data200datatext/html200text/html;charset=ISO-8859-1404html<xml-fragment/>http://${#Project#E3Gateway}text/plain403 500data200data200data0data0data0data200data200data200data200data200data200datatext/html200text/html;charset=ISO-8859-1404html0datatext/html; charset=iso-8859-1404html<xml-fragment/>http://${#Project#E3Gateway}text/plain403data200data200data0data0data0data200data200data200data200data200data200datatext/html200text/html;charset=ISO-8859-1404html<xml-fragment/>http://${#Project#E3Gateway}text/html200text/plain403 500datatext/html404htmlhttp://${#Project#E3Gateway} + + + http://${#Project#E3Gateway}/auth-extended-endpoint1?key=auth-extended-key1http://${#Project#E3Gateway}/auth-extended-endpoint1http://${#Project#E3Gateway}/auth-extended-endpoint2http://${#Project#E3Gateway}/api-header-transform-endpoint1?key=api-header-transform-key1http://${#Project#E3Gateway}/api-header-transform-endpoint2?key=api-header-transform-key2http://${#Project#E3Gateway}/api-header-transform-endpoint3?key=api-header-transform-key3http://${#Project#E3Gateway}/provision-api-ext-endpoint1http://${#Project#E3Gateway}/provision-api-ext-endpoint3?key=provision-api-ext-key3https://${#Project#E3Gateway}/tls2ways-call-expired-endpoint1https://${#Project#E3Gateway}/tls2ways-call-ko-endpoint1https://${#Project#E3Gateway}/tls2ways-call-no-cert-endpoint1https://${#Project#E3Gateway}/tls2ways-call-ok-endpoint1https://${#Project#E3Gateway}:25101/provision-sslkey-endpoint3https://${#Project#E3Gateway}:25101/provision-sslkey-endpoint4?key=provision-sslkey-key4http://${#Project#E3Gateway}/tdr-smoke-endpoint1?key=tdr-smoke-key1http://${#Project#E3Gateway}/tdr-endpoint1?key=tdr-key1http://${#Project#E3Gateway}/rate-limit-aib-and-cluster-endpoint2?key=rate-limit-aib-and-cluster-key2http://${#Project#E3Gateway}/rate-limit-aib-and-cluster-endpoint3?key=rate-limit-aib-and-cluster-key3http://${#Project#E3Gateway}/rate-limit-aib-endpoint2http://${#Project#E3Gateway}/rate-limit-aib-endpoint3?key=rate-limit-aib-key3 + + + + + + keyQUERY + + text/html + 200 + + html + + + + 0 + + data + + + text/plain + 500 403 401 429 + + data + + + + 200 + + data + + + + 200 + + data + + + text/html + 404 + + html + + 0data0data0data0data0data + 0data0datatext/xml200data<xml-fragment xmlns:con="http://eviware.com/soapui/config"> + <con:entry key="WAIT" value="0"/> + <con:entry key="SIZE" value="100"/> +</xml-fragment>http://${#Project#E3Gateway}/endpoint1<xml-fragment xmlns:con="http://eviware.com/soapui/config"> + <con:entry key="WAIT" value="0"/> + <con:entry key="SIZE" value="100"/> +</xml-fragment>http://${#Project#E3Gateway}/endpoint1 + text/plain401 403 429 500datatext/html200html0data0data0data0datatext/html404htmltext/xml200data0data0data0data0data0data0data0data0data0data0data0data<xml-fragment xmlns:con="http://eviware.com/soapui/config"> + <con:entry key="WAIT" value="0"/> + <con:entry key="SIZE" value="100"/> +</xml-fragment>http://${#Project#E3Gateway}/endpoint1text/plain401 500 429data0data0data0data0data0data0data0data0data0data0datatext/xml200datatext/html404html<xml-fragment xmlns:con="http://eviware.com/soapui/config"> + <con:entry key="Authorization" value="Basic dGVzdGVyOnRlc3RlcnBhc3N3b3Jk"/> + <con:entry key="WAIT" value="0"/> + <con:entry key="SIZE" value="100"/> +</xml-fragment>http://${#Project#E3Gateway}/endpoint1<xml-fragment xmlns:con="http://eviware.com/soapui/config"> + <con:entry key="Authorization" value="Basic invalidbasic"/> + <con:entry key="WAIT" value="0"/> + <con:entry key="SIZE" value="100"/> +</xml-fragment>http://${#Project#E3Gateway}/endpoint1text/xml200datatext/html200data<xml-fragment xmlns:con="http://eviware.com/soapui/config"> + <con:entry key="WAIT" value="0"/> + <con:entry key="SIZE" value="100"/> +</xml-fragment>http://${#Project#E3Gateway}/endpoint1?key=e88ba0c1e4c34f25bf95733eebd8574f + http://${#Project#E3Gateway}:8181/cxf/e3/prov/v1?_wadl&_type=xml + + + + E3 REST API to create, update or delete an API + + Used to get all API IDs. + + + + + + This REST API is used to create an API. + + + + + + + + + + + This REST API is used to delete an API. + + + + + + + Used to get an API by this ID. + + + + + + + This REST API is used to update an API. + + + + + + + + + + + E3 REST API to create, update or delete a policy + + This REST API is used to fetch all policy ids. + + + + + + This REST API is used to create a policy. + + + + + + + + + + + This REST API is used to delete a policy. + + + + + + + This REST API is used to fetch policy data. + + + + + + + This REST API is used to update a policy. + + + + + + + + + + + + This REST API is used to create a QuotaRLBucket in a policy. + + + + + + + + + + + + + This REST API is used to remove a bucket from a policy. + + + + + + + This REST API is used to append auths to a bucket. + + + + + + + + + + + + + + This REST API is used to remove an auth from a bucket. + + + + + + + + + E3 REST API provision authentications on E3 subsystem + + This REST API is used to get all authentications from E3 subsystem. + + + + + + This REST API is used to create an authentication element on E3 subsystem. + + + + + + + + + + + This REST API is used to delete an Auth. + + + + + + + This REST API is used to get an authentication by ID from E3 subsystem. + + + + + + + This REST API is used to update an authentication. + + + + + + + + + + + E3 REST API to create or delete a bucket of auths associated to a list of policies + + This REST API is used to create a bucket linked to a list of policies. + + + + + + + + + + + This REST API is used to append auths to a bucket for several policies. + + + + + + + + + + + + This REST API is used to remove a bucket from a list of policies. + + + + + + + + + + + E3 REST API provision SSLKeys and SSLCerts on E3 subsystem + + This REST API is used to get all SSLKeys from E3 subsystem. + + + + + + This REST API is used to create an SSLKey element on E3 subsystem. + + + + + + + + + + + This REST API is used to delete an SSLKey. + + + + + + + This REST API is used to get an SSLKey by ID from E3 subsystem. + + + + + + + This REST API is used to update an SSLKey. + + + + + + + + + + + + This REST API is used to get all SSLCerts for a key. + + + + + + + This REST API is used to create an SSLCert element on E3 subsystem. + + + + + + + + + + + + + This REST API is used to delete an SSLCert. + + + + + + + This REST API is used to get an SSLKey by ID from E3 subsystem. + + + + + + + This REST API is used to update an SSLKey. + + + + + + + + + + + + This REST API is used to get a CSR for the given SSLKey ID from E3 subsystem. + + + + + + + + + + This REST API is used to create a self-signed cert for an existing Key + + + + + + + + + E3 REST API to add/update/delete trusted CAs and CRLs + + + This REST API is used to fetch all trusted certificates authorithies. + + + + + + This REST API is used to add a trusted Certificate Authority. + + + + + + + + + + + + This REST API is used to remove a trusted Certificate Authority. + + + + + + + This REST API is used to fetch trusted Certificate Authority. + + + + + + + This REST API is used to update a trusted Certificate Authority. + + + + + + + + + + + This REST API is used to fetch trusted Certificate Authority. + + + + + + This REST API is used to add a Certificate Revocation List for this Certificate Authority. + + + + + + + + + + + + This REST API is used to remove a certificate revocation list from a certificate authority. + + + + + + + This REST API is used to fetch Certificate Revocation List. + + + + + + + This REST API is used to update a certificate revocation list. + + + + + + + + + + +]]>http://wadl.dev.java.net/2009/02http://${#Project#E3Gateway}:8181API_IDTEMPLATExs:stringapplication/xmlhttp://${#Project#E3Gateway}:8181application/xmlhttp://${#Project#E3Gateway}:8181application/xmlapplication/xmlhttp://${#Project#E3Gateway}:8181application/xmlhttp://${#Project#E3Gateway}:8181application/xmlapplication/xmlhttp://${#Project#E3Gateway}:8181POLICY_IDTEMPLATExs:stringapplication/xmlhttp://${#Project#E3Gateway}:8181application/xmlhttp://${#Project#E3Gateway}:8181application/xmlapplication/xmlhttp://${#Project#E3Gateway}:8181POLICY_IDTEMPLATExs:stringapplication/xmlapplication/xmlhttp://${#Project#E3Gateway}:8181POLICY_IDTEMPLATExs:stringBUCKET_IDTEMPLATExs:stringapplication/xmlhttp://${#Project#E3Gateway}:8181application/xmlapplication/xmlhttp://${#Project#E3Gateway}:8181POLICY_IDTEMPLATExs:stringBUCKET_IDTEMPLATExs:stringAUTH_IDTEMPLATExs:stringapplication/xmlhttp://${#Project#E3Gateway}:8181application/xmlhttp://${#Project#E3Gateway}:8181application/xmlapplication/xmlhttp://${#Project#E3Gateway}:8181AUTH_IDTEMPLATExs:stringapplication/xmlhttp://${#Project#E3Gateway}:8181application/xmlhttp://${#Project#E3Gateway}:8181application/xmlapplication/xmlhttp://${#Project#E3Gateway}:8181application/xmlhttp://${#Project#E3Gateway}:8181application/xmlapplication/xmlhttp://${#Project#E3Gateway}:8181BUCKET_IDTEMPLATExs:stringapplication/xmlapplication/xmlhttp://${#Project#E3Gateway}:8181BUCKET_IDTEMPLATExs:stringapplication/xmlapplication/xmlhttp://${#Project#E3Gateway}:8181application/xmlapplication/xmlhttp://${#Project#E3Gateway}:8181KEY_IDTEMPLATExs:stringapplication/xmlhttp://${#Project#E3Gateway}:8181application/xmlhttp://${#Project#E3Gateway}:8181application/xmlapplication/xmlhttp://${#Project#E3Gateway}:8181KEY_IDTEMPLATExs:stringapplication/xmlhttp://${#Project#E3Gateway}:8181application/xmlapplication/xmlhttp://${#Project#E3Gateway}:8181KEY_IDTEMPLATExs:stringCERT_IDTEMPLATExs:stringapplication/xmlhttp://${#Project#E3Gateway}:8181application/xmlhttp://${#Project#E3Gateway}:8181application/xmlapplication/xmlhttp://${#Project#E3Gateway}:8181KEY_IDTEMPLATExs:stringapplication/xmlhttp://${#Project#E3Gateway}:8181KEY_IDTEMPLATExs:stringapplication/xmlhttp://${#Project#E3Gateway}:8181application/xml<xml-fragment/>http://${#Project#E3Gateway}:8181application/xmlapplication/xmlhttp://${#Project#E3Gateway}:8181application/xml<xml-fragment/>http://${#Project#E3Gateway}:8181application/xmlapplication/xmlhttp://${#Project#E3Gateway}:8181CA_IDTEMPLATExs:stringapplication/xmlhttp://${#Project#E3Gateway}:8181application/xmlhttp://${#Project#E3Gateway}:8181application/xmlapplication/xmlhttp://${#Project#E3Gateway}:8181application/xmlhttp://${#Project#E3Gateway}:8181application/xmlapplication/xmlhttp://${#Project#E3Gateway}:8181CRL_IDTEMPLATExs:stringapplication/xmlhttp://${#Project#E3Gateway}:8181application/xmlhttp://${#Project#E3Gateway}:8181application/xmlapplication/xmlhttp://${#Project#E3Gateway}:8181file:/D:/Documents%20and%20Settings/mtobiasz/Desktop/targertest_1.wadl + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + +]]>http://wadl.dev.java.net/2009/02http://${#Project#E3Gateway}http://${#Project#E3Gateway}/api-http-method-endpoint1?key=api-http-method-key1http://${#Project#E3Gateway}/api-http-method-endpoint2?key=api-http-method-key2http://${#Project#E3Gateway}/api-http-method-endpoint3?key=api-http-method-key3http://${#Project#E3Gateway}/api-http-method-endpoint4?key=api-http-method-key40text/html200http://${#Project#E3Gateway}application/xml0application/xmltext/plain403 405 429text/xml200ns:responsehttp://${#Project#E3Gateway}application/xmlapplication/xmltext/plain405 429text/xml200ns:responsehttp://${#Project#E3Gateway}text/plain405 429text/xml200ns:responsehttp://${#Project#E3Gateway}0text/plain405text/xml200http://${#Project#E3Gateway}http://135.248.213.24:8181pathToConfigFilesDirectoryTEMPLATExs:stringapplication/octet-streamhttp://135.248.213.24:8181application/octet-streamhttp://135.248.213.24:8181numLinesTEMPLATExs:stringapplication/xmlhttp://135.248.213.24:8181numLinesTEMPLATExs:stringapplication/xmlhttp://135.248.213.24:8181application/xmlhttp://135.248.213.24:8181instanceIdTEMPLATExs:stringapplication/xmlhttp://135.248.213.24:8181application/octet-streamapplication/xmlhttp://135.248.213.24:8181instanceIdTEMPLATExs:stringapplication/xmlhttp://135.248.213.24:8181application/octet-streamapplication/xmlhttp://135.248.213.24:8181instanceIdTEMPLATExs:stringapplication/xmlhttp://135.248.213.24:8181application/octet-streamapplication/xmlhttp://135.248.213.24:8181application/octet-streamhttp://135.248.213.24:8181application/octet-streamhttp://135.248.213.24:8181application/xmlhttp://135.248.213.24:8181application/octet-streamapplication/xmlhttp://135.248.213.24:8181application/xmlhttp://135.248.213.24:8181application/xmlapplication/xmlhttp://135.248.213.24:8181application/xmlhttp://135.248.213.24:8181application/octet-streamapplication/xmlhttp://135.248.213.24:8181application/xmlhttp://135.248.213.24:8181application/octet-streamapplication/xmlhttp://135.248.213.24:8181 + TestSuite generated for REST Service + [functional-test-provision-api] + + SEQUENTIAL + + + + + TestCase generated for REST Resource [/apis] located + at [/apis] + + + + + + + + + + + + +]]> + + http://${#Project#E3Manager}:8181 + + + + + Global HTTP Settings + + + + + + <xml-fragment/>http://${#Project#E3Manager}:8181Global HTTP Settings + <xml-fragment/>http://${#Project#E3Manager}:8181Global HTTP Settings + + + + + + + + + + + +]]> + + http://${#Project#E3Manager}:8181 + + tdr-smoke-api1 + tdr-smoke-api1 + PassThrough + active + tdr-smoke-endpoint1 + false + + + authKey + + + key + + + + true + + + + active + + + http://${#Project#Target1}:8080/proxySize + + NoAuth + + key000Val + + + + + 10 + 0.0 + 200 + 1.0 + + + + + + + + +]]> + + 200 + + + + /response/status + SUCCESS + false + false + false + + + + /response/idtdr-smoke-api1falsefalsefalse + + Global HTTP Settings + + + + + + <xml-fragment/>http://${#Project#E3Manager}:8181 + tdr-smoke-auth1 + active + authKey + + + + tdr-smoke-key1 + + + + + + CompanyQuota + Billing + + + + + + CompanyQuota + Billing + + + +]]>200/response/idtdr-smoke-auth1falsefalsefalse/response/statusSUCCESSfalsefalsefalseGlobal HTTP Settings<xml-fragment/>http://${#Project#E3Manager}:8181 + tdr-smoke-policy1 + + tdr-smoke-api1 + + + + tdr-smoke-auth1 + + + + + active + + active + reject + 2 + 2 + + + +]]>200/response/idtdr-smoke-policy1falsefalsefalse/response/statusSUCCESSfalsefalsefalseGlobal HTTP Settings + + + + + <entry key="SIZE" value="10" xmlns="http://eviware.com/soapui/config"/> + + http://${#Project#E3Gateway}/tdr-smoke-endpoint1?key=tdr-smoke-key1 + + + 200 + + /data9876543210falsefalsefalseGlobal HTTP Settings + + + + + + + + + + <entry key="SIZE" value="10" xmlns="http://eviware.com/soapui/config"/> + + http://${#Project#E3Gateway}/tdr-smoke-endpoint1?key=tdr-smoke-key1 + + + + 200 + + + /data9876543210falsefalsefalseGlobal HTTP Settings + + + + + + + + + + <entry key="SIZE" value="10" xmlns="http://eviware.com/soapui/config"/> + + http://${#Project#E3Gateway}/tdr-smoke-endpoint1?key=tdr-smoke-key1 + + + 429 + + /data9876543210falsefalsefalseGlobal HTTP Settings + + + + + + + + + + + + + + +]]> + false + http://${#Project#E3Manager}:8181 + + + 200 + + + + + /response/status + SUCCESS + false + false + false + + + Global HTTP Settings + + + + + <xml-fragment/>http://${#Project#E3Manager}:8181200/response/statusSUCCESSfalsefalsefalseGlobal HTTP Settings<xml-fragment/>http://${#Project#E3Manager}:8181200/response/statusSUCCESSfalsefalsefalseGlobal HTTP Settings + + + + + + + + + + + + + E3Manager135.248.213.24E3Gateway135.248.213.24Target110.168.168.49uniqdeleteLOG4J_LEVEL_VALUES(ALL|TRACE|DEBUG|INFO|WARN|ERROR|FATAL|OFF)STATUS_SUCCESSSUCCESSSYSLOG_LEVEL_VALUES(DEBUG|INFO|NOTICE|WARNING|ERR|CRIT|ALERT|EMERG) \ No newline at end of file diff --git a/tests/functional-tests/provision-sslkey/pom.xml b/tests/functional-tests/provision-sslkey/pom.xml new file mode 100644 index 0000000..19b0602 --- /dev/null +++ b/tests/functional-tests/provision-sslkey/pom.xml @@ -0,0 +1,49 @@ + + 4.0.0 + com.alu.e3.functional-tests.samples + provision-sslkey + pom + + + + eviware + maven-soapui-plugin + 4.0.1 + + + mysql + mysql-connector-java + 5.1.6 + + + junit + junit + 4.8.1 + + + + + test + + test + + + ${basedir}/soapui-project.xml + ${basedir}/target/surefire-reports + true + ${basedir}/soapui-project-properties.xml + + + + + + + + com.alu.e3.functional-tests + functional-tests + 0.0.1-SNAPSHOT + .. + + Functional test provision SSL + SOAP UI tests for the SSL provisioning interface + \ No newline at end of file diff --git a/tests/functional-tests/provision-sslkey/soapui-project.xml b/tests/functional-tests/provision-sslkey/soapui-project.xml new file mode 100644 index 0000000..ea0a00d --- /dev/null +++ b/tests/functional-tests/provision-sslkey/soapui-project.xml @@ -0,0 +1,1530 @@ + + +http://${#Project#E3Gateway}/api-parameters-endpoint1?param1=value1&key=api-parameters-key1&param2=value2http://${#Project#E3Gateway}/api-parameters-endpoint2/five?key=api-parameters-key2http://${#Project#E3Gateway}/api-parameters-endpoint2/three/five?key=api-parameters-key2apiauthTEMPLATEkeymykeyQUERYmykeyparam1QUERYtext/plain403 500 429data200data200data0data0data0data200data200data200data200data200data200data0datatext/html200<xml-fragment/>http://${#Project#E3Gateway}keymykeyQUERYmykeyparam1value1QUERYvalue1param2value2QUERYvalue2text/plain403data200data200data0data0data0data200data200data200data200data200data200data200datatext/html2000data<xml-fragment/>http://${#Project#E3Gateway}param1value1QUERYvalue1keymykeyQUERYxs:stringmykeyparam2value2QUERYvalue2text/plain403data200data200data0data0data0data200data200data200data200data200data200datatext/html200<xml-fragment/>http://${#Project#E3Gateway}param1value1QUERYvalue1param2value2QUERYvalue2keymykeyQUERYxs:stringmykeytext/plain403data200data200data0data0data0data200data200data200data200data200data200datatext/html200<xml-fragment/>http://${#Project#E3Gateway}text/plain403data200data200data0data0data0data200data200data200data200data200data200datatext/html200text/html;charset=ISO-8859-1404htmltext/html404html<xml-fragment/>http://${#Project#E3Gateway}param1QUERYtext/plain403 500 429data200data200data0data0data0data200data200data200data200data200data200data0datatext/html200text/html404html<xml-fragment/>http://${#Project#E3Gateway}keyQUERYtext/plain403 500 429data200data200data0data0data0data200data200data200data200data200data200data0datatext/html200text/html;charset=ISO-8859-1404html<xml-fragment/>http://${#Project#E3Gateway}text/plain403data200data200data0data0data0data200data200data200data200data200data200datatext/html200text/html;charset=ISO-8859-1404html0data<xml-fragment/>http://${#Project#E3Gateway}text/plain403data200data200data0data0data0data200data200data200data200data200data200datatext/html200text/html;charset=ISO-8859-1404html<xml-fragment/>http://${#Project#E3Gateway}text/plain403data200data200data0data0data0data200data200data200data200data200data200datatext/html200text/html;charset=ISO-8859-1404html0data0data0data0data<xml-fragment/>http://${#Project#E3Gateway}param1QUERYtext/plain403data200data200data0data0data0data200data200data200data200data200data200datatext/html200text/html;charset=ISO-8859-1404html0data<xml-fragment/>http://${#Project#E3Gateway}param1QUERYkeyQUERYtext/plain403data200data200data0data0data0data200data200data200data200data200data200datatext/html200text/html;charset=ISO-8859-1404html0data<xml-fragment/>http://${#Project#E3Gateway}keyQUERYtext/plain403data200data200data0data0data0data200data200data200data200data200data200datatext/html200text/html;charset=ISO-8859-1404html0data<xml-fragment/>http://${#Project#E3Gateway}text/plain403data200data200data0data0data0data200data200data200data200data200data200datatext/html200text/html;charset=ISO-8859-1404html0data0data<xml-fragment/>http://${#Project#E3Gateway}param1QUERYtext/plain403data200data200data0data0data0data200data200data200data200data200data200datatext/html200text/html;charset=ISO-8859-1404html0data<xml-fragment/>http://${#Project#E3Gateway}param1QUERYkeyQUERYtext/plain403data200data200data0data0data0data200data200data200data200data200data200datatext/html200text/html;charset=ISO-8859-1404html0data<xml-fragment/>http://${#Project#E3Gateway}text/plain403data200data200data0data0data0data200data200data200data200data200data200datatext/html200text/html;charset=ISO-8859-1404html<xml-fragment/>http://${#Project#E3Gateway}text/plain403 500data200data200data0data0data0data200data200data200data200data200data200datatext/html200text/html;charset=ISO-8859-1404html0datatext/html; charset=iso-8859-1404html<xml-fragment/>http://${#Project#E3Gateway}text/plain403data200data200data0data0data0data200data200data200data200data200data200datatext/html200text/html;charset=ISO-8859-1404html<xml-fragment/>http://${#Project#E3Gateway}text/html200text/plain403 500datatext/html404htmlhttp://${#Project#E3Gateway} + + + http://${#Project#E3Gateway}/auth-extended-endpoint1?key=auth-extended-key1http://${#Project#E3Gateway}/auth-extended-endpoint1http://${#Project#E3Gateway}/auth-extended-endpoint2http://${#Project#E3Gateway}/api-header-transform-endpoint1?key=api-header-transform-key1http://${#Project#E3Gateway}/api-header-transform-endpoint2?key=api-header-transform-key2http://${#Project#E3Gateway}/api-header-transform-endpoint3?key=api-header-transform-key3http://${#Project#E3Gateway}/provision-api-ext-endpoint1http://${#Project#E3Gateway}/provision-api-ext-endpoint3?key=provision-api-ext-key3https://${#Project#E3Gateway}/tls2ways-crl-ok-endpoint1https://${#Project#E3Gateway}/tls2ways-crl-ok-endpoint2 + + + + + + keyQUERY + + text/html + 200 + + html + + + + 0 + + data + + + text/plain + 500 403 401 429 + + data + + + + 200 + + data + + + + 200 + + data + + + text/html + 404 + + html + + 0data0data0data0data0data + 0data0datatext/xml200data<xml-fragment xmlns:con="http://eviware.com/soapui/config"> + <con:entry key="WAIT" value="0"/> + <con:entry key="SIZE" value="100"/> +</xml-fragment>http://${#Project#E3Gateway}/endpoint1<xml-fragment xmlns:con="http://eviware.com/soapui/config"> + <con:entry key="WAIT" value="0"/> + <con:entry key="SIZE" value="100"/> +</xml-fragment>http://${#Project#E3Gateway}/endpoint1 + text/plain401 403 429 500datatext/html200html0data0data0data0datatext/html404 503htmltext/xml200data0data0data0data0data<xml-fragment xmlns:con="http://eviware.com/soapui/config"> + <con:entry key="WAIT" value="0"/> + <con:entry key="SIZE" value="100"/> +</xml-fragment>http://${#Project#E3Gateway}/endpoint1text/plain401 500 429data0data0data0data0data0data0data0data0data0data0datatext/xml200datatext/html404html<xml-fragment xmlns:con="http://eviware.com/soapui/config"> + <con:entry key="Authorization" value="Basic dGVzdGVyOnRlc3RlcnBhc3N3b3Jk"/> + <con:entry key="WAIT" value="0"/> + <con:entry key="SIZE" value="100"/> +</xml-fragment>http://${#Project#E3Gateway}/endpoint1<xml-fragment xmlns:con="http://eviware.com/soapui/config"> + <con:entry key="Authorization" value="Basic invalidbasic"/> + <con:entry key="WAIT" value="0"/> + <con:entry key="SIZE" value="100"/> +</xml-fragment>http://${#Project#E3Gateway}/endpoint1text/xml200datatext/html200data<xml-fragment xmlns:con="http://eviware.com/soapui/config"> + <con:entry key="WAIT" value="0"/> + <con:entry key="SIZE" value="100"/> +</xml-fragment>http://${#Project#E3Gateway}/endpoint1?key=e88ba0c1e4c34f25bf95733eebd8574f + http://${#Project#E3Gateway}:8181/cxf/e3/prov/v1?_wadl&_type=xml + + + + E3 REST API to create, update or delete an API + + Used to get all API IDs. + + + + + + This REST API is used to create an API. + + + + + + + + + + + This REST API is used to delete an API. + + + + + + + Used to get an API by this ID. + + + + + + + This REST API is used to update an API. + + + + + + + + + + + E3 REST API to create, update or delete a policy + + This REST API is used to fetch all policy ids. + + + + + + This REST API is used to create a policy. + + + + + + + + + + + This REST API is used to delete a policy. + + + + + + + This REST API is used to fetch policy data. + + + + + + + This REST API is used to update a policy. + + + + + + + + + + + + This REST API is used to create a QuotaRLBucket in a policy. + + + + + + + + + + + + + This REST API is used to remove a bucket from a policy. + + + + + + + This REST API is used to append auths to a bucket. + + + + + + + + + + + + + + This REST API is used to remove an auth from a bucket. + + + + + + + + + E3 REST API provision authentications on E3 subsystem + + This REST API is used to get all authentications from E3 subsystem. + + + + + + This REST API is used to create an authentication element on E3 subsystem. + + + + + + + + + + + This REST API is used to delete an Auth. + + + + + + + This REST API is used to get an authentication by ID from E3 subsystem. + + + + + + + This REST API is used to update an authentication. + + + + + + + + + + + E3 REST API to create or delete a bucket of auths associated to a list of policies + + This REST API is used to create a bucket linked to a list of policies. + + + + + + + + + + + This REST API is used to append auths to a bucket for several policies. + + + + + + + + + + + + This REST API is used to remove a bucket from a list of policies. + + + + + + + + + + + E3 REST API provision SSLKeys and SSLCerts on E3 subsystem + + This REST API is used to get all SSLKeys from E3 subsystem. + + + + + + This REST API is used to create an SSLKey element on E3 subsystem. + + + + + + + + + + + This REST API is used to delete an SSLKey. + + + + + + + This REST API is used to get an SSLKey by ID from E3 subsystem. + + + + + + + This REST API is used to update an SSLKey. + + + + + + + + + + + + This REST API is used to get all SSLCerts for a key. + + + + + + + This REST API is used to create an SSLCert element on E3 subsystem. + + + + + + + + + + + + + This REST API is used to delete an SSLCert. + + + + + + + This REST API is used to get an SSLKey by ID from E3 subsystem. + + + + + + + This REST API is used to update an SSLKey. + + + + + + + + + + + + This REST API is used to get a CSR for the given SSLKey ID from E3 subsystem. + + + + + + + + + + This REST API is used to create a self-signed cert for an existing Key + + + + + + + + + E3 REST API to add/update/delete trusted CAs and CRLs + + + This REST API is used to fetch all trusted certificates authorithies. + + + + + + This REST API is used to add a trusted Certificate Authority. + + + + + + + + + + + + This REST API is used to remove a trusted Certificate Authority. + + + + + + + This REST API is used to fetch trusted Certificate Authority. + + + + + + + This REST API is used to update a trusted Certificate Authority. + + + + + + + + + + + This REST API is used to fetch trusted Certificate Authority. + + + + + + This REST API is used to add a Certificate Revocation List for this Certificate Authority. + + + + + + + + + + + + This REST API is used to remove a certificate revocation list from a certificate authority. + + + + + + + This REST API is used to fetch Certificate Revocation List. + + + + + + + This REST API is used to update a certificate revocation list. + + + + + + + + + + +]]>http://wadl.dev.java.net/2009/02http://${#Project#E3Gateway}:8181API_IDTEMPLATExs:stringapplication/xmlhttp://${#Project#E3Gateway}:8181application/xmlhttp://${#Project#E3Gateway}:8181application/xmlapplication/xmlhttp://${#Project#E3Gateway}:8181application/xmlhttp://${#Project#E3Gateway}:8181application/xmlapplication/xmlhttp://${#Project#E3Gateway}:8181POLICY_IDTEMPLATExs:stringapplication/xmlhttp://${#Project#E3Gateway}:8181application/xmlhttp://${#Project#E3Gateway}:8181application/xmlapplication/xmlhttp://${#Project#E3Gateway}:8181POLICY_IDTEMPLATExs:stringapplication/xmlapplication/xmlhttp://${#Project#E3Gateway}:8181POLICY_IDTEMPLATExs:stringBUCKET_IDTEMPLATExs:stringapplication/xmlhttp://${#Project#E3Gateway}:8181application/xmlapplication/xmlhttp://${#Project#E3Gateway}:8181POLICY_IDTEMPLATExs:stringBUCKET_IDTEMPLATExs:stringAUTH_IDTEMPLATExs:stringapplication/xmlhttp://${#Project#E3Gateway}:8181application/xmlhttp://${#Project#E3Gateway}:8181application/xmlapplication/xmlhttp://${#Project#E3Gateway}:8181AUTH_IDTEMPLATExs:stringapplication/xmlhttp://${#Project#E3Gateway}:8181application/xmlhttp://${#Project#E3Gateway}:8181application/xmlapplication/xmlhttp://${#Project#E3Gateway}:8181application/xmlhttp://${#Project#E3Gateway}:8181application/xmlapplication/xmlhttp://${#Project#E3Gateway}:8181BUCKET_IDTEMPLATExs:stringapplication/xmlapplication/xmlhttp://${#Project#E3Gateway}:8181BUCKET_IDTEMPLATExs:stringapplication/xmlapplication/xmlhttp://${#Project#E3Gateway}:8181application/xmlapplication/xmlhttp://${#Project#E3Gateway}:8181KEY_IDTEMPLATExs:stringapplication/xmlhttp://${#Project#E3Gateway}:8181application/xmlhttp://${#Project#E3Gateway}:8181application/xmlapplication/xmlhttp://${#Project#E3Gateway}:8181KEY_IDTEMPLATExs:stringapplication/xmlhttp://${#Project#E3Gateway}:8181application/xmlapplication/xmlhttp://${#Project#E3Gateway}:8181KEY_IDTEMPLATExs:stringCERT_IDTEMPLATExs:stringapplication/xmlhttp://${#Project#E3Gateway}:8181application/xmlhttp://${#Project#E3Gateway}:8181application/xmlapplication/xmlhttp://${#Project#E3Gateway}:8181KEY_IDTEMPLATExs:stringapplication/xmlhttp://${#Project#E3Gateway}:8181KEY_IDTEMPLATExs:stringapplication/xmlhttp://${#Project#E3Gateway}:8181application/xmlhttp://${#Project#E3Gateway}:8181application/xmlapplication/xmlhttp://${#Project#E3Gateway}:8181application/xmlhttp://${#Project#E3Gateway}:8181application/xmlapplication/xmlhttp://${#Project#E3Gateway}:8181CA_IDTEMPLATExs:stringapplication/xmlhttp://${#Project#E3Gateway}:8181application/xmlhttp://${#Project#E3Gateway}:8181application/xmlapplication/xmlhttp://${#Project#E3Gateway}:8181application/xmlhttp://${#Project#E3Gateway}:8181application/xmlapplication/xmlhttp://${#Project#E3Gateway}:8181CRL_IDTEMPLATExs:stringapplication/xmlhttp://${#Project#E3Gateway}:8181application/xmlhttp://${#Project#E3Gateway}:8181application/xmlapplication/xmlhttp://${#Project#E3Gateway}:8181file:/D:/Documents%20and%20Settings/mtobiasz/Desktop/targertest_1.wadl + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + +]]>http://wadl.dev.java.net/2009/02http://${#Project#E3Gateway}http://${#Project#E3Gateway}/api-http-method-endpoint1?key=api-http-method-key1http://${#Project#E3Gateway}/api-http-method-endpoint2?key=api-http-method-key2http://${#Project#E3Gateway}/api-http-method-endpoint3?key=api-http-method-key3http://${#Project#E3Gateway}/api-http-method-endpoint4?key=api-http-method-key40text/html200http://${#Project#E3Gateway}application/xml0application/xmltext/plain403 405 429text/xml200ns:responsehttp://${#Project#E3Gateway}application/xmlapplication/xmltext/plain405 429text/xml200ns:responsehttp://${#Project#E3Gateway}text/plain405 429text/xml200ns:responsehttp://${#Project#E3Gateway}0text/plain405text/xml200http://${#Project#E3Gateway} + + SEQUENTIAL + + + + + + + + <xml-fragment/> + + UTF-8 + http://${#Project#E3Manager}:8181 + + + + + + + + + + + + + <xml-fragment/> + + UTF-8 + http://${#Project#E3Manager}:8181 + + provision-sslkey-content1 + Key DisplayName +]]> + + + /response/status + SUCCESS + false + false + + + + /response/idprovision-sslkey-key1falsefalsefalse + + + + + + + + + + + + + <xml-fragment/> + + UTF-8 + http://${#Project#E3Manager}:8181 + + + + /response/status + SUCCESS + false + false + + + + /response/key/@idprovision-sslkey-key1falsefalsefalse + + + + + + + + + + + + + + <xml-fragment/> + + UTF-8 + http://${#Project#E3Manager}:8181 + <key id="provision-sslkey-key1"> + <displayName>new key name</displayName> +</key> + + + /response/statusSUCCESSfalsefalsefalse + + + + + + + + + + + + + <xml-fragment/> + + UTF-8 + http://${#Project#E3Manager}:8181 + + provision-sslkey-content1 + failed +]]> + + + /response/statusFAILUREfalsefalsefalse + + + + + + + + + + + + + <xml-fragment/> + + UTF-8 + http://${#Project#E3Manager}:8181 + + + + /response/status + SUCCESS + false + false + + + + /response/key/@idprovision-sslkey-key1falsefalsefalse + + + + + + + + + + + + + + <xml-fragment/> + + UTF-8 + http://${#Project#E3Manager}:8181 + + + /response/ids/idprovision-sslkey-key1falsefalsefalse + + + + + + + + + + + <xml-fragment/> + UTF-8 + http://${#Project#E3Manager}:8181 + + /response/statusSUCCESSfalsefalse + + + + + + + <xml-fragment/> + http://${#Project#E3Manager}:8181 + /response/statusFAILUREfalsefalse + + + + + + <xml-fragment/> + UTF-8 + http://${#Project#E3Manager}:8181 + + /response/statusFAILUREfalsefalse + + + + + + + + + + <xml-fragment/> + UTF-8 + http://${#Project#E3Manager}:8181 + + <id>1234</id>falsefalse + + + + + + + + + + + <xml-fragment/> + + UTF-8 + http://${#Project#E3Manager}:8181 + <key id="provision-sslkey-key1"> + <displayName>New Name</displayName> +</key> + + + /response/status + FAILURE + false + false + + + + + + + + + + + <xml-fragment/> + http://${#Project#E3Manager}:8181 + + + <xml-fragment/> + http://${#Project#E3Manager}:8181 + + > + provision-sslkey-key2 +]]>/response/statusSUCCESSfalsefalse + + <xml-fragment/> + http://${#Project#E3Manager}:8181 + /response/statusSUCCESSfalsefalse<id>falsefalse + + <xml-fragment/> + http://${#Project#E3Manager}:8181 + + > + provision-sslkey-cert2 +]]>/response/statusSUCCESSfalsefalse/response/idprovision-sslkey-cert2falsefalsefalse + + <xml-fragment/> + http://${#Project#E3Manager}:8181 + /response/statusSUCCESSfalsefalse/response/cert/@idprovision-sslkey-cert2falsefalsefalse/response/cert/content-----BEGIN CERTIFICATE----- +MIICuzCCAiQCCQDxj0dkEy3MLzANBgkqhkiG9w0BAQUFADCBoTELMAkGA1UEBhMC +VVMxEzARBgNVBAgTCkNhbGlmb3JuaWExEzARBgNVBAcTClNhbnRhIENydXoxEzAR +BgNVBAoTClByb2R1Y3RPcHMxFDASBgNVBAsTC2RldmVsb3BtZW50MRMwEQYDVQQD +EwpFcmljIEZ1bHR6MSgwJgYJKoZIhvcNAQkBFhllcmljLmZ1bHR6QHByb2R1Y3Rv +cHMuY29tMB4XDTEyMDUwNDIxMzYxNVoXDTEzMDUwNDIxMzYxNVowgaExCzAJBgNV +BAYTAlVTMRMwEQYDVQQIEwpDYWxpZm9ybmlhMRMwEQYDVQQHEwpTYW50YSBDcnV6 +MRMwEQYDVQQKEwpQcm9kdWN0T3BzMRQwEgYDVQQLEwtkZXZlbG9wbWVudDETMBEG +A1UEAxMKRXJpYyBGdWx0ejEoMCYGCSqGSIb3DQEJARYZZXJpYy5mdWx0ekBwcm9k +dWN0b3BzLmNvbTCBnzANBgkqhkiG9w0BAQEFAAOBjQAwgYkCgYEAxtJijhRJDMVJ +CrVmgMQaKT43+DUjdz28m1OS/wbGyRqZmwHWWXSgPHeuu30Opw/MxpgqlxfqAScZ +4nRfSq3kjENeoNAO8OPbKStT/5Y5HqEE6Ipfy8OU95Q4EbuGdSidrJDyHvWayNjc +GWBbvh7HnDwMkqiETFJZiP3y+ASunJcCAwEAATANBgkqhkiG9w0BAQUFAAOBgQAP +F9XVSlNSk6JJFzF3xA7FmAbB5Bf1kk0xmYt63Q3dsUHX++aVkC/TDnpAexvpA7sE +tKi20XthyjBWTB7KgfnQeoIz0tHJikbjTPo0yNZhv2p9DtApz12sGVIqtC7zR3rU +f1y9BHz8IM584dECmkd3lgBIbx2fClxvPX5zLbTYgw== +-----END CERTIFICATE-----falsefalsefalse + + + + + <xml-fragment/> + http://${#Project#E3Manager}:8181 + /response/ids/idprovision-sslkey-cert2falsefalsefalse + + <xml-fragment/> + http://${#Project#E3Manager}:8181 + + provision-sslkey-content2 + will fail +]]>/response/statusFAILUREfalsefalsefalse + + + + + <xml-fragment/> + http://${#Project#E3Manager}:8181 + <cert id="provision-sslkey-cert2"> + <displayName>new cert name</displayName> +</cert>/response/statusSUCCESSfalsefalse/response/idprovision-sslkey-cert2falsefalsefalse + + + + + <xml-fragment/> + http://${#Project#E3Manager}:8181 + /response/cert/displayNamenew cert namefalsefalsefalse + + + + <xml-fragment/>http://${#Project#E3Manager}:8181<?xml version="1.0" encoding="UTF-8" standalone="yes"?> +<key id="provision-sslkey-key2"> + <activeCertId>provision-sslkey-cert2</activeCertId> +</key>/response/statusSUCCESSfalsefalsefalse<xml-fragment/>UTF-8http://${#Project#E3Manager}:8181/response/statusSUCCESSfalsefalsefalse/response/key/activeCertIdprovision-sslkey-cert2falsefalsefalse + <xml-fragment/> + http://${#Project#E3Manager}:8181 + /response/statusFAILUREfalsefalsefalse + + + + <xml-fragment/>http://${#Project#E3Manager}:8181<?xml version="1.0" encoding="UTF-8" standalone="yes"?> +<key id="provision-sslkey-key2"> + <activeCertId /> +</key>/response/statusSUCCESSfalsefalsefalse + <xml-fragment/> + http://${#Project#E3Manager}:8181 + /response/statusSUCCESSfalsefalse + + + + + <xml-fragment/> + http://${#Project#E3Manager}:8181 + /response/statusFAILUREfalsefalse + + + + + <xml-fragment/> + http://${#Project#E3Manager}:8181 + /response/statusFAILUREfalsefalse + + + + + <xml-fragment/> + http://${#Project#E3Manager}:8181 + <id>1</id>falsefalse + + <xml-fragment/> + http://${#Project#E3Manager}:8181 + + 2012-04-25T08:28:15.801-04:00 + abcdef +]]>/response/statusFAILUREfalsefalse + + + + + <xml-fragment/> + http://${#Project#E3Manager}:8181 + /response/statusSUCCESSfalsefalse + + <xml-fragment/> + http://${#Project#E3Manager}:8181 + + + + + + + + +]]> + + http://${#Project#E3Manager}:8181 + + + + + + <xml-fragment/> + http://${#Project#E3Manager}:8181 + + > + TestKey +]]>/response/statusSUCCESSfalsefalse + + <xml-fragment/> + http://${#Project#E3Manager}:8181 + + > + Self-Signed Cert +]]>/response/statusSUCCESSfalsefalse/response/idprovision-sslkey-cert3falsefalsefalse + <xml-fragment/>http://${#Project#E3Manager}:8181<?xml version="1.0" encoding="UTF-8" standalone="yes"?> +<key id="provision-sslkey-key3"> + <activeCertId>provision-sslkey-cert3</activeCertId> +</key>/response/statusSUCCESSfalsefalsefalse + + + + + + +]]> + + http://${#Project#E3Manager}:8181 + + provision-sslkey-api3 + test_route_1 + PassThrough + active + provision-sslkey-endpoint3 + true + + + noAuth + + + + true + + + + active + + + http://${#Project#Target1}:8080/proxySize + + NoAuth + + key000Val + + + + + 10000 + 0.0 + 600000 + 0.0 + + + + + + + CompanyQuota + Billing + + + + + + CompanyQuota + Billing + + + +]]> + 200/response/statusSUCCESSfalsefalsefalse + + + <entry key="SIZE" value="10" xmlns="http://eviware.com/soapui/config"/>UTF-8https://${#Project#E3Gateway}/provision-sslkey-endpoint32009876543210falsefalse + + + + + + +]]> + + http://${#Project#E3Manager}:8181 + + 200/response/statusSUCCESSfalsefalsefalse + + + <xml-fragment/>http://${#Project#E3Manager}:8181<?xml version="1.0" encoding="UTF-8" standalone="yes"?> +<key id="provision-sslkey-key3"> + <activeCertId /> +</key>/response/statusSUCCESSfalsefalsefalse + <xml-fragment/> + http://${#Project#E3Manager}:8181 + /response/statusSUCCESSfalsefalse + + + + + <xml-fragment/> + http://${#Project#E3Manager}:8181 + /response/statusSUCCESSfalsefalse + + <xml-fragment/> + http://${#Project#E3Manager}:8181 + + + + + + + + +]]> + + http://${#Project#E3Manager}:8181 + + + + + + + http://${#Project#E3Manager}:8181 + + + <xml-fragment/> + http://${#Project#E3Manager}:8181 + + + <xml-fragment/> + http://${#Project#E3Manager}:8181 + + > + TestKey +]]>/response/statusSUCCESSfalsefalse + + <xml-fragment/> + http://${#Project#E3Manager}:8181 + + > + Self-Signed Cert +]]>/response/statusSUCCESSfalsefalse/response/idprovision-sslkey-cert4falsefalsefalse + <xml-fragment/>http://${#Project#E3Manager}:8181<?xml version="1.0" encoding="UTF-8" standalone="yes"?> +<key id="provision-sslkey-key4"> + <activeCertId>provision-sslkey-cert4</activeCertId> +</key>/response/statusSUCCESSfalsefalsefalse + + + + + + +]]> + + http://${#Project#E3Manager}:8181 + + provision-sslkey-api4 + provision-sslkey-api4 + PassThrough + active + provision-sslkey-endpoint4 + true + + + authKey + + + key + + + + true + + + + active + + + http://${#Project#Target1}:8080/proxySize + + NoAuth + + key000Val + + + + + 10000 + 0.0 + 600000 + 0.0 + + + + + + + CompanyQuota + Billing + + + + + + CompanyQuota + Billing + + + +]]> + 200/response/statusSUCCESSfalsefalsefalse + + + + <xml-fragment/> + http://${#Project#E3Manager}:8181 + + provision-sslkey-auth4 + active + authKey + + + + + provision-sslkey-key4 + + + + + + CompanyQuota + Billing + + + + + + CompanyQuota + Billing + + + + +]]>/response/statusSUCCESSfalsefalsefalse/response/idprovision-sslkey-auth4falsefalsefalse200 + + <xml-fragment/> + http://${#Project#E3Manager}:8181 + + provision-sslkey-p4 + + provision-sslkey-api4 + + + + provision-sslkey-auth4 + + + + + active + + active + reject + 98 + 1000 + + + + active + + + +]]>/response/statusSUCCESSfalsefalsefalse/response/idprovision-sslkey-p4falsefalsefalse200 + <entry key="SIZE" value="10" xmlns="http://eviware.com/soapui/config"/>UTF-8https://${#Project#E3Gateway}:25101/provision-sslkey-endpoint4?key=provision-sslkey-key42009876543210falsefalse + + http://${#Project#E3Manager}:8181 + 200/response/statusSUCCESSfalsefalsefalse + + + http://${#Project#E3Manager}:8181 + 200/response/statusSUCCESSfalsefalsefalse + + + + + + + +]]> + + http://${#Project#E3Manager}:8181 + + 200/response/statusSUCCESSfalsefalsefalse + + + <xml-fragment/>http://${#Project#E3Manager}:8181<?xml version="1.0" encoding="UTF-8" standalone="yes"?> +<key id="provision-sslkey-key4"> + <activeCertId /> +</key>/response/statusSUCCESSfalsefalsefalse + <xml-fragment/> + http://${#Project#E3Manager}:8181 + /response/statusSUCCESSfalsefalse + + + + + <xml-fragment/> + http://${#Project#E3Manager}:8181 + /response/statusSUCCESSfalsefalse + + <xml-fragment/> + http://${#Project#E3Manager}:8181 + + + + + + + + +]]> + + http://${#Project#E3Manager}:8181 + + + + + + <xml-fragment/> + http://${#Project#E3Manager}:8181 + + > + TestKey +]]>/response/statusSUCCESSfalsefalse + + <xml-fragment/> + http://${#Project#E3Manager}:8181 + + > + Self-Signed Cert +]]>/response/statusSUCCESSfalsefalse/response/idprovision-sslkey-cert5falsefalsefalse + <xml-fragment/>http://${#Project#E3Manager}:8181 + provision-sslkey-cert5 + test +]]>/response/statusSUCCESSfalsefalsefalse + + + + + + +]]> + + http://${#Project#E3Manager}:8181 + + provision-sslkey-api5 + test_route_1 + PassThrough + active + provision-sslkey-endpoint5 + true + + + noAuth + + + + true + + + + active + + + http://${#Project#Target1}:8080/proxySize + + NoAuth + + key000Val + + + + + 10000 + 0.0 + 600000 + 0.0 + + + + + + + CompanyQuota + Billing + + + + + + CompanyQuota + Billing + + + +]]> + 200/response/statusSUCCESSfalsefalsefalse + + + <entry key="SIZE" value="10" xmlns="http://eviware.com/soapui/config"/>UTF-8https://${#Project#E3Gateway}/provision-sslkey-endpoint52009876543210falsefalse + + + + + + +]]> + + http://${#Project#E3Manager}:8181 + + 200/response/statusSUCCESSfalsefalsefalse + + + <xml-fragment/>http://${#Project#E3Manager}:8181<?xml version="1.0" encoding="UTF-8" standalone="yes"?> +<key id="provision-sslkey-key5"> + <activeCertId /> +</key>/response/statusSUCCESSfalsefalsefalse + <xml-fragment/> + http://${#Project#E3Manager}:8181 + /response/statusSUCCESSfalsefalse + + + + + <xml-fragment/> + http://${#Project#E3Manager}:8181 + /response/statusSUCCESSfalsefalse + + E3Manager192.168.84.134E3Gateway192.168.84.134Target1192.168.84.90uniqdeleteC:/Users/rpiro/Documents/workspaceE3/E3/tests/certificates/client/client3.p12test \ No newline at end of file diff --git a/tests/functional-tests/smokepom.xml b/tests/functional-tests/smokepom.xml new file mode 100644 index 0000000..1739821 --- /dev/null +++ b/tests/functional-tests/smokepom.xml @@ -0,0 +1,26 @@ + + 4.0.0 + + tests + com.alu.e3 + 0.0.1-SNAPSHOT + .. + + com.alu.e3.functional-tests + functional-tests + pom + + + functional-test-provision-api + functional-test-provision-api-ext + functional-test-provision-policy + functional-test-provision-auth + functional-test-auth-basic + functional-test-rate-limit + provision-sslkey + functional-test-ca-prov + functional-test-header-transform + functional-test-http-method + + + diff --git a/tests/pom.xml b/tests/pom.xml new file mode 100644 index 0000000..cb025dd --- /dev/null +++ b/tests/pom.xml @@ -0,0 +1,59 @@ + + 4.0.0 + + root + com.alu.e3 + 0.0.1-SNAPSHOT + .. + + + tests + pom + + + eviwarePluginRepository + http://www.eviware.com/repository/maven2/ + + + + + functional-tests + + + + + + org.apache.maven.plugins + maven-compiler-plugin + 2.1 + + 1.6 + 1.6 + + + + org.apache.maven.plugins + maven-jar-plugin + 2.2 + + + + test-jar + + + + + + + + + + + junit + junit + 4.8.1 + test + + + \ No newline at end of file diff --git a/tests/src/site/compositeEndpoint.php b/tests/src/site/compositeEndpoint.php new file mode 100644 index 0000000..d776d75 --- /dev/null +++ b/tests/src/site/compositeEndpoint.php @@ -0,0 +1,20 @@ + + + + + \ No newline at end of file diff --git a/tests/src/site/displayBody.php b/tests/src/site/displayBody.php new file mode 100644 index 0000000..a0dc62d --- /dev/null +++ b/tests/src/site/displayBody.php @@ -0,0 +1,6 @@ + diff --git a/tests/src/site/mockTarget.php b/tests/src/site/mockTarget.php new file mode 100644 index 0000000..628359d --- /dev/null +++ b/tests/src/site/mockTarget.php @@ -0,0 +1,139 @@ + + + +<?= $statusHeaderString; ?> + + +

    mock

    +[IP address:] +
    +
    + +Current status for id :
    + (refresh) / available - overloaded - unavailable + +Current status:
    + +
    + + diff --git a/tests/src/site/parametersEndpoint.php b/tests/src/site/parametersEndpoint.php new file mode 100644 index 0000000..7b40071 --- /dev/null +++ b/tests/src/site/parametersEndpoint.php @@ -0,0 +1,45 @@ + + + + $value):?> + + + $value):?> + + + $value):?> + + + + + strlen($str)) { + print $str; + $size -= strlen($str); +} + +while ( $size > 0 ) { + print $str[$size-1]; + $size--; +} + +?> + + \ No newline at end of file diff --git a/tests/src/site/proxySize.php b/tests/src/site/proxySize.php new file mode 100644 index 0000000..61c7415 --- /dev/null +++ b/tests/src/site/proxySize.php @@ -0,0 +1,25 @@ + + strlen($str)) { + print $str; + $size -= strlen($str); +} + +while ( $size > 0 ) { + print $str[$size-1]; + $size--; +} + +?> + \ No newline at end of file diff --git a/tests/src/site/proxyWait.php b/tests/src/site/proxyWait.php new file mode 100644 index 0000000..86b4732 --- /dev/null +++ b/tests/src/site/proxyWait.php @@ -0,0 +1,14 @@ + + SUCCESS + \ No newline at end of file diff --git a/thirdparty-dependencies/thirdparty-dependencies.tar.gz b/thirdparty-dependencies/thirdparty-dependencies.tar.gz new file mode 100644 index 0000000..5a773ff Binary files /dev/null and b/thirdparty-dependencies/thirdparty-dependencies.tar.gz differ diff --git a/tools/apache-servicemix-4.3.1-fuse-01-09.tar.gz b/tools/apache-servicemix-4.3.1-fuse-01-09.tar.gz new file mode 100644 index 0000000..92975ba Binary files /dev/null and b/tools/apache-servicemix-4.3.1-fuse-01-09.tar.gz differ