Search in sources :

Example 6 with ClientException

use of com.github.davidmoten.odata.client.ClientException 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 7 with ClientException

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

the class RequestHelper method patchOrPut.

@SuppressWarnings("unused")
private static <T extends ODataEntityType> T patchOrPut(T entity, ContextPath contextPath, RequestOptions options, HttpMethod method) {
    Preconditions.checkArgument(method == HttpMethod.PUT || method == HttpMethod.PATCH);
    final String json;
    if (method == HttpMethod.PATCH) {
        json = Serializer.INSTANCE.serializeChangesOnly(entity);
    } else {
        json = Serializer.INSTANCE.serialize(entity);
    }
    // build the url
    ContextPath cp = contextPath.addQueries(options.getQueries());
    List<RequestHeader> h = cleanAndSupplementRequestHeaders(options, "minimal", true);
    final String url;
    String editLink = (String) entity.getUnmappedFields().get("@odata.editLink");
    // TODO get patch working when editLink present (does not work with MsGraph)
    if (editLink != null && false) {
        if (editLink.startsWith(HTTPS) || editLink.startsWith("http://")) {
            url = editLink;
        } else {
            // TOOD unit test relative url in editLink
            // from
            // http://docs.oasis-open.org/odata/odata-json-format/v4.01/cs01/odata-json-format-v4.01-cs01.html#_Toc499720582
            String context = (String) entity.getUnmappedFields().get("@odata.context");
            if (context != null) {
                try {
                    URL u = new URL(context);
                    String p = u.getPath();
                    String basePath = p.substring(0, p.lastIndexOf('/'));
                    url = basePath + "/" + editLink;
                } catch (MalformedURLException e) {
                    throw new ClientException(e);
                }
            } else {
                url = cp.context().service().getBasePath().toUrl() + "/" + editLink;
            }
        }
    } else {
        url = cp.toUrl();
    }
    // get the response
    HttpService service = cp.context().service();
    final HttpResponse response = service.submit(method, url, h, json, options);
    checkResponseCodeOk(cp, response);
    // original?
    return entity;
}
Also used : ContextPath(com.github.davidmoten.odata.client.ContextPath) MalformedURLException(java.net.MalformedURLException) HttpService(com.github.davidmoten.odata.client.HttpService) RequestHeader(com.github.davidmoten.odata.client.RequestHeader) HttpResponse(com.github.davidmoten.odata.client.HttpResponse) ClientException(com.github.davidmoten.odata.client.ClientException) URL(java.net.URL)

Example 8 with ClientException

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

the class ClientCredentialsAccessTokenProvider method refreshAccessToken.

private String refreshAccessToken() {
    // need to refresh the token
    try {
        log.debug("refreshing access token");
        URL url = new URL(authenticationEndpoint + tenantName + OAUTH2_TOKEN_URL_SUFFIX);
        final HttpsURLConnection con;
        if (proxyHost.isPresent()) {
            InetSocketAddress proxyInet = new InetSocketAddress(proxyHost.get(), proxyPort.get());
            Proxy proxy = new Proxy(Proxy.Type.HTTP, proxyInet);
            con = (HttpsURLConnection) url.openConnection(proxy);
            if (proxyUsername.isPresent()) {
                String usernameAndPassword = proxyUsername.get() + ":" + proxyPassword.get();
                String authString = "Basic " + Base64.getEncoder().encodeToString(usernameAndPassword.getBytes(StandardCharsets.UTF_8));
                con.setRequestProperty("Proxy-Authorization", authString);
            }
        // TODO support NTLM?
        } else {
            con = (HttpsURLConnection) url.openConnection();
        }
        con.setConnectTimeout((int) connectTimeoutMs);
        con.setReadTimeout((int) readTimeoutMs);
        con.setRequestMethod(POST);
        con.setRequestProperty(REQUEST_HEADER, APPLICATION_JSON);
        StringBuilder params = new StringBuilder();
        add(params, PARAMETER_RESOURCE, resource);
        add(params, PARAMETER_CLIENT_ID, clientId);
        add(params, PARAMETER_GRANT_TYPE, GRANT_TYPE_CLIENT_CREDENTIALS);
        add(params, PARAMETER_CLIENT_SECRET, clientSecret);
        for (String scope : scopes) {
            add(params, PARAMETER_SCOPE, scope);
        }
        con.setDoOutput(true);
        try (DataOutputStream dos = new DataOutputStream(con.getOutputStream())) {
            dos.writeBytes(params.toString());
        }
        int responseCode = con.getResponseCode();
        String json = Util.readString(con.getInputStream(), StandardCharsets.UTF_8);
        if (responseCode != OK) {
            throw new ClientException(responseCode, json);
        } else {
            ObjectMapper om = new ObjectMapper();
            JsonNode o = om.readTree(json);
            // update the cached values
            expiryTime = o.get("expires_on").asLong() * 1000;
            accessToken = o.get("access_token").asText();
            log.debug("refreshed access token, expires on " + new Date(expiryTime));
            return accessToken;
        }
    } catch (IOException e) {
        // reset stuff
        expiryTime = 0;
        accessToken = null;
        Optional<Integer> code = extractStatusCode(e.getMessage());
        if (code.isPresent()) {
            throw new ClientException(code.get(), e);
        } else {
            throw new ClientException(e);
        }
    }
}
Also used : Optional(java.util.Optional) InetSocketAddress(java.net.InetSocketAddress) DataOutputStream(java.io.DataOutputStream) JsonNode(com.fasterxml.jackson.databind.JsonNode) IOException(java.io.IOException) URL(java.net.URL) Date(java.util.Date) Proxy(java.net.Proxy) ClientException(com.github.davidmoten.odata.client.ClientException) HttpsURLConnection(javax.net.ssl.HttpsURLConnection) ObjectMapper(com.fasterxml.jackson.databind.ObjectMapper)

Example 9 with ClientException

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

the class ApacheHttpClientHttpService method getResponse.

private HttpResponse getResponse(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);
    for (RequestHeader header : requestHeadersModifier.apply(toUrl(request), requestHeaders)) {
        request.addHeader(header.name(), header.value());
    }
    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");
        try (CloseableHttpResponse response = client.execute(request)) {
            int statusCode = response.getStatusLine().getStatusCode();
            log.debug("executed request, code={}", statusCode);
            HttpEntity entity = response.getEntity();
            final byte[] bytes;
            if (entity == null) {
                bytes = null;
            } else {
                bytes = Util.read(entity.getContent());
            }
            if (log.isDebugEnabled()) {
                log.debug("response text=\n{}", bytes == null ? "null" : new String(bytes, StandardCharsets.UTF_8));
            }
            return new HttpResponse(statusCode, bytes);
        }
    } catch (IOException e) {
        throw new ClientException(e);
    }
}
Also used : RequestConfig(org.apache.http.client.config.RequestConfig) HttpEntity(org.apache.http.HttpEntity) Builder(org.apache.http.client.config.RequestConfig.Builder) HttpClientBuilder(org.apache.http.impl.client.HttpClientBuilder) CloseableHttpResponse(org.apache.http.client.methods.CloseableHttpResponse) HttpResponse(com.github.davidmoten.odata.client.HttpResponse) 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)

Aggregations

ClientException (com.github.davidmoten.odata.client.ClientException)9 RequestHeader (com.github.davidmoten.odata.client.RequestHeader)5 IOException (java.io.IOException)5 URL (java.net.URL)4 HttpResponse (com.github.davidmoten.odata.client.HttpResponse)3 HttpURLConnection (java.net.HttpURLConnection)2 GraphService (odata.msgraph.client.container.GraphService)2 HttpEntityEnclosingRequest (org.apache.http.HttpEntityEnclosingRequest)2 RequestConfig (org.apache.http.client.config.RequestConfig)2 Builder (org.apache.http.client.config.RequestConfig.Builder)2 CloseableHttpResponse (org.apache.http.client.methods.CloseableHttpResponse)2 InputStreamEntity (org.apache.http.entity.InputStreamEntity)2 HttpClientBuilder (org.apache.http.impl.client.HttpClientBuilder)2 Test (org.junit.Test)2 JsonNode (com.fasterxml.jackson.databind.JsonNode)1 ObjectMapper (com.fasterxml.jackson.databind.ObjectMapper)1 ContextPath (com.github.davidmoten.odata.client.ContextPath)1 HttpService (com.github.davidmoten.odata.client.HttpService)1 DataOutputStream (java.io.DataOutputStream)1 InputStream (java.io.InputStream)1