use of org.structr.core.entity.AbstractNode in project structr by structr.
the class HtmlServlet method findFirstNodeByName.
/**
* Find first node whose name matches the last part of the given path
*
* @param securityContext
* @param request
* @param path
* @return node
* @throws FrameworkException
*/
private AbstractNode findFirstNodeByName(final SecurityContext securityContext, final HttpServletRequest request, final String path) throws FrameworkException {
final String name = PathHelper.getName(path);
if (!name.isEmpty()) {
logger.debug("Requested name: {}", name);
final Query query = StructrApp.getInstance(securityContext).nodeQuery();
final ConfigurationProvider config = StructrApp.getConfiguration();
if (!possiblePropertyNamesForEntityResolving.isEmpty()) {
query.and();
resolvePossiblePropertyNamesForObjectResolution(config, query, name);
query.parent();
}
final Result results = query.getResult();
logger.debug("{} results", results.size());
request.setAttribute(POSSIBLE_ENTRY_POINTS_KEY, results.getResults());
return (results.size() > 0 ? (AbstractNode) results.get(0) : null);
}
return null;
}
use of org.structr.core.entity.AbstractNode in project structr by structr.
the class HtmlServlet method doHead.
@Override
protected void doHead(final HttpServletRequest request, final HttpServletResponse response) {
final Authenticator auth = getConfig().getAuthenticator();
SecurityContext securityContext;
List<Page> pages = null;
boolean requestUriContainsUuids = false;
final App app;
try {
assertInitialized();
String path = request.getPathInfo();
// isolate request authentication in a transaction
try (final Tx tx = StructrApp.getInstance().tx()) {
securityContext = auth.initializeAndExamineRequest(request, response);
tx.success();
}
app = StructrApp.getInstance(securityContext);
try (final Tx tx = app.tx()) {
// Ensure access mode is frontend
securityContext.setAccessMode(AccessMode.Frontend);
request.setCharacterEncoding("UTF-8");
// Important: Set character encoding before calling response.getWriter() !!, see Servlet Spec 5.4
response.setCharacterEncoding("UTF-8");
response.setContentLength(0);
boolean dontCache = false;
logger.debug("Path info {}", path);
// don't continue on redirects
if (response.getStatus() == 302) {
tx.success();
return;
}
final Principal user = securityContext.getUser(false);
if (user != null) {
// Don't cache if a user is logged in
dontCache = true;
}
final RenderContext renderContext = RenderContext.getInstance(securityContext, request, response);
renderContext.setResourceProvider(config.getResourceProvider());
final EditMode edit = renderContext.getEditMode(user);
DOMNode rootElement = null;
AbstractNode dataNode = null;
String[] uriParts = PathHelper.getParts(path);
if ((uriParts == null) || (uriParts.length == 0)) {
// find a visible page
rootElement = findIndexPage(securityContext, pages, edit);
logger.debug("No path supplied, trying to find index page");
} else {
if (rootElement == null) {
rootElement = findPage(securityContext, pages, path, edit);
} else {
dontCache = true;
}
}
if (rootElement == null) {
// No page found
// Look for a file
File file = findFile(securityContext, request, path);
if (file != null) {
// streamFile(securityContext, file, request, response, edit);
tx.success();
return;
}
if (uriParts != null) {
// store remaining path parts in request
Matcher matcher = threadLocalUUIDMatcher.get();
for (int i = 0; i < uriParts.length; i++) {
request.setAttribute(uriParts[i], i);
matcher.reset(uriParts[i]);
// set to "true" if part matches UUID pattern
requestUriContainsUuids |= matcher.matches();
}
}
if (!requestUriContainsUuids) {
// Try to find a data node by name
dataNode = findFirstNodeByName(securityContext, request, path);
} else {
dataNode = findNodeByUuid(securityContext, PathHelper.getName(path));
}
if (dataNode != null && !(dataNode instanceof Linkable)) {
// Last path part matches a data node
// Remove last path part and try again searching for a page
// clear possible entry points
request.removeAttribute(POSSIBLE_ENTRY_POINTS_KEY);
rootElement = findPage(securityContext, pages, StringUtils.substringBeforeLast(path, PathHelper.PATH_SEP), edit);
renderContext.setDetailsDataObject(dataNode);
// Start rendering on data node
if (rootElement == null && dataNode instanceof DOMNode) {
rootElement = ((DOMNode) dataNode);
}
}
}
// look for pages with HTTP Basic Authentication (must be done as superuser)
if (rootElement == null) {
final HttpBasicAuthResult authResult = checkHttpBasicAuth(request, response, path);
switch(authResult.authState()) {
// Element with Basic Auth found and authentication succeeded
case Authenticated:
final Linkable result = authResult.getRootElement();
if (result instanceof Page) {
rootElement = (DOMNode) result;
renderContext.pushSecurityContext(authResult.getSecurityContext());
} else if (result instanceof File) {
// streamFile(authResult.getSecurityContext(), (File)result, request, response, EditMode.NONE);
tx.success();
return;
}
break;
// Page with Basic Auth found but not yet authenticated
case MustAuthenticate:
tx.success();
return;
// no Basic Auth for given path, go on
case NoBasicAuth:
break;
}
}
// Still nothing found, do error handling
if (rootElement == null) {
// Check if security context has set an 401 status
if (response.getStatus() == HttpServletResponse.SC_UNAUTHORIZED) {
try {
UiAuthenticator.writeUnauthorized(response);
} catch (IllegalStateException ise) {
}
} else {
rootElement = notFound(response, securityContext);
}
}
if (rootElement == null) {
// no content
response.setContentLength(0);
response.getOutputStream().close();
tx.success();
return;
}
// check dont cache flag on page (if root element is a page)
// but don't modify true to false
dontCache |= rootElement.dontCache();
if (EditMode.WIDGET.equals(edit) || dontCache) {
setNoCacheHeaders(response);
}
if (!securityContext.isVisible(rootElement)) {
rootElement = notFound(response, securityContext);
if (rootElement == null) {
tx.success();
return;
}
}
if (securityContext.isVisible(rootElement)) {
if (!EditMode.WIDGET.equals(edit) && !dontCache && notModifiedSince(request, response, rootElement, dontCache)) {
response.getOutputStream().close();
} else {
// prepare response
response.setCharacterEncoding("UTF-8");
String contentType = rootElement.getProperty(StructrApp.key(Page.class, "contentType"));
if (contentType == null) {
// Default
contentType = "text/html;charset=UTF-8";
}
if (contentType.equals("text/html")) {
contentType = contentType.concat(";charset=UTF-8");
}
response.setContentType(contentType);
setCustomResponseHeaders(response);
response.getOutputStream().close();
}
} else {
notFound(response, securityContext);
response.getOutputStream().close();
}
tx.success();
} catch (Throwable fex) {
logger.error("Exception while processing request", fex);
}
} catch (FrameworkException t) {
logger.error("Exception while processing request", t);
UiAuthenticator.writeInternalServerError(response);
}
}
use of org.structr.core.entity.AbstractNode in project structr by structr.
the class AbstractCommand method getNode.
/**
* Returns the node with the given id.
*
* @param id
* @return the node
*/
public AbstractNode getNode(final String id) {
final SecurityContext securityContext = getWebSocket().getSecurityContext();
final App app = StructrApp.getInstance(securityContext);
try (final Tx tx = app.tx()) {
final AbstractNode node = (AbstractNode) app.getNodeById(id);
tx.success();
return node;
} catch (FrameworkException fex) {
logger.warn("Unable to get node", fex);
}
return null;
}
use of org.structr.core.entity.AbstractNode in project structr by structr.
the class AppendChildCommand method processMessage.
@Override
public void processMessage(final WebSocketMessage webSocketData) {
String id = webSocketData.getId();
Map<String, Object> nodeData = webSocketData.getNodeData();
String parentId = (String) nodeData.get("parentId");
// check node to append
if (id == null) {
getWebSocket().send(MessageBuilder.status().code(422).message("Cannot append node, no id is given").build(), true);
return;
}
// check for parent ID
if (parentId == null) {
getWebSocket().send(MessageBuilder.status().code(422).message("Cannot add node without parentId").build(), true);
return;
}
// check if parent node with given ID exists
AbstractNode parentNode = getNode(parentId);
if (parentNode == null) {
getWebSocket().send(MessageBuilder.status().code(404).message("Parent node not found").build(), true);
return;
}
if (parentNode instanceof DOMNode) {
DOMNode parentDOMNode = getDOMNode(parentId);
if (parentDOMNode == null) {
getWebSocket().send(MessageBuilder.status().code(422).message("Parent node is no DOM node").build(), true);
return;
}
DOMNode node = (DOMNode) getDOMNode(id);
// append node to parent
if (node != null) {
parentDOMNode.appendChild(node);
}
} else {
// send exception
getWebSocket().send(MessageBuilder.status().code(422).message("Cannot use given node, not instance of DOMNode").build(), true);
}
}
use of org.structr.core.entity.AbstractNode in project structr by structr.
the class AppendContentItemCommand method processMessage.
@Override
public void processMessage(final WebSocketMessage webSocketData) {
String id = webSocketData.getId();
Map<String, Object> nodeData = webSocketData.getNodeData();
String parentId = (String) nodeData.get("parentId");
// check node to append
if (id == null) {
getWebSocket().send(MessageBuilder.status().code(422).message("Cannot append node, no id is given").build(), true);
return;
}
// check for parent ID
if (parentId == null) {
getWebSocket().send(MessageBuilder.status().code(422).message("Cannot append node without parentId").build(), true);
return;
}
// never append to self
if (parentId.equals(id)) {
getWebSocket().send(MessageBuilder.status().code(422).message("Cannot append node as its own child.").build(), true);
return;
}
// check if parent node with given ID exists
AbstractNode parentNode = getNode(parentId);
if (parentNode == null) {
getWebSocket().send(MessageBuilder.status().code(404).message("Parent node not found").build(), true);
return;
}
if (parentNode instanceof ContentContainer) {
ContentContainer container = (ContentContainer) parentNode;
ContentItem item = (ContentItem) getNode(id);
if (item != null) {
try {
final List<ContentItem> items = container.getItems();
items.add(item);
container.setProperty(StructrApp.key(ContentContainer.class, "items"), items);
TransactionCommand.registerNodeCallback(item, callback);
} catch (FrameworkException ex) {
logger.error("", ex);
getWebSocket().send(MessageBuilder.status().code(422).message("Cannot append content item").build(), true);
}
}
} else {
// send exception
getWebSocket().send(MessageBuilder.status().code(422).message("Parent node is not instance of ContentContainer").build(), true);
}
}
Aggregations