Search in sources :

Example 6 with BodyBuilder

use of org.springframework.http.ResponseEntity.BodyBuilder in project connectors-workspace-one by vmware.

the class ExceptionHandlers method handleStatusCodeException.

@ExceptionHandler
@ResponseBody
public ResponseEntity<Object> handleStatusCodeException(WebClientResponseException e) {
    // Map the status to a 500 unlesss it's a 401. If that's the case
    // then we know the client has passed in an invalid X-xxx-Authorization header and it's a 400.
    logger.error("Backend returned {} {} \n {}", e.getStatusCode(), e.getStatusCode().getReasonPhrase(), e.getResponseBodyAsString());
    String backendStatus = Integer.toString(e.getRawStatusCode());
    if (e.getStatusCode() == UNAUTHORIZED) {
        Map<String, String> body = Collections.singletonMap("error", "invalid_connector_token");
        return ResponseEntity.status(BAD_REQUEST).header(BACKEND_STATUS, backendStatus).contentType(APPLICATION_JSON).body(body);
    } else {
        BodyBuilder builder = ResponseEntity.status(INTERNAL_SERVER_ERROR).header(BACKEND_STATUS, backendStatus);
        if (e.getHeaders().getContentType() != null) {
            builder.contentType(e.getHeaders().getContentType());
        }
        return builder.body(e.getResponseBodyAsString());
    }
}
Also used : BodyBuilder(org.springframework.http.ResponseEntity.BodyBuilder) ExceptionHandler(org.springframework.web.bind.annotation.ExceptionHandler) ResponseBody(org.springframework.web.bind.annotation.ResponseBody)

Example 7 with BodyBuilder

use of org.springframework.http.ResponseEntity.BodyBuilder in project CzechIdMng by bcvsolutions.

the class IdmIdentityController method getProfileImage.

/**
 * Returns profile image attachment from identity
 *
 * @return
 * @since 9.0.0
 */
@RequestMapping(value = "/{backendId}/profile/image", method = RequestMethod.GET)
@ResponseBody
@PreAuthorize("hasAuthority('" + CoreGroupPermission.PROFILE_AUTOCOMPLETE + "')")
@ApiOperation(value = "Profile image", nickname = "getProfileImage", tags = { IdmIdentityController.TAG }, notes = "Returns input stream to identity profile image.", authorizations = { @Authorization(value = SwaggerConfig.AUTHENTICATION_BASIC, scopes = { @AuthorizationScope(scope = CoreGroupPermission.PROFILE_AUTOCOMPLETE, description = "") }), @Authorization(value = SwaggerConfig.AUTHENTICATION_CIDMST, scopes = { @AuthorizationScope(scope = CoreGroupPermission.PROFILE_AUTOCOMPLETE, description = "") }) })
public ResponseEntity<InputStreamResource> getProfileImage(@ApiParam(value = "Identity's uuid identifier or username.", required = true) @PathVariable String backendId) {
    IdmProfileDto profile = profileService.findOneByIdentity(backendId, IdmBasePermission.AUTOCOMPLETE);
    if (profile == null) {
        return new ResponseEntity<InputStreamResource>(HttpStatus.NO_CONTENT);
    }
    if (profile.getImage() == null) {
        return new ResponseEntity<InputStreamResource>(HttpStatus.NO_CONTENT);
    }
    IdmAttachmentDto attachment = attachmentManager.get(profile.getImage());
    String mimetype = attachment.getMimetype();
    InputStream is = attachmentManager.getAttachmentData(attachment.getId());
    try {
        BodyBuilder response = ResponseEntity.ok().contentLength(is.available()).header(HttpHeaders.CONTENT_DISPOSITION, String.format("attachment; filename=\"%s\"", attachment.getName()));
        // append media type, if it's filled
        if (StringUtils.isNotBlank(mimetype)) {
            response = response.contentType(MediaType.valueOf(attachment.getMimetype()));
        }
        // 
        return response.body(new InputStreamResource(is));
    } catch (IOException e) {
        throw new ResultCodeException(CoreResultCode.INTERNAL_SERVER_ERROR, e);
    }
}
Also used : IdmAttachmentDto(eu.bcvsolutions.idm.core.ecm.api.dto.IdmAttachmentDto) IdmProfileDto(eu.bcvsolutions.idm.core.api.dto.IdmProfileDto) ResponseEntity(org.springframework.http.ResponseEntity) InputStream(java.io.InputStream) ResultCodeException(eu.bcvsolutions.idm.core.api.exception.ResultCodeException) IOException(java.io.IOException) BodyBuilder(org.springframework.http.ResponseEntity.BodyBuilder) InputStreamResource(org.springframework.core.io.InputStreamResource) ApiOperation(io.swagger.annotations.ApiOperation) PreAuthorize(org.springframework.security.access.prepost.PreAuthorize) RequestMapping(org.springframework.web.bind.annotation.RequestMapping) ResponseBody(org.springframework.web.bind.annotation.ResponseBody)

Example 8 with BodyBuilder

use of org.springframework.http.ResponseEntity.BodyBuilder in project CzechIdMng by bcvsolutions.

the class IdmFormDefinitionController method previewAttachment.

/**
 * Returns input stream to attachment saved in given form value.
 *
 * @param value
 * @return
 * @since 9.4.0
 */
public ResponseEntity<InputStreamResource> previewAttachment(IdmFormValueDto value) {
    Assert.notNull(value, "Form value holds the attachment identifier is required to download the attachment.");
    // 
    if (value.getPersistentType() != PersistentType.ATTACHMENT) {
        throw new ResultCodeException(CoreResultCode.FORM_VALUE_WRONG_TYPE, "Download attachment of form value [%s], attribute [%s] with type [%s] is not supported. Download supports [%] persistent type only.", ImmutableMap.of("value", Objects.toString(value.getId()), "formAttribute", value.getFormAttribute().toString(), "persistentType", value.getPersistentType().toString(), "requiredPersistentType", PersistentType.ATTACHMENT.toString()));
    }
    if (value.getUuidValue() == null) {
        throw new ResultCodeException(CoreResultCode.BAD_VALUE, "Attachment of form value [%s], attribute [%s] is empty, cannot be dowloaded.", ImmutableMap.of("value", Objects.toString(value.getId()), "formAttribute", value.getFormAttribute().toString()));
    }
    // 
    IdmAttachmentDto attachment = attachmentManager.get(value.getUuidValue());
    if (attachment == null) {
        throw new ResultCodeException(CoreResultCode.NOT_FOUND, ImmutableMap.of("entity", value.getUuidValue()));
    }
    String mimetype = attachment.getMimetype();
    // TODO: naive check => implement better + image resize (thumbnail)
    if (!mimetype.startsWith("image/")) {
        return new ResponseEntity<>(HttpStatus.NO_CONTENT);
    }
    // 
    InputStream is = attachmentManager.getAttachmentData(attachment.getId());
    try {
        BodyBuilder response = ResponseEntity.ok().contentLength(is.available()).header(HttpHeaders.CONTENT_DISPOSITION, String.format("inline; filename=\"%s\"", attachment.getName()));
        // append media type, if it's filled
        if (StringUtils.isNotBlank(mimetype)) {
            response = response.contentType(MediaType.valueOf(attachment.getMimetype()));
        }
        // 
        return response.body(new InputStreamResource(is));
    } catch (IOException e) {
        throw new ResultCodeException(CoreResultCode.INTERNAL_SERVER_ERROR, e);
    }
}
Also used : IdmAttachmentDto(eu.bcvsolutions.idm.core.ecm.api.dto.IdmAttachmentDto) ResponseEntity(org.springframework.http.ResponseEntity) InputStream(java.io.InputStream) ResultCodeException(eu.bcvsolutions.idm.core.api.exception.ResultCodeException) IOException(java.io.IOException) BodyBuilder(org.springframework.http.ResponseEntity.BodyBuilder) InputStreamResource(org.springframework.core.io.InputStreamResource)

Example 9 with BodyBuilder

use of org.springframework.http.ResponseEntity.BodyBuilder in project CzechIdMng by bcvsolutions.

the class IdmFormDefinitionController method downloadAttachment.

/**
 * Returns input stream to attachment saved in given form value.
 *
 * @param value
 * @return
 * @since 9.4.0
 */
public ResponseEntity<InputStreamResource> downloadAttachment(IdmFormValueDto value) {
    Assert.notNull(value, "Form value holds the attachment identifier is required to download the attachment.");
    // 
    if (value.getPersistentType() != PersistentType.ATTACHMENT) {
        throw new ResultCodeException(CoreResultCode.FORM_VALUE_WRONG_TYPE, "Download attachment of form value [%s], attribute [%s] with type [%s] is not supported. Download supports [%] persistent type only.", ImmutableMap.of("value", Objects.toString(value.getId()), "formAttribute", value.getFormAttribute().toString(), "persistentType", value.getPersistentType().toString(), "requiredPersistentType", PersistentType.ATTACHMENT.toString()));
    }
    if (value.getUuidValue() == null) {
        throw new ResultCodeException(CoreResultCode.BAD_VALUE, "Attachment of form value [%s], attribute [%s] is empty, cannot be dowloaded.", ImmutableMap.of("value", Objects.toString(value.getId()), "formAttribute", value.getFormAttribute().toString()));
    }
    // 
    IdmAttachmentDto attachment = attachmentManager.get(value.getUuidValue());
    if (attachment == null) {
        throw new ResultCodeException(CoreResultCode.NOT_FOUND, ImmutableMap.of("entity", value.getUuidValue()));
    }
    String mimetype = attachment.getMimetype();
    InputStream is = attachmentManager.getAttachmentData(attachment.getId());
    try {
        BodyBuilder response = ResponseEntity.ok().contentLength(is.available()).header(HttpHeaders.CONTENT_DISPOSITION, String.format("inline; filename=\"%s\"", attachmentManager.getValidFileName(attachment.getName())));
        // append media type, if it's filled
        if (StringUtils.isNotBlank(mimetype)) {
            response = response.contentType(MediaType.valueOf(attachment.getMimetype()));
        }
        // 
        return response.body(new InputStreamResource(is));
    } catch (IOException e) {
        throw new ResultCodeException(CoreResultCode.INTERNAL_SERVER_ERROR, e);
    }
}
Also used : IdmAttachmentDto(eu.bcvsolutions.idm.core.ecm.api.dto.IdmAttachmentDto) InputStream(java.io.InputStream) ResultCodeException(eu.bcvsolutions.idm.core.api.exception.ResultCodeException) IOException(java.io.IOException) BodyBuilder(org.springframework.http.ResponseEntity.BodyBuilder) InputStreamResource(org.springframework.core.io.InputStreamResource)

Example 10 with BodyBuilder

use of org.springframework.http.ResponseEntity.BodyBuilder in project tutorials by eugenp.

the class ExceptionTranslator method processRuntimeException.

@ExceptionHandler(Exception.class)
public ResponseEntity<ErrorVM> processRuntimeException(Exception ex) {
    BodyBuilder builder;
    ErrorVM errorVM;
    ResponseStatus responseStatus = AnnotationUtils.findAnnotation(ex.getClass(), ResponseStatus.class);
    if (responseStatus != null) {
        builder = ResponseEntity.status(responseStatus.value());
        errorVM = new ErrorVM("error." + responseStatus.value().value(), responseStatus.reason());
    } else {
        builder = ResponseEntity.status(HttpStatus.INTERNAL_SERVER_ERROR);
        errorVM = new ErrorVM(ErrorConstants.ERR_INTERNAL_SERVER_ERROR, "Internal server error");
    }
    return builder.body(errorVM);
}
Also used : BodyBuilder(org.springframework.http.ResponseEntity.BodyBuilder)

Aggregations

BodyBuilder (org.springframework.http.ResponseEntity.BodyBuilder)11 ResultCodeException (eu.bcvsolutions.idm.core.api.exception.ResultCodeException)5 IdmAttachmentDto (eu.bcvsolutions.idm.core.ecm.api.dto.IdmAttachmentDto)5 IOException (java.io.IOException)5 InputStream (java.io.InputStream)5 InputStreamResource (org.springframework.core.io.InputStreamResource)5 ApiOperation (io.swagger.annotations.ApiOperation)3 ResponseEntity (org.springframework.http.ResponseEntity)3 RequestMapping (org.springframework.web.bind.annotation.RequestMapping)3 ResponseBody (org.springframework.web.bind.annotation.ResponseBody)3 UUID (java.util.UUID)2 PreAuthorize (org.springframework.security.access.prepost.PreAuthorize)2 IdmProfileDto (eu.bcvsolutions.idm.core.api.dto.IdmProfileDto)1 EntityNotFoundException (eu.bcvsolutions.idm.core.api.exception.EntityNotFoundException)1 IdmNotificationAttachmentDto (eu.bcvsolutions.idm.core.notification.api.dto.IdmNotificationAttachmentDto)1 ExceptionHandler (org.springframework.web.bind.annotation.ExceptionHandler)1