use of org.structr.core.entity.AbstractNode in project structr by structr.
the class SearchAndSortingTest method test09SearchByEmptyStringField.
@Test
public void test09SearchByEmptyStringField() {
try {
PropertyMap props = new PropertyMap();
AbstractNode node = createTestNode(TestOne.class, props);
try (final Tx tx = app.tx()) {
Result result = app.nodeQuery(TestOne.class).and(TestOne.aString, null).includeDeletedAndHidden().getResult();
assertTrue(result.size() == 1);
assertTrue(result.get(0).equals(node));
}
} catch (FrameworkException ex) {
logger.warn("", ex);
logger.error(ex.toString());
fail("Unexpected exception");
}
}
use of org.structr.core.entity.AbstractNode in project structr by structr.
the class SearchAndSortingTest method test11SearchByEmptyIntField.
@Test
public void test11SearchByEmptyIntField() {
try {
PropertyMap props = new PropertyMap();
AbstractNode node = createTestNode(TestOne.class, props);
try (final Tx tx = app.tx()) {
Result result = app.nodeQuery(TestOne.class).and(TestOne.anInt, null).includeDeletedAndHidden().getResult();
assertTrue(result.size() == 1);
assertTrue(result.get(0).equals(node));
}
} catch (Throwable ex) {
logger.warn("", ex);
logger.error(ex.toString());
fail("Unexpected exception");
}
}
use of org.structr.core.entity.AbstractNode in project structr by structr.
the class HtmlServlet method doGet.
@Override
protected void doGet(final HttpServletRequest request, final HttpServletResponse response) {
final Authenticator auth = getConfig().getAuthenticator();
List<Page> pages = null;
boolean requestUriContainsUuids = false;
SecurityContext securityContext;
final App app;
try {
assertInitialized();
final String path = request.getPathInfo() != null ? request.getPathInfo() : "/";
// check for registration (has its own tx because of write access
if (checkRegistration(auth, request, response, path)) {
return;
}
// check for registration (has its own tx because of write access
if (checkResetPassword(auth, request, response, path)) {
return;
}
// isolate request authentication in a transaction
try (final Tx tx = StructrApp.getInstance().tx()) {
securityContext = auth.initializeAndExamineRequest(request, response);
tx.success();
} catch (AuthenticationException aex) {
response.sendError(HttpServletResponse.SC_UNAUTHORIZED);
return;
}
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");
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;
final 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
// In case of a file, try to find a file with the query string in the filename
final String queryString = request.getQueryString();
// Look for a file, first include the query string
File file = findFile(securityContext, request, path + (queryString != null ? "?" + queryString : ""));
// If no file with query string in the file name found, try without query string
if (file == null) {
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
final 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)) {
if (dataNode != null) {
// 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) {
// check visibleForSite here as well
if (!(dataNode instanceof Page) || isVisibleForSite(request, (Page) dataNode)) {
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;
securityContext = authResult.getSecurityContext();
renderContext.pushSecurityContext(securityContext);
} 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:
final Page errorPage = StructrApp.getInstance().nodeQuery(Page.class).and(StructrApp.key(Page.class, "showOnErrorCodes"), "401", false).getFirst();
if (errorPage != null && isVisibleForSite(request, errorPage)) {
// set error page
rootElement = errorPage;
// don't cache the error page
dontCache = true;
} else {
// send error
response.sendError(HttpServletResponse.SC_UNAUTHORIZED);
tx.success();
return;
}
break;
// no Basic Auth for given path, go on
case NoBasicAuth:
break;
}
}
// Still nothing found, do error handling
if (rootElement == null) {
rootElement = notFound(response, securityContext);
}
if (rootElement == null) {
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;
}
} else {
if (!EditMode.WIDGET.equals(edit) && !dontCache && notModifiedSince(request, response, rootElement, dontCache)) {
ServletOutputStream out = response.getOutputStream();
out.flush();
// response.flushBuffer();
out.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);
final boolean createsRawData = rootElement.getProperty(StructrApp.key(Page.class, "pageCreatesRawData"));
// async or not?
if (isAsync && !createsRawData) {
final AsyncContext async = request.startAsync();
final ServletOutputStream out = async.getResponse().getOutputStream();
final AtomicBoolean finished = new AtomicBoolean(false);
final DOMNode rootNode = rootElement;
threadPool.submit(new Runnable() {
@Override
public void run() {
try (final Tx tx = app.tx()) {
// render
rootNode.render(renderContext, 0);
finished.set(true);
tx.success();
} catch (Throwable t) {
t.printStackTrace();
logger.warn("Error while rendering page {}: {}", rootNode.getName(), t.getMessage());
try {
response.sendError(HttpServletResponse.SC_INTERNAL_SERVER_ERROR);
finished.set(true);
} catch (IOException ex) {
logger.warn("", ex);
}
}
}
});
// start output write listener
out.setWriteListener(new WriteListener() {
@Override
public void onWritePossible() throws IOException {
try {
final Queue<String> queue = renderContext.getBuffer().getQueue();
while (out.isReady()) {
String buffer = null;
synchronized (queue) {
buffer = queue.poll();
}
if (buffer != null) {
out.print(buffer);
} else {
if (finished.get()) {
async.complete();
// prevent this block from being called again
break;
}
Thread.sleep(1);
}
}
} catch (Throwable t) {
logger.warn("", t);
}
}
@Override
public void onError(Throwable t) {
logger.warn("", t);
}
});
} else {
final StringRenderBuffer buffer = new StringRenderBuffer();
renderContext.setBuffer(buffer);
// render
rootElement.render(renderContext, 0);
try {
response.getOutputStream().write(buffer.getBuffer().toString().getBytes("utf-8"));
response.getOutputStream().flush();
response.getOutputStream().close();
} catch (IOException ioex) {
logger.warn("", ioex);
}
}
}
}
tx.success();
} catch (FrameworkException fex) {
logger.error("Exception while processing request: {}", fex.getMessage());
}
} catch (FrameworkException fex) {
logger.error("Exception while processing request: {}", fex.getMessage());
UiAuthenticator.writeFrameworkException(response, fex);
} catch (IOException ioex) {
logger.error("Exception while processing request: {}", ioex.getMessage());
UiAuthenticator.writeInternalServerError(response);
}
}
use of org.structr.core.entity.AbstractNode in project structr by structr.
the class WebsocketController method broadcast.
private void broadcast(final WebSocketMessage webSocketData, final String exemptedSessionId) {
// session must be valid to be received by the client
webSocketData.setSessionValid(true);
final String pagePath = (String) webSocketData.getNodeData().get("pagePath");
final String encodedPath = URIUtil.encodePath(pagePath);
final List<StructrWebSocket> clientsToRemove = new LinkedList<>();
final List<? extends GraphObject> result = webSocketData.getResult();
final String command = webSocketData.getCommand();
final GraphObject obj = webSocketData.getGraphObject();
String message;
// create message
for (StructrWebSocket socket : clients) {
String clientPagePath = socket.getPagePath();
if (clientPagePath != null && !clientPagePath.equals(encodedPath)) {
continue;
}
Session session = socket.getSession();
if (session != null && socket.isAuthenticated()) {
final SecurityContext securityContext = socket.getSecurityContext();
if (exemptedSessionId != null && exemptedSessionId.equals(securityContext.getSessionId())) {
// session id is supposed to be exempted from this broadcast message
continue;
}
// THEN skip sending a message
if (obj instanceof AbstractNode) {
final AbstractNode node = (AbstractNode) obj;
if (node.isHidden() || !securityContext.isVisible(node)) {
continue;
}
} else {
if (!socket.isPrivilegedUser(socket.getCurrentUser())) {
continue;
}
}
if (result != null && !result.isEmpty() && BroadcastCommands.contains(command)) {
final WebSocketMessage clientData = webSocketData.copy();
clientData.setResult(filter(securityContext, result));
message = gson.toJson(clientData, WebSocketMessage.class);
} else {
message = gson.toJson(webSocketData, WebSocketMessage.class);
}
try {
session.getRemote().sendString(message);
} catch (Throwable t) {
if (t instanceof WebSocketException) {
WebSocketException wse = (WebSocketException) t;
if ("RemoteEndpoint unavailable, current state [CLOSED], expecting [OPEN or CONNECTED]".equals(wse.getMessage())) {
clientsToRemove.add(socket);
}
}
logger.debug("Error sending message to client.", t);
}
}
}
for (StructrWebSocket s : clientsToRemove) {
unregisterClient(s);
logger.warn("Client removed from broadcast list: {}", s);
}
}
use of org.structr.core.entity.AbstractNode in project structr by structr.
the class ListSchemaPropertiesCommand method processMessage.
@Override
public void processMessage(final WebSocketMessage webSocketData) {
final String view = (String) webSocketData.getNodeData().get("view");
final String id = webSocketData.getId();
final List<GraphObject> result = new LinkedList();
if (view != null) {
if (id != null) {
AbstractNode schemaObject = getNode(id);
if (schemaObject != null) {
final ConfigurationProvider config = StructrApp.getConfiguration();
String typeName = schemaObject.getProperty(AbstractNode.name);
if (typeName == null && schemaObject instanceof SchemaRelationshipNode) {
typeName = ((SchemaRelationshipNode) schemaObject).getClassName();
}
Class type = config.getNodeEntityClass(typeName);
if (type == null || GenericNode.class.equals(type)) {
type = config.getRelationshipEntityClass(typeName);
}
if (type != null) {
final Set<PropertyKey> allProperties = config.getPropertySet(type, PropertyView.All);
final Set<PropertyKey> viewProperties = config.getPropertySet(type, view);
final Set<PropertyKey> parentProperties = config.getPropertySet(type.getSuperclass(), view);
for (final PropertyKey key : allProperties) {
final String declaringClass = key.getDeclaringClass() != null ? key.getDeclaringClass().getSimpleName() : "GraphObject";
final String propertyName = key.jsonName();
final GraphObjectMap property = new GraphObjectMap();
final Class valueType = key.valueType();
String valueTypeName = "Unknown";
boolean _isDisabled = false;
if (valueType != null) {
valueTypeName = valueType.getSimpleName();
}
// (since it has to be configured there instead of locally)
if (parentProperties.contains(key)) {
_isDisabled = true;
}
property.put(AbstractNode.name, propertyName);
property.put(isSelected, viewProperties.contains(key));
property.put(isDisabled, _isDisabled);
property.put(SchemaProperty.propertyType, valueTypeName);
property.put(SchemaProperty.notNull, key.isNotNull());
property.put(SchemaProperty.unique, key.isUnique());
property.put(SchemaProperty.isDynamic, key.isDynamic());
property.put(SchemaProperty.declaringClass, declaringClass);
// store in result
result.add(property);
}
} else {
getWebSocket().send(MessageBuilder.status().code(404).message("Type " + typeName + " not found.").build(), true);
}
} else {
getWebSocket().send(MessageBuilder.status().code(404).message("Schema node with ID " + id + " not found.").build(), true);
}
} else {
getWebSocket().send(MessageBuilder.status().code(422).message("LIST_SCHEMA_PROPERTIES needs an ID.").build(), true);
}
} else {
getWebSocket().send(MessageBuilder.status().code(422).message("LIST_SCHEMA_PROPERTIES needs a view name in nodeData.").build(), true);
}
webSocketData.setView(PropertyView.Ui);
webSocketData.setResult(result);
webSocketData.setRawResultCount(1);
// send only over local connection
getWebSocket().send(webSocketData, true);
}
Aggregations