List of usage examples for org.apache.http.entity ContentType create
private static ContentType create(HeaderElement headerElement)
From source file:com.telefonica.iot.tidoop.apiext.backends.ckan.CKANBackend.java
/** * Common method to perform HTTP requests using the CKAN API with payload. * @param method HTTP method//from w w w . j a v a2 s .c o m * @param url URL path to be added to the base URL * @param payload Request payload * @return CKANResponse associated to the request * @throws Exception */ public CKANResponse doCKANRequest(String method, String url, String payload) throws Exception { HttpRequestBase request = null; HttpResponse response = null; try { // do the post if (method.equals("GET")) { request = new HttpGet(url); } else if (method.equals("POST")) { HttpPost r = new HttpPost(url); // payload (optional) if (!payload.equals("")) { logger.debug("request payload: " + payload); r.setEntity(new StringEntity(payload, ContentType.create("application/json"))); } // if request = r; } else { throw new Exception("HTTP method not supported: " + method); } // if else // headers request.addHeader("Authorization", apiKey); // execute the request logger.debug("CKAN operation: " + request.toString()); } catch (Exception e) { throw e; } // try catch try { response = httpClientFactory.getHttpClient(ssl).execute(request); } catch (Exception e) { throw new Exception(e.getMessage()); } // try catch try { BufferedReader reader = new BufferedReader(new InputStreamReader(response.getEntity().getContent())); String res = ""; String line; while ((line = reader.readLine()) != null) { res += line; } // while request.releaseConnection(); long l = response.getEntity().getContentLength(); logger.debug("CKAN response (" + l + " bytes): " + response.getStatusLine().toString()); // get the JSON encapsulated in the response logger.debug("response payload: " + res); JSONParser j = new JSONParser(); JSONObject o = (JSONObject) j.parse(res); // return result return new CKANResponse(o, response.getStatusLine().getStatusCode()); } catch (IOException e) { throw e; } catch (IllegalStateException e) { throw e; } catch (ParseException e) { throw e; } // try catch }
From source file:org.elasticsearch.client.Request.java
static Request update(UpdateRequest updateRequest) throws IOException { String endpoint = endpoint(updateRequest.index(), updateRequest.type(), updateRequest.id(), "_update"); Params parameters = Params.builder(); parameters.withRouting(updateRequest.routing()); parameters.withParent(updateRequest.parent()); parameters.withTimeout(updateRequest.timeout()); parameters.withRefreshPolicy(updateRequest.getRefreshPolicy()); parameters.withWaitForActiveShards(updateRequest.waitForActiveShards()); parameters.withDocAsUpsert(updateRequest.docAsUpsert()); parameters.withFetchSourceContext(updateRequest.fetchSource()); parameters.withRetryOnConflict(updateRequest.retryOnConflict()); parameters.withVersion(updateRequest.version()); parameters.withVersionType(updateRequest.versionType()); // The Java API allows update requests with different content types // set for the partial document and the upsert document. This client // only accepts update requests that have the same content types set // for both doc and upsert. XContentType xContentType = null;//from ww w .j a va2 s. co m if (updateRequest.doc() != null) { xContentType = updateRequest.doc().getContentType(); } if (updateRequest.upsertRequest() != null) { XContentType upsertContentType = updateRequest.upsertRequest().getContentType(); if ((xContentType != null) && (xContentType != upsertContentType)) { throw new IllegalStateException("Update request cannot have different content types for doc [" + xContentType + "]" + " and upsert [" + upsertContentType + "] documents"); } else { xContentType = upsertContentType; } } if (xContentType == null) { xContentType = Requests.INDEX_CONTENT_TYPE; } BytesRef source = XContentHelper.toXContent(updateRequest, xContentType, false).toBytesRef(); HttpEntity entity = new ByteArrayEntity(source.bytes, source.offset, source.length, ContentType.create(xContentType.mediaType())); return new Request(HttpPost.METHOD_NAME, endpoint, parameters.getParams(), entity); }
From source file:org.apache.stanbol.workflow.jersey.writers.ContentItemWriter.java
@Override public void writeTo(ContentItem ci, Class<?> type, Type genericType, Annotation[] annotations, MediaType mediaType, MultivaluedMap<String, Object> httpHeaders, OutputStream entityStream) throws IOException, WebApplicationException { //(0) handle default dataType Map<String, Object> reqProp = ContentItemHelper.getRequestPropertiesContentPart(ci); boolean omitMetadata = isOmitMetadata(reqProp); if (!MULTIPART.isCompatible(mediaType)) { //two possible cases if (!omitMetadata) { // (1) just return the RDF data //(1.a) Backward support for default dataType if no Accept header is set StringBuilder ctb = new StringBuilder(); if (mediaType.isWildcardType() || TEXT_PLAIN_TYPE.isCompatible(mediaType) || APPLICATION_OCTET_STREAM_TYPE.isCompatible(mediaType)) { ctb.append(APPLICATION_LD_JSON); } else { ctb.append(mediaType.getType()).append('/').append(mediaType.getSubtype()); }/* w w w . ja v a 2s . c o m*/ ctb.append(";charset=").append(UTF8.name()); String contentType = ctb.toString(); httpHeaders.putSingle(HttpHeaders.CONTENT_TYPE, contentType); try { serializer.serialize(entityStream, ci.getMetadata(), contentType); } catch (UnsupportedSerializationFormatException e) { throw new WebApplicationException("The enhancement results " + "cannot be serialized in the requested media type: " + mediaType.toString(), Response.Status.NOT_ACCEPTABLE); } } else { // (2) return a single content part Entry<UriRef, Blob> contentPart = getBlob(ci, Collections.singleton(mediaType.toString())); if (contentPart == null) { //no alternate content with the requeste media type throw new WebApplicationException("The requested enhancement chain has not created an " + "version of the parsed content in the reuqest media type " + mediaType.toString(), Response.Status.UNSUPPORTED_MEDIA_TYPE); } else { //found -> stream the content to the client //NOTE: This assumes that the presence of a charset // implies reading/writing character streams String requestedCharset = mediaType.getParameters().get("charset"); String blobCharset = contentPart.getValue().getParameter().get("charset"); Charset readerCharset = blobCharset == null ? UTF8 : Charset.forName(blobCharset); Charset writerCharset = requestedCharset == null ? null : Charset.forName(requestedCharset); if (writerCharset != null && !writerCharset.equals(readerCharset)) { //we need to transcode Reader reader = new InputStreamReader(contentPart.getValue().getStream(), readerCharset); Writer writer = new OutputStreamWriter(entityStream, writerCharset); IOUtils.copy(reader, writer); IOUtils.closeQuietly(reader); } else { //no transcoding if (requestedCharset == null && blobCharset != null) { httpHeaders.putSingle(HttpHeaders.CONTENT_TYPE, mediaType.toString() + "; charset=" + blobCharset); } InputStream in = contentPart.getValue().getStream(); IOUtils.copy(in, entityStream); IOUtils.closeQuietly(in); } } } } else { // multipart mime requested! final String charsetName = mediaType.getParameters().get("charset"); final Charset charset = charsetName != null ? Charset.forName(charsetName) : UTF8; MediaType rdfFormat; String rdfFormatString = getRdfFormat(reqProp); if (rdfFormatString == null || rdfFormatString.isEmpty()) { rdfFormat = DEFAULT_RDF_FORMAT; } else { try { rdfFormat = MediaType.valueOf(rdfFormatString); if (rdfFormat.getParameters().get("charset") == null) { //use the charset of the default RDF format rdfFormat = new MediaType(rdfFormat.getType(), rdfFormat.getSubtype(), DEFAULT_RDF_FORMAT.getParameters()); } } catch (IllegalArgumentException e) { throw new WebApplicationException( "The specified RDF format '" + rdfFormatString + "' (used to serialize all RDF parts of " + "multipart MIME responses) is not a well formated MIME type", Response.Status.BAD_REQUEST); } } //(1) setting the correct header String contentType = String.format("%s/%s; charset=%s; boundary=%s", mediaType.getType(), mediaType.getSubtype(), charset.toString(), CONTENT_ITEM_BOUNDARY); httpHeaders.putSingle(HttpHeaders.CONTENT_TYPE, contentType); MultipartEntityBuilder entityBuilder = MultipartEntityBuilder.create(); entityBuilder.setBoundary(CONTENT_ITEM_BOUNDARY); //HttpMultipart entity = new HttpMultipart("from-data", charset ,CONTENT_ITEM_BOUNDARY); //(2) serialising the metadata if (!isOmitMetadata(reqProp)) { entityBuilder.addPart("metadata", new ClerezzaContentBody(ci.getUri().getUnicodeString(), ci.getMetadata(), rdfFormat)); // entity.addBodyPart(new FormBodyPart("metadata", new ClerezzaContentBody( // ci.getUri().getUnicodeString(), ci.getMetadata(), // rdfFormat))); } //(3) serialising the Content (Bloby) //(3.a) Filter based on parameter List<Entry<UriRef, Blob>> includedBlobs = filterBlobs(ci, reqProp); //(3.b) Serialise the filtered if (!includedBlobs.isEmpty()) { Map<String, ContentBody> contentParts = new LinkedHashMap<String, ContentBody>(); for (Entry<UriRef, Blob> entry : includedBlobs) { Blob blob = entry.getValue(); ContentType ct = ContentType.create(blob.getMimeType()); String cs = blob.getParameter().get("charset"); if (StringUtils.isNotBlank(cs)) { ct = ct.withCharset(cs); } contentParts.put(entry.getKey().getUnicodeString(), new InputStreamBody(blob.getStream(), ct)); } //add all the blobs entityBuilder.addPart("content", new MultipartContentBody(contentParts, CONTENT_PARTS_BOUNDERY, MULTIPART_ALTERNATE)); } //else no content to include Set<String> includeContentParts = getIncludedContentPartURIs(reqProp); if (includeContentParts != null) { //(4) serialise the Request Properties if (includeContentParts.isEmpty() || includeContentParts.contains(REQUEST_PROPERTIES_URI.getUnicodeString())) { JSONObject object; try { object = toJson(reqProp); } catch (JSONException e) { String message = "Unable to convert Request Properties " + "to JSON (values : " + reqProp + ")!"; log.error(message, e); throw new WebApplicationException(message, Response.Status.INTERNAL_SERVER_ERROR); } entityBuilder.addTextBody(REQUEST_PROPERTIES_URI.getUnicodeString(), object.toString(), ContentType.APPLICATION_JSON.withCharset(UTF8)); } //(5) additional RDF metadata stored in contentParts for (Entry<UriRef, TripleCollection> entry : getContentParts(ci, TripleCollection.class) .entrySet()) { if (includeContentParts.isEmpty() || includeContentParts.contains(entry.getKey())) { entityBuilder.addPart(entry.getKey().getUnicodeString(), new ClerezzaContentBody(null, //no file name entry.getValue(), rdfFormat)); } // else ignore this content part } } entityBuilder.build().writeTo(entityStream); } }
From source file:at.gv.egiz.pdfas.lib.pki.impl.OCSPClient.java
/** * Retrieves an OCSP response for a certain certificate ({@code eeCertificate}) of a certain CA * ({@code issuerCertificate}).// ww w . j a va 2 s . com * * @param issuerCertificate The issuer certificate (required; must not be {@code null}). * @param eeCertificate The end entity certificate (required; must not be {@code null}). * @return The OCSP response (never {@code null}) with guaranteed response status "successful" and with <strong>any * revocation state</strong>. * @throws IOException Thrown in case of error communicating with OCSP responder. * @throws OCSPClientException In case the client could not process the response (e.g. non-successful response * state like malformedRequest, internalError... or an unknown/unsupported response * type). * @throws IllegalArgumentException In case the provided {@code eeCertificate} does not provide an OCSP responder * url (use {@link Util#hasOcspResponder(X509Certificate)} in order to determine if * it is safe to call this method) or the provided certificates could not be used * for OCSP request creation. * @implNote This implementation just returns OCSP responses (<strong>of any revocation status</strong>) as they * were retrieved from the OCSP responder (provided the response status indicates a successful response) * without performing further checks like OCSP signature verification or OCSP responder certificate * validation. */ public OCSPResponse getOcspResponse(X509Certificate issuerCertificate, X509Certificate eeCertificate) throws IOException, OCSPClientException { Objects.requireNonNull(issuerCertificate, "Issuer certificate required... must not be null."); Objects.requireNonNull(eeCertificate, "End-entity certificate required... must not be null."); StopWatch sw = new StopWatch(); sw.start(); if (log.isDebugEnabled()) { log.debug("Retrieving OCSP revocation info for: {}", eeCertificate.getSubjectDN()); } else if (log.isInfoEnabled()) { log.info("Retrieving OCSP revocation info for certificate (SHA-1 fingerprint): {}", Hex.encodeHexString(eeCertificate.getFingerprintSHA())); } String ocspUrl = Util.getOcspUrl(eeCertificate); if (ocspUrl == null) { throw new IllegalArgumentException("The provided certificate does not feature an ocsp responder url."); } // create request byte[] ocspRequestEncoded; ReqCert reqCert; try { CertID certID = new CertID(AlgorithmID.sha1, issuerCertificate, eeCertificate); reqCert = new ReqCert(ReqCert.certID, certID); Request request = new Request(reqCert); OCSPRequest ocspRequest = new OCSPRequest(); ocspRequest.setRequestList(new Request[] { request }); ocspRequestEncoded = ocspRequest.getEncoded(); if (log.isTraceEnabled()) { log.trace("Creating OCSP request: {}", request); } } catch (NoSuchAlgorithmException e) { // should not occur actually throw new IllegalStateException("Required algorithm (SHA-1) not available.", e); } catch (CodingException e) { throw new IllegalArgumentException( "Unable to encode ocsp request with the provided issuer and end-entity certificates.", e); } // https://tools.ietf.org/html/rfc6960 // GET {url}/{url-encoding of base-64 encoding of the DER encoding of the OCSPRequest} String b64OcspRequest = org.apache.commons.codec.binary.Base64.encodeBase64String(ocspRequestEncoded); String urlEncodedB64OcspRequest = URLEncoder.encode(b64OcspRequest, "UTF-8"); HttpRequestBase request; if (httpCachingEnabled && urlEncodedB64OcspRequest.length() <= 255) { // spec proposes GET request URI ocspResponderUri; try { URIBuilder uriBuilder = new URIBuilder(ocspUrl); uriBuilder .setPath(StringUtils.appendIfMissing(uriBuilder.getPath(), "/") + urlEncodedB64OcspRequest); ocspResponderUri = uriBuilder.build(); } catch (URISyntaxException e) { // can only occur with eeCertificate containing invalid ocsp responder url throw new IllegalArgumentException( "Unable process OCSP responder uri of provided certificate: " + ocspUrl, e); } request = new HttpGet(ocspResponderUri); log.debug("Sending OCSP request using HTTP GET to: {}", ocspUrl); } else { // spec proposes POST request HttpPost httpPost = new HttpPost(ocspUrl); httpPost.setEntity( new ByteArrayEntity(ocspRequestEncoded, ContentType.create("application/ocsp-request"))); request = httpPost; log.debug("Sending OCSP request using HTTP POST to: {}", ocspUrl); } request.setConfig(requestConfig); try (CloseableHttpResponse httpResponse = httpClient.execute(request)) { StatusLine statusLine = httpResponse.getStatusLine(); log.debug("OCSP response HTTP status: {}", statusLine); if (statusLine.getStatusCode() != HttpStatus.SC_OK) { throw new IOException("OCSP responder did not report HTTP 200: " + statusLine); } HttpEntity responseEntity = httpResponse.getEntity(); OCSPResponse ocspResponse; try (InputStream in = responseEntity.getContent()) { ocspResponse = new OCSPResponse(in); } catch (UnknownResponseException e) { throw new OCSPClientException("Unknown (unsupported) OCSP response type: " + e.getResponseType(), e); } if (log.isTraceEnabled()) { log.trace("OCSP response: {}", ocspResponse); } log.debug("OCSP response status: {}", ocspResponse.getResponseStatusName()); if (ocspResponse.getResponseStatus() != OCSPResponse.successful) { throw new OCSPClientException("OCSP response status was not successful, got response status: " + ocspResponse.getResponseStatusName()); } // get the basic ocsp response (which is the only type currently supported, otherwise an // UnknownResponseException would have been thrown during parsing the response) BasicOCSPResponse basicOCSPResponse = (BasicOCSPResponse) ocspResponse.getResponse(); // for future improvement: verify ocsp response, responder certificate... SingleResponse singleResponse; try { log.trace("Looking for OCSP response specific for: {}", reqCert); singleResponse = basicOCSPResponse.getSingleResponse(reqCert); } catch (OCSPException e) { try { singleResponse = basicOCSPResponse.getSingleResponse(issuerCertificate, eeCertificate, null); } catch (OCSPException e1) { throw new OCSPClientException( "Unable to process received OCSP response for the provided certificate (SHA-1 fingerprint): " + Hex.encodeHexString(eeCertificate.getFingerprintSHA()), e1); } } if (log.isTraceEnabled()) { log.trace("OCSP respose for specific certificate: {}", singleResponse); } CertStatus certStatus = singleResponse.getCertStatus(); String formattedThisUpdate = DateFormatUtils.ISO_DATETIME_TIME_ZONE_FORMAT .format(singleResponse.getThisUpdate()); log.info("Certificate revocation state (@{}}: {}", formattedThisUpdate, certStatus); sw.stop(); log.debug("OCSP query took: {}ms", sw.getTime()); return ocspResponse; } // close httpResponse }
From source file:com.buffalokiwi.aerodrome.Aerodrome.java
private static void testUpload(final APIHttpClient client, final JetConfig config) { final JetAPIBulkProductUpload up = new JetAPIBulkProductUpload(client, config); List<ProductRec> products = new ArrayList<>(); products.add(getTestProduct());/*from w w w . j a v a 2s. co m*/ //..The local filename to write the bulk product data to final File file = new File("/home/john/jetproducttext.json.gz"); try (final BulkProductFileGenerator gen = new BulkProductFileGenerator(file)) { //..Write the product json to a gzip file for (final ProductRec pRec : products) { gen.writeLine(pRec); } } catch (IOException e) { fail("Failed to open output file", 0, e); } try { //..Get authorization to upload a file final BulkUploadAuthRec uploadToken = up.getUploadToken(); //..Sends the authorized gzip file to the url specified in the uploadToken response. up.sendAuthorizedFile(uploadToken.getUrl(), new PostFile(file, ContentType.create("application/x-gzip"), "gzip", uploadToken.getJetFileId())); //..If you want to add an additional file to an existing authorization token/processing batch on jet, create a new PostFile instance for the new file final PostFile pf = new PostFile(file, ContentType.DEFAULT_BINARY, "gzip", file.getName()); //..Post the request for a file addition to JsonObject addRes = up .sendPostUploadedFiles(uploadToken.getUrl(), pf.getFilename(), BulkUploadFileType.MERCHANT_SKUS) .getJsonObject(); //..Send the next file up to the batch up.sendAuthorizedFile(addRes.getString("url"), pf); //..Get some stats for an uploaded file up.getJetFileId(uploadToken.getJetFileId()); //..And get some stats for the other uploaded file. up.getJetFileId(addRes.getString("jet_file_id")); } catch (Exception e) { fail("Failed to bulk", 0, e); } try { //System.out.println( up.getUploadToken().getUrl()); } catch (Exception e) { fail("failed to do upload stuff", 0, e); } }
From source file:com.github.avarabyeu.restendpoint.http.HttpClientRestEndpoint.java
/** * Executes request command// w w w . j av a 2s.c o m * * @param command REST request representation * @return Future wrapper of REST response * @throws RestEndpointIOException In case of error * @see com.github.avarabyeu.wills.Will */ @Override public final <RQ, RS> Will<Response<RS>> executeRequest(RestCommand<RQ, RS> command) throws RestEndpointIOException { URI uri = spliceUrl(command.getUri()); HttpUriRequest rq; Serializer serializer; switch (command.getHttpMethod()) { case GET: rq = new HttpGet(uri); break; case POST: serializer = getSupportedSerializer(command.getRequest()); rq = new HttpPost(uri); ((HttpPost) rq).setEntity(new ByteArrayEntity(serializer.serialize(command.getRequest()), ContentType.create(serializer.getMimeType()))); break; case PUT: serializer = getSupportedSerializer(command.getRequest()); rq = new HttpPut(uri); ((HttpPut) rq).setEntity(new ByteArrayEntity(serializer.serialize(command.getRequest()), ContentType.create(serializer.getMimeType()))); break; case DELETE: rq = new HttpDelete(uri); break; case PATCH: serializer = getSupportedSerializer(command.getRequest()); rq = new HttpPatch(uri); ((HttpPatch) rq).setEntity(new ByteArrayEntity(serializer.serialize(command.getRequest()), ContentType.create(serializer.getMimeType()))); break; default: throw new IllegalArgumentException("Method '" + command.getHttpMethod() + "' is unsupported"); } return executeInternal(rq, new TypeConverterCallback<RS>(serializers, command.getResponseType())); }
From source file:org.votingsystem.util.HttpHelper.java
public ResponseVS sendFile(File file, ContentTypeVS contentTypeVS, String serverURL, String... headerNames) { log.info("sendFile - contentType: " + contentTypeVS + " - serverURL: " + serverURL); ResponseVS responseVS = null;//from w ww.ja v a2s . com HttpPost httpPost = null; ContentTypeVS responseContentType = null; CloseableHttpResponse response = null; try { httpPost = new HttpPost(serverURL); ContentType contentType = null; if (contentTypeVS != null) contentType = ContentType.create(contentTypeVS.getName()); FileEntity entity = new FileEntity(file, contentType); httpPost.setEntity(entity); response = httpClient.execute(httpPost); log.info("----------------------------------------"); log.info(response.getStatusLine().toString() + " - connManager stats: " + connManager.getTotalStats().toString()); log.info("----------------------------------------"); Header header = response.getFirstHeader("Content-Type"); if (header != null) responseContentType = ContentTypeVS.getByName(header.getValue()); byte[] responseBytes = EntityUtils.toByteArray(response.getEntity()); responseVS = new ResponseVS(response.getStatusLine().getStatusCode(), responseBytes, responseContentType); if (headerNames != null) { List<String> headerValues = new ArrayList<String>(); for (String headerName : headerNames) { org.apache.http.Header headerValue = response.getFirstHeader(headerName); headerValues.add(headerValue.getValue()); } responseVS.setData(headerValues); } } catch (Exception ex) { log.log(Level.SEVERE, ex.getMessage(), ex); responseVS = new ResponseVS(ResponseVS.SC_ERROR, ex.getMessage()); if (httpPost != null) httpPost.abort(); } finally { try { if (response != null) response.close(); } catch (Exception ex) { log.log(Level.SEVERE, ex.getMessage(), ex); } return responseVS; } }
From source file:com.smartsheet.api.internal.AbstractResources.java
/** * Create a resource using Smartsheet REST API. * * Exceptions:/*from w w w . ja va 2 s . c o m*/ * IllegalArgumentException : if any argument is null, or path is empty string * InvalidRequestException : if there is any problem with the REST API request * AuthorizationException : if there is any problem with the REST API authorization(access token) * ServiceUnavailableException : if the REST API service is not available (possibly due to rate limiting) * SmartsheetRestException : if there is any other REST API related error occurred during the operation * SmartsheetException : if there is any other error occurred during the operation * * @param <T> the generic type * @param path the relative path of the resource collections * @param objectClass the resource object class * @param object the object to create * @return the created resource * @throws SmartsheetException the smartsheet exception */ protected <T> T createResourceWithAttachment(String path, Class<T> objectClass, T object, String partName, InputStream inputStream, String contentType, String attachmentName) throws SmartsheetException { Util.throwIfNull(path, object); Util.throwIfEmpty(path); HttpRequest request; final String boundary = "----" + System.currentTimeMillis(); CloseableHttpClient httpClient = HttpClients.createDefault(); HttpPost uploadFile = createHttpPost(this.getSmartsheet().getBaseURI().resolve(path)); try { uploadFile.setHeader("Content-Type", "multipart/form-data; boundary=" + boundary); } catch (Exception e) { throw new RuntimeException(e); } MultipartEntityBuilder builder = MultipartEntityBuilder.create(); builder.setBoundary(boundary); builder.addTextBody(partName, this.getSmartsheet().getJsonSerializer().serialize(object), ContentType.APPLICATION_JSON); builder.addBinaryBody("file", inputStream, ContentType.create(contentType), attachmentName); org.apache.http.HttpEntity multipart = builder.build(); uploadFile.setEntity(multipart); T obj = null; //implement switch case try { CloseableHttpResponse response = httpClient.execute(uploadFile); org.apache.http.HttpEntity responseEntity = response.getEntity(); obj = this.getSmartsheet().getJsonSerializer() .deserializeResult(objectClass, responseEntity.getContent()).getResult(); } catch (Exception e) { throw new RuntimeException(e); } return obj; }