Example usage for org.apache.http.client.methods HttpOptions HttpOptions

List of usage examples for org.apache.http.client.methods HttpOptions HttpOptions

Introduction

In this page you can find the example usage for org.apache.http.client.methods HttpOptions HttpOptions.

Prototype

public HttpOptions(final String uri) 

Source Link

Usage

From source file:org.switchyard.component.http.OutboundHandler.java

/**
 * The handler method that invokes the actual HTTP service when the
 * component is used as a HTTP consumer.
 * @param exchange the Exchange// w  w  w . j av a  2 s  . c om
 * @throws HandlerException handler exception
 */
@Override
public void handleMessage(final Exchange exchange) throws HandlerException {
    // identify ourselves
    exchange.getContext().setProperty(ExchangeCompletionEvent.GATEWAY_NAME, _bindingName, Scope.EXCHANGE)
            .addLabels(BehaviorLabel.TRANSIENT.label());
    if (getState() != State.STARTED) {
        final String m = HttpMessages.MESSAGES.bindingNotStarted(_referenceName, _bindingName);
        LOGGER.error(m);
        throw new HandlerException(m);
    }

    HttpClient httpclient = new DefaultHttpClient();
    if (_timeout != null) {
        HttpParams httpParams = httpclient.getParams();
        HttpConnectionParams.setConnectionTimeout(httpParams, _timeout);
        HttpConnectionParams.setSoTimeout(httpParams, _timeout);
    }
    try {
        if (_credentials != null) {
            ((DefaultHttpClient) httpclient).getCredentialsProvider().setCredentials(_authScope, _credentials);
            List<String> authpref = new ArrayList<String>();
            authpref.add(AuthPolicy.NTLM);
            authpref.add(AuthPolicy.BASIC);
            httpclient.getParams().setParameter(AuthPNames.TARGET_AUTH_PREF, authpref);
        }
        if (_proxyHost != null) {
            httpclient.getParams().setParameter(ConnRoutePNames.DEFAULT_PROXY, _proxyHost);
        }
        HttpBindingData httpRequest = _messageComposer.decompose(exchange, new HttpRequestBindingData());
        HttpRequestBase request = null;
        if (_httpMethod.equals(HTTP_GET)) {
            request = new HttpGet(_baseAddress);
        } else if (_httpMethod.equals(HTTP_POST)) {
            request = new HttpPost(_baseAddress);
            ((HttpPost) request).setEntity(new BufferedHttpEntity(
                    new InputStreamEntity(httpRequest.getBodyBytes(), httpRequest.getBodyBytes().available())));
        } else if (_httpMethod.equals(HTTP_DELETE)) {
            request = new HttpDelete(_baseAddress);
        } else if (_httpMethod.equals(HTTP_HEAD)) {
            request = new HttpHead(_baseAddress);
        } else if (_httpMethod.equals(HTTP_PUT)) {
            request = new HttpPut(_baseAddress);
            ((HttpPut) request).setEntity(new BufferedHttpEntity(
                    new InputStreamEntity(httpRequest.getBodyBytes(), httpRequest.getBodyBytes().available())));
        } else if (_httpMethod.equals(HTTP_OPTIONS)) {
            request = new HttpOptions(_baseAddress);
        }
        Iterator<Map.Entry<String, List<String>>> entries = httpRequest.getHeaders().entrySet().iterator();
        while (entries.hasNext()) {
            Map.Entry<String, List<String>> entry = entries.next();
            String name = entry.getKey();
            if (REQUEST_HEADER_BLACKLIST.contains(name)) {
                HttpLogger.ROOT_LOGGER.removingProhibitedRequestHeader(name);
                continue;
            }
            List<String> values = entry.getValue();
            for (String value : values) {
                request.addHeader(name, value);
            }
        }
        if (_contentType != null) {
            request.addHeader("Content-Type", _contentType);
        }

        HttpResponse response = null;
        if ((_credentials != null) && (_credentials instanceof NTCredentials)) {
            // Send a request for the Negotiation
            response = httpclient.execute(new HttpGet(_baseAddress));
            HttpClientUtils.closeQuietly(response);
        }
        if (_authCache != null) {
            BasicHttpContext context = new BasicHttpContext();
            context.setAttribute(ClientContext.AUTH_CACHE, _authCache);
            response = httpclient.execute(request, context);
        } else {
            response = httpclient.execute(request);
        }
        int status = response.getStatusLine().getStatusCode();

        HttpEntity entity = response.getEntity();
        HttpResponseBindingData httpResponse = new HttpResponseBindingData();
        Header[] headers = response.getAllHeaders();
        for (Header header : headers) {
            httpResponse.addHeader(header.getName(), header.getValue());
        }
        if (entity != null) {
            if (entity.getContentType() != null) {
                httpResponse.setContentType(new ContentType(entity.getContentType().getValue()));
            } else {
                httpResponse.setContentType(new ContentType());
            }
            httpResponse.setBodyFromStream(entity.getContent());
        }
        httpResponse.setStatus(status);
        Message out = _messageComposer.compose(httpResponse, exchange);
        if (httpResponse.getStatus() < 400) {
            exchange.send(out);
        } else {
            exchange.sendFault(out);
        }
    } catch (Exception e) {
        final String m = HttpMessages.MESSAGES.unexpectedExceptionHandlingHTTPMessage();
        LOGGER.error(m, e);
        throw new HandlerException(m, e);
    } finally {
        // When HttpClient instance is no longer needed,
        // shut down the connection manager to ensure
        // immediate deallocation of all system resources
        httpclient.getConnectionManager().shutdown();
    }
}

From source file:org.keycloak.testsuite.util.OAuthClient.java

public CloseableHttpResponse doPreflightRequest() {
    try (CloseableHttpClient client = httpClient.get()) {
        HttpOptions options = new HttpOptions(getAccessTokenUrl());
        options.setHeader("Origin", "http://example.com");

        return client.execute(options);
    } catch (IOException ioe) {
        throw new RuntimeException(ioe);
    }//from  w  ww .j a v a  2 s.c  o m
}

From source file:uk.co.tfd.sm.proxy.ProxyClientServiceImpl.java

/**
 * Executes a HTTP call using a path in the JCR to point to a template and a
 * map of properties to populate that template with. An example might be a
 * SOAP call.//from  w w w . java  2 s .c  o m
 * 
 * <pre>
 * {http://www.w3.org/2001/12/soap-envelope}Envelope:{
 *  {http://www.w3.org/2001/12/soap-envelope}Body:{
 *   {http://www.example.org/stock}GetStockPriceResponse:{
 *    &gt;body:[       ]
 *    {http://www.example.org/stock}Price:{
 *     &gt;body:[34.5]
 *    }
 *   }
 *   &gt;body:[  ]
 *  }
 *  &gt;body:[   ]
 *  {http://www.w3.org/2001/12/soap-envelope}encodingStyle:[http://www.w3.org/2001/12/soap-encoding]
 * }
 * 
 * </pre>
 * 
 * @param resource
 *            the resource containing the proxy end point specification.
 * @param headers
 *            a map of headers to set int the request.
 * @param input
 *            a map of parameters for all templates (both url and body)
 * @param requestInputStream
 *            containing the request body (can be null if the call requires
 *            no body or the template will be used to generate the body)
 * @param requestContentLength
 *            if the requestImputStream is specified, the length specifies
 *            the lenght of the body.
 * @param requerstContentType
 *            the content type of the request, if null the node property
 *            sakai:proxy-request-content-type will be used.
 * @throws ProxyClientException
 */
public ProxyResponse executeCall(Map<String, Object> config, Map<String, Object> headers,
        Map<String, Object> input, InputStream requestInputStream, long requestContentLength,
        String requestContentType) throws ProxyClientException {
    try {
        LOGGER.info(
                "Calling Execute Call with Config:[{}] Headers:[{}] Input:[{}] "
                        + "RequestInputStream:[{}] InputStreamContentLength:[{}] RequestContentType:[{}] ",
                new Object[] { config, headers, input, requestInputStream, requestContentLength,
                        requestContentType });
        bindConfig(config);

        if (config != null && config.containsKey(CONFIG_REQUEST_PROXY_ENDPOINT)) {
            // setup the post request
            String endpointURL = (String) config.get(CONFIG_REQUEST_PROXY_ENDPOINT);
            if (isUnsafeProxyDefinition(config)) {
                try {
                    URL u = new URL(endpointURL);
                    String host = u.getHost();
                    if (host.indexOf('$') >= 0) {
                        throw new ProxyClientException(
                                "Invalid Endpoint template, relies on request to resolve valid URL " + u);
                    }
                } catch (MalformedURLException e) {
                    throw new ProxyClientException(
                            "Invalid Endpoint template, relies on request to resolve valid URL", e);
                }
            }

            LOGGER.info("Valied Endpoint Def");

            Map<String, Object> context = Maps.newHashMap(input);

            // add in the config properties from the bundle overwriting
            // everything else.
            context.put("config", configProperties);

            endpointURL = processUrlTemplate(endpointURL, context);

            LOGGER.info("Calling URL {} ", endpointURL);

            ProxyMethod proxyMethod = ProxyMethod.GET;
            if (config.containsKey(CONFIG_REQUEST_PROXY_METHOD)) {
                try {
                    proxyMethod = ProxyMethod.valueOf((String) config.get(CONFIG_REQUEST_PROXY_METHOD));
                } catch (Exception e) {

                }
            }

            HttpClient client = getHttpClient();

            HttpUriRequest method = null;
            switch (proxyMethod) {
            case GET:
                if (config.containsKey(CONFIG_LIMIT_GET_SIZE)) {
                    long maxSize = (Long) config.get(CONFIG_LIMIT_GET_SIZE);
                    HttpHead h = new HttpHead(endpointURL);

                    HttpParams params = h.getParams();
                    // make certain we reject the body of a head
                    params.setBooleanParameter("http.protocol.reject-head-body", true);
                    h.setParams(params);
                    populateMessage(method, config, headers);
                    HttpResponse response = client.execute(h);
                    if (response.getStatusLine().getStatusCode() == 200) {
                        // Check if the content-length is smaller than the
                        // maximum (if any).
                        Header contentLengthHeader = response.getLastHeader("Content-Length");
                        if (contentLengthHeader != null) {
                            long length = Long.parseLong(contentLengthHeader.getValue());
                            if (length > maxSize) {
                                return new ProxyResponseImpl(HttpServletResponse.SC_PRECONDITION_FAILED,
                                        "Response too large", response);
                            }
                        }
                    } else {
                        return new ProxyResponseImpl(response);
                    }
                }
                method = new HttpGet(endpointURL);
                break;
            case HEAD:
                method = new HttpHead(endpointURL);
                break;
            case OPTIONS:
                method = new HttpOptions(endpointURL);
                break;
            case POST:
                method = new HttpPost(endpointURL);
                break;
            case PUT:
                method = new HttpPut(endpointURL);
                break;
            default:
                method = new HttpGet(endpointURL);
            }

            populateMessage(method, config, headers);

            if (requestInputStream == null && !config.containsKey(CONFIG_PROXY_REQUEST_TEMPLATE)) {
                if (method instanceof HttpPost) {
                    HttpPost postMethod = (HttpPost) method;
                    MultipartEntity multipart = new MultipartEntity();
                    for (Entry<String, Object> param : input.entrySet()) {
                        String key = param.getKey();
                        Object value = param.getValue();
                        if (value instanceof Object[]) {
                            for (Object val : (Object[]) value) {
                                addPart(multipart, key, val);
                            }
                        } else {
                            addPart(multipart, key, value);
                        }
                        postMethod.setEntity(multipart);
                    }
                }
            } else {

                if (method instanceof HttpEntityEnclosingRequestBase) {
                    String contentType = requestContentType;
                    if (contentType == null && config.containsKey(CONFIG_REQUEST_CONTENT_TYPE)) {
                        contentType = (String) config.get(CONFIG_REQUEST_CONTENT_TYPE);

                    }
                    if (contentType == null) {
                        contentType = APPLICATION_OCTET_STREAM;
                    }
                    HttpEntityEnclosingRequestBase eemethod = (HttpEntityEnclosingRequestBase) method;
                    if (requestInputStream != null) {
                        eemethod.setHeader(HttpHeaders.CONTENT_TYPE, contentType);
                        eemethod.setEntity(new InputStreamEntity(requestInputStream, requestContentLength));
                    } else {
                        // build the request
                        StringWriter body = new StringWriter();
                        templateService.evaluate(context, body, (String) config.get("path"),
                                (String) config.get(CONFIG_PROXY_REQUEST_TEMPLATE));
                        byte[] soapBodyContent = body.toString().getBytes("UTF-8");
                        eemethod.setHeader(HttpHeaders.CONTENT_TYPE, contentType);
                        eemethod.setEntity(new InputStreamEntity(new ByteArrayInputStream(soapBodyContent),
                                soapBodyContent.length));

                    }
                }
            }

            HttpResponse response = client.execute(method);
            if (response.getStatusLine().getStatusCode() == 302
                    && method instanceof HttpEntityEnclosingRequestBase) {
                // handle redirects on post and put
                String url = response.getFirstHeader("Location").getValue();
                method = new HttpGet(url);
                response = client.execute(method);
            }

            return new ProxyResponseImpl(response);
        }

    } catch (ProxyClientException e) {
        throw e;
    } catch (Exception e) {
        LOGGER.error(e.getMessage(), e);
        throw new ProxyClientException("The Proxy request specified by  " + config + " failed, cause follows:",
                e);
    } finally {
        unbindConfig();
    }
    throw new ProxyClientException(
            "The Proxy request specified by " + config + " does not contain a valid endpoint specification ");
}

From source file:org.eclipse.aether.transport.http.HttpTransporter.java

private void prepare(HttpUriRequest request, SharingHttpContext context) {
    boolean put = HttpPut.METHOD_NAME.equalsIgnoreCase(request.getMethod());
    if (state.getWebDav() == null && (put || isPayloadPresent(request))) {
        try {//w  ww.  j  a  v  a  2  s.  c  o  m
            HttpOptions req = commonHeaders(new HttpOptions(request.getURI()));
            HttpResponse response = client.execute(server, req, context);
            state.setWebDav(isWebDav(response));
            EntityUtils.consumeQuietly(response.getEntity());
        } catch (IOException e) {
            LOGGER.debug("Failed to prepare HTTP context", e);
        }
    }
    if (put && Boolean.TRUE.equals(state.getWebDav())) {
        mkdirs(request.getURI(), context);
    }
}

From source file:org.apache.cxf.systest.jaxrs.cors.CrossOriginSimpleTest.java

@Test
public void simplePostClassAnnotation() throws ClientProtocolException, IOException {
    HttpClient httpclient = HttpClientBuilder.create().build();
    HttpOptions httpoptions = new HttpOptions("http://localhost:" + PORT + "/antest/unannotatedPost");
    httpoptions.addHeader("Origin", "http://in.org");
    // nonsimple header
    httpoptions.addHeader("Content-Type", "text/plain");
    httpoptions.addHeader(CorsHeaderConstants.HEADER_AC_REQUEST_METHOD, "POST");
    HttpResponse response = httpclient.execute(httpoptions);
    assertEquals(200, response.getStatusLine().getStatusCode());
    if (httpclient instanceof Closeable) {
        ((Closeable) httpclient).close();
    }//from   ww  w.  ja va2  s  .  c  o m

}

From source file:com.nesscomputing.httpclient.factory.httpclient4.ApacheHttpClient4Factory.java

@Override
public <T> T performRequest(final HttpClientRequest<T> incomingRequest) throws IOException {
    checkRunning();/*from   w  w w  . j  a  va  2s  . c o m*/

    HttpClientRequest<T> request = incomingRequest;

    if (CollectionUtils.isNotEmpty(httpClientObservers)) {
        LOG.trace("Executing Observers");
        for (HttpClientObserver observer : httpClientObservers) {
            request = observer.<T>onRequestSubmitted(request);
        }

        if (request != incomingRequest) {
            LOG.trace("Request was modified by Observers!");
        }
    }

    request = contributeAcceptEncoding(request);

    LOG.trace("Got a '%s' request", request.getHttpMethod());

    switch (request.getHttpMethod()) {
    case DELETE:
        return executeRequest(new HttpDelete(request.getUri()), request);

    case HEAD:
        return executeRequest(new HttpHead(request.getUri()), request);

    case OPTIONS:
        return executeRequest(new HttpOptions(request.getUri()), request);

    case POST:
        final HttpPost httpPost = new HttpPost(request.getUri());
        final HttpClientBodySource postSource = request.getHttpBodySource();

        if (postSource instanceof InternalHttpBodySource) {
            httpPost.setEntity(((InternalHttpBodySource) postSource).getHttpEntity());
        }
        return executeRequest(httpPost, request);

    case PUT:
        final HttpPut httpPut = new HttpPut(request.getUri());
        final HttpClientBodySource putSource = request.getHttpBodySource();

        if (putSource instanceof InternalHttpBodySource) {
            httpPut.setEntity(((InternalHttpBodySource) putSource).getHttpEntity());
        }
        return executeRequest(httpPut, request);

    case GET:
        return executeRequest(new HttpGet(request.getUri()), request);

    default:
        LOG.warn("Got an unknown request type: '%s', falling back to GET", request.getHttpMethod());
        return executeRequest(new HttpGet(request.getUri()), request);
    }
}

From source file:org.apache.hadoop.gateway.dispatch.DefaultDispatch.java

@Override
public void doOptions(URI url, HttpServletRequest request, HttpServletResponse response)
        throws IOException, URISyntaxException {
    HttpOptions method = new HttpOptions(url);
    executeRequest(method, request, response);
}

From source file:com.machinepublishers.jbrowserdriver.StreamConnection.java

/**
 * {@inheritDoc}/*from   w w  w  .j av a  2  s.  c om*/
 */
@Override
public void connect() throws IOException {
    try {
        if (connected.compareAndSet(false, true)) {
            if (StatusMonitor.instance().isDiscarded(urlString)) {
                skip.set(true);
                LogsServer.instance().trace("Media skipped: " + urlString);
            } else if (isBlocked(url.getHost())) {
                skip.set(true);
            } else if (SettingsManager.settings() != null) {
                config.get().setCookieSpec("custom")
                        .setSocketTimeout(SettingsManager.settings().socketTimeout())
                        .setConnectTimeout(SettingsManager.settings().connectTimeout())
                        .setConnectionRequestTimeout(SettingsManager.settings().connectionReqTimeout());
                URI uri = null;
                try {
                    uri = url.toURI();
                } catch (URISyntaxException e) {
                    //decode components of the url first, because often the problem is partially encoded urls
                    uri = new URI(url.getProtocol(), url.getAuthority(),
                            url.getPath() == null ? null : URLDecoder.decode(url.getPath(), "utf-8"),
                            url.getQuery() == null ? null : URLDecoder.decode(url.getQuery(), "utf-8"),
                            url.getRef() == null ? null : URLDecoder.decode(url.getRef(), "utf-8"));
                }
                if ("OPTIONS".equals(method.get())) {
                    req.set(new HttpOptions(uri));
                } else if ("GET".equals(method.get())) {
                    req.set(new HttpGet(uri));
                } else if ("HEAD".equals(method.get())) {
                    req.set(new HttpHead(uri));
                } else if ("POST".equals(method.get())) {
                    req.set(new HttpPost(uri));
                } else if ("PUT".equals(method.get())) {
                    req.set(new HttpPut(uri));
                } else if ("DELETE".equals(method.get())) {
                    req.set(new HttpDelete(uri));
                } else if ("TRACE".equals(method.get())) {
                    req.set(new HttpTrace(uri));
                }
                processHeaders(SettingsManager.settings(), req.get());
                ProxyConfig proxy = SettingsManager.settings().proxy();
                if (proxy != null && !proxy.directConnection()
                        && !proxy.nonProxyHosts().contains(uri.getHost())) {
                    config.get().setExpectContinueEnabled(proxy.expectContinue());
                    InetSocketAddress proxyAddress = new InetSocketAddress(proxy.host(), proxy.port());
                    if (proxy.type() == ProxyConfig.Type.SOCKS) {
                        context.get().setAttribute("proxy.socks.address", proxyAddress);
                    } else {
                        config.get().setProxy(new HttpHost(proxy.host(), proxy.port()));
                    }
                }
                context.get().setCookieStore(cookieStore);
                context.get().setRequestConfig(config.get().build());
                StatusMonitor.instance().monitor(url, this);
            }
        }
    } catch (Throwable t) {
        throw new IOException(t.getMessage() + ": " + urlString, t);
    }
}

From source file:com.ibm.sbt.service.basic.ProxyService.java

protected HttpRequestBase createMethod(String smethod, URI uri, HttpServletRequest request)
        throws ServletException {
    Object timedObject = ProxyProfiler.getTimedObject();
    if (getDebugHook() != null) {
        getDebugHook().getDumpRequest().setMethod(smethod);
        getDebugHook().getDumpRequest().setUrl(uri.toString());
    }/*from w w w . j  ava  2 s  .c o m*/
    if (smethod.equalsIgnoreCase("get")) {
        HttpGet method = new HttpGet(uri);
        ProxyProfiler.profileTimedRequest(timedObject, "create HttpGet");
        return method;
    } else if (smethod.equalsIgnoreCase("put")) {
        HttpPut method = new HttpPut(uri);
        method = (HttpPut) prepareMethodWithUpdatedContent(method, request);
        ProxyProfiler.profileTimedRequest(timedObject, "create HttpPut");
        return method;
    } else if (smethod.equalsIgnoreCase("post")) {
        HttpPost method = new HttpPost(uri);
        method = (HttpPost) prepareMethodWithUpdatedContent(method, request);
        ProxyProfiler.profileTimedRequest(timedObject, "create HttpPost");
        return method;
    } else if (smethod.equalsIgnoreCase("delete")) {
        HttpDelete method = new HttpDelete(uri);
        ProxyProfiler.profileTimedRequest(timedObject, "create HttpDelete");
        return method;
    } else if (smethod.equalsIgnoreCase("head")) {
        HttpHead method = new HttpHead(uri);
        ProxyProfiler.profileTimedRequest(timedObject, "create HttpHead");
        return method;
    } else if (smethod.equalsIgnoreCase("options")) {
        HttpOptions method = new HttpOptions(uri);
        ProxyProfiler.profileTimedRequest(timedObject, "create HttpOptions");
        return method;
    } else {
        ProxyProfiler.profileTimedRequest(timedObject, "failed creating method");
        throw new ServletException("Illegal method, should be GET, PUT, POST, DELETE or HEAD");
    }
}

From source file:com.github.restdriver.clientdriver.integration.ClientDriverSuccessTest.java

@Test
public void testHttpOPTIONS() throws Exception {

    String baseUrl = driver.getBaseUrl();
    driver.addExpectation(onRequestTo("/blah2").withMethod(Method.OPTIONS),
            giveResponse(null, null).withStatus(200).withHeader("Allow", "POST, OPTIONS"));

    HttpClient client = new DefaultHttpClient();
    HttpOptions options = new HttpOptions(baseUrl + "/blah2");
    HttpResponse response = client.execute(options);

    assertThat(response.getStatusLine().getStatusCode(), is(200));
    assertThat(response.getHeaders("Allow")[0].getValue(), equalTo("POST, OPTIONS"));
}