Search in sources :

Example 51 with NotNull

use of javax.validation.constraints.NotNull in project mod-inventory-storage by folio-org.

the class ItemStorageAPI method putItemStorageItemsByItemId.

@Validate
@Override
public void putItemStorageItemsByItemId(@PathParam("itemId") @NotNull String itemId, @QueryParam("lang") @DefaultValue("en") @Pattern(regexp = "[a-zA-Z]{2}") String lang, Item entity, java.util.Map<String, String> okapiHeaders, io.vertx.core.Handler<io.vertx.core.AsyncResult<Response>> asyncResultHandler, Context vertxContext) throws Exception {
    String tenantId = okapiHeaders.get(TENANT_HEADER);
    try {
        PostgresClient postgresClient = PostgresClient.getInstance(vertxContext.owner(), TenantTool.calculateTenantId(tenantId));
        vertxContext.runOnContext(v -> {
            try {
                getMaterialType(vertxContext.owner(), tenantId, entity, replyHandler -> {
                    int res = replyHandler.result();
                    if (res == 0) {
                        String message = "Can not add " + entity.getMaterialTypeId() + ". Material type not found";
                        log.error(message);
                        asyncResultHandler.handle(io.vertx.core.Future.succeededFuture(PutItemStorageItemsByItemIdResponse.withPlainBadRequest(message)));
                    } else if (res == -1) {
                        asyncResultHandler.handle(Future.succeededFuture(ItemStorageResource.PostItemStorageItemsResponse.withPlainInternalServerError("")));
                    } else {
                        try {
                            String[] fieldList = { "*" };
                            String query = String.format("id==%s", itemId);
                            CQLWrapper cql = getCQL(query, 1, 0);
                            log.info(String.format("SQL generated from CQL: %s", cql.toString()));
                            postgresClient.get(getTableName(query), Item.class, fieldList, cql, true, false, reply -> {
                                if (reply.succeeded()) {
                                    List<Item> itemList = (List<Item>) reply.result().getResults();
                                    if (itemList.size() == 1) {
                                        try {
                                            postgresClient.update("item", entity, entity.getId(), update -> {
                                                try {
                                                    if (update.succeeded()) {
                                                        OutStream stream = new OutStream();
                                                        stream.setData(entity);
                                                        asyncResultHandler.handle(Future.succeededFuture(PutItemStorageItemsByItemIdResponse.withNoContent()));
                                                    } else {
                                                        String message = PgExceptionUtil.badRequestMessage(update.cause());
                                                        if (message != null) {
                                                            asyncResultHandler.handle(Future.succeededFuture(PutItemStorageItemsByItemIdResponse.withPlainBadRequest(message)));
                                                        } else {
                                                            asyncResultHandler.handle(Future.succeededFuture(PutItemStorageItemsByItemIdResponse.withPlainInternalServerError(update.cause().getMessage())));
                                                        }
                                                    }
                                                } catch (Exception e) {
                                                    asyncResultHandler.handle(Future.succeededFuture(PostItemStorageItemsResponse.withPlainInternalServerError(e.getMessage())));
                                                }
                                            });
                                        } catch (Exception e) {
                                            asyncResultHandler.handle(Future.succeededFuture(PutItemStorageItemsByItemIdResponse.withPlainInternalServerError(e.getMessage())));
                                        }
                                    } else {
                                        try {
                                            postgresClient.save("item", entity.getId(), entity, save -> {
                                                try {
                                                    if (save.succeeded()) {
                                                        OutStream stream = new OutStream();
                                                        stream.setData(entity);
                                                        asyncResultHandler.handle(Future.succeededFuture(PutItemStorageItemsByItemIdResponse.withNoContent()));
                                                    } else {
                                                        asyncResultHandler.handle(Future.succeededFuture(PutItemStorageItemsByItemIdResponse.withPlainInternalServerError(save.cause().getMessage())));
                                                    }
                                                } catch (Exception e) {
                                                    asyncResultHandler.handle(Future.succeededFuture(PostItemStorageItemsResponse.withPlainInternalServerError(e.getMessage())));
                                                }
                                            });
                                        } catch (Exception e) {
                                            asyncResultHandler.handle(Future.succeededFuture(PutItemStorageItemsByItemIdResponse.withPlainInternalServerError(e.getMessage())));
                                        }
                                    }
                                } else {
                                    asyncResultHandler.handle(Future.succeededFuture(PutItemStorageItemsByItemIdResponse.withPlainInternalServerError(reply.cause().getMessage())));
                                }
                            });
                        } catch (Exception e) {
                            asyncResultHandler.handle(Future.succeededFuture(ItemStorageResource.PostItemStorageItemsResponse.withPlainInternalServerError(e.getMessage())));
                        }
                    }
                });
            } catch (Exception e) {
                asyncResultHandler.handle(Future.succeededFuture(ItemStorageResource.PostItemStorageItemsResponse.withPlainInternalServerError(e.getMessage())));
            }
        });
    } catch (Exception e) {
        asyncResultHandler.handle(Future.succeededFuture(ItemStorageResource.PostItemStorageItemsResponse.withPlainInternalServerError(e.getMessage())));
    }
}
Also used : PathParam(javax.ws.rs.PathParam) Arrays(java.util.Arrays) CQLWrapper(org.folio.rest.persist.cql.CQLWrapper) io.vertx.core(io.vertx.core) Criteria(org.folio.rest.persist.Criteria.Criteria) LoggerFactory(io.vertx.core.logging.LoggerFactory) QueryParam(javax.ws.rs.QueryParam) Limit(org.folio.rest.persist.Criteria.Limit) PgExceptionUtil(org.folio.rest.persist.PgExceptionUtil) Map(java.util.Map) DefaultValue(javax.ws.rs.DefaultValue) FieldException(org.z3950.zing.cql.cql2pgjson.FieldException) Offset(org.folio.rest.persist.Criteria.Offset) Logger(io.vertx.core.logging.Logger) ItemStorageResource(org.folio.rest.jaxrs.resource.ItemStorageResource) UUID(java.util.UUID) NotNull(javax.validation.constraints.NotNull) Validate(org.folio.rest.annotations.Validate) TenantTool(org.folio.rest.tools.utils.TenantTool) PostgresClient(org.folio.rest.persist.PostgresClient) org.folio.rest.jaxrs.model(org.folio.rest.jaxrs.model) OutStream(org.folio.rest.tools.utils.OutStream) List(java.util.List) Criterion(org.folio.rest.persist.Criteria.Criterion) Response(javax.ws.rs.core.Response) Pattern(javax.validation.constraints.Pattern) CQL2PgJSON(org.z3950.zing.cql.cql2pgjson.CQL2PgJSON) PostgresClient(org.folio.rest.persist.PostgresClient) List(java.util.List) OutStream(org.folio.rest.tools.utils.OutStream) CQLWrapper(org.folio.rest.persist.cql.CQLWrapper) FieldException(org.z3950.zing.cql.cql2pgjson.FieldException) Validate(org.folio.rest.annotations.Validate)

Example 52 with NotNull

use of javax.validation.constraints.NotNull in project crnk-framework by crnk-project.

the class ValidationMetaProvider method getFilters.

@Override
public Collection<MetaFilter> getFilters() {
    return Arrays.asList((MetaFilter) new MetaFilterBase() {

        @Override
        public void onInitialized(MetaElement element) {
            if (element instanceof MetaAttribute) {
                MetaAttribute attr = (MetaAttribute) element;
                NotNull notNull = attr.getAnnotation(NotNull.class);
                if (notNull != null) {
                    attr.setNullable(false);
                }
            }
        }
    });
}
Also used : MetaElement(io.crnk.meta.model.MetaElement) MetaAttribute(io.crnk.meta.model.MetaAttribute) MetaFilterBase(io.crnk.meta.provider.MetaFilterBase) NotNull(javax.validation.constraints.NotNull)

Example 53 with NotNull

use of javax.validation.constraints.NotNull in project mica2 by obiba.

the class DataAccessRequestService method save.

public DataAccessRequest save(@NotNull DataAccessRequest request) {
    DataAccessRequest saved = request;
    DataAccessRequest.Status from = null;
    Iterable<Attachment> attachmentsToDelete = null;
    Iterable<Attachment> attachmentsToSave = null;
    if (request.isNew()) {
        setAndLogStatus(saved, DataAccessRequest.Status.OPENED);
        saved.setId(generateId());
        attachmentsToSave = saved.getAttachments();
    } else {
        saved = dataAccessRequestRepository.findOne(request.getId());
        if (saved != null) {
            attachmentsToDelete = Sets.difference(Sets.newHashSet(saved.getAttachments()), Sets.newHashSet(request.getAttachments()));
            attachmentsToSave = Sets.difference(Sets.newHashSet(request.getAttachments()), Sets.newHashSet(saved.getAttachments()));
            from = saved.getStatus();
            // validate the status
            dataAccessRequestUtilService.checkStatusTransition(saved, request.getStatus());
            saved.setStatus(request.getStatus());
            if (request.hasStatusChangeHistory())
                saved.setStatusChangeHistory(request.getStatusChangeHistory());
            // merge beans
            BeanUtils.copyProperties(request, saved, "id", "version", "createdBy", "createdDate", "lastModifiedBy", "lastModifiedDate", "statusChangeHistory");
        } else {
            saved = request;
            setAndLogStatus(saved, DataAccessRequest.Status.OPENED);
        }
    }
    schemaFormContentFileService.save(saved, dataAccessRequestRepository.findOne(request.getId()), String.format("/data-access-request/%s", saved.getId()));
    if (attachmentsToSave != null)
        attachmentsToSave.forEach(a -> {
            fileStoreService.save(a.getId());
            a.setJustUploaded(false);
            attachmentRepository.save(a);
        });
    saved.setLastModifiedDate(DateTime.now());
    dataAccessRequestRepository.saveWithReferences(saved);
    if (attachmentsToDelete != null)
        attachmentsToDelete.forEach(a -> fileStoreService.delete(a.getId()));
    eventBus.post(new DataAccessRequestUpdatedEvent(saved));
    sendNotificationEmails(saved, from);
    return saved;
}
Also used : DataAccessForm(org.obiba.mica.micaConfig.domain.DataAccessForm) AttachmentRepository(org.obiba.mica.core.repository.AttachmentRepository) DataAccessRequestDeletedEvent(org.obiba.mica.access.event.DataAccessRequestDeletedEvent) Roles(org.obiba.mica.security.Roles) LoggerFactory(org.slf4j.LoggerFactory) StatusChange(org.obiba.mica.access.domain.StatusChange) FileStoreService(org.obiba.mica.file.FileStoreService) IdentifierGenerator(org.obiba.mica.core.support.IdentifierGenerator) Locale(java.util.Locale) Configuration(com.jayway.jsonpath.Configuration) Map(java.util.Map) SchemaFormContentFileService(org.obiba.mica.core.service.SchemaFormContentFileService) Resource(org.springframework.core.io.Resource) DataAccessRequestRepository(org.obiba.mica.access.DataAccessRequestRepository) Option(com.jayway.jsonpath.Option) NotNull(javax.validation.constraints.NotNull) Collectors(java.util.stream.Collectors) Sets(com.google.common.collect.Sets) PdfUtils(org.obiba.mica.PdfUtils) NoSuchDataAccessRequestException(org.obiba.mica.access.NoSuchDataAccessRequestException) List(java.util.List) ByteStreams(com.google.common.io.ByteStreams) PathNotFoundException(com.jayway.jsonpath.PathNotFoundException) SecurityUtils(org.apache.shiro.SecurityUtils) BeanUtils(org.springframework.beans.BeanUtils) ByteArrayOutputStream(java.io.ByteArrayOutputStream) Inject(javax.inject.Inject) EventBus(com.google.common.eventbus.EventBus) Value(org.springframework.beans.factory.annotation.Value) Strings(com.google.common.base.Strings) DataAccessFormService(org.obiba.mica.micaConfig.service.DataAccessFormService) Service(org.springframework.stereotype.Service) DataAccessRequest(org.obiba.mica.access.domain.DataAccessRequest) Nullable(javax.annotation.Nullable) OutputStream(java.io.OutputStream) MailService(org.obiba.mica.core.service.MailService) Validated(org.springframework.validation.annotation.Validated) Attachment(org.obiba.mica.file.Attachment) Logger(org.slf4j.Logger) InvalidPathException(com.jayway.jsonpath.InvalidPathException) DataAccessRequestUpdatedEvent(org.obiba.mica.access.event.DataAccessRequestUpdatedEvent) DateTime(org.joda.time.DateTime) Throwables(com.google.common.base.Throwables) IOException(java.io.IOException) JsonPath(com.jayway.jsonpath.JsonPath) Maps(com.google.common.collect.Maps) DocumentException(com.itextpdf.text.DocumentException) MicaConfigService(org.obiba.mica.micaConfig.service.MicaConfigService) Configuration.defaultConfiguration(com.jayway.jsonpath.Configuration.defaultConfiguration) DataAccessRequest(org.obiba.mica.access.domain.DataAccessRequest) Attachment(org.obiba.mica.file.Attachment) DataAccessRequestUpdatedEvent(org.obiba.mica.access.event.DataAccessRequestUpdatedEvent)

Example 54 with NotNull

use of javax.validation.constraints.NotNull in project mica2 by obiba.

the class DataAccessRequestDtos method fromDto.

@NotNull
public DataAccessRequest fromDto(@NotNull Mica.DataAccessRequestDto dto) {
    DataAccessRequest.Builder builder = DataAccessRequest.newBuilder();
    builder.applicant(dto.getApplicant()).status(dto.getStatus());
    if (dto.hasContent())
        builder.content(dto.getContent());
    DataAccessRequest request = builder.build();
    if (dto.hasId())
        request.setId(dto.getId());
    if (dto.getAttachmentsCount() > 0) {
        request.setAttachments(dto.getAttachmentsList().stream().map(attachmentDtos::fromDto).collect(Collectors.toList()));
    }
    TimestampsDtos.fromDto(dto.getTimestamps(), request);
    return request;
}
Also used : DataAccessRequest(org.obiba.mica.access.domain.DataAccessRequest) NotNull(javax.validation.constraints.NotNull)

Example 55 with NotNull

use of javax.validation.constraints.NotNull in project mica2 by obiba.

the class NetworkDtos method asDtoBuilder.

@NotNull
Mica.NetworkDto.Builder asDtoBuilder(@NotNull Network network, boolean asDraft) {
    Mica.NetworkDto.Builder builder = Mica.NetworkDto.newBuilder();
    if (network.hasModel())
        builder.setContent(JSONUtils.toJSON(network.getModel()));
    // 
    builder.setId(network.getId()).addAllName(// 
    localizedStringDtos.asDto(network.getName())).addAllDescription(// 
    localizedStringDtos.asDto(network.getDescription())).addAllAcronym(localizedStringDtos.asDto(network.getAcronym()));
    Mica.PermissionsDto permissionsDto = permissionsDtos.asDto(network);
    NetworkState networkState = networkService.getEntityState(network.getId());
    builder.setPublished(networkState.isPublished());
    if (asDraft) {
        // 
        builder.setTimestamps(TimestampsDtos.asDto(network)).setPublished(// 
        networkState.isPublished()).setExtension(Mica.EntityStateDto.state, entityStateDtos.asDto(networkState).setPermissions(permissionsDto).build());
    }
    builder.setPermissions(permissionsDto);
    List<String> roles = micaConfigService.getConfig().getRoles();
    if (network.getMemberships() != null) {
        List<Mica.MembershipsDto> memberships = network.getMemberships().entrySet().stream().filter(e -> roles.contains(e.getKey())).map(e -> Mica.MembershipsDto.newBuilder().setRole(e.getKey()).addAllMembers(e.getValue().stream().map(m -> personDtos.asDto(m.getPerson(), asDraft)).collect(toList())).build()).collect(toList());
        builder.addAllMemberships(memberships);
    }
    List<BaseStudy> publishedStudies = publishedStudyService.findByIds(network.getStudyIds());
    Set<String> publishedStudyIds = publishedStudies.stream().map(AbstractGitPersistable::getId).collect(Collectors.toSet());
    Sets.SetView<String> unpublishedStudyIds = Sets.difference(ImmutableSet.copyOf(network.getStudyIds().stream().filter(sId -> asDraft && subjectAclService.isPermitted("/draft/individual-study", "VIEW", sId) || subjectAclService.isAccessible("/individual-study", sId)).collect(toList())), publishedStudyIds);
    if (!publishedStudies.isEmpty()) {
        Map<String, Long> datasetVariableCounts = asDraft ? null : datasetVariableService.getCountByStudyIds(Lists.newArrayList(publishedStudyIds));
        publishedStudies.forEach(study -> {
            builder.addStudyIds(study.getId());
            builder.addStudySummaries(studySummaryDtos.asDtoBuilder(study, true, datasetVariableCounts == null ? 0 : datasetVariableCounts.get(study.getId())));
        });
    }
    unpublishedStudyIds.forEach(studyId -> {
        try {
            builder.addStudySummaries(studySummaryDtos.asDto(studyId));
            builder.addStudyIds(studyId);
        } catch (NoSuchEntityException e) {
            log.warn("Study not found in network {}: {}", network.getId(), studyId);
        // ignore
        }
    });
    if (network.getLogo() != null) {
        builder.setLogo(attachmentDtos.asDto(network.getLogo()));
    }
    network.getNetworkIds().stream().filter(nId -> asDraft && subjectAclService.isPermitted("/draft/network", "VIEW", nId) || subjectAclService.isAccessible("/network", nId)).forEach(nId -> {
        try {
            builder.addNetworkSummaries(networkSummaryDtos.asDtoBuilder(nId, asDraft));
            builder.addNetworkIds(nId);
        } catch (NoSuchEntityException e) {
            log.warn("Network not found in network {}: {}", network.getId(), nId);
        // ignore
        }
    });
    return builder;
}
Also used : LoggerFactory(org.slf4j.LoggerFactory) Membership(org.obiba.mica.core.domain.Membership) HashMap(java.util.HashMap) AbstractGitPersistable(org.obiba.mica.core.domain.AbstractGitPersistable) Inject(javax.inject.Inject) Strings(com.google.common.base.Strings) Map(java.util.Map) JSONUtils(org.obiba.mica.JSONUtils) Network(org.obiba.mica.network.domain.Network) Lists(jersey.repackaged.com.google.common.collect.Lists) PublishedDatasetVariableService(org.obiba.mica.study.service.PublishedDatasetVariableService) ImmutableSet(com.google.common.collect.ImmutableSet) SubjectAclService(org.obiba.mica.security.service.SubjectAclService) Logger(org.slf4j.Logger) HarmonizationStudy(org.obiba.mica.study.domain.HarmonizationStudy) BaseStudy(org.obiba.mica.study.domain.BaseStudy) Set(java.util.Set) NotNull(javax.validation.constraints.NotNull) Collectors(java.util.stream.Collectors) Maps(com.google.common.collect.Maps) Sets(com.google.common.collect.Sets) NoSuchEntityException(org.obiba.mica.NoSuchEntityException) PublishedStudyService(org.obiba.mica.study.service.PublishedStudyService) List(java.util.List) Component(org.springframework.stereotype.Component) Collectors.toList(java.util.stream.Collectors.toList) Study(org.obiba.mica.study.domain.Study) MicaConfigService(org.obiba.mica.micaConfig.service.MicaConfigService) NetworkState(org.obiba.mica.network.domain.NetworkState) NetworkService(org.obiba.mica.network.service.NetworkService) NoSuchEntityException(org.obiba.mica.NoSuchEntityException) Sets(com.google.common.collect.Sets) NetworkState(org.obiba.mica.network.domain.NetworkState) BaseStudy(org.obiba.mica.study.domain.BaseStudy) NotNull(javax.validation.constraints.NotNull)

Aggregations

NotNull (javax.validation.constraints.NotNull)77 List (java.util.List)24 Map (java.util.Map)18 Collectors (java.util.stream.Collectors)16 Inject (javax.inject.Inject)16 Logger (org.slf4j.Logger)14 ArrayList (java.util.ArrayList)13 LoggerFactory (org.slf4j.LoggerFactory)13 HashMap (java.util.HashMap)11 Response (javax.ws.rs.core.Response)10 Optional (java.util.Optional)9 Strings (com.google.common.base.Strings)8 Lists (com.google.common.collect.Lists)8 Set (java.util.Set)8 Valid (javax.validation.Valid)8 Api (io.swagger.annotations.Api)7 ApiParam (io.swagger.annotations.ApiParam)7 IOException (java.io.IOException)7 Collection (java.util.Collection)7 Nullable (javax.annotation.Nullable)7