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

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

Introduction

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

Prototype

String CONTENT_DISPOSITION

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

Click Source Link

Usage

From source file:au.com.permeance.liferay.portlet.documentlibrary.action.DownloadFolderZipAction.java

License:Open Source License

protected void sendZipFile(ResourceRequest resourceRequest, ResourceResponse resourceResponse, File zipFile,
        String zipFileName) throws Exception {

    FileInputStream zipFileInputStream = null;

    try {/*from  w  w w  . java  2 s  .  c  o m*/

        if (StringUtils.isEmpty(zipFileName)) {
            zipFileName = FilenameUtils.getBaseName(zipFile.getName());
        }

        String zipFileMimeType = MimeTypesUtil.getContentType(zipFileName);
        resourceResponse.setContentType(zipFileMimeType);

        int folderDownloadCacheMaxAge = DownloadFolderZipPropsValues.DL_FOLDER_DOWNLOAD_CACHE_MAX_AGE;
        if (folderDownloadCacheMaxAge > 0) {
            String cacheControlValue = "max-age=" + folderDownloadCacheMaxAge + ", must-revalidate";
            resourceResponse.addProperty(HttpHeaders.CACHE_CONTROL, cacheControlValue);
        }

        String contentDispositionValue = "attachment; filename=\"" + zipFileName + "\"";
        resourceResponse.addProperty(HttpHeaders.CONTENT_DISPOSITION, contentDispositionValue);

        // NOTE: java.io.File may return a length of 0 (zero) for a valid file
        // @see java.io.File#length()
        long zipFileLength = zipFile.length();
        if ((zipFileLength > 0L) && (zipFileLength < (long) Integer.MAX_VALUE)) {
            resourceResponse.setContentLength((int) zipFileLength);
        }

        zipFileInputStream = new FileInputStream(zipFile);
        OutputStream responseOutputStream = resourceResponse.getPortletOutputStream();
        long responseByteCount = IOUtils.copy(zipFileInputStream, responseOutputStream);
        responseOutputStream.flush();
        responseOutputStream.close();
        zipFileInputStream.close();
        zipFileInputStream = null;

        if (s_log.isDebugEnabled()) {
            s_log.debug("sent " + responseByteCount + " byte(s) for ZIP file " + zipFileName);
        }

    } catch (Exception e) {

        String name = StringPool.BLANK;
        if (zipFile != null) {
            name = zipFile.getName();
        }

        String msg = "Error sending ZIP file " + name + " : " + e.getMessage();
        s_log.error(msg);
        throw new PortalException(msg, e);

    } finally {

        if (zipFileInputStream != null) {
            try {
                zipFileInputStream.close();
                zipFileInputStream = null;
            } catch (Exception e) {
                String msg = "Error closing ZIP input stream : " + e.getMessage();
                s_log.error(msg);
            }
        }

    }
}

From source file:au.com.permeance.utility.propertiesviewer.portlets.PropertiesViewerPortlet.java

License:Open Source License

@Override
public void serveResource(final ResourceRequest resourceRequest, final ResourceResponse resourceResponse)
        throws IOException, PortletException {

    try {//  w w  w. ja  va2s  .c om
        ThemeDisplay themeDisplay = (ThemeDisplay) resourceRequest.getAttribute(WebKeys.THEME_DISPLAY);
        PortletDisplay portletDisplay = themeDisplay.getPortletDisplay();
        String portletId = portletDisplay.getId();

        PermissionChecker checker = PermissionThreadLocal.getPermissionChecker();
        if (checker != null && (checker.isCompanyAdmin() || checker.isOmniadmin()
                || PortletPermissionUtil.contains(checker, portletId, ActionKeys.VIEW))) {

            UploadPortletRequest uploadRequest = PortalUtil.getUploadPortletRequest(resourceRequest);

            String exportType = GetterUtil
                    .getString(uploadRequest.getParameter(PropertiesViewerConstants.PARAM_EXPORTTYPE), "all");
            String exportSection = GetterUtil.getString(
                    uploadRequest.getParameter(PropertiesViewerConstants.PARAM_EXPORTSECTION), "system");
            String term = GetterUtil.getString(
                    uploadRequest.getParameter(PropertiesViewerConstants.PARAM_SEARCH), StringPool.BLANK);
            boolean passwordSafe = GetterUtil.getBoolean(
                    uploadRequest.getParameter(PropertiesViewerConstants.PARAM_PASSWORDSAFE), false);

            String filename = PropertiesViewerConstants.SECTION_SYSTEM;
            Properties toOutput = PropertiesSearchUtil.createSortedProperties();
            if (PropertiesViewerConstants.SECTION_SYSTEM.equals(exportSection)) {

                if (PropertiesViewerConstants.TYPE_ALL.equals(exportType) || term.length() == 0) {
                    toOutput = PropertiesSearchUtil.searchSystemProperties(toOutput, StringPool.BLANK);
                } else {
                    // search
                    filename += PropertiesViewerConstants.FILE_SEARCH;
                    toOutput = PropertiesSearchUtil.searchSystemProperties(toOutput, term);
                }
                if (passwordSafe) {
                    filterPasswordSafe(toOutput);
                    filename += PropertiesViewerConstants.FILE_PASSWORDSAFE;
                }
            } else if (PropertiesViewerConstants.SECTION_PORTAL.equals(exportSection)) {
                // portal
                filename = PropertiesViewerConstants.SECTION_PORTAL;
                if (PropertiesViewerConstants.TYPE_ALL.equals(exportType) || term.length() == 0) {
                    toOutput = PropertiesSearchUtil.searchPortalProperties(toOutput, StringPool.BLANK);
                } else {
                    // search
                    filename += PropertiesViewerConstants.FILE_SEARCH;
                    toOutput = PropertiesSearchUtil.searchPortalProperties(toOutput, term);
                }
                if (passwordSafe) {
                    filterPasswordSafe(toOutput);
                    filename += PropertiesViewerConstants.FILE_PASSWORDSAFE;
                }
            } else if (PropertiesViewerConstants.SECTION_UPLOAD.equals(exportSection)) {
                // uploaded
                filename = PropertiesViewerConstants.FILE_FORMATTED;
                File uploaded = uploadRequest.getFile(PropertiesViewerConstants.PARAM_FILE);
                if (uploaded != null) {
                    FileInputStream fis = new FileInputStream(uploaded);
                    try {
                        toOutput.load(fis);
                    } finally {
                        try {
                            if (fis != null) {
                                fis.close();
                            }
                        } catch (Exception e) {
                        }
                    }
                }
            } else {
                throw new PortletException(PropertiesViewerConstants.EXCEPTION_INVALID_OPERATION);
            }

            resourceResponse.setContentType(PropertiesViewerConstants.PROPERTIES_MIME_TYPE);
            resourceResponse.addProperty(HttpHeaders.CACHE_CONTROL,
                    PropertiesViewerConstants.CACHE_HEADER_VALUE);
            resourceResponse.addProperty(HttpHeaders.CONTENT_DISPOSITION,
                    "attachment; filename=" + filename + ".properties");

            toOutput.store(resourceResponse.getPortletOutputStream(), StringPool.BLANK);
        }
    } catch (IOException e) {
        throw e;
    } catch (PortletException e) {
        throw e;
    } catch (Exception e) {
        throw new PortletException(e);
    }
}

From source file:com.knowarth.portlet.downloadinterceptor.DownloadInterceptorPortlet.java

License:Open Source License

public void serveResource(ResourceRequest resourceRequest, ResourceResponse resourceResponse)
        throws IOException {
    //Setting out email parameters
    String emailAdd = resourceRequest.getParameter("emailAddress");
    String visitorName = resourceRequest.getParameter("visitorName");
    String cmpName = resourceRequest.getParameter("companyName");
    String phoneNumber = resourceRequest.getParameter("phoneNumber");
    String comments = resourceRequest.getParameter("comments");

    //Getting the preferences and reading URL Location reading from edit mode
    PortletPreferences prefs = resourceRequest.getPreferences();
    String resourceurl = prefs.getValue("resourceurl", "");
    String caseStudyName = prefs.getValue("caseStudyName", "");
    String receiveEmailAdd = prefs.getValue("receiverEmailAdd", "");
    //emailBodyContent Return the template stored in preferences edit mode.
    String emailBodyContent = prefs.getValue("emailBodyTemplate", "");
    String emailsubj = prefs.getValue("emailSubjectTemplate", "");
    String resExtension = prefs.getValue("ResourceExtension", "");
    String body = StringUtil.replace(emailBodyContent,
            new String[] { "[$VISITOR_NAME$]", "[$COMPANY_NAME$]", "[$EMAIL_ADDRESS$]", "[$PHONE_NUMBER$]",
                    "[$COMMENTS$]", "[$CASE_STUDY_NAME$]" },
            new String[] { visitorName, cmpName, emailAdd, phoneNumber, comments, caseStudyName });

    //Setting out body and email parameters
    String subject = StringUtil.replace(emailsubj, new String[] { "[$VISITOR_NAME$]", "[$CASE_STUDY_NAME$]" },
            new String[] { visitorName, caseStudyName });
    //code for sending email
    try {/*from  w  w  w.j a va2s  . c  o m*/
        InternetAddress fromAddress = new InternetAddress(emailAdd);
        InternetAddress toAddress = new InternetAddress(receiveEmailAdd);

        MailMessage mailMessage = new MailMessage(fromAddress, toAddress, subject, body, true);
        MailServiceUtil.sendEmail(mailMessage);

    } catch (AddressException e) {
        // TODO Auto-generated catch block
        _log.error("Error Sending Message", e);
    } finally {
        //For Downloading a resource

        String contentDisposition = "attachment; filename=" + caseStudyName + "." + resExtension;
        OutputStream out = resourceResponse.getPortletOutputStream();

        //LInk for resource URL Goes here. Uncomment it out for dynamic location and comment out the static link
        URL url = new URL(resourceurl);
        URLConnection conn = url.openConnection();
        resourceResponse.setContentType(conn.getContentType());
        resourceResponse.setContentLength(conn.getContentLength());
        resourceResponse.setCharacterEncoding(conn.getContentEncoding());
        resourceResponse.setProperty(HttpHeaders.CONTENT_DISPOSITION, contentDisposition);
        resourceResponse.addProperty(HttpHeaders.CACHE_CONTROL, "max-age=3600");

        // open the stream and put it into BufferedReader
        InputStream stream = conn.getInputStream();
        int c;
        while ((c = stream.read()) != -1) {
            out.write(c);
        }
        out.flush();
        out.close();
        stream.close();

    }

}

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 {/*from  w w  w .  ja v  a  2  s . c  o  m*/
        resourceResponse.setContentType(contentType);

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

From source file:com.liferay.opensocial.shindig.service.LiferayMediaItemService.java

License:Open Source License

protected String getFileName(MediaItem mediaItem, Http.Options options) {
    Http.Response response = options.getResponse();

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

    if (contentDisposition == null) {
        return FileUtil.getShortFileName(mediaItem.getUrl());
    }//from   w  w  w  .  j a v  a  2  s  .com

    Matcher fileNameMatcher = _fileNamePattern.matcher(contentDisposition);

    if (fileNameMatcher.find()) {
        return fileNameMatcher.group(1);
    } else {
        return mediaItem.getTitle();
    }
}

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());
        }//from  w  w w.  j  a  v a 2 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.consumer.portlet.ConsumerPortlet.java

License:Open Source License

protected Object[] processMultipartForm(PortletRequest portletRequest, PortletResponse portletResponse)
        throws Exception {

    List<NamedString> formParameters = new ArrayList<NamedString>();
    List<UploadContext> uploadContexts = new ArrayList<UploadContext>();

    UploadPortletRequest uploadPortletRequest = PortalUtil.getUploadPortletRequest(portletRequest);

    Enumeration<String> enu = uploadPortletRequest.getParameterNames();

    while (enu.hasMoreElements()) {
        String name = enu.nextElement();

        if (isReservedParameter(name) || name.startsWith("p_p_")) {
            continue;
        }//from w  w  w.j  ava2 s .c  o m

        if (uploadPortletRequest.isFormField(name)) {
            String[] values = uploadPortletRequest.getParameterValues(name);

            if (values == null) {
                continue;
            }

            addFormField(formParameters, name, values);
        } else {
            UploadContext uploadContext = new UploadContext();

            String contentType = uploadPortletRequest.getContentType(name);

            uploadContext.setMimeType(contentType);

            StringBuilder sb = new StringBuilder();

            sb.append("form-data; ");
            sb.append("name=");
            sb.append(name);
            sb.append("; filename=");
            sb.append(uploadPortletRequest.getFileName(name));

            NamedString mimeAttribute = new NamedString();

            mimeAttribute.setName(HttpHeaders.CONTENT_DISPOSITION);
            mimeAttribute.setValue(sb.toString());

            uploadContext.setMimeAttributes(new NamedString[] { mimeAttribute });

            InputStream inputStream = null;

            try {
                inputStream = uploadPortletRequest.getFileAsStream(name);

                if (inputStream == null) {
                    continue;
                }

                byte[] bytes = FileUtil.getBytes(inputStream);

                if (bytes == null) {
                    continue;
                }

                uploadContext.setUploadData(bytes);
            } finally {
                StreamUtil.cleanUp(inputStream);
            }

            uploadContexts.add(uploadContext);
        }
    }

    return new Object[] { formParameters, uploadContexts };
}

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

License:Open Source License

protected void processResourceResponse(ResourceRequest resourceRequest, ResourceResponse resourceResponse,
        WSRPConsumerManager wsrpConsumerManager, ServiceHolder serviceHolder,
        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);
    }// w w w.  j a  v a 2  s .c o  m

    SessionContext sessionContext = wsrpResourceResponse.getSessionContext();

    updateSessionContext(portletSession, serviceHolder, sessionContext);

    ResourceContext resourceContext = wsrpResourceResponse.getResourceContext();

    CacheControl cacheControl = resourceContext.getCacheControl();

    if (cacheControl != null) {
        if (cacheControl.getExpires() == 0) {
            resourceResponse.setProperty(HttpHeaders.CACHE_CONTROL, HttpHeaders.CACHE_CONTROL_NO_CACHE_VALUE);
        } else if (cacheControl.getExpires() > 0) {
            resourceResponse.setProperty(HttpHeaders.CACHE_CONTROL, "max-age=" + cacheControl.getExpires());
        } else {
            resourceResponse.setProperty(HttpHeaders.CACHE_CONTROL, HttpHeaders.CACHE_CONTROL_DEFAULT_VALUE);
        }
    }

    NamedString[] clientAttributes = resourceContext.getClientAttributes();

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

            if (StringUtil.equalsIgnoreCase(name, HttpHeaders.CONTENT_DISPOSITION)) {

                resourceResponse.setProperty(HttpHeaders.CONTENT_DISPOSITION, value);

                break;
            }
        }
    }

    processMimeResponse(resourceRequest, resourceResponse, resourceContext);
}

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

License:Open Source License

protected void proxyURL(ResourceRequest resourceRequest, ResourceResponse resourceResponse, String url)
        throws Exception {

    PortletSession portletSession = resourceRequest.getPortletSession();

    WSRPConsumerPortlet wsrpConsumerPortlet = getWSRPConsumerPortlet();

    WSRPConsumer wsrpConsumer = WSRPConsumerLocalServiceUtil
            .getWSRPConsumer(wsrpConsumerPortlet.getWsrpConsumerId());

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

    options.setLocation(url);// w ww  .  j a v a 2s  .  co  m

    String cookieKey = getSessionKey(WebKeys.COOKIE, resourceRequest, wsrpConsumer);

    String cookie = (String) portletSession.getAttribute(cookieKey, PortletSession.APPLICATION_SCOPE);

    if (Validator.isNotNull(cookie)) {
        Map<String, String> headers = new HashMap<String, String>();

        headers.put(HttpHeaders.COOKIE, cookie);

        options.setHeaders(headers);
    }

    byte[] bytes = HttpUtil.URLtoByteArray(options);

    Http.Response response = options.getResponse();

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

    if (Validator.isNotNull(contentDisposition)) {
        resourceResponse.setProperty(HttpHeaders.CONTENT_DISPOSITION, contentDisposition);
    }

    int contentLength = response.getContentLength();

    if (contentLength >= 0) {
        resourceResponse.setContentLength(contentLength);
    }

    String contentType = response.getContentType();

    if (Validator.isNotNull(contentType)) {
        resourceResponse.setContentType(contentType);
    }

    String charSet = getCharSet(contentType);

    if (ParamUtil.getBoolean(resourceRequest, "wsrp-requiresRewrite")) {
        String content = rewriteURLs(resourceRequest, resourceResponse, new String(bytes, charSet));

        PortletResponseUtil.write(resourceResponse, content);
    } else {
        PortletResponseUtil.write(resourceResponse, bytes);
    }
}

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

License:Open Source License

protected Object[] processMultipartForm(PortletRequest portletRequest, PortletResponse portletResponse)
        throws Exception {

    List<NamedString> formParameters = new ArrayList<NamedString>();
    List<UploadContext> uploadContexts = new ArrayList<UploadContext>();

    UploadPortletRequest uploadPortletRequest = PortalUtil.getUploadPortletRequest(portletRequest);

    Enumeration<String> enu = uploadPortletRequest.getParameterNames();

    while (enu.hasMoreElements()) {
        String name = enu.nextElement();

        if (isReservedParameter(name) || name.startsWith("p_p_")) {
            continue;
        }/*from  w w  w. j  av a  2 s.  c om*/

        if (uploadPortletRequest.isFormField(name)) {
            String[] values = uploadPortletRequest.getParameterValues(name);

            if (values == null) {
                continue;
            }

            addFormField(formParameters, name, values);
        } else {
            UploadContext uploadContext = new UploadContext();

            String contentType = uploadPortletRequest.getContentType(name);

            uploadContext.setMimeType(contentType);

            StringBuilder sb = new StringBuilder();

            sb.append("form-data; ");
            sb.append("name=");
            sb.append(name);
            sb.append("; filename=");
            sb.append(uploadPortletRequest.getFileName(name));

            NamedString mimeAttribute = new NamedString();

            mimeAttribute.setName(HttpHeaders.CONTENT_DISPOSITION);
            mimeAttribute.setValue(sb.toString());

            uploadContext.setMimeAttributes(new NamedString[] { mimeAttribute });

            File file = uploadPortletRequest.getFile(name);

            byte[] bytes = FileUtil.getBytes(file);

            if (bytes == null) {
                continue;
            }

            uploadContext.setUploadData(bytes);

            uploadContexts.add(uploadContext);
        }
    }

    return new Object[] { formParameters, uploadContexts };
}