├── .gitignore
├── .openapi-generator-ignore
├── .openapi-generator
└── VERSION
├── .travis.yml
├── Dockerfile
├── LICENSE
├── README.md
├── pom.xml
└── src
└── main
├── java
└── org
│ └── openapitools
│ ├── OpenAPI2SpringBoot.java
│ ├── RFC3339DateFormat.java
│ ├── api
│ ├── ApiUtil.java
│ ├── ExceptionTranslator.java
│ ├── PetApiDelegateImpl.java
│ ├── StoreApiDelegateImpl.java
│ └── UserApiDelegateImpl.java
│ ├── configuration
│ ├── AuthorizationServerConfiguration.java
│ ├── HomeController.java
│ ├── OpenAPIConfiguration.java
│ ├── ResourceServerConfiguration.java
│ └── SecurityConfiguration.java
│ └── repository
│ ├── HashMapRepository.java
│ ├── OrderRepository.java
│ ├── PetRepository.java
│ └── UserRepository.java
└── resources
├── application.properties
├── openapi.yaml
└── public
└── index.html
/.gitignore:
--------------------------------------------------------------------------------
1 | ######################
2 | # Eclipse
3 | ######################
4 | *.pydevproject
5 | .project
6 | .metadata
7 | tmp/
8 | tmp/**/*
9 | *.tmp
10 | *.bak
11 | *.swp
12 | *~.nib
13 | local.properties
14 | .classpath
15 | .settings/
16 | .loadpath
17 | .factorypath
18 | /<%= SERVER_MAIN_RES_DIR %>rebel.xml
19 |
20 | # External tool builders
21 | .externalToolBuilders/**
22 |
23 | # Locally stored "Eclipse launch configurations"
24 | *.launch
25 |
26 | # CDT-specific
27 | .cproject
28 |
29 | # PDT-specific
30 | .buildpath
31 |
32 | ######################
33 | # Intellij
34 | ######################
35 | .idea/
36 | *.iml
37 | *.iws
38 | *.ipr
39 | *.ids
40 | *.orig
41 | classes/
42 | out/
43 |
44 | ######################
45 | # Visual Studio Code
46 | ######################
47 | .vscode/
48 |
49 | ######################
50 | # Maven
51 | ######################
52 | /log/
53 | /target/
54 |
55 | ######################
56 | # Package Files
57 | ######################
58 | *.jar
59 | *.war
60 | *.ear
61 | *.db
62 |
63 | ######################
64 | # Windows
65 | ######################
66 | # Windows image file caches
67 | Thumbs.db
68 |
69 | # Folder config file
70 | Desktop.ini
71 |
72 | ######################
73 | # Mac OSX
74 | ######################
75 | .DS_Store
76 | .svn
77 |
78 | # Thumbnails
79 | ._*
80 |
81 | # Files that might appear on external disk
82 | .Spotlight-V100
83 | .Trashes
84 |
85 | ######################
86 | # Directories
87 | ######################
88 | /bin/
89 | /deploy/
90 |
91 | ######################
92 | # Logs
93 | ######################
94 | *.log*
95 |
96 | ######################
97 | # Others
98 | ######################
99 | *.class
100 | *.*~
101 | *~
102 | .merge_file*
103 |
104 |
--------------------------------------------------------------------------------
/.openapi-generator-ignore:
--------------------------------------------------------------------------------
1 | # OpenAPI Generator Ignore
2 | # Generated by openapi-generator https://github.com/openapitools/openapi-generator
3 |
4 | # Use this file to prevent files from being overwritten by the generator.
5 | # The patterns follow closely to .gitignore or .dockerignore.
6 |
7 | # As an example, the C# client generator defines ApiClient.cs.
8 | # You can make changes and tell OpenAPI Generator to ignore just this file by uncommenting the following line:
9 | #ApiClient.cs
10 |
11 | # You can match any string of characters against a directory, file or extension with a single asterisk (*):
12 | #foo/*/qux
13 | # The above matches foo/bar/qux and foo/baz/qux, but not foo/bar/baz/qux
14 |
15 | # You can recursively match patterns against a directory, file or extension with a double asterisk (**):
16 | #foo/**/qux
17 | # This matches foo/bar/qux, foo/baz/qux, and foo/bar/baz/qux
18 |
19 | # You can also negate patterns with an exclamation (!).
20 | # For example, you can ignore all files in a docs folder with the file extension .md:
21 | #docs/*.md
22 | # Then explicitly reverse the ignore rule for a single file:
23 | #!docs/README.md
24 |
--------------------------------------------------------------------------------
/.openapi-generator/VERSION:
--------------------------------------------------------------------------------
1 | 3.0.0-SNAPSHOT
--------------------------------------------------------------------------------
/.travis.yml:
--------------------------------------------------------------------------------
1 | sudo: required
2 | language: java
3 | jdk:
4 | - openjdk8
5 | services:
6 | - docker
7 | cache:
8 | directories:
9 | - $HOME/.m2
10 |
11 | script:
12 | - mvn clean package
13 |
14 | before_deploy:
15 | - docker login -u $DOCKER_HUB_USERNAME -p $DOCKER_HUB_PASSWORD
16 | - docker build -t openapitools/openapi-petstore .
17 |
18 | deploy:
19 | provider: script
20 | script: docker push openapitools/openapi-petstore
21 | on:
22 | branch: master
--------------------------------------------------------------------------------
/Dockerfile:
--------------------------------------------------------------------------------
1 | FROM openjdk:8-jre-alpine
2 |
3 | WORKDIR /petstore
4 |
5 | ENV OPENAPI_BASE_PATH=/v3
6 |
7 | COPY target/openapi-petstore-3.0.0.jar /petstore/openapi-petstore.jar
8 |
9 | EXPOSE 8080
10 |
11 | CMD ["java", "-Dopenapi.openAPIPetstore.base-path=${OPENAPI_BASE_PATH}", "-jar", "/petstore/openapi-petstore.jar"]
12 |
--------------------------------------------------------------------------------
/LICENSE:
--------------------------------------------------------------------------------
1 | Apache License
2 | Version 2.0, January 2004
3 | http://www.apache.org/licenses/
4 |
5 | TERMS AND CONDITIONS FOR USE, REPRODUCTION, AND DISTRIBUTION
6 |
7 | 1. Definitions.
8 |
9 | "License" shall mean the terms and conditions for use, reproduction,
10 | and distribution as defined by Sections 1 through 9 of this document.
11 |
12 | "Licensor" shall mean the copyright owner or entity authorized by
13 | the copyright owner that is granting the License.
14 |
15 | "Legal Entity" shall mean the union of the acting entity and all
16 | other entities that control, are controlled by, or are under common
17 | control with that entity. For the purposes of this definition,
18 | "control" means (i) the power, direct or indirect, to cause the
19 | direction or management of such entity, whether by contract or
20 | otherwise, or (ii) ownership of fifty percent (50%) or more of the
21 | outstanding shares, or (iii) beneficial ownership of such entity.
22 |
23 | "You" (or "Your") shall mean an individual or Legal Entity
24 | exercising permissions granted by this License.
25 |
26 | "Source" form shall mean the preferred form for making modifications,
27 | including but not limited to software source code, documentation
28 | source, and configuration files.
29 |
30 | "Object" form shall mean any form resulting from mechanical
31 | transformation or translation of a Source form, including but
32 | not limited to compiled object code, generated documentation,
33 | and conversions to other media types.
34 |
35 | "Work" shall mean the work of authorship, whether in Source or
36 | Object form, made available under the License, as indicated by a
37 | copyright notice that is included in or attached to the work
38 | (an example is provided in the Appendix below).
39 |
40 | "Derivative Works" shall mean any work, whether in Source or Object
41 | form, that is based on (or derived from) the Work and for which the
42 | editorial revisions, annotations, elaborations, or other modifications
43 | represent, as a whole, an original work of authorship. For the purposes
44 | of this License, Derivative Works shall not include works that remain
45 | separable from, or merely link (or bind by name) to the interfaces of,
46 | the Work and Derivative Works thereof.
47 |
48 | "Contribution" shall mean any work of authorship, including
49 | the original version of the Work and any modifications or additions
50 | to that Work or Derivative Works thereof, that is intentionally
51 | submitted to Licensor for inclusion in the Work by the copyright owner
52 | or by an individual or Legal Entity authorized to submit on behalf of
53 | the copyright owner. For the purposes of this definition, "submitted"
54 | means any form of electronic, verbal, or written communication sent
55 | to the Licensor or its representatives, including but not limited to
56 | communication on electronic mailing lists, source code control systems,
57 | and issue tracking systems that are managed by, or on behalf of, the
58 | Licensor for the purpose of discussing and improving the Work, but
59 | excluding communication that is conspicuously marked or otherwise
60 | designated in writing by the copyright owner as "Not a Contribution."
61 |
62 | "Contributor" shall mean Licensor and any individual or Legal Entity
63 | on behalf of whom a Contribution has been received by Licensor and
64 | subsequently incorporated within the Work.
65 |
66 | 2. Grant of Copyright License. Subject to the terms and conditions of
67 | this License, each Contributor hereby grants to You a perpetual,
68 | worldwide, non-exclusive, no-charge, royalty-free, irrevocable
69 | copyright license to reproduce, prepare Derivative Works of,
70 | publicly display, publicly perform, sublicense, and distribute the
71 | Work and such Derivative Works in Source or Object form.
72 |
73 | 3. Grant of Patent License. Subject to the terms and conditions of
74 | this License, each Contributor hereby grants to You a perpetual,
75 | worldwide, non-exclusive, no-charge, royalty-free, irrevocable
76 | (except as stated in this section) patent license to make, have made,
77 | use, offer to sell, sell, import, and otherwise transfer the Work,
78 | where such license applies only to those patent claims licensable
79 | by such Contributor that are necessarily infringed by their
80 | Contribution(s) alone or by combination of their Contribution(s)
81 | with the Work to which such Contribution(s) was submitted. If You
82 | institute patent litigation against any entity (including a
83 | cross-claim or counterclaim in a lawsuit) alleging that the Work
84 | or a Contribution incorporated within the Work constitutes direct
85 | or contributory patent infringement, then any patent licenses
86 | granted to You under this License for that Work shall terminate
87 | as of the date such litigation is filed.
88 |
89 | 4. Redistribution. You may reproduce and distribute copies of the
90 | Work or Derivative Works thereof in any medium, with or without
91 | modifications, and in Source or Object form, provided that You
92 | meet the following conditions:
93 |
94 | (a) You must give any other recipients of the Work or
95 | Derivative Works a copy of this License; and
96 |
97 | (b) You must cause any modified files to carry prominent notices
98 | stating that You changed the files; and
99 |
100 | (c) You must retain, in the Source form of any Derivative Works
101 | that You distribute, all copyright, patent, trademark, and
102 | attribution notices from the Source form of the Work,
103 | excluding those notices that do not pertain to any part of
104 | the Derivative Works; and
105 |
106 | (d) If the Work includes a "NOTICE" text file as part of its
107 | distribution, then any Derivative Works that You distribute must
108 | include a readable copy of the attribution notices contained
109 | within such NOTICE file, excluding those notices that do not
110 | pertain to any part of the Derivative Works, in at least one
111 | of the following places: within a NOTICE text file distributed
112 | as part of the Derivative Works; within the Source form or
113 | documentation, if provided along with the Derivative Works; or,
114 | within a display generated by the Derivative Works, if and
115 | wherever such third-party notices normally appear. The contents
116 | of the NOTICE file are for informational purposes only and
117 | do not modify the License. You may add Your own attribution
118 | notices within Derivative Works that You distribute, alongside
119 | or as an addendum to the NOTICE text from the Work, provided
120 | that such additional attribution notices cannot be construed
121 | as modifying the License.
122 |
123 | You may add Your own copyright statement to Your modifications and
124 | may provide additional or different license terms and conditions
125 | for use, reproduction, or distribution of Your modifications, or
126 | for any such Derivative Works as a whole, provided Your use,
127 | reproduction, and distribution of the Work otherwise complies with
128 | the conditions stated in this License.
129 |
130 | 5. Submission of Contributions. Unless You explicitly state otherwise,
131 | any Contribution intentionally submitted for inclusion in the Work
132 | by You to the Licensor shall be under the terms and conditions of
133 | this License, without any additional terms or conditions.
134 | Notwithstanding the above, nothing herein shall supersede or modify
135 | the terms of any separate license agreement you may have executed
136 | with Licensor regarding such Contributions.
137 |
138 | 6. Trademarks. This License does not grant permission to use the trade
139 | names, trademarks, service marks, or product names of the Licensor,
140 | except as required for reasonable and customary use in describing the
141 | origin of the Work and reproducing the content of the NOTICE file.
142 |
143 | 7. Disclaimer of Warranty. Unless required by applicable law or
144 | agreed to in writing, Licensor provides the Work (and each
145 | Contributor provides its Contributions) on an "AS IS" BASIS,
146 | WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or
147 | implied, including, without limitation, any warranties or conditions
148 | of TITLE, NON-INFRINGEMENT, MERCHANTABILITY, or FITNESS FOR A
149 | PARTICULAR PURPOSE. You are solely responsible for determining the
150 | appropriateness of using or redistributing the Work and assume any
151 | risks associated with Your exercise of permissions under this License.
152 |
153 | 8. Limitation of Liability. In no event and under no legal theory,
154 | whether in tort (including negligence), contract, or otherwise,
155 | unless required by applicable law (such as deliberate and grossly
156 | negligent acts) or agreed to in writing, shall any Contributor be
157 | liable to You for damages, including any direct, indirect, special,
158 | incidental, or consequential damages of any character arising as a
159 | result of this License or out of the use or inability to use the
160 | Work (including but not limited to damages for loss of goodwill,
161 | work stoppage, computer failure or malfunction, or any and all
162 | other commercial damages or losses), even if such Contributor
163 | has been advised of the possibility of such damages.
164 |
165 | 9. Accepting Warranty or Additional Liability. While redistributing
166 | the Work or Derivative Works thereof, You may choose to offer,
167 | and charge a fee for, acceptance of support, warranty, indemnity,
168 | or other liability obligations and/or rights consistent with this
169 | License. However, in accepting such obligations, You may act only
170 | on Your own behalf and on Your sole responsibility, not on behalf
171 | of any other Contributor, and only if You agree to indemnify,
172 | defend, and hold each Contributor harmless for any liability
173 | incurred by, or claims asserted against, such Contributor by reason
174 | of your accepting any such warranty or additional liability.
175 |
176 | END OF TERMS AND CONDITIONS
177 |
178 | APPENDIX: How to apply the Apache License to your work.
179 |
180 | To apply the Apache License to your work, attach the following
181 | boilerplate notice, with the fields enclosed by brackets "[]"
182 | replaced with your own identifying information. (Don't include
183 | the brackets!) The text should be enclosed in the appropriate
184 | comment syntax for the file format. We also recommend that a
185 | file or class name and description of purpose be included on the
186 | same "printed page" as the copyright notice for easier
187 | identification within third-party archives.
188 |
189 | Copyright [yyyy] [name of copyright owner]
190 |
191 | Licensed under the Apache License, Version 2.0 (the "License");
192 | you may not use this file except in compliance with the License.
193 | You may obtain a copy of the License at
194 |
195 | http://www.apache.org/licenses/LICENSE-2.0
196 |
197 | Unless required by applicable law or agreed to in writing, software
198 | distributed under the License is distributed on an "AS IS" BASIS,
199 | WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
200 | See the License for the specific language governing permissions and
201 | limitations under the License.
202 |
--------------------------------------------------------------------------------
/README.md:
--------------------------------------------------------------------------------
1 | # OpenAPI petstore
2 |
3 | This is an implementation of the OpenAPI pet store based on Spring-Boot.
4 |
5 | ## Overview
6 |
7 | Start your server as a simple Spring-Boot application
8 | ```
9 | mvn spring-boot:run
10 | ```
11 | Or package it then run it as a Java application
12 | ```
13 | mvn package
14 | java -jar target/openapi-petstore-{VERSION}.jar
15 | ```
16 |
17 | You can view the api documentation in swagger-ui by pointing to
18 | http://localhost:8080/
19 |
20 | ## Docker
21 |
22 | To start the server via docker, please run the following commands:
23 | ```sh
24 | docker pull openapitools/openapi-petstore
25 | docker run -d -e OPENAPI_BASE_PATH=/v3 -p 80:8080 openapitools/openapi-petstore
26 | ```
27 |
28 | Ref: https://hub.docker.com/r/openapitools/openapi-petstore/
29 |
30 | ## Security
31 |
32 | ### API key
33 | Use `special-key` for endpoints protected by the API key
34 |
35 | ### OAuth2
36 | By default the server supports the implicit and the password flow (even though only the implicit flow is described in the OAI spec)
37 | The default credentials are:
38 | * client-id: sample-client-id
39 | * client-secret: secret
40 | * username: user
41 | * password: user
42 |
43 | ## Configuration
44 |
45 | Spring parameters in application.properties:
46 | * Server port : `server.port` (default=8080)
47 | * API base path : `openapi.openAPIPetstore.base-path` (default=/v3). In the docker image the base path can also be set with the `OPENAPI_BASE_PATH` environment variable.
48 |
49 | Environment variables:
50 | * `DISABLE_API_KEY` : if set to "1", the server will not check the api key for the relevant endpoints.
51 | * `DISABLE_OAUTH` : if set to "1", the server will not check for an OAuth2 access token.
52 |
53 | ## License
54 |
55 | [Apache 2.0 License](http://www.apache.org/licenses/LICENSE-2.0)
--------------------------------------------------------------------------------
/pom.xml:
--------------------------------------------------------------------------------
1 |
2 | 4.0.0
3 | org.openapitools
4 | openapi-petstore
5 | jar
6 | openapi-petstore
7 | 3.0.0
8 |
9 | 1.8
10 | ${java.version}
11 | ${java.version}
12 |
13 |
14 | org.springframework.boot
15 | spring-boot-starter-parent
16 | 2.0.2.RELEASE
17 |
18 |
19 |
20 | Apache License 2.0
21 | http://www.apache.org/licenses/LICENSE-2.0.html
22 | repo
23 |
24 |
25 |
26 | src/main/java
27 |
28 |
29 | org.springframework.boot
30 | spring-boot-maven-plugin
31 |
32 |
33 |
34 | repackage
35 |
36 |
37 |
38 |
39 |
40 | org.openapitools
41 | openapi-generator-maven-plugin
42 | 3.0.0
43 |
44 |
45 |
46 | generate
47 |
48 |
49 | src/main/resources/openapi.yaml
50 | spring
51 | org.openapitools.api
52 | org.openapitools.model
53 | false
54 |
55 | true
56 | true
57 |
58 |
59 |
60 |
61 |
62 |
63 |
64 |
65 |
66 | org.springframework.boot
67 | spring-boot-starter-web
68 |
69 |
70 | org.springframework.boot
71 | spring-boot-starter-security
72 |
73 |
74 | org.springframework.security.oauth.boot
75 | spring-security-oauth2-autoconfigure
76 | 2.0.1.RELEASE
77 |
78 |
79 | org.springframework.data
80 | spring-data-commons
81 |
82 |
83 | io.swagger.parser.v3
84 | swagger-parser
85 | 2.0.1
86 |
87 |
88 | org.webjars
89 | swagger-ui
90 | 3.14.2
91 |
92 |
93 | io.swagger
94 | swagger-annotations
95 | 1.5.14
96 |
97 |
98 | com.fasterxml.jackson.dataformat
99 | jackson-dataformat-yaml
100 |
101 |
102 | com.fasterxml.jackson.dataformat
103 | jackson-dataformat-xml
104 |
105 |
106 | com.fasterxml.woodstox
107 | woodstox-core
108 | 5.1.0
109 |
110 |
111 | com.fasterxml.jackson.datatype
112 | jackson-datatype-jsr310
113 |
114 |
115 |
116 | javax.validation
117 | validation-api
118 |
119 |
120 |
121 |
--------------------------------------------------------------------------------
/src/main/java/org/openapitools/OpenAPI2SpringBoot.java:
--------------------------------------------------------------------------------
1 | package org.openapitools;
2 |
3 | import org.springframework.boot.CommandLineRunner;
4 | import org.springframework.boot.ExitCodeGenerator;
5 | import org.springframework.boot.SpringApplication;
6 | import org.springframework.boot.autoconfigure.SpringBootApplication;
7 | import org.springframework.context.annotation.Bean;
8 | import org.springframework.context.annotation.ComponentScan;
9 | import org.springframework.web.servlet.config.annotation.CorsRegistry;
10 | import org.springframework.web.servlet.config.annotation.ResourceHandlerRegistry;
11 | import org.springframework.web.servlet.config.annotation.WebMvcConfigurer;
12 |
13 | @SpringBootApplication
14 | @ComponentScan(basePackages = {"org.openapitools", "org.openapitools.api" , "org.openapitools.configuration"})
15 | public class OpenAPI2SpringBoot implements CommandLineRunner {
16 |
17 | @Override
18 | public void run(String... arg0) {
19 | if (arg0.length > 0 && arg0[0].equals("exitcode")) {
20 | throw new ExitException();
21 | }
22 | }
23 |
24 | public static void main(String[] args) {
25 | new SpringApplication(OpenAPI2SpringBoot.class).run(args);
26 | }
27 |
28 | class ExitException extends RuntimeException implements ExitCodeGenerator {
29 | private static final long serialVersionUID = 1L;
30 |
31 | @Override
32 | public int getExitCode() {
33 | return 10;
34 | }
35 |
36 | }
37 |
38 | @Bean
39 | public WebMvcConfigurer webConfigurer() {
40 | return new WebMvcConfigurer() {
41 | @Override
42 | public void addCorsMappings(CorsRegistry registry) {
43 | registry.addMapping("/**")
44 | .allowedOrigins("*")
45 | .allowedMethods("*")
46 | .allowedHeaders("Content-Type");
47 | }
48 |
49 | @Override
50 | public void addResourceHandlers(ResourceHandlerRegistry registry) {
51 | registry.addResourceHandler("/swagger-ui/**")
52 | .addResourceLocations("classpath:/META-INF/resources/webjars/swagger-ui/3.14.2/");
53 | }
54 | };
55 | }
56 |
57 | }
58 |
--------------------------------------------------------------------------------
/src/main/java/org/openapitools/RFC3339DateFormat.java:
--------------------------------------------------------------------------------
1 | package org.openapitools;
2 |
3 | import com.fasterxml.jackson.databind.util.ISO8601DateFormat;
4 | import com.fasterxml.jackson.databind.util.ISO8601Utils;
5 |
6 | import java.text.FieldPosition;
7 | import java.util.Date;
8 |
9 |
10 | public class RFC3339DateFormat extends ISO8601DateFormat {
11 |
12 | private static final long serialVersionUID = 1L;
13 |
14 | // Same as ISO8601DateFormat but serializing milliseconds.
15 | @Override
16 | public StringBuffer format(Date date, StringBuffer toAppendTo, FieldPosition fieldPosition) {
17 | String value = ISO8601Utils.format(date, true);
18 | toAppendTo.append(value);
19 | return toAppendTo;
20 | }
21 |
22 | }
--------------------------------------------------------------------------------
/src/main/java/org/openapitools/api/ApiUtil.java:
--------------------------------------------------------------------------------
1 | package org.openapitools.api;
2 |
3 | import org.springframework.http.HttpStatus;
4 | import org.springframework.web.context.request.NativeWebRequest;
5 | import org.springframework.web.server.ResponseStatusException;
6 |
7 | import javax.servlet.http.HttpServletResponse;
8 | import java.io.IOException;
9 |
10 | public class ApiUtil {
11 |
12 | public static void setExampleResponse(NativeWebRequest req, String contentType, String example) {
13 | try {
14 | req.getNativeResponse(HttpServletResponse.class).addHeader("Content-Type", contentType);
15 | req.getNativeResponse(HttpServletResponse.class).getOutputStream().print(example);
16 | } catch (IOException e) {
17 | throw new RuntimeException(e);
18 | }
19 | }
20 |
21 | public static void checkApiKey(NativeWebRequest req) {
22 | if (!"1".equals(System.getenv("DISABLE_API_KEY")) && !"special-key".equals(req.getHeader("api_key"))) {
23 | throw new ResponseStatusException(HttpStatus.UNAUTHORIZED, "Missing API key!");
24 | }
25 | }
26 | }
--------------------------------------------------------------------------------
/src/main/java/org/openapitools/api/ExceptionTranslator.java:
--------------------------------------------------------------------------------
1 | package org.openapitools.api;
2 |
3 | import org.springframework.boot.web.servlet.error.ErrorAttributes;
4 | import org.springframework.http.HttpStatus;
5 | import org.springframework.web.bind.annotation.ExceptionHandler;
6 | import org.springframework.web.bind.annotation.ResponseStatus;
7 | import org.springframework.web.bind.annotation.RestControllerAdvice;
8 | import org.springframework.web.context.request.RequestAttributes;
9 | import org.springframework.web.context.request.WebRequest;
10 |
11 | import javax.validation.ConstraintViolationException;
12 | import java.util.Map;
13 |
14 | @RestControllerAdvice
15 | public class ExceptionTranslator {
16 |
17 | private final ErrorAttributes errorAttributes;
18 |
19 | public ExceptionTranslator(ErrorAttributes errorAttributes) {
20 | this.errorAttributes = errorAttributes;
21 | }
22 |
23 | @ExceptionHandler(ConstraintViolationException.class)
24 | @ResponseStatus(HttpStatus.BAD_REQUEST)
25 | public Map processConstraintViolationException(WebRequest request) {
26 | request.setAttribute("javax.servlet.error.status_code", HttpStatus.BAD_REQUEST.value(), RequestAttributes.SCOPE_REQUEST);
27 | return errorAttributes.getErrorAttributes(request, false);
28 | }
29 | }
30 |
--------------------------------------------------------------------------------
/src/main/java/org/openapitools/api/PetApiDelegateImpl.java:
--------------------------------------------------------------------------------
1 | package org.openapitools.api;
2 |
3 | import org.apache.tomcat.util.http.fileupload.IOUtils;
4 | import org.openapitools.model.Category;
5 | import org.openapitools.model.ModelApiResponse;
6 | import org.openapitools.model.Pet;
7 | import org.openapitools.model.Tag;
8 | import org.openapitools.repository.PetRepository;
9 | import org.springframework.http.HttpStatus;
10 | import org.springframework.http.ResponseEntity;
11 | import org.springframework.stereotype.Service;
12 | import org.springframework.util.StringUtils;
13 | import org.springframework.web.context.request.NativeWebRequest;
14 | import org.springframework.web.multipart.MultipartFile;
15 | import org.springframework.web.server.ResponseStatusException;
16 |
17 | import javax.annotation.PostConstruct;
18 | import java.io.File;
19 | import java.io.FileOutputStream;
20 | import java.util.Arrays;
21 | import java.util.List;
22 | import java.util.Optional;
23 | import java.util.concurrent.atomic.AtomicLong;
24 | import java.util.stream.Collectors;
25 |
26 | @Service
27 | public class PetApiDelegateImpl implements PetApiDelegate {
28 |
29 | private final PetRepository petRepository;
30 |
31 | private final NativeWebRequest request;
32 |
33 | public PetApiDelegateImpl(PetRepository petRepository, NativeWebRequest request) {
34 | this.petRepository = petRepository;
35 | this.request = request;
36 | }
37 |
38 | @PostConstruct
39 | private void initPets() {
40 | Category dogs = new Category().id(1L).name("Dogs");
41 | Category cats = new Category().id(2L).name("Cats");
42 | Category rabbits = new Category().id(3L).name("Rabbits");
43 | Category lions = new Category().id(4L).name("Lions");
44 |
45 | petRepository.save(createPet(1, cats, "Cat 1", new String[] {
46 | "url1", "url2" }, new String[] { "tag1", "tag2" }, Pet.StatusEnum.AVAILABLE));
47 | petRepository.save(createPet(2, cats, "Cat 2", new String[] {
48 | "url1", "url2" }, new String[] { "tag2", "tag3" }, Pet.StatusEnum.AVAILABLE));
49 | petRepository.save(createPet(3, cats, "Cat 3", new String[] {
50 | "url1", "url2" }, new String[] { "tag3", "tag4" }, Pet.StatusEnum.PENDING));
51 |
52 | petRepository.save(createPet(4, dogs, "Dog 1", new String[] {
53 | "url1", "url2" }, new String[] { "tag1", "tag2" }, Pet.StatusEnum.AVAILABLE));
54 | petRepository.save(createPet(5, dogs, "Dog 2", new String[] {
55 | "url1", "url2" }, new String[] { "tag2", "tag3" }, Pet.StatusEnum.SOLD));
56 | petRepository.save(createPet(6, dogs, "Dog 3", new String[] {
57 | "url1", "url2" }, new String[] { "tag3", "tag4" }, Pet.StatusEnum.PENDING));
58 |
59 | petRepository.save(createPet(7, lions, "Lion 1", new String[] {
60 | "url1", "url2" }, new String[] { "tag1", "tag2" }, Pet.StatusEnum.AVAILABLE));
61 | petRepository.save(createPet(8, lions, "Lion 2", new String[] {
62 | "url1", "url2" }, new String[] { "tag2", "tag3" }, Pet.StatusEnum.AVAILABLE));
63 | petRepository.save(createPet(9, lions, "Lion 3", new String[] {
64 | "url1", "url2" }, new String[] { "tag3", "tag4" }, Pet.StatusEnum.AVAILABLE));
65 |
66 | petRepository.save(createPet(10, rabbits, "Rabbit 1", new String[] {
67 | "url1", "url2" }, new String[] { "tag3", "tag4" }, Pet.StatusEnum.AVAILABLE));
68 | }
69 |
70 |
71 | @Override
72 | public ResponseEntity addPet(Pet pet) {
73 | petRepository.save(pet);
74 | return ResponseEntity.ok().build();
75 | }
76 |
77 | @Override
78 | public ResponseEntity deletePet(Long petId, String apiKey) {
79 | petRepository.deleteById(petId);
80 | return ResponseEntity.ok().build();
81 | }
82 |
83 | @Override
84 | public ResponseEntity> findPetsByStatus(List statusList) {
85 | List statusEnums = statusList.stream()
86 | .map(s -> Optional.ofNullable(Pet.StatusEnum.fromValue(s))
87 | .orElseThrow(() -> new ResponseStatusException(HttpStatus.BAD_REQUEST, "Invalid status: " + s))
88 | )
89 | .collect(Collectors.toList());
90 | return ResponseEntity.ok(petRepository.findPetsByStatus(statusEnums));
91 | }
92 |
93 | @Override
94 | public ResponseEntity> findPetsByTags(List tags) {
95 | return ResponseEntity.ok(petRepository.findPetsByTags(tags));
96 | }
97 |
98 | @Override
99 | public ResponseEntity getPetById(Long petId) {
100 | ApiUtil.checkApiKey(request);
101 | return petRepository.findById(petId)
102 | .map(ResponseEntity::ok)
103 | .orElseThrow(() -> new ResponseStatusException(HttpStatus.NOT_FOUND));
104 | }
105 |
106 | @Override
107 | public ResponseEntity updatePet(Pet pet) {
108 | return addPet(pet);
109 | }
110 |
111 | @Override
112 | public ResponseEntity updatePetWithForm(Long petId, String name, String status) {
113 | Pet pet = petRepository.findById(petId)
114 | .orElseThrow(() -> new ResponseStatusException(HttpStatus.NOT_FOUND));
115 | if(!StringUtils.isEmpty(name))
116 | pet.name(name);
117 | if(!StringUtils.isEmpty(name))
118 | pet.setStatus(Pet.StatusEnum.fromValue(status));
119 | return addPet(pet);
120 | }
121 |
122 | @Override
123 | public ResponseEntity uploadFile(Long petId, String additionalMetadata, MultipartFile file) {
124 | try {
125 | String uploadedFileLocation = "./" + file.getName();
126 | System.out.println("uploading to " + uploadedFileLocation);
127 | IOUtils.copy(file.getInputStream(), new FileOutputStream(uploadedFileLocation));
128 | String msg = String.format("additionalMetadata: %s\nFile uploaded to %s, %d bytes", additionalMetadata, uploadedFileLocation, (new File(uploadedFileLocation)).length());
129 | ModelApiResponse output = new ModelApiResponse().code(200).message(msg);
130 | return ResponseEntity.ok(output);
131 | }
132 | catch (Exception e) {
133 | throw new ResponseStatusException(HttpStatus.INTERNAL_SERVER_ERROR, "Couldn't upload file", e);
134 | }
135 | }
136 |
137 | private static Pet createPet(long id, Category category, String name, String[] urls,
138 | String[] tags, Pet.StatusEnum status) {
139 | Pet pet = new Pet()
140 | .id(id)
141 | .category(category)
142 | .name(name)
143 | .status(status);
144 |
145 | if (null != urls) {
146 | pet.setPhotoUrls(Arrays.asList(urls));
147 | }
148 |
149 | final AtomicLong i = new AtomicLong(0);
150 | if (null != tags) {
151 | Arrays.stream(tags)
152 | .map(tag -> new Tag().name(tag).id(i.incrementAndGet()))
153 | .forEach(pet::addTagsItem);
154 | }
155 | return pet;
156 | }
157 |
158 | }
159 |
--------------------------------------------------------------------------------
/src/main/java/org/openapitools/api/StoreApiDelegateImpl.java:
--------------------------------------------------------------------------------
1 | package org.openapitools.api;
2 |
3 | import org.openapitools.model.Order;
4 | import org.openapitools.model.Pet;
5 | import org.openapitools.repository.OrderRepository;
6 | import org.openapitools.repository.PetRepository;
7 | import org.springframework.http.HttpStatus;
8 | import org.springframework.http.ResponseEntity;
9 | import org.springframework.stereotype.Service;
10 | import org.springframework.web.context.request.NativeWebRequest;
11 | import org.springframework.web.server.ResponseStatusException;
12 |
13 | import javax.annotation.PostConstruct;
14 | import java.time.OffsetDateTime;
15 | import java.util.Map;
16 | import java.util.stream.Collectors;
17 |
18 | @Service
19 | public class StoreApiDelegateImpl implements StoreApiDelegate {
20 |
21 | private final OrderRepository orderRepository;
22 |
23 | private final PetRepository petRepository;
24 |
25 | private final NativeWebRequest request;
26 |
27 | public StoreApiDelegateImpl(OrderRepository orderRepository, PetRepository petRepository, NativeWebRequest request) {
28 | this.orderRepository = orderRepository;
29 | this.petRepository = petRepository;
30 | this.request = request;
31 | }
32 |
33 | @PostConstruct
34 | void initOrders() {
35 | orderRepository.save(createOrder(1, 1, Order.StatusEnum.PLACED));
36 | orderRepository.save(createOrder(2, 1, Order.StatusEnum.DELIVERED));
37 | orderRepository.save(createOrder(3, 2, Order.StatusEnum.PLACED));
38 | orderRepository.save(createOrder(4, 2, Order.StatusEnum.DELIVERED));
39 | orderRepository.save(createOrder(5, 3, Order.StatusEnum.PLACED));
40 | orderRepository.save(createOrder(6, 3, Order.StatusEnum.PLACED));
41 | orderRepository.save(createOrder(7, 3, Order.StatusEnum.PLACED));
42 | orderRepository.save(createOrder(8, 3, Order.StatusEnum.PLACED));
43 | orderRepository.save(createOrder(9, 3, Order.StatusEnum.PLACED));
44 | orderRepository.save(createOrder(10, 3, Order.StatusEnum.PLACED));
45 | }
46 |
47 |
48 | @Override
49 | public ResponseEntity deleteOrder(String orderId) {
50 | Order order = orderRepository.findById(Long.valueOf(orderId))
51 | .orElseThrow(() -> new ResponseStatusException(HttpStatus.NOT_FOUND));
52 | orderRepository.delete(order);
53 | return ResponseEntity.ok().build();
54 | }
55 |
56 | @Override
57 | public ResponseEntity