Example usage for javax.servlet.http HttpServletResponse setHeader

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

Introduction

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

Prototype

public void setHeader(String name, String value);

Source Link

Document

Sets a response header with the given name and value.

Usage

From source file:org.nsesa.editor.gwt.an.amendments.server.service.HtmlExportService.java

@Override
public void export(final AmendmentContainerDTO object, final HttpServletResponse response) throws IOException {
    response.setContentType("text/html; charset=UTF-8");
    response.setHeader("Content-Disposition",
            "attachment;filename=" + object.getAmendmentContainerID() + ".html");
    response.setCharacterEncoding("UTF8");

    final String content = object.getBody();
    final InputSource inputSource;
    inputSource = new InputSource(new StringReader(content));

    try {//from ww w.  j  ava  2 s  .com
        final NodeModel model = NodeModel.parse(inputSource);
        final Configuration configuration = new Configuration();
        configuration.setDefaultEncoding("UTF-8");
        configuration.setDirectoryForTemplateLoading(template.getFile().getParentFile());
        final StringWriter sw = new StringWriter();
        Map<String, Object> root = new HashMap<String, Object>();
        root.put("amendment", model);
        root.put("editorUrl", editorUrl);
        configuration.getTemplate(template.getFile().getName()).process(root, sw);
        byte[] bytes = sw.toString().getBytes("utf-8");
        IOUtils.copy(new ByteArrayInputStream(bytes), response.getOutputStream());
        response.setContentLength(bytes.length);
        response.flushBuffer();

    } catch (IOException e) {
        throw new RuntimeException("Could not read file.", e);
    } catch (SAXException e) {
        throw new RuntimeException("Could not parse file.", e);
    } catch (ParserConfigurationException e) {
        throw new RuntimeException("Could not parse file.", e);
    } catch (TemplateException e) {
        throw new RuntimeException("Could not load template.", e);
    }
}

From source file:org.openmrs.module.clinicalsummary.web.controller.evaluator.EvaluatePatientController.java

/**
 * Attach the file to the servlet response body
 *
 * @param response the response/*from  w w w .ja  v a2 s.  c  o m*/
 * @param file     the file
 * @throws Exception
 */
private void attachAndPurgeFile(final HttpServletResponse response, final File file) throws Exception {
    response.setHeader("Content-Disposition", "attachment; filename=" + file.getName());
    response.setContentType(MimeConstants.MIME_PDF);
    response.setContentLength((int) file.length());

    FileCopyUtils.copy(new FileInputStream(file), response.getOutputStream());

    if (!file.delete()) {
        log.info("Deleting temporary file failed!");
    }
}

From source file:org.codice.ddf.security.servlet.logout.LocalLogoutServlet.java

@Override
protected void doGet(HttpServletRequest request, HttpServletResponse response)
        throws ServletException, IOException {
    response.setHeader("Cache-Control", "no-cache, no-store");
    response.setHeader("Pragma", "no-cache");
    response.setContentType("text/html");

    URIBuilder redirectUrlBuilder = null;
    List<NameValuePair> params = new ArrayList<>();

    try {/*from  w  w w  . j a v a  2  s. com*/
        redirectUrlBuilder = new URIBuilder("/logout/logout-response.html");

        HttpSession session = request.getSession();
        if (session != null) {
            SecurityTokenHolder savedToken = (SecurityTokenHolder) session
                    .getAttribute(SecurityConstants.SAML_ASSERTION);
            if (savedToken != null) {
                Subject subject = ThreadContext.getSubject();
                boolean hasSecurityAuditRole = Arrays
                        .stream(System.getProperty("security.audit.roles").split(","))
                        .anyMatch(subject::hasRole);
                if (hasSecurityAuditRole) {
                    SecurityLogger.audit("Subject with admin privileges has logged out", subject);
                }

                savedToken.removeAll();
            }
            session.invalidate();
            deleteJSessionId(response);
        }

        //Check for pki
        if (request.getAttribute("javax.servlet.request.X509Certificate") != null
                && ((X509Certificate[]) request
                        .getAttribute("javax.servlet.request.X509Certificate")).length > 0) {
            params.add(new BasicNameValuePair("msg", "Please close your browser to finish logging out"));
        }

        //Check for basic
        Enumeration authHeaders = request.getHeaders(javax.ws.rs.core.HttpHeaders.AUTHORIZATION);
        while (authHeaders.hasMoreElements()) {
            if (((String) authHeaders.nextElement()).contains("Basic")) {
                params.add(new BasicNameValuePair("msg", "Please close your browser to finish logging out"));
                break;
            }
        }
        redirectUrlBuilder.addParameters(params);
        response.sendRedirect(redirectUrlBuilder.build().toString());
    } catch (URISyntaxException e) {
        LOGGER.debug("Invalid URI", e);
    }
}

From source file:apm.common.servlet.ValidateCodeServlet.java

private void createImage(HttpServletRequest request, HttpServletResponse response) throws IOException {

    response.setHeader("Pragma", "no-cache");
    response.setHeader("Cache-Control", "no-cache");
    response.setDateHeader("Expires", 0);
    response.setContentType("image/jpeg");

    /*/*from   w ww  .  j a va 2 s  . c  om*/
     * ??
     */
    String width = request.getParameter("width");
    String height = request.getParameter("height");
    if (StringUtils.isNumeric(width) && StringUtils.isNumeric(height)) {
        w = NumberUtils.toInt(width);
        h = NumberUtils.toInt(height);
    }

    BufferedImage image = new BufferedImage(w, h, BufferedImage.TYPE_INT_RGB);
    Graphics g = image.getGraphics();

    /*
     * ?
     */
    createBackground(g);

    /*
     * ?
     */
    String s = createCharacter(g);
    request.getSession().setAttribute(VALIDATE_CODE, s);

    g.dispose();
    OutputStream out = response.getOutputStream();
    ImageIO.write(image, "JPEG", out);
    out.close();

}

From source file:de.iew.raspimotion.controllers.MotionJpegController.java

public void sendCachingHeaders(HttpServletResponse response) {
    response.setHeader("Cache-Control",
            "no-store, no-cache, must-revalidate, pre-check=0, post-check=0, max-age=0");
    response.setHeader("Pragma", "no-cache");
    response.setHeader("Expires", "Mon, 3 Jan 2000 12:34:56 GMT");
}

From source file:org.shredzone.cilla.plugin.sitemap.SitemapView.java

/**
 * Renders a sitemap of all pages.//from w w  w. j  a va  2 s  .c o m
 */
@View(pattern = "/sitemap.xml.gz", name = "sitemap")
public void sitemapView(HttpServletRequest req, HttpServletResponse resp) throws ViewException {
    try {
        resp.setContentType("text/xml");
        resp.setHeader("Content-Encoding", "gzip");

        try (GZIPOutputStream go = new GZIPOutputStream(resp.getOutputStream())) {
            SitemapWriter writer = new SitemapWriter(go);

            writer.writeHeader();
            writeHome(writer);
            writePages(writer);
            writer.writeFooter();
            writer.flush();

            go.finish();
        }
    } catch (IOException ex) {
        throw new ViewException(ex);
    }
}

From source file:fi.vm.sade.osoitepalvelu.kooste.mvc.SeachController.java

/**
 * Produces the excel for previously stored search parameters. A downloadId may only be used once and
 * only by the same user that has stored the parameters for that id. Results for any given downloadId may be
 * removed if downloadId has not been used instantly after storeExcelParameters call.
 *
 * @throws fi.vm.sade.osoitepalvelu.kooste.service.search.TooFewSearchConditionsForOrganisaatiosException
 * @throws fi.vm.sade.osoitepalvelu.kooste.service.search.TooFewSearchConditionsForHenkilosException
 * @throws fi.vm.sade.osoitepalvelu.kooste.service.search.TooFewSearchConditionsForKoulutusException
 * @throws fi.vm.sade.osoitepalvelu.kooste.service.search.OrganisaatioTyyppiMissingForOrganisaatiosException
 * @see #storeExcelParameters(fi.vm.sade.osoitepalvelu.kooste.mvc.dto.FilteredSearchParametersDto)
 * There might be a better way around. Done this way so that we can avoid too long GET-request and redirect
 * browser to the download action without the need to store data on disk/db.
 *
 * @param downlaodId id returned form a prepare.excel.do call (associated with stored parameters)
 * @param lang the language to use/*from  w  w  w . ja  v a2s .c o  m*/
 * @return the Excel presentation
 * @throws NotFoundException if downloadId did not exist or already used.
 */
@ApiOperation("Palauttaa Excel-tiedoston hakutuloksista aiemman prepare.excel.do-operaatiokutsun palauttaman"
        + " tunnisteen perusteella.")
@ApiResponse(code = HttpStatus.SC_NOT_FOUND, message = "Hakua ei lytynyt downlaodId:ll.")
@RequestMapping(value = "excel.do", method = RequestMethod.GET)
public View downloadExcel(@RequestParam("downloadId") String downlaodId, @RequestParam("lang") String lang)
        throws NotFoundException, TooFewSearchConditionsForOrganisaatiosException,
        TooFewSearchConditionsForHenkilosException, TooFewSearchConditionsForKoulutusException,
        OrganisaatioTyyppiMissingForOrganisaatiosException {
    String storeKey = resultTransformerService.getLoggeInUserOid() + "@" + downlaodId;
    FilteredSearchParametersDto searchParameters = storedParameters.get(storeKey);
    if (searchParameters == null) {
        throw new NotFoundException("Excel not found for download with key = " + downlaodId);
    }
    this.storedParameters.remove(storeKey); // <- not really REST here :/
    searchParameters.getSearchTerms().setLocale(parseLocale(lang));
    CamelRequestContext context = new DefaultCamelRequestContext();
    SearchResultsDto results = searchService.find(searchParameters.getSearchTerms(), context);
    SearchResultPresentation presentation = new SearchResultPresentationByAddressFieldsDto(
            searchParameters.getSearchTerms(), searchParameters.getNonIncludedOrganisaatioOids());
    final SearchResultsPresentationDto searchResults = resultTransformerService.transformToResultRows(results,
            presentation, context, searchParameters.getSearchTerms().getSearchType());
    return new AbstractExcelView() {
        @Override
        protected void buildExcelDocument(Map<String, Object> model, HSSFWorkbook workbook,
                HttpServletRequest request, HttpServletResponse response) {
            response.setHeader("Content-Disposition", "attachment;filename=\"osoitteet.xls\"");
            searchExcelService.produceExcel(workbook, searchResults);
        }
    };
}

From source file:org.osiam.resources.controller.GroupController.java

private void setLocation(HttpServletRequest request, HttpServletResponse response) {
    String requestUrl = request.getRequestURL().toString();
    response.setHeader("Location", requestUrl);
}

From source file:com.jfinal.weixin.sdk.jfinal.MsgInterceptor.java

public void writeText(HttpServletResponse response, String text) {
    response.setContentType("text/x-json;charset=utf-8");
    response.setHeader("Cache-Control", "no-store, max-age=0, no-cache, must-revalidate");
    response.addHeader("Cache-Control", "post-check=0, pre-check=0");
    response.setHeader("Pragma", "no-cache");
    try {//w  ww.j  ava 2s  . c  o m
        PrintWriter out = response.getWriter();
        out.write(text);
        out.close();
    } catch (IOException e) {
        logger.error("error write json data", e);
    }
}

From source file:mobi.jenkinsci.server.core.servlet.HttpRequestDispatcherServlet.java

private void setResponseHeaders(final HttpServletResponse resp, final AbstractNode responseTree) {
    if (!responseTree.isCacheable()) {
        resp.setHeader("Cache-Control", "no-cache");
    }/*  ww w  . ja v  a2  s .c  o m*/
    final String eTag = responseTree.getETag();
    if (eTag != null) {
        resp.setHeader("ETag", eTag);
    }
    if (responseTree.getHttpCharacterEncoding() != null) {
        resp.setCharacterEncoding(responseTree.getHttpCharacterEncoding());
    }
}