├── .gitignore ├── .reuse └── dep5 ├── CREDITS ├── LICENSE ├── LICENSES └── Apache-2.0.txt ├── README.md ├── documents ├── df_object_storage.png ├── objectstore-sample-architecture.jpg ├── objectstore-sample-architecture.png ├── postRequest.png └── test.rtf ├── manifest.yml ├── pom.xml └── src └── main ├── java └── com │ └── sap │ └── refapps │ └── objectstore │ ├── Application.java │ ├── config │ ├── AmazonWebServiceConfiguration.java │ ├── AzureStorageConfiguration.java │ ├── GoogleCloudPlatformConfiguration.java │ └── ObjectStoreContextInitializer.java │ ├── controller │ └── ObjectstoreController.java │ ├── model │ └── BlobFile.java │ ├── repository │ └── ObjectStoreRepository.java │ ├── service │ ├── AWSObjectStoreService.java │ ├── AzureObjectStoreService.java │ ├── GCPObjectStoreService.java │ └── ObjectStoreService.java │ └── util │ ├── CloudProviders.java │ ├── EnvironmentUtil.java │ └── ObjectStoreUtil.java └── resources ├── Banner.txt └── application.properties /.gitignore: -------------------------------------------------------------------------------- 1 | # Compiled class file 2 | *.class 3 | 4 | # Log file 5 | *.log 6 | 7 | # BlueJ files 8 | *.ctxt 9 | 10 | # Mobile Tools for Java (J2ME) 11 | .mtj.tmp/ 12 | 13 | # Package Files # 14 | *.jar 15 | *.war 16 | *.ear 17 | *.zip 18 | *.tar.gz 19 | *.rar 20 | target 21 | .classpath 22 | .project 23 | .settings 24 | .springBeans 25 | .factorypath 26 | 27 | # virtual machine crash logs, see http://www.java.com/en/download/help/error_hotspot.xml 28 | hs_err_pid* 29 | -------------------------------------------------------------------------------- /.reuse/dep5: -------------------------------------------------------------------------------- 1 | Format: https://www.debian.org/doc/packaging-manuals/copyright-format/1.0/ 2 | Upstream-Name: cloud-objectstore-java-sample 3 | Upstream-Contact: ospo@sap.com 4 | Source: https://github.com/SAP-samples/cloud-objectstore-java-sample 5 | Disclaimer: The code in this project may include calls to APIs ("API Calls") of 6 | SAP or third-party products or services developed outside of this project 7 | ("External Products"). 8 | "APIs" means application programming interfaces, as well as their respective 9 | specifications and implementing code that allows software to communicate with 10 | other software. 11 | API Calls to External Products are not licensed under the open source license 12 | that governs this project. The use of such API Calls and related External 13 | Products are subject to applicable additional agreements with the relevant 14 | provider of the External Products. In no event shall the open source license 15 | that governs this project grant any rights in or to any External Products,or 16 | alter, expand or supersede any terms of the applicable additional agreements. 17 | If you have a valid license agreement with SAP for the use of a particular SAP 18 | External Product, then you may make use of any API Calls included in this 19 | project's code for that SAP External Product, subject to the terms of such 20 | license agreement. If you do not have a valid license agreement for the use of 21 | a particular SAP External Product, then you may only make use of any API Calls 22 | in this project for that SAP External Product for your internal, non-productive 23 | and non-commercial test and evaluation of such API Calls. Nothing herein grants 24 | you any rights to use or access any SAP External Product, or provide any third 25 | parties the right to use of access any SAP External Product, through API Calls. 26 | 27 | Files: * 28 | Copyright: 2023 SAP SE or an SAP affiliate company and btp-developer-guide-cap contributors 29 | License: Apache-2.0 30 | -------------------------------------------------------------------------------- /CREDITS: -------------------------------------------------------------------------------- 1 | This program references the following third party open source or other free download components. 2 | The third party licensors of these components may provide additional license rights, 3 | terms and conditions and/or require certain notices as described below. 4 | 5 | Spring boot (https://spring.io/projects/spring-boot) 6 | Licensed under Apache License, Version 2.0 - http://www.apache.org/licenses/LICENSE-2.0 7 | 8 | Jackson Databind (http://github.com/FasterXML/jackson) 9 | Licensed under Apache License, Version 2.0 - http://www.apache.org/licenses/LICENSE-2.0 10 | 11 | Guava (https://github.com/google/guava/) 12 | Licensed under Apache License, Version 2.0 - http://www.apache.org/licenses/LICENSE-2.0 13 | 14 | jclouds (https://jclouds.apache.org/) 15 | Licensed under Apache License, Version 2.0 - http://www.apache.org/licenses/LICENSE-2.0 16 | 17 | Commons Fileupload (https://commons.apache.org/proper/commons-fileupload/) 18 | Licensed under Apache License, Version 2.0 - http://www.apache.org/licenses/LICENSE-2.0 19 | -------------------------------------------------------------------------------- /LICENSE: -------------------------------------------------------------------------------- 1 | Apache License 2 | Version 2.0, January 2004 3 | http://www.apache.org/licenses/ 4 | 5 | TERMS AND CONDITIONS FOR USE, REPRODUCTION, AND DISTRIBUTION 6 | 7 | 1. Definitions. 8 | 9 | "License" shall mean the terms and conditions for use, reproduction, 10 | and distribution as defined by Sections 1 through 9 of this document. 11 | 12 | "Licensor" shall mean the copyright owner or entity authorized by 13 | the copyright owner that is granting the License. 14 | 15 | "Legal Entity" shall mean the union of the acting entity and all 16 | other entities that control, are controlled by, or are under common 17 | control with that entity. For the purposes of this definition, 18 | "control" means (i) the power, direct or indirect, to cause the 19 | direction or management of such entity, whether by contract or 20 | otherwise, or (ii) ownership of fifty percent (50%) or more of the 21 | outstanding shares, or (iii) beneficial ownership of such entity. 22 | 23 | "You" (or "Your") shall mean an individual or Legal Entity 24 | exercising permissions granted by this License. 25 | 26 | "Source" form shall mean the preferred form for making modifications, 27 | including but not limited to software source code, documentation 28 | source, and configuration files. 29 | 30 | "Object" form shall mean any form resulting from mechanical 31 | transformation or translation of a Source form, including but 32 | not limited to compiled object code, generated documentation, 33 | and conversions to other media types. 34 | 35 | "Work" shall mean the work of authorship, whether in Source or 36 | Object form, made available under the License, as indicated by a 37 | copyright notice that is included in or attached to the work 38 | (an example is provided in the Appendix below). 39 | 40 | "Derivative Works" shall mean any work, whether in Source or Object 41 | form, that is based on (or derived from) the Work and for which the 42 | editorial revisions, annotations, elaborations, or other modifications 43 | represent, as a whole, an original work of authorship. For the purposes 44 | of this License, Derivative Works shall not include works that remain 45 | separable from, or merely link (or bind by name) to the interfaces of, 46 | the Work and Derivative Works thereof. 47 | 48 | "Contribution" shall mean any work of authorship, including 49 | the original version of the Work and any modifications or additions 50 | to that Work or Derivative Works thereof, that is intentionally 51 | submitted to Licensor for inclusion in the Work by the copyright owner 52 | or by an individual or Legal Entity authorized to submit on behalf of 53 | the copyright owner. For the purposes of this definition, "submitted" 54 | means any form of electronic, verbal, or written communication sent 55 | to the Licensor or its representatives, including but not limited to 56 | communication on electronic mailing lists, source code control systems, 57 | and issue tracking systems that are managed by, or on behalf of, the 58 | Licensor for the purpose of discussing and improving the Work, but 59 | excluding communication that is conspicuously marked or otherwise 60 | designated in writing by the copyright owner as "Not a Contribution." 61 | 62 | "Contributor" shall mean Licensor and any individual or Legal Entity 63 | on behalf of whom a Contribution has been received by Licensor and 64 | subsequently incorporated within the Work. 65 | 66 | 2. Grant of Copyright License. Subject to the terms and conditions of 67 | this License, each Contributor hereby grants to You a perpetual, 68 | worldwide, non-exclusive, no-charge, royalty-free, irrevocable 69 | copyright license to reproduce, prepare Derivative Works of, 70 | publicly display, publicly perform, sublicense, and distribute the 71 | Work and such Derivative Works in Source or Object form. 72 | 73 | 3. Grant of Patent License. Subject to the terms and conditions of 74 | this License, each Contributor hereby grants to You a perpetual, 75 | worldwide, non-exclusive, no-charge, royalty-free, irrevocable 76 | (except as stated in this section) patent license to make, have made, 77 | use, offer to sell, sell, import, and otherwise transfer the Work, 78 | where such license applies only to those patent claims licensable 79 | by such Contributor that are necessarily infringed by their 80 | Contribution(s) alone or by combination of their Contribution(s) 81 | with the Work to which such Contribution(s) was submitted. If You 82 | institute patent litigation against any entity (including a 83 | cross-claim or counterclaim in a lawsuit) alleging that the Work 84 | or a Contribution incorporated within the Work constitutes direct 85 | or contributory patent infringement, then any patent licenses 86 | granted to You under this License for that Work shall terminate 87 | as of the date such litigation is filed. 88 | 89 | 4. Redistribution. You may reproduce and distribute copies of the 90 | Work or Derivative Works thereof in any medium, with or without 91 | modifications, and in Source or Object form, provided that You 92 | meet the following conditions: 93 | 94 | (a) You must give any other recipients of the Work or 95 | Derivative Works a copy of this License; and 96 | 97 | (b) You must cause any modified files to carry prominent notices 98 | stating that You changed the files; and 99 | 100 | (c) You must retain, in the Source form of any Derivative Works 101 | that You distribute, all copyright, patent, trademark, and 102 | attribution notices from the Source form of the Work, 103 | excluding those notices that do not pertain to any part of 104 | the Derivative Works; and 105 | 106 | (d) If the Work includes a "NOTICE" text file as part of its 107 | distribution, then any Derivative Works that You distribute must 108 | include a readable copy of the attribution notices contained 109 | within such NOTICE file, excluding those notices that do not 110 | pertain to any part of the Derivative Works, in at least one 111 | of the following places: within a NOTICE text file distributed 112 | as part of the Derivative Works; within the Source form or 113 | documentation, if provided along with the Derivative Works; or, 114 | within a display generated by the Derivative Works, if and 115 | wherever such third-party notices normally appear. The contents 116 | of the NOTICE file are for informational purposes only and 117 | do not modify the License. You may add Your own attribution 118 | notices within Derivative Works that You distribute, alongside 119 | or as an addendum to the NOTICE text from the Work, provided 120 | that such additional attribution notices cannot be construed 121 | as modifying the License. 122 | 123 | You may add Your own copyright statement to Your modifications and 124 | may provide additional or different license terms and conditions 125 | for use, reproduction, or distribution of Your modifications, or 126 | for any such Derivative Works as a whole, provided Your use, 127 | reproduction, and distribution of the Work otherwise complies with 128 | the conditions stated in this License. 129 | 130 | 5. Submission of Contributions. Unless You explicitly state otherwise, 131 | any Contribution intentionally submitted for inclusion in the Work 132 | by You to the Licensor shall be under the terms and conditions of 133 | this License, without any additional terms or conditions. 134 | Notwithstanding the above, nothing herein shall supersede or modify 135 | the terms of any separate license agreement you may have executed 136 | with Licensor regarding such Contributions. 137 | 138 | 6. Trademarks. This License does not grant permission to use the trade 139 | names, trademarks, service marks, or product names of the Licensor, 140 | except as required for reasonable and customary use in describing the 141 | origin of the Work and reproducing the content of the NOTICE file. 142 | 143 | 7. Disclaimer of Warranty. Unless required by applicable law or 144 | agreed to in writing, Licensor provides the Work (and each 145 | Contributor provides its Contributions) on an "AS IS" BASIS, 146 | WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or 147 | implied, including, without limitation, any warranties or conditions 148 | of TITLE, NON-INFRINGEMENT, MERCHANTABILITY, or FITNESS FOR A 149 | PARTICULAR PURPOSE. You are solely responsible for determining the 150 | appropriateness of using or redistributing the Work and assume any 151 | risks associated with Your exercise of permissions under this License. 152 | 153 | 8. Limitation of Liability. In no event and under no legal theory, 154 | whether in tort (including negligence), contract, or otherwise, 155 | unless required by applicable law (such as deliberate and grossly 156 | negligent acts) or agreed to in writing, shall any Contributor be 157 | liable to You for damages, including any direct, indirect, special, 158 | incidental, or consequential damages of any character arising as a 159 | result of this License or out of the use or inability to use the 160 | Work (including but not limited to damages for loss of goodwill, 161 | work stoppage, computer failure or malfunction, or any and all 162 | other commercial damages or losses), even if such Contributor 163 | has been advised of the possibility of such damages. 164 | 165 | 9. Accepting Warranty or Additional Liability. While redistributing 166 | the Work or Derivative Works thereof, You may choose to offer, 167 | and charge a fee for, acceptance of support, warranty, indemnity, 168 | or other liability obligations and/or rights consistent with this 169 | License. However, in accepting such obligations, You may act only 170 | on Your own behalf and on Your sole responsibility, not on behalf 171 | of any other Contributor, and only if You agree to indemnify, 172 | defend, and hold each Contributor harmless for any liability 173 | incurred by, or claims asserted against, such Contributor by reason 174 | of your accepting any such warranty or additional liability. 175 | 176 | END OF TERMS AND CONDITIONS 177 | 178 | APPENDIX: How to apply the Apache License to your work. 179 | 180 | To apply the Apache License to your work, attach the following 181 | boilerplate notice, with the fields enclosed by brackets "[]" 182 | replaced with your own identifying information. (Don't include 183 | the brackets!) The text should be enclosed in the appropriate 184 | comment syntax for the file format. We also recommend that a 185 | file or class name and description of purpose be included on the 186 | same "printed page" as the copyright notice for easier 187 | identification within third-party archives. 188 | 189 | Copyright 2021 SAP 190 | 191 | Licensed under the Apache License, Version 2.0 (the "License"); 192 | you may not use this file except in compliance with the License. 193 | You may obtain a copy of the License at 194 | 195 | http://www.apache.org/licenses/LICENSE-2.0 196 | 197 | Unless required by applicable law or agreed to in writing, software 198 | distributed under the License is distributed on an "AS IS" BASIS, 199 | WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. 200 | See the License for the specific language governing permissions and 201 | limitations under the License. 202 | -------------------------------------------------------------------------------- /LICENSES/Apache-2.0.txt: -------------------------------------------------------------------------------- 1 | Apache License 2 | 3 | Version 2.0, January 2004 4 | 5 | http://www.apache.org/licenses/ TERMS AND CONDITIONS FOR USE, REPRODUCTION, 6 | AND DISTRIBUTION 7 | 8 | 1. Definitions. 9 | 10 | 11 | 12 | "License" shall mean the terms and conditions for use, reproduction, and distribution 13 | as defined by Sections 1 through 9 of this document. 14 | 15 | 16 | 17 | "Licensor" shall mean the copyright owner or entity authorized by the copyright 18 | owner that is granting the License. 19 | 20 | 21 | 22 | "Legal Entity" shall mean the union of the acting entity and all other entities 23 | that control, are controlled by, or are under common control with that entity. 24 | For the purposes of this definition, "control" means (i) the power, direct 25 | or indirect, to cause the direction or management of such entity, whether 26 | by contract or otherwise, or (ii) ownership of fifty percent (50%) or more 27 | of the outstanding shares, or (iii) beneficial ownership of such entity. 28 | 29 | 30 | 31 | "You" (or "Your") shall mean an individual or Legal Entity exercising permissions 32 | granted by this License. 33 | 34 | 35 | 36 | "Source" form shall mean the preferred form for making modifications, including 37 | but not limited to software source code, documentation source, and configuration 38 | files. 39 | 40 | 41 | 42 | "Object" form shall mean any form resulting from mechanical transformation 43 | or translation of a Source form, including but not limited to compiled object 44 | code, generated documentation, and conversions to other media types. 45 | 46 | 47 | 48 | "Work" shall mean the work of authorship, whether in Source or Object form, 49 | made available under the License, as indicated by a copyright notice that 50 | is included in or attached to the work (an example is provided in the Appendix 51 | below). 52 | 53 | 54 | 55 | "Derivative Works" shall mean any work, whether in Source or Object form, 56 | that is based on (or derived from) the Work and for which the editorial revisions, 57 | annotations, elaborations, or other modifications represent, as a whole, an 58 | original work of authorship. For the purposes of this License, Derivative 59 | Works shall not include works that remain separable from, or merely link (or 60 | bind by name) to the interfaces of, the Work and Derivative Works thereof. 61 | 62 | 63 | 64 | "Contribution" shall mean any work of authorship, including the original version 65 | of the Work and any modifications or additions to that Work or Derivative 66 | Works thereof, that is intentionally submitted to Licensor for inclusion in 67 | the Work by the copyright owner or by an individual or Legal Entity authorized 68 | to submit on behalf of the copyright owner. For the purposes of this definition, 69 | "submitted" means any form of electronic, verbal, or written communication 70 | sent to the Licensor or its representatives, including but not limited to 71 | communication on electronic mailing lists, source code control systems, and 72 | issue tracking systems that are managed by, or on behalf of, the Licensor 73 | for the purpose of discussing and improving the Work, but excluding communication 74 | that is conspicuously marked or otherwise designated in writing by the copyright 75 | owner as "Not a Contribution." 76 | 77 | 78 | 79 | "Contributor" shall mean Licensor and any individual or Legal Entity on behalf 80 | of whom a Contribution has been received by Licensor and subsequently incorporated 81 | within the Work. 82 | 83 | 2. Grant of Copyright License. Subject to the terms and conditions of this 84 | License, each Contributor hereby grants to You a perpetual, worldwide, non-exclusive, 85 | no-charge, royalty-free, irrevocable copyright license to reproduce, prepare 86 | Derivative Works of, publicly display, publicly perform, sublicense, and distribute 87 | the Work and such Derivative Works in Source or Object form. 88 | 89 | 3. Grant of Patent License. Subject to the terms and conditions of this License, 90 | each Contributor hereby grants to You a perpetual, worldwide, non-exclusive, 91 | no-charge, royalty-free, irrevocable (except as stated in this section) patent 92 | license to make, have made, use, offer to sell, sell, import, and otherwise 93 | transfer the Work, where such license applies only to those patent claims 94 | licensable by such Contributor that are necessarily infringed by their Contribution(s) 95 | alone or by combination of their Contribution(s) with the Work to which such 96 | Contribution(s) was submitted. If You institute patent litigation against 97 | any entity (including a cross-claim or counterclaim in a lawsuit) alleging 98 | that the Work or a Contribution incorporated within the Work constitutes direct 99 | or contributory patent infringement, then any patent licenses granted to You 100 | under this License for that Work shall terminate as of the date such litigation 101 | is filed. 102 | 103 | 4. Redistribution. You may reproduce and distribute copies of the Work or 104 | Derivative Works thereof in any medium, with or without modifications, and 105 | in Source or Object form, provided that You meet the following conditions: 106 | 107 | (a) You must give any other recipients of the Work or Derivative Works a copy 108 | of this License; and 109 | 110 | (b) You must cause any modified files to carry prominent notices stating that 111 | You changed the files; and 112 | 113 | (c) You must retain, in the Source form of any Derivative Works that You distribute, 114 | all copyright, patent, trademark, and attribution notices from the Source 115 | form of the Work, excluding those notices that do not pertain to any part 116 | of the Derivative Works; and 117 | 118 | (d) If the Work includes a "NOTICE" text file as part of its distribution, 119 | then any Derivative Works that You distribute must include a readable copy 120 | of the attribution notices contained within such NOTICE file, excluding those 121 | notices that do not pertain to any part of the Derivative Works, in at least 122 | one of the following places: within a NOTICE text file distributed as part 123 | of the Derivative Works; within the Source form or documentation, if provided 124 | along with the Derivative Works; or, within a display generated by the Derivative 125 | Works, if and wherever such third-party notices normally appear. The contents 126 | of the NOTICE file are for informational purposes only and do not modify the 127 | License. You may add Your own attribution notices within Derivative Works 128 | that You distribute, alongside or as an addendum to the NOTICE text from the 129 | Work, provided that such additional attribution notices cannot be construed 130 | as modifying the License. 131 | 132 | You may add Your own copyright statement to Your modifications and may provide 133 | additional or different license terms and conditions for use, reproduction, 134 | or distribution of Your modifications, or for any such Derivative Works as 135 | a whole, provided Your use, reproduction, and distribution of the Work otherwise 136 | complies with the conditions stated in this License. 137 | 138 | 5. Submission of Contributions. Unless You explicitly state otherwise, any 139 | Contribution intentionally submitted for inclusion in the Work by You to the 140 | Licensor shall be under the terms and conditions of this License, without 141 | any additional terms or conditions. Notwithstanding the above, nothing herein 142 | shall supersede or modify the terms of any separate license agreement you 143 | may have executed with Licensor regarding such Contributions. 144 | 145 | 6. Trademarks. This License does not grant permission to use the trade names, 146 | trademarks, service marks, or product names of the Licensor, except as required 147 | for reasonable and customary use in describing the origin of the Work and 148 | reproducing the content of the NOTICE file. 149 | 150 | 7. Disclaimer of Warranty. Unless required by applicable law or agreed to 151 | in writing, Licensor provides the Work (and each Contributor provides its 152 | Contributions) on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY 153 | KIND, either express or implied, including, without limitation, any warranties 154 | or conditions of TITLE, NON-INFRINGEMENT, MERCHANTABILITY, or FITNESS FOR 155 | A PARTICULAR PURPOSE. You are solely responsible for determining the appropriateness 156 | of using or redistributing the Work and assume any risks associated with Your 157 | exercise of permissions under this License. 158 | 159 | 8. Limitation of Liability. In no event and under no legal theory, whether 160 | in tort (including negligence), contract, or otherwise, unless required by 161 | applicable law (such as deliberate and grossly negligent acts) or agreed to 162 | in writing, shall any Contributor be liable to You for damages, including 163 | any direct, indirect, special, incidental, or consequential damages of any 164 | character arising as a result of this License or out of the use or inability 165 | to use the Work (including but not limited to damages for loss of goodwill, 166 | work stoppage, computer failure or malfunction, or any and all other commercial 167 | damages or losses), even if such Contributor has been advised of the possibility 168 | of such damages. 169 | 170 | 9. Accepting Warranty or Additional Liability. While redistributing the Work 171 | or Derivative Works thereof, You may choose to offer, and charge a fee for, 172 | acceptance of support, warranty, indemnity, or other liability obligations 173 | and/or rights consistent with this License. However, in accepting such obligations, 174 | You may act only on Your own behalf and on Your sole responsibility, not on 175 | behalf of any other Contributor, and only if You agree to indemnify, defend, 176 | and hold each Contributor harmless for any liability incurred by, or claims 177 | asserted against, such Contributor by reason of your accepting any such warranty 178 | or additional liability. END OF TERMS AND CONDITIONS 179 | 180 | APPENDIX: How to apply the Apache License to your work. 181 | 182 | To apply the Apache License to your work, attach the following boilerplate 183 | notice, with the fields enclosed by brackets "[]" replaced with your own identifying 184 | information. (Don't include the brackets!) The text should be enclosed in 185 | the appropriate comment syntax for the file format. We also recommend that 186 | a file or class name and description of purpose be included on the same "printed 187 | page" as the copyright notice for easier identification within third-party 188 | archives. 189 | 190 | Copyright [yyyy] [name of copyright owner] 191 | 192 | Licensed under the Apache License, Version 2.0 (the "License"); 193 | 194 | you may not use this file except in compliance with the License. 195 | 196 | You may obtain a copy of the License at 197 | 198 | http://www.apache.org/licenses/LICENSE-2.0 199 | 200 | Unless required by applicable law or agreed to in writing, software 201 | 202 | distributed under the License is distributed on an "AS IS" BASIS, 203 | 204 | WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. 205 | 206 | See the License for the specific language governing permissions and 207 | 208 | limitations under the License. -------------------------------------------------------------------------------- /README.md: -------------------------------------------------------------------------------- 1 | # Object Store Reference Application 2 | 3 | [![REUSE status](https://api.reuse.software/badge/github.com/SAP-samples/cloud-objectstore-java-sample)](https://api.reuse.software/info/github.com/SAP-samples/cloud-objectstore-java-sample) 4 | 5 | Object Store reference application is built to showcase the method of developing a single code-line multi cloud application consuming Object Store Service of SAP Business Technology Platform (SAP BTP) Cloud Foundry Environment. 6 | 7 | ## Description 8 | Object Store service enables the storage and management of objects, which involves creation, upload, download, and deletion of objects. SAP provides Object Store Service on its SAP Business Technology Platform running on different IaaS providers like Amazon Web Service, Azure, Google Cloud Platform. [Please click here for more information on Object Store Service](https://help.sap.com/docs/object-store/object-store-service-on-sap-btp/what-is-object-store). 9 | 10 | Though the Object Store Service is provided by SAP on multiple IaaS providers, the way to connect to and use the service varies for each IaaS provider due to changes in the structure of credentials and in the configurations. Writing a single code-line application that works seamlessly on all these IaaS providers is a challenge that many developers face. 11 | 12 | We have developed a single code line reference application that can work with Object Store Service on SAP Business Technology Platform Cloud Foundry Environment hosted on multiple IaaS providers. This application performs operations like upload, download, delete and listing of files. It is a spring boot application that uses [Apache jclouds](https://jclouds.apache.org/) library which provides a multi-cloud toolkit that gives a developer the freedom to create applications that are portable across IaaS providers. 13 | 14 | #### Features of the Application 15 | 16 | • The application provides RESTful endpoints to upload, download, delete and list files. 17 | 18 | • It calls jclouds library's API endpoints to perform the above operations on the files in Object Store Service. JClouds abstracts the code to perform these operation on the different providers like AWS S3, Google Cloud Storage and Azure Storage. 19 | 20 | ## Architecture 21 | 22 | ![Alt text](./documents/objectstore-sample-architecture.jpg "Architecture") 23 | 24 | A single REST controller accepts the request (GET, POST, DELETE). 25 | 26 | Separate service implementations and configuration classes are provided for each of the Object Store Service provider. The right service implementation and configuration is loaded by spring boot based on the IaaS provider that the application is deployed on. 27 | 28 | A single DAO (Data Access Object)/repository class calls the jclouds api’s to perform upload, download, delete operations on the Object Store. 29 | 30 | ## Referenced Libraries 31 | Following jclouds dependencies are used in the application. 32 | 33 | ~~~ 34 | 35 | 36 | org.apache.jclouds.provider 37 | aws-s3 38 | 2.3.0 39 | 40 | 41 | org.apache.jclouds.provider 42 | google-cloud-storage 43 | 2.3.0 44 | 45 | 46 | org.apache.jclouds.provider 47 | azureblob 48 | 2.3.0 49 | 50 | ~~~ 51 | The size of each of the jclouds dependencies are as follows: 52 | ~~~ 53 | Dependency Size 54 | ------------- ------- 55 | aws-s3 29kb 56 | google-cloud-storage 158kb 57 | azureblob 138kb 58 | ~~~ 59 | 60 | Besides spring-boot and jclouds the other dependencies used in the application are: 61 | 62 | • jackson-databind: to parse json file 63 | 64 | • commons-fileupload: to upload files 65 | 66 | For more information about the dependencies please refer [pom.xml file](./pom.xml). 67 | 68 | 69 | ## Requirements 70 | - [Java 11](https://sap.github.io/SapMachine/) 71 | - [Apache Maven 3.3+](https://maven.apache.org/download.cgi) 72 | - [Cloud Foundry CLI](https://github.com/cloudfoundry/cli#downloads) 73 | - SAP Business Technology Platform Global account 74 | - [Provision Object Store service](https://discovery-center.cloud.sap/#/serviceCatalog/object-store-service). It is a paid service on Cloud Foundry. 75 | - A Cloud Foundry user with SpaceDeveloper role to deploy the application 76 | 77 | ## Download and Installation 78 | 79 | #### Build the Application 80 | - [Clone](https://help.github.com/articles/cloning-a-repository/) the application `cloud-objectstore-java-sample` to your system 81 | 82 | Clone URL : `https://github.com/SAP-samples/cloud-objectstore-java-sample.git` 83 | - Navigate to the root folder of the application and run the below maven command to build the application: 84 | ``` 85 | mvn clean install 86 | ``` 87 | 88 | #### Deploy the Application on Cloud Foundry 89 | 90 | 1. Logon to the Cloud Foundry environment using the following commands on the command prompt: 91 | ``` 92 | cf api 93 | cf login 94 | ``` 95 | `api` - [URL of the Cloud Foundry landscape](https://help.sap.com/viewer/65de2977205c403bbc107264b8eccf4b/Cloud/en-US/350356d1dc314d3199dca15bd2ab9b0e.html) that you are trying to connect to. 96 | 97 | Enter username, password, org and space when prompted to. [Please click here for more information](https://help.sap.com/viewer/65de2977205c403bbc107264b8eccf4b/Cloud/en-US/75125ef1e60e490e91eb58fe48c0f9e7.html#loio4ef907afb1254e8286882a2bdef0edf4). 98 | 99 | Check if the Cloud Foundry Space you will be deploying the application has the following entitlements: 100 | 101 | | Landscape | Service | Plan | Number of Instances | 102 | |-----------------|-----------------|----------------|:-------------------:| 103 | | AWS | objectstore | s3-standard | 1 | 104 | | GCP | objectstore | gcs-standard | 1 | 105 | | Azure | objectstore | azure-standard | 1 | 106 | 107 | 2. Create the Cloud Foundry Object Store Service Instance 108 | 109 | - To run the application on AWS landscape, create a service by executing the below command: 110 | 111 | `cf create-service objectstore s3-standard objectstore-service` 112 | 113 | - To run the application on GCP landscape, create a service by executing the below command: 114 | 115 | `cf create-service objectstore gcs-standard objectstore-service` 116 | 117 | - To run the application on Azure landscape, create a service by executing the below command: 118 | 119 | `cf create-service objectstore azure-standard objectstore-service` 120 | 121 | 122 | 3. Edit manifest.yml file. Replace the `` placeholder with any unique string. You can use your *SAP User ID* so that the application name is unique in the CF landscape. You can find your *SAP User ID* in [your sap.com profile](https://people.sap.com/#personal_info). 123 | 124 | ~~~ 125 | --- 126 | applications: 127 | - name: -objectstore-sample-svc 128 | memory: 2G 129 | buildpack: sap_java_buildpack 130 | path: target/objectstore-sample-1.1.1.jar 131 | env: 132 | JBP_CONFIG_COMPONENTS: "jres: ['com.sap.xs.java.buildpack.jdk.SAPMachineJDK']" 133 | JBP_CONFIG_SAP_MACHINE_JRE: '{ jre: { version: "11.+" } }' 134 | SERVICE_LABEL: "objectstore" 135 | services: 136 | - objectstore-service 137 | ~~~ 138 | 139 | 4. To deploy the application, navigate to the root of the application and execute the below command: 140 | ``` 141 | cf push 142 | ``` 143 | 144 | #### Test the Application 145 | 146 | [Postman Client](https://www.getpostman.com/apps) can be used to test / access the REST API endpoints. 147 | 148 | Replace the `` placeholder in the below steps with the URL of the application you deployed. 149 | 150 | ##### Upload a file / object 151 | 152 | POST 153 | 154 | To upload a file / object set the below request body and hit the endpoint url. 155 | 156 | EndPoint URL : `/objectstorage.svc/api/v1/storage/` 157 | 158 | Request Body : form-data with key-value pair. Pass the name of the key as `file` and the value is `the path of the file`. 159 | 160 | > For the file upload, we have provided a [test file](/documents/test.rtf) in the documents folder which you can use if needed for the upload testing. 161 | 162 | ![Alt text](./documents/postRequest.png "post request") 163 | 164 | > The file upload option may differ version by version of postman. So keeping the above screenshot as generic, kindly adopt accordingly. 165 | 166 | A successful upload operation gives the following response : 167 | 168 | Status: 202 169 | 170 | Response Body: ` is successfully uploaded.` 171 | 172 | 173 | ##### List all the files / objects 174 | 175 | GET 176 | 177 | To get the list of a files / objects set the content-type and hit the below endpoint url. 178 | 179 | EndPoint URL : `https:///objectstorage.svc/api/v1/storage/` 180 | 181 | Content-Type : `application/json` 182 | 183 | A successful GET operation gives the following response : 184 | 185 | Status: 200 186 | 187 | Response Body: 188 | ~~~ 189 | [ 190 | { 191 | "etag": "CIjak4uDxeACEAE=", 192 | "bucket": "sap-cp-osaas-a78345d3-e45d-42eb-9c03-c47393d0d436", 193 | "name": "SampleFile.pdf", 194 | "url": "https://www.googleapis.com/storage/v1/b/sap-cp-osaas-a78345d3-e45d-42eb-9c03-c47393d0d436/o/SampleFile.pdf", 195 | "lastModified": "Mon Feb 18 15:30:22 IST 2019", 196 | "size": "245.7 KB", 197 | "contentType": "application/pdf", 198 | "userMetadata": { 199 | "description": "sample content" 200 | } 201 | }, 202 | { 203 | "etag": "COf+0p7uxOACEAE=", 204 | "bucket": "sap-cp-osaas-a78345d3-e45d-42eb-9c03-c47393d0d436", 205 | "name": "SampleImage.jpg", 206 | "url": "https://www.googleapis.com/storage/v1/b/sap-cp-osaas-a78345d3-e45d-42eb-9c03-c47393d0d436/o/SampleImage.jpg", 207 | "lastModified": "Mon Feb 18 13:57:06 IST 2019", 208 | "size": "46.1 KB", 209 | "contentType": "image/jpeg", 210 | "userMetadata": { 211 | "description": "sample content" 212 | } 213 | } 214 | ... 215 | 216 | ] 217 | ~~~ 218 | 219 | ##### Download a file / object 220 | 221 | GET 222 | 223 | > Please open any browser and hit the below endpoint url to download a file / object rather than using Postman to test it. 224 | 225 | EndPoint URL : `https:///objectstorage.svc/api/v1/storage/{file-name}` 226 | 227 | ##### Delete a file / object 228 | 229 | DELETE 230 | 231 | To delete a file / object hit the below endpoint url by appending the file / object name in postman. 232 | 233 | EndPoint URL : `https:///objectstorage.svc/api/v1/storage/{file-name}` 234 | 235 | A successful upload operation gives the following response : 236 | 237 | Status: 200 238 | 239 | Response Body: ` is successfully deleted.` 240 | 241 | ## How to obtain support 242 | 243 | In case you find a bug, or you need additional support, please open an issue here in GitHub. 244 | 245 | ## Known Issues 246 | - Using InputStream instead of ByteArray to upload large files to make the read operation faster causes issues. For more information see [here](https://issues.apache.org/jira/browse/JCLOUDS-1451). 247 | 248 | ## License 249 | 250 | Copyright (c) 2020 SAP SE or an SAP affiliate company. All rights reserved. This project is licensed under the Apache Software License, version 2.0 except as noted otherwise in the [LICENSE](LICENSES/Apache-2.0.txt) file. 251 | -------------------------------------------------------------------------------- /documents/df_object_storage.png: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/SAP-samples/cloud-objectstore-java-sample/ac6ab3de8d3ae8d75556155486a4f89a7ba5e4c9/documents/df_object_storage.png -------------------------------------------------------------------------------- /documents/objectstore-sample-architecture.jpg: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/SAP-samples/cloud-objectstore-java-sample/ac6ab3de8d3ae8d75556155486a4f89a7ba5e4c9/documents/objectstore-sample-architecture.jpg -------------------------------------------------------------------------------- /documents/objectstore-sample-architecture.png: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/SAP-samples/cloud-objectstore-java-sample/ac6ab3de8d3ae8d75556155486a4f89a7ba5e4c9/documents/objectstore-sample-architecture.png -------------------------------------------------------------------------------- /documents/postRequest.png: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/SAP-samples/cloud-objectstore-java-sample/ac6ab3de8d3ae8d75556155486a4f89a7ba5e4c9/documents/postRequest.png -------------------------------------------------------------------------------- /documents/test.rtf: -------------------------------------------------------------------------------- 1 | {\rtf1\ansi\ansicpg1252\cocoartf1561\cocoasubrtf600 2 | {\fonttbl\f0\fswiss\fcharset0 Helvetica;} 3 | {\colortbl;\red255\green255\blue255;} 4 | {\*\expandedcolortbl;;} 5 | \paperw11900\paperh16840\margl1440\margr1440\vieww10800\viewh8400\viewkind0 6 | \pard\tx566\tx1133\tx1700\tx2267\tx2834\tx3401\tx3968\tx4535\tx5102\tx5669\tx6236\tx6803\pardirnatural\partightenfactor0 7 | 8 | \f0\fs24 \cf0 hello} -------------------------------------------------------------------------------- /manifest.yml: -------------------------------------------------------------------------------- 1 | --- 2 | applications: 3 | - name: -objectstore-sample-svc 4 | memory: 2G 5 | buildpack: sap_java_buildpack 6 | path: target/objectstore-sample-1.1.1.jar 7 | env: 8 | JBP_CONFIG_COMPONENTS: "jres: ['com.sap.xs.java.buildpack.jdk.SAPMachineJDK']" 9 | JBP_CONFIG_SAP_MACHINE_JRE: '{ jre: { version: "11.+" } }' 10 | SERVICE_LABEL: "objectstore" 11 | services: 12 | - objectstore-service 13 | -------------------------------------------------------------------------------- /pom.xml: -------------------------------------------------------------------------------- 1 | 2 | 4 | 4.0.0 5 | 6 | com.sap.refapps.objectstore 7 | objectstore-sample 8 | 1.1.1 9 | jar 10 | 11 | objectstore-sample 12 | Object Store reference application 13 | 14 | 15 | org.springframework.boot 16 | spring-boot-starter-parent 17 | 2.6.10 18 | 19 | 20 | 21 | 22 | UTF-8 23 | UTF-8 24 | 11 25 | 2.3.0 26 | 2.17.0 27 | 5.1.0 28 | 3.1.1 29 | 2.2.4.RELEASE 30 | 31 | 32 | 33 | 34 | 35 | 36 | org.springframework.boot 37 | spring-boot-starter-web 38 | 39 | 40 | org.springframework.boot 41 | spring-boot-configuration-processor 42 | true 43 | 44 | 45 | org.springframework.boot 46 | spring-boot-starter-test 47 | 48 | 49 | 50 | 51 | org.apache.jclouds.provider 52 | aws-s3 53 | ${jclouds.version} 54 | 55 | 56 | org.apache.jclouds.provider 57 | google-cloud-storage 58 | ${jclouds.version} 59 | 60 | 61 | 62 | org.apache.jclouds.provider 63 | azureblob 64 | ${jclouds.version} 65 | 66 | 67 | 68 | com.fasterxml.jackson.core 69 | jackson-databind 70 | 71 | 72 | commons-fileupload 73 | commons-fileupload 74 | 1.3.3 75 | 76 | 77 | 78 | 79 | com.google.inject.extensions 80 | guice-assistedinject 81 | ${guice.assistedinject.version} 82 | 83 | 84 | 85 | 86 | io.pivotal.cfenv 87 | java-cfenv-boot 88 | ${java.cfenv.boot.version} 89 | 90 | 91 | 92 | 93 | 94 | 95 | org.springframework.boot 96 | spring-boot-maven-plugin 97 | 98 | 99 | 100 | 101 | -------------------------------------------------------------------------------- /src/main/java/com/sap/refapps/objectstore/Application.java: -------------------------------------------------------------------------------- 1 | package com.sap.refapps.objectstore; 2 | 3 | import org.springframework.boot.autoconfigure.SpringBootApplication; 4 | import org.springframework.boot.builder.SpringApplicationBuilder; 5 | 6 | import com.sap.refapps.objectstore.config.ObjectStoreContextInitializer; 7 | 8 | @SpringBootApplication 9 | public class Application { 10 | 11 | public static void main(String[] args) { 12 | new SpringApplicationBuilder(Application.class) 13 | .initializers(new ObjectStoreContextInitializer()).run(args); 14 | } 15 | 16 | } 17 | 18 | -------------------------------------------------------------------------------- /src/main/java/com/sap/refapps/objectstore/config/AmazonWebServiceConfiguration.java: -------------------------------------------------------------------------------- 1 | package com.sap.refapps.objectstore.config; 2 | 3 | import org.jclouds.ContextBuilder; 4 | import org.jclouds.blobstore.BlobStoreContext; 5 | import org.springframework.context.annotation.Configuration; 6 | import org.springframework.context.annotation.Profile; 7 | 8 | import com.sap.refapps.objectstore.util.CloudProviders; 9 | 10 | import io.pivotal.cfenv.core.CfEnv; 11 | 12 | /** 13 | * This is AWS Credentials Configuration class 14 | * 15 | */ 16 | 17 | @Profile("cloud-aws") 18 | @Configuration 19 | public class AmazonWebServiceConfiguration { 20 | 21 | private static final String ACCESS_KEY_ID = "access_key_id"; 22 | private static final String SECRET_ACCESS_KEY = "secret_access_key"; 23 | private static final String BUCKET = "bucket"; 24 | private static final String SERVICE_LABEL = "SERVICE_LABEL"; 25 | 26 | private String accessKeyId; 27 | private String bucket; 28 | private String secretAccessKey; 29 | 30 | public String getBucket() { 31 | return bucket; 32 | } 33 | 34 | /** 35 | * @return blobStoreContext 36 | */ 37 | public BlobStoreContext getBlobStoreContext() { 38 | 39 | var serviceLabel = System.getenv(SERVICE_LABEL); 40 | var cfenv = new CfEnv(); 41 | var cfService = cfenv.findServiceByLabel(serviceLabel); 42 | var cfCredentials = cfService.getCredentials(); 43 | 44 | this.accessKeyId = cfCredentials.getString(ACCESS_KEY_ID); 45 | this.secretAccessKey = cfCredentials.getString(SECRET_ACCESS_KEY); 46 | this.bucket = cfCredentials.getString(BUCKET); 47 | 48 | return ContextBuilder.newBuilder(CloudProviders.PROVIDER_AWS.toString()) 49 | .credentials(this.accessKeyId, this.secretAccessKey) 50 | .buildView(BlobStoreContext.class); 51 | } 52 | 53 | } -------------------------------------------------------------------------------- /src/main/java/com/sap/refapps/objectstore/config/AzureStorageConfiguration.java: -------------------------------------------------------------------------------- 1 | package com.sap.refapps.objectstore.config; 2 | 3 | import org.jclouds.ContextBuilder; 4 | import org.jclouds.blobstore.BlobStoreContext; 5 | import org.springframework.context.annotation.Bean; 6 | import org.springframework.context.annotation.Configuration; 7 | import org.springframework.context.annotation.Profile; 8 | 9 | import com.sap.refapps.objectstore.util.CloudProviders; 10 | 11 | import io.pivotal.cfenv.core.CfEnv; 12 | 13 | /** 14 | * This is MS Azure Credentials Configuration class 15 | * 16 | */ 17 | 18 | @Profile("cloud-azure") 19 | @Configuration 20 | public class AzureStorageConfiguration { 21 | 22 | private static final String ACCOUNT_NAME = "account_name"; 23 | private static final String SAS_TOKEN = "sas_token"; 24 | private static final String CONTAINER_NAME = "container_name"; 25 | private static final String CONTAINER_URI = "container_uri"; 26 | private static final String SERVICE_LABEL = "SERVICE_LABEL"; 27 | 28 | private String accountName; 29 | private String containerName; 30 | private String sasToken; 31 | private String containerUri; 32 | 33 | public String getContainerName() { 34 | return containerName; 35 | } 36 | 37 | @Bean 38 | public BlobStoreContext getBlobStoreContext() { 39 | 40 | var serviceLabel = System.getenv(SERVICE_LABEL); 41 | var cfenv = new CfEnv(); 42 | var cfService = cfenv.findServiceByLabel(serviceLabel); 43 | var cfCredentials = cfService.getCredentials(); 44 | 45 | this.accountName = cfCredentials.getString(ACCOUNT_NAME); 46 | this.sasToken = cfCredentials.getString(SAS_TOKEN); 47 | this.containerName = cfCredentials.getString(CONTAINER_NAME); 48 | this.containerUri = cfCredentials.getString(CONTAINER_URI); 49 | 50 | String blobEndPoint = containerUri.replace("/" + containerName, ""); 51 | BlobStoreContext blobStoreContext = ContextBuilder.newBuilder(CloudProviders.PROVIDER_AZURE.toString()) 52 | .endpoint(blobEndPoint) 53 | .credentials(this.accountName, this.sasToken) 54 | .buildView(BlobStoreContext.class); 55 | 56 | return blobStoreContext; 57 | } 58 | 59 | } -------------------------------------------------------------------------------- /src/main/java/com/sap/refapps/objectstore/config/GoogleCloudPlatformConfiguration.java: -------------------------------------------------------------------------------- 1 | package com.sap.refapps.objectstore.config; 2 | 3 | import java.nio.charset.Charset; 4 | import java.util.Base64; 5 | 6 | import org.jclouds.ContextBuilder; 7 | import org.jclouds.blobstore.BlobStoreContext; 8 | import org.jclouds.domain.Credentials; 9 | import org.jclouds.googlecloud.GoogleCredentialsFromJson; 10 | import org.springframework.context.annotation.Configuration; 11 | import org.springframework.context.annotation.Profile; 12 | 13 | import com.google.common.base.Supplier; 14 | import com.sap.refapps.objectstore.util.CloudProviders; 15 | 16 | import io.pivotal.cfenv.core.CfEnv; 17 | 18 | /** 19 | * This is GCP Credentials Configuration class 20 | * 21 | */ 22 | 23 | @Profile("cloud-gcp") 24 | @Configuration 25 | public class GoogleCloudPlatformConfiguration { 26 | 27 | private static final String BASE64_ENCODED_PRIVATE_KEY_DATA = "base64EncodedPrivateKeyData"; 28 | private static final String BUCKET = "bucket"; 29 | private static final String SERVICE_LABEL = "SERVICE_LABEL"; 30 | 31 | private String base64EncodedPrivateKeyData; 32 | private String bucket; 33 | 34 | public String getBucket() { 35 | return bucket; 36 | } 37 | 38 | /** 39 | * @return blobStoreContext 40 | */ 41 | public BlobStoreContext getBlobStoreContext() { 42 | 43 | var serviceLabel = System.getenv(SERVICE_LABEL); 44 | var cfenv = new CfEnv(); 45 | var cfService = cfenv.findServiceByLabel(serviceLabel); 46 | var cfCredentials = cfService.getCredentials(); 47 | 48 | this.base64EncodedPrivateKeyData = cfCredentials.getString(BASE64_ENCODED_PRIVATE_KEY_DATA); 49 | this.bucket = cfCredentials.getString(BUCKET); 50 | 51 | final byte[] decodedKey = Base64.getDecoder().decode(this.base64EncodedPrivateKeyData); 52 | final String decodedCredential = new String(decodedKey, Charset.forName("UTF-8")); 53 | Supplier supplierCredential = new GoogleCredentialsFromJson(decodedCredential); 54 | BlobStoreContext blobStoreContext = ContextBuilder.newBuilder(CloudProviders.PROVIDER_GCP.toString()) 55 | .credentialsSupplier(supplierCredential).buildView(BlobStoreContext.class); 56 | 57 | return blobStoreContext; 58 | } 59 | } 60 | -------------------------------------------------------------------------------- /src/main/java/com/sap/refapps/objectstore/config/ObjectStoreContextInitializer.java: -------------------------------------------------------------------------------- 1 | package com.sap.refapps.objectstore.config; 2 | 3 | import org.springframework.context.ApplicationContextInitializer; 4 | import org.springframework.context.ConfigurableApplicationContext; 5 | import org.springframework.core.env.ConfigurableEnvironment; 6 | 7 | import com.sap.refapps.objectstore.util.EnvironmentUtil; 8 | 9 | public class ObjectStoreContextInitializer implements ApplicationContextInitializer { 10 | 11 | @Override 12 | public void initialize(ConfigurableApplicationContext applicationContext) { 13 | final ConfigurableEnvironment applicationEnvironment = applicationContext.getEnvironment(); 14 | final String profileToActive = EnvironmentUtil.getActiveProfile(); 15 | // Active profile is set based on the objectore service connected to. (s3/gcs etc..) 16 | applicationEnvironment.addActiveProfile(profileToActive); 17 | } 18 | 19 | } 20 | -------------------------------------------------------------------------------- /src/main/java/com/sap/refapps/objectstore/controller/ObjectstoreController.java: -------------------------------------------------------------------------------- 1 | package com.sap.refapps.objectstore.controller; 2 | 3 | import java.io.IOException; 4 | import java.io.InputStream; 5 | import java.util.List; 6 | import java.util.Optional; 7 | 8 | import javax.servlet.http.HttpServletRequest; 9 | 10 | import org.apache.commons.fileupload.FileItemIterator; 11 | import org.apache.commons.fileupload.FileItemStream; 12 | import org.apache.commons.fileupload.FileUploadException; 13 | import org.apache.commons.fileupload.servlet.ServletFileUpload; 14 | import org.slf4j.Logger; 15 | import org.slf4j.LoggerFactory; 16 | import org.springframework.beans.factory.annotation.Autowired; 17 | import org.springframework.core.io.InputStreamResource; 18 | import org.springframework.http.HttpHeaders; 19 | import org.springframework.http.HttpStatus; 20 | import org.springframework.http.ResponseEntity; 21 | import org.springframework.web.bind.annotation.DeleteMapping; 22 | import org.springframework.web.bind.annotation.GetMapping; 23 | import org.springframework.web.bind.annotation.PathVariable; 24 | import org.springframework.web.bind.annotation.PostMapping; 25 | import org.springframework.web.bind.annotation.RequestMapping; 26 | import org.springframework.web.bind.annotation.ResponseBody; 27 | import org.springframework.web.bind.annotation.RestController; 28 | 29 | import com.google.common.io.ByteStreams; 30 | import com.sap.refapps.objectstore.model.BlobFile; 31 | import com.sap.refapps.objectstore.service.ObjectStoreService; 32 | import com.sap.refapps.objectstore.util.ObjectStoreUtil; 33 | 34 | @RestController 35 | @RequestMapping("/objectstorage.svc/api/v1") 36 | public class ObjectstoreController { 37 | 38 | private ObjectStoreService objectStoreService; 39 | private static Logger logger = LoggerFactory.getLogger(ObjectstoreController.class); 40 | 41 | @Autowired 42 | public ObjectstoreController(final ObjectStoreService objectStoreService) { 43 | this.objectStoreService = objectStoreService; 44 | } 45 | 46 | /** 47 | * @return list of blobfiles 48 | * Function to get the list of objects in the objectStore. 49 | */ 50 | @GetMapping("/storage") 51 | @ResponseBody 52 | public ResponseEntity> listFiles() { 53 | 54 | List blobFiles = this.objectStoreService.listObjects(); 55 | return new ResponseEntity<>(blobFiles, HttpStatus.OK); 56 | } 57 | 58 | /** 59 | * @param request 60 | * @return Message indicating if the file has been uploaded 61 | * Function to upload objects to objectStore. 62 | */ 63 | @PostMapping("/storage") 64 | public ResponseEntity uploadFile(HttpServletRequest request) throws IOException, FileUploadException { 65 | 66 | byte[] byteArray = null; 67 | String message = ""; 68 | Optional fileItemStream = Optional.empty(); 69 | 70 | var isMultipart = ServletFileUpload.isMultipartContent(request); 71 | 72 | if(isMultipart) { 73 | var upload = new ServletFileUpload(); 74 | FileItemIterator fileItemIterator = upload.getItemIterator(request); 75 | 76 | while(fileItemIterator.hasNext()) { 77 | fileItemStream = Optional.of(fileItemIterator.next()); 78 | InputStream inputStream = fileItemStream.get().openStream(); 79 | byteArray = ByteStreams.toByteArray(inputStream); 80 | if(!fileItemStream.get().isFormField()) { 81 | final String contentType = fileItemStream.get().getContentType(); 82 | message = objectStoreService.uploadFile(byteArray, fileItemStream.get().getName(), contentType); 83 | } 84 | } 85 | } 86 | return new ResponseEntity<>(message, HttpStatus.ACCEPTED); 87 | } 88 | 89 | /** 90 | * @param fileName 91 | * @return inputStream containing the file 92 | * Function to get a particular objects from objectStore. 93 | */ 94 | @GetMapping(value = "/storage/{name:.*}") 95 | public ResponseEntity getFile(@PathVariable(value = "name") String fileName) { 96 | 97 | if (fileName != null) { 98 | var respHeaders = new HttpHeaders(); 99 | 100 | if (this.objectStoreService.isBlobExist(fileName)) { 101 | respHeaders.setContentDispositionFormData("attachment", fileName); 102 | var inputStreamResource = new InputStreamResource(this.objectStoreService.getFile(fileName)); 103 | return new ResponseEntity(inputStreamResource, respHeaders, HttpStatus.OK); 104 | } else { 105 | return errorMessage(fileName + ObjectStoreUtil.FILE_DOESNOT_EXIST, HttpStatus.NOT_FOUND); 106 | } 107 | } 108 | 109 | // Default to 200, when input is missing 110 | return new ResponseEntity(HttpStatus.OK); 111 | } 112 | 113 | /** 114 | * @param fileName 115 | * @return Message indicating if the file has been deleted 116 | * Function to delete an object 117 | */ 118 | @DeleteMapping("/storage/{name}") 119 | public ResponseEntity deleteFile(@PathVariable(value = "name") String fileName) { 120 | var msg = ObjectStoreUtil.CANNOT_DELETE_NULL; 121 | if (fileName != null) { 122 | if (this.objectStoreService.isBlobExist(fileName)) { 123 | if (this.objectStoreService.deleteFile(fileName)) { 124 | msg = fileName + ObjectStoreUtil.DELETE_SUCCESSFUL; 125 | } else { 126 | msg = ObjectStoreUtil.DELETE_FAILED + fileName; 127 | return new ResponseEntity<>(msg, HttpStatus.INTERNAL_SERVER_ERROR); 128 | } 129 | } else { 130 | msg = fileName + ObjectStoreUtil.FILE_DOESNOT_EXIST; 131 | return errorMessage(msg, HttpStatus.NOT_FOUND); 132 | } 133 | 134 | } 135 | 136 | return new ResponseEntity<>(msg, HttpStatus.OK); 137 | } 138 | 139 | /** 140 | * @param message 141 | * @param status 142 | * @return ResponseEntity with HTTP status,headers and body 143 | * helper function to form the responseEntity 144 | */ 145 | private static ResponseEntity errorMessage(String message, HttpStatus status) { 146 | var headers = new HttpHeaders(); 147 | headers.setContentType(org.springframework.http.MediaType.TEXT_PLAIN); 148 | 149 | return ResponseEntity.status(status).headers(headers).body(message); 150 | } 151 | 152 | } 153 | -------------------------------------------------------------------------------- /src/main/java/com/sap/refapps/objectstore/model/BlobFile.java: -------------------------------------------------------------------------------- 1 | package com.sap.refapps.objectstore.model; 2 | 3 | import java.util.Map; 4 | 5 | /** 6 | * Model class to store the properties of a BLOB file. 7 | * 8 | */ 9 | public class BlobFile { 10 | 11 | private String etag; 12 | private String bucket; 13 | private String name; 14 | private String url; 15 | private String lastModified; 16 | private String size; 17 | private String contentType; 18 | 19 | private Map userMetadata; 20 | 21 | public BlobFile() { 22 | } 23 | 24 | public BlobFile(final String name){ 25 | this.name = name; 26 | } 27 | 28 | public BlobFile(final String etag, final String name, final String url, final String lastModified, final String size, final String contenType){ 29 | this.etag = etag; 30 | this.name = name; 31 | this.url = url; 32 | this.size = size; 33 | this.lastModified = lastModified; 34 | this.contentType = contenType; 35 | } 36 | 37 | public BlobFile(final String etag, final String bucket, final String name, final String url, final String size, final String lastModified, 38 | final String contenType, final Map userMetadata) { 39 | this.etag = etag; 40 | this.bucket = bucket; 41 | this.name = name; 42 | this.url = url; 43 | this.size = size; 44 | this.lastModified = lastModified; 45 | this.contentType = contenType; 46 | this.userMetadata = userMetadata; 47 | } 48 | 49 | public Map getUserMetadata() { 50 | return userMetadata; 51 | } 52 | 53 | public String getContentType(){ 54 | return contentType; 55 | } 56 | 57 | public String getLastModified() { 58 | return lastModified; 59 | } 60 | 61 | public String getSize() { 62 | return size; 63 | } 64 | 65 | public String getEtag() { 66 | return etag; 67 | } 68 | 69 | public String getBucket() { 70 | return bucket; 71 | } 72 | 73 | public String getName() { 74 | return name; 75 | } 76 | 77 | public String getUrl() { 78 | return url; 79 | } 80 | 81 | } 82 | -------------------------------------------------------------------------------- /src/main/java/com/sap/refapps/objectstore/repository/ObjectStoreRepository.java: -------------------------------------------------------------------------------- 1 | package com.sap.refapps.objectstore.repository; 2 | 3 | import java.io.IOException; 4 | import java.io.InputStream; 5 | import java.util.ArrayList; 6 | import java.util.HashMap; 7 | import java.util.Iterator; 8 | import java.util.List; 9 | import java.util.Map; 10 | 11 | import org.jclouds.blobstore.BlobStore; 12 | import org.jclouds.blobstore.BlobStoreContext; 13 | import org.jclouds.blobstore.domain.Blob; 14 | import org.jclouds.blobstore.domain.PageSet; 15 | import org.jclouds.blobstore.domain.StorageMetadata; 16 | import org.jclouds.io.Payload; 17 | import org.jclouds.io.payloads.ByteArrayPayload; 18 | 19 | import org.slf4j.Logger; 20 | import org.slf4j.LoggerFactory; 21 | 22 | import org.springframework.stereotype.Repository; 23 | 24 | import com.sap.refapps.objectstore.model.BlobFile; 25 | import com.sap.refapps.objectstore.util.ObjectStoreUtil; 26 | 27 | @Repository 28 | public class ObjectStoreRepository { 29 | 30 | private BlobStoreContext context; 31 | private BlobStore blobStore; 32 | 33 | private static Logger logger = LoggerFactory.getLogger(ObjectStoreRepository.class); 34 | 35 | public BlobStoreContext getContext() { 36 | return context; 37 | } 38 | 39 | public void setContext(BlobStoreContext context) { 40 | this.context = context; 41 | } 42 | 43 | /** 44 | * @param bucketName 45 | * @param data 46 | * @param fileName 47 | * @return message 48 | */ 49 | public String uploadFile(String bucketName, byte[] bytes, String fileName, String contentType) { 50 | 51 | String message = null; 52 | 53 | try { 54 | // getting blob store 55 | blobStore = getContext().getBlobStore(); 56 | 57 | // creating payload 58 | Payload payload = new ByteArrayPayload(bytes); 59 | 60 | // adding user metadata to the blob 61 | Map userMetadata = new HashMap(); 62 | userMetadata.put("description", "sample content"); 63 | 64 | // creating Blob 65 | Blob blob = blobStore.blobBuilder(fileName) 66 | .payload(payload) 67 | .contentType(contentType) 68 | .userMetadata(userMetadata) 69 | .build(); 70 | 71 | // multipart issue: (https://issues.apache.org/jira/browse/JCLOUDS-1064). 72 | blobStore.putBlob(bucketName, blob); 73 | message = fileName + ObjectStoreUtil.UPLOAD_SUCCESSFUL; 74 | 75 | } finally { 76 | getContext().close(); 77 | } 78 | 79 | return message; 80 | } 81 | 82 | /** 83 | * @param bucketName 84 | * @return List 85 | */ 86 | public List listFiles(String bucketName) { 87 | 88 | List files = new ArrayList<>(); 89 | PageSet list; 90 | 91 | try { 92 | //getting blobstore 93 | blobStore = getContext().getBlobStore(); 94 | 95 | //List all files from the bucket 96 | list = blobStore.list(bucketName); 97 | 98 | if(list != null) { 99 | // Iterate and form the list to be returned 100 | for (Iterator it = list.iterator(); it.hasNext(); ) { 101 | StorageMetadata storageMetadata = it.next(); 102 | Blob blob = blobStore.getBlob(bucketName, storageMetadata.getName()); 103 | files.add(ObjectStoreUtil.createBlobFile(blob)); 104 | } 105 | } 106 | } finally { 107 | getContext().close(); 108 | } 109 | return files; 110 | } 111 | 112 | /** 113 | * @param bucketName 114 | * @param fileName 115 | * @return InputStream 116 | */ 117 | public InputStream downloadFile(String bucketName, String fileName) { 118 | 119 | InputStream inputStream = null; 120 | try { 121 | //getting blobstore 122 | blobStore = getContext().getBlobStore(); 123 | 124 | // getting blob 125 | Blob blob = blobStore.getBlob(bucketName, fileName); 126 | 127 | inputStream = blob.getPayload().openStream(); 128 | logger.info(fileName + ObjectStoreUtil.DOWNLOAD_SUCCESSFUL); 129 | 130 | } catch(IOException e) { 131 | logger.error(ObjectStoreUtil.DOWNLOAD_FAILED + fileName + e); 132 | 133 | } finally { 134 | getContext().close(); 135 | } 136 | 137 | return inputStream; 138 | } 139 | 140 | /** 141 | * @param bucketName 142 | * @param fileName 143 | * @return true/false if the blobfile has been deleted 144 | */ 145 | public boolean deleteFile(String bucketName, String fileName) { 146 | 147 | boolean isBlobRemoved = false; 148 | try { 149 | //getting blobstore 150 | blobStore = getContext().getBlobStore(); 151 | //removing blob 152 | blobStore.removeBlob(bucketName,fileName); 153 | 154 | if(!isBlobExist(bucketName, fileName)) { 155 | isBlobRemoved = true; 156 | logger.info(fileName + ObjectStoreUtil.DELETE_SUCCESSFUL); 157 | } 158 | } finally { 159 | getContext().close(); 160 | } 161 | 162 | return isBlobRemoved; 163 | } 164 | 165 | public boolean isBlobExist(String bucketName,String fileName) { 166 | 167 | boolean isExist = false; 168 | try { 169 | //getting blobstore 170 | blobStore = getContext().getBlobStore(); 171 | isExist = blobStore.blobExists(bucketName, fileName); 172 | } finally { 173 | getContext().close(); 174 | } 175 | return isExist; 176 | } 177 | 178 | } 179 | -------------------------------------------------------------------------------- /src/main/java/com/sap/refapps/objectstore/service/AWSObjectStoreService.java: -------------------------------------------------------------------------------- 1 | package com.sap.refapps.objectstore.service; 2 | 3 | import java.io.InputStream; 4 | import java.util.List; 5 | 6 | import org.slf4j.Logger; 7 | import org.slf4j.LoggerFactory; 8 | 9 | import org.springframework.beans.factory.annotation.Autowired; 10 | import org.springframework.context.annotation.Profile; 11 | import org.springframework.stereotype.Service; 12 | 13 | import com.sap.refapps.objectstore.config.AmazonWebServiceConfiguration; 14 | import com.sap.refapps.objectstore.model.BlobFile; 15 | import com.sap.refapps.objectstore.repository.ObjectStoreRepository; 16 | 17 | @Profile("cloud-aws") 18 | @Service 19 | public class AWSObjectStoreService implements ObjectStoreService { 20 | 21 | private final AmazonWebServiceConfiguration awsConfig; 22 | private final ObjectStoreRepository repository; 23 | private static Logger logger = LoggerFactory.getLogger(AWSObjectStoreService.class); 24 | 25 | @Autowired 26 | public AWSObjectStoreService(final AmazonWebServiceConfiguration awsConfig, ObjectStoreRepository repository) { 27 | this.awsConfig = awsConfig; 28 | this.repository = repository; 29 | } 30 | 31 | @Override 32 | public String uploadFile(byte[] bytes, String fileName, String contentType) { 33 | repository.setContext(awsConfig.getBlobStoreContext()); 34 | logger.info("Upload started"); 35 | var message = repository.uploadFile(awsConfig.getBucket(), bytes, fileName, contentType); 36 | logger.info("upload completed"); 37 | return message; 38 | } 39 | 40 | public List listObjects() { 41 | repository.setContext(awsConfig.getBlobStoreContext()); 42 | List files = repository.listFiles(awsConfig.getBucket()); 43 | return files; 44 | } 45 | 46 | @Override 47 | public InputStream getFile(String fileName) { 48 | repository.setContext(awsConfig.getBlobStoreContext()); 49 | var inputStream = repository.downloadFile(awsConfig.getBucket(), fileName); 50 | return inputStream; 51 | } 52 | 53 | @Override 54 | public boolean deleteFile(String fileName) { 55 | repository.setContext(awsConfig.getBlobStoreContext()); 56 | var status = repository.deleteFile(awsConfig.getBucket(), fileName); 57 | return status; 58 | 59 | } 60 | 61 | @Override 62 | public boolean isBlobExist(String fileName) { 63 | repository.setContext(awsConfig.getBlobStoreContext()); 64 | var status = repository.isBlobExist(awsConfig.getBucket(), fileName); 65 | return status; 66 | } 67 | } 68 | -------------------------------------------------------------------------------- /src/main/java/com/sap/refapps/objectstore/service/AzureObjectStoreService.java: -------------------------------------------------------------------------------- 1 | package com.sap.refapps.objectstore.service; 2 | 3 | import java.io.InputStream; 4 | import java.util.List; 5 | 6 | import org.slf4j.Logger; 7 | import org.slf4j.LoggerFactory; 8 | import org.springframework.beans.factory.annotation.Autowired; 9 | import org.springframework.context.annotation.Profile; 10 | import org.springframework.stereotype.Service; 11 | 12 | import com.sap.refapps.objectstore.config.AzureStorageConfiguration; 13 | import com.sap.refapps.objectstore.model.BlobFile; 14 | import com.sap.refapps.objectstore.repository.ObjectStoreRepository; 15 | 16 | @Profile("cloud-azure") 17 | @Service 18 | public class AzureObjectStoreService implements ObjectStoreService { 19 | 20 | private final AzureStorageConfiguration azureConfig; 21 | private final ObjectStoreRepository repository; 22 | private static Logger logger = LoggerFactory.getLogger(AzureObjectStoreService.class); 23 | 24 | @Autowired 25 | public AzureObjectStoreService(final AzureStorageConfiguration azureConfig, ObjectStoreRepository repository) { 26 | this.azureConfig = azureConfig; 27 | this.repository = repository; 28 | } 29 | 30 | @Override 31 | public String uploadFile(byte[] bytes, String fileName, String contentType) { 32 | repository.setContext(azureConfig.getBlobStoreContext()); 33 | logger.info("Upload started"); 34 | var message = repository.uploadFile(azureConfig.getContainerName(), bytes, fileName, contentType); 35 | logger.info("Upload completed"); 36 | 37 | return message; 38 | } 39 | 40 | public List listObjects() { 41 | repository.setContext(azureConfig.getBlobStoreContext()); 42 | logger.info("Retrieving objects from container"); 43 | List files = repository.listFiles(azureConfig.getContainerName()); 44 | logger.info("Retrieval of objects completed"); 45 | 46 | return files; 47 | } 48 | 49 | @Override 50 | public InputStream getFile(String fileName) { 51 | repository.setContext(azureConfig.getBlobStoreContext()); 52 | var inputStream = repository.downloadFile(azureConfig.getContainerName(), fileName); 53 | 54 | return inputStream; 55 | } 56 | 57 | @Override 58 | public boolean deleteFile(String fileName) { 59 | repository.setContext(azureConfig.getBlobStoreContext()); 60 | logger.info("Deletion started"); 61 | var status = repository.deleteFile(azureConfig.getContainerName(), fileName); 62 | logger.info("Deletion completed"); 63 | 64 | return status; 65 | 66 | } 67 | 68 | @Override 69 | public boolean isBlobExist(String fileName) { 70 | repository.setContext(azureConfig.getBlobStoreContext()); 71 | var status = repository.isBlobExist(azureConfig.getContainerName(), fileName); 72 | 73 | return status; 74 | } 75 | 76 | } -------------------------------------------------------------------------------- /src/main/java/com/sap/refapps/objectstore/service/GCPObjectStoreService.java: -------------------------------------------------------------------------------- 1 | package com.sap.refapps.objectstore.service; 2 | 3 | import java.io.InputStream; 4 | import java.util.List; 5 | 6 | import org.slf4j.Logger; 7 | import org.slf4j.LoggerFactory; 8 | 9 | import org.springframework.beans.factory.annotation.Autowired; 10 | import org.springframework.context.annotation.Profile; 11 | import org.springframework.stereotype.Service; 12 | 13 | import com.sap.refapps.objectstore.config.GoogleCloudPlatformConfiguration; 14 | import com.sap.refapps.objectstore.model.BlobFile; 15 | import com.sap.refapps.objectstore.repository.ObjectStoreRepository; 16 | 17 | @Profile("cloud-gcp") 18 | @Service 19 | public class GCPObjectStoreService implements ObjectStoreService { 20 | 21 | private final GoogleCloudPlatformConfiguration gcpConfig; 22 | private final ObjectStoreRepository repository; 23 | private static Logger logger = LoggerFactory.getLogger(GCPObjectStoreService.class); 24 | 25 | @Autowired 26 | public GCPObjectStoreService(final GoogleCloudPlatformConfiguration gcpConfig, final ObjectStoreRepository repository) { 27 | this.gcpConfig = gcpConfig; 28 | this.repository = repository; 29 | } 30 | 31 | @Override 32 | public String uploadFile(byte[] bytes, String fileName, String contentType) { 33 | repository.setContext(gcpConfig.getBlobStoreContext()); 34 | logger.info("Upload started"); 35 | var message = repository.uploadFile(gcpConfig.getBucket(), bytes, fileName, contentType); 36 | logger.info("upload completed"); 37 | return message; 38 | } 39 | 40 | public List listObjects() { 41 | repository.setContext(gcpConfig.getBlobStoreContext()); 42 | List listBlobs = repository.listFiles(gcpConfig.getBucket()); 43 | return listBlobs; 44 | } 45 | 46 | @Override 47 | public InputStream getFile(String fileName) { 48 | repository.setContext(gcpConfig.getBlobStoreContext()); 49 | var inputStream = repository.downloadFile(gcpConfig.getBucket(), fileName); 50 | return inputStream; 51 | } 52 | 53 | @Override 54 | public boolean deleteFile(String fileName) { 55 | repository.setContext(gcpConfig.getBlobStoreContext()); 56 | var blobRemove = repository.deleteFile(gcpConfig.getBucket(), fileName); 57 | return blobRemove; 58 | 59 | } 60 | 61 | @Override 62 | public boolean isBlobExist(String fileName) { 63 | repository.setContext(gcpConfig.getBlobStoreContext()); 64 | var blobExist = repository.isBlobExist(gcpConfig.getBucket(), fileName); 65 | return blobExist; 66 | } 67 | 68 | } 69 | -------------------------------------------------------------------------------- /src/main/java/com/sap/refapps/objectstore/service/ObjectStoreService.java: -------------------------------------------------------------------------------- 1 | package com.sap.refapps.objectstore.service; 2 | 3 | import java.io.InputStream; 4 | import java.util.List; 5 | 6 | import org.springframework.stereotype.Service; 7 | 8 | import com.sap.refapps.objectstore.model.BlobFile; 9 | 10 | @Service 11 | public interface ObjectStoreService { 12 | 13 | /** 14 | * @param bytes 15 | * @param name 16 | * @param contentType 17 | * @return 18 | */ 19 | public String uploadFile(byte[] bytes, String name, String contentType); 20 | 21 | /** 22 | * @param blobFile 23 | * @return true/false if file has been deleted 24 | */ 25 | public boolean deleteFile(String fileName); 26 | 27 | /** 28 | * @param file 29 | * @return InputStream 30 | */ 31 | public InputStream getFile(String fileName); 32 | 33 | /** 34 | * @return list of blobFile 35 | */ 36 | public List listObjects(); 37 | 38 | /** 39 | * @param name 40 | * @return 41 | */ 42 | public boolean isBlobExist(String name); 43 | } 44 | -------------------------------------------------------------------------------- /src/main/java/com/sap/refapps/objectstore/util/CloudProviders.java: -------------------------------------------------------------------------------- 1 | package com.sap.refapps.objectstore.util; 2 | 3 | /** 4 | * This enum class stores the different Objectstore plans,providers available in SCP 5 | * across landscapes. 6 | * 7 | */ 8 | public enum CloudProviders { 9 | 10 | PROVIDER_AWS ("aws-s3"), 11 | PROVIDER_GCP ("google-cloud-storage"), 12 | PROVIDER_AZURE("azureblob"), 13 | 14 | PROFILE_AWS ("cloud-aws"), 15 | PROFILE_GCP ("cloud-gcp"), 16 | PROFILE_AZURE("cloud-azure"), 17 | 18 | PlAN_AWS ("s3-standard"), 19 | PLAN_GCP ("gcs-standard"), 20 | PLAN_AZURE("azure-standard"); 21 | 22 | private final String providerName; 23 | 24 | private CloudProviders(final String providerName){ 25 | this.providerName = providerName; 26 | } 27 | 28 | public String toString() { 29 | return this.providerName; 30 | } 31 | } 32 | -------------------------------------------------------------------------------- /src/main/java/com/sap/refapps/objectstore/util/EnvironmentUtil.java: -------------------------------------------------------------------------------- 1 | package com.sap.refapps.objectstore.util; 2 | 3 | import java.io.IOException; 4 | import java.util.Optional; 5 | 6 | import org.slf4j.Logger; 7 | import org.slf4j.LoggerFactory; 8 | 9 | import com.fasterxml.jackson.databind.JsonNode; 10 | import com.fasterxml.jackson.databind.ObjectMapper; 11 | 12 | public class EnvironmentUtil { 13 | 14 | private static final Logger logger = LoggerFactory.getLogger(EnvironmentUtil.class); 15 | 16 | private static String activeProfile; 17 | 18 | private static final String VCAP_SERVICE = "VCAP_SERVICES"; 19 | private static final String OBJECTSTORE = "objectstore"; 20 | private static final String PLAN = "plan"; 21 | 22 | /** 23 | * This method is used to return the profile name to 24 | * activate based on service plans. 25 | * 26 | * @return profile name 27 | */ 28 | public static String getActiveProfile(){ 29 | final String servicePlan = getServicePlan(); 30 | if(servicePlan.equals(CloudProviders.PlAN_AWS.toString())) { 31 | activeProfile = CloudProviders.PROFILE_AWS.toString(); 32 | } 33 | else if (servicePlan.equals(CloudProviders.PLAN_GCP.toString())) { 34 | activeProfile = CloudProviders.PROFILE_GCP.toString(); 35 | } 36 | else if (servicePlan.equals(CloudProviders.PLAN_AZURE.toString())) { 37 | activeProfile = CloudProviders.PROFILE_AZURE.toString(); 38 | } 39 | 40 | return activeProfile; 41 | } 42 | 43 | /** 44 | * This method is used to parse the service plan name from VCAP_SERVICES 45 | * 46 | * @return service plan name 47 | */ 48 | private static String getServicePlan(){ 49 | Optional servicePlan = Optional.empty(); 50 | final String jsonString = System.getenv(VCAP_SERVICE); 51 | if(jsonString != null){ 52 | try { 53 | ObjectMapper mapper = new ObjectMapper(); 54 | JsonNode root = mapper.readTree(jsonString); 55 | JsonNode objectstoreNode = root.path(OBJECTSTORE); 56 | 57 | for (JsonNode node : objectstoreNode) { 58 | servicePlan = Optional.of(node.path(PLAN).asText()); 59 | } 60 | 61 | } catch (IOException e) { 62 | logger.error("Exception occurred: " + e); 63 | } 64 | } 65 | return servicePlan.get(); 66 | } 67 | 68 | } 69 | -------------------------------------------------------------------------------- /src/main/java/com/sap/refapps/objectstore/util/ObjectStoreUtil.java: -------------------------------------------------------------------------------- 1 | package com.sap.refapps.objectstore.util; 2 | 3 | import java.text.DecimalFormat; 4 | import java.util.Date; 5 | 6 | import org.jclouds.blobstore.domain.Blob; 7 | 8 | import com.sap.refapps.objectstore.model.BlobFile; 9 | 10 | public class ObjectStoreUtil { 11 | 12 | private static final String BYTE = "B"; 13 | private static final String KILLOBYTE = "KB"; 14 | private static final String MEGABYTE = "MB"; 15 | private static final String GIGABYTE = "GB"; 16 | private static final String TERABYTE = "TB"; 17 | private static final String DECIMAL_FORMAT_PATTERN = "#,##0.#"; 18 | 19 | public static final String FILE_ALREADY_EXIST = " already exists in the container."; 20 | public static final String FILE_DOESNOT_EXIST = " does not exist in the container"; 21 | 22 | public static final String UPLOAD_SUCCESSFUL = " is successfully uploaded."; 23 | public static final String DOWNLOAD_SUCCESSFUL = " is successfully downloaded."; 24 | public static final String DELETE_SUCCESSFUL = " is successfully deleted."; 25 | 26 | public static final String UPLOAD_FAILED = "Error occured while uploading the object: "; 27 | public static final String DOWNLOAD_FAILED = "Error occured while downloading the object: "; 28 | public static final String DELETE_FAILED = "Error occured while deleting the object: "; 29 | 30 | public static final String CANNOT_DELETE_NULL = "Could not delete a null object."; 31 | public static final String FEATURE_NOT_SUPPORTED_GCP = "The BlobStore list api for GCP is only supported in Jclouds 2.2.0 which is yet to be released."; 32 | 33 | /** 34 | * @param size 35 | * @return decimalformat of size of file along with unit 36 | */ 37 | private static String readableFileSize(final long size) { 38 | if (size <= 0) 39 | return "0"; 40 | final String[] units = new String[] { BYTE, KILLOBYTE, MEGABYTE, GIGABYTE, TERABYTE }; 41 | int digitGroups = (int) (Math.log10(size) / Math.log10(1024)); 42 | return new DecimalFormat(DECIMAL_FORMAT_PATTERN).format(size / Math.pow(1024, digitGroups)) + " " 43 | + units[digitGroups]; 44 | } 45 | 46 | /** 47 | * @param fileName 48 | * @return name along with timestamp. 49 | */ 50 | public static String generateFileName(final String fileName) { 51 | return new Date().getTime() + "-" + fileName.replace(" ", "_"); 52 | } 53 | 54 | /** 55 | * @param blob 56 | * @return blobFile 57 | */ 58 | public static BlobFile createBlobFile(final Blob blob) { 59 | return new BlobFile( 60 | blob.getMetadata().getETag(), 61 | blob.getMetadata().getContainer(), 62 | blob.getMetadata().getName(), 63 | blob.getMetadata().getUri().toString(), 64 | readableFileSize(blob.getMetadata().getSize()), 65 | blob.getMetadata().getLastModified().toString(), 66 | blob.getPayload().getContentMetadata().getContentType(), 67 | blob.getMetadata().getUserMetadata() 68 | ); 69 | 70 | } 71 | 72 | } 73 | -------------------------------------------------------------------------------- /src/main/resources/Banner.txt: -------------------------------------------------------------------------------- 1 | ___ _ _ _ ____ _ ____ _ 2 | / _ \ | |__ (_) ___ ___ | |_ / ___| | |_ ___ _ __ ___ / ___| __ _ _ __ ___ _ __ | | ___ 3 | | | | | | '_ \ | | / _ \ / __| | __| \___ \ | __| / _ \ | '__| / _ \ \___ \ / _` | | '_ ` _ \ | '_ \ | | / _ \ 4 | | |_| | | |_) | | | | __/ | (__ | |_ ___) | | |_ | (_) | | | | __/ ___) | | (_| | | | | | | | | |_) | | | | __/ 5 | \___/ |_.__/ _/ | \___| \___| \__| |____/ \__| \___/ |_| \___| |____/ \__,_| |_| |_| |_| | .__/ |_| \___| 6 | |__/ |_| -------------------------------------------------------------------------------- /src/main/resources/application.properties: -------------------------------------------------------------------------------- 1 | #server port 2 | server.port=5555 3 | 4 | #spring.servlet.multipart.max-file-size=2050MB 5 | #spring.servlet.multipart.maxRequestSize=2050MB 6 | spring.servlet.multipart.max-file-size=-1 7 | spring.servlet.multipart.maxRequestSize=-1 8 | spring.servlet.multipart.enabled=false --------------------------------------------------------------------------------