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:net.shibboleth.idp.authn.spnego.impl.SPNEGOAuthnController.java

/**
 * Send back a Negotiate challenge token.
 * /*ww  w  . jav a  2s  . c  o  m*/
 * @param profileRequestContext profile request context
 * @param httpRequest servlet request
 * @param httpResponse servlet response
 * @param base64Token challenge token to send back
 * 
 * @return a {@link ModelAndView} wrapping the response
 */
@Nonnull
private ModelAndView replyUnauthorizedNegotiate(@Nonnull final ProfileRequestContext profileRequestContext,
        @Nonnull final HttpServletRequest httpRequest, @Nonnull final HttpServletResponse httpResponse,
        @Nonnull final String base64Token) {

    final StringBuilder authenticateHeader = new StringBuilder("Negotiate");
    if (!base64Token.isEmpty()) {
        authenticateHeader.append(" " + base64Token);
    }
    httpResponse.addHeader(HttpHeaders.WWW_AUTHENTICATE, authenticateHeader.toString());
    httpResponse.setStatus(HttpServletResponse.SC_UNAUTHORIZED);
    return createModelAndView(profileRequestContext, httpRequest, httpResponse);
}

From source file:ch.silviowangler.dox.web.DocumentController.java

@RequestMapping(method = GET, value = "/document/{hash}.thumbnail")
public void getDocument(@PathVariable("hash") String hash, HttpServletResponse response,
        @RequestHeader("User-Agent") String userAgent) {

    File thumbnailsDir = new File(this.archiveDirectory, "thumbnails");

    final Browser browser = parseUserAgentString(userAgent);

    File webp = new File(thumbnailsDir, hash + ".webp");
    File jpg = new File(thumbnailsDir, hash + ".jpg");

    if (isWebpSupportedBrowser(userAgent, browser) && webp.exists()) {
        response.setStatus(SC_OK);//from   ww  w . j a va 2  s .  co  m
        response.addHeader("Content-Type", "image/webp");
        response.addHeader("Content-Disposition", "inline; filename=\"" + webp.getName() + "\"");

        try {
            IOUtils.copy(new FileInputStream(webp), response.getOutputStream());
            response.getOutputStream().flush();
        } catch (IOException e) {
            logger.error("Unable to write thumbnail for hash {} to output stream", hash, e);
        }
    } else if (jpg.exists()) {
        response.setStatus(SC_OK);
        response.addHeader("Content-Type", "image/jpeg");
        response.addHeader("Content-Disposition", "inline; filename=\"" + jpg.getName() + "\"");

        try {
            IOUtils.copy(new FileInputStream(jpg), response.getOutputStream());
            response.getOutputStream().flush();
        } catch (IOException e) {
            logger.error("Unable to write thumbnail for hash {} to output stream", hash, e);
        }
    } else {
        response.setStatus(SC_NOT_FOUND);
    }
}

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

/**
 * Export mime types//from  www  .  j  a  v  a2s. com
 */
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 = "OpenKM_" + 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 OKM_MIME_TYPE;");
    out.println("DELETE FROM OKM_MIME_TYPE_EXTENSION;");

    for (MimeType mimeType : MimeTypeDAO.findAll("mt.id")) {
        StringBuffer insertMime = new StringBuffer(
                "INSERT INTO OKM_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 OKM_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.EstudiosEmpleadoController.java

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

}

From source file:org.geoserver.ows.AbstractURLPublisher.java

protected ModelAndView handleRequestInternal(HttpServletRequest request, HttpServletResponse response)
        throws Exception {
    URL url = getUrl(request);/*from  w  ww  . j  a  v  a 2  s  .  c  o m*/

    // if not found return a 404
    if (url == null) {
        response.sendError(HttpServletResponse.SC_NOT_FOUND);
        return null;
    }

    File file = DataUtilities.urlToFile(url);
    if (file != null && file.exists() && file.isDirectory()) {
        String uri = request.getRequestURI().toString();
        uri += uri.endsWith("/") ? "index.html" : "/index.html";

        response.addHeader("Location", uri);
        response.sendError(HttpServletResponse.SC_MOVED_TEMPORARILY);

        return null;
    }

    // set the mime if known by the servlet container, set nothing otherwise
    // (Tomcat behaves like this when it does not recognize the file format)
    String mime = getServletContext().getMimeType(new File(url.getFile()).getName());
    if (mime != null) {
        response.setContentType(mime);
    }

    // set the content length and content type
    URLConnection connection = null;
    InputStream input = null;
    try {
        connection = url.openConnection();
        long length = connection.getContentLength();
        if (length > 0 && length <= Integer.MAX_VALUE) {
            response.setContentLength((int) length);
        }

        long lastModified = connection.getLastModified();
        if (lastModified > 0) {
            SimpleDateFormat format = new SimpleDateFormat("EEE, d MMM yyyy HH:mm:ss", Locale.ENGLISH);
            format.setTimeZone(TimeZone.getTimeZone("GMT"));
            String formatted = format.format(new Date(lastModified)) + " GMT";
            response.setHeader("Last-Modified", formatted);
        }

        // Guessing the charset (and closing the stream)
        EncodingInfo encInfo = null;
        OutputStream output = null;
        final byte[] b4 = new byte[4];
        int count = 0;
        // open the output
        input = connection.getInputStream();

        // Read the first four bytes, and determine charset encoding
        count = input.read(b4);
        encInfo = XmlCharsetDetector.getEncodingName(b4, count);
        response.setCharacterEncoding(encInfo.getEncoding() != null ? encInfo.getEncoding() : "UTF-8");

        // send out the first four bytes read
        output = response.getOutputStream();
        output.write(b4, 0, count);

        // copy the content to the output
        byte[] buffer = new byte[8192];
        int n = -1;
        while ((n = input.read(buffer)) != -1) {
            output.write(buffer, 0, n);
        }
    } finally {
        if (input != null)
            input.close();
    }

    return null;
}

From source file:com.pkrete.locationservice.admin.controller.rest.v1.RestExceptionHandler.java

@ExceptionHandler(HttpRequestMethodNotSupportedException.class)
@ResponseBody//  w w  w  .  j a  v a2s . com
protected Map handleHttpRequestMethodNotSupported(HttpRequestMethodNotSupportedException ex, WebRequest request,
        HttpServletResponse response) {
    // Get supported methods
    StringBuilder methods = new StringBuilder();
    for (int i = 0; i < ex.getSupportedMethods().length; i++) {
        methods.append(ex.getSupportedMethods()[i]);
        if (i < ex.getSupportedMethods().length - 1) {
            methods.append(", ");
        }
    }
    // Set response status
    response.setStatus(405);
    // Set Allow  header
    response.addHeader("Allow", methods.toString());
    // Create Map containing all the fields   
    Map errors = new HashMap<String, String>();
    // Set message arguments
    Object[] args = new Object[] { ex.getMethod(), methods };
    // Get message and set argument values
    String message = messageSource.getMessage("rest.http.request.method.not.supported", args, null);
    // Add error message
    errors.put("error", message);
    // Not authenticated -> return error
    return errors;
}

From source file:com.ge.predix.web.cors.CORSFilter.java

void buildCorsXhrPreFlightResponse(final HttpServletRequest request, final HttpServletResponse response) {
    String accessControlRequestMethod = request.getHeader("Access-Control-Request-Method");
    if (null == accessControlRequestMethod) {
        response.setStatus(HttpStatus.BAD_REQUEST.value());
        return;/* w  ww.  ja  va2  s  .c  o m*/
    }
    if (!"GET".equalsIgnoreCase(accessControlRequestMethod)) {
        response.setStatus(HttpStatus.METHOD_NOT_ALLOWED.value());
        return;
    }
    response.addHeader("Access-Control-Allow-Methods", "GET");

    String accessControlRequestHeaders = request.getHeader("Access-Control-Request-Headers");
    if (null == accessControlRequestHeaders) {
        response.setStatus(HttpStatus.BAD_REQUEST.value());
        return;
    }
    if (!headersAllowed(accessControlRequestHeaders)) {
        response.setStatus(HttpStatus.FORBIDDEN.value());
        return;
    }
    response.addHeader("Access-Control-Allow-Headers", "Authorization, X-Requested-With");
    response.addHeader("Access-Control-Max-Age", this.maxAge);
}

From source file:com.citrix.cpbm.portal.fragment.controllers.AbstractReportController.java

@RequestMapping(value = "/generate_CSV", method = RequestMethod.POST)
@ResponseBody/*from   w  ww.j  a v  a  2  s. com*/
public void generateCSV(@RequestParam(value = "csvdata", required = true) String csvdata, ModelMap modelMap,
        HttpServletResponse response) {
    logger.debug("###Entering generateCSV method @");

    response.setContentType("application/csv");
    response.setHeader("Content-Disposition", "attachment; filename=report.csv");
    response.addHeader("Cache-Control", "no-store, no-cache");
    OutputStream out;
    try {
        out = response.getOutputStream();
        response.setContentLength(csvdata.getBytes().length);
        out.write(csvdata.getBytes());
        out.flush();
        out.close();
    } catch (IOException e) {
        logger.error(e.getMessage(), e);
    }
    logger.debug("###Exiting generateCSV method @");
}

From source file:uk.ac.ebi.eva.vcfdump.server.VcfDumperWSServer.java

private StreamingResponseBody getStreamingResponseBody(String species, String dbName, List<String> studies,
        Properties evaProperties, MultivaluedMap<String, String> queryParameters,
        HttpServletResponse response) {

    return new StreamingResponseBody() {
        @Override//  ww w .j a  v  a2  s  .co  m
        public void writeTo(OutputStream outputStream) throws IOException, WebApplicationException {
            VariantExporterController controller;
            try {
                controller = new VariantExporterController(species, dbName, studies, outputStream,
                        evaProperties, queryParameters);
                // tell the client that the file is an attachment, so it will download it instead of showing it
                response.addHeader(HttpHeaders.CONTENT_DISPOSITION,
                        "attachment;filename=" + controller.getOutputFileName());
                controller.run();
            } catch (Exception e) {
                throw new WebApplicationException(e);
            }
        }
    };
}

From source file:net.sourceforge.fenixedu.presentationTier.Action.publico.FileDownload.java

@Override
public ActionForward execute(final ActionMapping mapping, final ActionForm actionForm,
        final HttpServletRequest request, final HttpServletResponse response) throws Exception {
    final String oid = request.getParameter("oid");
    final File file = FenixFramework.getDomainObject(oid);
    if (file == null) {
        response.setStatus(HttpServletResponse.SC_BAD_REQUEST);
        response.getWriter().write(HttpStatus.getStatusText(HttpStatus.SC_BAD_REQUEST));
        response.getWriter().close();/*from www.j a v  a 2  s  .c  o m*/
    } else {
        final Person person = AccessControl.getPerson();
        if (!file.isPrivate() || file.isPersonAllowedToAccess(person)) {
            response.setContentType(file.getContentType());
            response.addHeader("Content-Disposition", "attachment; filename=" + file.getFilename());
            response.setContentLength(file.getSize().intValue());
            final DataOutputStream dos = new DataOutputStream(response.getOutputStream());
            dos.write(file.getContents());
            dos.close();
        } else if (file.isPrivate() && person == null) {
            response.setStatus(HttpServletResponse.SC_UNAUTHORIZED);
            response.getWriter().write(HttpStatus.getStatusText(HttpStatus.SC_UNAUTHORIZED));
            response.getWriter().close();
        } else {
            response.setStatus(HttpServletResponse.SC_FORBIDDEN);
            response.getWriter().write(HttpStatus.getStatusText(HttpStatus.SC_FORBIDDEN));
            response.getWriter().close();
        }
    }
    return null;
}