com.sun.jersey.multipart.FormDataParam Java Examples

The following examples show how to use com.sun.jersey.multipart.FormDataParam. 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: PetApi.java    From openapi-generator with Apache License 2.0 6 votes vote down vote up
@POST
@Path("/fake/{petId}/uploadImageWithRequiredFile")
@Consumes({ "multipart/form-data" })
@Produces({ "application/json" })
@io.swagger.annotations.ApiOperation(value = "uploads an image (required)", notes = "", response = ModelApiResponse.class, authorizations = {
    @io.swagger.annotations.Authorization(value = "petstore_auth", scopes = {
        @io.swagger.annotations.AuthorizationScope(scope = "write:pets", description = "modify pets in your account"),
        @io.swagger.annotations.AuthorizationScope(scope = "read:pets", description = "read your pets")
    })
}, tags={ "pet" })
@io.swagger.annotations.ApiResponses(value = { 
    @io.swagger.annotations.ApiResponse(code = 200, message = "successful operation", response = ModelApiResponse.class) })
public Response uploadFileWithRequiredFile(
    @ApiParam(value = "ID of pet to update", required = true) @PathParam("petId") @NotNull  Long petId,
    @FormDataParam("requiredFile") InputStream inputStream,
    @FormDataParam("requiredFile") FormDataContentDisposition fileDetail,
    @FormDataParam("additionalMetadata")  String additionalMetadata,
    @Context SecurityContext securityContext)
throws NotFoundException {
    return delegate.uploadFileWithRequiredFile(petId,inputStream, fileDetail,additionalMetadata,securityContext);
}
 
Example #2
Source File: ArchiveRepositoryResource.java    From Nicobar with Apache License 2.0 6 votes vote down vote up
@POST
@Consumes(MediaType.MULTIPART_FORM_DATA)
public void insertArchive(
        @FormDataParam("moduleSpec") ScriptModuleSpec moduleSpec,
        @FormDataParam("archiveJar") InputStream file) {
    validateModuleSpec(moduleSpec);
    String moduleId = moduleSpec.getModuleId().toString();
    try {
        java.nio.file.Path tempFile = Files.createTempFile(moduleId, ".jar");
        Files.copy(file, tempFile, StandardCopyOption.REPLACE_EXISTING);
        JarScriptArchive jarScriptArchive = new JarScriptArchive.Builder(tempFile)
            .setModuleSpec(moduleSpec)
            .build();
        repository.insertArchive(jarScriptArchive);
    } catch (IOException e) {
        throw new WebApplicationException(e);
    }
}
 
Example #3
Source File: StaashDataResourceImpl.java    From staash with Apache License 2.0 6 votes vote down vote up
@POST
@Path("/kvstore/name/{name}")
@Consumes(MediaType.MULTIPART_FORM_DATA)
@Produces(MediaType.APPLICATION_JSON)
   @ResourceFilters(StaashAuditFilter.class)
public String storeNamedFile(
		@FormDataParam("value") InputStream uploadedInputStream,
		@PathParam("name") String name) {
	try {
		writeToChunkedKVStore(uploadedInputStream, name);
	} catch (IOException e) {
		e.printStackTrace();
		return "{\"msg\":\"file could not be uploaded\"}";
	}
	return "{\"msg\":\"file successfully uploaded\"}";
}
 
Example #4
Source File: StaashDataResourceImpl.java    From staash with Apache License 2.0 6 votes vote down vote up
@POST
@Path("/kvstore")
@Consumes(MediaType.MULTIPART_FORM_DATA)
@Produces(MediaType.APPLICATION_JSON)
   @ResourceFilters(StaashAuditFilter.class)
public String storeFile(
		@FormDataParam("value") InputStream uploadedInputStream,
		@FormDataParam("value") FormDataContentDisposition fileDetail) {
	try {
		writeToChunkedKVStore(uploadedInputStream, fileDetail.getFileName());
	} catch (IOException e) {
		e.printStackTrace();
		return "{\"msg\":\"file could not be uploaded\"}";
	}
	return "{\"msg\":\"file successfully uploaded\"}";
}
 
Example #5
Source File: FileResource.java    From ctsms with GNU Lesser General Public License v2.1 6 votes vote down vote up
@PUT
@Consumes(MediaType.MULTIPART_FORM_DATA)
@Produces({ MediaType.APPLICATION_JSON })
public FileOutVO updateFile(@FormDataParam("json") FormDataBodyPart json,
		@FormDataParam("data") FormDataBodyPart content,
		@FormDataParam("data") FormDataContentDisposition contentDisposition,
		@FormDataParam("data") final InputStream input) throws AuthenticationException, AuthorisationException, ServiceException {
	json.setMediaType(MediaType.APPLICATION_JSON_TYPE);
	FileInVO in = json.getValueAs(FileInVO.class);
	FileStreamInVO stream = new FileStreamInVO();
	stream.setStream(input);
	stream.setMimeType(content.getMediaType().toString());
	stream.setSize(contentDisposition.getSize());
	stream.setFileName(contentDisposition.getFileName());
	return WebUtil.getServiceLocator().getFileService().updateFile(auth, in, stream);
}
 
Example #6
Source File: FileResource.java    From ctsms with GNU Lesser General Public License v2.1 6 votes vote down vote up
@POST
@Consumes(MediaType.MULTIPART_FORM_DATA)
@Produces({ MediaType.APPLICATION_JSON })
public FileOutVO addFile(@FormDataParam("json") FormDataBodyPart json,
		@FormDataParam("data") FormDataBodyPart content,
		@FormDataParam("data") FormDataContentDisposition contentDisposition,
		@FormDataParam("data") final InputStream input) throws AuthenticationException, AuthorisationException, ServiceException {
	// https://stackoverflow.com/questions/27609569/file-upload-along-with-other-object-in-jersey-restful-web-service
	json.setMediaType(MediaType.APPLICATION_JSON_TYPE);
	FileInVO in = json.getValueAs(FileInVO.class);
	FileStreamInVO stream = new FileStreamInVO();
	stream.setStream(input);
	stream.setMimeType(content.getMediaType().toString());
	stream.setSize(contentDisposition.getSize());
	stream.setFileName(contentDisposition.getFileName());
	return WebUtil.getServiceLocator().getFileService().addFile(auth, in, stream);
}
 
Example #7
Source File: PetApi.java    From openapi-generator with Apache License 2.0 6 votes vote down vote up
@POST
@Path("/pet/{petId}/uploadImage")
@Consumes({ "multipart/form-data" })
@Produces({ "application/json" })
@io.swagger.annotations.ApiOperation(value = "uploads an image", notes = "", response = ModelApiResponse.class, authorizations = {
    @io.swagger.annotations.Authorization(value = "petstore_auth", scopes = {
        @io.swagger.annotations.AuthorizationScope(scope = "write:pets", description = "modify pets in your account"),
        @io.swagger.annotations.AuthorizationScope(scope = "read:pets", description = "read your pets")
    })
}, tags={ "pet",  })
@io.swagger.annotations.ApiResponses(value = { 
    @io.swagger.annotations.ApiResponse(code = 200, message = "successful operation", response = ModelApiResponse.class) })
public Response uploadFile(
    @ApiParam(value = "ID of pet to update", required = true) @PathParam("petId") @NotNull  Long petId,
    @FormDataParam("additionalMetadata")  String additionalMetadata,
    @FormDataParam("file") InputStream inputStream,
    @FormDataParam("file") FormDataContentDisposition fileDetail,
    @Context SecurityContext securityContext)
throws NotFoundException {
    return delegate.uploadFile(petId,additionalMetadata,inputStream, fileDetail,securityContext);
}
 
Example #8
Source File: FakeApi.java    From openapi-generator with Apache License 2.0 6 votes vote down vote up
@POST
@Path("/{petId}/uploadImageWithRequiredFile")
@Consumes({ "multipart/form-data" })
@Produces({ "application/json" })
@io.swagger.annotations.ApiOperation(value = "uploads an image (required)", notes = "", response = ModelApiResponse.class, authorizations = {
    @io.swagger.annotations.Authorization(value = "petstore_auth", scopes = {
        @io.swagger.annotations.AuthorizationScope(scope = "write:pets", description = "modify pets in your account"),
        @io.swagger.annotations.AuthorizationScope(scope = "read:pets", description = "read your pets")
    })
}, tags={ "pet" })
@io.swagger.annotations.ApiResponses(value = { 
    @io.swagger.annotations.ApiResponse(code = 200, message = "successful operation", response = ModelApiResponse.class) })
public Response uploadFileWithRequiredFile(
    @ApiParam(value = "ID of pet to update", required = true) @PathParam("petId") @NotNull  Long petId,
    @FormDataParam("requiredFile") InputStream inputStream,
    @FormDataParam("requiredFile") FormDataContentDisposition fileDetail,
    @FormDataParam("additionalMetadata")  String additionalMetadata,
    @Context SecurityContext securityContext)
throws NotFoundException {
    return delegate.uploadFileWithRequiredFile(petId,inputStream, fileDetail,additionalMetadata,securityContext);
}
 
Example #9
Source File: PetApi.java    From openapi-generator with Apache License 2.0 6 votes vote down vote up
@POST
@Path("/{petId}/uploadImage")
@Consumes({ "multipart/form-data" })
@Produces({ "application/json" })
@io.swagger.annotations.ApiOperation(value = "uploads an image", notes = "", response = ModelApiResponse.class, authorizations = {
    @io.swagger.annotations.Authorization(value = "petstore_auth", scopes = {
        @io.swagger.annotations.AuthorizationScope(scope = "write:pets", description = "modify pets in your account"),
        @io.swagger.annotations.AuthorizationScope(scope = "read:pets", description = "read your pets")
    })
}, tags={ "pet" })
@io.swagger.annotations.ApiResponses(value = { 
    @io.swagger.annotations.ApiResponse(code = 200, message = "successful operation", response = ModelApiResponse.class) })
public Response uploadFile(
    @ApiParam(value = "ID of pet to update", required = true) @PathParam("petId") @NotNull  Long petId,
    @FormDataParam("additionalMetadata")  String additionalMetadata,
    @FormDataParam("file") InputStream inputStream,
    @FormDataParam("file") FormDataContentDisposition fileDetail,
    @Context SecurityContext securityContext)
throws NotFoundException {
    return delegate.uploadFile(petId,additionalMetadata,inputStream, fileDetail,securityContext);
}
 
Example #10
Source File: AdminResource.java    From incubator-atlas with Apache License 2.0 5 votes vote down vote up
@POST
@Path("/import")
@Produces(Servlets.JSON_MEDIA_TYPE)
@Consumes(MediaType.MULTIPART_FORM_DATA)
public AtlasImportResult importData(@FormDataParam("request") String jsonData,
                                    @FormDataParam("data") InputStream inputStream) throws AtlasBaseException {
    if (LOG.isDebugEnabled()) {
        LOG.debug("==> AdminResource.importData(jsonData={}, inputStream={})", jsonData, (inputStream != null));
    }

    acquireExportImportLock("import");

    AtlasImportResult result;

    try {
        if (StringUtils.isEmpty(jsonData)) {
            jsonData = "{}";
        }

        AtlasImportRequest request = AtlasType.fromJson(jsonData, AtlasImportRequest.class);
        ZipSource zipSource = new ZipSource(inputStream);

        result = importService.run(zipSource, request, Servlets.getUserName(httpServletRequest),
                Servlets.getHostName(httpServletRequest),
                AtlasAuthorizationUtils.getRequestIpAddress(httpServletRequest));
    } catch (Exception excp) {
        LOG.error("importData(binary) failed", excp);

        throw new AtlasBaseException(excp);
    } finally {
        releaseExportImportLock();

        if (LOG.isDebugEnabled()) {
            LOG.debug("<== AdminResource.importData(binary)");
        }
    }

    return result;
}
 
Example #11
Source File: FakeApi.java    From openapi-generator with Apache License 2.0 5 votes vote down vote up
@POST

@Consumes({ "application/x-www-form-urlencoded" })

@io.swagger.annotations.ApiOperation(value = "Fake endpoint for testing various parameters  假端點  偽のエンドポイント  가짜 엔드 포인트", notes = "Fake endpoint for testing various parameters  假端點  偽のエンドポイント  가짜 엔드 포인트", response = Void.class, authorizations = {
    @io.swagger.annotations.Authorization(value = "http_basic_test")
}, tags={ "fake",  })
@io.swagger.annotations.ApiResponses(value = { 
    @io.swagger.annotations.ApiResponse(code = 400, message = "Invalid username supplied", response = Void.class),
    @io.swagger.annotations.ApiResponse(code = 404, message = "User not found", response = Void.class) })
public Response testEndpointParameters(
    @ApiParam(value = "None", required=true)  @FormParam("number")  BigDecimal number,
    @ApiParam(value = "None", required=true)  @FormParam("double")  Double _double,
    @ApiParam(value = "None", required=true)  @FormParam("pattern_without_delimiter")  String patternWithoutDelimiter,
    @ApiParam(value = "None", required=true)  @FormParam("byte")  byte[] _byte,
    @ApiParam(value = "None")  @FormParam("integer")  Integer integer,
    @ApiParam(value = "None")  @FormParam("int32")  Integer int32,
    @ApiParam(value = "None")  @FormParam("int64")  Long int64,
    @ApiParam(value = "None")  @FormParam("float")  Float _float,
    @ApiParam(value = "None")  @FormParam("string")  String string,
    @FormDataParam("binary") InputStream inputStream,
    @FormDataParam("binary") FormDataContentDisposition fileDetail,
    @ApiParam(value = "None")  @FormParam("date")  Date date,
    @ApiParam(value = "None")  @FormParam("dateTime")  Date dateTime,
    @ApiParam(value = "None")  @FormParam("password")  String password,
    @ApiParam(value = "None")  @FormParam("callback")  String paramCallback,
    @Context SecurityContext securityContext)
throws NotFoundException {
    return delegate.testEndpointParameters(number,_double,patternWithoutDelimiter,_byte,integer,int32,int64,_float,string,inputStream, fileDetail,date,dateTime,password,paramCallback,securityContext);
}
 
Example #12
Source File: RESTInterface.java    From nadia with Apache License 2.0 5 votes vote down vote up
@POST
@Path("dialog/load")
@Produces( MediaType.TEXT_PLAIN )
@Consumes(MediaType.MULTIPART_FORM_DATA)
public Response createDialogFromXML(
		@FormDataParam("dialogxml") String dialogxml) throws URISyntaxException, InstantiationException, IllegalAccessException
{
	String instanceid=generateDialogID();
	create_dialog(instanceid, dialogxml);		
	return init_dialog(instanceid); //init dialogue, i.e. get first question
}
 
Example #13
Source File: MultipartResource.java    From cukes with Apache License 2.0 5 votes vote down vote up
@POST
@Consumes(MediaType.MULTIPART_FORM_DATA)
public Response upload(@FormDataParam("file") InputStream is) throws IOException {
    byte[] bytes = IOUtils.toByteArray(is);
    System.out.println("Read " + bytes.length + " byte(s)");
    return rest.ok(new String(bytes));
}
 
Example #14
Source File: NerdRestService.java    From entity-fishing with Apache License 2.0 5 votes vote down vote up
@POST
@Path(CUSTOMISATIONS)
@Produces(MediaType.APPLICATION_JSON)
@Consumes(MediaType.MULTIPART_FORM_DATA)
public Response addCustomisation(@FormDataParam(NAME) String name, @FormDataParam(VALUE) String content) {
    boolean ok = false;
    Response response = null;
    try {
        ok = NerdRestCustomisation.createCustomisation(name, content);
        response = Response
                .status(Response.Status.OK)
                .entity(responseJson(ok, null))
                .header(HttpHeaders.CONTENT_TYPE, MediaType.APPLICATION_JSON + "; charset=UTF-8")
                .header("Access-Control-Allow-Origin", "*")
                .header("Access-Control-Allow-Methods", "GET, POST, DELETE, PUT")
                .build();

    } catch (CustomisationException ce) {
        response = Response
                .status(Response.Status.BAD_REQUEST)
                .entity(responseJson(ok, ce.getMessage()))
                .build();

    } catch (Exception e) {
        response = Response
                .status(Response.Status.INTERNAL_SERVER_ERROR)
                .build();
    }
    return response;
}
 
Example #15
Source File: NerdRestService.java    From entity-fishing with Apache License 2.0 5 votes vote down vote up
@PUT
@Path(CUSTOMISATION + "/{name}")
@Produces(MediaType.APPLICATION_JSON)
@Consumes(MediaType.MULTIPART_FORM_DATA)
public Response updateCustomisation(@PathParam(NAME) String name, @FormDataParam(VALUE) String newContent) {
    boolean ok = false;
    Response response = null;
    try {
        ok = NerdRestCustomisation.updateCustomisation(name, newContent);

        response = Response
                .status(Response.Status.OK)
                .entity(responseJson(ok, null))
                .header(HttpHeaders.CONTENT_TYPE, MediaType.APPLICATION_JSON + "; charset=UTF-8")
                .header("Access-Control-Allow-Origin", "*")
                .header("Access-Control-Allow-Methods", "GET, POST, DELETE, PUT")
                .build();

    } catch (CustomisationException ce) {
        response = Response
                .status(Response.Status.BAD_REQUEST)
                .entity(responseJson(ok, ce.getMessage()))
                .build();

    } catch (Exception e) {
        response = Response
                .status(Response.Status.INTERNAL_SERVER_ERROR)
                .build();
    }
    return response;


}
 
Example #16
Source File: NerdRestService.java    From entity-fishing with Apache License 2.0 5 votes vote down vote up
/**
 * @see com.scienceminer.nerd.service.NerdRestProcessString#processLanguageIdentification(String)
 */
@POST
@Path(LANGUAGE)
@Produces(MediaType.APPLICATION_JSON)
@Consumes(MediaType.MULTIPART_FORM_DATA)
public Response processLanguageIdentificationPost(@FormDataParam(TEXT) String text) {
    return NerdRestProcessString.processLanguageIdentification(text);
}
 
Example #17
Source File: NerdRestService.java    From entity-fishing with Apache License 2.0 5 votes vote down vote up
@POST
@Path(SEGMENTATION)
@Produces(MediaType.APPLICATION_JSON)
@Consumes(MediaType.MULTIPART_FORM_DATA)
public Response processSentenceSegmentationPost(@FormDataParam(TEXT) String text) {
    return NerdRestProcessString.processSentenceSegmentation(text);
}
 
Example #18
Source File: InputFieldResource.java    From ctsms with GNU Lesser General Public License v2.1 5 votes vote down vote up
@PUT
@Consumes(MediaType.MULTIPART_FORM_DATA)
@Produces({ MediaType.APPLICATION_JSON })
public InputFieldOutVO updateInputField(@FormDataParam("json") FormDataBodyPart json,
		@FormDataParam("data") FormDataBodyPart content,
		@FormDataParam("data") FormDataContentDisposition contentDisposition,
		@FormDataParam("data") final InputStream input) throws Exception {
	json.setMediaType(MediaType.APPLICATION_JSON_TYPE);
	InputFieldInVO in = json.getValueAs(InputFieldInVO.class);
	in.setDatas(CommonUtil.inputStreamToByteArray(input));
	in.setMimeType(content.getMediaType().toString());
	in.setFileName(contentDisposition.getFileName());
	return WebUtil.getServiceLocator().getInputFieldService().updateInputField(auth, in);
}
 
Example #19
Source File: InputFieldResource.java    From ctsms with GNU Lesser General Public License v2.1 5 votes vote down vote up
@POST
@Consumes(MediaType.MULTIPART_FORM_DATA)
@Produces({ MediaType.APPLICATION_JSON })
public InputFieldOutVO addInputField(@FormDataParam("json") FormDataBodyPart json,
		@FormDataParam("data") FormDataBodyPart content,
		@FormDataParam("data") FormDataContentDisposition contentDisposition,
		@FormDataParam("data") final InputStream input) throws Exception {
	json.setMediaType(MediaType.APPLICATION_JSON_TYPE);
	InputFieldInVO in = json.getValueAs(InputFieldInVO.class);
	in.setDatas(CommonUtil.inputStreamToByteArray(input));
	in.setMimeType(content.getMediaType().toString());
	in.setFileName(contentDisposition.getFileName());
	return WebUtil.getServiceLocator().getInputFieldService().addInputField(auth, in);
}
 
Example #20
Source File: AuthenticationService.java    From query2report with GNU General Public License v3.0 5 votes vote down vote up
@Path("/login")
@POST
@Consumes(MediaType.MULTIPART_FORM_DATA)
public Response authUser(@FormDataParam("username") String userName,
		@FormDataParam("password") String password){
	logger.info("Authenticating user "+userName);
	try{
		String token = UserManager.getUserManager().authUser(userName, password);
		return Response.ok(token).build();
	}catch(Exception e){
		return Response.serverError().entity(e.getMessage()).status(Response.Status.UNAUTHORIZED).build();
	}
}
 
Example #21
Source File: StaffResource.java    From ctsms with GNU Lesser General Public License v2.1 5 votes vote down vote up
@PUT
@Consumes(MediaType.MULTIPART_FORM_DATA)
@Produces({ MediaType.APPLICATION_JSON })
public StaffImageOutVO setStaffImage(@FormDataParam("json") FormDataBodyPart json,
		@FormDataParam("data") FormDataBodyPart content,
		@FormDataParam("data") FormDataContentDisposition contentDisposition,
		@FormDataParam("data") final InputStream input) throws Exception {
	json.setMediaType(MediaType.APPLICATION_JSON_TYPE);
	StaffImageInVO in = json.getValueAs(StaffImageInVO.class);
	in.setDatas(CommonUtil.inputStreamToByteArray(input));
	in.setMimeType(content.getMediaType().toString());
	in.setFileName(contentDisposition.getFileName());
	return WebUtil.getServiceLocator().getStaffService().setStaffImage(auth, in);
}
 
Example #22
Source File: ProbandResource.java    From ctsms with GNU Lesser General Public License v2.1 5 votes vote down vote up
@PUT
@Consumes(MediaType.MULTIPART_FORM_DATA)
@Produces({ MediaType.APPLICATION_JSON })
public ProbandImageOutVO setProbandImage(@FormDataParam("json") FormDataBodyPart json,
		@FormDataParam("data") FormDataBodyPart content,
		@FormDataParam("data") FormDataContentDisposition contentDisposition,
		@FormDataParam("data") final InputStream input) throws Exception {
	json.setMediaType(MediaType.APPLICATION_JSON_TYPE);
	ProbandImageInVO in = json.getValueAs(ProbandImageInVO.class);
	in.setDatas(CommonUtil.inputStreamToByteArray(input));
	in.setMimeType(content.getMediaType().toString());
	in.setFileName(contentDisposition.getFileName());
	return WebUtil.getServiceLocator().getProbandService().setProbandImage(auth, in);
}
 
Example #23
Source File: FileUploadService.java    From Tutorials with Apache License 2.0 5 votes vote down vote up
/**
    * Returns text response to caller containing current time-stamp
    * @return error response in case of missing parameters an internal exception or
    * success response if file has been stored successfully 
    */
@POST
@Consumes(MediaType.MULTIPART_FORM_DATA)
   public Response uploadFile(
       @FormDataParam("file") InputStream uploadedInputStream,
       @FormDataParam("file") FormDataContentDisposition fileDetail) {
	
	// check if all form parameters are provided
	if (uploadedInputStream == null || fileDetail == null)
		return Response.status(400).entity("Invalid form data").build();
	
	// create our destination folder, if it not exists
	try {
		createFolderIfNotExists(UPLOAD_FOLDER);
	} catch (SecurityException se) {
		return Response.status(500).entity("Can not create destination folder on server").build();
	}

       String uploadedFileLocation = UPLOAD_FOLDER + fileDetail.getFileName();
       try {
		saveToFile(uploadedInputStream, uploadedFileLocation);
	} catch (IOException e) {
		return Response.status(500).entity("Can not save file").build();
	}

       return Response.status(200).entity("File saved to " + uploadedFileLocation).build();
   }
 
Example #24
Source File: FakeApi.java    From openapi-generator with Apache License 2.0 5 votes vote down vote up
@POST

@Consumes({ "application/x-www-form-urlencoded" })

@io.swagger.annotations.ApiOperation(value = "Fake endpoint for testing various parameters  假端點  偽のエンドポイント  가짜 엔드 포인트", notes = "Fake endpoint for testing various parameters  假端點  偽のエンドポイント  가짜 엔드 포인트", response = Void.class, authorizations = {
    @io.swagger.annotations.Authorization(value = "http_basic_test")
}, tags={ "fake",  })
@io.swagger.annotations.ApiResponses(value = { 
    @io.swagger.annotations.ApiResponse(code = 400, message = "Invalid username supplied", response = Void.class),
    @io.swagger.annotations.ApiResponse(code = 404, message = "User not found", response = Void.class) })
public Response testEndpointParameters(
    @ApiParam(value = "None", required=true)  @FormParam("number")  BigDecimal number,
    @ApiParam(value = "None", required=true)  @FormParam("double")  Double _double,
    @ApiParam(value = "None", required=true)  @FormParam("pattern_without_delimiter")  String patternWithoutDelimiter,
    @ApiParam(value = "None", required=true)  @FormParam("byte")  byte[] _byte,
    @ApiParam(value = "None")  @FormParam("integer")  Integer integer,
    @ApiParam(value = "None")  @FormParam("int32")  Integer int32,
    @ApiParam(value = "None")  @FormParam("int64")  Long int64,
    @ApiParam(value = "None")  @FormParam("float")  Float _float,
    @ApiParam(value = "None")  @FormParam("string")  String string,
    @FormDataParam("binary") InputStream inputStream,
    @FormDataParam("binary") FormDataContentDisposition fileDetail,
    @ApiParam(value = "None")  @FormParam("date")  Date date,
    @ApiParam(value = "None")  @FormParam("dateTime")  Date dateTime,
    @ApiParam(value = "None")  @FormParam("password")  String password,
    @ApiParam(value = "None")  @FormParam("callback")  String paramCallback,
    @Context SecurityContext securityContext)
throws NotFoundException {
    return delegate.testEndpointParameters(number,_double,patternWithoutDelimiter,_byte,integer,int32,int64,_float,string,inputStream, fileDetail,date,dateTime,password,paramCallback,securityContext);
}
 
Example #25
Source File: JobResource.java    From ctsms with GNU Lesser General Public License v2.1 5 votes vote down vote up
@POST
@Consumes(MediaType.MULTIPART_FORM_DATA)
@Produces({ MediaType.APPLICATION_JSON })
public JobOutVO addJob(@FormDataParam("json") FormDataBodyPart json,
		@FormDataParam("data") FormDataBodyPart content,
		@FormDataParam("data") FormDataContentDisposition contentDisposition,
		@FormDataParam("data") final InputStream input) throws Exception {
	json.setMediaType(MediaType.APPLICATION_JSON_TYPE);
	JobAddVO in = json.getValueAs(JobAddVO.class);
	in.setDatas(CommonUtil.inputStreamToByteArray(input));
	in.setMimeType(content.getMediaType().toString());
	in.setFileName(contentDisposition.getFileName());
	return WebUtil.getServiceLocator().getJobService().addJob(auth, in);
}
 
Example #26
Source File: JobResource.java    From ctsms with GNU Lesser General Public License v2.1 5 votes vote down vote up
@PUT
@Consumes(MediaType.MULTIPART_FORM_DATA)
@Produces({ MediaType.APPLICATION_JSON })
public JobOutVO updateJob(@FormDataParam("json") FormDataBodyPart json,
		@FormDataParam("data") FormDataBodyPart content,
		@FormDataParam("data") FormDataContentDisposition contentDisposition,
		@FormDataParam("data") final InputStream input) throws Exception {
	//https://stackoverflow.com/questions/27609569/file-upload-along-with-other-object-in-jersey-restful-web-service/27614403
	json.setMediaType(MediaType.APPLICATION_JSON_TYPE);
	JobUpdateVO in = json.getValueAs(JobUpdateVO.class);
	in.setDatas(CommonUtil.inputStreamToByteArray(input));
	in.setMimeType(content.getMediaType().toString());
	in.setFileName(contentDisposition.getFileName());
	return WebUtil.getServiceLocator().getJobService().updateJob(auth, in);
}
 
Example #27
Source File: RunManagerResource.java    From usergrid with Apache License 2.0 4 votes vote down vote up
@SuppressWarnings( "unchecked" )
@POST
@Path( "/store" )
@Consumes( MediaType.MULTIPART_FORM_DATA )
@Produces( MediaType.APPLICATION_JSON )
public Response store(
        @QueryParam( RUNNER_HOSTNAME ) String runnerHostName,
        @QueryParam( COMMIT_ID ) String commitId,
        @QueryParam( RUN_ID ) String runId,
        @QueryParam( RUN_NUMBER ) int runNumber,
        @FormDataParam( CONTENT ) InputStream resultsFileInputStream,
        @Nullable @QueryParam( TestMode.TEST_MODE_PROPERTY ) String testMode
                             ) throws Exception {

    if( inTestMode( testMode ) ) {
        LOG.info( "Calling /run/store in test mode ..." );
        LOG.info( "{} is {}", RUNNER_HOSTNAME, runnerHostName );
        LOG.info( "{} is {}", COMMIT_ID, commitId );
        LOG.info( "{} is {}", RUN_ID, runId );
        LOG.info( "{} is {}", RUN_NUMBER, runNumber );

        return Response.status( Response.Status.CREATED ).entity( SUCCESSFUL_TEST_MESSAGE ).build();
    }
    LOG.info( "/run/store called ..." );

    String message;
    JSONObject object = ( JSONObject ) new JSONParser().parse( new InputStreamReader( resultsFileInputStream ) );
    String testClass = Util.getString( object, "testClass" );

    // First save the summary info
    BasicRun run = new BasicRun( runId, commitId, runnerHostName, runNumber, testClass );
    run.copyJson( object );
    if ( runDao.save( run ) ) {
        LOG.info( "Created new Run {} ", run );
    }
    else {
        message = "Failed to create new Run";
        LOG.warn( message );
        throw new IllegalStateException( message );
    }

    // Here is the list of BasicRunResults
    JSONArray runResults = ( JSONArray ) object.get( "runResults" );
    Iterator<JSONObject> iterator = runResults.iterator();
    while( iterator.hasNext() ) {
        JSONObject jsonResult = iterator.next();

        int failureCount = Util.getInt( jsonResult, "failureCount" );
        BasicRunResult runResult = new BasicRunResult(
                runId,
                Util.getInt( jsonResult, "runCount"),
                Util.getInt( jsonResult, "runTime" ),
                Util.getInt( jsonResult, "ignoreCount" ),
                failureCount
        );
        if( failureCount != 0 ) {
            try {
                for( Object result : runResults ) {
                    JSONObject failures = ( JSONObject ) result;
                    JSONArray obj = ( JSONArray ) failures.get( "failures" );
                    runResult.setFailures( obj.toJSONString() );
                    LOG.info( "Saving run results into Elastic Search." );
                }
            }catch ( Exception e ){
                LOG.warn( "Could not serialize runResults JSON object", e );
            }
        }

        if ( runResultDao.save( runResult ) ) {
            LOG.info( "Saved run result.");
        }
    }

    return Response.status( Response.Status.CREATED ).entity( "TRUE" ).build();
}
 
Example #28
Source File: PurgeResource.java    From pentaho-kettle with Apache License 2.0 4 votes vote down vote up
/**
 * Provides a utility for purging files and/or revision history for the DI server.
 * 
 * <p>
 * <b>Example Request:</b><br>
 * POST /pur-repository-plugin/api/purge/path:to:file/purge
 * </p>
 * 
 * @param pathId
 *          Colon separated path for the repository file. Processing of files will occur under this path. Exception:
 *          If purgeSharedObject=true other files may be affected as well.
 * @param purgeFiles
 *          If true, files will be purged completely. This options erases files and all history. This effectively
 *          disables all parameters effecting revisions since all revisions will be deleted unconditionally.
 * @param purgeRevisions
 *          If true, all revisions to the targeted files will be purged. The current state of the file will be
 *          retained.
 * @param purgeSharedObjects
 *          If true, Shared objects will also be targeted by the purge operation. This does not replace the pathId and
 *          fileFilter processing, but rather, is in addition to that processing. If it is desired to purge shared
 *          objects only without effecting other files, then set the pathId to a single space character. Some examples
 *          of shared objects database connections, Slave Servers, Cluster Schemas, and partition Schemas.
 * @param versionCount
 *          If present, the number of historical revisions to keep. If there are more revisions for a file than
 *          versionCount, the older ones will be removed.
 * @param purgeBeforeDate
 *          If set, remove all version history created prior to this date.
 * @param fileFilter
 *          The file filter to be applied when determining what files are affected by the purge. This filter is used
 *          by the <code>tree</code> endpoint to determine what files to return. The fileFilter is a list of allowed
 *          names of files separated by the pipe (|) character. Each file name in the filter may be a full name or a
 *          partial name with one or more wildcard characters ("*"). (eg: *.ktr|*.kjb returns all files with a ktr or
 *          kjb extension).
 * @param logLevelName
 *          The standard name for the log level (ie: INFO, DEBUG)
 * @return A text file containing a log of the service execution.
 */
@POST
@Path( "{pathId : .+}/purge" )
@StatusCodes( { @ResponseCode( code = 200, condition = "Successfully purged specified target" ),
  @ResponseCode( code = 500, condition = "Something failed when attempting to purge " ),
  @ResponseCode( code = 404, condition = "Invalid path" ) } )
@Consumes( MediaType.MULTIPART_FORM_DATA )
@Produces( { WILDCARD } )
public Response doDeleteRevisions( @PathParam( "pathId" ) String pathId,
    @DefaultValue( "false" ) @FormDataParam( "purgeFiles" ) boolean purgeFiles,
    @DefaultValue( "false" ) @FormDataParam( "purgeRevisions" ) boolean purgeRevisions,
    @DefaultValue( "false" ) @FormDataParam( "purgeSharedObjects" ) boolean purgeSharedObjects,
    @DefaultValue( "-1" ) @FormDataParam( "versionCount" ) int versionCount,
    @FormDataParam( "purgeBeforeDate" ) Date purgeBeforeDate,
    @DefaultValue( "*" ) @FormDataParam( "fileFilter" ) String fileFilter,
    @DefaultValue( "INFO" ) @FormDataParam( "logLevel" ) String logLevelName ) {

  // A version count of 0 is illegal.
  if ( versionCount == 0 ) {
    return Response.serverError().build();
  }

  if ( purgeRevisions && ( versionCount > 0 || purgeBeforeDate != null ) ) {
    purgeRevisions = false;
  }

  IPurgeService purgeService = new UnifiedRepositoryPurgeService( this.repository );
  Level logLevel = Level.toLevel( logLevelName );

  PurgeUtilitySpecification purgeSpecification = new PurgeUtilitySpecification();
  purgeSpecification.setPath( idToPath( pathId ) );
  purgeSpecification.setPurgeFiles( purgeFiles );
  purgeSpecification.setPurgeRevisions( purgeRevisions );
  purgeSpecification.setSharedObjects( purgeSharedObjects );
  purgeSpecification.setVersionCount( versionCount );
  purgeSpecification.setBeforeDate( purgeBeforeDate );
  purgeSpecification.setFileFilter( fileFilter );
  purgeSpecification.setLogLevel( logLevel );

  // Initialize the logger
  ByteArrayOutputStream purgeUtilityStream = new ByteArrayOutputStream();
  PurgeUtilityLogger.createNewInstance( purgeUtilityStream, purgeSpecification.getPath(), logLevel );

  try {
    purgeService.doDeleteRevisions( purgeSpecification );
  } catch ( Exception e ) {
    PurgeUtilityLogger.getPurgeUtilityLogger().error( e );
    return Response.ok( encodeOutput( purgeUtilityStream ), MediaType.TEXT_HTML ).build();
  }

  return Response.ok( encodeOutput( purgeUtilityStream ), MediaType.TEXT_HTML ).build();
}
 
Example #29
Source File: GenericEntityServiceResource.java    From eagle with Apache License 2.0 4 votes vote down vote up
@PUT
@Consumes({MediaType.MULTIPART_FORM_DATA})
@Produces(MediaType.APPLICATION_JSON)
public GenericServiceAPIResponseEntity update(@FormDataParam("file") InputStream fileInputStream,
                                              @FormDataParam("file") FormDataContentDisposition cdh,
                                              @QueryParam("serviceName") String serviceName){
    GenericServiceAPIResponseEntity<String> response = new GenericServiceAPIResponseEntity<String>();
    DataStorage dataStorage;
    Map<String,Object> meta = new HashMap<>();
    StopWatch stopWatch = new StopWatch();
    try {
        stopWatch.start();
        EntityDefinition entityDefinition = EntityDefinitionManager.getEntityByServiceName(serviceName);

        if(entityDefinition == null){
            throw new IllegalArgumentException("entity definition of service "+serviceName+" not found");
        }

        List<? extends TaggedLogAPIEntity> entities = unmarshalEntitiesByServie(fileInputStream, entityDefinition);
        dataStorage = DataStorageManager.getDataStorageByEagleConfig();

        UpdateStatement updateStatement = new UpdateStatement(entities,entityDefinition);
        ModifyResult<String> result = updateStatement.execute(dataStorage);
        if(result.isSuccess()) {
            List<String> keys =result.getIdentifiers();
            if(keys != null) {
                response.setObj(keys, String.class);
                meta.put(TOTAL_RESULTS,keys.size());
            }else{
                meta.put(TOTAL_RESULTS,0);
            }
            meta.put(ELAPSEDMS,stopWatch.getTime());
            response.setMeta(meta);
            response.setSuccess(true);
        }
    } catch (Exception e) {
        LOG.error(e.getMessage(), e);
        response.setException(e);
    } finally {
        stopWatch.stop();
    }
    return response;
}
 
Example #30
Source File: GenericEntityServiceResource.java    From eagle with Apache License 2.0 4 votes vote down vote up
@POST
@Consumes({MediaType.MULTIPART_FORM_DATA})
@Produces(MediaType.APPLICATION_JSON)
public GenericServiceAPIResponseEntity create(@FormDataParam("file") InputStream fileInputStream,
                                              @FormDataParam("file") FormDataContentDisposition cdh,
                                              @QueryParam("serviceName") String serviceName) {
    GenericServiceAPIResponseEntity<String> response = new GenericServiceAPIResponseEntity<String>();
    Map<String,Object> meta = new HashMap<>();
    StopWatch stopWatch = new StopWatch();
    try {
        stopWatch.start();
        EntityDefinition entityDefinition = EntityDefinitionManager.getEntityByServiceName(serviceName);

        if(entityDefinition == null){
            throw new IllegalArgumentException("entity definition of service "+serviceName+" not found");
        }

        List<? extends TaggedLogAPIEntity> entities = unmarshalEntitiesByServie(fileInputStream, entityDefinition);
        DataStorage dataStorage = DataStorageManager.getDataStorageByEagleConfig();
        CreateStatement createStatement = new CreateStatement(entities,entityDefinition);
        ModifyResult<String> result = createStatement.execute(dataStorage);
        if(result.isSuccess()) {
            List<String> keys =result.getIdentifiers();
            if(keys != null) {
                response.setObj(keys, String.class);
                response.setObj(keys, String.class);
                meta.put(TOTAL_RESULTS,keys.size());
            }else{
                meta.put(TOTAL_RESULTS,0);
            }
            meta.put(ELAPSEDMS,stopWatch.getTime());
            response.setMeta(meta);
            response.setSuccess(true);
        }
    } catch (Exception e) {
        LOG.error(e.getMessage(), e);
        response.setException(e);
    }finally {
        stopWatch.stop();
    }
    return response;
}