Example usage for javax.servlet.http HttpServletResponse addHeader

List of usage examples for javax.servlet.http HttpServletResponse addHeader

Introduction

In this page you can find the example usage for javax.servlet.http HttpServletResponse addHeader.

Prototype

public void addHeader(String name, String value);

Source Link

Document

Adds a response header with the given name and value.

Usage

From source file:org.appverse.web.framework.backend.frontfacade.rest.authentication.filter.XSSHeaderFilter.java

@Override
public void doFilter(ServletRequest servletRequest, ServletResponse servletResponse, FilterChain filterChain)
        throws IOException, ServletException {
    if (servletResponse instanceof HttpServletResponse) {
        logger.trace("XSS Headers ...");
        HttpServletResponse response = (HttpServletResponse) servletResponse;
        if (accessControlAllow) {
            String urlString = ACCESS_CONTROL_ALLOW_ORIGIN_DEFAULT;
            String testUrl = ((HttpServletRequest) servletRequest).getHeader(REQUEST_ORIGIN);
            if (testUrl != null && !StringUtils.isEmpty(testUrl)) {
                urlString = testUrl;//from  ww w.  java2  s.c o m
            }
            response.addHeader("Access-Control-Allow-Origin", urlString);
            response.addHeader("Access-Control-Allow-Credentials", ACCESS_CONTROL_ALLOW_CREDENTIALS);
            response.addHeader("Access-Control-Allow-Headers", ACCESS_CONTROL_ALLOW_HEADERS);
            response.addHeader("Access-Control-Allow-Methods", ACCESS_CONTROL_ALLOW_METHODS);
        }
        response.addHeader("Cache-Control", "private");
        logger.trace("XSS Headers done.");
    }

    //follow the chain
    filterChain.doFilter(servletRequest, servletResponse);
}

From source file:com.jada.browser.YuiImageBrowser.java

public void doPost(HttpServletRequest request, HttpServletResponse response) {
    try {/*  ww w .  j av  a 2s  .c  om*/
        response.setContentType("text/html; charset=utf-8");
        response.addHeader("Pragma", "no-cache");
        response.addHeader("Cache-Control", "no-cache");
        response.addHeader("Cache-Control", "must-revalidate");
        response.addHeader("Expires", "Mon, 8 Aug 2006 10:00:00 GMT");
        PrintWriter out = response.getWriter();
        if (securityManager != null) {
            if (!securityManager.isAllowAccess(request)) {
                out.println("Access denied.  You are not allowed to access Image Browser service.");
                out.flush();
                out.close();
                return;
            }
        }

        String action = request.getParameter("action");
        String currentFolder = request.getParameter("currentFolder");
        String targetFolder = request.getParameter("targetFolder");
        String result = null;
        if (action.equals(ACTION_LISTCURRENT) || action.equals(ACTION_LISTNEXT)
                || action.equals(ACTION_LISTPREVIOUS)) {
            result = performActionList(action, currentFolder, targetFolder, request);
        }
        if (action.equals(ACTION_UPLOADFILE)) {
            result = performUpload(request, currentFolder);
        }
        if (action.equals(ACTION_REMOVEFILE)) {
            result = performRemove(request, currentFolder);
        }
        if (action.equals(ACTION_CREATEFOLDER)) {
            result = performCreate(request, currentFolder);
        }
        response.setContentLength(result.length());
        out.print(result);
        out.flush();
        out.close();
    } catch (IOException ioException) {
        ioException.printStackTrace();
    } catch (Exception e) {
        e.printStackTrace();
    }
}

From source file:com.googlecode.psiprobe.controllers.RememberVisibilityController.java

protected ModelAndView handleRequestInternal(HttpServletRequest request, HttpServletResponse response)
        throws Exception {
    String cookieName = ServletRequestUtils.getStringParameter(request, "cn");
    String state = ServletRequestUtils.getStringParameter(request, "state");
    if (cookieName != null && state != null) {
        cookieName = Functions.safeCookieName(cookieName);
        ////w  w w  . ja  v a 2 s.  c  o  m
        // expire the cookis at the current date + 10years (roughly, nevermind leap years)
        //
        response.addHeader("Set-Cookie", cookieName + "=" + state + "; Expires="
                + sdf.format(new Date(System.currentTimeMillis() + 315360000000L)));
    }
    return null;
}

From source file:net.contextfw.web.application.internal.service.InitHandler.java

public final void handleRequest(final UriMapping mapping, final List<Class<? extends Component>> chain,
        final HttpServlet servlet, final HttpServletRequest request, final HttpServletResponse response)
        throws ServletException, IOException {

    if (watcher != null && watcher.hasChanged()) {
        logger.debug("Reloading resources");
        cleaner.clean();/*  ww w . ja  v  a2  s  . c o m*/
        internalDevelopmentTools.reloadResources();
    }

    response.addHeader("Expires", "Sun, 19 Nov 1978 05:00:00 GMT");
    response.addHeader("Last-Modified", new Date().toString());
    response.addHeader("Cache-Control", "no-store, no-cache, must-revalidate");
    response.addHeader("Cache-Control", "post-check=0, pre-check=0");
    response.addHeader("Pragma", "no-cache");

    if (chain == null) {
        response.sendError(HttpServletResponse.SC_NOT_FOUND);
    } else {

        WebApplicationPage page = pageScope.createPage(servlet, request, response);
        final MutableBoolean expired = new MutableBoolean(false);
        storage.initialize(page, request, System.currentTimeMillis() + HOUR,
                new ScopedWebApplicationExecution() {
                    @Override
                    public void execute(net.contextfw.web.application.WebApplication application) {
                        try {
                            WebApplicationPage page = (WebApplicationPage) application;
                            WebApplication app = webApplicationProvider.get();
                            app.setInitializerChain(chain);
                            page.setWebApplication(app);
                            listeners.beforeInitialize();
                            page.getWebApplication().initState(mapping);
                            listeners.afterInitialize();
                            listeners.beforeRender();
                            expired.setValue(page.getWebApplication().sendResponse());
                            listeners.afterRender();
                        } catch (Exception e) {
                            // TODO Fix this construct with test
                            if (e instanceof MetaComponentException) {
                                ErrorResolution resolution = ((MetaComponentException) e).getResolution();
                                try {
                                    if (resolution == ErrorResolution.SEND_NOT_FOUND_ERROR) {
                                        response.sendError(HttpServletResponse.SC_NOT_FOUND);
                                    } else if (resolution == ErrorResolution.SEND_BAD_REQUEST_ERROR) {
                                        response.sendError(HttpServletResponse.SC_BAD_REQUEST);
                                    }
                                } catch (IOException e1) {
                                    throw new WebApplicationException(e1);
                                }
                            }
                            listeners.onException(e);
                        } finally {
                            pageScope.deactivateCurrentPage();
                        }

                    }
                });
        // Setting expiration here so that long page
        // processing is
        // not
        // penalizing client
        if (expired.booleanValue()) {
            storage.remove(page.getHandle(), request);
        } else {
            storage.refresh(page.getHandle(), request, System.currentTimeMillis() + initialMaxInactivity);
        }
    }
}

From source file:AutoServlet.java

public void doGet(HttpServletRequest request, HttpServletResponse response)
        throws ServletException, java.io.IOException {

    //client browser will request the page every 60 seconds
    HttpSession session = request.getSession();
    Long times = (Long) session.getAttribute("times");
    if (times == null)
        session.setAttribute("times", new Long(0));
    long temp = 1;
    if (times != null)
        temp = (times.longValue()) + 1;//from w  w w.java 2s . c om

    if (temp < 5)
        response.addHeader("Refresh", "15");

    response.setContentType("text/html");
    java.io.PrintWriter out = response.getWriter();
    out.println("<html><head><title>Client Refresh</title></head><body>");

    //More HTML or dynamic content
    out.println("You've viewed this page " + temp + " times.");
    session.setAttribute("times", new Long(temp));
    out.println("</body></html>");

}

From source file:com.groupdocs.ui.servlets.ViewDocument.java

protected void doPost(HttpServletRequest request, HttpServletResponse response)
        throws ServletException, IOException {

    response.addHeader("Content-Type", "application/json");
    ViewDocumentParameters params = new ObjectMapper().readValue(request.getInputStream(),
            ViewDocumentParameters.class);

    ViewDocumentResponse result = new ViewDocumentResponse();
    FileData fileData = ViewerUtils.factoryFileData(params.getPath());
    DocumentInfoContainer docInfo = null;

    try {/*from   w  w  w.j  a  v a  2 s.co m*/
        result.setDocumentDescription(
                (new FileDataJsonSerializer(fileData, new FileDataOptions())).Serialize(false));
    } catch (ParseException x) {
        throw new ServletException(x);
    }

    if (params.getUseHtmlBasedEngine()) {
        try {
            docInfo = ViewerUtils.getViewerHtmlHandler()
                    .getDocumentInfo(new DocumentInfoOptions(params.getPath()));
        } catch (Exception x) {
            throw new ServletException(x);
        }

        result.setPageCss(new String[0]);
        result.setLic(true);
        result.setPdfDownloadUrl(GetPdfDownloadUrl(params));
        result.setPdfPrintUrl(GetPdfPrintUrl(params));
        result.setUrl(GetFileUrl(params));
        result.setPath(params.getPath());
        result.setName(params.getPath());
        result.setDocType(docInfo.getDocumentType());
        result.setFileType(docInfo.getFileType());

        HtmlOptions htmlOptions = new HtmlOptions();
        htmlOptions.setResourcesEmbedded(true);

        htmlOptions.setHtmlResourcePrefix("/GetResourceForHtml?documentPath=" + params.getPath()
                + "&pageNumber={page-number}&resourceName=");

        if (!DotNetToJavaStringHelper.isNullOrEmpty(params.getPreloadPagesCount().toString())
                && params.getPreloadPagesCount().intValue() > 0) {
            htmlOptions.setPageNumber(1);
            htmlOptions.setCountPagesToConvert(params.getPreloadPagesCount().intValue());
        }

        String[] cssList = null;

        RefObject<ArrayList<String>> tempRef_cssList = new RefObject<ArrayList<String>>(cssList);

        List<PageHtml> htmlPages = GetHtmlPages(params.getPath(), htmlOptions);
        cssList = tempRef_cssList.argValue;

        ArrayList<String> pagesContent = new ArrayList<String>();
        for (PageHtml page : htmlPages) {
            pagesContent.add(page.getHtmlContent());
        }
        String[] htmlContent = pagesContent.toArray(new String[0]);
        result.setPageHtml(htmlContent);
        result.setPageCss(new String[] { String.join(" ", temp_cssList) });

        for (int i = 0; i < result.getPageHtml().length; i++) {
            String html = result.getPageHtml()[i];
            int indexOfScript = html.indexOf("script");
            if (indexOfScript > 0) {
                result.getPageHtml()[i] = html.substring(0, indexOfScript);
            }
        }

    } else {

        try {
            docInfo = ViewerUtils.getViewerImageHandler()
                    .getDocumentInfo(new DocumentInfoOptions(params.getPath()));
        } catch (Exception x) {
            throw new ServletException(x);
        }

        int maxWidth = 0;
        int maxHeight = 0;
        for (PageData pageData : docInfo.getPages()) {
            if (pageData.getHeight() > maxHeight) {
                maxHeight = pageData.getHeight();
                maxWidth = pageData.getWidth();
            }
        }

        fileData.setDateCreated(new Date());
        fileData.setDateModified(docInfo.getLastModificationDate());
        fileData.setPageCount(docInfo.getPages().size());
        fileData.setPages(docInfo.getPages());
        fileData.setMaxWidth(maxWidth);
        fileData.setMaxHeight(maxHeight);

        result.setPageCss(new String[0]);
        result.setLic(true);
        result.setPdfDownloadUrl(GetPdfDownloadUrl(params));
        result.setPdfPrintUrl(GetPdfPrintUrl(params));
        result.setUrl(GetFileUrl(params.getPath(), true, false, params.getFileDisplayName(),
                params.getWatermarkText(), params.getWatermarkColor(), params.getWatermarkPostion(),
                params.getWatermarkWidth(), params.getIgnoreDocumentAbsence(), params.getUseHtmlBasedEngine(),
                params.getSupportPageRotation()));
        result.setPath(params.getPath());
        result.setName(params.getPath());

        result.setDocType(docInfo.getDocumentType());
        result.setFileType(docInfo.getFileType());

        int[] pageNumbers = new int[docInfo.getPages().size()];
        int count = 0;
        for (PageData page : docInfo.getPages()) {

            pageNumbers[count] = page.getNumber();
            count++;
        }
        String applicationHost = request.getScheme() + "://" + request.getServerName() + ":"
                + request.getServerPort();
        String[] imageUrls = ImageUrlHelper.GetImageUrls(applicationHost, pageNumbers, params);

        result.setImageUrls(imageUrls);

    }

    new ObjectMapper().writeValue(response.getOutputStream(), result);

}

From source file:edu.cornell.mannlib.vitro.webapp.filters.CachingResponseFilter.java

private void produceCacheableResponse(HttpServletRequest req, HttpServletResponse resp, FilterChain chain,
        String etag) throws IOException, ServletException {
    log.debug("Produce cacheable response: etag='" + etag + "'");
    resp.addHeader("ETag", etag);
    resp.addHeader("Vary", "Accept-Language");
    chain.doFilter(req, resp);/*from w ww. j  a va  2 s.co  m*/
}

From source file:com.woonoz.proxy.servlet.HttpRequestHandler.java

protected void copyHeaders(final HttpResponse from, final HttpServletResponse to,
        ServerHeadersHandler serverHeadersHandler) throws URISyntaxException, MalformedURLException {
    for (final Header header : from.getAllHeaders()) {
        final String modifiedValue = serverHeadersHandler.handleHeader(header.getName(), header.getValue());
        if (modifiedValue != null) {
            to.addHeader(header.getName(), modifiedValue);
        }// w w  w . j a  va 2  s. c om
    }
}

From source file:net.sf.ginp.GinpServlet.java

/**
 * Sets the headers on the servlet request such that
 * the page is not cached./*  w  w w  .  j  ava 2 s. c o m*/
 * @param res the servlet response
 */
private void setNoCache(final HttpServletResponse res) {
    // DO NOT cache the output form this servlet.
    res.setHeader("Expires", "-1");
    res.setHeader("Cache-Control", "no-store, no-cache, must-revalidate");
    res.addHeader("Cache-Control", "post-check=0, pre-check=0");
    res.setHeader("Pragma", "no-cache");
}