/** * Invoke when an entity fails to write correctly */ public void entityFailed( final String message ) { entitiesFailed.incrementAndGet(); FailedImportEntity failedImportEntity = new FailedImportEntity(); failedImportEntity.setErrorMessage( message ); try { EntityManager entityManager = emf.getEntityManager(emf.getManagementAppId()); failedImportEntity = entityManager.create( failedImportEntity ); entityManager.createConnection( fileImport, ERRORS_CONNECTION_NAME, failedImportEntity ); } catch ( Exception e ) { throw new PersistenceException( "Unable to save failed entity import message", e ); } maybeFlush(); }
@Override public void remove(Entity entity) throws Exception { em.delete( entity ); }
public ServiceResults getApplicationEntity( ServiceContext context ) throws Exception { checkPermissionsForPath( context, "/" ); Entity entity = em.get( em.getApplicationRef() ); Results r = Results.fromEntity( entity ); Map<String, Object> collections = em.getApplicationCollectionMetadata(); // Set<String> collections = em.getApplicationCollections(); if ( collections.size() > 0 ) { r.setMetadata( em.getApplicationRef().getUuid(), "collections", collections ); } return genericServiceResults( r ); }
protected void saveToConfiguration(String providerKey, Map<String, Object> config) { try { entityManager.addMapToDictionary(entityManager.getApplication(), providerKey, config); } catch (Exception ex) { logger.error("Error in saveToConfiguration for {}", providerKey, ex); } } }
/** * Encapsulates the dictionary lookup for any configuration required */ protected Map<Object, Object> loadConfigurationFor(String providerKey) { try { return entityManager.getDictionaryAsMap(entityManager.getApplication(), providerKey); } catch (Exception ex) { logger.error("Error in loadConfigurationFor for {}", providerKey, ex); } return null; }
public void distribute( EntityRef group, Entity activity ) throws Exception { if ( activity == null ) { return; } em.addToCollection( group, "feed", activity ); Results r = em.getCollection( group, "users", null, 10000, Level.REFS, false ); List<EntityRef> refs = r.getRefs(); if ( refs != null ) { em.addToCollections( refs, "feed", activity ); } } }
@Test public void testCreateAndDelete() throws Exception { logger.info( "EntityDaoTest.testCreateAndDelete" ); EntityManager em = app.getEntityManager(); String name = "test.thing" + UUIDUtils.newTimeUUID(); Map<String, Object> properties = new LinkedHashMap<String, Object>(); properties.put( "name", name ); properties.put( "foo", "bar" ); logger.info( "Starting entity create" ); Entity thing = em.create( "thing", properties ); logger.info( "Entity created" ); app.waitForQueueDrainAndRefreshIndex(); logger.info( "Starting entity delete" ); em.delete( thing ); logger.info( "Entity deleted" ); app.waitForQueueDrainAndRefreshIndex(); // now search by username, no results should be returned final Query emailQuery = Query.fromQL( "name = '" + name + "'" ); Results r = em.searchCollection( em.getApplicationRef(), "thing", emailQuery ); assertEquals( 0, r.size() ); }
Entity oldAppEntity = managementEm.get(new SimpleEntityRef( deleteTypeName, applicationUUID)); final EntityRef alias = managementEm.getAlias( createCollectionName, oldAppEntity.getName() ); if ( alias != null ) { throw new ConflictException( "Cannot delete app with same name as already deleted app" ); managementEm.create( new SimpleId( applicationUUID, createTypeName ), oldAppEntity.getProperties() ); final Set<String> connectionTypes = managementEm.getConnectionTypes( oldAppEntity ); Observable copyConnections = Observable.from( connectionTypes ).doOnNext( connType -> { try { final Results connResults = managementEm.getTargetEntities( oldAppEntity, connType, null, Query.Level.ALL_PROPERTIES ); connResults.getEntities().forEach( entity -> { try { managementEm.createConnection( newAppEntity, connType, entity ); try { if ( oldAppEntity != null ) { managementEm.delete( oldAppEntity ); applicationIdCache.evictAppId( oldAppEntity.getName() );
}}); }}; Entity user = em.create("user", properties); assertNotNull(user); app.waitForQueueDrainAndRefreshIndex(); Results listResults = em.searchCollection(em.getApplicationRef(), "users", query); assertEquals("1 result returned", 1, listResults.size()); em.updateProperties(user, properties); em.update(user); app.waitForQueueDrainAndRefreshIndex(); listResults = em.searchCollection(em.getApplicationRef(), "users", query); assertEquals(0, listResults.size()); em.delete(user);
userProperties.put( "name", "user" + i ); userProperties.put( "email", "user" + i + "@test.com" ); entity[i] = em.create( "usertests", userProperties ); em.getCollections(entity[i]).contains("usertests"); ConnectedEntityRef ref = em.createConnection( entity[0], "related", entity[1]); em.createConnection( entity[1], "related", entity[0]); Set<String> collections = em.getApplicationCollections(); Iterator<String> itr = collections.iterator(); while (itr.hasNext()) { String collectionName = itr.next(); Results collection = em.getCollection(appID, collectionName, null, Level.ALL_PROPERTIES); List<Entity> entities = collection.getEntities(); List<ConnectionRef> connections; for (int i = 0; i < 2; i++) { r = em.getTargetEntities(entities.get(i), "related", null, Level.IDS); connections = r.getConnections(); assertNotNull(connections); for (int i = 0; i < 3; i++) { er = entities.get(i); dictionaries1 = em.getDictionaryAsMap(er, "connected_types"); dictionaries2 = em.getDictionaryAsMap(er, "connecting_types");
@Test public void stringWithSpaces() throws Exception { EntityManager em = app.getEntityManager(); assertNotNull( em ); logger.debug( "stringWithSpaces" ); Map<String, Object> props = new HashMap<String, Object>(); props.put( "myString", "My simple string" ); Entity saved = em.create( "test", props ); app.waitForQueueDrainAndRefreshIndex(); Query query = Query.fromQL( "myString = 'My simple string'" ); Results results = em.searchCollection( em.getApplicationRef(), "tests", query ); Entity entity = results.getEntitiesMap().get( saved.getUuid() ); assertNotNull( entity ); }
properties.put( "email", "ed@anuff.com" ); Entity user = em.create( "user", properties ); assertNotNull( user ); user = em.get( user ); assertNotNull( user ); assertEquals( "user.username not expected value", "edanuff", user.getProperty( "username" ) ); EntityRef userRef = em.getAlias( new SimpleEntityRef( "application", applicationId ), "users", "edanuff" ); Results results = em.searchCollection( em.getApplicationRef(), "users", query ); assertNotNull( results ); assertEquals( 1, results.size() ); results = em.searchCollection( em.getApplicationRef(), "users", emailQuery ); assertNotNull( results ); assertEquals( 1, results.size() );
@Override public void copyRelationships( String srcRelationName, EntityRef dstEntityRef, String dstRelationName ) throws Exception { headEntity = em.validate( headEntity ); dstEntityRef = em.validate( dstEntityRef ); CollectionInfo srcCollection = getDefaultSchema().getCollection( headEntity.getType(), srcRelationName ); CollectionInfo dstCollection = getDefaultSchema().getCollection( dstEntityRef.getType(), dstRelationName ); Results results = null; do { if ( srcCollection != null ) { results = em.getCollection( headEntity, srcRelationName, null, 5000, Level.REFS, false ); } else { results = em.getTargetEntities( headEntity, srcRelationName, null, Level.REFS ); } if ( ( results != null ) && ( results.size() > 0 ) ) { List<EntityRef> refs = results.getRefs(); for ( EntityRef ref : refs ) { if ( dstCollection != null ) { em.addToCollection( dstEntityRef, dstRelationName, ref ); } else { em.createConnection( dstEntityRef, dstRelationName, ref ); } } } } while ( ( results != null ) && ( results.hasMoreResults() ) ); }
/** * Create test entities of a specified type. * First two entities are connected. */ private void createTestEntities(final EntityManager em, Map<UUID, Entity> thingsMap, List<Entity> things, final String type) throws Exception { logger.debug("\n\nCreating new {} collection in application {}\n", type, em.getApplication().getName()); setup.getEntityIndex().refresh(em.getApplicationId()); List<Entity> created = new ArrayList<>(); for (int i = 0; i < 10; i++) { final int count = i; Entity e = em.create(type, new HashMap<String, Object>() {{ put("name", em.getApplication().getName() + "-" + type + "-" + count); put("originalAppId", em.getApplication().getUuid()); put("originalAppName", em.getApplication().getName()); }}); thingsMap.put(e.getUuid(), e); things.add(e); created.add(e); } // first two things are related to each other em.createConnection(new SimpleEntityRef(type, created.get(0).getUuid()), "related", new SimpleEntityRef(type, created.get(1).getUuid())); em.createConnection(new SimpleEntityRef(type, created.get(1).getUuid()), "related", new SimpleEntityRef(type, created.get(0).getUuid())); setup.getEntityIndex().refresh(em.getApplicationId()); }
@Override public JobStat getStatsForJob( String jobName, UUID jobId ) throws Exception { EntityManager em = emf.getEntityManager( emf.getManagementAppId() ); Query query = Query.fromQL( "select * where " + JOB_NAME + " = '" + jobName + "' AND " + JOB_ID + " = " + jobId ); Results r = em.searchCollection( em.getApplicationRef(), "job_stats", query ); if ( r.size() == 1 ) { return ( JobStat ) r.getEntity(); } return null; }
@Test public void testEntityConnectionsSimple() throws Exception { EntityManager em = app.getEntityManager(); assertNotNull( em ); User first = new User(); first.setUsername( "first" ); first.setEmail( "first@usergrid.com" ); Entity firstUserEntity = em.create( first ); assertNotNull( firstUserEntity ); User second = new User(); second.setUsername( "second" ); second.setEmail( "second@usergrid.com" ); Entity secondUserEntity = em.create( second ); assertNotNull( secondUserEntity ); em.createConnection( firstUserEntity, "likes", secondUserEntity ); Set<String> connectionTypes = em.getConnectionTypes(firstUserEntity); assertEquals( 1, connectionTypes.size()); assertEquals("likes", connectionTypes.iterator().next()); app.waitForQueueDrainAndRefreshIndex(); Results r = em.getTargetEntities(firstUserEntity, "likes", null, Level.IDS); List<ConnectionRef> connections = r.getConnections(); assertNotNull( connections ); assertEquals(1, connections.size()); assertEquals( secondUserEntity.getUuid(), connections.get( 0 ).getTargetRefs().getUuid() ); assertEquals( firstUserEntity.getUuid(), connections.get( 0 ).getSourceRefs().getUuid() ); }
@Ignore( "Pending https://issues.apache.org/jira/browse/USERGRID-1120. ") // needs to have elasticsearch refreshes implemented @Test public void testIncrementAndDecrement() throws Exception { logger.info( "CounterIT.testIncrementAndDecrement" ); EntityManager em = app.getEntityManager(); assertNotNull( em ); final UUID applicationId = em.getApplicationId(); Map<String, Long> counters = em.getEntityCounters( applicationId ); assertEquals( null, counters.get( "application.collection.users" ) ); UUID uuid = UUIDUtils.newTimeUUID(); // UUID.(); Map<String, Object> userProperties = new HashMap<String, Object>(); userProperties.put( "name", "test-name" ); userProperties.put( "username", "test-username" ); userProperties.put( "email", "test-email" ); User user = ( User ) em.create( uuid, "user", userProperties ).toTypedEntity(); logger.debug( "user={}", user ); em.refreshIndex(); counters = em.getEntityCounters( applicationId ); assertEquals( new Long( 1 ), counters.get( "application.collection.users" ) ); em.delete( user ); em.refreshIndex(); counters = em.getEntityCounters( applicationId ); assertEquals( new Long( 0 ), counters.get( "application.collection.users" ) ); }
first.setEmail( "first@usergrid.com" ); Entity firstUserEntity = em.create( first ); second.setEmail( "second@usergrid.com" ); Entity secondUserEntity = em.create( second ); data.put( "name", "4peaks" ); Entity fourpeaks = em.create( "restaurant", data ); em.createConnection( firstUserEntity, "likes", fourpeaks ); Entity arrogantbutcher = em.create( "restaurant", data ); em.createConnection( secondUserEntity, "likes", arrogantbutcher ); Results r = em.getTargetEntities(firstUserEntity, "likes", "restaurant", Level.IDS); assertTrue( em.isConnectionMember( firstUserEntity, "likes", fourpeaks ) ); assertFalse( em.isConnectionMember( firstUserEntity, "likes", arrogantbutcher ) ); r = em.getTargetEntities(secondUserEntity, "likes", "restaurant", Level.IDS); assertTrue( em.isConnectionMember( secondUserEntity, "likes", arrogantbutcher ) ); assertFalse( em.isConnectionMember( secondUserEntity, "likes", fourpeaks ) );
List<Entity> importedThings = emApp2.getCollection( appId2, "things", null, Level.ALL_PROPERTIES).getEntities(); assertTrue( !importedThings.isEmpty() ); Results r = emApp2.getTargetEntities(e, "related", null, Level.IDS); List<ConnectionRef> connections = r.getConnections(); conCount += connections.size(); Map connected0 = emApp2.getDictionaryAsMap(entity0, "connected_types"); Map connecting0 = emApp2.getDictionaryAsMap(entity0, "connected_types"); Assert.assertEquals( 1, connected0.size() ); Assert.assertEquals( 1, connecting0.size() ); Map connected1 = emApp2.getDictionaryAsMap(entity1, "connected_types"); Map connecting1 = emApp2.getDictionaryAsMap(entity1, "connected_types"); Assert.assertEquals( 1, connected1.size() ); Assert.assertEquals( 1, connecting1.size() ); Map connected2 = emApp2.getDictionaryAsMap(entity2, "connected_types"); Map connecting2 = emApp2.getDictionaryAsMap(entity2, "connected_types"); Assert.assertEquals( 0, connected2.size() ); Assert.assertEquals( 0, connecting2.size() ); emApp1.delete( importedThing ); importedThings = emApp2.getCollection( appId2, "things", null, Level.ALL_PROPERTIES).getEntities(); assertTrue( !importedThings.isEmpty() );
@Override public ServiceResults postItemById( ServiceContext context, UUID id ) throws Exception { User user = em.get( context.getOwner(), User.class ); Entity entity = sm.getService( "/roles" ).getEntity( context.getRequest(), id ); if ( entity != null ) { em.addUserToRole( user.getUuid(), entity.getName() ); ScopedCache scopedCache = cacheFactory.getScopedCache(new CacheScope(em.getApplication().asId())); scopedCache.invalidate(); localShiroCache.invalidateAll(); } return new ServiceResults( this, context, Type.COLLECTION, Results.fromRef( entity ), null, null ); }