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.rh.web.DependienteController.java

private void generaReporte(String tipo, List<Dependiente> dependientes, HttpServletResponse response)
        throws JRException, IOException {
    log.debug("Generando reporte {}", tipo);
    byte[] archivo = null;
    switch (tipo) {
    case "PDF":
        archivo = generaPdf(dependientes);
        response.setContentType("application/pdf");
        response.addHeader("Content-Disposition", "attachment; filename=Dependientes.pdf");
        break;/*from ww w  .  ja va  2  s  .  c  o m*/
    case "CSV":
        archivo = generaCsv(dependientes);
        response.setContentType("text/csv");
        response.addHeader("Content-Disposition", "attachment; filename=Dependientes.csv");
        break;
    case "XLS":
        archivo = generaXls(dependientes);
        response.setContentType("application/vnd.ms-excel");
        response.addHeader("Content-Disposition", "attachment; filename=Dependientes.xls");
    }
    if (archivo != null) {
        response.setContentLength(archivo.length);
        try (BufferedOutputStream bos = new BufferedOutputStream(response.getOutputStream())) {
            bos.write(archivo);
            bos.flush();
        }
    }

}

From source file:gov.nih.nci.ncicb.cadsr.ocbrowser.struts.actions.ObjectClassAction.java

/**
 *
 *
 * @param mapping The ActionMapping used to select this instance.
 * @param form The optional ActionForm bean for this request.
 * @param request The HTTP Request we are processing.
 * @param response The HTTP Response we are processing.
 *
 * @return//from  ww  w  .  j  a  va2 s  . co m
 *
 * @throws IOException
 * @throws ServletException
 */
public ActionForward viewReferenceDocAttchment(ActionMapping mapping, ActionForm form,
        HttpServletRequest request, HttpServletResponse response) throws IOException, ServletException {

    OutputStream out = null;

    InputStream is = null;
    out = response.getOutputStream();
    String attachmentName = request.getParameter(CaDSRConstants.REFERENCE_DOC_ATTACHMENT_NAME);
    response.addHeader("Content-Disposition", "inline;filename=" + attachmentName);
    response.addHeader("Pragma", "cache");
    response.addHeader("Cache-Control", "private");
    response.addHeader("Expires", "0");

    // first find out if the attachment is new and saved in the session

    Map attMap = (Map) getSessionObject(request, CaDSRConstants.REFDOC_ATTACHMENT_MAP);
    Attachment attachment = getAttachmentFromSession(attMap, attachmentName);

    if (attachment != null) {
        FormFile attFile = (FormFile) attMap.get(attachment);

        is = attFile.getInputStream();
        response.setContentType(attachment.getMimeType());
    } else {
        Blob theBlob = null;

        Connection conn = null;
        ResultSet rs = null;
        PreparedStatement ps = null;
        try {
            DBUtil dbUtil = new DBUtil();

            //String dsName = CDEBrowserParams.getInstance("cdebrowser").getSbrDSN();
            dbUtil.getOracleConnectionFromContainer();

            String sqlStmt = "SELECT blob_content, mime_type, doc_size from reference_blobs where name = ?";
            log.info(sqlStmt);
            conn = dbUtil.getConnection();
            ps = conn.prepareStatement(sqlStmt);
            ps.setString(1, attachmentName);
            rs = ps.executeQuery();
            boolean exists = false;

            if (rs.next()) {
                exists = true;

                String mimeType = rs.getString(2);
                //    (mimeType);

                response.setContentType(mimeType);
                //theBlob = ((OracleResultSet)rs).getBLOB(1);
                theBlob = rs.getBlob(1);
                is = theBlob.getBinaryStream();
                response.setContentLength(rs.getInt(3));
                response.setBufferSize(4 * 1024);

                //Writing to the OutputStream
                if (is != null) {
                    byte[] buf = new byte[4 * 1024]; // 4K buffer

                    int bytesRead;

                    while ((bytesRead = is.read(buf)) != -1) {
                        out.write(buf, 0, bytesRead);
                    }
                }
                response.setStatus(HttpServletResponse.SC_OK);
            }
        } catch (Exception ex) {
            log.error("Exception Caught in ObjectClassAction.viewReferenceDocAttchment:", ex);
        } finally {
            try {
                if (is != null)
                    is.close();

                if (out != null)
                    out.close();

                try {
                    if (ps != null)
                        ps.close();
                } catch (Exception e) {
                }
                try {
                    if (rs != null)
                        rs.close();
                } catch (Exception e) {
                }
                try {
                    if (conn != null)
                        conn.close();
                } catch (Exception e) {
                }
                //if (db != null) db.closeDB();
            } catch (Exception ex) {
                log.error("Exception Caught in ObjectClassAction during cleaning up :", ex);
            }
        }
    }
    return null;
}

From source file:io.wcm.caravan.commons.cors.impl.CorsServletFilter.java

@Override
public void doFilter(ServletRequest servletRequest, ServletResponse servletResponse, FilterChain chain)
        throws IOException, ServletException {
    if (!enabled) {
        chain.doFilter(servletRequest, servletResponse);
        return;/*w w  w.j  a  va 2  s.c  om*/
    }

    HttpServletRequest request = (HttpServletRequest) servletRequest;
    HttpServletResponse response = (HttpServletResponse) servletResponse;

    String origin = request.getHeader(HttpHeader.ORIGIN);
    if (StringUtils.isNotEmpty(origin)) {
        if (allowAllHosts) {
            response.setHeader(HttpHeader.ACCESS_CONTROL_ALLOW_ORIGIN, "*");
        } else if ((hostWhitelist.isEmpty() || hostWhitelist.contains(origin))
                && (hostBlacklist.isEmpty() || !hostBlacklist.contains(origin))) {
            response.setHeader(HttpHeader.ACCESS_CONTROL_ALLOW_ORIGIN, origin);
            response.addHeader(HttpHeader.VARY, HttpHeader.ORIGIN);
        }
    }

    chain.doFilter(request, response);
}

From source file:net.sf.j2ep.responsehandlers.ResponseHandlerBase.java

/**
 * Will write all response headers received in the method to the response.
 * One header, connection, is however omitted since we will only want the 
 * client to keep his connection to the proxy not to the backing server.
 * /*w  w  w.  j a v  a2  s  .c  om*/
 * @param response The response that will have headers written to it
 */
protected void setHeaders(HttpServletResponse response) {
    Header[] headers = method.getResponseHeaders();

    for (int i = 0; i < headers.length; i++) {
        Header header = headers[i];
        String name = header.getName();
        boolean contentLength = name.equalsIgnoreCase("content-length");
        boolean connection = name.equalsIgnoreCase("connection");
        boolean transferEncoding = name.equalsIgnoreCase("transfer-encoding");
        if (!contentLength && !connection && !transferEncoding) {

            response.addHeader(name, header.getValue());

        }
    }

    setViaHeader(response);
}

From source file:net.shopxx.interceptor.TokenInterceptor.java

@Override
public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler)
        throws Exception {
    String token = WebUtils.getCookie(request, TOKEN_COOKIE_NAME);
    if (StringUtils.equalsIgnoreCase(request.getMethod(), "POST")) {
        if (StringUtils.isNotEmpty(token)) {
            String requestType = request.getHeader("X-Requested-With");
            if (StringUtils.equalsIgnoreCase(requestType, "XMLHttpRequest")) {
                if (StringUtils.equals(token, request.getHeader(TOKEN_PARAMETER_NAME))) {
                    return true;
                } else {
                    response.addHeader("tokenStatus", "accessDenied");
                }/*from  w w w  . j  av  a  2s . com*/
            } else {
                if (StringUtils.equals(token, request.getParameter(TOKEN_PARAMETER_NAME))) {
                    return true;
                }
            }
        } else {
            WebUtils.addCookie(request, response, TOKEN_COOKIE_NAME,
                    DigestUtils.md5Hex(UUID.randomUUID() + RandomStringUtils.randomAlphabetic(30)));
        }
        response.sendError(HttpServletResponse.SC_FORBIDDEN, ERROR_MESSAGE);
        return false;
    } else {
        if (StringUtils.isEmpty(token)) {
            token = DigestUtils.md5Hex(UUID.randomUUID() + RandomStringUtils.randomAlphabetic(30));
            WebUtils.addCookie(request, response, TOKEN_COOKIE_NAME, token);
        }
        request.setAttribute(TOKEN_ATTRIBUTE_NAME, token);
        return true;
    }
}

From source file:com.edgenius.wiki.webapp.action.BaseAction.java

/**
 * @param dFile//  w w w .  ja va2s  . c  om
 */
protected void downloadFile(String name, File dFile) {
    HttpServletResponse response = getResponse();
    response.setContentType("application/octet-stream");
    response.setHeader("Content-Disposition", "attachment;filename=\"" + name + "\"");
    response.setHeader("Cache-control", "must-revalidate");
    response.addHeader("Content-Description", name);

    InputStream in = null;
    try {
        in = new BufferedInputStream(new FileInputStream(dFile));
        OutputStream out = response.getOutputStream();
        int count = 0;

        int len = 0;
        byte[] ch = new byte[10240];
        while ((len = in.read(ch)) != -1) {
            out.write(ch, 0, len);
            count += len;
        }
        response.setContentLength(count);
    } catch (IOException e) {
        log.error("Exception occured writing out file:" + name, e);
    } finally {
        try {
            if (in != null)
                in.close(); // very important
        } catch (IOException e) {
            log.error("Error Closing file. File already written out - no exception being thrown.", e);
        }
    }
}

From source file:it.cilea.osd.jdyna.web.controller.ExportConfigurazioneAnagrafica.java

/**
 * Esporta la configurazione anagrafica corrente di un oggetto in un file
 * xml//from   w w w.ja v  a2  s .com
 * 
 */
@Override
protected ModelAndView onSubmit(HttpServletRequest request, HttpServletResponse response, Object object,
        BindException errors) throws RuntimeException, IOException {
    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=\"" + tpClass.getCanonicalName() + "\">\n");
    writer.print("                    <ref bean=\"configurazione" + tpClass.getSimpleName() + "Editor\"/>\n");
    writer.print("                </entry>\n");
    writer.print("               <entry key=\"it.cilea.osd.jdyna.model.Soggettario\">\n");
    writer.print("                    <ref bean=\"configurazioneSoggettarioEditor\"/>\n");
    writer.print("                </entry>\n");
    writer.print("               <entry key=\"it.cilea.osd.jdyna.model.AlberoClassificatorio\">\n");
    writer.print("                    <ref bean=\"configurazioneAlberoClassificatorioEditor\"/>\n");
    writer.print("                </entry>\n");
    writer.print("             </map>\n");
    writer.print("          </property>\n");
    writer.print("       </bean>\n");

    // Tipologie di proprieta'
    List<TP> allTP = applicationService.getList(tpClass);
    for (TP tp : allTP) {

        toXML(writer, tp);

    }

    // Aree
    Class<H> areaClass = boxClass;
    List<H> allAree = applicationService.getList(areaClass);
    for (H area : allAree) {
        toXML(writer, area);
    }

    // Tipologia di oggetto
    if (typeClass != null) {
        List<TY> allType = applicationService.getList(typeClass);
        for (TY type : allType) {
            toXML(writer, type);
        }
    }

    response.getWriter().print("</beans>");
    return null;
}

From source file:com.ctb.prism.report.api.CustomViewerServlet.java

/**
 *
 *///from  w  w  w  .  j ava  2s.c  o m
public void service(HttpServletRequest request, HttpServletResponse response)
        throws IOException, ServletException {
    response.setContentType("text/html; charset=UTF-8");

    // 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");

    PrintWriter out = response.getWriter();

    WebReportContext webReportContext = WebReportContext.getInstance(request);

    try {
        render(request, webReportContext, out);
    } catch (Exception e) {
        log.error("Error on report execution", e);

        out.println("<html>");//FIXMEJIVE do we need to render this? or should this be done by the viewer?
        out.println("<head>");
        out.println("<title>JasperReports - Web Application Sample</title>");
        out.println("<link rel=\"stylesheet\" type=\"text/css\" href=\"../stylesheet.css\" title=\"Style\">");
        out.println("</head>");

        out.println("<body bgcolor=\"white\">");

        out.println("<span class=\"bnew\">JasperReports encountered this error :</span>");
        out.println("<pre>");

        e.printStackTrace(out);

        out.println("</pre>");

        out.println("</body>");
        out.println("</html>");
    }

}

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

/**
 * Export mime types//from  ww  w.  j  a  v a 2  s .  c o m
 */
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() + "_MimeTypes.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);
    out.println("DELETE FROM ikon_MIME_TYPE;");
    out.println("DELETE FROM ikon_MIME_TYPE_EXTENSION;");

    for (MimeType mimeType : MimeTypeDAO.findAll("mt.id")) {
        StringBuffer insertMime = new StringBuffer(
                "INSERT INTO ikon_MIME_TYPE (MT_ID, MT_NAME, MT_IMAGE_CONTENT, MT_IMAGE_MIME) VALUES (");
        insertMime.append(mimeType.getId()).append(", '");
        insertMime.append(mimeType.getName()).append("', '");
        insertMime.append(mimeType.getImageContent()).append("', '");
        insertMime.append(mimeType.getImageMime()).append("');");
        out.println(insertMime);

        for (String ext : mimeType.getExtensions()) {
            StringBuffer insertExtension = new StringBuffer(
                    "INSERT INTO ikon_MIME_TYPE_EXTENSION (MTE_ID, MTE_NAME) VALUES (");
            insertExtension.append(mimeType.getId()).append(", '");
            insertExtension.append(ext).append("');");
            out.println(insertExtension);
        }
    }
    out.flush();
    log.debug("export: sql-file");
}

From source file:mx.edu.um.mateo.rh.web.ClaveEmpleadoController.java

private void generaReporte(String tipo, List<ClaveEmpleado> claveEmpleados, HttpServletResponse response)
        throws JRException, IOException {
    log.debug("Generando reporte {}", tipo);
    byte[] archivo = null;
    switch (tipo) {
    case "PDF":
        archivo = generaPdf(claveEmpleados);
        response.setContentType("application/pdf");
        response.addHeader("Content-Disposition", "attachment; filename=clavesEmpleado.pdf");
        break;/*from w  ww  .  j a v  a2s .c o  m*/
    case "CSV":
        archivo = generaCsv(claveEmpleados);
        response.setContentType("text/csv");
        response.addHeader("Content-Disposition", "attachment; filename=clavesEmpleado.csv");
        break;
    case "XLS":
        archivo = generaXls(claveEmpleados);
        response.setContentType("application/vnd.ms-excel");
        response.addHeader("Content-Disposition", "attachment; filename=clavesEmpleado.xls");
    }
    if (archivo != null) {
        response.setContentLength(archivo.length);
        try (BufferedOutputStream bos = new BufferedOutputStream(response.getOutputStream())) {
            bos.write(archivo);
            bos.flush();
        }
    }

}