Example usage for com.squareup.okhttp.internal.http StatusLine StatusLine

List of usage examples for com.squareup.okhttp.internal.http StatusLine StatusLine

Introduction

In this page you can find the example usage for com.squareup.okhttp.internal.http StatusLine StatusLine.

Prototype

public StatusLine(Protocol protocol, int code, String message) 

Source Link

Usage

From source file:at.bitfire.dav4android.DavResource.java

License:Open Source License

private void parseMultiStatus_Response(XmlPullParser parser)
        throws IOException, XmlPullParserException, HttpException, UnsupportedDavException {
    /* <!ELEMENT response (href, ((href*, status)|(propstat+)),
                               error?, responsedescription? , location?) > */
    final int depth = parser.getDepth();

    HttpUrl href = null;//from  w w w  .  j av a 2 s.  c o  m
    StatusLine status = null;
    PropertyCollection properties = new PropertyCollection();

    int eventType = parser.getEventType();
    while (!(eventType == XmlPullParser.END_TAG && parser.getDepth() == depth)) {
        if (eventType == XmlPullParser.START_TAG && parser.getDepth() == depth + 1) {
            String ns = parser.getNamespace(), name = parser.getName();
            if (XmlUtils.NS_WEBDAV.equals(ns))
                switch (name) {
                case "href":
                    String sHref = parser.nextText();
                    if (!sHref.startsWith("/")) {
                        /* According to RFC 4918 8.3 URL Handling, only absolute paths are allowed as relative
                           URLs. However, some servers reply with relative paths. */
                        int firstColon = sHref.indexOf(':');
                        if (firstColon != -1) {
                            /* There are some servers which return not only relative paths, but relative paths like "a:b.vcf",
                               which would be interpreted as scheme: "a", scheme-specific part: "b.vcf" normally.
                               For maximum compatibility, we prefix all relative paths which contain ":" (but not "://"),
                               with "./" to allow resolving by HttpUrl. */
                            boolean hierarchical = false;
                            try {
                                if ("://".equals(sHref.substring(firstColon, firstColon + 3)))
                                    hierarchical = true;
                            } catch (IndexOutOfBoundsException e) {
                                // no "://"
                            }
                            if (!hierarchical)
                                sHref = "./" + sHref;
                        }
                    }
                    href = location.resolve(sHref);
                    break;
                case "status":
                    try {
                        status = StatusLine.parse(parser.nextText());
                    } catch (ProtocolException e) {
                        log.warn("Invalid status line, treating as 500 Server Error");
                        status = new StatusLine(Protocol.HTTP_1_1, 500, "Invalid status line");
                    }
                    break;
                case "propstat":
                    PropertyCollection prop = parseMultiStatus_PropStat(parser);
                    if (prop != null)
                        properties.merge(prop, false);
                    break;
                case "location":
                    throw new UnsupportedDavException("Redirected child resources are not supported yet");
                }
        }
        eventType = parser.next();
    }

    if (href == null) {
        log.warn("Ignoring <response> without valid <href>");
        return;
    }

    // if we know this resource is a collection, make sure href has a trailing slash (for clarity and resolving relative paths)
    ResourceType type = (ResourceType) properties.get(ResourceType.NAME);
    if (type != null && type.types.contains(ResourceType.COLLECTION))
        href = UrlUtils.withTrailingSlash(href);

    log.debug("Received <response> for " + href + ", status: " + status + ", properties: " + properties);

    if (status != null)
        // treat an HTTP error of a single response (i.e. requested resource or a member) like an HTTP error of the requested resource
        checkStatus(status);

    // Which resource does this <response> represent?
    DavResource target = null;
    if (UrlUtils.equals(UrlUtils.omitTrailingSlash(href), UrlUtils.omitTrailingSlash(location))) {
        // it's about ourselves
        target = this;
    } else if (location.scheme().equals(href.scheme()) && location.host().equals(href.host())
            && location.port() == href.port()) {
        List<String> locationSegments = location.pathSegments(), hrefSegments = href.pathSegments();

        // don't compare trailing slash segment ("")
        int nBasePathSegments = locationSegments.size();
        if ("".equals(locationSegments.get(nBasePathSegments - 1)))
            nBasePathSegments--;

        /* example:   locationSegments  = [ "davCollection", "" ]
                  nBasePathSegments = 1
                  hrefSegments      = [ "davCollection", "aMember" ]
        */

        if (hrefSegments.size() > nBasePathSegments) {
            boolean sameBasePath = true;
            for (int i = 0; i < nBasePathSegments; i++) {
                if (!locationSegments.get(i).equals(hrefSegments.get(i))) {
                    sameBasePath = false;
                    break;
                }
            }

            if (sameBasePath)
                members.add(target = new DavResource(log, httpClient, href));
        }
    }

    // set properties for target
    if (target != null)
        target.properties.merge(properties, true);
    else
        log.warn("Received <response> not for self and not for member resource");
}

From source file:at.bitfire.dav4android.DavResource.java

License:Open Source License

private PropertyCollection parseMultiStatus_PropStat(XmlPullParser parser)
        throws IOException, XmlPullParserException {
    // <!ELEMENT propstat (prop, status, error?, responsedescription?) >
    final int depth = parser.getDepth();

    StatusLine status = null;/*  w  w w. j  av  a  2  s.c om*/
    PropertyCollection prop = null;

    int eventType = parser.getEventType();
    while (!(eventType == XmlPullParser.END_TAG && parser.getDepth() == depth)) {
        if (eventType == XmlPullParser.START_TAG && parser.getDepth() == depth + 1) {
            String ns = parser.getNamespace(), name = parser.getName();
            if (XmlUtils.NS_WEBDAV.equals(ns))
                switch (name) {
                case "prop":
                    prop = parseMultiStatus_Prop(parser);
                    break;
                case "status":
                    try {
                        status = StatusLine.parse(parser.nextText());
                    } catch (ProtocolException e) {
                        log.warn("Invalid status line, treating as 500 Server Error");
                        status = new StatusLine(Protocol.HTTP_1_1, 500, "Invalid status line");
                    }
                }
        }
        eventType = parser.next();
    }

    if (status != null && status.code / 100 != 2)
        // not successful, null out property values so that they can be removed when merging in parseMultiStatus_Response
        prop.nullAllValues();

    return prop;
}

From source file:com.microsoft.windowsazure.mobileservices.sdk.testapp.framework.filters.EchoFilter.java

License:Open Source License

@Override
public ListenableFuture<ServiceFilterResponse> handleRequest(ServiceFilterRequest request,
        NextServiceFilterCallback nextServiceFilterCallback) {
    ServiceFilterResponseMock response = new ServiceFilterResponseMock();
    response.setContent(request.getRawContent());
    response.setStatus(new StatusLine(Protocol.HTTP_2, 200, ""));

    ServiceFilterRequestMock requestMock = new ServiceFilterRequestMock(response);
    return nextServiceFilterCallback.onNext(requestMock);

    //return nextServiceFilterCallback.onNext(request);
}

From source file:com.microsoft.windowsazure.mobileservices.sdk.testapp.framework.filters.HttpMetaEchoFilter.java

License:Open Source License

@Override
public ListenableFuture<ServiceFilterResponse> handleRequest(ServiceFilterRequest request,
        NextServiceFilterCallback nextServiceFilterCallback) {

    JsonObject jResponse = new JsonObject();

    jResponse.addProperty("method", request.getMethod());

    Headers headers = request.getHeaders();
    if (headers != null && headers.size() > 0) {
        JsonObject jHeaders = new JsonObject();

        for (int i = 0; i < headers.size(); i++) {
            jHeaders.addProperty(headers.name(i), headers.value(i));
        }//from  ww  w  .j  a va 2 s  .co m

        jResponse.add("headers", jHeaders);
    }

    Uri uri = Uri.parse(request.getUrl());
    String query = uri.getQuery();

    if (query != null && query.trim() != "") {
        JsonObject jParameters = new JsonObject();

        for (String parameter : query.split("&")) {
            jParameters.addProperty(parameter.split("=")[0], parameter.split("=")[1]);
        }
        jResponse.add("parameters", jParameters);
    }

    ServiceFilterResponseMock response = new ServiceFilterResponseMock();
    response.setContent(jResponse.toString());
    response.setStatus(new StatusLine(Protocol.HTTP_2, 200, ""));

    ServiceFilterRequestMock requestMock = new ServiceFilterRequestMock(response);
    return nextServiceFilterCallback.onNext(requestMock);

    //return nextServiceFilterCallback.onNext(request);
}

From source file:com.microsoft.windowsazure.mobileservices.sdk.testapp.framework.filters.NullResponseContentFilter.java

License:Open Source License

@Override
public ListenableFuture<ServiceFilterResponse> handleRequest(ServiceFilterRequest request,
        NextServiceFilterCallback nextServiceFilterCallback) {
    ServiceFilterResponseMock response = new ServiceFilterResponseMock();

    response.setContent((String) null);
    response.setStatus(new StatusLine(Protocol.HTTP_2, 200, ""));

    ServiceFilterRequestMock requestMock = new ServiceFilterRequestMock(response);
    return nextServiceFilterCallback.onNext(requestMock);
}

From source file:com.microsoft.windowsazure.mobileservices.sdk.testapp.test.CustomApiClientTests.java

License:Open Source License

public void testResponseWithNon2xxStatusShouldThrowException() throws Throwable {

    final ResultsContainer container = new ResultsContainer();

    MobileServiceClient client = null;/*  ww w.j  a  v  a  2  s. c o  m*/

    try {
        client = new MobileServiceClient(appUrl, getInstrumentation().getTargetContext());

        client = client.withFilter(new ServiceFilter() {

            @Override
            public ListenableFuture<ServiceFilterResponse> handleRequest(ServiceFilterRequest request,
                    NextServiceFilterCallback nextServiceFilterCallback) {

                ServiceFilterResponseMock mockResponse = new ServiceFilterResponseMock();
                mockResponse.setStatus(new StatusLine(Protocol.HTTP_2, 418, "")); // I'm a
                // teapot
                // status
                // code
                ServiceFilterRequestMock mockRequest = new ServiceFilterRequestMock(mockResponse);

                return nextServiceFilterCallback.onNext(mockRequest);
            }
        });

        List<Pair<String, String>> mockHeaders = new ArrayList<Pair<String, String>>();
        List<Pair<String, String>> mockParameters = new ArrayList<Pair<String, String>>();

        client.invokeApi("myApi", new byte[] { 1, 2, 3, 4 }, HttpConstants.PostMethod, mockHeaders,
                mockParameters).get();

    } catch (Exception exception) {
        if (exception instanceof ExecutionException) {
            container.setException((Exception) exception.getCause());
        } else {
            container.setException(exception);
        }
    }

    // Asserts
    Exception exception = container.getException();
    if (!(exception instanceof MobileServiceException)) {
        fail("Expected Exception MobileServiceException");
    }
}

From source file:com.microsoft.windowsazure.mobileservices.sdk.testapp.test.EnhancedPushTests.java

License:Open Source License

public void testUnregister() throws Throwable {

    final Container container = new Container();

    MobileServiceClient client = null;//  w  w  w . j  a v  a  2  s . co  m

    String installationId = MobileServiceApplication.getInstallationId(getInstrumentation().getTargetContext());

    final String expectedUrl = appUrl + pnsApiUrl + "/installations/" + Uri.encode(installationId);

    try {
        client = new MobileServiceClient(appUrl, getInstrumentation().getTargetContext());

        client = client.withFilter(new ServiceFilter() {

            @Override
            public ListenableFuture<ServiceFilterResponse> handleRequest(ServiceFilterRequest request,
                    NextServiceFilterCallback nextServiceFilterCallback) {

                container.requestUrl = request.getUrl();
                container.requestMethod = request.getMethod();

                ServiceFilterResponseMock mockResponse = new ServiceFilterResponseMock();
                mockResponse.setStatus(new StatusLine(Protocol.HTTP_2, 204, ""));

                ServiceFilterRequestMock mockRequest = new ServiceFilterRequestMock(mockResponse);

                return nextServiceFilterCallback.onNext(mockRequest);
            }
        });

        final MobileServicePush push = client.getPush();
        push.unregister().get();

    } catch (Exception exception) {
        if (exception instanceof ExecutionException) {
            container.exception = (Exception) exception.getCause();
        } else {
            container.exception = exception;
        }

        fail(container.exception.getMessage());
    }

    // Asserts
    Assert.assertEquals(expectedUrl, container.requestUrl);
    Assert.assertEquals(HttpConstants.DeleteMethod, container.requestMethod);
}

From source file:com.microsoft.windowsazure.mobileservices.sdk.testapp.test.EnhancedPushTests.java

License:Open Source License

public void testRegister() throws Throwable {

    final Container container = new Container();

    MobileServiceClient client = null;//from   ww w .j a v  a 2s . c  om
    final String handle = "handle";

    String installationId = MobileServiceApplication.getInstallationId(getInstrumentation().getTargetContext());

    final String expectedUrl = appUrl + pnsApiUrl + "/installations/" + Uri.encode(installationId);
    final String expectedContent = "{\"pushChannel\":\"handle\",\"platform\":\"gcm\"}";
    try {
        client = new MobileServiceClient(appUrl, getInstrumentation().getTargetContext());

        client = client.withFilter(new ServiceFilter() {

            @Override
            public ListenableFuture<ServiceFilterResponse> handleRequest(ServiceFilterRequest request,
                    NextServiceFilterCallback nextServiceFilterCallback) {

                container.requestUrl = request.getUrl();
                container.requestContent = request.getContent();
                container.requestMethod = request.getMethod();

                ServiceFilterResponseMock mockResponse = new ServiceFilterResponseMock();
                mockResponse.setStatus(new StatusLine(Protocol.HTTP_2, 204, ""));

                ServiceFilterRequestMock mockRequest = new ServiceFilterRequestMock(mockResponse);

                return nextServiceFilterCallback.onNext(mockRequest);
            }
        });

        final MobileServicePush push = client.getPush();
        push.register(handle).get();

    } catch (Exception exception) {
        if (exception instanceof ExecutionException) {
            container.exception = (Exception) exception.getCause();
        } else {
            container.exception = exception;
        }

        fail(container.exception.getMessage());
    }

    // Asserts
    Assert.assertEquals(expectedUrl, container.requestUrl);
    Assert.assertEquals(expectedContent, container.requestContent);
    Assert.assertEquals(HttpConstants.PutMethod, container.requestMethod);
}

From source file:com.microsoft.windowsazure.mobileservices.sdk.testapp.test.EnhancedPushTests.java

License:Open Source License

public void testRegisterTemplate() throws Throwable {

    final Container container = new Container();

    MobileServiceClient client = null;// w w w  . j a  v  a 2s . com
    final String handle = "handle";

    String installationId = MobileServiceApplication.getInstallationId(getInstrumentation().getTargetContext());

    final String expectedUrl = appUrl + pnsApiUrl + "/installations/" + Uri.encode(installationId);
    final String expectedContent = "{\"pushChannel\":\"handle\",\"platform\":\"gcm\",\"templates\":{\"template1\":{\"body\":\"{\\\"data\\\":\\\"abc\\\"}\"}}}";
    try {
        client = new MobileServiceClient(appUrl, getInstrumentation().getTargetContext());

        client = client.withFilter(new ServiceFilter() {

            @Override
            public ListenableFuture<ServiceFilterResponse> handleRequest(ServiceFilterRequest request,
                    NextServiceFilterCallback nextServiceFilterCallback) {

                container.requestUrl = request.getUrl();
                container.requestContent = request.getContent();
                container.requestMethod = request.getMethod();

                ServiceFilterResponseMock mockResponse = new ServiceFilterResponseMock();
                mockResponse.setStatus(new StatusLine(Protocol.HTTP_2, 204, ""));

                ServiceFilterRequestMock mockRequest = new ServiceFilterRequestMock(mockResponse);

                return nextServiceFilterCallback.onNext(mockRequest);
            }
        });

        final MobileServicePush push = client.getPush();
        push.registerTemplate(handle, "template1", "{\"data\":\"abc\"}").get();

    } catch (Exception exception) {
        if (exception instanceof ExecutionException) {
            container.exception = (Exception) exception.getCause();
        } else {
            container.exception = exception;
        }

        fail(container.exception.getMessage());
    }

    // Asserts
    Assert.assertEquals(expectedUrl, container.requestUrl);
    Assert.assertEquals(expectedContent, container.requestContent);
    Assert.assertEquals(HttpConstants.PutMethod, container.requestMethod);
}

From source file:com.microsoft.windowsazure.mobileservices.sdk.testapp.test.IdPropertyTests.java

License:Open Source License

private ServiceFilter getTestFilter(final int statusCode, final String content) {
    return new ServiceFilter() {

        @Override//from  ww  w  .ja  va  2 s  . co m
        public ListenableFuture<ServiceFilterResponse> handleRequest(ServiceFilterRequest request,
                NextServiceFilterCallback nextServiceFilterCallback) {

            // Create a mock response simulating an error
            ServiceFilterResponseMock response = new ServiceFilterResponseMock();
            response.setStatus(new StatusLine(Protocol.HTTP_2, statusCode, ""));
            response.setContent(content);

            // create a mock request to replace the existing one
            ServiceFilterRequestMock requestMock = new ServiceFilterRequestMock(response);
            return nextServiceFilterCallback.onNext(requestMock);
        }
    };
}