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.sourceforge.fenixedu.presentationTier.Action.internationalRelatOffice.candidacy.erasmus.ErasmusIndividualCandidacyProcessDA.java

public ActionForward retrieveLearningAgreement(ActionMapping mapping, ActionForm form,
        HttpServletRequest request, HttpServletResponse response) throws Exception {
    MobilityIndividualApplicationProcess process = getProcess(request);

    final LearningAgreementDocument document = new LearningAgreementDocument(process);
    byte[] data = ReportsUtils.exportMultipleToPdfAsByteArray(document);

    response.setContentLength(data.length);
    response.setContentType("application/pdf");
    response.addHeader("Content-Disposition", "attachment; filename=" + document.getReportFileName() + ".pdf");

    final ServletOutputStream writer = response.getOutputStream();
    writer.write(data);/*w  w  w .j av a 2s. c o  m*/
    writer.flush();
    writer.close();

    response.flushBuffer();
    return mapping.findForward("");
}

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

/**
 * Export configuration/*from  w w w .  jav  a  2 s  . c o  m*/
 */
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() + "_cfg.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);

    for (Config cfg : ConfigDAO.findAll()) {
        if (!Config.HIDDEN.equals(cfg.getType())) {
            out.println("DELETE FROM OKM_CONFIG WHERE CFG_KEY='" + cfg.getKey() + "';");
        }
    }

    for (Config cfg : ConfigDAO.findAll()) {
        if (!Config.HIDDEN.equals(cfg.getType())) {
            StringBuffer insertCfg = new StringBuffer(
                    "INSERT INTO OKM_CONFIG (CFG_KEY, CFG_TYPE, CFG_VALUE) VALUES ('");
            insertCfg.append(cfg.getKey()).append("', '");
            insertCfg.append(cfg.getType()).append("', '");

            if (cfg.getValue() == null || cfg.getValue().equals("null")) {
                insertCfg.append("").append("');");
            } else {
                insertCfg.append(cfg.getValue()).append("');");
            }

            out.println(insertCfg);
        }
    }

    out.flush();
    log.debug("export: void");
}

From source file:io.starter.datamodel.Sys.java

/**
 * Get the /1.0/application.wadl/*w  ww.  jav  a 2  s . c  o  m*/
 * 
 * TODO: implement extended WADL Apply XSLT to the WADL output to generate
 * human-readable api docs per: https://wikis.oracle.com/display/Jersey/WADL
 * 
 * 
 * @return
 * @throws IOException
 * @throws TransformerException
 */
@GET
@Path("apidocs")
@Produces(MediaType.TEXT_HTML)
public String getWADL(@Context HttpServletRequest servletRequest, @Context HttpServletResponse servletResponse)
        throws IOException, TransformerException {

    servletResponse.addHeader("Access-Control-Allow-Origin", "*");

    // Transform the WADL to HTML using XSLT
    TransformerFactory factory = TransformerFactory.newInstance();

    // Make a URL to the XML
    String iserv = servletRequest.getScheme() + "://" + servletRequest.getServerName() + ":"
            + servletRequest.getServerPort() + "/" + SystemConstants.REST_BASE_PATH + "/";
    URL url = new URL(iserv + WADL_SOURCE_URL);

    URLConnection con = url.openConnection();
    con.setDoOutput(true);
    Source text = new StreamSource(con.getInputStream());

    // path to the XSLT
    URL urlx = new URL(SystemConstants.REST_API_SERVER_HOST + "/wadl_html_doc.xslt");
    HttpURLConnection urlConnection = (HttpURLConnection) urlx.openConnection();

    InputStream is = null;

    is = new BufferedInputStream(urlConnection.getInputStream());

    Source xslt = new StreamSource(is);

    Transformer transformer = factory.newTransformer(xslt);
    servletResponse.setContentType("text/html");
    OutputStream ous = servletResponse.getOutputStream();

    transformer.transform(text, new StreamResult(ous));
    ous.flush();
    ous.close();

    return "ok";
}

From source file:com.adaptris.core.http.jetty.ResponseProducer.java

@Override
public void produce(AdaptrisMessage msg, ProduceDestination destination) throws ProduceException {
    JettyWrapper wrapper = JettyWrapper.unwrap(msg);
    HttpServletResponse response = wrapper.getResponse();
    InputStream in = null;/*from  ww  w  .  j  ava 2 s.c  o  m*/

    try {
        wrapper.lock();
        if (response == null) {
            log.debug("No HttpServletResponse in object metadata, nothing to do");
            return;
        }
        for (Iterator i = additionalHeaders.getKeyValuePairs().iterator(); i.hasNext();) {
            KeyValuePair k = (KeyValuePair) i.next();
            response.addHeader(k.getKey(), k.getValue());
        }

        MetadataCollection metadataSubset = getMetadataFilter().filter(msg);
        for (MetadataElement me : metadataSubset) {
            response.addHeader(me.getKey(), me.getValue());
        }

        if (getContentTypeKey() != null && msg.containsKey(getContentTypeKey())) {
            response.setContentType(msg.getMetadataValue(getContentTypeKey()));
        }
        response.setStatus(getStatus(msg).getCode());
        if (sendPayload()) {
            if (getEncoder() != null) {
                getEncoder().writeMessage(msg, response);
            } else {
                if (msg.getSize() > 0) {
                    in = msg.getInputStream();
                    try {
                        StreamUtil.copyStream(in, response.getOutputStream());
                    } catch (IOException ioe) {
                        // if we catch an IOE here, chances are the connection is down and there isn't much we can do.
                        log.error(
                                "Cannot send the response, the connection appears to be down, either a timeout or the client has closed the connection.");
                        if (forwardConnectionExceptions())
                            throw ioe;
                    }
                }
            }
        } else {
            log.trace("Ignoring Payload");
        }
        if (flushBuffers()) {
            response.flushBuffer();
        }
        wrapper.setResponse(null);
    } catch (Exception e) {
        throw new ProduceException(e);
    } finally {
        IOUtils.closeQuietly(in);
        wrapper.unlock();
    }
}

From source file:org.craftercms.engine.http.impl.HttpProxyImpl.java

protected void copyActualResponseHeaders(HttpUriRequest httpRequest, HttpServletResponse response) {
    Header[] headers = httpRequest.getAllHeaders();
    for (Header header : headers) {
        String headerName = header.getName();
        String headerValue = header.getValue();

        if (!headerName.equals("Transfer-Encoding") && !header.equals("chunked")) {
            if (logger.isTraceEnabled()) {
                logger.trace(getRequestDescription(httpRequest) + " copying response header " + headerName
                        + ": " + headerValue);
            }//from w  ww  .  ja  v a  2  s.co m

            if (response.containsHeader(headerName)) {
                response.setHeader(headerName, headerValue);
            } else {
                response.addHeader(headerName, headerValue);
            }
        }
    }
}

From source file:com.ikon.servlet.admin.LanguageServlet.java

private void export(String userId, HttpServletRequest request, HttpServletResponse response)
        throws DatabaseException, IOException {
    log.debug("export({}, {}, {})", new Object[] { userId, request, response });
    String lgId = WebUtils.getString(request, "lg_id");
    Language language = LanguageDAO.findByPk(lgId);

    // 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 = "ikon_" + WarUtils.getAppVersion().getVersion() + "_" + language.getId() + ".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 ikon_TRANSLATION WHERE TR_LANGUAGE='" + language.getId() + "';");
    out.println("DELETE FROM ikon_LANGUAGE WHERE LG_ID='" + language.getId() + "';");
    StringBuffer insertLang = new StringBuffer(
            "INSERT INTO ikon_LANGUAGE (LG_ID, LG_NAME, LG_IMAGE_CONTENT, LG_IMAGE_MIME) VALUES ('");
    insertLang.append(language.getId()).append("', '");
    insertLang.append(language.getName()).append("', '");
    insertLang.append(language.getImageContent()).append("', '");
    insertLang.append(language.getImageMime()).append("');");
    out.println(insertLang);/*  ww w.j a va  2  s .  co m*/

    for (Translation translation : language.getTranslations()) {
        StringBuffer insertTranslation = new StringBuffer(
                "INSERT INTO ikon_TRANSLATION (TR_MODULE, TR_KEY, TR_TEXT, TR_LANGUAGE) VALUES (");
        insertTranslation.append("'");
        insertTranslation.append(translation.getTranslationId().getModule()).append("', '");
        insertTranslation.append(translation.getTranslationId().getKey()).append("', '");
        insertTranslation.append(translation.getText().replaceAll("'", "''")).append("', '"); // replace ' to '' in translation text
        insertTranslation.append(language.getId()).append("');");
        out.println(insertTranslation);
    }

    out.flush();
    log.debug("export: void");
}

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

private void export(String userId, HttpServletRequest request, HttpServletResponse response)
        throws DatabaseException, IOException {
    log.debug("export({}, {}, {})", new Object[] { userId, request, response });
    String lgId = WebUtils.getString(request, "lg_id");
    Language language = LanguageDAO.findByPk(lgId);

    // 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() + "_" + language.getId() + ".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_TRANSLATION WHERE TR_LANGUAGE='" + language.getId() + "';");
    out.println("DELETE FROM OKM_LANGUAGE WHERE LG_ID='" + language.getId() + "';");
    StringBuffer insertLang = new StringBuffer(
            "INSERT INTO OKM_LANGUAGE (LG_ID, LG_NAME, LG_IMAGE_CONTENT, LG_IMAGE_MIME) VALUES ('");
    insertLang.append(language.getId()).append("', '");
    insertLang.append(language.getName()).append("', '");
    insertLang.append(language.getImageContent()).append("', '");
    insertLang.append(language.getImageMime()).append("');");
    out.println(insertLang);//from  w  w  w.  j a  va2 s .  c om

    for (Translation translation : language.getTranslations()) {
        StringBuffer insertTranslation = new StringBuffer(
                "INSERT INTO OKM_TRANSLATION (TR_MODULE, TR_KEY, TR_TEXT, TR_LANGUAGE) VALUES (");
        insertTranslation.append("'");
        insertTranslation.append(translation.getTranslationId().getModule()).append("', '");
        insertTranslation.append(translation.getTranslationId().getKey()).append("', '");
        insertTranslation.append(translation.getText().replaceAll("'", "''")).append("', '"); // replace ' to '' in translation text
        insertTranslation.append(language.getId()).append("');");
        out.println(insertTranslation);
    }

    out.flush();
    log.debug("export: void");
}

From source file:com.nkapps.billing.controllers.ReportController.java

@RequestMapping(value = "/print-smst", method = RequestMethod.POST)
public void printSmst(HttpServletRequest request, HttpServletResponse response) throws Exception {
    HSSFWorkbook workbook = null;/*from   w  w  w  .  j a va2 s  .c o  m*/

    SimpleDateFormat sdf = new SimpleDateFormat("dd.MM.yyyy");
    Date periodStart = sdf.parse(request.getParameter("periodStart"));
    Date periodEnd = sdf.parse(request.getParameter("periodEnd"));

    List<ReportSmstListPojo> listPojo = reportService.getPrintSmstList(periodStart, periodEnd);
    workbook = reportPrintService.printSmst(listPojo);

    String fileName = new SimpleDateFormat("dd.MM.yyyy HH-mm-ss").format(Calendar.getInstance().getTime());
    response.setContentType("application/vnd.ms-excel");
    response.setHeader("Content-Disposition", "attachment; filename=\"" + fileName + ".xls\"");
    response.addHeader("Cache-Control", "max-age=1, must-revalidate");
    response.addHeader("Pragma", "no-cache");

    OutputStream stream = response.getOutputStream();
    workbook.write(stream);

}

From source file:co.cask.common.security.server.GrantAccessToken.java

private void grantToken(HttpServletRequest request, HttpServletResponse response, long tokenValidity)
        throws IOException, ServletException {

    String username = request.getUserPrincipal().getName();
    List<String> userGroups = Collections.emptyList();

    long issueTime = System.currentTimeMillis();
    long expireTime = issueTime + tokenValidity;
    // Create and sign a new AccessTokenIdentifier to generate the AccessToken.
    AccessTokenIdentifier tokenIdentifier = new AccessTokenIdentifier(username, userGroups, issueTime,
            expireTime);//from  w ww .  j a  v a 2  s.  c o m
    AccessToken token = tokenManager.signIdentifier(tokenIdentifier);
    LOG.debug("Issued token for user {}", username);

    // Set response headers
    response.setContentType("application/json;charset=UTF-8");
    response.addHeader("Cache-Control", "no-store");
    response.addHeader("Pragma", "no-cache");

    // Set response body
    JsonObject json = new JsonObject();
    byte[] encodedIdentifier = Base64.encodeBase64(tokenCodec.encode(token));
    json.addProperty(ExternalAuthenticationServer.ResponseFields.ACCESS_TOKEN,
            new String(encodedIdentifier, Charsets.UTF_8));
    json.addProperty(ExternalAuthenticationServer.ResponseFields.TOKEN_TYPE,
            ExternalAuthenticationServer.ResponseFields.TOKEN_TYPE_BODY);
    json.addProperty(ExternalAuthenticationServer.ResponseFields.EXPIRES_IN,
            TimeUnit.SECONDS.convert(tokenValidity, TimeUnit.MILLISECONDS));

    response.getOutputStream().print(json.toString());
    response.setStatus(HttpServletResponse.SC_OK);
}

From source file:co.cask.cdap.security.server.GrantAccessToken.java

private void grantToken(HttpServletRequest request, HttpServletResponse response, long tokenValidity)
        throws IOException, ServletException {

    String username = request.getUserPrincipal().getName();
    List<String> userGroups = Collections.emptyList();

    long issueTime = System.currentTimeMillis();
    long expireTime = issueTime + tokenValidity;
    // Create and sign a new AccessTokenIdentifier to generate the AccessToken.
    AccessTokenIdentifier tokenIdentifier = new AccessTokenIdentifier(username, userGroups, issueTime,
            expireTime);//from w  w w. ja  va 2  s . c  o m
    AccessToken token = tokenManager.signIdentifier(tokenIdentifier);
    LOG.debug("Issued token for user {}", username);

    // Set response headers
    response.setContentType("application/json;charset=UTF-8");
    response.addHeader(HttpHeaders.Names.CACHE_CONTROL, "no-store");
    response.addHeader(HttpHeaders.Names.PRAGMA, "no-cache");

    // Set response body
    JsonObject json = new JsonObject();
    byte[] encodedIdentifier = Base64.encodeBase64(tokenCodec.encode(token));
    json.addProperty(ExternalAuthenticationServer.ResponseFields.ACCESS_TOKEN,
            new String(encodedIdentifier, Charsets.UTF_8));
    json.addProperty(ExternalAuthenticationServer.ResponseFields.TOKEN_TYPE,
            ExternalAuthenticationServer.ResponseFields.TOKEN_TYPE_BODY);
    json.addProperty(ExternalAuthenticationServer.ResponseFields.EXPIRES_IN,
            TimeUnit.SECONDS.convert(tokenValidity, TimeUnit.MILLISECONDS));

    response.getOutputStream().print(json.toString());
    response.setStatus(HttpServletResponse.SC_OK);
}