Java Code Examples for com.sun.jersey.multipart.file.FileDataBodyPart

The following examples show how to use com.sun.jersey.multipart.file.FileDataBodyPart. These examples are extracted from open source projects. 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 Project: osiris   Source File: RestRequestSender.java    License: 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 Project: db   Source File: RestApiUtils.java    License: GNU Affero General Public License v3.0 6 votes vote down vote up
/**
 * Invokes an HTTP request to append to target file upload on target site.
 *
 * @param credential
 *            the credential containing the authentication token to use for
 *            this request
 * @param siteId
 *            the ID of the target site
 * @param uploadSessionId
 *            the session ID of the target file upload
 * @param chunk
 *            the chunk of data to append to target file upload
 * @param numChunkBytes
 *            the number of bytes in the chunk of data
 */
private void invokeAppendFileUpload(TableauCredentialsType credential, String siteId, String uploadSessionId,
        byte[] chunk, int numChunkBytes) {

    m_logger.info(String.format("Appending to file upload '%s'.", uploadSessionId));

    String url = Operation.APPEND_FILE_UPLOAD.getUrl(siteId, uploadSessionId);

    // Writes the chunk of data to a temporary file
    try (FileOutputStream outputStream = new FileOutputStream("appendFileUpload.temp")) {
        outputStream.write(chunk, 0, numChunkBytes);
    } catch (IOException e) {
        throw new IllegalStateException("Failed to create temporary file to append to file upload");
    }

    // Makes a multipart PUT request with specified credential's
    // authenticity token and payload
    BodyPart filePart = new FileDataBodyPart("tableau_file", new File("appendFileUpload.temp"),
            MediaType.APPLICATION_OCTET_STREAM_TYPE);
    putMultipart(url, credential.getToken(), null, filePart);
}
 
Example 3
Source Project: db   Source File: RestApiUtils.java    License: GNU Affero General Public License v3.0 6 votes vote down vote up
/**
 * Invokes an HTTP request to publish a workbook to target site including
 * the workbook in the request.
 *
 * @param credential
 *            the credential containing the authentication token to use for
 *            this request
 * @param siteId
 *            the ID of the target site
 * @param requestPayload
 *            the XML payload containing the workbook attributes used to
 *            publish the workbook
 * @param workbookFile
 *            the workbook file to publish
 * @return the workbook if it was published successfully, otherwise
 *         <code>null</code>
 */
private WorkbookType invokePublishWorkbookSimple(TableauCredentialsType credential, String siteId,
        String projectId, String workbookName, File workbookFile) {

    String url = Operation.PUBLISH_WORKBOOK.getUrl(siteId);

    // Creates the payload to publish the workbook
    TsRequest payload = createPayloadToPublishWorkbook(workbookName, projectId);

    // Makes a multipart POST request with specified credential's
    // authenticity token and payload
    BodyPart filePart = new FileDataBodyPart("tableau_workbook", workbookFile,
            MediaType.APPLICATION_OCTET_STREAM_TYPE);
    TsResponse response = postMultipart(url, credential.getToken(), payload, filePart);

    // Verifies that the response has a workbook element
    if (response.getWorkbook() != null) {
        m_logger.info("Publish workbook is successful!");

        return response.getWorkbook();
    }

    // No workbook was published
    return null;
}
 
Example 4
Source Project: carbon-identity-framework   Source File: ApiClient.java    License: 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 5
Source Project: forge-api-java-client   Source File: ApiClient.java    License: 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 6
Source Project: java-docs-samples   Source File: MailgunServlet.java    License: 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 <[email protected]" + 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 7
Source Project: java-docs-samples   Source File: MailgunServlet.java    License: 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 <[email protected]" + 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 8
Source Project: osiris   Source File: RestRequestSender.java    License: 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 9
Source Project: roboconf-platform   Source File: ManagementWsDelegate.java    License: 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 10
Source Project: phoebus   Source File: OlogClient.java    License: Eclipse Public License 1.0 5 votes vote down vote up
@Override
public Collection<LogEntry> call() {
    Collection<LogEntry> returnLogs = new HashSet<LogEntry>();
    for (LogEntry log : logs) {
        XmlLogs xmlLogs = new XmlLogs();
        XmlLog xmlLog = new XmlLog(log);
        xmlLog.setLevel("Info");
        xmlLogs.getLogs().add(xmlLog);

        ClientResponse clientResponse = service.path("logs")
                .accept(MediaType.APPLICATION_XML)
                .accept(MediaType.APPLICATION_JSON)
                .post(ClientResponse.class, xmlLogs);

        if (clientResponse.getStatus() < 300) {

            // XXX there is an assumption that the result without an error status will consist of a single created log entry
            XmlLog createdLog = clientResponse.getEntity(XmlLogs.class).getLogs().iterator().next();
            log.getAttachments().forEach(attachment -> {
                FormDataMultiPart form = new FormDataMultiPart();
                form.bodyPart(new FileDataBodyPart("file", attachment.getFile()));
                XmlAttachment createdAttachment = service.path("attachments").path(createdLog.getId().toString())
                        .type(MediaType.MULTIPART_FORM_DATA).accept(MediaType.APPLICATION_XML)
                        .post(XmlAttachment.class, form);
                createdLog.addXmlAttachment(createdAttachment);
            });
            returnLogs.add(new OlogLog(createdLog));

        } else
            throw new UniformInterfaceException(clientResponse);
        
    }

    return Collections.unmodifiableCollection(returnLogs);

}
 
Example 11
Source Project: rtc2jira   Source File: JiraExporter.java    License: 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 12
Source Project: jira-rest-client   Source File: IssueService.java    License: 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 13
Source Project: atlas   Source File: AtlasBaseClient.java    License: Apache License 2.0 4 votes vote down vote up
public AtlasImportResult importData(AtlasImportRequest request, String absoluteFilePath) throws AtlasServiceException {
    return performImportData(getImportRequestBodyPart(request),
                        new FileDataBodyPart(IMPORT_DATA_PARAMETER, new File(absoluteFilePath)));
}
 
Example 14
Source Project: phoebus   Source File: OlogClient.java    License: 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);
    }
}