List of usage examples for org.apache.commons.httpclient HttpClient getParams
public HttpClientParams getParams()
From source file:org.apache.axis2.transport.http.impl.httpclient3.HTTPProxcyConfigurator.java
/** * Configure HTTP Proxy settings of commons-httpclient HostConfiguration. * Proxy settings can be get from axis2.xml, Java proxy settings or can be * override through property in message context. * <p/>//from www.ja v a2 s.co m * HTTP Proxy setting element format: <parameter name="Proxy"> * <Configuration> <ProxyHost>example.org</ProxyHost> * <ProxyPort>3128</ProxyPort> <ProxyUser>EXAMPLE/John</ProxyUser> * <ProxyPassword>password</ProxyPassword> <Configuration> <parameter> * * @param messageContext * in message context for * @param httpClient * commons-httpclient instance * @param config * commons-httpclient HostConfiguration * @throws AxisFault * if Proxy settings are invalid */ public static void configure(MessageContext messageContext, HttpClient httpClient, HostConfiguration config) throws AxisFault { Credentials proxyCredentials = null; String proxyHost = null; String nonProxyHosts = null; Integer proxyPort = -1; String proxyUser = null; String proxyPassword = null; // Getting configuration values from Axis2.xml Parameter proxySettingsFromAxisConfig = messageContext.getConfigurationContext().getAxisConfiguration() .getParameter(HTTPTransportConstants.ATTR_PROXY); if (proxySettingsFromAxisConfig != null) { OMElement proxyConfiguration = getProxyConfigurationElement(proxySettingsFromAxisConfig); proxyHost = getProxyHost(proxyConfiguration); proxyPort = getProxyPort(proxyConfiguration); proxyUser = getProxyUser(proxyConfiguration); proxyPassword = getProxyPassword(proxyConfiguration); if (proxyUser != null) { if (proxyPassword == null) { proxyPassword = ""; } int proxyUserDomainIndex = proxyUser.indexOf("\\"); if (proxyUserDomainIndex > 0) { String domain = proxyUser.substring(0, proxyUserDomainIndex); if (proxyUser.length() > proxyUserDomainIndex + 1) { String user = proxyUser.substring(proxyUserDomainIndex + 1); proxyCredentials = new NTCredentials(user, proxyPassword, proxyHost, domain); } } proxyCredentials = new UsernamePasswordCredentials(proxyUser, proxyPassword); } } // If there is runtime proxy settings, these settings will override // settings from axis2.xml HttpTransportProperties.ProxyProperties proxyProperties = (HttpTransportProperties.ProxyProperties) messageContext .getProperty(HTTPConstants.PROXY); if (proxyProperties != null) { String proxyHostProp = proxyProperties.getProxyHostName(); if (proxyHostProp == null || proxyHostProp.length() <= 0) { throw new AxisFault("HTTP Proxy host is not available. Host is a MUST parameter"); } else { proxyHost = proxyHostProp; } proxyPort = proxyProperties.getProxyPort(); // Overriding credentials String userName = proxyProperties.getUserName(); String password = proxyProperties.getPassWord(); String domain = proxyProperties.getDomain(); if (userName != null && password != null && domain != null) { proxyCredentials = new NTCredentials(userName, password, proxyHost, domain); } else if (userName != null && domain == null) { proxyCredentials = new UsernamePasswordCredentials(userName, password); } } // Overriding proxy settings if proxy is available from JVM settings String host = System.getProperty(HTTPTransportConstants.HTTP_PROXY_HOST); if (host != null) { proxyHost = host; } String port = System.getProperty(HTTPTransportConstants.HTTP_PROXY_PORT); if (port != null) { proxyPort = Integer.parseInt(port); } if (proxyCredentials != null) { httpClient.getParams().setAuthenticationPreemptive(true); HttpState cachedHttpState = (HttpState) messageContext.getProperty(HTTPConstants.CACHED_HTTP_STATE); if (cachedHttpState != null) { httpClient.setState(cachedHttpState); } httpClient.getState().setProxyCredentials(AuthScope.ANY, proxyCredentials); } config.setProxy(proxyHost, proxyPort); }
From source file:org.apache.axis2.transport.http.impl.httpclient3.HTTPProxyConfigurator.java
/** * Configure HTTP Proxy settings of commons-httpclient HostConfiguration. * Proxy settings can be get from axis2.xml, Java proxy settings or can be * override through property in message context. * <p/>// ww w . j a va 2s . c o m * HTTP Proxy setting element format: <parameter name="Proxy"> * <Configuration> <ProxyHost>example.org</ProxyHost> * <ProxyPort>3128</ProxyPort> <ProxyUser>EXAMPLE/John</ProxyUser> * <ProxyPassword>password</ProxyPassword> <Configuration> <parameter> * * @param messageContext * in message context for * @param httpClient * commons-httpclient instance * @param config * commons-httpclient HostConfiguration * @throws AxisFault * if Proxy settings are invalid */ public static void configure(MessageContext messageContext, HttpClient httpClient, HostConfiguration config) throws AxisFault { Credentials proxyCredentials = null; String proxyHost = null; String nonProxyHosts = null; Integer proxyPort = -1; String proxyUser = null; String proxyPassword = null; // Getting configuration values from Axis2.xml Parameter proxySettingsFromAxisConfig = messageContext.getConfigurationContext().getAxisConfiguration() .getParameter(HTTPTransportConstants.ATTR_PROXY); if (proxySettingsFromAxisConfig != null) { OMElement proxyConfiguration = getProxyConfigurationElement(proxySettingsFromAxisConfig); proxyHost = getProxyHost(proxyConfiguration); proxyPort = getProxyPort(proxyConfiguration); proxyUser = getProxyUser(proxyConfiguration); proxyPassword = getProxyPassword(proxyConfiguration); if (proxyUser != null) { if (proxyPassword == null) { proxyPassword = ""; } proxyCredentials = new UsernamePasswordCredentials(proxyUser, proxyPassword); int proxyUserDomainIndex = proxyUser.indexOf("\\"); if (proxyUserDomainIndex > 0) { String domain = proxyUser.substring(0, proxyUserDomainIndex); if (proxyUser.length() > proxyUserDomainIndex + 1) { String user = proxyUser.substring(proxyUserDomainIndex + 1); proxyCredentials = new NTCredentials(user, proxyPassword, proxyHost, domain); } } } } // If there is runtime proxy settings, these settings will override // settings from axis2.xml HttpTransportProperties.ProxyProperties proxyProperties = (HttpTransportProperties.ProxyProperties) messageContext .getProperty(HTTPConstants.PROXY); if (proxyProperties != null) { String proxyHostProp = proxyProperties.getProxyHostName(); if (proxyHostProp == null || proxyHostProp.length() <= 0) { throw new AxisFault("HTTP Proxy host is not available. Host is a MUST parameter"); } else { proxyHost = proxyHostProp; } proxyPort = proxyProperties.getProxyPort(); // Overriding credentials String userName = proxyProperties.getUserName(); String password = proxyProperties.getPassWord(); String domain = proxyProperties.getDomain(); if (userName != null && password != null && domain != null) { proxyCredentials = new NTCredentials(userName, password, proxyHost, domain); } else if (userName != null && domain == null) { proxyCredentials = new UsernamePasswordCredentials(userName, password); } } // Overriding proxy settings if proxy is available from JVM settings String host = System.getProperty(HTTPTransportConstants.HTTP_PROXY_HOST); if (host != null) { proxyHost = host; } String port = System.getProperty(HTTPTransportConstants.HTTP_PROXY_PORT); if (port != null) { proxyPort = Integer.parseInt(port); } if (proxyCredentials != null) { httpClient.getParams().setAuthenticationPreemptive(true); HttpState cachedHttpState = (HttpState) messageContext.getProperty(HTTPConstants.CACHED_HTTP_STATE); if (cachedHttpState != null) { httpClient.setState(cachedHttpState); } httpClient.getState().setProxyCredentials(AuthScope.ANY, proxyCredentials); } config.setProxy(proxyHost, proxyPort); }
From source file:org.apache.axis2.transport.http.impl.httpclient3.HTTPSenderImpl.java
protected void setAuthenticationInfo(HttpClient agent, MessageContext msgCtx, HostConfiguration config) throws AxisFault { HTTPAuthenticator authenticator;/*from w w w . j a va 2 s . c o m*/ Object obj = msgCtx.getProperty(HTTPConstants.AUTHENTICATE); if (obj != null) { if (obj instanceof HTTPAuthenticator) { authenticator = (HTTPAuthenticator) obj; String username = authenticator.getUsername(); String password = authenticator.getPassword(); String host = authenticator.getHost(); String domain = authenticator.getDomain(); int port = authenticator.getPort(); String realm = authenticator.getRealm(); /* If retrying is available set it first */ isAllowedRetry = authenticator.isAllowedRetry(); Credentials creds; HttpState tmpHttpState = null; HttpState httpState = (HttpState) msgCtx.getProperty(HTTPConstants.CACHED_HTTP_STATE); if (httpState != null) { tmpHttpState = httpState; } else { tmpHttpState = agent.getState(); } agent.getParams().setAuthenticationPreemptive(authenticator.getPreemptiveAuthentication()); if (host != null) { if (domain != null) { /* Credentials for NTLM Authentication */ creds = new NTCredentials(username, password, host, domain); } else { /* Credentials for Digest and Basic Authentication */ creds = new UsernamePasswordCredentials(username, password); } tmpHttpState.setCredentials(new AuthScope(host, port, realm), creds); } else { if (domain != null) { /* * Credentials for NTLM Authentication when host is * ANY_HOST */ creds = new NTCredentials(username, password, AuthScope.ANY_HOST, domain); tmpHttpState.setCredentials(new AuthScope(AuthScope.ANY_HOST, port, realm), creds); } else { /* Credentials only for Digest and Basic Authentication */ creds = new UsernamePasswordCredentials(username, password); tmpHttpState.setCredentials(new AuthScope(AuthScope.ANY), creds); } } /* Customizing the priority Order */ List schemes = authenticator.getAuthSchemes(); if (schemes != null && schemes.size() > 0) { List authPrefs = new ArrayList(3); for (int i = 0; i < schemes.size(); i++) { if (schemes.get(i) instanceof AuthPolicy) { authPrefs.add(schemes.get(i)); continue; } String scheme = (String) schemes.get(i); authPrefs.add(authenticator.getAuthPolicyPref(scheme)); } agent.getParams().setParameter(AuthPolicy.AUTH_SCHEME_PRIORITY, authPrefs); } } else { throw new AxisFault("HttpTransportProperties.Authenticator class cast exception"); } } }
From source file:org.apache.axis2.transport.http.impl.httpclient3.HTTPSenderImpl.java
/** * Method used to copy all the common properties * /*from w w w. j a v a2 s . co m*/ * @param msgContext * - The messageContext of the request message * @param url * - The target URL * @param httpMethod * - The http method used to send the request * @param httpClient * - The httpclient used to send the request * @param soapActionString * - The soap action atring of the request message * @return MessageFormatter - The messageFormatter for the relavent request * message * @throws AxisFault * - Thrown in case an exception occurs */ protected MessageFormatter populateCommonProperties(MessageContext msgContext, URL url, HttpMethodBase httpMethod, HttpClient httpClient, String soapActionString) throws AxisFault { if (isAuthenticationEnabled(msgContext)) { httpMethod.setDoAuthentication(true); } MessageFormatter messageFormatter = TransportUtils.getMessageFormatter(msgContext); url = messageFormatter.getTargetAddress(msgContext, format, url); httpMethod.setPath(url.getPath()); httpMethod.setQueryString(url.getQuery()); httpMethod.setRequestHeader(HTTPConstants.HEADER_CONTENT_TYPE, messageFormatter.getContentType(msgContext, format, soapActionString)); httpMethod.setRequestHeader(HTTPConstants.HEADER_HOST, url.getHost()); if (msgContext.getOptions() != null && msgContext.getOptions().isManageSession()) { // setting the cookie in the out path Object cookieString = msgContext.getProperty(HTTPConstants.COOKIE_STRING); if (cookieString != null) { StringBuffer buffer = new StringBuffer(); buffer.append(cookieString); httpMethod.setRequestHeader(HTTPConstants.HEADER_COOKIE, buffer.toString()); } } if (httpVersion.equals(HTTPConstants.HEADER_PROTOCOL_10)) { httpClient.getParams().setVersion(HttpVersion.HTTP_1_0); } return messageFormatter; }
From source file:org.apache.axis2.transport.http.impl.httpclient3.HTTPSenderImpl.java
protected HttpClient getHttpClient(MessageContext msgContext) { ConfigurationContext configContext = msgContext.getConfigurationContext(); HttpClient httpClient = (HttpClient) msgContext.getProperty(HTTPConstants.CACHED_HTTP_CLIENT); if (httpClient == null) { httpClient = (HttpClient) configContext.getProperty(HTTPConstants.CACHED_HTTP_CLIENT); }/*from w w w . j a va2 s.com*/ if (httpClient != null) { return httpClient; } synchronized (this) { httpClient = (HttpClient) msgContext.getProperty(HTTPConstants.CACHED_HTTP_CLIENT); if (httpClient == null) { httpClient = (HttpClient) configContext.getProperty(HTTPConstants.CACHED_HTTP_CLIENT); } if (httpClient != null) { return httpClient; } HttpConnectionManager connManager = (HttpConnectionManager) msgContext .getProperty(HTTPConstants.MULTITHREAD_HTTP_CONNECTION_MANAGER); if (connManager == null) { connManager = (HttpConnectionManager) msgContext .getProperty(HTTPConstants.MULTITHREAD_HTTP_CONNECTION_MANAGER); } if (connManager == null) { // reuse HttpConnectionManager synchronized (configContext) { connManager = (HttpConnectionManager) configContext .getProperty(HTTPConstants.MULTITHREAD_HTTP_CONNECTION_MANAGER); if (connManager == null) { log.trace("Making new ConnectionManager"); connManager = new MultiThreadedHttpConnectionManager(); configContext.setProperty(HTTPConstants.MULTITHREAD_HTTP_CONNECTION_MANAGER, connManager); } } } /* * Create a new instance of HttpClient since the way it is used here * it's not fully thread-safe. */ httpClient = new HttpClient(connManager); // Set the default timeout in case we have a connection pool // starvation to 30sec httpClient.getParams().setConnectionManagerTimeout(30000); // Get the timeout values set in the runtime initializeTimeouts(msgContext, httpClient); return httpClient; } }
From source file:org.apache.axis2.transport.http.util.HTTPProxyConfigurationUtil.java
/** * Configure HTTP Proxy settings of commons-httpclient HostConfiguration. Proxy settings can be get from * axis2.xml, Java proxy settings or can be override through property in message context. * <p/>/*from w w w. ja v a 2 s. co m*/ * HTTP Proxy setting element format: * <parameter name="Proxy"> * <Configuration> * <ProxyHost>example.org</ProxyHost> * <ProxyPort>3128</ProxyPort> * <ProxyUser>EXAMPLE/John</ProxyUser> * <ProxyPassword>password</ProxyPassword> * <Configuration> * <parameter> * * @param messageContext in message context for * @param httpClient commons-httpclient instance * @param config commons-httpclient HostConfiguration * @throws AxisFault if Proxy settings are invalid */ public static void configure(MessageContext messageContext, HttpClient httpClient, HostConfiguration config) throws AxisFault { Credentials proxyCredentials = null; String proxyHost = null; String nonProxyHosts = null; Integer proxyPort = -1; String proxyUser = null; String proxyPassword = null; //Getting configuration values from Axis2.xml Parameter proxySettingsFromAxisConfig = messageContext.getConfigurationContext().getAxisConfiguration() .getParameter(ATTR_PROXY); if (proxySettingsFromAxisConfig != null) { OMElement proxyConfiguration = getProxyConfigurationElement(proxySettingsFromAxisConfig); proxyHost = getProxyHost(proxyConfiguration); proxyPort = getProxyPort(proxyConfiguration); proxyUser = getProxyUser(proxyConfiguration); proxyPassword = getProxyPassword(proxyConfiguration); if (proxyUser != null) { if (proxyPassword == null) { proxyPassword = ""; } int proxyUserDomainIndex = proxyUser.indexOf("\\"); if (proxyUserDomainIndex > 0) { String domain = proxyUser.substring(0, proxyUserDomainIndex); if (proxyUser.length() > proxyUserDomainIndex + 1) { String user = proxyUser.substring(proxyUserDomainIndex + 1); proxyCredentials = new NTCredentials(user, proxyPassword, proxyHost, domain); } } proxyCredentials = new UsernamePasswordCredentials(proxyUser, proxyPassword); } } // If there is runtime proxy settings, these settings will override settings from axis2.xml HttpTransportProperties.ProxyProperties proxyProperties = (HttpTransportProperties.ProxyProperties) messageContext .getProperty(HTTPConstants.PROXY); if (proxyProperties != null) { String proxyHostProp = proxyProperties.getProxyHostName(); if (proxyHostProp == null || proxyHostProp.length() <= 0) { throw new AxisFault("HTTP Proxy host is not available. Host is a MUST parameter"); } else { proxyHost = proxyHostProp; } proxyPort = proxyProperties.getProxyPort(); // Overriding credentials String userName = proxyProperties.getUserName(); String password = proxyProperties.getPassWord(); String domain = proxyProperties.getDomain(); if (userName != null && password != null && domain != null) { proxyCredentials = new NTCredentials(userName, password, proxyHost, domain); } else if (userName != null && domain == null) { proxyCredentials = new UsernamePasswordCredentials(userName, password); } } // Overriding proxy settings if proxy is available from JVM settings String host = System.getProperty(HTTP_PROXY_HOST); if (host != null) { proxyHost = host; } String port = System.getProperty(HTTP_PROXY_PORT); if (port != null) { proxyPort = Integer.parseInt(port); } if (proxyCredentials != null) { httpClient.getParams().setAuthenticationPreemptive(true); HttpState cachedHttpState = (HttpState) messageContext.getProperty(HTTPConstants.CACHED_HTTP_STATE); if (cachedHttpState != null) { httpClient.setState(cachedHttpState); } httpClient.getState().setProxyCredentials(AuthScope.ANY, proxyCredentials); } config.setProxy(proxyHost, proxyPort); }
From source file:org.apache.camel.component.http.HttpEndpoint.java
/** * Factory method used by producers and consumers to create a new {@link HttpClient} instance *//*from w ww.j av a 2 s. co m*/ public HttpClient createHttpClient() { ObjectHelper.notNull(clientParams, "clientParams"); ObjectHelper.notNull(httpConnectionManager, "httpConnectionManager"); HttpClient answer = new HttpClient(getClientParams()); // configure http proxy from camelContext if (ObjectHelper.isNotEmpty(getCamelContext().getProperty("http.proxyHost")) && ObjectHelper.isNotEmpty(getCamelContext().getProperty("http.proxyPort"))) { String host = getCamelContext().getProperty("http.proxyHost"); int port = Integer.parseInt(getCamelContext().getProperty("http.proxyPort")); LOG.debug( "CamelContext properties http.proxyHost and http.proxyPort detected. Using http proxy host: {} port: {}", host, port); answer.getHostConfiguration().setProxy(host, port); } if (proxyHost != null) { LOG.debug("Using proxy: {}:{}", proxyHost, proxyPort); answer.getHostConfiguration().setProxy(proxyHost, proxyPort); } if (authMethodPriority != null) { List<String> authPrefs = new ArrayList<String>(); Iterator<?> it = getCamelContext().getTypeConverter().convertTo(Iterator.class, authMethodPriority); int i = 1; while (it.hasNext()) { Object value = it.next(); AuthMethod auth = getCamelContext().getTypeConverter().convertTo(AuthMethod.class, value); if (auth == null) { throw new IllegalArgumentException( "Unknown authMethod: " + value + " in authMethodPriority: " + authMethodPriority); } LOG.debug("Using authSchemePriority #{}: {}", i, auth); authPrefs.add(auth.name()); i++; } if (!authPrefs.isEmpty()) { answer.getParams().setParameter(AuthPolicy.AUTH_SCHEME_PRIORITY, authPrefs); } } answer.setHttpConnectionManager(httpConnectionManager); HttpClientConfigurer configurer = getHttpClientConfigurer(); if (configurer != null) { configurer.configureHttpClient(answer); } return answer; }
From source file:org.apache.cocoon.transformation.SparqlTransformer.java
private void executeRequest(String url, String method, Map httpHeaders, SourceParameters requestParameters) throws ProcessingException, IOException, SAXException { HttpClient httpclient = new HttpClient(); if (System.getProperty("http.proxyHost") != null) { // getLogger().warn("PROXY: "+System.getProperty("http.proxyHost")); String nonProxyHostsRE = System.getProperty("http.nonProxyHosts", ""); if (nonProxyHostsRE.length() > 0) { String[] pHosts = nonProxyHostsRE.replaceAll("\\.", "\\\\.").replaceAll("\\*", ".*").split("\\|"); nonProxyHostsRE = ""; for (String pHost : pHosts) { nonProxyHostsRE += "|(^https?://" + pHost + ".*$)"; }// w w w . j a va 2 s. c om nonProxyHostsRE = nonProxyHostsRE.substring(1); } if (nonProxyHostsRE.length() == 0 || !url.matches(nonProxyHostsRE)) { try { HostConfiguration hostConfiguration = httpclient.getHostConfiguration(); hostConfiguration.setProxy(System.getProperty("http.proxyHost"), Integer.parseInt(System.getProperty("http.proxyPort", "80"))); httpclient.setHostConfiguration(hostConfiguration); } catch (Exception e) { throw new ProcessingException("Cannot set proxy!", e); } } } // Make the HttpMethod. HttpMethod httpMethod = null; // Do not use empty query parameter. if (requestParameters.getParameter(parameterName).trim().equals("")) { requestParameters.removeParameter(parameterName); } // Instantiate different HTTP methods. if ("GET".equalsIgnoreCase(method)) { httpMethod = new GetMethod(url); if (requestParameters.getEncodedQueryString() != null) { httpMethod.setQueryString( requestParameters.getEncodedQueryString().replace("\"", "%22")); /* Also escape '"' */ } else { httpMethod.setQueryString(""); } } else if ("POST".equalsIgnoreCase(method)) { PostMethod httpPostMethod = new PostMethod(url); if (httpHeaders.containsKey(HTTP_CONTENT_TYPE) && ((String) httpHeaders.get(HTTP_CONTENT_TYPE)) .startsWith("application/x-www-form-urlencoded")) { // Encode parameters in POST body. Iterator parNames = requestParameters.getParameterNames(); while (parNames.hasNext()) { String parName = (String) parNames.next(); httpPostMethod.addParameter(parName, requestParameters.getParameter(parName)); } } else { // Use query parameter as POST body httpPostMethod.setRequestBody(requestParameters.getParameter(parameterName)); // Add other parameters to query string requestParameters.removeParameter(parameterName); if (requestParameters.getEncodedQueryString() != null) { httpPostMethod.setQueryString( requestParameters.getEncodedQueryString().replace("\"", "%22")); /* Also escape '"' */ } else { httpPostMethod.setQueryString(""); } } httpMethod = httpPostMethod; } else if ("PUT".equalsIgnoreCase(method)) { PutMethod httpPutMethod = new PutMethod(url); httpPutMethod.setRequestBody(requestParameters.getParameter(parameterName)); requestParameters.removeParameter(parameterName); httpPutMethod.setQueryString(requestParameters.getEncodedQueryString()); httpMethod = httpPutMethod; } else if ("DELETE".equalsIgnoreCase(method)) { httpMethod = new DeleteMethod(url); httpMethod.setQueryString(requestParameters.getEncodedQueryString()); } else { throw new ProcessingException("Unsupported method: " + method); } // Authentication (optional). if (credentials != null && credentials.length() > 0) { String[] unpw = credentials.split("\t"); httpclient.getParams().setAuthenticationPreemptive(true); httpclient.getState().setCredentials(new AuthScope(httpMethod.getURI().getHost(), httpMethod.getURI().getPort(), AuthScope.ANY_REALM), new UsernamePasswordCredentials(unpw[0], unpw[1])); } // Add request headers. Iterator headers = httpHeaders.entrySet().iterator(); while (headers.hasNext()) { Map.Entry header = (Map.Entry) headers.next(); httpMethod.addRequestHeader((String) header.getKey(), (String) header.getValue()); } // Declare some variables before the try-block. XMLizer xmlizer = null; try { // Execute the request. int responseCode; responseCode = httpclient.executeMethod(httpMethod); // Handle errors, if any. if (responseCode < 200 || responseCode >= 300) { if (showErrors) { AttributesImpl attrs = new AttributesImpl(); attrs.addCDATAAttribute("status", "" + responseCode); xmlConsumer.startElement(SPARQL_NAMESPACE_URI, "error", "sparql:error", attrs); String responseBody = httpMethod.getStatusText(); //httpMethod.getResponseBodyAsString(); xmlConsumer.characters(responseBody.toCharArray(), 0, responseBody.length()); xmlConsumer.endElement(SPARQL_NAMESPACE_URI, "error", "sparql:error"); return; // Not a nice, but quick and dirty way to end. } else { throw new ProcessingException("Received HTTP status code " + responseCode + " " + httpMethod.getStatusText() + ":\n" + httpMethod.getResponseBodyAsString()); } } // Parse the response if (responseCode == 204) { // No content. String statusLine = httpMethod.getStatusLine().toString(); xmlConsumer.startElement(SPARQL_NAMESPACE_URI, "result", "sparql:result", EMPTY_ATTRIBUTES); xmlConsumer.characters(statusLine.toCharArray(), 0, statusLine.length()); xmlConsumer.endElement(SPARQL_NAMESPACE_URI, "result", "sparql:result"); } else if (parse.equalsIgnoreCase("xml")) { InputStream responseBodyStream = httpMethod.getResponseBodyAsStream(); xmlizer = (XMLizer) manager.lookup(XMLizer.ROLE); xmlizer.toSAX(responseBodyStream, "text/xml", httpMethod.getURI().toString(), new IncludeXMLConsumer(xmlConsumer)); responseBodyStream.close(); } else if (parse.equalsIgnoreCase("text")) { xmlConsumer.startElement(SPARQL_NAMESPACE_URI, "result", "sparql:result", EMPTY_ATTRIBUTES); String responseBody = httpMethod.getResponseBodyAsString(); xmlConsumer.characters(responseBody.toCharArray(), 0, responseBody.length()); xmlConsumer.endElement(SPARQL_NAMESPACE_URI, "result", "sparql:result"); } else { throw new ProcessingException("Unknown parse type: " + parse); } } catch (ServiceException e) { throw new ProcessingException("Cannot find the right XMLizer for " + XMLizer.ROLE, e); } finally { if (xmlizer != null) manager.release((Component) xmlizer); httpMethod.releaseConnection(); } }
From source file:org.apache.gobblin.kafka.schemareg.HttpClientFactory.java
@Override public HttpClient create() throws Exception { HttpClient client = new HttpClient(); if (soTimeout >= 0) { client.getParams().setSoTimeout(soTimeout); }//from ww w . j a va 2 s .co m if (connTimeout >= 0) { client.getHttpConnectionManager().getParams().setConnectionTimeout(connTimeout); } return client; }
From source file:org.apache.hadoop.fs.swift.http.SwiftRestClient.java
/** * Execute a method in a new HttpClient instance. * If the auth failed, authenticate then retry the method. * @param method methot to exec// w w w .j av a2 s. co m * @param <M> Method type * @return the status code * @throws IOException on any failure * @throws SwiftConnectionException failure to connect or authenticate */ private <M extends HttpMethod> int exec(M method) throws IOException, SwiftConnectionException { final HttpClient client = new HttpClient(); if (proxyHost != null) { client.getParams().setParameter(HTTP_ROUTE_DEFAULT_PROXY, new HttpHost(proxyHost, proxyPort)); } int statusCode = execWithDebugOutput(method, client); if (method.getStatusCode() == HttpStatus.SC_UNAUTHORIZED) { //unauthed -look at what raised the response if (method.getURI().toString().equals(authUri.toString())) { //unauth response from the AUTH URI itself. throw new SwiftConnectionException("Authentication failed, URI credentials are incorrect," + " or Openstack Keystone is configured incorrectly. URL='" + authUri + "' " + "username={" + username + "} " + "password length=" + password.length()); } else { //any other URL: try again if (LOG.isDebugEnabled()) { LOG.debug("Reauthenticating"); } authenticate(); if (LOG.isDebugEnabled()) { LOG.debug("Retrying original request"); } statusCode = execWithDebugOutput(method, client); } } return statusCode; }