List of usage examples for org.apache.http.impl.client CloseableHttpClient execute
public CloseableHttpResponse execute(final HttpUriRequest request) throws IOException, ClientProtocolException
From source file:org.apache.ofbiz.passport.event.GitHubEvents.java
/** * Parse GitHub login response and login the user if possible. * //www . j a v a 2 s. co m * @return */ public static String parseGitHubResponse(HttpServletRequest request, HttpServletResponse response) { String authorizationCode = request.getParameter(PassportUtil.COMMON_CODE); String state = request.getParameter(PassportUtil.COMMON_STATE); if (!state.equals(request.getSession().getAttribute(SESSION_GITHUB_STATE))) { String errMsg = UtilProperties.getMessage(resource, "GitHubFailedToMatchState", UtilHttp.getLocale(request)); request.setAttribute("_ERROR_MESSAGE_", errMsg); return "error"; } if (UtilValidate.isEmpty(authorizationCode)) { String error = request.getParameter(PassportUtil.COMMON_ERROR); String errorDescpriton = request.getParameter(PassportUtil.COMMON_ERROR_DESCRIPTION); String errMsg = null; try { errMsg = UtilProperties.getMessage(resource, "FailedToGetGitHubAuthorizationCode", UtilMisc.toMap(PassportUtil.COMMON_ERROR, error, PassportUtil.COMMON_ERROR_DESCRIPTION, URLDecoder.decode(errorDescpriton, "UTF-8")), UtilHttp.getLocale(request)); } catch (UnsupportedEncodingException e) { errMsg = UtilProperties.getMessage(resource, "GetGitHubAuthorizationCodeError", UtilHttp.getLocale(request)); } request.setAttribute("_ERROR_MESSAGE_", errMsg); return "error"; } Debug.logInfo("GitHub authorization code: " + authorizationCode, module); GenericValue oauth2GitHub = getOAuth2GitHubConfig(request); if (UtilValidate.isEmpty(oauth2GitHub)) { String errMsg = UtilProperties.getMessage(resource, "GetOAuth2GitHubConfigError", UtilHttp.getLocale(request)); request.setAttribute("_ERROR_MESSAGE_", errMsg); return "error"; } String clientId = oauth2GitHub.getString(PassportUtil.COMMON_CLIENT_ID); String secret = oauth2GitHub.getString(PassportUtil.COMMON_CLIENT_SECRET); String returnURI = oauth2GitHub.getString(PassportUtil.COMMON_RETURN_RUL); // Grant token from authorization code and oauth2 token // Use the authorization code to obtain an access token String accessToken = null; String tokenType = null; try { URI uri = new URIBuilder().setScheme(TokenEndpoint.substring(0, TokenEndpoint.indexOf(":"))) .setHost(TokenEndpoint.substring(TokenEndpoint.indexOf(":") + 3)).setPath(TokenServiceUri) .setParameter("client_id", clientId).setParameter("client_secret", secret) .setParameter("code", authorizationCode).setParameter("redirect_uri", returnURI).build(); HttpPost postMethod = new HttpPost(uri); CloseableHttpClient jsonClient = HttpClients.custom().build(); // Debug.logInfo("GitHub get access token query string: " + postMethod.getURI(), module); postMethod.setConfig(PassportUtil.StandardRequestConfig); postMethod.setHeader(PassportUtil.ACCEPT_HEADER, "application/json"); CloseableHttpResponse postResponse = jsonClient.execute(postMethod); String responseString = new BasicResponseHandler().handleResponse(postResponse); // Debug.logInfo("GitHub get access token response code: " + postResponse.getStatusLine().getStatusCode(), module); // Debug.logInfo("GitHub get access token response content: " + responseString, module); if (postResponse.getStatusLine().getStatusCode() == HttpStatus.SC_OK) { Debug.logInfo("Json Response from GitHub: " + responseString, module); JSON jsonObject = JSON.from(responseString); JSONToMap jsonMap = new JSONToMap(); Map<String, Object> userMap = jsonMap.convert(jsonObject); accessToken = (String) userMap.get("access_token"); tokenType = (String) userMap.get("token_type"); // Debug.logInfo("Generated Access Token : " + accessToken, module); // Debug.logInfo("Token Type: " + tokenType, module); } else { String errMsg = UtilProperties.getMessage(resource, "GetOAuth2GitHubAccessTokenError", UtilMisc.toMap("error", responseString), UtilHttp.getLocale(request)); request.setAttribute("_ERROR_MESSAGE_", errMsg); return "error"; } } catch (UnsupportedEncodingException e) { request.setAttribute("_ERROR_MESSAGE_", e.toString()); return "error"; } catch (IOException e) { request.setAttribute("_ERROR_MESSAGE_", e.toString()); return "error"; } catch (ConversionException e) { request.setAttribute("_ERROR_MESSAGE_", e.toString()); return "error"; } catch (URISyntaxException e) { request.setAttribute("_ERROR_MESSAGE_", e.toString()); return "error"; } // Get User Profile HttpGet getMethod = new HttpGet(ApiEndpoint + UserApiUri); Map<String, Object> userInfo = null; try { userInfo = GitHubAuthenticator.getUserInfo(getMethod, accessToken, tokenType, UtilHttp.getLocale(request)); } catch (AuthenticatorException e) { request.setAttribute("_ERROR_MESSAGE_", e.toString()); return "error"; } finally { getMethod.releaseConnection(); } // Debug.logInfo("GitHub User Info:" + userInfo, module); // Store the user info and check login the user return checkLoginGitHubUser(request, userInfo, accessToken); }
From source file:com.welocalize.dispatcherMW.client.Main.java
public static String uploadXLF(String p_fileName, String p_securityCode) { CloseableHttpClient httpClient = HttpClients.createDefault(); HttpPost httpPost = new HttpPost(getFunctinURL(TYPE_UPLOAD, p_securityCode, null)); try {/* ww w. jav a 2 s . c om*/ HttpEntity reqEntity = MultipartEntityBuilder.create() .addPart("fileName", new StringBody(p_fileName, ContentType.create("text/plain", Consts.UTF_8))) .addPart("file", new FileBody(new File(p_fileName))).build(); httpPost.setEntity(reqEntity); // send the http request and get the http response HttpResponse response = httpClient.execute(httpPost); HttpEntity resEntity = response.getEntity(); String jobID = null; String msg = EntityUtils.toString(resEntity); if (msg.contains("\"jobID\":\"")) { int startIndex = msg.indexOf("\"jobID\":\""); jobID = msg.substring(startIndex + 9, msg.indexOf(",", startIndex) - 1); System.out.println("Create Job: " + jobID + ", wtih file:" + p_fileName); return jobID; } System.out.println(msg); return jobID; } catch (Exception e) { System.out.println("testHTTPClient error. " + e); } finally { httpPost.releaseConnection(); } return null; }
From source file:org.darkware.wpman.wpcli.WPCLI.java
/** * Update the local WP-CLI tool to the most recent version. *//* ww w. j a va 2 s. c om*/ public static void update() { try { WPManager.log.info("Downloading new version of WP-CLI."); CloseableHttpClient httpclient = HttpClients.createDefault(); URI pharURI = new URIBuilder().setScheme("http").setHost("raw.githubusercontent.com") .setPath("/wp-cli/builds/gh-pages/phar/wp-cli.phar").build(); WPManager.log.info("Downloading from: {}", pharURI); HttpGet downloadRequest = new HttpGet(pharURI); CloseableHttpResponse response = httpclient.execute(downloadRequest); WPManager.log.info("Download response: {}", response.getStatusLine()); WPManager.log.info("Download content type: {}", response.getFirstHeader("Content-Type").getValue()); FileChannel wpcliFile = FileChannel.open(WPCLI.toolPath, StandardOpenOption.CREATE, StandardOpenOption.TRUNCATE_EXISTING, StandardOpenOption.WRITE); response.getEntity().writeTo(Channels.newOutputStream(wpcliFile)); wpcliFile.close(); Set<PosixFilePermission> wpcliPerms = new HashSet<>(); wpcliPerms.add(PosixFilePermission.OWNER_READ); wpcliPerms.add(PosixFilePermission.OWNER_WRITE); wpcliPerms.add(PosixFilePermission.OWNER_EXECUTE); wpcliPerms.add(PosixFilePermission.GROUP_READ); wpcliPerms.add(PosixFilePermission.GROUP_EXECUTE); Files.setPosixFilePermissions(WPCLI.toolPath, wpcliPerms); } catch (URISyntaxException e) { WPManager.log.error("Failure building URL for WPCLI download.", e); System.exit(1); } catch (IOException e) { WPManager.log.error("Error while downloading WPCLI client.", e); e.printStackTrace(); System.exit(1); } }
From source file:org.wuspba.ctams.ws.ITBandRegistrationController.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.bandRegistration.getId()).build(); HttpDelete httpDelete = new HttpDelete(uri); CloseableHttpResponse response = null; try {/*from w w w. j av 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); } } } ITBandController.delete(); }
From source file:org.wuspba.ctams.ws.ITSoloRegistrationController.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.soloRegistration.getId()).build(); HttpDelete httpDelete = new HttpDelete(uri); CloseableHttpResponse response = null; try {//from w w w . ja v a2 s . c o 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); } } } ITPersonController.delete(); }
From source file:fr.lissi.belilif.om2m.rest.WebServiceActions.java
/** * Do post./*from w w w .j ava 2 s .com*/ * * @param uri * the uri * @param body * the body * @param headers * the headers * @return the int * @throws ClientProtocolException * the client protocol exception * @throws IOException * Signals that an I/O exception has occurred. * @throws HttpResponseException * the http response exception */ public static int doPost(String uri, String body, HashMap<String, String> headers) throws ClientProtocolException, IOException, HttpResponseException { // TODO delete before commit // System.out.println("doPost>> uri:"+uri +"\nbody:"+body+"\n"); CloseableHttpClient httpclient = HttpClients.createDefault(); int resp = -1; try { HttpPost httpPost = new HttpPost(uri); for (String key : headers.keySet()) { httpPost.addHeader(key, headers.get(key)); // System.out.println("header:"+key+"/"+headers.get(key)); } // System.out.println("doPost<<"); httpPost.setEntity(new StringEntity(body)); CloseableHttpResponse response = httpclient.execute(httpPost); resp = response.getStatusLine().getStatusCode(); if (response.getStatusLine().getStatusCode() == HttpStatus.SC_CREATED) { response.close(); } else { throw new HttpResponseException(response.getStatusLine().getStatusCode(), response.getStatusLine().getReasonPhrase()); } } finally { httpclient.close(); } return resp; }
From source file:com.evrythng.java.wrapper.util.FileUtils.java
/** * Uploads a {@code File} with PRIVATE read access. * * @param uri upload {@link URI}//from w ww . j ava 2 s . com * @param contentTypeString content type * @param contentFile the file to upload * @throws IOException */ public static void uploadPrivateContent(final URI uri, final String contentTypeString, final File contentFile) throws IOException { LOGGER.info("uploadPrivateContent START: uri: [{}]; content type: [{}], content file: [{}]", new Object[] { uri, contentTypeString, contentFile }); CloseableHttpClient closeableHttpClient = HttpClients.createDefault(); HttpPut httpPut = new HttpPut(uri); httpPut.addHeader(HttpHeaders.CONTENT_TYPE, contentTypeString); httpPut.addHeader(FileUtils.X_AMZ_ACL_HEADER_NAME, FileUtils.X_AMZ_ACL_HEADER_VALUE_PRIVATE); ContentType contentType = ContentType.create(contentTypeString); FileEntity fileEntity = new FileEntity(contentFile, contentType); httpPut.setEntity(fileEntity); CloseableHttpResponse response = closeableHttpClient.execute(httpPut); StatusLine statusLine = response.getStatusLine(); if (!(statusLine.getStatusCode() == HttpStatus.SC_OK)) { throw new IOException(String.format("An error occurred while trying to upload private file - %d: %s", statusLine.getStatusCode(), statusLine.getReasonPhrase())); } LOGGER.info("uploadPrivateContent END: uri: [{}]; content type: [{}], content file: [{}]", new Object[] { uri, contentTypeString, contentFile }); }
From source file:org.wuspba.ctams.ws.ITJudgeQualificationController.java
public static JudgeQualification getQualification(JudgePanelType panel, JudgeType type) throws Exception { CloseableHttpClient httpclient = HttpClients.createDefault(); JudgeQualification ret;/* w w w. j a va 2 s . c o m*/ URI uri = new URIBuilder().setScheme(PROTOCOL).setHost(HOST).setPort(PORT).setPath(PATH) .setParameter("panel", panel.toString()).setParameter("type", type.toString()).build(); HttpGet httpGet = new HttpGet(uri); try (CloseableHttpResponse response = httpclient.execute(httpGet)) { assertEquals(response.getStatusLine().toString(), IntegrationTestUtils.OK_STRING); HttpEntity entity = response.getEntity(); CTAMSDocument doc = IntegrationTestUtils.convertEntity(entity); assertEquals(doc.getJudgeQualifications().size(), 1); ret = doc.getJudgeQualifications().get(0); EntityUtils.consume(entity); } return ret; }
From source file:com.dtstack.jlogstash.distributed.http.cilent.HttpClient.java
public static String post(String url, Map<String, Object> bodyData) { String responseBody = null;//w w w . jav a 2s .c om CloseableHttpClient httpClient = null; try { httpClient = getHttpClient(); HttpPost httPost = new HttpPost(url); if (SetTimeOut) { RequestConfig requestConfig = RequestConfig.custom().setSocketTimeout(SocketTimeout) .setConnectTimeout(ConnectTimeout).build();// httPost.setConfig(requestConfig); } if (bodyData != null && bodyData.size() > 0) { httPost.setEntity(new StringEntity(objectMapper.writeValueAsString(bodyData))); } //? CloseableHttpResponse response = httpClient.execute(httPost); int status = response.getStatusLine().getStatusCode(); if (status == HttpStatus.SC_OK) { HttpEntity entity = response.getEntity(); //FIXME ?header? responseBody = EntityUtils.toString(entity, Charsets.UTF_8); } else { logger.error("url:" + url + "--->http return status error:" + status); } } catch (Exception e) { logger.error("url:" + url + "--->http request error", e); } finally { try { if (httpClient != null) httpClient.close(); } catch (Exception e) { // TODO Auto-generated catch block logger.error(ExceptionUtil.getErrorMessage(e)); } } return responseBody; }
From source file:org.wuspba.ctams.ws.ITBandMemberController.java
private static void add(BandMember m) throws Exception { CTAMSDocument doc = new CTAMSDocument(); doc.getPeople().add(m.getPerson());/*from www .j ava 2s .com*/ doc.getBandMembers().add(m); 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); m.setId(doc.getBandMembers().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); } } } }