com.sun.jersey.multipart.FormDataMultiPart Java Examples

The following examples show how to use com.sun.jersey.multipart.FormDataMultiPart. 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: 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 #3
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 #4
Source File: RestRequestSender.java    From osiris with Apache License 2.0 6 votes vote down vote up
public void uploadVoid(String url, File f, String formName, Headers... headers) {

		FormDataMultiPart form = new FormDataMultiPart().field(formName, f, MediaType.MULTIPART_FORM_DATA_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);

		for (Headers h : headers) {
			builder.header(h.getKey(), h.getValue());
		}

		builder.post(form);
	}
 
Example #5
Source File: MailgunService.java    From teammates with GNU General Public License v2.0 6 votes vote down vote up
/**
 * {@inheritDoc}
 */
@Override
public FormDataMultiPart parseToEmail(EmailWrapper wrapper) {
    FormDataMultiPart formData = new FormDataMultiPart();

    String sender = wrapper.getSenderName() == null || wrapper.getSenderName().isEmpty()
                    ? wrapper.getSenderEmail()
                    : wrapper.getSenderName() + " <" + wrapper.getSenderEmail() + ">";
    formData.field("from", sender);

    formData.field("to", wrapper.getRecipient());

    if (wrapper.getBcc() != null && !wrapper.getBcc().isEmpty()) {
        formData.field("bcc", wrapper.getBcc());
    }

    formData.field("h:Reply-To", wrapper.getReplyTo());
    formData.field("subject", wrapper.getSubject());
    formData.field("html", wrapper.getContent());

    return formData;
}
 
Example #6
Source File: MailgunService.java    From teammates with GNU General Public License v2.0 6 votes vote down vote up
@Override
public EmailSendingStatus sendEmail(EmailWrapper wrapper) {
    try (FormDataMultiPart email = parseToEmail(wrapper)) {
        Client client = Client.create();
        client.addFilter(new HTTPBasicAuthFilter("api", Config.MAILGUN_APIKEY));
        WebResource webResource =
                client.resource("https://api.mailgun.net/v3/" + Config.MAILGUN_DOMAINNAME + "/messages");

        ClientResponse response = webResource.type(MediaType.MULTIPART_FORM_DATA_TYPE)
                .post(ClientResponse.class, email);

        return new EmailSendingStatus(response.getStatus(), response.getStatusInfo().getReasonPhrase());
    } catch (IOException e) {
        log.warning("Could not clean up resources after sending email: " + TeammatesException.toStringWithStackTrace(e));
        return new EmailSendingStatus(HttpStatus.SC_OK, e.getMessage());
    }
}
 
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: 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 #11
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 #12
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 #13
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 #14
Source File: RepositoryCleanupUtil.java    From pentaho-kettle with Apache License 2.0 6 votes vote down vote up
/**
 * Create payload to supply with POST to REST API
 * 
 * @return
 */
private FormDataMultiPart createParametersForm() {
  FormDataMultiPart form = new FormDataMultiPart();
  if ( verCount != -1 && !purgeRev ) {
    form.field( VER_COUNT, Integer.toString( verCount ), MediaType.MULTIPART_FORM_DATA_TYPE );
  }
  if ( delFrom != null && !purgeRev ) {
    form.field( DEL_DATE, delFrom, MediaType.MULTIPART_FORM_DATA_TYPE );
  }
  if ( fileFilter != null ) {
    form.field( FILE_FILTER, fileFilter, MediaType.MULTIPART_FORM_DATA_TYPE );
  }
  if ( logLevel != null ) {
    form.field( LOG_LEVEL, logLevel, MediaType.MULTIPART_FORM_DATA_TYPE );
  }
  if ( purgeFiles ) {
    form.field( PURGE_FILES, Boolean.toString( purgeFiles ), MediaType.MULTIPART_FORM_DATA_TYPE );
  }
  if ( purgeRev ) {
    form.field( PURGE_REV, Boolean.toString( purgeRev ), MediaType.MULTIPART_FORM_DATA_TYPE );
  }
  if ( purgeShared ) {
    form.field( PURGE_SHARED, Boolean.toString( purgeShared ), MediaType.MULTIPART_FORM_DATA_TYPE );
  }
  return form;
}
 
Example #15
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 #16
Source File: RepositoryCleanupUtil.java    From pentaho-kettle with Apache License 2.0 5 votes vote down vote up
/**
 * Create parameters and send HTTP request to purge REST endpoint
 * 
 * @param options
 */
public void purge( String[] options ) {
  FormDataMultiPart form = null;
  try {
    Map<String, String> parameters = parseExecutionOptions( options );
    validateParameters( parameters );
    authenticateLoginCredentials();

    String serviceURL = createPurgeServiceURL();
    form = createParametersForm();

    WebResource resource = client.resource( serviceURL );
    ClientResponse response = resource.type( MediaType.MULTIPART_FORM_DATA ).post( ClientResponse.class, form );

    if ( response != null && response.getStatus() == 200 ) {
      String resultLog = response.getEntity( String.class );
      String logName = writeLog( resultLog );
      writeOut( Messages.getInstance().getString( "REPOSITORY_CLEANUP_UTIL.INFO_0001.OP_SUCCESS", logName ), false );
    } else {
      writeOut( Messages.getInstance().getString( "REPOSITORY_CLEANUP_UTIL.ERROR_0001.OP_FAILURE" ), true );
    }

  } catch ( Exception e ) {
    if ( e.getMessage() != null ) {
      System.out.println( e.getMessage() );
    } else {
      if ( !( e instanceof NormalExitException ) ) {
        e.printStackTrace();
      }
    }
  } finally {
    if ( client != null ) {
      client.destroy();
    }

    if ( form != null ) {
      form.cleanup();
    }
  }
}
 
Example #17
Source File: EmailSenderTest.java    From teammates with GNU General Public License v2.0 5 votes vote down vote up
@Test
public void testConvertToMailgun() throws Exception {
    EmailWrapper wrapper = getTypicalEmailWrapper();
    try (FormDataMultiPart formData = new MailgunService().parseToEmail(wrapper)) {

        assertEquals(wrapper.getSenderName() + " <" + wrapper.getSenderEmail() + ">",
                formData.getField("from").getValue());
        assertEquals(wrapper.getRecipient(), formData.getField("to").getValue());
        assertEquals(wrapper.getBcc(), formData.getField("bcc").getValue());
        assertEquals(wrapper.getReplyTo(), formData.getField("h:Reply-To").getValue());
        assertEquals(wrapper.getSubject(), formData.getField("subject").getValue());
        assertEquals(wrapper.getContent(), formData.getField("html").getValue());
    }
}
 
Example #18
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 #19
Source File: AtlasBaseClient.java    From atlas with Apache License 2.0 5 votes vote down vote up
private AtlasImportResult performImportData(BodyPart requestPart, BodyPart filePart) throws AtlasServiceException {
    MultiPart multipartEntity = new FormDataMultiPart()
            .bodyPart(requestPart)
            .bodyPart(filePart);

    return callAPI(IMPORT, AtlasImportResult.class, multipartEntity);
}
 
Example #20
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 #21
Source File: RestRequestSender.java    From osiris with Apache License 2.0 5 votes vote down vote up
public void uploadVoid(String url, File f, String formName) {

		FormDataMultiPart form = new FormDataMultiPart().field(formName, f, MediaType.MULTIPART_FORM_DATA_TYPE);
		String urlCreated = createURI(url);
		ClientConfig cc = new DefaultClientConfig();
		cc.getClasses().add(MultiPartWriter.class);
		WebResource webResource = Client.create(cc).resource(urlCreated);
		webResource.type(MULTIPART_MEDIA).accept(MEDIA).post(form);
	}
 
Example #22
Source File: RestRequestSender.java    From osiris with Apache License 2.0 5 votes vote down vote up
public SimpleClientResponse upload(String url, File f, String formName) {
	@SuppressWarnings("resource")
	FormDataMultiPart form = new FormDataMultiPart().field(formName, f, MediaType.MULTIPART_FORM_DATA_TYPE);
	String urlCreated = createURI(url);
	ClientConfig cc = new DefaultClientConfig();
	cc.getClasses().add(MultiPartWriter.class);
	WebResource webResource = Client.create(cc).resource(urlCreated);
	webResource.type(MULTIPART_MEDIA).accept(MEDIA).post(form);
	return new SimpleClientResponse(com.sun.jersey.api.client.ClientResponse.Status.NO_CONTENT);
}
 
Example #23
Source File: OlogClient.java    From phoebus with 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 #24
Source File: DefaultApi.java    From qbit-microservices-examples with Apache License 2.0 4 votes vote down vote up
/**
 * adds todo
 * add a todo item to the list
 * @param body 
 * @return Boolean
 */
public Boolean add (Todo body) throws ApiException {
  Object postBody = body;
  
  // verify the required parameter 'body' is set
  if (body == null) {
     throw new ApiException(400, "Missing the required parameter 'body' when calling add");
  }
  

  // create path and map variables
  String path = "/todo-service/todo".replaceAll("\\{format\\}","json");

  // query params
  List<Pair> queryParams = new ArrayList<Pair>();
  Map<String, String> headerParams = new HashMap<String, String>();
  Map<String, String> formParams = new HashMap<String, String>();

  

  

  final String[] accepts = {
    "application/json"
  };
  final String accept = apiClient.selectHeaderAccept(accepts);

  final String[] contentTypes = {
    
  };
  final String contentType = apiClient.selectHeaderContentType(contentTypes);

  if(contentType.startsWith("multipart/form-data")) {
    boolean hasFields = false;
    FormDataMultiPart mp = new FormDataMultiPart();
    
    if(hasFields)
      postBody = mp;
  }
  else {
    
  }

  try {
    String[] authNames = new String[] {  };
    String response = apiClient.invokeAPI(path, "POST", queryParams, postBody, headerParams, formParams, accept, contentType, authNames);
    if(response != null){
      return (Boolean) apiClient.deserialize(response, "", Boolean.class);
    }
    else {
      return null;
    }
  } catch (ApiException ex) {
    throw ex;
  }
}
 
Example #25
Source File: DefaultApi.java    From qbit-microservices-examples with Apache License 2.0 4 votes vote down vote up
/**
 * delete a todo item
 * Deletes an item by id
 * @param id id of Todo item to delete
 * @return String
 */
public String remove (String id) throws ApiException {
  Object postBody = null;
  

  // create path and map variables
  String path = "/todo-service/todo".replaceAll("\\{format\\}","json");

  // query params
  List<Pair> queryParams = new ArrayList<Pair>();
  Map<String, String> headerParams = new HashMap<String, String>();
  Map<String, String> formParams = new HashMap<String, String>();

  
  queryParams.addAll(apiClient.parameterToPairs("", "id", id));
  

  

  final String[] accepts = {
    
  };
  final String accept = apiClient.selectHeaderAccept(accepts);

  final String[] contentTypes = {
    
  };
  final String contentType = apiClient.selectHeaderContentType(contentTypes);

  if(contentType.startsWith("multipart/form-data")) {
    boolean hasFields = false;
    FormDataMultiPart mp = new FormDataMultiPart();
    
    if(hasFields)
      postBody = mp;
  }
  else {
    
  }

  try {
    String[] authNames = new String[] {  };
    String response = apiClient.invokeAPI(path, "DELETE", queryParams, postBody, headerParams, formParams, accept, contentType, authNames);
    if(response != null){
      return (String) apiClient.deserialize(response, "", String.class);
    }
    else {
      return null;
    }
  } catch (ApiException ex) {
    throw ex;
  }
}
 
Example #26
Source File: DefaultApi.java    From qbit-microservices-examples with Apache License 2.0 4 votes vote down vote up
/**
 * list items
 * List all items in the system
 * @return List<Todo>
 */
public List<Todo> list () throws ApiException {
  Object postBody = null;
  

  // create path and map variables
  String path = "/todo-service/todo".replaceAll("\\{format\\}","json");

  // query params
  List<Pair> queryParams = new ArrayList<Pair>();
  Map<String, String> headerParams = new HashMap<String, String>();
  Map<String, String> formParams = new HashMap<String, String>();

  

  

  final String[] accepts = {
    "application/json"
  };
  final String accept = apiClient.selectHeaderAccept(accepts);

  final String[] contentTypes = {
    
  };
  final String contentType = apiClient.selectHeaderContentType(contentTypes);

  if(contentType.startsWith("multipart/form-data")) {
    boolean hasFields = false;
    FormDataMultiPart mp = new FormDataMultiPart();
    
    if(hasFields)
      postBody = mp;
  }
  else {
    
  }

  try {
    String[] authNames = new String[] {  };
    String response = apiClient.invokeAPI(path, "GET", queryParams, postBody, headerParams, formParams, accept, contentType, authNames);
    if(response != null){
      return (List<Todo>) apiClient.deserialize(response, "array", Todo.class);
    }
    else {
      return null;
    }
  } catch (ApiException ex) {
    throw ex;
  }
}
 
Example #27
Source File: DefaultApi.java    From qbit-microservices-examples with Apache License 2.0 4 votes vote down vote up
/**
 * no summary
 * no description
 * @param departmentId no description
 * @param body 
 * @param employeeId no description
 * @param X_PASS_CODE no description
 * @return Boolean
 */
public Boolean addPhoneNumberKitchenSink (Integer departmentId, PhoneNumber body, Integer employeeId, String X_PASS_CODE) throws ApiException {
  Object postBody = body;
  
  // verify the required parameter 'departmentId' is set
  if (departmentId == null) {
     throw new ApiException(400, "Missing the required parameter 'departmentId' when calling addPhoneNumberKitchenSink");
  }
  
  // verify the required parameter 'body' is set
  if (body == null) {
     throw new ApiException(400, "Missing the required parameter 'body' when calling addPhoneNumberKitchenSink");
  }
  

  // create path and map variables
  String path = "/hr/kitchen/{departmentId}/employee/phoneNumber/kitchen/".replaceAll("\\{format\\}","json")
    .replaceAll("\\{" + "departmentId" + "\\}", apiClient.escapeString(departmentId.toString()));

  // query params
  List<Pair> queryParams = new ArrayList<Pair>();
  Map<String, String> headerParams = new HashMap<String, String>();
  Map<String, String> formParams = new HashMap<String, String>();

  
  queryParams.addAll(apiClient.parameterToPairs("", "employeeId", employeeId));
  

  if (X_PASS_CODE != null)
  headerParams.put("X-PASS-CODE", apiClient.parameterToString(X_PASS_CODE));
  

  final String[] accepts = {
    "application/json"
  };
  final String accept = apiClient.selectHeaderAccept(accepts);

  final String[] contentTypes = {
    
  };
  final String contentType = apiClient.selectHeaderContentType(contentTypes);

  if(contentType.startsWith("multipart/form-data")) {
    boolean hasFields = false;
    FormDataMultiPart mp = new FormDataMultiPart();
    
    if(hasFields)
      postBody = mp;
  }
  else {
    
  }

  try {
    String[] authNames = new String[] {  };
    String response = apiClient.invokeAPI(path, "POST", queryParams, postBody, headerParams, formParams, accept, contentType, authNames);
    if(response != null){
      return (Boolean) apiClient.deserialize(response, "", Boolean.class);
    }
    else {
      return null;
    }
  } catch (ApiException ex) {
    throw ex;
  }
}
 
Example #28
Source File: DefaultApi.java    From qbit-microservices-examples with Apache License 2.0 4 votes vote down vote up
/**
 * no summary
 * no description
 * @param departmentId no description
 * @param employeeId no description
 * @param body 
 * @return Boolean
 */
public Boolean addPhoneNumber (Integer departmentId, Integer employeeId, PhoneNumber body) throws ApiException {
  Object postBody = body;
  
  // verify the required parameter 'departmentId' is set
  if (departmentId == null) {
     throw new ApiException(400, "Missing the required parameter 'departmentId' when calling addPhoneNumber");
  }
  
  // verify the required parameter 'employeeId' is set
  if (employeeId == null) {
     throw new ApiException(400, "Missing the required parameter 'employeeId' when calling addPhoneNumber");
  }
  
  // verify the required parameter 'body' is set
  if (body == null) {
     throw new ApiException(400, "Missing the required parameter 'body' when calling addPhoneNumber");
  }
  

  // create path and map variables
  String path = "/hr/department/{departmentId}/employee/{employeeId}/phoneNumber/".replaceAll("\\{format\\}","json")
    .replaceAll("\\{" + "departmentId" + "\\}", apiClient.escapeString(departmentId.toString()))
    .replaceAll("\\{" + "employeeId" + "\\}", apiClient.escapeString(employeeId.toString()));

  // query params
  List<Pair> queryParams = new ArrayList<Pair>();
  Map<String, String> headerParams = new HashMap<String, String>();
  Map<String, String> formParams = new HashMap<String, String>();

  

  

  final String[] accepts = {
    "application/json"
  };
  final String accept = apiClient.selectHeaderAccept(accepts);

  final String[] contentTypes = {
    
  };
  final String contentType = apiClient.selectHeaderContentType(contentTypes);

  if(contentType.startsWith("multipart/form-data")) {
    boolean hasFields = false;
    FormDataMultiPart mp = new FormDataMultiPart();
    
    if(hasFields)
      postBody = mp;
  }
  else {
    
  }

  try {
    String[] authNames = new String[] {  };
    String response = apiClient.invokeAPI(path, "POST", queryParams, postBody, headerParams, formParams, accept, contentType, authNames);
    if(response != null){
      return (Boolean) apiClient.deserialize(response, "", Boolean.class);
    }
    else {
      return null;
    }
  } catch (ApiException ex) {
    throw ex;
  }
}
 
Example #29
Source File: DefaultApi.java    From qbit-microservices-examples with Apache License 2.0 4 votes vote down vote up
/**
 * no summary
 * no description
 * @param departmentId no description
 * @param employeeId no description
 * @return List<PhoneNumber>
 */
public List<PhoneNumber> getPhoneNumbers (Integer departmentId, Integer employeeId) throws ApiException {
  Object postBody = null;
  
  // verify the required parameter 'departmentId' is set
  if (departmentId == null) {
     throw new ApiException(400, "Missing the required parameter 'departmentId' when calling getPhoneNumbers");
  }
  
  // verify the required parameter 'employeeId' is set
  if (employeeId == null) {
     throw new ApiException(400, "Missing the required parameter 'employeeId' when calling getPhoneNumbers");
  }
  

  // create path and map variables
  String path = "/hr/department/{departmentId}/employee/{employeeId}/phoneNumber/".replaceAll("\\{format\\}","json")
    .replaceAll("\\{" + "departmentId" + "\\}", apiClient.escapeString(departmentId.toString()))
    .replaceAll("\\{" + "employeeId" + "\\}", apiClient.escapeString(employeeId.toString()));

  // query params
  List<Pair> queryParams = new ArrayList<Pair>();
  Map<String, String> headerParams = new HashMap<String, String>();
  Map<String, String> formParams = new HashMap<String, String>();

  

  

  final String[] accepts = {
    "application/json"
  };
  final String accept = apiClient.selectHeaderAccept(accepts);

  final String[] contentTypes = {
    
  };
  final String contentType = apiClient.selectHeaderContentType(contentTypes);

  if(contentType.startsWith("multipart/form-data")) {
    boolean hasFields = false;
    FormDataMultiPart mp = new FormDataMultiPart();
    
    if(hasFields)
      postBody = mp;
  }
  else {
    
  }

  try {
    String[] authNames = new String[] {  };
    String response = apiClient.invokeAPI(path, "GET", queryParams, postBody, headerParams, formParams, accept, contentType, authNames);
    if(response != null){
      return (List<PhoneNumber>) apiClient.deserialize(response, "array", PhoneNumber.class);
    }
    else {
      return null;
    }
  } catch (ApiException ex) {
    throw ex;
  }
}
 
Example #30
Source File: DefaultApi.java    From qbit-microservices-examples with Apache License 2.0 4 votes vote down vote up
/**
 * no summary
 * no description
 * @param departmentId no description
 * @param employeeId no description
 * @return Employee
 */
public Employee getEmployee (Integer departmentId, Integer employeeId) throws ApiException {
  Object postBody = null;
  
  // verify the required parameter 'departmentId' is set
  if (departmentId == null) {
     throw new ApiException(400, "Missing the required parameter 'departmentId' when calling getEmployee");
  }
  
  // verify the required parameter 'employeeId' is set
  if (employeeId == null) {
     throw new ApiException(400, "Missing the required parameter 'employeeId' when calling getEmployee");
  }
  

  // create path and map variables
  String path = "/hr/department/{departmentId}/employee/{employeeId}".replaceAll("\\{format\\}","json")
    .replaceAll("\\{" + "departmentId" + "\\}", apiClient.escapeString(departmentId.toString()))
    .replaceAll("\\{" + "employeeId" + "\\}", apiClient.escapeString(employeeId.toString()));

  // query params
  List<Pair> queryParams = new ArrayList<Pair>();
  Map<String, String> headerParams = new HashMap<String, String>();
  Map<String, String> formParams = new HashMap<String, String>();

  

  

  final String[] accepts = {
    "application/json"
  };
  final String accept = apiClient.selectHeaderAccept(accepts);

  final String[] contentTypes = {
    
  };
  final String contentType = apiClient.selectHeaderContentType(contentTypes);

  if(contentType.startsWith("multipart/form-data")) {
    boolean hasFields = false;
    FormDataMultiPart mp = new FormDataMultiPart();
    
    if(hasFields)
      postBody = mp;
  }
  else {
    
  }

  try {
    String[] authNames = new String[] {  };
    String response = apiClient.invokeAPI(path, "GET", queryParams, postBody, headerParams, formParams, accept, contentType, authNames);
    if(response != null){
      return (Employee) apiClient.deserialize(response, "", Employee.class);
    }
    else {
      return null;
    }
  } catch (ApiException ex) {
    throw ex;
  }
}