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:de.u808.simpleinquest.web.download.DownloadController.java

private void handleDownload(HttpServletResponse response, File file) throws IOException {
    response.reset();//w  w  w  .  ja  va2  s .  c  o m
    response.setContentType(mimeTypeRegistry.getMimeType(file));
    response.setHeader("Pragma", "private");
    response.setHeader("Cache-Control", "private, must-revalidate");
    response.setHeader("Content-Disposition", "attachment; filename=\"" + file.getName() + "\"");

    FileInputStream fis = new FileInputStream(file);
    OutputStream os = response.getOutputStream();
    int len = -1;
    int x = 0;
    while ((len = fis.read(buf)) != -1) {
        os.write(buf, 0, len);
    }

    response.getOutputStream().flush();
    response.getOutputStream().close();
}

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

/**
 * Handles the HTTP//from  w  w w .  jav a 2s.  com
 * <code>GET</code> method.
 *
 * @param request servlet request
 * @param response servlet response
 * @throws ServletException if a servlet-specific error occurs
 * @throws IOException if an I/O error occurs
 */
@Override
protected void doGet(HttpServletRequest request, HttpServletResponse response)
        throws ServletException, IOException {
    try {
        response.setHeader("Cache-Control", "no-cache"); // input comes from referrer
        response.setContentType("application/json");
        boolean authenticated = request.isUserInRole("member");

        JSONObject json = new JSONObject();
        Key parent = getAncestor(request);
        if (parent != null) {
            KeyInfo keyInfo = new KeyInfo(entities, events, races, "", parent, authenticated);
            Map<String, Object> m = keyInfo.getMap();
            String clubDiscount = (String) m.get("RaceSeries.ClubDiscount");
            String club = (String) m.get("Club");
            if (Boolean.parseBoolean(clubDiscount) && "HSK".equalsIgnoreCase(club)) {
                m.put("isClubDiscountGranted", true);
            } else {
                m.put("isClubDiscountGranted", false);
            }
            for (Map.Entry<String, Object> e : m.entrySet()) {
                if (e.getValue() instanceof List) {
                    JSONArray a = new JSONArray();
                    json.put(e.getKey(), a);
                    List<String> l = (List<String>) e.getValue();
                    for (String s : l) {
                        a.put(s);
                    }
                } else {
                    if (e.getValue() instanceof char[]) {
                        JSONArray a = new JSONArray();
                        json.put(e.getKey(), a);
                        char[] ar = (char[]) e.getValue();
                        for (char c : ar) {
                            a.put((int) c);
                        }
                    } else {
                        json.put(e.getKey(), e.getValue());
                    }
                }
            }
            json.write(response.getWriter());
        }
    } catch (EntityNotFoundException ex) {
        log(ex.getMessage(), ex);
        response.setStatus(HttpServletResponse.SC_NOT_FOUND);
    } catch (JSONException ex) {
        log(ex.getMessage(), ex);
        throw new ServletException(ex);
    }
}

From source file:cn.leancloud.diamond.server.controller.ConfigController.java

public String getConfig(HttpServletRequest request, HttpServletResponse response, String dataId, String group) {
    response.setHeader("Content-Type", "text/html;charset=UTF-8");
    final String address = getRemortIP(request);
    if (address == null) {
        // ?400//from   ww  w. j  ava2  s . co m
        response.setStatus(HttpServletResponse.SC_BAD_REQUEST);
        return "400";
    }

    if (GlobalCounter.getCounter().decrementAndGet() >= 0) {
        response.setStatus(HttpServletResponse.SC_SERVICE_UNAVAILABLE);
        return "503";
    }

    String md5 = this.configService.getContentMD5(dataId, group);
    if (md5 == null) {
        return "404";
    }

    response.setHeader(Constants.CONTENT_MD5, md5);

    // 304???double-check??
    if (diskService.isModified(dataId, group)) {
        response.setStatus(HttpServletResponse.SC_NOT_MODIFIED);
        return "304";
    }
    String path = configService.getConfigInfoPath(dataId, group);
    // ?
    if (diskService.isModified(dataId, group)) {
        response.setStatus(HttpServletResponse.SC_NOT_MODIFIED);
        return "304";
    }
    // ?
    response.setHeader("Pragma", "no-cache");
    response.setDateHeader("Expires", 0);
    response.setHeader("Cache-Control", "no-cache,no-store");
    return "forward:" + path;
}

From source file:com.mec.Services.JWTService.java

public void addAuthentication(HttpServletResponse res, String username) {
    //System.out.println("TokenAuthenticationService addAuth");
    try {//from w  w  w .j  a v  a2 s  . c o  m
        res.setHeader("Date", DateUtils.formatterTime.format(LocalDateTime.now()));
        Date expires = new Date(System.currentTimeMillis() + EXPIRATIONTIME);
        String token = JWT.create().withSubject(username).withIssuer("MEC").withExpiresAt(expires)
                .sign(algorithm);
        res.addHeader(HEADER_STRING, TOKEN_PREFIX + " " + token);
        res.addHeader("Content-Type", "application/json");
        res.setHeader("Expires", DateUtils.formatterTime.format(DateUtils.asLocalDateTime(expires)));
        try {
            JSONObject json = new JSONObject("{\"token\":\"" + token + "\",\"expires\":\""
                    + DateUtils.formatterTime.format(DateUtils.asLocalDateTime(expires)) + "\"}");
            json.write(res.getWriter());
        } catch (JSONException ex) {
            Logger.getLogger(JWTService.class.getName()).log(Level.SEVERE, null, ex);
        } catch (IOException ex) {
            Logger.getLogger(JWTService.class.getName()).log(Level.SEVERE, null, ex);
        }
    } catch (JWTCreationException exception) {
        System.out.println("JWTCreationException " + exception.toString());
        try {
            JSONObject json = new JSONObject("{\"token\":\"" + exception.toString() + "\"}");
            json.write(res.getWriter());
        } catch (JSONException ex) {
            Logger.getLogger(JWTService.class.getName()).log(Level.SEVERE, null, ex);
        } catch (IOException ex) {
            Logger.getLogger(JWTService.class.getName()).log(Level.SEVERE, null, ex);
        } /*finally{
          throw new JWTCreationException(exception.toString(), exception.getCause());/*finally{
          throw new JWTCreationException(exception.toString(), exception.getCause());
          }*/
    }
}

From source file:com.taobao.diamond.server.controller.ConfigController.java

public String getConfig(HttpServletRequest request, HttpServletResponse response, String dataId, String group) {
    response.setHeader("Content-Type", "text/html;charset=GBK");
    final String address = getRemortIP(request);
    if (address == null) {
        // 400//from   ww  w. j  ava  2 s  .  co m
        response.setStatus(HttpServletResponse.SC_BAD_REQUEST);
        return "400";
    }

    if (GlobalCounter.getCounter().decrementAndGet() >= 0) {
        response.setStatus(HttpServletResponse.SC_SERVICE_UNAVAILABLE);
        return "503";
    }

    String md5 = this.configService.getContentMD5(dataId, group);
    if (md5 == null) {
        return "404";
    }

    response.setHeader(Constants.CONTENT_MD5, md5);

    // 304double-check
    if (diskService.isModified(dataId, group)) {
        response.setStatus(HttpServletResponse.SC_NOT_MODIFIED);
        return "304";
    }
    String path = configService.getConfigInfoPath(dataId, group);
    // 
    if (diskService.isModified(dataId, group)) {
        response.setStatus(HttpServletResponse.SC_NOT_MODIFIED);
        return "304";
    }
    // 
    response.setHeader("Pragma", "no-cache");
    response.setDateHeader("Expires", 0);
    response.setHeader("Cache-Control", "no-cache,no-store");
    return "forward:" + path;
}

From source file:edu.wisc.doit.tcrypt.controller.DownloadController.java

@RequestMapping("/download")
public void downloadKey(@RequestParam("serviceName") String serviceName,
        @RequestParam("keyType") String keyType, HttpServletRequest request, HttpServletResponse response)
        throws Exception {
    try {// w  w  w  .  j  a  va 2  s. c  o  m
        KeyPair sk = (KeyPair) request.getSession().getAttribute("serviceKey_" + serviceName);

        response.setContentType("application/x-pem-file");
        response.setHeader("Content-Disposition",
                "attachment; filename=\"" + keyType + "-" + serviceName + ".pem" + "\"");

        Key key = "private".equalsIgnoreCase(keyType) ? sk.getPrivate() : sk.getPublic();

        try (final PEMWriter pemWriter = new PEMWriter(new PrintWriter(response.getOutputStream()))) {
            pemWriter.writeObject(key);
        }
    } catch (Exception e) {
        logger.error("Issue downloading the key " + keyType, e);
        throw new Exception(e);
    }
}

From source file:technology.tikal.ventas.service.pedido.PartidaService.java

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

From source file:com.sap.dirigible.runtime.registry.RegistryServlet.java

private void setContentLengthHeader(IEntity entity, int contentLength, HttpServletRequest request,
        HttpServletResponse response) throws IOException {
    response.setHeader(CONTENT_LENGTH_HEADER, Integer.toString(contentLength));
}

From source file:cz.zcu.kiv.eegdatabase.logic.controller.nif.NIFMultiController.java

/**
 * Generates a csv file from scenarios/*from  ww  w.j a va2 s  .c o  m*/
 * @param request
 * @param response
 * @return
 * @throws Exception
 */
public ModelAndView getScenariosCSVFile(HttpServletRequest request, HttpServletResponse response)
        throws Exception {
    log.debug("Controller for creating csv file for NIF");
    OutputStream out = null;
    int headerBufferSize = 8096;

    response.setHeader("Content-Type", "text/csv");
    response.setContentType("text/csv");
    response.setHeader("Content-Disposition", "attachment;filename=EEGbase_scenarios.csv");

    log.debug("Creating output stream");
    response.setStatus(HttpServletResponse.SC_OK);
    response.setBufferSize(headerBufferSize);

    log.debug("Generating csv");
    out = csvFactory.generateScenariosCsvFile();
    ByteArrayOutputStream bout = (ByteArrayOutputStream) out;
    response.getOutputStream().write(bout.toByteArray());
    return null;
}

From source file:com.ddubyat.develop.jhawtcode.web.InternalResourceController.java

/**
 * Controller method to deliver application CSS
 *
 * @param response The http response object from a spring controller
 * @throws IOException if the css content is inaccessible
 *///  w  ww. j a v  a2 s  .  co  m
@RequestMapping(value = "/jhawtcode/jhc.css", method = { RequestMethod.GET })
public void requestCSS(HttpServletResponse response) throws IOException {
    log.debug("Creating application CSS");

    response.setHeader("Server", "jhawtconsole");
    response.setContentType("text/css");
    response.setHeader("Cache-Control", "no-cache,no-store,must-revalidate");
    response.setHeader("Pragma", "no-cache");
    response.setDateHeader("Expires", -1);

    if (!propertyUtil.canHawtTheCode()) {
        log.trace("Not delivering CSS, application not enabled");
    }

    String heightOriginal = "height: 200px;";
    String heightOverride = heightOriginal;
    String sysHeightProp = System.getProperty("jhawtcode.console.height");
    if (sysHeightProp != null && StringUtil.isNotEmpty(sysHeightProp) && isNumeric(sysHeightProp)) {
        heightOverride = heightOriginal.replaceAll("200", sysHeightProp);
        log.debug("Overriding console height to {}", heightOverride);
    }

    try {
        log.debug("Attempting to return CSS");
        response.getWriter().write(resourceUtil.readLocalResource("classpath:/css/jhawtcode.css")
                .replaceAll(heightOriginal, heightOverride));
    } catch (IOException ioe) {
        log.debug("Unable to create CSS", ioe);
    }
}