Java Code Examples for com.sun.jersey.multipart.FormDataMultiPart#bodyPart()

The following examples show how to use com.sun.jersey.multipart.FormDataMultiPart#bodyPart() . 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: RestRequestSender.java    From osiris with Apache License 2.0 9 votes vote down vote up
public ClientResponse<File> upload(String url, File f, Headers... headers) {
	@SuppressWarnings("resource")
	FormDataMultiPart form = new FormDataMultiPart();
	form.bodyPart(new FileDataBodyPart("file", f, MediaType.APPLICATION_OCTET_STREAM_TYPE));

	String urlCreated = createURI(url);
	ClientConfig cc = new DefaultClientConfig();
	cc.getClasses().add(MultiPartWriter.class);
	WebResource webResource = Client.create(cc).resource(urlCreated);
	Builder builder = webResource.type(MULTIPART_MEDIA).accept(MEDIA).accept("text/plain");
	for (Headers h : headers) {
		builder.header(h.getKey(), h.getValue());
	}

	com.sun.jersey.api.client.ClientResponse clienteResponse = null;

	clienteResponse = builder.post(com.sun.jersey.api.client.ClientResponse.class, form);

	return new ClientResponse<File>(clienteResponse, File.class);
}
 
Example 2
Source File: ApiClient.java    From carbon-identity-framework with Apache License 2.0 6 votes vote down vote up
/**
 * Serialize the given Java object into string according the given
 * Content-Type (only JSON is supported for now).
 */
public Object serialize(Object obj, String contentType, Map<String, Object> formParams) throws ApiException {
    if (contentType.startsWith("multipart/form-data")) {
        FormDataMultiPart mp = new FormDataMultiPart();
        for (Entry<String, Object> param : formParams.entrySet()) {
            if (param.getValue() instanceof File) {
                File file = (File) param.getValue();
                mp.bodyPart(new FileDataBodyPart(param.getKey(), file, MediaType.MULTIPART_FORM_DATA_TYPE));
            } else {
                mp.field(param.getKey(), parameterToString(param.getValue()), MediaType.MULTIPART_FORM_DATA_TYPE);
            }
        }
        return mp;
    } else if (contentType.startsWith("application/x-www-form-urlencoded")) {
        return this.getXWWWFormUrlencodedParams(formParams);
    } else {
        // We let Jersey attempt to serialize the body
        return obj;
    }
}
 
Example 3
Source File: ApiClient.java    From forge-api-java-client with Apache License 2.0 6 votes vote down vote up
/**
 * Serialize the given Java object into string according the given
 * Content-Type (only JSON is supported for now).
 */
public Object serialize(Object obj, String contentType, Map<String, Object> formParams) throws ApiException {
  if (contentType.startsWith("multipart/form-data")) {
    FormDataMultiPart mp = new FormDataMultiPart();
    for (Entry<String, Object> param: formParams.entrySet()) {
      if (param.getValue() instanceof File) {
        File file = (File) param.getValue();
        mp.bodyPart(new FileDataBodyPart(param.getKey(), file, MediaType.MULTIPART_FORM_DATA_TYPE));
      } else {
        mp.field(param.getKey(), parameterToString(param.getValue()), MediaType.MULTIPART_FORM_DATA_TYPE);
      }
    }
    return mp;
  } else if (contentType.startsWith("application/x-www-form-urlencoded")) {
    return this.getXWWWFormUrlencodedParams(formParams);
  } else {
    // We let Jersey attempt to serialize the body
    return obj;
  }
}
 
Example 4
Source File: MailgunServlet.java    From java-docs-samples with Apache License 2.0 6 votes vote down vote up
private ClientResponse sendComplexMessage(String recipient) {
  Client client = Client.create();
  client.addFilter(new HTTPBasicAuthFilter("api", MAILGUN_API_KEY));
  WebResource webResource =
      client.resource("https://api.mailgun.net/v3/" + MAILGUN_DOMAIN_NAME + "/messages");
  FormDataMultiPart formData = new FormDataMultiPart();
  formData.field("from", "Mailgun User <mailgun@" + MAILGUN_DOMAIN_NAME + ">");
  formData.field("to", recipient);
  formData.field("subject", "Complex Mailgun Example");
  formData.field("html", "<html>HTML <strong>content</strong></html>");
  ClassLoader classLoader = getClass().getClassLoader();
  File txtFile = new File(classLoader.getResource("example-attachment.txt").getFile());
  formData.bodyPart(new FileDataBodyPart("attachment", txtFile, MediaType.TEXT_PLAIN_TYPE));
  return webResource
      .type(MediaType.MULTIPART_FORM_DATA_TYPE)
      .post(ClientResponse.class, formData);
}
 
Example 5
Source File: MailgunServlet.java    From java-docs-samples with Apache License 2.0 6 votes vote down vote up
@SuppressWarnings("VariableDeclarationUsageDistance")
private ClientResponse sendComplexMessage(String recipient) {
  Client client = Client.create();
  client.addFilter(new HTTPBasicAuthFilter("api", MAILGUN_API_KEY));
  FormDataMultiPart formData = new FormDataMultiPart();
  formData.field("from", "Mailgun User <mailgun@" + MAILGUN_DOMAIN_NAME + ">");
  formData.field("to", recipient);
  formData.field("subject", "Complex Mailgun Example");
  formData.field("html", "<html>HTML <strong>content</strong></html>");
  ClassLoader classLoader = getClass().getClassLoader();
  File txtFile = new File(classLoader.getResource("example-attachment.txt").getFile());
  formData.bodyPart(new FileDataBodyPart("attachment", txtFile, MediaType.TEXT_PLAIN_TYPE));
  WebResource webResource =
      client.resource("https://api.mailgun.net/v3/" + MAILGUN_DOMAIN_NAME + "/messages");
  return webResource
      .type(MediaType.MULTIPART_FORM_DATA_TYPE)
      .post(ClientResponse.class, formData);
}
 
Example 6
Source File: RestRequestSender.java    From osiris with Apache License 2.0 6 votes vote down vote up
public <T> ClientResponse<T> upload(String url, File f, Class<T> expectedResponse, Headers... headers) {
	
	@SuppressWarnings("resource")
	FormDataMultiPart form = new FormDataMultiPart();
	form.bodyPart(new FileDataBodyPart("file", f, MediaType.APPLICATION_OCTET_STREAM_TYPE));

	String urlCreated = createURI(url);
	ClientConfig cc = new DefaultClientConfig();
	cc.getClasses().add(MultiPartWriter.class);
	WebResource webResource = Client.create(cc).resource(urlCreated);
	Builder builder = webResource.type(MULTIPART_MEDIA).accept(MEDIA).accept("text/plain");
	for (Headers h : headers) {
		builder.header(h.getKey(), h.getValue());
	}

	com.sun.jersey.api.client.ClientResponse clienteResponse = null;

	clienteResponse = builder.post(com.sun.jersey.api.client.ClientResponse.class, form);

	return new ClientResponse<T>(clienteResponse, expectedResponse);
}
 
Example 7
Source File: ManagementWsDelegate.java    From roboconf-platform with Apache License 2.0 6 votes vote down vote up
/**
 * Uploads a ZIP file and loads its application template.
 * @param applicationFile a ZIP archive file
 * @throws ManagementWsException if a problem occurred with the applications management
 * @throws IOException if the file was not found or is invalid
 */
public void uploadZippedApplicationTemplate( File applicationFile ) throws ManagementWsException, IOException {

	if( applicationFile == null
			|| ! applicationFile.exists()
			|| ! applicationFile.isFile())
		throw new IOException( "Expected an existing file as parameter." );

	this.logger.finer( "Loading an application from " + applicationFile.getAbsolutePath() + "..." );

	FormDataMultiPart part = new FormDataMultiPart();
	part.bodyPart( new FileDataBodyPart( "file", applicationFile, MediaType.APPLICATION_OCTET_STREAM_TYPE));

	WebResource path = this.resource.path( UrlConstants.APPLICATIONS ).path( "templates" );
	ClientResponse response = this.wsClient.createBuilder( path )
			.type( MediaType.MULTIPART_FORM_DATA_TYPE )
			.post( ClientResponse.class, part );

	if( Family.SUCCESSFUL != response.getStatusInfo().getFamily()) {
		String value = response.getEntity( String.class );
		this.logger.finer( response.getStatusInfo() + ": " + value );
		throw new ManagementWsException( response.getStatusInfo().getStatusCode(), value );
	}

	this.logger.finer( String.valueOf( response.getStatusInfo()));
}
 
Example 8
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 9
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 10
Source File: JiraExporter.java    From rtc2jira with GNU General Public License v2.0 5 votes vote down vote up
private void persistAttachments(ODocument item, Issue issue) throws IOException {
  AttachmentStorage storage = new AttachmentStorage();
  String id = item.field(FieldNames.ID);
  List<Attachment> attachments = storage.readAttachments(Long.parseLong(id));
  if (attachments.size() > 0) {
    List<String> alreadyExportedAttachments = getAlreadyExportedAttachments(issue);
    final FormDataMultiPart multiPart = new FormDataMultiPart();
    int newlyAdded = 0;
    for (Attachment attachment : attachments) {
      // check if already exported
      if (!alreadyExportedAttachments.contains(attachment.getPath().getFileName().toString())) {
        final File fileToUpload = attachment.getPath().toFile();
        if (fileToUpload != null) {
          multiPart.bodyPart(new FileDataBodyPart("file", fileToUpload, MediaType.APPLICATION_OCTET_STREAM_TYPE));
          newlyAdded++;
        }
      }
    }
    if (newlyAdded > 0) {
      try {
        getRestAccess().postMultiPart(issue.getSelfPath() + "/attachments", multiPart);
      } catch (Exception e) {
        LOGGER.severe("Could not upload attachments");
      }
    }
  }
}
 
Example 11
Source File: IssueService.java    From jira-rest-client with Apache License 2.0 5 votes vote down vote up
/**
 * Add one or more attachments to an issue.
 *
 * @param issue Issue object
 * @return List
 * @throws JsonParseException json parsing failed
 * @throws JsonMappingException json mapping failed
 * @throws IOException general IO exception
 */
public List<Attachment> postAttachment(Issue issue) throws JsonParseException, JsonMappingException, IOException {
    List<File> files = issue.getFields().getFileList();

    if (files == null || files.size() == 0) {
        throw new IllegalStateException("Oops! Attachment Not Found.");
    }

    if ((issue.getId() == null || issue.getId().isEmpty())
            && (issue.getKey() == null || issue.getKey().isEmpty())) {
        throw new IllegalStateException("Oops! Issue id or Key not set.");
    }

    String idOrKey = issue.getId() == null ? issue.getKey() : issue.getId();

    FormDataMultiPart form = new FormDataMultiPart();
    for (int i = 0; i < files.size(); i++) {
        // The name of the multipart/form-data parameter that contains attachments must be "file"
        FileDataBodyPart fdp = new FileDataBodyPart("file", files.get(i));

        form.bodyPart(fdp);
    }

    client.setResourceName(Constants.JIRA_RESOURCE_ISSUE + "/" + idOrKey + "/attachments");

    ClientResponse response = client.postMultiPart(form);
    String content = response.getEntity(String.class);

    ObjectMapper mapper = new ObjectMapper();
    mapper.configure(DeserializationConfig.Feature.FAIL_ON_UNKNOWN_PROPERTIES, true);

    TypeReference<List<Attachment>> ref = new TypeReference<List<Attachment>>() {
    };
    List<Attachment> res = mapper.readValue(content, ref);

    return res;
}
 
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();
    }