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:alfio.controller.TicketController.java

@RequestMapping(value = "/event/{eventName}/ticket/{ticketIdentifier}/download-ticket", method = RequestMethod.GET)
public void generateTicketPdf(@PathVariable("eventName") String eventName,
        @PathVariable("ticketIdentifier") String ticketIdentifier, HttpServletRequest request,
        HttpServletResponse response) throws IOException, WriterException {

    Optional<Triple<Event, TicketReservation, Ticket>> oData = ticketReservationManager
            .fetchCompleteAndAssigned(eventName, ticketIdentifier);
    if (!oData.isPresent()) {
        response.sendError(HttpServletResponse.SC_FORBIDDEN);
        return;//from  ww  w  .  j  a  v  a 2 s.  c  o m
    }
    Triple<Event, TicketReservation, Ticket> data = oData.get();

    Ticket ticket = data.getRight();

    response.setContentType("application/pdf");
    response.addHeader("Content-Disposition", "attachment; filename=ticket-" + ticketIdentifier + ".pdf");
    try (OutputStream os = response.getOutputStream()) {
        PdfBoxRenderer renderer = preparePdfTicket(request, data.getLeft(), data.getMiddle(), ticket)
                .generate(ticket);
        if (renderer != null) {
            renderer.createPDF(os);
        }
    }
}

From source file:at.gv.egovernment.moa.id.auth.servlet.VerifyCertificateServlet.java

/**
 * Gets the signer certificate from the InfoboxReadRequest and 
 * responds with a new /*from   w  w  w .j a  va 2 s  . co m*/
 * <code>CreateXMLSignatureRequest</code>.
 * <br>
 * Request parameters:
 * <ul>
 * <li>MOASessionID: ID of associated authentication session</li>
 * <li>XMLResponse: <code>&lt;InfoboxReadResponse&gt;</code></li>
 * </ul>
 * @see javax.servlet.http.HttpServlet#doPost(HttpServletRequest, HttpServletResponse)
 */
protected void doPost(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {

    Logger.debug("POST VerifyCertificateServlet");

    Logger.warn(getClass().getName() + " is deprecated and should not be used any more.");

    resp.setHeader(MOAIDAuthConstants.HEADER_EXPIRES, MOAIDAuthConstants.HEADER_VALUE_EXPIRES);
    resp.setHeader(MOAIDAuthConstants.HEADER_PRAGMA, MOAIDAuthConstants.HEADER_VALUE_PRAGMA);
    resp.setHeader(MOAIDAuthConstants.HEADER_CACHE_CONTROL, MOAIDAuthConstants.HEADER_VALUE_CACHE_CONTROL);
    resp.addHeader(MOAIDAuthConstants.HEADER_CACHE_CONTROL, MOAIDAuthConstants.HEADER_VALUE_CACHE_CONTROL_IE);

    String pendingRequestID = null;

    Map<String, String> parameters;
    try {
        parameters = getParameters(req);
    } catch (FileUploadException e) {
        Logger.error("Parsing mulitpart/form-data request parameters failed: " + e.getMessage());
        throw new IOException(e.getMessage());
    }
    String sessionID = req.getParameter(PARAM_SESSIONID);

    // escape parameter strings
    sessionID = StringEscapeUtils.escapeHtml(sessionID);

    pendingRequestID = AuthenticationSessionStoreage.getPendingRequestID(sessionID);

    AuthenticationSession session = null;
    try {
        // check parameter
        if (!ParamValidatorUtils.isValidSessionID(sessionID))
            throw new WrongParametersException("VerifyCertificate", PARAM_SESSIONID, "auth.12");

        session = AuthenticationServer.getSession(sessionID);

        //change MOASessionID
        sessionID = AuthenticationSessionStoreage.changeSessionID(session);

        X509Certificate cert = AuthenticationServer.getInstance().getCertificate(sessionID, parameters);
        if (cert == null) {
            Logger.error("Certificate could not be read.");
            throw new AuthenticationException("auth.14", null);
        }

        boolean useMandate = session.getUseMandate();

        if (useMandate) {

            // verify certificate for OrganWalter
            String createXMLSignatureRequestOrRedirect = AuthenticationServer.getInstance()
                    .verifyCertificate(session, cert);

            try {
                AuthenticationSessionStoreage.storeSession(session);
            } catch (MOADatabaseException e) {
                throw new MOAIDException("session store error", null);
            }

            ServletUtils.writeCreateXMLSignatureRequestOrRedirect(resp, session,
                    createXMLSignatureRequestOrRedirect, AuthenticationServer.REQ_PROCESS_VALIDATOR_INPUT,
                    "VerifyCertificate");

        } else {

            String countrycode = CertificateUtils.getIssuerCountry(cert);
            if (countrycode != null) {
                if (countrycode.compareToIgnoreCase("AT") == 0) {
                    Logger.error(
                            "Certificate issuer country code is \"AT\". Login not support in foreign identities mode.");
                    throw new AuthenticationException("auth.22", null);
                }
            }

            // Foreign Identities Modus   
            String createXMLSignatureRequest = AuthenticationServer.getInstance()
                    .createXMLSignatureRequestForeignID(session, cert);
            // build dataurl (to the GetForeignIDSerlvet)
            String dataurl = new DataURLBuilder().buildDataURL(session.getAuthURL(), REQ_GET_FOREIGN_ID,
                    session.getSessionID());

            try {
                AuthenticationSessionStoreage.storeSession(session);
            } catch (MOADatabaseException e) {
                throw new MOAIDException("session store error", null);
            }

            ServletUtils.writeCreateXMLSignatureRequest(resp, createXMLSignatureRequest,
                    AuthenticationServer.REQ_PROCESS_VALIDATOR_INPUT, "GetForeignID", dataurl);

            Logger.debug("Send CreateXMLSignatureRequest to BKU");
        }
    } catch (MOAIDException ex) {
        handleError(null, ex, req, resp, pendingRequestID);

    } catch (Exception e) {
        Logger.error("CertificateValidation has an interal Error.", e);
    }

    finally {
        ConfigurationDBUtils.closeSession();
    }
}

From source file:org.apache.ofbiz.base.util.UtilHttp.java

public static void setResponseBrowserProxyNoCache(HttpServletResponse response) {
    long nowMillis = System.currentTimeMillis();
    response.setDateHeader("Expires", nowMillis);
    response.setDateHeader("Last-Modified", nowMillis); // always modified
    response.setHeader("Cache-Control", "no-store, no-cache, must-revalidate"); // HTTP/1.1
    response.addHeader("Cache-Control", "post-check=0, pre-check=0, false");
    response.setHeader("Pragma", "no-cache"); // HTTP/1.0
}

From source file:com.vico.license.controller.LicenseController.java

/**
 * @param serialNumberId//ww w .  ja v  a 2  s . com
 * @return
 * @throws IOException
 * @param:
 * @return: ProcessResult
 * @Title: useLicense
 * @Description: ??
 */
@RequestMapping(value = "uselicense")
public void useLicense(@PathParam("serialNumberId") String serialNumberId, HttpServletResponse response) {
    ProcessResult processResult = new ProcessResult();
    String path = ClassPathResourceURI.getResourceURI("/").getPath();
    boolean creatsucess = false;
    String nameofzip = "license.zip";
    creatsucess = licenseService.createZIPFile(Integer.parseInt(serialNumberId));
    if (!creatsucess) {
        logger.error("?ZIP!");
        return;
    }

    try {
        FileInputStream inputStream1 = new FileInputStream(path + nameofzip);
        response.addHeader("Content-disposition", "attachment;filename=license.zip");
        response.setContentType("zip/plain");
        IOUtils.copy(inputStream1, response.getOutputStream());
        response.flushBuffer();
    } catch (Exception e) {
        logger.error(e);
    }

    try {
        int i = licenseService.modifyLicenseState(Integer.parseInt(serialNumberId));
        if (i == 1) {
            processResult.setResultcode(ProcessResultEnum.RETURN_RESULT_SUCCESS);
            processResult.setResultdesc(ProcessResultEnum.MODIFY_SUCCESS);
        } else {
            processResult.setResultcode(ProcessResultEnum.RETURN_RESULT_FAIL);
            processResult.setResultdesc(ProcessResultEnum.MODIFY_FAIL);
        }
    } catch (Exception e) {
        logger.error(ProcessResultEnum.MODIFY_ERROR + ProcessResultEnum.getClassPath());
    }
}

From source file:com.vico.license.controller.LicenseController.java

@RequestMapping(value = "uselicense/{serialNumberId}")
public void useLicenseAngu(@PathVariable("serialNumberId") String serialNumberId,
        HttpServletResponse response) {
    ProcessResult processResult = new ProcessResult();
    String path = ClassPathResourceURI.getResourceURI("/").getPath();
    boolean creatsucess = false;
    String nameofzip = "license.zip";
    creatsucess = licenseService.createZIPFile(Integer.parseInt(serialNumberId));
    if (!creatsucess) {
        logger.error("?ZIP!");
        return;/*from www  .  j av  a2 s.c  om*/
    }

    try {
        FileInputStream inputStream1 = new FileInputStream(path + nameofzip);
        response.addHeader("Content-disposition", "attachment;filename=license.zip");
        response.setContentType("zip/plain");
        IOUtils.copy(inputStream1, response.getOutputStream());
        response.flushBuffer();
    } catch (Exception e) {
        logger.error(e);
    }

    try {
        int i = licenseService.modifyLicenseState(Integer.parseInt(serialNumberId));
        if (i == 1) {
            processResult.setResultcode(ProcessResultEnum.RETURN_RESULT_SUCCESS);
            processResult.setResultdesc(ProcessResultEnum.MODIFY_SUCCESS);
        } else {
            processResult.setResultcode(ProcessResultEnum.RETURN_RESULT_FAIL);
            processResult.setResultdesc(ProcessResultEnum.MODIFY_FAIL);
        }
    } catch (Exception e) {
        logger.error(ProcessResultEnum.MODIFY_ERROR + ProcessResultEnum.getClassPath());
    }
}

From source file:com.acc.storefront.security.cookie.EnhancedCookieGenerator.java

@Override
public void addCookie(final HttpServletResponse response, final String cookieValue) {
    super.addCookie(new HttpServletResponseWrapper(response) {
        @Override//w ww.  j  ava 2s .co m
        public void addCookie(final Cookie cookie) {
            setEnhancedCookiePath(cookie);

            if (isHttpOnly()) {
                // Custom code to write the cookie including the httpOnly flag
                final StringBuffer headerBuffer = new StringBuffer(100);
                ServerCookie.appendCookieValue(headerBuffer, cookie.getVersion(), cookie.getName(),
                        cookie.getValue(), cookie.getPath(), cookie.getDomain(), cookie.getComment(),
                        cookie.getMaxAge(), cookie.getSecure(), true);
                response.addHeader(HEADER_COOKIE, headerBuffer.toString());
            } else {
                // Write the cookie as normal
                super.addCookie(cookie);
            }
        }
    }, cookieValue);
}

From source file:org.bedework.notifier.web.MethodBase.java

protected void addHeaders(final HttpServletResponse resp) throws NoteException {
    // This probably needs changes
    /*/*  w  w  w.j  a v  a2  s  .c  om*/
        StringBuilder methods = new StringBuilder();
        for (String name: getNotifier().getMethodNames()) {
          if (methods.length() > 0) {
            methods.append(", ");
          }
            
          methods.append(name);
        }
            
        resp.addHeader("Allow", methods.toString());
        */
    resp.addHeader("Allow", "POST, GET");
}

From source file:org.ngrinder.script.controller.FileEntryController.java

/**
 * Download file entry of given path.//from  w ww .  j av a 2s  . c o m
 *
 * @param user     current user
 * @param path     user
 * @param response response
 */
@RequestMapping("/download/**")
public void download(User user, @RemainedPath String path, HttpServletResponse response) {
    FileEntry fileEntry = fileEntryService.getOne(user, path);
    if (fileEntry == null) {
        LOG.error("{} requested to download not existing file entity {}", user.getUserId(), path);
        return;
    }
    response.reset();
    try {
        response.addHeader("Content-Disposition", "attachment;filename="
                + java.net.URLEncoder.encode(FilenameUtils.getName(fileEntry.getPath()), "utf8"));
    } catch (UnsupportedEncodingException e1) {
        LOG.error(e1.getMessage(), e1);
    }
    response.setContentType("application/octet-stream; charset=UTF-8");
    response.addHeader("Content-Length", "" + fileEntry.getFileSize());
    byte[] buffer = new byte[4096];
    ByteArrayInputStream fis = null;
    OutputStream toClient = null;
    try {
        fis = new ByteArrayInputStream(fileEntry.getContentBytes());
        toClient = new BufferedOutputStream(response.getOutputStream());
        int readLength;
        while (((readLength = fis.read(buffer)) != -1)) {
            toClient.write(buffer, 0, readLength);
        }
    } catch (IOException e) {
        throw processException("error while download file", e);
    } finally {
        IOUtils.closeQuietly(fis);
        IOUtils.closeQuietly(toClient);
    }
}

From source file:cn.featherfly.web.spring.servlet.view.ResourceView.java

protected void download(HttpServletRequest request, HttpServletResponse response, InputStream is,
        Object downloadObj, String name) throws IOException {
    if (StringUtils.isBlank(getContentType())) {
        setContentType("application/octet-stream;charset=" + encodeCharset);
    }/*from  w  ww.j  av  a  2s  . co m*/
    if (StringUtils.isNotBlank(fileName)) {
        name = fileName;
    }
    if (StringUtils.isBlank(name)) {
        throw new StandardSysException("??");
    }
    if (!allowCaching) {
        response.addHeader("Pragma", "no-cache");
        response.addHeader("Cache-Control", "no-cache");
    }
    String encodeName = getEncodeName(name);
    if (request.getHeader("User-Agent").indexOf("MSIE 5.5") != -1) {
        response.setHeader("Content-Disposition", "filename=" + encodeName);
    } else {
        String contentDisposition = null;
        if (downloadable) {
            contentDisposition = "attachment;filename=" + encodeName;
        } else {
            contentDisposition = "inline;filename=" + encodeName;
        }
        response.setHeader("Content-disposition", contentDisposition);
    }
    response.setHeader("Content-Type", getContentType());
    response.setContentType(getContentType());

    byte[] buffer = new byte[bufferSize];
    int length = 0;
    try {
        OutputStream os = response.getOutputStream();
        while ((length = is.read(buffer)) > 0) {
            os.write(buffer, 0, length);
        }
        os.flush();
        os.close();
    } finally {
        is.close();
        delete(downloadObj);
    }
}

From source file:org.xmlactions.web.conceal.HttpPager.java

private String serviceJasperPdfRequest(HttpServletResponse response, byte[] pdfImage,
        String outputPdfFileName) {

    InputStream inputStream = null;
    OutputStream responseOutputStream = null;
    try {/*from w ww . j  a  v  a2  s  .com*/
        response.setContentType("application/pdf");
        response.addHeader("Content-Disposition", "attachment; filename=" + outputPdfFileName);
        response.setContentLength(pdfImage.length);

        inputStream = new ByteArrayInputStream(pdfImage);
        responseOutputStream = response.getOutputStream();
        int bytes;
        while ((bytes = inputStream.read()) != -1) {
            responseOutputStream.write(bytes);
        }
    } catch (Exception ex) {
        return ("EX:" + ex.getMessage());
    } finally {
        IOUtils.closeQuietly(inputStream);
        // IOUtils.closeQuietly(responseOutputStream);
    }
    return null;
}