use of org.structr.core.Result in project structr by structr.
the class Factory method page.
protected Result page(final QueryResult<S> input, final int offset, final int pageSize) throws FrameworkException {
final SecurityContext securityContext = factoryProfile.getSecurityContext();
final boolean dontCheckCount = securityContext.ignoreResultCount();
final List<T> nodes = new ArrayList<>();
int overallCount = 0;
int position = 0;
int count = 0;
try (final QueryResult<S> tmp = input) {
for (final S item : tmp) {
final T n = instantiate(item);
if (n != null) {
overallCount++;
position++;
if (disablePaging || (position > offset && position <= offset + pageSize)) {
nodes.add(n);
// stop if we got enough nodes
if (++count == pageSize && dontCheckCount && !disablePaging) {
break;
}
}
}
}
} catch (NetworkException nex) {
throw new FrameworkException(503, nex.getMessage());
}
// The overall count may be inaccurate
return new Result(nodes, overallCount, true, false);
}
use of org.structr.core.Result in project structr by structr.
the class SearchCommand method doSearch.
private Result<T> doSearch() throws FrameworkException {
if (page == 0 || pageSize <= 0) {
return Result.EMPTY_RESULT;
}
final Factory<S, T> factory = getFactory(securityContext, includeDeletedAndHidden, publicOnly, pageSize, page);
boolean hasGraphSources = false;
boolean hasSpatialSource = false;
if (securityContext.getUser(false) == null && !isRelationshipSearch()) {
rootGroup.add(new PropertySearchAttribute(GraphObject.visibleToPublicUsers, true, Occurrence.REQUIRED, true));
} else if (securityContext.getUser(false) == null && isRelationshipSearch()) {
rootGroup.add(new RelationshipVisibilitySearchAttribute());
}
// special handling of deleted and hidden flags
if (!includeDeletedAndHidden && !isRelationshipSearch()) {
rootGroup.add(new PropertySearchAttribute(NodeInterface.hidden, true, Occurrence.FORBIDDEN, true));
rootGroup.add(new PropertySearchAttribute(NodeInterface.deleted, true, Occurrence.FORBIDDEN, true));
}
// At this point, all search attributes are ready
final List<SourceSearchAttribute> sources = new ArrayList<>();
boolean hasEmptySearchFields = false;
boolean hasRelationshipVisibilitySearch = false;
Result intermediateResult = null;
// (some query types seem to allow no MUST occurs)
for (final Iterator<SearchAttribute> it = rootGroup.getSearchAttributes().iterator(); it.hasNext(); ) {
final SearchAttribute attr = it.next();
if (attr instanceof SearchAttributeGroup) {
// fixme: this needs to be done recursively, but how?
for (final Iterator<SearchAttribute> groupIterator = ((SearchAttributeGroup) attr).getSearchAttributes().iterator(); groupIterator.hasNext(); ) {
final SearchAttribute item = groupIterator.next();
if (item instanceof SourceSearchAttribute) {
sources.add((SourceSearchAttribute) item);
// remove attribute from filter list
groupIterator.remove();
hasGraphSources = true;
}
if (item instanceof EmptySearchAttribute) {
hasEmptySearchFields = true;
}
}
}
// check for distance search and initialize
if (attr instanceof DistanceSearchAttribute) {
final DistanceSearchAttribute distanceSearch = (DistanceSearchAttribute) attr;
if (distanceSearch.needsGeocding()) {
final GeoCodingResult coords = GeoHelper.geocode(distanceSearch);
if (coords != null) {
distanceSearch.setCoords(coords.toArray());
}
}
hasSpatialSource = true;
}
// store source attributes for later use
if (attr instanceof SourceSearchAttribute) {
sources.add((SourceSearchAttribute) attr);
hasGraphSources = true;
}
if (attr instanceof EmptySearchAttribute) {
hasEmptySearchFields = true;
}
if (attr instanceof RelationshipVisibilitySearchAttribute) {
hasRelationshipVisibilitySearch = true;
}
}
// use filters to filter sources otherwise
if (!hasSpatialSource && !sources.isEmpty()) {
intermediateResult = new Result(new ArrayList<>(), null, false, false);
} else {
// apply sorting
if (sortKey != null && !doNotSort) {
rootGroup.setSortKey(sortKey);
rootGroup.sortDescending(sortDescending);
}
final Index<S> index = getIndex();
if (index != null) {
// paging needs to be done AFTER instantiating all nodes
if (hasEmptySearchFields || comparator != null) {
factory.disablePaging();
}
// do query
final QueryResult hits = index.query(getQueryContext(), rootGroup);
intermediateResult = factory.instantiate(hits);
if (comparator != null) {
final List<T> rawResult = intermediateResult.getResults();
Collections.sort(rawResult, comparator);
return new Result(PagingHelper.subList(rawResult, pageSize, page), rawResult.size(), true, false);
}
}
}
if (intermediateResult != null && (hasEmptySearchFields || hasGraphSources || hasSpatialSource || hasRelationshipVisibilitySearch)) {
// sorted result set
final Set<GraphObject> intermediateResultSet = new LinkedHashSet<>(intermediateResult.getResults());
final List<GraphObject> finalResult = new ArrayList<>();
int resultCount = 0;
if (hasGraphSources) {
// merge sources according to their occur flag
final Set<GraphObject> mergedSources = mergeSources(sources);
if (hasSpatialSource) {
// CHM 2014-02-24: preserve sorting of intermediate result, might be sorted by distance which we cannot reproduce easily
intermediateResultSet.retainAll(mergedSources);
} else {
intermediateResultSet.addAll(mergedSources);
}
}
// Filter intermediate result
for (final GraphObject obj : intermediateResultSet) {
boolean addToResult = true;
// check all attributes before adding a node
for (SearchAttribute attr : rootGroup.getSearchAttributes()) {
// check all search attributes
addToResult &= attr.includeInResult(obj);
}
if (addToResult) {
finalResult.add(obj);
resultCount++;
}
}
// sort list
Collections.sort(finalResult, new GraphObjectComparator(sortKey, sortDescending));
// return paged final result
return new Result(PagingHelper.subList(finalResult, pageSize, page), resultCount, true, false);
} else {
// no filtering
return intermediateResult;
}
}
use of org.structr.core.Result in project structr by structr.
the class ODSExporter method exportAttributes.
public static void exportAttributes(final ODSExporter thisNode, final String uuid) throws FrameworkException {
final SecurityContext securityContext = thisNode.getSecurityContext();
final File output = thisNode.getResultDocument();
final VirtualType transformation = thisNode.getTransformationProvider();
try {
final App app = StructrApp.getInstance();
final Result result = app.nodeQuery(AbstractNode.class).and(GraphObject.id, uuid).getResult();
final Result transformedResult = transformation.transformOutput(securityContext, AbstractNode.class, result);
Map<String, Object> nodeProperties = new HashMap<>();
GraphObjectMap node = (GraphObjectMap) transformedResult.get(0);
node.getPropertyKeys(null).forEach(p -> nodeProperties.put(p.dbName(), node.getProperty(p)));
OdfSpreadsheetDocument spreadsheet = OdfSpreadsheetDocument.loadDocument(output.getFileOnDisk().getAbsolutePath());
OdfTable sheet = spreadsheet.getTableList().get(0);
Iterator<Entry<String, Object>> it = nodeProperties.entrySet().iterator();
while (it.hasNext()) {
Entry<String, Object> currentEntry = it.next();
String address = currentEntry.getKey();
Object val = currentEntry.getValue();
if (val instanceof Collection) {
Collection col = (Collection) val;
writeCollectionToCells(sheet, sheet.getCellByPosition(address), col);
} else if (val instanceof String[]) {
String[] arr = (String[]) val;
List<String> list = new ArrayList<>(Arrays.asList(arr));
writeCollectionToCells(sheet, sheet.getCellByPosition(address), list);
} else {
writeObjectToCell(sheet.getCellByPosition(address), val);
}
}
spreadsheet.save(output.getFileOnDisk().getAbsolutePath());
spreadsheet.close();
} catch (Exception e) {
logger.error("Error while exporting to ODS", e);
}
}
use of org.structr.core.Result in project structr by structr.
the class ODTExporter method exportAttributes.
static void exportAttributes(final ODTExporter thisNode, final String uuid) throws FrameworkException {
final SecurityContext securityContext = thisNode.getSecurityContext();
final File output = thisNode.getResultDocument();
final VirtualType transformation = thisNode.getTransformationProvider();
try {
final App app = StructrApp.getInstance();
final Result result = app.nodeQuery(AbstractNode.class).and(GraphObject.id, uuid).getResult();
final Result transformedResult = transformation.transformOutput(securityContext, AbstractNode.class, result);
Map<String, Object> nodeProperties = new HashMap<>();
GraphObjectMap node = (GraphObjectMap) transformedResult.get(0);
node.getPropertyKeys(null).forEach(p -> nodeProperties.put(p.dbName(), node.getProperty(p)));
TextDocument text = TextDocument.loadDocument(output.getFileOnDisk().getAbsolutePath());
NodeList nodes = text.getContentRoot().getElementsByTagName(ODT_FIELD_TAG_NAME);
for (int i = 0; i < nodes.getLength(); i++) {
Node currentNode = nodes.item(i);
NamedNodeMap attrs = currentNode.getAttributes();
Node fieldName = attrs.getNamedItem(ODT_FIELD_ATTRIBUTE_NAME);
Object nodeFieldValue = nodeProperties.get(fieldName.getNodeValue());
Node currentContent = attrs.getNamedItem(ODT_FIELD_ATTRIBUTE_VALUE);
if (nodeFieldValue != null) {
if (nodeFieldValue instanceof String[]) {
String[] arr = (String[]) nodeFieldValue;
List<String> list = new ArrayList<>(Arrays.asList(arr));
StringBuilder sb = new StringBuilder();
list.forEach(s -> sb.append(s + "\n"));
currentContent.setNodeValue(sb.toString());
} else if (nodeFieldValue instanceof Collection) {
Collection col = (Collection) nodeFieldValue;
StringBuilder sb = new StringBuilder();
col.forEach(s -> sb.append(s + "\n"));
currentContent.setNodeValue(sb.toString());
} else {
currentContent.setNodeValue(nodeFieldValue.toString());
}
}
}
text.save(output.getFileOnDisk().getAbsolutePath());
text.close();
} catch (Exception e) {
logger.error("Error while exporting to ODT", e);
}
}
use of org.structr.core.Result in project structr by structr.
the class RelationshipResource method doGet.
@Override
public Result doGet(final PropertyKey sortKey, final boolean sortDescending, final int pageSize, final int page) throws FrameworkException {
// fetch all results, paging is applied later
final List<? extends GraphObject> results = wrappedResource.doGet(null, false, NodeFactory.DEFAULT_PAGE_SIZE, NodeFactory.DEFAULT_PAGE).getResults();
final App app = StructrApp.getInstance();
if (results != null && !results.isEmpty()) {
try {
final List<GraphObject> resultList = new LinkedList<>();
for (GraphObject obj : results) {
if (obj instanceof AbstractNode) {
final List<? extends RelationshipInterface> relationships = Direction.INCOMING.equals(direction) ? Iterables.toList(((AbstractNode) obj).getIncomingRelationships()) : Iterables.toList(((AbstractNode) obj).getOutgoingRelationships());
if (relationships != null) {
boolean filterInternalRelationshipTypes = false;
if (securityContext != null && securityContext.getRequest() != null) {
final String filterInternal = securityContext.getRequest().getParameter(REQUEST_PARAMETER_FILTER_INTERNAL_RELATIONSHIP_TYPES);
if (filterInternal != null) {
filterInternalRelationshipTypes = "true".equals(filterInternal);
}
}
// the result set using the request parameter "filterInternal=true"
if (filterInternalRelationshipTypes) {
for (final RelationshipInterface rel : relationships) {
if (!rel.isInternal()) {
resultList.add(rel);
}
}
} else {
resultList.addAll(relationships);
}
}
}
}
final int rawResultCount = resultList.size();
return new Result(PagingHelper.subList(resultList, pageSize, page), rawResultCount, true, false);
} catch (Throwable t) {
logger.warn("Exception while fetching relationships", t);
}
} else {
logger.info("No results from parent..");
}
throw new IllegalPathException(getResourceSignature() + " can only be applied to a non-empty resource");
}
Aggregations