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:com.salesmanager.core.security.JAASCustomerSecurityFilter.java

@Override
public void doFilter(ServletRequest request, ServletResponse response, FilterChain chain)
        throws IOException, ServletException {
    HttpServletRequest req = (HttpServletRequest) request;
    HttpServletResponse resp = (HttpServletResponse) response;
    resp.setHeader("Cache-Control", "no-cache");
    resp.setHeader("Pragma", "no-cache");
    resp.setDateHeader("Expires", 0);
    String url = req.getRequestURI();
    if (isEscapeUrlFromFilter(url) || url.endsWith(".css") || url.endsWith(".js")) {
        chain.doFilter(request, response);
        return;/*from   w  w w  .  ja va2s. c  om*/
    }

    String authToken = request.getParameter(CUSTOMER_AUTH_TOKEN);
    if (StringUtils.isBlank(authToken)) {

        HttpSession session = req.getSession();
        if (session == null) {
            resp.sendRedirect(getLogonPage(req));
        } else {
            if (session.getAttribute(SecurityConstants.SM_CUSTOMER_USER) != null) {
                chain.doFilter(request, response);
            } else {
                resp.sendRedirect(getLogonPage(req));
            }
        }
    } else {
        if (logonModule.isValidAuthToken(authToken)) {
            chain.doFilter(request, response);
        } else {
            ((HttpServletResponse) response).setStatus(HttpServletResponse.SC_UNAUTHORIZED);
            return;
        }
    }

}

From source file:gumga.framework.presentation.api.AbstractReportAPI.java

protected void setContentType(HttpServletResponse response, String reportName, ReportType type) {
    response.setContentType(type.getContentType());
    response.setHeader("Content-disposition", "inline; filename=" + reportName);
}

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

@Override
public void export(AmendmentContainerDTO object, HttpServletResponse response) {
    response.setContentType("application/pdf");
    response.setHeader("Content-Disposition",
            "attachment;filename=" + object.getAmendmentContainerID() + ".pdf");
    response.setCharacterEncoding("UTF8");
    final String content = object.getBody();
    final InputSource inputSource;
    byte[] bytes = content.getBytes(Charset.forName("UTF-8"));
    inputSource = new InputSource(new ByteArrayInputStream(bytes));

    try {/* w  ww  .  ja  v  a2  s.  c  o m*/
        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);
        configuration.getTemplate(template.getFile().getName()).process(root, sw);
        ITextRenderer renderer = new ITextRenderer();
        renderer.setDocumentFromString(sw.toString(), editorUrl + "/");
        renderer.layout();
        renderer.createPDF(response.getOutputStream());
        response.setContentLength(sw.toString().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);
    } catch (DocumentException e) {
        throw new RuntimeException("Export to pdf failed", e);
    }

}

From source file:com.controlj.green.istat.web.StatServlet.java

@Override
protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {

    resp.setHeader("Expires", "Wed, 01 Jan 2003 12:00:00 GMT");
    resp.setHeader("Cache-Control", "no-cache");
    ServletOutputStream out = resp.getOutputStream();

    try {// w  w  w .ja  v  a  2 s  . co  m
        writeStats(out, req.getParameter("loc"), req);
    } catch (Exception e) {
        resp.sendError(500, e.getMessage());
        //throw new ServletException(e);
    }

    /*
    out.println("[{ hsp:67,");
    out.println("csp: 74,");
    out.println("off: 1.5,");
    out.println("lim: 3.0,");
    out.println("current:71,");
    out.println("loc:'"+req.getParameter("loc")+"',");
    out.println("time:'"+new Date().getSeconds()+"'");
    out.println("}]");
    */
}

From source file:com.konakart.actions.gateways.GlobalCollectBaseAction.java

/**
 * Common code for setting up the redirect response.
 * //w w w  .j a  v  a 2s.co m
 * @param response
 */
protected void setupResponseForTemporaryRedirect(HttpServletResponse response) {
    response.setStatus(302);
    response.setHeader("Expires", "Wed, 11 Jan 1984 05:00:00 GMT");
    response.setHeader("Cache-Control", "max-age=0, no-cache, no-store, must-revalidate");
    response.setHeader("Pragma", "no-cache");
    response.setHeader("Connection", "close");
}

From source file:com.aurel.track.exchange.docx.exporter.DocxExportBL.java

/**
 * Serializes the docx content into the response's output stream
 * @param response//from  w  w w  .  ja  va  2  s  . c om
 * @param wordMLPackage
 * @return
 */
static String prepareReportResponse(HttpServletResponse response, String baseFileName,
        WordprocessingMLPackage wordMLPackage) {
    if (baseFileName == null) {
        baseFileName = "TrackReport";
    } else {
        baseFileName = StringEscapeUtils.unescapeHtml4(baseFileName);
        StringBuffer sb = new StringBuffer(baseFileName.replaceAll("[^a-zA-Z0-9_]", "_"));
        Pattern regex = Pattern.compile("(_[a-z])");
        Matcher regexMatcher = regex.matcher(sb);
        StringBuffer sb2 = new StringBuffer();

        try {
            while (regexMatcher.find()) {
                regexMatcher.appendReplacement(sb2, regexMatcher.group(1).toUpperCase());
            }
            regexMatcher.appendTail(sb2);

        } catch (Exception e) {
            LOGGER.error(e.getMessage());
        }
        baseFileName = sb2.toString().replaceAll("_", "");
    }
    response.reset();
    response.setHeader("Content-Type",
            "application/vnd.openxmlformats-officedocument.wordprocessingml.document");
    response.setHeader("Content-Disposition", "attachment; filename=\"" + baseFileName + ".docx\"");
    DownloadUtil.prepareCacheControlHeader(ServletActionContext.getRequest(), response);
    OutputStream outputStream = null;
    try {
        outputStream = response.getOutputStream();
    } catch (IOException e) {
        LOGGER.error("Getting the output stream failed with " + e.getMessage());
        LOGGER.error(ExceptionUtils.getStackTrace(e));
    }
    try {
        Docx4J.save(wordMLPackage, outputStream, Docx4J.FLAG_NONE);
        /*SaveToZipFile saver = new SaveToZipFile(wordMLPackage);
        saver.save(outputStream);*/
    } catch (Exception e) {
        LOGGER.error("Exporting the docx failed with throwable " + e.getMessage());
        LOGGER.debug(ExceptionUtils.getStackTrace(e));
    }
    return null;
}

From source file:com.zuoxiaolong.niubi.job.test.http.DownloadFileController.java

@RequestMapping("/download/test.jar")
public void downloadJar(HttpServletResponse response) throws IOException {
    String fileName = "test.jar";
    response.setContentType("application/octet-stream");
    response.setHeader("Content-Disposition", "attachment; filename=" + fileName);
    OutputStream outputStream = response.getOutputStream();
    outputStream.write("hello".getBytes());
    outputStream.flush();//from  w w  w  .j av  a 2s  .c  o m
    outputStream.close();
}

From source file:com.alliander.osgp.shared.security.AuthenticationTokenProcessingFilter.java

@Override
public void doFilter(final ServletRequest request, final ServletResponse response, final FilterChain chain)
        throws IOException, ServletException {

    if (!(request instanceof HttpServletRequest)) {
        throw new IOException("Expecting a HTTP request");
    }//from w  w  w  .jav  a2s .c  om

    // Read the token from the HTTP Headers
    final HttpServletRequest httpRequest = (HttpServletRequest) request;
    final String authToken = this.getValue(httpRequest, TOKEN_HEADER_KEY, TOKEN_PARAM_KEY);
    final String organisation = this.getValue(httpRequest, ORGANISATION_HEADER_KEY, ORGANISATION_PARAM_KEY);

    if (authToken != null && organisation != null) {
        // Validate the token in the authentication manager
        final CustomAuthentication authentication = new CustomAuthentication();
        authentication.setOrganisationIdentification(organisation);
        authentication.setToken(authToken);

        try {
            // Perform validation and set security context
            this.authenticationManager.validateToken(authentication);
            SecurityContextHolder.getContext().setAuthentication(authentication);

            // Set header with new token (if available)
            final HttpServletResponse httpResponse = (HttpServletResponse) response;
            httpResponse.setHeader(TOKEN_HEADER_KEY, authentication.getToken());

        } catch (final AuthenticationClientException e) {
            LOGGER.warn("Failed to validate token", e);
        }
    }

    // Continue with next filter
    chain.doFilter(request, response);
}

From source file:eu.planets_project.pp.plato.util.Downloader.java

/**
 * Starts a client side download. All information provided by parameters.
 *
 * @param file data file contains//  w  ww.ja  v a 2  s . c o m
 * @param fileName name of the file (e.g. report.pdf)
 * @param contentType mime type of the content to be downloaded
 */
public void download(byte[] file, String fileName, String contentType) {
    FacesContext facesContext = FacesContext.getCurrentInstance();
    ExternalContext context = facesContext.getExternalContext();

    HttpServletResponse response = (HttpServletResponse) context.getResponse();
    response.setHeader("Content-Disposition", "attachment;filename=\"" + fileName + "\"");
    response.setContentLength((int) file.length);
    response.setContentType(contentType);

    try {
        ByteArrayInputStream in = new ByteArrayInputStream(file);
        OutputStream out = response.getOutputStream();

        // Copy the contents of the file to the output stream
        byte[] buf = new byte[1024];
        int count;
        while ((count = in.read(buf)) >= 0) {
            out.write(buf, 0, count);
        }
        in.close();
        out.flush();
        out.close();
        facesContext.responseComplete();
    } catch (IOException ex) {
        log.error("Error in downloadFile: " + ex.getMessage());
        FacesMessages.instance().add(FacesMessage.SEVERITY_ERROR, "Download couldn't be executed");
        ex.printStackTrace();
    }
}

From source file:cn.zhuqi.mavenssh.web.servlet.ShowPic.java

/**
 * Processes requests for both HTTP <code>GET</code> and <code>POST</code>
 * methods.//from  w  w w .  j av  a 2s . c  o  m
 *
 * @param request servlet request
 * @param response servlet response
 * @throws ServletException if a servlet-specific error occurs
 * @throws IOException if an I/O error occurs
 */
protected void processRequest(HttpServletRequest request, HttpServletResponse response)
        throws ServletException, IOException {
    response.setHeader("Pragma", "No-cache");// ?????
    response.setHeader("Cache-Control", "no-cache");
    response.setDateHeader("Expire", 0);
    // ?Application
    ServletContext application = this.getServletContext();
    String sid = request.getParameter("id");
    ApplicationContext ctx = WebApplicationContextUtils.getWebApplicationContext(application);

    // ?spring IOC
    userService = (IUserService) ctx.getBean(IUserService.class);
    User user = userService.findById(Integer.valueOf(sid));
    String imgFile = user.getPicurl();
    response.setContentType(application.getMimeType(imgFile));

    FTPClientTemplate ftpClient = new FTPClientTemplate(ip, 21, username, pwd);
    ServletOutputStream sos = response.getOutputStream();
    try {
        ftpClient.get(attachment + "/" + imgFile, sos);
    } catch (Exception ex) {
    }
}