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.wso2.am.integration.tests.other.APIMANAGER3965TestCase.java

@Test(groups = { "wso2.am" }, description = "Sample API creation")
public void testAPICreationWithOutCorsConfiguration() throws Exception {
    apiRequest.setProvider(user.getUserName());
    apiPublisher.addAPI(apiRequest);//from  w ww  .j a v  a  2  s .co  m
    APILifeCycleStateRequest updateRequest = new APILifeCycleStateRequest(apiName, user.getUserName(),
            APILifeCycleState.PUBLISHED);
    apiPublisher.changeAPILifeCycleStatus(updateRequest);

    waitForAPIDeploymentSync(apiRequest.getProvider(), apiRequest.getName(), apiRequest.getVersion(),
            APIMIntegrationConstants.IS_API_EXISTS);
    String apiInvocationUrl = getAPIInvocationURLHttp(apiContext + "/1.0.0/customers/123");

    HttpClient httpclient = HttpClientBuilder.create().build();
    HttpUriRequest option = new HttpOptions(apiInvocationUrl);
    option.addHeader("Origin", "http://localhost:9443");
    HttpResponse serviceResponse = httpclient.execute(option);
    String accessControlAllowOrigin = serviceResponse.getFirstHeader("Access-Control-Allow-Origin").getValue();
    String accessControlAllowHeaders = serviceResponse.getFirstHeader("Access-Control-Allow-Headers")
            .getValue();
    String accessControlAllowMethods = serviceResponse.getFirstHeader("Access-Control-Allow-Methods")
            .getValue();
    assertEquals(serviceResponse.getStatusLine().getStatusCode(), Response.Status.OK.getStatusCode(),
            "Response code mismatched when api invocation");
    assertEquals(accessControlAllowOrigin, "*",
            "Access Control allow origin values get mismatched in option Call");
    assertEquals(accessControlAllowHeaders, "authorization,Access-Control-Allow-Origin,Content-Type,SOAPAction",
            "Access Control allow Headers values get mismatched in option Call");
    assertTrue(accessControlAllowMethods.contains("GET") && accessControlAllowMethods.contains("POST")
            && !accessControlAllowMethods.contains("DELETE") && !accessControlAllowMethods.contains("PUT")
            && !accessControlAllowMethods.contains("PATCH"),
            "Access Control allow Method values get mismatched in option Call");
}

From source file:com.vanillasource.gerec.httpclient.AsyncApacheHttpClient.java

@Override
public CompletableFuture<HttpResponse> doOptions(URI uri, HttpRequest.HttpRequestChange change) {
    return execute(new HttpOptions(uri), change);
}

From source file:org.sonatype.nexus.test.utils.hc4client.Hc4MethodCall.java

/**
 * Constructor.//  w  w  w  . ja  va  2 s  .  c o  m
 *
 * @param helper     The parent HTTP client helper.
 * @param method     The method name.
 * @param requestUri The request URI.
 * @param hasEntity  Indicates if the call will have an entity to send to the server.
 */
public Hc4MethodCall(Hc4ClientHelper helper, final String method, String requestUri, boolean hasEntity)
        throws IOException {
    super(helper, method, requestUri);
    this.clientHelper = helper;

    if (requestUri.startsWith("http")) {
        if (method.equalsIgnoreCase(Method.GET.getName())) {
            this.httpMethod = new HttpGet(requestUri);
        } else if (method.equalsIgnoreCase(Method.POST.getName())) {
            this.httpMethod = new HttpPost(requestUri);
        } else if (method.equalsIgnoreCase(Method.PUT.getName())) {
            this.httpMethod = new HttpPut(requestUri);
        } else if (method.equalsIgnoreCase(Method.HEAD.getName())) {
            this.httpMethod = new HttpHead(requestUri);
        } else if (method.equalsIgnoreCase(Method.DELETE.getName())) {
            this.httpMethod = new HttpDelete(requestUri);
        } else if (method.equalsIgnoreCase(Method.CONNECT.getName())) {
            // CONNECT unsupported (and is unused by legacy ITs)
            throw new UnsupportedOperationException("Not implemented");
        } else if (method.equalsIgnoreCase(Method.OPTIONS.getName())) {
            this.httpMethod = new HttpOptions(requestUri);
        } else if (method.equalsIgnoreCase(Method.TRACE.getName())) {
            this.httpMethod = new HttpTrace(requestUri);
        } else {
            // custom HTTP verbs unsupported (and is unused by legacy ITs)
            throw new UnsupportedOperationException("Not implemented");
        }

        this.httpMethod.getParams().setBooleanParameter(ClientPNames.HANDLE_REDIRECTS,
                this.clientHelper.isFollowRedirects());
        // retry handler setting unsupported (legaacy ITs use default HC4 retry handler)
        this.responseHeadersAdded = false;
        setConfidential(this.httpMethod.getURI().getScheme().equalsIgnoreCase(Protocol.HTTPS.getSchemeName()));
    } else {
        throw new IllegalArgumentException("Only HTTP or HTTPS resource URIs are allowed here");
    }
}

From source file:com.griddynamics.jagger.invoker.http.HttpInvoker.java

private HttpRequestBase createMethod(HttpQuery query, URI uri) throws UnsupportedEncodingException {
    HttpRequestBase method;/*from  w  ww . j a v  a 2  s. co  m*/
    switch (query.getMethod()) {
    case POST:
        method = new HttpPost(uri);
        List<NameValuePair> nameValuePairs = new ArrayList<NameValuePair>();
        for (Map.Entry<String, String> methodParam : query.getMethodParams().entrySet()) {
            nameValuePairs.add(new BasicNameValuePair(methodParam.getKey(), methodParam.getValue()));
        }
        ((HttpPost) method).setEntity(new UrlEncodedFormEntity(nameValuePairs));
        break;
    case PUT:
        method = new HttpPut(uri);
        break;
    case GET:
        method = new HttpGet(uri);
        break;
    case DELETE:
        method = new HttpDelete(uri);
        break;
    case TRACE:
        method = new HttpTrace(uri);
        break;
    case HEAD:
        method = new HttpHead(uri);
        break;
    case OPTIONS:
        method = new HttpOptions(uri);
        break;
    default:
        throw new UnsupportedOperationException(
                "Invoker does not support \"" + query.getMethod() + "\" HTTP request.");
    }
    return method;
}

From source file:de.adorsys.forge.plugin.curl.CurlPlugin.java

private HttpUriRequest createRequest(final String url, RequestMethod command, String headers) {
    HttpUriRequest request;/*w w w .  j  av  a2  s .  co m*/

    switch (command) {

    case HEAD:
        request = new HttpHead(url);
        break;

    case OPTIONS:
        request = new HttpOptions(url);
        break;

    case POST:
        request = new HttpPost(url);
        break;

    case PUT:
        request = new HttpPut(url);
        break;

    default:
        request = new HttpGet(url);
        break;
    }

    setHeaders(request, headers);

    return request;
}

From source file:com.github.tomakehurst.wiremock.http.HttpClientFactory.java

public static HttpUriRequest getHttpRequestFor(RequestMethod method, String url) {
    notifier().info("Proxying: " + method + " " + url);

    if (method.equals(GET))
        return new HttpGet(url);
    else if (method.equals(POST))
        return new HttpPost(url);
    else if (method.equals(PUT))
        return new HttpPut(url);
    else if (method.equals(DELETE))
        return new HttpDelete(url);
    else if (method.equals(HEAD))
        return new HttpHead(url);
    else if (method.equals(OPTIONS))
        return new HttpOptions(url);
    else if (method.equals(TRACE))
        return new HttpTrace(url);
    else if (method.equals(PATCH))
        return new HttpPatch(url);
    else/*from   w  w w  .  j  a  v a2  s  . c  o  m*/
        return new GenericHttpUriRequest(method.toString(), url);
}

From source file:net.gcolin.httpquery.HttpHandlerImpl.java

@Override
public Request options(String uri) {
    return new RequestImpl(new HttpOptions(uri));
}

From source file:com.lovebridge.library.volley.toolbox.HttpClientStack.java

/**
 * Creates the appropriate subclass of HttpUriRequest for passed in request.
 *//*from  ww  w  . ja  v  a2 s.  c  om*/
@SuppressWarnings("deprecation")
/* protected */ static HttpUriRequest createHttpRequest(Request<?> request,
        Map<String, String> additionalHeaders) throws AuthFailureError {
    switch (request.getMethod()) {
    case Method.DEPRECATED_GET_OR_POST: {
        // This is the deprecated way that needs to be handled for
        // backwards compatibility.
        // If the request's post body is null, then the assumption is
        // that the request is
        // GET. Otherwise, it is assumed that the request is a POST.
        byte[] postBody = request.getPostBody();
        if (postBody != null) {
            HttpPost postRequest = new HttpPost(request.getUrl());
            postRequest.addHeader(HEADER_CONTENT_TYPE, request.getPostBodyContentType());
            HttpEntity entity;
            entity = new ByteArrayEntity(postBody);
            postRequest.setEntity(entity);
            return postRequest;
        } else {
            return new HttpGet(request.getUrl());
        }
    }
    case Method.GET:
        return new HttpGet(request.getUrl());
    case Method.DELETE:
        return new HttpDelete(request.getUrl());
    case Method.POST: {
        HttpPost postRequest = new HttpPost(request.getUrl());
        postRequest.addHeader(HEADER_CONTENT_TYPE, request.getBodyContentType());
        setEntityIfNonEmptyBody(postRequest, request);
        return postRequest;
    }
    case Method.PUT: {
        HttpPut putRequest = new HttpPut(request.getUrl());
        putRequest.addHeader(HEADER_CONTENT_TYPE, request.getBodyContentType());
        setEntityIfNonEmptyBody(putRequest, request);
        return putRequest;
    }
    case Method.HEAD:
        return new HttpHead(request.getUrl());
    case Method.OPTIONS:
        return new HttpOptions(request.getUrl());
    case Method.TRACE:
        return new HttpTrace(request.getUrl());
    case Method.PATCH: {
        HttpPatch patchRequest = new HttpPatch(request.getUrl());
        patchRequest.addHeader(HEADER_CONTENT_TYPE, request.getBodyContentType());
        setEntityIfNonEmptyBody(patchRequest, request);
        return patchRequest;
    }
    default:
        throw new IllegalStateException("Unknown request method.");
    }
}

From source file:com.sayar.requests.impl.HttpClientRequestHandler.java

public Response execute(final RequestArguments args) throws AuthenticationException, InvalidParameterException {
    // Parse params
    final String url = args.getUrl();
    final Map<String, String> params = args.getParams();
    final HttpAuthentication httpAuth = args.getHttpAuth();

    String formattedUrl;/*from w ww . j av a 2 s . co m*/
    try {
        formattedUrl = RequestHandlerUtils.formatUrl(url, params);
    } catch (final UnsupportedEncodingException e) {
        Log.e(RequestsConstants.LOG_TAG, "Unsupported Encoding Exception in Url Parameters.", e);
        throw new InvalidParameterException("Url Parameter Encoding is invalid.");

    }

    final RequestMethod method = args.getMethod();
    HttpUriRequest request = null;
    if (method == RequestMethod.GET) {
        request = new HttpGet(formattedUrl);
    } else if (method == RequestMethod.DELETE) {
        request = new HttpDelete(formattedUrl);
    } else if (method == RequestMethod.OPTIONS) {
        request = new HttpOptions(formattedUrl);
    } else if (method == RequestMethod.HEAD) {
        request = new HttpHead(formattedUrl);
    } else if (method == RequestMethod.TRACE) {
        request = new HttpTrace(formattedUrl);
    } else if (method == RequestMethod.POST || method == RequestMethod.PUT) {
        request = method == RequestMethod.POST ? new HttpPost(formattedUrl) : new HttpPut(formattedUrl);
        if (args.getRequestEntity() != null) {
            ((HttpEntityEnclosingRequestBase) request).setEntity(args.getRequestEntity());
        }
    } else {
        throw new InvalidParameterException("Request Method is not set.");
    }

    if (httpAuth != null) {
        try {
            HttpClientRequestHandler.addAuthentication(request, httpAuth);
        } catch (final AuthenticationException e) {
            Log.e(RequestsConstants.LOG_TAG, "Adding Authentication Failed.", e);
            throw e;
        }
    }
    if (args.getHeaders() != null) {
        HttpClientRequestHandler.addHeaderParams(request, args.getHeaders());
    }

    final Response response = new Response();

    final HttpClient client = this.getHttpClient(args);

    try {
        final HttpResponse httpResponse = client.execute(request);

        response.setResponseVersion(httpResponse.getProtocolVersion());
        response.setStatusAndCode(httpResponse.getStatusLine());

        final HttpEntity entity = httpResponse.getEntity();

        if (entity != null) {
            // Convert the stream into a string and store into the RAW
            // field.
            // InputStream instream = entity.getContent();
            // response.setRaw(RequestHandlerUtils.convertStreamToString(instream));
            // instream.close(); // Closing the input stream will trigger
            // connection release

            // TODO: Perhaps we should be dealing with the charset
            response.setRaw(EntityUtils.toString(entity));

            try {
                // Get the Content Type
                final String contenttype = entity.getContentType().getValue();

                RequestParser parser = null;

                // Check if a request-specific parser was set.
                if (args.getRequestParser() == null) {
                    // Parse the request according to the user's wishes.
                    final String extractionFormat = args.getParseAs();

                    // Determine extraction format if none are set.
                    if (extractionFormat == null) {
                        // If we can not find an appropriate parser, the
                        // default one will be returned.
                        parser = RequestParserFactory.findRequestParser(contenttype);
                    } else {
                        // Try to get the requested parser. This will throw
                        // an exception if we can't get it.
                        parser = RequestParserFactory.getRequestParser(extractionFormat);
                    }
                } else {
                    // Set a request specific parser.
                    parser = args.getRequestParser();
                }

                // Parse the content.. and if it throws an exception log it.
                final Object result = parser.parse(response.getRaw());
                // Check the result of the parser.
                if (result != null) {
                    response.setContent(result);
                    response.setParsedAs(parser.getName());
                } else {
                    // If the parser returned nothing (and most likely it
                    // wasn't the default parser).

                    // We already have the raw response, user the default
                    // parser fallback.
                    response.setContent(RequestParserFactory.DEFAULT_PARSER.parse(response.getRaw()));
                    response.setParsedAs(RequestParserFactory.DEFAULT_PARSER.getName());
                }
            } catch (final InvalidParameterException e) {
                Log.e(RequestsConstants.LOG_TAG, "Parser Requested Could Not Be Found.", e);
                throw e;
            } catch (final Exception e) {
                // Catch any parsing exception.
                Log.e(RequestsConstants.LOG_TAG, "Parser Failed Exception.", e);
                // Informed it was parsed as nothing... aka look at the raw
                // string.
                response.setParsedAs(null);
            }

        } else {
            if (args.getMethod() != RequestMethod.HEAD) {
                Log.w(RequestsConstants.LOG_TAG, "Entity is empty?");
            }
        }
    } catch (final ClientProtocolException e) {
        Log.e(RequestsConstants.LOG_TAG, "Client Protocol Exception", e);
    } catch (final IOException e) {
        Log.e(RequestsConstants.LOG_TAG, "IO Exception.", e);
    } finally {
    }

    return response;
}

From source file:org.jboss.as.test.integration.web.security.servlet.methods.DenyUncoveredHttpMethodsTestCase.java

@Test
public void testOptionsMethod() throws Exception {
    HttpOptions httpOptions = new HttpOptions(getURL());
    HttpResponse response = getHttpResponse(httpOptions);

    assertThat(statusCodeOf(response), is(HttpServletResponse.SC_FORBIDDEN));
}