List of usage examples for org.apache.http.client.methods CloseableHttpResponse getStatusLine
StatusLine getStatusLine();
From source file:org.wuspba.ctams.ws.ITRosterController.java
private static void add(Roster roster) throws Exception { CTAMSDocument doc = new CTAMSDocument(); doc.getRosters().add(roster);//from w w w. jav a2s. com 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); roster.setId(doc.getRosters().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.event.LinkedInEvents.java
/** * Parse LinkedIn login response and login the user if possible. * /* ww w . j av a 2 s . com*/ * @return */ public static String parseLinkedInResponse(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_LINKEDIN_STATE))) { String errMsg = UtilProperties.getMessage(resource, "LinkedInFailedToMatchState", 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, "FailedToGetLinkedInAuthorizationCode", 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, "GetLinkedInAuthorizationCodeError", UtilHttp.getLocale(request)); } request.setAttribute("_ERROR_MESSAGE_", errMsg); return "error"; } // Debug.logInfo("LinkedIn authorization code: " + authorizationCode, module); GenericValue oauth2LinkedIn = getOAuth2LinkedInConfig(request); if (UtilValidate.isEmpty(oauth2LinkedIn)) { String errMsg = UtilProperties.getMessage(resource, "GetOAuth2LinkedInConfigError", UtilHttp.getLocale(request)); request.setAttribute("_ERROR_MESSAGE_", errMsg); return "error"; } String clientId = oauth2LinkedIn.getString(PassportUtil.ApiKeyLabel); String secret = oauth2LinkedIn.getString(PassportUtil.SecretKeyLabel); String returnURI = oauth2LinkedIn.getString(envPrefix + PassportUtil.ReturnUrlLabel); // Grant token from authorization code and oauth2 token // Use the authorization code to obtain an access token String accessToken = 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("grant_type", "authorization_code").setParameter("code", authorizationCode) .setParameter("redirect_uri", returnURI).build(); HttpPost postMethod = new HttpPost(uri); CloseableHttpClient jsonClient = HttpClients.custom().build(); // Debug.logInfo("LinkedIn get access token query string: " + postMethod.getURI(), module); postMethod.setConfig(PassportUtil.StandardRequestConfig); CloseableHttpResponse postResponse = jsonClient.execute(postMethod); String responseString = new BasicResponseHandler().handleResponse(postResponse); // Debug.logInfo("LinkedIn get access token response code: " + postResponse.getStatusLine().getStatusCode(), module); // Debug.logInfo("LinkedIn get access token response content: " + responseString, module); if (postResponse.getStatusLine().getStatusCode() == HttpStatus.SC_OK) { // Debug.logInfo("Json Response from LinkedIn: " + responseString, module); JSON jsonObject = JSON.from(responseString); JSONToMap jsonMap = new JSONToMap(); Map<String, Object> userMap = jsonMap.convert(jsonObject); accessToken = (String) userMap.get("access_token"); // Debug.logInfo("Generated Access Token : " + accessToken, module); } else { String errMsg = UtilProperties.getMessage(resource, "GetOAuth2LinkedInAccessTokenError", 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(TokenEndpoint + UserApiUri + "?oauth2_access_token=" + accessToken); Document userInfo = null; try { userInfo = LinkedInAuthenticator.getUserInfo(getMethod, UtilHttp.getLocale(request)); } catch (IOException e) { request.setAttribute("_ERROR_MESSAGE_", e.toString()); return "error"; } catch (AuthenticatorException e) { request.setAttribute("_ERROR_MESSAGE_", e.toString()); return "error"; } catch (SAXException e) { request.setAttribute("_ERROR_MESSAGE_", e.toString()); return "error"; } catch (ParserConfigurationException e) { request.setAttribute("_ERROR_MESSAGE_", e.toString()); return "error"; } finally { getMethod.releaseConnection(); } // Debug.logInfo("LinkedIn User Info:" + userInfo, module); // Store the user info and check login the user return checkLoginLinkedInUser(request, userInfo, accessToken); }
From source file:org.wuspba.ctams.ws.ITBandContestController.java
protected static void add() throws Exception { ITVenueController.add();/*from w w w . j av a 2 s. com*/ ITJudgeController.add(); ITHiredJudgeController.add(); CTAMSDocument doc = new CTAMSDocument(); doc.getVenues().add(TestFixture.INSTANCE.venue); doc.getJudges().add(TestFixture.INSTANCE.judgeAndy); doc.getJudges().add(TestFixture.INSTANCE.judgeJamie); doc.getJudges().add(TestFixture.INSTANCE.judgeBob); doc.getJudges().add(TestFixture.INSTANCE.judgeEoin); doc.getBandContests().add(TestFixture.INSTANCE.bandContest); String xml = XMLUtils.marshal(doc); CloseableHttpClient httpclient = HttpClients.createDefault(); URI uri = new URIBuilder().setScheme(PROTOCOL).setHost(HOST).setPort(PORT).setPath(ITVenueController.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.bandContest.setId(doc.getBandContests().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); } } } uri = new URIBuilder().setScheme(PROTOCOL).setHost(HOST).setPort(PORT).setPath(ITJudgeController.PATH) .build(); httpPost = new HttpPost(uri); xmlEntity = new StringEntity(xml, ContentType.APPLICATION_XML); response = null; try { httpPost.setEntity(xmlEntity); response = httpclient.execute(httpPost); 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); } } } uri = new URIBuilder().setScheme(PROTOCOL).setHost(HOST).setPort(PORT).setPath(PATH).build(); httpPost = new HttpPost(uri); xmlEntity = new StringEntity(xml, ContentType.APPLICATION_XML); 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.bandContest.setId(doc.getBandContests().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:httpServerClient.app.QuickStart.java
public static void getAllMessages(String[] args) throws Exception { // arguments to run Quick start: // args[0] GET // args[1] IPAddress of server // args[2] port No. CloseableHttpClient httpclient = HttpClients.createDefault(); JacksonObjectMapperToList myList = new JacksonObjectMapperToList(); try {/*from ww w . j ava 2s . com*/ HttpGet httpGet = new HttpGet("http://" + args[1] + ":" + args[2] + "/getAllMessages"); CloseableHttpResponse response1 = httpclient.execute(httpGet); // The underlying HTTP connection is still held by the response // object // to allow the response content to be streamed directly from the // network socket. // In order to ensure correct deallocation of system resources // the user MUST call CloseableHttpResponse#close() from a finally // clause. // Please note that if response content is not fully consumed the // underlying // connection cannot be safely re-used and will be shut down and // discarded // by the connection manager. try { System.out.println(response1.getStatusLine()); HttpEntity entity1 = response1.getEntity(); String result = EntityUtils.toString(entity1); /* * Vypisanie odpovede do konzoly a discard dat zo serveru. */ //myList.jsonToList(result); myList.jacksonToList(result); myList.PrintList(); EntityUtils.consume(entity1); } finally { response1.close(); } } finally { httpclient.close(); } }
From source file:httpServerClient.app.QuickStart.java
public static void sendMessage(String[] args) throws Exception { // arguments to run Quick start POST: // args[0] POST // args[1] IPAddress of server // args[2] port No. // args[3] user name // args[4] myMessage CloseableHttpClient httpclient = HttpClients.createDefault(); try {//w ww . j a v a 2 s. co m HttpPost httpPost = new HttpPost("http://" + args[1] + ":" + args[2] + "/sendMessage"); // httpPost.setEntity(new StringEntity("lubo je kral")); httpPost.setEntity( new StringEntity("{\"name\":\"" + args[3] + "\",\"myMessage\":\"" + args[4] + "\"}")); CloseableHttpResponse response1 = httpclient.execute(httpPost); // The underlying HTTP connection is still held by the response // object // to allow the response content to be streamed directly from the // network socket. // In order to ensure correct deallocation of system resources // the user MUST call CloseableHttpResponse#close() from a finally // clause. // Please note that if response content is not fully consumed the // underlying // connection cannot be safely re-used and will be shut down and // discarded // by the connection manager. try { System.out.println(response1.getStatusLine()); HttpEntity entity1 = response1.getEntity(); /* * Vypisanie odpovede do konzoly a discard dat zo serveru. */ System.out.println(EntityUtils.toString(entity1)); EntityUtils.consume(entity1); } finally { response1.close(); } } finally { httpclient.close(); } }
From source file:gda.util.ElogEntry.java
/** * Creates an ELog entry. Default ELog server is "http://rdb.pri.diamond.ac.uk/devl/php/elog/cs_logentryext_bl.php" * which is the development database. "http://rdb.pri.diamond.ac.uk/php/elog/cs_logentryext_bl.php" is the * production database. The java.properties file contains the property "gda.elog.targeturl" which can be set to be * either the development or production databases. * //from w w w .ja v a 2 s . com * @param title * The ELog title * @param content * The ELog content * @param userID * The user ID e.g. epics or gda or abc12345 * @param visit * The visit number * @param logID * The type of log book, The log book ID: Beam Lines: - BLB16, BLB23, BLI02, BLI03, BLI04, BLI06, BLI11, * BLI16, BLI18, BLI19, BLI22, BLI24, BLI15, DAG = Data Acquisition, EHC = Experimental Hall * Coordinators, OM = Optics and Meteorology, OPR = Operations, E * @param groupID * The group sending the ELog, DA = Data Acquisition, EHC = Experimental Hall Coordinators, OM = Optics * and Meteorology, OPR = Operations CS = Control Systems, GroupID Can also be a beam line, * @param fileLocations * The image file names with path to upload * @throws ELogEntryException */ public static void post(String title, String content, String userID, String visit, String logID, String groupID, String[] fileLocations) throws ELogEntryException { String targetURL = POST_UPLOAD_URL; try { String entryType = "41";// entry type is always a log (41) String titleForPost = visit == null ? title : "Visit: " + visit + " - " + title; MultipartEntityBuilder request = MultipartEntityBuilder.create().addTextBody("txtTITLE", titleForPost) .addTextBody("txtCONTENT", content).addTextBody("txtLOGBOOKID", logID) .addTextBody("txtGROUPID", groupID).addTextBody("txtENTRYTYPEID", entryType) .addTextBody("txtUSERID", userID); if (fileLocations != null) { for (int i = 1; i < fileLocations.length + 1; i++) { File targetFile = new File(fileLocations[i - 1]); request = request.addBinaryBody("userfile" + i, targetFile, ContentType.create("image/png"), targetFile.getName()); } } HttpEntity entity = request.build(); targetURL = LocalProperties.get("gda.elog.targeturl", POST_UPLOAD_URL); HttpPost httpPost = new HttpPost(targetURL); httpPost.setEntity(entity); CloseableHttpClient httpClient = HttpClients.createDefault(); CloseableHttpResponse response = httpClient.execute(httpPost); try { String responseString = EntityUtils.toString(response.getEntity()); System.out.println(responseString); if (!responseString.contains("New Log Entry ID")) { throw new ELogEntryException("Upload failed, status=" + response.getStatusLine().getStatusCode() + " response=" + responseString + " targetURL = " + targetURL + " titleForPost = " + titleForPost + " logID = " + logID + " groupID = " + groupID + " entryType = " + entryType + " userID = " + userID); } } finally { response.close(); httpClient.close(); } } catch (ELogEntryException e) { throw e; } catch (Exception e) { throw new ELogEntryException("Error in ELogger. Database:" + targetURL, e); } }
From source file:org.cloudsimulator.utility.RestAPI.java
public static ResponseMessageString sendString(final String requestMethod, final String restAPIURI, final String username, final String password, final String stringToSend, final String typeOfString, final String charset) throws IOException { CloseableHttpClient httpClient = HttpClients.createDefault(); CloseableHttpResponse httpResponse = null; ResponseMessageString responseMessageString = null; if ("PUT".equals(requestMethod)) { httpResponse = putRequestBasicAuth(httpClient, escapeURI(restAPIURI), username, password, typeOfString, new ByteArrayEntity(stringToSend.getBytes(charset))); }//from ww w . jav a 2 s.c om if ("POST".equals(requestMethod)) { httpResponse = postRequestBasicAuth(httpClient, escapeURI(restAPIURI), username, password, typeOfString, new ByteArrayEntity(stringToSend.getBytes(charset))); } if (httpResponse != null) { if (httpResponse.getStatusLine() != null) { if (httpResponse.getEntity() != null) { responseMessageString = new ResponseMessageString(httpResponse.getStatusLine().getStatusCode(), httpResponse.getStatusLine().getReasonPhrase(), IOUtils.toString(httpResponse.getEntity().getContent(), charset)); } else { responseMessageString = new ResponseMessageString(httpResponse.getStatusLine().getStatusCode(), httpResponse.getStatusLine().getReasonPhrase(), null); } } else { if (httpResponse.getEntity() != null) { responseMessageString = new ResponseMessageString(null, null, IOUtils.toString(httpResponse.getEntity().getContent(), charset)); } } httpResponse.close(); } httpClient.close(); return responseMessageString; }
From source file:org.sahli.asciidoc.confluence.publisher.client.http.ConfluenceRestClientTest.java
private static CloseableHttpClient recordHttpClientForSingleJsonAndStatusCodeResponse(String jsonResponse, int statusCode) throws IOException { CloseableHttpResponse httpResponseMock = mock(CloseableHttpResponse.class); HttpEntity httpEntityMock = recordHttpEntityForContent(jsonResponse); when(httpResponseMock.getEntity()).thenReturn(httpEntityMock); StatusLine statusLineMock = recordStatusLine(statusCode); when(httpResponseMock.getStatusLine()).thenReturn(statusLineMock); CloseableHttpClient httpClientMock = anyCloseableHttpClient(); when(httpClientMock.execute(any(HttpPost.class), any(HttpContext.class))).thenReturn(httpResponseMock); return httpClientMock; }
From source file:org.wuspba.ctams.ws.ITSoloContestController.java
protected static void add() throws Exception { ITVenueController.add();//from www. j a va 2 s .com ITHiredJudgeController.add(); ITJudgeController.add(); CTAMSDocument doc = new CTAMSDocument(); doc.getVenues().add(TestFixture.INSTANCE.venue); doc.getPeople().add(TestFixture.INSTANCE.andy); doc.getPeople().add(TestFixture.INSTANCE.jamie); doc.getPeople().add(TestFixture.INSTANCE.bob); doc.getPeople().add(TestFixture.INSTANCE.eoin); doc.getJudges().add(TestFixture.INSTANCE.judgeAndy); doc.getJudges().add(TestFixture.INSTANCE.judgeJamie); doc.getJudges().add(TestFixture.INSTANCE.judgeBob); doc.getJudges().add(TestFixture.INSTANCE.judgeEoin); doc.getHiredJudges().add(TestFixture.INSTANCE.hiredJudgeAndy); doc.getHiredJudges().add(TestFixture.INSTANCE.hiredJudgeJamie); doc.getHiredJudges().add(TestFixture.INSTANCE.hiredJudgeBob); doc.getHiredJudges().add(TestFixture.INSTANCE.hiredJudgeEoin); doc.getSoloContests().add(TestFixture.INSTANCE.soloContest); String xml = XMLUtils.marshal(doc); CloseableHttpClient httpclient = HttpClients.createDefault(); URI uri = new URIBuilder().setScheme(PROTOCOL).setHost(HOST).setPort(PORT).setPath(ITVenueController.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.soloContest.setId(doc.getSoloContests().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); } } } uri = new URIBuilder().setScheme(PROTOCOL).setHost(HOST).setPort(PORT).setPath(ITJudgeController.PATH) .build(); httpPost = new HttpPost(uri); xmlEntity = new StringEntity(xml, ContentType.APPLICATION_XML); response = null; try { httpPost.setEntity(xmlEntity); response = httpclient.execute(httpPost); 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); } } } uri = new URIBuilder().setScheme(PROTOCOL).setHost(HOST).setPort(PORT).setPath(PATH).build(); httpPost = new HttpPost(uri); xmlEntity = new StringEntity(xml, ContentType.APPLICATION_XML); 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.soloContest.setId(doc.getSoloContests().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:com.vmware.gemfire.tools.pulse.tests.junit.BaseServiceTest.java
/** * Login to pulse server and setup httpClient for tests * To be called from setupBeforeClass in each test class *///from w ww. ja v a 2 s . c om protected static void doLogin() throws Exception { System.out.println("BaseServiceTest :: Executing doLogin with user : admin, password : admin."); CloseableHttpResponse loginResponse = null; try { BasicCookieStore cookieStore = new BasicCookieStore(); httpclient = HttpClients.custom().setDefaultCookieStore(cookieStore).build(); HttpUriRequest login = RequestBuilder.post().setUri(new URI(LOGIN_URL)) .addParameter("j_username", "admin").addParameter("j_password", "admin").build(); loginResponse = httpclient.execute(login); try { HttpEntity entity = loginResponse.getEntity(); EntityUtils.consume(entity); System.out.println("BaseServiceTest :: HTTP request status : " + loginResponse.getStatusLine()); List<Cookie> cookies = cookieStore.getCookies(); if (cookies.isEmpty()) { } else { for (int i = 0; i < cookies.size(); i++) { } } } finally { if (loginResponse != null) loginResponse.close(); } } catch (Exception failed) { logException(failed); throw failed; } System.out.println("BaseServiceTest :: Executed doLogin"); }