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.megacasting_ppe.web.ServletLoadOffreView.java

/**
 * Processes requests for both HTTP <code>GET</code> and <code>POST</code>
 * methods.//w  ww  . jav  a  2 s  . 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.setContentType("application/json");
    response.setHeader("Cache-Control", "no-cache");
    HttpSession session = request.getSession();

    JSONObject global = (JSONObject) session.getAttribute("offres_lib");

    Candidat candidat = (Candidat) session.getAttribute("CandidatObject");
    String connecterOk = (String) session.getAttribute("Connecter");

    if (candidat != null && connecterOk != null) {

        JSONObject infoAuth = new JSONObject();

        infoAuth.put("Nom", candidat.getNom());
        infoAuth.put("Prenom", candidat.getPrenom());
        infoAuth.put("connecter", connecterOk);

        global.put("infoauth", infoAuth);

    } else {

        JSONObject infoAuth = new JSONObject();
        infoAuth.put("connecter", "false");

        global.put("infoauth", infoAuth);
    }

    try (PrintWriter out = response.getWriter()) {
        out.println(global.toString());
    }

}

From source file:it.eng.spagobi.kpi.service.KpiXmlExporterAction.java

/**
 * This action is called by the user who wants to export the result of a Kpi in XML
 * // ww w  . ja v  a 2  s  .c om
 */

public void service(SourceBean serviceRequest, SourceBean serviceResponse) throws Exception {

    File tmpFile = null;
    logger.debug("IN");
    HttpServletRequest httpRequest = getHttpRequest();
    HttpSession session = httpRequest.getSession();

    this.freezeHttpResponse();

    try {
        // get KPI result
        List<KpiResourceBlock> listKpiBlocks = (List<KpiResourceBlock>) session.getAttribute("KPI_BLOCK");
        String title = (String) session.getAttribute("TITLE");
        String subtitle = (String) session.getAttribute("SUBTITLE");
        if (title == null)
            title = "";
        if (subtitle == null)
            subtitle = "";

        // recover BiObject Name
        Object idObject = serviceRequest.getAttribute(SpagoBIConstants.OBJECT_ID);
        if (idObject == null) {
            logger.error("Document id not found");
            return;
        }

        Integer id = Integer.valueOf(idObject.toString());
        BIObject document = DAOFactory.getBIObjectDAO().loadBIObjectById(id);
        String docName = document.getName();

        //Recover user Id
        HashedMap parameters = new HashedMap();
        String userId = null;
        Object userIdO = serviceRequest.getAttribute("user_id");
        if (userIdO != null)
            userId = userIdO.toString();

        it.eng.spagobi.engines.exporters.KpiExporter exporter = new KpiExporter();
        tmpFile = exporter.getKpiExportXML(listKpiBlocks, document, userId);

        String outputType = "XML";

        String mimeType = "text/xml";

        logger.debug("Report exported succesfully");

        HttpServletResponse response = getHttpResponse();
        response.setContentType(mimeType);
        response.setHeader("Content-Disposition", "filename=\"report." + outputType + "\";");
        response.setContentLength((int) tmpFile.length());

        BufferedInputStream in = new BufferedInputStream(new FileInputStream(tmpFile));
        int b = -1;
        while ((b = in.read()) != -1) {
            response.getOutputStream().write(b);
        }
        response.getOutputStream().flush();
        in.close();
        logger.debug("OUT");

    } catch (Throwable e) {
        logger.error("An exception has occured", e);
        throw new Exception(e);
    } finally {

        tmpFile.delete();

    }
}

From source file:org.vbossica.springbox.metrics.HealthCheckController.java

@RequestMapping(value = "/metrics/healthcheck", method = RequestMethod.GET)
public void process(
        @RequestParam(value = "pretty", required = false, defaultValue = "true") boolean prettyPrint,
        HttpServletResponse resp) throws IOException {
    SortedMap<String, HealthCheck.Result> results = registry.runHealthChecks();
    resp.setContentType("application/json");
    resp.setHeader("Cache-Control", "must-revalidate,no-cache,no-store");
    if (results.isEmpty()) {
        resp.setStatus(SC_NOT_IMPLEMENTED);
    } else {//ww w . j a v a2  s . co m
        resp.setStatus(isAllHealthy(results) ? SC_OK : SC_INTERNAL_SERVER_ERROR);
    }

    OutputStream output = resp.getOutputStream();
    try {
        (prettyPrint ? mapper.writerWithDefaultPrettyPrinter() : mapper.writer()).writeValue(output, results);
    } finally {
        output.close();
    }
}

From source file:com.ecyrd.jspwiki.dav.WikiDavServlet.java

@Override
protected void doOptions(HttpServletRequest req, HttpServletResponse res) {
    log.debug("DAV doOptions for path " + req.getPathInfo());

    res.setHeader("DAV", "1"); // We support only Class 1
    res.setHeader("Allow", "GET, PUT, POST, OPTIONS, PROPFIND, PROPPATCH, MOVE, COPY, DELETE");
    res.setStatus(HttpServletResponse.SC_OK);
}

From source file:com.googlesource.gerrit.plugins.gitblit.auth.GerritAuthenticationFilter.java

public boolean filterBasicAuth(HttpServletRequest request, HttpServletResponse response, String hdr)
        throws IOException, UnsupportedEncodingException {
    if (!hdr.startsWith(LIT_BASIC)) {
        response.setHeader("WWW-Authenticate", "Basic realm=\"Gerrit Code Review\"");
        response.sendError(SC_UNAUTHORIZED);
        return false;
    }//www.  ja va 2  s  . c  o m

    final byte[] decoded = new Base64().decode(hdr.substring(LIT_BASIC.length()).getBytes());
    String encoding = request.getCharacterEncoding();
    if (encoding == null) {
        encoding = "UTF-8";
    }
    String usernamePassword = new String(decoded, encoding);
    int splitPos = usernamePassword.indexOf(':');
    if (splitPos < 1) {
        response.setHeader("WWW-Authenticate", "Basic realm=\"Gerrit Code Review\"");
        response.sendError(SC_UNAUTHORIZED);
        return false;
    }
    request.setAttribute("gerrit-username", usernamePassword.substring(0, splitPos));
    request.setAttribute("gerrit-password", usernamePassword.substring(splitPos + 1));

    return true;
}

From source file:edu.mayo.cts2.framework.plugin.service.lexevs.bulk.AbstractBulkDownloadController.java

/**
 * Sets the headers.//from   w  w w. ja  va 2s  . c  o m
 *
 * @param response the response
 * @param filename the filename
 */
protected void setHeaders(HttpServletResponse response, String filename) {
    String headerKey = "Content-Disposition";
    String headerValue = String.format("attachment; filename=\"%s\"", filename);
    response.setHeader(headerKey, headerValue);
    response.setContentType("text/plain; charset=utf-8");
}

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

@Override
public void export(AmendmentContainerDTO object, HttpServletResponse response) throws IOException {

    response.setContentType("application/vnd.openxmlformats-officedocument.wordprocessingml.document");
    response.setHeader("Content-Disposition",
            "attachment;filename=" + object.getAmendmentContainerID() + ".docx");
    response.setCharacterEncoding("UTF8");

    final String content = object.getBody();
    final InputSource inputSource;
    inputSource = new InputSource(new StringReader(content));

    try {/*from  w w  w  . j a  va 2  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);
        byte[] bytes = sw.toString().getBytes("utf-8");
        IOUtils.copy(new ByteArrayInputStream(bytes), 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);
    }
}

From source file:technology.tikal.ventas.service.pedimento.PedimentoBatchService.java

@RequestMapping(method = RequestMethod.POST)
@ResponseStatus(HttpStatus.CREATED)//from  w  w  w . j  av  a  2 s  .  c  o  m
public void crear(@PathVariable final Long pedidoId, @Valid @RequestBody final Pedimento request,
        final BindingResult result, final HttpServletRequest httpRequest,
        final HttpServletResponse httpResponse) {
    if (result.hasErrors()) {
        throw new NotValidException(result);
    }
    Pedimento nuevo = pedimentoController.crear(pedidoId, request);
    httpResponse.setHeader("Location", httpRequest.getRequestURI() + "/" + nuevo.getId());
}

From source file:be.fedict.eid.applet.service.PhotoServlet.java

@Override
protected void doGet(HttpServletRequest request, HttpServletResponse response)
        throws ServletException, IOException {
    LOG.debug("doGet");
    response.setContentType("image/jpg");
    response.setHeader("Cache-Control", "no-cache, no-store, must-revalidate, max-age=-1"); // http 1.1
    response.setHeader("Pragma", "no-cache, no-store"); // http 1.0
    response.setDateHeader("Expires", -1);
    ServletOutputStream out = response.getOutputStream();
    HttpSession session = request.getSession();
    byte[] photoData = (byte[]) session.getAttribute(IdentityDataMessageHandler.PHOTO_SESSION_ATTRIBUTE);
    if (null != photoData) {
        BufferedImage photo = ImageIO.read(new ByteArrayInputStream(photoData));
        if (null == photo) {
            /*//from w ww . ja  v a  2s.  c  o m
             * In this case we render a photo containing some error message.
             */
            photo = new BufferedImage(140, 200, BufferedImage.TYPE_INT_RGB);
            Graphics2D graphics = (Graphics2D) photo.getGraphics();
            RenderingHints renderingHints = new RenderingHints(RenderingHints.KEY_TEXT_ANTIALIASING,
                    RenderingHints.VALUE_TEXT_ANTIALIAS_ON);
            graphics.setRenderingHints(renderingHints);
            graphics.setColor(Color.WHITE);
            graphics.fillRect(1, 1, 140 - 1 - 1, 200 - 1 - 1);
            graphics.setColor(Color.RED);
            graphics.setFont(new Font("Dialog", Font.BOLD, 20));
            graphics.drawString("Photo Error", 0, 200 / 2);
            graphics.dispose();
            ImageIO.write(photo, "jpg", out);
        } else {
            out.write(photoData);
        }
    }
    out.close();
}

From source file:com.googlesource.gerrit.plugins.gitblit.auth.GerritAuthFilter.java

public boolean filterBasicAuth(HttpServletRequest request, HttpServletResponse response, String hdr)
        throws IOException, UnsupportedEncodingException {
    if (!hdr.startsWith(LIT_BASIC)) {
        response.setHeader("WWW-Authenticate", "Basic realm=\"Gerrit Code Review\"");
        response.sendError(SC_UNAUTHORIZED);
        return false;
    }//from  www  .j a  v  a 2s  .co m

    final byte[] decoded = new Base64().decode(hdr.substring(LIT_BASIC.length()).getBytes());
    String usernamePassword = new String(decoded,
            Objects.firstNonNull(request.getCharacterEncoding(), "UTF-8"));
    int splitPos = usernamePassword.indexOf(':');
    if (splitPos < 1) {
        response.setHeader("WWW-Authenticate", "Basic realm=\"Gerrit Code Review\"");
        response.sendError(SC_UNAUTHORIZED);
        return false;
    }
    request.setAttribute("gerrit-username", usernamePassword.substring(0, splitPos));
    request.setAttribute("gerrit-password", usernamePassword.substring(splitPos + 1));

    return true;
}