├── .github ├── dco.yml ├── dependabot.yml └── workflows │ └── continuous-integration-build.yml ├── .gitignore ├── CONTRIBUTING.adoc ├── LICENSE.txt ├── LICENSE.writing.txt ├── README.adoc ├── complete ├── .mvn │ └── wrapper │ │ ├── maven-wrapper.jar │ │ └── maven-wrapper.properties ├── build.gradle ├── gradle │ └── wrapper │ │ ├── gradle-wrapper.jar │ │ └── gradle-wrapper.properties ├── gradlew ├── gradlew.bat ├── mvnw ├── mvnw.cmd ├── pom.xml ├── settings.gradle └── src │ ├── main │ ├── java │ │ └── com │ │ │ └── example │ │ │ └── uploadingfiles │ │ │ ├── FileUploadController.java │ │ │ ├── UploadingFilesApplication.java │ │ │ └── storage │ │ │ ├── FileSystemStorageService.java │ │ │ ├── StorageException.java │ │ │ ├── StorageFileNotFoundException.java │ │ │ ├── StorageProperties.java │ │ │ └── StorageService.java │ └── resources │ │ ├── application.properties │ │ └── templates │ │ └── uploadForm.html │ └── test │ ├── java │ └── com │ │ └── example │ │ └── uploadingfiles │ │ ├── FileUploadIntegrationTests.java │ │ ├── FileUploadTests.java │ │ └── storage │ │ └── FileSystemStorageServiceTests.java │ └── resources │ └── com │ └── example │ └── uploadingfiles │ └── testupload.txt └── initial ├── .mvn └── wrapper │ ├── maven-wrapper.jar │ └── maven-wrapper.properties ├── build.gradle ├── gradle └── wrapper │ ├── gradle-wrapper.jar │ └── gradle-wrapper.properties ├── gradlew ├── gradlew.bat ├── mvnw ├── mvnw.cmd ├── pom.xml ├── settings.gradle └── src └── main ├── java └── com │ └── example │ └── uploadingfiles │ ├── UploadingFilesApplication.java │ └── storage │ ├── FileSystemStorageService.java │ ├── StorageException.java │ ├── StorageFileNotFoundException.java │ ├── StorageProperties.java │ └── StorageService.java └── resources └── application.properties /.github/dco.yml: -------------------------------------------------------------------------------- 1 | require: 2 | members: false 3 | -------------------------------------------------------------------------------- /.github/dependabot.yml: -------------------------------------------------------------------------------- 1 | version: 2 2 | updates: 3 | 4 | - package-ecosystem: "maven" 5 | directories: 6 | - "/initial" 7 | - "/complete" 8 | ignore: 9 | - dependency-name: "*" 10 | update-types: ["version-update:semver-patch"] 11 | schedule: 12 | interval: "monthly" 13 | target-branch: "main" 14 | groups: 15 | guide-dependencies-maven: 16 | patterns: 17 | - "*" 18 | 19 | - package-ecosystem: "gradle" 20 | directories: 21 | - "/initial" 22 | - "/complete" 23 | ignore: 24 | - dependency-name: "*" 25 | update-types: ["version-update:semver-patch"] 26 | schedule: 27 | interval: "monthly" 28 | target-branch: "main" 29 | groups: 30 | guide-dependencies-gradle: 31 | patterns: 32 | - "*" 33 | -------------------------------------------------------------------------------- /.github/workflows/continuous-integration-build.yml: -------------------------------------------------------------------------------- 1 | name: CI Build 2 | 3 | on: 4 | push: 5 | branches: 6 | - main 7 | pull_request: 8 | branches: 9 | - main 10 | 11 | jobs: 12 | build: 13 | uses: spring-guides/getting-started-macros/.github/workflows/build_initial_complete_maven_gradle.yml@main 14 | -------------------------------------------------------------------------------- /.gitignore: -------------------------------------------------------------------------------- 1 | # Operating System Files 2 | 3 | *.DS_Store 4 | Thumbs.db 5 | 6 | # Build Files # 7 | 8 | bin 9 | target 10 | build/ 11 | .gradle 12 | 13 | # Eclipse Project Files # 14 | 15 | .classpath 16 | .project 17 | .settings 18 | 19 | # IntelliJ IDEA Files # 20 | 21 | *.iml 22 | *.ipr 23 | *.iws 24 | *.idea 25 | 26 | # Test files 27 | 28 | *-uploaded 29 | dependency-reduced-pom.xml 30 | README.html 31 | 32 | upload-dir 33 | -------------------------------------------------------------------------------- /CONTRIBUTING.adoc: -------------------------------------------------------------------------------- 1 | All commits must include a __Signed-off-by__ trailer at the end of each commit message to indicate that the contributor agrees to the Developer Certificate of Origin. 2 | For additional details, please refer to the blog post https://spring.io/blog/2025/01/06/hello-dco-goodbye-cla-simplifying-contributions-to-spring[Hello DCO, Goodbye CLA: Simplifying Contributions to Spring]. 3 | -------------------------------------------------------------------------------- /LICENSE.txt: -------------------------------------------------------------------------------- 1 | 2 | Apache License 3 | Version 2.0, January 2004 4 | https://www.apache.org/licenses/ 5 | 6 | TERMS AND CONDITIONS FOR USE, REPRODUCTION, AND DISTRIBUTION 7 | 8 | 1. Definitions. 9 | 10 | "License" shall mean the terms and conditions for use, reproduction, 11 | and distribution as defined by Sections 1 through 9 of this document. 12 | 13 | "Licensor" shall mean the copyright owner or entity authorized by 14 | the copyright owner that is granting the License. 15 | 16 | "Legal Entity" shall mean the union of the acting entity and all 17 | other entities that control, are controlled by, or are under common 18 | control with that entity. For the purposes of this definition, 19 | "control" means (i) the power, direct or indirect, to cause the 20 | direction or management of such entity, whether by contract or 21 | otherwise, or (ii) ownership of fifty percent (50%) or more of the 22 | outstanding shares, or (iii) beneficial ownership of such entity. 23 | 24 | "You" (or "Your") shall mean an individual or Legal Entity 25 | exercising permissions granted by this License. 26 | 27 | "Source" form shall mean the preferred form for making modifications, 28 | including but not limited to software source code, documentation 29 | source, and configuration files. 30 | 31 | "Object" form shall mean any form resulting from mechanical 32 | transformation or translation of a Source form, including but 33 | not limited to compiled object code, generated documentation, 34 | and conversions to other media types. 35 | 36 | "Work" shall mean the work of authorship, whether in Source or 37 | Object form, made available under the License, as indicated by a 38 | copyright notice that is included in or attached to the work 39 | (an example is provided in the Appendix below). 40 | 41 | "Derivative Works" shall mean any work, whether in Source or Object 42 | form, that is based on (or derived from) the Work and for which the 43 | editorial revisions, annotations, elaborations, or other modifications 44 | represent, as a whole, an original work of authorship. For the purposes 45 | of this License, Derivative Works shall not include works that remain 46 | separable from, or merely link (or bind by name) to the interfaces of, 47 | the Work and Derivative Works thereof. 48 | 49 | "Contribution" shall mean any work of authorship, including 50 | the original version of the Work and any modifications or additions 51 | to that Work or Derivative Works thereof, that is intentionally 52 | submitted to Licensor for inclusion in the Work by the copyright owner 53 | or by an individual or Legal Entity authorized to submit on behalf of 54 | the copyright owner. For the purposes of this definition, "submitted" 55 | means any form of electronic, verbal, or written communication sent 56 | to the Licensor or its representatives, including but not limited to 57 | communication on electronic mailing lists, source code control systems, 58 | and issue tracking systems that are managed by, or on behalf of, the 59 | Licensor for the purpose of discussing and improving the Work, but 60 | excluding communication that is conspicuously marked or otherwise 61 | designated in writing by the copyright owner as "Not a Contribution." 62 | 63 | "Contributor" shall mean Licensor and any individual or Legal Entity 64 | on behalf of whom a Contribution has been received by Licensor and 65 | subsequently incorporated within the Work. 66 | 67 | 2. Grant of Copyright License. Subject to the terms and conditions of 68 | this License, each Contributor hereby grants to You a perpetual, 69 | worldwide, non-exclusive, no-charge, royalty-free, irrevocable 70 | copyright license to reproduce, prepare Derivative Works of, 71 | publicly display, publicly perform, sublicense, and distribute the 72 | Work and such Derivative Works in Source or Object form. 73 | 74 | 3. Grant of Patent License. Subject to the terms and conditions of 75 | this License, each Contributor hereby grants to You a perpetual, 76 | worldwide, non-exclusive, no-charge, royalty-free, irrevocable 77 | (except as stated in this section) patent license to make, have made, 78 | use, offer to sell, sell, import, and otherwise transfer the Work, 79 | where such license applies only to those patent claims licensable 80 | by such Contributor that are necessarily infringed by their 81 | Contribution(s) alone or by combination of their Contribution(s) 82 | with the Work to which such Contribution(s) was submitted. If You 83 | institute patent litigation against any entity (including a 84 | cross-claim or counterclaim in a lawsuit) alleging that the Work 85 | or a Contribution incorporated within the Work constitutes direct 86 | or contributory patent infringement, then any patent licenses 87 | granted to You under this License for that Work shall terminate 88 | as of the date such litigation is filed. 89 | 90 | 4. Redistribution. You may reproduce and distribute copies of the 91 | Work or Derivative Works thereof in any medium, with or without 92 | modifications, and in Source or Object form, provided that You 93 | meet the following conditions: 94 | 95 | (a) You must give any other recipients of the Work or 96 | Derivative Works a copy of this License; and 97 | 98 | (b) You must cause any modified files to carry prominent notices 99 | stating that You changed the files; and 100 | 101 | (c) You must retain, in the Source form of any Derivative Works 102 | that You distribute, all copyright, patent, trademark, and 103 | attribution notices from the Source form of the Work, 104 | excluding those notices that do not pertain to any part of 105 | the Derivative Works; and 106 | 107 | (d) If the Work includes a "NOTICE" text file as part of its 108 | distribution, then any Derivative Works that You distribute must 109 | include a readable copy of the attribution notices contained 110 | within such NOTICE file, excluding those notices that do not 111 | pertain to any part of the Derivative Works, in at least one 112 | of the following places: within a NOTICE text file distributed 113 | as part of the Derivative Works; within the Source form or 114 | documentation, if provided along with the Derivative Works; or, 115 | within a display generated by the Derivative Works, if and 116 | wherever such third-party notices normally appear. The contents 117 | of the NOTICE file are for informational purposes only and 118 | do not modify the License. You may add Your own attribution 119 | notices within Derivative Works that You distribute, alongside 120 | or as an addendum to the NOTICE text from the Work, provided 121 | that such additional attribution notices cannot be construed 122 | as modifying the License. 123 | 124 | You may add Your own copyright statement to Your modifications and 125 | may provide additional or different license terms and conditions 126 | for use, reproduction, or distribution of Your modifications, or 127 | for any such Derivative Works as a whole, provided Your use, 128 | reproduction, and distribution of the Work otherwise complies with 129 | the conditions stated in this License. 130 | 131 | 5. Submission of Contributions. Unless You explicitly state otherwise, 132 | any Contribution intentionally submitted for inclusion in the Work 133 | by You to the Licensor shall be under the terms and conditions of 134 | this License, without any additional terms or conditions. 135 | Notwithstanding the above, nothing herein shall supersede or modify 136 | the terms of any separate license agreement you may have executed 137 | with Licensor regarding such Contributions. 138 | 139 | 6. Trademarks. This License does not grant permission to use the trade 140 | names, trademarks, service marks, or product names of the Licensor, 141 | except as required for reasonable and customary use in describing the 142 | origin of the Work and reproducing the content of the NOTICE file. 143 | 144 | 7. Disclaimer of Warranty. Unless required by applicable law or 145 | agreed to in writing, Licensor provides the Work (and each 146 | Contributor provides its Contributions) on an "AS IS" BASIS, 147 | WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or 148 | implied, including, without limitation, any warranties or conditions 149 | of TITLE, NON-INFRINGEMENT, MERCHANTABILITY, or FITNESS FOR A 150 | PARTICULAR PURPOSE. You are solely responsible for determining the 151 | appropriateness of using or redistributing the Work and assume any 152 | risks associated with Your exercise of permissions under this License. 153 | 154 | 8. Limitation of Liability. In no event and under no legal theory, 155 | whether in tort (including negligence), contract, or otherwise, 156 | unless required by applicable law (such as deliberate and grossly 157 | negligent acts) or agreed to in writing, shall any Contributor be 158 | liable to You for damages, including any direct, indirect, special, 159 | incidental, or consequential damages of any character arising as a 160 | result of this License or out of the use or inability to use the 161 | Work (including but not limited to damages for loss of goodwill, 162 | work stoppage, computer failure or malfunction, or any and all 163 | other commercial damages or losses), even if such Contributor 164 | has been advised of the possibility of such damages. 165 | 166 | 9. Accepting Warranty or Additional Liability. While redistributing 167 | the Work or Derivative Works thereof, You may choose to offer, 168 | and charge a fee for, acceptance of support, warranty, indemnity, 169 | or other liability obligations and/or rights consistent with this 170 | License. However, in accepting such obligations, You may act only 171 | on Your own behalf and on Your sole responsibility, not on behalf 172 | of any other Contributor, and only if You agree to indemnify, 173 | defend, and hold each Contributor harmless for any liability 174 | incurred by, or claims asserted against, such Contributor by reason 175 | of your accepting any such warranty or additional liability. 176 | 177 | END OF TERMS AND CONDITIONS 178 | 179 | APPENDIX: How to apply the Apache License to your work. 180 | 181 | To apply the Apache License to your work, attach the following 182 | boilerplate notice, with the fields enclosed by brackets "{}" 183 | replaced with your own identifying information. (Don't include 184 | the brackets!) The text should be enclosed in the appropriate 185 | comment syntax for the file format. We also recommend that a 186 | file or class name and description of purpose be included on the 187 | same "printed page" as the copyright notice for easier 188 | identification within third-party archives. 189 | 190 | Copyright {yyyy} {name of copyright owner} 191 | 192 | Licensed under the Apache License, Version 2.0 (the "License"); 193 | you may not use this file except in compliance with the License. 194 | You may obtain a copy of the License at 195 | 196 | https://www.apache.org/licenses/LICENSE-2.0 197 | 198 | Unless required by applicable law or agreed to in writing, software 199 | distributed under the License is distributed on an "AS IS" BASIS, 200 | WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. 201 | See the License for the specific language governing permissions and 202 | limitations under the License. 203 | -------------------------------------------------------------------------------- /LICENSE.writing.txt: -------------------------------------------------------------------------------- 1 | Except where otherwise noted, this work is licensed under https://creativecommons.org/licenses/by-nd/3.0/ 2 | -------------------------------------------------------------------------------- /README.adoc: -------------------------------------------------------------------------------- 1 | :toc: 2 | :icons: font 3 | :source-highlighter: prettify 4 | :project_id: gs-uploading-files 5 | 6 | This guide walks you through the process of creating a server application that can receive 7 | HTTP multi-part file uploads. 8 | 9 | == What You Will Build 10 | 11 | You will create a Spring Boot web application that accepts file uploads. You will also 12 | build a simple HTML interface to upload a test file. 13 | 14 | == What You Need 15 | 16 | include::https://raw.githubusercontent.com/spring-guides/getting-started-macros/main/prereq_editor_jdk_buildtools.adoc[] 17 | 18 | include::https://raw.githubusercontent.com/spring-guides/getting-started-macros/main/how_to_complete_this_guide.adoc[] 19 | 20 | [[scratch]] 21 | == Starting with Spring Initializr 22 | 23 | You can use this https://start.spring.io/#!type=maven-project&groupId=com.example&artifactId=uploading-files&name=uploading-files&description=Demo%20project%20for%20Spring%20Boot&packageName=com.example.uploading-files&dependencies=web,thymeleaf[pre-initialized project] and click Generate to download a ZIP file. This project is configured to fit the examples in this tutorial. 24 | 25 | To manually initialize the project: 26 | 27 | . Navigate to https://start.spring.io. 28 | This service pulls in all the dependencies you need for an application and does most of the setup for you. 29 | . Choose either Gradle or Maven and the language you want to use. This guide assumes that you chose Java. 30 | . Click *Dependencies* and select *Spring Web* and *Thymeleaf*. 31 | . Click *Generate*. 32 | . Download the resulting ZIP file, which is an archive of a web application that is configured with your choices. 33 | 34 | NOTE: If your IDE has the Spring Initializr integration, you can complete this process from your IDE. 35 | 36 | NOTE: You can also fork the project from Github and open it in your IDE or other editor. 37 | 38 | [[initial]] 39 | == Create an Application Class 40 | 41 | To start a Spring Boot MVC application, you first need a starter. In this sample, 42 | `spring-boot-starter-thymeleaf` and `spring-boot-starter-web` are already added as 43 | dependencies. To upload files with Servlet containers, you need to register a 44 | `MultipartConfigElement` class (which would be `` in web.xml). Thanks to 45 | Spring Boot, everything is auto-configured for you! 46 | 47 | All you need to get started with this application is the following 48 | `UploadingFilesApplication` class (from 49 | `src/main/java/com/example/uploadingfiles/UploadingFilesApplication.java`): 50 | 51 | ==== 52 | [source,java] 53 | ---- 54 | include::initial/src/main/java/com/example/uploadingfiles/UploadingFilesApplication.java[] 55 | ---- 56 | ==== 57 | 58 | As part of auto-configuring Spring MVC, Spring Boot will create a `MultipartConfigElement` 59 | bean and make itself ready for file uploads. 60 | 61 | == Create a File Upload Controller 62 | 63 | The initial application already contains a few classes to deal with storing and loading 64 | the uploaded files on disk. They are all located in the 65 | `com.example.uploadingfiles.storage` package. You will use those in your new 66 | `FileUploadController`. The following listing (from 67 | `src/main/java/com/example/uploadingfiles/FileUploadController.java`) shows the file 68 | upload controller: 69 | 70 | ==== 71 | [source,java] 72 | ---- 73 | include::complete/src/main/java/com/example/uploadingfiles/FileUploadController.java[] 74 | ---- 75 | ==== 76 | 77 | The `FileUploadController` class is annotated with `@Controller` so that Spring MVC can 78 | pick it up and look for routes. Each method is tagged with `@GetMapping` or `@PostMapping` 79 | to tie the path and the HTTP action to a particular controller action. 80 | 81 | In this case: 82 | 83 | * `GET /`: Looks up the current list of uploaded files from the `StorageService` and loads 84 | it into a Thymeleaf template. It calculates a link to the actual resource by using 85 | `MvcUriComponentsBuilder`. 86 | * `GET /files/{filename}`: Loads the resource (if it exists) and sends it to the browser 87 | to download by using a `Content-Disposition` response header. 88 | * `POST /`: Handles a multi-part message `file` and gives it to the `StorageService` for 89 | saving. 90 | 91 | NOTE: In a production scenario, you more likely would store the files in a temporary 92 | location, a database, or perhaps a NoSQL store (such as 93 | https://docs.mongodb.org/manual/core/gridfs[Mongo's GridFS]). It is best to NOT load up 94 | the file system of your application with content. 95 | 96 | You will need to provide a `StorageService` so that the controller can interact with a 97 | storage layer (such as a file system). The following listing (from 98 | `src/main/java/com/example/uploadingfiles/storage/StorageService.java`) shows that 99 | interface: 100 | 101 | ==== 102 | [source,java] 103 | ---- 104 | include::complete/src/main/java/com/example/uploadingfiles//storage/StorageService.java[] 105 | ---- 106 | ==== 107 | 108 | You also need four classes to support the storage service: 109 | 110 | ==== 111 | [source,java] 112 | ---- 113 | include::complete/src/main/java/com/example/uploadingfiles//storage/StorageProperties.java[] 114 | ---- 115 | ==== 116 | 117 | ==== 118 | [source,java] 119 | ---- 120 | include::complete/src/main/java/com/example/uploadingfiles//storage/StorageException.java[] 121 | ---- 122 | ==== 123 | 124 | ==== 125 | [source,java] 126 | ---- 127 | include::complete/src/main/java/com/example/uploadingfiles//storage/StorageFileNotFoundException.java[] 128 | ---- 129 | ==== 130 | 131 | ==== 132 | [source,java] 133 | ---- 134 | include::complete/src/main/java/com/example/uploadingfiles//storage/FileSystemStorageService.java[] 135 | ---- 136 | ==== 137 | 138 | == Creating an HTML Template 139 | 140 | The following Thymeleaf template (from `src/main/resources/templates/uploadForm.html`) 141 | shows an example of how to upload files and show what has been uploaded: 142 | 143 | ==== 144 | [source,xml] 145 | ---- 146 | include::complete/src/main/resources/templates/uploadForm.html[] 147 | ---- 148 | ==== 149 | 150 | This template has three parts: 151 | 152 | * An optional message at the top where Spring MVC writes a 153 | https://docs.spring.io/spring/docs/current/spring-framework-reference/htmlsingle/#mvc-flash-attributes[flash-scoped message]. 154 | * A form that lets the user upload files. 155 | * A list of files supplied from the backend. 156 | 157 | == Tuning File Upload Limits 158 | 159 | When configuring file uploads, it is often useful to set limits on the size of files. 160 | Imagine trying to handle a 5GB file upload! With Spring Boot, we can tune its 161 | auto-configured `MultipartConfigElement` with some property settings. 162 | 163 | Add the following properties to your existing properties settings (in 164 | `src/main/resources/application.properties`): 165 | 166 | ==== 167 | [source,java] 168 | ---- 169 | include::complete/src/main/resources/application.properties[] 170 | ---- 171 | ==== 172 | 173 | The multipart settings are constrained as follows: 174 | 175 | * `spring.servlet.multipart.max-file-size` is set to 128KB, meaning total file size cannot 176 | exceed 128KB. 177 | * `spring.servlet.multipart.max-request-size` is set to 128KB, meaning total request size for 178 | a `multipart/form-data` cannot exceed 128KB. 179 | 180 | == Update the Application 181 | 182 | You want a target folder to which to upload files, so you need to enhance the basic 183 | `UploadingFilesApplication` class that Spring Initializr created and add a Boot 184 | `CommandLineRunner` to delete and re-create that folder at startup. The following listing 185 | (from `src/main/java/com/example/uploadingfiles/UploadingFilesApplication.java`) shows how 186 | to do so: 187 | 188 | ==== 189 | [source,java] 190 | ---- 191 | include::complete/src/main/java/com/example/uploadingfiles/UploadingFilesApplication.java[] 192 | ---- 193 | ==== 194 | 195 | == Run the Application 196 | 197 | include::https://raw.githubusercontent.com/spring-guides/getting-started-macros/main/spring-boot-application-new-path.adoc[] 198 | 199 | include::https://raw.githubusercontent.com/spring-guides/getting-started-macros/main/build_an_executable_jar_subhead.adoc[] 200 | include::https://raw.githubusercontent.com/spring-guides/getting-started-macros/main/build_an_executable_jar_with_both.adoc[] 201 | 202 | That runs the server-side piece that receives file uploads. Logging output is displayed. 203 | The service should be up and running within a few seconds. 204 | 205 | With the server running, you need to open a browser and visit `http://localhost:8080/` to 206 | see the upload form. Pick a (small) file and press *Upload*. You should see the success 207 | page from the controller. If you choose a file that is too large, you will get an ugly 208 | error page. 209 | 210 | You should then see a line resembling the following in your browser window: 211 | 212 | "`You successfully uploaded !`" 213 | 214 | == Testing Your Application 215 | 216 | There are multiple ways to test this particular feature in our application. The following 217 | listing (from `src/test/java/com/example/uploadingfiles/FileUploadTests.java`) shows one 218 | example that uses `MockMvc` so that it does not require starting the servlet container: 219 | 220 | ==== 221 | [source,java] 222 | ---- 223 | include::complete/src/test/java/com/example/uploadingfiles/FileUploadTests.java[] 224 | ---- 225 | ==== 226 | 227 | In those tests, you use various mocks to set up the interactions with your controller and 228 | the `StorageService` but also with the Servlet container itself by using 229 | `MockMultipartFile`. 230 | 231 | For an example of an integration test, see the `FileUploadIntegrationTests` class (which 232 | is in `src/test/java/com/example/uploadingfiles`). 233 | 234 | == Summary 235 | 236 | Congratulations! You have just written a web application that uses Spring to handle file 237 | uploads. 238 | 239 | == See Also 240 | 241 | The following guides may also be helpful: 242 | 243 | * https://spring.io/guides/gs/serving-web-content/[Serving Web Content with Spring MVC] 244 | * https://spring.io/guides/gs/handling-form-submission/[Handling Form Submission] 245 | * https://spring.io/guides/gs/securing-web/[Securing a Web Application] 246 | * https://spring.io/guides/gs/spring-boot/[Building an Application with Spring Boot] 247 | 248 | include::https://raw.githubusercontent.com/spring-guides/getting-started-macros/main/footer.adoc[] 249 | -------------------------------------------------------------------------------- /complete/.mvn/wrapper/maven-wrapper.jar: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/spring-guides/gs-uploading-files/0bd41221f63af049e5b4cd16a2748b1ab1dcce76/complete/.mvn/wrapper/maven-wrapper.jar -------------------------------------------------------------------------------- /complete/.mvn/wrapper/maven-wrapper.properties: -------------------------------------------------------------------------------- 1 | distributionUrl=https://repo.maven.apache.org/maven2/org/apache/maven/apache-maven/3.6.3/apache-maven-3.6.3-bin.zip 2 | wrapperUrl=https://repo.maven.apache.org/maven2/io/takari/maven-wrapper/0.5.2/maven-wrapper-0.5.2.tar.gz 3 | -------------------------------------------------------------------------------- /complete/build.gradle: -------------------------------------------------------------------------------- 1 | plugins { 2 | id 'org.springframework.boot' version '3.3.0' 3 | id 'java' 4 | } 5 | 6 | apply plugin: 'io.spring.dependency-management' 7 | 8 | group = 'com.example' 9 | version = '0.0.1-SNAPSHOT' 10 | sourceCompatibility = '17' 11 | 12 | repositories { 13 | mavenCentral() 14 | } 15 | 16 | dependencies { 17 | implementation 'org.springframework.boot:spring-boot-starter-thymeleaf' 18 | implementation 'org.springframework.boot:spring-boot-starter-web' 19 | testImplementation('org.springframework.boot:spring-boot-starter-test') 20 | } 21 | 22 | test { 23 | useJUnitPlatform() 24 | } 25 | -------------------------------------------------------------------------------- /complete/gradle/wrapper/gradle-wrapper.jar: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/spring-guides/gs-uploading-files/0bd41221f63af049e5b4cd16a2748b1ab1dcce76/complete/gradle/wrapper/gradle-wrapper.jar -------------------------------------------------------------------------------- /complete/gradle/wrapper/gradle-wrapper.properties: -------------------------------------------------------------------------------- 1 | distributionBase=GRADLE_USER_HOME 2 | distributionPath=wrapper/dists 3 | distributionUrl=https\://services.gradle.org/distributions/gradle-8.7-bin.zip 4 | networkTimeout=10000 5 | validateDistributionUrl=true 6 | zipStoreBase=GRADLE_USER_HOME 7 | zipStorePath=wrapper/dists 8 | -------------------------------------------------------------------------------- /complete/gradlew: -------------------------------------------------------------------------------- 1 | #!/bin/sh 2 | 3 | # 4 | # Copyright © 2015-2021 the original authors. 5 | # 6 | # Licensed under the Apache License, Version 2.0 (the "License"); 7 | # you may not use this file except in compliance with the License. 8 | # You may obtain a copy of the License at 9 | # 10 | # https://www.apache.org/licenses/LICENSE-2.0 11 | # 12 | # Unless required by applicable law or agreed to in writing, software 13 | # distributed under the License is distributed on an "AS IS" BASIS, 14 | # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. 15 | # See the License for the specific language governing permissions and 16 | # limitations under the License. 17 | # 18 | 19 | ############################################################################## 20 | # 21 | # Gradle start up script for POSIX generated by Gradle. 22 | # 23 | # Important for running: 24 | # 25 | # (1) You need a POSIX-compliant shell to run this script. If your /bin/sh is 26 | # noncompliant, but you have some other compliant shell such as ksh or 27 | # bash, then to run this script, type that shell name before the whole 28 | # command line, like: 29 | # 30 | # ksh Gradle 31 | # 32 | # Busybox and similar reduced shells will NOT work, because this script 33 | # requires all of these POSIX shell features: 34 | # * functions; 35 | # * expansions «$var», «${var}», «${var:-default}», «${var+SET}», 36 | # «${var#prefix}», «${var%suffix}», and «$( cmd )»; 37 | # * compound commands having a testable exit status, especially «case»; 38 | # * various built-in commands including «command», «set», and «ulimit». 39 | # 40 | # Important for patching: 41 | # 42 | # (2) This script targets any POSIX shell, so it avoids extensions provided 43 | # by Bash, Ksh, etc; in particular arrays are avoided. 44 | # 45 | # The "traditional" practice of packing multiple parameters into a 46 | # space-separated string is a well documented source of bugs and security 47 | # problems, so this is (mostly) avoided, by progressively accumulating 48 | # options in "$@", and eventually passing that to Java. 49 | # 50 | # Where the inherited environment variables (DEFAULT_JVM_OPTS, JAVA_OPTS, 51 | # and GRADLE_OPTS) rely on word-splitting, this is performed explicitly; 52 | # see the in-line comments for details. 53 | # 54 | # There are tweaks for specific operating systems such as AIX, CygWin, 55 | # Darwin, MinGW, and NonStop. 56 | # 57 | # (3) This script is generated from the Groovy template 58 | # https://github.com/gradle/gradle/blob/HEAD/subprojects/plugins/src/main/resources/org/gradle/api/internal/plugins/unixStartScript.txt 59 | # within the Gradle project. 60 | # 61 | # You can find Gradle at https://github.com/gradle/gradle/. 62 | # 63 | ############################################################################## 64 | 65 | # Attempt to set APP_HOME 66 | 67 | # Resolve links: $0 may be a link 68 | app_path=$0 69 | 70 | # Need this for daisy-chained symlinks. 71 | while 72 | APP_HOME=${app_path%"${app_path##*/}"} # leaves a trailing /; empty if no leading path 73 | [ -h "$app_path" ] 74 | do 75 | ls=$( ls -ld "$app_path" ) 76 | link=${ls#*' -> '} 77 | case $link in #( 78 | /*) app_path=$link ;; #( 79 | *) app_path=$APP_HOME$link ;; 80 | esac 81 | done 82 | 83 | # This is normally unused 84 | # shellcheck disable=SC2034 85 | APP_BASE_NAME=${0##*/} 86 | # Discard cd standard output in case $CDPATH is set (https://github.com/gradle/gradle/issues/25036) 87 | APP_HOME=$( cd "${APP_HOME:-./}" > /dev/null && pwd -P ) || exit 88 | 89 | # Use the maximum available, or set MAX_FD != -1 to use that value. 90 | MAX_FD=maximum 91 | 92 | warn () { 93 | echo "$*" 94 | } >&2 95 | 96 | die () { 97 | echo 98 | echo "$*" 99 | echo 100 | exit 1 101 | } >&2 102 | 103 | # OS specific support (must be 'true' or 'false'). 104 | cygwin=false 105 | msys=false 106 | darwin=false 107 | nonstop=false 108 | case "$( uname )" in #( 109 | CYGWIN* ) cygwin=true ;; #( 110 | Darwin* ) darwin=true ;; #( 111 | MSYS* | MINGW* ) msys=true ;; #( 112 | NONSTOP* ) nonstop=true ;; 113 | esac 114 | 115 | CLASSPATH=$APP_HOME/gradle/wrapper/gradle-wrapper.jar 116 | 117 | 118 | # Determine the Java command to use to start the JVM. 119 | if [ -n "$JAVA_HOME" ] ; then 120 | if [ -x "$JAVA_HOME/jre/sh/java" ] ; then 121 | # IBM's JDK on AIX uses strange locations for the executables 122 | JAVACMD=$JAVA_HOME/jre/sh/java 123 | else 124 | JAVACMD=$JAVA_HOME/bin/java 125 | fi 126 | if [ ! -x "$JAVACMD" ] ; then 127 | die "ERROR: JAVA_HOME is set to an invalid directory: $JAVA_HOME 128 | 129 | Please set the JAVA_HOME variable in your environment to match the 130 | location of your Java installation." 131 | fi 132 | else 133 | JAVACMD=java 134 | if ! command -v java >/dev/null 2>&1 135 | then 136 | die "ERROR: JAVA_HOME is not set and no 'java' command could be found in your PATH. 137 | 138 | Please set the JAVA_HOME variable in your environment to match the 139 | location of your Java installation." 140 | fi 141 | fi 142 | 143 | # Increase the maximum file descriptors if we can. 144 | if ! "$cygwin" && ! "$darwin" && ! "$nonstop" ; then 145 | case $MAX_FD in #( 146 | max*) 147 | # In POSIX sh, ulimit -H is undefined. That's why the result is checked to see if it worked. 148 | # shellcheck disable=SC2039,SC3045 149 | MAX_FD=$( ulimit -H -n ) || 150 | warn "Could not query maximum file descriptor limit" 151 | esac 152 | case $MAX_FD in #( 153 | '' | soft) :;; #( 154 | *) 155 | # In POSIX sh, ulimit -n is undefined. That's why the result is checked to see if it worked. 156 | # shellcheck disable=SC2039,SC3045 157 | ulimit -n "$MAX_FD" || 158 | warn "Could not set maximum file descriptor limit to $MAX_FD" 159 | esac 160 | fi 161 | 162 | # Collect all arguments for the java command, stacking in reverse order: 163 | # * args from the command line 164 | # * the main class name 165 | # * -classpath 166 | # * -D...appname settings 167 | # * --module-path (only if needed) 168 | # * DEFAULT_JVM_OPTS, JAVA_OPTS, and GRADLE_OPTS environment variables. 169 | 170 | # For Cygwin or MSYS, switch paths to Windows format before running java 171 | if "$cygwin" || "$msys" ; then 172 | APP_HOME=$( cygpath --path --mixed "$APP_HOME" ) 173 | CLASSPATH=$( cygpath --path --mixed "$CLASSPATH" ) 174 | 175 | JAVACMD=$( cygpath --unix "$JAVACMD" ) 176 | 177 | # Now convert the arguments - kludge to limit ourselves to /bin/sh 178 | for arg do 179 | if 180 | case $arg in #( 181 | -*) false ;; # don't mess with options #( 182 | /?*) t=${arg#/} t=/${t%%/*} # looks like a POSIX filepath 183 | [ -e "$t" ] ;; #( 184 | *) false ;; 185 | esac 186 | then 187 | arg=$( cygpath --path --ignore --mixed "$arg" ) 188 | fi 189 | # Roll the args list around exactly as many times as the number of 190 | # args, so each arg winds up back in the position where it started, but 191 | # possibly modified. 192 | # 193 | # NB: a `for` loop captures its iteration list before it begins, so 194 | # changing the positional parameters here affects neither the number of 195 | # iterations, nor the values presented in `arg`. 196 | shift # remove old arg 197 | set -- "$@" "$arg" # push replacement arg 198 | done 199 | fi 200 | 201 | 202 | # Add default JVM options here. You can also use JAVA_OPTS and GRADLE_OPTS to pass JVM options to this script. 203 | DEFAULT_JVM_OPTS='"-Xmx64m" "-Xms64m"' 204 | 205 | # Collect all arguments for the java command: 206 | # * DEFAULT_JVM_OPTS, JAVA_OPTS, JAVA_OPTS, and optsEnvironmentVar are not allowed to contain shell fragments, 207 | # and any embedded shellness will be escaped. 208 | # * For example: A user cannot expect ${Hostname} to be expanded, as it is an environment variable and will be 209 | # treated as '${Hostname}' itself on the command line. 210 | 211 | set -- \ 212 | "-Dorg.gradle.appname=$APP_BASE_NAME" \ 213 | -classpath "$CLASSPATH" \ 214 | org.gradle.wrapper.GradleWrapperMain \ 215 | "$@" 216 | 217 | # Stop when "xargs" is not available. 218 | if ! command -v xargs >/dev/null 2>&1 219 | then 220 | die "xargs is not available" 221 | fi 222 | 223 | # Use "xargs" to parse quoted args. 224 | # 225 | # With -n1 it outputs one arg per line, with the quotes and backslashes removed. 226 | # 227 | # In Bash we could simply go: 228 | # 229 | # readarray ARGS < <( xargs -n1 <<<"$var" ) && 230 | # set -- "${ARGS[@]}" "$@" 231 | # 232 | # but POSIX shell has neither arrays nor command substitution, so instead we 233 | # post-process each arg (as a line of input to sed) to backslash-escape any 234 | # character that might be a shell metacharacter, then use eval to reverse 235 | # that process (while maintaining the separation between arguments), and wrap 236 | # the whole thing up as a single "set" statement. 237 | # 238 | # This will of course break if any of these variables contains a newline or 239 | # an unmatched quote. 240 | # 241 | 242 | eval "set -- $( 243 | printf '%s\n' "$DEFAULT_JVM_OPTS $JAVA_OPTS $GRADLE_OPTS" | 244 | xargs -n1 | 245 | sed ' s~[^-[:alnum:]+,./:=@_]~\\&~g; ' | 246 | tr '\n' ' ' 247 | )" '"$@"' 248 | 249 | exec "$JAVACMD" "$@" 250 | -------------------------------------------------------------------------------- /complete/gradlew.bat: -------------------------------------------------------------------------------- 1 | @rem 2 | @rem Copyright 2015 the original author or authors. 3 | @rem 4 | @rem Licensed under the Apache License, Version 2.0 (the "License"); 5 | @rem you may not use this file except in compliance with the License. 6 | @rem You may obtain a copy of the License at 7 | @rem 8 | @rem https://www.apache.org/licenses/LICENSE-2.0 9 | @rem 10 | @rem Unless required by applicable law or agreed to in writing, software 11 | @rem distributed under the License is distributed on an "AS IS" BASIS, 12 | @rem WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. 13 | @rem See the License for the specific language governing permissions and 14 | @rem limitations under the License. 15 | @rem 16 | 17 | @if "%DEBUG%"=="" @echo off 18 | @rem ########################################################################## 19 | @rem 20 | @rem Gradle startup script for Windows 21 | @rem 22 | @rem ########################################################################## 23 | 24 | @rem Set local scope for the variables with windows NT shell 25 | if "%OS%"=="Windows_NT" setlocal 26 | 27 | set DIRNAME=%~dp0 28 | if "%DIRNAME%"=="" set DIRNAME=. 29 | @rem This is normally unused 30 | set APP_BASE_NAME=%~n0 31 | set APP_HOME=%DIRNAME% 32 | 33 | @rem Resolve any "." and ".." in APP_HOME to make it shorter. 34 | for %%i in ("%APP_HOME%") do set APP_HOME=%%~fi 35 | 36 | @rem Add default JVM options here. You can also use JAVA_OPTS and GRADLE_OPTS to pass JVM options to this script. 37 | set DEFAULT_JVM_OPTS="-Xmx64m" "-Xms64m" 38 | 39 | @rem Find java.exe 40 | if defined JAVA_HOME goto findJavaFromJavaHome 41 | 42 | set JAVA_EXE=java.exe 43 | %JAVA_EXE% -version >NUL 2>&1 44 | if %ERRORLEVEL% equ 0 goto execute 45 | 46 | echo. 1>&2 47 | echo ERROR: JAVA_HOME is not set and no 'java' command could be found in your PATH. 1>&2 48 | echo. 1>&2 49 | echo Please set the JAVA_HOME variable in your environment to match the 1>&2 50 | echo location of your Java installation. 1>&2 51 | 52 | goto fail 53 | 54 | :findJavaFromJavaHome 55 | set JAVA_HOME=%JAVA_HOME:"=% 56 | set JAVA_EXE=%JAVA_HOME%/bin/java.exe 57 | 58 | if exist "%JAVA_EXE%" goto execute 59 | 60 | echo. 1>&2 61 | echo ERROR: JAVA_HOME is set to an invalid directory: %JAVA_HOME% 1>&2 62 | echo. 1>&2 63 | echo Please set the JAVA_HOME variable in your environment to match the 1>&2 64 | echo location of your Java installation. 1>&2 65 | 66 | goto fail 67 | 68 | :execute 69 | @rem Setup the command line 70 | 71 | set CLASSPATH=%APP_HOME%\gradle\wrapper\gradle-wrapper.jar 72 | 73 | 74 | @rem Execute Gradle 75 | "%JAVA_EXE%" %DEFAULT_JVM_OPTS% %JAVA_OPTS% %GRADLE_OPTS% "-Dorg.gradle.appname=%APP_BASE_NAME%" -classpath "%CLASSPATH%" org.gradle.wrapper.GradleWrapperMain %* 76 | 77 | :end 78 | @rem End local scope for the variables with windows NT shell 79 | if %ERRORLEVEL% equ 0 goto mainEnd 80 | 81 | :fail 82 | rem Set variable GRADLE_EXIT_CONSOLE if you need the _script_ return code instead of 83 | rem the _cmd.exe /c_ return code! 84 | set EXIT_CODE=%ERRORLEVEL% 85 | if %EXIT_CODE% equ 0 set EXIT_CODE=1 86 | if not ""=="%GRADLE_EXIT_CONSOLE%" exit %EXIT_CODE% 87 | exit /b %EXIT_CODE% 88 | 89 | :mainEnd 90 | if "%OS%"=="Windows_NT" endlocal 91 | 92 | :omega 93 | -------------------------------------------------------------------------------- /complete/mvnw: -------------------------------------------------------------------------------- 1 | #!/bin/sh 2 | # ---------------------------------------------------------------------------- 3 | # Licensed to the Apache Software Foundation (ASF) under one 4 | # or more contributor license agreements. See the NOTICE file 5 | # distributed with this work for additional information 6 | # regarding copyright ownership. The ASF licenses this file 7 | # to you under the Apache License, Version 2.0 (the 8 | # "License"); you may not use this file except in compliance 9 | # with the License. You may obtain a copy of the License at 10 | # 11 | # http://www.apache.org/licenses/LICENSE-2.0 12 | # 13 | # Unless required by applicable law or agreed to in writing, 14 | # software distributed under the License is distributed on an 15 | # "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY 16 | # KIND, either express or implied. See the License for the 17 | # specific language governing permissions and limitations 18 | # under the License. 19 | # ---------------------------------------------------------------------------- 20 | 21 | # ---------------------------------------------------------------------------- 22 | # Maven2 Start Up Batch script 23 | # 24 | # Required ENV vars: 25 | # ------------------ 26 | # JAVA_HOME - location of a JDK home dir 27 | # 28 | # Optional ENV vars 29 | # ----------------- 30 | # M2_HOME - location of maven2's installed home dir 31 | # MAVEN_OPTS - parameters passed to the Java VM when running Maven 32 | # e.g. to debug Maven itself, use 33 | # set MAVEN_OPTS=-Xdebug -Xrunjdwp:transport=dt_socket,server=y,suspend=y,address=8000 34 | # MAVEN_SKIP_RC - flag to disable loading of mavenrc files 35 | # ---------------------------------------------------------------------------- 36 | 37 | if [ -z "$MAVEN_SKIP_RC" ] ; then 38 | 39 | if [ -f /etc/mavenrc ] ; then 40 | . /etc/mavenrc 41 | fi 42 | 43 | if [ -f "$HOME/.mavenrc" ] ; then 44 | . "$HOME/.mavenrc" 45 | fi 46 | 47 | fi 48 | 49 | # OS specific support. $var _must_ be set to either true or false. 50 | cygwin=false; 51 | darwin=false; 52 | mingw=false 53 | case "`uname`" in 54 | CYGWIN*) cygwin=true ;; 55 | MINGW*) mingw=true;; 56 | Darwin*) darwin=true 57 | # Use /usr/libexec/java_home if available, otherwise fall back to /Library/Java/Home 58 | # See https://developer.apple.com/library/mac/qa/qa1170/_index.html 59 | if [ -z "$JAVA_HOME" ]; then 60 | if [ -x "/usr/libexec/java_home" ]; then 61 | export JAVA_HOME="`/usr/libexec/java_home`" 62 | else 63 | export JAVA_HOME="/Library/Java/Home" 64 | fi 65 | fi 66 | ;; 67 | esac 68 | 69 | if [ -z "$JAVA_HOME" ] ; then 70 | if [ -r /etc/gentoo-release ] ; then 71 | JAVA_HOME=`java-config --jre-home` 72 | fi 73 | fi 74 | 75 | if [ -z "$M2_HOME" ] ; then 76 | ## resolve links - $0 may be a link to maven's home 77 | PRG="$0" 78 | 79 | # need this for relative symlinks 80 | while [ -h "$PRG" ] ; do 81 | ls=`ls -ld "$PRG"` 82 | link=`expr "$ls" : '.*-> \(.*\)$'` 83 | if expr "$link" : '/.*' > /dev/null; then 84 | PRG="$link" 85 | else 86 | PRG="`dirname "$PRG"`/$link" 87 | fi 88 | done 89 | 90 | saveddir=`pwd` 91 | 92 | M2_HOME=`dirname "$PRG"`/.. 93 | 94 | # make it fully qualified 95 | M2_HOME=`cd "$M2_HOME" && pwd` 96 | 97 | cd "$saveddir" 98 | # echo Using m2 at $M2_HOME 99 | fi 100 | 101 | # For Cygwin, ensure paths are in UNIX format before anything is touched 102 | if $cygwin ; then 103 | [ -n "$M2_HOME" ] && 104 | M2_HOME=`cygpath --unix "$M2_HOME"` 105 | [ -n "$JAVA_HOME" ] && 106 | JAVA_HOME=`cygpath --unix "$JAVA_HOME"` 107 | [ -n "$CLASSPATH" ] && 108 | CLASSPATH=`cygpath --path --unix "$CLASSPATH"` 109 | fi 110 | 111 | # For Mingw, ensure paths are in UNIX format before anything is touched 112 | if $mingw ; then 113 | [ -n "$M2_HOME" ] && 114 | M2_HOME="`(cd "$M2_HOME"; pwd)`" 115 | [ -n "$JAVA_HOME" ] && 116 | JAVA_HOME="`(cd "$JAVA_HOME"; pwd)`" 117 | fi 118 | 119 | if [ -z "$JAVA_HOME" ]; then 120 | javaExecutable="`which javac`" 121 | if [ -n "$javaExecutable" ] && ! [ "`expr \"$javaExecutable\" : '\([^ ]*\)'`" = "no" ]; then 122 | # readlink(1) is not available as standard on Solaris 10. 123 | readLink=`which readlink` 124 | if [ ! `expr "$readLink" : '\([^ ]*\)'` = "no" ]; then 125 | if $darwin ; then 126 | javaHome="`dirname \"$javaExecutable\"`" 127 | javaExecutable="`cd \"$javaHome\" && pwd -P`/javac" 128 | else 129 | javaExecutable="`readlink -f \"$javaExecutable\"`" 130 | fi 131 | javaHome="`dirname \"$javaExecutable\"`" 132 | javaHome=`expr "$javaHome" : '\(.*\)/bin'` 133 | JAVA_HOME="$javaHome" 134 | export JAVA_HOME 135 | fi 136 | fi 137 | fi 138 | 139 | if [ -z "$JAVACMD" ] ; then 140 | if [ -n "$JAVA_HOME" ] ; then 141 | if [ -x "$JAVA_HOME/jre/sh/java" ] ; then 142 | # IBM's JDK on AIX uses strange locations for the executables 143 | JAVACMD="$JAVA_HOME/jre/sh/java" 144 | else 145 | JAVACMD="$JAVA_HOME/bin/java" 146 | fi 147 | else 148 | JAVACMD="`which java`" 149 | fi 150 | fi 151 | 152 | if [ ! -x "$JAVACMD" ] ; then 153 | echo "Error: JAVA_HOME is not defined correctly." >&2 154 | echo " We cannot execute $JAVACMD" >&2 155 | exit 1 156 | fi 157 | 158 | if [ -z "$JAVA_HOME" ] ; then 159 | echo "Warning: JAVA_HOME environment variable is not set." 160 | fi 161 | 162 | CLASSWORLDS_LAUNCHER=org.codehaus.plexus.classworlds.launcher.Launcher 163 | 164 | # traverses directory structure from process work directory to filesystem root 165 | # first directory with .mvn subdirectory is considered project base directory 166 | find_maven_basedir() { 167 | 168 | if [ -z "$1" ] 169 | then 170 | echo "Path not specified to find_maven_basedir" 171 | return 1 172 | fi 173 | 174 | basedir="$1" 175 | wdir="$1" 176 | while [ "$wdir" != '/' ] ; do 177 | if [ -d "$wdir"/.mvn ] ; then 178 | basedir=$wdir 179 | break 180 | fi 181 | # workaround for JBEAP-8937 (on Solaris 10/Sparc) 182 | if [ -d "${wdir}" ]; then 183 | wdir=`cd "$wdir/.."; pwd` 184 | fi 185 | # end of workaround 186 | done 187 | echo "${basedir}" 188 | } 189 | 190 | # concatenates all lines of a file 191 | concat_lines() { 192 | if [ -f "$1" ]; then 193 | echo "$(tr -s '\n' ' ' < "$1")" 194 | fi 195 | } 196 | 197 | BASE_DIR=`find_maven_basedir "$(pwd)"` 198 | if [ -z "$BASE_DIR" ]; then 199 | exit 1; 200 | fi 201 | 202 | ########################################################################################## 203 | # Extension to allow automatically downloading the maven-wrapper.jar from Maven-central 204 | # This allows using the maven wrapper in projects that prohibit checking in binary data. 205 | ########################################################################################## 206 | if [ -r "$BASE_DIR/.mvn/wrapper/maven-wrapper.jar" ]; then 207 | if [ "$MVNW_VERBOSE" = true ]; then 208 | echo "Found .mvn/wrapper/maven-wrapper.jar" 209 | fi 210 | else 211 | if [ "$MVNW_VERBOSE" = true ]; then 212 | echo "Couldn't find .mvn/wrapper/maven-wrapper.jar, downloading it ..." 213 | fi 214 | if [ "$MVNW_REPOURL" = true]; then 215 | jarUrl="$MVNW_REPOURL/io/takari/maven-wrapper/0.5.2/maven-wrapper-0.5.2.jar" 216 | else 217 | jarUrl="https://repo.maven.apache.org/maven2/io/takari/maven-wrapper/0.5.2/maven-wrapper-0.5.2.jar" 218 | fi 219 | while IFS="=" read key value; do 220 | case "$key" in (wrapperUrl) jarUrl="$value"; break ;; 221 | esac 222 | done < "$BASE_DIR/.mvn/wrapper/maven-wrapper.properties" 223 | if [ "$MVNW_VERBOSE" = true ]; then 224 | echo "Downloading from: $jarUrl" 225 | fi 226 | wrapperJarPath="$BASE_DIR/.mvn/wrapper/maven-wrapper.jar" 227 | if $cygwin; then 228 | wrapperJarPath=`cygpath --path --windows "$wrapperJarPath"` 229 | fi 230 | 231 | if command -v wget > /dev/null; then 232 | if [ "$MVNW_VERBOSE" = true ]; then 233 | echo "Found wget ... using wget" 234 | fi 235 | if [ -z "$MVNW_USERNAME" ] || [ -z "$MVNW_PASSWORD" ]; then 236 | wget "$jarUrl" -O "$wrapperJarPath" 237 | else 238 | wget --http-user=$MVNW_USERNAME --http-password=$MVNW_PASSWORD "$jarUrl" -O "$wrapperJarPath" 239 | fi 240 | elif command -v curl > /dev/null; then 241 | if [ "$MVNW_VERBOSE" = true ]; then 242 | echo "Found curl ... using curl" 243 | fi 244 | if [ -z "$MVNW_USERNAME" ] || [ -z "$MVNW_PASSWORD" ]; then 245 | curl -o "$wrapperJarPath" "$jarUrl" -f 246 | else 247 | curl --user $MVNW_USERNAME:$MVNW_PASSWORD -o "$wrapperJarPath" "$jarUrl" -f 248 | fi 249 | 250 | else 251 | if [ "$MVNW_VERBOSE" = true ]; then 252 | echo "Falling back to using Java to download" 253 | fi 254 | javaClass="$BASE_DIR/.mvn/wrapper/MavenWrapperDownloader.java" 255 | # For Cygwin, switch paths to Windows format before running javac 256 | if $cygwin; then 257 | javaClass=`cygpath --path --windows "$javaClass"` 258 | fi 259 | if [ -e "$javaClass" ]; then 260 | if [ ! -e "$BASE_DIR/.mvn/wrapper/MavenWrapperDownloader.class" ]; then 261 | if [ "$MVNW_VERBOSE" = true ]; then 262 | echo " - Compiling MavenWrapperDownloader.java ..." 263 | fi 264 | # Compiling the Java class 265 | ("$JAVA_HOME/bin/javac" "$javaClass") 266 | fi 267 | if [ -e "$BASE_DIR/.mvn/wrapper/MavenWrapperDownloader.class" ]; then 268 | # Running the downloader 269 | if [ "$MVNW_VERBOSE" = true ]; then 270 | echo " - Running MavenWrapperDownloader.java ..." 271 | fi 272 | ("$JAVA_HOME/bin/java" -cp .mvn/wrapper MavenWrapperDownloader "$MAVEN_PROJECTBASEDIR") 273 | fi 274 | fi 275 | fi 276 | fi 277 | ########################################################################################## 278 | # End of extension 279 | ########################################################################################## 280 | 281 | export MAVEN_PROJECTBASEDIR=${MAVEN_BASEDIR:-"$BASE_DIR"} 282 | if [ "$MVNW_VERBOSE" = true ]; then 283 | echo $MAVEN_PROJECTBASEDIR 284 | fi 285 | MAVEN_OPTS="$(concat_lines "$MAVEN_PROJECTBASEDIR/.mvn/jvm.config") $MAVEN_OPTS" 286 | 287 | # For Cygwin, switch paths to Windows format before running java 288 | if $cygwin; then 289 | [ -n "$M2_HOME" ] && 290 | M2_HOME=`cygpath --path --windows "$M2_HOME"` 291 | [ -n "$JAVA_HOME" ] && 292 | JAVA_HOME=`cygpath --path --windows "$JAVA_HOME"` 293 | [ -n "$CLASSPATH" ] && 294 | CLASSPATH=`cygpath --path --windows "$CLASSPATH"` 295 | [ -n "$MAVEN_PROJECTBASEDIR" ] && 296 | MAVEN_PROJECTBASEDIR=`cygpath --path --windows "$MAVEN_PROJECTBASEDIR"` 297 | fi 298 | 299 | WRAPPER_LAUNCHER=org.apache.maven.wrapper.MavenWrapperMain 300 | 301 | exec "$JAVACMD" \ 302 | $MAVEN_OPTS \ 303 | -classpath "$MAVEN_PROJECTBASEDIR/.mvn/wrapper/maven-wrapper.jar" \ 304 | "-Dmaven.home=${M2_HOME}" "-Dmaven.multiModuleProjectDirectory=${MAVEN_PROJECTBASEDIR}" \ 305 | ${WRAPPER_LAUNCHER} $MAVEN_CONFIG "$@" 306 | -------------------------------------------------------------------------------- /complete/mvnw.cmd: -------------------------------------------------------------------------------- 1 | @REM ---------------------------------------------------------------------------- 2 | @REM Licensed to the Apache Software Foundation (ASF) under one 3 | @REM or more contributor license agreements. See the NOTICE file 4 | @REM distributed with this work for additional information 5 | @REM regarding copyright ownership. The ASF licenses this file 6 | @REM to you under the Apache License, Version 2.0 (the 7 | @REM "License"); you may not use this file except in compliance 8 | @REM with the License. You may obtain a copy of the License at 9 | @REM 10 | @REM http://www.apache.org/licenses/LICENSE-2.0 11 | @REM 12 | @REM Unless required by applicable law or agreed to in writing, 13 | @REM software distributed under the License is distributed on an 14 | @REM "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY 15 | @REM KIND, either express or implied. See the License for the 16 | @REM specific language governing permissions and limitations 17 | @REM under the License. 18 | @REM ---------------------------------------------------------------------------- 19 | 20 | @REM ---------------------------------------------------------------------------- 21 | @REM Maven2 Start Up Batch script 22 | @REM 23 | @REM Required ENV vars: 24 | @REM JAVA_HOME - location of a JDK home dir 25 | @REM 26 | @REM Optional ENV vars 27 | @REM M2_HOME - location of maven2's installed home dir 28 | @REM MAVEN_BATCH_ECHO - set to 'on' to enable the echoing of the batch commands 29 | @REM MAVEN_BATCH_PAUSE - set to 'on' to wait for a key stroke before ending 30 | @REM MAVEN_OPTS - parameters passed to the Java VM when running Maven 31 | @REM e.g. to debug Maven itself, use 32 | @REM set MAVEN_OPTS=-Xdebug -Xrunjdwp:transport=dt_socket,server=y,suspend=y,address=8000 33 | @REM MAVEN_SKIP_RC - flag to disable loading of mavenrc files 34 | @REM ---------------------------------------------------------------------------- 35 | 36 | @REM Begin all REM lines with '@' in case MAVEN_BATCH_ECHO is 'on' 37 | @echo off 38 | @REM set title of command window 39 | title %0 40 | @REM enable echoing my setting MAVEN_BATCH_ECHO to 'on' 41 | @if "%MAVEN_BATCH_ECHO%" == "on" echo %MAVEN_BATCH_ECHO% 42 | 43 | @REM set %HOME% to equivalent of $HOME 44 | if "%HOME%" == "" (set "HOME=%HOMEDRIVE%%HOMEPATH%") 45 | 46 | @REM Execute a user defined script before this one 47 | if not "%MAVEN_SKIP_RC%" == "" goto skipRcPre 48 | @REM check for pre script, once with legacy .bat ending and once with .cmd ending 49 | if exist "%HOME%\mavenrc_pre.bat" call "%HOME%\mavenrc_pre.bat" 50 | if exist "%HOME%\mavenrc_pre.cmd" call "%HOME%\mavenrc_pre.cmd" 51 | :skipRcPre 52 | 53 | @setlocal 54 | 55 | set ERROR_CODE=0 56 | 57 | @REM To isolate internal variables from possible post scripts, we use another setlocal 58 | @setlocal 59 | 60 | @REM ==== START VALIDATION ==== 61 | if not "%JAVA_HOME%" == "" goto OkJHome 62 | 63 | echo. 64 | echo Error: JAVA_HOME not found in your environment. >&2 65 | echo Please set the JAVA_HOME variable in your environment to match the >&2 66 | echo location of your Java installation. >&2 67 | echo. 68 | goto error 69 | 70 | :OkJHome 71 | if exist "%JAVA_HOME%\bin\java.exe" goto init 72 | 73 | echo. 74 | echo Error: JAVA_HOME is set to an invalid directory. >&2 75 | echo JAVA_HOME = "%JAVA_HOME%" >&2 76 | echo Please set the JAVA_HOME variable in your environment to match the >&2 77 | echo location of your Java installation. >&2 78 | echo. 79 | goto error 80 | 81 | @REM ==== END VALIDATION ==== 82 | 83 | :init 84 | 85 | @REM Find the project base dir, i.e. the directory that contains the folder ".mvn". 86 | @REM Fallback to current working directory if not found. 87 | 88 | set MAVEN_PROJECTBASEDIR=%MAVEN_BASEDIR% 89 | IF NOT "%MAVEN_PROJECTBASEDIR%"=="" goto endDetectBaseDir 90 | 91 | set EXEC_DIR=%CD% 92 | set WDIR=%EXEC_DIR% 93 | :findBaseDir 94 | IF EXIST "%WDIR%"\.mvn goto baseDirFound 95 | cd .. 96 | IF "%WDIR%"=="%CD%" goto baseDirNotFound 97 | set WDIR=%CD% 98 | goto findBaseDir 99 | 100 | :baseDirFound 101 | set MAVEN_PROJECTBASEDIR=%WDIR% 102 | cd "%EXEC_DIR%" 103 | goto endDetectBaseDir 104 | 105 | :baseDirNotFound 106 | set MAVEN_PROJECTBASEDIR=%EXEC_DIR% 107 | cd "%EXEC_DIR%" 108 | 109 | :endDetectBaseDir 110 | 111 | IF NOT EXIST "%MAVEN_PROJECTBASEDIR%\.mvn\jvm.config" goto endReadAdditionalConfig 112 | 113 | @setlocal EnableExtensions EnableDelayedExpansion 114 | for /F "usebackq delims=" %%a in ("%MAVEN_PROJECTBASEDIR%\.mvn\jvm.config") do set JVM_CONFIG_MAVEN_PROPS=!JVM_CONFIG_MAVEN_PROPS! %%a 115 | @endlocal & set JVM_CONFIG_MAVEN_PROPS=%JVM_CONFIG_MAVEN_PROPS% 116 | 117 | :endReadAdditionalConfig 118 | 119 | SET MAVEN_JAVA_EXE="%JAVA_HOME%\bin\java.exe" 120 | set WRAPPER_JAR="%MAVEN_PROJECTBASEDIR%\.mvn\wrapper\maven-wrapper.jar" 121 | set WRAPPER_LAUNCHER=org.apache.maven.wrapper.MavenWrapperMain 122 | 123 | set DOWNLOAD_URL="https://repo.maven.apache.org/maven2/io/takari/maven-wrapper/0.5.2/maven-wrapper-0.5.2.jar" 124 | 125 | FOR /F "tokens=1,2 delims==" %%A IN ("%MAVEN_PROJECTBASEDIR%\.mvn\wrapper\maven-wrapper.properties") DO ( 126 | IF "%%A"=="wrapperUrl" SET DOWNLOAD_URL=%%B 127 | ) 128 | 129 | @REM Extension to allow automatically downloading the maven-wrapper.jar from Maven-central 130 | @REM This allows using the maven wrapper in projects that prohibit checking in binary data. 131 | if exist %WRAPPER_JAR% ( 132 | echo Found %WRAPPER_JAR% 133 | ) else ( 134 | if not "%MVNW_REPOURL%" == "" ( 135 | SET DOWNLOAD_URL="%MVNW_REPOURL%/io/takari/maven-wrapper/0.5.2/maven-wrapper-0.5.2.jar" 136 | ) 137 | echo Couldn't find %WRAPPER_JAR%, downloading it ... 138 | echo Downloading from: %DOWNLOAD_URL% 139 | 140 | powershell -Command "&{"^ 141 | "$webclient = new-object System.Net.WebClient;"^ 142 | "if (-not ([string]::IsNullOrEmpty('%MVNW_USERNAME%') -and [string]::IsNullOrEmpty('%MVNW_PASSWORD%'))) {"^ 143 | "$webclient.Credentials = new-object System.Net.NetworkCredential('%MVNW_USERNAME%', '%MVNW_PASSWORD%');"^ 144 | "}"^ 145 | "[Net.ServicePointManager]::SecurityProtocol = [Net.SecurityProtocolType]::Tls12; $webclient.DownloadFile('%DOWNLOAD_URL%', '%WRAPPER_JAR%')"^ 146 | "}" 147 | echo Finished downloading %WRAPPER_JAR% 148 | ) 149 | @REM End of extension 150 | 151 | %MAVEN_JAVA_EXE% %JVM_CONFIG_MAVEN_PROPS% %MAVEN_OPTS% %MAVEN_DEBUG_OPTS% -classpath %WRAPPER_JAR% "-Dmaven.multiModuleProjectDirectory=%MAVEN_PROJECTBASEDIR%" %WRAPPER_LAUNCHER% %MAVEN_CONFIG% %* 152 | if ERRORLEVEL 1 goto error 153 | goto end 154 | 155 | :error 156 | set ERROR_CODE=1 157 | 158 | :end 159 | @endlocal & set ERROR_CODE=%ERROR_CODE% 160 | 161 | if not "%MAVEN_SKIP_RC%" == "" goto skipRcPost 162 | @REM check for post script, once with legacy .bat ending and once with .cmd ending 163 | if exist "%HOME%\mavenrc_post.bat" call "%HOME%\mavenrc_post.bat" 164 | if exist "%HOME%\mavenrc_post.cmd" call "%HOME%\mavenrc_post.cmd" 165 | :skipRcPost 166 | 167 | @REM pause the script if MAVEN_BATCH_PAUSE is set to 'on' 168 | if "%MAVEN_BATCH_PAUSE%" == "on" pause 169 | 170 | if "%MAVEN_TERMINATE_CMD%" == "on" exit %ERROR_CODE% 171 | 172 | exit /B %ERROR_CODE% 173 | -------------------------------------------------------------------------------- /complete/pom.xml: -------------------------------------------------------------------------------- 1 | 2 | 4 | 4.0.0 5 | 6 | org.springframework.boot 7 | spring-boot-starter-parent 8 | 3.3.0 9 | 10 | 11 | com.example 12 | uploading-files-complete 13 | 0.0.1-SNAPSHOT 14 | uploading-files-complete 15 | Demo project for Spring Boot 16 | 17 | 18 | 17 19 | 20 | 21 | 22 | 23 | org.springframework.boot 24 | spring-boot-starter-thymeleaf 25 | 26 | 27 | org.springframework.boot 28 | spring-boot-starter-web 29 | 30 | 31 | 32 | org.springframework.boot 33 | spring-boot-starter-test 34 | test 35 | 36 | 37 | 38 | 39 | 40 | 41 | org.springframework.boot 42 | spring-boot-maven-plugin 43 | 44 | 45 | 46 | 47 | 48 | -------------------------------------------------------------------------------- /complete/settings.gradle: -------------------------------------------------------------------------------- 1 | rootProject.name = 'uploading-files' 2 | -------------------------------------------------------------------------------- /complete/src/main/java/com/example/uploadingfiles/FileUploadController.java: -------------------------------------------------------------------------------- 1 | package com.example.uploadingfiles; 2 | 3 | import java.io.IOException; 4 | import java.util.stream.Collectors; 5 | 6 | import org.springframework.beans.factory.annotation.Autowired; 7 | import org.springframework.core.io.Resource; 8 | import org.springframework.http.HttpHeaders; 9 | import org.springframework.http.ResponseEntity; 10 | import org.springframework.stereotype.Controller; 11 | import org.springframework.ui.Model; 12 | import org.springframework.web.bind.annotation.ExceptionHandler; 13 | import org.springframework.web.bind.annotation.GetMapping; 14 | import org.springframework.web.bind.annotation.PathVariable; 15 | import org.springframework.web.bind.annotation.PostMapping; 16 | import org.springframework.web.bind.annotation.RequestParam; 17 | import org.springframework.web.bind.annotation.ResponseBody; 18 | import org.springframework.web.multipart.MultipartFile; 19 | import org.springframework.web.servlet.mvc.method.annotation.MvcUriComponentsBuilder; 20 | import org.springframework.web.servlet.mvc.support.RedirectAttributes; 21 | 22 | import com.example.uploadingfiles.storage.StorageFileNotFoundException; 23 | import com.example.uploadingfiles.storage.StorageService; 24 | 25 | @Controller 26 | public class FileUploadController { 27 | 28 | private final StorageService storageService; 29 | 30 | @Autowired 31 | public FileUploadController(StorageService storageService) { 32 | this.storageService = storageService; 33 | } 34 | 35 | @GetMapping("/") 36 | public String listUploadedFiles(Model model) throws IOException { 37 | 38 | model.addAttribute("files", storageService.loadAll().map( 39 | path -> MvcUriComponentsBuilder.fromMethodName(FileUploadController.class, 40 | "serveFile", path.getFileName().toString()).build().toUri().toString()) 41 | .collect(Collectors.toList())); 42 | 43 | return "uploadForm"; 44 | } 45 | 46 | @GetMapping("/files/{filename:.+}") 47 | @ResponseBody 48 | public ResponseEntity serveFile(@PathVariable String filename) { 49 | 50 | Resource file = storageService.loadAsResource(filename); 51 | 52 | if (file == null) 53 | return ResponseEntity.notFound().build(); 54 | 55 | return ResponseEntity.ok().header(HttpHeaders.CONTENT_DISPOSITION, 56 | "attachment; filename=\"" + file.getFilename() + "\"").body(file); 57 | } 58 | 59 | @PostMapping("/") 60 | public String handleFileUpload(@RequestParam("file") MultipartFile file, 61 | RedirectAttributes redirectAttributes) { 62 | 63 | storageService.store(file); 64 | redirectAttributes.addFlashAttribute("message", 65 | "You successfully uploaded " + file.getOriginalFilename() + "!"); 66 | 67 | return "redirect:/"; 68 | } 69 | 70 | @ExceptionHandler(StorageFileNotFoundException.class) 71 | public ResponseEntity handleStorageFileNotFound(StorageFileNotFoundException exc) { 72 | return ResponseEntity.notFound().build(); 73 | } 74 | 75 | } 76 | -------------------------------------------------------------------------------- /complete/src/main/java/com/example/uploadingfiles/UploadingFilesApplication.java: -------------------------------------------------------------------------------- 1 | package com.example.uploadingfiles; 2 | 3 | import org.springframework.boot.CommandLineRunner; 4 | import org.springframework.boot.SpringApplication; 5 | import org.springframework.boot.autoconfigure.SpringBootApplication; 6 | import org.springframework.boot.context.properties.EnableConfigurationProperties; 7 | import org.springframework.context.annotation.Bean; 8 | 9 | import com.example.uploadingfiles.storage.StorageProperties; 10 | import com.example.uploadingfiles.storage.StorageService; 11 | 12 | @SpringBootApplication 13 | @EnableConfigurationProperties(StorageProperties.class) 14 | public class UploadingFilesApplication { 15 | 16 | public static void main(String[] args) { 17 | SpringApplication.run(UploadingFilesApplication.class, args); 18 | } 19 | 20 | @Bean 21 | CommandLineRunner init(StorageService storageService) { 22 | return (args) -> { 23 | storageService.deleteAll(); 24 | storageService.init(); 25 | }; 26 | } 27 | } 28 | -------------------------------------------------------------------------------- /complete/src/main/java/com/example/uploadingfiles/storage/FileSystemStorageService.java: -------------------------------------------------------------------------------- 1 | package com.example.uploadingfiles.storage; 2 | 3 | import java.io.IOException; 4 | import java.io.InputStream; 5 | import java.net.MalformedURLException; 6 | import java.nio.file.Files; 7 | import java.nio.file.Path; 8 | import java.nio.file.Paths; 9 | import java.nio.file.StandardCopyOption; 10 | import java.util.stream.Stream; 11 | 12 | import org.springframework.beans.factory.annotation.Autowired; 13 | import org.springframework.core.io.Resource; 14 | import org.springframework.core.io.UrlResource; 15 | import org.springframework.stereotype.Service; 16 | import org.springframework.util.FileSystemUtils; 17 | import org.springframework.util.StringUtils; 18 | import org.springframework.web.multipart.MultipartFile; 19 | 20 | @Service 21 | public class FileSystemStorageService implements StorageService { 22 | 23 | private final Path rootLocation; 24 | 25 | @Autowired 26 | public FileSystemStorageService(StorageProperties properties) { 27 | 28 | if(properties.getLocation().trim().length() == 0){ 29 | throw new StorageException("File upload location can not be Empty."); 30 | } 31 | 32 | this.rootLocation = Paths.get(properties.getLocation()); 33 | } 34 | 35 | @Override 36 | public void store(MultipartFile file) { 37 | try { 38 | if (file.isEmpty()) { 39 | throw new StorageException("Failed to store empty file."); 40 | } 41 | Path destinationFile = this.rootLocation.resolve( 42 | Paths.get(file.getOriginalFilename())) 43 | .normalize().toAbsolutePath(); 44 | if (!destinationFile.getParent().equals(this.rootLocation.toAbsolutePath())) { 45 | // This is a security check 46 | throw new StorageException( 47 | "Cannot store file outside current directory."); 48 | } 49 | try (InputStream inputStream = file.getInputStream()) { 50 | Files.copy(inputStream, destinationFile, 51 | StandardCopyOption.REPLACE_EXISTING); 52 | } 53 | } 54 | catch (IOException e) { 55 | throw new StorageException("Failed to store file.", e); 56 | } 57 | } 58 | 59 | @Override 60 | public Stream loadAll() { 61 | try { 62 | return Files.walk(this.rootLocation, 1) 63 | .filter(path -> !path.equals(this.rootLocation)) 64 | .map(this.rootLocation::relativize); 65 | } 66 | catch (IOException e) { 67 | throw new StorageException("Failed to read stored files", e); 68 | } 69 | 70 | } 71 | 72 | @Override 73 | public Path load(String filename) { 74 | return rootLocation.resolve(filename); 75 | } 76 | 77 | @Override 78 | public Resource loadAsResource(String filename) { 79 | try { 80 | Path file = load(filename); 81 | Resource resource = new UrlResource(file.toUri()); 82 | if (resource.exists() || resource.isReadable()) { 83 | return resource; 84 | } 85 | else { 86 | throw new StorageFileNotFoundException( 87 | "Could not read file: " + filename); 88 | 89 | } 90 | } 91 | catch (MalformedURLException e) { 92 | throw new StorageFileNotFoundException("Could not read file: " + filename, e); 93 | } 94 | } 95 | 96 | @Override 97 | public void deleteAll() { 98 | FileSystemUtils.deleteRecursively(rootLocation.toFile()); 99 | } 100 | 101 | @Override 102 | public void init() { 103 | try { 104 | Files.createDirectories(rootLocation); 105 | } 106 | catch (IOException e) { 107 | throw new StorageException("Could not initialize storage", e); 108 | } 109 | } 110 | } 111 | -------------------------------------------------------------------------------- /complete/src/main/java/com/example/uploadingfiles/storage/StorageException.java: -------------------------------------------------------------------------------- 1 | package com.example.uploadingfiles.storage; 2 | 3 | public class StorageException extends RuntimeException { 4 | 5 | public StorageException(String message) { 6 | super(message); 7 | } 8 | 9 | public StorageException(String message, Throwable cause) { 10 | super(message, cause); 11 | } 12 | } 13 | -------------------------------------------------------------------------------- /complete/src/main/java/com/example/uploadingfiles/storage/StorageFileNotFoundException.java: -------------------------------------------------------------------------------- 1 | package com.example.uploadingfiles.storage; 2 | 3 | public class StorageFileNotFoundException extends StorageException { 4 | 5 | public StorageFileNotFoundException(String message) { 6 | super(message); 7 | } 8 | 9 | public StorageFileNotFoundException(String message, Throwable cause) { 10 | super(message, cause); 11 | } 12 | } 13 | -------------------------------------------------------------------------------- /complete/src/main/java/com/example/uploadingfiles/storage/StorageProperties.java: -------------------------------------------------------------------------------- 1 | package com.example.uploadingfiles.storage; 2 | 3 | import org.springframework.boot.context.properties.ConfigurationProperties; 4 | 5 | @ConfigurationProperties("storage") 6 | public class StorageProperties { 7 | 8 | /** 9 | * Folder location for storing files 10 | */ 11 | private String location = "upload-dir"; 12 | 13 | public String getLocation() { 14 | return location; 15 | } 16 | 17 | public void setLocation(String location) { 18 | this.location = location; 19 | } 20 | 21 | } 22 | -------------------------------------------------------------------------------- /complete/src/main/java/com/example/uploadingfiles/storage/StorageService.java: -------------------------------------------------------------------------------- 1 | package com.example.uploadingfiles.storage; 2 | 3 | import org.springframework.core.io.Resource; 4 | import org.springframework.web.multipart.MultipartFile; 5 | 6 | import java.nio.file.Path; 7 | import java.util.stream.Stream; 8 | 9 | public interface StorageService { 10 | 11 | void init(); 12 | 13 | void store(MultipartFile file); 14 | 15 | Stream loadAll(); 16 | 17 | Path load(String filename); 18 | 19 | Resource loadAsResource(String filename); 20 | 21 | void deleteAll(); 22 | 23 | } 24 | -------------------------------------------------------------------------------- /complete/src/main/resources/application.properties: -------------------------------------------------------------------------------- 1 | spring.servlet.multipart.max-file-size=128KB 2 | spring.servlet.multipart.max-request-size=128KB 3 | -------------------------------------------------------------------------------- /complete/src/main/resources/templates/uploadForm.html: -------------------------------------------------------------------------------- 1 | 2 | 3 | 4 |
5 |

6 |

7 | 8 |
9 |
10 | 11 | 12 | 13 |
File to upload:
14 |
15 |
16 | 17 |
18 | 23 |
24 | 25 | 26 | 27 | -------------------------------------------------------------------------------- /complete/src/test/java/com/example/uploadingfiles/FileUploadIntegrationTests.java: -------------------------------------------------------------------------------- 1 | package com.example.uploadingfiles; 2 | 3 | import org.junit.jupiter.api.Test; 4 | 5 | import org.springframework.beans.factory.annotation.Autowired; 6 | import org.springframework.boot.test.context.SpringBootTest; 7 | import org.springframework.boot.test.mock.mockito.MockBean; 8 | import org.springframework.boot.test.web.client.TestRestTemplate; 9 | import org.springframework.boot.test.web.server.LocalServerPort; 10 | import org.springframework.core.io.ClassPathResource; 11 | import org.springframework.http.HttpHeaders; 12 | import org.springframework.http.HttpStatus; 13 | import org.springframework.http.ResponseEntity; 14 | import org.springframework.util.LinkedMultiValueMap; 15 | import org.springframework.util.MultiValueMap; 16 | import org.springframework.web.multipart.MultipartFile; 17 | 18 | import static org.assertj.core.api.Assertions.assertThat; 19 | import static org.mockito.BDDMockito.given; 20 | import static org.mockito.BDDMockito.then; 21 | import static org.mockito.ArgumentMatchers.any; 22 | 23 | import com.example.uploadingfiles.storage.StorageService; 24 | 25 | @SpringBootTest(webEnvironment = SpringBootTest.WebEnvironment.RANDOM_PORT) 26 | public class FileUploadIntegrationTests { 27 | 28 | @Autowired 29 | private TestRestTemplate restTemplate; 30 | 31 | @MockBean 32 | private StorageService storageService; 33 | 34 | @LocalServerPort 35 | private int port; 36 | 37 | @Test 38 | public void shouldUploadFile() throws Exception { 39 | ClassPathResource resource = new ClassPathResource("testupload.txt", getClass()); 40 | 41 | MultiValueMap map = new LinkedMultiValueMap(); 42 | map.add("file", resource); 43 | ResponseEntity response = this.restTemplate.postForEntity("/", map, 44 | String.class); 45 | 46 | assertThat(response.getStatusCode()).isEqualTo(HttpStatus.FOUND); 47 | assertThat(response.getHeaders().getLocation().toString()) 48 | .startsWith("http://localhost:" + this.port + "/"); 49 | then(storageService).should().store(any(MultipartFile.class)); 50 | } 51 | 52 | @Test 53 | public void shouldDownloadFile() throws Exception { 54 | ClassPathResource resource = new ClassPathResource("testupload.txt", getClass()); 55 | given(this.storageService.loadAsResource("testupload.txt")).willReturn(resource); 56 | 57 | ResponseEntity response = this.restTemplate 58 | .getForEntity("/files/{filename}", String.class, "testupload.txt"); 59 | 60 | assertThat(response.getStatusCodeValue()).isEqualTo(200); 61 | assertThat(response.getHeaders().getFirst(HttpHeaders.CONTENT_DISPOSITION)) 62 | .isEqualTo("attachment; filename=\"testupload.txt\""); 63 | assertThat(response.getBody()).isEqualTo("Spring Framework"); 64 | } 65 | 66 | } 67 | -------------------------------------------------------------------------------- /complete/src/test/java/com/example/uploadingfiles/FileUploadTests.java: -------------------------------------------------------------------------------- 1 | package com.example.uploadingfiles; 2 | 3 | import java.nio.file.Paths; 4 | import java.util.stream.Stream; 5 | 6 | import org.hamcrest.Matchers; 7 | import org.junit.jupiter.api.Test; 8 | 9 | import org.springframework.beans.factory.annotation.Autowired; 10 | import org.springframework.boot.test.autoconfigure.web.servlet.AutoConfigureMockMvc; 11 | import org.springframework.boot.test.context.SpringBootTest; 12 | import org.springframework.boot.test.mock.mockito.MockBean; 13 | import org.springframework.mock.web.MockMultipartFile; 14 | import org.springframework.test.web.servlet.MockMvc; 15 | 16 | import static org.mockito.BDDMockito.given; 17 | import static org.mockito.BDDMockito.then; 18 | import static org.springframework.test.web.servlet.request.MockMvcRequestBuilders.get; 19 | import static org.springframework.test.web.servlet.request.MockMvcRequestBuilders.multipart; 20 | import static org.springframework.test.web.servlet.result.MockMvcResultMatchers.header; 21 | import static org.springframework.test.web.servlet.result.MockMvcResultMatchers.model; 22 | import static org.springframework.test.web.servlet.result.MockMvcResultMatchers.status; 23 | 24 | import com.example.uploadingfiles.storage.StorageFileNotFoundException; 25 | import com.example.uploadingfiles.storage.StorageService; 26 | 27 | @AutoConfigureMockMvc 28 | @SpringBootTest 29 | public class FileUploadTests { 30 | 31 | @Autowired 32 | private MockMvc mvc; 33 | 34 | @MockBean 35 | private StorageService storageService; 36 | 37 | @Test 38 | public void shouldListAllFiles() throws Exception { 39 | given(this.storageService.loadAll()) 40 | .willReturn(Stream.of(Paths.get("first.txt"), Paths.get("second.txt"))); 41 | 42 | this.mvc.perform(get("/")).andExpect(status().isOk()) 43 | .andExpect(model().attribute("files", 44 | Matchers.contains("http://localhost/files/first.txt", 45 | "http://localhost/files/second.txt"))); 46 | } 47 | 48 | @Test 49 | public void shouldSaveUploadedFile() throws Exception { 50 | MockMultipartFile multipartFile = new MockMultipartFile("file", "test.txt", 51 | "text/plain", "Spring Framework".getBytes()); 52 | this.mvc.perform(multipart("/").file(multipartFile)) 53 | .andExpect(status().isFound()) 54 | .andExpect(header().string("Location", "/")); 55 | 56 | then(this.storageService).should().store(multipartFile); 57 | } 58 | 59 | @SuppressWarnings("unchecked") 60 | @Test 61 | public void should404WhenMissingFile() throws Exception { 62 | given(this.storageService.loadAsResource("test.txt")) 63 | .willThrow(StorageFileNotFoundException.class); 64 | 65 | this.mvc.perform(get("/files/test.txt")).andExpect(status().isNotFound()); 66 | } 67 | 68 | } 69 | -------------------------------------------------------------------------------- /complete/src/test/java/com/example/uploadingfiles/storage/FileSystemStorageServiceTests.java: -------------------------------------------------------------------------------- 1 | /* 2 | * Copyright 2016-2017 the original author or authors. 3 | * 4 | * Licensed under the Apache License, Version 2.0 (the "License"); 5 | * you may not use this file except in compliance with the License. 6 | * You may obtain a copy of the License at 7 | * 8 | * https://www.apache.org/licenses/LICENSE-2.0 9 | * 10 | * Unless required by applicable law or agreed to in writing, software 11 | * distributed under the License is distributed on an "AS IS" BASIS, 12 | * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. 13 | * See the License for the specific language governing permissions and 14 | * limitations under the License. 15 | */ 16 | package com.example.uploadingfiles.storage; 17 | 18 | import java.nio.file.Files; 19 | import java.nio.file.Paths; 20 | import java.util.Random; 21 | 22 | import org.junit.jupiter.api.BeforeEach; 23 | import org.junit.jupiter.api.Test; 24 | import static org.junit.jupiter.api.Assertions.assertThrows; 25 | 26 | import org.junit.jupiter.api.condition.EnabledOnOs; 27 | import org.junit.jupiter.api.condition.OS; 28 | import org.springframework.http.MediaType; 29 | import org.springframework.mock.web.MockMultipartFile; 30 | 31 | import static org.assertj.core.api.Assertions.assertThat; 32 | import static org.junit.jupiter.api.Assertions.assertTrue; 33 | 34 | /** 35 | * @author Dave Syer 36 | * 37 | */ 38 | public class FileSystemStorageServiceTests { 39 | 40 | private StorageProperties properties = new StorageProperties(); 41 | private FileSystemStorageService service; 42 | 43 | @BeforeEach 44 | public void init() { 45 | properties.setLocation("target/files/" + Math.abs(new Random().nextLong())); 46 | service = new FileSystemStorageService(properties); 47 | service.init(); 48 | } 49 | 50 | @Test 51 | public void emptyUploadLocation() { 52 | service = null; 53 | properties.setLocation(""); 54 | assertThrows(StorageException.class, () -> { 55 | service = new FileSystemStorageService(properties); 56 | }); 57 | } 58 | 59 | @Test 60 | public void loadNonExistent() { 61 | assertThat(service.load("foo.txt")).doesNotExist(); 62 | } 63 | 64 | @Test 65 | public void saveAndLoad() { 66 | service.store(new MockMultipartFile("foo", "foo.txt", MediaType.TEXT_PLAIN_VALUE, 67 | "Hello, World".getBytes())); 68 | assertThat(service.load("foo.txt")).exists(); 69 | } 70 | 71 | @Test 72 | public void saveRelativePathNotPermitted() { 73 | assertThrows(StorageException.class, () -> { 74 | service.store(new MockMultipartFile("foo", "../foo.txt", 75 | MediaType.TEXT_PLAIN_VALUE, "Hello, World".getBytes())); 76 | }); 77 | } 78 | 79 | @Test 80 | public void saveAbsolutePathNotPermitted() { 81 | assertThrows(StorageException.class, () -> { 82 | service.store(new MockMultipartFile("foo", "/etc/passwd", 83 | MediaType.TEXT_PLAIN_VALUE, "Hello, World".getBytes())); 84 | }); 85 | } 86 | 87 | @Test 88 | @EnabledOnOs({OS.LINUX}) 89 | public void saveAbsolutePathInFilenamePermitted() { 90 | //Unix file systems (e.g. ext4) allows backslash '\' in file names. 91 | String fileName="\\etc\\passwd"; 92 | service.store(new MockMultipartFile(fileName, fileName, 93 | MediaType.TEXT_PLAIN_VALUE, "Hello, World".getBytes())); 94 | assertTrue(Files.exists( 95 | Paths.get(properties.getLocation()).resolve(Paths.get(fileName)))); 96 | } 97 | 98 | @Test 99 | public void savePermitted() { 100 | service.store(new MockMultipartFile("foo", "bar/../foo.txt", 101 | MediaType.TEXT_PLAIN_VALUE, "Hello, World".getBytes())); 102 | } 103 | 104 | } 105 | -------------------------------------------------------------------------------- /complete/src/test/resources/com/example/uploadingfiles/testupload.txt: -------------------------------------------------------------------------------- 1 | Spring Framework -------------------------------------------------------------------------------- /initial/.mvn/wrapper/maven-wrapper.jar: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/spring-guides/gs-uploading-files/0bd41221f63af049e5b4cd16a2748b1ab1dcce76/initial/.mvn/wrapper/maven-wrapper.jar -------------------------------------------------------------------------------- /initial/.mvn/wrapper/maven-wrapper.properties: -------------------------------------------------------------------------------- 1 | distributionUrl=https://repo.maven.apache.org/maven2/org/apache/maven/apache-maven/3.6.3/apache-maven-3.6.3-bin.zip 2 | wrapperUrl=https://repo.maven.apache.org/maven2/io/takari/maven-wrapper/0.5.2/maven-wrapper-0.5.2.tar.gz 3 | -------------------------------------------------------------------------------- /initial/build.gradle: -------------------------------------------------------------------------------- 1 | plugins { 2 | id 'org.springframework.boot' version '3.3.0' 3 | id 'java' 4 | } 5 | 6 | apply plugin: 'io.spring.dependency-management' 7 | 8 | group = 'com.example' 9 | version = '0.0.1-SNAPSHOT' 10 | sourceCompatibility = '17' 11 | 12 | repositories { 13 | mavenCentral() 14 | } 15 | 16 | dependencies { 17 | implementation 'org.springframework.boot:spring-boot-starter-thymeleaf' 18 | implementation 'org.springframework.boot:spring-boot-starter-web' 19 | testImplementation('org.springframework.boot:spring-boot-starter-test') 20 | } 21 | 22 | test { 23 | useJUnitPlatform() 24 | } 25 | -------------------------------------------------------------------------------- /initial/gradle/wrapper/gradle-wrapper.jar: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/spring-guides/gs-uploading-files/0bd41221f63af049e5b4cd16a2748b1ab1dcce76/initial/gradle/wrapper/gradle-wrapper.jar -------------------------------------------------------------------------------- /initial/gradle/wrapper/gradle-wrapper.properties: -------------------------------------------------------------------------------- 1 | distributionBase=GRADLE_USER_HOME 2 | distributionPath=wrapper/dists 3 | distributionUrl=https\://services.gradle.org/distributions/gradle-8.7-bin.zip 4 | networkTimeout=10000 5 | validateDistributionUrl=true 6 | zipStoreBase=GRADLE_USER_HOME 7 | zipStorePath=wrapper/dists 8 | -------------------------------------------------------------------------------- /initial/gradlew: -------------------------------------------------------------------------------- 1 | #!/bin/sh 2 | 3 | # 4 | # Copyright © 2015-2021 the original authors. 5 | # 6 | # Licensed under the Apache License, Version 2.0 (the "License"); 7 | # you may not use this file except in compliance with the License. 8 | # You may obtain a copy of the License at 9 | # 10 | # https://www.apache.org/licenses/LICENSE-2.0 11 | # 12 | # Unless required by applicable law or agreed to in writing, software 13 | # distributed under the License is distributed on an "AS IS" BASIS, 14 | # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. 15 | # See the License for the specific language governing permissions and 16 | # limitations under the License. 17 | # 18 | 19 | ############################################################################## 20 | # 21 | # Gradle start up script for POSIX generated by Gradle. 22 | # 23 | # Important for running: 24 | # 25 | # (1) You need a POSIX-compliant shell to run this script. If your /bin/sh is 26 | # noncompliant, but you have some other compliant shell such as ksh or 27 | # bash, then to run this script, type that shell name before the whole 28 | # command line, like: 29 | # 30 | # ksh Gradle 31 | # 32 | # Busybox and similar reduced shells will NOT work, because this script 33 | # requires all of these POSIX shell features: 34 | # * functions; 35 | # * expansions «$var», «${var}», «${var:-default}», «${var+SET}», 36 | # «${var#prefix}», «${var%suffix}», and «$( cmd )»; 37 | # * compound commands having a testable exit status, especially «case»; 38 | # * various built-in commands including «command», «set», and «ulimit». 39 | # 40 | # Important for patching: 41 | # 42 | # (2) This script targets any POSIX shell, so it avoids extensions provided 43 | # by Bash, Ksh, etc; in particular arrays are avoided. 44 | # 45 | # The "traditional" practice of packing multiple parameters into a 46 | # space-separated string is a well documented source of bugs and security 47 | # problems, so this is (mostly) avoided, by progressively accumulating 48 | # options in "$@", and eventually passing that to Java. 49 | # 50 | # Where the inherited environment variables (DEFAULT_JVM_OPTS, JAVA_OPTS, 51 | # and GRADLE_OPTS) rely on word-splitting, this is performed explicitly; 52 | # see the in-line comments for details. 53 | # 54 | # There are tweaks for specific operating systems such as AIX, CygWin, 55 | # Darwin, MinGW, and NonStop. 56 | # 57 | # (3) This script is generated from the Groovy template 58 | # https://github.com/gradle/gradle/blob/HEAD/subprojects/plugins/src/main/resources/org/gradle/api/internal/plugins/unixStartScript.txt 59 | # within the Gradle project. 60 | # 61 | # You can find Gradle at https://github.com/gradle/gradle/. 62 | # 63 | ############################################################################## 64 | 65 | # Attempt to set APP_HOME 66 | 67 | # Resolve links: $0 may be a link 68 | app_path=$0 69 | 70 | # Need this for daisy-chained symlinks. 71 | while 72 | APP_HOME=${app_path%"${app_path##*/}"} # leaves a trailing /; empty if no leading path 73 | [ -h "$app_path" ] 74 | do 75 | ls=$( ls -ld "$app_path" ) 76 | link=${ls#*' -> '} 77 | case $link in #( 78 | /*) app_path=$link ;; #( 79 | *) app_path=$APP_HOME$link ;; 80 | esac 81 | done 82 | 83 | # This is normally unused 84 | # shellcheck disable=SC2034 85 | APP_BASE_NAME=${0##*/} 86 | # Discard cd standard output in case $CDPATH is set (https://github.com/gradle/gradle/issues/25036) 87 | APP_HOME=$( cd "${APP_HOME:-./}" > /dev/null && pwd -P ) || exit 88 | 89 | # Use the maximum available, or set MAX_FD != -1 to use that value. 90 | MAX_FD=maximum 91 | 92 | warn () { 93 | echo "$*" 94 | } >&2 95 | 96 | die () { 97 | echo 98 | echo "$*" 99 | echo 100 | exit 1 101 | } >&2 102 | 103 | # OS specific support (must be 'true' or 'false'). 104 | cygwin=false 105 | msys=false 106 | darwin=false 107 | nonstop=false 108 | case "$( uname )" in #( 109 | CYGWIN* ) cygwin=true ;; #( 110 | Darwin* ) darwin=true ;; #( 111 | MSYS* | MINGW* ) msys=true ;; #( 112 | NONSTOP* ) nonstop=true ;; 113 | esac 114 | 115 | CLASSPATH=$APP_HOME/gradle/wrapper/gradle-wrapper.jar 116 | 117 | 118 | # Determine the Java command to use to start the JVM. 119 | if [ -n "$JAVA_HOME" ] ; then 120 | if [ -x "$JAVA_HOME/jre/sh/java" ] ; then 121 | # IBM's JDK on AIX uses strange locations for the executables 122 | JAVACMD=$JAVA_HOME/jre/sh/java 123 | else 124 | JAVACMD=$JAVA_HOME/bin/java 125 | fi 126 | if [ ! -x "$JAVACMD" ] ; then 127 | die "ERROR: JAVA_HOME is set to an invalid directory: $JAVA_HOME 128 | 129 | Please set the JAVA_HOME variable in your environment to match the 130 | location of your Java installation." 131 | fi 132 | else 133 | JAVACMD=java 134 | if ! command -v java >/dev/null 2>&1 135 | then 136 | die "ERROR: JAVA_HOME is not set and no 'java' command could be found in your PATH. 137 | 138 | Please set the JAVA_HOME variable in your environment to match the 139 | location of your Java installation." 140 | fi 141 | fi 142 | 143 | # Increase the maximum file descriptors if we can. 144 | if ! "$cygwin" && ! "$darwin" && ! "$nonstop" ; then 145 | case $MAX_FD in #( 146 | max*) 147 | # In POSIX sh, ulimit -H is undefined. That's why the result is checked to see if it worked. 148 | # shellcheck disable=SC2039,SC3045 149 | MAX_FD=$( ulimit -H -n ) || 150 | warn "Could not query maximum file descriptor limit" 151 | esac 152 | case $MAX_FD in #( 153 | '' | soft) :;; #( 154 | *) 155 | # In POSIX sh, ulimit -n is undefined. That's why the result is checked to see if it worked. 156 | # shellcheck disable=SC2039,SC3045 157 | ulimit -n "$MAX_FD" || 158 | warn "Could not set maximum file descriptor limit to $MAX_FD" 159 | esac 160 | fi 161 | 162 | # Collect all arguments for the java command, stacking in reverse order: 163 | # * args from the command line 164 | # * the main class name 165 | # * -classpath 166 | # * -D...appname settings 167 | # * --module-path (only if needed) 168 | # * DEFAULT_JVM_OPTS, JAVA_OPTS, and GRADLE_OPTS environment variables. 169 | 170 | # For Cygwin or MSYS, switch paths to Windows format before running java 171 | if "$cygwin" || "$msys" ; then 172 | APP_HOME=$( cygpath --path --mixed "$APP_HOME" ) 173 | CLASSPATH=$( cygpath --path --mixed "$CLASSPATH" ) 174 | 175 | JAVACMD=$( cygpath --unix "$JAVACMD" ) 176 | 177 | # Now convert the arguments - kludge to limit ourselves to /bin/sh 178 | for arg do 179 | if 180 | case $arg in #( 181 | -*) false ;; # don't mess with options #( 182 | /?*) t=${arg#/} t=/${t%%/*} # looks like a POSIX filepath 183 | [ -e "$t" ] ;; #( 184 | *) false ;; 185 | esac 186 | then 187 | arg=$( cygpath --path --ignore --mixed "$arg" ) 188 | fi 189 | # Roll the args list around exactly as many times as the number of 190 | # args, so each arg winds up back in the position where it started, but 191 | # possibly modified. 192 | # 193 | # NB: a `for` loop captures its iteration list before it begins, so 194 | # changing the positional parameters here affects neither the number of 195 | # iterations, nor the values presented in `arg`. 196 | shift # remove old arg 197 | set -- "$@" "$arg" # push replacement arg 198 | done 199 | fi 200 | 201 | 202 | # Add default JVM options here. You can also use JAVA_OPTS and GRADLE_OPTS to pass JVM options to this script. 203 | DEFAULT_JVM_OPTS='"-Xmx64m" "-Xms64m"' 204 | 205 | # Collect all arguments for the java command: 206 | # * DEFAULT_JVM_OPTS, JAVA_OPTS, JAVA_OPTS, and optsEnvironmentVar are not allowed to contain shell fragments, 207 | # and any embedded shellness will be escaped. 208 | # * For example: A user cannot expect ${Hostname} to be expanded, as it is an environment variable and will be 209 | # treated as '${Hostname}' itself on the command line. 210 | 211 | set -- \ 212 | "-Dorg.gradle.appname=$APP_BASE_NAME" \ 213 | -classpath "$CLASSPATH" \ 214 | org.gradle.wrapper.GradleWrapperMain \ 215 | "$@" 216 | 217 | # Stop when "xargs" is not available. 218 | if ! command -v xargs >/dev/null 2>&1 219 | then 220 | die "xargs is not available" 221 | fi 222 | 223 | # Use "xargs" to parse quoted args. 224 | # 225 | # With -n1 it outputs one arg per line, with the quotes and backslashes removed. 226 | # 227 | # In Bash we could simply go: 228 | # 229 | # readarray ARGS < <( xargs -n1 <<<"$var" ) && 230 | # set -- "${ARGS[@]}" "$@" 231 | # 232 | # but POSIX shell has neither arrays nor command substitution, so instead we 233 | # post-process each arg (as a line of input to sed) to backslash-escape any 234 | # character that might be a shell metacharacter, then use eval to reverse 235 | # that process (while maintaining the separation between arguments), and wrap 236 | # the whole thing up as a single "set" statement. 237 | # 238 | # This will of course break if any of these variables contains a newline or 239 | # an unmatched quote. 240 | # 241 | 242 | eval "set -- $( 243 | printf '%s\n' "$DEFAULT_JVM_OPTS $JAVA_OPTS $GRADLE_OPTS" | 244 | xargs -n1 | 245 | sed ' s~[^-[:alnum:]+,./:=@_]~\\&~g; ' | 246 | tr '\n' ' ' 247 | )" '"$@"' 248 | 249 | exec "$JAVACMD" "$@" 250 | -------------------------------------------------------------------------------- /initial/gradlew.bat: -------------------------------------------------------------------------------- 1 | @rem 2 | @rem Copyright 2015 the original author or authors. 3 | @rem 4 | @rem Licensed under the Apache License, Version 2.0 (the "License"); 5 | @rem you may not use this file except in compliance with the License. 6 | @rem You may obtain a copy of the License at 7 | @rem 8 | @rem https://www.apache.org/licenses/LICENSE-2.0 9 | @rem 10 | @rem Unless required by applicable law or agreed to in writing, software 11 | @rem distributed under the License is distributed on an "AS IS" BASIS, 12 | @rem WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. 13 | @rem See the License for the specific language governing permissions and 14 | @rem limitations under the License. 15 | @rem 16 | 17 | @if "%DEBUG%"=="" @echo off 18 | @rem ########################################################################## 19 | @rem 20 | @rem Gradle startup script for Windows 21 | @rem 22 | @rem ########################################################################## 23 | 24 | @rem Set local scope for the variables with windows NT shell 25 | if "%OS%"=="Windows_NT" setlocal 26 | 27 | set DIRNAME=%~dp0 28 | if "%DIRNAME%"=="" set DIRNAME=. 29 | @rem This is normally unused 30 | set APP_BASE_NAME=%~n0 31 | set APP_HOME=%DIRNAME% 32 | 33 | @rem Resolve any "." and ".." in APP_HOME to make it shorter. 34 | for %%i in ("%APP_HOME%") do set APP_HOME=%%~fi 35 | 36 | @rem Add default JVM options here. You can also use JAVA_OPTS and GRADLE_OPTS to pass JVM options to this script. 37 | set DEFAULT_JVM_OPTS="-Xmx64m" "-Xms64m" 38 | 39 | @rem Find java.exe 40 | if defined JAVA_HOME goto findJavaFromJavaHome 41 | 42 | set JAVA_EXE=java.exe 43 | %JAVA_EXE% -version >NUL 2>&1 44 | if %ERRORLEVEL% equ 0 goto execute 45 | 46 | echo. 1>&2 47 | echo ERROR: JAVA_HOME is not set and no 'java' command could be found in your PATH. 1>&2 48 | echo. 1>&2 49 | echo Please set the JAVA_HOME variable in your environment to match the 1>&2 50 | echo location of your Java installation. 1>&2 51 | 52 | goto fail 53 | 54 | :findJavaFromJavaHome 55 | set JAVA_HOME=%JAVA_HOME:"=% 56 | set JAVA_EXE=%JAVA_HOME%/bin/java.exe 57 | 58 | if exist "%JAVA_EXE%" goto execute 59 | 60 | echo. 1>&2 61 | echo ERROR: JAVA_HOME is set to an invalid directory: %JAVA_HOME% 1>&2 62 | echo. 1>&2 63 | echo Please set the JAVA_HOME variable in your environment to match the 1>&2 64 | echo location of your Java installation. 1>&2 65 | 66 | goto fail 67 | 68 | :execute 69 | @rem Setup the command line 70 | 71 | set CLASSPATH=%APP_HOME%\gradle\wrapper\gradle-wrapper.jar 72 | 73 | 74 | @rem Execute Gradle 75 | "%JAVA_EXE%" %DEFAULT_JVM_OPTS% %JAVA_OPTS% %GRADLE_OPTS% "-Dorg.gradle.appname=%APP_BASE_NAME%" -classpath "%CLASSPATH%" org.gradle.wrapper.GradleWrapperMain %* 76 | 77 | :end 78 | @rem End local scope for the variables with windows NT shell 79 | if %ERRORLEVEL% equ 0 goto mainEnd 80 | 81 | :fail 82 | rem Set variable GRADLE_EXIT_CONSOLE if you need the _script_ return code instead of 83 | rem the _cmd.exe /c_ return code! 84 | set EXIT_CODE=%ERRORLEVEL% 85 | if %EXIT_CODE% equ 0 set EXIT_CODE=1 86 | if not ""=="%GRADLE_EXIT_CONSOLE%" exit %EXIT_CODE% 87 | exit /b %EXIT_CODE% 88 | 89 | :mainEnd 90 | if "%OS%"=="Windows_NT" endlocal 91 | 92 | :omega 93 | -------------------------------------------------------------------------------- /initial/mvnw: -------------------------------------------------------------------------------- 1 | #!/bin/sh 2 | # ---------------------------------------------------------------------------- 3 | # Licensed to the Apache Software Foundation (ASF) under one 4 | # or more contributor license agreements. See the NOTICE file 5 | # distributed with this work for additional information 6 | # regarding copyright ownership. The ASF licenses this file 7 | # to you under the Apache License, Version 2.0 (the 8 | # "License"); you may not use this file except in compliance 9 | # with the License. You may obtain a copy of the License at 10 | # 11 | # http://www.apache.org/licenses/LICENSE-2.0 12 | # 13 | # Unless required by applicable law or agreed to in writing, 14 | # software distributed under the License is distributed on an 15 | # "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY 16 | # KIND, either express or implied. See the License for the 17 | # specific language governing permissions and limitations 18 | # under the License. 19 | # ---------------------------------------------------------------------------- 20 | 21 | # ---------------------------------------------------------------------------- 22 | # Maven2 Start Up Batch script 23 | # 24 | # Required ENV vars: 25 | # ------------------ 26 | # JAVA_HOME - location of a JDK home dir 27 | # 28 | # Optional ENV vars 29 | # ----------------- 30 | # M2_HOME - location of maven2's installed home dir 31 | # MAVEN_OPTS - parameters passed to the Java VM when running Maven 32 | # e.g. to debug Maven itself, use 33 | # set MAVEN_OPTS=-Xdebug -Xrunjdwp:transport=dt_socket,server=y,suspend=y,address=8000 34 | # MAVEN_SKIP_RC - flag to disable loading of mavenrc files 35 | # ---------------------------------------------------------------------------- 36 | 37 | if [ -z "$MAVEN_SKIP_RC" ] ; then 38 | 39 | if [ -f /etc/mavenrc ] ; then 40 | . /etc/mavenrc 41 | fi 42 | 43 | if [ -f "$HOME/.mavenrc" ] ; then 44 | . "$HOME/.mavenrc" 45 | fi 46 | 47 | fi 48 | 49 | # OS specific support. $var _must_ be set to either true or false. 50 | cygwin=false; 51 | darwin=false; 52 | mingw=false 53 | case "`uname`" in 54 | CYGWIN*) cygwin=true ;; 55 | MINGW*) mingw=true;; 56 | Darwin*) darwin=true 57 | # Use /usr/libexec/java_home if available, otherwise fall back to /Library/Java/Home 58 | # See https://developer.apple.com/library/mac/qa/qa1170/_index.html 59 | if [ -z "$JAVA_HOME" ]; then 60 | if [ -x "/usr/libexec/java_home" ]; then 61 | export JAVA_HOME="`/usr/libexec/java_home`" 62 | else 63 | export JAVA_HOME="/Library/Java/Home" 64 | fi 65 | fi 66 | ;; 67 | esac 68 | 69 | if [ -z "$JAVA_HOME" ] ; then 70 | if [ -r /etc/gentoo-release ] ; then 71 | JAVA_HOME=`java-config --jre-home` 72 | fi 73 | fi 74 | 75 | if [ -z "$M2_HOME" ] ; then 76 | ## resolve links - $0 may be a link to maven's home 77 | PRG="$0" 78 | 79 | # need this for relative symlinks 80 | while [ -h "$PRG" ] ; do 81 | ls=`ls -ld "$PRG"` 82 | link=`expr "$ls" : '.*-> \(.*\)$'` 83 | if expr "$link" : '/.*' > /dev/null; then 84 | PRG="$link" 85 | else 86 | PRG="`dirname "$PRG"`/$link" 87 | fi 88 | done 89 | 90 | saveddir=`pwd` 91 | 92 | M2_HOME=`dirname "$PRG"`/.. 93 | 94 | # make it fully qualified 95 | M2_HOME=`cd "$M2_HOME" && pwd` 96 | 97 | cd "$saveddir" 98 | # echo Using m2 at $M2_HOME 99 | fi 100 | 101 | # For Cygwin, ensure paths are in UNIX format before anything is touched 102 | if $cygwin ; then 103 | [ -n "$M2_HOME" ] && 104 | M2_HOME=`cygpath --unix "$M2_HOME"` 105 | [ -n "$JAVA_HOME" ] && 106 | JAVA_HOME=`cygpath --unix "$JAVA_HOME"` 107 | [ -n "$CLASSPATH" ] && 108 | CLASSPATH=`cygpath --path --unix "$CLASSPATH"` 109 | fi 110 | 111 | # For Mingw, ensure paths are in UNIX format before anything is touched 112 | if $mingw ; then 113 | [ -n "$M2_HOME" ] && 114 | M2_HOME="`(cd "$M2_HOME"; pwd)`" 115 | [ -n "$JAVA_HOME" ] && 116 | JAVA_HOME="`(cd "$JAVA_HOME"; pwd)`" 117 | fi 118 | 119 | if [ -z "$JAVA_HOME" ]; then 120 | javaExecutable="`which javac`" 121 | if [ -n "$javaExecutable" ] && ! [ "`expr \"$javaExecutable\" : '\([^ ]*\)'`" = "no" ]; then 122 | # readlink(1) is not available as standard on Solaris 10. 123 | readLink=`which readlink` 124 | if [ ! `expr "$readLink" : '\([^ ]*\)'` = "no" ]; then 125 | if $darwin ; then 126 | javaHome="`dirname \"$javaExecutable\"`" 127 | javaExecutable="`cd \"$javaHome\" && pwd -P`/javac" 128 | else 129 | javaExecutable="`readlink -f \"$javaExecutable\"`" 130 | fi 131 | javaHome="`dirname \"$javaExecutable\"`" 132 | javaHome=`expr "$javaHome" : '\(.*\)/bin'` 133 | JAVA_HOME="$javaHome" 134 | export JAVA_HOME 135 | fi 136 | fi 137 | fi 138 | 139 | if [ -z "$JAVACMD" ] ; then 140 | if [ -n "$JAVA_HOME" ] ; then 141 | if [ -x "$JAVA_HOME/jre/sh/java" ] ; then 142 | # IBM's JDK on AIX uses strange locations for the executables 143 | JAVACMD="$JAVA_HOME/jre/sh/java" 144 | else 145 | JAVACMD="$JAVA_HOME/bin/java" 146 | fi 147 | else 148 | JAVACMD="`which java`" 149 | fi 150 | fi 151 | 152 | if [ ! -x "$JAVACMD" ] ; then 153 | echo "Error: JAVA_HOME is not defined correctly." >&2 154 | echo " We cannot execute $JAVACMD" >&2 155 | exit 1 156 | fi 157 | 158 | if [ -z "$JAVA_HOME" ] ; then 159 | echo "Warning: JAVA_HOME environment variable is not set." 160 | fi 161 | 162 | CLASSWORLDS_LAUNCHER=org.codehaus.plexus.classworlds.launcher.Launcher 163 | 164 | # traverses directory structure from process work directory to filesystem root 165 | # first directory with .mvn subdirectory is considered project base directory 166 | find_maven_basedir() { 167 | 168 | if [ -z "$1" ] 169 | then 170 | echo "Path not specified to find_maven_basedir" 171 | return 1 172 | fi 173 | 174 | basedir="$1" 175 | wdir="$1" 176 | while [ "$wdir" != '/' ] ; do 177 | if [ -d "$wdir"/.mvn ] ; then 178 | basedir=$wdir 179 | break 180 | fi 181 | # workaround for JBEAP-8937 (on Solaris 10/Sparc) 182 | if [ -d "${wdir}" ]; then 183 | wdir=`cd "$wdir/.."; pwd` 184 | fi 185 | # end of workaround 186 | done 187 | echo "${basedir}" 188 | } 189 | 190 | # concatenates all lines of a file 191 | concat_lines() { 192 | if [ -f "$1" ]; then 193 | echo "$(tr -s '\n' ' ' < "$1")" 194 | fi 195 | } 196 | 197 | BASE_DIR=`find_maven_basedir "$(pwd)"` 198 | if [ -z "$BASE_DIR" ]; then 199 | exit 1; 200 | fi 201 | 202 | ########################################################################################## 203 | # Extension to allow automatically downloading the maven-wrapper.jar from Maven-central 204 | # This allows using the maven wrapper in projects that prohibit checking in binary data. 205 | ########################################################################################## 206 | if [ -r "$BASE_DIR/.mvn/wrapper/maven-wrapper.jar" ]; then 207 | if [ "$MVNW_VERBOSE" = true ]; then 208 | echo "Found .mvn/wrapper/maven-wrapper.jar" 209 | fi 210 | else 211 | if [ "$MVNW_VERBOSE" = true ]; then 212 | echo "Couldn't find .mvn/wrapper/maven-wrapper.jar, downloading it ..." 213 | fi 214 | if [ "$MVNW_REPOURL" = true]; then 215 | jarUrl="$MVNW_REPOURL/io/takari/maven-wrapper/0.5.2/maven-wrapper-0.5.2.jar" 216 | else 217 | jarUrl="https://repo.maven.apache.org/maven2/io/takari/maven-wrapper/0.5.2/maven-wrapper-0.5.2.jar" 218 | fi 219 | while IFS="=" read key value; do 220 | case "$key" in (wrapperUrl) jarUrl="$value"; break ;; 221 | esac 222 | done < "$BASE_DIR/.mvn/wrapper/maven-wrapper.properties" 223 | if [ "$MVNW_VERBOSE" = true ]; then 224 | echo "Downloading from: $jarUrl" 225 | fi 226 | wrapperJarPath="$BASE_DIR/.mvn/wrapper/maven-wrapper.jar" 227 | if $cygwin; then 228 | wrapperJarPath=`cygpath --path --windows "$wrapperJarPath"` 229 | fi 230 | 231 | if command -v wget > /dev/null; then 232 | if [ "$MVNW_VERBOSE" = true ]; then 233 | echo "Found wget ... using wget" 234 | fi 235 | if [ -z "$MVNW_USERNAME" ] || [ -z "$MVNW_PASSWORD" ]; then 236 | wget "$jarUrl" -O "$wrapperJarPath" 237 | else 238 | wget --http-user=$MVNW_USERNAME --http-password=$MVNW_PASSWORD "$jarUrl" -O "$wrapperJarPath" 239 | fi 240 | elif command -v curl > /dev/null; then 241 | if [ "$MVNW_VERBOSE" = true ]; then 242 | echo "Found curl ... using curl" 243 | fi 244 | if [ -z "$MVNW_USERNAME" ] || [ -z "$MVNW_PASSWORD" ]; then 245 | curl -o "$wrapperJarPath" "$jarUrl" -f 246 | else 247 | curl --user $MVNW_USERNAME:$MVNW_PASSWORD -o "$wrapperJarPath" "$jarUrl" -f 248 | fi 249 | 250 | else 251 | if [ "$MVNW_VERBOSE" = true ]; then 252 | echo "Falling back to using Java to download" 253 | fi 254 | javaClass="$BASE_DIR/.mvn/wrapper/MavenWrapperDownloader.java" 255 | # For Cygwin, switch paths to Windows format before running javac 256 | if $cygwin; then 257 | javaClass=`cygpath --path --windows "$javaClass"` 258 | fi 259 | if [ -e "$javaClass" ]; then 260 | if [ ! -e "$BASE_DIR/.mvn/wrapper/MavenWrapperDownloader.class" ]; then 261 | if [ "$MVNW_VERBOSE" = true ]; then 262 | echo " - Compiling MavenWrapperDownloader.java ..." 263 | fi 264 | # Compiling the Java class 265 | ("$JAVA_HOME/bin/javac" "$javaClass") 266 | fi 267 | if [ -e "$BASE_DIR/.mvn/wrapper/MavenWrapperDownloader.class" ]; then 268 | # Running the downloader 269 | if [ "$MVNW_VERBOSE" = true ]; then 270 | echo " - Running MavenWrapperDownloader.java ..." 271 | fi 272 | ("$JAVA_HOME/bin/java" -cp .mvn/wrapper MavenWrapperDownloader "$MAVEN_PROJECTBASEDIR") 273 | fi 274 | fi 275 | fi 276 | fi 277 | ########################################################################################## 278 | # End of extension 279 | ########################################################################################## 280 | 281 | export MAVEN_PROJECTBASEDIR=${MAVEN_BASEDIR:-"$BASE_DIR"} 282 | if [ "$MVNW_VERBOSE" = true ]; then 283 | echo $MAVEN_PROJECTBASEDIR 284 | fi 285 | MAVEN_OPTS="$(concat_lines "$MAVEN_PROJECTBASEDIR/.mvn/jvm.config") $MAVEN_OPTS" 286 | 287 | # For Cygwin, switch paths to Windows format before running java 288 | if $cygwin; then 289 | [ -n "$M2_HOME" ] && 290 | M2_HOME=`cygpath --path --windows "$M2_HOME"` 291 | [ -n "$JAVA_HOME" ] && 292 | JAVA_HOME=`cygpath --path --windows "$JAVA_HOME"` 293 | [ -n "$CLASSPATH" ] && 294 | CLASSPATH=`cygpath --path --windows "$CLASSPATH"` 295 | [ -n "$MAVEN_PROJECTBASEDIR" ] && 296 | MAVEN_PROJECTBASEDIR=`cygpath --path --windows "$MAVEN_PROJECTBASEDIR"` 297 | fi 298 | 299 | WRAPPER_LAUNCHER=org.apache.maven.wrapper.MavenWrapperMain 300 | 301 | exec "$JAVACMD" \ 302 | $MAVEN_OPTS \ 303 | -classpath "$MAVEN_PROJECTBASEDIR/.mvn/wrapper/maven-wrapper.jar" \ 304 | "-Dmaven.home=${M2_HOME}" "-Dmaven.multiModuleProjectDirectory=${MAVEN_PROJECTBASEDIR}" \ 305 | ${WRAPPER_LAUNCHER} $MAVEN_CONFIG "$@" 306 | -------------------------------------------------------------------------------- /initial/mvnw.cmd: -------------------------------------------------------------------------------- 1 | @REM ---------------------------------------------------------------------------- 2 | @REM Licensed to the Apache Software Foundation (ASF) under one 3 | @REM or more contributor license agreements. See the NOTICE file 4 | @REM distributed with this work for additional information 5 | @REM regarding copyright ownership. The ASF licenses this file 6 | @REM to you under the Apache License, Version 2.0 (the 7 | @REM "License"); you may not use this file except in compliance 8 | @REM with the License. You may obtain a copy of the License at 9 | @REM 10 | @REM http://www.apache.org/licenses/LICENSE-2.0 11 | @REM 12 | @REM Unless required by applicable law or agreed to in writing, 13 | @REM software distributed under the License is distributed on an 14 | @REM "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY 15 | @REM KIND, either express or implied. See the License for the 16 | @REM specific language governing permissions and limitations 17 | @REM under the License. 18 | @REM ---------------------------------------------------------------------------- 19 | 20 | @REM ---------------------------------------------------------------------------- 21 | @REM Maven2 Start Up Batch script 22 | @REM 23 | @REM Required ENV vars: 24 | @REM JAVA_HOME - location of a JDK home dir 25 | @REM 26 | @REM Optional ENV vars 27 | @REM M2_HOME - location of maven2's installed home dir 28 | @REM MAVEN_BATCH_ECHO - set to 'on' to enable the echoing of the batch commands 29 | @REM MAVEN_BATCH_PAUSE - set to 'on' to wait for a key stroke before ending 30 | @REM MAVEN_OPTS - parameters passed to the Java VM when running Maven 31 | @REM e.g. to debug Maven itself, use 32 | @REM set MAVEN_OPTS=-Xdebug -Xrunjdwp:transport=dt_socket,server=y,suspend=y,address=8000 33 | @REM MAVEN_SKIP_RC - flag to disable loading of mavenrc files 34 | @REM ---------------------------------------------------------------------------- 35 | 36 | @REM Begin all REM lines with '@' in case MAVEN_BATCH_ECHO is 'on' 37 | @echo off 38 | @REM set title of command window 39 | title %0 40 | @REM enable echoing my setting MAVEN_BATCH_ECHO to 'on' 41 | @if "%MAVEN_BATCH_ECHO%" == "on" echo %MAVEN_BATCH_ECHO% 42 | 43 | @REM set %HOME% to equivalent of $HOME 44 | if "%HOME%" == "" (set "HOME=%HOMEDRIVE%%HOMEPATH%") 45 | 46 | @REM Execute a user defined script before this one 47 | if not "%MAVEN_SKIP_RC%" == "" goto skipRcPre 48 | @REM check for pre script, once with legacy .bat ending and once with .cmd ending 49 | if exist "%HOME%\mavenrc_pre.bat" call "%HOME%\mavenrc_pre.bat" 50 | if exist "%HOME%\mavenrc_pre.cmd" call "%HOME%\mavenrc_pre.cmd" 51 | :skipRcPre 52 | 53 | @setlocal 54 | 55 | set ERROR_CODE=0 56 | 57 | @REM To isolate internal variables from possible post scripts, we use another setlocal 58 | @setlocal 59 | 60 | @REM ==== START VALIDATION ==== 61 | if not "%JAVA_HOME%" == "" goto OkJHome 62 | 63 | echo. 64 | echo Error: JAVA_HOME not found in your environment. >&2 65 | echo Please set the JAVA_HOME variable in your environment to match the >&2 66 | echo location of your Java installation. >&2 67 | echo. 68 | goto error 69 | 70 | :OkJHome 71 | if exist "%JAVA_HOME%\bin\java.exe" goto init 72 | 73 | echo. 74 | echo Error: JAVA_HOME is set to an invalid directory. >&2 75 | echo JAVA_HOME = "%JAVA_HOME%" >&2 76 | echo Please set the JAVA_HOME variable in your environment to match the >&2 77 | echo location of your Java installation. >&2 78 | echo. 79 | goto error 80 | 81 | @REM ==== END VALIDATION ==== 82 | 83 | :init 84 | 85 | @REM Find the project base dir, i.e. the directory that contains the folder ".mvn". 86 | @REM Fallback to current working directory if not found. 87 | 88 | set MAVEN_PROJECTBASEDIR=%MAVEN_BASEDIR% 89 | IF NOT "%MAVEN_PROJECTBASEDIR%"=="" goto endDetectBaseDir 90 | 91 | set EXEC_DIR=%CD% 92 | set WDIR=%EXEC_DIR% 93 | :findBaseDir 94 | IF EXIST "%WDIR%"\.mvn goto baseDirFound 95 | cd .. 96 | IF "%WDIR%"=="%CD%" goto baseDirNotFound 97 | set WDIR=%CD% 98 | goto findBaseDir 99 | 100 | :baseDirFound 101 | set MAVEN_PROJECTBASEDIR=%WDIR% 102 | cd "%EXEC_DIR%" 103 | goto endDetectBaseDir 104 | 105 | :baseDirNotFound 106 | set MAVEN_PROJECTBASEDIR=%EXEC_DIR% 107 | cd "%EXEC_DIR%" 108 | 109 | :endDetectBaseDir 110 | 111 | IF NOT EXIST "%MAVEN_PROJECTBASEDIR%\.mvn\jvm.config" goto endReadAdditionalConfig 112 | 113 | @setlocal EnableExtensions EnableDelayedExpansion 114 | for /F "usebackq delims=" %%a in ("%MAVEN_PROJECTBASEDIR%\.mvn\jvm.config") do set JVM_CONFIG_MAVEN_PROPS=!JVM_CONFIG_MAVEN_PROPS! %%a 115 | @endlocal & set JVM_CONFIG_MAVEN_PROPS=%JVM_CONFIG_MAVEN_PROPS% 116 | 117 | :endReadAdditionalConfig 118 | 119 | SET MAVEN_JAVA_EXE="%JAVA_HOME%\bin\java.exe" 120 | set WRAPPER_JAR="%MAVEN_PROJECTBASEDIR%\.mvn\wrapper\maven-wrapper.jar" 121 | set WRAPPER_LAUNCHER=org.apache.maven.wrapper.MavenWrapperMain 122 | 123 | set DOWNLOAD_URL="https://repo.maven.apache.org/maven2/io/takari/maven-wrapper/0.5.2/maven-wrapper-0.5.2.jar" 124 | 125 | FOR /F "tokens=1,2 delims==" %%A IN ("%MAVEN_PROJECTBASEDIR%\.mvn\wrapper\maven-wrapper.properties") DO ( 126 | IF "%%A"=="wrapperUrl" SET DOWNLOAD_URL=%%B 127 | ) 128 | 129 | @REM Extension to allow automatically downloading the maven-wrapper.jar from Maven-central 130 | @REM This allows using the maven wrapper in projects that prohibit checking in binary data. 131 | if exist %WRAPPER_JAR% ( 132 | echo Found %WRAPPER_JAR% 133 | ) else ( 134 | if not "%MVNW_REPOURL%" == "" ( 135 | SET DOWNLOAD_URL="%MVNW_REPOURL%/io/takari/maven-wrapper/0.5.2/maven-wrapper-0.5.2.jar" 136 | ) 137 | echo Couldn't find %WRAPPER_JAR%, downloading it ... 138 | echo Downloading from: %DOWNLOAD_URL% 139 | 140 | powershell -Command "&{"^ 141 | "$webclient = new-object System.Net.WebClient;"^ 142 | "if (-not ([string]::IsNullOrEmpty('%MVNW_USERNAME%') -and [string]::IsNullOrEmpty('%MVNW_PASSWORD%'))) {"^ 143 | "$webclient.Credentials = new-object System.Net.NetworkCredential('%MVNW_USERNAME%', '%MVNW_PASSWORD%');"^ 144 | "}"^ 145 | "[Net.ServicePointManager]::SecurityProtocol = [Net.SecurityProtocolType]::Tls12; $webclient.DownloadFile('%DOWNLOAD_URL%', '%WRAPPER_JAR%')"^ 146 | "}" 147 | echo Finished downloading %WRAPPER_JAR% 148 | ) 149 | @REM End of extension 150 | 151 | %MAVEN_JAVA_EXE% %JVM_CONFIG_MAVEN_PROPS% %MAVEN_OPTS% %MAVEN_DEBUG_OPTS% -classpath %WRAPPER_JAR% "-Dmaven.multiModuleProjectDirectory=%MAVEN_PROJECTBASEDIR%" %WRAPPER_LAUNCHER% %MAVEN_CONFIG% %* 152 | if ERRORLEVEL 1 goto error 153 | goto end 154 | 155 | :error 156 | set ERROR_CODE=1 157 | 158 | :end 159 | @endlocal & set ERROR_CODE=%ERROR_CODE% 160 | 161 | if not "%MAVEN_SKIP_RC%" == "" goto skipRcPost 162 | @REM check for post script, once with legacy .bat ending and once with .cmd ending 163 | if exist "%HOME%\mavenrc_post.bat" call "%HOME%\mavenrc_post.bat" 164 | if exist "%HOME%\mavenrc_post.cmd" call "%HOME%\mavenrc_post.cmd" 165 | :skipRcPost 166 | 167 | @REM pause the script if MAVEN_BATCH_PAUSE is set to 'on' 168 | if "%MAVEN_BATCH_PAUSE%" == "on" pause 169 | 170 | if "%MAVEN_TERMINATE_CMD%" == "on" exit %ERROR_CODE% 171 | 172 | exit /B %ERROR_CODE% 173 | -------------------------------------------------------------------------------- /initial/pom.xml: -------------------------------------------------------------------------------- 1 | 2 | 4 | 4.0.0 5 | 6 | org.springframework.boot 7 | spring-boot-starter-parent 8 | 3.3.0 9 | 10 | 11 | com.example 12 | uploading-files-initial 13 | 0.0.1-SNAPSHOT 14 | uploading-files-initial 15 | Demo project for Spring Boot 16 | 17 | 18 | 17 19 | 20 | 21 | 22 | 23 | org.springframework.boot 24 | spring-boot-starter-thymeleaf 25 | 26 | 27 | org.springframework.boot 28 | spring-boot-starter-web 29 | 30 | 31 | 32 | org.springframework.boot 33 | spring-boot-starter-test 34 | test 35 | 36 | 37 | 38 | 39 | 40 | 41 | org.springframework.boot 42 | spring-boot-maven-plugin 43 | 44 | 45 | 46 | 47 | 48 | -------------------------------------------------------------------------------- /initial/settings.gradle: -------------------------------------------------------------------------------- 1 | rootProject.name = 'uploading-files' 2 | -------------------------------------------------------------------------------- /initial/src/main/java/com/example/uploadingfiles/UploadingFilesApplication.java: -------------------------------------------------------------------------------- 1 | package com.example.uploadingfiles; 2 | 3 | import org.springframework.boot.SpringApplication; 4 | import org.springframework.boot.autoconfigure.SpringBootApplication; 5 | 6 | @SpringBootApplication 7 | public class UploadingFilesApplication { 8 | 9 | public static void main(String[] args) { 10 | SpringApplication.run(UploadingFilesApplication.class, args); 11 | } 12 | 13 | } 14 | -------------------------------------------------------------------------------- /initial/src/main/java/com/example/uploadingfiles/storage/FileSystemStorageService.java: -------------------------------------------------------------------------------- 1 | package com.example.uploadingfiles.storage; 2 | 3 | import org.springframework.beans.factory.annotation.Autowired; 4 | import org.springframework.core.io.Resource; 5 | import org.springframework.core.io.UrlResource; 6 | import org.springframework.stereotype.Service; 7 | import org.springframework.util.FileSystemUtils; 8 | import org.springframework.web.multipart.MultipartFile; 9 | 10 | import java.io.IOException; 11 | import java.net.MalformedURLException; 12 | import java.nio.file.Files; 13 | import java.nio.file.Path; 14 | import java.nio.file.Paths; 15 | import java.util.stream.Stream; 16 | 17 | @Service 18 | public class FileSystemStorageService implements StorageService { 19 | 20 | private final Path rootLocation; 21 | 22 | @Autowired 23 | public FileSystemStorageService(StorageProperties properties) { 24 | 25 | if(properties.getLocation().trim().length() == 0){ 26 | throw new StorageException("File upload location can not be Empty."); 27 | } 28 | 29 | this.rootLocation = Paths.get(properties.getLocation()); 30 | } 31 | 32 | @Override 33 | public void store(MultipartFile file) { 34 | try { 35 | if (file.isEmpty()) { 36 | throw new StorageException("Failed to store empty file " + file.getOriginalFilename()); 37 | } 38 | Files.copy(file.getInputStream(), this.rootLocation.resolve(file.getOriginalFilename())); 39 | } catch (IOException e) { 40 | throw new StorageException("Failed to store file " + file.getOriginalFilename(), e); 41 | } 42 | } 43 | 44 | @Override 45 | public Stream loadAll() { 46 | try { 47 | return Files.walk(this.rootLocation, 1) 48 | .filter(path -> !path.equals(this.rootLocation)) 49 | .map(path -> this.rootLocation.relativize(path)); 50 | } catch (IOException e) { 51 | throw new StorageException("Failed to read stored files", e); 52 | } 53 | 54 | } 55 | 56 | @Override 57 | public Path load(String filename) { 58 | return rootLocation.resolve(filename); 59 | } 60 | 61 | @Override 62 | public Resource loadAsResource(String filename) { 63 | try { 64 | Path file = load(filename); 65 | Resource resource = new UrlResource(file.toUri()); 66 | if(resource.exists() || resource.isReadable()) { 67 | return resource; 68 | } 69 | else { 70 | throw new StorageFileNotFoundException("Could not read file: " + filename); 71 | 72 | } 73 | } catch (MalformedURLException e) { 74 | throw new StorageFileNotFoundException("Could not read file: " + filename, e); 75 | } 76 | } 77 | 78 | @Override 79 | public void deleteAll() { 80 | FileSystemUtils.deleteRecursively(rootLocation.toFile()); 81 | } 82 | 83 | @Override 84 | public void init() { 85 | try { 86 | Files.createDirectory(rootLocation); 87 | } catch (IOException e) { 88 | throw new StorageException("Could not initialize storage", e); 89 | } 90 | } 91 | } 92 | -------------------------------------------------------------------------------- /initial/src/main/java/com/example/uploadingfiles/storage/StorageException.java: -------------------------------------------------------------------------------- 1 | package com.example.uploadingfiles.storage; 2 | 3 | public class StorageException extends RuntimeException { 4 | 5 | public StorageException(String message) { 6 | super(message); 7 | } 8 | 9 | public StorageException(String message, Throwable cause) { 10 | super(message, cause); 11 | } 12 | } 13 | -------------------------------------------------------------------------------- /initial/src/main/java/com/example/uploadingfiles/storage/StorageFileNotFoundException.java: -------------------------------------------------------------------------------- 1 | package com.example.uploadingfiles.storage; 2 | 3 | public class StorageFileNotFoundException extends StorageException { 4 | 5 | public StorageFileNotFoundException(String message) { 6 | super(message); 7 | } 8 | 9 | public StorageFileNotFoundException(String message, Throwable cause) { 10 | super(message, cause); 11 | } 12 | } 13 | -------------------------------------------------------------------------------- /initial/src/main/java/com/example/uploadingfiles/storage/StorageProperties.java: -------------------------------------------------------------------------------- 1 | package com.example.uploadingfiles.storage; 2 | 3 | import org.springframework.boot.context.properties.ConfigurationProperties; 4 | 5 | @ConfigurationProperties("storage") 6 | public class StorageProperties { 7 | 8 | /** 9 | * Folder location for storing files 10 | */ 11 | private String location = "upload-dir"; 12 | 13 | public String getLocation() { 14 | return location; 15 | } 16 | 17 | public void setLocation(String location) { 18 | this.location = location; 19 | } 20 | 21 | } 22 | -------------------------------------------------------------------------------- /initial/src/main/java/com/example/uploadingfiles/storage/StorageService.java: -------------------------------------------------------------------------------- 1 | package com.example.uploadingfiles.storage; 2 | 3 | import org.springframework.core.io.Resource; 4 | import org.springframework.web.multipart.MultipartFile; 5 | 6 | import java.nio.file.Path; 7 | import java.util.stream.Stream; 8 | 9 | public interface StorageService { 10 | 11 | void init(); 12 | 13 | void store(MultipartFile file); 14 | 15 | Stream loadAll(); 16 | 17 | Path load(String filename); 18 | 19 | Resource loadAsResource(String filename); 20 | 21 | void deleteAll(); 22 | 23 | } 24 | -------------------------------------------------------------------------------- /initial/src/main/resources/application.properties: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/spring-guides/gs-uploading-files/0bd41221f63af049e5b4cd16a2748b1ab1dcce76/initial/src/main/resources/application.properties --------------------------------------------------------------------------------