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

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

Introduction

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

Prototype

String CACHE_CONTROL

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

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 ww.j a v a2s  .  c om*/

        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.logviewer.portlets.LogViewerPortlet.java

License:Open Source License

/**
 * serveResource method/*from w  w  w  . j a v a 2  s .  c om*/
 */
@Override
public void serveResource(final ResourceRequest resourceRequest, final ResourceResponse resourceResponse) {
    try {
        resourceResponse.setContentType(PortletConstants.MIME_TYPE_JSON);
        resourceResponse.addProperty(HttpHeaders.CACHE_CONTROL, PortletConstants.NO_CACHE);

        final String cmd = resourceRequest.getParameter(PARAM_OP);

        if (OP_ATTACH.equals(cmd)) {
            try {
                LogHolder.attach();
                final JSONObject obj = JSONFactoryUtil.createJSONObject();
                obj.put(ATTRIB_RESULT, RESULT_SUCCESS);
                resourceResponse.getWriter().print(obj.toString());
            } catch (final Exception e) {
                final StringWriter sw = new StringWriter();
                final PrintWriter pw = new PrintWriter(sw);
                e.printStackTrace(pw);
                pw.close();
                sw.close();

                final JSONObject obj = JSONFactoryUtil.createJSONObject();
                obj.put(ATTRIB_RESULT, RESULT_ERROR);
                obj.put(ATTRIB_ERROR, e.toString());
                obj.put(ATTRIB_TRACE, sw.toString());

                resourceResponse.getWriter().print(obj.toString());

                log.error(e);
            }
        } else if (OP_DETACH.equals(cmd)) {
            LogHolder.detach();
            final JSONObject obj = JSONFactoryUtil.createJSONObject();
            obj.put(ATTRIB_RESULT, RESULT_SUCCESS);
            resourceResponse.getWriter().print(obj.toString());
        } else {

            final int pointer = GetterUtil.getInteger(resourceRequest.getParameter(ATTRIB_POINTER), -1);

            final RollingLogViewer viewer = LogHolder.getViewer();

            int curpointer = -1;
            String content = StringPool.BLANK;
            String mode = MODE_DETACHED;
            if (viewer != null) {
                curpointer = viewer.getCurrentPointer();
                content = HtmlUtil.escape(new String(viewer.getBuffer(pointer, curpointer)));
                mode = MODE_ATTACHED;
            }
            final JSONObject obj = JSONFactoryUtil.createJSONObject();
            obj.put(ATTRIB_POINTER, Integer.toString(curpointer));
            obj.put(ATTRIB_CONTENT, content);
            obj.put(ATTRIB_MODE, mode);

            resourceResponse.getWriter().print(obj.toString());
        }
    } catch (Exception e) {
        log.warn(e);
    }
}

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 .  j  a  va  2s  .  com
        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 {/* w  w  w  .j  a va  2s  .co  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.rtl.servlet.filters.ComboServletFilter.java

License:Open Source License

protected byte[] getResourceContent(HttpServletRequest request, HttpServletResponse response, URL resourceURL,
        String resourcePath, String minifierType) throws IOException {

    String fileContentKey = resourcePath.concat(StringPool.QUESTION).concat(minifierType);

    FileContentBag fileContentBag = _fileContentBagPortalCache.get(fileContentKey);

    if ((fileContentBag != null) && !PropsValues.COMBO_CHECK_TIMESTAMP) {
        return fileContentBag._fileContent;
    }// w w w  .java  2s  .  com

    URLConnection urlConnection = null;

    if (resourceURL != null) {
        urlConnection = resourceURL.openConnection();
    }

    if ((fileContentBag != null) && PropsValues.COMBO_CHECK_TIMESTAMP) {
        long elapsedTime = System.currentTimeMillis() - fileContentBag._lastModified;

        if ((urlConnection != null) && (elapsedTime <= PropsValues.COMBO_CHECK_TIMESTAMP_INTERVAL)
                && (urlConnection.getLastModified() == fileContentBag._lastModified)) {

            return fileContentBag._fileContent;
        }

        _fileContentBagPortalCache.remove(fileContentKey);
    }

    if (resourceURL == null) {
        fileContentBag = _EMPTY_FILE_CONTENT_BAG;
    } else {
        String stringFileContent = StringUtil.read(urlConnection.getInputStream());

        if (!StringUtil.endsWith(resourcePath, _CSS_MINIFIED_SUFFIX)
                && !StringUtil.endsWith(resourcePath, _JAVASCRIPT_MINIFIED_SUFFIX)) {

            if (minifierType.equals("css")) {
                try {
                    stringFileContent = DynamicCSSUtil.parseSass(_servletContext, request, resourcePath,
                            stringFileContent);
                } catch (Exception e) {
                    _log.error("Unable to parse SASS on CSS " + resourceURL.getPath(), e);

                    if (_log.isDebugEnabled()) {
                        _log.debug(stringFileContent);
                    }

                    response.setHeader(HttpHeaders.CACHE_CONTROL, HttpHeaders.CACHE_CONTROL_NO_CACHE_VALUE);
                }

                String baseURL = StringPool.BLANK;

                int index = resourcePath.lastIndexOf(CharPool.SLASH);

                if (index != -1) {
                    baseURL = resourcePath.substring(0, index + 1);
                }

                stringFileContent = AggregateUtil.updateRelativeURLs(stringFileContent, baseURL);

                stringFileContent = MinifierUtil.minifyCss(stringFileContent);
            } else if (minifierType.equals("js")) {
                stringFileContent = MinifierUtil.minifyJavaScript(stringFileContent);
            }
        }

        fileContentBag = new FileContentBag(stringFileContent.getBytes(StringPool.UTF8),
                urlConnection.getLastModified());
    }

    if (PropsValues.COMBO_CHECK_TIMESTAMP) {
        int timeToLive = (int) (PropsValues.COMBO_CHECK_TIMESTAMP_INTERVAL / Time.SECOND);

        _fileContentBagPortalCache.put(fileContentKey, fileContentBag, timeToLive);
    }

    return fileContentBag._fileContent;
}

From source file:com.liferay.rtl.servlet.filters.ComboServletFilter.java

License:Open Source License

@Override
protected void processFilter(HttpServletRequest request, HttpServletResponse response, FilterChain filterChain)
        throws Exception {

    Set<String> modulePathsSet = new LinkedHashSet<String>();

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

    if (ServerDetector.isWebSphere()) {
        Map<String, String[]> parameterMap = HttpUtil.getParameterMap(request.getQueryString());

        enu = Collections.enumeration(parameterMap.keySet());
    }// www .  ja  va 2 s  . com

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

        if (_protectedParameters.contains(name)) {
            continue;
        }

        modulePathsSet.add(name);
    }

    if (modulePathsSet.size() == 0) {
        response.sendError(HttpServletResponse.SC_BAD_REQUEST, "Modules paths set is empty");

        return;
    }

    String[] modulePaths = modulePathsSet.toArray(new String[modulePathsSet.size()]);

    String firstModulePath = modulePaths[0];

    String extension = FileUtil.getExtension(firstModulePath);

    String minifierType = ParamUtil.getString(request, "minifierType");

    if (Validator.isNull(minifierType)) {
        minifierType = "js";

        if (StringUtil.equalsIgnoreCase(extension, _CSS_EXTENSION)) {
            minifierType = "css";
        }
    }

    if (!minifierType.equals("css") && !minifierType.equals("js")) {
        minifierType = "js";
    }

    String modulePathsString = null;

    byte[][] bytesArray = null;

    if (!PropsValues.COMBO_CHECK_TIMESTAMP) {
        modulePathsString = Arrays.toString(modulePaths);

        if (minifierType.equals("css") && DynamicCSSUtil.isRightToLeft(request)) {

            modulePathsString += ".rtl";
        }

        bytesArray = _bytesArrayPortalCache.get(modulePathsString);
    }

    if (bytesArray == null) {
        String rootPath = ServletContextUtil.getRootPath(_servletContext);

        bytesArray = new byte[modulePaths.length][];

        for (int i = 0; i < modulePaths.length; i++) {
            String modulePath = modulePaths[i];

            if (!validateModuleExtension(modulePath)) {
                response.setHeader(HttpHeaders.CACHE_CONTROL, HttpHeaders.CACHE_CONTROL_NO_CACHE_VALUE);
                response.setStatus(HttpServletResponse.SC_NOT_FOUND);

                return;
            }

            byte[] bytes = new byte[0];

            if (Validator.isNotNull(modulePath)) {
                modulePath = StringUtil.replaceFirst(modulePath, PortalUtil.getPathContext(), StringPool.BLANK);

                URL url = getResourceURL(_servletContext, rootPath, modulePath);

                if (url == null) {
                    response.setHeader(HttpHeaders.CACHE_CONTROL, HttpHeaders.CACHE_CONTROL_NO_CACHE_VALUE);
                    response.setStatus(HttpServletResponse.SC_NOT_FOUND);

                    return;
                }

                bytes = getResourceContent(request, response, url, modulePath, minifierType);
            }

            bytesArray[i] = bytes;
        }

        if ((modulePathsString != null) && !PropsValues.COMBO_CHECK_TIMESTAMP) {

            _bytesArrayPortalCache.put(modulePathsString, bytesArray);
        }
    }

    String contentType = ContentTypes.TEXT_JAVASCRIPT;

    if (StringUtil.equalsIgnoreCase(extension, _CSS_EXTENSION)) {
        contentType = ContentTypes.TEXT_CSS;
    }

    response.setContentType(contentType);

    ServletResponseUtil.write(response, bytesArray);
}

From source file:com.liferay.rtl.servlet.filters.dynamiccss.DynamicCSSFilter.java

License:Open Source License

protected Object getDynamicContent(HttpServletRequest request, HttpServletResponse response,
        FilterChain filterChain) throws Exception {

    String requestURI = request.getRequestURI();

    String requestPath = requestURI;

    String contextPath = request.getContextPath();

    if (!contextPath.equals(StringPool.SLASH)) {
        requestPath = requestPath.substring(contextPath.length());
    }//from  w  w w  . j av a 2s . c  o m

    URL resourceURL = _servletContext.getResource(requestPath);

    if (resourceURL == null) {
        return null;
    }

    URLConnection urlConnection = resourceURL.openConnection();

    String cacheCommonFileName = getCacheFileName(request);

    File cacheContentTypeFile = new File(_tempDir, cacheCommonFileName + "_E_CONTENT_TYPE");
    File cacheDataFile = new File(_tempDir, cacheCommonFileName + "_E_DATA");

    if (cacheDataFile.exists() && (cacheDataFile.lastModified() >= urlConnection.getLastModified())) {

        if (cacheContentTypeFile.exists()) {
            String contentType = FileUtil.read(cacheContentTypeFile);

            response.setContentType(contentType);
        }

        return cacheDataFile;
    }

    String dynamicContent = null;

    String content = null;

    try {
        if (requestPath.endsWith(_CSS_EXTENSION)) {
            if (_log.isInfoEnabled()) {
                _log.info("Parsing SASS on CSS " + requestPath);
            }

            content = StringUtil.read(urlConnection.getInputStream());

            dynamicContent = DynamicCSSUtil.parseSass(_servletContext, request, requestPath, content);

            response.setContentType(ContentTypes.TEXT_CSS);

            FileUtil.write(cacheContentTypeFile, ContentTypes.TEXT_CSS);
        } else if (requestPath.endsWith(_JSP_EXTENSION)) {
            if (_log.isInfoEnabled()) {
                _log.info("Parsing SASS on JSP or servlet " + requestPath);
            }

            BufferCacheServletResponse bufferCacheServletResponse = new BufferCacheServletResponse(response);

            processFilter(DynamicCSSFilter.class, request, bufferCacheServletResponse, filterChain);

            bufferCacheServletResponse.finishResponse();

            content = bufferCacheServletResponse.getString();

            dynamicContent = DynamicCSSUtil.parseSass(_servletContext, request, requestPath, content);

            FileUtil.write(cacheContentTypeFile, bufferCacheServletResponse.getContentType());
        } else {
            return null;
        }
    } catch (Exception e) {
        _log.error("Unable to parse SASS on CSS " + requestPath, e);

        if (_log.isDebugEnabled()) {
            _log.debug(content);
        }

        response.setHeader(HttpHeaders.CACHE_CONTROL, HttpHeaders.CACHE_CONTROL_NO_CACHE_VALUE);
    }

    if (dynamicContent != null) {
        FileUtil.write(cacheDataFile, dynamicContent);
    } else {
        dynamicContent = content;
    }

    return dynamicContent;
}

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);
    }/*from  www  . j a  v a  2s.  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.servlet.ProxyServlet.java

License:Open Source License

protected void proxyURL(HttpServletRequest request, HttpServletResponse response, URL url) throws Exception {

    URLConnection urlConnection = url.openConnection();

    urlConnection.setIfModifiedSince(request.getDateHeader(HttpHeaders.IF_MODIFIED_SINCE));

    HttpSession session = request.getSession();

    String cookie = (String) session.getAttribute(WebKeys.COOKIE);

    if (Validator.isNotNull(cookie)) {
        urlConnection.setRequestProperty(HttpHeaders.COOKIE, cookie);
    }/*from w w w.ja va 2  s  . c  om*/

    boolean useCaches = true;

    Enumeration<String> enumeration = request.getHeaderNames();

    while (enumeration.hasMoreElements()) {
        String headerName = enumeration.nextElement();

        if (StringUtil.equalsIgnoreCase(headerName, HttpHeaders.COOKIE)
                || StringUtil.equalsIgnoreCase(headerName, HttpHeaders.IF_MODIFIED_SINCE)) {

            continue;
        }

        String headerValue = request.getHeader(headerName);

        if (Validator.isNotNull(headerValue)) {
            if (StringUtil.equalsIgnoreCase(headerName, HttpHeaders.CACHE_CONTROL)
                    && headerValue.contains(HttpHeaders.CACHE_CONTROL_NO_CACHE_VALUE)) {

                useCaches = false;
            }

            urlConnection.setRequestProperty(headerName, headerValue);
        }
    }

    urlConnection.setUseCaches(useCaches);

    urlConnection.connect();

    response.setContentLength(urlConnection.getContentLength());
    response.setContentType(urlConnection.getContentType());

    Map<String, List<String>> headers = urlConnection.getHeaderFields();

    for (Map.Entry<String, List<String>> entry : headers.entrySet()) {
        String headerName = entry.getKey();

        if (Validator.isNotNull(headerName) && !response.containsHeader(headerName)) {

            response.setHeader(headerName, urlConnection.getHeaderField(headerName));
        }
    }

    if (urlConnection instanceof HttpURLConnection) {
        HttpURLConnection httpURLConnection = (HttpURLConnection) urlConnection;

        response.setStatus(httpURLConnection.getResponseCode());
    }

    ServletResponseUtil.write(response, urlConnection.getInputStream());
}

From source file:com.permeance.utility.scriptinghelper.portlets.ScriptingHelperPortlet.java

License:Open Source License

@Override
public void serveResource(ResourceRequest resourceRequest, ResourceResponse resourceResponse) {
    ZipOutputStream zout = null;//from   w  w w . j  a  v a  2 s.  c  o m
    OutputStream out = null;
    try {
        sCheckPermissions(resourceRequest);
        _log.info("Export All As Zip");

        Map<String, String> savedscripts = new TreeMap<String, String>();
        PortletPreferences prefs = resourceRequest.getPreferences();
        for (String prefName : prefs.getMap().keySet()) {
            if (prefName != null && prefName.startsWith("savedscript.")) {
                String scriptName = prefName.substring("savedscript.".length());
                String script = prefs.getValue(prefName, "");
                String lang = prefs.getValue("lang." + scriptName, getDefaultLanguage());
                savedscripts.put(scriptName + "." + lang, script);
            }
        }

        String filename = "liferay-scripts.zip";

        out = resourceResponse.getPortletOutputStream();
        zout = new ZipOutputStream(out);
        for (String key : savedscripts.keySet()) {
            String value = savedscripts.get(key);
            zout.putNextEntry(new ZipEntry(key));
            zout.write(value.getBytes("utf-8"));
        }
        resourceResponse.setContentType("application/zip");
        resourceResponse.addProperty(HttpHeaders.CACHE_CONTROL, "max-age=3600, must-revalidate");
        resourceResponse.addProperty(HttpHeaders.CONTENT_DISPOSITION, "filename=" + filename);

    } catch (Exception e) {
        _log.error(e);
    } finally {
        try {
            if (zout != null) {
                zout.close();
            }
        } catch (Exception e) {
        }
        try {
            if (out != null) {
                out.close();
            }
        } catch (Exception e) {
        }
    }
}