http://git-wip-us.apache.org/repos/asf/zest-java/blob/bd6fbad9/extensions/entitystore-preferences/src/main/java/org/apache/zest/entitystore/prefs/PreferencesEntityStoreMixin.java ---------------------------------------------------------------------- diff --git a/extensions/entitystore-preferences/src/main/java/org/apache/zest/entitystore/prefs/PreferencesEntityStoreMixin.java b/extensions/entitystore-preferences/src/main/java/org/apache/zest/entitystore/prefs/PreferencesEntityStoreMixin.java index 7bc4ddb..ac1098b 100644 --- a/extensions/entitystore-preferences/src/main/java/org/apache/zest/entitystore/prefs/PreferencesEntityStoreMixin.java +++ b/extensions/entitystore-preferences/src/main/java/org/apache/zest/entitystore/prefs/PreferencesEntityStoreMixin.java @@ -29,7 +29,6 @@ import java.util.concurrent.ScheduledThreadPoolExecutor; import java.util.concurrent.TimeUnit; import java.util.prefs.BackingStoreException; import java.util.prefs.Preferences; -import org.apache.zest.api.association.AssociationDescriptor; import org.apache.zest.api.cache.CacheOptions; import org.apache.zest.api.common.QualifiedName; import org.apache.zest.api.entity.EntityDescriptor; @@ -74,9 +73,6 @@ import org.apache.zest.spi.module.ModuleSpi; import org.slf4j.Logger; import org.slf4j.LoggerFactory; -import static org.apache.zest.functional.Iterables.first; -import static org.apache.zest.functional.Iterables.map; - /** * Implementation of EntityStore that is backed by the Preferences API. * @@ -108,9 +104,13 @@ public class PreferencesEntityStoreMixin private ValueSerialization valueSerialization; private Preferences root; + protected String uuid; + private int count; + public Logger logger; + public ScheduledThreadPoolExecutor reloadExecutor; @Override @@ -125,23 +125,19 @@ public class PreferencesEntityStoreMixin // Reload underlying store every 60 seconds reloadExecutor = new ScheduledThreadPoolExecutor( 1 ); reloadExecutor.setExecuteExistingDelayedTasksAfterShutdownPolicy( false ); - reloadExecutor.scheduleAtFixedRate( new Runnable() - { - @Override - public void run() + reloadExecutor.scheduleAtFixedRate( () -> { + try { - try + //noinspection SynchronizeOnNonFinalField + synchronized( root ) { - synchronized( root ) - { - root.sync(); - } - } - catch( BackingStoreException e ) - { - logger.warn( "Could not reload preferences", e ); + root.sync(); } } + catch( BackingStoreException e ) + { + logger.warn( "Could not reload preferences", e ); + } }, 0, 60, TimeUnit.SECONDS ); } @@ -193,8 +189,8 @@ public class PreferencesEntityStoreMixin output.receiveFrom( new Sender<EntityState, EntityStoreException>() { @Override - public <ReceiverThrowableType extends Throwable> void sendTo( Receiver<? super EntityState, ReceiverThrowableType> receiver ) - throws ReceiverThrowableType, EntityStoreException + public <RecThrowableType extends Throwable> void sendTo( Receiver<? super EntityState, RecThrowableType> receiver ) + throws RecThrowableType, EntityStoreException { UsecaseBuilder builder = UsecaseBuilder.buildUsecase( "zest.entitystore.preferences.visit" ); Usecase visitUsecase = builder.withMetaInfo( CacheOptions.NEVER ).newUsecase(); @@ -251,54 +247,74 @@ public class PreferencesEntityStoreMixin { throw new EntityTypeNotFoundException( type, module.name(), - map( ModelModule.toStringFunction, - module.findVisibleEntityTypes() - ) ); + module.findVisibleEntityTypes() + .map( ModelModule.toStringFunction ) + ); } Map<QualifiedName, Object> properties = new HashMap<>(); - Preferences propsPrefs = null; - for( PropertyDescriptor persistentPropertyDescriptor : entityDescriptor.state().properties() ) + final Preferences propsPrefs = entityPrefs.node( "properties" ); + entityDescriptor.state().properties().forEach( persistentPropertyDescriptor -> { if( persistentPropertyDescriptor.qualifiedName().name().equals( "identity" ) ) { // Fake identity property properties.put( persistentPropertyDescriptor.qualifiedName(), identity.identity() ); - continue; - } - - if( propsPrefs == null ) - { - propsPrefs = entityPrefs.node( "properties" ); } - - ValueType propertyType = persistentPropertyDescriptor.valueType(); - Class<?> mainType = propertyType.mainType(); - if( Number.class.isAssignableFrom( mainType ) ) + else { - if( mainType.equals( Long.class ) ) - { - properties.put( persistentPropertyDescriptor.qualifiedName(), - this.getNumber( propsPrefs, persistentPropertyDescriptor, LONG_PARSER ) ); - } - else if( mainType.equals( Integer.class ) ) - { - properties.put( persistentPropertyDescriptor.qualifiedName(), - this.getNumber( propsPrefs, persistentPropertyDescriptor, INT_PARSER ) ); - } - else if( mainType.equals( Double.class ) ) + ValueType propertyType = persistentPropertyDescriptor.valueType(); + Class<?> mainType = propertyType.mainType(); + if( Number.class.isAssignableFrom( mainType ) ) { - properties.put( persistentPropertyDescriptor.qualifiedName(), - this.getNumber( propsPrefs, persistentPropertyDescriptor, DOUBLE_PARSER ) ); + if( mainType.equals( Long.class ) ) + { + properties.put( persistentPropertyDescriptor.qualifiedName(), + this.getNumber( propsPrefs, persistentPropertyDescriptor, LONG_PARSER ) ); + } + else if( mainType.equals( Integer.class ) ) + { + properties.put( persistentPropertyDescriptor.qualifiedName(), + this.getNumber( propsPrefs, persistentPropertyDescriptor, INT_PARSER ) ); + } + else if( mainType.equals( Double.class ) ) + { + properties.put( persistentPropertyDescriptor.qualifiedName(), + this.getNumber( propsPrefs, persistentPropertyDescriptor, DOUBLE_PARSER ) ); + } + else if( mainType.equals( Float.class ) ) + { + properties.put( persistentPropertyDescriptor.qualifiedName(), + this.getNumber( propsPrefs, persistentPropertyDescriptor, FLOAT_PARSER ) ); + } + else + { + // Load as string even though it's a number + String json = propsPrefs.get( persistentPropertyDescriptor.qualifiedName().name(), null ); + Object value; + if( json == null ) + { + value = null; + } + else + { + value = valueSerialization.deserialize( persistentPropertyDescriptor.valueType(), json ); + } + properties.put( persistentPropertyDescriptor.qualifiedName(), value ); + } } - else if( mainType.equals( Float.class ) ) + else if( mainType.equals( Boolean.class ) ) { + Boolean initialValue = (Boolean) persistentPropertyDescriptor.initialValue( module ); properties.put( persistentPropertyDescriptor.qualifiedName(), - this.getNumber( propsPrefs, persistentPropertyDescriptor, FLOAT_PARSER ) ); + propsPrefs.getBoolean( persistentPropertyDescriptor.qualifiedName().name(), + initialValue == null ? false : initialValue ) ); } - else + else if( propertyType instanceof ValueCompositeType + || propertyType instanceof MapType + || propertyType instanceof CollectionType + || propertyType instanceof EnumType ) { - // Load as string even though it's a number String json = propsPrefs.get( persistentPropertyDescriptor.qualifiedName().name(), null ); Object value; if( json == null ) @@ -311,82 +327,49 @@ public class PreferencesEntityStoreMixin } properties.put( persistentPropertyDescriptor.qualifiedName(), value ); } - } - else if( mainType.equals( Boolean.class ) ) - { - Boolean initialValue = (Boolean) persistentPropertyDescriptor.initialValue( module ); - properties.put( persistentPropertyDescriptor.qualifiedName(), - propsPrefs.getBoolean( persistentPropertyDescriptor.qualifiedName().name(), - initialValue == null ? false : initialValue ) ); - } - else if( propertyType instanceof ValueCompositeType - || propertyType instanceof MapType - || propertyType instanceof CollectionType - || propertyType instanceof EnumType ) - { - String json = propsPrefs.get( persistentPropertyDescriptor.qualifiedName().name(), null ); - Object value; - if( json == null ) - { - value = null; - } else { - value = valueSerialization.deserialize( persistentPropertyDescriptor.valueType(), json ); - } - properties.put( persistentPropertyDescriptor.qualifiedName(), value ); - } - else - { - String json = propsPrefs.get( persistentPropertyDescriptor.qualifiedName().name(), null ); - if( json == null ) - { - if( persistentPropertyDescriptor.initialValue( module ) != null ) + String json = propsPrefs.get( persistentPropertyDescriptor.qualifiedName().name(), null ); + if( json == null ) { - properties.put( persistentPropertyDescriptor.qualifiedName(), persistentPropertyDescriptor.initialValue( module ) ); + if( persistentPropertyDescriptor.initialValue( module ) != null ) + { + properties.put( persistentPropertyDescriptor.qualifiedName(), persistentPropertyDescriptor + .initialValue( module ) ); + } + else + { + properties.put( persistentPropertyDescriptor.qualifiedName(), null ); + } } else { - properties.put( persistentPropertyDescriptor.qualifiedName(), null ); + Object value = valueSerialization.deserialize( propertyType, json ); + properties.put( persistentPropertyDescriptor.qualifiedName(), value ); } } - else - { - Object value = valueSerialization.deserialize( propertyType, json ); - properties.put( persistentPropertyDescriptor.qualifiedName(), value ); - } } - } + } ); // Associations Map<QualifiedName, EntityReference> associations = new HashMap<>(); - Preferences assocs = null; - for( AssociationDescriptor associationType : entityDescriptor.state().associations() ) - { - if( assocs == null ) - { - assocs = entityPrefs.node( "associations" ); - } - + final Preferences assocs = entityPrefs.node( "associations" ); + entityDescriptor.state().associations().forEach( associationType -> { String associatedEntity = assocs.get( associationType.qualifiedName().name(), null ); EntityReference value = associatedEntity == null ? null : EntityReference.parseEntityReference( associatedEntity ); associations.put( associationType.qualifiedName(), value ); - } + } ); // ManyAssociations Map<QualifiedName, List<EntityReference>> manyAssociations = new HashMap<>(); - Preferences manyAssocs = null; - for( AssociationDescriptor manyAssociationType : entityDescriptor.state().manyAssociations() ) - { - if( manyAssocs == null ) - { - manyAssocs = entityPrefs.node( "manyassociations" ); - } - + Preferences manyAssocs = entityPrefs.node( "manyassociations" ); + entityDescriptor.state().manyAssociations().forEach( manyAssociationType -> { List<EntityReference> references = new ArrayList<>(); - String entityReferences = manyAssocs.get( manyAssociationType.qualifiedName().name(), null ); + String entityReferences = manyAssocs.get( manyAssociationType + .qualifiedName() + .name(), null ); if( entityReferences == null ) { // ManyAssociation not found, default to empty one @@ -404,18 +387,12 @@ public class PreferencesEntityStoreMixin } manyAssociations.put( manyAssociationType.qualifiedName(), references ); } - } + } ); // NamedAssociations Map<QualifiedName, Map<String, EntityReference>> namedAssociations = new HashMap<>(); - Preferences namedAssocs = null; - for( AssociationDescriptor namedAssociationType : entityDescriptor.state().namedAssociations() ) - { - if( namedAssocs == null ) - { - namedAssocs = entityPrefs.node( "namedassociations" ); - } - + Preferences namedAssocs = entityPrefs.node( "namedassociations" ); + entityDescriptor.state().namedAssociations().forEach( namedAssociationType -> { Map<String, EntityReference> references = new LinkedHashMap<>(); String entityReferences = namedAssocs.get( namedAssociationType.qualifiedName().name(), null ); if( entityReferences == null ) @@ -438,7 +415,7 @@ public class PreferencesEntityStoreMixin } namedAssociations.put( namedAssociationType.qualifiedName(), references ); } - } + } ); return new DefaultEntityState( entityPrefs.get( "version", "" ), entityPrefs.getLong( "modified", unitOfWork.currentTime() ), @@ -514,73 +491,74 @@ public class PreferencesEntityStoreMixin try { // Store into Preferences API - entityPrefs.put( "type", first( state.entityDescriptor().types() ).getName() ); + entityPrefs.put( "type", state.entityDescriptor().types().findFirst().get().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" ) ) - { - continue; // Skip Identity.identity() - } - - 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 ); + state.entityDescriptor().state().properties() + .filter(property -> ! property.qualifiedName().name().equals( "identity" )) + .forEach( persistentProperty -> + { + 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() ) @@ -661,41 +639,13 @@ public class PreferencesEntityStoreMixin T parse( String str ); } - private static final NumberParser<Long> LONG_PARSER = new NumberParser<Long>() - { - @Override - public Long parse( String str ) - { - return Long.parseLong( str ); - } - }; + private static final NumberParser<Long> LONG_PARSER = Long::parseLong; - private static final NumberParser<Integer> INT_PARSER = new NumberParser<Integer>() - { - @Override - public Integer parse( String str ) - { - return Integer.parseInt( str ); - } - }; + private static final NumberParser<Integer> INT_PARSER = Integer::parseInt; - private static final NumberParser<Double> DOUBLE_PARSER = new NumberParser<Double>() - { - @Override - public Double parse( String str ) - { - return Double.parseDouble( str ); - } - }; + private static final NumberParser<Double> DOUBLE_PARSER = Double::parseDouble; - private static final NumberParser<Float> FLOAT_PARSER = new NumberParser<Float>() - { - @Override - public Float parse( String str ) - { - return Float.parseFloat( str ); - } - }; + private static final NumberParser<Float> FLOAT_PARSER = Float::parseFloat; private <T> T getNumber( Preferences prefs, PropertyDescriptor pDesc, NumberParser<T> parser ) {
http://git-wip-us.apache.org/repos/asf/zest-java/blob/bd6fbad9/extensions/entitystore-sql/src/main/java/org/apache/zest/entitystore/sql/SQLEntityStoreMixin.java ---------------------------------------------------------------------- diff --git a/extensions/entitystore-sql/src/main/java/org/apache/zest/entitystore/sql/SQLEntityStoreMixin.java b/extensions/entitystore-sql/src/main/java/org/apache/zest/entitystore/sql/SQLEntityStoreMixin.java index f79e5b6..6dfdae0 100644 --- a/extensions/entitystore-sql/src/main/java/org/apache/zest/entitystore/sql/SQLEntityStoreMixin.java +++ b/extensions/entitystore-sql/src/main/java/org/apache/zest/entitystore/sql/SQLEntityStoreMixin.java @@ -30,12 +30,6 @@ import java.util.List; import java.util.Map; import java.util.UUID; import java.util.concurrent.atomic.AtomicInteger; -import org.json.JSONArray; -import org.json.JSONException; -import org.json.JSONObject; -import org.json.JSONTokener; -import org.json.JSONWriter; -import org.apache.zest.api.association.AssociationDescriptor; import org.apache.zest.api.cache.CacheOptions; import org.apache.zest.api.common.Optional; import org.apache.zest.api.common.QualifiedName; @@ -44,7 +38,6 @@ import org.apache.zest.api.entity.EntityReference; import org.apache.zest.api.injection.scope.Service; import org.apache.zest.api.injection.scope.Structure; import org.apache.zest.api.injection.scope.This; -import org.apache.zest.api.property.PropertyDescriptor; import org.apache.zest.api.service.ServiceActivation; import org.apache.zest.api.service.qualifier.Tagged; import org.apache.zest.api.structure.Application; @@ -80,12 +73,14 @@ import org.apache.zest.spi.entitystore.helpers.Migration; import org.apache.zest.spi.entitystore.helpers.StateStore; import org.apache.zest.spi.module.ModelModule; import org.apache.zest.spi.module.ModuleSpi; +import org.json.JSONArray; +import org.json.JSONException; +import org.json.JSONObject; +import org.json.JSONTokener; +import org.json.JSONWriter; import org.slf4j.Logger; import org.slf4j.LoggerFactory; -import static org.apache.zest.functional.Iterables.first; -import static org.apache.zest.functional.Iterables.map; - /** * SQL EntityStore core Mixin. */ @@ -275,25 +270,19 @@ public class SQLEntityStoreMixin output.receiveFrom( new Sender<EntityState, EntityStoreException>() { @Override - public <ReceiverThrowableType extends Throwable> void sendTo( final Receiver<? super EntityState, ReceiverThrowableType> receiver ) - throws ReceiverThrowableType, EntityStoreException + public <RecThrowableType extends Throwable> void sendTo( final Receiver<? super EntityState, RecThrowableType> receiver ) + throws RecThrowableType, EntityStoreException { - queryAllEntities( module, new EntityStatesVisitor() - { - @Override - public boolean visit( EntityState visited ) - throws SQLException + queryAllEntities( module, visited -> { + try + { + receiver.receive( visited ); + } + catch( Throwable receiverThrowableType ) { - try - { - receiver.receive( visited ); - } - catch( Throwable receiverThrowableType ) - { - throw new SQLException( receiverThrowableType ); - } - return true; + throw new SQLException( receiverThrowableType ); } + return true; } ); } } ); @@ -308,6 +297,8 @@ public class SQLEntityStoreMixin ResultSet rs = null; UsecaseBuilder builder = UsecaseBuilder.buildUsecase( "zest.entitystore.sql.visit" ); Usecase usecase = builder.withMetaInfo( CacheOptions.NEVER ).newUsecase(); + + // TODO: This unit of work creation seem to not be cleaned up properly... CHECK!!! final ModuleEntityStoreUnitOfWork uow = (ModuleEntityStoreUnitOfWork) newUnitOfWork( usecase, module, System.currentTimeMillis() ); try @@ -353,7 +344,7 @@ public class SQLEntityStoreMixin try { JSONObject jsonObject = new JSONObject( new JSONTokener( entityState ) ); - EntityStatus status = EntityStatus.LOADED; + final EntityStatus[] status = {EntityStatus.LOADED}; String version = jsonObject.getString( JSONKeys.VERSION ); long modified = jsonObject.getLong( JSONKeys.MODIFIED ); @@ -377,7 +368,7 @@ public class SQLEntityStoreMixin identity, currentAppVersion, application.version() ); // State changed - status = EntityStatus.UPDATED; + status[0] = EntityStatus.UPDATED; } String type = jsonObject.getString( JSONKeys.TYPE ); @@ -387,43 +378,40 @@ public class SQLEntityStoreMixin { throw new EntityTypeNotFoundException( type, module.name(), - map( ModelModule.toStringFunction, - module.findVisibleEntityTypes() - ) ); + module.findVisibleEntityTypes() + .map( ModelModule.toStringFunction ) + ); } Map<QualifiedName, Object> properties = new HashMap<>(); JSONObject props = jsonObject.getJSONObject( JSONKeys.PROPERTIES ); - for( PropertyDescriptor propertyDescriptor : entityDescriptor.state().properties() ) - { + entityDescriptor.state().properties().forEach( propertyDescriptor -> { Object jsonValue; try { jsonValue = props.get( propertyDescriptor.qualifiedName().name() ); + if( JSONObject.NULL.equals( jsonValue ) ) + { + properties.put( propertyDescriptor.qualifiedName(), null ); + } + else + { + Object value = valueSerialization.deserialize( propertyDescriptor.valueType(), jsonValue.toString() ); + properties.put( propertyDescriptor.qualifiedName(), value ); + } } catch( JSONException e ) { // Value not found, default it Object initialValue = propertyDescriptor.initialValue( module ); properties.put( propertyDescriptor.qualifiedName(), initialValue ); - status = EntityStatus.UPDATED; - continue; + status[0] = EntityStatus.UPDATED; } - if( JSONObject.NULL.equals( jsonValue ) ) - { - properties.put( propertyDescriptor.qualifiedName(), null ); - } - else - { - Object value = valueSerialization.deserialize( propertyDescriptor.valueType(), jsonValue.toString() ); - properties.put( propertyDescriptor.qualifiedName(), value ); - } - } + } ); Map<QualifiedName, EntityReference> associations = new HashMap<>(); JSONObject assocs = jsonObject.getJSONObject( JSONKeys.ASSOCIATIONS ); - for( AssociationDescriptor associationType : entityDescriptor.state().associations() ) - { + entityDescriptor.state().associations().forEach( associationType -> { try { Object jsonValue = assocs.get( associationType.qualifiedName().name() ); @@ -435,14 +423,13 @@ public class SQLEntityStoreMixin { // Association not found, default it to null associations.put( associationType.qualifiedName(), null ); - status = EntityStatus.UPDATED; + status[0] = EntityStatus.UPDATED; } - } + } ); JSONObject manyAssocs = jsonObject.getJSONObject( JSONKeys.MANY_ASSOCIATIONS ); Map<QualifiedName, List<EntityReference>> manyAssociations = new HashMap<>(); - for( AssociationDescriptor manyAssociationType : entityDescriptor.state().manyAssociations() ) - { + entityDescriptor.state().manyAssociations().forEach( manyAssociationType -> { List<EntityReference> references = new ArrayList<>(); try { @@ -461,14 +448,13 @@ public class SQLEntityStoreMixin // ManyAssociation not found, default to empty one manyAssociations.put( manyAssociationType.qualifiedName(), references ); } - } + } ); JSONObject namedAssocs = jsonObject.has( JSONKeys.NAMED_ASSOCIATIONS ) ? jsonObject.getJSONObject( JSONKeys.NAMED_ASSOCIATIONS ) : new JSONObject(); Map<QualifiedName, Map<String, EntityReference>> namedAssociations = new HashMap<>(); - for( AssociationDescriptor namedAssociationType : entityDescriptor.state().namedAssociations() ) - { + entityDescriptor.state().namedAssociations().forEach( namedAssociationType -> { Map<String, EntityReference> references = new LinkedHashMap<>(); try { @@ -490,10 +476,10 @@ public class SQLEntityStoreMixin // NamedAssociation not found, default to empty one namedAssociations.put( namedAssociationType.qualifiedName(), references ); } - } + }); return new DefaultEntityState( version, modified, - EntityReference.parseEntityReference( identity ), status, entityDescriptor, + EntityReference.parseEntityReference( identity ), status[0], entityDescriptor, properties, associations, manyAssociations, namedAssociations ); } catch( JSONException e ) @@ -556,40 +542,45 @@ public class SQLEntityStoreMixin JSONWriter properties = json.object(). key( JSONKeys.IDENTITY ).value( state.identity().identity() ). key( JSONKeys.APPLICATION_VERSION ).value( application.version() ). - key( JSONKeys.TYPE ).value( first( state.entityDescriptor().types() ).getName() ). + key( JSONKeys.TYPE ).value( state.entityDescriptor().types().findFirst().get().getName() ). key( JSONKeys.VERSION ).value( version ). key( JSONKeys.MODIFIED ).value( state.lastModified() ). key( JSONKeys.PROPERTIES ).object(); - for( PropertyDescriptor persistentProperty : state.entityDescriptor().state().properties() ) - { - Object value = state.properties().get( persistentProperty.qualifiedName() ); - json.key( persistentProperty.qualifiedName().name() ); - if( value == null || ValueType.isPrimitiveValue( value ) ) - { - json.value( value ); - } - else + state.entityDescriptor().state().properties().forEach( persistentProperty -> { + try { - String serialized = valueSerialization.serialize( value ); - if( serialized.startsWith( "{" ) ) - { - json.value( new JSONObject( serialized ) ); - } - else if( serialized.startsWith( "[" ) ) + Object value = state.properties().get( persistentProperty.qualifiedName() ); + json.key( persistentProperty.qualifiedName().name() ); + if( value == null || ValueType.isPrimitiveValue( value ) ) { - json.value( new JSONArray( serialized ) ); + json.value( value ); } else { - json.value( serialized ); + String serialized = valueSerialization.serialize( value ); + if( serialized.startsWith( "{" ) ) + { + json.value( new JSONObject( serialized ) ); + } + else if( serialized.startsWith( "[" ) ) + { + json.value( new JSONArray( serialized ) ); + } + else + { + json.value( serialized ); + } } } - } + catch( JSONException e ) + { + throw new EntityStoreException( "Could not store EntityState", e ); + } + } ); JSONWriter associations = properties.endObject().key( JSONKeys.ASSOCIATIONS ).object(); - for( Map.Entry<QualifiedName, EntityReference> stateNameEntityReferenceEntry : state.associations() - .entrySet() ) + for( Map.Entry<QualifiedName, EntityReference> stateNameEntityReferenceEntry : state.associations().entrySet() ) { EntityReference value = stateNameEntityReferenceEntry.getValue(); associations.key( stateNameEntityReferenceEntry.getKey().name() ). @@ -597,8 +588,7 @@ public class SQLEntityStoreMixin } JSONWriter manyAssociations = associations.endObject().key( JSONKeys.MANY_ASSOCIATIONS ).object(); - for( Map.Entry<QualifiedName, List<EntityReference>> stateNameListEntry : state.manyAssociations() - .entrySet() ) + for( Map.Entry<QualifiedName, List<EntityReference>> stateNameListEntry : state.manyAssociations().entrySet() ) { JSONWriter assocs = manyAssociations.key( stateNameListEntry.getKey().name() ).array(); for( EntityReference entityReference : stateNameListEntry.getValue() ) http://git-wip-us.apache.org/repos/asf/zest-java/blob/bd6fbad9/extensions/indexing-elasticsearch/src/main/java/org/apache/zest/index/elasticsearch/ElasticSearchIndexer.java ---------------------------------------------------------------------- diff --git a/extensions/indexing-elasticsearch/src/main/java/org/apache/zest/index/elasticsearch/ElasticSearchIndexer.java b/extensions/indexing-elasticsearch/src/main/java/org/apache/zest/index/elasticsearch/ElasticSearchIndexer.java index 94941c8..6929351 100644 --- a/extensions/indexing-elasticsearch/src/main/java/org/apache/zest/index/elasticsearch/ElasticSearchIndexer.java +++ b/extensions/indexing-elasticsearch/src/main/java/org/apache/zest/index/elasticsearch/ElasticSearchIndexer.java @@ -20,27 +20,19 @@ package org.apache.zest.index.elasticsearch; import java.util.Collections; import java.util.HashMap; import java.util.Map; -import org.elasticsearch.action.bulk.BulkRequestBuilder; -import org.elasticsearch.action.bulk.BulkResponse; -import org.json.JSONArray; -import org.json.JSONException; -import org.json.JSONObject; -import org.apache.zest.api.association.AssociationDescriptor; +import java.util.stream.Collectors; import org.apache.zest.api.entity.EntityDescriptor; import org.apache.zest.api.entity.EntityReference; import org.apache.zest.api.injection.scope.Service; import org.apache.zest.api.injection.scope.Structure; import org.apache.zest.api.injection.scope.This; import org.apache.zest.api.mixin.Mixins; -import org.apache.zest.api.property.PropertyDescriptor; import org.apache.zest.api.service.qualifier.Tagged; import org.apache.zest.api.type.ValueType; import org.apache.zest.api.usecase.UsecaseBuilder; -import org.apache.zest.api.util.Classes; import org.apache.zest.api.value.ValueSerialization; import org.apache.zest.api.value.ValueSerializer; import org.apache.zest.api.value.ValueSerializer.Options; -import org.apache.zest.functional.Iterables; import org.apache.zest.spi.entity.EntityState; import org.apache.zest.spi.entity.EntityStatus; import org.apache.zest.spi.entity.ManyAssociationState; @@ -49,6 +41,11 @@ import org.apache.zest.spi.entitystore.EntityStore; import org.apache.zest.spi.entitystore.EntityStoreUnitOfWork; import org.apache.zest.spi.entitystore.StateChangeListener; import org.apache.zest.spi.module.ModuleSpi; +import org.elasticsearch.action.bulk.BulkRequestBuilder; +import org.elasticsearch.action.bulk.BulkResponse; +import org.json.JSONArray; +import org.json.JSONException; +import org.json.JSONObject; import org.slf4j.Logger; import org.slf4j.LoggerFactory; @@ -188,18 +185,23 @@ public interface ElasticSearchIndexer */ private String toJSON( EntityState state, Map<String, EntityState> newStates, EntityStoreUnitOfWork uow ) { + JSONObject json = new JSONObject(); + try { - JSONObject json = new JSONObject(); - json.put( "_identity", state.identity().identity() ); - json.put( "_types", Iterables.toList( Iterables.map( Classes.toClassName(), state.entityDescriptor() - .mixinTypes() ) ) ); + json.put( "_types", state.entityDescriptor().mixinTypes().collect( Collectors.toList() ) ); + } + catch( JSONException e ) + { + throw new ElasticSearchIndexException( "Could not index EntityState", e ); + } - EntityDescriptor entityType = state.entityDescriptor(); + EntityDescriptor entityType = state.entityDescriptor(); - // Properties - for( PropertyDescriptor propDesc : entityType.state().properties() ) + // Properties + entityType.state().properties().forEach( propDesc -> { + try { if( propDesc.queryable() ) { @@ -228,9 +230,15 @@ public interface ElasticSearchIndexer } } } + catch( JSONException e ) + { + throw new ElasticSearchIndexException( "Could not index EntityState", e ); + } + } ); - // Associations - for( AssociationDescriptor assocDesc : entityType.state().associations() ) + // Associations + entityType.state().associations().forEach( assocDesc -> { + try { if( assocDesc.queryable() ) { @@ -264,9 +272,15 @@ public interface ElasticSearchIndexer json.put( key, value ); } } + catch( JSONException e ) + { + throw new ElasticSearchIndexException( "Could not index EntityState", e ); + } + } ); - // ManyAssociations - for( AssociationDescriptor manyAssocDesc : entityType.state().manyAssociations() ) + // ManyAssociations + entityType.state().manyAssociations().forEach( manyAssocDesc -> { + try { if( manyAssocDesc.queryable() ) { @@ -296,9 +310,15 @@ public interface ElasticSearchIndexer json.put( key, array ); } } + catch( JSONException e ) + { + throw new ElasticSearchIndexException( "Could not index EntityState", e ); + } + } ); - // NamedAssociations - for( AssociationDescriptor namedAssocDesc : entityType.state().namedAssociations() ) + // NamedAssociations + entityType.state().namedAssociations().forEach( namedAssocDesc -> { + try { if( namedAssocDesc.queryable() ) { @@ -336,13 +356,12 @@ public interface ElasticSearchIndexer json.put( key, array ); } } - - return json.toString(); - } - catch( JSONException e ) - { - throw new ElasticSearchIndexException( "Could not index EntityState", e ); - } + catch( JSONException e ) + { + throw new ElasticSearchIndexException( "Could not index EntityState", e ); + } + } ); + return json.toString(); } } } http://git-wip-us.apache.org/repos/asf/zest-java/blob/bd6fbad9/extensions/indexing-rdf/src/main/java/org/apache/zest/index/rdf/indexing/RdfIndexingService.java ---------------------------------------------------------------------- diff --git a/extensions/indexing-rdf/src/main/java/org/apache/zest/index/rdf/indexing/RdfIndexingService.java b/extensions/indexing-rdf/src/main/java/org/apache/zest/index/rdf/indexing/RdfIndexingService.java index 3c7e34b..bf0c9ac 100644 --- a/extensions/indexing-rdf/src/main/java/org/apache/zest/index/rdf/indexing/RdfIndexingService.java +++ b/extensions/indexing-rdf/src/main/java/org/apache/zest/index/rdf/indexing/RdfIndexingService.java @@ -18,16 +18,10 @@ package org.apache.zest.index.rdf.indexing; -import java.io.File; import java.util.ArrayList; import java.util.HashSet; import java.util.List; import java.util.Set; -import org.openrdf.model.*; -import org.openrdf.model.impl.GraphImpl; -import org.openrdf.repository.Repository; -import org.openrdf.repository.RepositoryConnection; -import org.openrdf.repository.RepositoryException; import org.apache.zest.api.activation.ActivatorAdapter; import org.apache.zest.api.activation.Activators; import org.apache.zest.api.entity.EntityDescriptor; @@ -41,8 +35,15 @@ import org.apache.zest.library.rdf.entity.EntityTypeSerializer; import org.apache.zest.spi.entity.EntityState; import org.apache.zest.spi.entity.EntityStatus; import org.apache.zest.spi.entitystore.StateChangeListener; - -import static org.apache.zest.functional.Iterables.first; +import org.openrdf.model.Graph; +import org.openrdf.model.Resource; +import org.openrdf.model.Statement; +import org.openrdf.model.URI; +import org.openrdf.model.ValueFactory; +import org.openrdf.model.impl.GraphImpl; +import org.openrdf.repository.Repository; +import org.openrdf.repository.RepositoryConnection; +import org.openrdf.repository.RepositoryException; @Mixins( RdfIndexingService.RdfEntityIndexerMixin.class ) @Activators( RdfIndexingService.Activator.class ) @@ -51,18 +52,17 @@ public interface RdfIndexingService { void initialize(); - File dataDir(); +// File dataDir(); class Activator extends ActivatorAdapter<ServiceReference<RdfIndexingService>> { @Override public void afterActivation( ServiceReference<RdfIndexingService> activated ) - throws Exception + throws Exception { activated.get().initialize(); } - } /** @@ -140,11 +140,13 @@ public interface RdfIndexingService } } - private Set<EntityDescriptor> indexUpdates( Iterable<EntityState> entityStates, RepositoryConnection connection ) + private Set<EntityDescriptor> indexUpdates( Iterable<EntityState> entityStates, + RepositoryConnection connection + ) throws RepositoryException { // Figure out what to update - final Set<EntityDescriptor> entityTypes = new HashSet<EntityDescriptor>(); + final Set<EntityDescriptor> entityTypes = new HashSet<>(); for( EntityState entityState : entityStates ) { if( entityState.status().equals( EntityStatus.UPDATED ) ) @@ -164,7 +166,7 @@ public interface RdfIndexingService private void removeEntityStates( Iterable<EntityState> entityStates, RepositoryConnection connection ) throws RepositoryException { - List<URI> removedStates = new ArrayList<URI>(); + List<URI> removedStates = new ArrayList<>(); for( EntityState entityState : entityStates ) { if( entityState.status().equals( EntityStatus.REMOVED ) ) @@ -205,7 +207,8 @@ public interface RdfIndexingService { if( entityType.queryable() ) { - final URI compositeURI = getValueFactory().createURI( Classes.toURI(first( entityType.types() )) ); + final URI compositeURI = getValueFactory().createURI( + Classes.toURI( entityType.types().findFirst().orElse( null ) ) ); // remove composite type if already present connection.clear( compositeURI ); @@ -223,10 +226,10 @@ public interface RdfIndexingService return valueFactory; } - @Override - public File dataDir() - { - return repository.get().getDataDir(); - } +// @Override +// public File dataDir() +// { +// return repository.get().getDataDir(); +// } } } http://git-wip-us.apache.org/repos/asf/zest-java/blob/bd6fbad9/extensions/indexing-solr/src/main/java/org/apache/zest/index/solr/internal/SolrEntityIndexerMixin.java ---------------------------------------------------------------------- diff --git a/extensions/indexing-solr/src/main/java/org/apache/zest/index/solr/internal/SolrEntityIndexerMixin.java b/extensions/indexing-solr/src/main/java/org/apache/zest/index/solr/internal/SolrEntityIndexerMixin.java index 1445a69..3243ec9 100644 --- a/extensions/indexing-solr/src/main/java/org/apache/zest/index/solr/internal/SolrEntityIndexerMixin.java +++ b/extensions/indexing-solr/src/main/java/org/apache/zest/index/solr/internal/SolrEntityIndexerMixin.java @@ -34,10 +34,8 @@ import org.openrdf.model.Literal; import org.openrdf.model.Resource; import org.openrdf.model.Statement; import org.openrdf.model.URI; -import org.openrdf.model.ValueFactory; import org.openrdf.model.impl.GraphImpl; import org.openrdf.model.impl.URIImpl; -import org.openrdf.model.impl.ValueFactoryImpl; import org.apache.zest.api.injection.scope.Service; import org.apache.zest.api.injection.scope.Uses; import org.apache.zest.index.solr.EmbeddedSolrService; @@ -48,8 +46,6 @@ import org.apache.zest.spi.entity.EntityStatus; import org.slf4j.Logger; import org.slf4j.LoggerFactory; -import static org.apache.zest.functional.Iterables.first; - /** * JAVADOC */ @@ -62,7 +58,7 @@ public abstract class SolrEntityIndexerMixin @Uses private EntityStateSerializer stateSerializer; - private ValueFactory valueFactory = new ValueFactoryImpl(); +// private ValueFactory valueFactory = new ValueFactoryImpl(); private SolrServer server; private Map<String, SchemaField> indexedFields; @@ -99,7 +95,7 @@ public abstract class SolrEntityIndexerMixin { // Figure out what to update List<String> deleted = null; - List<SolrInputDocument> added = new ArrayList<SolrInputDocument>(); + List<SolrInputDocument> added = new ArrayList<>(); for( EntityState entityState : entityStates ) { if( entityState.entityDescriptor().queryable() ) @@ -107,14 +103,14 @@ public abstract class SolrEntityIndexerMixin if( entityState.status().equals( EntityStatus.REMOVED ) ) { if( deleted == null ) - deleted = new ArrayList<String>(); + deleted = new ArrayList<>(); deleted.add( entityState.identity().identity() ); } else if( entityState.status().equals( EntityStatus.UPDATED ) ) { - added.add( indexEntityState( entityState, server ) ); + added.add( indexEntityState( entityState ) ); } else if( entityState.status().equals( EntityStatus.NEW ) ) { - added.add( indexEntityState( entityState, server ) ); + added.add( indexEntityState( entityState ) ); } } } @@ -138,8 +134,7 @@ public abstract class SolrEntityIndexerMixin } } - private SolrInputDocument indexEntityState( final EntityState entityState, - final SolrServer server ) + private SolrInputDocument indexEntityState( final EntityState entityState ) throws IOException, SolrServerException, JSONException { Graph graph = new GraphImpl(); @@ -147,7 +142,7 @@ public abstract class SolrEntityIndexerMixin SolrInputDocument input = new SolrInputDocument(); input.addField( "id", entityState.identity().identity() ); - input.addField( "type", first(entityState.entityDescriptor().types()).getName() ); + input.addField( "type", entityState.entityDescriptor().types().findFirst().get().getName() ); input.addField( "lastModified", new Date( entityState.lastModified() ) ); for( Statement statement : graph ) http://git-wip-us.apache.org/repos/asf/zest-java/blob/bd6fbad9/extensions/indexing-sql/src/main/java/org/apache/zest/index/sql/support/skeletons/AbstractSQLIndexing.java ---------------------------------------------------------------------- diff --git a/extensions/indexing-sql/src/main/java/org/apache/zest/index/sql/support/skeletons/AbstractSQLIndexing.java b/extensions/indexing-sql/src/main/java/org/apache/zest/index/sql/support/skeletons/AbstractSQLIndexing.java index 7f8e5a1..f39f4af 100644 --- a/extensions/indexing-sql/src/main/java/org/apache/zest/index/sql/support/skeletons/AbstractSQLIndexing.java +++ b/extensions/indexing-sql/src/main/java/org/apache/zest/index/sql/support/skeletons/AbstractSQLIndexing.java @@ -34,7 +34,6 @@ import java.util.Set; import java.util.function.Predicate; import javax.sql.DataSource; import org.apache.zest.api.ZestAPI; -import org.apache.zest.api.association.AssociationDescriptor; import org.apache.zest.api.common.QualifiedName; import org.apache.zest.api.entity.EntityReference; import org.apache.zest.api.entity.Identity; @@ -42,7 +41,6 @@ import org.apache.zest.api.injection.scope.Service; import org.apache.zest.api.injection.scope.Structure; import org.apache.zest.api.injection.scope.This; import org.apache.zest.api.injection.scope.Uses; -import org.apache.zest.api.property.PropertyDescriptor; import org.apache.zest.api.property.StateHolder; import org.apache.zest.api.service.ServiceDescriptor; import org.apache.zest.api.structure.Application; @@ -55,11 +53,11 @@ import org.apache.zest.index.sql.support.common.QNameInfo; import org.apache.zest.index.sql.support.common.QNameInfo.QNameType; import org.apache.zest.index.sql.support.postgresql.PostgreSQLTypeHelper; import org.apache.zest.index.sql.support.skeletons.SQLSkeletonUtil.Lazy; -import org.apache.zest.index.sql.support.skeletons.SQLSkeletonUtil.LazyInit; import org.apache.zest.library.sql.common.SQLUtil; import org.apache.zest.spi.ZestSPI; import org.apache.zest.spi.entity.EntityState; import org.apache.zest.spi.entity.EntityStatus; +import org.apache.zest.spi.entitystore.EntityStoreException; import org.sql.generation.api.grammar.builders.modification.ColumnSourceByValuesBuilder; import org.sql.generation.api.grammar.builders.modification.DeleteBySearchBuilder; import org.sql.generation.api.grammar.builders.modification.UpdateBySearchBuilder; @@ -140,40 +138,16 @@ public abstract class AbstractSQLIndexing PreparedStatement insertToPropertyQNamesPS = null; PreparedStatement clearEntityDataPS = null; Lazy<PreparedStatement, SQLException> queryEntityPKPS = new Lazy<>( - new LazyInit<PreparedStatement, SQLException>() - { - @Override - public PreparedStatement create() - throws SQLException - { - return connection.prepareStatement( - vendor.toString( createQueryEntityPkByIdentityStatement( schemaName, vendor ) ) ); - } - } ); + () -> connection.prepareStatement( + vendor.toString( createQueryEntityPkByIdentityStatement( schemaName, vendor ) ) ) ); Lazy<PreparedStatement, SQLException> insertToEntityTableAutoGenerated = new Lazy<>( - new LazyInit<PreparedStatement, SQLException>() - { - @Override - public PreparedStatement create() - throws SQLException - { - return connection.prepareStatement( - createInsertStatementWithAutoGeneratedIDForEntitiesTable( schemaName, - ENTITY_TABLE_NAME, - vendor ).toString() ); - } - } ); + () -> connection.prepareStatement( + createInsertStatementWithAutoGeneratedIDForEntitiesTable( schemaName, + ENTITY_TABLE_NAME, + vendor ).toString() ) ); Lazy<PreparedStatement, SQLException> insertToEntityTypeTablePS = new Lazy<>( - new LazyInit<PreparedStatement, SQLException>() - { - @Override - public PreparedStatement create() - throws SQLException - { - return connection.prepareStatement( - createInsertEntityTypeStatement( schemaName, vendor ).toString() ); - } - } ); + () -> connection.prepareStatement( + createInsertEntityTypeStatement( schemaName, vendor ).toString() ) ); Map<QualifiedName, PreparedStatement> qNameInsertPSs = new HashMap<>(); try @@ -237,26 +211,25 @@ public abstract class AbstractSQLIndexing { this.removeEntity( eState, removeEntityPS ); } - else - { - // TODO possibly handle LOADED state somehow - // throw new - // UnsupportedOperationException("Did not understand what to do with state [id = " - // + - // eState.identity().identity() + ", status = " + status + "]."); - } +// else +// { +// // TODO possibly handle LOADED state somehow +// // throw new +// // UnsupportedOperationException("Did not understand what to do with state [id = " +// // + +// // eState.identity().identity() + ", status = " + status + "]."); +// } } if( needToInsert ) { - pk = this.getPKFromAutoGeneratedIDInsert( eState, - insertToEntityTableAutoGenerated.getValue(), - vendor, - connection ); - this.insertPropertyType( connection, insertToEntityTypeTablePS.getValue(), - eState, pk ); - this.insertProperties( connection, qNameInsertPSs, - insertToPropertyQNamesPS, eState, pk, qNamePKs ); + pk = this.getPKFromAutoGeneratedIDInsert( + eState, + insertToEntityTableAutoGenerated.getValue(), + vendor, + connection ); + insertPropertyType( insertToEntityTypeTablePS.getValue(), eState, pk ); + insertProperties( connection, qNameInsertPSs, insertToPropertyQNamesPS, eState, pk, qNamePKs ); } if( pk != null ) { @@ -311,10 +284,7 @@ public abstract class AbstractSQLIndexing SQLUtil.closeQuietly( removeEntityPS ); SQLUtil.closeQuietly( insertToPropertyQNamesPS ); SQLUtil.closeQuietly( clearEntityDataPS ); - for( PreparedStatement ps : qNameInsertPSs.values() ) - { - SQLUtil.closeQuietly( ps ); - } + qNameInsertPSs.values().forEach( SQLUtil::closeQuietly ); } finally { @@ -351,10 +321,12 @@ public abstract class AbstractSQLIndexing } protected abstract InsertStatement createInsertStatementWithAutoGeneratedIDForEntitiesTable( - String schemaName, String tableName, SQLVendor vendor ); + String schemaName, String tableName, SQLVendor vendor + ); protected void addEntityInfoToInsertToEntityTablePS( EntityState state, PreparedStatement ps, - int startingIndex ) + int startingIndex + ) throws SQLException { ps.setString( startingIndex, state.identity().identity() ); @@ -364,7 +336,8 @@ public abstract class AbstractSQLIndexing } protected Long findEntityPK( EntityState state, - Lazy<PreparedStatement, SQLException> queryPKPS ) + Lazy<PreparedStatement, SQLException> queryPKPS + ) throws SQLException { // TODO build cache: Zest Identity -> PK @@ -391,11 +364,12 @@ public abstract class AbstractSQLIndexing protected abstract long getPKFromAutoGeneratedIDInsert( EntityState state, PreparedStatement autoGeneratedIDStatement, SQLVendor vendor, - Connection connection ) + Connection connection + ) throws SQLException; protected UpdateStatement - createUpdateEntityTableStatement( String schemaName, SQLVendor vendor ) + createUpdateEntityTableStatement( String schemaName, SQLVendor vendor ) { ModificationFactory m = vendor.getModificationFactory(); BooleanFactory b = vendor.getBooleanFactory(); @@ -426,7 +400,8 @@ public abstract class AbstractSQLIndexing } protected QueryExpression createQueryEntityPkByIdentityStatement( String schemaName, - SQLVendor vendor ) + SQLVendor vendor + ) { BooleanFactory b = vendor.getBooleanFactory(); LiteralFactory l = vendor.getLiteralFactory(); @@ -449,14 +424,15 @@ public abstract class AbstractSQLIndexing } protected DeleteStatement createDeleteFromEntityTableStatement( String schemaName, - SQLVendor vendor ) + SQLVendor vendor + ) { return this.createDeleteFromTableStatement( schemaName, DBNames.ENTITY_TABLE_NAME, DBNames.ENTITY_TABLE_IDENTITY_COLUMN_NAME, vendor ); } protected DeleteStatement - createClearEntityDataStatement( String schemaName, SQLVendor vendor ) + createClearEntityDataStatement( String schemaName, SQLVendor vendor ) { return this.createDeleteFromTableStatement( schemaName, DBNames.ALL_QNAMES_TABLE_NAME, DBNames.ENTITY_TABLE_PK_COLUMN_NAME, vendor ); @@ -504,7 +480,8 @@ public abstract class AbstractSQLIndexing } protected InsertStatement createAssoInsert( QNameInfo qNameInfo, SQLVendor vendor, - Integer amountOfParams ) + Integer amountOfParams + ) { ModificationFactory m = vendor.getModificationFactory(); LiteralFactory l = vendor.getLiteralFactory(); @@ -548,7 +525,7 @@ public abstract class AbstractSQLIndexing ) throws SQLException { - Set<QualifiedName> copy = new HashSet<QualifiedName>( qNames ); + Set<QualifiedName> copy = new HashSet<>( qNames ); copy.removeAll( qNameInsertPSs.keySet() ); for( QualifiedName qName : copy ) { @@ -589,7 +566,7 @@ public abstract class AbstractSQLIndexing } private PreparedStatement - createInsertAssociationPS( Connection connection, QNameInfo qNameInfo ) + createInsertAssociationPS( Connection connection, QNameInfo qNameInfo ) throws SQLException { SQLVendor vendor = this.descriptor.metaInfo( SQLVendor.class ); @@ -599,7 +576,8 @@ public abstract class AbstractSQLIndexing } private PreparedStatement createInsertManyAssociationPS( Connection connection, - QNameInfo qNameInfo ) + QNameInfo qNameInfo + ) throws SQLException { SQLVendor vendor = this.descriptor.metaInfo( SQLVendor.class ); @@ -623,83 +601,98 @@ public abstract class AbstractSQLIndexing { Set<QualifiedName> qNames = this._state.entityUsedQNames().get().get( state.entityDescriptor() ); this.syncQNamesInsertPSs( connection, qNameInsertPSs, qNames ); - Integer propertyPK = 0; - for( PropertyDescriptor pDesc : state.entityDescriptor().state().properties() ) - { - if( SQLSkeletonUtil.isQueryable( pDesc.accessor() ) ) - { - propertyPK = this.insertProperty( - qNameInsertPSs, - insertAllQNamesPS, - propertyPK, - entityPK, - pDesc.qualifiedName(), - state.propertyValueOf( pDesc.qualifiedName() ), - null // - ); - } - } - - return propertyPK; + final Integer propertyPK[] = {0}; + state.entityDescriptor().state().properties() + .filter( pDesc -> SQLSkeletonUtil.isQueryable( pDesc.accessor() ) ) + .forEach( pDesc -> { + try + { + propertyPK[0] = this.insertProperty( + qNameInsertPSs, + insertAllQNamesPS, + propertyPK[0], + entityPK, + pDesc.qualifiedName(), + state.propertyValueOf( pDesc.qualifiedName() ), + null // + ); + } + catch( SQLException e ) + { + throw new EntityStoreException( "Underlying exception when inserting property " + pDesc ); + } + } ); + return propertyPK[0]; } private void insertAssoAndManyAssoQNames( Map<QualifiedName, PreparedStatement> qNameInsertPSs, PreparedStatement insertToAllQNamesPS, EntityState state, - Integer qNamePK, + final Integer localPK, Long entityPK ) throws SQLException { - for( AssociationDescriptor aDesc : state.entityDescriptor().state().associations() ) - { - if( SQLSkeletonUtil.isQueryable( aDesc.accessor() ) ) - { - QualifiedName qName = aDesc.qualifiedName(); - PreparedStatement ps = qNameInsertPSs.get( qName ); - EntityReference ref = state.associationValueOf( qName ); - if( ref != null ) - { - insertToAllQNamesPS.setInt( 1, qNamePK ); - insertToAllQNamesPS.setLong( 2, entityPK ); - insertToAllQNamesPS.addBatch(); - - ps.setInt( 1, qNamePK ); - ps.setLong( 2, entityPK ); - ps.setString( 3, ref.identity() ); - ps.addBatch(); - - ++qNamePK; - } - } - } - - for( AssociationDescriptor mDesc : state.entityDescriptor().state().manyAssociations() ) - { - if( SQLSkeletonUtil.isQueryable( mDesc.accessor() ) ) - { - QualifiedName qName = mDesc.qualifiedName(); - PreparedStatement ps = qNameInsertPSs.get( qName ); - Integer index = 0; - for( EntityReference ref : state.manyAssociationValueOf( qName ) ) + final Integer[] qNamePK = {localPK}; + state.entityDescriptor().state().associations() + .filter( aDesc -> SQLSkeletonUtil.isQueryable( aDesc.accessor() ) ) + .forEach( aDesc -> { + try { + QualifiedName qName = aDesc.qualifiedName(); + PreparedStatement ps = qNameInsertPSs.get( qName ); + EntityReference ref = state.associationValueOf( qName ); if( ref != null ) { - insertToAllQNamesPS.setInt( 1, qNamePK ); + insertToAllQNamesPS.setInt( 1, qNamePK[0] ); insertToAllQNamesPS.setLong( 2, entityPK ); insertToAllQNamesPS.addBatch(); - ps.setInt( 1, qNamePK ); + ps.setInt( 1, qNamePK[0] ); ps.setLong( 2, entityPK ); - ps.setInt( 3, index ); - ps.setString( 4, ref.identity() ); + ps.setString( 3, ref.identity() ); ps.addBatch(); - ++qNamePK; + + qNamePK[0] += 1; } - ++index; } - } - } + catch( SQLException e ) + { + throw new EntityStoreException( "Underlying exception when inserting association " + aDesc ); + } + } ); + + state.entityDescriptor().state().manyAssociations() + .filter( mDesc -> SQLSkeletonUtil.isQueryable( mDesc.accessor() ) ) + .forEach( mDesc -> { + try + { + QualifiedName qName = mDesc.qualifiedName(); + PreparedStatement ps = qNameInsertPSs.get( qName ); + Integer index = 0; + for( EntityReference ref : state.manyAssociationValueOf( qName ) ) + { + if( ref != null ) + { + insertToAllQNamesPS.setInt( 1, qNamePK[0] ); + insertToAllQNamesPS.setLong( 2, entityPK ); + insertToAllQNamesPS.addBatch(); + + ps.setInt( 1, qNamePK[0] ); + ps.setLong( 2, entityPK ); + ps.setInt( 3, index ); + ps.setString( 4, ref.identity() ); + ps.addBatch(); + qNamePK[0] += 1; + } + ++index; + } + } + catch( SQLException e ) + { + throw new EntityStoreException( "Underlying exception when inserting manyassociation " + mDesc ); + } + } ); } private Integer insertProperty( @@ -759,7 +752,7 @@ public abstract class AbstractSQLIndexing info ); propertyPK = this.storeCollectionItems( qNameInsertPSs, property, insertAllQNamesPS, - DBNames.QNAME_TABLE_COLLECTION_PATH_TOP_LEVEL_NAME, ps, info.getTableName(), + DBNames.QNAME_TABLE_COLLECTION_PATH_TOP_LEVEL_NAME, ps, propertyPK, entityPK, parentQNameID, info.getFinalType(), info.isFinalTypePrimitive() ); return propertyPK; @@ -778,6 +771,8 @@ public abstract class AbstractSQLIndexing ps.setInt( 1, propertyPK ); ps.setLong( 2, entityPK ); ps.setObject( 3, parentQNameID, Types.BIGINT ); + + //noinspection SuspiciousNameCombination ps.setString( 4, DBNames.QNAME_TABLE_COLLECTION_PATH_TOP_LEVEL_NAME ); if( info.isFinalTypePrimitive() ) { @@ -797,7 +792,6 @@ public abstract class AbstractSQLIndexing PreparedStatement insertAllQNamesPS, String path, PreparedStatement ps, - String tableName, Integer propertyPK, Long entityPK, Integer parentPK, @@ -812,16 +806,18 @@ public abstract class AbstractSQLIndexing String itemPath = path + DBNames.QNAME_TABLE_COLLECTION_PATH_SEPARATOR + index; if( o instanceof Collection<?> ) { - propertyPK = this.storeCollectionItems( qNameInsertPSs, (Collection<?>) o, - insertAllQNamesPS, itemPath, - ps, tableName, propertyPK, entityPK, parentPK, finalType, - isFinalTypePrimitive ); + propertyPK = this.storeCollectionItems( + qNameInsertPSs, (Collection<?>) o, + insertAllQNamesPS, itemPath, + ps, propertyPK, entityPK, parentPK, finalType, + isFinalTypePrimitive ); } else { - propertyPK = this.storeCollectionItem( qNameInsertPSs, ps, insertAllQNamesPS, propertyPK, - entityPK, - parentPK, itemPath, o, isFinalTypePrimitive, finalType ); + propertyPK = this.storeCollectionItem( + qNameInsertPSs, ps, insertAllQNamesPS, propertyPK, + entityPK, + parentPK, itemPath, o, isFinalTypePrimitive, finalType ); ps.addBatch(); } ++index; @@ -920,31 +916,36 @@ public abstract class AbstractSQLIndexing private Integer storePropertiesOfVC( Map<QualifiedName, PreparedStatement> qNameInsertPSs, PreparedStatement insertAllQNamesPS, - Integer propertyPK, + Integer localPK, Long entityPK, Object property ) throws SQLException { - ValueDescriptor vDesc = this._qi4SPI.valueDescriptorFor( (ValueComposite) property ); + ValueDescriptor vDesc = this._qi4SPI.valueDescriptorFor( property ); StateHolder state = ZestAPI.FUNCTION_COMPOSITE_INSTANCE_OF.apply( (ValueComposite) property ).state(); - Integer originalPropertyPK = propertyPK; - ++propertyPK; - for( PropertyDescriptor pDesc : vDesc.state().properties() ) - { + Integer propertyPK[] = { localPK + 1 }; + vDesc.state().properties().forEach( pDesc -> { - propertyPK = this.insertProperty( - qNameInsertPSs, - insertAllQNamesPS, - propertyPK, - entityPK, - pDesc.qualifiedName(), - state.propertyFor( pDesc.accessor() ).get(), - originalPropertyPK - ); - } + try + { + propertyPK[0] = this.insertProperty( + qNameInsertPSs, + insertAllQNamesPS, + propertyPK[0], + entityPK, + pDesc.qualifiedName(), + state.propertyFor( pDesc.accessor() ).get(), + localPK + ); + } + catch( SQLException e ) + { + throw new EntityStoreException( "Underlying exception when inserting property " + pDesc + " in value " + vDesc, e ); + } + } ); - return propertyPK; + return propertyPK[0]; } private void storePrimitiveUsingPS( PreparedStatement ps, Integer nextFreeIndex, @@ -964,7 +965,7 @@ public abstract class AbstractSQLIndexing ps.setInt( nextFreeIndex, this._state.enumPKs().get().get( - QualifiedName.fromClass( (Class<?>) primitiveType, primitive.toString() ).toString() ) + QualifiedName.fromClass( (Class<?>) primitiveType, primitive.toString() ).toString() ) ); } else @@ -1037,22 +1038,27 @@ public abstract class AbstractSQLIndexing ps.addBatch(); } - private void insertPropertyType( Connection connection, PreparedStatement insertPropertyTypePS, - EntityState state, Long entityPK ) + private void insertPropertyType( PreparedStatement insertPropertyTypePS, EntityState state, Long entityPK ) throws SQLException { - for( Class<?> clazz : state.entityDescriptor().types() ) - { + state.entityDescriptor().types().forEach( clazz -> { Integer typePK = this._state.entityTypePKs().get().get( clazz.getName() ); if( typePK == null ) { throw new InternalError( "Tried to get entity : " + clazz - + ", but only aware of the following entities: " + this._state - .entityTypePKs().get().keySet() ); + + ", but only aware of the following entities: " + + this._state.entityTypePKs().get().keySet() ); } - insertPropertyTypePS.setLong( 1, entityPK ); - insertPropertyTypePS.setInt( 2, typePK ); - insertPropertyTypePS.addBatch(); - } + try + { + insertPropertyTypePS.setLong( 1, entityPK ); + insertPropertyTypePS.setInt( 2, typePK ); + insertPropertyTypePS.addBatch(); + } + catch( SQLException e ) + { + throw new EntityStoreException( "Underlying Exception when inserting " + entityPK, e ); + } + } ); } }
