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:mx.edu.um.mateo.general.web.BaseController.java

protected void generaReporte(String tipo, List<?> lista, HttpServletResponse response, String nombre,
        String tipoReporte, Long id) throws ReporteException {
    try {//from www . j  av  a  2s. c o  m
        log.debug("Generando reporte {}", tipo);
        byte[] archivo = null;
        switch (tipo) {
        case "PDF":
            archivo = generaPdf(lista, nombre, tipoReporte, id);
            response.setContentType("application/pdf");
            response.addHeader("Content-Disposition", "attachment; filename=" + nombre + ".pdf");
            System.out.println("termina de generar pdf");
            break;
        case "CSV":
            archivo = generaCsv(lista, nombre, tipoReporte, id);
            response.setContentType("text/csv");
            response.addHeader("Content-Disposition", "attachment; filename=" + nombre + ".csv");
            break;
        case "XLS":
            archivo = generaXls(lista, nombre, tipoReporte, id);
            response.setContentType("application/vnd.ms-excel");
            response.addHeader("Content-Disposition", "attachment; filename=" + nombre + ".xls");
        }
        if (archivo != null) {
            response.setContentLength(archivo.length);
            try (BufferedOutputStream bos = new BufferedOutputStream(response.getOutputStream())) {
                bos.write(archivo);
                bos.flush();
            }
        }
    } catch (JRException | IOException e) {
        throw new ReporteException("No se pudo generar el reporte", e);
    }

}

From source file:com.ikon.servlet.admin.ConfigServlet.java

/**
 * Export configuration/* w  w w .  j av a 2 s. c om*/
 */
private void export(String userId, HttpServletRequest request, HttpServletResponse response)
        throws DatabaseException, IOException {
    log.debug("export({}, {}, {})", new Object[] { userId, request, response });

    // Disable browser cache
    response.setHeader("Expires", "Sat, 6 May 1971 12:00:00 GMT");
    response.setHeader("Cache-Control", "max-age=0, must-revalidate");
    response.addHeader("Cache-Control", "post-check=0, pre-check=0");
    String fileName = "ikon_" + WarUtils.getAppVersion().getVersion() + "_cfg.sql";

    response.setHeader("Content-disposition", "inline; filename=\"" + fileName + "\"");
    response.setContentType("text/x-sql; charset=UTF-8");
    PrintWriter out = new PrintWriter(new OutputStreamWriter(response.getOutputStream(), "UTF8"), true);

    for (Config cfg : ConfigDAO.findAll()) {
        if (!Config.HIDDEN.equals(cfg.getType())) {
            out.println("DELETE FROM ikon_CONFIG WHERE CFG_KEY='" + cfg.getKey() + "';");
        }
    }

    for (Config cfg : ConfigDAO.findAll()) {
        if (!Config.HIDDEN.equals(cfg.getType())) {
            StringBuffer insertCfg = new StringBuffer(
                    "INSERT INTO ikon_CONFIG (CFG_KEY, CFG_TYPE, CFG_VALUE) VALUES ('");
            insertCfg.append(cfg.getKey()).append("', '");
            insertCfg.append(cfg.getType()).append("', '");

            if (cfg.getValue() == null || cfg.getValue().equals("null")) {
                insertCfg.append("").append("');");
            } else {
                insertCfg.append(cfg.getValue()).append("');");
            }

            out.println(insertCfg);
        }
    }

    out.flush();
    log.debug("export: void");
}

From source file:org.apache.hadoop.gateway.dispatch.HttpClientDispatch.java

protected void writeOutboundResponse(HttpUriRequest outboundRequest, HttpServletRequest inboundRequest,
        HttpServletResponse outboundResponse, HttpResponse inboundResponse) throws IOException {
    // Copy the client respond header to the server respond.
    outboundResponse.setStatus(inboundResponse.getStatusLine().getStatusCode());
    Header[] headers = inboundResponse.getAllHeaders();
    for (Header header : headers) {
        String name = header.getName();
        if (name.equals(SET_COOKIE) || name.equals(WWW_AUTHENTICATE)) {
            continue;
        }//from  w  ww.j av a2 s  .c  om
        String value = header.getValue();
        outboundResponse.addHeader(name, value);
    }

    HttpEntity entity = inboundResponse.getEntity();
    if (entity != null) {
        Header contentType = entity.getContentType();
        if (contentType != null) {
            outboundResponse.setContentType(contentType.getValue());
        }
        //KM[ If this is set here it ends up setting the content length to the content returned from the server.
        // This length might not match if the the content is rewritten.
        //      long contentLength = entity.getContentLength();
        //      if( contentLength <= Integer.MAX_VALUE ) {
        //        outboundResponse.setContentLength( (int)contentLength );
        //      }
        //]
        writeResponse(inboundRequest, outboundResponse, entity.getContent());
    }
}

From source file:com.vmware.identity.proxyservice.LogonProcessorImpl.java

@Override
public void internalError(Exception error, Locale locale, String tenant, HttpServletRequest request,
        HttpServletResponse response) {
    log.error("Caught internalError in authenticating with external IDP! {}", error.toString());
    Validate.notNull(response, "response");
    try {//from  w w  w.  ja  va 2s.  c  o  m

        int httpErrorCode = HttpServletResponse.SC_INTERNAL_SERVER_ERROR;
        String messageStr = error.getMessage();
        response.addHeader(Shared.RESPONSE_ERROR_HEADER, Shared.encodeString(messageStr));
        response.sendError(httpErrorCode, messageStr);
        log.info("Send client browser error: " + httpErrorCode + ", message: " + messageStr);

    } catch (IOException e) {
        log.error("Caught IOException in sending out response to relying party! {}", e.toString());
    }
}

From source file:com.seajas.search.profiler.controller.DownloadController.java

/**
 * Handle the request.//ww  w.  j  a v  a 2  s  . c o m
 * 
 * @param model
 * @param request
 * @param response
 * @return ModelAndView
 * @throws IOException
 */
@RequestMapping(method = RequestMethod.GET)
public ModelAndView handleRequest(final ModelMap model, final WebRequest request,
        final HttpServletResponse response) throws IOException {
    String documentPath = request.getParameter(PARAM_DOCUMENT);

    if (!StringUtils.isEmpty(documentPath)) {
        RepositoryContent content = repositoryService.getResource(documentPath);

        if (content != null && content.getInputStream() != null) {
            try {
                String filename = documentPath.lastIndexOf("/") != -1
                        ? documentPath.substring(documentPath.lastIndexOf('/') + 1)
                        : documentPath;

                // Add extensions for some common MIME types

                if (content.getMimeType() != null) {
                    response.addHeader("Content-Type", content.getMimeType());

                    if (content.getMimeType().equals("text/html")
                            || content.getMimeType().equals("application/xhtml+xml"))
                        filename += ".html";
                    else if (content.getMimeType().equals("application/pdf"))
                        filename += ".pdf";
                    else if (content.getMimeType().equals("application/msword"))
                        filename += ".doc";
                    else if (content.getMimeType().equals("application/vnd.ms-excel"))
                        filename += ".xls";
                    else if (content.getMimeType().equals("application/vnd.ms-powerpoint"))
                        filename += ".ppt";
                    else if (content.getMimeType()
                            .equals("application/vnd.openxmlformats-officedocument.wordprocessingml.document"))
                        filename += ".docx";
                    else if (content.getMimeType()
                            .equals("application/vnd.openxmlformats-officedocument.spreadsheetml.sheet"))
                        filename += ".xlsx";
                    else if (content.getMimeType().equals(
                            "application/vnd.openxmlformats-officedocument.presentationml.presentation"))
                        filename += ".pptx";
                    else if (content.getMimeType().equals("application/vnd.oasis.opendocument.text"))
                        filename += ".odt";
                    else if (content.getMimeType().equals("application/vnd.oasis.opendocument.spreadsheet"))
                        filename += ".ods";
                    else if (content.getMimeType().equals("application/vnd.oasis.opendocument.presentation"))
                        filename += ".odp";
                }

                // And then add the disposition header

                response.addHeader("Content-Disposition", "attachment; filename=" + filename);

                // Copy the input stream content over to the servlet's output stream

                IOUtils.copy(content.getInputStream(), response.getOutputStream());

            } finally {
                IOUtils.closeQuietly(content.getInputStream());
            }
        } else
            response.getWriter().print("The requested document could not be retrieved for downloading.");
    } else
        response.getWriter().print("No document was specified for downloading.");

    return null;
}

From source file:org.frontcache.FrontCacheEngine.java

private void addResponseHeaders(WebResponse webResponse, RequestContext context) {
    HttpServletResponse servletResponse = context.getResponse();

    servletResponse.setStatus(webResponse.getStatusCode());

    servletResponse.addHeader(FCHeaders.X_FRONTCACHE_ID, fcHostId);
    servletResponse.addHeader(FCHeaders.X_FRONTCACHE_REQUEST_ID, context.getRequestId());

    if (webResponse.getHeaders() != null) {
        for (String name : webResponse.getHeaders().keySet()) {
            for (String value : webResponse.getHeaders().get(name)) {

                if (null == servletResponse.getHeader(name)) // if header already exist (e.g. in case of WebFilter) - do not duplicate
                    servletResponse.addHeader(name, value);
            }//from w w w.j  a  va2 s. com
        }
    }
}

From source file:com.idr.servlets.UploadServlet.java

/**
 * method check the current status of upload and conversion and sending response
 * to the client /* w  w w  .  j a  v  a2 s . c o  m*/
 * @param session
 * @param response
 * @throws Exception 
 */
private void doStatus(HttpServletRequest request, HttpServletResponse response) throws Exception {
    //        System.out.println("Doing Status"+System.currentTimeMillis());
    HttpSession session = request.getSession();
    if (session == null) {
        return;
    }
    // Make sure the status response is not cached by the browser
    response.addHeader("Expires", "0");
    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");

    UploadListener fileUploadStats = null;
    if (session.getAttribute("FILE_UPLOAD_STATS") != null) {
        fileUploadStats = (UploadListener) session.getAttribute("FILE_UPLOAD_STATS");
    }
    if (session.getAttribute("href") == null) {
        if (session.getAttribute("isUploading") != null && session.getAttribute("isUploading").equals("true")
                && fileUploadStats != null) {
            response.getWriter().println("<div class=\"prog-border\"><div class=\"prog-bar\" style=\"width: "
                    + fileUploadStats.getPercent() + "%;\"></div></div>");
            response.getWriter().println("Uploading: " + fileUploadStats.getMessage() + " ("
                    + fileUploadStats.getPercent() + "%) <br/>");
            response.getWriter().println("<div id='currentSt'>uploading</div>");
        } else if (session.getAttribute("isConverting") != null && session.getAttribute("pageCount") != null
                && session.getAttribute("isConverting").equals("true")) {
            int pageCount = (Integer) session.getAttribute("pageCount");
            int pageReached = (Integer) session.getAttribute("pageReached");
            if (pageCount > 0) {
                int percentage = (int) Math.round(100.00 * pageReached / pageCount);
                //                    if (session.getAttribute("fileAlreadyUploaded").equals("true")) {
                //                        response.getWriter().println("<p>File already uploaded</p>");
                //                    }
                response.getWriter().println("<div class=\"convert-border\">"
                        + "<div class=\"convert-bar\" style=\"width: " + percentage + "%;\"></div></div>");
                response.getWriter()
                        .println("Converting " + conversionCount + " of " + totalConversions
                                + " documents.<br/> Converting " + pageReached + " of " + pageCount + " pages ("
                                + percentage + "% complete)<br/>");
                response.getWriter().println("<div id='currentSt'>converting</div>");
            }
        } else if (session.getAttribute("isZipping") != null
                && session.getAttribute("isZipping").equals("true")) {
            response.getWriter().println("Zipping: " + "<img src='img/uploading.gif'/>");
            response.getWriter().println("<div id='currentSt'>zipping</div>");
        }
    } else {
        response.getWriter().println("<end></end>" + session.getAttribute("href") + "<br/>");
        response.getWriter().println("<div id='currentSt'></div>");
        cancelUpload(request, response);
    }
}

From source file:com.silverpeas.servlets.upload.AjaxFileUploadServlet.java

/**
 * Return the current status of the upload.
 *
 * @param session the HttpSession.//  w w  w.  ja  v a2  s .c o m
 * @param response where the status is to be written.
 * @throws IOException
 */
private void doStatus(HttpSession session, HttpServletResponse response) throws IOException {
    boolean isSavingUploadedFiles = isSavingUploadedFile(session);
    Long bytesProcessed = null;
    Long totalSize = null;
    FileUploadListener.FileUploadStats fileUploadStats = (FileUploadListener.FileUploadStats) session
            .getAttribute(FILE_UPLOAD_STATS);
    if (fileUploadStats != null) {
        bytesProcessed = fileUploadStats.getBytesRead();
        totalSize = fileUploadStats.getTotalSize();
    }

    // Make sure the status response is not cached by the browser
    response.addHeader("Expires", "0");
    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");

    String fatalError = (String) session.getAttribute(UPLOAD_FATAL_ERROR);
    if (StringUtil.isDefined(fatalError)) {
        List<String> paths = (List<String>) session.getAttribute(FILE_UPLOAD_PATHS);
        String uploadedFilePaths = getUploadedFilePaths(paths);
        response.getWriter().println("<b>Upload uncomplete.</b>");
        response.getWriter().println("<script type='text/javascript'>window.parent.stop('" + fatalError + "', "
                + uploadedFilePaths + "); stop('" + fatalError + "', " + uploadedFilePaths + ");</script>");
        return;
    }

    if (bytesProcessed != null) {
        long percentComplete = (long) Math
                .floor((bytesProcessed.doubleValue() / totalSize.doubleValue()) * 100.0);
        response.getWriter().println("<b>Upload Status:</b><br/>");

        if (!bytesProcessed.equals(totalSize)) {
            response.getWriter().println("<div class=\"prog-border\"><div class=\"prog-bar\" style=\"width: "
                    + percentComplete + "%;\"></div></div>");
        } else {
            response.getWriter()
                    .println("<div class=\"prog-border\"><div class=\"prog-bar\" style=\"width: 100%;"
                            + "\"></div></div>");

            if (!isSavingUploadedFiles) {
                List<String> paths = (List<String>) session.getAttribute(FILE_UPLOAD_PATHS);
                String uploadedFilePaths = getUploadedFilePaths(paths);
                String errors = (String) session.getAttribute(UPLOAD_ERRORS);
                if (StringUtil.isDefined(errors)) {
                    response.getWriter().println("<b>Upload complete with error(s).</b><br/>");
                } else {
                    response.getWriter().println("<b>Upload complete.</b><br/>");
                    errors = "";
                }
                response.getWriter()
                        .println("<script type='text/javascript'>window.parent.stop('" + errors + "', "
                                + uploadedFilePaths + "); stop('" + errors + "', " + uploadedFilePaths
                                + ");</script>");
            }
        }
    }
}

From source file:io.seldon.api.controller.JsPortholeController.java

/**
 *
 * @param request ...//from  w w  w .j a v  a 2s . com
 * @param response ...
 * @param localId if non-null, use this local id instead of generating a {@link UUID}.
 *                Typically this will be used to propagate client-specific cookies where browser privacy issues have
 *                blocked the server-side setting.
 * @return
 */
private String ensureCookie(HttpServletRequest request, HttpServletResponse response, String localId) {
    final Cookie[] cookies = request.getCookies();
    String uuid = null;
    if (cookies != null) {
        for (Cookie cookie : cookies) {
            if (cookie.getName().equals(RL_COOKIE_ID)) {
                uuid = cookie.getValue();
            }
        }
    }
    if (uuid == null) {
        if (localId != null) {
            logger.info("Using local ID for porthole session: " + localId);
            uuid = localId;
        } else {
            uuid = UUID.randomUUID().toString();
        }
        final Cookie cookie = new Cookie(RL_COOKIE_ID, uuid);
        cookie.setMaxAge(COOKIE_MAX_AGE);
        response.addCookie(cookie);
        response.addHeader("P3P", "CP=\"IDC DSP COR ADM DEVi TAIi PSA PSD IVAi IVDi CONi HIS OUR IND CNT\"");
    }
    return uuid;
}

From source file:httpmultiplexer.httpproxy.ProxyServlet.java

/**
 * Copy proxied response headers back to the servlet client.
 */// w w  w.j  a  v  a 2s  .  com
protected void copyResponseHeaders(HttpResponse proxyResponse, HttpServletResponse servletResponse) {
    for (Header header : proxyResponse.getAllHeaders()) {
        if (hopByHopHeaders.containsHeader(header.getName())) {
            continue;
        }
        servletResponse.addHeader(header.getName(), header.getValue());
    }
}