List of usage examples for org.apache.http.entity ContentType create
public static ContentType create(String str, String str2) throws UnsupportedCharsetException
From source file:de.hska.ld.oidc.client.SSSClient.java
public SSSEntryForDiscussionResponseDto createEntryForDiscussion( SSSEntryForDiscussionRequestDto entryForDiscRequestDto, String accessToken) throws IOException { String url = null;/*from w w w . j av a 2 s .c o m*/ if (getSssAPIVersion() == 1) { url = env.getProperty("sss.server.endpoint") + "/discs/discs"; } else { url = env.getProperty("sss.server.endpoint") + "/rest/discs"; } HttpClient client = getHttpClientFor(url); HttpPost post = new HttpPost(url); addHeaderInformation(post, accessToken); String sssLivingdocsRequestDtoString = mapper.writeValueAsString(entryForDiscRequestDto); StringEntity stringEntity = new StringEntity(sssLivingdocsRequestDtoString, ContentType.create("application/json", "UTF-8")); post.setEntity(stringEntity); BufferedReader rd = null; HttpResponse response = client.execute(post); System.out.println("Response Code : " + response.getStatusLine().getStatusCode()); if (response.getStatusLine().getStatusCode() != 200) { if (response.getStatusLine().getStatusCode() == 403) { throw new UserNotAuthorizedException(); } } try { rd = new BufferedReader(new InputStreamReader(response.getEntity().getContent())); StringBuilder result = new StringBuilder(); String line = ""; while ((line = rd.readLine()) != null) { result.append(line); } if (result.toString().contains("\"error_description\":\"Invalid access token:")) { throw new ValidationException("access token is invalid"); } mapper = new ObjectMapper().configure(DeserializationFeature.FAIL_ON_UNKNOWN_PROPERTIES, false); SSSEntryForDiscussionResponseDto sssEntryForDiscussionResponseDto = mapper.readValue(result.toString(), SSSEntryForDiscussionResponseDto.class); return sssEntryForDiscussionResponseDto; } catch (ValidationException ve) { throw ve; } catch (Exception e) { return null; } finally { if (rd != null) { rd.close(); } } }
From source file:com.nominanuda.web.http.HttpCoreHelper.java
public HttpResponse resp500TextPlainUtf8(Exception e) { BasicHttpResponse resp = new BasicHttpResponse(statusLine(500)); resp.setEntity(new StringEntity(Exceptions.toStackTrace(e), ContentType.create(CT_TEXT_PLAIN, CS_UTF_8))); return resp;//from www.jav a 2 s . co m }
From source file:de.tu_dortmund.ub.data.dswarm.Init.java
/** * creates a data model from given resource + configuration JSON (+ optional input schema) * * @param resourceJSON/*from w w w . j av a2s . c o m*/ * @param configurationJSON * @param optionalInputSchema * @param name * @param description * @return responseJson * @throws Exception */ private String createDataModel(final JsonObject resourceJSON, final JsonObject configurationJSON, final Optional<JsonObject> optionalInputSchema, final String name, final String description, final String serviceName, final String engineDswarmAPI, final boolean doIngest) throws Exception { try (final CloseableHttpClient httpclient = HttpClients.createDefault()) { final String uri = engineDswarmAPI + DswarmBackendStatics.DATAMODELS_ENDPOINT + APIStatics.QUESTION_MARK + DswarmBackendStatics.DO_DATA_MODEL_INGEST_IDENTIFIER + APIStatics.EQUALS + doIngest; final HttpPost httpPost = new HttpPost(uri); final StringWriter stringWriter = new StringWriter(); final JsonGenerator jp = Json.createGenerator(stringWriter); jp.writeStartObject(); jp.write(DswarmBackendStatics.NAME_IDENTIFIER, name); jp.write(DswarmBackendStatics.DESCRIPTION_IDENTIFIER, description); jp.write(CONFIGURATION_IDENTIFIER, configurationJSON); jp.write(DswarmBackendStatics.DATA_RESOURCE_IDENTIFIER, resourceJSON); if (optionalInputSchema.isPresent()) { LOG.info("[{}][{}] add existing input schema to input data model", serviceName, cnt); jp.write(DswarmBackendStatics.SCHEMA_IDENTIFIER, optionalInputSchema.get()); } jp.writeEnd(); jp.flush(); jp.close(); final StringEntity reqEntity = new StringEntity(stringWriter.toString(), ContentType.create(APIStatics.APPLICATION_JSON_MIMETYPE, Consts.UTF_8)); stringWriter.flush(); stringWriter.close(); httpPost.setEntity(reqEntity); LOG.info(String.format("[%s][%d] request : %s", serviceName, cnt, httpPost.getRequestLine())); try (final CloseableHttpResponse httpResponse = httpclient.execute(httpPost)) { final int statusCode = httpResponse.getStatusLine().getStatusCode(); final String message = String.format("[%s][%d] %d : %s", serviceName, cnt, statusCode, httpResponse.getStatusLine().getReasonPhrase()); final String response = TPUUtil.getResponseMessage(httpResponse); switch (statusCode) { case 201: { LOG.info(message); LOG.debug(String.format("[%s][%d] responseJson : %s", serviceName, cnt, response)); return response; } default: { LOG.error(message); throw new Exception("something went wrong at data model creation: " + message + " " + response); } } } } }
From source file:de.tu_dortmund.ub.data.dswarm.Task.java
/** * configuration and processing of the task * * @param inputDataModelID/* www . j a v a 2s. c om*/ * @param projectID * @param outputDataModelID * @return */ private String executeTask(String inputDataModelID, String projectID, String outputDataModelID) throws Exception { String jsonResponse = null; CloseableHttpClient httpclient = HttpClients.createDefault(); try { // Hole Mappings aus dem Projekt mit 'projectID' HttpGet httpGet = new HttpGet(config.getProperty("engine.dswarm.api") + "projects/" + projectID); CloseableHttpResponse httpResponse = httpclient.execute(httpGet); logger.info("[" + config.getProperty("service.name") + "] " + "request : " + httpGet.getRequestLine()); String mappings = ""; try { int statusCode = httpResponse.getStatusLine().getStatusCode(); HttpEntity httpEntity = httpResponse.getEntity(); switch (statusCode) { case 200: { StringWriter writer = new StringWriter(); IOUtils.copy(httpEntity.getContent(), writer, "UTF-8"); String responseJson = writer.toString(); logger.info("[" + config.getProperty("service.name") + "] responseJson : " + responseJson); JsonReader jsonReader = Json.createReader(IOUtils.toInputStream(responseJson, "UTF-8")); JsonObject jsonObject = jsonReader.readObject(); mappings = jsonObject.getJsonArray("mappings").toString(); logger.info("[" + config.getProperty("service.name") + "] mappings : " + mappings); break; } default: { logger.error("[" + config.getProperty("service.name") + "] " + statusCode + " : " + httpResponse.getStatusLine().getReasonPhrase()); } } EntityUtils.consume(httpEntity); } finally { httpResponse.close(); } // Hole InputDataModel String inputDataModel = ""; httpGet = new HttpGet(config.getProperty("engine.dswarm.api") + "datamodels/" + inputDataModelID); httpResponse = httpclient.execute(httpGet); logger.info("[" + config.getProperty("service.name") + "] " + "request : " + httpGet.getRequestLine()); try { int statusCode = httpResponse.getStatusLine().getStatusCode(); HttpEntity httpEntity = httpResponse.getEntity(); switch (statusCode) { case 200: { StringWriter writer = new StringWriter(); IOUtils.copy(httpEntity.getContent(), writer, "UTF-8"); inputDataModel = writer.toString(); logger.info("[" + config.getProperty("service.name") + "] inputDataModel : " + inputDataModel); JsonReader jsonReader = Json.createReader(IOUtils.toInputStream(inputDataModel, "UTF-8")); JsonObject jsonObject = jsonReader.readObject(); String inputResourceID = jsonObject.getJsonObject("data_resource").getString("uuid"); logger.info("[" + config.getProperty("service.name") + "] mappings : " + mappings); break; } default: { logger.error("[" + config.getProperty("service.name") + "] " + statusCode + " : " + httpResponse.getStatusLine().getReasonPhrase()); } } EntityUtils.consume(httpEntity); } finally { httpResponse.close(); } // Hole OutputDataModel String outputDataModel = ""; httpGet = new HttpGet(config.getProperty("engine.dswarm.api") + "datamodels/" + outputDataModelID); httpResponse = httpclient.execute(httpGet); logger.info("[" + config.getProperty("service.name") + "] " + "request : " + httpGet.getRequestLine()); try { int statusCode = httpResponse.getStatusLine().getStatusCode(); HttpEntity httpEntity = httpResponse.getEntity(); switch (statusCode) { case 200: { StringWriter writer = new StringWriter(); IOUtils.copy(httpEntity.getContent(), writer, "UTF-8"); outputDataModel = writer.toString(); logger.info( "[" + config.getProperty("service.name") + "] outputDataModel : " + outputDataModel); break; } default: { logger.error("[" + config.getProperty("service.name") + "] " + statusCode + " : " + httpResponse.getStatusLine().getReasonPhrase()); } } EntityUtils.consume(httpEntity); } finally { httpResponse.close(); } // erzeuge Task-JSON String task = "{"; task += "\"name\":\"" + "Task Batch-Prozess 'CrossRef'" + "\","; task += "\"description\":\"" + "Task Batch-Prozess 'CrossRef' zum InputDataModel '" + inputDataModelID + "'\","; task += "\"job\": { " + "\"mappings\": " + mappings + "," + "\"uuid\": \"" + UUID.randomUUID() + "\"" + " },"; task += "\"input_data_model\":" + inputDataModel + ","; task += "\"output_data_model\":" + outputDataModel; task += "}"; logger.info("[" + config.getProperty("service.name") + "] task : " + task); // POST /dmp/tasks/ HttpPost httpPost = new HttpPost(config.getProperty("engine.dswarm.api") + "tasks?persist=" + config.getProperty("results.persistInDMP")); StringEntity stringEntity = new StringEntity(task, ContentType.create("application/json", Consts.UTF_8)); httpPost.setEntity(stringEntity); logger.info("[" + config.getProperty("service.name") + "] " + "request : " + httpPost.getRequestLine()); httpResponse = httpclient.execute(httpPost); try { int statusCode = httpResponse.getStatusLine().getStatusCode(); HttpEntity httpEntity = httpResponse.getEntity(); switch (statusCode) { case 200: { logger.info("[" + config.getProperty("service.name") + "] " + statusCode + " : " + httpResponse.getStatusLine().getReasonPhrase()); StringWriter writer = new StringWriter(); IOUtils.copy(httpEntity.getContent(), writer, "UTF-8"); jsonResponse = writer.toString(); logger.info("[" + config.getProperty("service.name") + "] jsonResponse : " + jsonResponse); break; } default: { logger.error("[" + config.getProperty("service.name") + "] " + statusCode + " : " + httpResponse.getStatusLine().getReasonPhrase()); } } EntityUtils.consume(httpEntity); } finally { httpResponse.close(); } } finally { httpclient.close(); } return jsonResponse; }
From source file:com.nominanuda.web.http.HttpCoreHelper.java
public HttpResponse respInternalServerError() { BasicHttpResponse resp = new BasicHttpResponse(statusLine(500)); resp.setEntity(new StringEntity("Internal Server Error", ContentType.create(CT_TEXT_PLAIN, CS_UTF_8))); return resp;//from w w w. j a v a 2 s . c o m }
From source file:net.ymate.framework.commons.HttpClientHelper.java
public void download(String url, String content, IFileHandler handler) throws Exception { download(url, ContentType.create("application/x-www-form-urlencoded", DEFAULT_CHARSET), content, null, handler);//from w ww .j a v a2 s. c om }
From source file:com.vmware.vchs.publicapi.samples.GatewayRuleSample.java
/** * This method is to configure NAT and Firewall Rules to the EdgeGateway * //from w w w.ja v a 2s. co m * @param networkHref * the href to the network on which nat rules to be applied * @param serviceConfHref * the href to the service configure action of gateway * @return */ private void configureRules(String networkHref, String serviceConfHref) { // NAT Rules NatServiceType natService = new NatServiceType(); // To Enable the service using this flag natService.setIsEnabled(Boolean.TRUE); // Configuring Destination nat NatRuleType dnatRule = new NatRuleType(); // Setting Rule type Destination Nat DNAT dnatRule.setRuleType("DNAT"); dnatRule.setIsEnabled(Boolean.TRUE); GatewayNatRuleType dgatewayNat = new GatewayNatRuleType(); ReferenceType refd = new ReferenceType(); refd.setHref(networkHref); // Network on which nat rules to be applied dgatewayNat.setInterface(refd); // Setting Original IP dgatewayNat.setOriginalIp(options.externalIp); dgatewayNat.setOriginalPort("any"); dgatewayNat.setTranslatedIp(options.internalIp); // To allow all ports and all protocols // dgatewayNat.setTranslatedPort("any"); // dgatewayNat.setProtocol("Any"); // To allow only https use Port 443 and TCP protocol dgatewayNat.setTranslatedPort("any"); dgatewayNat.setProtocol("TCP"); // To allow only ssh use Port 22 and TCP protocol // dgatewayNat.setTranslatedPort("22"); // dgatewayNat.setProtocol("TCP"); // Setting Destination IP dnatRule.setGatewayNatRule(dgatewayNat); natService.getNatRule().add(dnatRule); // Configuring Source nat NatRuleType snatRule = new NatRuleType(); // Setting Rule type Source Nat SNAT snatRule.setRuleType("SNAT"); snatRule.setIsEnabled(Boolean.TRUE); GatewayNatRuleType sgatewayNat = new GatewayNatRuleType(); //ReferenceType refd = new ReferenceType(); //refd.setHref(networkHref); // Network on which nat rules to be applied sgatewayNat.setInterface(refd); // Setting Original IP sgatewayNat.setOriginalIp(options.internalIp); //sgatewayNat.setOriginalPort("any"); sgatewayNat.setTranslatedIp(options.externalIp); // Setting Source IP snatRule.setGatewayNatRule(sgatewayNat); natService.getNatRule().add(snatRule); // Firewall Rules FirewallServiceType firewallService = new FirewallServiceType(); // Enable or disable the service using this flag firewallService.setIsEnabled(Boolean.TRUE); // Default action of the firewall set to drop firewallService.setDefaultAction("drop"); // Flag to enable logging for default action firewallService.setLogDefaultAction(Boolean.FALSE); // Firewall Rule settings FirewallRuleType firewallInRule = new FirewallRuleType(); firewallInRule.setIsEnabled(Boolean.TRUE); firewallInRule.setMatchOnTranslate(Boolean.FALSE); firewallInRule.setDescription("Allow incoming https access"); firewallInRule.setPolicy("allow"); FirewallRuleProtocols firewallProtocol = new FirewallRuleProtocols(); firewallProtocol.setAny(Boolean.TRUE); firewallInRule.setProtocols(firewallProtocol); firewallInRule.setDestinationPortRange("any"); firewallInRule.setDestinationIp(options.externalIp); firewallInRule.setSourcePortRange("Any"); firewallInRule.setSourceIp("external"); firewallInRule.setEnableLogging(Boolean.FALSE); firewallService.getFirewallRule().add(firewallInRule); // To create the HttpPost request Body ObjectFactory objectFactory = new ObjectFactory(); GatewayFeaturesType gatewayFeatures = new GatewayFeaturesType(); JAXBElement<NetworkServiceType> serviceType = objectFactory.createNetworkService(natService); JAXBElement<NetworkServiceType> firewallserviceType = objectFactory.createNetworkService(firewallService); gatewayFeatures.getNetworkService().add(serviceType); gatewayFeatures.getNetworkService().add(firewallserviceType); JAXBContext jaxbContexts = null; try { jaxbContexts = JAXBContext.newInstance(GatewayFeaturesType.class); } catch (JAXBException ex) { ex.printStackTrace(); } OutputStream os = null; JAXBElement<GatewayFeaturesType> gateway_Features = objectFactory .createEdgeGatewayServiceConfiguration(gatewayFeatures); try { javax.xml.bind.Marshaller marshaller = jaxbContexts.createMarshaller(); marshaller.setProperty(javax.xml.bind.Marshaller.JAXB_FORMATTED_OUTPUT, Boolean.TRUE); os = new ByteArrayOutputStream(); // Marshal the JAXB class to XML marshaller.marshal(gateway_Features, os); } catch (JAXBException e) { e.printStackTrace(); } HttpPost httpPost = vcd.post(serviceConfHref, options); ContentType contentType = ContentType.create(SampleConstants.CONTENT_TYPE_EDGE_GATEWAY, "ISO-8859-1"); StringEntity rules = new StringEntity(os.toString(), contentType); httpPost.setEntity(rules); InputStream is = null; // Invoking api to add rules to gateway HttpResponse response = HttpUtils.httpInvoke(httpPost); // Make sure the response code is 202 ACCEPTED if (response.getStatusLine().getStatusCode() == HttpStatus.SC_ACCEPTED) { // System.out.println("ResponseCode : " + response.getStatusLine().getStatusCode()); System.out.println("\nRequest To update Gateway initiated sucessfully"); System.out.print("\nUpdating EdgeGateways to add NAT and Firewall Rules..."); taskStatus(response); } }
From source file:com.thinkbiganalytics.search.ElasticSearchRestService.java
private HttpEntity getDataDeleteRequestBodyDsl(@Nonnull String schema, @Nonnull String table) { String jsonBodyString = new JSONObject().toString(); try {/* ww w . ja v a2 s. com*/ JSONObject schemaMatchObject = new JSONObject().put("kylo_schema", schema); JSONObject tableMatchObject = new JSONObject().put("kylo_table", table); JSONObject firstMatchObject = new JSONObject().put("match", schemaMatchObject); JSONObject secondMatchObject = new JSONObject().put("match", tableMatchObject); JSONArray shouldArray = new JSONArray().put(firstMatchObject).put(secondMatchObject); JSONObject shouldObject = new JSONObject().put("must", shouldArray); JSONObject boolObject = new JSONObject().put("bool", shouldObject); JSONObject queryObject = new JSONObject().put("query", boolObject); jsonBodyString = queryObject.toString(); } catch (JSONException jsonException) { log.warn("Could not construct data deletion request body query dsl for schema {" + schema + "}, table {" + table + "}", jsonException); } return new StringEntity(jsonBodyString, ContentType.create("application/json", "UTF-8")); }
From source file:com.nominanuda.web.http.HttpCoreHelper.java
public HttpResponse createBasicResponse(int status, String message, String contentType) { BasicHttpResponse resp = new BasicHttpResponse(statusLine(status)); try {// w w w . j ava2 s. c om String declaredCharset = guessCharset(contentType); HttpEntity e = new StringEntity(message, declaredCharset == null ? ContentType.create(contentType, CS_UTF_8) : ContentType.create(contentType)); resp.setEntity(e); } catch (UnsupportedCharsetException ex) { throw new IllegalArgumentException(ex); } return resp; }
From source file:com.microsoft.alm.plugin.context.soap.CatalogServiceImpl.java
private static StringEntity generateSoapQuery(final String pathSpecs, final int queryOptions) { final StringBuilder stringBuilder = new StringBuilder(); stringBuilder.append("<?xml version='1.0' encoding='UTF-8'?>"); //$NON-NLS-1$ stringBuilder.append(/* w ww . j a va 2 s . c o m*/ "<soap:Envelope xmlns:soap=\"http://www.w3.org/2003/05/soap-envelope\" xmlns:xsi=\"http://www.w3.org/2001/XMLSchema-instance\" xmlns:xsd=\"http://www.w3.org/2001/XMLSchema\">");//$NON-NLS-1$ stringBuilder.append("<soap:Body xmlns=\"http://microsoft.com/webservices/\">");//$NON-NLS-1$ stringBuilder.append("<QueryNodes>");//$NON-NLS-1$ stringBuilder.append("<pathSpecs>");//$NON-NLS-1$ stringBuilder.append("<string>" + pathSpecs + "</string>");//$NON-NLS-1$ //$NON-NLS-2$ stringBuilder.append("</pathSpecs>");//$NON-NLS-1$ stringBuilder.append("<queryOptions>" + queryOptions + "</queryOptions>");//$NON-NLS-1$ stringBuilder.append("</QueryNodes>");//$NON-NLS-1$ stringBuilder.append("</soap:Body>");//$NON-NLS-1$ stringBuilder.append("</soap:Envelope>");//$NON-NLS-1$ final StringEntity stringEntity = new StringEntity(stringBuilder.toString(), ContentType.create("application/soap+xml", "utf-8"));//$NON-NLS-1$ //$NON-NLS-2$ return stringEntity; }