Commit dd7f776a authored by Spiros Koulouzis's avatar Spiros Koulouzis

added sample swagger project

parent d047cdfa
...@@ -30,4 +30,6 @@ ...@@ -30,4 +30,6 @@
/winery_service/src/winery/__pycache__/ /winery_service/src/winery/__pycache__/
/tosca_service/nbproject/private/ /tosca_service/nbproject/private/
/tosca_service/src/winery/__pycache__/ /tosca_service/src/winery/__pycache__/
/drip-deployer/venv/ /drip-deployer/venv/
\ No newline at end of file /drip/target/
/drip-manager/target/
\ No newline at end of file
...@@ -58,9 +58,6 @@ public class ToscaController { ...@@ -58,9 +58,6 @@ public class ToscaController {
@Autowired @Autowired
private ToscaService toscaService; private ToscaService toscaService;
@Autowired
private ConfigurationService configurationService;
@RequestMapping(value = "/post", method = RequestMethod.POST) @RequestMapping(value = "/post", method = RequestMethod.POST)
@RolesAllowed({UserService.USER, UserService.ADMIN}) @RolesAllowed({UserService.USER, UserService.ADMIN})
public @ResponseBody public @ResponseBody
...@@ -144,26 +141,6 @@ public class ToscaController { ...@@ -144,26 +141,6 @@ public class ToscaController {
return ids; return ids;
} }
/**
* Transforms the TOSCA description to docker compose
*
* @param id the ID TOSCA description.
* @param type. Transform it to a specific type e.g. "docker_compose"
* @return the docker-compose ID.
*/
@RequestMapping(value = "/transform/{id}", method = RequestMethod.GET, params = {"type"})
@RolesAllowed({UserService.USER, UserService.ADMIN})
public @ResponseBody
String transform(@PathVariable("id") String id, @RequestParam(value = "type") String type) {
try {
String ymlContents = toscaService.transform(id, type);
return configurationService.saveStringContents(ymlContents);
} catch (JSONException | IOException | TimeoutException | InterruptedException ex) {
Logger.getLogger(ToscaController.class.getName()).log(Level.SEVERE, null, ex);
}
return null;
}
/** /**
* Gets the IDs of all the stored TOSCA descriptions. * Gets the IDs of all the stored TOSCA descriptions.
* *
......
# Swagger Codegen Ignore
# Generated by swagger-codegen https://github.com/swagger-api/swagger-codegen
# Use this file to prevent files from being overwritten by the generator.
# The patterns follow closely to .gitignore or .dockerignore.
# As an example, the C# client generator defines ApiClient.cs.
# You can make changes and tell Swagger Codgen to ignore just this file by uncommenting the following line:
#ApiClient.cs
# You can match any string of characters against a directory, file or extension with a single asterisk (*):
#foo/*/qux
# The above matches foo/bar/qux and foo/baz/qux, but not foo/bar/baz/qux
# You can recursively match patterns against a directory, file or extension with a double asterisk (**):
#foo/**/qux
# This matches foo/bar/qux, foo/baz/qux, and foo/bar/baz/qux
# You can also negate patterns with an exclamation (!).
# For example, you can ignore all files in a docs folder with the file extension .md:
#docs/*.md
# Then explicitly reverse the ignore rule for a single file:
#!docs/README.md
2.4.8
\ No newline at end of file
# Swagger generated server
Spring Boot Server
## Overview
This server was generated by the [swagger-codegen](https://github.com/swagger-api/swagger-codegen) project.
By using the [OpenAPI-Spec](https://github.com/swagger-api/swagger-core), you can easily generate a server stub.
This is an example of building a swagger-enabled server in Java using the SpringBoot framework.
The underlying library integrating swagger to SpringBoot is [springfox](https://github.com/springfox/springfox)
Start your server as an simple java application
You can view the api documentation in swagger-ui by pointing to
http://localhost:8080/
Change default port value in application.properties
\ No newline at end of file
<?xml version="1.0" encoding="UTF-8"?>
<project-shared-configuration>
<!--
This file contains additional configuration written by modules in the NetBeans IDE.
The configuration is intended to be shared among all the users of project and
therefore it is assumed to be part of version control checkout.
Without this configuration present, some functionality in the IDE may be limited or fail altogether.
-->
<properties xmlns="http://www.netbeans.org/ns/maven-properties-data/1">
<!--
Properties that influence various parts of the IDE, especially code formatting and the like.
You can copy and paste the single properties, into the pom.xml file and the IDE will pick them up.
That way multiple projects can share the same settings (useful for formatting rules for example).
Any value defined here will override the pom.xml file value but is only applicable to the current project.
-->
<org-netbeans-modules-whitelist.whitelist-oracle>false</org-netbeans-modules-whitelist.whitelist-oracle>
</properties>
</project-shared-configuration>
<project xmlns="http://maven.apache.org/POM/4.0.0" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/maven-v4_0_0.xsd">
<modelVersion>4.0.0</modelVersion>
<groupId>nl.uva.sne.drip</groupId>
<artifactId>drip-manager</artifactId>
<packaging>jar</packaging>
<name>drip-manager</name>
<version>1.0.0</version>
<properties>
<maven.compiler.source>1.8</maven.compiler.source>
<maven.compiler.target>1.8</maven.compiler.target>
<springfox-version>2.9.2</springfox-version>
</properties>
<parent>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-parent</artifactId>
<version>2.1.8.RELEASE</version>
</parent>
<build>
<sourceDirectory>src/main/java</sourceDirectory>
<plugins>
<plugin>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-maven-plugin</artifactId>
<executions>
<execution>
<goals>
<goal>repackage</goal>
</goals>
</execution>
</executions>
</plugin>
</plugins>
</build>
<dependencies>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-web</artifactId>
</dependency>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-tomcat</artifactId>
</dependency>
<!--SpringFox dependencies -->
<dependency>
<groupId>io.springfox</groupId>
<artifactId>springfox-swagger2</artifactId>
<version>${springfox-version}</version>
</dependency>
<dependency>
<groupId>io.springfox</groupId>
<artifactId>springfox-swagger-ui</artifactId>
<version>${springfox-version}</version>
</dependency>
<dependency>
<groupId>com.github.joschi.jackson</groupId>
<artifactId>jackson-datatype-threetenbp</artifactId>
<version>2.6.4</version>
</dependency>
<!-- Bean Validation API support -->
<dependency>
<groupId>javax.validation</groupId>
<artifactId>validation-api</artifactId>
</dependency>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-test</artifactId>
<scope>test</scope>
</dependency>
<dependency>
<groupId>org.springframework.data</groupId>
<artifactId>spring-data-mongodb</artifactId>
<type>jar</type>
</dependency>
<dependency>
<groupId>io.swagger</groupId>
<artifactId>swagger-annotations</artifactId>
<version>1.5.20</version>
<type>jar</type>
</dependency>
</dependencies>
</project>
package nl.uva.sne.drip;
import com.fasterxml.jackson.databind.util.ISO8601DateFormat;
import com.fasterxml.jackson.databind.util.ISO8601Utils;
import java.text.FieldPosition;
import java.util.Date;
public class RFC3339DateFormat extends ISO8601DateFormat {
private static final long serialVersionUID = 1L;
// Same as ISO8601DateFormat but serializing milliseconds.
@Override
public StringBuffer format(Date date, StringBuffer toAppendTo, FieldPosition fieldPosition) {
String value = ISO8601Utils.format(date, true);
toAppendTo.append(value);
return toAppendTo;
}
}
\ No newline at end of file
package nl.uva.sne.drip;
import nl.uva.sne.drip.dao.TopologTemplateDAO;
import org.springframework.boot.CommandLineRunner;
import org.springframework.boot.ExitCodeGenerator;
import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;
import org.springframework.context.annotation.ComponentScan;
import org.springframework.data.mongodb.repository.config.EnableMongoRepositories;
import springfox.documentation.swagger2.annotations.EnableSwagger2;
@SpringBootApplication
@EnableSwagger2
@EnableMongoRepositories(basePackageClasses = {TopologTemplateDAO.class})
@ComponentScan(basePackages = {"nl.uva.sne.drip", "nl.uva.sne.drip.api", "nl.uva.sne.drip.configuration", "nl.uva.sne.drip.dao", "nl.uva.sne.drip.model", "nl.uva.sne.drip.service"})
public class Swagger2SpringBoot implements CommandLineRunner {
@Override
public void run(String... arg0) throws Exception {
if (arg0.length > 0 && arg0[0].equals("exitcode")) {
throw new ExitException();
}
}
public static void main(String[] args) throws Exception {
new SpringApplication(Swagger2SpringBoot.class).run(args);
}
class ExitException extends RuntimeException implements ExitCodeGenerator {
private static final long serialVersionUID = 1L;
@Override
public int getExitCode() {
return 10;
}
}
}
package nl.uva.sne.drip.api;
@javax.annotation.Generated(value = "nl.uva.sne.drip.codegen.languages.SpringCodegen", date = "2019-10-09T14:00:37.436Z")
public class ApiException extends Exception{
private int code;
public ApiException (int code, String msg) {
super(msg);
this.code = code;
}
}
package nl.uva.sne.drip.api;
import java.io.IOException;
import javax.servlet.*;
import javax.servlet.http.HttpServletResponse;
@javax.annotation.Generated(value = "nl.uva.sne.drip.codegen.languages.SpringCodegen", date = "2019-10-09T14:00:37.436Z")
public class ApiOriginFilter implements javax.servlet.Filter {
@Override
public void doFilter(ServletRequest request, ServletResponse response,
FilterChain chain) throws IOException, ServletException {
HttpServletResponse res = (HttpServletResponse) response;
res.addHeader("Access-Control-Allow-Origin", "*");
res.addHeader("Access-Control-Allow-Methods", "GET, POST, DELETE, PUT");
res.addHeader("Access-Control-Allow-Headers", "Content-Type");
chain.doFilter(request, response);
}
@Override
public void destroy() {
}
@Override
public void init(FilterConfig filterConfig) throws ServletException {
}
}
package nl.uva.sne.drip.api;
import javax.xml.bind.annotation.XmlTransient;
@javax.annotation.Generated(value = "nl.uva.sne.drip.codegen.languages.SpringCodegen", date = "2019-10-09T14:00:37.436Z")
@javax.xml.bind.annotation.XmlRootElement
public class ApiResponseMessage {
public static final int ERROR = 1;
public static final int WARNING = 2;
public static final int INFO = 3;
public static final int OK = 4;
public static final int TOO_BUSY = 5;
int code;
String type;
String message;
public ApiResponseMessage(){}
public ApiResponseMessage(int code, String message){
this.code = code;
switch(code){
case ERROR:
setType("error");
break;
case WARNING:
setType("warning");
break;
case INFO:
setType("info");
break;
case OK:
setType("ok");
break;
case TOO_BUSY:
setType("too busy");
break;
default:
setType("unknown");
break;
}
this.message = message;
}
@XmlTransient
public int getCode() {
return code;
}
public void setCode(int code) {
this.code = code;
}
public String getType() {
return type;
}
public void setType(String type) {
this.type = type;
}
public String getMessage() {
return message;
}
public void setMessage(String message) {
this.message = message;
}
}
package nl.uva.sne.drip.api;
@javax.annotation.Generated(value = "nl.uva.sne.drip.codegen.languages.SpringCodegen", date = "2019-10-09T14:00:37.436Z")
public class NotFoundException extends ApiException {
private int code;
public NotFoundException (int code, String msg) {
super(code, msg);
this.code = code;
}
}
/**
* NOTE: This class is auto generated by the swagger code generator program (2.4.8).
* https://github.com/swagger-api/swagger-codegen
* Do not edit the class manually.
*/
package nl.uva.sne.drip.api;
import org.springframework.core.io.Resource;
import io.swagger.annotations.*;
import org.springframework.http.ResponseEntity;
import org.springframework.validation.annotation.Validated;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestHeader;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.RequestPart;
import org.springframework.web.multipart.MultipartFile;
import javax.validation.Valid;
import javax.validation.constraints.*;
import java.util.List;
@javax.annotation.Generated(value = "nl.uva.sne.drip.codegen.languages.SpringCodegen", date = "2019-10-09T14:00:37.436Z")
@Api(value = "topolog_template", description = "the topolog_template API")
public interface TopologTemplateApi {
@ApiOperation(value = "upload a topolog template description file", nickname = "addTopologTemplate", notes = "", authorizations = {
@Authorization(value = "drip_auth", scopes = {
@AuthorizationScope(scope = "write:TopologTemplate", description = "modify topolog template in your account"),
@AuthorizationScope(scope = "read:TopologTemplate", description = "read your topolog template")
})
}, tags={ })
@ApiResponses(value = {
@ApiResponse(code = 405, message = "Invalid input") })
@RequestMapping(value = "/topolog_template",
consumes = { "multipart/form-data" },
method = RequestMethod.POST)
ResponseEntity<Void> addTopologTemplate(@ApiParam(value = "file detail") @Valid @RequestPart("file") MultipartFile file);
@ApiOperation(value = "Find topolog template by ID", nickname = "getTopologTemplateById", notes = "Returns a single topolog template", authorizations = {
@Authorization(value = "drip_auth", scopes = {
@AuthorizationScope(scope = "write:TopologTemplate", description = "modify topolog template in your account"),
@AuthorizationScope(scope = "read:TopologTemplate", description = "read your topolog template")
})
}, tags={ })
@ApiResponses(value = {
@ApiResponse(code = 200, message = "successful operation"),
@ApiResponse(code = 400, message = "Invalid ID supplied"),
@ApiResponse(code = 404, message = "TopologTemplate not found"),
@ApiResponse(code = 405, message = "Invalid input") })
@RequestMapping(value = "/topolog_template/{TopologTemplateId}",
produces = { "text/plain" },
method = RequestMethod.GET)
ResponseEntity<Void> getTopologTemplateById(@ApiParam(value = "ID of topolog template to return",required=true) @PathVariable("TopologTemplateId") Long topologTemplateId);
@ApiOperation(value = "Deletes a topolog template", nickname = "topologTemplate", notes = "", authorizations = {
@Authorization(value = "drip_auth", scopes = {
@AuthorizationScope(scope = "write:TopologTemplate", description = "modify topolog template in your account"),
@AuthorizationScope(scope = "read:TopologTemplate", description = "read your topolog template")
})
}, tags={ })
@ApiResponses(value = {
@ApiResponse(code = 200, message = "successful operation"),
@ApiResponse(code = 400, message = "Invalid ID supplied"),
@ApiResponse(code = 404, message = "TopologTemplate not found") })
@RequestMapping(value = "/topolog_template/{TopologTemplateId}",
method = RequestMethod.DELETE)
ResponseEntity<Void> topologTemplate(@ApiParam(value = "ID of topolog template to return",required=true) @PathVariable("TopologTemplateId") Long topologTemplateId,@ApiParam(value = "" ) @RequestHeader(value="api_key", required=false) String apiKey);
@ApiOperation(value = "Updates exisintg topolog template in the store", nickname = "updateTopologTemplate", notes = "", authorizations = {
@Authorization(value = "drip_auth", scopes = {
@AuthorizationScope(scope = "write:TopologTemplate", description = "modify topolog template in your account"),
@AuthorizationScope(scope = "read:TopologTemplate", description = "read your topolog template")
})
}, tags={ })
@ApiResponses(value = {
@ApiResponse(code = 200, message = "successful operation"),
@ApiResponse(code = 400, message = "Invalid ID supplied"),
@ApiResponse(code = 404, message = "TopologTemplate not found"),
@ApiResponse(code = 405, message = "Invalid input") })
@RequestMapping(value = "/topolog_template/{TopologTemplateId}",
produces = { "application/json" },
consumes = { "multipart/form-data" },
method = RequestMethod.POST)
ResponseEntity<Void> updateTopologTemplate(@ApiParam(value = "ID of topolog template to return",required=true) @PathVariable("TopologTemplateId") Long topologTemplateId,@ApiParam(value = "file detail") @Valid @RequestPart("file") MultipartFile file);
}
package nl.uva.sne.drip.api;
import com.fasterxml.jackson.databind.ObjectMapper;
import io.swagger.annotations.*;
import nl.uva.sne.drip.service.TopologTemplateService;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.http.HttpStatus;
import org.springframework.http.ResponseEntity;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestHeader;
import org.springframework.web.bind.annotation.RequestPart;
import org.springframework.web.multipart.MultipartFile;
import javax.validation.Valid;
import javax.servlet.http.HttpServletRequest;
import org.springframework.beans.factory.annotation.Autowired;
@javax.annotation.Generated(value = "nl.uva.sne.drip.codegen.languages.SpringCodegen", date = "2019-10-09T14:00:37.436Z")
@Controller
public class TopologTemplateApiController implements TopologTemplateApi {
private static final Logger log = LoggerFactory.getLogger(TopologTemplateApiController.class);
private final ObjectMapper objectMapper;
private final HttpServletRequest request;
@Autowired
private TopologTemplateService topologTemplateService;
@org.springframework.beans.factory.annotation.Autowired
public TopologTemplateApiController(ObjectMapper objectMapper, HttpServletRequest request) {
this.objectMapper = objectMapper;
this.request = request;
}
public ResponseEntity<Void> addTopologTemplate(@ApiParam(value = "file detail") @Valid @RequestPart("file") MultipartFile file) {
String accept = request.getHeader("Accept");
return new ResponseEntity<Void>(HttpStatus.NOT_IMPLEMENTED);
}
public ResponseEntity<Void> getTopologTemplateById(@ApiParam(value = "ID of topolog template to return", required = true) @PathVariable("TopologTemplateId") Long topologTemplateId) {
String accept = request.getHeader("Accept");
return new ResponseEntity<Void>(HttpStatus.NOT_IMPLEMENTED);
}
public ResponseEntity<Void> topologTemplate(@ApiParam(value = "ID of topolog template to return", required = true) @PathVariable("TopologTemplateId") Long topologTemplateId, @ApiParam(value = "") @RequestHeader(value = "api_key", required = false) String apiKey) {
String accept = request.getHeader("Accept");
return new ResponseEntity<Void>(HttpStatus.NOT_IMPLEMENTED);
}
public ResponseEntity<Void> updateTopologTemplate(@ApiParam(value = "ID of topolog template to return", required = true) @PathVariable("TopologTemplateId") Long topologTemplateId, @ApiParam(value = "file detail") @Valid @RequestPart("file") MultipartFile file) {
String accept = request.getHeader("Accept");
return new ResponseEntity<Void>(HttpStatus.NOT_IMPLEMENTED);
}
}
/**
* NOTE: This class is auto generated by the swagger code generator program (2.4.8).
* https://github.com/swagger-api/swagger-codegen
* Do not edit the class manually.
*/
package nl.uva.sne.drip.api;
import nl.uva.sne.drip.model.User;
import io.swagger.annotations.*;
import org.springframework.http.ResponseEntity;
import org.springframework.validation.annotation.Validated;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestHeader;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.RequestPart;
import org.springframework.web.multipart.MultipartFile;
import javax.validation.Valid;
import javax.validation.constraints.*;
import java.util.List;
@javax.annotation.Generated(value = "nl.uva.sne.drip.codegen.languages.SpringCodegen", date = "2019-10-09T14:00:37.436Z")
@Api(value = "user", description = "the user API")
public interface UserApi {
@ApiOperation(value = "Create user", nickname = "createUser", notes = "This can only be done by the logged in user.", authorizations = {
@Authorization(value = "drip_auth", scopes = {
@AuthorizationScope(scope = "admin:User", description = "Grants access to admin operations")
})
}, tags={ })
@ApiResponses(value = {
@ApiResponse(code = 200, message = "successful operation") })
@RequestMapping(value = "/user",
produces = { "application/json" },
method = RequestMethod.POST)
ResponseEntity<Void> createUser(@ApiParam(value = "Created user object" ,required=true ) @Valid @RequestBody User body);
@ApiOperation(value = "Delete user", nickname = "deleteUser", notes = "This can only be done by the logged in user.", authorizations = {
@Authorization(value = "drip_auth", scopes = {
@AuthorizationScope(scope = "admin:User", description = "Grants access to admin operations")
})
}, tags={ "user", })
@ApiResponses(value = {
@ApiResponse(code = 400, message = "Invalid username supplied"),
@ApiResponse(code = 404, message = "User not found") })
@RequestMapping(value = "/user/{username}",
produces = { "application/json" },
method = RequestMethod.DELETE)
ResponseEntity<Void> deleteUser(@ApiParam(value = "The name that needs to be deleted",required=true) @PathVariable("username") String username);
@ApiOperation(value = "Get user by user name", nickname = "getUserByName", notes = "", response = User.class, authorizations = {
@Authorization(value = "drip_auth", scopes = {
@AuthorizationScope(scope = "admin:User", description = "Grants access to admin operations")
})
}, tags={ })
@ApiResponses(value = {
@ApiResponse(code = 200, message = "successful operation", response = User.class),
@ApiResponse(code = 400, message = "Invalid username supplied"),
@ApiResponse(code = 404, message = "User not found") })
@RequestMapping(value = "/user/{username}",
produces = { "application/json" },
method = RequestMethod.GET)
ResponseEntity<User> getUserByName(@ApiParam(value = "The name that needs to be fetched. Use user1 for testing. ",required=true) @PathVariable("username") String username);
@ApiOperation(value = "Logs user into the system", nickname = "loginUser", notes = "", response = String.class, tags={ "user", })
@ApiResponses(value = {
@ApiResponse(code = 200, message = "successful operation", response = String.class),
@ApiResponse(code = 400, message = "Invalid username/password supplied") })
@RequestMapping(value = "/user/login",
produces = { "application/json" },
method = RequestMethod.GET)
ResponseEntity<String> loginUser(@NotNull @ApiParam(value = "The user name for login", required = true) @Valid @RequestParam(value = "username", required = true) String username,@NotNull @ApiParam(value = "The password for login in clear text", required = true) @Valid @RequestParam(value = "password", required = true) String password);
@ApiOperation(value = "Logs out current logged in user session", nickname = "logoutUser", notes = "", tags={ "user", })
@ApiResponses(value = {
@ApiResponse(code = 200, message = "successful operation") })
@RequestMapping(value = "/user/logout",
produces = { "application/json" },
method = RequestMethod.GET)
ResponseEntity<Void> logoutUser();
@ApiOperation(value = "Updated user", nickname = "updateUser", notes = "This can only be done by the logged in user.", authorizations = {
@Authorization(value = "drip_auth", scopes = {
@AuthorizationScope(scope = "admin:User", description = "Grants access to admin operations")
})
}, tags={ "user", })
@ApiResponses(value = {
@ApiResponse(code = 400, message = "Invalid user supplied"),
@ApiResponse(code = 404, message = "User not found") })
@RequestMapping(value = "/user/{username}",
produces = { "application/json" },
method = RequestMethod.PUT)
ResponseEntity<Void> updateUser(@ApiParam(value = "name that need to be updated",required=true) @PathVariable("username") String username,@ApiParam(value = "Updated user object" ,required=true ) @Valid @RequestBody User body);
}
package nl.uva.sne.drip.api;
import nl.uva.sne.drip.model.User;
import com.fasterxml.jackson.databind.ObjectMapper;
import io.swagger.annotations.*;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.http.HttpStatus;
import org.springframework.http.ResponseEntity;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestHeader;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.RequestPart;
import org.springframework.web.multipart.MultipartFile;
import javax.validation.constraints.*;
import javax.validation.Valid;
import javax.servlet.http.HttpServletRequest;
import java.io.IOException;
import java.util.List;
@javax.annotation.Generated(value = "nl.uva.sne.drip.codegen.languages.SpringCodegen", date = "2019-10-09T14:00:37.436Z")
@Controller
public class UserApiController implements UserApi {
private static final Logger log = LoggerFactory.getLogger(UserApiController.class);
private final ObjectMapper objectMapper;
private final HttpServletRequest request;
@org.springframework.beans.factory.annotation.Autowired
public UserApiController(ObjectMapper objectMapper, HttpServletRequest request) {
this.objectMapper = objectMapper;
this.request = request;
}
public ResponseEntity<Void> createUser(@ApiParam(value = "Created user object" ,required=true ) @Valid @RequestBody User body) {
String accept = request.getHeader("Accept");
return new ResponseEntity<Void>(HttpStatus.NOT_IMPLEMENTED);
}
public ResponseEntity<Void> deleteUser(@ApiParam(value = "The name that needs to be deleted",required=true) @PathVariable("username") String username) {
String accept = request.getHeader("Accept");
return new ResponseEntity<Void>(HttpStatus.NOT_IMPLEMENTED);
}
public ResponseEntity<User> getUserByName(@ApiParam(value = "The name that needs to be fetched. Use user1 for testing. ",required=true) @PathVariable("username") String username) {
String accept = request.getHeader("Accept");
if (accept != null && accept.contains("application/json")) {
try {
return new ResponseEntity<User>(objectMapper.readValue("{ \"firstName\" : \"firstName\", \"lastName\" : \"lastName\", \"password\" : \"password\", \"userStatus\" : 6, \"id\" : 0, \"email\" : \"email\", \"username\" : \"username\"}", User.class), HttpStatus.NOT_IMPLEMENTED);
} catch (IOException e) {
log.error("Couldn't serialize response for content type application/json", e);
return new ResponseEntity<User>(HttpStatus.INTERNAL_SERVER_ERROR);
}
}
return new ResponseEntity<User>(HttpStatus.NOT_IMPLEMENTED);
}
public ResponseEntity<String> loginUser(@NotNull @ApiParam(value = "The user name for login", required = true) @Valid @RequestParam(value = "username", required = true) String username,@NotNull @ApiParam(value = "The password for login in clear text", required = true) @Valid @RequestParam(value = "password", required = true) String password) {
String accept = request.getHeader("Accept");
if (accept != null && accept.contains("application/json")) {
try {
return new ResponseEntity<String>(objectMapper.readValue("\"\"", String.class), HttpStatus.NOT_IMPLEMENTED);
} catch (IOException e) {
log.error("Couldn't serialize response for content type application/json", e);
return new ResponseEntity<String>(HttpStatus.INTERNAL_SERVER_ERROR);
}
}
return new ResponseEntity<String>(HttpStatus.NOT_IMPLEMENTED);
}
public ResponseEntity<Void> logoutUser() {
String accept = request.getHeader("Accept");
return new ResponseEntity<Void>(HttpStatus.NOT_IMPLEMENTED);
}
public ResponseEntity<Void> updateUser(@ApiParam(value = "name that need to be updated",required=true) @PathVariable("username") String username,@ApiParam(value = "Updated user object" ,required=true ) @Valid @RequestBody User body) {
String accept = request.getHeader("Accept");
return new ResponseEntity<Void>(HttpStatus.NOT_IMPLEMENTED);
}
}
package nl.uva.sne.drip.configuration;
import com.fasterxml.jackson.core.JsonParser;
import com.fasterxml.jackson.core.JsonTokenId;
import com.fasterxml.jackson.databind.DeserializationContext;
import com.fasterxml.jackson.databind.DeserializationFeature;
import com.fasterxml.jackson.databind.JsonDeserializer;
import com.fasterxml.jackson.datatype.threetenbp.DateTimeUtils;
import com.fasterxml.jackson.datatype.threetenbp.DecimalUtils;
import com.fasterxml.jackson.datatype.threetenbp.deser.ThreeTenDateTimeDeserializerBase;
import com.fasterxml.jackson.datatype.threetenbp.function.BiFunction;
import com.fasterxml.jackson.datatype.threetenbp.function.Function;
import org.threeten.bp.DateTimeException;
import org.threeten.bp.Instant;
import org.threeten.bp.OffsetDateTime;
import org.threeten.bp.ZoneId;
import org.threeten.bp.ZonedDateTime;
import org.threeten.bp.format.DateTimeFormatter;
import org.threeten.bp.temporal.Temporal;
import org.threeten.bp.temporal.TemporalAccessor;
import java.io.IOException;
import java.math.BigDecimal;
/**
* Deserializer for ThreeTen temporal {@link Instant}s, {@link OffsetDateTime}, and {@link ZonedDateTime}s.
* Adapted from the jackson threetenbp InstantDeserializer to add support for deserializing rfc822 format.
*
* @author Nick Williams
*/
public class CustomInstantDeserializer<T extends Temporal>
extends ThreeTenDateTimeDeserializerBase<T> {
private static final long serialVersionUID = 1L;
public static final CustomInstantDeserializer<Instant> INSTANT = new CustomInstantDeserializer<Instant>(
Instant.class, DateTimeFormatter.ISO_INSTANT,
new Function<TemporalAccessor, Instant>() {
@Override
public Instant apply(TemporalAccessor temporalAccessor) {
return Instant.from(temporalAccessor);
}
},
new Function<FromIntegerArguments, Instant>() {
@Override
public Instant apply(FromIntegerArguments a) {
return Instant.ofEpochMilli(a.value);
}
},
new Function<FromDecimalArguments, Instant>() {
@Override
public Instant apply(FromDecimalArguments a) {
return Instant.ofEpochSecond(a.integer, a.fraction);
}
},
null
);
public static final CustomInstantDeserializer<OffsetDateTime> OFFSET_DATE_TIME = new CustomInstantDeserializer<OffsetDateTime>(
OffsetDateTime.class, DateTimeFormatter.ISO_OFFSET_DATE_TIME,
new Function<TemporalAccessor, OffsetDateTime>() {
@Override
public OffsetDateTime apply(TemporalAccessor temporalAccessor) {
return OffsetDateTime.from(temporalAccessor);
}
},
new Function<FromIntegerArguments, OffsetDateTime>() {
@Override
public OffsetDateTime apply(FromIntegerArguments a) {
return OffsetDateTime.ofInstant(Instant.ofEpochMilli(a.value), a.zoneId);
}
},
new Function<FromDecimalArguments, OffsetDateTime>() {
@Override
public OffsetDateTime apply(FromDecimalArguments a) {
return OffsetDateTime.ofInstant(Instant.ofEpochSecond(a.integer, a.fraction), a.zoneId);
}
},
new BiFunction<OffsetDateTime, ZoneId, OffsetDateTime>() {
@Override
public OffsetDateTime apply(OffsetDateTime d, ZoneId z) {
return d.withOffsetSameInstant(z.getRules().getOffset(d.toLocalDateTime()));
}
}
);
public static final CustomInstantDeserializer<ZonedDateTime> ZONED_DATE_TIME = new CustomInstantDeserializer<ZonedDateTime>(
ZonedDateTime.class, DateTimeFormatter.ISO_ZONED_DATE_TIME,
new Function<TemporalAccessor, ZonedDateTime>() {
@Override
public ZonedDateTime apply(TemporalAccessor temporalAccessor) {
return ZonedDateTime.from(temporalAccessor);
}
},
new Function<FromIntegerArguments, ZonedDateTime>() {
@Override
public ZonedDateTime apply(FromIntegerArguments a) {
return ZonedDateTime.ofInstant(Instant.ofEpochMilli(a.value), a.zoneId);
}
},
new Function<FromDecimalArguments, ZonedDateTime>() {
@Override
public ZonedDateTime apply(FromDecimalArguments a) {
return ZonedDateTime.ofInstant(Instant.ofEpochSecond(a.integer, a.fraction), a.zoneId);
}
},
new BiFunction<ZonedDateTime, ZoneId, ZonedDateTime>() {
@Override
public ZonedDateTime apply(ZonedDateTime zonedDateTime, ZoneId zoneId) {
return zonedDateTime.withZoneSameInstant(zoneId);
}
}
);
protected final Function<FromIntegerArguments, T> fromMilliseconds;
protected final Function<FromDecimalArguments, T> fromNanoseconds;
protected final Function<TemporalAccessor, T> parsedToValue;
protected final BiFunction<T, ZoneId, T> adjust;
protected CustomInstantDeserializer(Class<T> supportedType,
DateTimeFormatter parser,
Function<TemporalAccessor, T> parsedToValue,
Function<FromIntegerArguments, T> fromMilliseconds,
Function<FromDecimalArguments, T> fromNanoseconds,
BiFunction<T, ZoneId, T> adjust) {
super(supportedType, parser);
this.parsedToValue = parsedToValue;
this.fromMilliseconds = fromMilliseconds;
this.fromNanoseconds = fromNanoseconds;
this.adjust = adjust == null ? new BiFunction<T, ZoneId, T>() {
@Override
public T apply(T t, ZoneId zoneId) {
return t;
}
} : adjust;
}
@SuppressWarnings("unchecked")
protected CustomInstantDeserializer(CustomInstantDeserializer<T> base, DateTimeFormatter f) {
super((Class<T>) base.handledType(), f);
parsedToValue = base.parsedToValue;
fromMilliseconds = base.fromMilliseconds;
fromNanoseconds = base.fromNanoseconds;
adjust = base.adjust;
}
@Override
protected JsonDeserializer<T> withDateFormat(DateTimeFormatter dtf) {
if (dtf == _formatter) {
return this;
}
return new CustomInstantDeserializer<T>(this, dtf);
}
@Override
public T deserialize(JsonParser parser, DeserializationContext context) throws IOException {
//NOTE: Timestamps contain no timezone info, and are always in configured TZ. Only
//string values have to be adjusted to the configured TZ.
switch (parser.getCurrentTokenId()) {
case JsonTokenId.ID_NUMBER_FLOAT: {
BigDecimal value = parser.getDecimalValue();
long seconds = value.longValue();
int nanoseconds = DecimalUtils.extractNanosecondDecimal(value, seconds);
return fromNanoseconds.apply(new FromDecimalArguments(
seconds, nanoseconds, getZone(context)));
}
case JsonTokenId.ID_NUMBER_INT: {
long timestamp = parser.getLongValue();
if (context.isEnabled(DeserializationFeature.READ_DATE_TIMESTAMPS_AS_NANOSECONDS)) {
return this.fromNanoseconds.apply(new FromDecimalArguments(
timestamp, 0, this.getZone(context)
));
}
return this.fromMilliseconds.apply(new FromIntegerArguments(
timestamp, this.getZone(context)
));
}
case JsonTokenId.ID_STRING: {
String string = parser.getText().trim();
if (string.length() == 0) {
return null;
}
if (string.endsWith("+0000")) {
string = string.substring(0, string.length() - 5) + "Z";
}
T value;
try {
TemporalAccessor acc = _formatter.parse(string);
value = parsedToValue.apply(acc);
if (context.isEnabled(DeserializationFeature.ADJUST_DATES_TO_CONTEXT_TIME_ZONE)) {
return adjust.apply(value, this.getZone(context));
}
} catch (DateTimeException e) {
throw _peelDTE(e);
}
return value;
}
}
throw context.mappingException("Expected type float, integer, or string.");
}
private ZoneId getZone(DeserializationContext context) {
// Instants are always in UTC, so don't waste compute cycles
return (_valueClass == Instant.class) ? null : DateTimeUtils.timeZoneToZoneId(context.getTimeZone());
}
private static class FromIntegerArguments {
public final long value;
public final ZoneId zoneId;
private FromIntegerArguments(long value, ZoneId zoneId) {
this.value = value;
this.zoneId = zoneId;
}
}
private static class FromDecimalArguments {
public final long integer;
public final int fraction;
public final ZoneId zoneId;
private FromDecimalArguments(long integer, int fraction, ZoneId zoneId) {
this.integer = integer;
this.fraction = fraction;
this.zoneId = zoneId;
}
}
}
package nl.uva.sne.drip.configuration;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
/**
* Home redirection to swagger api documentation
*/
@Controller
public class HomeController {
@RequestMapping(value = "/")
public String index() {
System.out.println("swagger-ui.html");
return "redirect:swagger-ui.html";
}
}
package nl.uva.sne.drip.configuration;
import com.fasterxml.jackson.datatype.threetenbp.ThreeTenModule;
import org.springframework.boot.autoconfigure.condition.ConditionalOnMissingBean;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.threeten.bp.Instant;
import org.threeten.bp.OffsetDateTime;
import org.threeten.bp.ZonedDateTime;
@Configuration
public class JacksonConfiguration {
@Bean
@ConditionalOnMissingBean(ThreeTenModule.class)
ThreeTenModule threeTenModule() {
ThreeTenModule module = new ThreeTenModule();
module.addDeserializer(Instant.class, CustomInstantDeserializer.INSTANT);
module.addDeserializer(OffsetDateTime.class, CustomInstantDeserializer.OFFSET_DATE_TIME);
module.addDeserializer(ZonedDateTime.class, CustomInstantDeserializer.ZONED_DATE_TIME);
return module;
}
}
/*
* Copyright 2017 S. Koulouzis, Wang Junchao, Huan Zhou, Yang Hu
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package nl.uva.sne.drip.configuration;
import com.mongodb.Mongo;
import com.mongodb.MongoClient;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.context.annotation.ComponentScan;
import org.springframework.context.annotation.Configuration;
import org.springframework.context.annotation.PropertySource;
import org.springframework.context.annotation.PropertySources;
import org.springframework.data.mongodb.config.AbstractMongoConfiguration;
import org.springframework.data.mongodb.repository.config.EnableMongoRepositories;
/**
*
* @author S. Koulouzis
*/
@Configuration
@EnableMongoRepositories(basePackages = "nl.uva.sne.drip.api")
@PropertySources({
@PropertySource(value = "classpath:drip.properties", ignoreResourceNotFound = true)
,
@PropertySource(value = "file:etc/drip.properties", ignoreResourceNotFound = true)
})
@ComponentScan(basePackages = {"nl.uva.sne.drip", "nl.uva.sne.drip.api", "nl.uva.sne.drip.configuration", "nl.uva.sne.drip.dao", "nl.uva.sne.drip.model", "nl.uva.sne.drip.service"})
public class MongoConfig extends AbstractMongoConfiguration {
@Value("${db.name}")
private String dbName;
@Value("${db.host}")
private String dbHost;
@Value("${db.username}")
private String dbUsername;
@Value("${db.password}")
private String dbPass;
// @Autowired
// private MongoDbFactory mongoFactory;
// @Autowired
// private MongoMappingContext mongoMappingContext;
@Override
protected String getDatabaseName() {
return dbName;
}
@Override
protected String getMappingBasePackage() {
return "nl.uva.sne.drip";
}
@Override
public MongoClient mongoClient() {
return new MongoClient(dbHost, 27017);
}
}
package nl.uva.sne.drip.configuration;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import springfox.documentation.builders.ApiInfoBuilder;
import springfox.documentation.builders.RequestHandlerSelectors;
import springfox.documentation.service.ApiInfo;
import springfox.documentation.service.Contact;
import springfox.documentation.spi.DocumentationType;
import springfox.documentation.spring.web.plugins.Docket;
@javax.annotation.Generated(value = "nl.uva.sne.drip.codegen.languages.SpringCodegen", date = "2019-10-09T14:00:37.436Z")
@Configuration
public class SwaggerDocumentationConfig {
ApiInfo apiInfo() {
return new ApiInfoBuilder()
.title("DRIP")
.description("The Dynamic Real-time infrastructure planner (DRIP) allows application developers to seamlessly plan a customized virtual infrastructure based on application level constraints on QoS and resource budgets, provisioning the virtual infrastructure, deploy application components onto the virtual infrastructure, and start execution on demand using TOSCA.")
.license("Apache 2.0")
.licenseUrl("http://www.apache.org/licenses/LICENSE-2.0.html")
.termsOfServiceUrl("")
.version("3.0.0")
.contact(new Contact("","", "z.zhao@uva.nl"))
.build();
}
@Bean
public Docket customImplementation(){
return new Docket(DocumentationType.SWAGGER_2)
.select()
.apis(RequestHandlerSelectors.basePackage("nl.uva.sne.drip.api"))
.build()
.directModelSubstitute(org.threeten.bp.LocalDate.class, java.sql.Date.class)
.directModelSubstitute(org.threeten.bp.OffsetDateTime.class, java.util.Date.class)
.apiInfo(apiInfo());
}
}
/*
* To change this license header, choose License Headers in Project Properties.
* To change this template file, choose Tools | Templates
* and open the template in the editor.
*/
package nl.uva.sne.drip.dao;
import nl.uva.sne.drip.model.User;
import org.springframework.data.mongodb.repository.MongoRepository;
import org.springframework.stereotype.Repository;
/**
*
* @author S. Koulouzis
*/
@Repository
public interface TopologTemplateDAO extends MongoRepository<User, String> {
}
package nl.uva.sne.drip.model;
import java.util.Objects;
import com.fasterxml.jackson.annotation.JsonProperty;
import com.fasterxml.jackson.annotation.JsonCreator;
import io.swagger.annotations.ApiModel;
import io.swagger.annotations.ApiModelProperty;
import org.springframework.validation.annotation.Validated;
import javax.validation.Valid;
import javax.validation.constraints.*;
/**
* User
*/
@Validated
@javax.annotation.Generated(value = "nl.uva.sne.drip.codegen.languages.SpringCodegen", date = "2019-10-09T14:00:37.436Z")
public class User {
@JsonProperty("id")
private Long id = null;
@JsonProperty("username")
private String username = null;
@JsonProperty("firstName")
private String firstName = null;
@JsonProperty("lastName")
private String lastName = null;
@JsonProperty("email")
private String email = null;
@JsonProperty("password")
private String password = null;
@JsonProperty("userStatus")
private Integer userStatus = null;
public User id(Long id) {
this.id = id;
return this;
}
/**
* Get id
*
* @return id
*
*/
@ApiModelProperty(value = "")
public Long getId() {
return id;
}
public void setId(Long id) {
this.id = id;
}
public User username(String username) {
this.username = username;
return this;
}
/**
* Get username
*
* @return username
*
*/
@ApiModelProperty(value = "")
public String getUsername() {
return username;
}
public void setUsername(String username) {
this.username = username;
}
public User firstName(String firstName) {
this.firstName = firstName;
return this;
}
/**
* Get firstName
*
* @return firstName
*
*/
@ApiModelProperty(value = "")
public String getFirstName() {
return firstName;
}
public void setFirstName(String firstName) {
this.firstName = firstName;
}
public User lastName(String lastName) {
this.lastName = lastName;
return this;
}
/**
* Get lastName
*
* @return lastName
*
*/
@ApiModelProperty(value = "")
public String getLastName() {
return lastName;
}
public void setLastName(String lastName) {
this.lastName = lastName;
}
public User email(String email) {
this.email = email;
return this;
}
/**
* Get email
*
* @return email
*
*/
@ApiModelProperty(value = "")
public String getEmail() {
return email;
}
public void setEmail(String email) {
this.email = email;
}
public User password(String password) {
this.password = password;
return this;
}
/**
* Get password
*
* @return password
*
*/
@ApiModelProperty(value = "")
public String getPassword() {
return password;
}
public void setPassword(String password) {
this.password = password;
}
public User userStatus(Integer userStatus) {
this.userStatus = userStatus;
return this;
}
/**
* User Status
*
* @return userStatus
*
*/
@ApiModelProperty(value = "User Status")
public Integer getUserStatus() {
return userStatus;
}
public void setUserStatus(Integer userStatus) {
this.userStatus = userStatus;
}
@Override
public boolean equals(java.lang.Object o) {
if (this == o) {
return true;
}
if (o == null || getClass() != o.getClass()) {
return false;
}
User user = (User) o;
return Objects.equals(this.id, user.id)
&& Objects.equals(this.username, user.username)
&& Objects.equals(this.firstName, user.firstName)
&& Objects.equals(this.lastName, user.lastName)
&& Objects.equals(this.email, user.email)
&& Objects.equals(this.password, user.password)
&& Objects.equals(this.userStatus, user.userStatus);
}
@Override
public int hashCode() {
return Objects.hash(id, username, firstName, lastName, email, password, userStatus);
}
@Override
public String toString() {
StringBuilder sb = new StringBuilder();
sb.append("class User {\n");
sb.append(" id: ").append(toIndentedString(id)).append("\n");
sb.append(" username: ").append(toIndentedString(username)).append("\n");
sb.append(" firstName: ").append(toIndentedString(firstName)).append("\n");
sb.append(" lastName: ").append(toIndentedString(lastName)).append("\n");
sb.append(" email: ").append(toIndentedString(email)).append("\n");
sb.append(" password: ").append(toIndentedString(password)).append("\n");
sb.append(" userStatus: ").append(toIndentedString(userStatus)).append("\n");
sb.append("}");
return sb.toString();
}
/**
* Convert the given object to string with each line indented by 4 spaces
* (except the first line).
*/
private String toIndentedString(java.lang.Object o) {
if (o == null) {
return "null";
}
return o.toString().replace("\n", "\n ");
}
}
/*
* To change this license header, choose License Headers in Project Properties.
* To change this template file, choose Tools | Templates
* and open the template in the editor.
*/
package nl.uva.sne.drip.service;
import nl.uva.sne.drip.dao.TopologTemplateDAO;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
/**
*
* @author S. Koulouzis
*/
@Service
public class TopologTemplateService {
@Autowired
private TopologTemplateDAO dao;
}
springfox.documentation.swagger.v2.path=/api-docs
server.contextPath=/drip-api
server.port=8080
spring.jackson.date-format=nl.uva.sne.drip.RFC3339DateFormat
spring.jackson.serialization.WRITE_DATES_AS_TIMESTAMPS=false
message.broker.host=127.0.0.1
db.host=127.0.0.1
db.name=drip
db.username=drip-user
db.password=drip-pass
\ No newline at end of file
...@@ -14,5 +14,6 @@ ...@@ -14,5 +14,6 @@
<module>drip-planner2provisioner</module> <module>drip-planner2provisioner</module>
<module>drip-commons</module> <module>drip-commons</module>
<module>drip-provisioner</module> <module>drip-provisioner</module>
<module>drip-manager</module>
</modules> </modules>
</project> </project>
\ No newline at end of file
Markdown is supported
0% or
You are about to add 0 people to the discussion. Proceed with caution.
Finish editing this message first!
Please register or to comment