Search in sources :

Example 1 with EntityType

use of org.sagebionetworks.repo.model.EntityType in project Synapse-Repository-Services by Sage-Bionetworks.

the class DefaultControllerAutowiredAllTypesTest method createEntitesOfEachType.

/**
 * This is a test helper method that will create at least on of each type of entity.
 * @return
 * @throws IOException
 * @throws ServletException
 * @throws InvalidModelException
 * @throws IllegalAccessException
 * @throws InstantiationException
 * @throws UnauthorizedException
 * @throws NotFoundException
 * @throws DatastoreException
 */
private List<Entity> createEntitesOfEachType(int countPerType) throws ServletException, IOException, InstantiationException, IllegalAccessException, InvalidModelException, DatastoreException, NotFoundException, UnauthorizedException {
    // For now put each object in a project so their parent id is not null;
    // Create a project
    Project project = new Project();
    project.setName("createAtLeastOneOfEachType");
    project = ServletTestHelper.createEntity(dispatchServlet, project, userName);
    assertNotNull(project);
    toDelete.add(project.getId());
    // Create a dataset
    Study datasetParent = (Study) ObjectTypeFactory.createObjectForTest("datasetParent", EntityType.dataset, project.getId());
    datasetParent = ServletTestHelper.createEntity(dispatchServlet, datasetParent, userName);
    // Create a layer parent
    Data layerParent = (Data) ObjectTypeFactory.createObjectForTest("layerParent", EntityType.layer, datasetParent.getId());
    layerParent = ServletTestHelper.createEntity(dispatchServlet, layerParent, userName);
    // Now get the path of the layer
    List<EntityHeader> path = entityController.getEntityPath(userName, layerParent.getId());
    // This is the list of entities that will be created.
    List<Entity> newChildren = new ArrayList<Entity>();
    // Create one of each type
    EntityType[] types = EntityType.values();
    for (int i = 0; i < countPerType; i++) {
        int index = i;
        Study dataset = null;
        for (EntityType type : types) {
            String name = type.name() + index;
            // use the correct parent type.
            String parentId = findCompatableParentId(path, type);
            Entity object = ObjectTypeFactory.createObjectForTest(name, type, parentId);
            Entity clone = ServletTestHelper.createEntity(dispatchServlet, object, userName);
            assertNotNull(clone);
            assertNotNull(clone.getId());
            assertNotNull(clone.getEtag());
            // Mark entities for deletion after the current test completes
            toDelete.add(clone.getId());
            // Stash these for later use
            if (EntityType.dataset == type) {
                dataset = (Study) clone;
            }
            // Check the base urls
            UrlHelpers.validateAllUrls(clone);
            // Add this to the list of entities created
            newChildren.add(clone);
            index++;
        }
    }
    return newChildren;
}
Also used : EntityType(org.sagebionetworks.repo.model.EntityType) Project(org.sagebionetworks.repo.model.Project) Study(org.sagebionetworks.repo.model.Study) Entity(org.sagebionetworks.repo.model.Entity) EntityHeader(org.sagebionetworks.repo.model.EntityHeader) ArrayList(java.util.ArrayList) Data(org.sagebionetworks.repo.model.Data)

Example 2 with EntityType

use of org.sagebionetworks.repo.model.EntityType in project Synapse-Repository-Services by Sage-Bionetworks.

the class ControllerTest method testUpdateEntityMissingEtag.

/**
 * Test method for
 * {@link org.sagebionetworks.repo.web.EntityController#updateEntity} .
 *
 * @throws Exception
 */
@Test
public void testUpdateEntityMissingEtag() throws Exception {
    EntityType[] types = EntityType.values();
    // for (EntityType type: types) {
    String url = helper.getServletPrefix() + UrlHelpers.ENTITY;
    MockHttpServletRequest request = new MockHttpServletRequest();
    MockHttpServletResponse response = new MockHttpServletResponse();
    request.setMethod("PUT");
    request.addHeader("Accept", "application/json");
    request.setRequestURI(url + "/1");
    request.addHeader("Content-Type", "application/json; charset=UTF-8");
    request.setContent("{\"id\": 1, \"text\":\"updated dataset from a unit test\"}".getBytes("UTF-8"));
    servlet.service(request, response);
    log.info("Results: " + response.getContentAsString());
    assertEquals(HttpStatus.BAD_REQUEST.value(), response.getStatus());
    JSONObject results = new JSONObject(response.getContentAsString());
    // The response should be something like: {"reason":"Failed to
    // invoke handler method [public
    // org.sagebionetworks.repo.model.Dataset
    // org.sagebionetworks.repo.web.controller.DatasetController.updateDataset
    // (java.lang.Long,java.lang.String,org.sagebionetworks.repo.model.Dataset)
    // throws org.sagebionetworks.repo.web.NotFoundException]; nested
    // exception is java.lang.IllegalStateException:
    // Missing header 'Etag' of type [java.lang.String]"}
    assertTrue("Testing " + url, results.getString("reason").matches("(?s).*Missing header 'ETag'.*"));
// }
}
Also used : EntityType(org.sagebionetworks.repo.model.EntityType) JSONObject(org.json.JSONObject) MockHttpServletRequest(org.springframework.mock.web.MockHttpServletRequest) MockHttpServletResponse(org.springframework.mock.web.MockHttpServletResponse) Test(org.junit.Test)

Example 3 with EntityType

use of org.sagebionetworks.repo.model.EntityType in project Synapse-Repository-Services by Sage-Bionetworks.

the class EntityServiceImpl method deleteEntityVersion.

@Transactional(readOnly = false, propagation = Propagation.REQUIRED)
@Override
public void deleteEntityVersion(String userId, String id, Long versionNumber) throws NotFoundException, DatastoreException, UnauthorizedException, ConflictingUpdateException {
    String entityId = UrlHelpers.getEntityIdFromUriId(id);
    UserInfo userInfo = userManager.getUserInfo(userId);
    EntityType type = entityManager.getEntityType(userInfo, id);
    deleteEntityVersion(userId, entityId, versionNumber, type.getClassForType());
}
Also used : EntityType(org.sagebionetworks.repo.model.EntityType) UserInfo(org.sagebionetworks.repo.model.UserInfo) Transactional(org.springframework.transaction.annotation.Transactional)

Example 4 with EntityType

use of org.sagebionetworks.repo.model.EntityType in project Synapse-Repository-Services by Sage-Bionetworks.

the class NodeTranslationUtils method buildPrimaryFieldCache.

/**
 * Build up the cache of primary fields for each object type.
 *
 * @return
 */
private static void buildPrimaryFieldCache() {
    for (EntityType type : EntityType.values()) {
        HashSet<String> set = new HashSet<String>();
        // Add each field
        Field[] fields = type.getClassForType().getDeclaredFields();
        for (Field field : fields) {
            String name = field.getName();
            // Add this name and the node name
            set.add(name);
            String nodeName = nameConvertion.get(name);
            if (nodeName != null) {
                set.add(nodeName);
            }
        }
        primaryFieldsCache.put(type, set);
    }
}
Also used : EntityType(org.sagebionetworks.repo.model.EntityType) Field(java.lang.reflect.Field) HashSet(java.util.HashSet)

Example 5 with EntityType

use of org.sagebionetworks.repo.model.EntityType in project Synapse-Repository-Services by Sage-Bionetworks.

the class NodeBackupDriverImpl method restoreFromBackup.

/**
 * Restore from the backup.
 * @throws InterruptedException
 */
@Override
public boolean restoreFromBackup(File source, Progress progress) throws IOException, InterruptedException {
    if (source == null)
        throw new IllegalArgumentException("Source file cannot be null");
    if (!source.exists())
        throw new IllegalArgumentException("Source file dose not exist: " + source.getAbsolutePath());
    if (progress == null)
        throw new IllegalArgumentException("Progress cannot be null");
    FileInputStream fis = new FileInputStream(source);
    try {
        log.info("Restoring: " + source.getAbsolutePath());
        progress.appendLog("Restoring: " + source.getAbsolutePath());
        // First clear all data
        ZipInputStream zin = new ZipInputStream(new BufferedInputStream(fis));
        progress.setMessage("Reading: " + source.getAbsolutePath());
        progress.setTotalCount(source.length());
        // We need to map the node type to the node id.
        EntityType nodeType = null;
        NodeBackup backup = null;
        List<NodeRevisionBackup> revisions = null;
        ZipEntry entry;
        progress.appendLog("Processing nodes:");
        while ((entry = zin.getNextEntry()) != null) {
            progress.setMessage(entry.getName());
            // Check for termination.
            checkForTermination(progress);
            // Is this a node or a revision?
            if (isNodeBackupFile(entry.getName())) {
                // Push the current data
                if (backup != null) {
                    createOrUpdateNodeWithRevisions(backup, revisions);
                    // clear the current data
                    backup = null;
                }
                // This is a backup file.
                backup = nodeSerializer.readNodeBackup(zin);
                // Append this id to the log.
                progress.appendLog(backup.getNode().getId());
                revisions = new ArrayList<NodeRevisionBackup>();
                try {
                    nodeType = EntityType.valueOf(backup.getNode().getNodeType());
                } catch (IllegalArgumentException e) {
                    // This was likely a deleted entity type.
                    nodeType = EntityType.unknown;
                    backup = null;
                    // for now skip unknown types
                    continue;
                }
                migrationDriver.migrateNodePrincipals(backup);
                // Are we restoring the root node?
                if (backup.getNode().getParentId() == null) {
                    // This node is a root.  Does it match the current root?
                    String currentRootId = getCurrentRootId();
                    if (!backup.getNode().getId().equals(currentRootId)) {
                        // We are being asked to restore a root node but we already have one.
                        // Since the current root does not match the ID of the root we were given
                        // we must clear all data and start with a clean database
                        backupManager.clearAllData();
                    }
                }
            } else if (isNodeRevisionFile(entry.getName())) {
                // Skip unknown types.
                if (EntityType.unknown == nodeType)
                    continue;
                if (backup == null)
                    throw new IllegalArgumentException("Found a revsions without a matching entity.");
                if (revisions == null)
                    throw new IllegalArgumentException("Found a revisoin without any matching entity");
                // This is a revision file.
                NodeRevisionBackup revision = NodeSerializerUtil.readNodeRevision(zin);
                // Add this to the list
                // Migrate the revision to the current version
                nodeType = migrationDriver.migrateToCurrentVersion(revision, nodeType);
                // nodeType is changed as needed
                backup.getNode().setNodeType(nodeType.name());
                // Add this to the list of revisions to be processed
                revisions.add(revision);
            } else {
                throw new IllegalArgumentException("Did not recongnize file name: " + entry.getName());
            }
            progress.incrementProgressBy(entry.getCompressedSize());
            if (log.isTraceEnabled()) {
                log.trace(progress.toString());
            }
            // This is run in a tight loop so to be CPU friendly we should yield
            Thread.yield();
        }
        progress.appendLog("Finished processing nodes.");
        if (backup != null) {
            // do the final backup
            createOrUpdateNodeWithRevisions(backup, revisions);
        }
    } finally {
        if (fis != null) {
            fis.close();
        }
    }
    return true;
}
Also used : EntityType(org.sagebionetworks.repo.model.EntityType) ZipInputStream(java.util.zip.ZipInputStream) BufferedInputStream(java.io.BufferedInputStream) ZipEntry(java.util.zip.ZipEntry) NodeBackup(org.sagebionetworks.repo.model.NodeBackup) NodeRevisionBackup(org.sagebionetworks.repo.model.NodeRevisionBackup) FileInputStream(java.io.FileInputStream)

Aggregations

EntityType (org.sagebionetworks.repo.model.EntityType)48 Test (org.junit.Test)23 Annotations (org.sagebionetworks.repo.model.Annotations)13 NamedAnnotations (org.sagebionetworks.repo.model.NamedAnnotations)13 UserInfo (org.sagebionetworks.repo.model.UserInfo)13 ArrayList (java.util.ArrayList)12 List (java.util.List)11 EntityTypeMigrationSpec (org.sagebionetworks.repo.model.registry.EntityTypeMigrationSpec)9 FieldDescription (org.sagebionetworks.repo.model.registry.FieldDescription)9 FieldMigrationSpec (org.sagebionetworks.repo.model.registry.FieldMigrationSpec)9 MigrationSpec (org.sagebionetworks.repo.model.registry.MigrationSpec)9 MigrationSpecData (org.sagebionetworks.repo.model.registry.MigrationSpecData)9 Entity (org.sagebionetworks.repo.model.Entity)8 Transactional (org.springframework.transaction.annotation.Transactional)7 Ignore (org.junit.Ignore)6 EntityHeader (org.sagebionetworks.repo.model.EntityHeader)6 UnauthorizedException (org.sagebionetworks.repo.model.UnauthorizedException)3 BasicQuery (org.sagebionetworks.repo.model.query.BasicQuery)3 Field (java.lang.reflect.Field)2 AccessControlList (org.sagebionetworks.repo.model.AccessControlList)2