Example usage for org.springframework.http HttpHeaders setLocation

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

Introduction

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

Prototype

public void setLocation(@Nullable URI location) 

Source Link

Document

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

Usage

From source file:za.ac.cput.project.universalhardwarestorev2.api.LoginApi.java

@RequestMapping(value = "/login/create", method = RequestMethod.POST)
public ResponseEntity<Void> createLogin(@RequestBody Login login, UriComponentsBuilder ucBuilder) {
    System.out.println("Creating Login " + login.getName());

    //USE THIS IF YOU WANT TO CHECK UNIQUE OBJECT
    //      if (LoginService.isLoginExist(login)) {
    //            System.out.println("A Login with name " + Login.getName() + " already exist");
    //            return new ResponseEntity<Void>(HttpStatus.CONFLICT);
    //        }//from www  .j a  va 2s . co  m

    service.save(login);

    HttpHeaders headers = new HttpHeaders();
    headers.setLocation(ucBuilder.path("/login/{id}").buildAndExpand(login.getId()).toUri());
    return new ResponseEntity<Void>(headers, HttpStatus.CREATED);
}

From source file:io.github.howiefh.jeews.modules.oauth2.controller.AuthorizeController.java

@RequestMapping("/authentication")
public Object authorize(HttpServletRequest request) throws URISyntaxException, OAuthSystemException {
    try {//from   w w w .  j a v a  2 s. co  m

        // OAuth ?
        OAuthAuthzRequest oauthRequest = new OAuthAuthzRequest(request);

        // id?
        if (!oAuthService.checkClientId(oauthRequest.getClientId())) {
            OAuthResponse response = OAuthASResponse.errorResponse(HttpServletResponse.SC_BAD_REQUEST)
                    .setError(OAuthError.TokenResponse.INVALID_CLIENT)
                    .setErrorDescription(Constants.INVALID_CLIENT_DESCRIPTION).buildJSONMessage();
            return new ResponseEntity<String>(response.getBody(),
                    HttpStatus.valueOf(response.getResponseStatus()));
        }

        Subject subject = SecurityUtils.getSubject();
        // ?
        if (!subject.isAuthenticated()) {
            if (!login(subject, request)) {// ?
                // TODO
                HttpHeaders headers = new HttpHeaders();
                headers.setLocation(new URI(loginUrl));
                return new ResponseEntity<Object>(headers, HttpStatus.UNAUTHORIZED);
            }
        }

        String username = (String) subject.getPrincipal();
        // ???
        String authorizationCode = null;
        // responseType??CODE?TOKEN
        String responseType = oauthRequest.getParam(OAuth.OAUTH_RESPONSE_TYPE);
        OAuthIssuerImpl oauthIssuerImpl = new OAuthIssuerImpl(new MD5Generator());
        // OAuth?
        OAuthASResponse.OAuthAuthorizationResponseBuilder builder = OAuthASResponse
                .authorizationResponse(request, HttpServletResponse.SC_FOUND);
        if (responseType.equals(ResponseType.CODE.toString())) {
            authorizationCode = oauthIssuerImpl.authorizationCode();
            oAuthService.addAuthCode(authorizationCode, username);
            // ??
            builder.setCode(authorizationCode);
        } else if (responseType.equals(ResponseType.TOKEN.toString())) {
            final String accessToken = oauthIssuerImpl.accessToken();
            oAuthService.addAccessToken(accessToken, username);
            builder.setAccessToken(accessToken);
            builder.setParam("token_type", TokenType.BEARER.toString());
            builder.setExpiresIn(oAuthService.getExpireIn());
        }

        // ???
        String redirectURI = oauthRequest.getParam(OAuth.OAUTH_REDIRECT_URI);

        // ?
        final OAuthResponse response = builder.location(redirectURI).buildQueryMessage();

        // ?OAuthResponseResponseEntity?
        HttpHeaders headers = new HttpHeaders();
        headers.setLocation(new URI(response.getLocationUri()));
        return new ResponseEntity<Object>(headers, HttpStatus.valueOf(response.getResponseStatus()));
    } catch (OAuthProblemException e) {
        // ?
        String redirectUri = e.getRedirectUri();
        if (OAuthUtils.isEmpty(redirectUri)) {
            // redirectUri
            return new ResponseEntity<String>("OAuth callback url needs to be provided by client!!!",
                    HttpStatus.NOT_FOUND);
        }

        // ??error=
        final OAuthResponse response = OAuthASResponse.errorResponse(HttpServletResponse.SC_FOUND).error(e)
                .location(redirectUri).buildQueryMessage();
        HttpHeaders headers = new HttpHeaders();
        headers.setLocation(new URI(response.getLocationUri()));
        return new ResponseEntity<Object>(headers, HttpStatus.valueOf(response.getResponseStatus()));
    }
}

From source file:com.bennavetta.appsite.webapi.SettingsController.java

@RequestMapping(method = POST, value = "/{name}")
public ResponseEntity<String> putSetting(@PathVariable String name, @RequestBody String value) {
    settings.set(name, value);/*from ww  w  .j ava  2s .c  o m*/
    log.trace("Setting {} = {}", name, value);
    HttpHeaders headers = new HttpHeaders();
    URI location = ServletUriComponentsBuilder.fromCurrentServletMapping().path("/settings/{name}").build()
            .expand(name).toUri();
    headers.setLocation(location);
    return new ResponseEntity<String>(headers, HttpStatus.CREATED);
}

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

/**
 * This method requests payment of the order, locks the order and needs to return information on how to proceed.
 * Depending on PaymentService./*from  w  w w  .j a v  a  2s  . c  o  m*/
 *
 * @param orderId The order to be paid
 *
 * @return Instructions on how to proceed.
 */
@PreAuthorize("@currentUserServiceImpl.canAccessOrder(principal, #orderId)")
@RequestMapping(value = "/orders/{orderId}/checkout", method = RequestMethod.GET)
public ResponseEntity<?> payOrder(@PathVariable Long orderId) throws URISyntaxException {
    String paymentUrl = orderService.requestPayment(orderId);
    HttpHeaders headers = new HttpHeaders();
    headers.setLocation(new URI(paymentUrl));

    return createResponseEntity(HttpStatus.OK, headers,
            "Please go to " + paymentUrl + " to finish your payment");
}

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 av a  2s.  c  om*/
@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:org.jrb.commons.web.controller.CrudControllerUtils.java

/**
 * Spring MVC controller utility method that creates a domain entity. Within
 * a successful response, the following HATEOAS link(s) generated:
 * <ul>//from ww w. j  a v  a 2  s  .co m
 * <li>a <em>self</em> link pointing to at which this entity may be found</li>
 * <li>a <em>collections</em> link giving access to all entities</li>
 * </ul>
 * 
 * @param entity
 *            the entity to be created
 * @param entityClass
 *            the class of the entity to be created
 * @param entityResponseClass
 *            the class to use in generating the response
 * @param controllerClass
 *            the controller class used for generating HATEOAS links
 * @param callback
 *            a callback containing the actual logic to create the entity
 * @return a Spring MVC response containing the newly-created entity
 */
public ResponseEntity<R> createEntity(final E entity, final Class<E> entityClass,
        final Class<R> entityResponseClass, final Class<?> controllerClass,
        final CreateEntityCallback<E> callback) {

    final R response = responseUtils.createResponse(entityResponseClass);
    final E createdEntity = callback.createEntity(entity);
    response.setEntity(createdEntity);

    response.add(linkTo(controllerClass).slash(createdEntity).withSelfRel());
    response.add(linkTo(controllerClass).withRel(entityRel(entityClass)));

    final HttpHeaders headers = new HttpHeaders();
    headers.setLocation(linkTo(getClass()).slash(createdEntity).toUri());

    return responseUtils.finalize(response, HttpStatus.CREATED, headers);
}

From source file:io.pivotal.strepsirrhini.chaoslemur.Destroyer.java

@RequestMapping(method = RequestMethod.POST, value = "/chaos", consumes = MediaType.APPLICATION_JSON_VALUE)
ResponseEntity<?> eventRequest(@RequestBody Map<String, String> payload) {
    String value = payload.get("event");

    if (value == null) {
        return new ResponseEntity<>(HttpStatus.BAD_REQUEST);
    }//from ww w  . j av a2 s .  c  o  m

    HttpHeaders responseHeaders = new HttpHeaders();

    if ("destroy".equals(value.toLowerCase())) {
        Task task = this.taskRepository.create(Trigger.MANUAL);
        this.executorService.execute(() -> doDestroy(task));
        responseHeaders.setLocation(this.taskUriBuilder.getUri(task));
    } else {
        return new ResponseEntity<>(HttpStatus.BAD_REQUEST);
    }

    return new ResponseEntity<>(responseHeaders, HttpStatus.ACCEPTED);
}

From source file:org.javersion.json.web.JsonStoreController.java

private ResponseEntity<String> getResponse(String objectId, Merge<PropertyPath, Object, Void> merge,
        boolean create) {
    Map<PropertyPath, Object> properties = new HashMap<>(merge.getProperties());
    VersionMetadata ref = new VersionMetadata(objectId, merge.getMergeHeads(), merge.conflicts);
    properties.putAll(metaSerializer.toPropertyMap(ref));
    HttpHeaders headers = new HttpHeaders();
    headers.set("Content-Type", "application/json;charset=UTF-8");
    HttpStatus status;/*from w  w w . j a va2s  . c  om*/
    if (create) {
        status = CREATED;
        try {
            headers.setLocation(new URI("/objects/" + objectId));
        } catch (URISyntaxException e) {
            throw new Error(e);
        }
    } else {
        status = OK;
    }
    return new ResponseEntity<String>(jsonSerializer.serialize(properties), headers, status);
}

From source file:com.salmon.security.xacml.demo.springmvc.rest.controller.MarketPlacePopulatorController.java

@RequestMapping(method = RequestMethod.POST, consumes = "application/json", produces = "application/json", value = "vehicleadd")
@ResponseStatus(HttpStatus.CREATED)//ww w. ja  v a 2 s.  c o m
@ResponseBody
public ResponseEntity<Vehicle> createVehicle(@RequestBody Vehicle vehicle, UriComponentsBuilder builder) {

    LOG.info("REST CREATE Vechicle - " + vehicle.toString());

    marketPlaceController.registerVehicle(vehicle);

    HttpHeaders headers = new HttpHeaders();

    URI newVehicleLocation = builder.path("/aggregators/dvla/vehicles/{plate}")
            .buildAndExpand(vehicle.getPlate()).toUri();

    LOG.info("REST CREATE VEHICLE - new vehicle @ " + newVehicleLocation.toString());

    headers.setLocation(newVehicleLocation);

    return new ResponseEntity<Vehicle>(vehicle, headers, HttpStatus.CREATED);
}