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;
}
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'.*"));
// }
}
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());
}
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);
}
}
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;
}
Aggregations