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

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

Introduction

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

Prototype

ContentType APPLICATION_OCTET_STREAM

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

Click Source Link

Usage

From source file:de.siegmar.securetransfer.controller.MvcTest.java

@Test
public void messageWithFileWithPassword() throws Exception {
    final String messageToSend = "my secret message";
    final String password = "top secret password";
    final String fileContent = "test file content";

    final String boundary = "------TestBoundary" + UUID.randomUUID();
    final MultipartEntityBuilder builder = MultipartEntityBuilder.create().setBoundary(boundary)
            .addTextBody("expirationDays", "1").addTextBody("message", messageToSend)
            .addTextBody("password", password).addBinaryBody("files",
                    fileContent.getBytes(StandardCharsets.UTF_8), ContentType.APPLICATION_OCTET_STREAM,
                    "test.txt");

    // Create new message and expect redirect with flash message after store
    final MvcResult createMessageResult = mockMvc
            .perform(post("/send").content(ByteStreams.toByteArray(builder.build().getContent()))
                    .contentType(MediaType.MULTIPART_FORM_DATA_VALUE + "; boundary=" + boundary))
            .andExpect(status().isFound()).andExpect(redirectedUrlPattern("/send/**"))
            .andExpect(flash().attribute("message", messageToSend)).andReturn();

    // receive data after redirect
    final String messageStatusUrl = createMessageResult.getResponse().getRedirectedUrl();

    final String linkSecret = messageStatusUrl.replaceFirst(".*linkSecret=", "");
    HashCode.fromString(linkSecret);//from w w  w.  j  a v a  2s. com

    final MvcResult messageStatusResult = mockMvc.perform(get(messageStatusUrl)).andExpect(status().isOk())
            .andExpect(content().contentType("text/html;charset=UTF-8"))
            .andExpect(view().name("send/message_status")).andReturn();

    final SenderMessage senderMessage = (SenderMessage) messageStatusResult.getModelAndView().getModel()
            .get("senderMessage");

    assertNotNull(senderMessage);
    assertNotNull(senderMessage.getId());
    assertNotNull(senderMessage.getReceiverId());
    assertNotNull(senderMessage.getExpiration());
    assertNull(senderMessage.getReceived());
    assertTrue(senderMessage.isPasswordEncrypted());

    final String receiveUrl = (String) messageStatusResult.getModelAndView().getModel().get("receiveUrl");

    assertNotNull(receiveUrl);

    // call receiver URL
    final MvcResult confirmPage = mockMvc.perform(get(receiveUrl)).andExpect(status().isOk())
            .andExpect(content().contentType("text/html;charset=UTF-8"))
            .andExpect(view().name("receive/message_ask_password")).andReturn();

    final Document confirmPageDoc = Jsoup.parse(confirmPage.getResponse().getContentAsString());
    final String passwordUrl = confirmPageDoc.getElementsByTag("form").attr("action");

    // Receive message
    final MvcResult messageResult = mockMvc
            .perform(post(passwordUrl).param("linkSecret", linkSecret).param("password", password))
            .andExpect(status().isOk()).andExpect(content().contentType("text/html;charset=UTF-8"))
            .andExpect(view().name("receive/message")).andReturn();

    final DecryptedMessage decryptedMessage = (DecryptedMessage) messageResult.getModelAndView().getModel()
            .get("decryptedMessage");

    assertEquals(messageToSend, decryptedMessage.getMessage());
    assertEquals(1, decryptedMessage.getFiles().size());

    final DecryptedFile file = decryptedMessage.getFiles().get(0);
    final String fileId = file.getId();
    final String fileKey = file.getKeyHex();

    // Download file
    final MvcResult downloadResult = mockMvc
            .perform(get("/receive/file/{id}/{key}", fileId, fileKey).sessionAttr("iv_file_" + fileId,
                    file.getKeyIv().getIv()))
            .andExpect(request().asyncStarted())
            //.andExpect(request().asyncResult("Deferred result"))
            .andExpect(status().isOk()).andExpect(content().contentType("application/octet-stream"))
            .andReturn();

    downloadResult.getAsyncResult();
    assertEquals(fileContent, downloadResult.getResponse().getContentAsString());

    // Check message is burned
    mockMvc.perform(get(receiveUrl)).andExpect(status().isNotFound())
            .andExpect(content().contentType("text/html;charset=UTF-8"))
            .andExpect(view().name("message_not_found"));

    // Check file is burned
    mockMvc.perform(get("/receive/file/{id}/{key}", fileId, fileKey).sessionAttr("iv_file_" + fileId,
            file.getKeyIv().getIv())).andExpect(status().isNotFound())
            .andExpect(content().contentType("text/html;charset=UTF-8"))
            .andExpect(view().name("message_not_found"));

    // Check sender status page
    final MvcResult messageStatusResult2 = mockMvc.perform(get(messageStatusUrl)).andExpect(status().isOk())
            .andExpect(content().contentType("text/html;charset=UTF-8"))
            .andExpect(view().name("send/message_status")).andReturn();

    final SenderMessage senderMessage2 = (SenderMessage) messageStatusResult2.getModelAndView().getModel()
            .get("senderMessage");

    assertNotNull(senderMessage2);
    assertNotNull(senderMessage2.getId());
    assertNotNull(senderMessage2.getReceiverId());
    assertNotNull(senderMessage2.getExpiration());
    assertNotNull(senderMessage2.getReceived());
    assertTrue(senderMessage.isPasswordEncrypted());
}

From source file:com.frochr123.fabqr.FabQRFunctions.java

public static void uploadFabQRProject(String name, String email, String projectName, int licenseIndex,
        String tools, String description, String location, BufferedImage imageReal, BufferedImage imageScheme,
        PlfFile plfFile, String lasercutterName, String lasercutterMaterial) throws Exception {
    // Check for valid situation, otherwise abort
    if (MainView.getInstance() == null || VisicutModel.getInstance() == null
            || VisicutModel.getInstance().getPlfFile() == null || !isFabqrActive()
            || getFabqrPrivateURL() == null || getFabqrPrivateURL().isEmpty()
            || MaterialManager.getInstance() == null || MappingManager.getInstance() == null
            || VisicutModel.getInstance().getSelectedLaserDevice() == null) {
        throw new Exception("FabQR upload exception: Critical error");
    }//from w ww . j  a  v  a  2 s. c om

    // Check valid data
    if (name == null || email == null || projectName == null || projectName.length() < 3 || licenseIndex < 0
            || tools == null || tools.isEmpty() || description == null || description.isEmpty()
            || location == null || location.isEmpty() || imageScheme == null || plfFile == null
            || lasercutterName == null || lasercutterName.isEmpty() || lasercutterMaterial == null
            || lasercutterMaterial.isEmpty()) {
        throw new Exception("FabQR upload exception: Invalid input data");
    }

    // Convert images to byte data for PNG, imageReal is allowed to be empty
    byte[] imageSchemeBytes = null;
    ByteArrayOutputStream imageSchemeOutputStream = new ByteArrayOutputStream();
    PreviewImageExport.writePngToOutputStream(imageSchemeOutputStream, imageScheme);
    imageSchemeBytes = imageSchemeOutputStream.toByteArray();

    if (imageSchemeBytes == null) {
        throw new Exception("FabQR upload exception: Error converting scheme image");
    }

    byte[] imageRealBytes = null;

    if (imageReal != null) {
        // Need to convert image, ImageIO.write messes up the color space of the original input image
        BufferedImage convertedImage = new BufferedImage(imageReal.getWidth(), imageReal.getHeight(),
                BufferedImage.TYPE_3BYTE_BGR);
        ColorConvertOp op = new ColorConvertOp(null);
        op.filter(imageReal, convertedImage);

        ByteArrayOutputStream imageRealOutputStream = new ByteArrayOutputStream();
        ImageIO.write(convertedImage, "jpg", imageRealOutputStream);
        imageRealBytes = imageRealOutputStream.toByteArray();
    }

    // Extract all URLs from used QR codes
    List<String> referencesList = new LinkedList<String>();
    List<PlfPart> plfParts = plfFile.getPartsCopy();

    for (PlfPart plfPart : plfParts) {
        if (plfPart.getQRCodeInfo() != null && plfPart.getQRCodeInfo().getQRCodeSourceURL() != null
                && !plfPart.getQRCodeInfo().getQRCodeSourceURL().trim().isEmpty()) {
            // Process url, if it is URL of a FabQR system, remove download flag and point to project page instead
            // Use regex to check for FabQR system URL structure
            String qrCodeUrl = plfPart.getQRCodeInfo().getQRCodeSourceURL().trim();

            // Check for temporary URL structure of FabQR system
            Pattern fabQRUrlTemporaryPattern = Pattern
                    .compile("^https{0,1}://.*?" + "/" + FABQR_TEMPORARY_MARKER + "/" + "([a-z]|[0-9]){7,7}$");

            // Do not include link if it is just temporary
            if (fabQRUrlTemporaryPattern.matcher(qrCodeUrl).find()) {
                continue;
            }

            // Check for download URL structure of FabQR system
            // Change URL to point to project page instead
            Pattern fabQRUrlDownloadPattern = Pattern
                    .compile("^https{0,1}://.*?" + "/" + FABQR_DOWNLOAD_MARKER + "/" + "([a-z]|[0-9]){7,7}$");

            if (fabQRUrlDownloadPattern.matcher(qrCodeUrl).find()) {
                qrCodeUrl = qrCodeUrl.replace("/" + FABQR_DOWNLOAD_MARKER + "/", "/");
            }

            // Add URL if it is not yet in list
            if (!referencesList.contains(qrCodeUrl)) {
                referencesList.add(qrCodeUrl);
            }
        }
    }

    String references = "";

    for (String ref : referencesList) {
        // Add comma for non first entries
        if (!references.isEmpty()) {
            references = references + ",";
        }

        references = references + ref;
    }

    // Get bytes for PLF file
    byte[] plfFileBytes = null;
    ByteArrayOutputStream plfFileOutputStream = new ByteArrayOutputStream();
    VisicutModel.getInstance().savePlfToStream(MaterialManager.getInstance(), MappingManager.getInstance(),
            plfFileOutputStream);
    plfFileBytes = plfFileOutputStream.toByteArray();

    if (plfFileBytes == null) {
        throw new Exception("FabQR upload exception: Error saving PLF file");
    }

    // Begin uploading data
    String uploadUrl = getFabqrPrivateURL() + FABQR_API_UPLOAD_PROJECT;

    // Create HTTP client and cusomized config for timeouts
    CloseableHttpClient httpClient = HttpClients.createDefault();
    RequestConfig requestConfig = RequestConfig.custom().setSocketTimeout(FABQR_UPLOAD_TIMEOUT)
            .setConnectTimeout(FABQR_UPLOAD_TIMEOUT).setConnectionRequestTimeout(FABQR_UPLOAD_TIMEOUT).build();

    // Create HTTP Post request and entity builder
    HttpPost httpPost = new HttpPost(uploadUrl);
    httpPost.setConfig(requestConfig);
    MultipartEntityBuilder multipartEntityBuilder = MultipartEntityBuilder.create();

    // Insert file uploads
    multipartEntityBuilder.addBinaryBody("imageScheme", imageSchemeBytes, ContentType.APPLICATION_OCTET_STREAM,
            "imageScheme.png");
    multipartEntityBuilder.addBinaryBody("inputFile", plfFileBytes, ContentType.APPLICATION_OCTET_STREAM,
            "inputFile.plf");

    // Image real is allowed to be null, if it is not, send it
    if (imageRealBytes != null) {
        multipartEntityBuilder.addBinaryBody("imageReal", imageRealBytes, ContentType.APPLICATION_OCTET_STREAM,
                "imageReal.png");
    }

    // Prepare content type for text data, especially needed for correct UTF8 encoding
    ContentType contentType = ContentType.create("text/plain", Consts.UTF_8);

    // Insert text data
    multipartEntityBuilder.addTextBody("name", name, contentType);
    multipartEntityBuilder.addTextBody("email", email, contentType);
    multipartEntityBuilder.addTextBody("projectName", projectName, contentType);
    multipartEntityBuilder.addTextBody("licenseIndex", new Integer(licenseIndex).toString(), contentType);
    multipartEntityBuilder.addTextBody("tools", tools, contentType);
    multipartEntityBuilder.addTextBody("description", description, contentType);
    multipartEntityBuilder.addTextBody("location", location, contentType);
    multipartEntityBuilder.addTextBody("lasercutterName", lasercutterName, contentType);
    multipartEntityBuilder.addTextBody("lasercutterMaterial", lasercutterMaterial, contentType);
    multipartEntityBuilder.addTextBody("references", references, contentType);

    // Assign entity to this post request
    HttpEntity httpEntity = multipartEntityBuilder.build();
    httpPost.setEntity(httpEntity);

    // Set authentication information
    String encodedCredentials = Helper.getEncodedCredentials(FabQRFunctions.getFabqrPrivateUser(),
            FabQRFunctions.getFabqrPrivatePassword());
    if (!encodedCredentials.isEmpty()) {
        httpPost.addHeader("Authorization", "Basic " + encodedCredentials);
    }

    // Send request
    CloseableHttpResponse res = httpClient.execute(httpPost);

    // React to possible server side errors
    if (res.getStatusLine() == null || res.getStatusLine().getStatusCode() != HttpStatus.SC_OK) {
        throw new Exception("FabQR upload exception: Server sent wrong HTTP status code: "
                + new Integer(res.getStatusLine().getStatusCode()).toString());
    }

    // Close everything correctly
    res.close();
    httpClient.close();
}

From source file:ste.web.http.velocity.BugFreeVelocityHandler.java

@Test
public void setContentTypeIfNotSetAlready() throws Exception {
    ////from   w  ww .j a v  a  2s.c  o  m
    // content-type not set yet
    //
    context.setAttribute(ATTR_VIEW, TEST_VIEW1);
    handler.handle(request, response, context);
    then(response.getStatusLine().getStatusCode()).isEqualTo(HttpStatus.SC_OK);
    then(response.getEntity().getContentType().getValue()).isEqualTo(mime(ContentType.TEXT_HTML));

    //
    // content-type already set
    //
    ((BasicHttpEntity) response.getEntity()).setContentType(mime(ContentType.APPLICATION_OCTET_STREAM));
    handler.handle(request, response, context);
    then(response.getStatusLine().getStatusCode()).isEqualTo(HttpStatus.SC_OK);
    then(response.getEntity().getContentType().getValue())
            .isEqualTo(mime(ContentType.APPLICATION_OCTET_STREAM));
}

From source file:com.intuit.karate.http.apache.ApacheHttpClient.java

@Override
protected HttpEntity getEntity(List<MultiPartItem> items, String mediaType) {
    boolean hasNullName = false;
    for (MultiPartItem item : items) {
        if (item.getName() == null) {
            hasNullName = true;/*from   w w w  . ja va 2 s . c  om*/
            break;
        }
    }
    if (hasNullName) { // multipart/related
        String boundary = createBoundary();
        String text = getAsStringEntity(items, boundary);
        ContentType ct = ContentType.create(mediaType)
                .withParameters(new BasicNameValuePair("boundary", boundary));
        return new StringEntity(text, ct);
    } else {
        MultipartEntityBuilder builder = MultipartEntityBuilder.create()
                .setContentType(ContentType.create(mediaType));
        for (MultiPartItem item : items) {
            if (item.getValue() == null || item.getValue().isNull()) {
                logger.warn("ignoring null multipart value for key: {}", item.getName());
                continue;
            }
            String name = item.getName();
            ScriptValue sv = item.getValue();
            if (name == null) {
                // builder.addPart(bodyPart);
            } else {
                FormBodyPartBuilder formBuilder = FormBodyPartBuilder.create().setName(name);
                ContentBody contentBody;
                switch (sv.getType()) {
                case INPUT_STREAM:
                    InputStream is = (InputStream) sv.getValue();
                    contentBody = new InputStreamBody(is, ContentType.APPLICATION_OCTET_STREAM, name);
                    break;
                case XML:
                    contentBody = new StringBody(sv.getAsString(), ContentType.APPLICATION_XML);
                    break;
                case JSON:
                    contentBody = new StringBody(sv.getAsString(), ContentType.APPLICATION_JSON);
                    break;
                default:
                    contentBody = new StringBody(sv.getAsString(), ContentType.TEXT_PLAIN);
                }
                formBuilder = formBuilder.setBody(contentBody);
                builder = builder.addPart(formBuilder.build());
            }
        }
        return builder.build();
    }
}

From source file:com.joyent.manta.client.multipart.ServerSideMultipartManagerTest.java

public void canCreateMpuRequestBodyJsonWithHeaders() throws IOException {
    final String path = "/user/stor/object";
    final MantaHttpHeaders headers = new MantaHttpHeaders();

    headers.setDurabilityLevel(5);/*from   w  w  w  . j a v  a2  s . c  o m*/
    headers.setContentLength(423534L);
    headers.setContentMD5("e59ff97941044f85df5297e1c302d260");
    headers.setContentType(ContentType.APPLICATION_OCTET_STREAM.toString());
    final Set<String> roles = new HashSet<>();
    roles.add("manta");
    roles.add("role2");
    headers.setRoles(roles);

    final byte[] json = ServerSideMultipartManager.createMpuRequestBody(path, null, headers);

    ObjectNode jsonObject = mapper.readValue(json, ObjectNode.class);

    try {
        Assert.assertEquals(jsonObject.get("objectPath").textValue(), path);
        ObjectNode jsonHeaders = (ObjectNode) jsonObject.get("headers");

        Assert.assertEquals(jsonHeaders.get(MantaHttpHeaders.HTTP_DURABILITY_LEVEL.toLowerCase()).asInt(),
                headers.getDurabilityLevel().intValue());
        Assert.assertEquals(jsonHeaders.get(HttpHeaders.CONTENT_LENGTH.toLowerCase()).asLong(),
                headers.getContentLength().longValue());
        Assert.assertEquals(jsonHeaders.get(HttpHeaders.CONTENT_MD5.toLowerCase()).textValue(),
                headers.getContentMD5());
        Assert.assertEquals(jsonHeaders.get(MantaHttpHeaders.HTTP_ROLE_TAG.toLowerCase()).textValue(),
                headers.getFirstHeaderStringValue(MantaHttpHeaders.HTTP_ROLE_TAG.toLowerCase()));
        Assert.assertEquals(jsonHeaders.get(HttpHeaders.CONTENT_TYPE.toLowerCase()).textValue(),
                "application/octet-stream");
    } catch (AssertionError e) {
        System.err.println(new String(json, StandardCharsets.UTF_8));
        throw e;
    }
}

From source file:org.wso2.carbon.ml.integration.common.utils.MLHttpClient.java

/**
 * Upload a sample datatset from resources
 * /*from w w  w . j a  v a 2 s. c  o  m*/
 * @param datasetName   Name for the dataset
 * @param version       Version for the dataset
 * @param resourcePath  Relative path the CSV file in resources
 * @return              Response from the backend
 * @throws              MLHttpClientException 
 */
public CloseableHttpResponse uploadDatasetFromCSV(String datasetName, String version, String resourcePath)
        throws MLHttpClientException {
    CloseableHttpClient httpClient = HttpClients.createDefault();
    try {
        HttpPost httpPost = new HttpPost(getServerUrlHttps() + "/api/datasets/");
        httpPost.setHeader(MLIntegrationTestConstants.AUTHORIZATION_HEADER, getBasicAuthKey());

        MultipartEntityBuilder multipartEntityBuilder = MultipartEntityBuilder.create();
        multipartEntityBuilder.addPart("description",
                new StringBody("Sample dataset for Testing", ContentType.TEXT_PLAIN));
        multipartEntityBuilder.addPart("sourceType", new StringBody("file", ContentType.TEXT_PLAIN));
        multipartEntityBuilder.addPart("destination", new StringBody("file", ContentType.TEXT_PLAIN));
        multipartEntityBuilder.addPart("dataFormat", new StringBody("CSV", ContentType.TEXT_PLAIN));
        multipartEntityBuilder.addPart("containsHeader", new StringBody("true", ContentType.TEXT_PLAIN));

        if (datasetName != null) {
            multipartEntityBuilder.addPart("datasetName", new StringBody(datasetName, ContentType.TEXT_PLAIN));
        }
        if (version != null) {
            multipartEntityBuilder.addPart("version", new StringBody(version, ContentType.TEXT_PLAIN));
        }
        if (resourcePath != null) {
            File file = new File(getResourceAbsolutePath(resourcePath));
            multipartEntityBuilder.addBinaryBody("file", file, ContentType.APPLICATION_OCTET_STREAM,
                    "IndiansDiabetes.csv");
        }
        httpPost.setEntity(multipartEntityBuilder.build());
        return httpClient.execute(httpPost);
    } catch (Exception e) {
        throw new MLHttpClientException("Failed to upload dataset from csv " + resourcePath, e);
    }
}

From source file:com.nridge.ds.solr.SolrConfigSet.java

/**
 * Uploads the Solr config set ZIP file into the search cluster.
 *
 * @see <a href="http://lucene.apache.org/solr/guide/7_6/configsets-api.html">Solr ConfigSets API</a>
 * @see <a href="https://www.baeldung.com/httpclient-post-http-request">Upload Binary File with HttpClient 4</a>
 *
 * @param aPathFileName Path file name of ZIP containing the configuration set.
 * @param aConfigSetName Config set name.
 *
 * @throws DSException Solr Data Source exception.
 *///  w w w  .ja v a2 s  .co m
public void uploadZipFile(String aPathFileName, String aConfigSetName) throws DSException {
    Logger appLogger = mAppMgr.getLogger(this, "uploadZipFile");

    appLogger.trace(mAppMgr.LOGMSG_TRACE_ENTER);

    initialize();

    String baseSolrURL = mSolrDS.getBaseURL(false);
    String solrURI = String.format("%s/admin/configs?action=UPLOAD&name=%s", baseSolrURL, aConfigSetName);

    File pathFile = new File(aPathFileName);
    CloseableHttpResponse httpResponse = null;
    HttpPost httpPost = new HttpPost(solrURI);
    MultipartEntityBuilder multipartEntityBuilder = MultipartEntityBuilder.create();
    multipartEntityBuilder.addBinaryBody("file", pathFile, ContentType.APPLICATION_OCTET_STREAM, "file.zip");
    HttpEntity httpEntity = multipartEntityBuilder.build();
    httpPost.setEntity(httpEntity);
    CloseableHttpClient httpClient = HttpClients.createDefault();
    try {
        httpResponse = httpClient.execute(httpPost);
        StatusLine statusLine = httpResponse.getStatusLine();
        int statusCode = statusLine.getStatusCode();
        String msgStr = String.format("%s [%d]: %s", solrURI, statusCode, statusLine);
        appLogger.debug(msgStr);
        if (statusCode == HttpStatus.SC_OK) {
            httpEntity = httpResponse.getEntity();
            EntityUtils.consume(httpEntity);
        } else {
            msgStr = String.format("%s [%d]: %s", solrURI, statusCode, statusLine);
            appLogger.error(msgStr);
            throw new DSException(msgStr);
        }
    } catch (IOException e) {
        String msgStr = String.format("%s: %s", solrURI, e.getMessage());
        appLogger.error(msgStr, e);
        throw new DSException(msgStr);
    } finally {
        if (httpResponse != null)
            IO.closeQuietly(httpResponse);
    }

    appLogger.trace(mAppMgr.LOGMSG_TRACE_DEPART);
}

From source file:de.elomagic.carafile.client.CaraFileClient.java

/**
 * Uploads a file (Multi chunk upload).// w ww . j  a  v a  2s.c  o  m
 * <p/>
 * Multi chunk upload means that the file will be devived in one or more chunks and each chunk can be downloaded to a different peer.
 *
 * @param path Must be a file and not a directory. File will not be deleted
 * @param filename Name of the file. If null then name of the parameter path will be used
 * @return Returns the {@link MetaData} of the uploaded stream
 * @throws IOException Thrown when unable to call REST services
 * @throws java.security.GeneralSecurityException Thrown when unable to determine SHA-1 of the file
 * @see CaraFileClient#uploadFile(java.net.URI, java.io.InputStream, java.lang.String, long)
 */
public MetaData uploadFile(final Path path, final String filename)
        throws IOException, GeneralSecurityException {
    if (registryURI == null) {
        throw new IllegalArgumentException("Parameter 'registryURI' must not be null!");
    }

    if (path == null) {
        throw new IllegalArgumentException("Parameter 'path' must not be null!");
    }

    if (Files.notExists(path)) {
        throw new FileNotFoundException("File \"" + path + "\" doesn't exists!");
    }

    if (Files.isDirectory(path)) {
        throw new IOException("Parameter 'path' is not a file!");
    }

    String fn = filename == null ? path.getFileName().toString() : filename;

    MetaData md = CaraFileUtils.createMetaData(path, fn);
    md.setRegistryURI(registryURI);

    String json = JsonUtil.write(md);

    LOG.debug("Register " + md.getId() + " file at " + registryURI.toString());
    URI uri = CaraFileUtils.buildURI(registryURI, "registry", "register");
    HttpResponse response = executeRequest(Request.Post(uri).bodyString(json, ContentType.APPLICATION_JSON))
            .returnResponse();

    if (response.getStatusLine().getStatusCode() != HttpStatus.SC_OK) {
        throw new IOException("Unable to register file. " + response.getStatusLine().getReasonPhrase());
    }

    Set<PeerData> peerDataSet = downloadPeerSet();

    byte[] buffer = new byte[md.getChunkSize()];
    try (InputStream in = Files.newInputStream(path, StandardOpenOption.READ);
            BufferedInputStream bis = new BufferedInputStream(in, md.getChunkSize())) {
        int bytesRead;
        int chunkIndex = 0;
        while ((bytesRead = bis.read(buffer)) > 0) {
            String chunkId = md.getChunk(chunkIndex).getId();

            URI peerURI = peerSelector.getURI(peerDataSet, chunkIndex);
            URI seedChunkUri = CaraFileUtils.buildURI(peerURI, "peer", "seedChunk", chunkId);

            LOG.debug("Uploading chunk " + chunkId + " to peer " + seedChunkUri.toString() + ";Index="
                    + chunkIndex + ";Length=" + bytesRead);
            response = executeRequest(Request.Post(seedChunkUri).bodyStream(
                    new ByteArrayInputStream(buffer, 0, bytesRead), ContentType.APPLICATION_OCTET_STREAM))
                            .returnResponse();

            if (response.getStatusLine().getStatusCode() != HttpStatus.SC_OK) {
                throw new IOException("Unable to upload file. " + response.getStatusLine().getStatusCode() + " "
                        + response.getStatusLine().getReasonPhrase());
            }

            chunkIndex++;
        }
    }

    return md;
}

From source file:org.mule.module.http.functional.listener.HttpListenerAttachmentsTestCase.java

private HttpEntity getMultipartEntity(boolean withFile) {
    MultipartEntityBuilder builder = MultipartEntityBuilder.create();
    builder.addTextBody(TEXT_BODY_FIELD_NAME, TEXT_BODY_FIELD_VALUE, ContentType.TEXT_PLAIN);
    if (withFile) {
        builder.addBinaryBody(FILE_BODY_FIELD_NAME, FILE_BODY_FIELD_VALUE.getBytes(),
                ContentType.APPLICATION_OCTET_STREAM, FIELD_BDOY_FILE_NAME);
    }//from ww  w. j  a  va 2s  . c o m
    return builder.build();
}

From source file:com.ibm.ws.lars.rest.PermissionTest.java

/**
 * POST /assets/{assetId}/attachments Content-type: application/json
 *
 * Allowed for ADMIN// w  w  w. j  a  v  a  2  s. c o m
 *
 */
@Test
public void testPostAttachmentWithContent()
        throws ClientProtocolException, InvalidJsonAssetException, IOException {
    byte[] content = "I am the content.\nThere is not much to me.\n".getBytes(StandardCharsets.UTF_8);
    String name = "theAttachment";

    if (role.isAdmin()) {
        userContext.doPostAttachmentWithContent(createdAsset.get_id(), name, attachment, content,
                ContentType.APPLICATION_OCTET_STREAM);
    } else {
        userContext.doPostBadAttachmentWithContent(createdAsset.get_id(), "I am the attachment!", attachment,
                content, ContentType.APPLICATION_OCTET_STREAM, RC_REJECT, null);
    }
}