use of org.structr.schema.ConfigurationProvider in project structr by structr.
the class CMISRepositoryService method getBaseTypeChildren.
private List<TypeDefinition> getBaseTypeChildren(final BaseTypeId baseTypeId, final Boolean includePropertyDefinitions) {
final ConfigurationProvider config = StructrApp.getConfiguration();
final List<TypeDefinition> result = new LinkedList<>();
final App app = StructrApp.getInstance();
// static definition of base type children, add new types here!
switch(baseTypeId) {
case CMIS_DOCUMENT:
result.add(extendTypeDefinition(File.class, includePropertyDefinitions));
break;
case CMIS_FOLDER:
result.add(extendTypeDefinition(Folder.class, includePropertyDefinitions));
break;
case CMIS_ITEM:
try (final Tx tx = app.tx()) {
for (final SchemaNode schemaNode : app.nodeQuery(SchemaNode.class).sort(AbstractNode.name).getAsList()) {
final Class type = config.getNodeEntityClass(schemaNode.getClassName());
if (type != null) {
final CMISInfo info = getCMISInfo(type);
if (info != null && baseTypeId.equals(info.getBaseTypeId())) {
final TypeDefinition extendedTypeDefinition = extendTypeDefinition(type, includePropertyDefinitions);
if (extendedTypeDefinition != null) {
result.add(extendedTypeDefinition);
}
}
}
}
tx.success();
} catch (final FrameworkException fex) {
logger.warn("", fex);
}
break;
}
return result;
}
use of org.structr.schema.ConfigurationProvider in project structr by structr.
the class GetOrCreateFunction method apply.
@Override
public Object apply(final ActionContext ctx, final Object caller, final Object[] sources) throws FrameworkException {
try {
if (sources == null) {
throw new IllegalArgumentException();
}
final SecurityContext securityContext = ctx.getSecurityContext();
final ConfigurationProvider config = StructrApp.getConfiguration();
final App app = StructrApp.getInstance(securityContext);
final PropertyMap properties = new PropertyMap();
// the type to query for
Class type = null;
if (sources.length >= 1 && sources[0] != null) {
final String typeString = sources[0].toString();
type = config.getNodeEntityClass(typeString);
if (type == null) {
logger.warn("Error in get_or_create(): type \"{}\" not found.", typeString);
return ERROR_MESSAGE_TYPE_NOT_FOUND + typeString;
}
}
// exit gracefully instead of crashing..
if (type == null) {
logger.warn("Error in get_or_create(): no type specified. Parameters: {}", getParametersAsString(sources));
return ERROR_MESSAGE_NO_TYPE_SPECIFIED;
}
// experimental: disable result count, prevents instantiation
// of large collections just for counting all the objects..
securityContext.ignoreResultCount(true);
// extension for native javascript objects
if (sources.length == 2 && sources[1] instanceof Map) {
properties.putAll(PropertyMap.inputTypeToJavaType(securityContext, type, (Map) sources[1]));
} else {
final int parameter_count = sources.length;
if (parameter_count % 2 == 0) {
throw new FrameworkException(400, "Invalid number of parameters: " + parameter_count + ". Should be uneven: " + ERROR_MESSAGE_GET_OR_CREATE);
}
for (int c = 1; c < parameter_count; c += 2) {
if (sources[c] == null) {
throw new IllegalArgumentException();
}
final PropertyKey key = StructrApp.key(type, sources[c].toString());
if (key != null) {
final PropertyConverter inputConverter = key.inputConverter(securityContext);
Object value = sources[c + 1];
if (inputConverter != null) {
value = inputConverter.convert(value);
}
properties.put(key, value);
}
}
}
final GraphObject obj = app.nodeQuery(type).disableSorting().pageSize(1).and(properties).getFirst();
if (obj != null) {
// return existing object
return obj;
}
// create new object
return app.create(type, properties);
} catch (final IllegalArgumentException e) {
logParameterError(caller, sources, ctx.isJavaScriptContext());
return usage(ctx.isJavaScriptContext());
}
}
use of org.structr.schema.ConfigurationProvider in project structr by structr.
the class PrivilegedFindFunction method apply.
@Override
public Object apply(final ActionContext ctx, final Object caller, Object[] sources) throws FrameworkException {
if (sources != null) {
final SecurityContext securityContext = SecurityContext.getSuperUserInstance();
final ConfigurationProvider config = StructrApp.getConfiguration();
final Query query = StructrApp.getInstance(securityContext).nodeQuery().sort(GraphObject.createdDate).order(false);
// the type to query for
Class type = null;
if (sources.length >= 1 && sources[0] != null) {
final String typeString = sources[0].toString();
type = config.getNodeEntityClass(typeString);
if (type != null) {
query.andTypes(type);
} else {
logger.warn("Error in find_privileged(): type \"{}\" not found.", typeString);
return "Error in find_privileged(): type " + typeString + " not found.";
}
}
// exit gracefully instead of crashing..
if (type == null) {
logger.warn("Error in find_privileged(): no type specified. Parameters: {}", getParametersAsString(sources));
return "Error in find_privileged(): no type specified.";
}
// experimental: disable result count, prevents instantiation
// of large collections just for counting all the objects..
securityContext.ignoreResultCount(true);
// extension for native javascript objects
if (sources.length == 2 && sources[1] instanceof Map) {
query.and(PropertyMap.inputTypeToJavaType(securityContext, type, (Map) sources[1]));
} else if (sources.length == 2) {
if (sources[1] == null) {
throw new IllegalArgumentException();
}
// special case: second parameter is a UUID
final PropertyKey key = StructrApp.key(type, "id");
query.and(key, sources[1].toString());
final int resultCount = query.getResult().size();
switch(resultCount) {
case 1:
return query.getFirst();
case 0:
return null;
default:
throw new FrameworkException(400, "Multiple Objects found for id! [" + sources[1].toString() + "]");
}
} else {
final int parameter_count = sources.length;
if (parameter_count % 2 == 0) {
throw new FrameworkException(400, "Invalid number of parameters: " + parameter_count + ". Should be uneven: " + ERROR_MESSAGE_PRIVILEGEDFIND);
}
for (int c = 1; c < parameter_count; c += 2) {
final PropertyKey key = StructrApp.key(type, sources[c].toString());
if (key != null) {
final PropertyConverter inputConverter = key.inputConverter(securityContext);
Object value = sources[c + 1];
if (inputConverter != null) {
value = inputConverter.convert(value);
}
query.and(key, value);
}
}
}
return query.getAsList();
}
return "";
}
use of org.structr.schema.ConfigurationProvider in project structr by structr.
the class ScriptingTest method testGrantViaScripting.
@Test
public void testGrantViaScripting() {
Settings.LogSchemaOutput.setValue(true);
// setup phase: create schema nodes
try (final Tx tx = app.tx()) {
// create two nodes and associate them with each other
final SchemaNode sourceNode = createTestNode(SchemaNode.class, "Source");
final SchemaMethod method = createTestNode(SchemaMethod.class, new NodeAttribute(AbstractNode.name, "doTest01"), new NodeAttribute(SchemaMethod.source, "{ var e = Structr.get('this'); e.grant(Structr.find('Principal')[0], 'read', 'write'); }"));
sourceNode.setProperty(SchemaNode.schemaMethods, Arrays.asList(new SchemaMethod[] { method }));
tx.success();
} catch (FrameworkException fex) {
fex.printStackTrace();
fail("Unexpected exception.");
}
final ConfigurationProvider config = StructrApp.getConfiguration();
final Class sourceType = config.getNodeEntityClass("Source");
Principal testUser = null;
// create test node as superuser
try (final Tx tx = app.tx()) {
app.create(sourceType);
tx.success();
} catch (FrameworkException fex) {
logger.warn("", fex);
fail("Unexpected exception.");
}
// create test user
try (final Tx tx = app.tx()) {
testUser = app.create(Principal.class, new NodeAttribute<>(Principal.name, "test"), new NodeAttribute<>(StructrApp.key(Principal.class, "password"), "test"));
tx.success();
} catch (FrameworkException fex) {
logger.warn("", fex);
fail("Unexpected exception.");
}
final App userApp = StructrApp.getInstance(SecurityContext.getInstance(testUser, AccessMode.Backend));
// first test without grant, expect no test object to be found using the user context
try (final Tx tx = userApp.tx()) {
assertEquals("Invalid grant() scripting result", 0, userApp.nodeQuery(sourceType).getAsList().size());
tx.success();
} catch (FrameworkException fex) {
logger.warn("", fex);
fail("Unexpected exception.");
}
// grant read access to test user
try (final Tx tx = app.tx()) {
app.nodeQuery(sourceType).getFirst().invokeMethod("doTest01", Collections.EMPTY_MAP, true);
tx.success();
} catch (FrameworkException fex) {
fex.printStackTrace();
fail("Unexpected exception.");
}
// first test without grant, expect no test object to be found using the user context
try (final Tx tx = userApp.tx()) {
assertEquals("Invalid grant() scripting result", 1, userApp.nodeQuery(sourceType).getAsList().size());
tx.success();
} catch (FrameworkException fex) {
logger.warn("", fex);
fail("Unexpected exception.");
}
}
use of org.structr.schema.ConfigurationProvider in project structr by structr.
the class SchemaImporter method analyzeSchema.
public void analyzeSchema() {
final App app = StructrApp.getInstance();
final FileBasedHashLongMap<NodeInfo> nodeIdMap = new FileBasedHashLongMap<>(userHome + File.separator + ".structrSchemaAnalyzer");
final DatabaseService graphDb = app.getDatabaseService();
final ConfigurationProvider configuration = Services.getInstance().getConfigurationProvider();
final Set<NodeInfo> nodeTypes = new LinkedHashSet<>();
final Set<RelationshipInfo> relationships = new LinkedHashSet<>();
final Map<String, SchemaNode> schemaNodes = new LinkedHashMap<>();
final Map<String, List<TypeInfo>> typeInfoTypeMap = new LinkedHashMap<>();
final List<TypeInfo> reducedTypeInfos = new LinkedList<>();
final List<TypeInfo> typeInfos = new LinkedList<>();
Iterator<Relationship> relIterator = null;
Iterator<Node> nodeIterator = null;
info("Fetching all nodes iterator..");
try (final Tx tx = app.tx()) {
nodeIterator = Iterables.filter(new StructrAndSpatialPredicate(false, false, true), graphDb.getAllNodes()).iterator();
tx.success();
} catch (FrameworkException fex) {
logger.warn("", fex);
}
info("Starting to analyze nodes..");
bulkGraphOperation(SecurityContext.getSuperUserInstance(), nodeIterator, 100000, "Analyzing nodes", new BulkGraphOperation<Node>() {
@Override
public void handleGraphObject(final SecurityContext securityContext, final Node node) throws FrameworkException {
final NodeInfo nodeInfo = new NodeInfo(node);
// hashcode of nodeInfo is derived from its property and type signature!
nodeTypes.add(nodeInfo);
// add node ID to our new test datastructure
nodeIdMap.add(nodeInfo, node.getId());
}
});
info("Identifying common base classes..");
try (final Tx tx = app.tx(true, false, false)) {
// nodeTypes now contains all existing node types and their property sets
identifyCommonBaseClasses(app, nodeTypes, nodeIdMap, typeInfos);
tx.success();
} catch (FrameworkException fex) {
logger.warn("", fex);
}
info("Collecting type information..");
try (final Tx tx = app.tx(true, false, false)) {
// group type infos by type
collectTypeInfos(typeInfos, typeInfoTypeMap);
tx.success();
} catch (FrameworkException fex) {
logger.warn("", fex);
}
info("Aggregating type information..");
try (final Tx tx = app.tx(true, false, false)) {
// reduce type infos with more than one type
reduceTypeInfos(typeInfoTypeMap, reducedTypeInfos);
tx.success();
} catch (FrameworkException fex) {
logger.warn("", fex);
}
info("Identifying property sets..");
try (final Tx tx = app.tx(true, false, false)) {
// intersect property sets of type infos
intersectPropertySets(reducedTypeInfos);
tx.success();
} catch (FrameworkException fex) {
logger.warn("", fex);
}
info("Sorting result..");
try (final Tx tx = app.tx(true, false, false)) {
// sort type infos
Collections.sort(reducedTypeInfos, new HierarchyComparator(false));
tx.success();
} catch (FrameworkException fex) {
logger.warn("", fex);
}
final Map<String, TypeInfo> reducedTypeInfoMap = new LinkedHashMap<>();
for (final TypeInfo info : reducedTypeInfos) {
final String type = info.getPrimaryType();
// map TypeInfo to type for later use
reducedTypeInfoMap.put(type, info);
info("Starting with setting of type and ID for type {}", type);
bulkGraphOperation(SecurityContext.getSuperUserInstance(), info.getNodeIds().iterator(), 10000, "Setting type and ID", new BulkGraphOperation<Long>() {
@Override
public void handleGraphObject(SecurityContext securityContext, Long nodeId) throws FrameworkException {
final Node node = graphDb.getNodeById(nodeId);
node.setProperty(GraphObject.id.dbName(), NodeServiceCommand.getNextUuid());
node.setProperty(GraphObject.type.dbName(), type);
}
});
}
info("Fetching all relationships iterator..");
try (final Tx tx = app.tx(true, false, false)) {
relIterator = Iterables.filter(new StructrAndSpatialPredicate(false, false, true), graphDb.getAllRelationships()).iterator();
tx.success();
} catch (FrameworkException fex) {
logger.warn("", fex);
}
info("Starting with analyzing relationships..");
bulkGraphOperation(SecurityContext.getSuperUserInstance(), relIterator, 10000, "Analyzing relationships", new BulkGraphOperation<Relationship>() {
@Override
public void handleGraphObject(SecurityContext securityContext, Relationship rel) throws FrameworkException {
final Node startNode = rel.getStartNode();
final Node endNode = rel.getEndNode();
// make sure node has been successfully identified above
if (startNode.hasProperty("type") && endNode.hasProperty("type")) {
final String relationshipType = rel.getType().name();
final String startNodeType = (String) startNode.getProperty("type");
final String endNodeType = (String) endNode.getProperty("type");
relationships.add(new RelationshipInfo(startNodeType, endNodeType, relationshipType));
// create combined type on imported relationship
if (startNodeType != null && endNodeType != null) {
final String combinedType = getCombinedType(startNodeType, relationshipType, endNodeType);
logger.debug("Combined relationship type {} found for rel type {}, start node type {}, end node type {}", new Object[] { combinedType, relationshipType, startNodeType, endNodeType });
rel.setProperty(GraphObject.type.dbName(), combinedType);
}
// create ID on imported relationship
rel.setProperty(GraphObject.id.dbName(), NodeServiceCommand.getNextUuid());
}
}
});
info("Grouping relationships..");
// group relationships by type
final Map<String, List<RelationshipInfo>> relTypeInfoMap = new LinkedHashMap<>();
for (final RelationshipInfo relInfo : relationships) {
// final String relType = relInfo.getRelType();
final String combinedType = getCombinedType(relInfo.getStartNodeType(), relInfo.getRelType(), relInfo.getEndNodeType());
List<RelationshipInfo> infos = relTypeInfoMap.get(combinedType);
if (infos == null) {
infos = new LinkedList<>();
relTypeInfoMap.put(combinedType, infos);
}
infos.add(relInfo);
}
info("Aggregating relationship information..");
final List<RelationshipInfo> reducedRelationshipInfos = new ArrayList<>();
if (Settings.InheritanceDetection.getValue()) {
// reduce relationship infos into one
for (final List<RelationshipInfo> infos : relTypeInfoMap.values()) {
reducedRelationshipInfos.addAll(reduceNodeTypes(infos, reducedTypeInfoMap));
}
} else {
reducedRelationshipInfos.addAll(relationships);
}
info("Starting with schema node creation..");
bulkGraphOperation(SecurityContext.getSuperUserInstance(), reducedTypeInfos.iterator(), 100000, "Creating schema nodes", new BulkGraphOperation<TypeInfo>() {
@Override
public void handleGraphObject(SecurityContext securityContext, TypeInfo typeInfo) throws FrameworkException {
final String type = typeInfo.getPrimaryType();
if (!"ReferenceNode".equals(type)) {
final Map<String, Class> props = typeInfo.getPropertySet();
final PropertyMap propertyMap = new PropertyMap();
// add properties
for (final Map.Entry<String, Class> propertyEntry : props.entrySet()) {
final String propertyName = propertyEntry.getKey();
final Class propertyType = propertyEntry.getValue();
// handle array types differently
String propertyTypeName = propertyType.getSimpleName();
if (propertyType.isArray()) {
// remove "[]" from the end and append "Array" to match the appropriate parser
propertyTypeName = propertyTypeName.substring(0, propertyTypeName.length() - 2).concat("Array");
}
propertyMap.put(new StringProperty("_".concat(propertyName)), propertyTypeName);
}
// set node type which is in "name" property
propertyMap.put(AbstractNode.name, type);
// check if there is an existing Structr entity with the same type
// and make the dynamic class extend the existing class if yes.
final Class existingType = configuration.getNodeEntityClass(type);
if (existingType != null) {
propertyMap.put(SchemaNode.extendsClass, existingType.getName());
} else if (!typeInfo.getOtherTypes().isEmpty()) {
// only the first supertype is supported
propertyMap.put(SchemaNode.extendsClass, typeInfo.getSuperclass(reducedTypeInfoMap));
}
final SchemaNode existingNode = app.nodeQuery(SchemaNode.class).andName(type).getFirst();
if (existingNode != null) {
for (final Entry<PropertyKey, Object> entry : propertyMap.entrySet()) {
existingNode.setProperty(entry.getKey(), entry.getValue());
}
schemaNodes.put(type, existingNode);
} else {
// create schema node
schemaNodes.put(type, app.create(SchemaNode.class, propertyMap));
}
}
}
});
info("Starting with schema relationship creation..");
bulkGraphOperation(SecurityContext.getSuperUserInstance(), reducedRelationshipInfos.iterator(), 100000, "Creating schema relationships", new BulkGraphOperation<RelationshipInfo>() {
@Override
public void handleGraphObject(SecurityContext securityContext, RelationshipInfo template) throws FrameworkException {
final String startNodeType = template.getStartNodeType();
final String endNodeType = template.getEndNodeType();
if (startNodeType != null && endNodeType != null) {
final SchemaNode startNode = schemaNodes.get(startNodeType);
final SchemaNode endNode = schemaNodes.get(endNodeType);
if (startNode != null && endNode != null) {
final String relationshipType = template.getRelType();
final PropertyMap propertyMap = new PropertyMap();
propertyMap.put(SchemaRelationshipNode.sourceId, startNode.getUuid());
propertyMap.put(SchemaRelationshipNode.targetId, endNode.getUuid());
propertyMap.put(SchemaRelationshipNode.relationshipType, relationshipType);
app.create(SchemaRelationshipNode.class, propertyMap);
} else {
info("Unable to create schema relationship node for {} -> {}, no schema nodes found", startNodeType, endNodeType);
}
}
}
});
info("Starting with index rebuild..");
// rebuild index
app.command(BulkRebuildIndexCommand.class).execute(Collections.EMPTY_MAP);
}
Aggregations