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.gob.cfe.documentos.web.DepuracionController.java

/**
 * Metodo utilizado para generrar el pdf
 *
 * @param tipo/*from w  ww.j a  v a  2s . c o m*/
 * @param documentos
 * @param response
 * @throws JRException
 * @throws IOException
 */
private void generaReporte(String tipo, List<Documento> documentos, HttpServletResponse response)
        throws JRException, IOException {
    log.debug("Generando reporte {}", tipo);
    byte[] archivo = null;
    switch (tipo) {
    case "PDF":
        archivo = generaPdf(documentos);
        response.setContentType("application/pdf");
        Date fecha = new Date();
        response.addHeader("Content-Disposition",
                "attachment; filename=" + fecha.toString() + "depuracion.pdf");
        break;

    }
    if (archivo != null) {
        response.setContentLength(archivo.length);
        try (BufferedOutputStream bos = new BufferedOutputStream(response.getOutputStream())) {
            bos.write(archivo);
            bos.flush();
        }
    }

}

From source file:com.googlesource.gerrit.plugins.lfs.fs.LfsFsContentServlet.java

@Override
protected void doHead(HttpServletRequest req, HttpServletResponse rsp) throws ServletException, IOException {
    String verifyId = req.getHeader(HttpHeaders.IF_NONE_MATCH);
    if (Strings.isNullOrEmpty(verifyId)) {
        doGet(req, rsp);//from ww  w .j  a  v a 2  s  .  c  o m
        return;
    }

    Optional<AnyLongObjectId> obj = validateGetRequest(req, rsp);
    if (obj.isPresent() && obj.get().getName().equalsIgnoreCase(verifyId)) {
        rsp.addHeader(HttpHeaders.ETAG, obj.get().getName());
        rsp.setStatus(HttpStatus.SC_NOT_MODIFIED);
        return;
    }

    getObject(req, rsp, obj);
}

From source file:com.viewer.servlets.ViewDocument.java

protected void doPost(HttpServletRequest request, HttpServletResponse response)
        throws ServletException, IOException {

    response.addHeader("Content-Type", "application/json");
    ViewDocumentParameters params = new ObjectMapper().readValue(request.getInputStream(),
            ViewDocumentParameters.class);

    ViewDocumentResponse result = new ViewDocumentResponse();
    FileData fileData = ViewerUtils.factoryFileData(params.getPath());
    DocumentInfoContainer docInfo = null;

    try {/*ww w  .  j  a  va  2 s  . c  o  m*/
        result.setDocumentDescription(
                (new FileDataJsonSerializer(fileData, new FileDataOptions())).Serialize(false));
    } catch (ParseException x) {
        throw new ServletException(x);
    }

    if (params.getUseHtmlBasedEngine()) {
        try {
            docInfo = ViewerUtils.getViewerHtmlHandler()
                    .getDocumentInfo(new DocumentInfoOptions(params.getPath()));
        } catch (Exception x) {
            throw new ServletException(x);
        }

        result.setPageCss(new String[0]);
        result.setLic(true);
        result.setPdfDownloadUrl(GetPdfDownloadUrl(params));
        result.setPdfPrintUrl(GetPdfPrintUrl(params));
        result.setUrl(GetFileUrl(params));
        result.setPath(params.getPath());
        result.setName(params.getPath());
        try {
            result.setDocumentDescription(
                    (new FileDataJsonSerializer(fileData, new FileDataOptions())).Serialize(false));
        } catch (ParseException x) {
            throw new ServletException(x);
        }
        result.setDocType(docInfo.getDocumentType());
        result.setFileType(docInfo.getFileType());

        HtmlOptions htmlOptions = new HtmlOptions();
        htmlOptions.setResourcesEmbedded(true);

        htmlOptions.setHtmlResourcePrefix("/GetResourceForHtml?documentPath=" + params.getPath()
                + "&pageNumber={page-number}&resourceName=");

        if (!DotNetToJavaStringHelper.isNullOrEmpty(params.getPreloadPagesCount().toString())
                && params.getPreloadPagesCount().intValue() > 0) {
            htmlOptions.setPageNumber(1);
            htmlOptions.setCountPagesToConvert(params.getPreloadPagesCount().intValue());
        }

        String[] cssList = null;

        RefObject<ArrayList<String>> tempRef_cssList = new RefObject<ArrayList<String>>(cssList);

        List<PageHtml> htmlPages;
        try {
            htmlPages = GetHtmlPages(params.getPath(), htmlOptions);
            cssList = tempRef_cssList.argValue;

            ArrayList<String> pagesContent = new ArrayList<String>();
            for (PageHtml page : htmlPages) {
                pagesContent.add(page.getHtmlContent());
            }
            String[] htmlContent = pagesContent.toArray(new String[0]);
            result.setPageHtml(htmlContent);
            result.setPageCss(new String[] { String.join(" ", temp_cssList) });

            for (int i = 0; i < result.getPageHtml().length; i++) {
                String html = result.getPageHtml()[i];
                int indexOfScript = html.indexOf("script");
                if (indexOfScript > 0) {
                    result.getPageHtml()[i] = html.substring(0, indexOfScript);
                }
            }
        } catch (Exception e) {
            // TODO Auto-generated catch block
            e.printStackTrace();
        }

    } else {

        try {
            docInfo = ViewerUtils.getViewerImageHandler()
                    .getDocumentInfo(new DocumentInfoOptions(params.getPath()));
        } catch (Exception x) {
            throw new ServletException(x);
        }

        int maxWidth = 0;
        int maxHeight = 0;
        for (PageData pageData : docInfo.getPages()) {
            if (pageData.getHeight() > maxHeight) {
                maxHeight = pageData.getHeight();
                maxWidth = pageData.getWidth();
            }
        }

        fileData.setDateCreated(new Date());
        fileData.setDateModified(docInfo.getLastModificationDate());
        fileData.setPageCount(docInfo.getPages().size());
        fileData.setPages(docInfo.getPages());
        fileData.setMaxWidth(maxWidth);
        fileData.setMaxHeight(maxHeight);

        result.setPageCss(new String[0]);
        result.setLic(true);
        result.setPdfDownloadUrl(GetPdfDownloadUrl(params));
        result.setPdfPrintUrl(GetPdfPrintUrl(params));
        result.setUrl(GetFileUrl(params.getPath(), true, false, params.getFileDisplayName(),
                params.getWatermarkText(), params.getWatermarkColor(), params.getWatermarkPostion(),
                params.getWatermarkWidth(), params.getIgnoreDocumentAbsence(), params.getUseHtmlBasedEngine(),
                params.getSupportPageRotation()));
        result.setPath(params.getPath());
        result.setName(params.getPath());

        result.setDocType(docInfo.getDocumentType());
        result.setFileType(docInfo.getFileType());

        int[] pageNumbers = new int[docInfo.getPages().size()];
        int count = 0;
        for (PageData page : docInfo.getPages()) {

            pageNumbers[count] = page.getNumber();
            count++;
        }
        String applicationHost = request.getScheme() + "://" + request.getServerName() + ":"
                + request.getServerPort();
        String[] imageUrls = ImageUrlHelper.GetImageUrls(applicationHost, pageNumbers, params);

        result.setImageUrls(imageUrls);

    }

    new ObjectMapper().writeValue(response.getOutputStream(), result);

}

From source file:biz.webgate.dominoext.poi.component.kernel.CSVProcessor.java

public void generateNewFile(UICSV csvDef, HttpServletResponse httpResponse, FacesContext context) {

    try {//  w w  w. j  a v a  2s .c om
        // First getting the File

        ByteArrayOutputStream csvBAOS = generateCSV(csvDef, context);

        httpResponse.setContentType("text/csv");
        httpResponse.setHeader("Cache-Control", "no-cache");
        httpResponse.setDateHeader("Expires", -1);
        httpResponse.setContentLength(csvBAOS.size());
        httpResponse.addHeader("Content-disposition",
                "inline; filename=\"" + csvDef.getDownloadFileName() + "\"");
        OutputStream os = httpResponse.getOutputStream();
        csvBAOS.writeTo(os);
        os.close();
    } catch (Exception e) {
        ErrorPageBuilder.getInstance().processError(httpResponse, "Error during CSV-Generation", e);
    }

}

From source file:control.HelperServlets.GenerarPdfServlet.java

/**
 * //from  w  ww . ja  v  a  2  s  .c o  m
 * Envia el archivo pdf a la vista para que sea descargado.
 * 
 * @param ruta
 * @param nombreArchivo
 * @param request
 * @param response
 * @throws FileNotFoundException
 * @throws IOException 
 */
public void enviarPDF(String ruta, String nombreArchivo, HttpServletRequest request,
        HttpServletResponse response) throws FileNotFoundException, IOException {

    //Obtenemos el archivo
    File pdfFile = new File(ruta);

    //Enviamos el pdf a la vista para que sea descargado.
    response.setContentType("application/pdf");
    response.addHeader("Content-Disposition", "attachment; filename=" + nombreArchivo);
    response.setContentLength((int) pdfFile.length());

    FileInputStream fileInputStream = new FileInputStream(pdfFile);
    OutputStream responseOutputStream = response.getOutputStream();
    int bytes;
    while ((bytes = fileInputStream.read()) != -1) {
        responseOutputStream.write(bytes);
    }
}

From source file:jp.rough_diamond.framework.web.struts.BaseAction.java

@Override
protected ActionForward dispatchMethod(ActionMapping mapping, ActionForm form, HttpServletRequest request,
        HttpServletResponse response, String name) throws Exception {
    Method method = null;// w w  w  .j av  a2 s.co  m
    try {
        method = getMethod(name);
        NoCache noCache = method.getAnnotation(NoCache.class);
        if (noCache != null) {
            log.debug("LbVNGXg?B");
            response.addHeader("Pragma", "no-cache");
            response.addHeader("Cache-Control", "no-cache");
            response.addHeader("Expires", "-1");
        }
        ContentType ct = method.getAnnotation(ContentType.class);
        if (ct != null) {
            if (log.isDebugEnabled()) {
                log.debug("ContentType:" + ct.value());
            }
            response.setContentType(ct.value());
        }
        //?
    } catch (NoSuchMethodException e) {
        String message = messages.getMessage("dispatch.method", mapping.getPath(), name);
        log.error(message, e);
        throw e;
    }

    ActionForward forward = null;
    try {
        Object args[] = { mapping, form, request, response };
        forward = (ActionForward) method.invoke(this, args);
        if (form instanceof BaseForm) {
            BaseForm baseForm = (BaseForm) form;
            Messages msg;
            msg = baseForm.getMessage();
            if (msg.hasError()) {
                saveMessages(request, MessagesTranslator.translate(msg));
            }
            msg = baseForm.getErrors();
            if (msg.hasError()) {
                saveErrors(request, MessagesTranslator.translate(msg));
            }
        }
    } catch (ClassCastException e) {
        String message = messages.getMessage("dispatch.return", mapping.getPath(), name);
        log.error(message, e);
        throw e;

    } catch (IllegalAccessException e) {
        String message = messages.getMessage("dispatch.error", mapping.getPath(), name);
        log.error(message, e);
        throw e;

    } catch (InvocationTargetException e) {
        // Rethrow the target exception if possible so that the
        // exception handling machinery can deal with it
        Throwable t = e.getTargetException();
        if (t instanceof Exception) {
            throw ((Exception) t);
        } else {
            String message = messages.getMessage("dispatch.error", mapping.getPath(), name);
            log.error(message, e);
            throw new ServletException(t);
        }
    }

    // Return the returned ActionForward instance
    return (forward);
}

From source file:org.apache.cxf.fediz.service.idp.protocols.TrustedIdpSAMLProtocolHandler.java

@Override
public URL mapSignInRequest(RequestContext context, Idp idp, TrustedIdp trustedIdp) {

    try {//from w ww .j a v a2s .  c o m
        Document doc = DOMUtils.createDocument();
        doc.appendChild(doc.createElement("root"));
        // Create the AuthnRequest
        AuthnRequest authnRequest = authnRequestBuilder.createAuthnRequest(null, idp.getRealm(),
                idp.getIdpUrl().toString());

        boolean signRequest = isPropertyConfigured(trustedIdp, SIGN_REQUEST, true);
        if (signRequest) {
            authnRequest.setDestination(trustedIdp.getUrl());
        }
        Element authnRequestElement = OpenSAMLUtil.toDom(authnRequest, doc);
        String authnRequestEncoded = encodeAuthnRequest(authnRequestElement);

        String urlEncodedRequest = URLEncoder.encode(authnRequestEncoded, "UTF-8");

        UriBuilder ub = UriBuilder.fromUri(trustedIdp.getUrl());

        ub.queryParam(SSOConstants.SAML_REQUEST, urlEncodedRequest);

        String wctx = context.getFlowScope().getString(FederationConstants.PARAM_CONTEXT);
        if (wctx != null) {
            ub.queryParam(SSOConstants.RELAY_STATE, wctx);
        }
        if (signRequest) {
            signRequest(urlEncodedRequest, wctx, idp, ub);
        }

        // Store the Request ID
        String authnRequestId = authnRequest.getID();
        WebUtils.putAttributeInExternalContext(context, SAML_SSO_REQUEST_ID, authnRequestId);

        HttpServletResponse response = WebUtils.getHttpServletResponse(context);
        response.addHeader("Cache-Control", "no-cache, no-store");
        response.addHeader("Pragma", "no-cache");

        return ub.build().toURL();
    } catch (MalformedURLException ex) {
        LOG.error("Invalid Redirect URL for Trusted Idp", ex);
        throw new IllegalStateException("Invalid Redirect URL for Trusted Idp");
    } catch (UnsupportedEncodingException ex) {
        LOG.error("Invalid Redirect URL for Trusted Idp", ex);
        throw new IllegalStateException("Invalid Redirect URL for Trusted Idp");
    } catch (Exception ex) {
        LOG.error("Invalid Redirect URL for Trusted Idp", ex);
        throw new IllegalStateException("Invalid Redirect URL for Trusted Idp");
    }
}

From source file:at.gv.egovernment.moa.id.proxy.servlet.ProxyServlet.java

private static void generateErrorAndRedirct(HttpServletResponse resp, String errorURL, String message) {
    try {/*from  w w w  .  j  a  va 2  s .  c  o m*/
        errorURL = addURLParameter(errorURL, PARAM_ERRORMASSAGE, URLEncoder.encode(message, "UTF-8"));

    } catch (UnsupportedEncodingException e) {
        errorURL = addURLParameter(errorURL, PARAM_ERRORMASSAGE,
                "Fehlermeldung%20konnte%20nicht%20%C3%BCbertragen%20werden.");
    }

    errorURL = resp.encodeRedirectURL(errorURL);
    resp.setContentType("text/html");
    resp.setStatus(302);
    resp.addHeader("Location", errorURL);
}

From source file:com.ibm.sbt.service.basic.ProxyService.java

public static void writeErrorResponse(int httpstatus, String errorMessage, String[] parameters, String[] values,
        HttpServletResponse response, HttpServletRequest request) throws ServletException {
    JsonJavaObject o = new JsonJavaObject();
    o.putString("Message", errorMessage);
    List<JsonJavaObject> params = new ArrayList<JsonJavaObject>();
    if (parameters != null && parameters.length > 0) {
        for (int i = 0; i < parameters.length; i++) {
            JsonJavaObject e = new JsonJavaObject();
            e.putString(parameters[i], values[i]);
            params.add(e);//www. j a v  a  2 s  . co m
        }
    }
    o.putObject("Parameters", params);

    try {
        response.setStatus(httpstatus);
        //response.setStatus(HttpServletResponse.SC_FORBIDDEN);
        response.addHeader("content-type", "application/json"); // $NON-NLS-1$ $NON-NLS-2$
        response.addHeader("Server", "SBT"); // $NON-NLS-1$ $NON-NLS-2$
        response.addHeader("Connection", "close"); // $NON-NLS-1$ $NON-NLS-2$
        response.addDateHeader("Date", System.currentTimeMillis()); // $NON-NLS-1$
        response.getOutputStream().print(JsonGenerator.toJson(JsonJavaFactory.instanceEx, o));
    } catch (Exception e) {
    }
}

From source file:com.roche.iceboar.demo.JnlpServlet.java

/**
 * This method handle all HTTP requests for *.jnlp files (defined in web.xml). Method check, is name correct
 * (allowed), read file from disk, replace #{codebase} (it's necessary to be generated based on where application
 * is deployed), #{host} () and write to the response.
 * <p>/*  www.j  ava2  s .  co m*/
 * You can use this class in your code for downloading JNLP files.
 * Return a content of requested jnlp file in response.
 *
 * @throws IOException when can't close some stream
 */
@Override
public void doGet(HttpServletRequest request, HttpServletResponse response) throws IOException {
    String contextPath = request.getContextPath();
    String requestURI = request.getRequestURI();
    String host = request.getScheme() + "://" + request.getServerName() + ":" + request.getServerPort();
    String codebase = host + contextPath;
    String filename = StringUtils.removeStart(requestURI, contextPath);
    response.setContentType("application/x-java-jnlp-file");
    response.addHeader("Pragma", "no-cache");
    response.addHeader("Expires", "-1");

    OutputStreamWriter out = new OutputStreamWriter(response.getOutputStream());

    InputStream in = JnlpServlet.class.getResourceAsStream(filename);
    if (in == null) {
        error(response, "Can't open: " + filename);
        return;
    }
    BufferedReader reader = new BufferedReader(new InputStreamReader(in));

    String line = reader.readLine();
    while (line != null) {
        line = line.replace("#{codebase}", codebase);
        line = line.replace("#{host}", host);
        out.write(line);
        out.write("\n");
        line = reader.readLine();
    }

    out.flush();
    out.close();
    reader.close();
}