Search in sources :

Example 1 with HttpVersion

use of org.apache.http.HttpVersion in project opennms by OpenNMS.

the class HttpNorthbounder method forwardAlarms.

/* (non-Javadoc)
     * @see org.opennms.netmgt.alarmd.api.support.AbstractNorthbounder#forwardAlarms(java.util.List)
     */
@Override
public void forwardAlarms(List<NorthboundAlarm> alarms) throws NorthbounderException {
    LOG.info("Forwarding {} alarms", alarms.size());
    //Need a configuration bean for these
    int connectionTimeout = 3000;
    int socketTimeout = 3000;
    Integer retryCount = Integer.valueOf(3);
    URI uri = m_config.getURI();
    final HttpClientWrapper clientWrapper = HttpClientWrapper.create().setConnectionTimeout(connectionTimeout).setSocketTimeout(socketTimeout).setRetries(retryCount).useBrowserCompatibleCookies();
    if (m_config.getVirtualHost() != null && !m_config.getVirtualHost().trim().isEmpty()) {
        clientWrapper.setVirtualHost(m_config.getVirtualHost());
    }
    if (m_config.getUserAgent() != null && !m_config.getUserAgent().trim().isEmpty()) {
        clientWrapper.setUserAgent(m_config.getUserAgent());
    }
    if ("https".equals(uri.getScheme())) {
        try {
            clientWrapper.useRelaxedSSL("https");
        } catch (final GeneralSecurityException e) {
            throw new NorthbounderException("Failed to configure HTTP northbounder for relaxed SSL.", e);
        }
    }
    HttpUriRequest method = null;
    if (HttpMethod.POST == (m_config.getMethod())) {
        HttpPost postMethod = new HttpPost(uri);
        //TODO: need to configure these
        List<NameValuePair> postParms = new ArrayList<NameValuePair>();
        //FIXME:do this for now
        NameValuePair p = new BasicNameValuePair("foo", "bar");
        postParms.add(p);
        UrlEncodedFormEntity formEntity = new UrlEncodedFormEntity(postParms, StandardCharsets.UTF_8);
        postMethod.setEntity(formEntity);
        HttpEntity entity = null;
        try {
            //I have no idea what I'm doing here ;)
            entity = new StringEntity("XML HERE");
        } catch (UnsupportedEncodingException e) {
            // TODO Auto-generated catch block
            e.printStackTrace();
        }
        postMethod.setEntity(entity);
        method = postMethod;
    } else if (HttpMethod.GET == m_config.getMethod()) {
        //TODO: need to configure these
        //List<NameValuePair> getParms = null;
        method = new HttpGet(uri);
    }
    HttpVersion httpVersion = determineHttpVersion(m_config.getHttpVersion());
    clientWrapper.setVersion(httpVersion);
    HttpResponse response = null;
    try {
        response = clientWrapper.execute(method);
        int code = response.getStatusLine().getStatusCode();
        HttpResponseRange range = new HttpResponseRange("200-399");
        if (!range.contains(code)) {
            LOG.debug("response code out of range for uri:{}.  Expected {} but received {}", uri, range, code);
            throw new NorthbounderException("response code out of range for uri:" + uri + ".  Expected " + range + " but received " + code);
        }
        LOG.debug("HTTP Northbounder received response: {}", response.getStatusLine().getReasonPhrase());
    } catch (final ClientProtocolException e) {
        throw new NorthbounderException(e);
    } catch (final IOException e) {
        throw new NorthbounderException(e);
    } finally {
        IOUtils.closeQuietly(clientWrapper);
    }
}
Also used : HttpUriRequest(org.apache.http.client.methods.HttpUriRequest) HttpPost(org.apache.http.client.methods.HttpPost) BasicNameValuePair(org.apache.http.message.BasicNameValuePair) NameValuePair(org.apache.http.NameValuePair) HttpEntity(org.apache.http.HttpEntity) GeneralSecurityException(java.security.GeneralSecurityException) HttpGet(org.apache.http.client.methods.HttpGet) ArrayList(java.util.ArrayList) UnsupportedEncodingException(java.io.UnsupportedEncodingException) HttpResponse(org.apache.http.HttpResponse) UrlEncodedFormEntity(org.apache.http.client.entity.UrlEncodedFormEntity) IOException(java.io.IOException) URI(java.net.URI) ClientProtocolException(org.apache.http.client.ClientProtocolException) HttpResponseRange(org.opennms.core.utils.HttpResponseRange) StringEntity(org.apache.http.entity.StringEntity) NorthbounderException(org.opennms.netmgt.alarmd.api.NorthbounderException) BasicNameValuePair(org.apache.http.message.BasicNameValuePair) HttpClientWrapper(org.opennms.core.web.HttpClientWrapper) HttpVersion(org.apache.http.HttpVersion)

Example 2 with HttpVersion

use of org.apache.http.HttpVersion in project camel by apache.

the class HttpProducer method process.

public void process(Exchange exchange) throws Exception {
    if (getEndpoint().isClearExpiredCookies() && !getEndpoint().isBridgeEndpoint()) {
        // create the cookies before the invocation
        getEndpoint().getCookieStore().clearExpired(new Date());
    }
    // if we bridge endpoint then we need to skip matching headers with the HTTP_QUERY to avoid sending
    // duplicated headers to the receiver, so use this skipRequestHeaders as the list of headers to skip
    Map<String, Object> skipRequestHeaders = null;
    if (getEndpoint().isBridgeEndpoint()) {
        exchange.setProperty(Exchange.SKIP_GZIP_ENCODING, Boolean.TRUE);
        String queryString = exchange.getIn().getHeader(Exchange.HTTP_QUERY, String.class);
        if (queryString != null) {
            skipRequestHeaders = URISupport.parseQuery(queryString, false, true);
        }
    }
    HttpRequestBase httpRequest = createMethod(exchange);
    Message in = exchange.getIn();
    String httpProtocolVersion = in.getHeader(Exchange.HTTP_PROTOCOL_VERSION, String.class);
    if (httpProtocolVersion != null) {
        // set the HTTP protocol version
        int[] version = HttpHelper.parserHttpVersion(httpProtocolVersion);
        httpRequest.setProtocolVersion(new HttpVersion(version[0], version[1]));
    }
    HeaderFilterStrategy strategy = getEndpoint().getHeaderFilterStrategy();
    // propagate headers as HTTP headers
    for (Map.Entry<String, Object> entry : in.getHeaders().entrySet()) {
        String key = entry.getKey();
        Object headerValue = in.getHeader(key);
        if (headerValue != null) {
            // use an iterator as there can be multiple values. (must not use a delimiter, and allow empty values)
            final Iterator<?> it = ObjectHelper.createIterator(headerValue, null, true);
            // the value to add as request header
            final List<String> values = new ArrayList<String>();
            // should be combined into a single value
            while (it.hasNext()) {
                String value = exchange.getContext().getTypeConverter().convertTo(String.class, it.next());
                // as then we would duplicate headers on both the endpoint uri, and in HTTP headers as well
                if (skipRequestHeaders != null && skipRequestHeaders.containsKey(key)) {
                    continue;
                }
                if (value != null && strategy != null && !strategy.applyFilterToCamelHeaders(key, value, exchange)) {
                    values.add(value);
                }
            }
            // add the value(s) as a http request header
            if (values.size() > 0) {
                // use the default toString of a ArrayList to create in the form [xxx, yyy]
                // if multi valued, for a single value, then just output the value as is
                String s = values.size() > 1 ? values.toString() : values.get(0);
                httpRequest.addHeader(key, s);
            }
        }
    }
    if (getEndpoint().getCookieHandler() != null) {
        Map<String, List<String>> cookieHeaders = getEndpoint().getCookieHandler().loadCookies(exchange, httpRequest.getURI());
        for (Map.Entry<String, List<String>> entry : cookieHeaders.entrySet()) {
            String key = entry.getKey();
            if (entry.getValue().size() > 0) {
                // use the default toString of a ArrayList to create in the form [xxx, yyy]
                // if multi valued, for a single value, then just output the value as is
                String s = entry.getValue().size() > 1 ? entry.getValue().toString() : entry.getValue().get(0);
                httpRequest.addHeader(key, s);
            }
        }
    }
    //if this option is set, and the exchange Host header is not null, we will set it's current value on the httpRequest
    if (getEndpoint().isPreserveHostHeader()) {
        String hostHeader = exchange.getIn().getHeader("Host", String.class);
        if (hostHeader != null) {
            //HttpClient 4 will check to see if the Host header is present, and use it if it is, see org.apache.http.protocol.RequestTargetHost in httpcore
            httpRequest.setHeader("Host", hostHeader);
        }
    }
    if (getEndpoint().isConnectionClose()) {
        httpRequest.addHeader("Connection", HTTP.CONN_CLOSE);
    }
    // lets store the result in the output message.
    HttpResponse httpResponse = null;
    try {
        if (LOG.isDebugEnabled()) {
            LOG.debug("Executing http {} method: {}", httpRequest.getMethod(), httpRequest.getURI().toString());
        }
        httpResponse = executeMethod(httpRequest);
        int responseCode = httpResponse.getStatusLine().getStatusCode();
        LOG.debug("Http responseCode: {}", responseCode);
        if (!throwException) {
            // if we do not use failed exception then populate response for all response codes
            populateResponse(exchange, httpRequest, httpResponse, in, strategy, responseCode);
        } else {
            boolean ok = HttpHelper.isStatusCodeOk(responseCode, getEndpoint().getOkStatusCodeRange());
            if (ok) {
                // only populate response for OK response
                populateResponse(exchange, httpRequest, httpResponse, in, strategy, responseCode);
            } else {
                // operation failed so populate exception to throw
                throw populateHttpOperationFailedException(exchange, httpRequest, httpResponse, responseCode);
            }
        }
    } finally {
        final HttpResponse response = httpResponse;
        if (httpResponse != null && getEndpoint().isDisableStreamCache()) {
            // close the stream at the end of the exchange to ensure it gets eventually closed later
            exchange.addOnCompletion(new SynchronizationAdapter() {

                @Override
                public void onDone(Exchange exchange) {
                    try {
                        EntityUtils.consume(response.getEntity());
                    } catch (Throwable e) {
                    // ignore
                    }
                }
            });
        } else if (httpResponse != null) {
            // close the stream now
            try {
                EntityUtils.consume(response.getEntity());
            } catch (Throwable e) {
            // ignore
            }
        }
    }
}
Also used : HttpRequestBase(org.apache.http.client.methods.HttpRequestBase) Message(org.apache.camel.Message) ArrayList(java.util.ArrayList) HttpResponse(org.apache.http.HttpResponse) HeaderFilterStrategy(org.apache.camel.spi.HeaderFilterStrategy) HttpProtocolHeaderFilterStrategy(org.apache.camel.http.common.HttpProtocolHeaderFilterStrategy) Date(java.util.Date) Exchange(org.apache.camel.Exchange) List(java.util.List) ArrayList(java.util.ArrayList) HttpVersion(org.apache.http.HttpVersion) Map(java.util.Map) HashMap(java.util.HashMap) SynchronizationAdapter(org.apache.camel.support.SynchronizationAdapter)

Example 3 with HttpVersion

use of org.apache.http.HttpVersion in project opennms by OpenNMS.

the class NCSNorthbounder method postAlarms.

private void postAlarms(HttpEntity entity) {
    //Need a configuration bean for these
    int connectionTimeout = 3000;
    int socketTimeout = 3000;
    Integer retryCount = 3;
    HttpVersion httpVersion = determineHttpVersion(m_config.getHttpVersion());
    URI uri = m_config.getURI();
    System.err.println("uri = " + uri);
    final HttpClientWrapper clientWrapper = HttpClientWrapper.create().setSocketTimeout(socketTimeout).setConnectionTimeout(connectionTimeout).setRetries(retryCount).useBrowserCompatibleCookies().dontReuseConnections();
    if ("https".equals(uri.getScheme())) {
        try {
            clientWrapper.useRelaxedSSL("https");
        } catch (final GeneralSecurityException e) {
            throw new NorthbounderException("Failed to configure Relaxed SSL handling.", e);
        }
    }
    final HttpEntityEnclosingRequestBase method = m_config.getMethod().getRequestMethod(uri);
    if (m_config.getVirtualHost() != null && !m_config.getVirtualHost().trim().isEmpty()) {
        method.setHeader(HTTP.TARGET_HOST, m_config.getVirtualHost());
    }
    if (m_config.getUserAgent() != null && !m_config.getUserAgent().trim().isEmpty()) {
        method.setHeader(HTTP.USER_AGENT, m_config.getUserAgent());
    }
    method.setProtocolVersion(httpVersion);
    method.setEntity(entity);
    CloseableHttpResponse response = null;
    try {
        System.err.println("execute: " + method);
        response = clientWrapper.execute(method);
    } catch (ClientProtocolException e) {
        throw new NorthbounderException(e);
    } catch (IOException e) {
        throw new NorthbounderException(e);
    } finally {
        IOUtils.closeQuietly(clientWrapper);
    }
    if (response != null) {
        try {
            int code = response.getStatusLine().getStatusCode();
            final HttpResponseRange range = new HttpResponseRange("200-399");
            if (!range.contains(code)) {
                LOG.warn("response code out of range for uri: {}.  Expected {} but received {}", uri, range, code);
                throw new NorthbounderException("response code out of range for uri:" + uri + ".  Expected " + range + " but received " + code);
            }
        } finally {
            IOUtils.closeQuietly(clientWrapper);
        }
    }
    LOG.debug(response != null ? response.getStatusLine().getReasonPhrase() : "Response was null");
}
Also used : HttpResponseRange(org.opennms.core.utils.HttpResponseRange) HttpEntityEnclosingRequestBase(org.apache.http.client.methods.HttpEntityEnclosingRequestBase) NorthbounderException(org.opennms.netmgt.alarmd.api.NorthbounderException) GeneralSecurityException(java.security.GeneralSecurityException) HttpClientWrapper(org.opennms.core.web.HttpClientWrapper) CloseableHttpResponse(org.apache.http.client.methods.CloseableHttpResponse) IOException(java.io.IOException) HttpVersion(org.apache.http.HttpVersion) URI(java.net.URI) ClientProtocolException(org.apache.http.client.ClientProtocolException)

Example 4 with HttpVersion

use of org.apache.http.HttpVersion in project opennms by OpenNMS.

the class HttpCollector method doCollection.

/**
     * Performs HTTP collection.
     * 
     * Couple of notes to make the implementation of this client library
     * less obtuse:
     * 
     *   - HostConfiguration class is not created here because the library
     *     builds it when a URI is defined.
     *     
     * @param collectorAgent
     * @throws HttpCollectorException
     */
private static void doCollection(final HttpCollectorAgent collectorAgent, final CollectionSetBuilder collectionSetBuilder) throws HttpCollectorException {
    HttpRequestBase method = null;
    HttpClientWrapper clientWrapper = null;
    try {
        final HttpVersion httpVersion = computeVersion(collectorAgent.getUriDef());
        clientWrapper = HttpClientWrapper.create().setConnectionTimeout(ParameterMap.getKeyedInteger(collectorAgent.getParameters(), ParameterName.TIMEOUT.toString(), DEFAULT_SO_TIMEOUT)).setSocketTimeout(ParameterMap.getKeyedInteger(collectorAgent.getParameters(), ParameterName.TIMEOUT.toString(), DEFAULT_SO_TIMEOUT)).useBrowserCompatibleCookies();
        if ("https".equals(collectorAgent.getUriDef().getUrl().getScheme())) {
            clientWrapper.useRelaxedSSL("https");
        }
        String key = ParameterName.RETRY.toString();
        if (collectorAgent.getParameters().containsKey(ParameterName.RETRIES.toString())) {
            key = ParameterName.RETRIES.toString();
        }
        Integer retryCount = ParameterMap.getKeyedInteger(collectorAgent.getParameters(), key, DEFAULT_RETRY_COUNT);
        clientWrapper.setRetries(retryCount);
        method = buildHttpMethod(collectorAgent);
        method.setProtocolVersion(httpVersion);
        final String userAgent = determineUserAgent(collectorAgent);
        if (userAgent != null && !userAgent.trim().isEmpty()) {
            clientWrapper.setUserAgent(userAgent);
        }
        final HttpClientWrapper wrapper = clientWrapper;
        if (collectorAgent.getUriDef().getUrl().getUserInfo().isPresent()) {
            final String userInfo = collectorAgent.getUriDef().getUrl().getUserInfo().get();
            final String[] streetCred = userInfo.split(":", 2);
            if (streetCred.length == 2) {
                wrapper.addBasicCredentials(streetCred[0], streetCred[1]);
            } else {
                LOG.warn("Illegal value found for username/password HTTP credentials: {}", userInfo);
            }
        }
        LOG.info("doCollection: collecting using method: {}", method);
        final CloseableHttpResponse response = clientWrapper.execute(method);
        //Not really a persist as such; it just stores data in collectionSet for later retrieval
        persistResponse(collectorAgent, collectionSetBuilder, response);
    } catch (URISyntaxException e) {
        throw new HttpCollectorException("Error building HttpClient URI", e);
    } catch (IOException e) {
        throw new HttpCollectorException("IO Error retrieving page", e);
    } catch (PatternSyntaxException e) {
        throw new HttpCollectorException("Invalid regex specified in HTTP collection configuration", e);
    } catch (Throwable e) {
        throw new HttpCollectorException("Unexpected exception caught during HTTP collection", e);
    } finally {
        IOUtils.closeQuietly(clientWrapper);
    }
}
Also used : HttpRequestBase(org.apache.http.client.methods.HttpRequestBase) HttpClientWrapper(org.opennms.core.web.HttpClientWrapper) CloseableHttpResponse(org.apache.http.client.methods.CloseableHttpResponse) URISyntaxException(java.net.URISyntaxException) IOException(java.io.IOException) HttpVersion(org.apache.http.HttpVersion) PatternSyntaxException(java.util.regex.PatternSyntaxException)

Aggregations

HttpVersion (org.apache.http.HttpVersion)4 IOException (java.io.IOException)3 HttpClientWrapper (org.opennms.core.web.HttpClientWrapper)3 URI (java.net.URI)2 GeneralSecurityException (java.security.GeneralSecurityException)2 ArrayList (java.util.ArrayList)2 HttpResponse (org.apache.http.HttpResponse)2 ClientProtocolException (org.apache.http.client.ClientProtocolException)2 CloseableHttpResponse (org.apache.http.client.methods.CloseableHttpResponse)2 HttpRequestBase (org.apache.http.client.methods.HttpRequestBase)2 HttpResponseRange (org.opennms.core.utils.HttpResponseRange)2 NorthbounderException (org.opennms.netmgt.alarmd.api.NorthbounderException)2 UnsupportedEncodingException (java.io.UnsupportedEncodingException)1 URISyntaxException (java.net.URISyntaxException)1 Date (java.util.Date)1 HashMap (java.util.HashMap)1 List (java.util.List)1 Map (java.util.Map)1 PatternSyntaxException (java.util.regex.PatternSyntaxException)1 Exchange (org.apache.camel.Exchange)1