List of usage examples for org.apache.http.message BasicHttpResponse getEntity
public HttpEntity getEntity()
From source file:com.msopentech.applicationgateway.connection.Router.java
/** * Performs HTTP GET request and retrieves proxy agents list. * /*w w w .j ava2 s . c o m*/ * @param traits Connection traits. * * @return {@link JSONArray} containing agents list. Returns <code>null</code> if exception is caught. Always provides error description if error occurs. */ private static JSONArray obtainAgents(ConnectionTraits traits) { try { if (traits == null || TextUtils.isEmpty(traits.token)) { String errorText = String.format(ERROR_AGENT, "Traits argument is null or does not contain valid token."); if (traits != null) { traits.setError(errorText); } else { traits = new ConnectionTraits(errorText); } return null; } HttpClient agentsClient = new DefaultHttpClient(); HttpGet agentsRequest = new HttpGet( EnterpriseBrowserActivity.CLOUD_CONNECTION_HOST_PREFIX + "user/agents"); agentsRequest.addHeader("X-Bhut-AuthN-Token", traits.token); BasicHttpResponse response = null; response = (BasicHttpResponse) agentsClient.execute(agentsRequest); HttpEntity responseEntity = response.getEntity(); InputStream responseStream = null; JSONObject responseObject = null; JSONArray agentsArray = null; responseStream = responseEntity.getContent(); BufferedReader responseReader = new BufferedReader(new InputStreamReader(responseStream)); String line; StringBuffer actualResponse = new StringBuffer(); while ((line = responseReader.readLine()) != null) { actualResponse.append(line); actualResponse.append('\r'); } responseObject = new JSONObject(actualResponse.toString()); agentsArray = responseObject.getJSONArray(JSON_AGENTS_KEY); if (agentsArray == null || agentsArray.length() <= 0) { traits.setError(String.format(ERROR_AGENT, "No connectors found.")); } else { return agentsArray; } } catch (final Exception e) { logError(e, Router.class.getSimpleName() + ".obtainConnectors() Failed"); traits.setError(String.format(ERROR_AGENT, "Connectors retrieval failed.")); } return null; }
From source file:com.msopentech.applicationgateway.connection.Router.java
/** * Performs HTTP POST request and obtains session ID. * /*from w ww . j a va 2 s . c om*/ * @param traits Connection traits. * @param agentIdJSON Selected proxy agent ID (in JSON string format) that will be used to route through all the requests. * * @return Session ID. Returns <code>null</code> if exception is caught. Always provides error description if error occurs. */ private static String obtainSession(ConnectionTraits traits, String agentIdJSON) { try { if (traits == null || TextUtils.isEmpty(traits.token)) { String errorText = String.format(ERROR_SESSION, "Traits argument is null or does not contain valid token."); if (traits != null) { traits.setError(errorText); } else { traits = new ConnectionTraits(errorText); } return null; } HttpClient sessionClient = new DefaultHttpClient(); HttpPost sessionRequest = new HttpPost( EnterpriseBrowserActivity.CLOUD_CONNECTION_HOST_PREFIX + "user/session"); sessionRequest.addHeader("x-bhut-authN-token", traits.token); StringEntity requestBody = null; requestBody = new StringEntity(agentIdJSON); requestBody.setContentType("application/json"); sessionRequest.setEntity(requestBody); BasicHttpResponse response = null; response = (BasicHttpResponse) sessionClient.execute(sessionRequest); HttpEntity responseEntity = response.getEntity(); InputStream responseStream = null; String result = null; responseStream = responseEntity.getContent(); BufferedReader responseReader = new BufferedReader(new InputStreamReader(responseStream)); String line; StringBuffer actualResponse = new StringBuffer(); while ((line = responseReader.readLine()) != null) { actualResponse.append(line); actualResponse.append('\r'); } result = actualResponse.toString(); JSONObject session = null; session = new JSONObject(result); result = session.getString(JSON_SESSION_ID_KEY); if (TextUtils.isEmpty(result)) { traits.setError(String.format(ERROR_SESSION, "Session is null or empty.")); } else { traits.setSession(result); return result; } } catch (final Exception e) { logError(e, Router.class.getSimpleName() + ".obtainSession() Failed"); traits.setError(String.format(ERROR_SESSION, "Session retrieval failed.")); } return null; }
From source file:com.msopentech.applicationgateway.connection.Router.java
/** * Performs HTTP POST request and obtains authentication token. * //from ww w .jav a2s . com * @param credentials Authentication credentials * * @return {@link ConnectionTraits} with valid token OR with an error message if exception is caught or token retrieval failed or * token is <code>null</code> or an empty string. Does NOT return <code>null</code>. */ private static ConnectionTraits obtainToken(Credentials credentials) { ConnectionTraits connection = new ConnectionTraits(); try { HttpClient client = new DefaultHttpClient(); HttpPost request = new HttpPost("https://login.microsoftonline.com/extSTS.srf"); request.addHeader("SOAPAction", "http://docs.oasis-open.org/ws-sx/ws-trust/200512/RST/Issue"); request.addHeader("Content-Type", "application/soap+xml; charset=utf-8"); Date now = new Date(); DateFormat df = new SimpleDateFormat("yyyy-MM-dd'T'HH:mm:ss.sssZ"); String nowAsString = df.format(now); Calendar calendar = Calendar.getInstance(); calendar.setTime(now); calendar.add(Calendar.SECOND, 10 * 60); Date expires = calendar.getTime(); String expirationAsString = df.format(expires); String message = requestTemplate; message = message.replace("#{user}", credentials.getUsername()); message = message.replace("#{pass}", credentials.getPassword()); message = message.replace("#{created}", nowAsString); message = message.replace("#{expires}", expirationAsString); message = message.replace("#{resource}", "appgportal.cloudapp.net"); StringEntity requestBody = new StringEntity(message, HTTP.UTF_8); requestBody.setContentType("text/xml"); request.setEntity(requestBody); BasicHttpResponse response = null; response = (BasicHttpResponse) client.execute(request); HttpEntity entity = response.getEntity(); InputStream inputStream = null; String token = null; inputStream = entity.getContent(); BufferedReader reader = new BufferedReader(new InputStreamReader(inputStream)); String line; StringBuffer actualResponse = new StringBuffer(); while ((line = reader.readLine()) != null) { actualResponse.append(line); actualResponse.append('\r'); } token = actualResponse.toString(); String start = "<wst:RequestedSecurityToken>"; int index = token.indexOf(start); if (-1 == index) { DocumentBuilderFactory documentFactory = DocumentBuilderFactory.newInstance(); DocumentBuilder documentBuilder = documentFactory.newDocumentBuilder(); InputStream errorInputStream = new ByteArrayInputStream(token.getBytes()); Document currentDoc = documentBuilder.parse(errorInputStream); if (currentDoc == null) { return null; } String errorReason = null; String errorExplained = null; Node rootNode = null; if ((rootNode = currentDoc.getFirstChild()) != null && /* <S:Envelope> */ (rootNode = XmlUtility.getChildNode(rootNode, "S:Body")) != null && (rootNode = XmlUtility.getChildNode(rootNode, "S:Fault")) != null) { Node node = null; if ((node = XmlUtility.getChildNode(rootNode, "S:Reason")) != null) { errorReason = XmlUtility.getChildNodeValue(node, "S:Text"); } if ((node = XmlUtility.getChildNode(rootNode, "S:Detail")) != null && (node = XmlUtility.getChildNode(node, "psf:error")) != null && (node = XmlUtility.getChildNode(node, "psf:internalerror")) != null) { errorExplained = XmlUtility.getChildNodeValue(node, "psf:text"); } } if (!TextUtils.isEmpty(errorReason) && !TextUtils.isEmpty(errorExplained)) { logError(null, Router.class.getSimpleName() + ".obtainToken(): " + errorReason + " - " + errorExplained); connection.setError(String.format(ERROR_TOKEN, errorReason + ": " + errorExplained)); return connection; } } else { token = token.substring(index); String end = "</wst:RequestedSecurityToken>"; index = token.indexOf(end) + end.length(); token = token.substring(0, index); if (!TextUtils.isEmpty(token)) { connection.setToken(token); return connection; } } } catch (final Exception e) { logError(e, Router.class.getSimpleName() + ".obtainToken() Failed"); return connection.setError(String.format(ERROR_TOKEN, "Token retrieval failed with exception.")); } return connection.setError(String.format(ERROR_TOKEN, "Token retrieval failed.")); }
From source file:org.apache.hadoop.gateway.rm.dispatch.RMHaDispatchTest.java
@Test public void testConnectivityFailover() throws Exception { String serviceName = "RESOURCEMANAGER"; HaDescriptor descriptor = HaDescriptorFactory.createDescriptor(); descriptor.addServiceConfig(//from w ww . j a va2s .co m HaDescriptorFactory.createServiceConfig(serviceName, "true", "1", "1000", "2", "1000", null, null)); HaProvider provider = new DefaultHaProvider(descriptor); URI uri1 = new URI("http://passive-host"); URI uri2 = new URI("http://other-host"); URI uri3 = new URI("http://active-host"); ArrayList<String> urlList = new ArrayList<>(); urlList.add(uri1.toString()); urlList.add(uri2.toString()); urlList.add(uri3.toString()); provider.addHaService(serviceName, urlList); FilterConfig filterConfig = EasyMock.createNiceMock(FilterConfig.class); ServletContext servletContext = EasyMock.createNiceMock(ServletContext.class); EasyMock.expect(filterConfig.getServletContext()).andReturn(servletContext).anyTimes(); EasyMock.expect(servletContext.getAttribute(HaServletContextListener.PROVIDER_ATTRIBUTE_NAME)) .andReturn(provider).anyTimes(); BasicHttpResponse inboundResponse = EasyMock.createNiceMock(BasicHttpResponse.class); EasyMock.expect(inboundResponse.getStatusLine()).andReturn(getStatusLine()).anyTimes(); EasyMock.expect(inboundResponse.getEntity()).andReturn(getResponseEntity()).anyTimes(); EasyMock.expect(inboundResponse.getFirstHeader(LOCATION)).andReturn(getFirstHeader(uri3.toString())) .anyTimes(); BasicHttpParams params = new BasicHttpParams(); HttpUriRequest outboundRequest = EasyMock.createNiceMock(HttpRequestBase.class); EasyMock.expect(outboundRequest.getMethod()).andReturn("GET").anyTimes(); EasyMock.expect(outboundRequest.getURI()).andReturn(uri1).anyTimes(); EasyMock.expect(outboundRequest.getParams()).andReturn(params).anyTimes(); HttpServletRequest inboundRequest = EasyMock.createNiceMock(HttpServletRequest.class); EasyMock.expect(inboundRequest.getRequestURL()).andReturn(new StringBuffer(uri2.toString())).once(); EasyMock.expect(inboundRequest.getAttribute("dispatch.ha.failover.counter")).andReturn(new AtomicInteger(0)) .once(); EasyMock.expect(inboundRequest.getAttribute("dispatch.ha.failover.counter")).andReturn(new AtomicInteger(1)) .once(); HttpServletResponse outboundResponse = EasyMock.createNiceMock(HttpServletResponse.class); EasyMock.expect(outboundResponse.getOutputStream()).andAnswer(new IAnswer<ServletOutputStream>() { @Override public ServletOutputStream answer() throws Throwable { return new ServletOutputStream() { @Override public void write(int b) throws IOException { throw new IOException("unreachable-host"); } @Override public void setWriteListener(WriteListener arg0) { } @Override public boolean isReady() { return false; } }; } }).once(); Assert.assertEquals(uri1.toString(), provider.getActiveURL(serviceName)); EasyMock.replay(filterConfig, servletContext, inboundResponse, outboundRequest, inboundRequest, outboundResponse); RMHaDispatch dispatch = new RMHaDispatch(); dispatch.setHttpClient(new DefaultHttpClient()); dispatch.setHaProvider(provider); dispatch.init(); long startTime = System.currentTimeMillis(); try { dispatch.setInboundResponse(inboundResponse); dispatch.executeRequest(outboundRequest, inboundRequest, outboundResponse); } catch (IOException e) { //this is expected after the failover limit is reached } Assert.assertEquals(uri3.toString(), dispatch.getUriFromInbound(inboundRequest, inboundResponse, null).toString()); long elapsedTime = System.currentTimeMillis() - startTime; Assert.assertEquals(uri3.toString(), provider.getActiveURL(serviceName)); //test to make sure the sleep took place Assert.assertTrue(elapsedTime > 1000); }
From source file:ch.scythe.hsr.api.TimeTableAPI.java
private void updateCache(String dateString, Date cacheTimestamp, String login, String password) throws RequestException, ServerConnectionException, ResponseParseException, AccessDeniedException { Log.i(LOGGING_TAG, "Starting to read data from the server."); long before = System.currentTimeMillis(); try {/* w w w . ja va 2 s . c o m*/ HttpGet get = createHttpGet(URL + METHOD_GET_TIMETABLE + login, login, password); HttpClient httpclient = new DefaultHttpClient(); BasicHttpResponse httpResponse = (BasicHttpResponse) httpclient.execute(get); InputStream jsonStream = null; int httpStatus = httpResponse.getStatusLine().getStatusCode(); if (httpStatus == HttpStatus.SC_OK) { jsonStream = httpResponse.getEntity().getContent(); } else if (httpStatus == HttpStatus.SC_UNAUTHORIZED) { throw new AccessDeniedException(); } else { throw new RequestException("Request not successful. \nHTTP Status: " + httpStatus); } Log.i(LOGGING_TAG, "Finished reading from server."); // convert JSON to Java objects JsonTimetableWeek serverData = new GsonParser().parse(jsonStream); UiWeek uiWeek = DataAssembler.convert(serverData); // open streams to cache the files DataOutputStream cacheTimestampOutputStream = new DataOutputStream( context.openFileOutput(TIMETABLE_CACHE_TIMESTAMP, Context.MODE_PRIVATE)); FileOutputStream xmlCacheOutputStream = context.openFileOutput(TIMETABLE_CACHE_SERIALIZED, Context.MODE_PRIVATE); // write data to streams ObjectOutputStream out = new ObjectOutputStream(xmlCacheOutputStream); out.writeObject(uiWeek); cacheTimestampOutputStream.writeLong(new Date().getTime()); safeCloseStream(xmlCacheOutputStream); safeCloseStream(cacheTimestampOutputStream); } catch (UnsupportedEncodingException e) { throw new RequestException(e); } catch (IllegalStateException e) { throw new RequestException(e); } catch (IOException e) { throw new ServerConnectionException(e); } Log.i(LOGGING_TAG, "Read and parsed data from the server in " + (System.currentTimeMillis() - before) + "ms."); }
From source file:com.netscape.certsrv.client.PKIConnection.java
public void storeResponse(File file, HttpResponse response) throws IOException { try (PrintStream out = new PrintStream(file)) { out.println(response.getStatusLine()); for (Header header : response.getAllHeaders()) { out.println(header.getName() + ": " + header.getValue()); }//ww w . j a v a 2s . c o m out.println(); if (response instanceof BasicHttpResponse) { BasicHttpResponse basicResponse = (BasicHttpResponse) response; HttpEntity entity = basicResponse.getEntity(); if (entity == null) return; if (!entity.isRepeatable()) { BufferedHttpEntity bufferedEntity = new BufferedHttpEntity(entity); basicResponse.setEntity(bufferedEntity); entity = bufferedEntity; } storeEntity(out, entity); } } }
From source file:com.nxt.zyl.data.volley.toolbox.HurlStack.java
@Override public HttpResponse performRequest(Request<?> request, Map<String, String> additionalHeaders) throws IOException, AuthFailureError { String url = request.getUrl(); HashMap<String, String> map = new HashMap<String, String>(); // chenbo add gzip support,new user-agent if (request.isShouldGzip()) { map.put(HEADER_ACCEPT_ENCODING, ENCODING_GZIP); }/*w w w . j av a 2s.c o m*/ map.put(USER_AGENT, mUserAgent); // end map.putAll(request.getHeaders()); map.putAll(additionalHeaders); if (mUrlRewriter != null) { String rewritten = mUrlRewriter.rewriteUrl(url); if (rewritten == null) { throw new IOException("URL blocked by rewriter: " + url); } url = rewritten; } URL parsedUrl = new URL(url); HttpURLConnection connection = openConnection(parsedUrl, request); for (String headerName : map.keySet()) { connection.addRequestProperty(headerName, map.get(headerName)); } // if (request instanceof MultiPartRequest) { // setConnectionParametersForMultipartRequest(connection, request); // } else { // } setConnectionParametersForRequest(connection, request); // Initialize HttpResponse with data from the HttpURLConnection. ProtocolVersion protocolVersion = new ProtocolVersion("HTTP", 1, 1); int responseCode = connection.getResponseCode(); if (responseCode == -1) { // -1 is returned by getResponseCode() if the response code could not be retrieved. // Signal to the caller that something was wrong with the connection. throw new IOException("Could not retrieve response code from HttpUrlConnection."); } StatusLine responseStatus = new BasicStatusLine(protocolVersion, connection.getResponseCode(), connection.getResponseMessage()); BasicHttpResponse response = new BasicHttpResponse(responseStatus); response.setEntity(entityFromConnection(connection)); for (Entry<String, List<String>> header : connection.getHeaderFields().entrySet()) { if (header.getKey() != null) { Header h = new BasicHeader(header.getKey(), header.getValue().get(0)); response.addHeader(h); } } if (ENCODING_GZIP.equalsIgnoreCase(connection.getContentEncoding())) { response.setEntity(new InflatingEntity(response.getEntity())); } return response; }
From source file:org.elasticsearch.client.RequestLoggerTests.java
public void testTraceResponse() throws IOException { ProtocolVersion protocolVersion = new ProtocolVersion("HTTP", 1, 1); int statusCode = randomIntBetween(200, 599); String reasonPhrase = "REASON"; BasicStatusLine statusLine = new BasicStatusLine(protocolVersion, statusCode, reasonPhrase); String expected = "# " + statusLine.toString(); BasicHttpResponse httpResponse = new BasicHttpResponse(statusLine); int numHeaders = randomIntBetween(0, 3); for (int i = 0; i < numHeaders; i++) { httpResponse.setHeader("header" + i, "value"); expected += "\n# header" + i + ": value"; }//from w w w . ja va 2s . co m expected += "\n#"; boolean hasBody = getRandom().nextBoolean(); String responseBody = "{\n \"field\": \"value\"\n}"; if (hasBody) { expected += "\n# {"; expected += "\n# \"field\": \"value\""; expected += "\n# }"; HttpEntity entity; switch (randomIntBetween(0, 2)) { case 0: entity = new StringEntity(responseBody, ContentType.APPLICATION_JSON); break; case 1: //test a non repeatable entity entity = new InputStreamEntity( new ByteArrayInputStream(responseBody.getBytes(StandardCharsets.UTF_8)), ContentType.APPLICATION_JSON); break; case 2: // Evil entity without a charset entity = new StringEntity(responseBody, ContentType.create("application/json", (Charset) null)); break; default: throw new UnsupportedOperationException(); } httpResponse.setEntity(entity); } String traceResponse = RequestLogger.buildTraceResponse(httpResponse); assertThat(traceResponse, equalTo(expected)); if (hasBody) { //check that the body is still readable as most entities are not repeatable String body = EntityUtils.toString(httpResponse.getEntity(), StandardCharsets.UTF_8); assertThat(body, equalTo(responseBody)); } }
From source file:water.ga.GoogleAnalytics.java
@SuppressWarnings({ "rawtypes" }) public GoogleAnalyticsResponse post(GoogleAnalyticsRequest request) { GoogleAnalyticsResponse response = new GoogleAnalyticsResponse(); if (!config.isEnabled()) { return response; }// w w w .j a v a 2s. co m BasicHttpResponse httpResponse = null; try { List<NameValuePair> postParms = new ArrayList<NameValuePair>(); //Log.debug("GA Processing " + request); //Process the parameters processParameters(request, postParms); //Process custom dimensions processCustomDimensionParameters(request, postParms); //Process custom metrics processCustomMetricParameters(request, postParms); //Log.debug("GA Processed all parameters and sending the request " + postParms); HttpPost httpPost = new HttpPost(config.getUrl()); try { httpPost.setEntity(new UrlEncodedFormEntity(postParms, "UTF-8")); } catch (UnsupportedEncodingException e) { Log.warn("This systems doesn't support UTF-8!"); } try { httpResponse = (BasicHttpResponse) httpClient.execute(httpPost); } catch (ClientProtocolException e) { //Log.trace("GA connectivity had a problem or the connectivity was aborted. "+e.toString()); } catch (IOException e) { //Log.trace("GA connectivity suffered a protocol error. "+e.toString()); } //Log.debug("GA response: " +httpResponse.toString()); response.setStatusCode(httpResponse.getStatusLine().getStatusCode()); response.setPostedParms(postParms); try { EntityUtils.consume(httpResponse.getEntity()); } catch (IOException e) { /*consume quietly*/} if (config.isGatherStats()) { gatherStats(request); } } catch (Exception e) { if (e instanceof UnknownHostException) { //Log.trace("Coudln't connect to GA. Internet may not be available. " + e.toString()); } else { //Log.trace("Exception while sending the GA tracker request: " + request +". "+ e.toString()); } } return response; }