@Override public boolean delete() { final App app = StructrApp.getInstance(); try (Tx tx = StructrApp.getInstance().tx()) { app.delete(this); tx.success(); } catch (FrameworkException ex) { logger.log(Level.SEVERE, null, ex); } return true; }
@Override public void setTargetNodeId(final String targetIdNode) throws FrameworkException { // Do nothing if new id equals old if (getTargetNodeId().equals(targetIdNode)) { return; } final App app = StructrApp.getInstance(securityContext); final NodeInterface newTargetNode = (NodeInterface) app.get(targetIdNode); final NodeInterface startNode = getSourceNode(); final Class relationType = getClass(); final PropertyMap _props = getProperties(); final String type = this.getClass().getSimpleName(); if (newTargetNode == null) { throw new FrameworkException(type, new IdNotFoundToken(targetIdNode)); } // delete this as the new rel will be the container afterwards app.delete(this); // create new relationship and store here app.create(startNode, newTargetNode, relationType, _props); }
@Override public void processMessage(final WebSocketMessage webSocketData) { final SecurityContext securityContext = getWebSocket().getSecurityContext(); final int pageSize = webSocketData.getPageSize(); final int page = webSocketData.getPage(); final App app = StructrApp.getInstance(securityContext); try (final Tx tx = app.tx()) { // do search List<AbstractNode> filteredResults = getUnattachedNodes(app, securityContext, webSocketData); // save raw result count int resultCountBeforePaging = filteredResults.size(); // set full result list webSocketData.setResult(PagingHelper.subList(filteredResults, pageSize, page, null)); webSocketData.setRawResultCount(resultCountBeforePaging); // send only over local connection getWebSocket().send(webSocketData, true); tx.success(); } catch (FrameworkException fex) { logger.warn("Exception occured", fex); getWebSocket() .send( MessageBuilder.status().code(fex.getStatus()).message(fex.getMessage()).build(), true); } }
@Override public void processMessage(final WebSocketMessage webSocketData) { final String type = (String) webSocketData.getNodeData().get("type"); if (type == null) { logger.log(Level.WARNING, "Node type given not found"); getWebSocket().send(MessageBuilder.status().code(400).build(), true); } final SecurityContext securityContext = getWebSocket().getSecurityContext(); final App app = StructrApp.getInstance(securityContext); final SchemaNode typeNode; try { typeNode = app.nodeQuery(SchemaNode.class).andName(type).getFirst(); if (typeNode != null) { webSocketData.setResult(Arrays.asList(typeNode)); // send only over local connection (no broadcast) getWebSocket().send(webSocketData, true); } } catch (FrameworkException ex) { logger.log(Level.SEVERE, null, ex); getWebSocket().send(MessageBuilder.status().code(500).build(), true); } }
@Override public void ensureCardinality( final SecurityContext securityContext, final NodeInterface sourceNode, final NodeInterface targetNode) throws FrameworkException { final App app = StructrApp.getInstance(); final Class<? extends ManyToOne> clazz = this.getClass(); final Class<T> targetType = getTargetType(); if (sourceNode != null) { // check existing relationships final Relation<?, T, ?, ?> outgoingRel = sourceNode.getOutgoingRelationship(clazz); if (outgoingRel != null && targetType.isAssignableFrom(outgoingRel.getTargetType())) { try { app.beginTx(); app.delete(outgoingRel); app.commitTx(); } finally { app.finishTx(); } } } }
@Override public void execute(final StructrShellCommand parent) throws IOException { final App app = StructrApp.getInstance(); try (final Tx tx = app.tx()) { final Folder currentFolder = parent.getCurrentFolder(); if (currentFolder != null) { listFolder(parent, currentFolder.getProperty(AbstractFile.children)); } else { listFolder( parent, app.nodeQuery(AbstractFile.class).and(AbstractFile.parent, null).getAsList()); } tx.success(); } catch (FrameworkException fex) { logger.warn("", fex); } }
@Override public String getGroupName() { String name = ""; try (Tx tx = StructrApp.getInstance().tx()) { Principal owner = getOwner(); if (owner != null) { List<Principal> parents = owner.getParents(); if (!parents.isEmpty()) { name = parents.get(0).getProperty(AbstractNode.name); } } tx.success(); } catch (FrameworkException fex) { logger.log(Level.SEVERE, "Error while getting group name of " + this, fex); } return name; }
public static void importCypher(final List<String> sources) { final App app = StructrApp.getInstance(); final GraphDatabaseService graphDb = app.command(GraphDatabaseCommand.class).execute(); // nothing to do if (sources.isEmpty()) { return; } // first step: execute cypher queries for (final String source : sources) { try (final Transaction tx = graphDb.beginTx()) { // be very tolerant here, just execute everything graphDb.execute(source); tx.success(); } catch (Throwable t) { // ignore t.printStackTrace(); } } }
@Override public Comment createComment(String comment) { try { // create new content element org.structr.web.entity.dom.Comment commentNode = (org.structr.web.entity.dom.Comment) StructrApp.getInstance(securityContext) .command(CreateNodeCommand.class) .execute( new NodeAttribute( AbstractNode.type, org.structr.web.entity.dom.Comment.class.getSimpleName()), new NodeAttribute(Content.content, comment)); // create relationship from ownerDocument to new text element ((RelationProperty<DOMNode>) Page.elements) .addSingleElement(securityContext, Page.this, commentNode); // Page.elements.createRelationship(securityContext, Page.this, content); return commentNode; } catch (FrameworkException fex) { // FIXME: what to do with the exception here? logger.log(Level.WARNING, "", fex); } return null; }
@Override public List<GraphObject> getProperty( SecurityContext securityContext, GraphObject obj, boolean applyConverter, Predicate<GraphObject> predicate) { if (obj instanceof AbstractNode) { try { final String query = Scripting.replaceVariables(new ActionContext(securityContext), obj, this.format); final Map<String, Object> parameters = new LinkedHashMap<>(); parameters.put("id", obj.getUuid()); parameters.put("type", obj.getType()); return StructrApp.getInstance(securityContext) .command(CypherQueryCommand.class) .execute(query, parameters); } catch (Throwable t) { t.printStackTrace(); } } return null; }
public static ResourceAccess findGrant( final SecurityContext securityContext, final String signature) throws FrameworkException { ResourceAccess grant = grantCache.get(signature); if (grant == null) { // grant = // StructrApp.getInstance(securityContext).nodeQuery(ResourceAccess.class).and(ResourceAccess.signature, signature).getFirst(); // ignore security context for now, so ResourceAccess objects don't have to be visible grant = StructrApp.getInstance() .nodeQuery(ResourceAccess.class) .and(ResourceAccess.signature, signature) .getFirst(); if (grant != null) { grantCache.put(signature, grant); } else { logger.debug("No resource access object found for {}", signature); } } return grant; }
@Override public boolean move(FtpFile target) { try (Tx tx = StructrApp.getInstance().tx()) { logger.log(Level.INFO, "move()"); final AbstractStructrFtpFile targetFile = (AbstractStructrFtpFile) target; final String path = targetFile instanceof StructrFtpFile ? "/" : targetFile.getAbsolutePath(); try { if (!("/".equals(path))) { final String newName = path.contains("/") ? StringUtils.substringAfterLast(path, "/") : path; setProperty(AbstractNode.name, newName); } } catch (FrameworkException ex) { logger.log(Level.SEVERE, "Could not move ftp file", ex); return false; } tx.success(); return true; } catch (FrameworkException ex) { logger.log(Level.SEVERE, null, ex); } return false; }
@Override public CDATASection createCDATASection(String string) throws DOMException { try { // create new content element Cdata content = (Cdata) StructrApp.getInstance(securityContext) .command(CreateNodeCommand.class) .execute(new NodeAttribute(AbstractNode.type, Cdata.class.getSimpleName())); // create relationship from ownerDocument to new text element ((RelationProperty<DOMNode>) Page.elements) .addSingleElement(securityContext, Page.this, content); // Page.elements.createRelationship(securityContext, Page.this, content); return content; } catch (FrameworkException fex) { // FIXME: what to do with the exception here? logger.log(Level.WARNING, "", fex); } return null; }
@Override public DocumentFragment createDocumentFragment() { final App app = StructrApp.getInstance(securityContext); try { // create new content element org.structr.web.entity.dom.DocumentFragment fragment = app.create(org.structr.web.entity.dom.DocumentFragment.class); // create relationship from ownerDocument to new text element ((RelationProperty<DOMNode>) Page.elements) .addSingleElement(securityContext, Page.this, fragment); // Page.elements.createRelationship(securityContext, Page.this, fragment); return fragment; } catch (FrameworkException fex) { // FIXME: what to do with the exception here? logger.log(Level.WARNING, "", fex); } return null; }
/** * Find the page with the lowest position value which is visible in the current securit context * * @param securityContext * @return * @throws FrameworkException */ private Page findIndexPage(final SecurityContext securityContext) throws FrameworkException { Result<Page> results = StructrApp.getInstance(securityContext) .nodeQuery(Page.class) .sort(Page.position) .order(false) .getResult(); Collections.sort( results.getResults(), new GraphObjectComparator(Page.position, GraphObjectComparator.ASCENDING)); // Find first visible page Page page = null; if (!results.isEmpty()) { int i = 0; while (page == null || (i < results.size() && !securityContext.isVisible(page))) { page = results.get(i++); } } return page; }
private List<Linkable> findPossibleEntryPointsByName( final SecurityContext securityContext, HttpServletRequest request, final String name) throws FrameworkException { List<Linkable> possibleEntryPoints = (List<Linkable>) request.getAttribute(POSSIBLE_ENTRY_POINTS); if (CollectionUtils.isNotEmpty(possibleEntryPoints)) { return possibleEntryPoints; } if (name.length() > 0) { logger.log(Level.FINE, "Requested name: {0}", name); final Query query = StructrApp.getInstance(securityContext).nodeQuery(); query.and(AbstractNode.name, name); query.and().orType(Page.class).orTypes(File.class); // Searching for pages needs super user context anyway Result results = query.getResult(); logger.log(Level.FINE, "{0} results", results.size()); request.setAttribute(POSSIBLE_ENTRY_POINTS, results.getResults()); return (List<Linkable>) results.getResults(); } return Collections.EMPTY_LIST; }
@Override public void onWebSocketClose(final int closeCode, final String message) { logger.log( Level.INFO, "Connection closed with closeCode {0} and message {1}", new Object[] {closeCode, message}); final App app = StructrApp.getInstance(securityContext); try (final Tx tx = app.tx()) { this.session = null; syncController.unregisterClient(this); // flush and close open uploads for (FileUploadHandler upload : uploads.values()) { upload.finish(); } tx.success(); uploads.clear(); } catch (FrameworkException fex) { logger.log(Level.SEVERE, "Error while closing connection", fex); } }
private Principal getOwner() { try (Tx tx = StructrApp.getInstance().tx()) { Principal owner = getProperty(File.owner); tx.success(); return owner; } catch (FrameworkException fex) { logger.log(Level.SEVERE, "Error while getting owner of " + this, fex); } return null; }
// ----- interface FtpFile ----- @Override public String getAbsolutePath() { try (Tx tx = StructrApp.getInstance().tx()) { final String path = getPath(); tx.success(); return path; } catch (FrameworkException fex) { logger.log(Level.SEVERE, "Error in getPath() of abstract ftp file", fex); } return null; }
/** * Find node by uuid * * @param securityContext * @param request * @param uuid * @return * @throws FrameworkException */ private AbstractNode findNodeByUuid(final SecurityContext securityContext, final String uuid) throws FrameworkException { if (!uuid.isEmpty()) { logger.log(Level.FINE, "Requested id: {0}", uuid); return (AbstractNode) StructrApp.getInstance(securityContext).get(uuid); } return null; }
/** * Creates a new Page entity with the given name in the database. * * @param securityContext the security context to use * @param name the name of the new ownerDocument, defaults to "ownerDocument" if not set * @return the new ownerDocument * @throws FrameworkException */ public static Page createNewPage(SecurityContext securityContext, String name) throws FrameworkException { final App app = StructrApp.getInstance(securityContext); final PropertyMap properties = new PropertyMap(); properties.put(AbstractNode.name, name != null ? name : "page"); properties.put(AbstractNode.type, Page.class.getSimpleName()); properties.put(Page.contentType, "text/html"); return app.create(Page.class, properties); }
@Override public boolean setLastModified(long time) { try (Tx tx = StructrApp.getInstance().tx()) { setProperty(lastModifiedDate, new Date(time)); tx.success(); } catch (FrameworkException ex) { logger.log(Level.SEVERE, null, ex); } return true; }
@Override public void set( final SecurityContext securityContext, final NodeInterface targetNode, final Iterable<S> collection) throws FrameworkException { final App app = StructrApp.getInstance(securityContext); final Set<S> toBeDeleted = new LinkedHashSet<>(Iterables.toList(get(securityContext, targetNode, null))); final Set<S> toBeCreated = new LinkedHashSet<>(); if (collection != null) { Iterables.addAll(toBeCreated, collection); } // create intersection of both sets final Set<S> intersection = new LinkedHashSet<>(toBeCreated); intersection.retainAll(toBeDeleted); // intersection needs no change toBeCreated.removeAll(intersection); toBeDeleted.removeAll(intersection); // remove existing relationships for (S sourceNode : toBeDeleted) { for (AbstractRelationship rel : targetNode.getIncomingRelationships()) { final String relTypeName = rel.getRelType().name(); final String desiredRelType = relation.name(); if (relTypeName.equals(desiredRelType) && rel.getSourceNode().equals(sourceNode)) { app.delete(rel); } } } // create new relationships for (S sourceNode : toBeCreated) { relation.ensureCardinality(securityContext, sourceNode, targetNode); app.create( sourceNode, targetNode, relation.getClass(), getNotionProperties(securityContext, relation.getClass(), sourceNode.getUuid())); } }
public String getJavascriptLibraryCode(String fileName) { final StringBuilder buf = new StringBuilder(); final App app = StructrApp.getInstance(); try (final Tx tx = app.tx()) { final List<JavaScriptSource> jsFiles = app.nodeQuery(JavaScriptSource.class) .and(JavaScriptSource.name, fileName) .and(JavaScriptSource.useAsJavascriptLibrary, true) .getAsList(); if (jsFiles.isEmpty()) { logger.warn("No JavaScript library found with fileName: {}", fileName); } for (final JavaScriptSource jsLibraryFile : jsFiles) { final String contentType = jsLibraryFile.getContentType(); if (contentType != null) { final String lowerCaseContentType = contentType.toLowerCase(); if ("text/javascript".equals(lowerCaseContentType) || "application/javascript".equals(lowerCaseContentType)) { buf.append(jsLibraryFile.getJavascriptLibraryCode()); } else { logger.info( "Ignoring file {} for use as a Javascript library, content type {} not allowed. Use text/javascript or application/javascript.", new Object[] {jsLibraryFile.getName(), contentType}); } } else { logger.info( "Ignoring file {} for use as a Javascript library, content type not set. Use text/javascript or application/javascript.", new Object[] {jsLibraryFile.getName(), contentType}); } } tx.success(); } catch (FrameworkException fex) { logger.warn("", fex); } return buf.toString(); }
@Override public void processMessage(WebSocketMessage webSocketData) { final App app = StructrApp.getInstance(getWebSocket().getSecurityContext()); final String id = webSocketData.getId(); final Map<String, Object> nodeData = webSocketData.getNodeData(); final String source = (String) nodeData.get("source"); final String name = (String) nodeData.get("name"); // check for ID if (id == null) { getWebSocket() .send( MessageBuilder.status().code(422).message("Cannot create widget without id").build(), true); return; } // check if parent node with given ID exists DOMNode node = getDOMNode(id); if (node == null) { getWebSocket() .send(MessageBuilder.status().code(404).message("Node not found").build(), true); return; } try { // convertFromInput PropertyMap properties = new PropertyMap(); properties.put(AbstractNode.type, Widget.class.getSimpleName()); properties.put(AbstractNode.name, name); properties.put(Widget.source, source); app.create(Widget.class, properties); } catch (Throwable t) { logger.log(Level.WARNING, t.toString()); // send exception getWebSocket().send(MessageBuilder.status().code(422).message(t.toString()).build(), true); } }
/** * Return list of nodes which are not attached to a page and have no parent element (no incoming * CONTAINS rel) * * @param app * @param securityContext * @param webSocketData * @return * @throws FrameworkException */ protected static List<AbstractNode> getUnattachedNodes( final App app, final SecurityContext securityContext, final WebSocketMessage webSocketData) throws FrameworkException { final String sortOrder = webSocketData.getSortOrder(); final String sortKey = webSocketData.getSortKey(); final PropertyKey sortProperty = StructrApp.getConfiguration().getPropertyKeyForJSONName(DOMNode.class, sortKey); final Query query = StructrApp.getInstance(securityContext) .nodeQuery() .includeDeletedAndHidden() .sort(sortProperty) .order("desc".equals(sortOrder)); query.orTypes(DOMElement.class); query.orType(Content.class); query.orType(Template.class); // do search List<AbstractNode> filteredResults = new LinkedList(); List<? extends GraphObject> resultList = null; try (final Tx tx = app.tx()) { resultList = query.getAsList(); } catch (FrameworkException fex) { logger.warn("Exception occured", fex); } // determine which of the nodes have no incoming CONTAINS relationships and no page id for (GraphObject obj : resultList) { if (obj instanceof AbstractNode) { AbstractNode node = (AbstractNode) obj; if (!node.hasIncomingRelationships(DOMChildren.class) && node.getProperty(DOMNode.ownerDocument) == null && !(node instanceof ShadowDocument)) { filteredResults.add(node); } } } return filteredResults; }
@Override public InputStream createInputStream(long offset) throws IOException { ByteArrayInputStream bis = null; try (Tx tx = StructrApp.getInstance().tx()) { bis = new ByteArrayInputStream(getContent(RenderContext.EditMode.RAW).getBytes("UTF-8")); tx.success(); } catch (FrameworkException fex) { logger.log(Level.WARNING, "", fex); } return bis; }
@Override public String getName() { String name = null; try (Tx tx = StructrApp.getInstance().tx()) { name = getProperty(AbstractNode.name); tx.success(); } catch (FrameworkException fex) { logger.log(Level.SEVERE, "Error in getName() of page", fex); } return name; }
@Override public long getSize() { long size = 0L; try (Tx tx = StructrApp.getInstance().tx()) { size = getContent(RenderContext.EditMode.RAW).length(); tx.success(); } catch (FrameworkException fex) { logger.log(Level.SEVERE, "Error while last modified date of " + this, fex); } return size; }
@Override public boolean isHidden() { boolean hidden = true; try (Tx tx = StructrApp.getInstance().tx()) { hidden = getProperty(Page.hidden); tx.success(); } catch (FrameworkException fex) { logger.log(Level.SEVERE, "Error in isHidden() of page", fex); } return hidden; }