Example usage for org.springframework.http ResponseEntity ok

List of usage examples for org.springframework.http ResponseEntity ok

Introduction

In this page you can find the example usage for org.springframework.http ResponseEntity ok.

Prototype

public static <T> ResponseEntity<T> ok(T body) 

Source Link

Document

A shortcut for creating a ResponseEntity with the given body and the status set to HttpStatus#OK OK .

Usage

From source file:com.haulmont.restapi.idp.IdpAuthLifecycleManager.java

@Order(Events.HIGHEST_PLATFORM_PRECEDENCE + 100)
@EventListener//from w w w .ja  v  a 2s. co  m
public void handleOAuthTokenRevocationResponse(OAuthTokenRevokedResponseEvent event) {
    if (idpConfig.getIdpEnabled()) {
        if (event.getTokenValue() != null) {
            log.debug("OAuth2AccessToken {} revoked by client, redirect to IDP", event.getTokenValue());

            String idpLoginUrl = getIdpLogoutUrl(idpConfig.getIdpDefaultRedirectUrl());

            event.setResponseEntity(ResponseEntity.ok(new IdpLogoutResponse(idpLoginUrl)));
        }
    }
}

From source file:jp.classmethod.aws.brian.web.TriggerController.java

/**
 * Delete specified triggerGroup (belonging triggers).
 * //w w w.  j a  v  a 2  s  . co  m
 * @param triggerGroupName trigger group name
 * @return wherther the trigger is removed
 * @throws SchedulerException
 */
@ResponseBody
@RequestMapping(value = "/triggers/{triggerGroupName}/", method = RequestMethod.DELETE)
public ResponseEntity<?> deleteTriggerGroup(@PathVariable("triggerGroupName") String triggerGroupName)
        throws SchedulerException {
    logger.info("deleteTriggerGroup {}", triggerGroupName);

    List<String> triggers = listTriggers(triggerGroupName);
    Set<String> failed = triggers.stream().filter(triggerName -> {
        TriggerKey triggerKey = TriggerKey.triggerKey(triggerName, triggerGroupName);
        try {
            return scheduler.unscheduleJob(triggerKey) == false;
        } catch (SchedulerException e) {
            logger.error("unexpected", e);
        }
        return false;
    }).collect(Collectors.toSet());

    if (failed.isEmpty()) {
        return ResponseEntity.ok(triggers);
    }
    Map<String, Object> map = new HashMap<>();
    map.put("failed", failed);
    map.put("deleted", triggers.stream().filter(t -> failed.contains(t) == false).collect(Collectors.toList()));
    return ResponseEntity.status(HttpStatus.INTERNAL_SERVER_ERROR)
            .body(new BrianResponse<>(false, "failed to unschedule", map));
}

From source file:com.haulmont.restapi.ldap.LdapAuthController.java

@RequestMapping(value = "/v2/ldap/token", method = RequestMethod.POST)
public ResponseEntity<OAuth2AccessToken> postAccessToken(Principal principal,
        @RequestParam Map<String, String> parameters, HttpServletRequest request)
        throws HttpRequestMethodNotSupportedException {

    if (!ldapConfig.getLdapEnabled()) {
        log.debug("LDAP authentication is disabled. Property cuba.rest.ldap.enabled is false");

        throw new InvalidGrantException("LDAP is not supported");
    }//www  . j  a va2s .c  om

    if (!(principal instanceof Authentication)) {
        throw new InsufficientAuthenticationException(
                "There is no client authentication. Try adding an appropriate authentication filter.");
    }

    String grantType = parameters.get(OAuth2Utils.GRANT_TYPE);
    if (!"password".equals(grantType)) {
        throw new InvalidGrantException("grant type not supported for ldap/token endpoint");
    }

    String username = parameters.get("username");

    if (restApiConfig.getStandardAuthenticationUsers().contains(username)) {
        log.info("User {} is not allowed to use external login in REST API", username);
        throw new BadCredentialsException("Bad credentials");
    }

    String ipAddress = request.getRemoteAddr();

    String password = parameters.get("password");

    OAuth2AccessTokenResult tokenResult = authenticate(username, password, request.getLocale(), ipAddress,
            parameters);

    return ResponseEntity.ok(tokenResult.getAccessToken());
}

From source file:com.oembedler.moon.graphql.boot.GraphQLServerController.java

@RequestMapping(method = RequestMethod.POST, consumes = "application/json")
public ResponseEntity<Map<String, Object>> postJson(@RequestBody Map<String, Object> body,
        @RequestHeader(value = HEADER_SCHEMA_NAME, required = false) String graphQLSchemaName,
        HttpServletRequest httpServletRequest) {

    final String query = (String) body.get(getQueryKey());
    final String operationName = (String) body.get(DEFAULT_OPERATION_NAME_KEY);

    Map<String, Object> variables = null;
    Object variablesObject = body.get(getVariablesKey());
    if (variablesObject != null && variablesObject instanceof Map)
        variables = (Map<String, Object>) variablesObject;

    final GraphQLContext graphQLContext = new GraphQLContext();
    graphQLContext.setHttpRequest(httpServletRequest);

    final Map<String, Object> result = evaluateAndBuildResponseMap(query, operationName, graphQLContext,
            variables, graphQLSchemaName);

    return ResponseEntity.ok(result);
}

From source file:com.haulmont.restapi.idp.IdpAuthController.java

@PostMapping(value = "/v2/idp/token")
public ResponseEntity<OAuth2AccessToken> postAccessToken(Principal principal,
        @RequestParam Map<String, String> parameters, HttpServletRequest request)
        throws HttpRequestMethodNotSupportedException {

    if (!idpConfig.getIdpEnabled()) {
        log.debug("IDP authentication is disabled. Property cuba.rest.idp.enabled is false");

        throw new InvalidGrantException("IDP is not supported");
    }/*w ww  .j  a  v  a2  s  . c o m*/

    if (!(principal instanceof Authentication)) {
        throw new InsufficientAuthenticationException(
                "There is no client authentication. Try adding an appropriate authentication filter.");
    }

    // we cannot perform brute-force check here, since we don't know username

    String idpTicket = parameters.get("idp_ticket");
    String ipAddress = request.getRemoteAddr();

    OAuth2AccessTokenResult tokenResult = authenticate(idpTicket, request.getLocale(), ipAddress, parameters);

    return ResponseEntity.ok(tokenResult.getAccessToken());
}

From source file:io.ignitr.dispatchr.manager.controller.topic.TopicsController.java

/**
 * Find all SNS topics that have been registered with Dispatchr.
 *
 * @param offset index of item to start returning when using pagination
 * @param limit number of items to return when using pagination
 * @param sortDir sort order in which to return items when using pagination
 * @return an HTTP 200 response if the request was successful
 *//*from   w  w w  .ja  v a  2s . c o  m*/
@RequestMapping(method = RequestMethod.GET, value = "/registered", produces = MediaType.APPLICATION_JSON_VALUE)
public DeferredResult<ResponseEntity<FindTopicsResponse>> findRegistered(
        @RequestParam(value = "offset", defaultValue = "0") Long offset,
        @RequestParam(value = "limit", defaultValue = "25") Long limit,
        @RequestParam(value = "sort_dir", defaultValue = "asc") String sortDir,
        HttpServletRequest httpRequest) {
    final DeferredResult<ResponseEntity<FindTopicsResponse>> deferredResult = new DeferredResult<>();

    Observable.fromCallable(() -> SortDirectionValidator.validate(sortDir))
            .lift(new RequestContextStashOperator<>())
            .flatMap(valid -> Observable.create(new Observable.OnSubscribe<List<Topic>>() {
                List<Topic> topicMetadatas = new ArrayList<>();

                @Override
                public void call(Subscriber<? super List<Topic>> subscriber) {
                    service.findRegistered(offset, limit, sortDir).collect(() -> topicMetadatas, List::add)
                            .subscribe(topicMetadatas -> {
                                subscriber.onNext(topicMetadatas);
                                subscriber.onCompleted();
                            });
                }
            })).map(FindTopicsResponse::from).subscribeOn(Schedulers.io()).subscribe(body -> {
                deferredResult.setResult(ResponseEntity.ok(body));
            }, error -> {
                deferredResult.setErrorResult(errorHandler.handleError(httpRequest, error));
            });

    return deferredResult;
}

From source file:alfio.controller.api.admin.AdditionalServiceApiController.java

@RequestMapping(value = "/event/{eventId}/additional-services/{additionalServiceId}", method = RequestMethod.PUT)
@Transactional/* w ww  . j  a v  a  2  s. com*/
public ResponseEntity<EventModification.AdditionalService> update(@PathVariable("eventId") int eventId,
        @PathVariable("additionalServiceId") int additionalServiceId,
        @RequestBody EventModification.AdditionalService additionalService, BindingResult bindingResult) {
    ValidationResult validationResult = Validator.validateAdditionalService(additionalService, bindingResult);
    Validate.isTrue(validationResult.isSuccess(), "validation failed");
    Validate.isTrue(additionalServiceId == additionalService.getId(), "wrong input");
    return eventRepository.findOptionalById(eventId).map(event -> {
        int result = additionalServiceRepository.update(additionalServiceId, additionalService.isFixPrice(),
                additionalService.getOrdinal(), additionalService.getAvailableQuantity(),
                additionalService.getMaxQtyPerOrder(),
                additionalService.getInception().toZonedDateTime(event.getZoneId()),
                additionalService.getExpiration().toZonedDateTime(event.getZoneId()),
                additionalService.getVat(), additionalService.getVatType(),
                Optional.ofNullable(additionalService.getPrice()).map(MonetaryUtil::unitToCents).orElse(0));
        Validate.isTrue(result <= 1, "too many records updated");
        Stream.concat(additionalService.getTitle().stream(), additionalService.getDescription().stream())
                .forEach(t -> {
                    if (t.getId() != null) {
                        additionalServiceTextRepository.update(t.getId(), t.getLocale(), t.getType(),
                                t.getValue());
                    } else {
                        additionalServiceTextRepository.insert(additionalService.getId(), t.getLocale(),
                                t.getType(), t.getValue());
                    }
                });
        return ResponseEntity.ok(additionalService);
    }).orElseThrow(IllegalArgumentException::new);
}

From source file:org.createnet.raptor.auth.service.controller.AuthenticationController.java

@PreAuthorize("isAuthenticated()")
@RequestMapping(value = "${jwt.route.authentication.refresh}", method = RequestMethod.GET)
@ApiOperation(value = "Refresh a login token", notes = "The authentication token, provided via `Authorization` header must still be valid.", response = JwtResponse.class, nickname = "refreshToken")
public ResponseEntity<?> refreshToken(HttpServletRequest request, Principal principal) {

    String reqToken = request.getHeader(tokenHeader).replace("Bearer ", "");
    Token token = tokenService.read(reqToken);

    if (token == null) {
        return ResponseEntity.badRequest().body(null);
    }//ww  w .  ja  v a2  s .  c  o  m

    Token refreshedToken = tokenService.refreshToken(token);
    return ResponseEntity.ok(new JwtResponse((User) principal, refreshedToken.getToken()));
}

From source file:blankd.acme.pet.licensing.rest.controller.LicenseRestController.java

@RequestMapping(value = "/assign/force/{id}", method = RequestMethod.POST)
public ResponseEntity<?> forceAssignPetToLicense(@PathVariable String id, @RequestParam Long petId,
        @RequestParam String username) {
    License ret = this.repo.findOne(id);

    if (ret != null) {

        Pet pet = this.pRepo.findById(petId);
        if (pet == null) {
            ErrorMessage err = new ErrorMessage("Could not find pet");
            return ResponseEntity.ok(err);
        }//from   ww w  .jav a  2 s .co  m

        Account owner = this.aRepo.findByUsername(username);

        if (owner == null) {
            ErrorMessage err = new ErrorMessage("Could not find Account");
            return ResponseEntity.ok(err);
        }

        ret.setPet(pet);
        ret.setPetOwner(owner);
        ret.setExpires(this.generateExpireDate());

        return ResponseEntity.ok(this.repo.save(ret));
    } else {
        ErrorMessage err = new ErrorMessage("Could not assign license");
        return ResponseEntity.ok(err);
    }
}

From source file:io.ignitr.dispatchr.manager.controller.topic.TopicController.java

/**
 * Unregister an SNS topic with Dispatchr.
 *
 * @param topicName the name of the topic to delete
 * @param httpRequest http request//from   w  ww  .j  a v a 2 s . c o  m
 * @return an HTTP 204 response if the request was successful
 */
@RequestMapping(method = RequestMethod.DELETE, value = "/registered", produces = MediaType.APPLICATION_JSON_VALUE)
public DeferredResult<ResponseEntity<?>> unregister(@PathVariable("name") String topicName,
        HttpServletRequest httpRequest) {
    final DeferredResult<ResponseEntity<?>> deferredResult = new DeferredResult<>();

    service.unregister(topicName).lift(new RequestContextStashOperator<>()).last()
            .map(UnregisterTopicResponse::from).subscribeOn(Schedulers.io()).subscribe(body -> {
                deferredResult.setResult(ResponseEntity.ok(body));
            }, error -> {
                deferredResult.setErrorResult(errorHandler.handleError(httpRequest, error));
            });

    return deferredResult;
}