Search in sources :

Example 6 with RequestHeader

use of com.github.davidmoten.odata.client.RequestHeader in project odata-client by davidmoten.

the class ApacheHttpClientHttpService method getStream.

public InputStream getStream(List<RequestHeader> requestHeaders, HttpRequestBase request, InputStream content, int length, HttpRequestOptions options) {
    Preconditions.checkNotNull(options);
    log.debug("{} from url {}", request.getMethod(), request.getURI());
    log.debug("requestHeaders={}", requestHeaders);
    boolean contentLengthSet = false;
    for (RequestHeader header : requestHeadersModifier.apply(toUrl(request), requestHeaders)) {
        request.addHeader(header.name(), header.value());
        if ("Content-Length".equals(header.name())) {
            contentLengthSet = true;
        }
    }
    if (content != null && !contentLengthSet) {
        request.addHeader("Content-Length", Integer.toString(length));
    }
    CloseableHttpResponse response = null;
    try {
        if (content != null && request instanceof HttpEntityEnclosingRequest) {
            ((HttpEntityEnclosingRequest) request).setEntity(new InputStreamEntity(content, length));
            log.debug("content={}", content);
        }
        RequestConfig config = com.github.davidmoten.odata.client.Util.nvl(request.getConfig(), RequestConfig.DEFAULT);
        Builder builder = // 
        RequestConfig.copy(config);
        options.requestConnectTimeoutMs().ifPresent(x -> builder.setConnectTimeout(x.intValue()));
        options.requestReadTimeoutMs().ifPresent(x -> builder.setSocketTimeout(x.intValue()));
        config = builder.build();
        request.setConfig(config);
        log.debug("executing request");
        response = client.execute(request);
        int statusCode = response.getStatusLine().getStatusCode();
        log.debug("executed request, code={}", statusCode);
        InputStream is = response.getEntity().getContent();
        // ensure response is closed when input stream is closed
        InputStream in = new InputStreamWithCloseable(is, response);
        if (!isOk(statusCode)) {
            try {
                String msg = Util.readString(in, StandardCharsets.UTF_8);
                throw new ClientException(statusCode, // 
                "getStream returned HTTP " + statusCode + "\n" + "url=" + request.getURI() + // 
                "\n" + "headers=" + requestHeaders + // 
                "\n" + // 
                "response:\n" + msg);
            } finally {
                in.close();
            }
        } else {
            return in;
        }
    } catch (IOException e) {
        // ensure that response is closed on exception to avoid memory leak
        if (response != null) {
            try {
                response.close();
            } catch (IOException e1) {
                log.warn(e1.getMessage(), e);
            }
        }
        throw new ClientException(e);
    }
}
Also used : RequestConfig(org.apache.http.client.config.RequestConfig) InputStream(java.io.InputStream) Builder(org.apache.http.client.config.RequestConfig.Builder) HttpClientBuilder(org.apache.http.impl.client.HttpClientBuilder) IOException(java.io.IOException) InputStreamEntity(org.apache.http.entity.InputStreamEntity) HttpEntityEnclosingRequest(org.apache.http.HttpEntityEnclosingRequest) CloseableHttpResponse(org.apache.http.client.methods.CloseableHttpResponse) RequestHeader(com.github.davidmoten.odata.client.RequestHeader) ClientException(com.github.davidmoten.odata.client.ClientException)

Example 7 with RequestHeader

use of com.github.davidmoten.odata.client.RequestHeader in project odata-client by davidmoten.

the class AdHocMain method main.

public static void main(String[] args) {
    String tenantName = System.getProperty("tenantName");
    String clientId = System.getProperty("clientId");
    String clientSecret = System.getProperty("clientSecret");
    String mailbox = System.getProperty("mailbox");
    GraphService client = // 
    MsGraph.tenantName(// 
    tenantName).clientId(// 
    clientId).clientSecret(// 
    clientSecret).refreshBeforeExpiry(5, // 
    TimeUnit.MINUTES).authenticationEndpoint(// is default
    AuthenticationEndpoint.GLOBAL).build();
    client.users(mailbox).messages().get().currentPage().forEach(System.out::println);
    // if (false) {
    // String url =
    // "https://graph.microsoft.com/v1.0/users('dnex001%40amsa.gov.au')/mailFolders('inbox')/messages('AQMkADQ3YjdiNWUxLTBmYWQtNDMwYy04Yzc0LTI0MDdmOWQ4NDFjNgBGAAAD4Rwe0e6XOE6Ck412HUUUTwcAUb5I0z9LnUy3cpFj0m9MUgAAAgEMAAAA3NEVJKXfYEuEjYE7msyHXwACvGHoMgAAAA%3D%3D')/attachments('AQMkADQ3YjdiNWUxLTBmYWQtNDMwYy04Yzc0LTI0MDdmOWQ4NDFjNgBGAAAD4Rwe0e6XOE6Ck412HUUUTwcAUb5I0z9LnUy3cpFj0m9MUgAAAgEMAAAA3NEVJKXfYEuEjYE7msyHXwACvGHoMgAAAAESABAAEk3MvTWvlkaZoyGmFgr4ag%3D%3D')";
    // System.out.println(url + "\n->\n" + client._service().getStringUtf8(url,
    // Arrays.asList(new RequestHeader("Accept",
    // "application/json;odata.metadata=full"))));
    // System.exit(0);
    // }
    String a = client._custom().getString("https://graph.microsoft.com/v1.0/users/dnex001%40amsa.gov.au/messages('AQMkADQ3YjdiNWUxLTBmYWQtNDMwYy04Yzc0LTI0MDdmOWQ4NDFjNgBGAAAD4Rwe0e6XOE6Ck412HUUUTwcAUb5I0z9LnUy3cpFj0m9MUgAAAgEMAAAA3NEVJKXfYEuEjYE7msyHXwACvxQL4gAAAA==')/$value", RequestOptions.EMPTY, RequestHeader.ACCEPT_JSON, RequestHeader.ODATA_VERSION);
    System.out.println(a);
    System.exit(1);
    String s = client.users(mailbox).messages(// 
    "AQMkADQ3YjdiNWUxLTBmYWQtNDMwYy04Yzc0LTI0MDdmOWQ4NDFjNgBGAAAD4Rwe0e6XOE6Ck412HUUUTwcAUb5I0z9LnUy3cpFj0m9MUgAAAgEMAAAA3NEVJKXfYEuEjYE7msyHXwACvxQL4gAAAA==").metadataFull().get().getStream().get().getStringUtf8();
    System.out.println(s);
    // System.out.println(client.users(mailbox).get().revokeSignInSessions());
    System.exit(0);
    System.out.println(client.sites("root").get().getDisplayName().orElse(""));
    // client.users(mailbox).get().revokeSignInSessions(null)
    // test raw value of service
    // String s = client.users(mailbox) //
    // .mailFolders("Inbox") //
    // .messages() //
    // .filter("isRead eq false") //
    // .metadataFull() //
    // .get() //
    // .stream() //
    // .findFirst() //
    // .get() //
    // .getStream() //
    // .get() //
    // .getStringUtf8();
    // System.out.println(s);
    // 
    client.users(// 
    mailbox).mailFolders(// 
    "Inbox").messages().filter(// 
    "isRead eq false and startsWith(subject, 'test contact')").stream().peek(// 
    x -> System.out.println(x.getSubject().orElse(""))).flatMap(// 
    x -> x.getAttachments().metadataFull().get().stream()).filter(// 
    x -> x instanceof ItemAttachment).map(// 
    x -> (ItemAttachment) x).map(// 
    x -> x.getStream().get().getStringUtf8()).peek(// 
    System.out::println).findFirst();
    // 
    client.users(// 
    mailbox).mailFolders(// 
    "Inbox").messages().filter(// 
    "isRead eq false").stream().filter(// 
    x -> x.getHasAttachments().orElse(false)).peek(// 
    x -> System.out.println("Subject: " + x.getSubject().orElse(""))).flatMap(// 
    x -> x.getAttachments().get().stream()).peek(x -> System.out.println(// 
    "  " + x.getName().orElse("?") + " [" + x.getSize().orElse(0) + "]")).count();
}
Also used : GraphService(odata.msgraph.client.container.GraphService) TimeUnit(java.util.concurrent.TimeUnit) GraphService(odata.msgraph.client.container.GraphService) ItemAttachment(odata.msgraph.client.entity.ItemAttachment) AuthenticationEndpoint(com.github.davidmoten.microsoft.authentication.AuthenticationEndpoint) RequestOptions(com.github.davidmoten.odata.client.RequestOptions) RequestHeader(com.github.davidmoten.odata.client.RequestHeader) ItemAttachment(odata.msgraph.client.entity.ItemAttachment)

Example 8 with RequestHeader

use of com.github.davidmoten.odata.client.RequestHeader in project odata-client by davidmoten.

the class DefaultHttpService method getResponsePatchOverride.

private HttpResponse getResponsePatchOverride(String url, List<RequestHeader> requestHeaders, InputStream content, int length) {
    List<RequestHeader> list = Lists.newArrayList(requestHeaders);
    list.add(new RequestHeader("X-HTTP-Method-Override", "PATCH"));
    HttpResponse result = getResponse(url, list, HttpMethod.POST, true, content, length);
    // only indicate patch not supported if the result is returned ok
    patchSupported = false;
    return result;
}
Also used : RequestHeader(com.github.davidmoten.odata.client.RequestHeader) HttpResponse(com.github.davidmoten.odata.client.HttpResponse)

Example 9 with RequestHeader

use of com.github.davidmoten.odata.client.RequestHeader in project odata-client by davidmoten.

the class DefaultHttpService method getResponse.

private HttpResponse getResponse(String url, List<RequestHeader> requestHeaders, HttpMethod method, boolean doInput, InputStream content, int length) {
    try {
        URL u = new URL(url);
        HttpURLConnection c = (HttpURLConnection) u.openConnection();
        c.setInstanceFollowRedirects(true);
        c.setRequestMethod(method.toString());
        for (RequestHeader header : requestHeadersModifier.apply(requestHeaders)) {
            c.setRequestProperty(header.name(), header.value());
        }
        if (length != HttpService.LENGTH_UNKNOWN) {
            c.setRequestProperty("Content-Length", length + "");
        }
        c.setDoInput(doInput);
        c.setDoOutput(content != null);
        // apply just before connection established so further configuration can take
        // place like timeouts
        consumer.accept(c);
        if (content != null) {
            try (OutputStream out = c.getOutputStream()) {
                byte[] b = new byte[8192];
                int len;
                while ((len = content.read(b)) != -1) {
                    out.write(b, 0, len);
                }
            }
        }
        final byte[] bytes;
        if (doInput) {
            bytes = Util.read(c.getInputStream());
        } else {
            bytes = null;
        }
        return new HttpResponse(c.getResponseCode(), bytes);
    } catch (ProtocolException e) {
        throw new ProtocolRuntimeException(e);
    } catch (IOException e) {
        throw new ClientException(e);
    }
}
Also used : ProtocolException(java.net.ProtocolException) HttpURLConnection(java.net.HttpURLConnection) OutputStream(java.io.OutputStream) RequestHeader(com.github.davidmoten.odata.client.RequestHeader) HttpResponse(com.github.davidmoten.odata.client.HttpResponse) IOException(java.io.IOException) ClientException(com.github.davidmoten.odata.client.ClientException) URL(java.net.URL)

Example 10 with RequestHeader

use of com.github.davidmoten.odata.client.RequestHeader in project odata-client by davidmoten.

the class RequestHelper method getWithParametricType.

public static <T, S> T getWithParametricType(ContextPath contextPath, Class<T> cls, Class<S> parametricTypeClass, RequestOptions options) {
    // build the url
    ContextPath cp = contextPath.addQueries(options.getQueries());
    List<RequestHeader> h = cleanAndSupplementRequestHeaders(options, "minimal", false);
    // get the response
    HttpResponse response = cp.context().service().get(cp.toUrl(), h, options);
    checkResponseCode(cp, response, HttpURLConnection.HTTP_OK);
    // deserialize
    String text = response.getText();
    Class<? extends T> c = getSubClass(cp, contextPath.context().schemas(), cls, text);
    // FileAttachment which is a subclass of Attachment)
    return cp.context().serializer().deserializeWithParametricType(text, c, parametricTypeClass, contextPath, false);
}
Also used : ContextPath(com.github.davidmoten.odata.client.ContextPath) RequestHeader(com.github.davidmoten.odata.client.RequestHeader) HttpResponse(com.github.davidmoten.odata.client.HttpResponse)

Aggregations

RequestHeader (com.github.davidmoten.odata.client.RequestHeader)16 HttpResponse (com.github.davidmoten.odata.client.HttpResponse)13 ContextPath (com.github.davidmoten.odata.client.ContextPath)8 ClientException (com.github.davidmoten.odata.client.ClientException)6 HttpService (com.github.davidmoten.odata.client.HttpService)4 IOException (java.io.IOException)4 URL (java.net.URL)4 HttpURLConnection (java.net.HttpURLConnection)3 RequestOptions (com.github.davidmoten.odata.client.RequestOptions)2 InputStream (java.io.InputStream)2 MalformedURLException (java.net.MalformedURLException)2 ArrayList (java.util.ArrayList)2 Preconditions (com.github.davidmoten.guavamini.Preconditions)1 AuthenticationEndpoint (com.github.davidmoten.microsoft.authentication.AuthenticationEndpoint)1 Context (com.github.davidmoten.odata.client.Context)1 HttpMethod (com.github.davidmoten.odata.client.HttpMethod)1 HttpRequestOptions (com.github.davidmoten.odata.client.HttpRequestOptions)1 ODataEntityType (com.github.davidmoten.odata.client.ODataEntityType)1 ODataType (com.github.davidmoten.odata.client.ODataType)1 Path (com.github.davidmoten.odata.client.Path)1