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:csiro.pidsvc.servlet.info.java

/**
 * @see HttpServlet#doGet(HttpServletRequest request, HttpServletResponse
 *     response)//from  www.  j a v a  2 s .  com
 */
protected void doGet(HttpServletRequest request, HttpServletResponse response)
        throws ServletException, IOException {
    response.setDateHeader("Expires", 0);
    response.addHeader("Cache-Control",
            "no-cache,no-store,private,must-revalidate,max-stale=0,post-check=0,pre-check=0");

    String cmd = request.getParameter("cmd");
    if (cmd == null || cmd.isEmpty())
        return;

    ManagerJson mgr = null;
    JSONObject ret;
    try {
        Settings.init(this);
        mgr = new ManagerJson(request);

        response.setContentType("application/json");

        _logger.info("Processing \"{}\" command -> {}?{}", cmd, request.getRequestURL(),
                request.getQueryString());
        if (cmd.equalsIgnoreCase("search")) {
            int page = 1;
            String sPage = request.getParameter("page");
            if (sPage != null && sPage.matches("\\d+"))
                page = Integer.parseInt(sPage);

            ret = mgr.getMappings(page, request.getParameter("mapping"), request.getParameter("type"),
                    request.getParameter("creator"), Literals.toInt(request.getParameter("deprecated"), 0));
            response.getWriter().write(ret == null ? null : ret.toString());
        } else if (cmd.equalsIgnoreCase("get_pid_config")) {
            int mappingId = Literals.toInt(request.getParameter("mapping_id"), -1);
            String mappingPath = request.getParameter("mapping_path");

            ret = mappingId > 0 ? mgr.getPidConfig(mappingId)
                    : (mappingId == 0 ? mgr.getPidConfig((String) null) : mgr.getPidConfig(mappingPath));
            response.getWriter().write(ret == null ? null : ret.toString());
        } else if (cmd.equalsIgnoreCase("check_mapping_path_exists")) {
            response.getWriter()
                    .write(mgr.checkMappingPathExists(request.getParameter("mapping_path")).toString());
        } else if (cmd.equalsIgnoreCase("search_parent")) {
            int mappingId = Literals.toInt(request.getParameter("mapping_id"), -1);
            response.getWriter()
                    .write(mgr.searchParentMapping(mappingId, request.getParameter("q")).toString());
        } else if (cmd.equalsIgnoreCase("get_settings"))
            response.getWriter().write(mgr.getSettings().toString());
        else if (cmd.equalsIgnoreCase("search_condition_set")) {
            int page = 1;
            String sPage = request.getParameter("page");
            if (sPage != null && sPage.matches("\\d+"))
                page = Integer.parseInt(sPage);

            ret = mgr.getConditionSets(page, request.getParameter("q"));
            response.getWriter().write(ret == null ? null : ret.toString());
        } else if (cmd.equalsIgnoreCase("get_condition_set_config")) {
            String name = request.getParameter("name");
            ret = mgr.getConditionSetConfig(name);
            response.getWriter().write(ret == null ? null : ret.toString());
        } else if (cmd.equalsIgnoreCase("search_lookup")) {
            int page = 1;
            String sPage = request.getParameter("page");
            if (sPage != null && sPage.matches("\\d+"))
                page = Integer.parseInt(sPage);

            ret = mgr.getLookups(page, request.getParameter("ns"));
            response.getWriter().write(ret == null ? null : ret.toString());
        } else if (cmd.equalsIgnoreCase("get_lookup_config")) {
            String ns = request.getParameter("ns");
            ret = mgr.getLookupConfig(ns);
            response.getWriter().write(ret == null ? null : ret.toString());
        } else if (cmd.equalsIgnoreCase("get_manifest")) {
            response.getWriter().write(Settings.getInstance().getManifestJson().toString());
        } else if (cmd.equalsIgnoreCase("is_new_version_available")) {
            response.getWriter().write(Settings.getInstance().isNewVersionAvailableJson().toString());
        } else if (cmd.equalsIgnoreCase("global_js")) {
            response.setContentType("text/javascript");
            response.getWriter()
                    .write("var GlobalSettings = " + mgr.getGlobalSettings(request).toString() + ";");
        } else if (cmd.equalsIgnoreCase("chart")) {
            ret = mgr.getChart();
            response.getWriter().write(ret == null ? null : ret.toString());
        } else if (cmd.equalsIgnoreCase("get_mapping_dependencies")) {
            int mappingId = Literals.toInt(request.getParameter("mapping_id"), -1);
            String mappingPath = request.getParameter("mapping_path");
            String inputJson = request.getParameter("json");
            JSONObject jsonThis = (JSONObject) (new JSONParser()).parse(inputJson);

            if (mappingPath != null && mappingPath.isEmpty())
                mappingPath = null;
            if (jsonThis != null && jsonThis.isEmpty())
                jsonThis = null;
            ret = mgr.getMappingDependencies((Object) (jsonThis == null ? mappingId : jsonThis), mappingPath);
            response.getWriter()
                    .write(mappingId == -1 && jsonThis == null || ret == null ? "{}" : ret.toString());
        } else if (cmd.equalsIgnoreCase("echo")) {
            echo(request, response);
        }
    } catch (Exception e) {
        _logger.error(e);
        Http.returnErrorCode(response, HttpServletResponse.SC_INTERNAL_SERVER_ERROR, e);
    } finally {
        if (mgr != null)
            mgr.close();
    }
}

From source file:be.fedict.eid.pkira.blm.model.reporting.ReportConfigurationHandler.java

public void generateReport() {
    if (StringUtils.isBlank(startMonth) || StringUtils.isBlank(endMonth)) {
        return;/*from  ww  w .ja va 2s  . c om*/
    }

    if (startMonth.compareTo(endMonth) > 0) {
        facesMessages.addFromResourceBundle(Severity.ERROR, "reports.startAfterEnd");
        return;
    }

    HttpServletResponse response = (HttpServletResponse) externalContext.getResponse();
    response.setContentType("test/xml");
    String fileName = (StringUtils.equals(startMonth, endMonth) ? startMonth : startMonth + " - " + endMonth)
            + ".xml\"";
    response.addHeader("Content-disposition", "attachment; filename=\"" + fileName);

    String report = reportManager.generateReport(startMonth, endMonth, includeCertificateAuthorityReport,
            includeCertificateDomainReport);

    try {
        ServletOutputStream servletOutputStream = response.getOutputStream();
        servletOutputStream.write(report.getBytes());
        servletOutputStream.flush();
        servletOutputStream.close();
    } catch (IOException e) {
        throw new RuntimeException(e);
    }
    facesContext.responseComplete();
}

From source file:org.energyos.espi.thirdparty.web.BatchRESTController.java

@RequestMapping(value = Routes.BATCH_DOWNLOAD_MY_DATA_MEMBER, method = RequestMethod.GET, produces = "application/atom+xml")
@ResponseBody//  www . j a  v a 2  s  .com
public void download_member(HttpServletResponse response, @PathVariable Long retailCustomerId,
        @PathVariable Long usagePointId, @RequestParam Map<String, String> params)
        throws IOException, FeedException {

    response.setContentType(MediaType.APPLICATION_ATOM_XML_VALUE);
    response.addHeader("Content-Disposition", "attachment; filename=GreenButtonDownload.xml");
    try {

        // TODO -- need authorization hook
        exportService.exportUsagePointFull(0L, retailCustomerId, usagePointId, response.getOutputStream(),
                new ExportFilter(params));

    } catch (Exception e) {
        response.setStatus(HttpServletResponse.SC_BAD_REQUEST);
    }

}

From source file:com.tasktop.c2c.server.web.proxy.HttpProxy.java

private void copyProxyHeaders(Header[] headers, HttpServletResponse response) {
    for (Header h : headers) {
        String header = h.getName();
        String valR = headerFilter.processResponseHeader(header, h.getValue());
        if (valR != null) {
            response.addHeader(header, valR);
        }/* w  w w  .j av a 2  s .  c o m*/
    }
}

From source file:csiro.pidsvc.servlet.controller.java

/**
 * @see HttpServlet#doGet(HttpServletRequest request, HttpServletResponse
 *     response)/*from w  w w  . j a v a 2s.  com*/
 */
protected void doGet(HttpServletRequest request, HttpServletResponse response)
        throws ServletException, IOException {
    response.setDateHeader("Expires", 0);
    response.addHeader("Cache-Control",
            "no-cache,no-store,private,must-revalidate,max-stale=0,post-check=0,pre-check=0");

    String cmd = request.getParameter("cmd");
    if (cmd == null || cmd.isEmpty())
        return;

    ManagerJson mgr = null;
    try {
        mgr = new ManagerJson();

        _logger.info("Processing \"{}\" command -> {}?{}.", cmd, request.getRequestURL(),
                request.getQueryString());
        if (cmd.matches("(?i)^(?:full|partial)_export$")) {
            int mappingId = Literals.toInt(request.getParameter("mapping_id"), -1);
            String mappingPath = request.getParameter("mapping_path");
            String outputFormat = request.getParameter("format");
            String serializedConfig = mappingId > 0 ? mgr.exportMapping(mappingId)
                    : (mappingId == 0 ? mgr.exportCatchAllMapping(cmd.startsWith("full"))
                            : mgr.exportMapping(mappingPath, cmd.startsWith("full")));

            // Check output format.
            outputFormat = outputFormat != null && outputFormat.matches("(?i)^xml$") ? "xml" : "psb";

            returnAttachment(response,
                    "mapping." + (cmd.startsWith("full") ? "full" : "partial") + "."
                            + _sdfBackupStamp.format(new Date()) + "." + outputFormat,
                    outputFormat, serializedConfig);
        } else if (cmd.matches("(?i)^(?:full|partial)_backup$")) {
            String includeDeprecated = request.getParameter("deprecated");
            String includeConditionSets = request.getParameter("conditionsets");
            String includeLookupMaps = request.getParameter("lookup");
            String outputFormat = request.getParameter("format");
            String serializedConfig = mgr.backupDataStore(cmd.startsWith("full"),
                    includeDeprecated != null && includeDeprecated.equalsIgnoreCase("true"),
                    includeConditionSets == null || includeConditionSets.equalsIgnoreCase("true"),
                    includeLookupMaps == null || includeLookupMaps.equalsIgnoreCase("true"));

            // Check output format.
            outputFormat = outputFormat != null && outputFormat.matches("(?i)^xml$") ? "xml" : "psb";

            returnAttachment(response,
                    "backup." + (cmd.startsWith("full") ? "full" : "partial") + "."
                            + _sdfBackupStamp.format(new Date()) + "." + outputFormat,
                    outputFormat, serializedConfig);
        } else if (cmd.matches("(?i)export_lookup$")) {
            String ns = request.getParameter("ns");
            String outputFormat = request.getParameter("format");
            String serializedConfig = mgr.exportLookup(ns);

            // Check output format.
            outputFormat = outputFormat != null && outputFormat.matches("(?i)^xml$") ? "xml" : "psl";

            returnAttachment(response, "lookup." + (ns == null ? "backup." : "")
                    + _sdfBackupStamp.format(new Date()) + "." + outputFormat, outputFormat, serializedConfig);
        } else if (cmd.matches("(?i)export_condition_set$")) {
            String name = request.getParameter("name");
            String outputFormat = request.getParameter("format");
            String serializedConfig = mgr.exportConditionSet(name);

            // Check output format.
            outputFormat = outputFormat != null && outputFormat.matches("(?i)^xml$") ? "xml" : "psb";

            returnAttachment(
                    response, "conditionSet." + (name == null ? "backup." : "")
                            + _sdfBackupStamp.format(new Date()) + "." + outputFormat,
                    outputFormat, serializedConfig);
        }
    } catch (Exception e) {
        _logger.error(e);
        Http.returnErrorCode(response, HttpServletResponse.SC_INTERNAL_SERVER_ERROR, e);
    } finally {
        if (mgr != null)
            mgr.close();
    }
}

From source file:org.appverse.web.framework.backend.frontfacade.rest.authentication.basic.services.presentation.BasicAuthenticationServiceImpl.java

/**
 * Authenticates an user. Requires basic authentication header.
 * @param httpServletRequest/*  ww  w.j  a va2s .  co  m*/
 * @param httpServletResponse
 * @return
 * @throws Exception
 */
@RequestMapping(value = "${appverse.frontfacade.rest.basicAuthenticationEndpoint.path:/sec/login}", method = RequestMethod.POST)
public ResponseEntity<AuthorizationData> login(@RequestHeader("Authorization") String authorizationHeader,
        HttpServletRequest httpServletRequest, HttpServletResponse httpServletResponse) throws Exception {

    String[] userNameAndPassword;

    try {
        userNameAndPassword = obtainUserAndPasswordFromBasicAuthenticationHeader(httpServletRequest);
    } catch (BadCredentialsException e) {
        httpServletResponse.addHeader("WWW-Authenticate", "Basic");
        return new ResponseEntity<AuthorizationData>(HttpStatus.UNAUTHORIZED);
    }

    if (securityEnableCsrf) {
        // Obtain XSRFToken and add it as a response header
        // The token comes in the request (CsrFilter adds it) and we need to set it in the response so the clients 
        // have it to use it in the next requests
        CsrfToken csrfToken = (CsrfToken) httpServletRequest.getAttribute(CSRF_TOKEN_SESSION_ATTRIBUTE);
        httpServletResponse.addHeader(csrfToken.getHeaderName(), csrfToken.getToken());
    }

    try {
        // Authenticate principal and return authorization data
        AuthorizationData authData = userAndPasswordAuthenticationManager
                .authenticatePrincipal(userNameAndPassword[0], userNameAndPassword[1]);
        // AuthorizationDataVO
        return new ResponseEntity<AuthorizationData>(authData, HttpStatus.OK);
    } catch (AuthenticationException e) {
        httpServletResponse.addHeader("WWW-Authenticate", "Basic");
        return new ResponseEntity<AuthorizationData>(HttpStatus.UNAUTHORIZED);
    }
}

From source file:com.java2s.SendFilter.java

public void doFilter(ServletRequest request, ServletResponse response, FilterChain chain)
        throws java.io.IOException, ServletException {

    //get the file name from the 'file' parameter
    String fileName = request.getParameter("file");
    if (fileName == null || fileName.equals(""))
        throw new ServletException("Invalid or non-existent file parameter in SendPdf component.");

    if (fileName.indexOf(".pdf") == -1)
        fileName = fileName + ".pdf";

    ServletOutputStream stream = null;/*from  w w  w . j a  v a 2  s  .c om*/
    BufferedInputStream buf = null;
    HttpServletResponse httpResp = null;
    try {

        httpResp = (HttpServletResponse) response;
        stream = httpResp.getOutputStream();
        File pdf = new File(PDF_DIR + "/" + fileName);

        //set response headers
        httpResp.setContentType(PDF_CONTENT_TYPE);
        httpResp.addHeader("Content-Disposition", "attachment; filename=" + fileName);
        httpResp.setContentLength((int) pdf.length());

        FileInputStream input = new FileInputStream(pdf);
        buf = new BufferedInputStream(input);
        int readBytes = 0;
        //read from the file; write to the ServletOutputStream
        while ((readBytes = buf.read()) != -1)
            stream.write(readBytes);

    } catch (Exception ioe) {

        //  throw new ServletException(ioe.getMessage());
        System.out.println(ioe.getMessage());

    } finally {

        if (buf != null)
            buf.close();
        if (stream != null) {
            stream.flush();
            //stream.close();
        }

    } //end finally
    chain.doFilter(request, httpResp);
}

From source file:com.migo.controller.SysGeneratorController.java

/**
 * ??//from  w  w  w  . j a v  a2  s  . co  m
 */
@SysLog("??")
@RequestMapping("/code")
@RequiresPermissions("sys:generator:code")
public void code(String tables, HttpServletResponse response) throws IOException {
    String[] tableNames = new String[] {};
    tableNames = JSON.parseArray(tables).toArray(tableNames);

    byte[] data = sysGeneratorService.generatorCode(tableNames);

    response.reset();
    response.setHeader("Content-Disposition", "attachment; filename=\"migo.zip\"");
    response.addHeader("Content-Length", "" + data.length);
    response.setContentType("application/octet-stream; charset=UTF-8");

    IOUtils.write(data, response.getOutputStream());
}

From source file:com.hyeb.back.authenticate.AuthenticationFilter.java

@Override
protected boolean onAccessDenied(ServletRequest servletRequest, ServletResponse servletResponse)
        throws Exception {
    HttpServletRequest request = (HttpServletRequest) servletRequest;
    HttpServletResponse response = (HttpServletResponse) servletResponse;
    String requestType = request.getHeader("X-Requested-With");
    if (requestType != null && requestType.equalsIgnoreCase("XMLHttpRequest")) {
        response.addHeader("loginStatus", "accessDenied");
        response.sendError(HttpServletResponse.SC_FORBIDDEN);
        return false;
    }/* w  w  w  .  j a v a2  s  . co  m*/
    return super.onAccessDenied(request, response);
}

From source file:com.sample.RSSAdapterResource.java

public void execute(HttpUriRequest req, HttpServletResponse resultResponse)
        throws ClientProtocolException, IOException, IllegalStateException, SAXException {
    HttpResponse RSSResponse = client.execute(host, req);
    ServletOutputStream os = resultResponse.getOutputStream();
    if (RSSResponse.getStatusLine().getStatusCode() == HttpStatus.SC_OK) {
        resultResponse.addHeader("Content-Type", "application/json");
        String json = XML.toJson(RSSResponse.getEntity().getContent());
        os.write(json.getBytes(Charset.forName("UTF-8")));

    } else {//ww  w.  j  a v a 2s  .  c o  m
        resultResponse.setStatus(RSSResponse.getStatusLine().getStatusCode());
        RSSResponse.getEntity().getContent().close();
        os.write(RSSResponse.getStatusLine().getReasonPhrase().getBytes());
    }
    os.flush();
    os.close();
}