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);
}
}
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);
}
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;
}
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);
}
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);
}
Aggregations