com.sun.jersey.multipart.FormDataBodyPart Java Examples

The following examples show how to use com.sun.jersey.multipart.FormDataBodyPart. 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: 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 #2
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 #3
Source File: SeacloudsRest.java    From SeaCloudsPlatform with Apache License 2.0 6 votes vote down vote up
@Deprecated
@POST
@Path("agreements")
@Consumes(MediaType.MULTIPART_FORM_DATA)
public Response createAgreementMultipart(@Context UriInfo uriInfo, FormDataMultiPart form,
        @QueryParam("agreementId") String agreementId) 
        throws ParserException, InternalException {
    
    FormDataBodyPart slaPart = form.getField("sla");
    String slaPayload = slaPart.getValueAs(String.class);

    String id = createAgreementImpl(agreementId, slaPayload);
    String location = buildResourceLocation(uriInfo.getAbsolutePath().toString() ,id);
    logger.debug("EndOf createAgreement");
    return buildResponsePOST(
            HttpStatus.CREATED,
            createMessage(HttpStatus.CREATED, id, 
                    "The agreement has been stored successfully in the SLA Repository Database. "
                    + "It has location " + location), location);
}
 
Example #4
Source File: ChopUiTestUtils.java    From usergrid with Apache License 2.0 6 votes vote down vote up
static void testStoreResults( TestParams testParams ) throws Exception {
    FormDataMultiPart part = new FormDataMultiPart();
    File tmpFile = File.createTempFile("results", "tmp");
    FileInputStream in = new FileInputStream( tmpFile );
    FormDataBodyPart body = new FormDataBodyPart( RestParams.CONTENT, in, MediaType.APPLICATION_OCTET_STREAM_TYPE );
    part.bodyPart( body );

    ClientResponse response = testParams.addQueryParameters( QUERY_PARAMS )
            .setEndpoint( RunManagerResource.ENDPOINT )
            .newWebResource()
            .queryParam( RestParams.RUNNER_HOSTNAME, "localhost" )
            .queryParam( RestParams.RUN_ID, "112316437" )
            .queryParam( RestParams.RUN_NUMBER, "3" )
            .path( "/store" )
            .type( MediaType.MULTIPART_FORM_DATA_TYPE )
            .accept( MediaType.APPLICATION_JSON )
            .post( ClientResponse.class, part );

    tmpFile.delete();

    assertEquals( Response.Status.CREATED.getStatusCode(), response.getStatus() );

    assertEquals( UploadResource.SUCCESSFUL_TEST_MESSAGE, response.getEntity( String.class ) );
}
 
Example #5
Source File: RunManagerImpl.java    From usergrid with Apache License 2.0 6 votes vote down vote up
@Override
public void store( final Project project, final Summary summary, final File resultsFile,
                   final Class<?> testClass ) throws FileNotFoundException, MalformedURLException {
    Preconditions.checkNotNull( summary, "The summary argument cannot be null." );

    // upload the results file
    InputStream in = new FileInputStream( resultsFile );
    FormDataMultiPart part = new FormDataMultiPart();
    part.field( FILENAME, resultsFile.getName() );

    FormDataBodyPart body = new FormDataBodyPart( CONTENT, in, MediaType.APPLICATION_OCTET_STREAM_TYPE );
    part.bodyPart( body );

    WebResource resource = Client.create().resource( coordinatorFig.getEndpoint() );
    resource = addQueryParameters( resource, project, me );
    String result = resource.path( coordinatorFig.getStoreResultsPath() )
                     .queryParam( RUN_ID, summary.getRunId() )
                     .queryParam( RUN_NUMBER, "" + summary.getRunNumber() )
                     .type( MediaType.MULTIPART_FORM_DATA_TYPE )
                     .post( String.class, part );

    LOG.debug( "Got back result from results file store = {}", result );
}
 
Example #6
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 #7
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 #8
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 #9
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 #10
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 #11
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 #12
Source File: ChopUiTestUtils.java    From usergrid with Apache License 2.0 5 votes vote down vote up
static void testUpload(TestParams testParams) throws Exception {

        FormDataMultiPart part = new FormDataMultiPart();

        part.field( RestParams.COMMIT_ID, QUERY_PARAMS.get( RestParams.COMMIT_ID ) );
        part.field( RestParams.MODULE_GROUPID, QUERY_PARAMS.get( RestParams.MODULE_GROUPID ) );
        part.field( RestParams.MODULE_ARTIFACTID, QUERY_PARAMS.get( RestParams.MODULE_ARTIFACTID ) );
        part.field( RestParams.MODULE_VERSION, QUERY_PARAMS.get( RestParams.MODULE_VERSION ) );
        part.field( RestParams.USERNAME, QUERY_PARAMS.get( RestParams.USERNAME ) );
        part.field( RestParams.VCS_REPO_URL, "ssh://[email protected]:7999/chop/main.git" );
        part.field( RestParams.TEST_PACKAGE, QUERY_PARAMS.get( RestParams.TEST_PACKAGE ) );
        part.field( RestParams.MD5, "d7d4829506f6cb8c0ab2da9cb1daca02" );

        File tmpFile = File.createTempFile("runner", "jar");
        FileInputStream in = new FileInputStream( tmpFile );
        FormDataBodyPart body = new FormDataBodyPart( RestParams.CONTENT, in, MediaType.APPLICATION_OCTET_STREAM_TYPE );
        part.bodyPart( body );

        ClientResponse response = testParams.addQueryParameters( QUERY_PARAMS )
                .setEndpoint( UploadResource.ENDPOINT )
                .newWebResource()
                .path( "/runner" )
                .type( MediaType.MULTIPART_FORM_DATA )
                .accept( MediaType.TEXT_PLAIN )
                .post( ClientResponse.class, part );

        assertEquals( Response.Status.CREATED.getStatusCode(), response.getStatus() );

        assertEquals( UploadResource.SUCCESSFUL_TEST_MESSAGE, response.getEntity( String.class ) );

        tmpFile.delete();
    }
 
Example #13
Source File: RestApiUtils.java    From db with GNU Affero General Public License v3.0 4 votes vote down vote up
/**
 * Creates a multipart POST request using the specified URL with the specified payload.
 *
 * @param url
 *            the URL to send the request to
 * @param authToken
 *            the authentication token to use for this request
 * @param requestPayload
 *            the payload to send with the request
 * @param file
 *            the file to send with the request
 * @return the response from the request
 */
private TsResponse postMultipart(String url, String authToken, TsRequest requestPayload, BodyPart filePart) {
    // Creates an instance of StringWriter to hold the XML for the request
    StringWriter writer = new StringWriter();

    // Marshals the TsRequest object into XML format if it is not null
    if (requestPayload != null) {
        try {
            s_jaxbMarshaller.marshal(requestPayload, writer);
        } catch (JAXBException ex) {
            m_logger.error("There was a problem marshalling the payload");
        }
    }

    // Converts the XML into a string
    String payload = writer.toString();

    m_logger.debug("Input payload: \n" + payload);

    // Creates the XML request payload portion of the multipart request
    BodyPart payloadPart = new FormDataBodyPart(TABLEAU_PAYLOAD_NAME, payload);

    // Creates the multipart object and adds the file portion of the
    // multipart request to it
    MultiPart multipart = new MultiPart();
    multipart.bodyPart(payloadPart);

    if(filePart != null) {
        multipart.bodyPart(filePart);
    }

    // Creates the HTTP client object and makes the HTTP request to the
    // specified URL
    Client client = Client.create();
    WebResource webResource = client.resource(url);

    // Makes a multipart POST request with the multipart payload and
    // authenticity token
    ClientResponse clientResponse = webResource.header(TABLEAU_AUTH_HEADER, authToken)
            .type(MultiPartMediaTypes.createMixed()).post(ClientResponse.class, multipart);

    // Parses the response from the server into an XML string
    String responseXML = clientResponse.getEntity(String.class);

    m_logger.debug("Response: \n" + responseXML);

    // Returns the unmarshalled XML response
    return unmarshalResponse(responseXML);
}
 
Example #14
Source File: RestApiUtils.java    From db with GNU Affero General Public License v3.0 4 votes vote down vote up
/**
 * Creates a multipart PUT request using the specified URL with the
 * specified payload.
 *
 * @param url
 *            the URL to send the request to
 * @param authToken
 *            the authentication token to use for this request
 * @param requestPayload
 *            the payload to send with the request
 * @param file
 *            the file to send with the request
 * @return the response from the request
 */
private TsResponse putMultipart(String url, String authToken, TsRequest requestPayload, BodyPart filePart) {
    // Creates an instance of StringWriter to hold the XML for the request
    StringWriter writer = new StringWriter();

    // Marshals the TsRequest object into XML format if it is not null
    if (requestPayload != null) {
        try {
            s_jaxbMarshaller.marshal(requestPayload, writer);
        } catch (JAXBException ex) {
            m_logger.error("There was a problem marshalling the payload");
        }
    }

    // Converts the XML into a string
    String payload = writer.toString();

    m_logger.debug("Input payload: \n" + payload);

    // Creates the XML request payload portion of the multipart request
    BodyPart payloadPart = new FormDataBodyPart(TABLEAU_PAYLOAD_NAME, payload);

    // Creates the multipart object and adds the file portion of the
    // multipart request to it
    MultiPart multipart = new MultiPart();
    multipart.bodyPart(payloadPart);

    if(filePart != null) {
        multipart.bodyPart(filePart);
    }

    // Creates the HTTP client object and makes the HTTP request to the
    // specified URL
    Client client = Client.create();
    WebResource webResource = client.resource(url);

    // Makes a multipart POST request with the multipart payload and
    // authenticity token
    ClientResponse clientResponse = webResource.header(TABLEAU_AUTH_HEADER, authToken)
            .type(MultiPartMediaTypes.createMixed()).put(ClientResponse.class, multipart);

    // Parses the response from the server into an XML string
    String responseXML = clientResponse.getEntity(String.class);

    m_logger.debug("Response: \n" + responseXML);

    // Returns the unmarshalled XML response
    return unmarshalResponse(responseXML);
}
 
Example #15
Source File: AtlasBaseClient.java    From atlas with Apache License 2.0 4 votes vote down vote up
private FormDataBodyPart getImportRequestBodyPart(AtlasImportRequest request) {
    return new FormDataBodyPart(IMPORT_REQUEST_PARAMTER, AtlasType.toJson(request), MediaType.APPLICATION_JSON_TYPE);
}
 
Example #16
Source File: OlogClient.java    From phoebus with Eclipse Public License 1.0 4 votes vote down vote up
@Override
public LogEntry set(LogEntry log) throws LogbookException{
    ClientResponse clientResponse;

    try {
        clientResponse = service.path("logs")
                .type(MediaType.APPLICATION_JSON)
                .accept(MediaType.APPLICATION_XML)
                .accept(MediaType.APPLICATION_JSON)
                .put(ClientResponse.class, logEntrySerializer.writeValueAsString(log));

        if (clientResponse.getStatus() < 300)
        {
            XmlLog createdLog = logEntryDeserializer.readValue(clientResponse.getEntityInputStream(), XmlLog.class);
            log.getAttachments().stream().forEach(attachment -> {
                FormDataMultiPart form = new FormDataMultiPart();
                form.bodyPart(new FileDataBodyPart("file", attachment.getFile()));
                form.bodyPart(new FormDataBodyPart("filename", attachment.getName()));
                form.bodyPart(new FormDataBodyPart("fileMetadataDescription", attachment.getContentType()));

                ClientResponse attachementResponse = service.path("logs").path("attachments").path(String.valueOf(createdLog.getId()))
                       .type(MediaType.MULTIPART_FORM_DATA)
                       .accept(MediaType.APPLICATION_XML)
                       .accept(MediaType.APPLICATION_JSON)
                       .post(ClientResponse.class, form);
                if (attachementResponse.getStatus() > 300)
                {
                    // TODO failed to add attachments
                    logger.log(Level.SEVERE, "Failed to submit attachment(s), HTTP status: " + attachementResponse.getStatus());
                }
            });

            clientResponse = service.path("logs").path(String.valueOf(createdLog.getId()))
                    .type(MediaType.APPLICATION_JSON)
                    .accept(MediaType.APPLICATION_JSON)
                    .get(ClientResponse.class);
            return logEntryDeserializer.readValue(clientResponse.getEntityInputStream(), XmlLog.class);
        }
        else if(clientResponse.getStatus() == 401){
            logger.log(Level.SEVERE, "Submission of log entry returned HTTP status, invalid credentials");
            throw new LogbookException(Messages.SubmissionFailedInvalidCredentials);
        }
        else{
            logger.log(Level.SEVERE, "Submission of log entry returned HTTP status" + clientResponse.getStatus() );
            throw new LogbookException(MessageFormat.format(Messages.SubmissionFailedWithHttpStatus, clientResponse.getStatus()));
        }
    } catch (UniformInterfaceException | ClientHandlerException | IOException e) {
        logger.log(Level.SEVERE,"Failed to submit log entry, got client exception", e);
        throw new LogbookException(e);
    }
}