io.swagger.annotations.ExampleProperty Java Examples

The following examples show how to use io.swagger.annotations.ExampleProperty. You can vote up the ones you like or vote down the ones you don't like, and go to the original project or source file by following the links above each example. You may check out the related API usage on the sidebar.
Example #1
Source File: RestFolderService.java    From document-management-software with GNU Lesser General Public License v3.0 6 votes vote down vote up
@POST
@Path("/createSimpleJSON")
@Consumes({ MediaType.APPLICATION_JSON })
@ApiOperation(value = "Creates folders from path", notes = "Creates folders using an input path. All the folders in the path will be created. It returns the metadata object representing the latest created folder in the path")
public WSFolder createSimpleJSON(
		@ApiParam(name = "folderPath", value = "The string representing the path to be created", examples = @Example(value = {
				@ExampleProperty(value = "{\"folderPath\":\"/Default/central/repo\"}") })) String jsonstr)
		throws Exception {
	log.debug("createSimpleJSON()");

	String sid = validateSession();

	ObjectMapper mapper = new ObjectMapper();
	TypeReference<HashMap<String, String>> typeRef = new TypeReference<HashMap<String, String>>() {
	};
	HashMap<String, String> hm = mapper.readValue(jsonstr, typeRef);

	String folderPath = hm.get("folderPath");

	WSFolder root = super.getRootFolder(sid);
	return super.createPath(sid, root.getId(), folderPath);
}
 
Example #2
Source File: RestFolderService.java    From document-management-software with GNU Lesser General Public License v3.0 6 votes vote down vote up
@POST
@Path("/createSimple")
@Consumes({ MediaType.TEXT_PLAIN, MediaType.APPLICATION_JSON })
@ApiOperation(value = "Creates folders from path", notes = "Creates folders using an input path. All the folders in the path will be created. It returns the metadata object representing the latest created folder in the path. "
		+ "Example: curl -u admin:admin -X POST -H ''Content-Type: text/plain'' -H ''Accept: application/json'' -d ''/Default/Curl/newfolder'' http://localhost:8080/services/rest/folder/createSimple")
public WSFolder createSimple(
		@ApiParam(value = "The string representing the path to be created", examples = @Example(value = {
				@ExampleProperty(value = "/Default/newfolder") })) String folderPath)
		throws Exception {
	log.debug("createSimple()");

	String sid = validateSession();

	WSFolder root = super.getRootFolder(sid);
	return super.createPath(sid, root.getId(), folderPath);
}
 
Example #3
Source File: ParseService.java    From yauaa with Apache License 2.0 6 votes vote down vote up
@ApiOperation(
    value = "Analyze the provided User-Agent"
)
@PostMapping(
    value = { API_BASE_PATH + "/analyze", API_BASE_PATH + "/analyze/xml" },
    consumes = TEXT_PLAIN_VALUE,
    produces = APPLICATION_XML_VALUE
)
public String getXMLPOST(
    @ApiParam(
        name ="Request body",
        type = "Map",
        defaultValue = EXAMPLE_USERAGENT,
        value = "The entire POSTed value is used as the input that is to be analyzed.",
        examples = @Example(@ExampleProperty(mediaType = TEXT_PLAIN_VALUE, value = EXAMPLE_USERAGENT))
    )
    @RequestBody String userAgentString
) {
    return doXML(userAgentString);
}
 
Example #4
Source File: Reader.java    From dorado with Apache License 2.0 6 votes vote down vote up
private Map<String, Object> parseExamples(Example examples) {
	if (examples == null) {
		return null;
	}

	Map<String, Object> map = null;
	for (ExampleProperty prop : examples.value()) {

		if (prop.mediaType().equals("") && prop.value().equals("")) {
			continue;
		}

		map = map == null ? new LinkedHashMap<String, Object>() : map;
		map.put(prop.mediaType(), prop.value());
	}
	return map;
}
 
Example #5
Source File: SpringIntegrationWebMvcApplication.java    From springfox-demos with Apache License 2.0 5 votes vote down vote up
@ApiResponses(
        @ApiResponse(code = 200, message = "OK",
                examples = @Example(@ExampleProperty(mediaType = "application/json",
                        value = "{\"gnarf\": \"dragons\"}"))))
@PostMapping("/conversion/controller")
public @ResponseBody
Baz convert(@RequestBody Baz baz) {
    return baz;
}
 
Example #6
Source File: RestFolderService.java    From document-management-software with GNU Lesser General Public License v3.0 5 votes vote down vote up
@POST
@Path("/create")
@ApiOperation(nickname = "createFolderByModel", value = "Creates a new folder", notes = "The 'folder' metadata comes in the POST request body (encoded as JSON). Note: folder object must specify at least fields name and parentId")
public WSFolder create(@ApiParam(value = "The folder metadata", required = true, examples = @Example(value = {
		@ExampleProperty(value = "{ \"parentId\": 4, \"name\": \"Folder created by REST ws\"}") })) WSFolder folder)
		throws Exception {
	log.debug("create()");
	String sid = validateSession();
	return super.create(sid, folder);
}
 
Example #7
Source File: WorkspaceService.java    From che with Eclipse Public License 2.0 5 votes vote down vote up
@GET
@Path("/{key:.*}")
@Produces(APPLICATION_JSON)
@ApiOperation(
    value = "Get the workspace by the composite key",
    notes =
        "Composite key can be just workspace ID or in the "
            + "namespace:workspace_name form, where namespace is optional (e.g :workspace_name is valid key too."
            + "namespace/workspace_name form, where namespace can contain '/' character.")
@ApiResponses({
  @ApiResponse(code = 200, message = "The response contains requested workspace entity"),
  @ApiResponse(code = 404, message = "The workspace with specified id does not exist"),
  @ApiResponse(code = 403, message = "The user is not workspace owner"),
  @ApiResponse(code = 500, message = "Internal server error occurred")
})
public WorkspaceDto getByKey(
    @ApiParam(
            value = "Composite key",
            examples =
                @Example({
                  @ExampleProperty("workspace12345678"),
                  @ExampleProperty("namespace/workspace_name"),
                  @ExampleProperty("namespace_part_1/namespace_part_2/workspace_name")
                }))
        @PathParam("key")
        String key,
    @ApiParam("Whether to include internal servers into runtime or not")
        @DefaultValue("false")
        @QueryParam("includeInternalServers")
        String includeInternalServers)
    throws NotFoundException, ServerException, ForbiddenException, BadRequestException {
  validateKey(key);
  boolean bIncludeInternalServers =
      isNullOrEmpty(includeInternalServers) || Boolean.parseBoolean(includeInternalServers);
  return filterServers(
      asDtoWithLinksAndToken(workspaceManager.getWorkspace(key)), bIncludeInternalServers);
}
 
Example #8
Source File: ParseService.java    From yauaa with Apache License 2.0 5 votes vote down vote up
@ApiOperation(
    value = "Fire all available test cases against the analyzer to heat up the JVM"
)
@ApiResponses({
    @ApiResponse(
        code = 200, // HttpStatus.OK
        message = "The number of reported tests were done to preheat the engine",
        examples = @Example(
            value = {
                @ExampleProperty(mediaType = APPLICATION_JSON_VALUE, value = "{\n" +
                    "  \"status\": \"Ran tests\",\n" +
                    "  \"testsDone\": 2337,\n" +
                    "  \"timeInMs\": 3123\n" +
                    "}"),
            }
        )
    )
})
@GetMapping(
    value = API_BASE_PATH + "/preheat",
    produces = APPLICATION_JSON_VALUE
)
public String getPreHeat() {
    ensureStartedForApis(OutputType.JSON);
    final int cacheSize = userAgentAnalyzer.getCacheSize();
    userAgentAnalyzer.disableCaching();
    long       start     = System.nanoTime();
    final long testsDone = userAgentAnalyzer.preHeat();
    long       stop      = System.nanoTime();
    userAgentAnalyzer.setCacheSize(cacheSize);
    if (testsDone == 0) {
        return "{ \"status\": \"No testcases available\", \"testsDone\": 0 , \"timeInMs\" : -1 } ";
    }
    return "{ \"status\": \"Ran tests\", \"testsDone\": " + testsDone + " , \"timeInMs\" : " + (stop - start) / 1000000 + " } ";
}
 
Example #9
Source File: ParseService.java    From yauaa with Apache License 2.0 5 votes vote down vote up
@ApiOperation(
    value = "Analyze the provided User-Agent",
    notes = "<b>Trying this in swagger does not work in Chrome as Chrome does not allow setting " +
            "a different User-Agent: https://github.com/swagger-api/swagger-ui/issues/5035</b>"
)
@ApiResponses({
    @ApiResponse(
        code = 200, // HttpStatus.OK
        message = "The agent was successfully analyzed",
        examples = @Example({
            @ExampleProperty(mediaType = APPLICATION_JSON_VALUE, value = EXAMPLE_JSON),
            @ExampleProperty(mediaType = APPLICATION_XML_VALUE,  value = EXAMPLE_XML),
            @ExampleProperty(mediaType = TEXT_XYAML_VALUE,       value = EXAMPLE_YAML),
            @ExampleProperty(mediaType = TEXT_PLAIN_VALUE,       value = EXAMPLE_YAML)
        })
    )
})
@GetMapping(
    value = { API_BASE_PATH + "/analyze", API_BASE_PATH + "/analyze/xml" },
    produces = APPLICATION_XML_VALUE
)
public String getXMLGET(
    @ApiParam(
        value = "The standard browser request header User-Agent is used as the input that is to be analyzed.",
        example = EXAMPLE_USERAGENT
    )
    @RequestHeader("User-Agent")
        String userAgentString
) {
    return doXML(userAgentString);
}
 
Example #10
Source File: ParseService.java    From yauaa with Apache License 2.0 5 votes vote down vote up
@ApiOperation(
    value = "Analyze the provided User-Agent"
)
@PostMapping(
    value = { API_BASE_PATH + "/analyze", API_BASE_PATH + "/analyze/json" },
    consumes = TEXT_PLAIN_VALUE,
    produces = APPLICATION_JSON_VALUE
)
@ApiResponses({
    @ApiResponse(
        code = 200, // HttpStatus.OK
        message = "The agent was successfully analyzed",
        examples = @Example({
            @ExampleProperty(mediaType = APPLICATION_JSON_VALUE,    value = EXAMPLE_JSON),
            @ExampleProperty(mediaType = APPLICATION_XML_VALUE,     value = EXAMPLE_XML),
            @ExampleProperty(mediaType = TEXT_XYAML_VALUE,          value = EXAMPLE_YAML),
            @ExampleProperty(mediaType = TEXT_PLAIN_VALUE,          value = EXAMPLE_YAML)
        })
    )
})
public String getJSonPOST(
    @ApiParam(
        name ="Request body",
        type = "Map",
        defaultValue = EXAMPLE_USERAGENT,
        value = "The entire POSTed value is used as the input that is to be analyzed.",
        examples = @Example(@ExampleProperty(mediaType = TEXT_PLAIN_VALUE, value = EXAMPLE_USERAGENT))
    )
    @RequestBody String userAgentString
) {
    return doJSon(userAgentString);
}
 
Example #11
Source File: ParseService.java    From yauaa with Apache License 2.0 5 votes vote down vote up
@ApiOperation(
    value = "Analyze the provided User-Agent",
    notes = "<b>Trying this in swagger does not work in Chrome as Chrome does not allow setting " +
            "a different User-Agent: https://github.com/swagger-api/swagger-ui/issues/5035</b>"
)
@ApiResponses({
    @ApiResponse(
        code = 200, // HttpStatus.OK
        message = "The agent was successfully analyzed",
        examples = @Example({
            @ExampleProperty(mediaType = APPLICATION_JSON_VALUE,    value = EXAMPLE_JSON),
            @ExampleProperty(mediaType = APPLICATION_XML_VALUE,     value = EXAMPLE_XML),
            @ExampleProperty(mediaType = TEXT_XYAML_VALUE,          value = EXAMPLE_YAML),
            @ExampleProperty(mediaType = TEXT_PLAIN_VALUE,          value = EXAMPLE_YAML)
        })
    )
})
@GetMapping(
    value = { API_BASE_PATH + "/analyze", API_BASE_PATH + "/analyze/json" },
    produces = APPLICATION_JSON_VALUE
)
public String getJSonGET(
    @ApiParam(
        value = "The standard browser request header User-Agent is used as the input that is to be analyzed.",
        example = EXAMPLE_USERAGENT
    )
    @RequestHeader("User-Agent")
    String userAgentString
) {
    return doJSon(userAgentString);
}
 
Example #12
Source File: ParseService.java    From yauaa with Apache License 2.0 5 votes vote down vote up
@ApiOperation(
    value = "Analyze the provided User-Agent"
)
@PostMapping(
    value = { API_BASE_PATH + "/analyze", API_BASE_PATH + "/analyze/yaml" },
    consumes = TEXT_PLAIN_VALUE,
    produces = { TEXT_XYAML_VALUE, TEXT_PLAIN_VALUE }
)
@ApiResponses({
    @ApiResponse(
        code = 200, // HttpStatus.OK
        message = "The agent was successfully analyzed",
        examples = @Example({
            @ExampleProperty(mediaType = APPLICATION_JSON_VALUE,    value = EXAMPLE_JSON),
            @ExampleProperty(mediaType = APPLICATION_XML_VALUE,     value = EXAMPLE_XML),
            @ExampleProperty(mediaType = TEXT_XYAML_VALUE,          value = EXAMPLE_YAML),
            @ExampleProperty(mediaType = TEXT_PLAIN_VALUE,          value = EXAMPLE_YAML)
        })
    )
})
public String getYamlPOST(
    @ApiParam(
        name ="Request body",
        type = "Map",
        defaultValue = EXAMPLE_USERAGENT,
        value = "The entire POSTed value is used as the input that is to be analyzed.",
        examples = @Example(@ExampleProperty(mediaType = TEXT_PLAIN_VALUE, value = EXAMPLE_USERAGENT))
    )
    @RequestBody String userAgentString
) {
    return doYaml(userAgentString);
}
 
Example #13
Source File: ParseService.java    From yauaa with Apache License 2.0 5 votes vote down vote up
@ApiOperation(
    value = "Analyze the provided User-Agent",
    notes = "<b>Trying this in swagger does not work in Chrome as Chrome does not allow setting " +
        "a different User-Agent: https://github.com/swagger-api/swagger-ui/issues/5035</b>"
)
@ApiResponses({
    @ApiResponse(
        code = 200, // HttpStatus.OK
        message = "The agent was successfully analyzed",
        examples = @Example({
            @ExampleProperty(mediaType = APPLICATION_JSON_VALUE,    value = EXAMPLE_JSON),
            @ExampleProperty(mediaType = APPLICATION_XML_VALUE,     value = EXAMPLE_XML),
            @ExampleProperty(mediaType = TEXT_XYAML_VALUE,          value = EXAMPLE_YAML),
            @ExampleProperty(mediaType = TEXT_PLAIN_VALUE,          value = EXAMPLE_YAML)
        })
    )
})
@GetMapping(
    value = { API_BASE_PATH + "/analyze", API_BASE_PATH + "/analyze/yaml" },
    produces = { TEXT_XYAML_VALUE, TEXT_PLAIN_VALUE }
)
public String getYamlGET(
    @ApiParam(
        value = "The standard browser request header User-Agent is used as the input that is to be analyzed.",
        example = EXAMPLE_USERAGENT
    )
    @RequestHeader("User-Agent")
        String userAgentString
) {
    return doYaml(userAgentString);
}
 
Example #14
Source File: AnnotationUtils.java    From servicecomb-java-chassis with Apache License 2.0 5 votes vote down vote up
private static void addExamplesToResponse(Response response, ResponseConfig responseConfig) {
  if (responseConfig.getExamples() != null) {
    for (ExampleProperty property : responseConfig.getExamples().value()) {
      if (StringUtils.isEmpty(property.mediaType()) && StringUtils.isEmpty(property.value())) {
        // @ApiResponse default value has one element, but type and value is empty.
        // ignore this default value.
        continue;
      }
      if (StringUtils.isEmpty(property.mediaType())) {
        throw new IllegalStateException("media type is required in examples. e.g. 'text', 'json'.");
      }
      response.example(property.mediaType(), property.value());
    }
  }
}
 
Example #15
Source File: SpringMVCSchema.java    From servicecomb-java-chassis with Apache License 2.0 5 votes vote down vote up
@ApiResponses({
    @ApiResponse(code = 200, response = String.class, message = "success",
        examples = @Example({
            @ExampleProperty(value = "wget http://localhost/springMvcSchema/testApiExample", mediaType = "text"),
            @ExampleProperty(value = "{name:hello}", mediaType = "application/json"),
            @ExampleProperty(value = "{name:hello}", mediaType = "json")})
    )})
@RequestMapping(path = "/testApiExample", method = RequestMethod.POST)
public String testApiExample(@RequestBody String name, HttpServletRequest request) {
  return null;
}
 
Example #16
Source File: ApiParamSpringmvcSchema.java    From servicecomb-java-chassis with Apache License 2.0 5 votes vote down vote up
@PostMapping(path = "/body")
public void body(@ApiParam(value = "desc of body param",
    required = true,
    name = "modelEx",
    examples = @Example(value = {
        @ExampleProperty(mediaType = "k1", value = "v1"),
        @ExampleProperty(mediaType = "k2", value = "v2")})) @RequestBody CommonModel model) {

}
 
Example #17
Source File: RestSearchService.java    From document-management-software with GNU Lesser General Public License v3.0 5 votes vote down vote up
@POST
@Path("/find")
@ApiOperation(value = "Search documents", notes = "Runs a search on the server")
public WSSearchResult find(
		@ApiParam(value = "Search options", required = true, examples = @Example(value = { @ExampleProperty(value = "{\"maxHits\":50,\"expression\":\"document management system\",\"expressionLanguage\":\"en\",\"language\":\"en\"}") })) WSSearchOptions opt)
		throws Exception {
	String sid = validateSession();
	return super.find(sid, opt);
}
 
Example #18
Source File: RestDocumentService.java    From document-management-software with GNU Lesser General Public License v3.0 5 votes vote down vote up
@Override
@PUT
@Path("/update")
@ApiOperation(value = "Updates an existing document", notes = "Updates the metadata of an existing document. The ID of the document must be specified in the WSDocument value object. The provided example moves document with ID 1111111 to folder 3435433")
public void update(
		@ApiParam(value = "Document object that needs to be updated", required = true, examples = @Example(value = {
				@ExampleProperty(value = "{ \"id\": 1111111, \"folderId\": 3435433 }") })) WSDocument document)
		throws Exception {
	String sid = validateSession();
	super.update(sid, document);
}
 
Example #19
Source File: RestDocumentService.java    From document-management-software with GNU Lesser General Public License v3.0 5 votes vote down vote up
@Override
@POST
@Path("/create")
@Consumes(MediaType.MULTIPART_FORM_DATA)
@ApiOperation(nickname = "createDocument", value = "Creates a new document", notes = "Creates a new document using the metadata document object provided as JSON/XML", response = WSDocument.class)
@ApiImplicitParams({
		@ApiImplicitParam(name = "document", value = "The document metadata provided as WSDocument object encoded in JSON/XML format", required = true, dataType = "string", paramType = "form", examples = @Example(value = {
				@ExampleProperty(value = "{ \"fileName\":\"Help.pdf\",\"folderId\": 4, \"language\":\"en\" }") })),
		@ApiImplicitParam(name = "content", value = "File data", required = true, dataType = "file", paramType = "form") })
@ApiResponses(value = { @ApiResponse(code = 401, message = "Authentication failed"),
		@ApiResponse(code = 500, message = "Generic error, see the response message") })
public Response create(@ApiParam(hidden = true) List<Attachment> atts) throws Exception {
	log.debug("create()");

	String sid = validateSession();

	WSDocument document = null;
	DataHandler content = null;

	for (Attachment att : atts) {
		if ("document".equals(att.getContentDisposition().getParameter("name"))) {
			document = att.getObject(WSDocument.class);
		} else if ("content".equals(att.getContentDisposition().getParameter("name"))) {
			content = att.getDataHandler();
		}
	}

	log.debug("document: {}", document);
	log.debug("content: {}", content);

	try {
		// return super.create(sid, document, content);
		WSDocument cdoc = super.create(sid, document, content);
		return Response.ok().entity(cdoc).build();
	} catch (Exception e) {
		log.error(e.getMessage(), e);
		return Response.status(500).entity(e.getMessage()).build();
	}
}
 
Example #20
Source File: RestFolderService.java    From document-management-software with GNU Lesser General Public License v3.0 5 votes vote down vote up
@POST
@Path("/update")
@ApiOperation(nickname = "updateFolder", value = "Updates a folder", notes = "Updates a folder changing its metadata. The folder object in input must specify the property id")
public void update(
		@ApiParam(value = "A value object with the metadata of the folder to update", examples = @Example(value = {
				@ExampleProperty(value = "{ \"id\": 2335253, \"name\": \"Folder updated by REST ws\"}") })) WSFolder folder)
		throws Exception {
	log.debug("update()");
	String sid = validateSession();
	super.update(sid, folder);
}
 
Example #21
Source File: ParseService.java    From yauaa with Apache License 2.0 4 votes vote down vote up
@ApiOperation(
    value = "Fire all available test cases against the analyzer and return 200 if all tests were good"
)
@ApiResponses({
    @ApiResponse(
        code = 200, // HttpStatus.OK
        message = "All tests were good",
        examples = @Example(
            value = {
                @ExampleProperty(
                    mediaType = TEXT_PLAIN_VALUE,
                    value = "All tests passed"),
            }
        )
    ),
    @ApiResponse(
        code = 500, // HttpStatus.INTERNAL_SERVER_ERROR
        message = "A test failed",
        examples = @Example(
            value = {
                @ExampleProperty(
                    mediaType = TEXT_PLAIN_VALUE,
                    value = "Extensive text describing what went wrong in the test that failed"),
            }
        )
    )
})
@GetMapping(
    value = API_BASE_PATH + "/runtests",
    produces = TEXT_PLAIN_VALUE
)
public String getRunTests() {
    UserAgentAnalyzerTester tester = UserAgentAnalyzerTester.newBuilder()
        .hideMatcherLoadStats()
        .addOptionalResources("file:UserAgents*/*.yaml")
        .immediateInitialization()
        .keepTests()
        .build();
    StringBuilder errorMessage = new StringBuilder();
    boolean ok = tester.runTests(false, true, null, false, false, errorMessage);
    if (ok) {
        return "All tests passed";
    }
    throw new YauaaTestsFailed(errorMessage.toString());
}
 
Example #22
Source File: WorkspaceService.java    From che with Eclipse Public License 2.0 4 votes vote down vote up
@POST
@Consumes(APPLICATION_JSON)
@Produces(APPLICATION_JSON)
@ApiOperation(
    value = "Create a new workspace based on the configuration",
    notes =
        "This operation can be performed only by authorized user,"
            + "this user will be the owner of the created workspace",
    consumes = APPLICATION_JSON,
    produces = APPLICATION_JSON,
    response = WorkspaceConfigDto.class)
@ApiResponses({
  @ApiResponse(code = 201, message = "The workspace successfully created"),
  @ApiResponse(code = 400, message = "Missed required parameters, parameters are not valid"),
  @ApiResponse(code = 403, message = "The user does not have access to create a new workspace"),
  @ApiResponse(
      code = 409,
      message =
          "Conflict error occurred during the workspace creation"
              + "(e.g. The workspace with such name already exists)"),
  @ApiResponse(code = 500, message = "Internal server error occurred")
})
public Response create(
    @ApiParam(value = "The configuration to create the new workspace", required = true)
        WorkspaceConfigDto config,
    @ApiParam(
            value =
                "Workspace attribute defined in 'attrName:attrValue' format. "
                    + "The first ':' is considered as attribute name and value separator",
            examples = @Example({@ExampleProperty("attrName:value-with:colon")}))
        @QueryParam("attribute")
        List<String> attrsList,
    @ApiParam(
            value =
                "The target infrastructure namespace (Kubernetes namespace or OpenShift"
                    + " project) where the workspace should be deployed to when started. This"
                    + " parameter is optional. The workspace creation will fail if the Che server"
                    + " is configured to not allow deploying into that infrastructure namespace.")
        @QueryParam("infrastructure-namespace")
        String infrastructureNamespace,
    @ApiParam(
            "If true then the workspace will be immediately "
                + "started after it is successfully created")
        @QueryParam("start-after-create")
        @DefaultValue("false")
        Boolean startAfterCreate,
    @ApiParam("Namespace where workspace should be created") @QueryParam("namespace")
        String namespace)
    throws ConflictException, ServerException, BadRequestException, ForbiddenException,
        NotFoundException {
  requiredNotNull(config, "Workspace configuration");
  final Map<String, String> attributes = parseAttrs(attrsList);
  relativizeRecipeLinks(config);
  if (namespace == null) {
    namespace = EnvironmentContext.getCurrent().getSubject().getUserName();
  }
  if (!isNullOrEmpty(infrastructureNamespace)) {
    attributes.put(WORKSPACE_INFRASTRUCTURE_NAMESPACE_ATTRIBUTE, infrastructureNamespace);
  }
  WorkspaceImpl workspace;
  try {
    workspace = workspaceManager.createWorkspace(config, namespace, attributes);
  } catch (ValidationException x) {
    throw new BadRequestException(x.getMessage());
  }

  if (startAfterCreate) {
    workspaceManager.startWorkspace(workspace.getId(), null, new HashMap<>());
  }
  return Response.status(201).entity(asDtoWithLinksAndToken(workspace)).build();
}
 
Example #23
Source File: WorkspaceService.java    From che with Eclipse Public License 2.0 4 votes vote down vote up
@Path("/devfile")
@POST
@Consumes({APPLICATION_JSON, "text/yaml", "text/x-yaml"})
@Produces(APPLICATION_JSON)
@ApiOperation(
    value = "Creates a new workspace based on the Devfile.",
    consumes = "application/json, text/yaml, text/x-yaml",
    produces = APPLICATION_JSON,
    nickname = "createFromDevfile",
    response = WorkspaceConfigDto.class)
@ApiResponses({
  @ApiResponse(code = 201, message = "The workspace successfully created"),
  @ApiResponse(code = 400, message = "Missed required parameters, parameters are not valid"),
  @ApiResponse(code = 403, message = "The user does not have access to create a new workspace"),
  @ApiResponse(
      code = 409,
      message =
          "Conflict error occurred during the workspace creation"
              + "(e.g. The workspace with such name already exists)"),
  @ApiResponse(code = 500, message = "Internal server error occurred")
})
public Response create(
    @ApiParam(value = "The devfile of the workspace to create", required = true)
        DevfileDto devfile,
    @ApiParam(
            value =
                "Workspace attribute defined in 'attrName:attrValue' format. "
                    + "The first ':' is considered as attribute name and value separator",
            examples = @Example({@ExampleProperty("attrName:value-with:colon")}))
        @QueryParam("attribute")
        List<String> attrsList,
    @ApiParam(
            value =
                "The target infrastructure namespace (Kubernetes namespace or OpenShift"
                    + " project) where the workspace should be deployed to when started. This"
                    + " parameter is optional. The workspace creation will fail if the Che server"
                    + " is configured to not allow deploying into that infrastructure namespace.")
        @QueryParam("infrastructure-namespace")
        String infrastructureNamespace,
    @ApiParam(
            "If true then the workspace will be immediately "
                + "started after it is successfully created")
        @QueryParam("start-after-create")
        @DefaultValue("false")
        Boolean startAfterCreate,
    @ApiParam("Che namespace where workspace should be created") @QueryParam("namespace")
        String namespace,
    @HeaderParam(CONTENT_TYPE) MediaType contentType)
    throws ConflictException, BadRequestException, ForbiddenException, NotFoundException,
        ServerException {
  requiredNotNull(devfile, "Devfile");
  final Map<String, String> attributes = parseAttrs(attrsList);
  if (namespace == null) {
    namespace = EnvironmentContext.getCurrent().getSubject().getUserName();
  }
  if (!isNullOrEmpty(infrastructureNamespace)) {
    attributes.put(WORKSPACE_INFRASTRUCTURE_NAMESPACE_ATTRIBUTE, infrastructureNamespace);
  }
  WorkspaceImpl workspace;
  try {
    workspace =
        workspaceManager.createWorkspace(
            devfile,
            namespace,
            attributes,
            // create a new cache for each request so that we don't have to care about lifetime
            // of the cache, etc. The content is cached only for the duration of this call
            // (i.e. all the validation and provisioning of the devfile will download each
            // referenced file only once per request)
            FileContentProvider.cached(devfileContentProvider));
  } catch (ValidationException x) {
    throw new BadRequestException(x.getMessage());
  }

  if (startAfterCreate) {
    workspaceManager.startWorkspace(workspace.getId(), null, new HashMap<>());
  }
  return Response.status(201).entity(asDtoWithLinksAndToken(workspace)).build();
}