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:it.govpay.web.console.pagamenti.gde.exporter.EventiExporter.java

private void processRequest(HttpServletRequest req, HttpServletResponse resp)
        throws ServletException, IOException {
    try {/*  w  w  w. j a  v a  2s  .c o m*/

        //         ApplicationContext context = WebApplicationContextUtils.getWebApplicationContext(getServletContext());

        //           service = (IEventiService)context.getBean("eventiService");

        //         EventiSearchForm sfInSession =    (EventiSearchForm)context.getBean("searchFormEventi");
        //         EventiSearchForm searchForm = (EventiSearchForm)sfInSession.clone();
        //         service.setForm(searchForm);

        // Then we have to get the Response where to write our file
        HttpServletResponse response = resp;

        String isAllString = req.getParameter("isAll");
        Boolean isAll = Boolean.parseBoolean(isAllString);
        String idtransazioni = req.getParameter("ids");
        String[] ids = StringUtils.split(idtransazioni, ",");
        String formato = req.getParameter("formato");

        String fileName = "Eventi.zip";

        response.setContentType("x-download");
        response.setHeader("Content-Disposition", "attachment; filename=" + fileName);
        response.addHeader("Cache-Control", "no-cache");
        response.setStatus(200);
        response.setBufferSize(1024);
        // committing status and headers
        response.flushBuffer();

        ExporterProperties prop = new ExporterProperties();
        prop.setEnableHeaderInfo(EventiExporter.enableHeaderInfo);
        prop.setFormatoExport(formato);
        prop.setMimeThrowExceptionIfNotFound(EventiExporter.mimeThrowExceptionIfNotFound);

        SingleFileExporter sfe = new SingleFileExporter(response.getOutputStream(), prop, service);

        if (isAll) {
            //transazioni = service.findAll(start, limit);
            sfe.export();
        } else {
            List<String> idEvento = new ArrayList<String>();
            for (int j = 0; j < ids.length; j++) {
                idEvento.add(ids[j]);
            }
            sfe.export(idEvento);
        }

    } catch (IOException se) {
        this.log.error(se, se);
        throw se;
    } catch (Exception e) {
        this.log.error(e, e);
        throw new ServletException(e);
    }
}

From source file:edu.umn.cs.spatialHadoop.nasa.ShahedServer.java

@Override
public void handle(String target, HttpServletRequest request, HttpServletResponse response, int dispatch)
        throws IOException, ServletException {
    // Bypass cross-site scripting (XSS)
    response.addHeader("Access-Control-Allow-Origin", "*");
    response.addHeader("Access-Control-Allow-Credentials", "true");
    ((Request) request).setHandled(true);

    try {/*from   w w w.  j a va  2s.  c o m*/
        LOG.info("Received request: '" + request.getRequestURL() + "'");
        if (target.endsWith("/generate_image.cgi")) {
            LOG.info("Generating image");
            // Start a background thread that handles the request
            new ImageRequestHandler(request).start();
            response.setStatus(HttpServletResponse.SC_OK);
            response.setContentType("text/plain;charset=utf-8");
            response.getWriter().println("Image request received successfully");
        } else if (target.endsWith("/aggregate_query.cgi")) {
            handleAggregateQuery(request, response);
            LOG.info("Aggregate query results returned");
        } else if (target.endsWith("/selection_query.cgi")) {
            handleSelectionQuery(request, response);
            LOG.info("Selection query results returned");
        } else {
            if (target.equals("/"))
                target = "/index.html";
            tryToLoadStaticResource(target, response);
        }
    } catch (Exception e) {
        e.printStackTrace();
        reportError(response, "Error placing the request", e);
    }
}

From source file:org.energyos.espi.datacustodian.web.api.BatchRESTController.java

/**
 * Produce a Subscription for the requester. The resultant response will
 * contain a <feed> of the Usage Point(s) associated with the subscription.
 * //  w  w  w . java 2  s. co  m
 * Requires Authorization: Bearer [{data_custodian_access_token} |
 * {access_token}]
 * 
 * @param response
 *            HTTP Servlet Response
 * @param subscriptionId
 *            Long identifying the Subscription.id of the desired
 *            Authorization
 * @param params
 *            HTTP Query Parameters
 * @throws IOException
 * @throws FeedException
 * 
 * @usage GET /espi/1_1/resource/Batch/Subscription/{subscriptionId}
 */
@Transactional(readOnly = true)
@RequestMapping(value = Routes.BATCH_SUBSCRIPTION, method = RequestMethod.GET, produces = "application/atom+xml")
@ResponseBody
public void subscription(HttpServletResponse response, @PathVariable Long subscriptionId,
        @RequestParam Map<String, String> params) throws IOException, FeedException {

    response.setContentType(MediaType.APPLICATION_ATOM_XML_VALUE);
    response.addHeader("Content-Disposition", "attachment; filename=GreenButtonDownload.xml");
    try {
        exportService.exportBatchSubscription(subscriptionId, response.getOutputStream(),
                new ExportFilter(params));

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

}

From source file:org.energyos.espi.datacustodian.web.api.BatchRESTController.java

/**
 * Produce a Subscription for the requester. The resultant response will
 * contain a <feed> of the Usage Point(s) associated with the subscription.
 * //  ww  w.  j  a  v  a 2s .co m
 * Requires Authorization: Bearer [{data_custodian_access_token} |
 * {access_token}]
 * 
 * @param response
 *            HTTP Servlet Response
 * @param subscriptionId
 *            Long identifying the Subscription.id of the desired
 *            Authorization
 * @param params
 *            HTTP Query Parameters
 * @throws IOException
 * @throws FeedException
 * 
 * @usage GET
 *        /espi/1_1/resource/Batch/Subscription/{subscriptionId}/UsagePoint
 */
@Transactional(readOnly = true)
@RequestMapping(value = Routes.BATCH_SUBSCRIPTION_USAGEPOINT, method = RequestMethod.GET, produces = "application/atom+xml")
@ResponseBody
public void subscriptionUsagePoint(HttpServletResponse response, @PathVariable Long subscriptionId,
        @RequestParam Map<String, String> params) throws IOException, FeedException {

    response.setContentType(MediaType.APPLICATION_ATOM_XML_VALUE);
    response.addHeader("Content-Disposition", "attachment; filename=GreenButtonDownload.xml");
    try {
        exportService.exportBatchSubscriptionUsagePoint(subscriptionId, response.getOutputStream(),
                new ExportFilter(params));

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

}

From source file:org.energyos.espi.datacustodian.web.api.BatchRESTController.java

/**
 * Supports Green Button Download My Data - A DMD file will be produced that
 * contains all Usage Points for the requested Retail Customer.
 * /*w  w w  .  ja  va  2 s  .c  om*/
 * Requires Authorization: Bearer [{data_custodian_access_token} |
 * {upload_access_token}]
 * 
 * @param response
 *            HTTP Servlet Response
 * @param retailCustomerId
 *            The locally unique identifier of a Retail Customer - NOTE PII
 * @param HTTP
 *            Query Parameters
 * @throws IOException
 * @throws FeedException
 * 
 * @usage GET
 *        /espi/1_1/resource/Batch/RetailCustomer/{retailCustomerId}/UsagePoint
 */
@RequestMapping(value = Routes.BATCH_DOWNLOAD_MY_DATA_COLLECTION, method = RequestMethod.GET, produces = "application/atom+xml")
@ResponseBody
public void download_collection(HttpServletResponse response, @PathVariable Long retailCustomerId,
        @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.exportUsagePointsFull(0L, retailCustomerId, response.getOutputStream(),
                new ExportFilter(params));

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

}

From source file:com.maogousoft.wuliu.controller.DriverController.java

public void exportExcel() throws IOException {
    StringBuffer from = new StringBuffer();
    from.append("from logistics_driver where status = 1 ");
    from.append(createOrder());/*from   w w  w  .ja  v  a2  s . co  m*/
    Page<Record> page = Db.paginate(getPageIndex(), 100000, "select * ", from.toString());
    List<Record> list = page.getList();
    Dict.fillDictToRecords(page.getList());

    String headers = "?|?|??|??|?|??|||?|??||?|??|?|??|?";
    String attributes = "id|phone|name|recommender|plate_number|id_card|car_type_str|car_length|car_weight|gold|regist_time|car_phone|start_province_str|start_city_str|end_province_str|end_city_str";

    Workbook wb = new HSSFWorkbook();
    Sheet sheet = wb.createSheet();
    Row headerRow = sheet.createRow(0);
    List<String> headerList = WuliuStringUtils.parseVertical(headers);
    for (int j = 0; j < headerList.size(); j++) {
        String attr = headerList.get(j);
        Cell cell = headerRow.createCell(j);
        cell.setCellValue(attr);
    }

    for (int i = 0; i < list.size(); i++) {
        Record record = list.get(i);
        Row row = sheet.createRow(i + 1);

        List<String> attrList = WuliuStringUtils.parseVertical(attributes);
        for (int j = 0; j < attrList.size(); j++) {
            String attr = attrList.get(j);
            Cell cell = row.createCell(j);
            Object value = getValue(record, attr);
            cell.setCellValue(value + "");
        }
    }

    HttpServletResponse resp = getResponse();
    String filename = TimeUtil.format(new Date(), "'?'yyyyMMdd_HHmmss'.xls'");
    resp.addHeader("Content-Disposition",
            "attachment;filename=" + new String(filename.getBytes("GBK"), "ISO-8859-1"));
    ServletOutputStream out = resp.getOutputStream();
    wb.write(out);
    out.close();
    renderNull();
}

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

@RequestMapping(method = GET, value = "/document/{id}")
public void getDocument(@PathVariable("id") Long id, HttpServletResponse response) {
    try {/*from w  ww. j a v a2  s . com*/
        PhysicalDocument document = documentService.findPhysicalDocument(id);

        final Authentication authentication = SecurityContextHolder.getContext().getAuthentication();
        String username = (authentication != null) ? ((User) authentication.getPrincipal()).getUsername()
                : "anonymous";
        statisticsService.registerDocumentReferenceClick(String.valueOf(id), username);

        response.setStatus(SC_OK);
        response.addHeader("Content-Type", document.getMimeType());
        response.addHeader("Content-Disposition", "inline; filename=\"" + document.getFileName() + "\"");
        response.getOutputStream().write(document.getContent());
        response.getOutputStream().flush();
    } catch (DocumentNotFoundException | DocumentNotInStoreException e) {
        logger.warn("Document with id '{}' not found", id, e);
        response.setStatus(SC_NOT_FOUND);
    } catch (AccessDeniedException ade) {
        logger.warn("Access denied on document {}", id, ade);
        response.setStatus(SC_FORBIDDEN);
    } catch (IOException e) {
        logger.error("Could not write document to output stream", e);
        response.setStatus(SC_INTERNAL_SERVER_ERROR);
    }
}

From source file:com.jd.survey.web.surveys.SurveyController.java

@Secured({ "ROLE_ADMIN", "ROLE_SURVEY_ADMIN" })
@RequestMapping(value = "/doc/{Id}", produces = "text/html")
public void getQuestionDocument(@PathVariable("Id") Long surveyDocumentId, Principal principal,
        HttpServletResponse response) {
    try {/*from  w  w  w  .j a va2 s  .co  m*/
        SurveyDocument surveyDocument = surveyService.surveyDocumentDAO_findById(surveyDocumentId);

        response.setContentType(surveyDocument.getContentType());
        // Set standard HTTP/1.1 no-cache headers.
        response.setHeader("Cache-Control", "no-store, no-cache,must-revalidate");
        // Set IE extended HTTP/1.1 no-cache headers (use addHeader).
        response.addHeader("Cache-Control", "post-check=0, pre-check=0");
        // Set standard HTTP/1.0 no-cache header.
        response.setHeader("Pragma", "no-cache");
        response.setHeader("Content-Disposition", "inline;filename=" + surveyDocument.getFileName());
        ServletOutputStream servletOutputStream = response.getOutputStream();
        servletOutputStream.write(surveyDocument.getContent());
        servletOutputStream.flush();
    } catch (Exception e) {
        log.error(e.getMessage(), e);
        throw (new RuntimeException(e));
    }
}

From source file:io.mapzone.controller.vm.http.HttpResponseForwarder.java

/** 
 * Copy proxied response headers back to the servlet client. 
 *//*from w  ww  .  jav a 2  s.c o m*/
protected void copyResponseHeaders(HttpResponse proxyResponse, HttpServletRequest servletRequest,
        HttpServletResponse servletResponse) {
    for (Header header : proxyResponse.getAllHeaders()) {
        if (hopByHopHeaders.containsHeader(header.getName())) {
            continue;
        } else if (header.getName().equalsIgnoreCase(org.apache.http.cookie.SM.SET_COOKIE)
                || header.getName().equalsIgnoreCase(org.apache.http.cookie.SM.SET_COOKIE2)) {
            copyProxyCookie(servletRequest, servletResponse, header);
        } else {
            servletResponse.addHeader(header.getName(), header.getValue());
        }
    }
}

From source file:jp.go.nict.langrid.servicecontainer.handler.jsonrpc.servlet.JsonRpcServlet.java

private void doProcess(HttpServletRequest request, HttpServletResponse resp)
        throws ServletException, IOException {
    for (String[] h : additionalResponseHeaders) {
        resp.addHeader(h[0], h[1]);
    }// w ww  . j  ava2  s  .c  o  m
    resp.setCharacterEncoding("UTF-8");

    String serviceName = getServiceName(request);

    JsonRpcRequest req = null;
    if (request.getMethod().equals("GET")) {
        req = decodeFromPC(new URLParameterContext(request.getQueryString()));
    } else {
        req = JSON.decode(StreamUtil.readAsString(request.getInputStream(), "UTF-8"), JsonRpcRequest.class);
        String cb = request.getParameter("callback");
        if (cb != null) {
            req.setCallback(cb);
        }
        if (req.getHeaders() == null) {
            req.setHeaders(new RpcHeader[] {});
        }
    }
    // The handler is acquired from the service name.
    JsonRpcHandler h = handlers.get(serviceName);
    // Execution of service
    if (h == null) {
        h = new JsonRpcDynamicHandler();
    }
    ServiceContext sc = new ServletServiceContext(getServletConfig(), request, Arrays.asList(req.getHeaders()));
    ServiceLoader loader = new ServiceLoader(sc, defaultLoaders);
    OutputStream os = resp.getOutputStream();
    h.handle(sc, loader, serviceName, req, resp, os);
    os.flush();
}