Search in sources :

Example 6 with HttpRequestBase

use of org.apache.http.client.methods.HttpRequestBase in project gocd by gocd.

the class RemoteRegistrationRequesterTest method hasAllParams.

private TypeSafeMatcher<HttpRequestBase> hasAllParams(final String uuid, final String elasticAgentId, final String elasticPluginId) {
    return new TypeSafeMatcher<HttpRequestBase>() {

        @Override
        public boolean matchesSafely(HttpRequestBase item) {
            try {
                HttpEntityEnclosingRequestBase postMethod = (HttpEntityEnclosingRequestBase) item;
                List<NameValuePair> params = URLEncodedUtils.parse(postMethod.getEntity());
                assertThat(getParameter(params, "hostname"), is("cruise.com"));
                assertThat(getParameter(params, "uuid"), is(uuid));
                String workingDir = SystemUtil.currentWorkingDirectory();
                assertThat(getParameter(params, "location"), is(workingDir));
                assertThat(getParameter(params, "operatingSystem"), not(nullValue()));
                assertThat(getParameter(params, "agentAutoRegisterKey"), is("t0ps3cret"));
                assertThat(getParameter(params, "agentAutoRegisterResources"), is("linux, java"));
                assertThat(getParameter(params, "agentAutoRegisterEnvironments"), is("uat, staging"));
                assertThat(getParameter(params, "agentAutoRegisterHostname"), is("agent01.example.com"));
                assertThat(getParameter(params, "elasticAgentId"), is(elasticAgentId));
                assertThat(getParameter(params, "elasticPluginId"), is(elasticPluginId));
                return true;
            } catch (Exception e) {
                throw new RuntimeException(e);
            }
        }

        private String getParameter(List<NameValuePair> params, String paramName) {
            for (NameValuePair param : params) {
                if (param.getName().equals(paramName)) {
                    return param.getValue();
                }
            }
            return null;
        }

        public void describeTo(Description description) {
            description.appendText("params containing");
        }
    };
}
Also used : NameValuePair(org.apache.http.NameValuePair) HttpRequestBase(org.apache.http.client.methods.HttpRequestBase) HttpEntityEnclosingRequestBase(org.apache.http.client.methods.HttpEntityEnclosingRequestBase) TypeSafeMatcher(org.hamcrest.TypeSafeMatcher) Description(org.hamcrest.Description) List(java.util.List) IOException(java.io.IOException)

Example 7 with HttpRequestBase

use of org.apache.http.client.methods.HttpRequestBase in project opennms by OpenNMS.

the class HttpCollector method buildHttpMethod.

private static HttpRequestBase buildHttpMethod(final HttpCollectorAgent collectorAgent) throws URISyntaxException {
    HttpRequestBase method;
    final URI uri = buildUri(collectorAgent);
    final Url url = collectorAgent.getUriDef().getUrl();
    if ("GET".equals(url.getMethod())) {
        method = buildGetMethod(uri, collectorAgent);
    } else {
        method = buildPostMethod(uri, collectorAgent);
    }
    if (url.getVirtualHost().isPresent()) {
        final String virtualHost = url.getVirtualHost().get();
        if (!virtualHost.trim().isEmpty()) {
            method.setHeader(HTTP.TARGET_HOST, virtualHost);
        }
    }
    return method;
}
Also used : HttpRequestBase(org.apache.http.client.methods.HttpRequestBase) URI(java.net.URI) Url(org.opennms.netmgt.config.httpdatacollection.Url)

Example 8 with HttpRequestBase

use of org.apache.http.client.methods.HttpRequestBase in project opennms by OpenNMS.

the class HttpUrlConnection method getInputStream.

/* (non-Javadoc)
     * @see java.net.URLConnection#getInputStream()
     */
@Override
public InputStream getInputStream() throws IOException {
    try {
        if (m_clientWrapper == null) {
            connect();
        }
        // Build URL
        int port = m_url.getPort() > 0 ? m_url.getPort() : m_url.getDefaultPort();
        URIBuilder ub = new URIBuilder();
        ub.setPort(port);
        ub.setScheme(m_url.getProtocol());
        ub.setHost(m_url.getHost());
        ub.setPath(m_url.getPath());
        if (m_url.getQuery() != null && !m_url.getQuery().trim().isEmpty()) {
            final List<NameValuePair> params = URLEncodedUtils.parse(m_url.getQuery(), StandardCharsets.UTF_8);
            if (!params.isEmpty()) {
                ub.addParameters(params);
            }
        }
        // Build Request
        HttpRequestBase request = null;
        if (m_request != null && m_request.getMethod().equalsIgnoreCase("post")) {
            final Content cnt = m_request.getContent();
            HttpPost post = new HttpPost(ub.build());
            ContentType contentType = ContentType.create(cnt.getType());
            LOG.info("Processing POST request for {}", contentType);
            if (contentType.getMimeType().equals(ContentType.APPLICATION_FORM_URLENCODED.getMimeType())) {
                FormFields fields = JaxbUtils.unmarshal(FormFields.class, cnt.getData());
                post.setEntity(fields.getEntity());
            } else {
                StringEntity entity = new StringEntity(cnt.getData(), contentType);
                post.setEntity(entity);
            }
            request = post;
        } else {
            request = new HttpGet(ub.build());
        }
        if (m_request != null) {
            // Add Custom Headers
            for (final Header header : m_request.getHeaders()) {
                request.addHeader(header.getName(), header.getValue());
            }
        }
        // Get Response
        CloseableHttpResponse response = m_clientWrapper.execute(request);
        return response.getEntity().getContent();
    } catch (Exception e) {
        throw new IOException("Can't retrieve " + m_url.getPath() + " from " + m_url.getHost() + " because " + e.getMessage(), e);
    }
}
Also used : NameValuePair(org.apache.http.NameValuePair) HttpPost(org.apache.http.client.methods.HttpPost) HttpRequestBase(org.apache.http.client.methods.HttpRequestBase) ContentType(org.apache.http.entity.ContentType) HttpGet(org.apache.http.client.methods.HttpGet) IOException(java.io.IOException) GeneralSecurityException(java.security.GeneralSecurityException) IOException(java.io.IOException) URIBuilder(org.apache.http.client.utils.URIBuilder) StringEntity(org.apache.http.entity.StringEntity) Header(org.opennms.protocols.xml.config.Header) Content(org.opennms.protocols.xml.config.Content) CloseableHttpResponse(org.apache.http.client.methods.CloseableHttpResponse)

Example 9 with HttpRequestBase

use of org.apache.http.client.methods.HttpRequestBase in project tdi-studio-se by Talend.

the class DynamicsCRMClient method createAndExecuteRequest.

/**
     * Created and executes a request
     * 
     * @param uri the request URI
     * @param httpEntity the entity to send.
     * @param method HTTP method
     * 
     * @return the response to the request.
     * @throws ServiceUnavailableException
     */
protected HttpResponse createAndExecuteRequest(URI uri, HttpEntity httpEntity, HttpMethod method) throws ServiceUnavailableException {
    boolean hasRetried = false;
    while (true) {
        try {
            httpClient = (DefaultHttpClient) httpClientFactory.create(null, null);
            HttpRequestBase request = null;
            if (method == HttpMethod.POST) {
                request = new HttpPost(uri);
            } else if (method == HttpMethod.PATCH) {
                request = new HttpPatch(uri);
            } else if (method == HttpMethod.DELETE) {
                request = new HttpDelete(uri);
            } else {
                throw new HttpClientException("Unsupported operation:" + method);
            }
            request.addHeader(HttpHeader.AUTHORIZATION, "Bearer " + authResult.getAccessToken());
            if (request instanceof HttpEntityEnclosingRequestBase) {
                ((HttpEntityEnclosingRequestBase) request).setEntity(httpEntity);
            }
            HttpResponse response = httpClient.execute(request);
            if (isResponseSuccess(response.getStatusLine().getStatusCode())) {
                request.releaseConnection();
                EntityUtils.consume(response.getEntity());
                return response;
            } else {
                if (response.getStatusLine().getStatusCode() == HttpStatus.SC_UNAUTHORIZED && !hasRetried) {
                    refreshToken();
                    hasRetried = true;
                    continue;
                }
                HttpEntity entity = response.getEntity();
                String message = null;
                if (entity != null) {
                    message = odataClient.getDeserializer(ContentType.JSON).toError(entity.getContent()).getMessage();
                } else {
                    message = response.getStatusLine().getReasonPhrase();
                }
                throw new HttpClientException(message);
            }
        } catch (Exception e) {
            throw new HttpClientException(e);
        }
    }
}
Also used : HttpPost(org.apache.http.client.methods.HttpPost) HttpRequestBase(org.apache.http.client.methods.HttpRequestBase) HttpEntityEnclosingRequestBase(org.apache.http.client.methods.HttpEntityEnclosingRequestBase) HttpClientException(org.apache.olingo.client.api.http.HttpClientException) HttpDelete(org.apache.http.client.methods.HttpDelete) HttpEntity(org.apache.http.HttpEntity) HttpResponse(org.apache.http.HttpResponse) HttpPatch(org.apache.olingo.client.core.http.HttpPatch) URISyntaxException(java.net.URISyntaxException) ServiceUnavailableException(javax.naming.ServiceUnavailableException) ODataClientErrorException(org.apache.olingo.client.api.communication.ODataClientErrorException) HttpClientException(org.apache.olingo.client.api.http.HttpClientException)

Example 10 with HttpRequestBase

use of org.apache.http.client.methods.HttpRequestBase in project newsrob by marianokamp.

the class GRAnsweredBadRequestException method getStateChangesFromGR.

private Collection<StateChange> getStateChangesFromGR(long lastUpdated) throws IOException, ParserConfigurationException, SAXException, GRTokenExpiredException, GRAnsweredBadRequestException {
    Timing t = new Timing("EntriesRetriever.getStateChangesFromGR()", context);
    String url = getGoogleHost() + "/reader/api/0/stream/items/ids";
    // &s=deleted/user/-/state/com.google/starred";
    url += "?s=user/-/state/com.google/starred";
    url += "&s=user/-/state/com.google/read";
    url += "&s=" + NEWSROB_PINNED_STATE;
    // &s=deleted/user/-/state/com.google/read";
    url += "&n=10000&ot=" + lastUpdated;
    NewsRobHttpClient httpClient = NewsRobHttpClient.newInstance(false, context);
    try {
        HttpRequestBase req = createGRRequest(httpClient, url);
        HttpResponse response = executeGRRequest(httpClient, req, true);
        throwExceptionWhenNotStatusOK(response);
        final List<StateChange> stateChanges = new ArrayList<StateChange>(25);
        SAXParserFactory saxParserFactory = SAXParserFactory.newInstance();
        SAXParser parser = saxParserFactory.newSAXParser();
        DefaultHandler handler = new SimpleStringExtractorHandler() {

            private String currentAtomId;

            // cache
            String googleUserId = null;

            @Override
            public void receivedString(String localName, String fqn, String s) {
                if ("number".equals(localName)) {
                    long l = Long.parseLong(s);
                    currentAtomId = TAG_GR_ITEM + U.longToHex(l);
                } else if ("string".equals(localName)) {
                    boolean delete = s.startsWith("delete");
                    int state = -1;
                    if (s.endsWith("read"))
                        state = EntriesRetriever.StateChange.STATE_READ;
                    else if (s.endsWith("starred"))
                        state = EntriesRetriever.StateChange.STATE_STARRED;
                    if (state > -1) {
                        EntriesRetriever.StateChange sc = new EntriesRetriever.StateChange(currentAtomId, state, delete ? EntriesRetriever.StateChange.OPERATION_REMOVE : EntriesRetriever.StateChange.OPERATION_ADD);
                        stateChanges.add(sc);
                    }
                }
            }
        };
        parser.parse(NewsRobHttpClient.getUngzippedContent(response.getEntity(), context), handler);
        PL.log("Entries Retriever: Number of state changes=" + stateChanges.size(), context);
        if (NewsRob.isDebuggingEnabled(context))
            PL.log("State Changes: " + stateChanges, context);
        return stateChanges;
    } finally {
        httpClient.close();
        t.stop();
    }
}
Also used : HttpRequestBase(org.apache.http.client.methods.HttpRequestBase) SimpleStringExtractorHandler(com.newsrob.util.SimpleStringExtractorHandler) ArrayList(java.util.ArrayList) HttpResponse(org.apache.http.HttpResponse) DefaultHandler(org.xml.sax.helpers.DefaultHandler) NewsRobHttpClient(com.newsrob.download.NewsRobHttpClient) SAXParser(javax.xml.parsers.SAXParser) Timing(com.newsrob.util.Timing) SAXParserFactory(javax.xml.parsers.SAXParserFactory)

Aggregations

HttpRequestBase (org.apache.http.client.methods.HttpRequestBase)49 HttpResponse (org.apache.http.HttpResponse)24 HttpGet (org.apache.http.client.methods.HttpGet)15 IOException (java.io.IOException)11 Header (org.apache.http.Header)11 HttpPost (org.apache.http.client.methods.HttpPost)10 HttpEntity (org.apache.http.HttpEntity)9 URI (java.net.URI)7 ArrayList (java.util.ArrayList)6 CloseableHttpResponse (org.apache.http.client.methods.CloseableHttpResponse)6 HttpHead (org.apache.http.client.methods.HttpHead)6 Test (org.junit.Test)6 HttpEntityEnclosingRequestBase (org.apache.http.client.methods.HttpEntityEnclosingRequestBase)5 StringEntity (org.apache.http.entity.StringEntity)5 CloseableHttpClient (org.apache.http.impl.client.CloseableHttpClient)5 SimpleStringExtractorHandler (com.newsrob.util.SimpleStringExtractorHandler)4 Timing (com.newsrob.util.Timing)4 InputStream (java.io.InputStream)4 URISyntaxException (java.net.URISyntaxException)4 HttpPut (org.apache.http.client.methods.HttpPut)4