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:cz.zcu.kiv.eegdatabase.webservices.rest.datafile.DataFileServiceController.java

/**
 * Creates new DataFile under specified experiment.
 * In response is hidden url for file download.
 *
 * @param experimentId experiment identifier
 * @param description  data file description
 * @param file         data file multipart
 * @throws RestServiceException error while creating record
 *//*from  w  w  w.ja  v a2  s. co  m*/
@RequestMapping(method = RequestMethod.POST)
@ResponseStatus(HttpStatus.CREATED)
public void create(HttpServletRequest request, HttpServletResponse response,
        @RequestParam("experimentId") int experimentId, @RequestParam("description") String description,
        @RequestParam("file") MultipartFile file) throws RestServiceException {
    try {
        int pk = dataFileService.create(experimentId, description, file);
        response.addHeader("Location", buildLocation(request, pk));
        log.debug("File upload detected: " + file.getName());
    } catch (IOException e) {
        log.error("File upload failed: " + file.getName());
        throw new RestServiceException(e);
    }
}

From source file:com.rest4j.impl.ApiResponseImpl.java

@Override
public void outputBody(HttpServletResponse response) throws IOException {
    if (statusMessage == null)
        response.setStatus(status);/*from   w w  w  .  j  a v  a  2  s.c  o m*/
    else
        response.setStatus(status, statusMessage);
    headers.outputHeaders(response);
    if (this.response == null)
        return;
    response.addHeader("Content-type", this.response.getContentType());
    if (addEtag) {
        String etag = this.response.getETag();
        if (etag != null)
            response.addHeader("ETag", etag);
    }

    OutputStream outputStream;
    byte[] resourceBytes = ((JSONResource) this.response).getJSONObject().toString().getBytes();
    int contentLength = resourceBytes.length;
    if (compress) {
        response.addHeader("Content-encoding", "gzip");
        ByteArrayOutputStream outputByteStream = new ByteArrayOutputStream();
        GZIPOutputStream gzipOutputStream = new GZIPOutputStream(outputByteStream);
        gzipOutputStream.write(resourceBytes);
        gzipOutputStream.finish(); //     ??!
        contentLength = outputByteStream.toByteArray().length;
        gzipOutputStream.close();
        outputByteStream.close();

        outputStream = new GZIPOutputStream(response.getOutputStream());
    } else {
        outputStream = response.getOutputStream();
    }
    response.addHeader("Content-Length", String.valueOf(contentLength));

    if (this.response instanceof JSONResource) {
        ((JSONResource) this.response).setPrettify(prettify);
    }
    if (callbackFunctionName == null) {
        this.response.write(outputStream);
    } else {
        this.response.writeJSONP(outputStream, callbackFunctionName);
    }
    outputStream.close();
}

From source file:cn.shengyuan.yun.admin.system.controller.CommonController.java

@RequestMapping(value = "/captchaImage", method = RequestMethod.GET)
public String captchaImage(HttpServletRequest request, HttpServletResponse response) throws Exception {

    response.setDateHeader("Expires", 0);
    // 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");
    // return a jpeg
    response.setContentType("image/jpeg");
    // create the text for the image
    String capText = captchaProducer.createText();
    // store the text in the session
    request.getSession().setAttribute(Constants.KAPTCHA_SESSION_KEY, capText);
    // create the image with the text
    BufferedImage bi = captchaProducer.createImage(capText);
    ServletOutputStream out = response.getOutputStream();
    // write the data out
    ImageIO.write(bi, "jpg", out);
    try {//from  w w  w  .j  a  v a 2s  .co  m
        out.flush();
    } finally {
        out.close();
    }
    return null;

}

From source file:com.gsr.myschool.server.reporting.excel.ExcelController.java

@RequestMapping(method = RequestMethod.GET, value = "/excel", produces = "application/vnd.ms-excel")
@ResponseStatus(HttpStatus.OK)//from   w  w w.java2s. c om
public void generateExcel(@RequestParam String fileName, HttpServletRequest request,
        HttpServletResponse response) {
    try {
        final int buffersize = 1024;
        final byte[] buffer = new byte[buffersize];

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

        File file = new File(
                request.getSession().getServletContext().getRealPath("/") + TMP_FOLDER_PATH + fileName);
        InputStream inputStream = new FileInputStream(file);
        BufferedOutputStream outputStream = new BufferedOutputStream(response.getOutputStream());

        int available = 0;
        while ((available = inputStream.read(buffer)) >= 0) {
            outputStream.write(buffer, 0, available);
        }

        inputStream.close();

        outputStream.flush();
        outputStream.close();

        file.delete();
    } catch (Exception e) {
        throw new RuntimeException(e);
    }
}

From source file:com.gsr.myschool.server.reporting.excel.ExcelController.java

@RequestMapping(method = RequestMethod.GET, value = "/dossierconvoques", produces = "application/vnd.ms-excel")
@ResponseStatus(HttpStatus.OK)/*w  w  w.jav a 2 s . c  om*/
public void generateDossierConvoquesExcel(@RequestParam String fileName, HttpServletRequest request,
        HttpServletResponse response) {
    try {
        final int buffersize = 1024;
        final byte[] buffer = new byte[buffersize];

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

        File file = new File(
                request.getSession().getServletContext().getRealPath("/") + TMP_FOLDER_PATH + fileName);
        InputStream inputStream = new FileInputStream(file);
        BufferedOutputStream outputStream = new BufferedOutputStream(response.getOutputStream());

        int available = 0;
        while ((available = inputStream.read(buffer)) >= 0) {
            outputStream.write(buffer, 0, available);
        }

        inputStream.close();

        outputStream.flush();
        outputStream.close();

        file.delete();
    } catch (Exception e) {
        throw new RuntimeException(e);
    }
}

From source file:de.tu_dortmund.ub.hb_ng.middleware.MiddlewareHbNgEndpoint.java

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

    response.setHeader("Access-Control-Allow-Methods",
            this.config.getProperty(HBNGStatics.CORS_ACCESS_CONTROL_ALLOW_METHODS_IDENTIFIER));
    response.addHeader("Access-Control-Allow-Headers",
            this.config.getProperty(HBNGStatics.CORS_ACCESS_CONTROL_ALLOW_HEADERS_IDENTIFIER));
    response.setHeader("Access-Control-Allow-Origin",
            this.config.getProperty(HBNGStatics.CORS_ACCESS_CONTROL_ALLOW_ORIGIN_IDENTIFIER));
    response.setHeader("Accept", this.config.getProperty(HBNGStatics.CORS_ACCEPT_IDENTIFIER));

    response.getWriter().println();/*from  w  w  w  .j  a va  2  s  . c o m*/
}

From source file:edu.cornell.mannlib.vitro.webapp.filters.CachingResponseFilter.java

/**
 * Technically, if the request is not GET or HEAD, we should return 412
 * PreconditionFailed. However, we usually treat GET and POST as equivalent.
 *///  www  . jav a2 s.c  o  m
private void produceCacheHitResponse(HttpServletResponse resp, String etag) throws IOException {
    log.debug("Produce cache hit response: etag='" + etag + "'");
    resp.addHeader("ETag", etag);
    resp.addHeader("Vary", "Accept-Language");
    resp.sendError(HttpServletResponse.SC_NOT_MODIFIED, "Not Modified");
}

From source file:org.jasig.portlet.notice.controller.rest.JPANotificationRESTController.java

/**
 * Create a notification./*from w ww.j a va2s .  c o  m*/
 *
 * @param req the Http request
 * @param response the Http response
 * @param entry The Entry
 * @return The persisted entry
 */
@RequestMapping(method = RequestMethod.POST)
@ResponseStatus(HttpStatus.CREATED)
@ResponseBody
public EntryDTO createNotification(HttpServletRequest req, HttpServletResponse response,
        @RequestBody EntryDTO entry) {
    EntryDTO persisted = restService.createNotification(entry);

    String url = getSingleNotificationRESTUrl(req, persisted.getId());
    response.addHeader("Location", url);

    return persisted;
}

From source file:com.joliciel.jochre.search.web.JochreSearchServlet.java

@Override
protected void doGet(HttpServletRequest req, HttpServletResponse response)
        throws ServletException, IOException {
    try {//  w  w w  .j  a  v  a2 s. co m
        response.addHeader("Access-Control-Allow-Origin", "*");
        response.setCharacterEncoding("UTF-8");

        JochreSearchProperties props = JochreSearchProperties.getInstance(this.getServletContext());

        String command = req.getParameter("command");
        if (command == null) {
            command = "search";
        }

        if (command.equals("purge")) {
            JochreSearchProperties.purgeInstance();
            searcher = null;
            return;
        }

        Map<String, String> argMap = new HashMap<String, String>();
        @SuppressWarnings("rawtypes")
        Enumeration params = req.getParameterNames();
        while (params.hasMoreElements()) {
            String paramName = (String) params.nextElement();
            String value = req.getParameter(paramName);
            argMap.put(paramName, value);
        }

        SearchServiceLocator searchServiceLocator = SearchServiceLocator.getInstance();
        SearchService searchService = searchServiceLocator.getSearchService();

        double minWeight = 0;
        int titleSnippetCount = 1;
        int snippetCount = 3;
        int snippetSize = 80;
        boolean includeText = false;
        boolean includeGraphics = false;
        String snippetJson = null;
        Set<Integer> docIds = null;

        Set<String> handledArgs = new HashSet<String>();
        for (Entry<String, String> argEntry : argMap.entrySet()) {
            String argName = argEntry.getKey();
            String argValue = argEntry.getValue();
            argValue = URLDecoder.decode(argValue, "UTF-8");
            LOG.debug(argName + ": " + argValue);

            boolean handled = true;
            if (argName.equals("minWeight")) {
                minWeight = Double.parseDouble(argValue);
            } else if (argName.equals("titleSnippetCount")) {
                titleSnippetCount = Integer.parseInt(argValue);
            } else if (argName.equals("snippetCount")) {
                snippetCount = Integer.parseInt(argValue);
            } else if (argName.equals("snippetSize")) {
                snippetSize = Integer.parseInt(argValue);
            } else if (argName.equals("includeText")) {
                includeText = argValue.equalsIgnoreCase("true");
            } else if (argName.equals("includeGraphics")) {
                includeGraphics = argValue.equalsIgnoreCase("true");
            } else if (argName.equals("snippet")) {
                snippetJson = argValue;
            } else if (argName.equalsIgnoreCase("docIds")) {
                if (argValue.length() > 0) {
                    String[] idArray = argValue.split(",");
                    docIds = new HashSet<Integer>();
                    for (String id : idArray)
                        docIds.add(Integer.parseInt(id));
                }
            } else {
                handled = false;
            }
            if (handled) {
                handledArgs.add(argName);
            }
        }
        for (String argName : handledArgs)
            argMap.remove(argName);

        if (searcher == null) {
            String indexDirPath = props.getIndexDirPath();
            File indexDir = new File(indexDirPath);
            LOG.info("Index dir: " + indexDir.getAbsolutePath());
            searcher = searchService.getJochreIndexSearcher(indexDir);
        }

        if (command.equals("search")) {
            response.setContentType("text/plain;charset=UTF-8");
            PrintWriter out = response.getWriter();
            JochreQuery query = searchService.getJochreQuery(argMap);
            searcher.search(query, out);
            out.flush();
        } else if (command.equals("highlight") || command.equals("snippets")) {
            response.setContentType("text/plain;charset=UTF-8");
            PrintWriter out = response.getWriter();
            JochreQuery query = searchService.getJochreQuery(argMap);
            if (docIds == null)
                throw new RuntimeException("Command " + command + " requires docIds");

            HighlightServiceLocator highlightServiceLocator = HighlightServiceLocator
                    .getInstance(searchServiceLocator);
            HighlightService highlightService = highlightServiceLocator.getHighlightService();
            Highlighter highlighter = highlightService.getHighlighter(query, searcher.getIndexSearcher());
            HighlightManager highlightManager = highlightService
                    .getHighlightManager(searcher.getIndexSearcher());
            highlightManager.setDecimalPlaces(query.getDecimalPlaces());
            highlightManager.setMinWeight(minWeight);
            highlightManager.setIncludeText(includeText);
            highlightManager.setIncludeGraphics(includeGraphics);
            highlightManager.setTitleSnippetCount(titleSnippetCount);
            highlightManager.setSnippetCount(snippetCount);
            highlightManager.setSnippetSize(snippetSize);

            Set<String> fields = new HashSet<String>();
            fields.add("text");

            if (command.equals("highlight"))
                highlightManager.highlight(highlighter, docIds, fields, out);
            else
                highlightManager.findSnippets(highlighter, docIds, fields, out);
            out.flush();
        } else if (command.equals("imageSnippet")) {
            String mimeType = "image/png";
            response.setContentType(mimeType);
            if (snippetJson == null)
                throw new RuntimeException("Command " + command + " requires a snippet");
            Snippet snippet = new Snippet(snippetJson);

            if (LOG.isDebugEnabled()) {
                Document doc = searcher.getIndexSearcher().doc(snippet.getDocId());
                LOG.debug("Snippet in " + doc.get("id") + ", path: " + doc.get("path"));
            }

            HighlightServiceLocator highlightServiceLocator = HighlightServiceLocator
                    .getInstance(searchServiceLocator);
            HighlightService highlightService = highlightServiceLocator.getHighlightService();
            HighlightManager highlightManager = highlightService
                    .getHighlightManager(searcher.getIndexSearcher());
            ImageSnippet imageSnippet = highlightManager.getImageSnippet(snippet);
            OutputStream os = response.getOutputStream();
            ImageOutputStream ios = ImageIO.createImageOutputStream(os);
            BufferedImage image = imageSnippet.getImage();
            ImageReader imageReader = ImageIO.getImageReadersByMIMEType(mimeType).next();
            ImageWriter imageWriter = ImageIO.getImageWriter(imageReader);
            imageWriter.setOutput(ios);
            imageWriter.write(image);
            ios.flush();
        } else {
            throw new RuntimeException("Unknown command: " + command);
        }
    } catch (RuntimeException e) {
        LogUtils.logError(LOG, e);
        throw e;
    }
}

From source file:com.stormpath.spring.config.StormpathAuthenticationEntryPoint.java

@Override
public void commence(HttpServletRequest request, HttpServletResponse response,
        AuthenticationException authException) throws IOException, ServletException {
    log.debug("Pre-authenticated entry point called. Rejecting access");
    response.setStatus(HttpServletResponse.SC_UNAUTHORIZED);
    String bearerRealm = String.format("Bearer realm=\"%s\"", applicationName);
    response.addHeader("WWW-Authenticate", bearerRealm);
    if (isJsonPreferred(request, response)) {
        response.setContentType(MediaType.APPLICATION_JSON_VALUE);
        om.writeValue(response.getOutputStream(),
                new Error(ErrorConstants.ERR_ACCESS_DENIED, authException.getMessage()));
    } else {//from  w  ww  .  j  av  a2s.c om
        sendRedirect(request, response);
    }
}