Search in sources :

Example 1 with ClientException

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

the class GraphServiceTest method testPatchOfResourceNotFound.

@Test
public void testPatchOfResourceNotFound() {
    GraphService client = // 
    clientBuilder().expectRequest(// 
    "/users/1").withResponse(// 
    "/response-user.json").withRequestHeadersStandard().expectRequest(// 
    "/users/1").withPayload(// 
    "/request-user-patch.json").withResponseStatusCode(// 
    HttpURLConnection.HTTP_NOT_FOUND).withMethod(// 
    HttpMethod.PATCH).withRequestHeaders(RequestHeader.CONTENT_TYPE_JSON, RequestHeader.ODATA_VERSION, // 
    RequestHeader.ACCEPT_JSON).build();
    User user = client.users("1").get();
    try {
        user.withCity("Canberra").patch();
    } catch (ClientException e) {
        assertEquals(HttpURLConnection.HTTP_NOT_FOUND, (int) e.getStatusCode().get());
    }
}
Also used : GraphService(odata.msgraph.client.container.GraphService) User(odata.msgraph.client.entity.User) ClientException(com.github.davidmoten.odata.client.ClientException) Test(org.junit.Test)

Example 2 with ClientException

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

the class DefaultHttpService method getStream.

@Override
public InputStream getStream(HttpMethod method, String url, List<RequestHeader> requestHeaders, HttpRequestOptions options) {
    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());
        }
        c.setDoInput(true);
        c.setDoOutput(false);
        // apply just before connection established so further configuration can take
        // place like timeouts
        consumer.accept(c);
        // TODO check error code and throw message read from input stream
        return c.getInputStream();
    } catch (IOException e) {
        throw new ClientException(e);
    }
}
Also used : HttpURLConnection(java.net.HttpURLConnection) RequestHeader(com.github.davidmoten.odata.client.RequestHeader) IOException(java.io.IOException) ClientException(com.github.davidmoten.odata.client.ClientException) URL(java.net.URL)

Example 3 with ClientException

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

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

the class Util method odataTypeName.

@SuppressWarnings("unchecked")
public static <T extends ODataType> String odataTypeName(Class<T> cls) {
    try {
        Constructor<?> c = null;
        Constructor<?>[] constructors = cls.getDeclaredConstructors();
        for (Constructor<?> constructor : constructors) {
            if (constructor.getParameterCount() == 0) {
                constructor.setAccessible(true);
                c = constructor;
            }
        }
        T o = (T) c.newInstance();
        return o.odataTypeName();
    } catch (InstantiationException | IllegalAccessException | IllegalArgumentException | InvocationTargetException | SecurityException e) {
        throw new ClientException(e);
    }
}
Also used : Constructor(java.lang.reflect.Constructor) ClientException(com.github.davidmoten.odata.client.ClientException) InvocationTargetException(java.lang.reflect.InvocationTargetException)

Example 5 with ClientException

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

the class GraphServiceTest method testGetCollectionThrowsInformativeError.

@Test
public void testGetCollectionThrowsInformativeError() {
    GraphService client = // 
    clientBuilder().expectRequest(// 
    "/users").withRequestHeadersStandard().withResponse(// 
    "/response-get-collection-error.json").withResponseStatusCode(// 
    403).build();
    try {
        client.users().get().currentPage();
        Assert.fail();
    } catch (ClientException e) {
        assertTrue(e.getMessage().contains("Insufficient privileges"));
        assertEquals(403, (int) e.getStatusCode().get());
    }
}
Also used : GraphService(odata.msgraph.client.container.GraphService) ClientException(com.github.davidmoten.odata.client.ClientException) Test(org.junit.Test)

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