Example usage for org.springframework.http HttpHeaders add

List of usage examples for org.springframework.http HttpHeaders add

Introduction

In this page you can find the example usage for org.springframework.http HttpHeaders add.

Prototype

@Override
public void add(String headerName, @Nullable String headerValue) 

Source Link

Document

Add the given, single header value under the given name.

Usage

From source file:org.cloudfoundry.identity.uaa.login.RemoteUaaController.java

protected ResponseEntity<ExpiringCode> doGenerateCode(Object o) throws IOException {
    ExpiringCode ec = new ExpiringCode(null,
            new Timestamp(System.currentTimeMillis() + (getCodeExpirationMillis())),
            new ObjectMapper().writeValueAsString(o));

    // ec = generateCode
    HttpHeaders requestHeaders = new HttpHeaders();
    requestHeaders.add(ACCEPT, MediaType.APPLICATION_JSON_VALUE);
    requestHeaders.add(CONTENT_TYPE, MediaType.APPLICATION_JSON_VALUE);

    HttpEntity<ExpiringCode> requestEntity = new HttpEntity<ExpiringCode>(ec, requestHeaders);

    ResponseEntity<ExpiringCode> response = authorizationTemplate.exchange(getUaaBaseUrl() + "/Codes",
            HttpMethod.POST, requestEntity, ExpiringCode.class);

    if (response.getStatusCode() != HttpStatus.CREATED) {
        logger.warn("Request failed: " + requestEntity);
        // TODO throw exception with the correct error
        throw new RuntimeException(String.valueOf(response.getStatusCode()));
    }// www  .  java2 s.  c  om

    return response;
}

From source file:org.cloudfoundry.identity.uaa.login.RemoteUaaController.java

protected ResponseEntity<byte[]> passthru(HttpServletRequest request, HttpEntity entity,
        Map<String, Object> model, boolean loginClientRequired) throws Exception {

    String path = extractPath(request);

    RestOperations template = loginClientRequired ? getAuthorizationTemplate() : getDefaultTemplate();
    HttpHeaders requestHeaders = new HttpHeaders();
    requestHeaders.putAll(getRequestHeaders(entity.getHeaders()));
    requestHeaders.remove(COOKIE);/*from w ww.  j ava2  s .c o  m*/
    requestHeaders.remove(COOKIE.toLowerCase());
    // Get back end cookie if saved in session
    String cookie = (String) model.get(COOKIE_MODEL);
    if (cookie != null) {
        logger.debug("Found back end cookies: " + cookie);
        for (String value : cookie.split(";")) {
            requestHeaders.add(COOKIE, value);
        }
    }

    ResponseEntity<byte[]> response = template.exchange(getUaaBaseUrl() + "/" + path,
            HttpMethod.valueOf(request.getMethod()), new HttpEntity(entity.getBody(), requestHeaders),
            byte[].class);
    HttpHeaders outgoingHeaders = getResponseHeaders(response.getHeaders());
    return new ResponseEntity<byte[]>(response.getBody(), outgoingHeaders, response.getStatusCode());

}

From source file:org.cloudfoundry.identity.uaa.provider.oauth.XOAuthAuthenticationManager.java

private String getTokenFromCode(XOAuthCodeToken codeToken, AbstractXOAuthIdentityProviderDefinition config) {
    if (StringUtils.hasText(codeToken.getIdToken()) && "id_token".equals(getResponseType(config))) {
        logger.debug("XOauthCodeToken contains id_token, not exchanging code.");
        return codeToken.getIdToken();
    }/*  w w w . j a  v  a 2  s  .  c o  m*/
    MultiValueMap<String, String> body = new LinkedMaskingMultiValueMap<>("code");
    body.add("grant_type", "authorization_code");
    body.add("response_type", getResponseType(config));
    body.add("code", codeToken.getCode());
    body.add("redirect_uri", codeToken.getRedirectUrl());

    HttpHeaders headers = new HttpHeaders();
    String clientAuthHeader = getClientAuthHeader(config);
    headers.add("Authorization", clientAuthHeader);
    headers.add("Accept", "application/json");

    URI requestUri;
    HttpEntity requestEntity = new HttpEntity<>(body, headers);
    try {
        requestUri = config.getTokenUrl().toURI();
    } catch (URISyntaxException e) {
        logger.error("Invalid URI configured:" + config.getTokenUrl(), e);
        return null;
    }

    try {
        logger.debug(String.format("Performing token exchange with url:%s and request:%s", requestUri, body));
        // A configuration that skips SSL/TLS validation requires clobbering the rest template request factory
        // setup by the bean initializer.
        ResponseEntity<Map<String, String>> responseEntity = getRestTemplate(config).exchange(requestUri,
                HttpMethod.POST, requestEntity, new ParameterizedTypeReference<Map<String, String>>() {
                });
        logger.debug(String.format("Request completed with status:%s", responseEntity.getStatusCode()));
        return responseEntity.getBody().get(ID_TOKEN);
    } catch (HttpServerErrorException | HttpClientErrorException ex) {
        throw ex;
    }
}

From source file:org.cloudfoundry.identity.uaa.ServerRunning.java

public ResponseEntity<Void> postForRedirect(String path, HttpHeaders headers,
        MultiValueMap<String, String> params) {
    ResponseEntity<Void> exchange = postForResponse(path, headers, params);

    if (exchange.getStatusCode() != HttpStatus.FOUND) {
        throw new IllegalStateException(
                "Expected 302 but server returned status code " + exchange.getStatusCode());
    }/* w  w  w  .  j  a v a 2s.c  o m*/

    headers.remove("Cookie");
    if (exchange.getHeaders().containsKey("Set-Cookie")) {
        for (String cookie : exchange.getHeaders().get("Set-Cookie")) {
            headers.add("Cookie", cookie);
        }
    }

    String location = exchange.getHeaders().getLocation().toString();

    return client.exchange(location, HttpMethod.GET, new HttpEntity<Void>(null, headers), Void.class);
}

From source file:org.egov.adtax.web.controller.hoarding.CreateAdvertisementController.java

@RequestMapping(value = "/printack/{id}", method = GET)
@ResponseBody/*  w  w  w  .j  a va 2 s  . co m*/
public ResponseEntity<byte[]> printAck(@PathVariable Long id, final Model model,
        final HttpServletRequest request) {
    byte[] reportOutput;
    final String cityMunicipalityName = (String) request.getSession().getAttribute("citymunicipalityname");
    final String cityName = (String) request.getSession().getAttribute("cityname");
    AdvertisementPermitDetail advertisementPermitDetail = advertisementPermitDetailService
            .findBy(Long.valueOf(id));

    if (advertisementPermitDetail != null) {
        reportOutput = advertisementService
                .getReportParamsForAcknowdgement(advertisementPermitDetail, cityMunicipalityName, cityName)
                .getReportOutputData();
        if (reportOutput != null) {
            final HttpHeaders headers = new HttpHeaders();

            headers.setContentType(MediaType.parseMediaType(APPLICATION_PDF));
            headers.add("content-disposition", "inline;filename=hoarding-ack.pdf");
            return new ResponseEntity<>(reportOutput, headers, HttpStatus.CREATED);
        }
    }

    return null;

}

From source file:org.egov.adtax.web.controller.reports.ReportController.java

private ResponseEntity<byte[]> generatePermitOrder(HttpServletRequest request,
        final AdvertisementPermitDetail advertisementPermitDetail, final HttpSession session,
        final String workFlowAction) {
    ReportRequest reportInput = null;/* w w  w . j  a v a  2  s  .c o  m*/
    ReportOutput reportOutput = null;
    if (null != advertisementPermitDetail) {
        final Map<String, Object> reportParams = buildParametersForReport(request, advertisementPermitDetail);
        reportParams.put("advertisementtitle",
                WordUtils.capitalize(AdvertisementTaxConstants.ADVERTISEMENTPERMITODERTITLE));

        reportInput = new ReportRequest(AdvertisementTaxConstants.PERMITORDER, advertisementPermitDetail,
                reportParams);
    }
    final HttpHeaders headers = new HttpHeaders();
    headers.setContentType(MediaType.parseMediaType("application/pdf"));
    headers.add("content-disposition", "inline;filename=Permit Order.pdf");
    reportOutput = reportService.createReport(reportInput);
    return new ResponseEntity<byte[]>(reportOutput.getReportOutputData(), headers, HttpStatus.CREATED);
}

From source file:org.egov.adtax.web.controller.reports.ReportController.java

private ResponseEntity<byte[]> generateDemandNotice(HttpServletRequest request,
        final AdvertisementPermitDetail advertisementPermitDetail, final HttpSession session,
        final String workFlowAction) {
    ReportRequest reportInput = null;/* w  w  w. j a  v  a2 s.com*/
    ReportOutput reportOutput = null;
    if (null != advertisementPermitDetail) {

        final Map<String, Object> reportParams = buildParametersForReport(request, advertisementPermitDetail);
        reportParams.put("taxamount", advertisementPermitDetail.getTaxAmount() == null ? Long.valueOf(0)
                : advertisementPermitDetail.getTaxAmount());
        reportParams.put("encroachmentfee",
                advertisementPermitDetail.getEncroachmentFee() == null ? Long.valueOf(0)
                        : advertisementPermitDetail.getEncroachmentFee());
        reportInput = new ReportRequest(AdvertisementTaxConstants.DEMANDNOTICE, advertisementPermitDetail,
                reportParams);
    }
    final HttpHeaders headers = new HttpHeaders();
    headers.setContentType(MediaType.parseMediaType("application/pdf"));
    headers.add("content-disposition", "inline;filename=Demand Notice.pdf");
    reportOutput = reportService.createReport(reportInput);
    return new ResponseEntity<byte[]>(reportOutput.getReportOutputData(), headers, HttpStatus.CREATED);
}

From source file:org.egov.eis.web.controller.reports.EmployeeAssignmentReportPDFController.java

@RequestMapping(value = "/reports/employeeassignments/pdf", method = RequestMethod.GET)
public @ResponseBody ResponseEntity<byte[]> generateEmployeeAssignmentsPDF(final HttpServletRequest request,
        @RequestParam("code") final String code, @RequestParam("name") final String name,
        @RequestParam("departmentId") final Long departmentId,
        @RequestParam("designationId") final Long designationId,
        @RequestParam("positionId") final Long positionId,
        @RequestParam("contentType") final String contentType, @RequestParam("date") final Date date,
        final HttpSession session, final Model model) throws DocumentException {
    final EmployeeAssignmentSearch employeeAssignmentSearch = new EmployeeAssignmentSearch();
    employeeAssignmentSearch.setEmployeeCode(code);
    employeeAssignmentSearch.setEmployeeName(name);
    employeeAssignmentSearch.setDepartment(departmentId);
    employeeAssignmentSearch.setDesignation(designationId);
    employeeAssignmentSearch.setPosition(positionId);
    employeeAssignmentSearch.setAssignmentDate(date);

    final List<Employee> employeeList = assignmentService.searchEmployeeAssignments(employeeAssignmentSearch);
    final StringBuilder searchCriteria = new StringBuilder();
    searchCriteria.append("Employee Assignment Report as on ");
    if (employeeAssignmentSearch.getAssignmentDate() != null)
        searchCriteria.append(DateUtils.getDefaultFormattedDate(employeeAssignmentSearch.getAssignmentDate()));
    if (StringUtils.isNotBlank(employeeAssignmentSearch.getEmployeeName()))
        searchCriteria.append(", Employee Name : ").append(employeeAssignmentSearch.getEmployeeName())
                .append("");
    if (StringUtils.isNotBlank(employeeAssignmentSearch.getEmployeeCode()))
        searchCriteria.append(", Employee Code : ").append(employeeAssignmentSearch.getEmployeeCode())
                .append(" ");
    if (employeeAssignmentSearch.getDepartment() != null) {
        final Department department = departmentService
                .getDepartmentById(employeeAssignmentSearch.getDepartment());
        searchCriteria.append(" for Department : ").append(department.getName()).append(" ");
    }//  www.j av  a2  s . c o m
    if (employeeAssignmentSearch.getDesignation() != null) {
        final Designation designation = designationService
                .getDesignationById(employeeAssignmentSearch.getDesignation());
        searchCriteria.append(" and Designation : ").append(designation.getName()).append(" ");
    }
    if (employeeAssignmentSearch.getPosition() != null) {
        final Position position = positionMasterService.getPositionById(employeeAssignmentSearch.getPosition());
        searchCriteria.append(" and Position : ").append(position.getName()).append(" ");
    }

    String searchString = StringUtils.EMPTY;
    if (searchCriteria.toString().endsWith(" "))
        searchString = searchCriteria.substring(0, searchCriteria.length() - 1);

    final List<EmployeeAssignmentSearch> searchResult = new ArrayList<EmployeeAssignmentSearch>();
    Map<String, String> tempAssignments = null;
    EmployeeAssignmentSearch empAssignmentSearch = null;
    int maxTempAssignments = 0;
    for (final Employee employee : employeeList) {
        int index = 0;
        tempAssignments = new HashMap<String, String>();
        empAssignmentSearch = new EmployeeAssignmentSearch();
        empAssignmentSearch.setEmployeeCode(employee.getCode());
        empAssignmentSearch.setEmployeeName(employee.getName());
        for (final Assignment assignment : employee.getAssignments())
            if (assignment.getPrimary()) {
                empAssignmentSearch.setDepartmentName(assignment.getDepartment().getName());
                empAssignmentSearch.setDesignationName(assignment.getDesignation().getName());
                empAssignmentSearch.setPositionName(assignment.getPosition().getName());
                empAssignmentSearch.setDateRange(DateUtils.getDefaultFormattedDate(assignment.getFromDate())
                        + " - " + DateUtils.getDefaultFormattedDate(assignment.getToDate()));
            } else {
                tempAssignments.put("department_" + String.valueOf(index),
                        assignment.getDepartment().getName());
                tempAssignments.put("designation_" + String.valueOf(index),
                        assignment.getDesignation().getName());
                tempAssignments.put("position_" + String.valueOf(index), assignment.getPosition().getName());
                tempAssignments.put("daterange_" + String.valueOf(index),
                        DateUtils.getDefaultFormattedDate(assignment.getFromDate()) + " - "
                                + DateUtils.getDefaultFormattedDate(assignment.getToDate()));
                index++;
            }
        empAssignmentSearch.setTempPositionDetails(tempAssignments);
        searchResult.add(empAssignmentSearch);
        if (employee.getAssignments().size() >= maxTempAssignments)
            maxTempAssignments = employee.getAssignments().size();

    }
    JasperPrint jasperPrint;
    ByteArrayOutputStream outputBytes = null;
    try {
        jasperPrint = generateEmployeeAssignmentReport(searchResult, maxTempAssignments, searchString);
        outputBytes = new ByteArrayOutputStream(MB);
        JasperExportManager.exportReportToPdfStream(jasperPrint, outputBytes);
    } catch (final Exception e) {
        Log.error("Error while generating employee assignment report ", e);
    }
    final ReportOutput reportOutput = new ReportOutput();
    reportOutput.setReportOutputData(outputBytes.toByteArray());
    final HttpHeaders headers = new HttpHeaders();
    if (contentType.equalsIgnoreCase("pdf")) {
        reportOutput.setReportFormat(ReportFormat.PDF);
        reportOutput.setReportFormat(ReportFormat.PDF);
        headers.setContentType(MediaType.parseMediaType("application/pdf"));
        headers.add("content-disposition", "inline;filename=EmployeeAssignment.pdf");
    } else {
        reportOutput.setReportFormat(ReportFormat.XLS);
        headers.setContentType(MediaType.parseMediaType("application/vnd.ms-excel"));
        headers.add("content-disposition", "inline;filename=EmployeeAssignment.xls");
    }
    return new ResponseEntity<byte[]>(reportOutput.getReportOutputData(), headers, HttpStatus.CREATED);
}

From source file:org.egov.mrs.web.controller.application.registration.MarriageCertificateController.java

/**
 * @param fsm/*from w ww .ja v a2  s.co m*/
 * @return
 * @throws IOException
 */
private ResponseEntity<byte[]> getResponseEntity(final FileStoreMapper fsm) throws IOException {
    ReportOutput reportOutput = new ReportOutput();
    final File file = fileStoreService.fetch(fsm, MarriageConstants.FILESTORE_MODULECODE);
    final byte[] bFile = FileUtils.readFileToByteArray(file);
    reportOutput.setReportOutputData(bFile);
    reportOutput.setReportFormat(ReportFormat.PDF);
    final HttpHeaders headers = new HttpHeaders();
    headers.setContentType(MediaType.parseMediaType("application/pdf"));
    headers.add("content-disposition", "inline;filename=" + file.getName());
    return new ResponseEntity<byte[]>(reportOutput.getReportOutputData(), headers, HttpStatus.CREATED);
}

From source file:org.egov.mrs.web.controller.application.reissue.NewReIssueController.java

@RequestMapping(value = "/printreissuecertificateack", method = GET)
@ResponseBody/*  w  w  w .ja v  a2s . c o m*/
public ResponseEntity<byte[]> printAck(@RequestParam("applnNo") final String applnNo, final Model model,
        final HttpServletRequest request) {
    byte[] reportOutput;
    final String cityMunicipalityName = (String) request.getSession().getAttribute("citymunicipalityname");
    final String cityName = (String) request.getSession().getAttribute("cityname");
    final ReIssue reIssue = reIssueService.findByApplicationNo(applnNo);

    if (reIssue != null) {
        reportOutput = marriageRegistrationService
                .getReportParamsForAcknowdgementForMrgReissue(reIssue, cityMunicipalityName, cityName)
                .getReportOutputData();
        if (reportOutput != null) {
            final HttpHeaders headers = new HttpHeaders();

            headers.setContentType(MediaType.parseMediaType(MarriageConstants.APPLICATION_PDF));
            headers.add("content-disposition", "inline;filename=marriage-duplicate-certificate-ack.pdf");
            return new ResponseEntity<>(reportOutput, headers, HttpStatus.CREATED);
        }
    }

    return null;

}