Search in sources :

Example 26 with ResponseEntity

use of org.springframework.http.ResponseEntity in project spring-security-oauth by spring-projects.

the class PhotoController method getXmlPhotos.

@RequestMapping(value = "/photos", params = "format=xml")
@ResponseBody
public ResponseEntity<String> getXmlPhotos() throws Exception {
    Collection<PhotoInfo> photos = photoService.getPhotosForCurrentUser();
    StringBuilder out = new StringBuilder();
    out.append("<photos>");
    for (PhotoInfo photo : photos) {
        out.append(String.format("<photo id=\"%s\" name=\"%s\"/>", photo.getId(), photo.getName()));
    }
    out.append("</photos>");
    HttpHeaders headers = new HttpHeaders();
    headers.set("Content-Type", "application/xml");
    return new ResponseEntity<String>(out.toString(), headers, HttpStatus.OK);
}
Also used : PhotoInfo(org.springframework.security.oauth.examples.sparklr.PhotoInfo) HttpHeaders(org.springframework.http.HttpHeaders) ResponseEntity(org.springframework.http.ResponseEntity) RequestMapping(org.springframework.web.bind.annotation.RequestMapping) ResponseBody(org.springframework.web.bind.annotation.ResponseBody)

Example 27 with ResponseEntity

use of org.springframework.http.ResponseEntity in project spring-security-oauth by spring-projects.

the class SparklrController method photo.

@RequestMapping("/sparklr/photos/{id}")
public ResponseEntity<BufferedImage> photo(@PathVariable String id) throws Exception {
    InputStream photo = sparklrService.loadSparklrPhoto(id);
    if (photo == null) {
        throw new UnavailableException("The requested photo does not exist");
    }
    BufferedImage body;
    MediaType contentType = MediaType.IMAGE_JPEG;
    Iterator<ImageReader> imageReaders = ImageIO.getImageReadersByMIMEType(contentType.toString());
    if (imageReaders.hasNext()) {
        ImageReader imageReader = imageReaders.next();
        ImageReadParam irp = imageReader.getDefaultReadParam();
        imageReader.setInput(new MemoryCacheImageInputStream(photo), true);
        body = imageReader.read(0, irp);
    } else {
        throw new HttpMessageNotReadableException("Could not find javax.imageio.ImageReader for Content-Type [" + contentType + "]");
    }
    HttpHeaders headers = new HttpHeaders();
    headers.setContentType(MediaType.IMAGE_JPEG);
    return new ResponseEntity<BufferedImage>(body, headers, HttpStatus.OK);
}
Also used : ImageReadParam(javax.imageio.ImageReadParam) HttpHeaders(org.springframework.http.HttpHeaders) ResponseEntity(org.springframework.http.ResponseEntity) HttpMessageNotReadableException(org.springframework.http.converter.HttpMessageNotReadableException) MemoryCacheImageInputStream(javax.imageio.stream.MemoryCacheImageInputStream) InputStream(java.io.InputStream) UnavailableException(javax.servlet.UnavailableException) MemoryCacheImageInputStream(javax.imageio.stream.MemoryCacheImageInputStream) MediaType(org.springframework.http.MediaType) ImageReader(javax.imageio.ImageReader) BufferedImage(java.awt.image.BufferedImage) RequestMapping(org.springframework.web.bind.annotation.RequestMapping)

Example 28 with ResponseEntity

use of org.springframework.http.ResponseEntity in project spring-security-oauth by spring-projects.

the class DefaultOAuth2ExceptionRenderer method handleHttpEntityResponse.

public void handleHttpEntityResponse(HttpEntity<?> responseEntity, ServletWebRequest webRequest) throws Exception {
    if (responseEntity == null) {
        return;
    }
    HttpInputMessage inputMessage = createHttpInputMessage(webRequest);
    HttpOutputMessage outputMessage = createHttpOutputMessage(webRequest);
    if (responseEntity instanceof ResponseEntity && outputMessage instanceof ServerHttpResponse) {
        ((ServerHttpResponse) outputMessage).setStatusCode(((ResponseEntity<?>) responseEntity).getStatusCode());
    }
    HttpHeaders entityHeaders = responseEntity.getHeaders();
    if (!entityHeaders.isEmpty()) {
        outputMessage.getHeaders().putAll(entityHeaders);
    }
    Object body = responseEntity.getBody();
    if (body != null) {
        writeWithMessageConverters(body, inputMessage, outputMessage);
    } else {
        // flush headers
        outputMessage.getBody();
    }
}
Also used : HttpInputMessage(org.springframework.http.HttpInputMessage) HttpHeaders(org.springframework.http.HttpHeaders) ResponseEntity(org.springframework.http.ResponseEntity) HttpOutputMessage(org.springframework.http.HttpOutputMessage) ServerHttpResponse(org.springframework.http.server.ServerHttpResponse) ServletServerHttpResponse(org.springframework.http.server.ServletServerHttpResponse)

Example 29 with ResponseEntity

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

the class OidcDynamicClientRegistrationEndpointController method handleRequestInternal.

/**
     * Handle request.
     *
     * @param jsonInput the json input
     * @param request   the request
     * @param response  the response
     * @return the model and view
     * @throws Exception the exception
     */
@PostMapping(value = '/' + OidcConstants.BASE_OIDC_URL + '/' + OidcConstants.REGISTRATION_URL, consumes = MediaType.APPLICATION_JSON_VALUE, produces = MediaType.APPLICATION_JSON_VALUE)
public ResponseEntity<OidcClientRegistrationResponse> handleRequestInternal(@RequestBody final String jsonInput, final HttpServletRequest request, final HttpServletResponse response) throws Exception {
    try {
        final OidcClientRegistrationRequest registrationRequest = this.clientRegistrationRequestSerializer.from(jsonInput);
        LOGGER.debug("Received client registration request [{}]", registrationRequest);
        if (registrationRequest.getScopes().isEmpty()) {
            throw new Exception("Registration request does not contain any scope values");
        }
        if (!registrationRequest.getScope().contains(OidcConstants.OPENID)) {
            throw new Exception("Registration request scopes do not contain [{}]" + OidcConstants.OPENID);
        }
        final OidcRegisteredService registeredService = new OidcRegisteredService();
        registeredService.setName(registrationRequest.getClientName());
        if (StringUtils.isNotBlank(registrationRequest.getJwksUri())) {
            registeredService.setJwks(registrationRequest.getJwksUri());
            registeredService.setSignIdToken(true);
        }
        final String uri = registrationRequest.getRedirectUris().stream().findFirst().get();
        registeredService.setServiceId(uri);
        registeredService.setClientId(clientIdGenerator.getNewString());
        registeredService.setClientSecret(clientSecretGenerator.getNewString());
        registeredService.setEvaluationOrder(Integer.MIN_VALUE);
        final Set<String> supportedScopes = new HashSet<>(casProperties.getAuthn().getOidc().getScopes());
        supportedScopes.retainAll(registrationRequest.getScopes());
        final OidcClientRegistrationResponse clientResponse = getClientRegistrationResponse(registrationRequest, registeredService);
        registeredService.setScopes(supportedScopes);
        final Set<String> processedScopes = new LinkedHashSet<>(supportedScopes);
        registeredService.setScopes(processedScopes);
        registeredService.setDescription("Dynamically registered service ".concat(registeredService.getName()).concat(" with grant types ").concat(clientResponse.getGrantTypes().stream().collect(Collectors.joining(","))).concat(" and with scopes ").concat(registeredService.getScopes().stream().collect(Collectors.joining(","))).concat(" and response types ").concat(clientResponse.getResponseTypes().stream().collect(Collectors.joining(","))));
        registeredService.setDynamicallyRegistered(true);
        scopeToAttributesFilter.reconcile(registeredService);
        return new ResponseEntity<>(clientResponse, HttpStatus.CREATED);
    } catch (final Exception e) {
        LOGGER.error(e.getMessage(), e);
        final Map<String, String> map = new HashMap<>();
        map.put("error", "invalid_client_metadata");
        map.put("error_message", e.getMessage());
        return new ResponseEntity(map, HttpStatus.BAD_REQUEST);
    }
}
Also used : LinkedHashSet(java.util.LinkedHashSet) ResponseEntity(org.springframework.http.ResponseEntity) OidcRegisteredService(org.apereo.cas.services.OidcRegisteredService) OidcClientRegistrationRequest(org.apereo.cas.oidc.dynareg.OidcClientRegistrationRequest) HashMap(java.util.HashMap) Map(java.util.Map) OidcClientRegistrationResponse(org.apereo.cas.oidc.dynareg.OidcClientRegistrationResponse) HashSet(java.util.HashSet) LinkedHashSet(java.util.LinkedHashSet) PostMapping(org.springframework.web.bind.annotation.PostMapping)

Example 30 with ResponseEntity

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

the class RegisteredServiceResource method createService.

/**
     * Create new service.
     *
     * @param tgtId             ticket granting ticket id URI path param
     * @param serviceDataHolder the service to register and save in rest form
     * @return {@link ResponseEntity} representing RESTful response
     */
@PostMapping(value = "/v1/services/add/{tgtId:.+}", consumes = MediaType.APPLICATION_FORM_URLENCODED_VALUE)
public ResponseEntity<String> createService(@ModelAttribute final ServiceDataHolder serviceDataHolder, @PathVariable("tgtId") final String tgtId) {
    try {
        if (StringUtils.isBlank(this.attributeName) || StringUtils.isBlank(this.attributeValue)) {
            throw new IllegalArgumentException("Attribute name and/or value must be configured");
        }
        final TicketGrantingTicket ticket = this.centralAuthenticationService.getTicket(tgtId, TicketGrantingTicket.class);
        if (ticket == null || ticket.isExpired()) {
            throw new InvalidTicketException("Ticket-granting ticket " + tgtId + " is not found");
        }
        final Map<String, Object> attributes = ticket.getAuthentication().getPrincipal().getAttributes();
        if (attributes.containsKey(this.attributeName)) {
            final Collection<String> attributeValuesToCompare = new HashSet<>();
            final Object value = attributes.get(this.attributeName);
            if (value instanceof Collection) {
                attributeValuesToCompare.addAll((Collection<String>) value);
            } else {
                attributeValuesToCompare.add(value.toString());
            }
            if (attributeValuesToCompare.contains(this.attributeValue)) {
                final RegisteredService service = serviceDataHolder.getRegisteredService();
                final RegisteredService savedService = this.servicesManager.save(service);
                return new ResponseEntity<>(String.valueOf(savedService.getId()), HttpStatus.OK);
            }
        }
        throw new IllegalArgumentException("Request is not authorized");
    } catch (final InvalidTicketException e) {
        return new ResponseEntity<>("TicketGrantingTicket could not be found", HttpStatus.NOT_FOUND);
    } catch (final Exception e) {
        LOGGER.error(e.getMessage(), e);
        return new ResponseEntity<>(e.getMessage(), HttpStatus.BAD_REQUEST);
    }
}
Also used : RegexRegisteredService(org.apereo.cas.services.RegexRegisteredService) RegisteredService(org.apereo.cas.services.RegisteredService) TicketGrantingTicket(org.apereo.cas.ticket.TicketGrantingTicket) InvalidTicketException(org.apereo.cas.ticket.InvalidTicketException) ResponseEntity(org.springframework.http.ResponseEntity) InvalidTicketException(org.apereo.cas.ticket.InvalidTicketException) Collection(java.util.Collection) HashSet(java.util.HashSet) PostMapping(org.springframework.web.bind.annotation.PostMapping)

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