Search in sources :

Example 31 with ResponseEntity

use of org.springframework.http.ResponseEntity in project cas by apereo.

the class TicketsResource method createTicketGrantingTicket.

/**
     * Create new ticket granting ticket.
     *
     * @param requestBody username and password application/x-www-form-urlencoded values
     * @param request     raw HttpServletRequest used to call this method
     * @return ResponseEntity representing RESTful response
     * @throws JsonProcessingException in case of JSON parsing failure
     */
@PostMapping(value = "/v1/tickets", consumes = MediaType.APPLICATION_FORM_URLENCODED_VALUE)
public ResponseEntity<String> createTicketGrantingTicket(@RequestBody final MultiValueMap<String, String> requestBody, final HttpServletRequest request) throws JsonProcessingException {
    try {
        final Credential credential = this.credentialFactory.fromRequestBody(requestBody);
        final AuthenticationResult authenticationResult = this.authenticationSystemSupport.handleAndFinalizeSingleAuthenticationTransaction(null, credential);
        final TicketGrantingTicket tgtId = this.centralAuthenticationService.createTicketGrantingTicket(authenticationResult);
        final URI ticketReference = new URI(request.getRequestURL().toString() + '/' + tgtId.getId());
        final HttpHeaders headers = new HttpHeaders();
        headers.setLocation(ticketReference);
        headers.setContentType(MediaType.TEXT_HTML);
        final String tgtUrl = ticketReference.toString();
        final String response = new StringBuilder(SUCCESSFUL_TGT_CREATED_INITIAL_LENGTH + tgtUrl.length()).append(DOCTYPE_AND_OPENING_FORM).append(tgtUrl).append(REST_OF_THE_FORM_AND_CLOSING_TAGS).toString();
        return new ResponseEntity<>(response, headers, HttpStatus.CREATED);
    } catch (final AuthenticationException e) {
        final List<String> authnExceptions = e.getHandlerErrors().values().stream().map(Class::getSimpleName).collect(Collectors.toList());
        final Map<String, List<String>> errorsMap = new HashMap<>();
        errorsMap.put("authentication_exceptions", authnExceptions);
        LOGGER.error("[{}] Caused by: [{}]", e.getMessage(), authnExceptions, e);
        try {
            return new ResponseEntity<>(this.jacksonPrettyWriter.writeValueAsString(errorsMap), HttpStatus.UNAUTHORIZED);
        } catch (final JsonProcessingException exception) {
            LOGGER.error(e.getMessage(), e);
            return new ResponseEntity<>(e.getMessage(), HttpStatus.INTERNAL_SERVER_ERROR);
        }
    } catch (final BadRequestException e) {
        LOGGER.error(e.getMessage(), e);
        return new ResponseEntity<>(e.getMessage(), HttpStatus.BAD_REQUEST);
    } catch (final Throwable e) {
        LOGGER.error(e.getMessage(), e);
        return new ResponseEntity<>(e.getMessage(), HttpStatus.INTERNAL_SERVER_ERROR);
    }
}
Also used : HttpHeaders(org.springframework.http.HttpHeaders) Credential(org.apereo.cas.authentication.Credential) AuthenticationException(org.apereo.cas.authentication.AuthenticationException) TicketGrantingTicket(org.apereo.cas.ticket.TicketGrantingTicket) URI(java.net.URI) AuthenticationResult(org.apereo.cas.authentication.AuthenticationResult) ResponseEntity(org.springframework.http.ResponseEntity) List(java.util.List) HashMap(java.util.HashMap) Map(java.util.Map) MultiValueMap(org.springframework.util.MultiValueMap) JsonProcessingException(com.fasterxml.jackson.core.JsonProcessingException) PostMapping(org.springframework.web.bind.annotation.PostMapping)

Example 32 with ResponseEntity

use of org.springframework.http.ResponseEntity in project cas by apereo.

the class OAuth20UserProfileControllerController method handleRequestInternal.

/**
     * Handle request internal response entity.
     *
     * @param request  the request
     * @param response the response
     * @return the response entity
     * @throws Exception the exception
     */
@GetMapping(path = OAuthConstants.BASE_OAUTH20_URL + '/' + OAuthConstants.PROFILE_URL, produces = MediaType.APPLICATION_JSON_VALUE)
public ResponseEntity<String> handleRequestInternal(final HttpServletRequest request, final HttpServletResponse response) throws Exception {
    response.setContentType(MediaType.APPLICATION_JSON_VALUE);
    String accessToken = request.getParameter(OAuthConstants.ACCESS_TOKEN);
    if (StringUtils.isBlank(accessToken)) {
        final String authHeader = request.getHeader(HttpConstants.AUTHORIZATION_HEADER);
        if (StringUtils.isNotBlank(authHeader) && authHeader.toLowerCase().startsWith(OAuthConstants.BEARER_TOKEN.toLowerCase() + ' ')) {
            accessToken = authHeader.substring(OAuthConstants.BEARER_TOKEN.length() + 1);
        }
    }
    LOGGER.debug("[{}]: [{}]", OAuthConstants.ACCESS_TOKEN, accessToken);
    if (StringUtils.isBlank(accessToken)) {
        LOGGER.error("Missing [{}]", OAuthConstants.ACCESS_TOKEN);
        final LinkedMultiValueMap<String, String> map = new LinkedMultiValueMap<>(1);
        map.add(OAuthConstants.ERROR, OAuthConstants.MISSING_ACCESS_TOKEN);
        final String value = OAuthUtils.jsonify(map);
        return new ResponseEntity<>(value, HttpStatus.UNAUTHORIZED);
    }
    final AccessToken accessTokenTicket = getTicketRegistry().getTicket(accessToken, AccessToken.class);
    if (accessTokenTicket == null || accessTokenTicket.isExpired()) {
        LOGGER.error("Expired access token: [{}]", OAuthConstants.ACCESS_TOKEN);
        final LinkedMultiValueMap<String, String> map = new LinkedMultiValueMap<>(1);
        map.add(OAuthConstants.ERROR, OAuthConstants.EXPIRED_ACCESS_TOKEN);
        final String value = OAuthUtils.jsonify(map);
        return new ResponseEntity<>(value, HttpStatus.UNAUTHORIZED);
    }
    final Map<String, Object> map = writeOutProfileResponse(accessTokenTicket.getAuthentication(), accessTokenTicket.getAuthentication().getPrincipal());
    final String value = OAuthUtils.jsonify(map);
    LOGGER.debug("Final user profile is [{}]", value);
    return new ResponseEntity<>(value, HttpStatus.OK);
}
Also used : ResponseEntity(org.springframework.http.ResponseEntity) LinkedMultiValueMap(org.springframework.util.LinkedMultiValueMap) AccessToken(org.apereo.cas.ticket.accesstoken.AccessToken) GetMapping(org.springframework.web.bind.annotation.GetMapping)

Example 33 with ResponseEntity

use of org.springframework.http.ResponseEntity in project cas by apereo.

the class ClickatellSmsSender method send.

@Override
public boolean send(final String from, final String to, final String message) {
    try {
        final MultiValueMap<String, String> headers = new LinkedMultiValueMap<>();
        headers.add("Authorization", this.token);
        headers.add("Content-Type", MediaType.APPLICATION_JSON_VALUE);
        headers.add("Accept", MediaType.APPLICATION_JSON_VALUE);
        final Map<String, Object> map = new HashMap<>();
        map.put("content", message);
        map.put("to", Arrays.asList(to));
        map.put("from", from);
        final StringWriter stringify = new StringWriter();
        mapper.writeValue(stringify, map);
        final HttpEntity<String> request = new HttpEntity<>(stringify.toString(), headers);
        final ResponseEntity<Map> response = restTemplate.postForEntity(new URI(this.serverUrl), request, Map.class);
        if (response.hasBody()) {
            final List<Map> messages = (List<Map>) response.getBody().get("messages");
            final String error = (String) response.getBody().get("error");
            if (StringUtils.isNotBlank(error)) {
                LOGGER.error(error);
                return false;
            }
            final List<String> errors = messages.stream().filter(m -> m.containsKey("accepted") && !Boolean.valueOf(m.get("accepted").toString()) && m.containsKey("error")).map(m -> (String) m.get("error")).collect(Collectors.toList());
            if (errors.isEmpty()) {
                return true;
            }
            errors.forEach(LOGGER::error);
        }
    } catch (final Exception e) {
        LOGGER.error(e.getMessage(), e);
    }
    return false;
}
Also used : Arrays(java.util.Arrays) Logger(org.slf4j.Logger) MediaType(org.springframework.http.MediaType) StringWriter(java.io.StringWriter) ObjectMapper(com.fasterxml.jackson.databind.ObjectMapper) LoggerFactory(org.slf4j.LoggerFactory) MultiValueMap(org.springframework.util.MultiValueMap) HashMap(java.util.HashMap) StringUtils(org.apache.commons.lang3.StringUtils) Collectors(java.util.stream.Collectors) HttpEntity(org.springframework.http.HttpEntity) List(java.util.List) MappingJackson2HttpMessageConverter(org.springframework.http.converter.json.MappingJackson2HttpMessageConverter) Map(java.util.Map) ResponseEntity(org.springframework.http.ResponseEntity) URI(java.net.URI) LinkedMultiValueMap(org.springframework.util.LinkedMultiValueMap) RestTemplate(org.springframework.web.client.RestTemplate) SmsSender(org.apereo.cas.util.io.SmsSender) HttpEntity(org.springframework.http.HttpEntity) LinkedMultiValueMap(org.springframework.util.LinkedMultiValueMap) HashMap(java.util.HashMap) URI(java.net.URI) StringWriter(java.io.StringWriter) List(java.util.List) MultiValueMap(org.springframework.util.MultiValueMap) HashMap(java.util.HashMap) Map(java.util.Map) LinkedMultiValueMap(org.springframework.util.LinkedMultiValueMap)

Example 34 with ResponseEntity

use of org.springframework.http.ResponseEntity in project Settler by EmhyrVarEmreis.

the class CategoryService method getCategoriesWithValue.

public ResponseEntity<List<CategoryWithValueDTO>> getCategoriesWithValue(Long userId) {
    if (Objects.isNull(userId) || userId < 0) {
        userId = Security.currentUser().getId();
    }
    QCategory category = QCategory.category;
    QTransaction transaction = QTransaction.transaction;
    List<Tuple> fetch = new JPAQuery<>(entityManager).from(category, transaction).select(category, transaction.value.sum()).where(transaction.creator.id.eq(userId)).where(transaction.categories.contains(category)).groupBy(category.code, category.description).orderBy(transaction.value.sum().desc()).fetch();
    ModelMapper preparedModelMapper = getModelMapper();
    List<CategoryWithValueDTO> categoryWithValueDTOList = new ArrayList<>(fetch.size());
    for (Tuple tuple : fetch) {
        Category c = tuple.get(category);
        Double d = tuple.get(transaction.value.sum());
        if (Objects.nonNull(c)) {
            categoryWithValueDTOList.add(new CategoryWithValueDTO(userId, preparedModelMapper.map(c, CategoryDTO.class), d));
        }
    }
    return new ResponseEntity<>(categoryWithValueDTOList, HttpStatus.OK);
}
Also used : QTransaction(pl.morecraft.dev.settler.domain.QTransaction) ResponseEntity(org.springframework.http.ResponseEntity) Category(pl.morecraft.dev.settler.domain.Category) QCategory(pl.morecraft.dev.settler.domain.QCategory) ArrayList(java.util.ArrayList) CategoryWithValueDTO(pl.morecraft.dev.settler.web.dto.CategoryWithValueDTO) QCategory(pl.morecraft.dev.settler.domain.QCategory) Tuple(com.querydsl.core.Tuple) ModelMapper(org.modelmapper.ModelMapper)

Example 35 with ResponseEntity

use of org.springframework.http.ResponseEntity in project Settler by EmhyrVarEmreis.

the class CommentService method getByPrivilegeObject.

public ResponseEntity<List<CommentDTO>> getByPrivilegeObject(Long objectId) {
    PrivilegeObject privilegeObject = privilegeObjectRepository.findOne(objectId);
    if (privilegeObject == null) {
        return new ResponseEntity<>(HttpStatus.BAD_REQUEST);
    }
    List<Comment> commentList = getByPrivilegeObject(privilegeObject);
    List<CommentDTO> commentDTOList = getListPageConverter().convert(commentList, CommentDTO.class);
    return new ResponseEntity<>(commentDTOList, HttpStatus.OK);
}
Also used : PrivilegeObject(pl.morecraft.dev.settler.domain.PrivilegeObject) Comment(pl.morecraft.dev.settler.domain.Comment) QComment(pl.morecraft.dev.settler.domain.QComment) ResponseEntity(org.springframework.http.ResponseEntity) CommentDTO(pl.morecraft.dev.settler.web.dto.CommentDTO)

Aggregations

ResponseEntity (org.springframework.http.ResponseEntity)165 HttpHeaders (org.springframework.http.HttpHeaders)62 RequestMapping (org.springframework.web.bind.annotation.RequestMapping)56 Locale (java.util.Locale)32 ArrayList (java.util.ArrayList)31 HashMap (java.util.HashMap)29 StudyBean (org.akaza.openclinica.bean.managestudy.StudyBean)24 Test (org.junit.Test)19 UserAccountBean (org.akaza.openclinica.bean.login.UserAccountBean)16 ApiOperation (io.swagger.annotations.ApiOperation)15 ApiResponses (io.swagger.annotations.ApiResponses)15 MediaType (org.springframework.http.MediaType)13 List (java.util.List)12 HttpEntity (org.springframework.http.HttpEntity)12 PreAuthorize (org.springframework.security.access.prepost.PreAuthorize)12 HttpStatus (org.springframework.http.HttpStatus)10 InputStream (java.io.InputStream)9 Type (java.lang.reflect.Type)8 UserAccountDAO (org.akaza.openclinica.dao.login.UserAccountDAO)8 IOException (java.io.IOException)7