List of usage examples for org.apache.http.client.methods CloseableHttpResponse getStatusLine
StatusLine getStatusLine();
From source file:utils.APIExporter.java
/** * generate a archive of exporting API// w ww . j ava 2 s.c o m * @param apiName name of the API * @param provider provider of the API * @param version version of the API * @param accessToken valid access token */ private static void exportAPI(String destinationLocation, String apiName, String provider, String version, String accessToken) throws APIExportException { ApiImportExportConfiguration config = ApiImportExportConfiguration.getInstance(); //creating a directory to hold API details String APIFolderPath = destinationLocation.concat(File.separator + apiName + "-" + version); ImportExportUtils.createDirectory(APIFolderPath); //building the API id String apiId = provider + "-" + apiName + "-" + version; String responseString; try { //getting API meta- information CloseableHttpClient client = HttpClientGenerator.getHttpClient(config.getCheckSSLCertificate()); String metaInfoUrl = config.getPublisherUrl() + "apis/" + apiId; HttpGet request = new HttpGet(metaInfoUrl); request.setHeader(javax.ws.rs.core.HttpHeaders.AUTHORIZATION, ImportExportConstants.CONSUMER_KEY_SEGMENT + " " + accessToken); CloseableHttpResponse response = client.execute(request); if (response.getStatusLine().getStatusCode() == 404) { ////// TODO: 8/24/16 int value constant String message = "API " + apiId + "does not exist/ not found "; log.warn(message); return; } HttpEntity entity = response.getEntity(); responseString = EntityUtils.toString(entity, ImportExportConstants.CHARSET); } catch (IOException e) { String errorMsg = "Error occurred while retrieving the API meta information"; log.error(errorMsg, e); throw new APIExportException(errorMsg, e); } //creating directory to hold meta-information String metaInfoFolderPath = APIFolderPath.concat(File.separator + "meta-information"); ImportExportUtils.createDirectory(metaInfoFolderPath); //set API status and scope before exporting setJsonValues(responseString, ImportExportConstants.STATUS_CONSTANT, ImportExportConstants.CREATED); setJsonValues(responseString, ImportExportConstants.SCOPE_CONSTANT, null); try { //writing meta-information Object json = mapper.readValue(responseString, Object.class); String formattedJson = mapper.writerWithDefaultPrettyPrinter().writeValueAsString(json); writeFile(metaInfoFolderPath + File.separator + "api.json", formattedJson); } catch (IOException e) { String error = "Error occurred while formatting the json string"; log.error(error, e); throw new APIExportException(error, e); } JSONObject jsonObj = null; try { jsonObj = (JSONObject) parser.parse(responseString); String swagger = (String) jsonObj.get(ImportExportConstants.SWAGGER); writeFile(metaInfoFolderPath + File.separator + "swagger.json", swagger); } catch (ParseException e) { log.error("error occurred while getting swagger definision"); } //get API uuid String uuid = null; if (jsonObj != null) { uuid = (String) jsonObj.get(ImportExportConstants.UUID); } //export api thumbnail String thumbnailUrl = null; if (jsonObj != null) { thumbnailUrl = (String) jsonObj.get(ImportExportConstants.THUMBNAIL); } if (thumbnailUrl != null) { exportAPIThumbnail(uuid, accessToken, APIFolderPath); } //export api documents String documentationSummary = getAPIDocumentation(accessToken, uuid); exportAPIDocumentation(uuid, documentationSummary, accessToken, APIFolderPath); }
From source file:org.wuspba.ctams.ws.ITBandRegistrationController.java
protected static void add() throws Exception { ITBandController.add();//from w ww . ja v a 2s. c o m CTAMSDocument doc = new CTAMSDocument(); doc.getBands().add(TestFixture.INSTANCE.skye); doc.getBandRegistrations().add(TestFixture.INSTANCE.bandRegistration); String xml = XMLUtils.marshal(doc); CloseableHttpClient httpclient = HttpClients.createDefault(); URI uri = new URIBuilder().setScheme(PROTOCOL).setHost(HOST).setPort(PORT).setPath(PATH).build(); HttpPost httpPost = new HttpPost(uri); StringEntity xmlEntity = new StringEntity(xml, ContentType.APPLICATION_XML); CloseableHttpResponse response = null; try { httpPost.setEntity(xmlEntity); response = httpclient.execute(httpPost); assertEquals(IntegrationTestUtils.OK_STRING, response.getStatusLine().toString()); HttpEntity responseEntity = response.getEntity(); doc = IntegrationTestUtils.convertEntity(responseEntity); TestFixture.INSTANCE.bandRegistration.setId(doc.getBandRegistrations().get(0).getId()); EntityUtils.consume(responseEntity); } catch (UnsupportedEncodingException ex) { LOG.error("Unsupported coding", ex); } catch (IOException ioex) { LOG.error("IOException", ioex); } finally { if (response != null) { try { response.close(); } catch (IOException ex) { LOG.error("Could not close response", ex); } } } }
From source file:org.wuspba.ctams.ws.ITSoloRegistrationController.java
private static void add() throws Exception { ITPersonController.add();// www .j a va2s . c om CTAMSDocument doc = new CTAMSDocument(); doc.getPeople().add(TestFixture.INSTANCE.elaine); doc.getSoloRegistrations().add(TestFixture.INSTANCE.soloRegistration); String xml = XMLUtils.marshal(doc); CloseableHttpClient httpclient = HttpClients.createDefault(); URI uri = new URIBuilder().setScheme(PROTOCOL).setHost(HOST).setPort(PORT).setPath(PATH).build(); HttpPost httpPost = new HttpPost(uri); StringEntity xmlEntity = new StringEntity(xml, ContentType.APPLICATION_XML); CloseableHttpResponse response = null; try { httpPost.setEntity(xmlEntity); response = httpclient.execute(httpPost); assertEquals(IntegrationTestUtils.OK_STRING, response.getStatusLine().toString()); HttpEntity responseEntity = response.getEntity(); doc = IntegrationTestUtils.convertEntity(responseEntity); TestFixture.INSTANCE.soloRegistration.setId(doc.getSoloRegistrations().get(0).getId()); EntityUtils.consume(responseEntity); } catch (UnsupportedEncodingException ex) { LOG.error("Unsupported coding", ex); } catch (IOException ioex) { LOG.error("IOException", ioex); } finally { if (response != null) { try { response.close(); } catch (IOException ex) { LOG.error("Could not close response", ex); } } } }
From source file:org.wuspba.ctams.ws.ITSoloResultController.java
protected static void delete() throws Exception { CloseableHttpClient httpclient = HttpClients.createDefault(); URI uri = new URIBuilder().setScheme(PROTOCOL).setHost(HOST).setPort(PORT).setPath(PATH) .setParameter("id", TestFixture.INSTANCE.soloResult.getId()).build(); HttpDelete httpDelete = new HttpDelete(uri); CloseableHttpResponse response = null; try {// w ww . j a v a 2s. co m response = httpclient.execute(httpDelete); assertEquals(IntegrationTestUtils.OK_STRING, response.getStatusLine().toString()); HttpEntity responseEntity = response.getEntity(); EntityUtils.consume(responseEntity); } catch (UnsupportedEncodingException ex) { LOG.error("Unsupported coding", ex); } catch (IOException ioex) { LOG.error("IOException", ioex); } finally { if (response != null) { try { response.close(); } catch (IOException ex) { LOG.error("Could not close response", ex); } } } ITSoloContestController.delete(); }
From source file:eionet.gdem.qa.functions.Json.java
/** * Method converts the URL response body into XML format and returns it as String. If the response is not in JSON format, then JsonError object is converted to XML. * @param requestUrl Request URL to JSON format content. * @return String of XML//from ww w .j a v a 2 s .c o m */ public static String jsonRequest2xmlString(String requestUrl) { JsonError error = null; String responseString = null; String xml = null; HttpGet method = null; // Create an instance of HttpClient. CloseableHttpClient client = HttpClients.custom() .setRetryHandler(new DefaultHttpRequestRetryHandler(3, false)).build(); CloseableHttpResponse response = null; try { // Create a method instance. method = new HttpGet(requestUrl); // Provide custom retry handler is necessary //method.getParams().setParameter(HttpMethodParams.RETRY_HANDLER, new DefaultHttpMethodRetryHandler(3, false)); // Execute the method. response = client.execute(method); int statusCode = response.getStatusLine().getStatusCode(); if (statusCode != HttpStatus.SC_OK) { LOGGER.error("Method failed: " + response.getStatusLine()); error = new JsonError(statusCode, response.getStatusLine().getReasonPhrase()); } else { // Read the response body. HttpEntity entity = response.getEntity(); byte[] responseBody = IOUtils.toByteArray(entity.getContent()); responseString = new String(responseBody, "UTF-8"); } /*} catch (HttpException e) { LOGGER.error("Fatal protocol violation: " + e.getMessage()); e.printStackTrace(); error = new JsonError(HttpStatus.SC_INTERNAL_SERVER_ERROR, "Fatal protocol violation.");*/ } catch (IOException e) { LOGGER.error("Fatal transport error: " + e.getMessage()); error = new JsonError(HttpStatus.SC_INTERNAL_SERVER_ERROR, "Fatal transport error."); e.printStackTrace(); } catch (Exception e) { LOGGER.error("Error: " + e.getMessage()); e.printStackTrace(); error = new JsonError(HttpStatus.SC_INTERNAL_SERVER_ERROR, "Error." + e.getMessage()); } finally { // Release the connection. if (method != null) { method.releaseConnection(); } } if (responseString != null) { xml = jsonString2xml(responseString); } else if (error != null) { xml = jsonString2xml(error); } else { xml = jsonString2xml(new JsonError()); } return xml; }
From source file:org.wuspba.ctams.ws.ITJudgeController.java
private static void add(Judge j) throws Exception { CTAMSDocument doc = new CTAMSDocument(); doc.getPeople().add(j.getPerson());/*from w w w. j a v a 2 s .co m*/ doc.getJudgeQualifications().addAll(j.getQualifications()); doc.getJudges().add(j); String xml = XMLUtils.marshal(doc); CloseableHttpClient httpclient = HttpClients.createDefault(); URI uri = new URIBuilder().setScheme(PROTOCOL).setHost(HOST).setPort(PORT).setPath(PATH).build(); HttpPost httpPost = new HttpPost(uri); StringEntity xmlEntity = new StringEntity(xml, ContentType.APPLICATION_XML); CloseableHttpResponse response = null; try { httpPost.setEntity(xmlEntity); response = httpclient.execute(httpPost); assertEquals(IntegrationTestUtils.OK_STRING, response.getStatusLine().toString()); HttpEntity responseEntity = response.getEntity(); doc = IntegrationTestUtils.convertEntity(responseEntity); j.setId(doc.getJudges().get(0).getId()); EntityUtils.consume(responseEntity); } catch (UnsupportedEncodingException ex) { LOG.error("Unsupported coding", ex); } catch (IOException ioex) { LOG.error("IOException", ioex); } finally { if (response != null) { try { response.close(); } catch (IOException ex) { LOG.error("Could not close response", ex); } } } }
From source file:org.apache.ofbiz.passport.user.LinkedInAuthenticator.java
public static Document getUserInfo(HttpGet httpGet, Locale locale) throws IOException, AuthenticatorException, SAXException, ParserConfigurationException { Document userInfo = null;/*w w w . j a v a 2 s. c om*/ httpGet.setConfig(PassportUtil.StandardRequestConfig); CloseableHttpClient jsonClient = HttpClients.custom().build(); CloseableHttpResponse getResponse = jsonClient.execute(httpGet); String responseString = new BasicResponseHandler().handleResponse(getResponse); if (getResponse.getStatusLine().getStatusCode() == HttpStatus.SC_OK) { // Debug.logInfo("Json Response from LinkedIn: " + responseString, module); userInfo = UtilXml.readXmlDocument(responseString); } else { String errMsg = UtilProperties.getMessage(resource, "GetOAuth2AccessTokenError", UtilMisc.toMap("error", responseString), locale); throw new AuthenticatorException(errMsg); } return userInfo; }
From source file:org.wuspba.ctams.ws.ITJudgeQualificationController.java
protected static void add() throws Exception { CTAMSDocument doc = new CTAMSDocument(); doc.getJudgeQualifications().add(TestFixture.INSTANCE.drummingQual); doc.getJudgeQualifications().add(TestFixture.INSTANCE.ensembleQual); doc.getJudgeQualifications().add(TestFixture.INSTANCE.pipingQual); String xml = XMLUtils.marshal(doc); CloseableHttpClient httpclient = HttpClients.createDefault(); URI uri = new URIBuilder().setScheme(PROTOCOL).setHost(HOST).setPort(PORT).setPath(PATH).build(); HttpPost httpPost = new HttpPost(uri); StringEntity xmlEntity = new StringEntity(xml, ContentType.APPLICATION_XML); CloseableHttpResponse response = null; try {//w w w.j a va 2s.co m httpPost.setEntity(xmlEntity); response = httpclient.execute(httpPost); assertEquals(IntegrationTestUtils.OK_STRING, response.getStatusLine().toString()); HttpEntity responseEntity = response.getEntity(); doc = IntegrationTestUtils.convertEntity(responseEntity); for (JudgeQualification q : doc.getJudgeQualifications()) { if (q.getPanel() == TestFixture.INSTANCE.pipingQual.getPanel() && q.getType() == TestFixture.INSTANCE.pipingQual.getType()) { TestFixture.INSTANCE.pipingQual.setId(q.getId()); } else if (q.getPanel() == TestFixture.INSTANCE.drummingQual.getPanel() && q.getType() == TestFixture.INSTANCE.drummingQual.getType()) { TestFixture.INSTANCE.drummingQual.setId(q.getId()); } else if (q.getPanel() == TestFixture.INSTANCE.ensembleQual.getPanel() && q.getType() == TestFixture.INSTANCE.ensembleQual.getType()) { TestFixture.INSTANCE.ensembleQual.setId(q.getId()); } } EntityUtils.consume(responseEntity); } catch (UnsupportedEncodingException ex) { LOG.error("Unsupported coding", ex); } catch (IOException ioex) { LOG.error("IOException", ioex); } finally { if (response != null) { try { response.close(); } catch (IOException ex) { LOG.error("Could not close response", ex); } } } }
From source file:org.helm.notation2.wsadapter.MonomerWSLoader.java
/** * Loads the monomer categories using the URL configured in * {@code MonomerStoreConfiguration}.//from w ww . j a va 2s . c o m * * @return List containing monomer categories * * @throws IOException * @throws URISyntaxException */ public static List<CategorizedMonomer> loadMonomerCategorization() throws IOException, URISyntaxException { List<CategorizedMonomer> config = new LinkedList<CategorizedMonomer>(); CloseableHttpClient httpclient = HttpClients.createDefault(); // There is no need to provide user credentials // HttpClient will attempt to access current user security context // through Windows platform specific methods via JNI. CloseableHttpResponse response = null; try { response = WSAdapterUtils.getResource( MonomerStoreConfiguration.getInstance().getWebserviceEditorCategorizationFullURL()); LOG.debug(response.getStatusLine().toString()); JsonFactory jsonf = new JsonFactory(); InputStream instream = response.getEntity().getContent(); JsonParser jsonParser = jsonf.createJsonParser(instream); config = deserializeEditorCategorizationConfig(jsonParser); LOG.debug(config.size() + " categorization info entries loaded"); EntityUtils.consume(response.getEntity()); } finally { if (response != null) { response.close(); } if (httpclient != null) { httpclient.close(); } } return config; }
From source file:com.vmware.identity.openidconnect.client.OIDCClientUtils.java
static HttpResponse sendSecureRequest(HttpRequest httpRequest, SSLContext sslContext) throws OIDCClientException, SSLConnectionException { Validate.notNull(httpRequest, "httpRequest"); Validate.notNull(sslContext, "sslContext"); RequestConfig config = RequestConfig.custom().setConnectTimeout(HTTP_CLIENT_TIMEOUT_MILLISECS) .setConnectionRequestTimeout(HTTP_CLIENT_TIMEOUT_MILLISECS) .setSocketTimeout(HTTP_CLIENT_TIMEOUT_MILLISECS).build(); CloseableHttpClient client = HttpClients.custom().setSSLContext(sslContext).setDefaultRequestConfig(config) .build();/*w w w . j a va2 s . c o m*/ CloseableHttpResponse closeableHttpResponse = null; try { HttpRequestBase httpTask = httpRequest.toHttpTask(); closeableHttpResponse = client.execute(httpTask); int statusCodeInt = closeableHttpResponse.getStatusLine().getStatusCode(); StatusCode statusCode; try { statusCode = StatusCode.parse(statusCodeInt); } catch (ParseException e) { throw new OIDCClientException("failed to parse status code", e); } JSONObject jsonContent = null; HttpEntity httpEntity = closeableHttpResponse.getEntity(); if (httpEntity != null) { ContentType contentType; try { contentType = ContentType.get(httpEntity); } catch (UnsupportedCharsetException | org.apache.http.ParseException e) { throw new OIDCClientException("Error in setting content type in HTTP response."); } if (!StandardCharsets.UTF_8.equals(contentType.getCharset())) { throw new OIDCClientException("unsupported charset: " + contentType.getCharset()); } if (!ContentType.APPLICATION_JSON.getMimeType().equalsIgnoreCase(contentType.getMimeType())) { throw new OIDCClientException("unsupported mime type: " + contentType.getMimeType()); } String content = EntityUtils.toString(httpEntity); try { jsonContent = JSONUtils.parseJSONObject(content); } catch (ParseException e) { throw new OIDCClientException("failed to parse json response", e); } } closeableHttpResponse.close(); client.close(); return HttpResponse.createJsonResponse(statusCode, jsonContent); } catch (IOException e) { throw new OIDCClientException("IOException caught in HTTP communication:" + e.getMessage(), e); } }