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:com.toptal.controller.AbstractRestTest.java

/**
 * Adds Authorization http header./*w w w . j  a  v  a  2  s.co  m*/
 * @param headers Http headers.
 * @param user User name.
 * @param password Password.
 * @return Http headers.
 */
@SuppressWarnings("PMD.AvoidThrowingRawExceptionTypes")
protected final HttpHeaders addAuth(final HttpHeaders headers, final String user, final String password) {
    headers.add("Authorization",
            String.format("Basic %s", SecurityUtils.encode(String.format("%s:%s", user, password))));
    return headers;
}

From source file:org.jasig.portlet.notice.service.ssp.SSPApi.java

/**
 * Get the authentication token to use.//from   w w w . j  av  a 2 s  .  c  o  m
 *
 * @param forceUpdate if true, get a new auth token even if a cached instance exists.
 * @return The authentication token
 * @throws MalformedURLException if the authentication URL is invalid
 * @throws RestClientException if an error occurs when talking to SSP
 */
private synchronized SSPToken getAuthenticationToken(boolean forceUpdate)
        throws MalformedURLException, RestClientException {
    if (authenticationToken != null && !authenticationToken.hasExpired() && !forceUpdate) {
        return authenticationToken;
    }

    String authString = getClientId() + ":" + getClientSecret();
    String authentication = new Base64().encodeToString(authString.getBytes());

    HttpHeaders headers = new HttpHeaders();
    headers.add(AUTHORIZATION, BASIC + " " + authentication);

    // form encode the grant_type...
    MultiValueMap<String, String> form = new LinkedMultiValueMap<>();
    form.add(GRANT_TYPE, CLIENT_CREDENTIALS);

    HttpEntity<MultiValueMap<String, String>> request = new HttpEntity<>(form, headers);

    URL authURL = getAuthenticationURL();
    authenticationToken = restTemplate.postForObject(authURL.toExternalForm(), request, SSPToken.class);
    return authenticationToken;
}

From source file:com.arvato.thoroughly.util.RestTemplateUtil.java

/**
 * @return HttpHeaders/* w w w  . jav a  2  s .  c o m*/
 */
public HttpHeaders createHeaders() {
    String encoding = Base64.getEncoder()
            .encodeToString(String.format("%s:%s", datahubAuthUsername, datahubAuthPwd).getBytes());
    String authHeader = "Basic " + encoding;
    HttpHeaders headers = new HttpHeaders();
    headers.add("Authorization", authHeader);
    headers.add("Content-Type", defaultContentType);
    headers.add("User-Agent",
            "Mozilla/5.0 (Windows NT 6.1) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/31.0.1650.16 Safari/537.36");
    headers.add("Accept-Encoding", "gzip,deflate");
    headers.add("Accept-Language", "zh-CN");
    headers.add("Connection", "Keep-Alive");
    return headers;
}

From source file:com.hybris.datahub.outbound.utils.RestTemplateUtil.java

/**
 * @return HttpHeaders// w ww .  j a va2s  .  c o m
 */
public HttpHeaders createHeaders() {
    final String encoding = Base64.getEncoder()
            .encodeToString(String.format("%s:%s", baseAuthUser, baseAuthPwd).getBytes());
    final String authHeader = "Basic " + encoding;
    final HttpHeaders headers = new HttpHeaders();
    headers.add("Authorization", authHeader);
    headers.add("Content-Type", defaultContentType);
    headers.add("User-Agent",
            "Mozilla/5.0 (Windows NT 6.1) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/31.0.1650.16 Safari/537.36");
    headers.add("Accept-Encoding", "gzip,deflate");
    headers.add("Accept-Language", "zh-CN");
    headers.add("Connection", "Keep-Alive");
    return headers;
}

From source file:de.unimannheim.spa.process.rest.ProjectRestController.java

@RequestMapping(value = "/{projectID}/processes/{processID}", method = RequestMethod.GET, produces = "application/octet-stream")
public ResponseEntity<InputStreamResource> downloadProcessFile(@PathVariable("projectID") String projectID,
        @PathVariable("processID") String processID) throws IOException {
    HttpHeaders headers = new HttpHeaders();
    headers.add("Cache-Control", "no-cache, no-store, must-revalidate");
    headers.add("Pragma", "no-cache");
    headers.add("Expires", "0");

    final Optional<DataPool> dataPool = spaService.findProjectById(PROJECT_BASE_URL + projectID)
            .map(project -> project.getDataPools().get(0));
    final Optional<DataBucket> dataBucketToDownload = (dataPool.isPresent())
            ? dataPool.get().findDataBucketById(PROCESS_BASE_URL + processID)
            : Optional.empty();//www .j av  a 2 s. c o  m
    final File processFile = Files.createTempFile(dataBucketToDownload.get().getLabel(), "").toFile();

    spaService.exportData(dataBucketToDownload.get(), "BPMN2", processFile);

    headers.add("Content-Disposition", "attachment; filename=" + processFile.getName() + ".bpmn");
    headers.add("Access-Control-Expose-Headers", "Content-Disposition");

    return ResponseEntity.ok().headers(headers).contentLength(processFile.length())
            .contentType(OCTET_CONTENT_TYPE).body(new InputStreamResource(new FileInputStream(processFile)));
}

From source file:org.jodconverter.sample.springboot.ConverterController.java

@PostMapping("/converter")
public Object convert(@RequestParam("inputFile") final MultipartFile inputFile,
        @RequestParam(name = "outputFormat", required = false) final String outputFormat,
        final RedirectAttributes redirectAttributes) {

    if (inputFile.isEmpty()) {
        redirectAttributes.addFlashAttribute(ATTRNAME_ERROR_MESSAGE, "Please select a file to upload.");
        return ON_ERROR_REDIRECT;
    }//from   ww w .j a  va2  s .  c  om

    if (StringUtils.isBlank(outputFormat)) {
        redirectAttributes.addFlashAttribute(ATTRNAME_ERROR_MESSAGE, "Please select an output format.");
        return ON_ERROR_REDIRECT;
    }

    // Here, we could have a dedicated service that would convert document
    try (ByteArrayOutputStream baos = new ByteArrayOutputStream()) {

        final DocumentFormat targetFormat = DefaultDocumentFormatRegistry.getFormatByExtension(outputFormat);
        converter.convert(inputFile.getInputStream())
                .as(DefaultDocumentFormatRegistry
                        .getFormatByExtension(FilenameUtils.getExtension(inputFile.getOriginalFilename())))
                .to(baos).as(targetFormat).execute();

        final HttpHeaders headers = new HttpHeaders();
        headers.setContentType(MediaType.parseMediaType(targetFormat.getMediaType()));
        headers.add("Content-Disposition",
                "attachment; filename=" + FilenameUtils.getBaseName(inputFile.getOriginalFilename()) + "."
                        + targetFormat.getExtension());
        return new ResponseEntity<>(baos.toByteArray(), headers, HttpStatus.OK);

    } catch (OfficeException | IOException e) {
        redirectAttributes.addFlashAttribute(ATTRNAME_ERROR_MESSAGE,
                "Unable to convert the file " + inputFile.getOriginalFilename() + ". Cause: " + e.getMessage());
    }

    return ON_ERROR_REDIRECT;
}

From source file:com.basicservice.controller.UserController.java

@RequestMapping(value = "/register", method = RequestMethod.POST)
public ResponseEntity<String> register(HttpServletRequest request, @RequestParam(value = "name") String name,
        @RequestParam(value = "email") EmailValidatedString email,
        @RequestParam(value = "password") String password) {
    if (email == null || email.getValue() == null || password == null) {
        return new ResponseEntity<String>(HttpStatus.FORBIDDEN);
    }/*w ww  .  j a v  a  2s . c o  m*/
    LOG.debug("Got register request: email:" + email.getValue() + ", pass:" + password + ", name:" + name);

    User user = null;
    try {
        user = userService.register(name, email.getValue(), password);
    } catch (UserRegistrationException e) {
        if (e.getReason() == UserRegistrationException.reason.EMAIL_EXISTS) {
            return new ResponseEntity<String>(HttpStatus.FORBIDDEN);
        }
    }
    if (user == null) {
        return new ResponseEntity<String>(HttpStatus.INTERNAL_SERVER_ERROR);
    }

    LOG.debug("Preparing to save user to db");
    final String id = userService.save(user);
    if (id != null) {
        String from = Constants.REGISTRATION_FROM_ADDRESS;
        String to = email.getValue();
        Locale locale = LocaleContextHolder.getLocale();
        String subject = messageLocalizationService.getMessage(Constants.MLS_REGISTRATION_CONFIRMATION_SUBJECT,
                locale);
        Object[] args = new String[1];
        String path = Utils.getBasicPath(request);
        ConfirmationString cs = confirmationEmailService.getConfirmationString(user.getId());
        URI uri = new UriTemplate("{requestUrl}/api/users/registrationConfirmation/?key={key}").expand(path,
                cs.getKey());
        args[0] = uri.toASCIIString();
        String messageHtml = messageLocalizationService.getMessage(Constants.MLS_REGISTRATION_CONFIRMATION_HTML,
                args, locale);
        try {
            mailService.sendEmail(from, to, subject, messageHtml);
        } catch (Exception e) {
            LOG.debug("Failed to send confirmation email to: " + to, e);
        }
    }
    final HttpHeaders headers = new HttpHeaders();
    headers.add("Set-Cookie", Constants.AUTHENTICATED_USER_ID_COOKIE + "=" + id + "; Path=/");
    return new ResponseEntity<String>(headers, HttpStatus.CREATED);
}

From source file:ch.ralscha.extdirectspring.controller.RouterControllerTreeLoadTest.java

@SuppressWarnings("unchecked")
private void callTreeLoadAndCheckResult(String method) {
    HttpHeaders headers = new HttpHeaders();
    headers.add("aHeader", "true");

    Map<String, Object> requestParameters = new LinkedHashMap<String, Object>();
    requestParameters.put("node", "root");

    List<Node> nodes = (List<Node>) ControllerUtil.sendAndReceive(mockMvc, headers, "remoteProviderTreeLoad",
            method, new TypeReference<List<Node>>() {/* nothinghere */
            }, requestParameters);//  www .  ja  va2 s  .co  m

    String appendix = ":true;true;true";

    assertThat(nodes).hasSize(5).containsSequence(new Node("n1", "Node 1" + appendix, false),
            new Node("n2", "Node 2" + appendix, false), new Node("n3", "Node 3" + appendix, false),
            new Node("n4", "Node 4" + appendix, false), new Node("n5", "Node 5" + appendix, false));

    headers = new HttpHeaders();
    headers.add("aHeader", "false");

    nodes = (List<Node>) ControllerUtil.sendAndReceive(mockMvc, headers, "remoteProviderTreeLoad", method,
            new TypeReference<List<Node>>() {/* nothinghere */
            }, requestParameters);

    appendix = ":false;true;true";
    assertThat(nodes).hasSize(5).containsSequence(new Node("n1", "Node 1" + appendix, false),
            new Node("n2", "Node 2" + appendix, false), new Node("n3", "Node 3" + appendix, false),
            new Node("n4", "Node 4" + appendix, false), new Node("n5", "Node 5" + appendix, false));
}

From source file:io.syndesis.runtime.credential.CredentialITCase.java

private HttpHeaders persistAsCookie(final OAuth2CredentialFlowState flowState) {
    final NewCookie cookie = clientSideState.persist(flowState.persistenceKey(), "/", flowState);

    final HttpHeaders cookies = new HttpHeaders();
    cookies.add(HttpHeaders.COOKIE, cookie.toString());
    return cookies;
}

From source file:org.slc.sli.dashboard.client.RESTClient.java

/**
 * Make a PUT request to a REST service/* ww  w .j a  v a  2 s. c  om*/
 * 
 * @param path
 *            the unique portion of the requested REST service URL
 * @param token
 *            not used yet
 * 
 * @param entity
 *            entity used for update
 * 
 * @throws NoSessionException
 */
public void putJsonRequestWHeaders(String path, String token, Object entity) {

    if (token != null) {
        URLBuilder url = null;
        if (!path.startsWith("http")) {
            url = new URLBuilder(getSecurityUrl());
            url.addPath(path);
        } else {
            url = new URLBuilder(path);
        }

        HttpHeaders headers = new HttpHeaders();
        headers.add("Authorization", "Bearer " + token);
        headers.add("Content-Type", "application/json");
        HttpEntity requestEntity = new HttpEntity(entity, headers);
        logger.debug("Updating API at: {}", url);
        try {
            template.put(url.toString(), requestEntity);
        } catch (HttpClientErrorException e) {
            logger.debug("Catch HttpClientException: {}", e.getStatusCode());
        }
    }
}