Example usage for com.liferay.portal.kernel.servlet HttpHeaders CONTENT_LENGTH

List of usage examples for com.liferay.portal.kernel.servlet HttpHeaders CONTENT_LENGTH

Introduction

In this page you can find the example usage for com.liferay.portal.kernel.servlet HttpHeaders CONTENT_LENGTH.

Prototype

String CONTENT_LENGTH

To view the source code for com.liferay.portal.kernel.servlet HttpHeaders CONTENT_LENGTH.

Click Source Link

Usage

From source file:com.liferay.document.library.webserver.test.WebServerRangeTest.java

License:Open Source License

@Test
public void testSingleRangeByte() throws Exception {
    MockHttpServletResponse mockHttpServletResponse = testRange("bytes=10-10");

    Assert.assertEquals("1", mockHttpServletResponse.getHeader(HttpHeaders.CONTENT_LENGTH));
    Assert.assertEquals("bytes 10-10/80", mockHttpServletResponse.getHeader(HttpHeaders.CONTENT_RANGE));
    Assert.assertEquals("B", mockHttpServletResponse.getContentAsString());
}

From source file:com.liferay.document.library.webserver.test.WebServerRangeTest.java

License:Open Source License

@Test
public void testSingleRangeFirst() throws Exception {
    MockHttpServletResponse mockHttpServletResponse = testRange("bytes=0-9");

    Assert.assertEquals("10", mockHttpServletResponse.getHeader(HttpHeaders.CONTENT_LENGTH));
    Assert.assertEquals("bytes 0-9/80", mockHttpServletResponse.getHeader(HttpHeaders.CONTENT_RANGE));
    Assert.assertEquals("A123456789", mockHttpServletResponse.getContentAsString());
}

From source file:com.liferay.document.library.webserver.test.WebServerRangeTest.java

License:Open Source License

@Test
public void testSingleRangeLast() throws Exception {
    MockHttpServletResponse mockHttpServletResponse = testRange("bytes=70-79");

    Assert.assertEquals("10", mockHttpServletResponse.getHeader(HttpHeaders.CONTENT_LENGTH));
    Assert.assertEquals("bytes 70-79/80", mockHttpServletResponse.getHeader(HttpHeaders.CONTENT_RANGE));
    Assert.assertArrayEquals(_UNICODE_DATA.getBytes(), mockHttpServletResponse.getContentAsByteArray());
}

From source file:com.liferay.marketplace.store.web.internal.portlet.RemoteMVCPortlet.java

License:Open Source License

protected void remoteServeResource(ResourceRequest resourceRequest, ResourceResponse resourceResponse)
        throws Exception {

    ThemeDisplay themeDisplay = (ThemeDisplay) resourceRequest.getAttribute(WebKeys.THEME_DISPLAY);

    OAuthRequest oAuthRequest = new OAuthRequest(Verb.GET, getServerPortletURL());

    setRequestParameters(resourceRequest, resourceResponse, oAuthRequest);

    addOAuthParameter(oAuthRequest, "p_p_lifecycle", "2");
    addOAuthParameter(oAuthRequest, "p_p_resource_id", resourceRequest.getResourceID());

    Response response = getResponse(themeDisplay.getUser(), oAuthRequest);

    String contentType = response.getHeader(HttpHeaders.CONTENT_TYPE);

    if (contentType.startsWith(ContentTypes.APPLICATION_OCTET_STREAM)) {
        String contentDisposition = response.getHeader(HttpHeaders.CONTENT_DISPOSITION);
        int contentLength = GetterUtil.getInteger(response.getHeader(HttpHeaders.CONTENT_LENGTH));

        PortletResponseUtil.sendFile(resourceRequest, resourceResponse, getFileName(contentDisposition),
                response.getStream(), contentLength, contentType, HttpHeaders.CONTENT_DISPOSITION_ATTACHMENT);
    } else {/*  w w  w  .j av  a2 s  .  c o m*/
        resourceResponse.setContentType(contentType);

        PortletResponseUtil.write(resourceResponse, response.getStream());
    }
}

From source file:com.liferay.wsrp.bind.MarkupServiceImpl.java

License:Open Source License

protected void addHeaders(MimeRequest mimeRequest, Http.Options httpOptions) {

    ClientData clientData = mimeRequest.getClientData();

    Extension[] extensions = clientData.getExtensions();

    MessageElement[] clientAttributes = ExtensionUtil.getMessageElements(extensions);

    for (MessageElement clientAttribute : clientAttributes) {
        String name = clientAttribute.getName();
        String value = clientAttribute.getValue();

        if (name.equalsIgnoreCase(HttpHeaders.ACCEPT_ENCODING)
                || name.equalsIgnoreCase(HttpHeaders.CONTENT_LENGTH)
                || name.equalsIgnoreCase(HttpHeaders.CONTENT_TYPE)
                || name.equalsIgnoreCase(HttpHeaders.COOKIE)) {

            continue;
        }//from   w ww  .j  av a2 s.c  om

        httpOptions.addHeader(name, value);
    }
}

From source file:com.liferay.wsrp.bind.MarkupServiceImpl.java

License:Open Source License

protected ResourceResponse doGetResource(GetResource getResource) throws Exception {

    WSRPProducer wsrpProducer = getWSRPProducer();

    Http.Options httpOptions = new Http.Options();

    addHeaders(getResource.getResourceParams(), httpOptions);

    httpOptions.setLocation(getURL(getResource, wsrpProducer));

    ResourceParams resourceParams = getResource.getResourceParams();

    NamedString[] formParameters = resourceParams.getFormParameters();

    if (formParameters != null) {
        NavigationalContext navigationalContext = resourceParams.getNavigationalContext();

        PortletContext portletContext = getResource.getPortletContext();

        String namespace = PortalUtil.getPortletNamespace(getPortletId(portletContext, navigationalContext));

        for (NamedString formParameter : formParameters) {
            httpOptions.addPart(namespace + formParameter.getName(), formParameter.getValue());
        }/* w w w  .j a v a2  s .c  o m*/

        if (formParameters.length > 0) {
            httpOptions.setPost(true);
        }
    }

    httpOptions.setFollowRedirects(false);

    byte[] itemBinary = getBinaryContent(httpOptions);

    ResourceContext resourceContext = new ResourceContext();

    Http.Response response = httpOptions.getResponse();

    String contentType = response.getContentType();

    if (itemBinary != null) {
        if (Validator.isNotNull(contentType) && contentType.toLowerCase().startsWith("text")) {

            String content = new String(itemBinary);

            resourceContext.setItemString(content);
            resourceContext.setRequiresRewriting(true);
        } else {
            resourceContext.setItemBinary(itemBinary);
        }
    }

    List<NamedString> clientAttributes = new ArrayList<NamedString>();

    if (Validator.isNotNull(contentType)) {
        NamedString clientAttribute = new NamedString();

        clientAttribute.setName(HttpHeaders.CONTENT_TYPE);
        clientAttribute.setValue(contentType);

        clientAttributes.add(clientAttribute);
    }

    int contentLength = response.getContentLength();

    if (contentLength >= 0) {
        NamedString clientAttribute = new NamedString();

        clientAttribute.setName(HttpHeaders.CONTENT_LENGTH);
        clientAttribute.setValue(Integer.toString(contentLength));

        clientAttributes.add(clientAttribute);
    }

    resourceContext.setClientAttributes(clientAttributes.toArray(new NamedString[clientAttributes.size()]));

    ResourceResponse resourceResponse = new ResourceResponse();

    resourceResponse.setResourceContext(resourceContext);

    return resourceResponse;
}

From source file:com.liferay.wsrp.bind.V2MarkupServiceImpl.java

License:Open Source License

protected void addHeaders(MimeRequest mimeRequest, Http.Options httpOptions) {

    ClientData clientData = mimeRequest.getClientData();

    Extension[] extensions = clientData.getExtensions();

    MessageElement[] clientAttributes = ExtensionHelperUtil.getMessageElements(extensions);

    if (clientAttributes == null) {
        return;//from  w  w w  .ja  va  2 s  .c  o m
    }

    for (MessageElement clientAttribute : clientAttributes) {
        String name = ExtensionHelperUtil.getNameAttribute(clientAttribute);
        String value = clientAttribute.getValue();

        if (StringUtil.equalsIgnoreCase(name, HttpHeaders.ACCEPT_ENCODING)
                || StringUtil.equalsIgnoreCase(name, HttpHeaders.CONTENT_LENGTH)
                || StringUtil.equalsIgnoreCase(name, HttpHeaders.CONTENT_TYPE)
                || StringUtil.equalsIgnoreCase(name, HttpHeaders.COOKIE)) {

            continue;
        }

        httpOptions.addHeader(name, value);
    }
}

From source file:com.liferay.wsrp.bind.V2MarkupServiceImpl.java

License:Open Source License

protected ResourceResponse doGetResource(GetResource getResource) throws Exception {

    WSRPProducer wsrpProducer = getWSRPProducer();

    Http.Options httpOptions = new Http.Options();

    addHeaders(getResource.getResourceParams(), httpOptions);

    httpOptions.setLocation(getURL(getResource, wsrpProducer));

    ResourceParams resourceParams = getResource.getResourceParams();

    UploadContext[] uploadContexts = resourceParams.getUploadContexts();

    processUploadContexts(uploadContexts, httpOptions);

    NamedString[] formParameters = resourceParams.getFormParameters();

    if (formParameters != null) {
        NavigationalContext navigationalContext = resourceParams.getNavigationalContext();

        PortletContext portletContext = getResource.getPortletContext();

        String namespace = PortalUtil.getPortletNamespace(getPortletId(portletContext, navigationalContext));

        for (NamedString formParameter : formParameters) {
            httpOptions.addPart(namespace + formParameter.getName(), formParameter.getValue());
        }/* w w w. j  av a2  s.c  o  m*/

        if (formParameters.length > 0) {
            httpOptions.setPost(true);
        }
    }

    httpOptions.setFollowRedirects(false);

    byte[] itemBinary = getBinaryContent(httpOptions);

    ResourceContext resourceContext = new ResourceContext();

    Http.Response response = httpOptions.getResponse();

    String contentType = response.getContentType();

    if (itemBinary != null) {
        if (Validator.isNotNull(contentType) && StringUtil.toLowerCase(contentType).startsWith("text")) {

            String content = new String(itemBinary);

            resourceContext.setItemString(content);
            resourceContext.setRequiresRewriting(true);
        } else {
            resourceContext.setItemBinary(itemBinary);
        }
    }

    List<NamedString> clientAttributes = new ArrayList<NamedString>();

    String contentDisposition = response.getHeader(HttpHeaders.CONTENT_DISPOSITION);

    if (Validator.isNotNull(contentDisposition)) {
        NamedString clientAttribute = new NamedString();

        clientAttribute.setName(HttpHeaders.CONTENT_DISPOSITION);
        clientAttribute.setValue(contentDisposition);

        clientAttributes.add(clientAttribute);
    }

    if (Validator.isNotNull(contentType)) {
        resourceContext.setMimeType(contentType);

        NamedString clientAttribute = new NamedString();

        clientAttribute.setName(HttpHeaders.CONTENT_TYPE);
        clientAttribute.setValue(contentType);

        clientAttributes.add(clientAttribute);
    }

    int contentLength = response.getContentLength();

    if (contentLength >= 0) {
        NamedString clientAttribute = new NamedString();

        clientAttribute.setName(HttpHeaders.CONTENT_LENGTH);
        clientAttribute.setValue(Integer.toString(contentLength));

        clientAttributes.add(clientAttribute);
    }

    resourceContext.setClientAttributes(clientAttributes.toArray(new NamedString[clientAttributes.size()]));

    ResourceResponse resourceResponse = new ResourceResponse();

    resourceResponse.setResourceContext(resourceContext);

    return resourceResponse;
}

From source file:com.liferay.wsrp.portlet.ConsumerPortlet.java

License:Open Source License

protected void processResourceResponse(ResourceRequest resourceRequest, ResourceResponse resourceResponse,
        WSRPConsumerManager wsrpConsumerManager,
        oasis.names.tc.wsrp.v2.types.ResourceResponse wsrpResourceResponse) throws Exception {

    PortletSession portletSession = resourceRequest.getPortletSession();

    PortletContext portletContext = wsrpResourceResponse.getPortletContext();

    if (portletContext != null) {
        portletSession.setAttribute(WebKeys.PORTLET_CONTEXT, portletContext);
    }/*from   www  .  j a  va 2s  .c  o m*/

    SessionContext sessionContext = wsrpResourceResponse.getSessionContext();

    if (sessionContext != null) {
        portletSession.setAttribute(WebKeys.SESSION_CONTEXT, sessionContext);
    }

    ResourceContext resourceContext = wsrpResourceResponse.getResourceContext();

    NamedString[] clientAttributes = resourceContext.getClientAttributes();

    if (clientAttributes != null) {
        for (NamedString clientAttribute : clientAttributes) {
            String name = clientAttribute.getName();
            String value = clientAttribute.getValue();

            if (name.equalsIgnoreCase(HttpHeaders.CONTENT_LENGTH)) {
                resourceResponse.setContentLength(Integer.parseInt(value));
            } else if (name.equalsIgnoreCase(HttpHeaders.CONTENT_TYPE)) {
                resourceResponse.setContentType(value);
            }
        }
    }

    String itemString = resourceContext.getItemString();
    byte[] itemBinary = resourceContext.getItemBinary();

    if (Validator.isNotNull(itemString)) {
        PortletResponseUtil.write(resourceResponse, itemString);
    } else if (itemBinary != null) {
        PortletResponseUtil.write(resourceResponse, itemBinary);
    }
}

From source file:com.twelve.capital.external.feed.util.HttpImpl.java

License:Open Source License

protected byte[] URLtoByteArray(String location, Http.Method method, Map<String, String> headers,
        Cookie[] cookies, Http.Auth auth, Http.Body body, List<Http.FilePart> fileParts,
        Map<String, String> parts, Http.Response response, boolean followRedirects, String progressId,
        PortletRequest portletRequest) throws IOException {

    byte[] bytes = null;

    HttpMethod httpMethod = null;//from   w w  w. jav  a2  s. c  om
    HttpState httpState = null;

    try {
        _cookies.set(null);

        if (location == null) {
            return null;
        } else if (!location.startsWith(Http.HTTP_WITH_SLASH) && !location.startsWith(Http.HTTPS_WITH_SLASH)) {

            location = Http.HTTP_WITH_SLASH + location;
        }

        HostConfiguration hostConfiguration = getHostConfiguration(location);

        HttpClient httpClient = getClient(hostConfiguration);

        if (method.equals(Http.Method.POST) || method.equals(Http.Method.PUT)) {

            if (method.equals(Http.Method.POST)) {
                httpMethod = new PostMethod(location);
            } else {
                httpMethod = new PutMethod(location);
            }

            if (body != null) {
                RequestEntity requestEntity = new StringRequestEntity(body.getContent(), body.getContentType(),
                        body.getCharset());

                EntityEnclosingMethod entityEnclosingMethod = (EntityEnclosingMethod) httpMethod;

                entityEnclosingMethod.setRequestEntity(requestEntity);
            } else if (method.equals(Http.Method.POST)) {
                PostMethod postMethod = (PostMethod) httpMethod;

                if (!hasRequestHeader(postMethod, HttpHeaders.CONTENT_TYPE)) {

                    HttpClientParams httpClientParams = httpClient.getParams();

                    httpClientParams.setParameter(HttpMethodParams.HTTP_CONTENT_CHARSET, StringPool.UTF8);
                }

                processPostMethod(postMethod, fileParts, parts);
            }
        } else if (method.equals(Http.Method.DELETE)) {
            httpMethod = new DeleteMethod(location);
        } else if (method.equals(Http.Method.HEAD)) {
            httpMethod = new HeadMethod(location);
        } else {
            httpMethod = new GetMethod(location);
        }

        if (headers != null) {
            for (Map.Entry<String, String> header : headers.entrySet()) {
                httpMethod.addRequestHeader(header.getKey(), header.getValue());
            }
        }

        if ((method.equals(Http.Method.POST) || method.equals(Http.Method.PUT)) && ((body != null)
                || ((fileParts != null) && !fileParts.isEmpty()) || ((parts != null) && !parts.isEmpty()))) {
        } else if (!hasRequestHeader(httpMethod, HttpHeaders.CONTENT_TYPE)) {
            httpMethod.addRequestHeader(HttpHeaders.CONTENT_TYPE,
                    ContentTypes.APPLICATION_X_WWW_FORM_URLENCODED_UTF8);
        }

        if (!hasRequestHeader(httpMethod, HttpHeaders.USER_AGENT)) {
            httpMethod.addRequestHeader(HttpHeaders.USER_AGENT, _DEFAULT_USER_AGENT);
        }

        httpState = new HttpState();

        if (ArrayUtil.isNotEmpty(cookies)) {
            org.apache.commons.httpclient.Cookie[] commonsCookies = toCommonsCookies(cookies);

            httpState.addCookies(commonsCookies);

            HttpMethodParams httpMethodParams = httpMethod.getParams();

            httpMethodParams.setCookiePolicy(CookiePolicy.BROWSER_COMPATIBILITY);
        }

        if (auth != null) {
            httpMethod.setDoAuthentication(true);

            httpState.setCredentials(new AuthScope(auth.getHost(), auth.getPort(), auth.getRealm()),
                    new UsernamePasswordCredentials(auth.getUsername(), auth.getPassword()));
        }

        proxifyState(httpState, hostConfiguration);

        int responseCode = httpClient.executeMethod(hostConfiguration, httpMethod, httpState);

        response.setResponseCode(responseCode);

        Header locationHeader = httpMethod.getResponseHeader("location");

        if ((locationHeader != null) && !locationHeader.equals(location)) {
            String redirect = locationHeader.getValue();

            if (followRedirects) {
                return URLtoByteArray(redirect, Http.Method.GET, headers, cookies, auth, body, fileParts, parts,
                        response, followRedirects, progressId, portletRequest);
            } else {
                response.setRedirect(redirect);
            }
        }

        InputStream inputStream = httpMethod.getResponseBodyAsStream();

        if (inputStream != null) {
            int contentLength = 0;

            Header contentLengthHeader = httpMethod.getResponseHeader(HttpHeaders.CONTENT_LENGTH);

            if (contentLengthHeader != null) {
                contentLength = GetterUtil.getInteger(contentLengthHeader.getValue());

                response.setContentLength(contentLength);
            }

            Header contentType = httpMethod.getResponseHeader(HttpHeaders.CONTENT_TYPE);

            if (contentType != null) {
                response.setContentType(contentType.getValue());
            }

            if (Validator.isNotNull(progressId) && (portletRequest != null)) {

                ProgressInputStream progressInputStream = new ProgressInputStream(portletRequest, inputStream,
                        contentLength, progressId);

                UnsyncByteArrayOutputStream unsyncByteArrayOutputStream = new UnsyncByteArrayOutputStream(
                        contentLength);

                try {
                    progressInputStream.readAll(unsyncByteArrayOutputStream);
                } finally {
                    progressInputStream.clearProgress();
                }

                bytes = unsyncByteArrayOutputStream.unsafeGetByteArray();

                unsyncByteArrayOutputStream.close();
            } else {
                bytes = FileUtil.getBytes(inputStream);
            }
        }

        for (Header header : httpMethod.getResponseHeaders()) {
            response.addHeader(header.getName(), header.getValue());
        }

        return bytes;
    } finally {
        try {
            if (httpState != null) {
                _cookies.set(toServletCookies(httpState.getCookies()));
            }
        } catch (Exception e) {
            _log.error(e, e);
        }

        try {
            if (httpMethod != null) {
                httpMethod.releaseConnection();
            }
        } catch (Exception e) {
            _log.error(e, e);
        }
    }
}