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:it.cilea.osd.jdyna.web.controller.ExportConfigurazioneSoggettari.java

/**
 * Esporta la configurazione corrente di tutti i soggettari o,
 * se la request contiene un soggettario_id, solo il soggettario con
 * quell'ID specifico.//  w w  w  .j  av a 2s .c  o m
 * 
 */
@Override
protected ModelAndView onSubmit(HttpServletRequest request, HttpServletResponse response, Object object,
        BindException errors) throws RuntimeException, IOException {
    String soggettarioIDStr = request.getParameter("soggettario_id");
    Integer soggettarioID = null;
    if (soggettarioIDStr != null) {
        soggettarioID = Integer.parseInt(soggettarioIDStr);
    }
    Soggettario soggettario = null;
    if (soggettarioID != null) {
        soggettario = applicationService.get(Soggettario.class, soggettarioID);
    }

    String filename;
    if (soggettario == null) {
        filename = "configurazione-soggettari.xml";
    } else {
        filename = "configurazione-soggettario_" + soggettario.getNome().replaceAll(" ", "_") + ".xml";
    }
    response.setContentType("application/xml");
    response.addHeader("Content-Disposition", "attachment; filename=" + filename);

    PrintWriter writer = response.getWriter();
    writer.print("<?xml version=\"1.0\" encoding=\"UTF-8\"?>\n"
            + "<!DOCTYPE beans PUBLIC \"-//SPRING//DTD BEAN//EN\"\n"
            + "\"http://www.springframework.org/dtd/spring-beans.dtd\">\n\n\n");
    writer.print("<beans>\n");
    writer.print("   <!-- Configurazioni per il tool di import (NON MODIFICARE) -->\n");
    writer.print(
            "      <bean id=\"customEditorConfigurer\" class=\"org.springframework.beans.factory.config.CustomEditorConfigurer\">\n");
    writer.print("         <property name=\"customEditors\">\n");
    writer.print("              <map>\n");
    writer.print("               <entry key=\"it.cilea.osd.jdyna.model.Soggettario\">\n");
    writer.print("                    <ref bean=\"configurazioneSoggettarioEditor\"/>\n");
    writer.print("                </entry>\n");
    writer.print("             </map>\n");
    writer.print("          </property>\n");
    writer.print("       </bean>\n");

    if (soggettario != null) {
        toXML(writer, soggettario);
    } else {
        List<Soggettario> allSoggettari = applicationService.getList(Soggettario.class);
        for (Soggettario soggettarioIter : allSoggettari) {
            toXML(writer, soggettarioIter);
        }
    }
    response.getWriter().print("</beans>");
    return null;
}

From source file:ua.com.manometer.jasperreports.AbstractJasperReportsView.java

/**
 * Populates the headers in the <code>HttpServletResponse</code> with the
 * headers supplied by the user.//ww w .  ja v a2  s .  c om
 */
private void populateHeaders(HttpServletResponse response) {
    // Apply the headers to the response.
    for (Enumeration en = this.headers.propertyNames(); en.hasMoreElements();) {
        String key = (String) en.nextElement();
        response.addHeader(key, this.headers.getProperty(key));
    }
}

From source file:com.mirantis.cachemod.filter.CacheFilter.java

public void writeCacheToResponse(CacheEntry cacheEntry, ServletResponse response, boolean fragment)
        throws IOException {

    if (cacheEntry.getContentType() != null) {
        response.setContentType(cacheEntry.getContentType());
    }/*from  w  w  w . j  a v a 2  s . com*/

    if (!fragment) {

        if (response instanceof HttpServletResponse) {
            HttpServletResponse httpResponse = (HttpServletResponse) response;

            if (cacheEntry.getLastModified() != -1) {
                httpResponse.setDateHeader("Last-Modified", cacheEntry.getLastModified());
            }

            if (cacheEntry.getExpires() != Long.MAX_VALUE) {
                httpResponse.setDateHeader("Expires", cacheEntry.getExpires());
            }

            if (cacheEntry.getMaxAge() != -1) {
                if (cacheEntry.getMaxAge() < 0) { // set max-age based on life time
                    long currentMaxAge = -cacheEntry.getMaxAge() / 1000 - System.currentTimeMillis() / 1000;
                    if (currentMaxAge < 0) {
                        currentMaxAge = 0;
                    }
                    httpResponse.addHeader("Cache-Control", "max-age=" + currentMaxAge);
                } else {
                    httpResponse.addHeader("Cache-Control", "max-age=" + cacheEntry.getMaxAge());
                }
            }

        }
    }

    if (cacheEntry.getLocale() != null) {
        response.setLocale(cacheEntry.getLocale());
    }

    OutputStream out = new BufferedOutputStream(response.getOutputStream());
    response.setContentLength(cacheEntry.getContent().length);
    out.write(cacheEntry.getContent());
    out.flush();
}

From source file:com.monarchapis.driver.authentication.AuthenticatorV1Impl.java

/**
 * Prepares an authentication request and sends it to the Service API.
 * Response headers are added the API response.
 * //www .ja v a  2  s  . co m
 * @param requestWeight
 *            The request weight to count in rate limiting
 * @return the authentication response.
 */
private AuthenticationResponse processAuthentication(BigDecimal requestWeight) {
    ApiRequest apiRequest = ApiRequest.getCurrent();
    HttpServletResponse httpResponse = HttpResponseHolder.getCurrent();

    AuthenticationRequest authRequest = prepareAuthenticationRequest(apiRequest);
    authRequest.setRequestWeight(Optional.of(requestWeight.floatValue()));

    SecurityResource security = serviceApi.getSecurityResource();
    long begin = System.currentTimeMillis();
    AuthenticationResponse authResponse = security.authenticateRequest(authRequest);
    long duration = System.currentTimeMillis() - begin;
    logger.debug("authentication took {}ms", duration);

    if (authResponse.getResponseHeaders() != null) {
        for (HttpHeader header : authResponse.getResponseHeaders()) {
            httpResponse.addHeader(header.getName(), header.getValue());
        }
    }

    return authResponse;
}

From source file:de.betterform.agent.web.resources.ResourceServlet.java

/**
 * set the caching headers for the resource response. Caching can be disabled by adding and init-param
 * of 'caching' with value 'false' to web.xml
 *
 * @param request  the http servlet request
 * @param response the http servlet response
 *//*from   ww w  .ja v  a 2  s  .  c o  m*/
protected void setCaching(HttpServletRequest request, HttpServletResponse response) {
    long now = System.currentTimeMillis();
    if (caching) {
        response.setHeader("Cache-Control", "max-age=3600, public");
        response.setDateHeader("Date", now);
        response.setDateHeader("Expires", now + this.oneYear);
        response.setDateHeader("Last-Modified", this.getLastModifiedValue());
    } else {
        // Set to expire far in the past.
        response.setHeader("Expires", "Sat, 6 May 1995 12:00:00 GMT");
        // Set standard HTTP/1.1 no-cache headers.
        response.setHeader("Cache-Control", "no-store, no-cache, must-revalidate");
        // Set IE extended HTTP/1.1 no-cache headers (use addHeader).
        response.addHeader("Cache-Control", "post-check=0, pre-check=0");
        // Set standard HTTP/1.0 no-cache header.
        response.setHeader("Pragma", "no-cache");
    }
}

From source file:com.hmsinc.epicenter.webapp.data.DownloadService.java

/**
 * @param request/* ww  w  .j a va2s  .co m*/
 * @param response
 * @throws IOException
 */
@Transactional(readOnly = true)
@RequestMapping(value = "/download/cases", method = RequestMethod.POST)
public void downloadCases(final HttpServletRequest request, final HttpServletResponse response)
        throws IOException {

    final AnalysisParametersDTO queryParams = bind(request);
    final AnalysisParameters params = convertParameters(queryParams);
    logger.debug(params.toString());

    SpatialSecurity.checkAggregateOnlyAccess(getPrincipal(), params.getContainer());

    final String filename = new StringBuilder("cases-").append(params.getContainer().getName()).append("-")
            .append(FILE_TIMESTAMP_FORMAT.print(params.getStartDate())).append("-")
            .append(FILE_TIMESTAMP_FORMAT.print(params.getEndDate())).append(".csv").toString();

    response.setContentType(CONTENT_TYPE);
    response.addHeader("cache-control", "must-revalidate");
    response.addHeader("Content-Disposition", "attachment; filename=\"" + filename + "\"");

    final OutputStream stream = response.getOutputStream();
    final CSVPrinter csv = new CSVPrinter(stream);

    final String[] header = new String[] { "Interaction Date", "Age", "Gender", "Zipcode", "Facility",
            "Visit Number", "Reason", "Classifications" };
    csv.println(header);

    // Stream the file to the client by paging thru the database
    long offset = 0;
    final Long size = analysisRepository.getCasesCount(params);

    while (offset <= size) {

        final Collection<? extends Interaction> admits = analysisRepository.getCases(params, offset, PAGE_SIZE);

        for (Interaction a : admits) {

            final StringBuilder clz = new StringBuilder();
            for (Classification cc : a.getClassifications()) {
                if (params.getClassifications() == null || params.getClassifications().size() == 0
                        || params.getClassifications().contains(cc)) {
                    if (clz.length() > 0) {
                        clz.append(", ");
                    }
                    clz.append(cc.getCategory());
                }
            }

            if (params.getClassifications() == null || params.getClassifications().size() == 0
                    || clz.length() > 0) {

                String reason = null;
                if (a instanceof Registration) {
                    reason = ((Registration) a).getReason();
                }

                String visitNumber = null;
                if (a instanceof CodedVisit) {
                    visitNumber = ((CodedVisit) a).getVisitNumber();
                }

                final String[] entry = new String[] { DATE_FORMAT.print(a.getInteractionDate()),
                        ObjectUtils.toString(a.getAgeAtInteraction()),
                        a.getPatientDetail().getGender() == null ? ""
                                : a.getPatientDetail().getGender().getAbbreviation(),
                        ObjectUtils.toString(a.getPatientDetail().getZipcode()),
                        filterFacility(a.getPatient().getFacility()), ObjectUtils.toString(visitNumber),
                        ObjectUtils.toString(reason), ObjectUtils.toString(clz) };

                csv.println(entry);

                // Evict the object from the cache since we're done with it.
                analysisRepository.evict(a);

            }

        }

        stream.flush();

        offset = offset + PAGE_SIZE;
    }

    stream.flush();

}

From source file:edu.stanford.muse.webapp.JSPHelper.java

/**
 * makes the page un$able. warning: must be called before any part of the
 * response body is committed//  www .  ja  v a 2s .c o  m
 */
public static void setPageUncacheable(HttpServletResponse response) {
    // see http://stackoverflow.com/questions/5139785/how-to-prevent-the-result-of-servlets-from-being-cached
    response.setHeader("Cache-Control", "no-store, no-cache, must-revalidate");
    response.setHeader("Pragma", "no-cache");
    response.setHeader("Expires", "-1");

    // Set IE extended HTTP/1.1 no-cache headers (use addHeader).
    response.addHeader("Cache-Control", "post-check=0, pre-check=0");

    // Set standard HTTP/1.0 no-cache header.
    response.setDateHeader("Expires", 0); //prevent caching at the proxy server
}

From source file:airlift.servlet.rest.RestServlet.java

@Override
protected final void doHead(HttpServletRequest _httpServletRequest, HttpServletResponse _httpServletResponse)
        throws ServletException, IOException {
    _httpServletResponse.addHeader("Access-Control-Allow-Origin", "*");
    _httpServletResponse.addHeader("Access-Control-Allow-Headers",
            "Content-Type, Depth, User-Agent, X-File-Size, X-Requested-With, If-Modified-Since, X-File-Name, Cache-Control");
    _httpServletResponse.addHeader("Access-Control-Max-Age", "86400");
    _httpServletResponse.addHeader("Access-Control-Allow-Methods",
            "GET, HEAD, POST, PUT, DELETE, TRACE, OPTIONS");

    super.doHead(_httpServletRequest, _httpServletResponse);
}

From source file:airlift.servlet.rest.RestServlet.java

@Override
protected final void doTrace(HttpServletRequest _httpServletRequest, HttpServletResponse _httpServletResponse)
        throws ServletException, IOException {
    _httpServletResponse.addHeader("Access-Control-Allow-Origin", "*");
    _httpServletResponse.addHeader("Access-Control-Allow-Headers",
            "Content-Type, Depth, User-Agent, X-File-Size, X-Requested-With, If-Modified-Since, X-File-Name, Cache-Control");
    _httpServletResponse.addHeader("Access-Control-Max-Age", "86400");
    _httpServletResponse.addHeader("Access-Control-Allow-Methods",
            "GET, HEAD, POST, PUT, DELETE, TRACE, OPTIONS");

    super.doTrace(_httpServletRequest, _httpServletResponse);
}

From source file:SendXml.java

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

    //get the 'file' parameter
    String fileName = (String) request.getParameter("file");
    if (fileName == null || fileName.equals(""))
        throw new ServletException("Invalid or non-existent file parameter in SendXml servlet.");

    // add the .doc suffix if it doesn't already exist
    if (fileName.indexOf(".xml") == -1)
        fileName = fileName + ".xml";

    String xmlDir = getServletContext().getInitParameter("xml-dir");
    if (xmlDir == null || xmlDir.equals(""))
        throw new ServletException("Invalid or non-existent xmlDir context-param.");

    ServletOutputStream stream = null;/*from  www  .  j  ava2  s . c o m*/
    BufferedInputStream buf = null;
    try {

        stream = response.getOutputStream();
        File xml = new File(xmlDir + "/" + fileName);
        response.setContentType("text/xml");
        response.addHeader("Content-Disposition", "attachment; filename=" + fileName);

        response.setContentLength((int) xml.length());
        FileInputStream input = new FileInputStream(xml);
        buf = new BufferedInputStream(input);
        int readBytes = 0;
        while ((readBytes = buf.read()) != -1)
            stream.write(readBytes);
    } catch (IOException ioe) {
        throw new ServletException(ioe.getMessage());
    } finally {
        if (stream != null)
            stream.close();
        if (buf != null)
            buf.close();
    }
}