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.cilea.osd.jdyna.web.flow.GestioneAlberoDTO.java

public Event export(RequestContext context) throws Exception {

    DTOGestioneAlberoClassificatore alberoDTO = (DTOGestioneAlberoClassificatore) getFormObject(context);
    ServletExternalContext externalContext = (ServletExternalContext) context.getExternalContext();
    HttpServletResponse response = externalContext.getResponse();

    Integer alberoID = alberoDTO.getId();
    AlberoClassificatorio albero = null;
    if (alberoID != null) {
        albero = applicationService.get(AlberoClassificatorio.class, alberoID);
    }/* w  w  w  .j a v a 2 s . c om*/

    String filename;

    filename = "configurazione-albero_classificatorio_" + albero.getNome().replaceAll(" ", "_") + ".xml";

    response.setContentType("application/xml");
    response.addHeader("Content-Disposition", "attachment; filename=" + filename);

    PrintWriter writer = response.getWriter();
    exportUtils.writeDocTypeANDCustomEditorAlberoClassificatore(writer);

    if (albero != null) {
        exportUtils.alberoClassificatorioToXML(writer, albero);
    }

    response.getWriter().print("</beans>");
    response.flushBuffer();
    return success();
}

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

/**
 * /*from ww w . j  a v  a 2  s .c  om*/
 * @description ? 
 * @author shevliu
 * @email shevliu@gmail.com
 * 201386 ?11:47:19
 * @throws IOException
 */
public void exportPendingAudit() throws IOException {
    StringBuffer from = new StringBuffer();
    from.append("from logistics_driver where status = 0 ");
    from.append(createOrder());
    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:net.acesinc.convergentui.BaseFilter.java

protected void addResponseHeaders() {
    RequestContext context = RequestContext.getCurrentContext();
    HttpServletResponse servletResponse = context.getResponse();
    List<Pair<String, String>> zuulResponseHeaders = context.getZuulResponseHeaders();
    @SuppressWarnings("unchecked")
    List<String> rd = (List<String>) RequestContext.getCurrentContext().get("routingDebug");
    if (rd != null) {
        StringBuilder debugHeader = new StringBuilder();
        for (String it : rd) {
            debugHeader.append("[[[" + it + "]]]");
        }//from   w  w  w . j  a va2s  .c om
        if (INCLUDE_DEBUG_HEADER.get()) {
            servletResponse.addHeader("X-Zuul-Debug-Header", debugHeader.toString());
        }
    }
    if (zuulResponseHeaders != null) {
        for (Pair<String, String> it : zuulResponseHeaders) {
            servletResponse.addHeader(it.first(), it.second());
        }
    }
    RequestContext ctx = RequestContext.getCurrentContext();
    Integer contentLength = ctx.getOriginContentLength();
    // Only inserts Content-Length if origin provides it and origin response is not
    // gzipped
    if (SET_CONTENT_LENGTH.get()) {
        if (contentLength != null && !ctx.getResponseGZipped()) {
            servletResponse.setContentLength(contentLength);
        }
    }
}

From source file:info.rmapproject.webapp.controllers.ApiKeyController.java

/**
 * GET API Key file containing AccessKey and Secret that can be used for API requests.
 *
 * @param keyId the key id/*w w w .j  a  v  a  2  s  .  c  o  m*/
 * @param response the HTTP Response
 * @param session the HTTP session
 * @throws Exception the exception
 */
@LoginRequired
@RequestMapping(value = "/user/key/download", method = RequestMethod.GET)
public @ResponseBody void downloadKey(@RequestParam("keyid") Integer keyId, HttpServletResponse response,
        HttpSession session) throws Exception {
    User user = (User) session.getAttribute("user"); //retrieve logged in user
    ApiKey apiKey = this.userMgtService.getApiKeyById(keyId);
    if (apiKey.getUserId() == user.getUserId()) {
        String downloadFileName = "rmap.key";
        String key = apiKey.getAccessKey() + ":" + apiKey.getSecret();
        OutputStream out = response.getOutputStream();
        response.setContentType("text/plain; charset=utf-8");
        response.addHeader("Content-Disposition", "attachment; filename=\"" + downloadFileName + "\"");
        out.write(key.getBytes(Charset.forName("UTF-8")));
        out.flush();
        out.close();
    }

}

From source file:com.coinblesk.server.controller.UserController.java

@RequestMapping(value = "/login", method = POST, consumes = APPLICATION_JSON_UTF8_VALUE, produces = APPLICATION_JSON_UTF8_VALUE)
public ResponseEntity<?> login(@Valid @RequestBody LoginDTO loginDTO, HttpServletResponse response) {

    UsernamePasswordAuthenticationToken authenticationToken = new UsernamePasswordAuthenticationToken(
            loginDTO.getUsername().toLowerCase(Locale.ENGLISH), loginDTO.getPassword());

    try {/*  w ww  . ja v  a2s  .com*/
        Authentication authentication = this.authenticationManager.authenticate(authenticationToken);
        SecurityContextHolder.getContext().setAuthentication(authentication);

        String jwt = tokenProvider.createToken(authentication);
        response.addHeader(JWTConfigurer.AUTHORIZATION_HEADER, "Bearer " + jwt);

        return ResponseEntity.ok(Collections.singletonMap("token", jwt));
    } catch (AuthenticationException exception) {
        return new ResponseEntity<>(
                Collections.singletonMap("AuthenticationException", exception.getLocalizedMessage()),
                HttpStatus.UNAUTHORIZED);
    }
}

From source file:com.mmj.app.web.controller.user.UserController.java

@RequestMapping(value = "/gozapIdentifyCode")
public ModelAndView gozapIdentifyCode(String t, HttpServletRequest request, HttpServletResponse response) {

    response.setContentType("image/png; charset=utf-8");
    response.setHeader("Pragma", "no-cache");
    response.setHeader("Cache-Control",
            "private, must-revalidate,no-store, no-cache, must-revalidate,post-check=0, pre-check=0");
    response.addHeader("Content-Disposition", "attachment; filename=\"" + "gozapIdentifyCode" + "\"");
    response.setCharacterEncoding("UTF-8");

    final byte[] bytes = WebsiteCheckCodeManager.INSTANCE.create(CookieManagerLocator.get(request, response),
            response);//  w w w  .  j  av  a 2  s  . c o  m

    OutputStream os;
    try {
        os = response.getOutputStream();
        IOUtils.write(bytes, os);
        response.flushBuffer();
    } catch (IOException e) {
        e.printStackTrace();
    }
    return null;
}

From source file:de.codecentric.boot.admin.zuul.filters.post.SendResponseFilter.java

private void addResponseHeaders() {
    RequestContext context = RequestContext.getCurrentContext();
    HttpServletResponse servletResponse = context.getResponse();
    List<Pair<String, String>> zuulResponseHeaders = context.getZuulResponseHeaders();
    @SuppressWarnings("unchecked")
    List<String> rd = (List<String>) RequestContext.getCurrentContext().get("routingDebug");
    if (rd != null) {
        StringBuilder debugHeader = new StringBuilder();
        for (String it : rd) {
            debugHeader.append("[[[" + it + "]]]");
        }/*from   ww w.  jav  a 2 s.  co  m*/
        if (INCLUDE_DEBUG_HEADER.get()) {
            servletResponse.addHeader("X-Zuul-Debug-Header", debugHeader.toString());
        }
    }
    if (zuulResponseHeaders != null) {
        for (Pair<String, String> it : zuulResponseHeaders) {
            servletResponse.addHeader(it.first(), it.second());
        }
    }
    RequestContext ctx = RequestContext.getCurrentContext();
    Long contentLength = ctx.getOriginContentLength();
    // Only inserts Content-Length if origin provides it and origin response is not
    // gzipped
    if (SET_CONTENT_LENGTH.get()) {
        if (contentLength != null && !ctx.getResponseGZipped()) {
            servletResponse.setContentLengthLong(contentLength);
        }
    }
}

From source file:org.dspace.app.webui.cris.controller.ImportFormController.java

@Override
protected ModelAndView onSubmit(HttpServletRequest request, HttpServletResponse response, Object command,
        BindException errors) throws Exception {
    Context dspaceContext = UIUtil.obtainContext(request);

    ImportDTO object = (ImportDTO) command;
    MultipartFile fileDTO = object.getFile();

    // read folder from configuration and make dir
    String path = ConfigurationManager.getProperty(CrisConstants.CFG_MODULE, "researcherpage.file.import.path");
    File dir = new File(path);
    dir.mkdir();//  ww w  . j a v  a2s . com
    try {
        if (object.getModeXSD() != null) {
            response.setContentType("application/xml;charset=UTF-8");
            response.addHeader("Content-Disposition", "attachment; filename=rp.xsd");
            String nameXSD = "xsd-download-webuirequest.xsd";
            File filexsd = new File(dir, nameXSD);
            filexsd.createNewFile();
            ImportExportUtils.generateXSD(response.getWriter(), dir,
                    applicationService.findAllContainables(RPPropertiesDefinition.class), filexsd, null);
            response.getWriter().flush();
            response.getWriter().close();
            return null;
        } else {
            if (fileDTO != null && !fileDTO.getOriginalFilename().isEmpty()) {
                Boolean defaultStatus = ConfigurationManager.getBooleanProperty(CrisConstants.CFG_MODULE,
                        "researcherpage.file.import.rpdefaultstatus");
                if (AuthorizeManager.isAdmin(dspaceContext)) {
                    dspaceContext.turnOffAuthorisationSystem();
                }
                ImportExportUtils.importResearchersXML(fileDTO.getInputStream(), dir, applicationService,
                        dspaceContext, defaultStatus);
                saveMessage(request, getText("action.import.with.success", request.getLocale()));
            }
        }
    } catch (Exception e) {
        log.error(e.getMessage(), e);
        saveMessage(request, getText("action.import.with.noSuccess", e.getMessage(), request.getLocale()));
    }

    return new ModelAndView(getSuccessView());

}

From source file:org.dspace.app.webui.cris.controller.NewImportFormController.java

@Override
protected ModelAndView onSubmit(HttpServletRequest request, HttpServletResponse response, Object command,
        BindException errors) throws Exception {
    Context dspaceContext = UIUtil.obtainContext(request);

    ImportDTO object = (ImportDTO) command;
    MultipartFile fileDTO = object.getFile();

    // read folder from configuration and make dir
    String path = ConfigurationManager.getProperty(CrisConstants.CFG_MODULE, "researcherpage.file.import.path");
    File dir = new File(path);
    dir.mkdir();/*from ww  w . j  av a2  s  .  c  o  m*/
    try {
        if (object.getModeXSD() != null) {
            response.setContentType("application/xml;charset=UTF-8");
            response.addHeader("Content-Disposition", "attachment; filename=rp.xsd");
            String nameXSD = "xsd-download-webuirequest.xsd";
            File filexsd = new File(dir, nameXSD);
            filexsd.createNewFile();
            ImportExportUtils.newGenerateXSD(response.getWriter(), dir,
                    applicationService.findAllContainables(RPPropertiesDefinition.class), filexsd,
                    new String[] { "crisobjects", "crisobject" }, "rp:",
                    "http://www.cilea.it/researcherpage/schemas", "http://www.cilea.it/researcherpage/schemas",
                    new String[] { "publicID", "uuid", "businessID", "type" },
                    new boolean[] { false, false, true, true });
            response.getWriter().flush();
            response.getWriter().close();
            return null;
        } else {
            if (fileDTO != null && !fileDTO.getOriginalFilename().isEmpty()) {
                Boolean defaultStatus = ConfigurationManager.getBooleanProperty(CrisConstants.CFG_MODULE,
                        "researcherpage.file.import.rpdefaultstatus");
                if (AuthorizeManager.isAdmin(dspaceContext)) {
                    dspaceContext.turnOffAuthorisationSystem();
                }
                ImportExportUtils.importResearchersXML(fileDTO.getInputStream(), dir, applicationService,
                        dspaceContext, defaultStatus);
                saveMessage(request, getText("action.import.with.success", request.getLocale()));
            }
        }
    } catch (Exception e) {
        log.error(e.getMessage(), e);
        saveMessage(request, getText("action.import.with.noSuccess", e.getMessage(), request.getLocale()));
    }

    return new ModelAndView(getSuccessView());

}

From source file:com.flipkart.poseidon.core.PoseidonServlet.java

private void setHeaders(PoseidonResponse response, HttpServletResponse httpResponse) {
    Map<String, String> headers = response.getHeaders();
    for (String key : headers.keySet()) {
        httpResponse.setHeader(key, headers.get(key));
    }/*w  ww .  ja  va  2s  . c o  m*/

    Map<String, List<String>> multiValueHeaders = response.getMultiValueHeaders();
    for (String key : multiValueHeaders.keySet()) {
        Optional.ofNullable(multiValueHeaders.get(key))
                .ifPresent(values -> values.forEach(value -> httpResponse.addHeader(key, value)));
    }
}