Search in sources :

Example 6 with Usecase

use of org.qi4j.api.usecase.Usecase in project qi4j-sdk by Qi4j.

the class UnitOfWorkConcern method usecase.

private Usecase usecase() {
    String usecaseName = propagation.usecase();
    Usecase usecase;
    if (usecaseName == null) {
        usecase = Usecase.DEFAULT;
    } else {
        usecase = UsecaseBuilder.newUsecase(usecaseName);
    }
    return usecase;
}
Also used : Usecase(org.qi4j.api.usecase.Usecase)

Example 7 with Usecase

use of org.qi4j.api.usecase.Usecase in project qi4j-sdk by Qi4j.

the class UnitOfWorkInjectionTest method givenEntityInOneUnitOfWorkWhenCurrentUnitOfWorkHasChangedThenUnitOfWorkInjectionInEntityPointsToCorrectUow.

@Test
public void givenEntityInOneUnitOfWorkWhenCurrentUnitOfWorkHasChangedThenUnitOfWorkInjectionInEntityPointsToCorrectUow() throws Exception {
    Usecase usecase = UsecaseBuilder.newUsecase("usecase1");
    UnitOfWork uow = module.newUnitOfWork(usecase);
    try {
        Trial trial = uow.newEntity(Trial.class, "123");
        trial.doSomething();
        uow.complete();
        uow = module.newUnitOfWork(usecase);
        usecase = UsecaseBuilder.newUsecase("usecase2");
        UnitOfWork uow2 = module.newUnitOfWork(usecase);
        trial = uow.get(trial);
        trial.doSomething();
        assertEquals("123", ((EntityComposite) trial).identity().get());
        assertEquals("usecase1", trial.usecaseName());
        uow2.discard();
    } catch (Throwable ex) {
        ex.printStackTrace();
    } finally {
        try {
            while (module.isUnitOfWorkActive()) {
                uow = module.currentUnitOfWork();
                uow.discard();
            }
        } catch (IllegalStateException e) {
        // Continue
        }
    }
}
Also used : UnitOfWork(org.qi4j.api.unitofwork.UnitOfWork) EntityComposite(org.qi4j.api.entity.EntityComposite) Usecase(org.qi4j.api.usecase.Usecase) AbstractQi4jTest(org.qi4j.test.AbstractQi4jTest) Test(org.junit.Test)

Example 8 with Usecase

use of org.qi4j.api.usecase.Usecase in project qi4j-sdk by Qi4j.

the class EntityResource method delete.

@Override
protected Representation delete(Variant variant) throws ResourceException {
    Usecase usecase = UsecaseBuilder.newUsecase("Remove entity");
    EntityStoreUnitOfWork uow = entityStore.newUnitOfWork(usecase, module, System.currentTimeMillis());
    try {
        EntityReference identityRef = EntityReference.parseEntityReference(identity);
        uow.entityStateOf(identityRef).remove();
        uow.applyChanges().commit();
        getResponse().setStatus(Status.SUCCESS_NO_CONTENT);
    } catch (EntityNotFoundException e) {
        uow.discard();
        getResponse().setStatus(Status.CLIENT_ERROR_NOT_FOUND);
    }
    return new EmptyRepresentation();
}
Also used : EntityStoreUnitOfWork(org.qi4j.spi.entitystore.EntityStoreUnitOfWork) EmptyRepresentation(org.restlet.representation.EmptyRepresentation) EntityReference(org.qi4j.api.entity.EntityReference) Usecase(org.qi4j.api.usecase.Usecase) EntityNotFoundException(org.qi4j.spi.entitystore.EntityNotFoundException)

Example 9 with Usecase

use of org.qi4j.api.usecase.Usecase in project qi4j-sdk by Qi4j.

the class EntityResource method post.

@Override
public Representation post(Representation entityRepresentation, Variant variant) throws ResourceException {
    Usecase usecase = UsecaseBuilder.newUsecase("Update entity");
    EntityStoreUnitOfWork unitOfWork = entityStore.newUnitOfWork(usecase, module, System.currentTimeMillis());
    EntityState entity = getEntityState(unitOfWork);
    Form form = new Form(entityRepresentation);
    try {
        final EntityDescriptor descriptor = entity.entityDescriptor();
        // Parse JSON into properties
        for (PropertyDescriptor persistentProperty : descriptor.state().properties()) {
            if (!persistentProperty.isImmutable()) {
                String formValue = form.getFirstValue(persistentProperty.qualifiedName().name(), null);
                if (formValue == null) {
                    entity.setPropertyValue(persistentProperty.qualifiedName(), null);
                } else {
                    entity.setPropertyValue(persistentProperty.qualifiedName(), valueSerialization.deserialize(persistentProperty.valueType(), formValue));
                }
            }
        }
        for (AssociationDescriptor associationType : descriptor.state().associations()) {
            String newStringAssociation = form.getFirstValue(associationType.qualifiedName().name());
            if (newStringAssociation == null || newStringAssociation.isEmpty()) {
                entity.setAssociationValue(associationType.qualifiedName(), null);
            } else {
                entity.setAssociationValue(associationType.qualifiedName(), EntityReference.parseEntityReference(newStringAssociation));
            }
        }
        for (AssociationDescriptor associationType : descriptor.state().manyAssociations()) {
            String newStringAssociation = form.getFirstValue(associationType.qualifiedName().name());
            ManyAssociationState manyAssociation = entity.manyAssociationValueOf(associationType.qualifiedName());
            if (newStringAssociation == null) {
                // Remove "left-overs"
                for (EntityReference entityReference : manyAssociation) {
                    manyAssociation.remove(entityReference);
                }
                continue;
            }
            BufferedReader bufferedReader = new BufferedReader(new StringReader(newStringAssociation));
            String identity;
            try {
                // Synchronize old and new association
                int index = 0;
                while ((identity = bufferedReader.readLine()) != null) {
                    EntityReference reference = new EntityReference(identity);
                    if (manyAssociation.count() < index && manyAssociation.get(index).equals(reference)) {
                        continue;
                    }
                    try {
                        unitOfWork.entityStateOf(reference);
                        manyAssociation.remove(reference);
                        manyAssociation.add(index++, reference);
                    } catch (EntityNotFoundException e) {
                    // Ignore this entity - doesn't exist
                    }
                }
                // Remove "left-overs"
                while (manyAssociation.count() > index) {
                    manyAssociation.remove(manyAssociation.get(index));
                }
            } catch (IOException e) {
            // Ignore
            }
        }
        for (AssociationDescriptor associationType : descriptor.state().namedAssociations()) {
            String newStringAssociation = form.getFirstValue(associationType.qualifiedName().name());
            NamedAssociationState namedAssociation = entity.namedAssociationValueOf(associationType.qualifiedName());
            if (newStringAssociation == null) {
                // Remove "left-overs"
                for (String name : namedAssociation) {
                    namedAssociation.remove(name);
                }
                continue;
            }
            Set<String> names = new HashSet<>();
            BufferedReader bufferedReader = new BufferedReader(new StringReader(newStringAssociation));
            String line;
            try {
                while ((line = bufferedReader.readLine()) != null) {
                    String name = line;
                    line = bufferedReader.readLine();
                    if (line == null) {
                        break;
                    }
                    String identity = line;
                    EntityReference reference = new EntityReference(identity);
                    try {
                        unitOfWork.entityStateOf(reference);
                        namedAssociation.remove(name);
                        namedAssociation.put(name, reference);
                        names.add(name);
                    } catch (EntityNotFoundException e) {
                    // Ignore this entity - doesn't exist
                    }
                }
                // Remove "left-overs"
                for (String assocName : Iterables.toList(namedAssociation)) {
                    if (!names.contains(assocName)) {
                        namedAssociation.remove(assocName);
                    }
                }
            } catch (IOException e) {
            // Ignore
            }
        }
    } catch (ValueSerializationException | IllegalArgumentException e) {
        throw new ResourceException(Status.SERVER_ERROR_INTERNAL, e);
    }
    try {
        unitOfWork.applyChanges().commit();
    } catch (ConcurrentEntityStateModificationException e) {
        throw new ResourceException(Status.CLIENT_ERROR_CONFLICT);
    } catch (EntityNotFoundException e) {
        throw new ResourceException(Status.CLIENT_ERROR_GONE);
    }
    getResponse().setStatus(Status.SUCCESS_RESET_CONTENT);
    return new EmptyRepresentation();
}
Also used : PropertyDescriptor(org.qi4j.api.property.PropertyDescriptor) EntityStoreUnitOfWork(org.qi4j.spi.entitystore.EntityStoreUnitOfWork) Form(org.restlet.data.Form) NamedAssociationState(org.qi4j.spi.entity.NamedAssociationState) ValueSerializationException(org.qi4j.api.value.ValueSerializationException) EntityState(org.qi4j.spi.entity.EntityState) JSONEntityState(org.qi4j.spi.entitystore.helpers.JSONEntityState) AssociationDescriptor(org.qi4j.api.association.AssociationDescriptor) EntityNotFoundException(org.qi4j.spi.entitystore.EntityNotFoundException) IOException(java.io.IOException) ManyAssociationState(org.qi4j.spi.entity.ManyAssociationState) EntityDescriptor(org.qi4j.api.entity.EntityDescriptor) ConcurrentEntityStateModificationException(org.qi4j.spi.entitystore.ConcurrentEntityStateModificationException) EmptyRepresentation(org.restlet.representation.EmptyRepresentation) EntityReference(org.qi4j.api.entity.EntityReference) BufferedReader(java.io.BufferedReader) StringReader(java.io.StringReader) ResourceException(org.restlet.resource.ResourceException) Usecase(org.qi4j.api.usecase.Usecase) HashSet(java.util.HashSet)

Example 10 with Usecase

use of org.qi4j.api.usecase.Usecase in project qi4j-sdk by Qi4j.

the class ContextRestlet method handle.

@Override
public void handle(Request request, Response response) {
    super.handle(request, response);
    MDC.put("url", request.getResourceRef().toString());
    try {
        int tries = 0;
        // TODO Make this number configurable
        while (tries < 10) {
            tries++;
            // Root of the call
            Reference ref = request.getResourceRef();
            List<String> segments = ref.getScheme().equals("riap") ? ref.getRelativeRef(new Reference("riap://application/")).getSegments() : ref.getRelativeRef().getSegments();
            // Handle conversion of verbs into standard interactions
            if (segments.get(segments.size() - 1).equals("")) {
                if (request.getMethod().equals(Method.DELETE)) {
                    // Translate DELETE into command "delete"
                    segments.set(segments.size() - 1, "delete");
                } else if (request.getMethod().equals(Method.PUT)) {
                    // Translate PUT into command "update"
                    segments.set(segments.size() - 1, "update");
                }
            }
            request.getAttributes().put("segments", segments);
            request.getAttributes().put("template", new StringBuilder("/rest/"));
            Usecase usecase = UsecaseBuilder.buildUsecase(getUsecaseName(request)).withMetaInfo(request.getMethod().isSafe() ? CacheOptions.ALWAYS : CacheOptions.NEVER).newUsecase();
            UnitOfWork uow = module.newUnitOfWork(usecase);
            ObjectSelection.newSelection();
            try {
                // Start handling the build-up for the context
                Uniform resource = createRoot(request, response);
                resource.handle(request, response);
                if (response.getEntity() != null) {
                    if (response.getEntity().getModificationDate() == null) {
                        ResourceValidity validity = (ResourceValidity) Request.getCurrent().getAttributes().get(ContextResource.RESOURCE_VALIDITY);
                        if (validity != null) {
                            validity.updateResponse(response);
                        }
                    }
                    // Check if characterset is set
                    if (response.getEntity().getCharacterSet() == null) {
                        response.getEntity().setCharacterSet(CharacterSet.UTF_8);
                    }
                    // Check if language is set
                    if (response.getEntity().getLanguages().isEmpty()) {
                        response.getEntity().getLanguages().add(Language.ENGLISH);
                    }
                    uow.discard();
                } else {
                    // Check if last modified and tag is set
                    ResourceValidity validity = null;
                    try {
                        validity = ObjectSelection.type(ResourceValidity.class);
                    } catch (IllegalArgumentException e) {
                    // Ignore
                    }
                    uow.complete();
                    Object result = commandResult.getResult();
                    if (result != null) {
                        if (result instanceof Representation) {
                            response.setEntity((Representation) result);
                        } else {
                            if (!responseWriter.writeResponse(result, response)) {
                                throw new ResourceException(Status.SERVER_ERROR_INTERNAL, "Could not write result of type " + result.getClass().getName());
                            }
                        }
                        if (response.getEntity() != null) {
                            // Check if characterset is set
                            if (response.getEntity().getCharacterSet() == null) {
                                response.getEntity().setCharacterSet(CharacterSet.UTF_8);
                            }
                            // Check if language is set
                            if (response.getEntity().getLanguages().isEmpty()) {
                                response.getEntity().getLanguages().add(Language.ENGLISH);
                            }
                            // Check if last modified and tag should be set
                            if (validity != null) {
                                UnitOfWork lastModifiedUoW = module.newUnitOfWork();
                                try {
                                    validity.updateEntity(lastModifiedUoW);
                                    validity.updateResponse(response);
                                } finally {
                                    lastModifiedUoW.discard();
                                }
                            }
                        }
                    }
                    return;
                }
                return;
            } catch (ConcurrentEntityModificationException ex) {
                uow.discard();
                // Try again
                ObjectSelection.newSelection();
            } catch (Throwable e) {
                uow.discard();
                handleException(response, e);
                return;
            }
        }
    // Try again
    } finally {
        MDC.clear();
    }
}
Also used : UnitOfWork(org.qi4j.api.unitofwork.UnitOfWork) Reference(org.restlet.data.Reference) Uniform(org.restlet.Uniform) StringRepresentation(org.restlet.representation.StringRepresentation) Representation(org.restlet.representation.Representation) ConcurrentEntityModificationException(org.qi4j.api.unitofwork.ConcurrentEntityModificationException) ResourceException(org.restlet.resource.ResourceException) Usecase(org.qi4j.api.usecase.Usecase)

Aggregations

Usecase (org.qi4j.api.usecase.Usecase)11 UnitOfWork (org.qi4j.api.unitofwork.UnitOfWork)6 Test (org.junit.Test)4 Before (org.junit.Before)2 EntityReference (org.qi4j.api.entity.EntityReference)2 EntityNotFoundException (org.qi4j.spi.entitystore.EntityNotFoundException)2 EntityStoreUnitOfWork (org.qi4j.spi.entitystore.EntityStoreUnitOfWork)2 EmptyRepresentation (org.restlet.representation.EmptyRepresentation)2 ResourceException (org.restlet.resource.ResourceException)2 BufferedReader (java.io.BufferedReader)1 IOException (java.io.IOException)1 StringReader (java.io.StringReader)1 Connection (java.sql.Connection)1 PreparedStatement (java.sql.PreparedStatement)1 ResultSet (java.sql.ResultSet)1 SQLException (java.sql.SQLException)1 HashSet (java.util.HashSet)1 DateTime (org.joda.time.DateTime)1 Interval (org.joda.time.Interval)1 AssociationDescriptor (org.qi4j.api.association.AssociationDescriptor)1