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.yunmel.syncretic.core.BaseController.java

/**
 * ?/* w ww . jav a2s  .c  om*/
 * 
 * @param data
 * @return
 */
protected ResponseEntity<Result> ok(Object data) {
    return ResponseEntity.ok(Result.build(0, "?", data));
}

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

@RequestMapping(value = "/ops", method = RequestMethod.GET)
@ResponseBody//from   w  w  w. j  a  v a  2  s .  c  o m
public ResponseEntity<Long> getDokumenttiId(@RequestParam final Long opsId,
        @RequestParam(defaultValue = "fi") final String kieli) {
    Long dokumenttiId = service.getDokumenttiId(opsId, Kieli.of(kieli));
    return ResponseEntity.ok(dokumenttiId);
}

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

@ApiImplicitParams({
        @ApiImplicitParam(name = "dokumenttiId", dataType = "string", paramType = "path", required = true) })
@RequestMapping(value = "/{dokumenttiId}/tila", method = RequestMethod.GET)
public ResponseEntity<DokumenttiTila> exist(@RequestParam final Long opsId,
        @RequestParam(defaultValue = "fi") final String kieli) {
    Kieli k = Kieli.of(kieli);// w  w  w . j ava 2  s. c om
    DokumenttiTila tila = service.getTila(opsId, k);
    if (tila == null) {
        return new ResponseEntity<>(HttpStatus.NOT_FOUND);
    } else {
        return ResponseEntity.ok(tila);
    }
}

From source file:it.smartcommunitylab.aac.controller.TokenIntrospectionController.java

@ApiOperation(value = "Get token metadata")
@RequestMapping(method = RequestMethod.POST, value = "/token_introspection")
public ResponseEntity<AACTokenIntrospection> getTokenInfo(@RequestParam String token) {
    AACTokenIntrospection result = new AACTokenIntrospection();

    try {//from  w w w. j av  a 2  s.c o  m
        OAuth2Authentication auth = resourceServerTokenServices.loadAuthentication(token);

        OAuth2AccessToken storedToken = tokenStore.getAccessToken(auth);

        String clientId = auth.getOAuth2Request().getClientId();

        String userName = null;
        String userId = null;
        boolean applicationToken = false;

        if (auth.getPrincipal() instanceof User) {
            User principal = (User) auth.getPrincipal();
            userId = principal.getUsername();
        } else {
            ClientDetailsEntity client = clientDetailsRepository.findByClientId(clientId);
            applicationToken = true;
            userId = "" + client.getDeveloperId();
        }
        userName = userManager.getUserInternalName(Long.parseLong(userId));
        String localName = userName.substring(0, userName.lastIndexOf('@'));
        String tenant = userName.substring(userName.lastIndexOf('@') + 1);

        result.setUsername(localName);
        result.setClient_id(clientId);
        result.setScope(StringUtils.collectionToDelimitedString(auth.getOAuth2Request().getScope(), " "));
        result.setExp((int) (storedToken.getExpiration().getTime() / 1000));
        result.setIat(result.getExp() - storedToken.getExpiresIn());
        result.setIss(issuer);
        result.setNbf(result.getIat());
        result.setSub(userId);
        result.setAud(clientId);
        // jti is not supported in this form

        // only bearer tokens supported
        result.setToken_type(OAuth2AccessToken.BEARER_TYPE);
        result.setActive(true);

        result.setAac_user_id(userId);
        result.setAac_grantType(auth.getOAuth2Request().getGrantType());
        result.setAac_applicationToken(applicationToken);
        result.setAac_am_tenant(tenant);
    } catch (Exception e) {
        logger.error("Error getting info for token: " + e.getMessage());
        result = new AACTokenIntrospection();
        result.setActive(false);
    }
    return ResponseEntity.ok(result);
}

From source file:net.bis5.slack.command.gcal.SlashCommandApi.java

@RequestMapping(path = "/debug", method = RequestMethod.POST)
public ResponseEntity<String> execute(String body) {
    return ResponseEntity.ok(body);
}

From source file:net.bis5.slack.command.gcal.SlashCommandApi.java

@RequestMapping(path = "/execute", method = RequestMethod.POST)
public ResponseEntity<String> execute(@ModelAttribute RequestPayload payload) {
    log.info("Request: " + payload.toString());

    EventRequest event = payload.createEvent();
    log.info("Parsed Request: " + event.toString());

    try {/*  w ww  . j  a  va  2  s.c  om*/
        Event result = client.events().insert(config.getTargetCalendarId(), createEvent(event)).execute();
        log.info("Event Create Result: " + result.toString());

        ResponsePayload response = new ResponsePayload();
        Date date = toDate(event.getDate().atStartOfDay());
        Date start = toDate(LocalDateTime.of(event.getDate(), event.getFrom()));
        Date end = toDate(LocalDateTime.of(event.getDate(), event.getTo()));
        String user = payload.getUser_name();
        String title = event.getTitle();
        response.setText(String.format(
                "%s?????\n: %tY/%tm/%td\n: %tH:%tM\n: %tH:%tM\n??: %s", //
                user, date, date, date, start, start, end, end, title));

        try (CloseableHttpClient httpClient = HttpClients.createDefault()) {
            ObjectMapper mapper = new ObjectMapper();
            String responseBody = mapper.writeValueAsString(response);
            log.info("Response Payload: " + responseBody);
            Request.Post(payload.getResponse_url()).bodyString(responseBody, ContentType.APPLICATION_JSON)
                    .execute();
        }

        return ResponseEntity.ok(null);
    } catch (IOException ex) {
        log.error(ex.toString());
        return ResponseEntity.ok(ex.getMessage()); // OK??????????
    }
}

From source file:org.apereo.portal.rest.oauth.OidcUserInfoController.java

/**
 * Obtain an OIDC Id token for the specified <code>client_id</code>. At least one bean of type
 * {@link OAuthClient} is required to use this endpoint.
 *
 * <p>This token strategy supports Spring's <code>OAuth2RestTemplate</code> for accessing
 * uPortal REST APIs from external systems. Use a <code>ClientCredentialsResourceDetails</code>
 * with <code>clientAuthenticationScheme=AuthenticationScheme.form</code>, together with a
 * <code>ClientCredentialsAccessTokenProvider</code>.
 *
 * @since 5.5/* ww w. j av a  2s .  com*/
 */
@PostMapping(value = TOKEN_ENDPOINT_URI, produces = MediaType.APPLICATION_JSON_VALUE)
public ResponseEntity oauthToken(@RequestParam(value = "client_id") String clientId,
        @RequestParam(value = "client_secret") String clientSecret,
        @RequestParam(value = "grant_type", required = false, defaultValue = "client_credentials") String grantType,
        @RequestParam(value = "scope", required = false, defaultValue = "/all") String scope,
        @RequestParam(value = "claims", required = false) String claims,
        @RequestParam(value = "groups", required = false) String groups) {

    /*
     * NB:  Several of this method's parameters are not consumed (yet) in any way.  They are
     * defined to match a two-legged OAuth strategy and for future use.
     */

    final String msg = "Processing request for OAuth access token;  client_id='{}', client_secret='{}', "
            + "grant_type='{}', scope='{}', claims='{}', groups='{}'";
    logger.debug(msg, clientId, StringUtils.repeat("*", clientSecret.length()), grantType, scope, claims,
            groups);

    // STEP 1:  identify the client
    final OAuthClient oAuthClient = clientMap.get(clientId);
    if (oAuthClient == null) {
        return ResponseEntity.status(HttpStatus.FORBIDDEN)
                .body(Collections.singletonMap("message", "client_id not found"));
    }

    logger.debug("Selected known OAuthClient with client_id='{}' for access token request",
            oAuthClient.getClientId());

    // STEP 2:  validate the client_secret
    if (!oAuthClient.getClientSecret().equals(clientSecret)) {
        return ResponseEntity.status(HttpStatus.FORBIDDEN)
                .body(Collections.singletonMap("message", "authentication failed"));
    }

    // STEP 3:  obtain the specified user
    final IPerson person = personService.getPerson(oAuthClient.getPortalUserAccount());
    if (person == null) {
        return ResponseEntity.status(HttpStatus.INTERNAL_SERVER_ERROR).body(Collections.singletonMap("message",
                "portal user account not found: " + oAuthClient.getPortalUserAccount()));
    }

    logger.debug("Selected portal Person with username='{}' for client_id='{}'", person.getUserName(),
            oAuthClient.getClientId());

    // STEP 4:  build a standard OAuth2 access token response
    final String token = createToken(person, claims, groups);
    final Map<String, Object> rslt = new HashMap<>();
    rslt.put("access_token", token);
    rslt.put("token_type", "bearer");
    rslt.put("expires_in", timeoutSeconds > 2 ? timeoutSeconds - 2L /* fudge factor */ : timeoutSeconds);
    rslt.put("scope", scope);

    logger.debug("Produced the following access token for client_id='{}':  {}", oAuthClient.getClientId(),
            rslt);

    return ResponseEntity.ok(rslt);
}

From source file:org.hesperides.core.presentation.controllers.ModulesController.java

@ApiOperation("Update a module working copy")
@PutMapping/* w  w w.j a  v  a  2 s. co  m*/
public ResponseEntity<ModuleIO> updateWorkingCopy(Authentication authentication,
        @Valid @RequestBody final ModuleIO moduleInput) {

    log.info("Updating module workingcopy {}", moduleInput.toString());

    Module module = moduleInput.toDomainInstance();
    moduleUseCases.updateModuleTechnos(module, fromAuthentication(authentication));
    ModuleIO moduleOutput = moduleUseCases.getModule(module.getKey()).map(ModuleIO::new)
            .orElseThrow(() -> new ModuleNotFoundException(module.getKey()));

    return ResponseEntity.ok(moduleOutput);
}

From source file:org.hesperides.core.presentation.controllers.ModulesController.java

@ApiOperation("Get all module names")
@GetMapping//from   ww  w  .j a  v a 2s  . co  m
public ResponseEntity<List<String>> getModulesNames() {

    log.debug("getModulesNames");

    List<String> modulesNames = moduleUseCases.getModulesNames();
    log.debug("return getModulesNames: {}", modulesNames.toString());

    return ResponseEntity.ok(modulesNames);
}

From source file:org.hesperides.core.presentation.controllers.ModulesController.java

@ApiOperation("Get all versions for a given module")
@GetMapping("/{module_name}")
public ResponseEntity<List<String>> getModuleVersions(@PathVariable("module_name") final String moduleName) {

    log.debug("getModuleVersions moduleName: {}", moduleName);

    List<String> moduleVersions = moduleUseCases.getModuleVersions(moduleName);
    log.debug("return getModuleVersions: {}", moduleVersions.toString());

    return ResponseEntity.ok(moduleVersions);
}