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:illab.nabal.proxy.AbstractContext.java

/**
  * Get HTTP OPTIONS object./*from   w ww .ja  v a2  s  .  c  o m*/
 * 
 * @param apiUri
 * @return HttpOptions
 * @throws Exception
 */
protected synchronized HttpOptions getHttpOptions(String apiUri) throws Exception {
    return new HttpOptions(new URI(getApiHost() + apiUri));
}

From source file:org.georchestra.security.Proxy.java

private HttpRequestBase makeRequest(HttpServletRequest request, RequestType requestType, String sURL)
        throws IOException {
    HttpRequestBase targetRequest;/*from   www .j av  a  2  s .c  o m*/
    try {
        // Split URL
        URL url = new URL(sURL);
        URI uri = buildUri(url);

        switch (requestType) {
        case GET: {
            logger.debug("New request is: " + sURL + "\nRequest is GET");

            HttpGet get = new HttpGet(uri);
            targetRequest = get;
            break;
        }
        case POST: {
            logger.debug("New request is: " + sURL + "\nRequest is POST");

            HttpPost post = new HttpPost(uri);
            HttpEntity entity;
            request.setCharacterEncoding("UTF8");
            if (isFormContentType(request)) {
                logger.debug("Post is recognized as a form post.");
                List<NameValuePair> parameters = new ArrayList<NameValuePair>();
                for (Enumeration e = request.getParameterNames(); e.hasMoreElements();) {
                    String name = (String) e.nextElement();
                    String[] v = request.getParameterValues(name);
                    for (String value : v) {
                        NameValuePair nv = new BasicNameValuePair(name, value);
                        parameters.add(nv);
                    }
                }
                String charset = request.getCharacterEncoding();
                try {
                    Charset.forName(charset);
                } catch (Throwable t) {
                    charset = null;
                }
                if (charset == null) {
                    charset = defaultCharset;
                }
                entity = new UrlEncodedFormEntity(parameters, charset);
                post.setEntity(entity);

            } else {
                logger.debug("Post is NOT recognized as a form post. (Not an error, just a comment)");
                int contentLength = request.getContentLength();
                ServletInputStream inputStream = request.getInputStream();
                entity = new InputStreamEntity(inputStream, contentLength);
            }
            post.setEntity(entity);
            targetRequest = post;
            break;
        }
        case TRACE: {
            logger.debug("New request is: " + sURL + "\nRequest is TRACE");

            HttpTrace post = new HttpTrace(uri);

            targetRequest = post;
            break;
        }
        case OPTIONS: {
            logger.debug("New request is: " + sURL + "\nRequest is OPTIONS");

            HttpOptions post = new HttpOptions(uri);

            targetRequest = post;
            break;
        }
        case HEAD: {
            logger.debug("New request is: " + sURL + "\nRequest is HEAD");

            HttpHead post = new HttpHead(uri);

            targetRequest = post;
            break;
        }
        case PUT: {
            logger.debug("New request is: " + sURL + "\nRequest is PUT");

            HttpPut put = new HttpPut(uri);

            put.setEntity(new InputStreamEntity(request.getInputStream(), request.getContentLength()));

            targetRequest = put;
            break;
        }
        case DELETE: {
            logger.debug("New request is: " + sURL + "\nRequest is DELETE");

            HttpDelete delete = new HttpDelete(uri);

            targetRequest = delete;
            break;
        }
        default: {
            String msg = requestType + " not yet supported";
            logger.error(msg);
            throw new IllegalArgumentException(msg);
        }

        }
    } catch (URISyntaxException e) {
        logger.error("ERROR creating URI from " + sURL, e);
        throw new IOException(e);
    }

    return targetRequest;
}

From source file:com.rockagen.commons.http.HttpConn.java

/**
 * Get Http method instance by {@link com.rockagen.commons.http.RequestMethod}
 *
 * @param method {@link RequestMethod}//  ww  w . java 2  s . c  o  m
 * @param uri  the uri
 * @return {@link HttpRequestBase}
 */
private static HttpRequestBase getHttpMethod(RequestMethod method, String uri) {
    HttpRequestBase hm;
    if (method != null) {
        switch (method) {
        case POST:
            hm = new HttpPost(uri);
            break;
        case GET:
            hm = new HttpGet(uri);
            break;
        case PUT:
            hm = new HttpPut(uri);
            break;
        case DELETE:
            hm = new HttpDelete(uri);
            break;
        case HEAD:
            hm = new HttpHead(uri);
            break;
        case OPTIONS:
            hm = new HttpOptions(uri);
            break;
        case TRACE:
            hm = new HttpTrace(uri);
            break;
        case PATCH:
            hm = new HttpPatch(uri);
            break;
        default:
            hm = new HttpGet(uri);
            break;
        }
    } else
        hm = new HttpGet(uri);
    return hm;
}

From source file:org.dasein.cloud.azure.AzureStorageMethod.java

protected HttpRequestBase getMethod(@Nonnull String httpMethod, @Nonnull String endpoint,
        @Nonnull Map<String, String> queryParams, @Nullable Map<String, String> headers, boolean authorization)
        throws CloudException, InternalException {
    HttpRequestBase method;//ww  w.  jav a2 s  .  c o m

    if (httpMethod.equals("GET")) {
        method = new HttpGet(endpoint);
    } else if (httpMethod.equals("POST")) {
        method = new HttpPost(endpoint);
    } else if (httpMethod.equals("PUT")) {
        method = new HttpPut(endpoint);
    } else if (httpMethod.equals("DELETE")) {
        method = new HttpDelete(endpoint);
    } else if (httpMethod.equals("HEAD")) {
        method = new HttpHead(endpoint);
    } else if (httpMethod.equals("OPTIONS")) {
        method = new HttpOptions(endpoint);
    } else if (httpMethod.equals("HEAD")) {
        method = new HttpTrace(endpoint);
    } else {
        method = new HttpGet(endpoint);
    }
    if (!authorization) {
        return method;
    }
    if (headers == null) {
        headers = new TreeMap<String, String>();
    }

    String RFC1123_PATTERN = "EEE, dd MMM yyyy HH:mm:ss z";
    DateFormat rfc1123Format = new SimpleDateFormat(RFC1123_PATTERN);

    rfc1123Format.setTimeZone(TimeZone.getTimeZone("GMT"));
    headers.put("Date", rfc1123Format.format(new Date()));
    headers.put(Header_Prefix_MS + "version", VERSION);
    for (String key : headers.keySet()) {
        method.addHeader(key, headers.get(key));
    }

    if (method.getFirstHeader("content-type") == null && !httpMethod.equals("GET")) {
        method.addHeader("content-type", "application/xml;charset=utf-8");
    }
    method.addHeader("Authorization", "SharedKeyLite " + getStorageAccount() + ":"
            + calculatedSharedKeyLiteSignature(method, queryParams));
    return method;
}

From source file:com.android.exchange.EasSyncService.java

protected HttpResponse sendHttpClientOptions() throws IOException {
    HttpClient client = getHttpClient(COMMAND_TIMEOUT);
    String us = makeUriString("OPTIONS", null);
    HttpOptions method = new HttpOptions(URI.create(us));
    setHeaders(method, false);/*from  www.  j  a v a 2  s.c om*/
    return client.execute(method);
}

From source file:org.apache.jmeter.protocol.http.sampler.HTTPHC4Impl.java

@Override
protected HTTPSampleResult sample(URL url, String method, boolean areFollowingRedirect, int frameDepth) {

    if (log.isDebugEnabled()) {
        log.debug("Start : sample " + url.toString());
        log.debug("method " + method + " followingRedirect " + areFollowingRedirect + " depth " + frameDepth);
    }//from  ww  w.  j av  a2s  . co  m

    HTTPSampleResult res = createSampleResult(url, method);

    HttpClient httpClient = setupClient(url, res);

    HttpRequestBase httpRequest = null;
    try {
        URI uri = url.toURI();
        if (method.equals(HTTPConstants.POST)) {
            httpRequest = new HttpPost(uri);
        } else if (method.equals(HTTPConstants.GET)) {
            httpRequest = new HttpGet(uri);
        } else if (method.equals(HTTPConstants.PUT)) {
            httpRequest = new HttpPut(uri);
        } else if (method.equals(HTTPConstants.HEAD)) {
            httpRequest = new HttpHead(uri);
        } else if (method.equals(HTTPConstants.TRACE)) {
            httpRequest = new HttpTrace(uri);
        } else if (method.equals(HTTPConstants.OPTIONS)) {
            httpRequest = new HttpOptions(uri);
        } else if (method.equals(HTTPConstants.DELETE)) {
            httpRequest = new HttpDelete(uri);
        } else if (method.equals(HTTPConstants.PATCH)) {
            httpRequest = new HttpPatch(uri);
        } else if (HttpWebdav.isWebdavMethod(method)) {
            httpRequest = new HttpWebdav(method, uri);
        } else {
            throw new IllegalArgumentException("Unexpected method: '" + method + "'");
        }
        setupRequest(url, httpRequest, res); // can throw IOException
    } catch (Exception e) {
        res.sampleStart();
        res.sampleEnd();
        errorResult(e, res);
        return res;
    }

    HttpContext localContext = new BasicHttpContext();
    setupClientContextBeforeSample(localContext);

    res.sampleStart();

    final CacheManager cacheManager = getCacheManager();
    if (cacheManager != null && HTTPConstants.GET.equalsIgnoreCase(method)) {
        if (cacheManager.inCache(url)) {
            return updateSampleResultForResourceInCache(res);
        }
    }

    try {
        currentRequest = httpRequest;
        handleMethod(method, res, httpRequest, localContext);
        // store the SampleResult in LocalContext to compute connect time
        localContext.setAttribute(SAMPLER_RESULT_TOKEN, res);
        // perform the sample
        HttpResponse httpResponse = executeRequest(httpClient, httpRequest, localContext, url);

        // Needs to be done after execute to pick up all the headers
        final HttpRequest request = (HttpRequest) localContext.getAttribute(HttpCoreContext.HTTP_REQUEST);
        extractClientContextAfterSample(localContext);
        // We've finished with the request, so we can add the LocalAddress to it for display
        final InetAddress localAddr = (InetAddress) httpRequest.getParams()
                .getParameter(ConnRoutePNames.LOCAL_ADDRESS);
        if (localAddr != null) {
            request.addHeader(HEADER_LOCAL_ADDRESS, localAddr.toString());
        }
        res.setRequestHeaders(getConnectionHeaders(request));

        Header contentType = httpResponse.getLastHeader(HTTPConstants.HEADER_CONTENT_TYPE);
        if (contentType != null) {
            String ct = contentType.getValue();
            res.setContentType(ct);
            res.setEncodingAndType(ct);
        }
        HttpEntity entity = httpResponse.getEntity();
        if (entity != null) {
            res.setResponseData(readResponse(res, entity.getContent(), (int) entity.getContentLength()));
        }

        res.sampleEnd(); // Done with the sampling proper.
        currentRequest = null;

        // Now collect the results into the HTTPSampleResult:
        StatusLine statusLine = httpResponse.getStatusLine();
        int statusCode = statusLine.getStatusCode();
        res.setResponseCode(Integer.toString(statusCode));
        res.setResponseMessage(statusLine.getReasonPhrase());
        res.setSuccessful(isSuccessCode(statusCode));

        res.setResponseHeaders(getResponseHeaders(httpResponse, localContext));
        if (res.isRedirect()) {
            final Header headerLocation = httpResponse.getLastHeader(HTTPConstants.HEADER_LOCATION);
            if (headerLocation == null) { // HTTP protocol violation, but avoids NPE
                throw new IllegalArgumentException(
                        "Missing location header in redirect for " + httpRequest.getRequestLine());
            }
            String redirectLocation = headerLocation.getValue();
            res.setRedirectLocation(redirectLocation);
        }

        // record some sizes to allow HTTPSampleResult.getBytes() with different options
        HttpConnectionMetrics metrics = (HttpConnectionMetrics) localContext.getAttribute(CONTEXT_METRICS);
        long headerBytes = res.getResponseHeaders().length() // condensed length (without \r)
                + httpResponse.getAllHeaders().length // Add \r for each header
                + 1 // Add \r for initial header
                + 2; // final \r\n before data
        long totalBytes = metrics.getReceivedBytesCount();
        res.setHeadersSize((int) headerBytes);
        res.setBodySize((int) (totalBytes - headerBytes));
        if (log.isDebugEnabled()) {
            log.debug("ResponseHeadersSize=" + res.getHeadersSize() + " Content-Length=" + res.getBodySize()
                    + " Total=" + (res.getHeadersSize() + res.getBodySize()));
        }

        // If we redirected automatically, the URL may have changed
        if (getAutoRedirects()) {
            HttpUriRequest req = (HttpUriRequest) localContext.getAttribute(HttpCoreContext.HTTP_REQUEST);
            HttpHost target = (HttpHost) localContext.getAttribute(HttpCoreContext.HTTP_TARGET_HOST);
            URI redirectURI = req.getURI();
            if (redirectURI.isAbsolute()) {
                res.setURL(redirectURI.toURL());
            } else {
                res.setURL(new URL(new URL(target.toURI()), redirectURI.toString()));
            }
        }

        // Store any cookies received in the cookie manager:
        saveConnectionCookies(httpResponse, res.getURL(), getCookieManager());

        // Save cache information
        if (cacheManager != null) {
            cacheManager.saveDetails(httpResponse, res);
        }

        // Follow redirects and download page resources if appropriate:
        res = resultProcessing(areFollowingRedirect, frameDepth, res);

    } catch (IOException e) {
        log.debug("IOException", e);
        if (res.getEndTime() == 0) {
            res.sampleEnd();
        }
        // pick up headers if failed to execute the request
        if (res.getRequestHeaders() != null) {
            log.debug("Overwriting request old headers: " + res.getRequestHeaders());
        }
        res.setRequestHeaders(
                getConnectionHeaders((HttpRequest) localContext.getAttribute(HttpCoreContext.HTTP_REQUEST)));
        errorResult(e, res);
        return res;
    } catch (RuntimeException e) {
        log.debug("RuntimeException", e);
        if (res.getEndTime() == 0) {
            res.sampleEnd();
        }
        errorResult(e, res);
        return res;
    } finally {
        currentRequest = null;
        JMeterContextService.getContext().getSamplerContext().remove(HTTPCLIENT_TOKEN);
    }
    return res;
}

From source file:org.apache.nutch.protocol.httpclient.HttpClientRedirectStrategy.java

public HttpUriRequest getRedirect(final HttpRequest request, final HttpResponse response,
        final HttpContext context) throws ProtocolException {
    URI uri = getLocationURI(request, response, context);
    String method = request.getRequestLine().getMethod();
    if (method.equalsIgnoreCase(HttpHead.METHOD_NAME)) {
        return new HttpHead(uri);
    } else if (method.equalsIgnoreCase(HttpGet.METHOD_NAME)) {
        return new HttpGet(uri);
    } else {/*from www  .  j a va  2s . c om*/
        int status = response.getStatusLine().getStatusCode();
        if (status == HttpStatus.SC_TEMPORARY_REDIRECT) {
            if (method.equalsIgnoreCase(HttpPost.METHOD_NAME)) {
                return copyEntity(new HttpPost(uri), request);
            } else if (method.equalsIgnoreCase(HttpPut.METHOD_NAME)) {
                return copyEntity(new HttpPut(uri), request);
            } else if (method.equalsIgnoreCase(HttpDelete.METHOD_NAME)) {
                return new HttpDelete(uri);
            } else if (method.equalsIgnoreCase(HttpTrace.METHOD_NAME)) {
                return new HttpTrace(uri);
            } else if (method.equalsIgnoreCase(HttpOptions.METHOD_NAME)) {
                return new HttpOptions(uri);
            } else if (method.equalsIgnoreCase(HttpPatch.METHOD_NAME)) {
                return copyEntity(new HttpPatch(uri), request);
            }
        }
        return new HttpGet(uri);
    }
}

From source file:org.fcrepo.integration.http.api.FedoraLdpIT.java

License:asdf

@Test
public void testOptionsBinary() throws IOException {
    final String id = getRandomUniqueId();
    createDatastream(id, "x", id);

    final HttpOptions optionsRequest = new HttpOptions(serverAddress + id + "/x");
    try (final CloseableHttpResponse optionsResponse = execute(optionsRequest)) {
        assertEquals(OK.getStatusCode(), optionsResponse.getStatusLine().getStatusCode());
        assertResourceOptionsHeaders(optionsResponse);
        assertEquals("0", optionsResponse.getFirstHeader(CONTENT_LENGTH).getValue());
    }/*from  www  .  ja v a 2 s  .c o m*/
}

From source file:org.fcrepo.integration.http.api.FedoraLdpIT.java

License:asdf

@Test
public void testOptionsBinaryMetadata() throws IOException {
    final String id = getRandomUniqueId();
    createDatastream(id, "x", null);

    final HttpOptions optionsRequest = new HttpOptions(serverAddress + id + "/x/fcr:metadata");
    try (final CloseableHttpResponse optionsResponse = execute(optionsRequest)) {
        assertEquals(OK.getStatusCode(), optionsResponse.getStatusLine().getStatusCode());
        assertNonRdfResourceDescriptionOptionsHeaders(optionsResponse);
    }//from w ww. j a v  a2  s . c  o  m
}

From source file:org.fcrepo.integration.http.api.FedoraLdpIT.java

License:asdf

@Test
public void testOptionsBinaryMetadataWithUriEncoding() throws Exception {
    final String id = getRandomUniqueId();
    createDatastream(id, "x", null);
    final String location = serverAddress + id + "/x/fcr%3Ametadata";

    final HttpOptions optionsRequest = new HttpOptions(location);
    try (final CloseableHttpResponse optionsResponse = execute(optionsRequest)) {
        assertEquals(OK.getStatusCode(), optionsResponse.getStatusLine().getStatusCode());
        assertNonRdfResourceDescriptionOptionsHeaders(optionsResponse);
    }//from  w w  w .jav  a  2 s . co  m
}