You are viewing a plain text version of this content. The canonical link for it is here.
Posted to commits@usergrid.apache.org by mr...@apache.org on 2016/06/23 22:26:06 UTC
[01/11] usergrid git commit: Add new tool for scanning unique values.
Include option to skip read repair in the methods that load entities from the
unique index.
Repository: usergrid
Updated Branches:
refs/heads/release-2.1.1 9efa3b4c6 -> 574949259
Add new tool for scanning unique values. Include option to skip read repair in the methods that load entities from the unique index.
Project: http://git-wip-us.apache.org/repos/asf/usergrid/repo
Commit: http://git-wip-us.apache.org/repos/asf/usergrid/commit/06f77d7b
Tree: http://git-wip-us.apache.org/repos/asf/usergrid/tree/06f77d7b
Diff: http://git-wip-us.apache.org/repos/asf/usergrid/diff/06f77d7b
Branch: refs/heads/release-2.1.1
Commit: 06f77d7b385efdcb3655035e895d89f99710a70a
Parents: 9efa3b4
Author: Michael Russo <mr...@apigee.com>
Authored: Tue Jun 21 14:29:50 2016 -0700
Committer: Michael Russo <mr...@apigee.com>
Committed: Tue Jun 21 14:29:50 2016 -0700
----------------------------------------------------------------------
.../corepersistence/CpEntityManager.java | 9 +-
.../usergrid/persistence/EntityManager.java | 2 +-
.../collection/EntityCollectionManager.java | 3 +-
.../impl/EntityCollectionManagerImpl.java | 7 +-
.../UniqueValueSerializationStrategyImpl.java | 15 +-
.../collection/EntityCollectionManagerIT.java | 63 +++--
.../services/AbstractCollectionService.java | 8 +-
.../services/AbstractConnectionsService.java | 6 +-
.../usergrid/tools/UniqueValueScanner.java | 245 +++++++++++++++++++
9 files changed, 314 insertions(+), 44 deletions(-)
----------------------------------------------------------------------
http://git-wip-us.apache.org/repos/asf/usergrid/blob/06f77d7b/stack/core/src/main/java/org/apache/usergrid/corepersistence/CpEntityManager.java
----------------------------------------------------------------------
diff --git a/stack/core/src/main/java/org/apache/usergrid/corepersistence/CpEntityManager.java b/stack/core/src/main/java/org/apache/usergrid/corepersistence/CpEntityManager.java
index 82c4c87..ab62b36 100644
--- a/stack/core/src/main/java/org/apache/usergrid/corepersistence/CpEntityManager.java
+++ b/stack/core/src/main/java/org/apache/usergrid/corepersistence/CpEntityManager.java
@@ -853,10 +853,9 @@ public class CpEntityManager implements EntityManager {
}
@Override
- public Entity getUniqueEntityFromAlias( String collectionType, String aliasType ){
- String collName = Schema.defaultCollectionName( collectionType );
-
+ public Entity getUniqueEntityFromAlias(String collectionType, String aliasType, boolean useReadRepair){
+ String collName = Schema.defaultCollectionName( collectionType );
String propertyName = Schema.getDefaultSchema().aliasProperty( collName );
Timer.Context repairedEntityGet = entGetRepairedEntityTimer.time();
@@ -867,7 +866,7 @@ public class CpEntityManager implements EntityManager {
StringField uniqueLookupRepairField = new StringField( propertyName, aliasType.toString());
Observable<FieldSet> fieldSetObservable = ecm.getEntitiesFromFields(
- Inflector.getInstance().singularize( collectionType ), Arrays.<Field>asList( uniqueLookupRepairField ) );
+ Inflector.getInstance().singularize( collectionType ), Arrays.<Field>asList( uniqueLookupRepairField ), useReadRepair);
if(fieldSetObservable == null){
@@ -901,7 +900,7 @@ public class CpEntityManager implements EntityManager {
StringField uniqueLookupRepairField = new StringField( propertyName, aliasType);
Observable<FieldSet> fieldSetObservable = ecm.getEntitiesFromFields(
- Inflector.getInstance().singularize( collectionType ), Collections.singletonList(uniqueLookupRepairField));
+ Inflector.getInstance().singularize( collectionType ), Collections.singletonList(uniqueLookupRepairField), true);
if(fieldSetObservable == null){
http://git-wip-us.apache.org/repos/asf/usergrid/blob/06f77d7b/stack/core/src/main/java/org/apache/usergrid/persistence/EntityManager.java
----------------------------------------------------------------------
diff --git a/stack/core/src/main/java/org/apache/usergrid/persistence/EntityManager.java b/stack/core/src/main/java/org/apache/usergrid/persistence/EntityManager.java
index ef96f10..53a7a89 100644
--- a/stack/core/src/main/java/org/apache/usergrid/persistence/EntityManager.java
+++ b/stack/core/src/main/java/org/apache/usergrid/persistence/EntityManager.java
@@ -709,7 +709,7 @@ public interface EntityManager {
public void flushManagerCaches();
- public Entity getUniqueEntityFromAlias( String aliasType, String aliasValue );
+ public Entity getUniqueEntityFromAlias(String aliasType, String aliasValue, boolean useReadRepair);
public UUID getUniqueIdFromAlias( String aliasType, String aliasValue );
http://git-wip-us.apache.org/repos/asf/usergrid/blob/06f77d7b/stack/corepersistence/collection/src/main/java/org/apache/usergrid/persistence/collection/EntityCollectionManager.java
----------------------------------------------------------------------
diff --git a/stack/corepersistence/collection/src/main/java/org/apache/usergrid/persistence/collection/EntityCollectionManager.java b/stack/corepersistence/collection/src/main/java/org/apache/usergrid/persistence/collection/EntityCollectionManager.java
index 22fbb5f..ed43775 100644
--- a/stack/corepersistence/collection/src/main/java/org/apache/usergrid/persistence/collection/EntityCollectionManager.java
+++ b/stack/corepersistence/collection/src/main/java/org/apache/usergrid/persistence/collection/EntityCollectionManager.java
@@ -76,9 +76,10 @@ public interface EntityCollectionManager {
* Get a fieldset of all fields from the entities
* @param entityType The type of entity. From the "type" field in the id.
* @param fields The collection of fields to search
+ * @param useReadRepair
* @return
*/
- Observable<FieldSet> getEntitiesFromFields( String entityType, Collection<Field> fields );
+ Observable<FieldSet> getEntitiesFromFields(String entityType, Collection<Field> fields, boolean useReadRepair);
/**
* Gets the Id for a field
http://git-wip-us.apache.org/repos/asf/usergrid/blob/06f77d7b/stack/corepersistence/collection/src/main/java/org/apache/usergrid/persistence/collection/impl/EntityCollectionManagerImpl.java
----------------------------------------------------------------------
diff --git a/stack/corepersistence/collection/src/main/java/org/apache/usergrid/persistence/collection/impl/EntityCollectionManagerImpl.java b/stack/corepersistence/collection/src/main/java/org/apache/usergrid/persistence/collection/impl/EntityCollectionManagerImpl.java
index 77e452f..1ccc18f 100644
--- a/stack/corepersistence/collection/src/main/java/org/apache/usergrid/persistence/collection/impl/EntityCollectionManagerImpl.java
+++ b/stack/corepersistence/collection/src/main/java/org/apache/usergrid/persistence/collection/impl/EntityCollectionManagerImpl.java
@@ -65,7 +65,6 @@ import org.apache.usergrid.persistence.core.util.ValidationUtils;
import org.apache.usergrid.persistence.model.entity.Entity;
import org.apache.usergrid.persistence.model.entity.Id;
import org.apache.usergrid.persistence.model.field.Field;
-import org.apache.usergrid.persistence.model.util.EntityUtils;
import org.apache.usergrid.persistence.model.util.UUIDGenerator;
import com.codahale.metrics.Timer;
@@ -82,7 +81,6 @@ import com.netflix.astyanax.serializers.StringSerializer;
import rx.Observable;
import rx.Subscriber;
-import rx.functions.Action0;
/**
@@ -327,7 +325,7 @@ public class EntityCollectionManagerImpl implements EntityCollectionManager {
* Retrieves all entities that correspond to each field given in the Collection.
*/
@Override
- public Observable<FieldSet> getEntitiesFromFields( final String type, final Collection<Field> fields ) {
+ public Observable<FieldSet> getEntitiesFromFields(final String type, final Collection<Field> fields, boolean useReadRepair) {
final Observable<FieldSet> fieldSetObservable = Observable.just( fields ).map( fields1 -> {
try {
@@ -408,7 +406,7 @@ public class EntityCollectionManagerImpl implements EntityCollectionManager {
response.addEntity( expectedUnique.getField(), entity );
}
- if ( deleteBatch.getRowCount() > 0 ) {
+ if ( useReadRepair && deleteBatch.getRowCount() > 0 ) {
deleteBatch.execute();
@@ -436,7 +434,6 @@ public class EntityCollectionManagerImpl implements EntityCollectionManager {
}
-
return response;
}
catch ( ConnectionException e ) {
http://git-wip-us.apache.org/repos/asf/usergrid/blob/06f77d7b/stack/corepersistence/collection/src/main/java/org/apache/usergrid/persistence/collection/serialization/impl/UniqueValueSerializationStrategyImpl.java
----------------------------------------------------------------------
diff --git a/stack/corepersistence/collection/src/main/java/org/apache/usergrid/persistence/collection/serialization/impl/UniqueValueSerializationStrategyImpl.java b/stack/corepersistence/collection/src/main/java/org/apache/usergrid/persistence/collection/serialization/impl/UniqueValueSerializationStrategyImpl.java
index 622ebef..f7d5199 100644
--- a/stack/corepersistence/collection/src/main/java/org/apache/usergrid/persistence/collection/serialization/impl/UniqueValueSerializationStrategyImpl.java
+++ b/stack/corepersistence/collection/src/main/java/org/apache/usergrid/persistence/collection/serialization/impl/UniqueValueSerializationStrategyImpl.java
@@ -64,7 +64,7 @@ import com.netflix.astyanax.util.RangeBuilder;
public abstract class UniqueValueSerializationStrategyImpl<FieldKey, EntityKey>
implements UniqueValueSerializationStrategy {
- private static final Logger log = LoggerFactory.getLogger( UniqueValueSerializationStrategyImpl.class );
+ private static final Logger logger = LoggerFactory.getLogger( UniqueValueSerializationStrategyImpl.class );
private final MultiTenantColumnFamily<ScopedRowKey<FieldKey>, EntityVersion>
@@ -159,7 +159,7 @@ public abstract class UniqueValueSerializationStrategyImpl<FieldKey, EntityKey>
//we purposefully leave out TTL. Worst case we issue deletes against tombstoned columns
- //best case, we clean up an invalid secondary index entry when the log is used
+ //best case, we clean up an invalid secondary index entry when the logger is used
@Override
public void doLog( final ColumnListMutation<UniqueFieldEntry> colMutation ) {
colMutation.putColumn( uniqueFieldEntry, COL_VALUE );
@@ -225,8 +225,8 @@ public abstract class UniqueValueSerializationStrategyImpl<FieldKey, EntityKey>
ScopedRowKey.fromKey( applicationId, entityKey ) ) );
- if ( log.isTraceEnabled() ) {
- log.trace( "Writing unique value version={} name={} value={} ",
+ if ( logger.isTraceEnabled() ) {
+ logger.trace( "Writing unique value version={} name={} value={} ",
uniqueValue.getEntityVersion(), uniqueValue.getField().getName(),
uniqueValue.getField().getValue()
);
@@ -296,6 +296,13 @@ public abstract class UniqueValueSerializationStrategyImpl<FieldKey, EntityKey>
final UniqueValueImpl uniqueValue =
new UniqueValueImpl( field, entityVersion.getEntityId(), entityVersion.getEntityVersion() );
+ if(logger.isTraceEnabled()){
+ logger.trace("Putting unique value [{}={}] into result set with entity id [{}] and entity version [{}]",
+ field.getName(), field.getValue().toString(),
+ entityVersion.getEntityId(),
+ entityVersion.getEntityVersion());
+ }
+
uniqueValueSet.addValue( uniqueValue );
}
http://git-wip-us.apache.org/repos/asf/usergrid/blob/06f77d7b/stack/corepersistence/collection/src/test/java/org/apache/usergrid/persistence/collection/EntityCollectionManagerIT.java
----------------------------------------------------------------------
diff --git a/stack/corepersistence/collection/src/test/java/org/apache/usergrid/persistence/collection/EntityCollectionManagerIT.java b/stack/corepersistence/collection/src/test/java/org/apache/usergrid/persistence/collection/EntityCollectionManagerIT.java
index 115be99..10c7eb7 100644
--- a/stack/corepersistence/collection/src/test/java/org/apache/usergrid/persistence/collection/EntityCollectionManagerIT.java
+++ b/stack/corepersistence/collection/src/test/java/org/apache/usergrid/persistence/collection/EntityCollectionManagerIT.java
@@ -20,7 +20,6 @@ package org.apache.usergrid.persistence.collection;
import java.util.ArrayList;
import java.util.Arrays;
-import java.util.Collections;
import java.util.List;
import java.util.UUID;
@@ -118,27 +117,49 @@ public class EntityCollectionManagerIT {
EntityCollectionManager manager = factory.createCollectionManager( context );
- {
- Entity newEntity = new Entity( new SimpleId( "test" ) );
- newEntity.setField( new IntegerField( "count", 5, true ) );
+ Entity entity = new Entity( new SimpleId( "test" ) );
+ entity.setField( new IntegerField( "count", 5, true ) );
+
+ Observable<Entity> firstWrite = manager.write( entity );
+
+ Entity newEntity = null;
+ Entity firstReturned = null;
+
+ for(int i=0; i<500; i++){
- Observable<Entity> observable = manager.write( newEntity );
- Entity returned = observable.toBlocking().lastOrDefault( null );
- }
- {
- try {
- Entity newEntity = new Entity( new SimpleId( "test" ) );
- newEntity.setField( new IntegerField( "count", 5, true ) );
-
- manager.write( newEntity ).toBlocking().last();
- fail( "Write should have thrown an exception" );
- }
- catch ( Exception ex ) {
- WriteUniqueVerifyException e = ( WriteUniqueVerifyException ) ex;
- assertEquals( 1, e.getVioliations().size() );
- }
+ firstReturned = firstWrite.toBlocking().lastOrDefault( null );
+
}
+
+// try {
+// //newEntity = new Entity( new SimpleId( "test" ) );
+// //newEntity.setField( new IntegerField( "count", 5, true ) );
+//
+// Observable<Entity> secondWrite = manager.write( entity );
+// secondReturned = secondWrite.toBlocking().lastOrDefault( null );
+//
+// //fail( "Write should have thrown an exception" );
+// }
+// catch ( Exception ex ) {
+// WriteUniqueVerifyException e = ( WriteUniqueVerifyException ) ex;
+// assertEquals( 1, e.getVioliations().size() );
+// }
+
+ // try fetching the original one again
+
+ assertEquals(entity.getId().getUuid(), firstReturned.getId().getUuid());
+ assertEquals(entity.getVersion(), firstReturned.getVersion());
+
+
+ //assertEquals(newEntity.getId().getUuid(), secondReturned.getId().getUuid());
+ //assertEquals(newEntity.getVersion(), secondReturned.getVersion());
+
+
+
+
+
+
}
@@ -737,7 +758,7 @@ public class EntityCollectionManagerIT {
assertNotNull( "Version was assigned", createReturned.getVersion() );
FieldSet fieldResults =
- manager.getEntitiesFromFields( newEntity.getId().getType(), Arrays.<Field>asList( expectedInteger ) )
+ manager.getEntitiesFromFields( newEntity.getId().getType(), Arrays.<Field>asList( expectedInteger ), false)
.toBlocking().last();
assertEquals( 1, fieldResults.size() );
@@ -754,7 +775,7 @@ public class EntityCollectionManagerIT {
//try to load via the unique field, should have triggered repair
final FieldSet results =
- manager.getEntitiesFromFields( newEntity.getId().getType(), Arrays.<Field>asList( expectedInteger ) )
+ manager.getEntitiesFromFields( newEntity.getId().getType(), Arrays.<Field>asList( expectedInteger ), false)
.toBlocking().last();
http://git-wip-us.apache.org/repos/asf/usergrid/blob/06f77d7b/stack/services/src/main/java/org/apache/usergrid/services/AbstractCollectionService.java
----------------------------------------------------------------------
diff --git a/stack/services/src/main/java/org/apache/usergrid/services/AbstractCollectionService.java b/stack/services/src/main/java/org/apache/usergrid/services/AbstractCollectionService.java
index c5473cf..7b9e230 100644
--- a/stack/services/src/main/java/org/apache/usergrid/services/AbstractCollectionService.java
+++ b/stack/services/src/main/java/org/apache/usergrid/services/AbstractCollectionService.java
@@ -85,7 +85,7 @@ public class AbstractCollectionService extends AbstractService {
nameProperty = "name";
}
- Entity entity = em.getUniqueEntityFromAlias( getEntityType(), name );
+ Entity entity = em.getUniqueEntityFromAlias( getEntityType(), name, true);
if ( entity != null ) {
entity = importEntity( request, entity );
}
@@ -282,7 +282,7 @@ public class AbstractCollectionService extends AbstractService {
}
// EntityRef ref = em.getAlias( getEntityType(), name );
- Entity entity = em.getUniqueEntityFromAlias( getEntityType(), name );
+ Entity entity = em.getUniqueEntityFromAlias( getEntityType(), name, true);
if ( entity == null ) {
// null entity ref means we tried to put a non-existing entity
// before we create a new entity for it, we should check for permission
@@ -477,7 +477,7 @@ public class AbstractCollectionService extends AbstractService {
return super.postItemByName( context, name );
}
- Entity entity = em.getUniqueEntityFromAlias( getEntityType(), name );
+ Entity entity = em.getUniqueEntityFromAlias( getEntityType(), name, true);
if ( entity == null ) {
throw new ServiceResourceNotFoundException( context );
}
@@ -531,7 +531,7 @@ public class AbstractCollectionService extends AbstractService {
return getItemByName( context, name );
}
- Entity entity = em.getUniqueEntityFromAlias( getEntityType(), name );
+ Entity entity = em.getUniqueEntityFromAlias( getEntityType(), name, true);
if ( entity == null ) {
throw new ServiceResourceNotFoundException( context );
}
http://git-wip-us.apache.org/repos/asf/usergrid/blob/06f77d7b/stack/services/src/main/java/org/apache/usergrid/services/AbstractConnectionsService.java
----------------------------------------------------------------------
diff --git a/stack/services/src/main/java/org/apache/usergrid/services/AbstractConnectionsService.java b/stack/services/src/main/java/org/apache/usergrid/services/AbstractConnectionsService.java
index 395f2d4..5f7ca6b 100644
--- a/stack/services/src/main/java/org/apache/usergrid/services/AbstractConnectionsService.java
+++ b/stack/services/src/main/java/org/apache/usergrid/services/AbstractConnectionsService.java
@@ -271,7 +271,7 @@ public class AbstractConnectionsService extends AbstractService {
//TODO T.N. USERGRID-1919 actually validate this is connected
- Entity entity = em.getUniqueEntityFromAlias( query.getEntityType(), name );
+ Entity entity = em.getUniqueEntityFromAlias( query.getEntityType(), name, true);
if ( entity == null ) {
return null;
}
@@ -372,7 +372,7 @@ public class AbstractConnectionsService extends AbstractService {
if ( query.containsSingleNameOrEmailIdentifier() ) {
String name = query.getSingleNameOrEmailIdentifier();
- entity = em.getUniqueEntityFromAlias( query.getEntityType(), name );
+ entity = em.getUniqueEntityFromAlias( query.getEntityType(), name, true);
if ( entity == null ) {
throw new ServiceResourceNotFoundException( context );
}
@@ -529,7 +529,7 @@ public class AbstractConnectionsService extends AbstractService {
nameProperty = "name";
}
- Entity entity = em.getUniqueEntityFromAlias( query.getEntityType(), name );
+ Entity entity = em.getUniqueEntityFromAlias( query.getEntityType(), name, true);
if ( entity == null ) {
throw new ServiceResourceNotFoundException( context );
}
http://git-wip-us.apache.org/repos/asf/usergrid/blob/06f77d7b/stack/tools/src/main/java/org/apache/usergrid/tools/UniqueValueScanner.java
----------------------------------------------------------------------
diff --git a/stack/tools/src/main/java/org/apache/usergrid/tools/UniqueValueScanner.java b/stack/tools/src/main/java/org/apache/usergrid/tools/UniqueValueScanner.java
new file mode 100644
index 0000000..f884a1d
--- /dev/null
+++ b/stack/tools/src/main/java/org/apache/usergrid/tools/UniqueValueScanner.java
@@ -0,0 +1,245 @@
+/*
+ * Licensed to the Apache Software Foundation (ASF) under one or more
+ * contributor license agreements. See the NOTICE file distributed with
+ * this work for additional information regarding copyright ownership.
+ * The ASF licenses this file to You under the Apache License, Version 2.0
+ * (the "License"); you may not use this file except in compliance with
+ * the License. You may obtain a copy of the License at
+ *
+ * http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS,
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ * See the License for the specific language governing permissions and
+ * limitations under the License.
+ */
+package org.apache.usergrid.tools;
+
+
+import java.util.Collections;
+import java.util.Iterator;
+import java.util.UUID;
+
+import com.google.common.base.Optional;
+import com.netflix.astyanax.connectionpool.exceptions.ConnectionException;
+import com.netflix.astyanax.model.Column;
+import com.netflix.astyanax.util.RangeBuilder;
+import org.apache.usergrid.persistence.Entity;
+import org.apache.usergrid.persistence.EntityManager;
+import org.apache.usergrid.persistence.collection.MvccEntity;
+import org.apache.usergrid.persistence.collection.serialization.MvccEntitySerializationStrategy;
+import org.apache.usergrid.persistence.collection.serialization.UniqueValueSerializationStrategy;
+import org.apache.usergrid.persistence.collection.serialization.UniqueValueSet;
+import org.apache.usergrid.persistence.collection.serialization.impl.*;
+import org.apache.usergrid.persistence.core.scope.ApplicationScopeImpl;
+import org.apache.usergrid.persistence.model.entity.SimpleId;
+import org.apache.usergrid.persistence.model.field.StringField;
+import org.slf4j.Logger;
+import org.slf4j.LoggerFactory;
+
+import org.apache.commons.cli.CommandLine;
+import org.apache.commons.cli.Option;
+import org.apache.commons.cli.OptionBuilder;
+import org.apache.commons.cli.Options;
+
+
+import org.apache.usergrid.persistence.core.astyanax.MultiTenantColumnFamily;
+import org.apache.usergrid.persistence.core.astyanax.ScopedRowKey;
+import org.apache.usergrid.persistence.core.astyanax.ScopedRowKeySerializer;
+
+
+
+public class UniqueValueScanner extends ToolBase {
+
+ private static final Logger logger = LoggerFactory.getLogger( UniqueValueScanner.class );
+
+ private static final String APPLICATION_ARG = "app";
+
+ private static final String ENTITY_TYPE_ARG = "entityType";
+
+ private static final String ENTITY_NAME_ARG = "entityName";
+
+
+ //copied shamelessly from unique value serialization strat.
+ private static final ScopedRowKeySerializer<TypeField> ROW_KEY_SER =
+ new ScopedRowKeySerializer<>( UniqueTypeFieldRowKeySerializer.get() );
+
+
+ private final EntityVersionSerializer ENTITY_VERSION_SER = new EntityVersionSerializer();
+
+ private final MultiTenantColumnFamily<ScopedRowKey<TypeField>, EntityVersion> CF_UNIQUE_VALUES =
+ new MultiTenantColumnFamily<>( "Unique_Values_V2", ROW_KEY_SER, ENTITY_VERSION_SER );
+
+ private com.netflix.astyanax.Keyspace keyspace;
+
+ private MvccEntitySerializationStrategy mvccEntitySerializationStrategy;
+
+ private UniqueValueSerializationStrategy uniqueValueSerializationStrategy;
+
+ private EntityManager em;
+
+ @Override
+ @SuppressWarnings( "static-access" )
+ public Options createOptions() {
+
+
+ Options options = super.createOptions();
+
+
+ Option appOption = OptionBuilder.withArgName( APPLICATION_ARG ).hasArg().isRequired( true )
+ .withDescription( "application id" ).create( APPLICATION_ARG );
+
+
+ options.addOption( appOption );
+
+ Option collectionOption =
+ OptionBuilder.withArgName(ENTITY_TYPE_ARG).hasArg().isRequired( true ).withDescription( "collection name" )
+ .create(ENTITY_TYPE_ARG);
+
+ options.addOption( collectionOption );
+
+ Option specificEntityNameOption =
+ OptionBuilder.withArgName(ENTITY_NAME_ARG).hasArg().isRequired( true ).withDescription( "specific entity name" )
+ .create(ENTITY_NAME_ARG);
+
+ options.addOption( specificEntityNameOption );
+
+
+ return options;
+ }
+
+
+ /*
+ * (non-Javadoc)
+ *
+ * @see
+ * org.apache.usergrid.tools.ToolBase#runTool(org.apache.commons.cli.CommandLine)
+ */
+ @Override
+ public void runTool( CommandLine line ) throws Exception {
+
+ startSpring();
+
+ UUID appToFilter = null;
+ if (!line.getOptionValue(APPLICATION_ARG).isEmpty()) {
+ appToFilter = UUID.fromString(line.getOptionValue(APPLICATION_ARG));
+ }
+
+
+ logger.info("Starting entity unique scanner");
+
+ keyspace = injector.getInstance(com.netflix.astyanax.Keyspace.class);
+ mvccEntitySerializationStrategy = injector.getInstance(MvccEntitySerializationStrategy.class);
+ uniqueValueSerializationStrategy = injector.getInstance(UniqueValueSerializationStrategy.class);
+
+
+ String entityType = line.getOptionValue(ENTITY_TYPE_ARG);
+ String entityName = line.getOptionValue(ENTITY_NAME_ARG);
+
+ if (entityName != null && !entityName.isEmpty()) {
+
+ if(appToFilter == null){
+ throw new RuntimeException("Cannot execute UniqueValueScanner with specific entity without the " +
+ "application UUID for which the entity should exist.");
+ }
+
+ if(entityType == null){
+ throw new RuntimeException("Cannot execute UniqueValueScanner without the entity type (singular " +
+ "collection name).");
+ }
+
+ //do stuff
+ UniqueValueSet uniqueValueSet = uniqueValueSerializationStrategy.load(
+ new ApplicationScopeImpl( new SimpleId(appToFilter, "application" ) ),
+ entityType,
+ Collections.singletonList(new StringField( "name", entityName) ));
+
+ logger.info("Returned unique value set from serialization load = {}", uniqueValueSet);
+
+ } else {
+
+ // scan through all unique values and log some info
+
+ Iterator<com.netflix.astyanax.model.Row<ScopedRowKey<TypeField>, EntityVersion>> rows = null;
+ try {
+
+ rows = keyspace.prepareQuery(CF_UNIQUE_VALUES)
+ .getAllRows()
+ .withColumnRange(new RangeBuilder().build())
+ .execute().getResult().iterator();
+
+ } catch (ConnectionException e) {
+
+ }
+
+
+ UUID finalAppToFilter = appToFilter;
+ rows.forEachRemaining(row -> {
+
+ String fieldName = row.getKey().getKey().getField().getName();
+ String scopeType = row.getKey().getScope().getType();
+ UUID scopeUUID = row.getKey().getScope().getUuid();
+
+ if (!fieldName.equalsIgnoreCase("name") ||
+ (finalAppToFilter != null && !finalAppToFilter.equals(scopeUUID))
+ ) {
+ // do nothing
+
+ } else {
+
+ if (em == null && finalAppToFilter.equals(scopeUUID)) {
+ em = emf.getEntityManager(scopeUUID);
+ }
+
+ Iterator<Column<EntityVersion>> columns = row.getColumns().iterator();
+ columns.forEachRemaining(column -> {
+
+ EntityVersion entityVersion = column.getName();
+
+ if (entityType != null &&
+ entityVersion.getEntityId().getType().equalsIgnoreCase(entityType)
+ ) {
+
+ String fieldValue = row.getKey().getKey().getField().getValue().toString();
+
+ logger.trace(
+ scopeType + ": " + scopeUUID + ", " +
+ fieldName + ": " + fieldValue + ", " +
+ "entity type: " + entityVersion.getEntityId().getType() + ", " +
+ "entity uuid: " + entityVersion.getEntityId().getUuid()
+ );
+
+
+ Entity entity = em.getUniqueEntityFromAlias(entityType, fieldValue, false);
+
+// Optional<MvccEntity> entity = mvccEntitySerializationStrategy.
+// load(new ApplicationScopeImpl(new SimpleId(scopeUUID, scopeType)), entityVersion.getEntityId());
+//
+// if(!entity.isPresent()){
+
+ if (entity == null) {
+
+ logger.error("{}: {}. Entity with type=[{}], name=[{}], and uuid=[{}] has a unique value entry " +
+ "but cannot be loaded from Mvcc entity serialization",
+ scopeType,
+ scopeUUID,
+ entityVersion.getEntityId().getType(),
+ fieldValue,
+ entityVersion.getEntityId().getUuid());
+ }
+
+ } else {
+ // do nothing
+ }
+
+
+ });
+ }
+
+
+ });
+
+ }
+ }
+}
[10/11] usergrid git commit: Fix log statement. Only newer duplicate
unique value entries are removed ( it just might be the candidate or current
one in the loop).
Posted by mr...@apache.org.
Fix log statement. Only newer duplicate unique value entries are removed ( it just might be the candidate or current one in the loop).
Project: http://git-wip-us.apache.org/repos/asf/usergrid/repo
Commit: http://git-wip-us.apache.org/repos/asf/usergrid/commit/cf4c7f89
Tree: http://git-wip-us.apache.org/repos/asf/usergrid/tree/cf4c7f89
Diff: http://git-wip-us.apache.org/repos/asf/usergrid/diff/cf4c7f89
Branch: refs/heads/release-2.1.1
Commit: cf4c7f898d73b1a864ba541156cd1e5315b5c1d7
Parents: 20ae382
Author: Michael Russo <mr...@apigee.com>
Authored: Thu Jun 23 12:39:31 2016 -0700
Committer: Michael Russo <mr...@apigee.com>
Committed: Thu Jun 23 12:39:31 2016 -0700
----------------------------------------------------------------------
.../serialization/impl/UniqueValueSerializationStrategyImpl.java | 2 +-
1 file changed, 1 insertion(+), 1 deletion(-)
----------------------------------------------------------------------
http://git-wip-us.apache.org/repos/asf/usergrid/blob/cf4c7f89/stack/corepersistence/collection/src/main/java/org/apache/usergrid/persistence/collection/serialization/impl/UniqueValueSerializationStrategyImpl.java
----------------------------------------------------------------------
diff --git a/stack/corepersistence/collection/src/main/java/org/apache/usergrid/persistence/collection/serialization/impl/UniqueValueSerializationStrategyImpl.java b/stack/corepersistence/collection/src/main/java/org/apache/usergrid/persistence/collection/serialization/impl/UniqueValueSerializationStrategyImpl.java
index bf7d2fc..1c5b08f 100644
--- a/stack/corepersistence/collection/src/main/java/org/apache/usergrid/persistence/collection/serialization/impl/UniqueValueSerializationStrategyImpl.java
+++ b/stack/corepersistence/collection/src/main/java/org/apache/usergrid/persistence/collection/serialization/impl/UniqueValueSerializationStrategyImpl.java
@@ -333,7 +333,7 @@ public abstract class UniqueValueSerializationStrategyImpl<FieldKey, EntityKey>
try {
- logger.warn("Duplicate unique value [{}={}] found, removing older entry " +
+ logger.warn("Duplicate unique value [{}={}] found, removing newer entry " +
"with entity id [{}] and entity version [{}]", field.getName(), field.getValue().toString(),
candidate.getEntityId().getUuid(), candidate.getEntityVersion() );
[04/11] usergrid git commit: Implement smarter loading of unique
value entries in hopes to avoid duplicate problems. Update UniqueValueScanner
tool to allow specific entity fetch.
Posted by mr...@apache.org.
Implement smarter loading of unique value entries in hopes to avoid duplicate problems. Update UniqueValueScanner tool to allow specific entity fetch.
Project: http://git-wip-us.apache.org/repos/asf/usergrid/repo
Commit: http://git-wip-us.apache.org/repos/asf/usergrid/commit/75d2254e
Tree: http://git-wip-us.apache.org/repos/asf/usergrid/tree/75d2254e
Diff: http://git-wip-us.apache.org/repos/asf/usergrid/diff/75d2254e
Branch: refs/heads/release-2.1.1
Commit: 75d2254e3f57bdf78a965e71255910e25121fe94
Parents: 1997b57
Author: Michael Russo <mr...@apigee.com>
Authored: Wed Jun 22 16:34:28 2016 -0700
Committer: Michael Russo <mr...@apigee.com>
Committed: Wed Jun 22 16:34:28 2016 -0700
----------------------------------------------------------------------
.../mvcc/stage/write/WriteUniqueVerify.java | 34 +++++-
.../UniqueValueSerializationStrategy.java | 3 +-
.../UniqueValueSerializationStrategyImpl.java | 86 ++++++++++++----
.../collection/EntityCollectionManagerIT.java | 4 +-
...niqueValueSerializationStrategyImplTest.java | 103 ++++++++++++++++++-
.../collection/devices/DevicesResourceIT.java | 3 +-
.../usergrid/tools/UniqueValueScanner.java | 47 +++++++--
7 files changed, 245 insertions(+), 35 deletions(-)
----------------------------------------------------------------------
http://git-wip-us.apache.org/repos/asf/usergrid/blob/75d2254e/stack/corepersistence/collection/src/main/java/org/apache/usergrid/persistence/collection/mvcc/stage/write/WriteUniqueVerify.java
----------------------------------------------------------------------
diff --git a/stack/corepersistence/collection/src/main/java/org/apache/usergrid/persistence/collection/mvcc/stage/write/WriteUniqueVerify.java b/stack/corepersistence/collection/src/main/java/org/apache/usergrid/persistence/collection/mvcc/stage/write/WriteUniqueVerify.java
index afe681e..7b76dc8 100644
--- a/stack/corepersistence/collection/src/main/java/org/apache/usergrid/persistence/collection/mvcc/stage/write/WriteUniqueVerify.java
+++ b/stack/corepersistence/collection/src/main/java/org/apache/usergrid/persistence/collection/mvcc/stage/write/WriteUniqueVerify.java
@@ -18,10 +18,7 @@
package org.apache.usergrid.persistence.collection.mvcc.stage.write;
-import java.util.ArrayList;
-import java.util.HashMap;
-import java.util.List;
-import java.util.Map;
+import java.util.*;
import com.netflix.hystrix.HystrixCommandProperties;
import org.slf4j.Logger;
@@ -112,6 +109,7 @@ public class WriteUniqueVerify implements Action1<CollectionIoEvent<MvccEntity>>
// Construct all the functions for verifying we're unique
//
+ final Map<String, Field> preWriteUniquenessViolations = new HashMap<>( uniqueFields.size() );
for ( final Field field : EntityUtils.getUniqueFields(entity)) {
@@ -121,6 +119,28 @@ public class WriteUniqueVerify implements Action1<CollectionIoEvent<MvccEntity>>
// use write-first then read strategy
final UniqueValue written = new UniqueValueImpl( field, mvccEntity.getId(), mvccEntity.getVersion() );
+ try {
+
+ // loading will retrieve the oldest unique value entry for the field
+ UniqueValueSet set = uniqueValueStrat.load(scope, written.getEntityId().getType(), Collections.singletonList(written.getField()));
+
+
+ set.forEach(uniqueValue -> {
+
+ if(!uniqueValue.getEntityId().getUuid().equals(written.getEntityId().getUuid())){
+
+ preWriteUniquenessViolations.put(field.getName(), field);
+
+ }
+
+ });
+
+
+ } catch (ConnectionException e) {
+
+ throw new RuntimeException("Error connecting to cassandra", e);
+ }
+
// use TTL in case something goes wrong before entity is finally committed
final MutationBatch mb = uniqueValueStrat.write( scope, written, serializationFig.getTimeout() );
@@ -128,6 +148,11 @@ public class WriteUniqueVerify implements Action1<CollectionIoEvent<MvccEntity>>
uniqueFields.add(field);
}
+ if(preWriteUniquenessViolations.size() > 0 ){
+ throw new WriteUniqueVerifyException(mvccEntity, scope,
+ preWriteUniquenessViolations );
+ }
+
//short circuit nothing to do
if ( uniqueFields.size() == 0 ) {
return ;
@@ -191,6 +216,7 @@ public class WriteUniqueVerify implements Action1<CollectionIoEvent<MvccEntity>>
//now get the set of fields back
final UniqueValueSet uniqueValues;
try {
+ // load ascending for verification to make sure we wrote is the last read back
uniqueValues = uniqueValueSerializationStrategy.load( scope, consistencyLevel, type, uniqueFields );
}
catch ( ConnectionException e ) {
http://git-wip-us.apache.org/repos/asf/usergrid/blob/75d2254e/stack/corepersistence/collection/src/main/java/org/apache/usergrid/persistence/collection/serialization/UniqueValueSerializationStrategy.java
----------------------------------------------------------------------
diff --git a/stack/corepersistence/collection/src/main/java/org/apache/usergrid/persistence/collection/serialization/UniqueValueSerializationStrategy.java b/stack/corepersistence/collection/src/main/java/org/apache/usergrid/persistence/collection/serialization/UniqueValueSerializationStrategy.java
index 3645107..95cfa68 100644
--- a/stack/corepersistence/collection/src/main/java/org/apache/usergrid/persistence/collection/serialization/UniqueValueSerializationStrategy.java
+++ b/stack/corepersistence/collection/src/main/java/org/apache/usergrid/persistence/collection/serialization/UniqueValueSerializationStrategy.java
@@ -59,7 +59,8 @@ public interface UniqueValueSerializationStrategy extends Migration, VersionedDa
MutationBatch write( ApplicationScope applicationScope, UniqueValue uniqueValue, int timeToLive );
/**
- * Load UniqueValue that matches field from collection or null if that value does not exist.
+ * Load UniqueValue that matches field from collection or null if that value does not exist. Returns the oldest
+ * unique value entry if more than 1 exists
*
* @param applicationScope scope in which to look for field name/value
* @param type The type the unique value exists within
http://git-wip-us.apache.org/repos/asf/usergrid/blob/75d2254e/stack/corepersistence/collection/src/main/java/org/apache/usergrid/persistence/collection/serialization/impl/UniqueValueSerializationStrategyImpl.java
----------------------------------------------------------------------
diff --git a/stack/corepersistence/collection/src/main/java/org/apache/usergrid/persistence/collection/serialization/impl/UniqueValueSerializationStrategyImpl.java b/stack/corepersistence/collection/src/main/java/org/apache/usergrid/persistence/collection/serialization/impl/UniqueValueSerializationStrategyImpl.java
index f7d5199..a323746 100644
--- a/stack/corepersistence/collection/src/main/java/org/apache/usergrid/persistence/collection/serialization/impl/UniqueValueSerializationStrategyImpl.java
+++ b/stack/corepersistence/collection/src/main/java/org/apache/usergrid/persistence/collection/serialization/impl/UniqueValueSerializationStrategyImpl.java
@@ -18,13 +18,9 @@
package org.apache.usergrid.persistence.collection.serialization.impl;
-import java.util.ArrayList;
-import java.util.Arrays;
-import java.util.Collection;
-import java.util.Iterator;
-import java.util.List;
-import java.util.UUID;
+import java.util.*;
+import com.netflix.astyanax.util.RangeBuilder;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
@@ -55,7 +51,6 @@ import com.netflix.astyanax.model.Column;
import com.netflix.astyanax.model.ConsistencyLevel;
import com.netflix.astyanax.model.Row;
import com.netflix.astyanax.query.RowQuery;
-import com.netflix.astyanax.util.RangeBuilder;
/**
@@ -271,7 +266,8 @@ public abstract class UniqueValueSerializationStrategyImpl<FieldKey, EntityKey>
Iterator<Row<ScopedRowKey<FieldKey>, EntityVersion>> results =
keyspace.prepareQuery( CF_UNIQUE_VALUES ).setConsistencyLevel( consistencyLevel ).getKeySlice( keys )
- .withColumnRange( new RangeBuilder().setLimit( 1 ).build() ).execute().getResult().iterator();
+ .withColumnRange(new RangeBuilder().setLimit(serializationFig.getBufferSize()).build())
+ .execute().getResult().iterator();
while ( results.hasNext() )
@@ -280,7 +276,6 @@ public abstract class UniqueValueSerializationStrategyImpl<FieldKey, EntityKey>
final Row<ScopedRowKey<FieldKey>, EntityVersion> unique = results.next();
-
final Field field = parseRowKey( unique.getKey() );
final Iterator<Column<EntityVersion>> columnList = unique.getColumns().iterator();
@@ -290,20 +285,75 @@ public abstract class UniqueValueSerializationStrategyImpl<FieldKey, EntityKey>
continue;
}
- final EntityVersion entityVersion = columnList.next().getName();
+ // these used duplicate tracking and cleanup
+ UUID oldestEntityUUID = null;
+ UniqueValueImpl firstUniqueValue = null;
+
+
+ /**
+ * While iterating the columns, a rule is being enforced to only EVER return the oldest UUID. This means
+ * the UUID with the oldest timestamp ( it was the original entity written for the unique value ).
+ *
+ * We do this to prevent cycling of unique value -> entity UUID mappings as this data is ordered by the
+ * entity's version and not the entity's timestamp itself.
+ *
+ * If newer entity UUIDs are encountered, they are removed from the unique value tables, however their
+ * backing serialized entity data is left in tact in case a cleanup / audit is later needed.
+ */
+ while (columnList.hasNext()) {
+
+ final EntityVersion entityVersion = columnList.next().getName();
+
+ final UUID currentEntityUUID = entityVersion.getEntityId().getUuid();
+ final UniqueValueImpl uniqueValue =
+ new UniqueValueImpl(field, entityVersion.getEntityId(), entityVersion.getEntityVersion());
+
+
+ // keep track of the first and oldest entity (not version),
+ // knowing the the first one may not be the 'oldest'
+ if(oldestEntityUUID == null){
+
+ oldestEntityUUID = currentEntityUUID;
+ firstUniqueValue = uniqueValue;
+
+ }else if(currentEntityUUID.timestamp() < oldestEntityUUID.timestamp()){
+ oldestEntityUUID = currentEntityUUID;
+ }
- final UniqueValueImpl uniqueValue =
- new UniqueValueImpl( field, entityVersion.getEntityId(), entityVersion.getEntityVersion() );
- if(logger.isTraceEnabled()){
- logger.trace("Putting unique value [{}={}] into result set with entity id [{}] and entity version [{}]",
- field.getName(), field.getValue().toString(),
- entityVersion.getEntityId(),
- entityVersion.getEntityVersion());
+ // only return the oldest (original) unique value entries
+ if(currentEntityUUID.timestamp() <= oldestEntityUUID.timestamp() ){
+
+ if (logger.isTraceEnabled()) {
+ logger.trace("Putting unique value [{}={}] into result set with entity id [{}] and entity version [{}]",
+ field.getName(), field.getValue().toString(),
+ entityVersion.getEntityId(),
+ entityVersion.getEntityVersion());
+ }
+
+ uniqueValueSet.addValue(uniqueValue);
+
+ }
+ // remove the newer duplicated unique value entries
+ else{
+
+ delete(appScope, uniqueValue ).execute();
+
+ }
+
}
- uniqueValueSet.addValue( uniqueValue );
+ // check to see if the very first unique value entry was overwritten because it was not the oldest
+ // if so, clean up its unique index
+ if( !uniqueValueSet.getValue( firstUniqueValue.getField().getName() )
+ .getEntityId().getUuid().equals(firstUniqueValue.getEntityId().getUuid()) ){
+
+ delete(appScope, firstUniqueValue).execute();
+
+ }
+
+
}
return uniqueValueSet;
http://git-wip-us.apache.org/repos/asf/usergrid/blob/75d2254e/stack/corepersistence/collection/src/test/java/org/apache/usergrid/persistence/collection/EntityCollectionManagerIT.java
----------------------------------------------------------------------
diff --git a/stack/corepersistence/collection/src/test/java/org/apache/usergrid/persistence/collection/EntityCollectionManagerIT.java b/stack/corepersistence/collection/src/test/java/org/apache/usergrid/persistence/collection/EntityCollectionManagerIT.java
index 10c7eb7..f828c65 100644
--- a/stack/corepersistence/collection/src/test/java/org/apache/usergrid/persistence/collection/EntityCollectionManagerIT.java
+++ b/stack/corepersistence/collection/src/test/java/org/apache/usergrid/persistence/collection/EntityCollectionManagerIT.java
@@ -758,7 +758,7 @@ public class EntityCollectionManagerIT {
assertNotNull( "Version was assigned", createReturned.getVersion() );
FieldSet fieldResults =
- manager.getEntitiesFromFields( newEntity.getId().getType(), Arrays.<Field>asList( expectedInteger ), false)
+ manager.getEntitiesFromFields( newEntity.getId().getType(), Arrays.<Field>asList( expectedInteger ), true)
.toBlocking().last();
assertEquals( 1, fieldResults.size() );
@@ -775,7 +775,7 @@ public class EntityCollectionManagerIT {
//try to load via the unique field, should have triggered repair
final FieldSet results =
- manager.getEntitiesFromFields( newEntity.getId().getType(), Arrays.<Field>asList( expectedInteger ), false)
+ manager.getEntitiesFromFields( newEntity.getId().getType(), Arrays.<Field>asList( expectedInteger ), true)
.toBlocking().last();
http://git-wip-us.apache.org/repos/asf/usergrid/blob/75d2254e/stack/corepersistence/collection/src/test/java/org/apache/usergrid/persistence/collection/serialization/impl/UniqueValueSerializationStrategyImplTest.java
----------------------------------------------------------------------
diff --git a/stack/corepersistence/collection/src/test/java/org/apache/usergrid/persistence/collection/serialization/impl/UniqueValueSerializationStrategyImplTest.java b/stack/corepersistence/collection/src/test/java/org/apache/usergrid/persistence/collection/serialization/impl/UniqueValueSerializationStrategyImplTest.java
index fcf22cf..6c4e72b 100644
--- a/stack/corepersistence/collection/src/test/java/org/apache/usergrid/persistence/collection/serialization/impl/UniqueValueSerializationStrategyImplTest.java
+++ b/stack/corepersistence/collection/src/test/java/org/apache/usergrid/persistence/collection/serialization/impl/UniqueValueSerializationStrategyImplTest.java
@@ -33,7 +33,6 @@ import org.apache.usergrid.persistence.collection.guice.TestCollectionModule;
import org.apache.usergrid.persistence.collection.serialization.UniqueValue;
import org.apache.usergrid.persistence.collection.serialization.UniqueValueSerializationStrategy;
import org.apache.usergrid.persistence.collection.serialization.UniqueValueSet;
-import org.apache.usergrid.persistence.collection.serialization.impl.UniqueValueImpl;
import org.apache.usergrid.persistence.core.guice.MigrationManagerRule;
import org.apache.usergrid.persistence.core.scope.ApplicationScope;
import org.apache.usergrid.persistence.core.scope.ApplicationScopeImpl;
@@ -341,4 +340,106 @@ public abstract class UniqueValueSerializationStrategyImplTest {
}
+ /**
+ * Test that inserting duplicates always show the oldest entity UUID being returned (versions of that OK to change).
+ *
+ * @throws ConnectionException
+ * @throws InterruptedException
+ */
+ @Test
+ public void testWritingDuplicates() throws ConnectionException, InterruptedException {
+
+ ApplicationScope scope =
+ new ApplicationScopeImpl( new SimpleId( "organization" ) );
+
+ IntegerField field = new IntegerField( "count", 5 );
+ Id entityId1 = new SimpleId( UUIDGenerator.newTimeUUID(), "entity" );
+ Id entityId2 = new SimpleId( UUIDGenerator.newTimeUUID(), "entity" );
+
+
+
+ UUID version1 = UUIDGenerator.newTimeUUID();
+ UUID version2 = UUIDGenerator.newTimeUUID();
+
+ UniqueValue stored1 = new UniqueValueImpl( field, entityId1, version2 );
+ UniqueValue stored2 = new UniqueValueImpl( field, entityId2, version1 );
+
+
+ strategy.write( scope, stored1 ).execute();
+ strategy.write( scope, stored2 ).execute();
+
+ // load descending to get the older version of entity for this unique value
+ UniqueValueSet fields = strategy.load( scope, entityId1.getType(), Collections.<Field>singleton( field ));
+
+ UniqueValue retrieved = fields.getValue( field.getName() );
+
+ // validate that the first entity UUID is returned after inserting a duplicate mapping
+ assertEquals( stored1, retrieved );
+
+
+
+ UUID version3 = UUIDGenerator.newTimeUUID();
+ UniqueValue stored3 = new UniqueValueImpl( field, entityId2, version3);
+ strategy.write( scope, stored3 ).execute();
+
+ // load the values again, we should still only get back the original unique value
+ fields = strategy.load( scope, entityId1.getType(), Collections.<Field>singleton( field ));
+
+ retrieved = fields.getValue( field.getName() );
+
+ // validate that the first entity UUID is still returned after inserting duplicate with newer version
+ assertEquals( stored1, retrieved );
+
+
+ UUID version4 = UUIDGenerator.newTimeUUID();
+ UniqueValue stored4 = new UniqueValueImpl( field, entityId1, version4);
+ strategy.write( scope, stored4 ).execute();
+
+ // load the values again, now we should get the latest version of the original UUID written
+ fields = strategy.load( scope, entityId1.getType(), Collections.<Field>singleton( field ));
+
+ retrieved = fields.getValue( field.getName() );
+
+ // validate that the first entity UUID is still returned, but with the latest version
+ assertEquals( stored4, retrieved );
+
+ }
+
+ /**
+ * Test that inserting multiple versions of the same entity UUID result in the latest version being returned.
+ *
+ * @throws ConnectionException
+ * @throws InterruptedException
+ */
+ @Test
+ public void testMultipleVersionsSameEntity() throws ConnectionException, InterruptedException {
+
+ ApplicationScope scope =
+ new ApplicationScopeImpl( new SimpleId( "organization" ) );
+
+ IntegerField field = new IntegerField( "count", 5 );
+ Id entityId1 = new SimpleId( UUIDGenerator.newTimeUUID(), "entity" );
+
+
+
+ UUID version1 = UUIDGenerator.newTimeUUID();
+ UUID version2 = UUIDGenerator.newTimeUUID();
+
+ UniqueValue stored1 = new UniqueValueImpl( field, entityId1, version1 );
+ UniqueValue stored2 = new UniqueValueImpl( field, entityId1, version2 );
+
+
+ strategy.write( scope, stored1 ).execute();
+ strategy.write( scope, stored2 ).execute();
+
+ // load descending to get the older version of entity for this unique value
+ UniqueValueSet fields = strategy.load( scope, entityId1.getType(), Collections.<Field>singleton( field ));
+
+ UniqueValue retrieved = fields.getValue( field.getName() );
+ Assert.assertNotNull( retrieved );
+ assertEquals( stored2, retrieved );
+
+
+ }
+
}
http://git-wip-us.apache.org/repos/asf/usergrid/blob/75d2254e/stack/rest/src/test/java/org/apache/usergrid/rest/applications/collection/devices/DevicesResourceIT.java
----------------------------------------------------------------------
diff --git a/stack/rest/src/test/java/org/apache/usergrid/rest/applications/collection/devices/DevicesResourceIT.java b/stack/rest/src/test/java/org/apache/usergrid/rest/applications/collection/devices/DevicesResourceIT.java
index 02716a7..67cf19f 100644
--- a/stack/rest/src/test/java/org/apache/usergrid/rest/applications/collection/devices/DevicesResourceIT.java
+++ b/stack/rest/src/test/java/org/apache/usergrid/rest/applications/collection/devices/DevicesResourceIT.java
@@ -22,6 +22,7 @@ import java.util.Map;
import java.util.UUID;
import com.fasterxml.jackson.databind.JsonNode;
+import org.apache.usergrid.persistence.model.util.UUIDGenerator;
import org.apache.usergrid.rest.test.resource.AbstractRestIT;
import org.apache.usergrid.rest.test.resource.endpoints.CollectionEndpoint;
import org.apache.usergrid.rest.test.resource.model.ApiResponse;
@@ -45,7 +46,7 @@ public class DevicesResourceIT extends AbstractRestIT {
public void putWithUUIDShouldCreateAfterDelete() throws IOException {
Entity payload = new Entity().chainPut("name", "foo");
- UUID uuid = UUID.randomUUID();
+ UUID uuid = UUIDGenerator.newTimeUUID();
CollectionEndpoint devicesResource =this.app().collection("devices");
http://git-wip-us.apache.org/repos/asf/usergrid/blob/75d2254e/stack/tools/src/main/java/org/apache/usergrid/tools/UniqueValueScanner.java
----------------------------------------------------------------------
diff --git a/stack/tools/src/main/java/org/apache/usergrid/tools/UniqueValueScanner.java b/stack/tools/src/main/java/org/apache/usergrid/tools/UniqueValueScanner.java
index f884a1d..bdebd01 100644
--- a/stack/tools/src/main/java/org/apache/usergrid/tools/UniqueValueScanner.java
+++ b/stack/tools/src/main/java/org/apache/usergrid/tools/UniqueValueScanner.java
@@ -21,13 +21,11 @@ import java.util.Collections;
import java.util.Iterator;
import java.util.UUID;
-import com.google.common.base.Optional;
import com.netflix.astyanax.connectionpool.exceptions.ConnectionException;
import com.netflix.astyanax.model.Column;
import com.netflix.astyanax.util.RangeBuilder;
import org.apache.usergrid.persistence.Entity;
import org.apache.usergrid.persistence.EntityManager;
-import org.apache.usergrid.persistence.collection.MvccEntity;
import org.apache.usergrid.persistence.collection.serialization.MvccEntitySerializationStrategy;
import org.apache.usergrid.persistence.collection.serialization.UniqueValueSerializationStrategy;
import org.apache.usergrid.persistence.collection.serialization.UniqueValueSet;
@@ -60,6 +58,9 @@ public class UniqueValueScanner extends ToolBase {
private static final String ENTITY_NAME_ARG = "entityName";
+ private static final String ENTITY_FIELD_TYPE_ARG = "fieldType";
+
+
//copied shamelessly from unique value serialization strat.
private static final ScopedRowKeySerializer<TypeField> ROW_KEY_SER =
@@ -100,11 +101,16 @@ public class UniqueValueScanner extends ToolBase {
options.addOption( collectionOption );
Option specificEntityNameOption =
- OptionBuilder.withArgName(ENTITY_NAME_ARG).hasArg().isRequired( true ).withDescription( "specific entity name" )
+ OptionBuilder.withArgName(ENTITY_NAME_ARG).hasArg().isRequired( false ).withDescription( "specific entity name" )
.create(ENTITY_NAME_ARG);
options.addOption( specificEntityNameOption );
+ Option fieldTypeOption =
+ OptionBuilder.withArgName(ENTITY_FIELD_TYPE_ARG).hasArg().isRequired( false ).withDescription( "field type" )
+ .create(ENTITY_FIELD_TYPE_ARG);
+
+ options.addOption( fieldTypeOption );
return options;
}
@@ -126,14 +132,15 @@ public class UniqueValueScanner extends ToolBase {
appToFilter = UUID.fromString(line.getOptionValue(APPLICATION_ARG));
}
+ logger.info("Staring Tool: UniqueValueScanner");
- logger.info("Starting entity unique scanner");
keyspace = injector.getInstance(com.netflix.astyanax.Keyspace.class);
mvccEntitySerializationStrategy = injector.getInstance(MvccEntitySerializationStrategy.class);
uniqueValueSerializationStrategy = injector.getInstance(UniqueValueSerializationStrategy.class);
-
+ String fieldType =
+ line.getOptionValue(ENTITY_FIELD_TYPE_ARG) != null ? line.getOptionValue(ENTITY_FIELD_TYPE_ARG) : "name" ;
String entityType = line.getOptionValue(ENTITY_TYPE_ARG);
String entityName = line.getOptionValue(ENTITY_NAME_ARG);
@@ -149,16 +156,40 @@ public class UniqueValueScanner extends ToolBase {
"collection name).");
}
+ logger.info("Running entity unique load only");
+
+
//do stuff
UniqueValueSet uniqueValueSet = uniqueValueSerializationStrategy.load(
new ApplicationScopeImpl( new SimpleId(appToFilter, "application" ) ),
entityType,
- Collections.singletonList(new StringField( "name", entityName) ));
+ Collections.singletonList(new StringField( fieldType, entityName) ));
+
+ StringBuilder stringBuilder = new StringBuilder();
+
+ stringBuilder.append("[");
- logger.info("Returned unique value set from serialization load = {}", uniqueValueSet);
+ uniqueValueSet.forEach( uniqueValue -> {
+
+
+ String entry = "fieldName="+uniqueValue.getField().getName()+
+ ", fieldValue="+uniqueValue.getField().getValue()+
+ ", uuid="+uniqueValue.getEntityId().getUuid()+
+ ", type="+uniqueValue.getEntityId().getType()+
+ ", version="+uniqueValue.getEntityVersion();
+ stringBuilder.append("{").append(entry).append("},");
+ });
+
+ stringBuilder.deleteCharAt(stringBuilder.length() -1);
+ stringBuilder.append("]");
+
+ logger.info("Returned unique value set from serialization load = {}", stringBuilder.toString());
} else {
+ logger.info("Running entity unique scanner only");
+
+
// scan through all unique values and log some info
Iterator<com.netflix.astyanax.model.Row<ScopedRowKey<TypeField>, EntityVersion>> rows = null;
@@ -181,7 +212,7 @@ public class UniqueValueScanner extends ToolBase {
String scopeType = row.getKey().getScope().getType();
UUID scopeUUID = row.getKey().getScope().getUuid();
- if (!fieldName.equalsIgnoreCase("name") ||
+ if (!fieldName.equalsIgnoreCase(fieldType) ||
(finalAppToFilter != null && !finalAppToFilter.equals(scopeUUID))
) {
// do nothing
[07/11] usergrid git commit: Fix some comments.
Posted by mr...@apache.org.
Fix some comments.
Project: http://git-wip-us.apache.org/repos/asf/usergrid/repo
Commit: http://git-wip-us.apache.org/repos/asf/usergrid/commit/e24ea20d
Tree: http://git-wip-us.apache.org/repos/asf/usergrid/tree/e24ea20d
Diff: http://git-wip-us.apache.org/repos/asf/usergrid/diff/e24ea20d
Branch: refs/heads/release-2.1.1
Commit: e24ea20d7bd0a83b34577470e28327dccd174f66
Parents: 70f50c2
Author: Michael Russo <mr...@apigee.com>
Authored: Wed Jun 22 22:42:43 2016 -0700
Committer: Michael Russo <mr...@apigee.com>
Committed: Wed Jun 22 22:42:43 2016 -0700
----------------------------------------------------------------------
.../serialization/impl/UniqueValueSerializationStrategyImpl.java | 4 ++--
1 file changed, 2 insertions(+), 2 deletions(-)
----------------------------------------------------------------------
http://git-wip-us.apache.org/repos/asf/usergrid/blob/e24ea20d/stack/corepersistence/collection/src/main/java/org/apache/usergrid/persistence/collection/serialization/impl/UniqueValueSerializationStrategyImpl.java
----------------------------------------------------------------------
diff --git a/stack/corepersistence/collection/src/main/java/org/apache/usergrid/persistence/collection/serialization/impl/UniqueValueSerializationStrategyImpl.java b/stack/corepersistence/collection/src/main/java/org/apache/usergrid/persistence/collection/serialization/impl/UniqueValueSerializationStrategyImpl.java
index 2a53194..8a41bff 100644
--- a/stack/corepersistence/collection/src/main/java/org/apache/usergrid/persistence/collection/serialization/impl/UniqueValueSerializationStrategyImpl.java
+++ b/stack/corepersistence/collection/src/main/java/org/apache/usergrid/persistence/collection/serialization/impl/UniqueValueSerializationStrategyImpl.java
@@ -338,12 +338,14 @@ public abstract class UniqueValueSerializationStrategyImpl<FieldKey, EntityKey>
candidate.getEntityId().getUuid(), candidate.getEntityVersion() );
delete(appScope, candidate ).execute();
+
} catch (ConnectionException e) {
// do nothing for now
}
});
+ // clear the transient candidates list
candidates.clear();
if(logger.isTraceEnabled()) {
@@ -355,8 +357,6 @@ public abstract class UniqueValueSerializationStrategyImpl<FieldKey, EntityKey>
// add our new candidate to the list
candidates.add(uniqueValue);
- // add our new candidate to the result set
- //uniqueValueSet.addValue(candidate);
}else{
[11/11] usergrid git commit: Merge commit 'refs/pull/540/head' of
github.com:apache/usergrid into release-2.1.1
Posted by mr...@apache.org.
Merge commit 'refs/pull/540/head' of github.com:apache/usergrid into release-2.1.1
Project: http://git-wip-us.apache.org/repos/asf/usergrid/repo
Commit: http://git-wip-us.apache.org/repos/asf/usergrid/commit/57494925
Tree: http://git-wip-us.apache.org/repos/asf/usergrid/tree/57494925
Diff: http://git-wip-us.apache.org/repos/asf/usergrid/diff/57494925
Branch: refs/heads/release-2.1.1
Commit: 57494925989bcd6cc10f09af5d16b6af18d0e707
Parents: cf4c7f8 7f49c80
Author: Michael Russo <mr...@apigee.com>
Authored: Thu Jun 23 15:25:49 2016 -0700
Committer: Michael Russo <mr...@apigee.com>
Committed: Thu Jun 23 15:25:49 2016 -0700
----------------------------------------------------------------------
.../corepersistence/CpRelationManager.java | 32 +++++---
.../usergrid/rest/management/AdminUsersIT.java | 80 ++++++++++++++++++++
.../cassandra/ManagementServiceImpl.java | 33 +++++---
.../services/devices/DevicesService.java | 2 +
4 files changed, 126 insertions(+), 21 deletions(-)
----------------------------------------------------------------------
[03/11] usergrid git commit: Fixes for linked collections
Posted by mr...@apache.org.
Fixes for linked collections
Project: http://git-wip-us.apache.org/repos/asf/usergrid/repo
Commit: http://git-wip-us.apache.org/repos/asf/usergrid/commit/7f49c806
Tree: http://git-wip-us.apache.org/repos/asf/usergrid/tree/7f49c806
Diff: http://git-wip-us.apache.org/repos/asf/usergrid/diff/7f49c806
Branch: refs/heads/release-2.1.1
Commit: 7f49c8068ab68ab440d3c2e430cb69f68befc53e
Parents: 9efa3b4
Author: Mike Dunker <md...@apigee.com>
Authored: Wed Jun 22 13:41:12 2016 -0700
Committer: Mike Dunker <md...@apigee.com>
Committed: Wed Jun 22 13:41:12 2016 -0700
----------------------------------------------------------------------
.../corepersistence/CpRelationManager.java | 32 +++++---
.../usergrid/rest/management/AdminUsersIT.java | 80 ++++++++++++++++++++
.../cassandra/ManagementServiceImpl.java | 33 +++++---
.../services/devices/DevicesService.java | 2 +
4 files changed, 126 insertions(+), 21 deletions(-)
----------------------------------------------------------------------
http://git-wip-us.apache.org/repos/asf/usergrid/blob/7f49c806/stack/core/src/main/java/org/apache/usergrid/corepersistence/CpRelationManager.java
----------------------------------------------------------------------
diff --git a/stack/core/src/main/java/org/apache/usergrid/corepersistence/CpRelationManager.java b/stack/core/src/main/java/org/apache/usergrid/corepersistence/CpRelationManager.java
index 4082b45..39b3161 100644
--- a/stack/core/src/main/java/org/apache/usergrid/corepersistence/CpRelationManager.java
+++ b/stack/core/src/main/java/org/apache/usergrid/corepersistence/CpRelationManager.java
@@ -501,9 +501,9 @@ public class CpRelationManager implements RelationManager {
@Override
public void removeFromCollection( String collectionName, EntityRef itemRef ) throws Exception {
- // special handling for roles collection of the application
if ( headEntity.getUuid().equals( applicationId ) ) {
if ( collectionName.equals( COLLECTION_ROLES ) ) {
+ // special handling for roles collection of the application
Entity itemEntity = em.get( itemRef );
if ( itemEntity != null ) {
RoleRef roleRef = SimpleRoleRef.forRoleEntity( itemEntity );
@@ -511,12 +511,12 @@ public class CpRelationManager implements RelationManager {
return;
}
}
+ // handles normal app collection deletes
em.delete( itemRef );
return;
}
- // load the entity to be removed to the collection
-
+ // headEntity is not an application (used for management entities and entity collections like user devices)
if ( logger.isDebugEnabled() ) {
logger.debug( "Loading entity to remove from collection {}:{} from app {}\n",
@@ -531,12 +531,26 @@ public class CpRelationManager implements RelationManager {
GraphManager gm = managerCache.getGraphManager( applicationScope );
+ List<Edge> removedEdges = new ArrayList<>();
//run our delete
gm.loadEdgeVersions(
CpNamingUtils.createEdgeFromCollectionName( cpHeadEntity.getId(), collectionName, memberEntity.getId() ) )
- .flatMap(edge -> gm.markEdge(edge)).flatMap(edge -> gm.deleteEdge(edge)).toBlocking()
+ .flatMap(edge -> gm.markEdge(edge)).flatMap(edge -> gm.deleteEdge(edge))
+ .doOnNext(edge -> removedEdges.add(edge)).toBlocking()
.lastOrDefault(null);
+ CollectionInfo collection = getDefaultSchema().getCollection( headEntity.getType(), collectionName );
+ if (collection != null && collection.getLinkedCollection() != null) {
+ // delete reverse edges
+ final String pluralType = InflectionUtils.pluralize( cpHeadEntity.getId().getType() );
+ gm.loadEdgeVersions(
+ CpNamingUtils.createEdgeFromCollectionName( memberEntity.getId(), pluralType, cpHeadEntity.getId() ) )
+ .flatMap(reverseEdge -> gm.markEdge(reverseEdge))
+ .flatMap(reverseEdge -> gm.deleteEdge(reverseEdge))
+ .doOnNext(reverseEdge -> removedEdges.add(reverseEdge))
+ .toBlocking().lastOrDefault(null);
+ }
+
/**
* Remove from the index
@@ -544,12 +558,10 @@ public class CpRelationManager implements RelationManager {
*/
- //TODO: this should not happen here, needs to go to SQS
- //indexProducer.put(batch).subscribe();
- if ( !skipIndexingForType( memberEntity.getId().getType() ) ) {
-
- indexService.queueEntityDelete(applicationScope, memberEntity.getId());
- }
+ // item not deindexed, only edges
+ removedEdges.forEach(edge -> {
+ indexService.queueDeleteEdge(applicationScope, edge);
+ });
// special handling for roles collection of a group
if ( headEntity.getType().equals( Group.ENTITY_TYPE ) ) {
http://git-wip-us.apache.org/repos/asf/usergrid/blob/7f49c806/stack/rest/src/test/java/org/apache/usergrid/rest/management/AdminUsersIT.java
----------------------------------------------------------------------
diff --git a/stack/rest/src/test/java/org/apache/usergrid/rest/management/AdminUsersIT.java b/stack/rest/src/test/java/org/apache/usergrid/rest/management/AdminUsersIT.java
index 07132cb..3adc719 100644
--- a/stack/rest/src/test/java/org/apache/usergrid/rest/management/AdminUsersIT.java
+++ b/stack/rest/src/test/java/org/apache/usergrid/rest/management/AdminUsersIT.java
@@ -435,6 +435,7 @@ public class AdminUsersIT extends AbstractRestIT {
//Add a property to management user
Entity userProperty = new Entity( ).chainPut( "company","usergrid" );
management().users().user( newOrg.getUsername() ).put( userProperty );
+ fail("Should not have been allowed");
} catch( NotAuthorizedException e ){
@@ -445,6 +446,85 @@ public class AdminUsersIT extends AbstractRestIT {
}
+ @Test
+ public void testAdminRemovalFromOrg() throws Exception {
+ Organization newOrg = createOrgPayload( "testAdminRemovalFromOrg", null );
+ Organization orgReturned = clientSetup.getRestClient().management().orgs().post(newOrg);
+ User owner = orgReturned.getOwner();
+ assertNotNull(owner);
+ String orgName = orgReturned.getName();
+ Token ownerToken = management.token().get(owner.getUsername(), orgName);
+
+ // add a new admin user to the org
+ Entity adminUserPayload = new Entity();
+ String newAdminUserName = "newAdminUser"+UUIDUtils.newTimeUUID();
+ adminUserPayload.put( "username", newAdminUserName );
+ adminUserPayload.put( "name", newAdminUserName );
+ adminUserPayload.put( "email", newAdminUserName+"@usergrid.com" );
+ adminUserPayload.put( "password", newAdminUserName );
+
+ management.token().setToken(ownerToken);
+ management.orgs().org(orgName).users().post(User.class, adminUserPayload);
+
+ // get token of the new admin user
+ Token adminToken = management.token().get(newAdminUserName, newAdminUserName);
+ assertNotNull(adminToken);
+
+ // get org info
+ try {
+ management.token().setToken(adminToken);
+ management.orgs().org(orgName).get();
+ }
+ catch (Exception e) {
+ // should have been allowed
+ fail("Should have worked: " + e.getMessage());
+ }
+
+ // remove access
+ try {
+ management.token().setToken(ownerToken);
+ management.orgs().org(orgName).users().user(newAdminUserName).delete();
+ }
+ catch (Exception e) {
+ // should have been allowed
+ fail("Should have worked: " + e.getMessage());
+ }
+
+ // get org info (should be unsuccessful)
+ try {
+ management.token().setToken(adminToken);
+ management.orgs().org(orgName).get();
+ fail("Should not have allowed org access");
+ }
+ catch (NotAuthorizedException nae) {
+ // this is the right return
+
+ }
+ catch (Exception e) {
+ fail("Should have been unauthorized: " + e.getMessage());
+ }
+
+ // restore access
+ try {
+ management.token().setToken(ownerToken);
+ management.orgs().org(orgName).users().user(newAdminUserName).put(new Entity());
+ }
+ catch (Exception e) {
+ // should have been allowed
+ fail("Should have worked: " + e.getMessage());
+ }
+
+ // get org info
+ try {
+ management.token().setToken(adminToken);
+ management.orgs().org(orgName).get();
+ }
+ catch (Exception e) {
+ // should have been allowed
+ fail("Should have worked: " + e.getMessage());
+ }
+
+ }
/**
http://git-wip-us.apache.org/repos/asf/usergrid/blob/7f49c806/stack/services/src/main/java/org/apache/usergrid/management/cassandra/ManagementServiceImpl.java
----------------------------------------------------------------------
diff --git a/stack/services/src/main/java/org/apache/usergrid/management/cassandra/ManagementServiceImpl.java b/stack/services/src/main/java/org/apache/usergrid/management/cassandra/ManagementServiceImpl.java
index 73a56c8..b56f211 100644
--- a/stack/services/src/main/java/org/apache/usergrid/management/cassandra/ManagementServiceImpl.java
+++ b/stack/services/src/main/java/org/apache/usergrid/management/cassandra/ManagementServiceImpl.java
@@ -1580,7 +1580,8 @@ public class ManagementServiceImpl implements ManagementService {
BiMap<UUID, String> organizations = HashBiMap.create();
EntityManager em = emf.getEntityManager( smf.getManagementAppId() );
- Results results = em.getCollection( new SimpleEntityRef( User.ENTITY_TYPE, userId ),
+ EntityRef userRef = new SimpleEntityRef(User.ENTITY_TYPE, userId);
+ Results results = em.getCollection( userRef,
Schema.COLLECTION_GROUPS, null, 1000, Level.ALL_PROPERTIES, false );
do {
@@ -1592,10 +1593,17 @@ public class ManagementServiceImpl implements ManagementService {
path = path.toLowerCase();
}
- try {
- organizations.put( entity.getUuid(), path );
- } catch (IllegalArgumentException e) {
- logger.warn("Error adding {}:{} to BiMap: {}", entity.getUuid(), path, e.getMessage() );
+ // check that user is in users collection for org
+ EntityRef groupRef = new SimpleEntityRef(Group.ENTITY_TYPE, entity.getUuid());
+ if (em.isCollectionMember(groupRef, Schema.COLLECTION_USERS, userRef)) {
+ try {
+ organizations.put(entity.getUuid(), path);
+ } catch (IllegalArgumentException e) {
+ logger.warn("Error adding {}:{} to BiMap: {}", entity.getUuid(), path, e.getMessage());
+ }
+ } else {
+ // org doesn't know about user, so read repair
+ em.removeFromCollection(userRef, Schema.COLLECTION_GROUPS, groupRef);
}
}
@@ -1698,16 +1706,18 @@ public class ManagementServiceImpl implements ManagementService {
EntityManager em = emf.getEntityManager( smf.getManagementAppId() );
+ EntityRef orgRef = new SimpleEntityRef( Group.ENTITY_TYPE, organization.getUuid() );
+ EntityRef userRef = new SimpleEntityRef( User.ENTITY_TYPE, user.getUuid() );
+
- if(em.getCollection(organization.getUuid() ,"users",Query.fromQL( "select * where uuid ="+user.getUuid() ),Level.IDS ).size() >0){
+ if(em.isCollectionMember(orgRef, Schema.COLLECTION_USERS, userRef)) {
if(logger.isDebugEnabled()) {
logger.debug( "addAdminUserToOrganization - Found value: {} already in collection", user.getName() );
}
return;
}
- em.addToCollection(new SimpleEntityRef(Group.ENTITY_TYPE, organization.getUuid()), "users",
- new SimpleEntityRef(User.ENTITY_TYPE, user.getUuid()));
+ em.addToCollection(orgRef, Schema.COLLECTION_USERS, userRef);
invalidateManagementAppAuthCache();
@@ -1733,10 +1743,11 @@ public class ManagementServiceImpl implements ManagementService {
EntityManager em = emf.getEntityManager( smf.getManagementAppId() );
try {
- int size = em.getCollection( new SimpleEntityRef( Group.ENTITY_TYPE, organizationId ),
- "users", null, 2, Level.IDS, false ).size();
+ Results collection = em.getCollection( new SimpleEntityRef( Group.ENTITY_TYPE, organizationId ),
+ "users", null, 2, Level.IDS, false );
+ int size = collection.size();
- if ( !force && size <= 1 ) {
+ if ( !force && (size == 0 || (size == 1 && collection.getId() == userId))) {
throw new Exception();
}
}
http://git-wip-us.apache.org/repos/asf/usergrid/blob/7f49c806/stack/services/src/main/java/org/apache/usergrid/services/devices/DevicesService.java
----------------------------------------------------------------------
diff --git a/stack/services/src/main/java/org/apache/usergrid/services/devices/DevicesService.java b/stack/services/src/main/java/org/apache/usergrid/services/devices/DevicesService.java
index f57a03a..111c96a 100644
--- a/stack/services/src/main/java/org/apache/usergrid/services/devices/DevicesService.java
+++ b/stack/services/src/main/java/org/apache/usergrid/services/devices/DevicesService.java
@@ -85,6 +85,8 @@ public class DevicesService extends AbstractCollectionService {
for (EntityRef userDevice : userDevices) {
if(userDevice.getUuid().equals(deviceRef.getUuid())) { //only remove the current device from user
em.removeFromCollection(user, "devices", userDevice);
+ // TODO: may want to actually remove the device
+ // em.delete(userDevice);
}
}
em.removeFromCollection(deviceRef, "users", user);
[08/11] usergrid git commit: Fix log statement to use .trace()
Posted by mr...@apache.org.
Fix log statement to use .trace()
Project: http://git-wip-us.apache.org/repos/asf/usergrid/repo
Commit: http://git-wip-us.apache.org/repos/asf/usergrid/commit/b6b01324
Tree: http://git-wip-us.apache.org/repos/asf/usergrid/tree/b6b01324
Diff: http://git-wip-us.apache.org/repos/asf/usergrid/diff/b6b01324
Branch: refs/heads/release-2.1.1
Commit: b6b013240a3838ce0aa786ece3c20b916bc7af01
Parents: e24ea20
Author: Michael Russo <mr...@apigee.com>
Authored: Wed Jun 22 23:04:58 2016 -0700
Committer: Michael Russo <mr...@apigee.com>
Committed: Wed Jun 22 23:04:58 2016 -0700
----------------------------------------------------------------------
.../serialization/impl/UniqueValueSerializationStrategyImpl.java | 2 +-
1 file changed, 1 insertion(+), 1 deletion(-)
----------------------------------------------------------------------
http://git-wip-us.apache.org/repos/asf/usergrid/blob/b6b01324/stack/corepersistence/collection/src/main/java/org/apache/usergrid/persistence/collection/serialization/impl/UniqueValueSerializationStrategyImpl.java
----------------------------------------------------------------------
diff --git a/stack/corepersistence/collection/src/main/java/org/apache/usergrid/persistence/collection/serialization/impl/UniqueValueSerializationStrategyImpl.java b/stack/corepersistence/collection/src/main/java/org/apache/usergrid/persistence/collection/serialization/impl/UniqueValueSerializationStrategyImpl.java
index 8a41bff..bf7d2fc 100644
--- a/stack/corepersistence/collection/src/main/java/org/apache/usergrid/persistence/collection/serialization/impl/UniqueValueSerializationStrategyImpl.java
+++ b/stack/corepersistence/collection/src/main/java/org/apache/usergrid/persistence/collection/serialization/impl/UniqueValueSerializationStrategyImpl.java
@@ -349,7 +349,7 @@ public abstract class UniqueValueSerializationStrategyImpl<FieldKey, EntityKey>
candidates.clear();
if(logger.isTraceEnabled()) {
- logger.info("Updating candidate to entity id [{}] and entity version [{}]",
+ logger.trace("Updating candidate to entity id [{}] and entity version [{}]",
uniqueValue.getEntityId().getUuid(), uniqueValue.getEntityVersion());
}
[02/11] usergrid git commit: Allow tools to always be built,
but skip its tests for now. Also fix issue with tools ability to have
custom properties set in ToolBase or command line execution.
Posted by mr...@apache.org.
Allow tools to always be built, but skip its tests for now. Also fix issue with tools ability to have custom properties set in ToolBase or command line execution.
Project: http://git-wip-us.apache.org/repos/asf/usergrid/repo
Commit: http://git-wip-us.apache.org/repos/asf/usergrid/commit/1997b579
Tree: http://git-wip-us.apache.org/repos/asf/usergrid/tree/1997b579
Diff: http://git-wip-us.apache.org/repos/asf/usergrid/diff/1997b579
Branch: refs/heads/release-2.1.1
Commit: 1997b579cc780ef169c34d296dec953c91d2c4c5
Parents: 06f77d7
Author: Michael Russo <mr...@apigee.com>
Authored: Fri Jun 3 13:29:34 2016 -0700
Committer: Michael Russo <mr...@apigee.com>
Committed: Tue Jun 21 14:30:00 2016 -0700
----------------------------------------------------------------------
stack/pom.xml | 2 --
stack/tools/pom.xml | 1 +
.../org/apache/usergrid/tools/ToolBase.java | 28 ++++++++++++++++++--
.../main/resources/toolsApplicationContext.xml | 7 +++++
4 files changed, 34 insertions(+), 4 deletions(-)
----------------------------------------------------------------------
http://git-wip-us.apache.org/repos/asf/usergrid/blob/1997b579/stack/pom.xml
----------------------------------------------------------------------
diff --git a/stack/pom.xml b/stack/pom.xml
index a94233e..dd35891 100644
--- a/stack/pom.xml
+++ b/stack/pom.xml
@@ -195,9 +195,7 @@
<module>core</module>
<module>services</module>
<module>rest</module>
- <!-- Tools should be built separately
<module>tools</module>
- -->
<!--
<module>websocket</module>
-->
http://git-wip-us.apache.org/repos/asf/usergrid/blob/1997b579/stack/tools/pom.xml
----------------------------------------------------------------------
diff --git a/stack/tools/pom.xml b/stack/tools/pom.xml
index 2d6e7a2..06691de 100644
--- a/stack/tools/pom.xml
+++ b/stack/tools/pom.xml
@@ -65,6 +65,7 @@
<groupId>org.apache.maven.plugins</groupId>
<artifactId>maven-surefire-plugin</artifactId>
<configuration>
+ <skipTests>true</skipTests>
<systemPropertyVariables>
<storage-config>${basedir}/src/test/conf</storage-config>
</systemPropertyVariables>
http://git-wip-us.apache.org/repos/asf/usergrid/blob/1997b579/stack/tools/src/main/java/org/apache/usergrid/tools/ToolBase.java
----------------------------------------------------------------------
diff --git a/stack/tools/src/main/java/org/apache/usergrid/tools/ToolBase.java b/stack/tools/src/main/java/org/apache/usergrid/tools/ToolBase.java
index bd8686e..e82e5f8 100644
--- a/stack/tools/src/main/java/org/apache/usergrid/tools/ToolBase.java
+++ b/stack/tools/src/main/java/org/apache/usergrid/tools/ToolBase.java
@@ -17,6 +17,7 @@
package org.apache.usergrid.tools;
+import com.google.inject.Injector;
import me.prettyprint.hector.testutils.EmbeddedServerHelper;
import org.apache.commons.cli.*;
import org.apache.commons.lang.ClassUtils;
@@ -69,6 +70,10 @@ public abstract class ToolBase {
protected CassandraService cass;
+ protected Injector injector;
+
+
+
public void startTool( String[] args ) {
startTool( args, true );
@@ -88,6 +93,15 @@ public abstract class ToolBase {
return;
}
+ // notification queue listener not needed for tools
+ System.setProperty("usergrid.notifications.listener.run", "false");
+ System.setProperty("usergrid.push.worker_count", "0");
+
+ //job scheduler also not needed for tools
+ System.setProperty("usergrid.scheduler.enabled", "false");
+
+
+
if ( line.hasOption( "host" ) ) {
System.setProperty( "cassandra.url", line.getOptionValue( "host" ) );
System.setProperty( "elasticsearch.hosts", line.getOptionValue( "eshost" ) );
@@ -178,6 +192,10 @@ public abstract class ToolBase {
assertNotNull( emf );
assertTrue( "EntityManagerFactory is instance of EntityManagerFactory",
emf instanceof EntityManagerFactory );
+
+ injector = ac.getBean( Injector.class );
+
+
}
@@ -256,7 +274,10 @@ public abstract class ToolBase {
" cassandra.keyspace.application: {}\n" +
" cassandra.lock.keyspace: {}\n" +
" cassandra.keyspace.replication: {}\n" +
- " cassandra.connections: {}\n",
+ " cassandra.connections: {}\n" +
+ " usergrid.notifications.listener.run: {}\n" +
+ " usergrid.push.worker_count: {}\n" +
+ " usergrid.scheduler.enabled: {}\n",
properties.get("cassandra.url"),
properties.get("cassandra.datacenter.local"),
properties.get("cassandra.username"),
@@ -265,7 +286,10 @@ public abstract class ToolBase {
properties.get("cassandra.keyspace.application"),
properties.get("cassandra.lock.keyspace"),
properties.get("cassandra.keyspace.replication"),
- properties.get("cassandra.connections")
+ properties.get("cassandra.connections"),
+ properties.get("usergrid.notifications.listener.run"),
+ properties.get("usergrid.push.worker_count"),
+ properties.get("usergrid.scheduler.enabled")
);
}
http://git-wip-us.apache.org/repos/asf/usergrid/blob/1997b579/stack/tools/src/main/resources/toolsApplicationContext.xml
----------------------------------------------------------------------
diff --git a/stack/tools/src/main/resources/toolsApplicationContext.xml b/stack/tools/src/main/resources/toolsApplicationContext.xml
index 7e55893..f84501d 100644
--- a/stack/tools/src/main/resources/toolsApplicationContext.xml
+++ b/stack/tools/src/main/resources/toolsApplicationContext.xml
@@ -39,6 +39,8 @@
<bean id="properties"
class="org.springframework.beans.factory.config.PropertiesFactoryBean">
+ <property name="properties" ref="sysProps"/>
+ <property name="localOverride" value="true"/>
<property name="singleton" value="true" />
<property name="ignoreResourceNotFound" value="true" />
<property name="locations">
@@ -50,6 +52,11 @@
</property>
</bean>
+ <bean id="sysProps" class="org.springframework.beans.factory.config.MethodInvokingFactoryBean">
+ <property name="targetClass"><value>java.lang.System</value></property>
+ <property name="targetMethod"><value>getProperties</value></property>
+ </bean>
+
<bean id="propertyPlaceholderConfigurer"
class="org.springframework.beans.factory.config.PropertyPlaceholderConfigurer">
<property name="properties" ref="properties" />
[06/11] usergrid git commit: Better handle different combinations of
possible duplicate entities and their respective versions.
Posted by mr...@apache.org.
Better handle different combinations of possible duplicate entities and their respective versions.
Project: http://git-wip-us.apache.org/repos/asf/usergrid/repo
Commit: http://git-wip-us.apache.org/repos/asf/usergrid/commit/70f50c22
Tree: http://git-wip-us.apache.org/repos/asf/usergrid/tree/70f50c22
Diff: http://git-wip-us.apache.org/repos/asf/usergrid/diff/70f50c22
Branch: refs/heads/release-2.1.1
Commit: 70f50c22dfae76471713a6a01eae772b1b7bd9b6
Parents: 5c81a02
Author: Michael Russo <mr...@apigee.com>
Authored: Wed Jun 22 22:35:59 2016 -0700
Committer: Michael Russo <mr...@apigee.com>
Committed: Wed Jun 22 22:35:59 2016 -0700
----------------------------------------------------------------------
.../UniqueValueSerializationStrategyImpl.java | 116 +++++++++++++------
...niqueValueSerializationStrategyImplTest.java | 115 ++++++++++++++++++
2 files changed, 197 insertions(+), 34 deletions(-)
----------------------------------------------------------------------
http://git-wip-us.apache.org/repos/asf/usergrid/blob/70f50c22/stack/corepersistence/collection/src/main/java/org/apache/usergrid/persistence/collection/serialization/impl/UniqueValueSerializationStrategyImpl.java
----------------------------------------------------------------------
diff --git a/stack/corepersistence/collection/src/main/java/org/apache/usergrid/persistence/collection/serialization/impl/UniqueValueSerializationStrategyImpl.java b/stack/corepersistence/collection/src/main/java/org/apache/usergrid/persistence/collection/serialization/impl/UniqueValueSerializationStrategyImpl.java
index a323746..2a53194 100644
--- a/stack/corepersistence/collection/src/main/java/org/apache/usergrid/persistence/collection/serialization/impl/UniqueValueSerializationStrategyImpl.java
+++ b/stack/corepersistence/collection/src/main/java/org/apache/usergrid/persistence/collection/serialization/impl/UniqueValueSerializationStrategyImpl.java
@@ -71,6 +71,8 @@ public abstract class UniqueValueSerializationStrategyImpl<FieldKey, EntityKey>
public static final int COL_VALUE = 0x0;
+ private final Comparator<UniqueValue> uniqueValueComparator = new UniqueValueComparator();
+
private final SerializationFig serializationFig;
protected final Keyspace keyspace;
@@ -266,7 +268,7 @@ public abstract class UniqueValueSerializationStrategyImpl<FieldKey, EntityKey>
Iterator<Row<ScopedRowKey<FieldKey>, EntityVersion>> results =
keyspace.prepareQuery( CF_UNIQUE_VALUES ).setConsistencyLevel( consistencyLevel ).getKeySlice( keys )
- .withColumnRange(new RangeBuilder().setLimit(serializationFig.getBufferSize()).build())
+ .withColumnRange(new RangeBuilder().setLimit(serializationFig.getMaxLoadSize()).build())
.execute().getResult().iterator();
@@ -285,10 +287,8 @@ public abstract class UniqueValueSerializationStrategyImpl<FieldKey, EntityKey>
continue;
}
- // these used duplicate tracking and cleanup
- UUID oldestEntityUUID = null;
- UniqueValueImpl firstUniqueValue = null;
+ List<UniqueValue> candidates = new ArrayList<>();
/**
* While iterating the columns, a rule is being enforced to only EVER return the oldest UUID. This means
@@ -304,55 +304,77 @@ public abstract class UniqueValueSerializationStrategyImpl<FieldKey, EntityKey>
final EntityVersion entityVersion = columnList.next().getName();
- final UUID currentEntityUUID = entityVersion.getEntityId().getUuid();
- final UniqueValueImpl uniqueValue =
+ final UniqueValue uniqueValue =
new UniqueValueImpl(field, entityVersion.getEntityId(), entityVersion.getEntityVersion());
- // keep track of the first and oldest entity (not version),
- // knowing the the first one may not be the 'oldest'
- if(oldestEntityUUID == null){
+ // set the initial candidate and move on
+ if(candidates.size() == 0){
+ candidates.add(uniqueValue);
+ continue;
+ }
- oldestEntityUUID = currentEntityUUID;
- firstUniqueValue = uniqueValue;
+ final int result = uniqueValueComparator.compare(uniqueValue, candidates.get(candidates.size() -1));
- }else if(currentEntityUUID.timestamp() < oldestEntityUUID.timestamp()){
+ if(result == 0){
- oldestEntityUUID = currentEntityUUID;
- }
+ // do nothing, only versions can be newer and we're not worried about newer versions of same entity
+ if(logger.isTraceEnabled()){
+ logger.trace("Candidate unique value is equal to the current unique value");
+ }
+ // update candidate w/ latest version
+ candidates.add(uniqueValue);
- // only return the oldest (original) unique value entries
- if(currentEntityUUID.timestamp() <= oldestEntityUUID.timestamp() ){
+ }else if(result < 0){
- if (logger.isTraceEnabled()) {
- logger.trace("Putting unique value [{}={}] into result set with entity id [{}] and entity version [{}]",
- field.getName(), field.getValue().toString(),
- entityVersion.getEntityId(),
- entityVersion.getEntityVersion());
- }
+ // delete the duplicate from the unique value index
+ candidates.forEach(candidate -> {
- uniqueValueSet.addValue(uniqueValue);
+ try {
- }
- // remove the newer duplicated unique value entries
- else{
+ logger.warn("Duplicate unique value [{}={}] found, removing older entry " +
+ "with entity id [{}] and entity version [{}]", field.getName(), field.getValue().toString(),
+ candidate.getEntityId().getUuid(), candidate.getEntityVersion() );
- delete(appScope, uniqueValue ).execute();
+ delete(appScope, candidate ).execute();
+ } catch (ConnectionException e) {
+ // do nothing for now
+ }
- }
+ });
- }
+ candidates.clear();
+
+ if(logger.isTraceEnabled()) {
+ logger.info("Updating candidate to entity id [{}] and entity version [{}]",
+ uniqueValue.getEntityId().getUuid(), uniqueValue.getEntityVersion());
+
+ }
- // check to see if the very first unique value entry was overwritten because it was not the oldest
- // if so, clean up its unique index
- if( !uniqueValueSet.getValue( firstUniqueValue.getField().getName() )
- .getEntityId().getUuid().equals(firstUniqueValue.getEntityId().getUuid()) ){
+ // add our new candidate to the list
+ candidates.add(uniqueValue);
+
+ // add our new candidate to the result set
+ //uniqueValueSet.addValue(candidate);
+
+ }else{
+
+ logger.warn("Duplicate unique value [{}={}] found, removing newer entry " +
+ "with entity id [{}] and entity version [{}]", field.getName(), field.getValue().toString(),
+ uniqueValue.getEntityId().getUuid(), uniqueValue.getEntityVersion() );
+
+ // delete the duplicate from the unique value index
+ delete(appScope, uniqueValue ).execute();
+
+
+ }
- delete(appScope, firstUniqueValue).execute();
}
+ // take the last candidate ( should be the latest version) and add to the result set
+ uniqueValueSet.addValue(candidates.get(candidates.size() -1));
}
@@ -472,4 +494,30 @@ public abstract class UniqueValueSerializationStrategyImpl<FieldKey, EntityKey>
* @param uniqueValueId The uniqueValue
*/
protected abstract EntityKey createEntityUniqueLogKey(final Id applicationId, final Id uniqueValueId );
+
+
+
+ private class UniqueValueComparator implements Comparator<UniqueValue> {
+
+ @Override
+ public int compare(UniqueValue o1, UniqueValue o2) {
+
+ if( o1.getEntityId().getUuid().equals(o2.getEntityId().getUuid())){
+
+ return 0;
+
+ }else if( o1.getEntityId().getUuid().timestamp() < o2.getEntityId().getUuid().timestamp()){
+
+ return -1;
+
+ }
+
+ // if the UUIDs are not equal and o1's timestamp is not less than o2's timestamp,
+ // then o1 must be greater than o2
+ return 1;
+
+
+ }
+ }
+
}
http://git-wip-us.apache.org/repos/asf/usergrid/blob/70f50c22/stack/corepersistence/collection/src/test/java/org/apache/usergrid/persistence/collection/serialization/impl/UniqueValueSerializationStrategyImplTest.java
----------------------------------------------------------------------
diff --git a/stack/corepersistence/collection/src/test/java/org/apache/usergrid/persistence/collection/serialization/impl/UniqueValueSerializationStrategyImplTest.java b/stack/corepersistence/collection/src/test/java/org/apache/usergrid/persistence/collection/serialization/impl/UniqueValueSerializationStrategyImplTest.java
index 6c4e72b..ed3e42b 100644
--- a/stack/corepersistence/collection/src/test/java/org/apache/usergrid/persistence/collection/serialization/impl/UniqueValueSerializationStrategyImplTest.java
+++ b/stack/corepersistence/collection/src/test/java/org/apache/usergrid/persistence/collection/serialization/impl/UniqueValueSerializationStrategyImplTest.java
@@ -442,4 +442,119 @@ public abstract class UniqueValueSerializationStrategyImplTest {
}
+ @Test
+ public void testDuplicateEntitiesDescending() throws ConnectionException, InterruptedException {
+
+ ApplicationScope scope =
+ new ApplicationScopeImpl( new SimpleId( "organization" ) );
+
+ IntegerField field = new IntegerField( "count", 5 );
+ Id entityId1 = new SimpleId( UUIDGenerator.newTimeUUID(), "entity" );
+ Id entityId2 = new SimpleId( UUIDGenerator.newTimeUUID(), "entity" );
+ Id entityId3 = new SimpleId( UUIDGenerator.newTimeUUID(), "entity" );
+
+
+
+ UUID version1 = UUIDGenerator.newTimeUUID();
+ UUID version2 = UUIDGenerator.newTimeUUID();
+ UUID version3 = UUIDGenerator.newTimeUUID();
+
+ UniqueValue stored1 = new UniqueValueImpl( field, entityId3, version1 );
+ UniqueValue stored2 = new UniqueValueImpl( field, entityId2, version2 );
+ UniqueValue stored3 = new UniqueValueImpl( field, entityId1, version3 );
+
+
+ strategy.write( scope, stored1 ).execute();
+ strategy.write( scope, stored2 ).execute();
+ strategy.write( scope, stored3 ).execute();
+
+
+ // load descending to get the older version of entity for this unique value
+ UniqueValueSet fields = strategy.load( scope, entityId1.getType(), Collections.<Field>singleton( field ));
+
+ UniqueValue retrieved = fields.getValue( field.getName() );
+ assertEquals( stored3, retrieved );
+
+
+ }
+
+ @Test
+ public void testDuplicateEntitiesAscending() throws ConnectionException, InterruptedException {
+
+ ApplicationScope scope =
+ new ApplicationScopeImpl( new SimpleId( "organization" ) );
+
+ IntegerField field = new IntegerField( "count", 5 );
+ Id entityId1 = new SimpleId( UUIDGenerator.newTimeUUID(), "entity" );
+ Id entityId2 = new SimpleId( UUIDGenerator.newTimeUUID(), "entity" );
+ Id entityId3 = new SimpleId( UUIDGenerator.newTimeUUID(), "entity" );
+
+
+
+ UUID version1 = UUIDGenerator.newTimeUUID();
+ UUID version2 = UUIDGenerator.newTimeUUID();
+ UUID version3 = UUIDGenerator.newTimeUUID();
+
+ UniqueValue stored1 = new UniqueValueImpl( field, entityId1, version1 );
+ UniqueValue stored2 = new UniqueValueImpl( field, entityId2, version2 );
+ UniqueValue stored3 = new UniqueValueImpl( field, entityId3, version3 );
+
+
+ strategy.write( scope, stored1 ).execute();
+ strategy.write( scope, stored2 ).execute();
+ strategy.write( scope, stored3 ).execute();
+
+
+ // load descending to get the older version of entity for this unique value
+ UniqueValueSet fields = strategy.load( scope, entityId1.getType(), Collections.<Field>singleton( field ));
+
+ UniqueValue retrieved = fields.getValue( field.getName() );
+ assertEquals( stored1, retrieved );
+
+
+ }
+
+ @Test
+ public void testMixedDuplicates() throws ConnectionException, InterruptedException {
+
+ ApplicationScope scope =
+ new ApplicationScopeImpl( new SimpleId( "organization" ) );
+
+ IntegerField field = new IntegerField( "count", 5 );
+ Id entityId1 = new SimpleId( UUIDGenerator.newTimeUUID(), "entity" );
+ Id entityId2 = new SimpleId( UUIDGenerator.newTimeUUID(), "entity" );
+ Id entityId3 = new SimpleId( UUIDGenerator.newTimeUUID(), "entity" );
+
+
+
+ UUID version1 = UUIDGenerator.newTimeUUID();
+ UUID version2 = UUIDGenerator.newTimeUUID();
+ UUID version3 = UUIDGenerator.newTimeUUID();
+ UUID version4 = UUIDGenerator.newTimeUUID();
+ UUID version5 = UUIDGenerator.newTimeUUID();
+
+ UniqueValue stored1 = new UniqueValueImpl( field, entityId1, version5 );
+ UniqueValue stored2 = new UniqueValueImpl( field, entityId2, version4 );
+ UniqueValue stored3 = new UniqueValueImpl( field, entityId1, version3 );
+ UniqueValue stored4 = new UniqueValueImpl( field, entityId3, version2 );
+ UniqueValue stored5 = new UniqueValueImpl( field, entityId3, version1 );
+
+
+
+ strategy.write( scope, stored1 ).execute();
+ strategy.write( scope, stored2 ).execute();
+ strategy.write( scope, stored3 ).execute();
+ strategy.write( scope, stored4 ).execute();
+ strategy.write( scope, stored5 ).execute();
+
+
+ // load descending to get the older version of entity for this unique value
+ UniqueValueSet fields = strategy.load( scope, entityId1.getType(), Collections.<Field>singleton( field ));
+
+ UniqueValue retrieved = fields.getValue( field.getName() );
+ assertEquals( stored1, retrieved );
+
+
+ }
+
}
[09/11] usergrid git commit: Add additional logging around batch
entity creation.
Posted by mr...@apache.org.
Add additional logging around batch entity creation.
Project: http://git-wip-us.apache.org/repos/asf/usergrid/repo
Commit: http://git-wip-us.apache.org/repos/asf/usergrid/commit/20ae3824
Tree: http://git-wip-us.apache.org/repos/asf/usergrid/tree/20ae3824
Diff: http://git-wip-us.apache.org/repos/asf/usergrid/diff/20ae3824
Branch: refs/heads/release-2.1.1
Commit: 20ae3824b67f291b9b4dd065bf83c8eefc3bb408
Parents: b6b0132
Author: Michael Russo <mr...@apigee.com>
Authored: Thu Jun 23 11:25:00 2016 -0700
Committer: Michael Russo <mr...@apigee.com>
Committed: Thu Jun 23 11:25:00 2016 -0700
----------------------------------------------------------------------
.../graph/impl/GraphManagerImpl.java | 4 ++
.../services/AbstractCollectionService.java | 41 ++++++++++++--------
2 files changed, 28 insertions(+), 17 deletions(-)
----------------------------------------------------------------------
http://git-wip-us.apache.org/repos/asf/usergrid/blob/20ae3824/stack/corepersistence/graph/src/main/java/org/apache/usergrid/persistence/graph/impl/GraphManagerImpl.java
----------------------------------------------------------------------
diff --git a/stack/corepersistence/graph/src/main/java/org/apache/usergrid/persistence/graph/impl/GraphManagerImpl.java b/stack/corepersistence/graph/src/main/java/org/apache/usergrid/persistence/graph/impl/GraphManagerImpl.java
index e8761f8..5fcdcb4 100644
--- a/stack/corepersistence/graph/src/main/java/org/apache/usergrid/persistence/graph/impl/GraphManagerImpl.java
+++ b/stack/corepersistence/graph/src/main/java/org/apache/usergrid/persistence/graph/impl/GraphManagerImpl.java
@@ -483,6 +483,10 @@ public class GraphManagerImpl implements GraphManager {
return true;
}
+ if(logger.isTraceEnabled()){
+ logger.trace("Filtering edge {}", simpleMarkedEdge);
+ }
+
//if any one of these is true, we filter it
return !simpleMarkedEdge.isDeleted() && !simpleMarkedEdge.isSourceNodeDelete() && !simpleMarkedEdge.isTargetNodeDeleted();
});
http://git-wip-us.apache.org/repos/asf/usergrid/blob/20ae3824/stack/services/src/main/java/org/apache/usergrid/services/AbstractCollectionService.java
----------------------------------------------------------------------
diff --git a/stack/services/src/main/java/org/apache/usergrid/services/AbstractCollectionService.java b/stack/services/src/main/java/org/apache/usergrid/services/AbstractCollectionService.java
index 7b9e230..cbea659 100644
--- a/stack/services/src/main/java/org/apache/usergrid/services/AbstractCollectionService.java
+++ b/stack/services/src/main/java/org/apache/usergrid/services/AbstractCollectionService.java
@@ -17,11 +17,7 @@
package org.apache.usergrid.services;
-import java.util.ArrayList;
-import java.util.List;
-import java.util.Map;
-import java.util.Set;
-import java.util.UUID;
+import java.util.*;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
@@ -389,37 +385,48 @@ public class AbstractCollectionService extends AbstractService {
batch.size(), context.getCollectionName());
}
- int i = 1;
+
+ final Map<String, Boolean> nameValues = new HashMap<>(batch.size());
for ( Map<String, Object> p : batch ) {
+
+ // track unique name value in the batch to identify if duplicates are trying to be created
+ String name = p.get("name").toString();
+ if( name !=null && nameValues.get(name) !=null ){
+ logger.warn("Batch contains more than 1 entity with the same name: {}", name);
+ }else{
+ nameValues.put(name, true);
+ }
+
+
if (logger.isTraceEnabled()) {
- logger.trace("Creating entity {} in collection {}", i, context.getCollectionName());
+ logger.trace("Creating entity [{}] in collection [{}]", p, context.getCollectionName());
}
- Entity item = null;
+ Entity item = null;
try {
item = em.createItemInCollection( context.getOwner(), context.getCollectionName(), getEntityType(),
p );
}
catch ( Exception e ) {
- // TODO should we not log this as error?
- if (logger.isDebugEnabled()) {
- logger.debug("Entity {} unable to be created in collection {}", i, context.getCollectionName(),
- e);
- }
- i++;
+ logger.error("Entity [{}] unable to be created in collection [{}] due to [{} - {}]", p, context.getCollectionName(),
+ e.getClass().getSimpleName(), e.getMessage());
+
+ // move on as we can't block the whole batch if only 1 failed
continue;
}
+
+
if (logger.isTraceEnabled()) {
- logger.trace(
- "Entity {} created in collection {} with UUID {}", i, context.getCollectionName(), item.getUuid());
+ logger.trace("Successfully created entity [{}] in collection [{}]", p, context.getCollectionName());
}
+
item = importEntity( context, item );
entities.add( item );
- i++;
+
}
return new ServiceResults( this, context, Type.COLLECTION, Results.fromEntities( entities ), null, null );
}
[05/11] usergrid git commit: Reset unique value test to its original
state.
Posted by mr...@apache.org.
Reset unique value test to its original state.
Project: http://git-wip-us.apache.org/repos/asf/usergrid/repo
Commit: http://git-wip-us.apache.org/repos/asf/usergrid/commit/5c81a020
Tree: http://git-wip-us.apache.org/repos/asf/usergrid/tree/5c81a020
Diff: http://git-wip-us.apache.org/repos/asf/usergrid/diff/5c81a020
Branch: refs/heads/release-2.1.1
Commit: 5c81a0207f873f6ca54b40043143e87f65c2ced2
Parents: 75d2254
Author: Michael Russo <mr...@apigee.com>
Authored: Wed Jun 22 16:45:01 2016 -0700
Committer: Michael Russo <mr...@apigee.com>
Committed: Wed Jun 22 16:45:01 2016 -0700
----------------------------------------------------------------------
.../collection/EntityCollectionManagerIT.java | 58 ++++++--------------
1 file changed, 18 insertions(+), 40 deletions(-)
----------------------------------------------------------------------
http://git-wip-us.apache.org/repos/asf/usergrid/blob/5c81a020/stack/corepersistence/collection/src/test/java/org/apache/usergrid/persistence/collection/EntityCollectionManagerIT.java
----------------------------------------------------------------------
diff --git a/stack/corepersistence/collection/src/test/java/org/apache/usergrid/persistence/collection/EntityCollectionManagerIT.java b/stack/corepersistence/collection/src/test/java/org/apache/usergrid/persistence/collection/EntityCollectionManagerIT.java
index f828c65..0f3daa4 100644
--- a/stack/corepersistence/collection/src/test/java/org/apache/usergrid/persistence/collection/EntityCollectionManagerIT.java
+++ b/stack/corepersistence/collection/src/test/java/org/apache/usergrid/persistence/collection/EntityCollectionManagerIT.java
@@ -117,49 +117,27 @@ public class EntityCollectionManagerIT {
EntityCollectionManager manager = factory.createCollectionManager( context );
- Entity entity = new Entity( new SimpleId( "test" ) );
- entity.setField( new IntegerField( "count", 5, true ) );
-
- Observable<Entity> firstWrite = manager.write( entity );
-
- Entity newEntity = null;
- Entity firstReturned = null;
-
- for(int i=0; i<500; i++){
-
-
- firstReturned = firstWrite.toBlocking().lastOrDefault( null );
+ {
+ Entity newEntity = new Entity( new SimpleId( "test" ) );
+ newEntity.setField( new IntegerField( "count", 5, true ) );
+ Observable<Entity> observable = manager.write( newEntity );
+ Entity returned = observable.toBlocking().lastOrDefault( null );
}
-// try {
-// //newEntity = new Entity( new SimpleId( "test" ) );
-// //newEntity.setField( new IntegerField( "count", 5, true ) );
-//
-// Observable<Entity> secondWrite = manager.write( entity );
-// secondReturned = secondWrite.toBlocking().lastOrDefault( null );
-//
-// //fail( "Write should have thrown an exception" );
-// }
-// catch ( Exception ex ) {
-// WriteUniqueVerifyException e = ( WriteUniqueVerifyException ) ex;
-// assertEquals( 1, e.getVioliations().size() );
-// }
-
- // try fetching the original one again
-
- assertEquals(entity.getId().getUuid(), firstReturned.getId().getUuid());
- assertEquals(entity.getVersion(), firstReturned.getVersion());
-
-
- //assertEquals(newEntity.getId().getUuid(), secondReturned.getId().getUuid());
- //assertEquals(newEntity.getVersion(), secondReturned.getVersion());
-
-
-
-
-
-
+ {
+ try {
+ Entity newEntity = new Entity( new SimpleId( "test" ) );
+ newEntity.setField( new IntegerField( "count", 5, true ) );
+
+ manager.write( newEntity ).toBlocking().last();
+ fail( "Write should have thrown an exception" );
+ }
+ catch ( Exception ex ) {
+ WriteUniqueVerifyException e = ( WriteUniqueVerifyException ) ex;
+ assertEquals( 1, e.getVioliations().size() );
+ }
+ }
}