use of org.structr.core.entity.Relation in project structr by structr.
the class StaticRelationshipResource method doGet.
// ~--- methods --------------------------------------------------------
@Override
public Result doGet(final PropertyKey sortKey, final boolean sortDescending, final int pageSize, final int page) throws FrameworkException {
// ok, source node exists, fetch it
final GraphObject sourceEntity = typedIdResource.getEntity();
if (sourceEntity != null) {
// first try: look through existing relations
if (propertyKey == null) {
if (sourceEntity instanceof NodeInterface) {
if (!typeResource.isNode) {
final NodeInterface source = (NodeInterface) sourceEntity;
final Node sourceNode = source.getNode();
final Class relationshipType = typeResource.entityClass;
final Relation relation = AbstractNode.getRelationshipForType(relationshipType);
final Class destNodeType = relation.getOtherType(typedIdResource.getEntityClass());
final Set partialResult = new LinkedHashSet<>(typeResource.doGet(sortKey, sortDescending, NodeFactory.DEFAULT_PAGE_SIZE, NodeFactory.DEFAULT_PAGE).getResults());
// filter list according to end node type
final Set<GraphObject> set = Iterables.toSet(Iterables.filter(new OtherNodeTypeRelationFilter(securityContext, sourceNode, destNodeType), source.getRelationships(relationshipType)));
// intersect partial result with result list
set.retainAll(partialResult);
final List<GraphObject> finalResult = new LinkedList<>(set);
// sort after merge
applyDefaultSorting(finalResult, sortKey, sortDescending);
// return result
return new Result(PagingHelper.subList(finalResult, pageSize, page), finalResult.size(), isCollectionResource(), isPrimitiveArray());
} else {
// what here?
throw new NotFoundException("Cannot access relationship collection " + typeResource.getRawType());
}
}
} else {
Query query = typeResource.query;
if (query == null) {
query = StructrApp.getInstance(securityContext).nodeQuery();
}
// use search context from type resource
typeResource.collectSearchAttributes(query);
final Predicate<GraphObject> predicate = query.toPredicate();
final Object value = sourceEntity.getProperty(propertyKey, predicate);
if (value != null) {
if (value instanceof Iterable) {
final Set<Object> propertyResults = new LinkedHashSet<>();
Iterator<Object> iter = ((Iterable<Object>) value).iterator();
boolean iterableContainsGraphObject = false;
while (iter.hasNext()) {
Object obj = iter.next();
propertyResults.add(obj);
if (obj != null && !iterableContainsGraphObject) {
if (obj instanceof GraphObject) {
iterableContainsGraphObject = true;
}
}
}
int rawResultCount = propertyResults.size();
if (rawResultCount > 0 && !iterableContainsGraphObject) {
GraphObjectMap gObject = new GraphObjectMap();
gObject.setProperty(new ArrayProperty(this.typeResource.rawType, Object.class), propertyResults.toArray());
Result r = new Result(gObject, true);
r.setRawResultCount(rawResultCount);
return r;
}
final List<GraphObject> finalResult = new LinkedList<>();
propertyResults.forEach(v -> finalResult.add((GraphObject) v));
applyDefaultSorting(finalResult, sortKey, sortDescending);
// return result
Result r = new Result(PagingHelper.subList(finalResult, pageSize, page), finalResult.size(), isCollectionResource(), isPrimitiveArray());
r.setRawResultCount(rawResultCount);
return r;
} else if (value instanceof GraphObject) {
return new Result((GraphObject) value, isPrimitiveArray());
} else {
GraphObjectMap gObject = new GraphObjectMap();
PropertyKey key;
String keyName = this.typeResource.rawType;
int resultCount = 1;
// FIXME: Dynamically resolve all property types and their result count
if (value instanceof String) {
key = new StringProperty(keyName);
} else if (value instanceof Integer) {
key = new IntProperty(keyName);
} else if (value instanceof Long) {
key = new LongProperty(keyName);
} else if (value instanceof Double) {
key = new DoubleProperty(keyName);
} else if (value instanceof Boolean) {
key = new BooleanProperty(keyName);
} else if (value instanceof Date) {
key = new DateProperty(keyName);
} else if (value instanceof String[]) {
key = new ArrayProperty(keyName, String.class);
resultCount = ((String[]) value).length;
} else {
key = new GenericProperty(keyName);
}
gObject.setProperty(key, value);
Result r = new Result(gObject, true);
r.setRawResultCount(resultCount);
return r;
}
}
// check propertyKey to return the right variant of empty result
if (!(propertyKey instanceof StartNode || propertyKey instanceof EndNode)) {
return new Result(Collections.EMPTY_LIST, 1, false, true);
}
}
}
return new Result(Collections.EMPTY_LIST, 0, false, true);
}
use of org.structr.core.entity.Relation in project structr by structr.
the class TypeResource method doPost.
@Override
public RestMethodResult doPost(final Map<String, Object> propertySet) throws FrameworkException {
// virtual type?
if (virtualType != null) {
virtualType.transformInput(securityContext, entityClass, propertySet);
}
if (isNode) {
final RestMethodResult result = new RestMethodResult(HttpServletResponse.SC_CREATED);
final NodeInterface newNode = createNode(propertySet);
if (newNode != null) {
result.addHeader("Location", buildLocationHeader(newNode));
result.addContent(newNode);
}
result.serializeAsPrimitiveArray(true);
// finally: return 201 Created
return result;
} else {
final App app = StructrApp.getInstance(securityContext);
final Relation template = getRelationshipTemplate();
final ErrorBuffer errorBuffer = new ErrorBuffer();
if (template != null) {
final NodeInterface sourceNode = identifyStartNode(template, propertySet);
final NodeInterface targetNode = identifyEndNode(template, propertySet);
final PropertyMap properties = PropertyMap.inputTypeToJavaType(securityContext, entityClass, propertySet);
RelationshipInterface newRelationship = null;
if (sourceNode == null) {
errorBuffer.add(new EmptyPropertyToken(entityClass.getSimpleName(), template.getSourceIdProperty()));
}
if (targetNode == null) {
errorBuffer.add(new EmptyPropertyToken(entityClass.getSimpleName(), template.getTargetIdProperty()));
}
if (errorBuffer.hasError()) {
throw new FrameworkException(422, "Source node ID and target node ID of relationsips must be set", errorBuffer);
}
template.ensureCardinality(securityContext, sourceNode, targetNode);
newRelationship = app.create(sourceNode, targetNode, entityClass, properties);
RestMethodResult result = new RestMethodResult(HttpServletResponse.SC_CREATED);
if (newRelationship != null) {
result.addHeader("Location", buildLocationHeader(newRelationship));
result.addContent(newRelationship);
}
result.serializeAsPrimitiveArray(true);
// finally: return 201 Created
return result;
}
// shouldn't happen
throw new NotFoundException("Type" + rawType + " does not exist");
}
}
use of org.structr.core.entity.Relation in project structr by structr.
the class ImageHelper method findAndReconnectOriginalImage.
public static void findAndReconnectOriginalImage(final Image thumbnail) {
final Class<Relation> thumbnailRel = StructrApp.getConfiguration().getRelationshipEntityClass("ImageTHUMBNAILImage");
final PropertyKey<String> pathKey = StructrApp.key(Image.class, "path");
final String originalImageName = thumbnail.getOriginalImageName();
try {
final App app = StructrApp.getInstance();
final Image originalImage = (Image) app.nodeQuery(Image.class).and(pathKey, PathHelper.getFolderPath(thumbnail.getProperty(pathKey)) + PathHelper.PATH_SEP + originalImageName).getFirst();
if (originalImage != null) {
final PropertyMap relProperties = new PropertyMap();
relProperties.put(StructrApp.key(Image.class, "width"), thumbnail.getWidth());
relProperties.put(StructrApp.key(Image.class, "height"), thumbnail.getHeight());
relProperties.put(StructrApp.key(Image.class, "checksum"), originalImage.getChecksum());
app.create(originalImage, thumbnail, thumbnailRel, relProperties);
}
} catch (FrameworkException ex) {
logger.debug("Error reconnecting thumbnail " + thumbnail.getName() + " to original image " + originalImageName, ex);
}
}
use of org.structr.core.entity.Relation in project structr by structr.
the class ImageHelper method findAndReconnectThumbnails.
public static void findAndReconnectThumbnails(final Image originalImage) {
final Class<Relation> thumbnailRel = StructrApp.getConfiguration().getRelationshipEntityClass("ImageTHUMBNAILImage");
final PropertyKey<Image> tnSmallKey = StructrApp.key(Image.class, "tnSmall");
final PropertyKey<Image> tnMidKey = StructrApp.key(Image.class, "tnMid");
final PropertyKey<String> pathKey = StructrApp.key(Image.class, "path");
final App app = StructrApp.getInstance();
final Integer origWidth = originalImage.getWidth();
final Integer origHeight = originalImage.getHeight();
if (origWidth == null || origHeight == null) {
if (!Arrays.asList("image/svg+xml", "image/x-icon", "image/x-photoshop").contains(originalImage.getContentType())) {
logger.info("Could not determine width and heigth for {}", originalImage.getName());
}
return;
}
for (ThumbnailProperty tnProp : new ThumbnailProperty[] { (ThumbnailProperty) tnSmallKey, (ThumbnailProperty) tnMidKey }) {
int maxWidth = tnProp.getWidth();
int maxHeight = tnProp.getHeight();
boolean crop = tnProp.getCrop();
final float scale = getScaleRatio(origWidth, origHeight, maxWidth, maxHeight, crop);
final String tnName = ImageHelper.getThumbnailName(originalImage.getName(), getThumbnailWidth(origWidth, scale), getThumbnailHeight(origHeight, scale));
try {
final Image thumbnail = (Image) app.nodeQuery(Image.class).and(pathKey, PathHelper.getFolderPath(originalImage.getProperty(pathKey)) + PathHelper.PATH_SEP + tnName).getFirst();
if (thumbnail != null) {
app.create(originalImage, thumbnail, thumbnailRel);
}
} catch (FrameworkException ex) {
logger.debug("Error reconnecting thumbnail " + tnName + " to original image " + originalImage.getName(), ex);
}
}
}
use of org.structr.core.entity.Relation in project structr by structr.
the class SchemaHelper method getPropertyInfo.
public static Map<String, Object> getPropertyInfo(final SecurityContext securityContext, final PropertyKey property) {
final Map<String, Object> map = new LinkedHashMap();
map.put("dbName", property.dbName());
map.put("jsonName", property.jsonName());
map.put("className", property.getClass().getName());
final Class declaringClass = property.getDeclaringClass();
if (declaringClass != null) {
map.put("declaringClass", declaringClass.getSimpleName());
}
map.put("defaultValue", property.defaultValue());
if (property instanceof StringProperty) {
map.put("contentType", ((StringProperty) property).contentType());
}
map.put("format", property.format());
map.put("readOnly", property.isReadOnly());
map.put("system", property.isSystemInternal());
map.put("indexed", property.isIndexed());
map.put("indexedWhenEmpty", property.isIndexedWhenEmpty());
map.put("compound", property.isCompound());
map.put("unique", property.isUnique());
map.put("notNull", property.isNotNull());
map.put("dynamic", property.isDynamic());
map.put("hint", property.hint());
map.put("category", property.category());
final Class<? extends GraphObject> relatedType = property.relatedType();
if (relatedType != null) {
map.put("relatedType", relatedType.getName());
map.put("type", relatedType.getSimpleName());
map.put("uiType", relatedType.getSimpleName() + (property.isCollection() ? "[]" : ""));
} else {
map.put("type", property.typeName());
map.put("uiType", property.typeName() + (property.isCollection() ? "[]" : ""));
}
map.put("isCollection", property.isCollection());
final PropertyConverter databaseConverter = property.databaseConverter(securityContext, null);
final PropertyConverter inputConverter = property.inputConverter(securityContext);
if (databaseConverter != null) {
map.put("databaseConverter", databaseConverter.getClass().getName());
}
if (inputConverter != null) {
map.put("inputConverter", inputConverter.getClass().getName());
}
// if (declaringClass != null && ("org.structr.dynamic".equals(declaringClass.getPackage().getName()))) {
if (declaringClass != null && property instanceof RelationProperty) {
Relation relation = ((RelationProperty) property).getRelation();
if (relation != null) {
map.put("relationshipType", relation.name());
}
}
return map;
}
Aggregations