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:com.sap.core.odata.fit.basic.BasicHttpTest.java

@Test
public void unsupportedMethod() throws Exception {
    HttpResponse response = getHttpClient().execute(new HttpHead(getEndpoint()));
    assertEquals(HttpStatusCodes.NOT_IMPLEMENTED.getStatusCode(), response.getStatusLine().getStatusCode());

    response = getHttpClient().execute(new HttpOptions(getEndpoint()));
    assertEquals(HttpStatusCodes.NOT_IMPLEMENTED.getStatusCode(), response.getStatusLine().getStatusCode());
}

From source file:com.github.restdriver.serverdriver.RestServerDriver.java

/**
 * Perform an HTTP OPTIONS on a resource.
 * //from  w w  w . ja va  2 s  .c  o  m
 * @param url The URL of a resource. Accepts any Object and calls .toString() on it.
 * @return A Response encapsulating the server's reply.
 */
public static Response options(Object url) {
    ServerDriverHttpUriRequest request = new ServerDriverHttpUriRequest(new HttpOptions(url.toString()));
    return doHttpRequest(request);
}

From source file:org.orbeon.oxf.resources.handler.HTTPURLConnection.java

public void setRequestMethod(String methodName) throws ProtocolException {
    if (connected)
        throw new ProtocolException("Can't reset method: already connected");
    if ("GET".equals(methodName))
        method = new HttpGet(url.toString());
    else if ("POST".equals(methodName))
        method = new HttpPost(url.toString());
    else if ("HEAD".equals(methodName))
        method = new HttpHead(url.toString());
    else if ("OPTIONS".equals(methodName))
        method = new HttpOptions(url.toString());
    else if ("PUT".equals(methodName))
        method = new HttpPut(url.toString());
    else if ("DELETE".equals(methodName))
        method = new HttpDelete(url.toString());
    else if ("TRACE".equals(methodName))
        method = new HttpTrace(url.toString());
    else//  w  w  w  . ja  v  a2  s. c om
        throw new ProtocolException("Method " + methodName + " not supported");
}

From source file:org.apache.olingo.odata2.fit.basic.BasicHttpTest.java

@Test
public void unsupportedMethod() throws Exception {
    HttpResponse response = getHttpClient().execute(new HttpOptions(getEndpoint()));
    assertEquals(HttpStatusCodes.NOT_IMPLEMENTED.getStatusCode(), response.getStatusLine().getStatusCode());
}

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

@Test
public void preflightPostClassAnnotationPass2() throws ClientProtocolException, IOException {
    HttpClient httpclient = HttpClientBuilder.create().build();
    HttpOptions httpoptions = new HttpOptions("http://localhost:" + PORT + "/antest/unannotatedPost");
    httpoptions.addHeader("Origin", "http://area51.mil:31415");
    httpoptions.addHeader("Content-Type", "application/json");
    httpoptions.addHeader(CorsHeaderConstants.HEADER_AC_REQUEST_METHOD, "POST");
    httpoptions.addHeader(CorsHeaderConstants.HEADER_AC_REQUEST_HEADERS, "X-custom-1, X-custom-2");
    HttpResponse response = httpclient.execute(httpoptions);
    assertEquals(200, response.getStatusLine().getStatusCode());
    Header[] origin = response.getHeaders(CorsHeaderConstants.HEADER_AC_ALLOW_ORIGIN);
    assertEquals(1, origin.length);/*from   ww w .j a  v  a  2s  . c  o m*/
    assertEquals("http://area51.mil:31415", origin[0].getValue());
    Header[] method = response.getHeaders(CorsHeaderConstants.HEADER_AC_ALLOW_METHODS);
    assertEquals(1, method.length);
    assertEquals("POST", method[0].getValue());
    Header[] requestHeaders = response.getHeaders(CorsHeaderConstants.HEADER_AC_ALLOW_HEADERS);
    assertEquals(1, requestHeaders.length);
    assertTrue(requestHeaders[0].getValue().contains("X-custom-1"));
    assertTrue(requestHeaders[0].getValue().contains("X-custom-2"));
    if (httpclient instanceof Closeable) {
        ((Closeable) httpclient).close();
    }

}

From source file:com.android.exchange.service.EasServerConnection.java

/**
 * Send an http OPTIONS request to server.
 * @return The {@link EasResponse} from the Exchange server.
 * @throws IOException/*from  w  w  w .java2s .  c o  m*/
 */
protected EasResponse sendHttpClientOptions() throws IOException, CertificateException {
    // For OPTIONS, just use the base string and the single header
    final HttpOptions method = new HttpOptions(URI.create(makeBaseUriString()));
    method.setHeader("Authorization", makeAuthString());
    method.setHeader("User-Agent", getUserAgent());
    return EasResponse.fromHttpRequest(getClientConnectionManager(), getHttpClient(COMMAND_TIMEOUT), method);
}

From source file:com.cisco.oss.foundation.http.apache.ApacheHttpClient.java

private org.apache.http.HttpRequest buildHttpUriRequest(HttpRequest request, Joiner joiner, URI requestUri) {
    org.apache.http.HttpRequest httpRequest;
    if (autoEncodeUri) {
        switch (request.getHttpMethod()) {
        case GET:
            httpRequest = new HttpGet(requestUri);
            break;
        case POST:
            httpRequest = new HttpPost(requestUri);
            break;
        case PUT:
            httpRequest = new HttpPut(requestUri);
            break;
        case DELETE:
            httpRequest = new HttpDelete(requestUri);
            break;
        case HEAD:
            httpRequest = new HttpHead(requestUri);
            break;
        case OPTIONS:
            httpRequest = new HttpOptions(requestUri);
            break;
        case PATCH:
            httpRequest = new HttpPatch(requestUri);
            break;
        default:/*from w w  w.j a  va  2  s  .  c  o m*/
            throw new ClientException("You have to one of the REST verbs such as GET, POST etc.");
        }
    } else {
        switch (request.getHttpMethod()) {
        case POST:
        case PUT:
        case DELETE:
        case PATCH:
            httpRequest = new BasicHttpEntityEnclosingRequest(request.getHttpMethod().method(),
                    requestUri.toString());
            break;
        default:
            httpRequest = new BasicHttpRequest(request.getHttpMethod().method(), requestUri.toString());
        }

    }

    byte[] entity = request.getEntity();
    if (entity != null) {
        if (httpRequest instanceof HttpEntityEnclosingRequest) {
            HttpEntityEnclosingRequest httpEntityEnclosingRequestBase = (HttpEntityEnclosingRequest) httpRequest;
            httpEntityEnclosingRequestBase
                    .setEntity(new ByteArrayEntity(entity, ContentType.create(request.getContentType())));
        } else {
            throw new ClientException(
                    "sending content for request type " + request.getHttpMethod() + " is not supported!");
        }
    } else {
        if (request instanceof ApacheHttpRequest && httpRequest instanceof HttpEntityEnclosingRequest) {
            HttpEntityEnclosingRequest httpEntityEnclosingRequestBase = (HttpEntityEnclosingRequest) httpRequest;
            ApacheHttpRequest apacheHttpRequest = (ApacheHttpRequest) request;
            httpEntityEnclosingRequestBase.setEntity(apacheHttpRequest.getApacheHttpEntity());
        }
    }

    Map<String, Collection<String>> headers = request.getHeaders();
    for (Map.Entry<String, Collection<String>> stringCollectionEntry : headers.entrySet()) {
        String key = stringCollectionEntry.getKey();
        Collection<String> stringCollection = stringCollectionEntry.getValue();
        String value = joiner.join(stringCollection);
        httpRequest.setHeader(key, value);
    }
    return httpRequest;
}

From source file:org.wrml.core.www.WebClient.java

private Message sendRequestMessage(Message requestMessage) {

    HttpUriRequest request = null;/*from   w ww  . j a va2 s  .c  o m*/

    final RequestLine requestLine = (RequestLine) requestMessage.getStartLine();
    final Method method = requestLine.getMethod();
    final URI uri = requestLine.getUri();

    switch (method) {

    case GET:
        request = new HttpGet(uri);
        break;

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

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

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

    case DELETE:
        request = new HttpDelete(uri);
        break;

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

    case TRACE:
        request = new HttpTrace(uri);
        break;

    case CONNECT:
    default:
        break;
    }

    InputStream inputStream = null;

    MediaType responseMediaType = null;
    try {

        final HttpResponse response = _HttpClient.execute(request);
        final HttpEntity entity = response.getEntity();
        final Transformers<String> stringTransformers = getContext().getStringTransformers();
        responseMediaType = stringTransformers.getTransformer(MediaType.class)
                .bToA(entity.getContentType().getValue());

        if (entity != null) {
            inputStream = entity.getContent();
        }
    } catch (final ClientProtocolException e) {
        // TODO Auto-generated catch block
        e.printStackTrace();
    } catch (final IOException e) {
        // TODO Auto-generated catch block
        e.printStackTrace();
    }

    final StatusLine statusLine = new DefaultStatusLine();

    // TODO: Implement transformers for the string values to enums
    //statusLine.setHTTPVersion(httpVersion);
    //statusLine.setStatus(status);

    // Create the response message
    final Message responseMessage = createMessage(MessageType.RESPONSE, statusLine);
    final Entity responseEntity = responseMessage.getEntity();

    responseEntity.getHeaders().setContentType(responseMediaType);
    responseEntity.getBody().setInputStream(inputStream);

    return responseMessage;
}

From source file:nl.architolk.ldt.processors.HttpClientProcessor.java

public void generateData(PipelineContext context, ContentHandler contentHandler) throws SAXException {

    try {/*from w  w w  . j a  v  a2 s .  co m*/
        CloseableHttpClient httpclient = HttpClientProperties.createHttpClient();

        try {
            // Read content of config pipe
            Document configDocument = readInputAsDOM4J(context, INPUT_CONFIG);
            Node configNode = configDocument.selectSingleNode("//config");

            URL theURL = new URL(configNode.valueOf("url"));

            if (configNode.valueOf("auth-method").equals("basic")) {
                HttpHost targetHost = new HttpHost(theURL.getHost(), theURL.getPort(), theURL.getProtocol());
                //Authentication support
                CredentialsProvider credsProvider = new BasicCredentialsProvider();
                credsProvider.setCredentials(AuthScope.ANY, new UsernamePasswordCredentials(
                        configNode.valueOf("username"), configNode.valueOf("password")));
                // logger.info("Credentials: "+configNode.valueOf("username")+"/"+configNode.valueOf("password"));
                // Create AuthCache instance
                AuthCache authCache = new BasicAuthCache();
                authCache.put(targetHost, new BasicScheme());

                // Add AuthCache to the execution context
                httpContext = HttpClientContext.create();
                httpContext.setCredentialsProvider(credsProvider);
                httpContext.setAuthCache(authCache);
            } else if (configNode.valueOf("auth-method").equals("form")) {
                //Sign in. Cookie will be remembered bij httpclient
                HttpPost authpost = new HttpPost(configNode.valueOf("auth-url"));
                List<NameValuePair> nameValuePairs = new ArrayList<NameValuePair>();
                nameValuePairs.add(new BasicNameValuePair("userName", configNode.valueOf("username")));
                nameValuePairs.add(new BasicNameValuePair("password", configNode.valueOf("password")));
                authpost.setEntity(new UrlEncodedFormEntity(nameValuePairs));
                CloseableHttpResponse httpResponse = httpclient.execute(authpost);
                // logger.info("Signin response:"+Integer.toString(httpResponse.getStatusLine().getStatusCode()));
            }

            CloseableHttpResponse response;
            if (configNode.valueOf("method").equals("post")) {
                // POST
                HttpPost httpRequest = new HttpPost(configNode.valueOf("url"));
                setBody(httpRequest, context, configNode);
                response = executeRequest(httpRequest, httpclient);
            } else if (configNode.valueOf("method").equals("put")) {
                // PUT
                HttpPut httpRequest = new HttpPut(configNode.valueOf("url"));
                setBody(httpRequest, context, configNode);
                response = executeRequest(httpRequest, httpclient);
            } else if (configNode.valueOf("method").equals("delete")) {
                //DELETE
                HttpDelete httpRequest = new HttpDelete(configNode.valueOf("url"));
                response = executeRequest(httpRequest, httpclient);
            } else if (configNode.valueOf("method").equals("head")) {
                //HEAD
                HttpHead httpRequest = new HttpHead(configNode.valueOf("url"));
                response = executeRequest(httpRequest, httpclient);
            } else if (configNode.valueOf("method").equals("options")) {
                //OPTIONS
                HttpOptions httpRequest = new HttpOptions(configNode.valueOf("url"));
                response = executeRequest(httpRequest, httpclient);
            } else {
                //Default = GET
                HttpGet httpRequest = new HttpGet(configNode.valueOf("url"));
                String acceptHeader = configNode.valueOf("accept");
                if (!acceptHeader.isEmpty()) {
                    httpRequest.addHeader("accept", configNode.valueOf("accept"));
                }
                //Add proxy route if needed
                HttpClientProperties.setProxy(httpRequest, theURL.getHost());
                response = executeRequest(httpRequest, httpclient);
            }

            try {
                contentHandler.startDocument();

                int status = response.getStatusLine().getStatusCode();
                AttributesImpl statusAttr = new AttributesImpl();
                statusAttr.addAttribute("", "status", "status", "CDATA", Integer.toString(status));
                contentHandler.startElement("", "response", "response", statusAttr);
                if (status >= 200 && status < 300) {
                    HttpEntity entity = response.getEntity();
                    Header contentType = response.getFirstHeader("Content-Type");
                    if (entity != null && contentType != null) {
                        //logger.info("Contenttype: " + contentType.getValue());
                        //Read content into inputstream
                        InputStream inStream = entity.getContent();

                        // output-type = json means: response is json, convert to xml
                        if (configNode.valueOf("output-type").equals("json")) {
                            //TODO: net.sf.json.JSONObject might nog be the correct JSONObject. javax.json.JsonObject might be better!!!
                            //javax.json contains readers to read from an inputstream
                            StringWriter writer = new StringWriter();
                            IOUtils.copy(inStream, writer, "UTF-8");
                            JSONObject json = JSONObject.fromObject(writer.toString());
                            parseJSONObject(contentHandler, json);
                            // output-type = xml means: response is xml, keep it
                        } else if (configNode.valueOf("output-type").equals("xml")) {
                            try {
                                XMLReader saxParser = XMLParsing
                                        .newXMLReader(new XMLParsing.ParserConfiguration(false, false, false));
                                saxParser.setContentHandler(new ParseHandler(contentHandler));
                                saxParser.parse(new InputSource(inStream));
                            } catch (Exception e) {
                                throw new OXFException(e);
                            }
                            // output-type = jsonld means: reponse is json-ld, (a) convert to nquads; (b) convert to xml
                        } else if (configNode.valueOf("output-type").equals("jsonld")) {
                            try {
                                Object jsonObject = JsonUtils.fromInputStream(inStream, "UTF-8"); //TODO: UTF-8 should be read from response!
                                Object nquads = JsonLdProcessor.toRDF(jsonObject, new NQuadTripleCallback());

                                Any23 runner = new Any23();
                                DocumentSource source = new StringDocumentSource((String) nquads,
                                        configNode.valueOf("url"));
                                ByteArrayOutputStream out = new ByteArrayOutputStream();
                                TripleHandler handler = new RDFXMLWriter(out);
                                try {
                                    runner.extract(source, handler);
                                } finally {
                                    handler.close();
                                }
                                ByteArrayInputStream inJsonStream = new ByteArrayInputStream(out.toByteArray());
                                XMLReader saxParser = XMLParsing
                                        .newXMLReader(new XMLParsing.ParserConfiguration(false, false, false));
                                saxParser.setContentHandler(new ParseHandler(contentHandler));
                                saxParser.parse(new InputSource(inJsonStream));
                            } catch (Exception e) {
                                throw new OXFException(e);
                            }
                            // output-type = rdf means: response is some kind of rdf (except json-ld...), convert to xml
                        } else if (configNode.valueOf("output-type").equals("rdf")) {
                            try {
                                Any23 runner = new Any23();

                                DocumentSource source;
                                //If contentType = text/html than convert from html to xhtml to handle non-xml style html!
                                logger.info("Contenttype: " + contentType.getValue());
                                if (configNode.valueOf("tidy").equals("yes")
                                        && contentType.getValue().startsWith("text/html")) {
                                    org.jsoup.nodes.Document doc = Jsoup.parse(inStream, "UTF-8",
                                            configNode.valueOf("url")); //TODO UTF-8 should be read from response!

                                    RDFCleaner cleaner = new RDFCleaner();
                                    org.jsoup.nodes.Document cleandoc = cleaner.clean(doc);
                                    cleandoc.outputSettings().escapeMode(Entities.EscapeMode.xhtml);
                                    cleandoc.outputSettings()
                                            .syntax(org.jsoup.nodes.Document.OutputSettings.Syntax.xml);
                                    cleandoc.outputSettings().charset("UTF-8");

                                    source = new StringDocumentSource(cleandoc.html(),
                                            configNode.valueOf("url"), contentType.getValue());
                                } else {
                                    source = new ByteArrayDocumentSource(inStream, configNode.valueOf("url"),
                                            contentType.getValue());
                                }

                                ByteArrayOutputStream out = new ByteArrayOutputStream();
                                TripleHandler handler = new RDFXMLWriter(out);
                                try {
                                    runner.extract(source, handler);
                                } finally {
                                    handler.close();
                                }
                                ByteArrayInputStream inAnyStream = new ByteArrayInputStream(out.toByteArray());
                                XMLReader saxParser = XMLParsing
                                        .newXMLReader(new XMLParsing.ParserConfiguration(false, false, false));
                                saxParser.setContentHandler(new ParseHandler(contentHandler));
                                saxParser.parse(new InputSource(inAnyStream));

                            } catch (Exception e) {
                                throw new OXFException(e);
                            }
                        } else {
                            CharArrayWriter writer = new CharArrayWriter();
                            IOUtils.copy(inStream, writer, "UTF-8");
                            contentHandler.characters(writer.toCharArray(), 0, writer.size());
                        }
                    }
                }
                contentHandler.endElement("", "response", "response");

                contentHandler.endDocument();
            } finally {
                response.close();
            }
        } finally {
            httpclient.close();
        }
    } catch (Exception e) {
        throw new OXFException(e);
    }

}

From source file:de.taimos.httputils.HTTPRequest.java

/**
 * @param executor Thread pool/* ww  w  . j a v  a2s. co m*/
 * @param callback {@link HTTPResponseCallback}
 */
public void optionsAsync(final Executor executor, final HTTPResponseCallback callback) {
    this.executeAsync(executor, new HttpOptions(this.buildURI()), callback);
}