Example usage for org.apache.http.entity ContentType DEFAULT_BINARY

List of usage examples for org.apache.http.entity ContentType DEFAULT_BINARY

Introduction

In this page you can find the example usage for org.apache.http.entity ContentType DEFAULT_BINARY.

Prototype

ContentType DEFAULT_BINARY

To view the source code for org.apache.http.entity ContentType DEFAULT_BINARY.

Click Source Link

Usage

From source file:gov.osti.services.Metadata.java

/**
 * Send this Metadata to the ARCHIVER external support process.
 *
 * Needs a CODE ID and one of either an ARCHIVE FILE or REPOSITORY LINK.
 *
 * If nothing supplied to archive, do nothing.
 *
 * @param codeId the CODE ID for this METADATA
 * @param repositoryLink (optional) the REPOSITORY LINK value, or null if none
 * @param archiveFile (optional) the File recently uploaded to ARCHIVE, or null if none
 * @param archiveContainer (optional) the Container recently uploaded to ARCHIVE, or null if none
 * @throws IOException on IO transmission errors
 *///  w w w . j a va 2  s  .  c o  m
private static void sendToArchiver(Long codeId, String repositoryLink, File archiveFile, File archiveContainer)
        throws IOException {
    if ("".equals(ARCHIVER_URL))
        return;

    // Nothing sent?
    if (StringUtils.isBlank(repositoryLink) && null == archiveFile && null == archiveContainer)
        return;

    // set up a connection
    CloseableHttpClient hc = HttpClientBuilder.create().setDefaultRequestConfig(RequestConfig.custom()
            .setSocketTimeout(300000).setConnectTimeout(300000).setConnectionRequestTimeout(300000).build())
            .build();

    try {
        HttpPost post = new HttpPost(ARCHIVER_URL);
        // attributes to send
        ObjectNode request = mapper.createObjectNode();
        request.put("code_id", codeId);
        request.put("repository_link", repositoryLink);

        // determine if there's a file to send or not
        if (null == archiveFile && null == archiveContainer) {
            post.setHeader("Content-Type", "application/json");
            post.setHeader("Accept", "application/json");

            post.setEntity(new StringEntity(request.toString(), "UTF-8"));
        } else {
            MultipartEntityBuilder mpe = MultipartEntityBuilder.create()
                    .setMode(HttpMultipartMode.BROWSER_COMPATIBLE)
                    .addPart("project", new StringBody(request.toString(), ContentType.APPLICATION_JSON));

            if (archiveFile != null)
                mpe.addPart("file", new FileBody(archiveFile, ContentType.DEFAULT_BINARY));

            if (archiveContainer != null)
                mpe.addPart("container", new FileBody(archiveContainer, ContentType.DEFAULT_BINARY));

            post.setEntity(mpe.build());
        }
        HttpResponse response = hc.execute(post);

        int statusCode = response.getStatusLine().getStatusCode();

        if (HttpStatus.SC_OK != statusCode && HttpStatus.SC_CREATED != statusCode) {
            throw new IOException("Archiver Error: " + EntityUtils.toString(response.getEntity()));
        }
    } catch (IOException e) {
        log.warn("Archiver request error: " + e.getMessage());
        throw e;
    } finally {
        try {
            if (null != hc)
                hc.close();
        } catch (IOException e) {
            log.warn("Close Error: " + e.getMessage());
        }
    }
}

From source file:org.opentravel.schemacompiler.repository.impl.RemoteRepositoryClient.java

/**
 * @see org.opentravel.schemacompiler.repository.Repository#unlock(org.opentravel.schemacompiler.repository.RepositoryItem,
 *      boolean)/*from  w w  w. j a  v a2  s.com*/
 */
@SuppressWarnings("unchecked")
@Override
public void unlock(RepositoryItem item, boolean commitWIP) throws RepositoryException {
    InputStream wipContent = null;
    boolean success = false;
    try {
        validateRepositoryItem(item);
        manager.getFileManager().startChangeSet();

        // Build the HTTP request for the remote service
        RepositoryItemIdentityType itemIdentity = createItemIdentity(item);
        Marshaller marshaller = RepositoryFileManager.getSharedJaxbContext().createMarshaller();
        HttpPost request = newPostRequest(UNLOCK_ENDPOINT);

        MultipartEntityBuilder mpEntity = MultipartEntityBuilder.create();
        StringWriter xmlWriter = new StringWriter();

        if (commitWIP) {
            File wipFile = manager.getFileManager().getLibraryWIPContentLocation(item.getBaseNamespace(),
                    item.getFilename());

            if (!wipFile.exists()) {
                throw new RepositoryException("The work-in-process file does not exist: " + item.getFilename());
            }
            wipContent = new FileInputStream(wipFile);
            mpEntity.addBinaryBody("fileContent", toByteArray(wipContent), ContentType.DEFAULT_BINARY,
                    item.getFilename());
            // mpEntity.addPart( "fileContent", new InputStreamBody(wipContent,
            // item.getFilename()) );
        }
        marshaller.marshal(objectFactory.createRepositoryItemIdentity(itemIdentity), xmlWriter);
        mpEntity.addTextBody("item", xmlWriter.toString(), ContentType.TEXT_XML);
        request.setEntity(mpEntity.build());

        // Send the web service request and unmarshall the updated meta-data from the response
        log.info("Sending lock request to HTTP endpoint: " + endpointUrl);
        HttpResponse response = executeWithAuthentication(request);

        if (response.getStatusLine().getStatusCode() != HTTP_RESPONSE_STATUS_OK) {
            throw new RepositoryException(getResponseErrorMessage(response));
        }
        log.info("Lock response received - Status OK");

        Unmarshaller unmarshaller = RepositoryFileManager.getSharedJaxbContext().createUnmarshaller();
        JAXBElement<LibraryInfoType> jaxbElement = (JAXBElement<LibraryInfoType>) unmarshaller
                .unmarshal(response.getEntity().getContent());

        // Update the local cache with the content we just received from the remote web service
        manager.getFileManager().saveLibraryMetadata(jaxbElement.getValue());

        // Update the local repository item with the latest state information
        ((RepositoryItemImpl) item).setState(RepositoryItemState.MANAGED_UNLOCKED);
        ((RepositoryItemImpl) item).setLockedByUser(null);

        // Force a re-download of the updated content to make sure the local copy is
        // synchronized
        // with the remote repository.
        downloadContent(item, true);

        success = true;

    } catch (JAXBException e) {
        throw new RepositoryException("The format of the library meta-data is unreadable.", e);

    } catch (IOException e) {
        throw new RepositoryException("The remote repository is unavailable.", e);

    } finally {
        // Close the WIP content input stream
        try {
            if (wipContent != null)
                wipContent.close();
        } catch (Throwable t) {
        }

        // Commit or roll back the changes based on the result of the operation
        if (success) {
            manager.getFileManager().commitChangeSet();
        } else {
            try {
                manager.getFileManager().rollbackChangeSet();
            } catch (Throwable t) {
                log.error("Error rolling back the current change set.", t);
            }
        }
    }
}

From source file:org.flowable.app.service.editor.AppDefinitionPublishService.java

protected void deployZipArtifact(String artifactName, byte[] zipArtifact, String deploymentKey,
        String deploymentName) {//www.jav a  2s . com
    String deployApiUrl = environment.getRequiredProperty("deployment.api.url");
    String basicAuthUser = environment.getRequiredProperty("idm.admin.user");
    String basicAuthPassword = environment.getRequiredProperty("idm.admin.password");

    if (deployApiUrl.endsWith("/") == false) {
        deployApiUrl = deployApiUrl.concat("/");
    }
    deployApiUrl = deployApiUrl
            .concat(String.format("repository/deployments?deploymentKey=%s&deploymentName=%s",
                    encode(deploymentKey), encode(deploymentName)));

    HttpPost httpPost = new HttpPost(deployApiUrl);
    httpPost.setHeader(HttpHeaders.AUTHORIZATION, "Basic " + new String(
            Base64.encodeBase64((basicAuthUser + ":" + basicAuthPassword).getBytes(Charset.forName("UTF-8")))));

    MultipartEntityBuilder entityBuilder = MultipartEntityBuilder.create();
    entityBuilder.setMode(HttpMultipartMode.BROWSER_COMPATIBLE);
    entityBuilder.addBinaryBody("artifact", zipArtifact, ContentType.DEFAULT_BINARY, artifactName);

    HttpEntity entity = entityBuilder.build();
    httpPost.setEntity(entity);

    HttpClientBuilder clientBuilder = HttpClientBuilder.create();
    SSLConnectionSocketFactory sslsf = null;
    try {
        SSLContextBuilder builder = new SSLContextBuilder();
        builder.loadTrustMaterial(null, new TrustSelfSignedStrategy());
        sslsf = new SSLConnectionSocketFactory(builder.build(),
                SSLConnectionSocketFactory.ALLOW_ALL_HOSTNAME_VERIFIER);
        clientBuilder.setSSLSocketFactory(sslsf);
    } catch (Exception e) {
        logger.error("Could not configure SSL for http client", e);
        throw new InternalServerErrorException("Could not configure SSL for http client", e);
    }

    CloseableHttpClient client = clientBuilder.build();

    try {
        HttpResponse response = client.execute(httpPost);
        if (response.getStatusLine().getStatusCode() == HttpStatus.SC_CREATED) {
            return;
        } else {
            logger.error("Invalid deploy result code: {}", response.getStatusLine());
            throw new InternalServerErrorException("Invalid deploy result code: " + response.getStatusLine());
        }
    } catch (IOException ioe) {
        logger.error("Error calling deploy endpoint", ioe);
        throw new InternalServerErrorException("Error calling deploy endpoint: " + ioe.getMessage());
    } finally {
        if (client != null) {
            try {
                client.close();
            } catch (IOException e) {
                logger.warn("Exception while closing http client", e);
            }
        }
    }
}

From source file:org.rapidoid.http.HttpClient.java

public Future<byte[]> request(String verb, String uri, Map<String, String> headers, Map<String, String> data,
        Map<String, String> files, byte[] body, String contentType, Callback<byte[]> callback,
        boolean fullResponse) {

    headers = U.safe(headers);/*from   w ww  .  j  ava 2s .  c  o  m*/
    data = U.safe(data);
    files = U.safe(files);

    HttpRequestBase req;
    boolean canHaveBody = false;

    if ("GET".equalsIgnoreCase(verb)) {
        req = new HttpGet(uri);
    } else if ("DELETE".equalsIgnoreCase(verb)) {
        req = new HttpDelete(uri);
    } else if ("OPTIONS".equalsIgnoreCase(verb)) {
        req = new HttpOptions(uri);
    } else if ("HEAD".equalsIgnoreCase(verb)) {
        req = new HttpHead(uri);
    } else if ("TRACE".equalsIgnoreCase(verb)) {
        req = new HttpTrace(uri);
    } else if ("POST".equalsIgnoreCase(verb)) {
        req = new HttpPost(uri);
        canHaveBody = true;
    } else if ("PUT".equalsIgnoreCase(verb)) {
        req = new HttpPut(uri);
        canHaveBody = true;
    } else if ("PATCH".equalsIgnoreCase(verb)) {
        req = new HttpPatch(uri);
        canHaveBody = true;
    } else {
        throw U.illegalArg("Illegal HTTP verb: " + verb);
    }

    for (Entry<String, String> e : headers.entrySet()) {
        req.addHeader(e.getKey(), e.getValue());
    }

    if (canHaveBody) {
        HttpEntityEnclosingRequestBase entityEnclosingReq = (HttpEntityEnclosingRequestBase) req;

        if (body != null) {

            NByteArrayEntity entity = new NByteArrayEntity(body);

            if (contentType != null) {
                entity.setContentType(contentType);
            }

            entityEnclosingReq.setEntity(entity);
        } else {

            MultipartEntityBuilder builder = MultipartEntityBuilder.create();

            for (Entry<String, String> entry : files.entrySet()) {
                String filename = entry.getValue();
                File file = IO.file(filename);
                builder = builder.addBinaryBody(entry.getKey(), file, ContentType.DEFAULT_BINARY, filename);
            }

            for (Entry<String, String> entry : data.entrySet()) {
                builder = builder.addTextBody(entry.getKey(), entry.getValue(), ContentType.DEFAULT_TEXT);
            }

            ByteArrayOutputStream stream = new ByteArrayOutputStream();
            try {
                builder.build().writeTo(stream);
            } catch (IOException e) {
                throw U.rte(e);
            }

            byte[] bytes = stream.toByteArray();
            NByteArrayEntity entity = new NByteArrayEntity(bytes, ContentType.MULTIPART_FORM_DATA);

            entityEnclosingReq.setEntity(entity);
        }
    }

    Log.debug("Starting HTTP request", "request", req.getRequestLine());

    return execute(client, req, callback, fullResponse);
}

From source file:org.wso2.msf4j.example.SampleClient.java

private static HttpEntity createMessageForSimpleFormStreaming() {
    HttpEntity reqEntity = null;//from  w  ww  . java 2s  . c om
    try {
        reqEntity = MultipartEntityBuilder.create().addTextBody("name", "WSO2").addTextBody("age", "10")
                .addBinaryBody("file", new File(
                        Thread.currentThread().getContextClassLoader().getResource("sample.txt").toURI()),
                        ContentType.DEFAULT_BINARY, "sample.txt")
                .build();
    } catch (URISyntaxException e) {
        log.error("Error while getting the file from resource." + e.getMessage(), e);
    }
    return reqEntity;
}

From source file:org.wso2.msf4j.example.SampleClient.java

private static HttpEntity createMessageForComplexForm() {
    HttpEntity reqEntity = null;/*  w  ww  .  j  a va  2  s  . c  o m*/
    try {
        StringBody companyText = new StringBody("{\"type\": \"Open Source\"}", ContentType.APPLICATION_JSON);
        StringBody personList = new StringBody(
                "[{\"name\":\"Richard Stallman\",\"age\":63}, {\"name\":\"Linus Torvalds\",\"age\":46}]",
                ContentType.APPLICATION_JSON);
        reqEntity = MultipartEntityBuilder.create().addTextBody("id", "1").addPart("company", companyText)
                .addPart("people", personList)
                .addBinaryBody("file", new File(
                        Thread.currentThread().getContextClassLoader().getResource("sample.txt").toURI()),
                        ContentType.DEFAULT_BINARY, "sample.txt")
                .build();
    } catch (URISyntaxException e) {
        log.error("Error while getting the file from resource." + e.getMessage(), e);
    }
    return reqEntity;
}

From source file:org.wso2.msf4j.example.SampleClient.java

private static HttpEntity createMessageForMultipleFiles() {
    HttpEntity reqEntity = null;/*  ww  w .j  a  va2 s  .  co  m*/
    try {
        reqEntity = MultipartEntityBuilder.create()
                .addBinaryBody("files",
                        new File(Thread.currentThread().getContextClassLoader().getResource("sample.txt")
                                .toURI()),
                        ContentType.DEFAULT_BINARY, "sample.txt")
                .addBinaryBody("files", new File(
                        Thread.currentThread().getContextClassLoader().getResource("sample.jpg").toURI()),
                        ContentType.DEFAULT_BINARY, "sample.jpg")
                .build();
    } catch (URISyntaxException e) {
        log.error("Error while getting the file from resource." + e.getMessage(), e);
    }
    return reqEntity;
}

From source file:org.wso2.msf4j.HttpServerTest.java

@Test
public void testFormParamWithFile() throws IOException, URISyntaxException {
    HttpURLConnection connection = request("/test/v1/testFormParamWithFile", HttpMethod.POST);
    File file = new File(Thread.currentThread().getContextClassLoader().getResource("testJpgFile.jpg").toURI());
    MultipartEntityBuilder builder = MultipartEntityBuilder.create();
    FileBody fileBody = new FileBody(file, ContentType.DEFAULT_BINARY);
    builder.addPart("form", fileBody);
    HttpEntity build = builder.build();/* ww  w.  j a  va 2  s  . c o m*/
    connection.setRequestProperty("Content-Type", build.getContentType().getValue());
    try (OutputStream out = connection.getOutputStream()) {
        build.writeTo(out);
    }

    InputStream inputStream = connection.getInputStream();
    String response = StreamUtil.asString(inputStream);
    IOUtils.closeQuietly(inputStream);
    connection.disconnect();
    assertEquals(response, file.getName());
}

From source file:org.wso2.msf4j.HttpServerTest.java

@Test
public void testFormDataParamWithComplexForm() throws IOException, URISyntaxException {
    HttpURLConnection connection = request("/test/v1/complexForm", HttpMethod.POST);
    StringBody companyText = new StringBody("{\"type\": \"Open Source\"}", ContentType.APPLICATION_JSON);
    StringBody personList = new StringBody(
            "[{\"name\":\"Richard Stallman\",\"age\":63}, {\"name\":\"Linus Torvalds\",\"age\":46}]",
            ContentType.APPLICATION_JSON);
    HttpEntity reqEntity = MultipartEntityBuilder.create().addTextBody("id", "1")
            .addPart("company", companyText).addPart("people", personList)
            .addBinaryBody(/*from w ww.j a v  a2s  .  c o  m*/
                    "file", new File(Thread.currentThread().getContextClassLoader()
                            .getResource("testTxtFile.txt").toURI()),
                    ContentType.DEFAULT_BINARY, "testTxtFile.txt")
            .build();

    connection.setRequestProperty("Content-Type", reqEntity.getContentType().getValue());
    try (OutputStream out = connection.getOutputStream()) {
        reqEntity.writeTo(out);
    }

    InputStream inputStream = connection.getInputStream();
    String response = StreamUtil.asString(inputStream);
    IOUtils.closeQuietly(inputStream);
    connection.disconnect();
    assertEquals(response, "testTxtFile.txt:1:2:Open Source");
}