Example usage for org.springframework.http HttpHeaders getLocation

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

Introduction

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

Prototype

@Nullable
public URI getLocation() 

Source Link

Document

Return the (new) location of a resource as specified by the Location header.

Usage

From source file:org.zalando.riptide.Actions.java

/**
 * Normalizes the {@code Location} and {@code Content-Location} headers of any given response by resolving them
 * against the given {@code uri}./*from  w ww  . j  a v  a 2  s .  c o m*/
 *
 * @param uri the base uri to resolve against
 * @return a function that normalizes responses
 */
public static ThrowingFunction<ClientHttpResponse, ClientHttpResponse, IOException> normalize(final URI uri) {
    return response -> {
        final HttpHeaders headers = new HttpHeaders();
        headers.putAll(response.getHeaders());

        Optional.ofNullable(headers.getLocation()).map(uri::resolve).ifPresent(headers::setLocation);

        Optional.ofNullable(headers.getFirst(CONTENT_LOCATION)).map(uri::resolve)
                .ifPresent(location -> headers.set(CONTENT_LOCATION, location.toASCIIString()));

        return new ForwardingClientHttpResponse() {

            @Override
            protected ClientHttpResponse delegate() {
                return response;
            }

            @Override
            public HttpHeaders getHeaders() {
                return headers;
            }

        };
    };
}

From source file:com.ecsteam.cloudlaunch.services.jenkins.JenkinsService.java

public QueuedBuildResponse triggerBuild() {
    String urlTemplate = "{baseUrl}/job/{jobName}/build";

    RestTemplate template = new RestTemplate();
    ResponseEntity<Object> response = template.exchange(urlTemplate, HttpMethod.POST, getAuthorizationEntity(),
            Object.class, baseUrl, jobName);

    if (HttpStatus.CREATED.equals(response.getStatusCode())) {
        HttpHeaders headers = response.getHeaders();
        URI queueUri = headers.getLocation();

        String last = null;/*from   ww  w  . ja v  a 2 s . c o  m*/
        String current = null;
        String next = null;

        String[] parts = queueUri.getPath().split("/");

        QueuedBuildResponse responseObject = new QueuedBuildResponse();
        for (int i = parts.length - 1; i >= 0; --i) {
            last = parts[i];
            current = parts[i - 1];
            next = parts[i - 2];

            if ("queue".equals(next) && "item".equals(current)) {
                responseObject = new QueuedBuildResponse();
                responseObject.setMonitorUri(String.format("/services/builds/queue/%s", last));

                return responseObject;
            }
        }
    }
    return null;
}

From source file:edu.colorado.orcid.impl.OrcidServicePublicImpl.java

public String createOrcid(String email, String givenNames, String familyName)
        throws OrcidException, OrcidEmailExistsException, OrcidHttpException {

    String newOrcid = null;//from  ww  w.j  a  va 2s .  c o  m

    log.debug("Creating ORCID...");
    log.debug("email: " + email);
    log.debug("givenNames: " + givenNames);
    log.debug("familyName: " + familyName);

    HttpHeaders headers = new HttpHeaders();
    headers.set("Accept", "application/xml");
    headers.set("Content-Type", "application/vdn.orcid+xml");
    headers.set("Authorization", "Bearer " + orcidCreateToken);

    OrcidMessage message = new OrcidMessage();
    message.setEmail(email);
    message.setGivenNames(givenNames);
    message.setFamilyName(familyName);
    message.setMessageVersion(orcidMessageVersion);
    //TODO Affiliation should be set based on organization once faculty from more than one organization are processed
    message.setAffiliationType(OrcidMessage.AFFILIATION_TYPE_EMPLOYMENT);
    message.setAffiliationOrganizationName(OrcidMessage.CU_BOULDER);
    message.setAffiliationOrganizationAddressCity(OrcidMessage.BOULDER);
    message.setAffiliationOrganizationAddressRegion(OrcidMessage.CO);
    message.setAffiliationOrganizationAddressCountry(OrcidMessage.US);
    message.setAffiliationOrganizationDisambiguatedId(OrcidMessage.DISAMBIGUATED_ID_CU_BOULDER);
    message.setAffiliationOrganizationDisambiguationSource(OrcidMessage.DISAMBIGUATION_SOURCE_RINGOLD);

    HttpEntity entity = new HttpEntity(message, headers);

    log.debug("Configured RestTemplate Message Converters...");
    List<HttpMessageConverter<?>> converters = orcidRestTemplate.getMessageConverters();
    for (HttpMessageConverter<?> converter : converters) {
        log.debug("converter: " + converter);
        log.debug("supported media types: " + converter.getSupportedMediaTypes());
        log.debug("converter.canWrite(String.class, MediaType.APPLICATION_XML): "
                + converter.canWrite(String.class, MediaType.APPLICATION_XML));
        log.debug("converter.canWrite(Message.class, MediaType.APPLICATION_XML): "
                + converter.canWrite(OrcidMessage.class, MediaType.APPLICATION_XML));
    }

    log.debug("Request headers: " + headers);

    HttpStatus responseStatusCode = null;
    String responseBody = null;

    try {
        if (useTestHttpProxy.equalsIgnoreCase("TRUE")) {
            log.info("Using HTTP ***TEST*** proxy...");
            System.setProperty("http.proxyHost", testHttpProxyHost);
            System.setProperty("http.proxyPort", testHttpProxyPort);
            log.info("http.proxyHost: " + System.getProperty("http.proxyHost"));
            log.info("http.proxyPort: " + System.getProperty("http.proxyPort"));
        }
        ResponseEntity<String> responseEntity = orcidRestTemplate.postForEntity(orcidCreateURL, entity,
                String.class);
        responseStatusCode = responseEntity.getStatusCode();
        responseBody = responseEntity.getBody();
        HttpHeaders responseHeaders = responseEntity.getHeaders();
        URI locationURI = responseHeaders.getLocation();
        String uriString = locationURI.toString();
        newOrcid = extractOrcid(uriString);
        log.debug("HTTP response status code: " + responseStatusCode);
        log.debug("HTTP response headers:     " + responseHeaders);
        log.debug("HTTP response body:        " + responseBody);
        log.debug("HTTP response location:    " + locationURI);
        log.debug("New ORCID:                 " + newOrcid);
    } catch (HttpClientErrorException e) {
        if (e.getStatusCode().equals(HttpStatus.BAD_REQUEST)) {
            log.debug(e.getStatusCode());
            log.debug(e.getResponseBodyAsString());
            log.debug(e.getMessage());
            throw new OrcidEmailExistsException(e);
        }
        OrcidHttpException ohe = new OrcidHttpException(e);
        ohe.setStatusCode(e.getStatusCode());
        throw ohe;
    }

    return newOrcid;
}

From source file:ch.wisv.areafiftylan.users.controller.UserRestController.java

/**
 * This method accepts POST requests on /users. It will send the input to the {@link UserService} to create a new
 * user//from w ww .j ava2  s . com
 *
 * @param input The user that has to be created. It consists of 3 fields. The username, the email and the plain-text
 *              password. The password is saved hashed using the BCryptPasswordEncoder
 *
 * @return The generated object, in JSON format.
 */
@RequestMapping(method = RequestMethod.POST)
public ResponseEntity<?> add(HttpServletRequest request, @Validated @RequestBody UserDTO input) {
    User save = userService.create(input, request);

    // Create headers to set the location of the created User object.
    HttpHeaders httpHeaders = new HttpHeaders();
    httpHeaders.setLocation(ServletUriComponentsBuilder.fromCurrentRequest().path("/{id}")
            .buildAndExpand(save.getId()).toUri());

    return createResponseEntity(HttpStatus.CREATED, httpHeaders,
            "User successfully created at " + httpHeaders.getLocation(), save);
}

From source file:ch.wisv.areafiftylan.teams.controller.TeamRestController.java

/**
 * The method to handle POST requests on the /teams endpoint. This creates a new team. Users can only create new
 * Teams with themselves as Captain. Admins can also create Teams with other Users as Captain.
 *
 * @param teamDTO Object containing the Team name and Captain username. When coming from a user, username should
 *                equal their own username.
 * @param auth    Authentication object from Spring Security
 *
 * @return Return status message of the operation
 *///from   w w  w  .j  a v a 2 s.c o m
@PreAuthorize("isAuthenticated() and @currentUserServiceImpl.hasAnyTicket(principal)")
@JsonView(View.Public.class)
@RequestMapping(method = RequestMethod.POST)
ResponseEntity<?> add(@Validated @RequestBody TeamDTO teamDTO, Authentication auth) {
    if (teamService.teamnameUsed(teamDTO.getTeamName())) {
        return createResponseEntity(HttpStatus.CONFLICT,
                "Team with name \"" + teamDTO.getTeamName() + "\" already exists.");
    }

    Team team;
    // Users can only create teams with themselves as Captain
    if (auth.getAuthorities().contains(Role.ROLE_ADMIN)) {
        team = teamService.create(teamDTO.getCaptainUsername(), teamDTO.getTeamName());
    } else {
        // If the DTO contains another username as the the current user, return an error.
        if (!auth.getName().equalsIgnoreCase(teamDTO.getCaptainUsername())) {
            return createResponseEntity(HttpStatus.BAD_REQUEST,
                    "Can not create team with another user as Captain");
        }
        team = teamService.create(auth.getName(), teamDTO.getTeamName());
    }

    HttpHeaders httpHeaders = new HttpHeaders();
    httpHeaders.setLocation(ServletUriComponentsBuilder.fromCurrentRequest().path("/{id}")
            .buildAndExpand(team.getId()).toUri());

    return createResponseEntity(HttpStatus.CREATED, httpHeaders,
            "Team successfully created at " + httpHeaders.getLocation(), team);
}

From source file:ch.wisv.areafiftylan.products.controller.OrderRestController.java

@PreAuthorize("hasRole('ADMIN')")
@JsonView(View.OrderOverview.class)
@RequestMapping(value = "/users/{userId}/orders", method = RequestMethod.POST)
public ResponseEntity<?> createAdminOrder(@PathVariable Long userId,
        @RequestBody @Validated TicketDTO ticketDTO) {
    HttpHeaders headers = new HttpHeaders();
    Order order = orderService.create(userId, ticketDTO);

    headers.setLocation(ServletUriComponentsBuilder.fromCurrentContextPath().path("/orders/{id}")
            .buildAndExpand(order.getId()).toUri());

    return createResponseEntity(HttpStatus.CREATED, headers,
            "Ticket available and order successfully created at " + headers.getLocation(), order);
}

From source file:ch.wisv.areafiftylan.products.controller.OrderRestController.java

/**
 * When a User does a POST request to /orders, a new Order is created. The requestbody is a TicketDTO, so an order
 * always contains at least one ticket. Optional next tickets should be added to the order by POSTing to the
 * location provided./*  w w w.  j av a2  s. com*/
 *
 * @param auth      The User that is currently logged in
 * @param ticketDTO Object containing information about the Ticket that is being ordered.
 *
 * @return A message informing about the result of the request
 */
@PreAuthorize("isAuthenticated()")
@RequestMapping(value = "/orders", method = RequestMethod.POST)
@JsonView(View.OrderOverview.class)
public ResponseEntity<?> createOrder(Authentication auth, @RequestBody @Validated TicketDTO ticketDTO) {
    HttpHeaders headers = new HttpHeaders();
    User user = (User) auth.getPrincipal();

    // You can't buy non-buyable Tickts for yourself, this should be done via the createAdminOrder() method.
    if (!ticketDTO.getType().isBuyable()) {
        return createResponseEntity(HttpStatus.FORBIDDEN,
                "Can't order tickets with type " + ticketDTO.getType().getText());
    }

    Order order = orderService.create(user.getId(), ticketDTO);

    headers.setLocation(ServletUriComponentsBuilder.fromCurrentRequest().path("/{id}")
            .buildAndExpand(order.getId()).toUri());

    return createResponseEntity(HttpStatus.CREATED, headers,
            "Ticket available and order successfully created at " + headers.getLocation(), order);
}

From source file:com.vmware.bdd.cli.rest.RestClient.java

private TaskRead processResponse(ResponseEntity<String> response, HttpMethod verb, PrettyOutput... prettyOutput)
        throws Exception {

    HttpStatus responseStatus = response.getStatusCode();
    if (responseStatus == HttpStatus.ACCEPTED) {//Accepted with task in the location header
        //get task uri from response to trace progress
        HttpHeaders headers = response.getHeaders();
        URI taskURI = headers.getLocation();
        String[] taskURIs = taskURI.toString().split("/");
        String taskId = taskURIs[taskURIs.length - 1];

        TaskRead taskRead;// w w  w  .j  a v a2 s . co m
        int oldProgress = 0;
        Status oldTaskStatus = null;
        Status taskStatus = null;
        int progress = 0;
        do {
            ResponseEntity<TaskRead> taskResponse = restGetById(Constants.REST_PATH_TASK, taskId,
                    TaskRead.class, false);

            //task will not return exception as it has status
            taskRead = taskResponse.getBody();

            progress = (int) (taskRead.getProgress() * 100);
            taskStatus = taskRead.getStatus();

            //fix cluster deletion exception
            Type taskType = taskRead.getType();
            if ((taskType == Type.DELETE) && (taskStatus == TaskRead.Status.COMPLETED)) {
                clearScreen();
                System.out.println(taskStatus + " " + progress + "%\n");
                break;
            }

            if (taskType == Type.SHRINK && !taskRead.getFailNodes().isEmpty()) {
                throw new CliRestException(taskRead.getFailNodes().get(0).getErrorMessage());
            }

            if ((prettyOutput != null && prettyOutput.length > 0 && prettyOutput[0].isRefresh(true))
                    || oldTaskStatus != taskStatus || oldProgress != progress) {
                //clear screen and show progress every few seconds
                clearScreen();
                //output completed task summary first in the case there are several related tasks
                if (prettyOutput != null && prettyOutput.length > 0
                        && prettyOutput[0].getCompletedTaskSummary() != null) {
                    for (String summary : prettyOutput[0].getCompletedTaskSummary()) {
                        System.out.println(summary + "\n");
                    }
                }
                System.out.println(taskStatus + " " + progress + "%\n");

                if (prettyOutput != null && prettyOutput.length > 0) {
                    // print call back customize the detailed output case by case
                    prettyOutput[0].prettyOutput();
                }

                if (oldTaskStatus != taskStatus || oldProgress != progress) {
                    oldTaskStatus = taskStatus;
                    oldProgress = progress;
                    if (taskRead.getProgressMessage() != null) {
                        System.out.println(taskRead.getProgressMessage());
                    }
                }
            }
            try {
                Thread.sleep(3 * 1000);
            } catch (InterruptedException ex) {
                //ignore
            }
        } while (taskStatus != TaskRead.Status.COMPLETED && taskStatus != TaskRead.Status.FAILED
                && taskStatus != TaskRead.Status.ABANDONED && taskStatus != TaskRead.Status.STOPPED);

        String errorMsg = taskRead.getErrorMessage();
        if (!taskRead.getStatus().equals(TaskRead.Status.COMPLETED)) {
            throw new CliRestException(errorMsg);
        } else { //completed
            if (taskRead.getType().equals(Type.VHM)) {
                logger.info("task type is vhm");
                Thread.sleep(5 * 1000);
                if (prettyOutput != null && prettyOutput.length > 0 && prettyOutput[0].isRefresh(true)) {
                    //clear screen and show progress every few seconds
                    clearScreen();
                    System.out.println(taskStatus + " " + progress + "%\n");

                    // print call back customize the detailed output case by case
                    if (prettyOutput != null && prettyOutput.length > 0) {
                        prettyOutput[0].prettyOutput();
                    }
                }
            } else {
                return taskRead;
            }
        }
    }
    return null;
}

From source file:org.springframework.cloud.stream.app.http.source.DefaultMixedCaseContentTypeHttpHeaderMapper.java

private Object getHttpHeader(HttpHeaders source, String name) {
    if (ACCEPT.equalsIgnoreCase(name)) {
        return source.getAccept();
    } else if (ACCEPT_CHARSET.equalsIgnoreCase(name)) {
        return source.getAcceptCharset();
    } else if (ALLOW.equalsIgnoreCase(name)) {
        return source.getAllow();
    } else if (CACHE_CONTROL.equalsIgnoreCase(name)) {
        String cacheControl = source.getCacheControl();
        return (StringUtils.hasText(cacheControl)) ? cacheControl : null;
    } else if (CONTENT_LENGTH.equalsIgnoreCase(name)) {
        long contentLength = source.getContentLength();
        return (contentLength > -1) ? contentLength : null;
    } else if (CONTENT_TYPE.equalsIgnoreCase(name)) {
        return source.getContentType();
    } else if (DATE.equalsIgnoreCase(name)) {
        long date = source.getDate();
        return (date > -1) ? date : null;
    } else if (ETAG.equalsIgnoreCase(name)) {
        String eTag = source.getETag();
        return (StringUtils.hasText(eTag)) ? eTag : null;
    } else if (EXPIRES.equalsIgnoreCase(name)) {
        try {/*  w  w w .ja  va2 s  .c om*/
            long expires = source.getExpires();
            return (expires > -1) ? expires : null;
        } catch (Exception e) {
            if (logger.isDebugEnabled()) {
                logger.debug(e.getMessage());
            }
            // According to RFC 2616
            return null;
        }
    } else if (IF_NONE_MATCH.equalsIgnoreCase(name)) {
        return source.getIfNoneMatch();
    } else if (IF_MODIFIED_SINCE.equalsIgnoreCase(name)) {
        long modifiedSince = source.getIfModifiedSince();
        return (modifiedSince > -1) ? modifiedSince : null;
    } else if (IF_UNMODIFIED_SINCE.equalsIgnoreCase(name)) {
        String unmodifiedSince = source.getFirst(IF_UNMODIFIED_SINCE);
        return unmodifiedSince != null ? this.getFirstDate(unmodifiedSince, IF_UNMODIFIED_SINCE) : null;
    } else if (LAST_MODIFIED.equalsIgnoreCase(name)) {
        long lastModified = source.getLastModified();
        return (lastModified > -1) ? lastModified : null;
    } else if (LOCATION.equalsIgnoreCase(name)) {
        return source.getLocation();
    } else if (PRAGMA.equalsIgnoreCase(name)) {
        String pragma = source.getPragma();
        return (StringUtils.hasText(pragma)) ? pragma : null;
    }
    return source.get(name);
}

From source file:org.springframework.integration.http.support.DefaultHttpHeaderMapper.java

private Object getHttpHeader(HttpHeaders source, String name) {
    if (ACCEPT.equalsIgnoreCase(name)) {
        return source.getAccept();
    } else if (ACCEPT_CHARSET.equalsIgnoreCase(name)) {
        return source.getAcceptCharset();
    } else if (ALLOW.equalsIgnoreCase(name)) {
        return source.getAllow();
    } else if (CACHE_CONTROL.equalsIgnoreCase(name)) {
        String cacheControl = source.getCacheControl();
        return (StringUtils.hasText(cacheControl)) ? cacheControl : null;
    } else if (CONTENT_LENGTH.equalsIgnoreCase(name)) {
        long contentLength = source.getContentLength();
        return (contentLength > -1) ? contentLength : null;
    } else if (CONTENT_TYPE.equalsIgnoreCase(name)) {
        return source.getContentType();
    } else if (DATE.equalsIgnoreCase(name)) {
        long date = source.getDate();
        return (date > -1) ? date : null;
    } else if (ETAG.equalsIgnoreCase(name)) {
        String eTag = source.getETag();
        return (StringUtils.hasText(eTag)) ? eTag : null;
    } else if (EXPIRES.equalsIgnoreCase(name)) {
        try {/*from  w ww .ja v  a2 s  . c  o  m*/
            long expires = source.getExpires();
            return (expires > -1) ? expires : null;
        } catch (Exception e) {
            if (logger.isDebugEnabled()) {
                logger.debug(e.getMessage());
            }
            // According to RFC 2616
            return null;
        }
    } else if (IF_NONE_MATCH.equalsIgnoreCase(name)) {
        return source.getIfNoneMatch();
    } else if (IF_UNMODIFIED_SINCE.equalsIgnoreCase(name)) {
        long unmodifiedSince = source.getIfNotModifiedSince();
        return (unmodifiedSince > -1) ? unmodifiedSince : null;
    } else if (LAST_MODIFIED.equalsIgnoreCase(name)) {
        long lastModified = source.getLastModified();
        return (lastModified > -1) ? lastModified : null;
    } else if (LOCATION.equalsIgnoreCase(name)) {
        return source.getLocation();
    } else if (PRAGMA.equalsIgnoreCase(name)) {
        String pragma = source.getPragma();
        return (StringUtils.hasText(pragma)) ? pragma : null;
    }
    return source.get(name);
}