Example usage for org.springframework.http HttpHeaders set

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

Introduction

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

Prototype

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

Source Link

Document

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

Usage

From source file:de.blizzy.documentr.web.attachment.AttachmentController.java

@RequestMapping(value = "/{projectName:" + DocumentrConstants.PROJECT_NAME_PATTERN + "}/" + "{branchName:"
        + DocumentrConstants.BRANCH_NAME_PATTERN + "}/" + "{pagePath:"
        + DocumentrConstants.PAGE_PATH_URL_PATTERN + "}/"
        + "{name:.*}", method = { RequestMethod.GET, RequestMethod.HEAD })
@PreAuthorize("hasPagePermission(#projectName, #branchName, #pagePath, VIEW)")
public ResponseEntity<byte[]> getAttachment(@PathVariable String projectName, @PathVariable String branchName,
        @PathVariable String pagePath, @PathVariable String name,
        @RequestParam(required = false) boolean download, HttpServletRequest request) throws IOException {

    try {//from  w ww. java  2  s. c om
        pagePath = Util.toRealPagePath(pagePath);
        PageMetadata metadata = pageStore.getAttachmentMetadata(projectName, branchName, pagePath, name);
        HttpHeaders headers = new HttpHeaders();

        long lastEdited = metadata.getLastEdited().getTime();
        long authenticationCreated = AuthenticationUtil.getAuthenticationCreationTime(request.getSession());
        long lastModified = Math.max(lastEdited, authenticationCreated);
        if (!download) {
            long projectEditTime = PageUtil.getProjectEditTime(projectName);
            if (projectEditTime >= 0) {
                lastModified = Math.max(lastModified, projectEditTime);
            }

            long modifiedSince = request.getDateHeader("If-Modified-Since"); //$NON-NLS-1$
            if ((modifiedSince >= 0) && (lastModified <= modifiedSince)) {
                return new ResponseEntity<byte[]>(headers, HttpStatus.NOT_MODIFIED);
            }
        }

        headers.setLastModified(lastModified);
        headers.setExpires(0);
        headers.setCacheControl("must-revalidate, private"); //$NON-NLS-1$
        if (download) {
            headers.set("Content-Disposition", //$NON-NLS-1$
                    "attachment; filename=\"" + name.replace('"', '_') + "\""); //$NON-NLS-1$ //$NON-NLS-2$
        }

        Page attachment = pageStore.getAttachment(projectName, branchName, pagePath, name);
        headers.setContentType(MediaType.parseMediaType(attachment.getContentType()));
        return new ResponseEntity<byte[]>(attachment.getData().getData(), headers, HttpStatus.OK);
    } catch (PageNotFoundException e) {
        return new ResponseEntity<byte[]>(HttpStatus.NOT_FOUND);
    }
}

From source file:de.metas.ui.web.letter.LetterRestController.java

private ResponseEntity<byte[]> createPDFResponseEntry(final byte[] pdfData) {
    final String pdfFilename = Services.get(IMsgBL.class).getMsg(Env.getCtx(), Letters.MSG_Letter);
    final HttpHeaders headers = new HttpHeaders();
    headers.setContentType(MediaType.APPLICATION_PDF);
    headers.set(HttpHeaders.CONTENT_DISPOSITION, "inline; filename=\"" + pdfFilename + "\"");
    headers.setCacheControl("must-revalidate, post-check=0, pre-check=0");
    final ResponseEntity<byte[]> response = new ResponseEntity<>(pdfData, headers, HttpStatus.OK);
    return response;
}

From source file:edu.harvard.i2b2.fhir.FetchInterceptor.java

void alterResponse(HttpServletResponse response, String path) throws IOException {
    ourLog.info("altering response");

    RestTemplate restTemplate = new MyGlobal().getRestTemplate();
    HttpHeaders headers = new HttpHeaders();
    headers.set("Accept", "application/json");

    HttpEntity entity = new HttpEntity(headers);
    Map<String, String> params = new HashMap<String, String>();
    String url = "http://localhost:8080/fhirRest/" + path;
    UriComponentsBuilder builder = UriComponentsBuilder.fromHttpUrl(url);
    HttpEntity<String> responseEntity = restTemplate.exchange(builder.build().encode().toUri(), HttpMethod.GET,
            entity, String.class);
    String responseTxt = responseEntity.getBody();
    response.getWriter().println(responseTxt);

}

From source file:fi.vm.sade.eperusteet.ylops.resource.dokumentti.DokumenttiController.java

@RequestMapping(value = "/{dokumenttiId}", method = RequestMethod.GET, produces = "application/pdf")
public ResponseEntity<Object> get(@PathVariable final Long dokumenttiId) {
    byte[] pdfdata = service.get(dokumenttiId);

    if (pdfdata == null || pdfdata.length == 0) {
        return new ResponseEntity<>(HttpStatus.NOT_FOUND);
    }// w  ww .  j av  a2s.c  o m

    if (!service.hasPermission(dokumenttiId)) {
        return new ResponseEntity<>(HttpStatus.FORBIDDEN);
    }

    HttpHeaders headers = new HttpHeaders();
    headers.set("Content-disposition", "inline; filename=\"" + dokumenttiId + ".pdf\"");
    Optional.ofNullable(dokumenttiRepository.findOne(dokumenttiId)).filter(Objects::nonNull)
            .map(dokumentti -> opetussuunnitelmaRepository.findOne(dokumentti.getOpsId()))
            .filter(Objects::nonNull).map(Opetussuunnitelma::getNimi).filter(Objects::nonNull)
            .ifPresent(nimi -> headers.set("Content-disposition", "inline; filename=\"" + nimi + ".pdf\""));

    return new ResponseEntity<>(pdfdata, headers, HttpStatus.OK);
}

From source file:io.kahu.hawaii.rest.DefaultResponseManager.java

private ResponseEntity<String> myToResponse(JSONObject response) {
    HttpHeaders headers = new HttpHeaders();
    // explicitly set the application/json content type
    headers.setContentType(MediaType.APPLICATION_JSON);
    if (hawaiiTxIdHeaderEnabled) {
        // note the X-Hawaii-Tx-Id header can be disabled by setting
        // logging.context.txid=
        LoggingContext loggingContext = LoggingContext.get();
        Object hawaiiTxId = loggingContext.get(this.loggingContentTxId);
        Object callIds = loggingContext.get("call_ids");
        if (hawaiiTxId != null) {
            headers.set(X_HAWAII_TRANSACTION_ID_HEADER, ObjectUtils.toString(hawaiiTxId));
            headers.set(X_HAWAII_CALL_IDS_HEADER, ObjectUtils.toString(callIds));
        }/*from  w  w w  .j av  a 2  s .  c om*/
    }
    String json = response.toString();
    return ResponseEntity.ok().headers(headers).body(json);
}

From source file:io.spring.initializr.web.AbstractInitializrIntegrationTests.java

protected <T> ResponseEntity<T> execute(String contextPath, Class<T> responseType, String userAgentHeader,
        String... acceptHeaders) {
    HttpHeaders headers = new HttpHeaders();
    if (userAgentHeader != null) {
        headers.set("User-Agent", userAgentHeader);
    }/*www . j  a v a  2s .  c om*/
    if (acceptHeaders != null) {
        List<MediaType> mediaTypes = new ArrayList<>();
        for (String acceptHeader : acceptHeaders) {
            mediaTypes.add(MediaType.parseMediaType(acceptHeader));
        }
        headers.setAccept(mediaTypes);
    } else {
        headers.setAccept(Collections.emptyList());
    }
    return restTemplate.exchange(createUrl(contextPath), HttpMethod.GET, new HttpEntity<Void>(headers),
            responseType);
}

From source file:io.syndesis.runtime.BaseITCase.java

private void prepareHeaders(Object body, HttpHeaders headers, String token) {
    if (body != null) {
        headers.set(HttpHeaders.CONTENT_TYPE, "application/json");
    }/*w w w. j  a v a  2s. c  om*/
    if (token != null) {
        headers.set(HttpHeaders.AUTHORIZATION, "Bearer " + token);
    }
}

From source file:it.infn.mw.iam.authn.oidc.DefaultOidcTokenRequestor.java

private void basicAuthRequest(RegisteredClient clientConfig, HttpHeaders headers) {

    String auth = clientConfig.getClientId() + ":" + clientConfig.getClientSecret();
    byte[] encodedAuth = org.apache.commons.codec.binary.Base64
            .encodeBase64(auth.getBytes(StandardCharsets.US_ASCII));
    String authHeader = "Basic " + new String(encodedAuth);

    headers.set("Authorization", authHeader);
}

From source file:net.longfalcon.newsj.service.GoogleSearchService.java

public GoogleSearchResponse search(String searchString, String referer) {
    try {//from  w  w w.j  a va  2 s. c  o m
        if (ValidatorUtil.isNull(referer)) {
            referer = "http://longfalcon.net";
        }

        String v = "1.0";
        String userip = "192.168.0.1";
        HttpHeaders httpHeaders = new HttpHeaders();
        httpHeaders.set("Referer", referer);

        HttpEntity<?> requestEntity = new HttpEntity(httpHeaders);

        UriComponents uriComponents = UriComponentsBuilder.fromUriString(_SEARCH_URL).queryParam("v", v)
                .queryParam("q", searchString).queryParam("userip", userip).build();
        ResponseEntity<GoogleSearchResponse> responseEntity = restTemplate.exchange(uriComponents.toUri(),
                HttpMethod.GET, requestEntity, GoogleSearchResponse.class);
        HttpStatus statusCode = responseEntity.getStatusCode();
        if (statusCode.is2xxSuccessful() || statusCode.is3xxRedirection()) {
            return responseEntity.getBody();
        } else {
            _log.error(String.format("Search request: \n%s\n failed with HTTP code %s : %s",
                    uriComponents.toString(), statusCode.toString(), statusCode.getReasonPhrase()));
            return null;
        }
    } catch (Exception e) {
        _log.error(e);
    }

    return null;
}

From source file:net.longfalcon.newsj.service.TraktService.java

/**
 * call ID lookup web service/* w w w . j a va  2 s.c  om*/
 * @param id     id to look up that matches the id type. String to allow imdb queries "ttxxxxxx"
 * @param idType Possible values:  trakt-movie , trakt-show , trakt-episode , imdb , tmdb , tvdb , tvrage .
 * @return
 */
protected TraktResult[] searchById(String id, String idType) {
    try {
        String traktApiUrl = config.getTraktApiUrl();
        String traktAppId = config.getTraktAppId();

        HttpHeaders httpHeaders = new HttpHeaders();
        httpHeaders.set("Content-type", "application/json");
        httpHeaders.set("trakt-api-key", traktAppId);
        httpHeaders.set("trakt-api-version", "2");
        HttpEntity<?> requestEntity = new HttpEntity(httpHeaders);

        UriComponents uriComponents = UriComponentsBuilder.fromUriString(traktApiUrl + "/search")
                .queryParam("id_type", idType).queryParam("id", id).build();
        ResponseEntity<TraktResult[]> responseEntity = restTemplate.exchange(uriComponents.toUri(),
                HttpMethod.GET, requestEntity, TraktResult[].class);
        HttpStatus statusCode = responseEntity.getStatusCode();
        if (statusCode.is2xxSuccessful() || statusCode.is3xxRedirection()) {
            return responseEntity.getBody();
        } else {
            _log.error(String.format("Trakt Search request: \n%s\n failed with HTTP code %s : %s",
                    uriComponents.toString(), statusCode.toString(), statusCode.getReasonPhrase()));
            return null;
        }

    } catch (Exception e) {
        _log.error(e.toString(), e);
    }
    return null;
}