Search in sources :

Example 31 with EntityStoreException

use of org.qi4j.spi.entitystore.EntityStoreException in project qi4j-sdk by Qi4j.

the class SQLEntityStoreMixin method applyChanges.

@Override
public StateCommitter applyChanges(final EntityStoreUnitOfWork unitofwork, final Iterable<EntityState> states) {
    return new StateCommitter() {

        @Override
        public void commit() {
            Connection connection = null;
            PreparedStatement insertPS = null;
            PreparedStatement updatePS = null;
            PreparedStatement removePS = null;
            try {
                connection = database.getConnection();
                connection.setAutoCommit(false);
                insertPS = database.prepareInsertEntityStatement(connection);
                updatePS = database.prepareUpdateEntityStatement(connection);
                removePS = database.prepareRemoveEntityStatement(connection);
                for (EntityState state : states) {
                    EntityStatus status = state.status();
                    DefaultEntityState defState = ((SQLEntityState) state).getDefaultEntityState();
                    Long entityPK = ((SQLEntityState) state).getEntityPK();
                    if (EntityStatus.REMOVED.equals(status)) {
                        database.populateRemoveEntityStatement(removePS, entityPK, state.identity());
                        removePS.addBatch();
                    } else {
                        StringWriter writer = new StringWriter();
                        writeEntityState(defState, writer, unitofwork.identity());
                        writer.flush();
                        if (EntityStatus.UPDATED.equals(status)) {
                            Long entityOptimisticLock = ((SQLEntityState) state).getEntityOptimisticLock();
                            database.populateUpdateEntityStatement(updatePS, entityPK, entityOptimisticLock, defState.identity(), writer.toString(), unitofwork.currentTime());
                            updatePS.addBatch();
                        } else if (EntityStatus.NEW.equals(status)) {
                            database.populateInsertEntityStatement(insertPS, defState.identity(), writer.toString(), unitofwork.currentTime());
                            insertPS.addBatch();
                        }
                    }
                }
                removePS.executeBatch();
                insertPS.executeBatch();
                updatePS.executeBatch();
                connection.commit();
            } catch (SQLException sqle) {
                SQLUtil.rollbackQuietly(connection);
                if (LOGGER.isDebugEnabled()) {
                    StringWriter sb = new StringWriter();
                    sb.append("SQLException during commit, logging nested exceptions before throwing EntityStoreException:\n");
                    SQLException e = sqle;
                    while (e != null) {
                        e.printStackTrace(new PrintWriter(sb, true));
                        e = e.getNextException();
                    }
                    LOGGER.debug(sb.toString());
                }
                throw new EntityStoreException(sqle);
            } catch (RuntimeException re) {
                SQLUtil.rollbackQuietly(connection);
                throw new EntityStoreException(re);
            } finally {
                SQLUtil.closeQuietly(insertPS);
                SQLUtil.closeQuietly(updatePS);
                SQLUtil.closeQuietly(removePS);
                SQLUtil.closeQuietly(connection);
            }
        }

        @Override
        public void cancel() {
        }
    };
}
Also used : SQLEntityState(org.qi4j.entitystore.sql.internal.SQLEntityState) DefaultSQLEntityState(org.qi4j.entitystore.sql.internal.SQLEntityState.DefaultSQLEntityState) DefaultEntityState(org.qi4j.spi.entitystore.helpers.DefaultEntityState) SQLException(java.sql.SQLException) Connection(java.sql.Connection) PreparedStatement(java.sql.PreparedStatement) SQLEntityState(org.qi4j.entitystore.sql.internal.SQLEntityState) EntityState(org.qi4j.spi.entity.EntityState) DefaultSQLEntityState(org.qi4j.entitystore.sql.internal.SQLEntityState.DefaultSQLEntityState) DefaultEntityState(org.qi4j.spi.entitystore.helpers.DefaultEntityState) StringWriter(java.io.StringWriter) EntityStatus(org.qi4j.spi.entity.EntityStatus) StateCommitter(org.qi4j.spi.entitystore.StateCommitter) EntityStoreException(org.qi4j.spi.entitystore.EntityStoreException) PrintWriter(java.io.PrintWriter)

Example 32 with EntityStoreException

use of org.qi4j.spi.entitystore.EntityStoreException in project qi4j-sdk by Qi4j.

the class PreferencesEntityStoreMixin method writeEntityState.

protected void writeEntityState(DefaultEntityState state, Preferences entityPrefs, String identity, long lastModified) throws EntityStoreException {
    try {
        // Store into Preferences API
        entityPrefs.put("type", first(state.entityDescriptor().types()).getName());
        entityPrefs.put("version", identity);
        entityPrefs.putLong("modified", lastModified);
        // Properties
        Preferences propsPrefs = entityPrefs.node("properties");
        for (PropertyDescriptor persistentProperty : state.entityDescriptor().state().properties()) {
            if (persistentProperty.qualifiedName().name().equals("identity")) {
                // Skip Identity.identity()
                continue;
            }
            Object value = state.properties().get(persistentProperty.qualifiedName());
            if (value == null) {
                propsPrefs.remove(persistentProperty.qualifiedName().name());
            } else {
                ValueType valueType = persistentProperty.valueType();
                Class<?> mainType = valueType.mainType();
                if (Number.class.isAssignableFrom(mainType)) {
                    if (mainType.equals(Long.class)) {
                        propsPrefs.putLong(persistentProperty.qualifiedName().name(), (Long) value);
                    } else if (mainType.equals(Integer.class)) {
                        propsPrefs.putInt(persistentProperty.qualifiedName().name(), (Integer) value);
                    } else if (mainType.equals(Double.class)) {
                        propsPrefs.putDouble(persistentProperty.qualifiedName().name(), (Double) value);
                    } else if (mainType.equals(Float.class)) {
                        propsPrefs.putFloat(persistentProperty.qualifiedName().name(), (Float) value);
                    } else {
                        // Store as string even though it's a number
                        String jsonString = valueSerialization.serialize(value);
                        propsPrefs.put(persistentProperty.qualifiedName().name(), jsonString);
                    }
                } else if (mainType.equals(Boolean.class)) {
                    propsPrefs.putBoolean(persistentProperty.qualifiedName().name(), (Boolean) value);
                } else if (valueType instanceof ValueCompositeType || valueType instanceof MapType || valueType instanceof CollectionType || valueType instanceof EnumType) {
                    String jsonString = valueSerialization.serialize(value);
                    propsPrefs.put(persistentProperty.qualifiedName().name(), jsonString);
                } else {
                    String jsonString = valueSerialization.serialize(value);
                    propsPrefs.put(persistentProperty.qualifiedName().name(), jsonString);
                }
            }
        }
        // Associations
        if (!state.associations().isEmpty()) {
            Preferences assocsPrefs = entityPrefs.node("associations");
            for (Map.Entry<QualifiedName, EntityReference> association : state.associations().entrySet()) {
                if (association.getValue() == null) {
                    assocsPrefs.remove(association.getKey().name());
                } else {
                    assocsPrefs.put(association.getKey().name(), association.getValue().identity());
                }
            }
        }
        // ManyAssociations
        if (!state.manyAssociations().isEmpty()) {
            Preferences manyAssocsPrefs = entityPrefs.node("manyassociations");
            for (Map.Entry<QualifiedName, List<EntityReference>> manyAssociation : state.manyAssociations().entrySet()) {
                StringBuilder manyAssocs = new StringBuilder();
                for (EntityReference entityReference : manyAssociation.getValue()) {
                    if (manyAssocs.length() > 0) {
                        manyAssocs.append("\n");
                    }
                    manyAssocs.append(entityReference.identity());
                }
                if (manyAssocs.length() > 0) {
                    manyAssocsPrefs.put(manyAssociation.getKey().name(), manyAssocs.toString());
                }
            }
        }
        // NamedAssociations
        if (!state.namedAssociations().isEmpty()) {
            Preferences namedAssocsPrefs = entityPrefs.node("namedassociations");
            for (Map.Entry<QualifiedName, Map<String, EntityReference>> namedAssociation : state.namedAssociations().entrySet()) {
                StringBuilder namedAssocs = new StringBuilder();
                for (Map.Entry<String, EntityReference> namedRef : namedAssociation.getValue().entrySet()) {
                    if (namedAssocs.length() > 0) {
                        namedAssocs.append("\n");
                    }
                    namedAssocs.append(namedRef.getKey()).append("\n").append(namedRef.getValue().identity());
                }
                if (namedAssocs.length() > 0) {
                    namedAssocsPrefs.put(namedAssociation.getKey().name(), namedAssocs.toString());
                }
            }
        }
    } catch (ValueSerializationException e) {
        throw new EntityStoreException("Could not store EntityState", e);
    }
}
Also used : PropertyDescriptor(org.qi4j.api.property.PropertyDescriptor) ValueType(org.qi4j.api.type.ValueType) QualifiedName(org.qi4j.api.common.QualifiedName) ValueSerializationException(org.qi4j.api.value.ValueSerializationException) MapType(org.qi4j.api.type.MapType) EnumType(org.qi4j.api.type.EnumType) CollectionType(org.qi4j.api.type.CollectionType) EntityReference(org.qi4j.api.entity.EntityReference) List(java.util.List) ArrayList(java.util.ArrayList) EntityStoreException(org.qi4j.spi.entitystore.EntityStoreException) Preferences(java.util.prefs.Preferences) Map(java.util.Map) HashMap(java.util.HashMap) LinkedHashMap(java.util.LinkedHashMap) ValueCompositeType(org.qi4j.api.type.ValueCompositeType)

Example 33 with EntityStoreException

use of org.qi4j.spi.entitystore.EntityStoreException in project qi4j-sdk by Qi4j.

the class AbstractRiakMapEntityStore method applyChanges.

@Override
public void applyChanges(MapChanges changes) throws IOException {
    try {
        final Bucket bucket = riakClient.fetchBucket(bucketKey).execute();
        changes.visitMap(new MapChanger() {

            @Override
            public Writer newEntity(final EntityReference ref, EntityDescriptor entityDescriptor) throws IOException {
                return new StringWriter(1000) {

                    @Override
                    public void close() throws IOException {
                        try {
                            super.close();
                            bucket.store(ref.identity(), toString()).execute();
                        } catch (RiakException ex) {
                            throw new EntityStoreException("Unable to apply entity change: newEntity", ex);
                        }
                    }
                };
            }

            @Override
            public Writer updateEntity(final EntityReference ref, EntityDescriptor entityDescriptor) throws IOException {
                return new StringWriter(1000) {

                    @Override
                    public void close() throws IOException {
                        try {
                            super.close();
                            IRiakObject entity = bucket.fetch(ref.identity()).execute();
                            if (entity == null) {
                                throw new EntityNotFoundException(ref);
                            }
                            bucket.store(ref.identity(), toString()).execute();
                        } catch (RiakException ex) {
                            throw new EntityStoreException("Unable to apply entity change: updateEntity", ex);
                        }
                    }
                };
            }

            @Override
            public void removeEntity(EntityReference ref, EntityDescriptor entityDescriptor) throws EntityNotFoundException {
                try {
                    IRiakObject entity = bucket.fetch(ref.identity()).execute();
                    if (entity == null) {
                        throw new EntityNotFoundException(ref);
                    }
                    bucket.delete(ref.identity()).execute();
                } catch (RiakException ex) {
                    throw new EntityStoreException("Unable to apply entity change: removeEntity", ex);
                }
            }
        });
    } catch (RiakRetryFailedException ex) {
        throw new EntityStoreException("Unable to apply entity changes.", ex);
    }
}
Also used : IRiakObject(com.basho.riak.client.IRiakObject) IOException(java.io.IOException) EntityNotFoundException(org.qi4j.spi.entitystore.EntityNotFoundException) EntityDescriptor(org.qi4j.api.entity.EntityDescriptor) StringWriter(java.io.StringWriter) Bucket(com.basho.riak.client.bucket.Bucket) EntityReference(org.qi4j.api.entity.EntityReference) EntityStoreException(org.qi4j.spi.entitystore.EntityStoreException) RiakRetryFailedException(com.basho.riak.client.RiakRetryFailedException) StringWriter(java.io.StringWriter) Writer(java.io.Writer) RiakException(com.basho.riak.client.RiakException)

Example 34 with EntityStoreException

use of org.qi4j.spi.entitystore.EntityStoreException in project qi4j-sdk by Qi4j.

the class AbstractRiakMapEntityStore method get.

@Override
public Reader get(EntityReference entityReference) throws EntityStoreException {
    try {
        Bucket bucket = riakClient.fetchBucket(bucketKey).execute();
        IRiakObject entity = bucket.fetch(entityReference.identity()).execute();
        if (entity == null) {
            throw new EntityNotFoundException(entityReference);
        }
        String jsonState = entity.getValueAsString();
        return new StringReader(jsonState);
    } catch (RiakRetryFailedException ex) {
        throw new EntityStoreException("Unable to get Entity " + entityReference.identity(), ex);
    }
}
Also used : Bucket(com.basho.riak.client.bucket.Bucket) IRiakObject(com.basho.riak.client.IRiakObject) StringReader(java.io.StringReader) EntityNotFoundException(org.qi4j.spi.entitystore.EntityNotFoundException) EntityStoreException(org.qi4j.spi.entitystore.EntityStoreException) RiakRetryFailedException(com.basho.riak.client.RiakRetryFailedException)

Example 35 with EntityStoreException

use of org.qi4j.spi.entitystore.EntityStoreException in project qi4j-sdk by Qi4j.

the class VoldemortEntityStoreMixin method get.

@Override
public Reader get(EntityReference entityReference) throws EntityStoreException {
    try {
        Versioned<byte[]> versioned = client.get(entityReference.identity());
        if (versioned == null) {
            throw new EntityNotFoundException(entityReference);
        }
        byte[] serializedState = versioned.getValue();
        return new StringReader(new String(serializedState, "UTF-8"));
    } catch (IOException e) {
        throw new EntityStoreException(e);
    }
}
Also used : EntityNotFoundException(org.qi4j.spi.entitystore.EntityNotFoundException) EntityStoreException(org.qi4j.spi.entitystore.EntityStoreException)

Aggregations

EntityStoreException (org.qi4j.spi.entitystore.EntityStoreException)35 JSONException (org.json.JSONException)16 JSONObject (org.json.JSONObject)13 EntityReference (org.qi4j.api.entity.EntityReference)9 PropertyDescriptor (org.qi4j.api.property.PropertyDescriptor)9 EntityDescriptor (org.qi4j.api.entity.EntityDescriptor)8 EntityNotFoundException (org.qi4j.spi.entitystore.EntityNotFoundException)8 IOException (java.io.IOException)7 ArrayList (java.util.ArrayList)6 HashMap (java.util.HashMap)6 LinkedHashMap (java.util.LinkedHashMap)6 List (java.util.List)6 Map (java.util.Map)6 JSONArray (org.json.JSONArray)6 QualifiedName (org.qi4j.api.common.QualifiedName)6 ValueSerializationException (org.qi4j.api.value.ValueSerializationException)5 DefaultEntityState (org.qi4j.spi.entitystore.helpers.DefaultEntityState)5 StringReader (java.io.StringReader)4 Connection (java.sql.Connection)4 Module (org.qi4j.api.structure.Module)4