List of usage examples for org.apache.commons.httpclient.methods StringRequestEntity getContent
public String getContent()
From source file:com.zimbra.cs.index.elasticsearch.ElasticSearchConnector.java
public int executeMethod(HttpMethod method) throws IndexStoreException, IOException { String reqBody = ""; if (ZimbraLog.elasticsearch.isTraceEnabled() && method instanceof EntityEnclosingMethod) { EntityEnclosingMethod eem = (EntityEnclosingMethod) method; RequestEntity re = eem.getRequestEntity(); if (re instanceof StringRequestEntity) { StringRequestEntity sre = (StringRequestEntity) re; reqBody = Strings.nullToEmpty(sre.getContent()); if (reqBody.length() > 0) { reqBody = String.format("\nREQUEST BODY=%s", reqBody); }/* www . j a v a 2s . c om*/ } } try { HttpClient client = ZimbraHttpConnectionManager.getInternalHttpConnMgr().newHttpClient(); statusCode = client.executeMethod(method); } catch (ConnectException ce) { throw new ZimbraElasticSearchDownException(ce); } catch (NoHttpResponseException nhre) { // managed to connect to the ElasticSearch service but it either crashed or timed out before // we got sent back the response. // Could be a temporary problem or a problem with this particular request. // In the longer term we need to track failures related to particular items at a higher level and discard // them after retrying a number of times. throw new ZimbraElasticSearchNoResponseException(nhre); } body = method.getResponseBodyAsString(); ZimbraLog.elasticsearch.trace("ElasticSearch request:%s %s - statusCode=%d%s\nRESPONSE BODY=%s", method.getName(), method.getURI(), statusCode, reqBody, body); return statusCode; }
From source file:com.baidu.oped.apm.profiler.modifier.connector.httpclient3.interceptor.ExecuteInterceptor.java
private String readString(StringRequestEntity entity) { return StringUtils.drop(entity.getContent(), MAX_READ_SIZE); }
From source file:com.wso2telco.openidtokenbuilder.MIFEOpenIDTokenBuilder.java
/** * Gets the ACR app id./* w ww.j a v a2 s.co m*/ * * @param applicationName the application name * @return the ACR app id * @throws IdentityOAuth2Exception the identity o auth2 exception */ public String getACRAppID(String applicationName) throws IdentityOAuth2Exception { StringBuilder requestURLBuilder = new StringBuilder(); requestURLBuilder.append(ACR_HOST_URI); requestURLBuilder.append("/"); //$NON-NLS-1$ requestURLBuilder.append(APP_PROV_SERVICE); requestURLBuilder.append("/"); //$NON-NLS-1$ requestURLBuilder.append(SERVICE_PROVIDER); String requestURL = requestURLBuilder.toString(); JSONObject requestBody = new JSONObject(); JSONObject createRequest = null; try { requestBody.put("appName", applicationName); //$NON-NLS-1$ requestBody.put("serviceProviderAppId", applicationName); //$NON-NLS-1$ requestBody.put("description", applicationName + " description"); //$NON-NLS-1$ //$NON-NLS-2$ createRequest = new JSONObject().put("provisionAppRequest", requestBody); //$NON-NLS-1$ StringRequestEntity requestEntity = new StringRequestEntity(createRequest.toString(), "application/json", "UTF-8"); //$NON-NLS-1$ //$NON-NLS-2$ PostMethod postMethod = new PostMethod(requestURL); postMethod.addRequestHeader("Authorization-ACR", "ServiceKey " + SERVICE_KEY); //$NON-NLS-1$ //$NON-NLS-2$ postMethod.addRequestHeader("Authorization", "Bearer " + ACR_ACCESS_TOKEN); //$NON-NLS-1$ //$NON-NLS-2$ postMethod.setRequestEntity(requestEntity); if (DEBUG) { log.debug("Connecting to ACR engine @ " + ACR_HOST_URI); //$NON-NLS-1$ log.debug("Service name : " + APP_PROV_SERVICE); //$NON-NLS-1$ log.debug("Service provider : " + SERVICE_PROVIDER); //$NON-NLS-1$ log.debug("Request - ACR app : " + requestEntity.getContent()); //$NON-NLS-1$ } httpClient = new HttpClient(); httpClient.executeMethod(postMethod); String responseACRApp = new String(postMethod.getResponseBody(), "UTF-8"); //$NON-NLS-1$ String strACR = ""; //$NON-NLS-1$ if (null != responseACRApp && !"".equals(responseACRApp)) { //$NON-NLS-1$ try { if (DEBUG) { log.debug("Response - ACR app : " + responseACRApp); //$NON-NLS-1$ } strACR = JsonPath.read(responseACRApp, "$.provisionAppResponse.appID"); //$NON-NLS-1$ } catch (Exception e) { log.error("Provisioning of ACR app failed", e); //$NON-NLS-1$ throw new IdentityOAuth2Exception("Provisioning of ACR app failed", e); //$NON-NLS-1$ } } return strACR; //$NON-NLS-1$; } catch (UnsupportedEncodingException e) { log.error("Error occured while creating request", e); //$NON-NLS-1$ throw new IdentityOAuth2Exception("Error occured while creating request", e); //$NON-NLS-1$ } catch (JSONException e) { log.error("Error occured while creating request", e); //$NON-NLS-1$ throw new IdentityOAuth2Exception("Error occured while creating request", e); //$NON-NLS-1$ } catch (HttpException e) { log.error("Error occured while creating ACR app", e); //$NON-NLS-1$ throw new IdentityOAuth2Exception("Error occured while creating ACR app", e); //$NON-NLS-1$ } catch (IOException e) { log.error("Error occured while creating ACR app", e); //$NON-NLS-1$ throw new IdentityOAuth2Exception("Error occured while creating ACR app", e); //$NON-NLS-1$ } }
From source file:com.wso2telco.openidtokenbuilder.MIFEOpenIDTokenBuilder.java
/** * Creates the acr./*ww w. j a va2 s. c o m*/ * * @param msisdn the msisdn * @return the string * @throws IdentityOAuth2Exception the identity o auth2 exception */ public String createACR(String msisdn) throws IdentityOAuth2Exception { StringBuilder requestURLBuilder = new StringBuilder(); requestURLBuilder.append(ACR_HOST_URI); requestURLBuilder.append("/"); //$NON-NLS-1$ requestURLBuilder.append(CREATE_SERVICE); requestURLBuilder.append("/"); //$NON-NLS-1$ requestURLBuilder.append(SERVICE_PROVIDER); requestURLBuilder.append("/"); //$NON-NLS-1$ requestURLBuilder.append(acrAppID); String requestURL = requestURLBuilder.toString(); JSONObject requestBody = new JSONObject(); JSONObject createRequest = null; try { requestBody.put("MSISDN", (Object) new JSONArray().put(msisdn)); //$NON-NLS-1$ createRequest = new JSONObject().put("createAcrRequest", requestBody); //$NON-NLS-1$ StringRequestEntity requestEntity = new StringRequestEntity(createRequest.toString(), "application/json", "UTF-8"); //$NON-NLS-1$ //$NON-NLS-2$ PostMethod postMethod = new PostMethod(requestURL); postMethod.addRequestHeader("Authorization-ACR", "ServiceKey " + SERVICE_KEY); //$NON-NLS-1$ //$NON-NLS-2$ postMethod.addRequestHeader("Authorization", "Bearer " + ACR_ACCESS_TOKEN); //$NON-NLS-1$ //$NON-NLS-2$ postMethod.setRequestEntity(requestEntity); if (DEBUG) { log.debug("Connecting to ACR engine @ " + ACR_HOST_URI); //$NON-NLS-1$ log.debug("Service name : " + CREATE_SERVICE); //$NON-NLS-1$ log.debug("Service provider : " + SERVICE_PROVIDER); //$NON-NLS-1$ log.debug("App key : " + acrAppID); //$NON-NLS-1$ log.debug("Request - create ACR : " + requestEntity.getContent()); //$NON-NLS-1$ } httpClient = new HttpClient(); httpClient.executeMethod(postMethod); return new String(postMethod.getResponseBody(), "UTF-8"); //$NON-NLS-1$ } catch (UnsupportedEncodingException e) { log.error("Error occured while creating request", e); //$NON-NLS-1$ throw new IdentityOAuth2Exception("Error occured while creating request", e); //$NON-NLS-1$ } catch (JSONException e) { log.error("Error occured while creating request", e); //$NON-NLS-1$ throw new IdentityOAuth2Exception("Error occured while creating request", e); //$NON-NLS-1$ } catch (HttpException e) { log.error("Error occured while creating ACR", e); //$NON-NLS-1$ throw new IdentityOAuth2Exception("Error occured while creating ACR", e); //$NON-NLS-1$ } catch (IOException e) { log.error("Error occured while creating ACR", e); //$NON-NLS-1$ throw new IdentityOAuth2Exception("Error occured while creating ACR", e); //$NON-NLS-1$ } }
From source file:com.wso2telco.openidtokenbuilder.MIFEOpenIDTokenBuilder.java
/** * Retrieve acr./*from w w w . ja v a 2s .c o m*/ * * @param msisdn the msisdn * @return the string * @throws IdentityOAuth2Exception the identity o auth2 exception */ public String retrieveACR(String msisdn) throws IdentityOAuth2Exception { StringBuilder requestURLBuilder = new StringBuilder(); requestURLBuilder.append(ACR_HOST_URI); requestURLBuilder.append("/"); //$NON-NLS-1$ requestURLBuilder.append(RETRIEVE_SERVICE); requestURLBuilder.append("/"); //$NON-NLS-1$ requestURLBuilder.append(SERVICE_PROVIDER); requestURLBuilder.append("/"); //$NON-NLS-1$ requestURLBuilder.append(acrAppID); String requestURL = requestURLBuilder.toString(); JSONObject requestBody = new JSONObject(); JSONObject retrieveRequest = null; try { requestBody.put("MSISDN", msisdn); //$NON-NLS-1$ retrieveRequest = new JSONObject().put("retriveAcrRequest", requestBody); //$NON-NLS-1$ StringRequestEntity requestEntity = new StringRequestEntity(retrieveRequest.toString(), "application/json", "UTF-8"); //$NON-NLS-1$ //$NON-NLS-2$ PostMethod postMethod = new PostMethod(requestURL); postMethod.addRequestHeader(new Header("Authorization-ACR", "ServiceKey " + SERVICE_KEY)); //$NON-NLS-1$ // $NON-NLS-2$ postMethod.addRequestHeader("Authorization", "Bearer " + ACR_ACCESS_TOKEN); //$NON-NLS-1$ //$NON-NLS-2$ postMethod.setRequestEntity(requestEntity); if (DEBUG) { log.debug("Connecting to ACR engine @ " + ACR_HOST_URI); //$NON-NLS-1$ log.debug("Service name : " + RETRIEVE_SERVICE); //$NON-NLS-1$ log.debug("Service provider : " + SERVICE_PROVIDER); //$NON-NLS-1$ log.debug("App key : " + acrAppID); //$NON-NLS-1$ log.debug("Request - retrieve ACR : " + requestEntity.getContent()); //$NON-NLS-1$ } httpClient = new HttpClient(); httpClient.executeMethod(postMethod); return new String(postMethod.getResponseBody(), "UTF-8"); //$NON-NLS-1$ } catch (UnsupportedEncodingException e) { log.error("Error occured while creating request", e); //$NON-NLS-1$ throw new IdentityOAuth2Exception("Error occured while creating request", e); //$NON-NLS-1$ } catch (JSONException e) { log.error("Error occured while creating request", e); //$NON-NLS-1$ throw new IdentityOAuth2Exception("Error occured while creating request", e); //$NON-NLS-1$ } catch (HttpException e) { log.error("Error occured while retrieving ACR", e); //$NON-NLS-1$ throw new IdentityOAuth2Exception("Error occured while retrieving ACR", e); //$NON-NLS-1$ } catch (IOException e) { log.error("Error occured while retrieving ACR", e); //$NON-NLS-1$ throw new IdentityOAuth2Exception("Error occured while retrieving ACR", e); //$NON-NLS-1$ } }
From source file:org.alfresco.repo.remoteconnector.RemoteConnectorServiceImpl.java
/** * Executes the specified request, and return the response *//*from ww w .ja v a 2 s . co m*/ public RemoteConnectorResponse executeRequest(RemoteConnectorRequest request) throws IOException, AuthenticationException, RemoteConnectorClientException, RemoteConnectorServerException { RemoteConnectorRequestImpl reqImpl = (RemoteConnectorRequestImpl) request; HttpMethodBase httpRequest = reqImpl.getMethodInstance(); // Attach the headers to the request for (Header hdr : request.getRequestHeaders()) { httpRequest.addRequestHeader(hdr); } // Attach the body, if possible if (httpRequest instanceof EntityEnclosingMethod) { if (request.getRequestBody() != null) { ((EntityEnclosingMethod) httpRequest).setRequestEntity(reqImpl.getRequestBody()); } } // Grab our thread local HttpClient instance // Remember - we must then clean it up! HttpClient httpClient = HttpClientHelper.getHttpClient(); // The url should already be vetted by the RemoteConnectorRequest URL url = new URL(request.getURL()); // Use the appropriate Proxy Host if required if (httpProxyHost != null && url.getProtocol().equals("http") && requiresProxy(url.getHost())) { httpClient.getHostConfiguration().setProxyHost(httpProxyHost); if (logger.isDebugEnabled()) logger.debug(" - using HTTP proxy host for: " + url); if (httpProxyCredentials != null) { httpClient.getState().setProxyCredentials(httpAuthScope, httpProxyCredentials); if (logger.isDebugEnabled()) logger.debug(" - using HTTP proxy credentials for proxy: " + httpProxyHost.getHostName()); } } else if (httpsProxyHost != null && url.getProtocol().equals("https") && requiresProxy(url.getHost())) { httpClient.getHostConfiguration().setProxyHost(httpsProxyHost); if (logger.isDebugEnabled()) logger.debug(" - using HTTPS proxy host for: " + url); if (httpsProxyCredentials != null) { httpClient.getState().setProxyCredentials(httpsAuthScope, httpsProxyCredentials); if (logger.isDebugEnabled()) logger.debug(" - using HTTPS proxy credentials for proxy: " + httpsProxyHost.getHostName()); } } else { //host should not be proxied remove any configured proxies httpClient.getHostConfiguration().setProxyHost(null); httpClient.getState().clearProxyCredentials(); } // Log what we're doing if (logger.isDebugEnabled()) { logger.debug("Performing " + request.getMethod() + " request to " + request.getURL()); for (Header hdr : request.getRequestHeaders()) { logger.debug("Header: " + hdr); } Object requestBody = null; if (request != null) { requestBody = request.getRequestBody(); } if (requestBody != null && requestBody instanceof StringRequestEntity) { StringRequestEntity re = (StringRequestEntity) request.getRequestBody(); logger.debug("Payload (string): " + re.getContent()); } else if (requestBody != null && requestBody instanceof ByteArrayRequestEntity) { ByteArrayRequestEntity re = (ByteArrayRequestEntity) request.getRequestBody(); logger.debug("Payload (byte array): " + re.getContent().toString()); } else { logger.debug("Payload is not of a readable type."); } } // Perform the request, and wrap the response int status = -1; String statusText = null; RemoteConnectorResponse response = null; try { status = httpClient.executeMethod(httpRequest); statusText = httpRequest.getStatusText(); Header[] responseHdrs = httpRequest.getResponseHeaders(); Header responseContentTypeH = httpRequest .getResponseHeader(RemoteConnectorRequestImpl.HEADER_CONTENT_TYPE); String responseCharSet = httpRequest.getResponseCharSet(); String responseContentType = (responseContentTypeH != null ? responseContentTypeH.getValue() : null); if (logger.isDebugEnabled()) { logger.debug( "response url=" + request.getURL() + ", length =" + httpRequest.getResponseContentLength() + ", responceContentType " + responseContentType + ", statusText =" + statusText); } // Decide on how best to handle the response, based on the size // Ideally, we want to close the HttpClient resources immediately, but // that isn't possible for very large responses // If we can close immediately, it makes cleanup simpler and fool-proof if (httpRequest.getResponseContentLength() > MAX_BUFFER_RESPONSE_SIZE || httpRequest.getResponseContentLength() == -1) { if (logger.isTraceEnabled()) { logger.trace("large response (or don't know length) url=" + request.getURL()); } // Need to wrap the InputStream in something that'll close InputStream wrappedStream = new HttpClientReleasingInputStream(httpRequest); httpRequest = null; // Now build the response response = new RemoteConnectorResponseImpl(request, responseContentType, responseCharSet, status, responseHdrs, wrappedStream); } else { if (logger.isTraceEnabled()) { logger.debug("small response for url=" + request.getURL()); } // Fairly small response, just keep the bytes and make life simple response = new RemoteConnectorResponseImpl(request, responseContentType, responseCharSet, status, responseHdrs, httpRequest.getResponseBody()); // Now we have the bytes, we can close the HttpClient resources httpRequest.releaseConnection(); httpRequest = null; } } finally { // Make sure, problems or not, we always tidy up (if not large stream based) // This is important because we use a thread local HttpClient instance if (httpRequest != null) { httpRequest.releaseConnection(); httpRequest = null; } } // Log the response if (logger.isDebugEnabled()) logger.debug("Response was " + status + " " + statusText); // Decide if we should throw an exception if (status >= 300) { // Tidy if needed if (httpRequest != null) httpRequest.releaseConnection(); // Specific exceptions if (status == Status.STATUS_FORBIDDEN || status == Status.STATUS_UNAUTHORIZED) { // TODO Forbidden may need to be handled differently. // TODO Need to get error message into the AuthenticationException throw new AuthenticationException(statusText); } // Server side exceptions if (status >= 500 && status <= 599) { logger.error("executeRequest: remote connector server exception: [" + status + "] " + statusText); throw new RemoteConnectorServerException(status, statusText); } if (status == Status.STATUS_PRECONDITION_FAILED) { logger.error("executeRequest: remote connector client exception: [" + status + "] " + statusText); throw new RemoteConnectorClientException(status, statusText, response); } else { // Client request exceptions if (httpRequest != null) { // Response wasn't too big and is available, supply it logger.error( "executeRequest: remote connector client exception: [" + status + "] " + statusText); throw new RemoteConnectorClientException(status, statusText, response); } else { // Response was too large, report without it logger.error( "executeRequest: remote connector client exception: [" + status + "] " + statusText); throw new RemoteConnectorClientException(status, statusText, null); } } } // If we get here, then the request/response was all fine // So, return our created response return response; }
From source file:org.apache.cloudstack.network.element.SspClient.java
private String executeMethod(HttpMethod method) { String apiCallPath = null;//from w w w . j a v a2s. c o m try { apiCallPath = method.getName() + " " + method.getURI().toString(); } catch (URIException e) { s_logger.error("method getURI failed", e); } String response = null; try { client.executeMethod(method); response = method.getResponseBodyAsString(); } catch (HttpException e) { s_logger.error("ssp api call failed " + apiCallPath, e); return null; } catch (IOException e) { s_logger.error("ssp api call failed " + apiCallPath, e); return null; } finally { method.releaseConnection(); } if (method.getStatusCode() == HttpStatus.SC_UNAUTHORIZED) { if (!login()) { return null; } try { client.executeMethod(method); response = method.getResponseBodyAsString(); } catch (HttpException e) { s_logger.error("ssp api call failed " + apiCallPath, e); return null; } catch (IOException e) { s_logger.error("ssp api call failed " + apiCallPath, e); return null; } finally { method.releaseConnection(); } } s_logger.info("ssp api call:" + apiCallPath + " user=" + username + " status=" + method.getStatusLine()); if (method instanceof EntityEnclosingMethod) { EntityEnclosingMethod emethod = (EntityEnclosingMethod) method; RequestEntity reqEntity = emethod.getRequestEntity(); if (reqEntity instanceof StringRequestEntity) { StringRequestEntity strReqEntity = (StringRequestEntity) reqEntity; s_logger.debug("ssp api request body:" + strReqEntity.getContent()); } else { s_logger.debug("ssp api request body:" + emethod.getRequestEntity()); } } s_logger.debug("ssp api response body:" + response); return response; }
From source file:org.apache.cloudstack.network.opendaylight.api.test.NeutronNetworkAdapterTest.java
@Test public void gsonNeutronNetworkMarshalingTest() throws NeutronRestApiException { NeutronNetwork network = new NeutronNetwork(); network.setId(UUID.fromString("ca31aa7f-84c7-416d-bc00-1f84927367e0")); network.setName("test_gre"); network.setNetworkType("test"); network.setSegmentationId(1001);/*w w w . ja va2 s. com*/ network.setShared(true); network.setTenantId("wilder"); NeutronNetworkWrapper networkWrapper = new NeutronNetworkWrapper(); networkWrapper.setNetwork(network); StringRequestEntity entity; try { entity = new StringRequestEntity(gsonNeutronNetwork.toJson(networkWrapper), "application/json", null); String actual = entity.getContent(); Assert.assertEquals(jsonString, actual); } catch (UnsupportedEncodingException e) { Assert.fail(e.getMessage()); } }
From source file:org.apache.cloudstack.network.opendaylight.api.test.NeutronNodeAdapterTest.java
@Test public void gsonNeutronPortMarshalingTest() throws NeutronRestApiException { NeutronNode node = new NeutronNode("node-test", "test"); NeutronNodeWrapper nodeWrapper = new NeutronNodeWrapper(node); StringRequestEntity entity; try {// w w w.j a v a 2 s. co m entity = new StringRequestEntity(gsonNeutronNode.toJson(nodeWrapper), "application/json", null); String actual = entity.getContent(); Assert.assertEquals(jsonString, actual); } catch (UnsupportedEncodingException e) { Assert.fail(e.getMessage()); } }
From source file:org.apache.cloudstack.network.opendaylight.api.test.NeutronPortAdapterTest.java
@Test public void gsonNeutronPortMarshalingTest() throws NeutronRestApiException { NeutronPort port = new NeutronPort(); port.setId(UUID.fromString("ca31aa7f-84c7-416d-bc00-1f84927367e0")); port.setName("test_gre"); port.setAdminStateUp(true);/*from w w w. j av a2s . c om*/ port.setDeviceId(UUID.fromString("ca31aa7f-84c7-416d-bc00-1f84927367e0")); port.setMacAddress("ca31aa7f-84c7-416d-bc00-1f84927367e0"); port.setNetworkId(UUID.fromString("ca31aa7f-84c7-416d-bc00-1f84927367e0")); port.setStatus("ACTIVE"); port.setTenantId("wilder"); NeutronPortWrapper portWrapper = new NeutronPortWrapper(); portWrapper.setPort(port); StringRequestEntity entity; try { entity = new StringRequestEntity(gsonNeutronPort.toJson(portWrapper), "application/json", null); String actual = entity.getContent(); Assert.assertEquals(jsonString, actual); } catch (UnsupportedEncodingException e) { Assert.fail(e.getMessage()); } }