List of usage examples for org.apache.http.entity ByteArrayEntity ByteArrayEntity
public ByteArrayEntity(byte[] bArr, ContentType contentType)
From source file:com.flipkart.bifrost.http.HttpCallCommand.java
private HttpUriRequest generateRequestObject() throws BifrostException { try {/*w w w. j a v a2 s.c o m*/ switch (requestType) { case HTTP_GET: return new HttpGet(url); case HTTP_POST: HttpPost post = new HttpPost(url); post.setEntity(new ByteArrayEntity(mapper.writeValueAsBytes(request), ContentType.create(contentType, CharsetUtils.lookup("utf-8")))); return post; case HTTP_PUT: HttpPut put = new HttpPut(url); put.setEntity(new ByteArrayEntity(mapper.writeValueAsBytes(request), ContentType.create(contentType, CharsetUtils.lookup("utf-8")))); return put; case HTTP_DELETE: return new HttpDelete(url); } } catch (JsonProcessingException e) { throw new BifrostException(BifrostException.ErrorCode.SERIALIZATION_ERROR, "Could not serialize request body"); } throw new BifrostException(BifrostException.ErrorCode.UNSUPPORTED_REQUEST_TYPE, String.format("Request type %s is not supported", requestType.name())); }
From source file:org.obm.push.spushnik.resources.FolderSyncScenarioTest.java
private HttpResponse folderSyncScenarioWithRequest(String baseURL, String certificate) throws Exception { InputStream requestInputStream = ClassLoader.getSystemClassLoader().getResourceAsStream(certificate); byte[] requestContent = ByteStreams.toByteArray(requestInputStream); HttpPost httpPost = new HttpPost(buildRequestUrl(baseURL)); httpPost.setEntity(new ByteArrayEntity(requestContent, ContentType.APPLICATION_JSON)); return httpClient.execute(httpPost); }
From source file:com.easarrive.datasource.redis.etago.write.impl.TestThumborConfigureDao.java
private void callBack(ThumborConfigure configure) { if (callURLQueue == null) { return;/*from ww w. j av a2s .co m*/ } byte[] jsonByteArray = null; try { jsonByteArray = JsonUtil.toBytes(configure); } catch (Exception e) { return; } String sign = DigestUtils.md5Hex(jsonByteArray); List<Header> headerList = new ArrayList<Header>(); headerList.add(new BasicHeader("VERSION", "1.0.0.0.1")); headerList.add(new BasicHeader("CHARSET", "UTF-8")); headerList.add(new BasicHeader("DATA_SIGN", sign)); ByteArrayEntity entity = new ByteArrayEntity(jsonByteArray, ContentType.APPLICATION_JSON); boolean run = true; while (run) { //? if (callURLQueue == null || callURLQueue.size() < 1) { run = false; continue; } //?? ThumborCallBackURL callBackURL = callURLQueue.poll(); if (callBackURL == null) { continue; } //?? String callURL = callBackURL.getUrl(); if (StringUtil.isEmpty(callURL)) { continue; } //? int callCount = callBackURL.getCallCount(); if (callCount >= this.maxCallCount) { continue; } //? long lastRequestTime = callBackURL.getLastRequestTime(); if (lastRequestTime + this.maxTimeInterval > System.currentTimeMillis()) { callURLQueue.add(callBackURL);// continue; } try { // HttpResponse httpResponse = HttpClientUtil.post(callURL, headerList, entity); int statusCode = httpResponse.getStatusLine().getStatusCode(); Header contentEncodingHeader = httpResponse.getEntity().getContentEncoding(); String charset = null; if (contentEncodingHeader == null) { charset = Constant.Charset.UTF8; } else { charset = contentEncodingHeader.getValue(); } if (StringUtil.isEmpty(charset)) { charset = Constant.Charset.UTF8; } String content = IOUtil.getString(httpResponse.getEntity().getContent(), charset); System.out.println(httpResponse.getStatusLine().getReasonPhrase()); System.out.println(httpResponse.getEntity().getContentType()); System.out.println(httpResponse.getEntity().getContentEncoding()); System.out.println(content); if (statusCode != 200) { // callBackURL.setCallCount(callCount + 1); callBackURL.setLastRequestTime(System.currentTimeMillis()); callURLQueue.add(callBackURL);//? } } catch (IOException e) { // callBackURL.setCallCount(callCount + 1); callBackURL.setLastRequestTime(System.currentTimeMillis()); callURLQueue.add(callBackURL);//? } } }
From source file:org.jenkinsci.test.acceptance.update_center.MockUpdateCenter.java
public void ensureRunning() { if (original != null) { return;//from w w w. ja v a 2s .c o m } // TODO this will likely not work on arbitrary controllers, so perhaps limit to the default WinstoneController Jenkins jenkins = injector.getInstance(Jenkins.class); List<String> sites = new UpdateCenter(jenkins).getJson("tree=sites[url]").findValuesAsText("url"); if (sites.size() != 1) { // TODO ideally it would rather delegate to all of them, but that implies deprecating CachedUpdateCenterMetadataLoader.url and using whatever site(s) Jenkins itself specifies LOGGER.log(Level.WARNING, "found an unexpected number of update sites: {0}", sites); return; } UpdateCenterMetadata ucm; try { ucm = ucmd.get(jenkins); } catch (IOException x) { LOGGER.log(Level.WARNING, "cannot load data for mock update center", x); return; } JSONObject all; try { all = new JSONObject(ucm.originalJSON); all.remove("signature"); JSONObject plugins = all.getJSONObject("plugins"); LOGGER.info(() -> "editing JSON with " + plugins.length() + " plugins to reflect " + ucm.plugins.size() + " possible overrides"); for (PluginMetadata meta : ucm.plugins.values()) { String name = meta.getName(); String version = meta.getVersion(); JSONObject plugin = plugins.optJSONObject(name); if (plugin == null) { LOGGER.log(Level.INFO, "adding plugin {0}", name); plugin = new JSONObject().accumulate("name", name); plugins.put(name, plugin); } plugin.put("url", name + ".hpi"); updating(plugin, "version", version); updating(plugin, "gav", meta.gav); updating(plugin, "requiredCore", meta.requiredCore().toString()); updating(plugin, "dependencies", new JSONArray(meta.getDependencies().stream().map(d -> { try { return new JSONObject().accumulate("name", d.name).accumulate("version", d.version) .accumulate("optional", d.optional); } catch (JSONException x) { throw new AssertionError(x); } }).collect(Collectors.toList()))); plugin.remove("sha1"); } } catch (JSONException x) { LOGGER.log(Level.WARNING, "cannot prepare mock update center", x); return; } HttpProcessor proc = HttpProcessorBuilder.create().add(new ResponseServer("MockUpdateCenter")) .add(new ResponseContent()).add(new RequestConnControl()).build(); UriHttpRequestHandlerMapper handlerMapper = new UriHttpRequestHandlerMapper(); String json = "updateCenter.post(\n" + all + "\n);"; handlerMapper.register("/update-center.json", (HttpRequest request, HttpResponse response, HttpContext context) -> { response.setStatusCode(HttpStatus.SC_OK); response.setEntity(new StringEntity(json, ContentType.APPLICATION_JSON)); }); handlerMapper.register("*.hpi", (HttpRequest request, HttpResponse response, HttpContext context) -> { String plugin = request.getRequestLine().getUri().replaceFirst("^/(.+)[.]hpi$", "$1"); PluginMetadata meta = ucm.plugins.get(plugin); if (meta == null) { LOGGER.log(Level.WARNING, "no such plugin {0}", plugin); response.setStatusCode(HttpStatus.SC_NOT_FOUND); return; } File local = meta.resolve(injector, meta.getVersion()); LOGGER.log(Level.INFO, "serving {0}", local); response.setStatusCode(HttpStatus.SC_OK); response.setEntity(new FileEntity(local)); }); handlerMapper.register("*", (HttpRequest request, HttpResponse response, HttpContext context) -> { String location = original.replace("/update-center.json", request.getRequestLine().getUri()); LOGGER.log(Level.INFO, "redirect to {0}", location); /* TODO for some reason DownloadService.loadJSONHTML does not seem to process the redirect, despite calling setInstanceFollowRedirects(true): response.setStatusCode(HttpStatus.SC_MOVED_TEMPORARILY); response.setHeader("Location", location); */ HttpURLConnection uc = (HttpURLConnection) new URL(location).openConnection(); uc.setInstanceFollowRedirects(true); // TODO consider caching these downloads locally like CachedUpdateCenterMetadataLoader does for the main update-center.json byte[] data = IOUtils.toByteArray(uc); String contentType = uc.getContentType(); response.setStatusCode(HttpStatus.SC_OK); response.setEntity(new ByteArrayEntity(data, ContentType.create(contentType))); }); server = ServerBootstrap.bootstrap(). // could setLocalAddress if using a JenkinsController that requires it setHttpProcessor(proc).setHandlerMapper(handlerMapper).setExceptionLogger(serverExceptionHandler()) .create(); try { server.start(); } catch (IOException x) { LOGGER.log(Level.WARNING, "cannot start mock update center", x); return; } original = sites.get(0); // TODO figure out how to deal with Docker-based controllers which would need to have an IP address for the host String override = "http://" + server.getInetAddress().getHostAddress() + ":" + server.getLocalPort() + "/update-center.json"; LOGGER.log(Level.INFO, "replacing update site {0} with {1}", new Object[] { original, override }); jenkins.runScript( "DownloadService.signatureCheck = false; Jenkins.instance.updateCenter.sites.replaceBy([new UpdateSite(UpdateCenter.ID_DEFAULT, '%s')])", override); }
From source file:nl.knaw.dans.easy.sword2examples.Common.java
public static CloseableHttpResponse sendChunk(DigestInputStream dis, int size, String method, URI uri, String filename, String mimeType, CloseableHttpClient http, boolean inProgress) throws Exception { // System.out.println(String.format("Sending chunk to %s, filename = %s, chunk size = %d, MIME-Type = %s, In-Progress = %s ... ", uri.toString(), // filename, size, mimeType, Boolean.toString(inProgress))); byte[] chunk = readChunk(dis, size); String md5 = new String(Hex.encodeHex(dis.getMessageDigest().digest())); HttpUriRequest request = RequestBuilder.create(method).setUri(uri).setConfig(RequestConfig.custom() /*//ww w . j ava 2 s .c o m * When using an HTTPS-connection EXPECT-CONTINUE must be enabled, otherwise buffer overflow may follow */ .setExpectContinueEnabled(true).build()) // .addHeader("Content-Disposition", String.format("attachment; filename=%s", filename)) // .addHeader("Content-MD5", md5) // .addHeader("Packaging", BAGIT_URI) // .addHeader("In-Progress", Boolean.toString(inProgress)) // .setEntity(new ByteArrayEntity(chunk, ContentType.create(mimeType))) // .build(); CloseableHttpResponse response = http.execute(request); // System.out.println("Response received."); return response; }
From source file:eu.peppol.outbound.transmission.As2MessageSender.java
SendResult send(InputStream inputStream, ParticipantId recipient, ParticipantId sender, PeppolDocumentTypeId peppolDocumentTypeId, SmpLookupManager.PeppolEndpointData peppolEndpointData, PeppolAs2SystemIdentifier as2SystemIdentifierOfSender) { if (peppolEndpointData.getCommonName() == null) { throw new IllegalArgumentException("No common name in EndPoint object. " + peppolEndpointData); }/*from www . ja va 2 s . c o m*/ X509Certificate ourCertificate = keystoreManager.getOurCertificate(); SMimeMessageFactory sMimeMessageFactory = new SMimeMessageFactory(keystoreManager.getOurPrivateKey(), ourCertificate); MimeMessage signedMimeMessage = null; Mic mic = null; try { MimeBodyPart mimeBodyPart = MimeMessageHelper.createMimeBodyPart(inputStream, new MimeType("application/xml")); mic = MimeMessageHelper.calculateMic(mimeBodyPart); log.debug("Outbound MIC is : " + mic.toString()); signedMimeMessage = sMimeMessageFactory.createSignedMimeMessage(mimeBodyPart); } catch (MimeTypeParseException e) { throw new IllegalStateException("Problems with MIME types: " + e.getMessage(), e); } String endpointAddress = peppolEndpointData.getUrl().toExternalForm(); HttpPost httpPost = new HttpPost(endpointAddress); ByteArrayOutputStream byteArrayOutputStream = new ByteArrayOutputStream(); try { signedMimeMessage.writeTo(byteArrayOutputStream); } catch (Exception e) { throw new IllegalStateException("Unable to stream S/MIME message into byte array output stream"); } httpPost.addHeader(As2Header.AS2_FROM.getHttpHeaderName(), as2SystemIdentifierOfSender.toString()); try { httpPost.setHeader(As2Header.AS2_TO.getHttpHeaderName(), PeppolAs2SystemIdentifier.valueOf(peppolEndpointData.getCommonName()).toString()); } catch (InvalidAs2SystemIdentifierException e) { throw new IllegalArgumentException( "Unable to create valid AS2 System Identifier for receiving end point: " + peppolEndpointData); } httpPost.addHeader(As2Header.DISPOSITION_NOTIFICATION_TO.getHttpHeaderName(), "not.in.use@difi.no"); httpPost.addHeader(As2Header.DISPOSITION_NOTIFICATION_OPTIONS.getHttpHeaderName(), As2DispositionNotificationOptions.getDefault().toString()); httpPost.addHeader(As2Header.AS2_VERSION.getHttpHeaderName(), As2Header.VERSION); httpPost.addHeader(As2Header.SUBJECT.getHttpHeaderName(), "AS2 message from OXALIS"); TransmissionId transmissionId = new TransmissionId(); httpPost.addHeader(As2Header.MESSAGE_ID.getHttpHeaderName(), transmissionId.toString()); httpPost.addHeader(As2Header.DATE.getHttpHeaderName(), As2DateUtil.format(new Date())); // Inserts the S/MIME message to be posted. // Make sure we pass the same content type as the SignedMimeMessage, it'll end up as content-type HTTP header try { String contentType = signedMimeMessage.getContentType(); ContentType ct = ContentType.create(contentType); httpPost.setEntity(new ByteArrayEntity(byteArrayOutputStream.toByteArray(), ct)); } catch (Exception ex) { throw new IllegalStateException("Unable to set request header content type : " + ex.getMessage()); } CloseableHttpResponse postResponse = null; // EXECUTE !!!! try { CloseableHttpClient httpClient = createCloseableHttpClient(); log.debug("Sending AS2 from " + sender + " to " + recipient + " at " + endpointAddress + " type " + peppolDocumentTypeId); postResponse = httpClient.execute(httpPost); } catch (HttpHostConnectException e) { throw new IllegalStateException("The Oxalis server does not seem to be running at " + endpointAddress); } catch (Exception e) { throw new IllegalStateException( "Unexpected error during execution of http POST to " + endpointAddress + ": " + e.getMessage(), e); } if (postResponse.getStatusLine().getStatusCode() != HttpStatus.SC_OK) { log.error("AS2 HTTP POST expected HTTP OK, but got : " + postResponse.getStatusLine().getStatusCode() + " from " + endpointAddress); throw handleFailedRequest(postResponse); } // handle normal HTTP OK response log.debug("AS2 transmission " + transmissionId + " to " + endpointAddress + " returned HTTP OK, verify MDN response"); MimeMessage mimeMessage = handleTheHttpResponse(transmissionId, mic, postResponse, peppolEndpointData); // Transforms the signed MDN into a generic a As2RemWithMdnTransmissionEvidenceImpl MdnMimeMessageInspector mdnMimeMessageInspector = new MdnMimeMessageInspector(mimeMessage); Map<String, String> mdnFields = mdnMimeMessageInspector.getMdnFields(); String messageDigestAsBase64 = mdnFields.get(MdnMimeMessageFactory.X_ORIGINAL_MESSAGE_DIGEST); if (messageDigestAsBase64 == null) { messageDigestAsBase64 = new String(Base64.getEncoder().encode("null".getBytes())); } String receptionTimeStampAsString = mdnFields.get(MdnMimeMessageFactory.X_PEPPOL_TIME_STAMP); Date receptionTimeStamp = null; if (receptionTimeStampAsString != null) { receptionTimeStamp = As2DateUtil.parseIso8601TimeStamp(receptionTimeStampAsString); } else { receptionTimeStamp = new Date(); } // Converts the Oxalis DocumentTypeIdentifier into the corresponding type for peppol-evidence DocumentTypeIdentifier documentTypeIdentifier = new DocumentTypeIdentifier(peppolDocumentTypeId.toString()); @NotNull As2RemWithMdnTransmissionEvidenceImpl evidence = as2TransmissionEvidenceFactory.createEvidence( EventCode.DELIVERY, TransmissionRole.C_2, mimeMessage, new ParticipantIdentifier(recipient.stringValue()), // peppol-evidence uses it's own types new ParticipantIdentifier(sender.stringValue()), // peppol-evidence uses it's own types documentTypeIdentifier, receptionTimeStamp, Base64.getDecoder().decode(messageDigestAsBase64), transmissionId); ByteArrayOutputStream evidenceBytes; try { evidenceBytes = new ByteArrayOutputStream(); IOUtils.copy(evidence.getInputStream(), evidenceBytes); } catch (IOException e) { throw new IllegalStateException( "Unable to transform transport evidence to byte array." + e.getMessage(), e); } return new SendResult(transmissionId, evidenceBytes.toByteArray()); }