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.octo.captcha.module.web.image.ImageToJpegHelper.java

/**
 * retrieve a new ImageCaptcha using ImageCaptchaService and flush it to the response.<br/> Captcha are localized
 * using request locale.<br/>/*  w w w. j av  a 2 s  .com*/
 * <p/>
 * This method returns a 404 to the client instead of the image if the request isn't correct (missing parameters,
 * etc...)..<br/> The log may be null.<br/>
 *
 * @param theRequest  the request
 * @param theResponse the response
 * @param log         a commons logger
 * @param service     an ImageCaptchaService instance
 *
 * @throws java.io.IOException if a problem occurs during the jpeg generation process
 */
public static void flushNewCaptchaToResponse(HttpServletRequest theRequest, HttpServletResponse theResponse,
        Log log, ImageCaptchaService service, String id, Locale locale) throws IOException {

    // call the ImageCaptchaService method to retrieve a captcha
    byte[] captchaChallengeAsJpeg = null;
    ByteArrayOutputStream jpegOutputStream = new ByteArrayOutputStream();
    try {
        BufferedImage challenge = service.getImageChallengeForID(id, locale);
        // the output stream to render the captcha image as jpeg into

        ImageIO.write(challenge, "jpg", jpegOutputStream);

    } catch (IllegalArgumentException e) {
        //    log a security warning and return a 404...
        if (log != null && log.isWarnEnabled()) {
            log.warn("There was a try from " + theRequest.getRemoteAddr()
                    + " to render an captcha with invalid ID :'" + id + "' or with a too long one");
            theResponse.sendError(HttpServletResponse.SC_NOT_FOUND);
            return;
        }
    }

    captchaChallengeAsJpeg = jpegOutputStream.toByteArray();

    // render the captcha challenge as a JPEG image in the response
    theResponse.setHeader("Cache-Control", "no-store");
    theResponse.setHeader("Pragma", "no-cache");
    theResponse.setDateHeader("Expires", 0);

    theResponse.setContentType("image/jpeg");
    ServletOutputStream responseOutputStream = theResponse.getOutputStream();
    responseOutputStream.write(captchaChallengeAsJpeg);
    responseOutputStream.flush();
    responseOutputStream.close();
}

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

private User setLocationUriAndCreateUserForOutput(HttpServletRequest request, HttpServletResponse response,
        User createdUser) {/* w  w  w.  j av  a 2 s  .  co  m*/
    String requestUrl = request.getRequestURL().toString();
    response.setHeader("Location", requestUrl);
    Meta newMeta = new Meta.Builder(createdUser.getMeta()).setLocation(requestUrl).build();
    return new User.Builder(createdUser).setMeta(newMeta).build();
}

From source file:org.openmrs.module.pmtct.web.view.chart.AbstractChartView.java

/**
 * @see org.springframework.web.servlet.view.AbstractView
 *///w w  w. j  a v  a2  s . c om
@Override
@SuppressWarnings("unchecked")
protected void renderMergedOutputModel(Map model, HttpServletRequest request, HttpServletResponse response)
        throws Exception {
    // Respond as a PNG image
    response.setContentType("image/png");

    // Disable caching
    response.setHeader("Pragma", "No-cache");
    response.setDateHeader("Expires", 0);
    response.setHeader("Cache-Control", "no-cache");

    int width = 400;
    int height = 300;

    JFreeChart chart = createChart(model, request);
    chart.setBackgroundPaint(Color.WHITE);
    chart.getPlot().setOutlineStroke(new BasicStroke(0));
    chart.getPlot().setOutlinePaint(getBackgroundColor());
    chart.getPlot().setBackgroundPaint(getBackgroundColor());
    chart.getPlot().setNoDataMessage("No data available");

    ChartUtilities.writeChartAsPNG(response.getOutputStream(), chart, width, height);
}

From source file:com.buession.cas.web.controller.CaptchaController.java

@Override
protected ModelAndView handleRequestInternal(HttpServletRequest request, HttpServletResponse response)
        throws IOException {
    response.setContentType("image/jpg");
    response.setHeader("Pragma", "no-cache");
    response.setHeader("Cache-Control", "no-store, no-cache, must-revalidate");
    response.setDateHeader("Expires", 0);

    String text = producer.createText();
    captchaService.add(request, text);/* w w  w . j  a v  a 2 s  .  co m*/

    BufferedImage im = producer.createImage(text);
    ServletOutputStream out = response.getOutputStream();
    ImageIO.write(im, "jpg", out);

    try {
        out.flush();
    } finally {
        out.close();
    }

    return null;
}

From source file:no.dusken.aranea.web.control.IssueController.java

public ModelAndView handleRequestInternal(HttpServletRequest request, HttpServletResponse response)
        throws PageNotFoundException {

    // this content does not change that often, allow two hours cache
    response.setHeader("Cache-Control", "max-age=72000");

    Map<String, Object> map = new HashMap<String, Object>();
    map.put("baseImageDir", "/images");

    // LinkedHashMap maintains order...
    Map<Integer, Collection> issueMap = new LinkedHashMap<Integer, Collection>();
    int year = 0;
    List<Issue> issues;//from w ww.  ja  v a 2s .c  o m
    if (request.getParameter("year") != null) {
        try {
            year = ServletRequestUtils.getIntParameter(request, "year");
            issues = issueService.getIssuesPublished(year);
            if (issues == null || issues.size() == 0) {
                //Throwing exception so this can be threated as a 404 error on a higher level
                throw new PageNotFoundException("Issue in year " + year);
            }
            issueMap.put(year, issues);
        } catch (ServletRequestBindingException e) {
            log.info("Unable to get section name from request", e);
        }
    } else {
        // defaulting to all years
        year = (new GregorianCalendar()).get(GregorianCalendar.YEAR);
        issues = issueService.getIssuesPublished(year);
        issueMap.put(year, issues);
        // get all previous years
        do {
            year = year - 1;
            issues = issueService.getIssuesPublished(year);
            if (issues != null && issues.size() > 0) {
                issueMap.put(year, issues);
            }
        } while (issues != null && issues.size() > 0);

    }
    map.put("issueMap", issueMap);
    map.put("year", year);
    return new ModelAndView("no/dusken/aranea/base/web/pdf/view", map);
}

From source file:edu.stanford.epad.common.util.EPADFileUtils.java

public static void sendFile(HttpServletRequest httpRequest, HttpServletResponse httpResponse, File file,
        String fileName, boolean download) throws Exception {
    InputStream is = null;//from w  w w.  ja v  a2  s  .  co  m
    try {
        is = new BufferedInputStream(new FileInputStream(file));
        String mimeType = URLConnection.guessContentTypeFromStream(is);
        httpResponse.setContentType(mimeType);
        if (download)
            httpResponse.setHeader("Content-disposition", "attachment;filename=" + fileName);
        httpResponse.setHeader("pragma", "no-cache");
        OutputStream outStream = null;
        String encoding = null;
        if (httpRequest != null)
            encoding = httpRequest.getHeader("Accept-Encoding");

        if (false && encoding != null && encoding.indexOf("gzip") != -1) {
            httpResponse.setHeader("Content-Encoding", "gzip");
            outStream = new GZIPOutputStream(httpResponse.getOutputStream());
        } else if (false && encoding != null && encoding.indexOf("compress") != -1) {
            httpResponse.setHeader("Content-Encoding", "compress");
            outStream = new ZipOutputStream(httpResponse.getOutputStream());
        } else {
            outStream = httpResponse.getOutputStream();
        }
        int chunk = 1024;

        byte[] buffer = new byte[chunk];
        int length = -1;
        int i = 0;

        while ((length = is.read(buffer)) != -1) {
            outStream.write(buffer, 0, length);
            if (length < chunk)
                break;
        }
        is.close();
        is = null;
    } finally {
        if (is != null)
            is.close();
    }
}

From source file:com.parleys.server.frontend.web.ipad.filters.LoginFilter.java

@Override
public void doFilter(final ServletRequest req, final ServletResponse response, final FilterChain chain)
        throws IOException {
    final HttpServletResponse res = (HttpServletResponse) response;
    final PrintWriter writer = res.getWriter();
    res.setStatus(HttpServletResponse.SC_OK);
    res.setHeader("Cache-Control", "must-revalidate");
    res.setHeader("Expires", "Fri, 30 Oct 1998 14:19:41 GMT");
    try {/*  ww  w. j a  v a  2  s.com*/
        final String username = req.getParameter("username");
        final String password = req.getParameter("password");
        if (StringUtils.isNotBlank(username) && StringUtils.isNotBlank(password)) {
            final ParleysService bean = applicationContext.getBean(ParleysService.class);
            final Long userId = bean.getUserId(username, password);

            final String usernameAndPassword = username + ";" + password;
            final String encrypted = AESEncrypter.INSTANCE.encrypt(usernameAndPassword);
            final Cookie rememberMeCookie = new Cookie(PARLEYS_REMEMBER_ME_IPAD, encrypted);
            rememberMeCookie.setMaxAge(3600 * 24 * 7 * 26); // A half year
            res.addCookie(rememberMeCookie);

            writeUserId(writer, userId);
        } else {
            writeError(writer);
        }
    } catch (Exception e) {
        writeError(writer);
    }
}

From source file:com.marklogic.samplestack.web.security.SamplestackSecurityFilters.java

@Override
/**/*  ww w .jav  a 2 s .  co m*/
 * Hooks into Spring Security filter mechanism to manipulate
 * headers as needed.
 */
protected void doFilterInternal(HttpServletRequest request, HttpServletResponse response,
        FilterChain filterChain) throws ServletException, IOException {

    CsrfToken token = (CsrfToken) request.getAttribute("_csrf");
    if (token != null) {
        response.setHeader("X-CSRF-HEADER", token.getHeaderName());
        response.setHeader("X-CSRF-PARAM", token.getParameterName());
        response.setHeader(token.getHeaderName(), token.getToken());
    }
    response.setHeader("Access-Control-Allow-Origin", "*");
    response.setHeader("Access-Control-Allow-Methods", "POST, PUT, GET, OPTIONS, DELETE");
    response.setHeader("Access-Control-Max-Age", "3600");
    response.setHeader("Access-Control-Allow-Headers", "x-requested-with, content-type");
    filterChain.doFilter(request, response);

}

From source file:au.com.iglooit.shar.servlet.FileServlet.java

@Override
protected void doOptions(HttpServletRequest req, HttpServletResponse resp)
        throws ServletException, IOException {
    // pre-flight request processing
    resp.setHeader("Access-Control-Allow-Origin", "*");
    resp.setHeader("Access-Control-Allow-Methods", "GET, POST, OPTIONS");
    resp.setHeader("Access-Control-Allow-Headers", "Content-Type");
}

From source file:fi.hoski.web.forms.PaymentServlet.java

/**
 * Processes requests for both HTTP// w  ww .j  ava2s.  co  m
 * <code>GET</code> and
 * <code>POST</code> methods.
 *
 * @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("Cache-Control", "no-cache"); // input comes from referrer
    response.setContentType("application/json");
    JSONObject json = new JSONObject();
    JSONArray jsonArray = new JSONArray();
    try {
        String referer = request.getHeader("referer");
        log("referer=" + referer);
        if (referer != null) {
            int i1 = referer.indexOf("ancestor=");
            if (i1 != -1) {
                String ancestor = null;
                int i2 = referer.indexOf("&", i1);
                if (i2 != -1) {
                    ancestor = referer.substring(i1 + 9, i2);
                } else {
                    ancestor = referer.substring(i1 + 9);
                }
                Key raceEntryKey = KeyFactory.stringToKey(ancestor);
                BankingBarcode barcode = races.getBarcode(raceEntryKey);
                if (barcode != null) {
                    for (Map.Entry<String, Object> e : barcode.getMetaData().entrySet()) {
                        json.put(e.getKey(), e.getValue());
                    }
                    char[] bars = Code128.encode(barcode.toString());
                    int width = 0;
                    for (int cc : bars) {
                        width += cc;
                        jsonArray.put(cc);
                    }
                    json.put("barwidth", width);
                    json.put("bars", jsonArray);
                }
            }
        }
        json.write(response.getWriter());
    } catch (EntityNotFoundException ex) {
        throw new ServletException(ex);
    } catch (JSONException ex) {
        throw new ServletException(ex);
    } catch (CharNotInCodesetException ex) {
        throw new ServletException(ex);
    } finally {
    }
}