List of usage examples for org.apache.http.entity ContentType APPLICATION_OCTET_STREAM
ContentType APPLICATION_OCTET_STREAM
To view the source code for org.apache.http.entity ContentType APPLICATION_OCTET_STREAM.
Click Source Link
From source file:com.threatconnect.sdk.conn.HttpRequestExecutor.java
@Override public String executeUploadByteStream(String path, File file) throws IOException { if (this.conn.getConfig() == null) { throw new IllegalStateException("Can't execute HTTP request when configuration is undefined."); }// w w w . j a v a2s . c o m String fullPath = this.conn.getConfig().getTcApiUrl() + path.replace("/api/", "/"); logger.trace("Calling POST: " + fullPath); HttpPost httpBase = new HttpPost(fullPath); httpBase.setEntity(new FileEntity(file)); String headerPath = httpBase.getURI().getRawPath() + "?" + httpBase.getURI().getRawQuery(); ConnectionUtil.applyHeaders(this.conn.getConfig(), httpBase, httpBase.getMethod(), headerPath, ContentType.APPLICATION_OCTET_STREAM.toString()); logger.trace("Request: " + httpBase.getRequestLine()); CloseableHttpResponse response = this.conn.getApiClient().execute(httpBase); String result = null; logger.trace(response.getStatusLine().toString()); HttpEntity entity = response.getEntity(); if (entity != null) { try { result = EntityUtils.toString(entity, "iso-8859-1"); logger.trace("Result:" + result); EntityUtils.consume(entity); } finally { response.close(); } } return result; }
From source file:guru.nidi.ramltester.ServletRamlMessageTest.java
@Test public void multipartForm() throws Exception { final HttpPost post = new HttpPost(url("test/more")); final HttpEntity entity = MultipartEntityBuilder.create() .addBinaryBody("binary", new byte[] { 65, 66, 67 }, ContentType.APPLICATION_OCTET_STREAM, "filename") .addTextBody("param", "value").addTextBody("param", "v2").addTextBody("p2", "+$% ").build(); post.setEntity(entity);// w w w . ja v a 2 s . c o m execute(post, new MessageTester() { @Override public void test(HttpServletRequest servletRequest, HttpServletResponse servletResponse, RamlRequest ramlRequest, RamlResponse ramlResponse) throws IOException { final Values values = new Values().addValue("binary", new FileValue()).addValue("param", "value") .addValue("param", "v2").addValue("p2", "+$% "); assertEquals(values, ramlRequest.getFormValues()); } }); }
From source file:org.eclipse.vorto.repository.RestModelRepository.java
@Override public UploadResult upload(String name, byte[] model) { Objects.requireNonNull(model, "Model should not be null."); Objects.requireNonNull(name, "Name should not be null."); try {//from w w w. j av a 2 s . com MultipartEntityBuilder builder = MultipartEntityBuilder.create(); builder.addBinaryBody(FILE_PARAMETER_NAME, model, ContentType.APPLICATION_OCTET_STREAM, name); HttpEntity fileToUpload = builder.build(); UploadResultView uploadResult = httpClient.executePost("secure", fileToUpload, uploadResponseConverter); return uploadResultConverter.apply(uploadResult); } catch (Exception e) { throw new CheckInModelException("Error in uploading file to remote repository", e); } }
From source file:com.joyent.manta.client.crypto.AesCtrCipherDetailsTest.java
protected void canRandomlyReadPlaintextPositionFromCiphertext(final SecretKey secretKey, final SupportedCipherDetails cipherDetails) throws IOException, GeneralSecurityException { String text = "A SERGEANT OF THE LAW, wary and wise, " + "That often had y-been at the Parvis, <26> " + "There was also, full rich of excellence. " + "Discreet he was, and of great reverence: " + "He seemed such, his wordes were so wise, " + "Justice he was full often in assize, " + "By patent, and by plein* commission; " + "For his science, and for his high renown, " + "Of fees and robes had he many one. " + "So great a purchaser was nowhere none. " + "All was fee simple to him, in effect " + "His purchasing might not be in suspect* " + "Nowhere so busy a man as he there was " + "And yet he seemed busier than he was " + "In termes had he case' and doomes* all " + "That from the time of King Will. were fall. " + "Thereto he could indite, and make a thing " + "There coulde no wight *pinch at* his writing. " + "And every statute coud* he plain by rote " + "He rode but homely in a medley* coat, " + "Girt with a seint* of silk, with barres small; " + "Of his array tell I no longer tale."; byte[] plaintext = text.getBytes(StandardCharsets.US_ASCII); ContentType contentType = ContentType.APPLICATION_OCTET_STREAM; ExposedByteArrayEntity entity = new ExposedByteArrayEntity(plaintext, contentType); EncryptingEntity encryptingEntity = new EncryptingEntity(secretKey, cipherDetails, entity); final byte[] ciphertext; final byte[] iv = encryptingEntity.getCipher().getIV(); try (ByteArrayOutputStream out = new ByteArrayOutputStream()) { encryptingEntity.writeTo(out);//from ww w . j a v a 2s .c o m ciphertext = Arrays.copyOf(out.toByteArray(), out.toByteArray().length - cipherDetails.getAuthenticationTagOrHmacLengthInBytes()); } for (long startPlaintextRange = 0; startPlaintextRange < plaintext.length - 1; startPlaintextRange++) { for (long endPlaintextRange = startPlaintextRange; endPlaintextRange < plaintext.length; endPlaintextRange++) { byte[] adjustedPlaintext = Arrays.copyOfRange(plaintext, (int) startPlaintextRange, (int) endPlaintextRange + 1); ByteRangeConversion ranges = cipherDetails.translateByteRange(startPlaintextRange, endPlaintextRange); long startCipherTextRange = ranges.getCiphertextStartPositionInclusive(); long endCipherTextRange = ranges.getCiphertextEndPositionInclusive(); long adjustedPlaintextLength = ranges.getLengthOfPlaintextIncludingSkipBytes(); Cipher decryptor = cipherDetails.getCipher(); decryptor.init(Cipher.DECRYPT_MODE, secretKey, cipherDetails.getEncryptionParameterSpec(iv)); long adjustedPlaintextRange = cipherDetails.updateCipherToPosition(decryptor, startPlaintextRange); byte[] adjustedCipherText = Arrays.copyOfRange(ciphertext, (int) startCipherTextRange, (int) Math.min(ciphertext.length, endCipherTextRange + 1)); byte[] out = decryptor.doFinal(adjustedCipherText); byte[] decrypted = Arrays.copyOfRange(out, (int) adjustedPlaintextRange, (int) Math.min(out.length, adjustedPlaintextLength)); String decryptedText = new String(decrypted, StandardCharsets.UTF_8); String adjustedText = new String(adjustedPlaintext, StandardCharsets.UTF_8); Assert.assertEquals(adjustedText, decryptedText, "Random read output from ciphertext doesn't match expectation " + "[cipher=" + cipherDetails.getCipherId() + "]"); } } }
From source file:com.spectralogic.ds3client.commands.GetObjectRequest.java
@Override public String getContentType() { return ContentType.APPLICATION_OCTET_STREAM.toString(); }
From source file:de.elomagic.carafile.client.CaraFileClient.java
/** * Uploads data via an {@link InputStream} (Single chunk upload). * <p/>//from w w w . ja v a 2 s .co m * Single chunk upload means that the complete file will be upload in one step. * * @param in The input stream. It's not recommended to use a buffered stream. * @param filename Name of the file * @param contentLength Length of the content in bytes * @return Returns the {@link MetaData} of the uploaded stream * @throws IOException Thrown when unable to call REST services * @see CaraFileClient#uploadFile(java.net.URI, java.nio.file.Path, java.lang.String) */ public MetaData uploadFile(final InputStream in, final String filename, final long contentLength) throws IOException { if (registryURI == null) { throw new IllegalArgumentException("Parameter 'registryURI' must not be null!"); } if (in == null) { throw new IllegalArgumentException("Parameter 'in' must not be null!"); } URI peerURI = peerSelector.getURI(downloadPeerSet(), -1); if (peerURI == null) { throw new IOException("No peer for upload available"); } URI uri = CaraFileUtils.buildURI(peerURI, "peer", "seedFile", filename); MessageDigest messageDigest = DigestUtils.getSha1Digest(); try (BufferedInputStream bis = new BufferedInputStream(in); DigestInputStream dis = new DigestInputStream(bis, messageDigest)) { HttpResponse response = executeRequest( Request.Post(uri).bodyStream(dis, ContentType.APPLICATION_OCTET_STREAM)).returnResponse(); int statusCode = response.getStatusLine().getStatusCode(); if (statusCode != HttpStatus.SC_OK) { throw new HttpResponseException(statusCode, "Unable to upload file: " + response.getStatusLine().getReasonPhrase()); } MetaData md = getMetaDataFromResponse(response); if (!Hex.encodeHexString(messageDigest.digest()).equals(md.getId())) { throw new IOException("Peer response invalid SHA1 of file"); } return md; } }
From source file:com.frochr123.periodictasks.RefreshProjectorThread.java
public void updateProjectorImage() { if (!updateInProgress && !shutdownThreadRunning) { updateInProgress = true;/* w w w .ja v a2 s.c o m*/ new Thread() { @Override public void run() { try { if (VisicutModel.getInstance() != null && VisicutModel.getInstance().getSelectedLaserDevice() != null && VisicutModel.getInstance().getSelectedLaserDevice().getProjectorURL() != null && !VisicutModel.getInstance().getSelectedLaserDevice().getProjectorURL() .isEmpty()) { BufferedImage img = PreviewImageExport.generateImage(getProjectorWidth(), getProjectorHeight(), !isShutdownInProgress()); ByteArrayOutputStream outputStream = new ByteArrayOutputStream(); PreviewImageExport.writePngToOutputStream(outputStream, img); byte[] imagePostDataByte = outputStream.toByteArray(); // Create HTTP client and cusomized config for timeouts CloseableHttpClient httpClient = HttpClients.createDefault(); RequestConfig requestConfig = RequestConfig.custom() .setSocketTimeout(DEFAULT_PROJECTOR_TIMEOUT) .setConnectTimeout(DEFAULT_PROJECTOR_TIMEOUT) .setConnectionRequestTimeout(DEFAULT_PROJECTOR_TIMEOUT).build(); // Create HTTP Post request HttpPost httpPost = new HttpPost( VisicutModel.getInstance().getSelectedLaserDevice().getProjectorURL()); httpPost.setConfig(requestConfig); // Insert file upload MultipartEntityBuilder multipartEntityBuilder = MultipartEntityBuilder.create(); multipartEntityBuilder.addBinaryBody("data", imagePostDataByte, ContentType.APPLICATION_OCTET_STREAM, "data"); HttpEntity httpEntity = multipartEntityBuilder.build(); httpPost.setEntity(httpEntity); // Set authentication information String encodedCredentials = Helper.getEncodedCredentials( VisicutModel.getInstance().getSelectedLaserDevice().getURLUser(), VisicutModel.getInstance().getSelectedLaserDevice().getURLPassword()); 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("Server sent wrong HTTP status code: " + new Integer(res.getStatusLine().getStatusCode()).toString()); } // Close everything correctly res.close(); httpClient.close(); } } // This is caused internally in apache commons library for wrong authentication // Would need to add additional apache commons library file to get a correct exception back for that catch (NoClassDefFoundError error) { // Set flag for exception handling, sleep and message lastExceptionMessage = "Projector thread exception: Authentication error!"; } catch (Exception e) { // Set flag for exception handling, sleep and message lastExceptionMessage = "Projector thread exception (2): " + e.getMessage(); } updateInProgress = false; // Need to check if shutdown is set here first, otherwise these asynchronous calls // would always overwrite a call to shutdown in progress = true if (shutdownInProgress) { shutdownInProgress = false; } } }.start(); } }
From source file:org.hyperledger.fabric.sdkintegration.UpdateChannelIT.java
@Test public void setup() { try {//from w w w .j ava 2 s .co m //////////////////////////// // Setup client //Create instance of client. HFClient client = HFClient.createNewInstance(); client.setCryptoSuite(CryptoSuite.Factory.getCryptoSuite()); //////////////////////////// //Set up USERS //Persistence is not part of SDK. Sample file store is for demonstration purposes only! // MUST be replaced with more robust application implementation (Database, LDAP) File sampleStoreFile = new File(System.getProperty("java.io.tmpdir") + "/HFCSampletest.properties"); sampleStoreFile.deleteOnExit(); final SampleStore sampleStore = new SampleStore(sampleStoreFile); //SampleUser can be any implementation that implements org.hyperledger.fabric.sdk.User Interface //////////////////////////// // get users for all orgs for (SampleOrg sampleOrg : testSampleOrgs) { final String orgName = sampleOrg.getName(); sampleOrg.setPeerAdmin(sampleStore.getMember(orgName + "Admin", orgName)); } //////////////////////////// //Reconstruct and run the channels SampleOrg sampleOrg = testConfig.getIntegrationTestsSampleOrg("peerOrg1"); Channel fooChannel = reconstructChannel(FOO_CHANNEL_NAME, client, sampleOrg); // Getting foo channels current configuration bytes. byte[] channelConfigurationBytes = fooChannel.getChannelConfigurationBytes(); HttpClient httpclient = HttpClients.createDefault(); // HttpPost httppost = new HttpPost(CONFIGTXLATOR_LOCATION + "/protolator/decode/common.Config"); // httppost.setEntity(new ByteArrayEntity(channelConfigurationBytes)); String responseAsString = configTxlatorDecode(httpclient, channelConfigurationBytes); //responseAsString is JSON but use just string operations for this test. if (!responseAsString.contains(ORIGINAL_BATCH_TIMEOUT)) { fail(format("Did not find expected batch timeout '%s', in:%s", ORIGINAL_BATCH_TIMEOUT, responseAsString)); } //Now modify the batch timeout String updateString = responseAsString.replace(ORIGINAL_BATCH_TIMEOUT, UPDATED_BATCH_TIMEOUT); HttpPost httppost = new HttpPost(CONFIGTXLATOR_LOCATION + "/protolator/encode/common.Config"); httppost.setEntity(new StringEntity(updateString)); HttpResponse response = httpclient.execute(httppost); int statuscode = response.getStatusLine().getStatusCode(); out("Got %s status for encoding the new desired channel config bytes", statuscode); assertEquals(200, statuscode); byte[] newConfigBytes = EntityUtils.toByteArray(response.getEntity()); // Now send to configtxlator multipart form post with original config bytes, updated config bytes and channel name. httppost = new HttpPost(CONFIGTXLATOR_LOCATION + "/configtxlator/compute/update-from-configs"); HttpEntity multipartEntity = MultipartEntityBuilder.create() .setMode(HttpMultipartMode.BROWSER_COMPATIBLE) .addBinaryBody("original", channelConfigurationBytes, ContentType.APPLICATION_OCTET_STREAM, "originalFakeFilename") .addBinaryBody("updated", newConfigBytes, ContentType.APPLICATION_OCTET_STREAM, "updatedFakeFilename") .addBinaryBody("channel", fooChannel.getName().getBytes()).build(); httppost.setEntity(multipartEntity); response = httpclient.execute(httppost); statuscode = response.getStatusLine().getStatusCode(); out("Got %s status for updated config bytes needed for updateChannelConfiguration ", statuscode); assertEquals(200, statuscode); byte[] updateBytes = EntityUtils.toByteArray(response.getEntity()); UpdateChannelConfiguration updateChannelConfiguration = new UpdateChannelConfiguration(updateBytes); //To change the channel we need to sign with orderer admin certs which crypto gen stores: // private key: src/test/fixture/sdkintegration/e2e-2Orgs/channel/crypto-config/ordererOrganizations/example.com/users/Admin@example.com/msp/keystore/f1a9a940f57419a18a83a852884790d59b378281347dd3d4a88c2b820a0f70c9_sk //certificate: src/test/fixture/sdkintegration/e2e-2Orgs/channel/crypto-config/ordererOrganizations/example.com/users/Admin@example.com/msp/signcerts/Admin@example.com-cert.pem final String sampleOrgName = sampleOrg.getName(); final SampleUser ordererAdmin = sampleStore.getMember(sampleOrgName + "OrderAdmin", sampleOrgName, "OrdererMSP", Util.findFileSk(Paths.get("src/test/fixture/sdkintegration/e2e-2Orgs/" + testConfig.getFabricConfigGenVers() + "/crypto-config/ordererOrganizations/example.com/users/Admin@example.com/msp/keystore/") .toFile()), Paths.get("src/test/fixture/sdkintegration/e2e-2Orgs/" + testConfig.getFabricConfigGenVers() + "/crypto-config/ordererOrganizations/example.com/users/Admin@example.com/msp/signcerts/Admin@example.com-cert.pem") .toFile()); client.setUserContext(ordererAdmin); //Ok now do actual channel update. fooChannel.updateChannelConfiguration(updateChannelConfiguration, client.getUpdateChannelConfigurationSignature(updateChannelConfiguration, ordererAdmin)); Thread.sleep(3000); // give time for events to happen //Let's add some additional verification... client.setUserContext(sampleOrg.getPeerAdmin()); final byte[] modChannelBytes = fooChannel.getChannelConfigurationBytes(); responseAsString = configTxlatorDecode(httpclient, modChannelBytes); if (!responseAsString.contains(UPDATED_BATCH_TIMEOUT)) { //If it doesn't have the updated time out it failed. fail(format("Did not find updated expected batch timeout '%s', in:%s", UPDATED_BATCH_TIMEOUT, responseAsString)); } if (responseAsString.contains(ORIGINAL_BATCH_TIMEOUT)) { //Should not have been there anymore! fail(format("Found original batch timeout '%s', when it was not expected in:%s", ORIGINAL_BATCH_TIMEOUT, responseAsString)); } assertTrue(eventCountFilteredBlock > 0); // make sure we got blockevent that were tested.updateChannelConfiguration assertTrue(eventCountBlock > 0); // make sure we got blockevent that were tested. //Should be no anchor peers defined. assertFalse(responseAsString.matches(REGX_S_HOST_PEER_0_ORG_1_EXAMPLE_COM)); assertFalse(responseAsString.matches(REGX_S_ANCHOR_PEERS)); // Get config update for adding an anchor peer. Channel.AnchorPeersConfigUpdateResult configUpdateAnchorPeers = fooChannel.getConfigUpdateAnchorPeers( fooChannel.getPeers().iterator().next(), sampleOrg.getPeerAdmin(), Arrays.asList(PEER_0_ORG_1_EXAMPLE_COM_7051), null); assertNotNull(configUpdateAnchorPeers.getUpdateChannelConfiguration()); assertTrue(configUpdateAnchorPeers.getPeersAdded().contains(PEER_0_ORG_1_EXAMPLE_COM_7051)); //Now add anchor peer to channel configuration. fooChannel.updateChannelConfiguration(configUpdateAnchorPeers.getUpdateChannelConfiguration(), client.getUpdateChannelConfigurationSignature( configUpdateAnchorPeers.getUpdateChannelConfiguration(), sampleOrg.getPeerAdmin())); Thread.sleep(3000); // give time for events to happen // Getting foo channels current configuration bytes to check with configtxlator channelConfigurationBytes = fooChannel.getChannelConfigurationBytes(); responseAsString = configTxlatorDecode(httpclient, channelConfigurationBytes); // Check is anchor peer in config block? assertTrue(responseAsString.matches(REGX_S_HOST_PEER_0_ORG_1_EXAMPLE_COM)); assertTrue(responseAsString.matches(REGX_S_ANCHOR_PEERS)); //Should see what's there. configUpdateAnchorPeers = fooChannel.getConfigUpdateAnchorPeers(fooChannel.getPeers().iterator().next(), sampleOrg.getPeerAdmin(), null, null); assertNull(configUpdateAnchorPeers.getUpdateChannelConfiguration()); // not updating anything. assertTrue(configUpdateAnchorPeers.getCurrentPeers().contains(PEER_0_ORG_1_EXAMPLE_COM_7051)); // peer should be there. assertTrue(configUpdateAnchorPeers.getPeersRemoved().isEmpty()); // not removing any assertTrue(configUpdateAnchorPeers.getPeersAdded().isEmpty()); // not adding anything. assertTrue(configUpdateAnchorPeers.getUpdatedPeers().isEmpty()); // not updating anyting. //Now remove the anchor peer -- get the config update block. configUpdateAnchorPeers = fooChannel.getConfigUpdateAnchorPeers(fooChannel.getPeers().iterator().next(), sampleOrg.getPeerAdmin(), null, Arrays.asList(PEER_0_ORG_1_EXAMPLE_COM_7051)); assertNotNull(configUpdateAnchorPeers.getUpdateChannelConfiguration()); assertTrue(configUpdateAnchorPeers.getCurrentPeers().contains(PEER_0_ORG_1_EXAMPLE_COM_7051)); // peer should still be there. assertTrue(configUpdateAnchorPeers.getPeersRemoved().contains(PEER_0_ORG_1_EXAMPLE_COM_7051)); // peer to remove. assertTrue(configUpdateAnchorPeers.getPeersAdded().isEmpty()); // not adding anything. assertTrue(configUpdateAnchorPeers.getUpdatedPeers().isEmpty()); // no peers should be left. // Now do the actual update. fooChannel.updateChannelConfiguration(configUpdateAnchorPeers.getUpdateChannelConfiguration(), client.getUpdateChannelConfigurationSignature( configUpdateAnchorPeers.getUpdateChannelConfiguration(), sampleOrg.getPeerAdmin())); Thread.sleep(3000); // give time for events to happen // Getting foo channels current configuration bytes to check with configtxlator. channelConfigurationBytes = fooChannel.getChannelConfigurationBytes(); responseAsString = configTxlatorDecode(httpclient, channelConfigurationBytes); assertFalse(responseAsString.matches(REGX_S_HOST_PEER_0_ORG_1_EXAMPLE_COM)); // should be gone! assertTrue(responseAsString.matches(REGX_S_ANCHOR_PEERS)); //ODDLY we still want this even if it's empty! //Should see what's there. configUpdateAnchorPeers = fooChannel.getConfigUpdateAnchorPeers(fooChannel.getPeers().iterator().next(), sampleOrg.getPeerAdmin(), null, null); assertNull(configUpdateAnchorPeers.getUpdateChannelConfiguration()); // not updating anything. assertTrue(configUpdateAnchorPeers.getCurrentPeers().isEmpty()); // peer should be now gone. assertTrue(configUpdateAnchorPeers.getPeersRemoved().isEmpty()); // not removing any assertTrue(configUpdateAnchorPeers.getPeersAdded().isEmpty()); // not adding anything. assertTrue(configUpdateAnchorPeers.getUpdatedPeers().isEmpty()); // no peers should be left out("That's all folks!"); } catch (Exception e) { e.printStackTrace(); fail(e.getMessage()); } }
From source file:com.ibm.streamsx.topology.internal.context.AnalyticsServiceStreamsContext.java
private BigInteger postJob(CloseableHttpClient httpClient, JSONObject credentials, File bundle, JSONObject submitConfig) throws ClientProtocolException, IOException { String url = getSubmitURL(credentials, bundle); HttpPost postJobWithConfig = new HttpPost(url); postJobWithConfig.addHeader("accept", ContentType.APPLICATION_JSON.getMimeType()); FileBody bundleBody = new FileBody(bundle, ContentType.APPLICATION_OCTET_STREAM); StringBody configBody = new StringBody(submitConfig.serialize(), ContentType.APPLICATION_JSON); HttpEntity reqEntity = MultipartEntityBuilder.create().addPart("bin", bundleBody) .addPart("json", configBody).build(); postJobWithConfig.setEntity(reqEntity); JSONObject jsonResponse = getJsonResponse(httpClient, postJobWithConfig); Topology.STREAMS_LOGGER.info("Streaming Analytics Service submit job response:" + jsonResponse.serialize()); Object jobId = jsonResponse.get("jobId"); if (jobId == null) return BigInteger.valueOf(-1); return new BigInteger(jobId.toString()); }