Search in sources :

Example 11 with Services

use of org.structr.core.Services in project structr by structr.

the class StructrUiTest method start.

@BeforeClass
public static void start() throws Exception {
    final long timestamp = System.currentTimeMillis();
    basePath = "/tmp/structr-test-" + timestamp + "-" + System.nanoTime();
    Settings.Services.setValue("NodeService HttpService SchemaService");
    Settings.ConnectionUrl.setValue(Settings.TestingConnectionUrl.getValue());
    // example for new configuration setup
    Settings.BasePath.setValue(basePath);
    Settings.DatabasePath.setValue(basePath + "/db");
    Settings.FilesPath.setValue(basePath + "/files");
    Settings.RelationshipCacheSize.setValue(1000);
    Settings.NodeCacheSize.setValue(1000);
    Settings.SuperUserName.setValue("superadmin");
    Settings.SuperUserPassword.setValue("sehrgeheim");
    Settings.ApplicationTitle.setValue("structr unit test app" + timestamp);
    Settings.ApplicationHost.setValue(host);
    Settings.HttpPort.setValue(httpPort);
    Settings.Servlets.setValue("JsonRestServlet WebSocketServlet HtmlServlet");
    final Services services = Services.getInstance();
    // wait for service layer to be initialized
    do {
        try {
            Thread.sleep(100);
        } catch (Throwable t) {
        }
    } while (!services.isInitialized());
    securityContext = SecurityContext.getSuperUserInstance();
    app = StructrApp.getInstance(securityContext);
    graphDbCommand = app.command(GraphDatabaseCommand.class);
}
Also used : Services(org.structr.core.Services) GraphDatabaseCommand(org.structr.core.graph.GraphDatabaseCommand) BeforeClass(org.junit.BeforeClass)

Example 12 with Services

use of org.structr.core.Services in project structr by structr.

the class StructrXMPPModuleTest method startSystem.

@BeforeClass
public static void startSystem() {
    final Date now = new Date();
    final long timestamp = now.getTime();
    basePath = "/tmp/structr-test-" + timestamp;
    Settings.Services.setValue("NodeService LogService SchemaService HttpService AgentService");
    Settings.ConnectionUrl.setValue(Settings.TestingConnectionUrl.getValue());
    // example for new configuration setup
    Settings.BasePath.setValue(basePath);
    Settings.DatabasePath.setValue(basePath + "/db");
    Settings.FilesPath.setValue(basePath + "/files");
    Settings.RelationshipCacheSize.setValue(1000);
    Settings.NodeCacheSize.setValue(1000);
    Settings.SuperUserName.setValue("superadmin");
    Settings.SuperUserPassword.setValue("sehrgeheim");
    Settings.ApplicationTitle.setValue("structr unit test app" + timestamp);
    Settings.ApplicationHost.setValue(host);
    Settings.HttpPort.setValue(httpPort);
    Settings.Servlets.setValue("JsonRestServlet");
    final Services services = Services.getInstance();
    // wait for service layer to be initialized
    do {
        try {
            Thread.sleep(100);
        } catch (Throwable t) {
        }
    } while (!services.isInitialized());
    securityContext = SecurityContext.getSuperUserInstance();
    app = StructrApp.getInstance(securityContext);
}
Also used : Services(org.structr.core.Services) Date(java.util.Date) BeforeClass(org.junit.BeforeClass)

Example 13 with Services

use of org.structr.core.Services in project structr by structr.

the class StructrWebSocket method onWebSocketText.

@Override
public void onWebSocketText(final String data) {
    if (!Services.getInstance().isInitialized()) {
        // send 401 Authentication Required
        send(MessageBuilder.status().code(503).message("System is not initialized yet").build(), true);
    }
    final Services servicesInstance = Services.getInstance();
    // wait for service layer to be initialized
    while (!servicesInstance.isInitialized()) {
        try {
            Thread.sleep(1000);
        } catch (InterruptedException iex) {
        }
    }
    if (data == null) {
        logger.warn("Empty text message received.");
        return;
    }
    logger.debug("############################################################ RECEIVED \n{}", data.substring(0, Math.min(data.length(), 1000)));
    // parse web socket data from JSON
    final WebSocketMessage webSocketData = gson.fromJson(data, WebSocketMessage.class);
    final App app = StructrApp.getInstance(securityContext);
    final String command = webSocketData.getCommand();
    final Class type = commandSet.get(command);
    final String sessionIdFromMessage = webSocketData.getSessionId();
    if (type != null) {
        try (final Tx tx = app.tx()) {
            if (sessionIdFromMessage != null) {
                // try to authenticated this connection by sessionId
                authenticate(SessionHelper.getShortSessionId(sessionIdFromMessage), command.equals("PING"));
            }
            // we only permit LOGIN commands if authentication based on sessionId was not successful
            if (!isAuthenticated() && !type.equals(LoginCommand.class)) {
                // send 401 Authentication Required
                send(MessageBuilder.status().code(401).message("").build(), true);
                tx.success();
                return;
            }
            tx.success();
        } catch (DatabaseServiceNotAvailableException dbsnae) {
            logger.warn(dbsnae.getMessage());
        } catch (FrameworkException t) {
            logger.warn("Unable to parse message.", t);
        }
        // process message
        try {
            AbstractCommand abstractCommand = (AbstractCommand) type.newInstance();
            abstractCommand.setWebSocket(this);
            abstractCommand.setSession(session);
            abstractCommand.setCallback(webSocketData.getCallback());
            if (!(abstractCommand instanceof PingCommand)) {
                if (securityContext != null) {
                    final HttpSession session = SessionHelper.getSessionBySessionId(securityContext.getSessionId());
                    if (session != null) {
                        session.setMaxInactiveInterval(Services.getGlobalSessionTimeout());
                        try {
                            // Workaround to update lastAccessedTime() in Jetty's session via reflection
                            final Method accessMethod = ((org.eclipse.jetty.server.session.Session) session).getClass().getDeclaredMethod("access", long.class);
                            accessMethod.setAccessible(true);
                            accessMethod.invoke((org.eclipse.jetty.server.session.Session) session, System.currentTimeMillis());
                        } catch (Exception ex) {
                            logger.error("Access to method Session.access() via reflection failed: ", ex);
                        }
                    }
                }
            }
            // transactions in case of bulk processing commands etc.
            if (abstractCommand.requiresEnclosingTransaction()) {
                try (final Tx tx = app.tx()) {
                    // store authenticated-Flag in webSocketData
                    // so the command can access it
                    webSocketData.setSessionValid(isAuthenticated());
                    abstractCommand.processMessage(webSocketData);
                    // commit transaction
                    tx.success();
                }
            } else {
                try (final Tx tx = app.tx()) {
                    // store authenticated-Flag in webSocketData
                    // so the command can access it
                    webSocketData.setSessionValid(isAuthenticated());
                    // commit transaction
                    tx.success();
                }
                // process message without transaction context!
                abstractCommand.processMessage(webSocketData);
            }
        } catch (FrameworkException | InstantiationException | IllegalAccessException t) {
            try (final Tx tx = app.tx()) {
                // send 400 Bad Request
                if (t instanceof FrameworkException) {
                    final FrameworkException fex = (FrameworkException) t;
                    send(MessageBuilder.status().code(fex.getStatus()).message(fex.toString()).jsonErrorObject(fex.toJSON()).callback(webSocketData.getCallback()).build(), true);
                } else {
                    send(MessageBuilder.status().code(400).message(t.toString()).build(), true);
                }
                // commit transaction
                tx.success();
            } catch (FrameworkException fex) {
                logger.warn("Unable to send websocket result: {}", fex.getMessage());
            }
            return;
        }
    } else {
        logger.warn("Unknown command {}", command);
        // send 400 Bad Request
        send(MessageBuilder.status().code(400).message("Unknown command").build(), true);
        return;
    }
}
Also used : StructrApp(org.structr.core.app.StructrApp) App(org.structr.core.app.App) Tx(org.structr.core.graph.Tx) FrameworkException(org.structr.common.error.FrameworkException) HttpSession(javax.servlet.http.HttpSession) AbstractCommand(org.structr.websocket.command.AbstractCommand) DatabaseServiceNotAvailableException(org.structr.common.error.DatabaseServiceNotAvailableException) Method(java.lang.reflect.Method) FrameworkException(org.structr.common.error.FrameworkException) DatabaseServiceNotAvailableException(org.structr.common.error.DatabaseServiceNotAvailableException) IOException(java.io.IOException) PingCommand(org.structr.websocket.command.PingCommand) Services(org.structr.core.Services) WebSocketMessage(org.structr.websocket.message.WebSocketMessage)

Example 14 with Services

use of org.structr.core.Services in project structr by structr.

the class StructrDataFeedsModuleTest method startSystem.

@BeforeClass
public static void startSystem() {
    final Date now = new Date();
    final long timestamp = now.getTime();
    basePath = "/tmp/structr-test-" + timestamp;
    Settings.Services.setValue("NodeService LogService SchemaService HttpService AgentService");
    Settings.ConnectionUrl.setValue(Settings.TestingConnectionUrl.getValue());
    // example for new configuration setup
    Settings.BasePath.setValue(basePath);
    Settings.DatabasePath.setValue(basePath + "/db");
    Settings.FilesPath.setValue(basePath + "/files");
    Settings.RelationshipCacheSize.setValue(1000);
    Settings.NodeCacheSize.setValue(1000);
    Settings.SuperUserName.setValue("superadmin");
    Settings.SuperUserPassword.setValue("sehrgeheim");
    Settings.ApplicationTitle.setValue("structr unit test app" + timestamp);
    Settings.ApplicationHost.setValue(host);
    Settings.HttpPort.setValue(httpPort);
    Settings.Servlets.setValue("JsonRestServlet");
    // Settings.LogSchemaOutput.setValue(true);
    final Services services = Services.getInstance();
    // wait for service layer to be initialized
    do {
        try {
            Thread.sleep(100);
        } catch (Throwable t) {
        }
    } while (!services.isInitialized());
    securityContext = SecurityContext.getSuperUserInstance();
    app = StructrApp.getInstance(securityContext);
}
Also used : Services(org.structr.core.Services) Date(java.util.Date) BeforeClass(org.junit.BeforeClass)

Example 15 with Services

use of org.structr.core.Services in project structr by structr.

the class CacheExpression method evaluate.

@Override
public Object evaluate(final ActionContext ctx, final GraphObject entity) throws FrameworkException, UnlicensedException {
    if (keyExpression == null) {
        return "Error: cache(): key expression may not be empty.";
    }
    final Object keyObject = keyExpression.evaluate(ctx, entity);
    if (keyObject == null) {
        return "Error: cache(): key may not be empty.";
    }
    final String key = keyObject.toString();
    if (StringUtils.isBlank(key)) {
        return "Error: cache(): key may not be empty.";
    }
    if (timeoutExpression == null) {
        return "Error: cache(): timeout expression may not be empty.";
    }
    final Object timeoutValue = timeoutExpression.evaluate(ctx, entity);
    if (timeoutValue == null || !(timeoutValue instanceof Number)) {
        return "Error: cache(): timeout must be non-empty and a number.";
    }
    if (valueExpression == null) {
        return "Error: cache(): value expression may not be empty.";
    }
    final long timeout = ((Number) timeoutValue).longValue();
    // get or create new cached value
    final Services services = Services.getInstance();
    CachedValue cachedValue = (CachedValue) services.getAttribute(key);
    if (cachedValue == null) {
        cachedValue = new CachedValue(timeout);
        services.setAttribute(key, cachedValue);
    } else {
        cachedValue.setTimeoutSeconds(timeout);
    }
    // refresh value from value expression (this is the only place the value expression is evaluated)
    if (cachedValue.isExpired()) {
        cachedValue.refresh(valueExpression.evaluate(ctx, entity));
    }
    return cachedValue.getValue();
}
Also used : Services(org.structr.core.Services) GraphObject(org.structr.core.GraphObject)

Aggregations

Services (org.structr.core.Services)30 BeforeClass (org.junit.BeforeClass)21 Date (java.util.Date)20 SuperUserAuthenticator (org.structr.core.auth.SuperUserAuthenticator)5 DefaultResourceProvider (org.structr.rest.DefaultResourceProvider)5 GraphDatabaseCommand (org.structr.core.graph.GraphDatabaseCommand)4 Tx (org.structr.core.graph.Tx)2 IOException (java.io.IOException)1 Method (java.lang.reflect.Method)1 HttpSession (javax.servlet.http.HttpSession)1 Task (org.structr.agent.Task)1 SettingsGroup (org.structr.api.config.SettingsGroup)1 Service (org.structr.api.service.Service)1 StructrServices (org.structr.api.service.StructrServices)1 Attr (org.structr.api.util.html.Attr)1 Document (org.structr.api.util.html.Document)1 Tag (org.structr.api.util.html.Tag)1 SecurityContext (org.structr.common.SecurityContext)1 DatabaseServiceNotAvailableException (org.structr.common.error.DatabaseServiceNotAvailableException)1 FrameworkException (org.structr.common.error.FrameworkException)1