Search in sources :

Example 1 with Container

use of org.openremote.container.Container in project openremote by openremote.

the class AbstractProtocol method start.

@Override
public final void start(Container container) throws Exception {
    LOG.fine("Starting protocol: " + getProtocolName());
    this.messageBrokerContext = container.getService(MessageBrokerSetupService.class).getContext();
    this.producerTemplate = container.getService(MessageBrokerService.class).getProducerTemplate();
    withLock(getProtocolName() + "::start", () -> {
        try {
            messageBrokerContext.addRoutes(new RouteBuilder() {

                @Override
                public void configure() throws Exception {
                    from(ACTUATOR_TOPIC).routeId("Actuator-" + getProtocolName()).process(exchange -> {
                        String protocolName = exchange.getIn().getHeader(ACTUATOR_TOPIC_TARGET_PROTOCOL, String.class);
                        if (!getProtocolName().equals(protocolName))
                            return;
                        processLinkedAttributeWrite(exchange.getIn().getBody(AttributeEvent.class));
                    });
                }
            });
            doStart(container);
        } catch (Exception ex) {
            throw new RuntimeException(ex);
        }
    });
}
Also used : java.util(java.util) ProtocolConfiguration(org.openremote.model.asset.agent.ProtocolConfiguration) ConnectionStatus(org.openremote.model.asset.agent.ConnectionStatus) ValidationFailure(org.openremote.model.ValidationFailure) MessageFilter(org.openremote.agent.protocol.filter.MessageFilter) Point(com.vividsolutions.jts.geom.Point) Level(java.util.logging.Level) AgentLink(org.openremote.model.asset.agent.AgentLink) GlobalLock.withLockReturning(org.openremote.container.concurrent.GlobalLock.withLockReturning) Container(org.openremote.container.Container) ProducerTemplate(org.apache.camel.ProducerTemplate) Coordinate(com.vividsolutions.jts.geom.Coordinate) MessageBrokerService(org.openremote.container.message.MessageBrokerService) Logger(java.util.logging.Logger) MessageBrokerSetupService(org.openremote.container.message.MessageBrokerSetupService) AssetMeta(org.openremote.model.asset.AssetMeta) TimeUnit(java.util.concurrent.TimeUnit) Consumer(java.util.function.Consumer) org.openremote.model.value(org.openremote.model.value) RouteBuilder(org.apache.camel.builder.RouteBuilder) TimerService(org.openremote.container.timer.TimerService) MessageBrokerContext(org.openremote.container.message.MessageBrokerContext) org.openremote.model.attribute(org.openremote.model.attribute) ProtocolDescriptor(org.openremote.model.asset.agent.ProtocolDescriptor) GeometryFactory(com.vividsolutions.jts.geom.GeometryFactory) ValueHolder(org.openremote.model.ValueHolder) AssetAttribute(org.openremote.model.asset.AssetAttribute) GlobalLock(org.openremote.container.concurrent.GlobalLock) GlobalLock.withLock(org.openremote.container.concurrent.GlobalLock.withLock) RouteBuilder(org.apache.camel.builder.RouteBuilder)

Example 2 with Container

use of org.openremote.container.Container in project openremote by openremote.

the class WebService method build.

protected Undertow.Builder build(Container container, Undertow.Builder builder) {
    LOG.info("Building web routing with custom routes: " + getPrefixRoutes().keySet());
    IdentityService identityService = container.hasService(IdentityService.class) ? container.getService(IdentityService.class) : null;
    ResteasyDeployment resteasyDeployment = createResteasyDeployment(container);
    HttpHandler apiHandler = createApiHandler(identityService, resteasyDeployment);
    HttpHandler jsApiHandler = createJsApiHandler(identityService, resteasyDeployment);
    requestPathHandler = new PathHandler(apiHandler);
    HttpHandler handler = exchange -> {
        String requestPath = exchange.getRequestPath();
        LOG.fine("Handling request: " + exchange.getRequestMethod() + " " + exchange.getRequestPath());
        // Other services can register routes here with a prefix patch match
        boolean handled = false;
        for (Map.Entry<String, HttpHandler> entry : getPrefixRoutes().entrySet()) {
            if (requestPath.startsWith(entry.getKey())) {
                LOG.fine("Handling with '" + entry.getValue().getClass().getName() + "' path prefix: " + entry.getKey());
                entry.getValue().handleRequest(exchange);
                handled = true;
                break;
            }
        }
        if (handled)
            return;
        // Redirect / to default realm
        if (requestPath.equals("/")) {
            LOG.fine("Handling root request, redirecting client to default realm: " + requestPath);
            new RedirectHandler(fromUri(exchange.getRequestURL()).replacePath(getDefaultRealm()).build().toString()).handleRequest(exchange);
            return;
        }
        // Serve JavaScript API with path /jsapi/*
        if (jsApiHandler != null && requestPath.startsWith(JSAPI_PATH)) {
            LOG.fine("Serving JS API call: " + requestPath);
            jsApiHandler.handleRequest(exchange);
            return;
        }
        // Serve /<realm>/index.html
        Matcher realmRootMatcher = PATTERN_REALM_ROOT.matcher(requestPath);
        if (getRealmIndexHandler() != null && realmRootMatcher.matches()) {
            LOG.fine("Serving index document of realm: " + requestPath);
            exchange.setRelativePath("/index.html");
            getRealmIndexHandler().handleRequest(exchange);
            return;
        }
        Matcher realmSubMatcher = PATTERN_REALM_SUB.matcher(requestPath);
        if (!realmSubMatcher.matches()) {
            exchange.setStatusCode(NOT_FOUND.getStatusCode());
            throw new WebApplicationException(NOT_FOUND);
        }
        // Extract realm from path and push it into REQUEST_HEADER_REALM header
        String realm = realmSubMatcher.group(1);
        // Move the realm from path segment to header
        exchange.getRequestHeaders().put(HttpString.tryFromString(REQUEST_HEADER_REALM), realm);
        // Rewrite path, remove realm segment
        URI url = fromUri(exchange.getRequestURL()).replacePath(realmSubMatcher.group(2)).build();
        exchange.setRequestURI(url.toString(), true);
        exchange.setRequestPath(url.getPath());
        exchange.setRelativePath(url.getPath());
        // Look for registered path handlers and fallback to API handler
        LOG.fine("Serving HTTP call: " + url.getPath());
        requestPathHandler.handleRequest(exchange);
    };
    handler = new WebServiceExceptions.RootUndertowExceptionHandler(devMode, handler);
    if (getBoolean(container.getConfig(), WEBSERVER_DUMP_REQUESTS, WEBSERVER_DUMP_REQUESTS_DEFAULT)) {
        handler = new RequestDumpingHandler(handler);
    }
    builder.setHandler(handler);
    return builder;
}
Also used : java.util(java.util) UriBuilder.fromUri(javax.ws.rs.core.UriBuilder.fromUri) JSAPIServlet(org.openremote.container.web.jsapi.JSAPIServlet) ServletInfo(io.undertow.servlet.api.ServletInfo) Undertow(io.undertow.Undertow) HttpString(io.undertow.util.HttpString) RedirectHandler(io.undertow.server.handlers.RedirectHandler) Servlets(io.undertow.servlet.Servlets) Container(org.openremote.container.Container) PathHandler(io.undertow.server.handlers.PathHandler) Matcher(java.util.regex.Matcher) ResteasyDeployment(org.jboss.resteasy.spi.ResteasyDeployment) ContainerService(org.openremote.container.ContainerService) UriBuilder(javax.ws.rs.core.UriBuilder) URI(java.net.URI) RequestDumpingHandler(io.undertow.server.handlers.RequestDumpingHandler) NOT_FOUND(javax.ws.rs.core.Response.Status.NOT_FOUND) ModelValueMessageBodyConverter(org.openremote.container.json.ModelValueMessageBodyConverter) Logger(java.util.logging.Logger) DeploymentManager(io.undertow.servlet.api.DeploymentManager) Inet4Address(java.net.Inet4Address) HttpServlet30Dispatcher(org.jboss.resteasy.plugins.server.servlet.HttpServlet30Dispatcher) CORSFilter(org.openremote.container.security.CORSFilter) HttpHandler(io.undertow.server.HttpHandler) Options(org.xnio.Options) IdentityService(org.openremote.container.security.IdentityService) MapAccess(org.openremote.container.util.MapAccess) ResteasyContextParameters(org.jboss.resteasy.plugins.server.servlet.ResteasyContextParameters) JacksonConfig(org.openremote.container.json.JacksonConfig) WebApplicationException(javax.ws.rs.WebApplicationException) DeploymentInfo(io.undertow.servlet.api.DeploymentInfo) Pattern(java.util.regex.Pattern) HttpHandler(io.undertow.server.HttpHandler) WebApplicationException(javax.ws.rs.WebApplicationException) Matcher(java.util.regex.Matcher) RedirectHandler(io.undertow.server.handlers.RedirectHandler) PathHandler(io.undertow.server.handlers.PathHandler) HttpString(io.undertow.util.HttpString) URI(java.net.URI) IdentityService(org.openremote.container.security.IdentityService) ResteasyDeployment(org.jboss.resteasy.spi.ResteasyDeployment) RequestDumpingHandler(io.undertow.server.handlers.RequestDumpingHandler)

Example 3 with Container

use of org.openremote.container.Container in project openremote by openremote.

the class Main method main.

public static void main(String[] args) throws Exception {
    List<ContainerService> services = new ArrayList<ContainerService>() {

        {
            addAll(Arrays.asList(new TimerService(), new ManagerExecutorService(), new I18NService(), new ManagerPersistenceService(), new MessageBrokerSetupService(), new ManagerIdentityService(), new SetupService(), new ClientEventService(), new RulesetStorageService(), new RulesService(), new AssetStorageService(), new AssetDatapointService(), new AssetAttributeLinkingService(), new AssetProcessingService(), new MessageBrokerService()));
            ServiceLoader.load(Protocol.class).forEach(this::add);
            addAll(Arrays.asList(new AgentService(), new SimulatorService(), new MapService(), new NotificationService(), new ConsoleAppService(), new ManagerWebService()));
        }
    };
    new Container(services).startBackground();
}
Also used : MessageBrokerSetupService(org.openremote.container.message.MessageBrokerSetupService) AssetStorageService(org.openremote.manager.asset.AssetStorageService) ConsoleAppService(org.openremote.manager.apps.ConsoleAppService) ArrayList(java.util.ArrayList) AssetProcessingService(org.openremote.manager.asset.AssetProcessingService) TimerService(org.openremote.container.timer.TimerService) ManagerIdentityService(org.openremote.manager.security.ManagerIdentityService) AssetDatapointService(org.openremote.manager.datapoint.AssetDatapointService) Container(org.openremote.container.Container) AgentService(org.openremote.manager.agent.AgentService) RulesService(org.openremote.manager.rules.RulesService) ManagerWebService(org.openremote.manager.web.ManagerWebService) SimulatorService(org.openremote.manager.simulator.SimulatorService) ClientEventService(org.openremote.manager.event.ClientEventService) Protocol(org.openremote.agent.protocol.Protocol) MapService(org.openremote.manager.map.MapService) RulesetStorageService(org.openremote.manager.rules.RulesetStorageService) I18NService(org.openremote.manager.i18n.I18NService) ManagerPersistenceService(org.openremote.manager.persistence.ManagerPersistenceService) NotificationService(org.openremote.manager.notification.NotificationService) AssetAttributeLinkingService(org.openremote.manager.asset.AssetAttributeLinkingService) ManagerExecutorService(org.openremote.manager.concurrent.ManagerExecutorService) MessageBrokerSetupService(org.openremote.container.message.MessageBrokerSetupService) SetupService(org.openremote.manager.setup.SetupService) ContainerService(org.openremote.container.ContainerService) MessageBrokerService(org.openremote.container.message.MessageBrokerService)

Example 4 with Container

use of org.openremote.container.Container in project openremote by openremote.

the class ClientEventService method init.

@Override
public void init(Container container) throws Exception {
    timerService = container.getService(TimerService.class);
    messageBrokerService = container.getService(MessageBrokerService.class);
    identityService = container.getService(ManagerIdentityService.class);
    eventSubscriptions = new EventSubscriptions(container.getService(TimerService.class), container.getService(ManagerExecutorService.class));
    MessageBrokerSetupService messageBrokerSetupService = container.getService(MessageBrokerSetupService.class);
    messageBrokerSetupService.getContext().getTypeConverterRegistry().addTypeConverters(new EventTypeConverters());
    messageBrokerSetupService.getContext().addRoutes(new RouteBuilder() {

        @Override
        public void configure() throws Exception {
            from("websocket://" + WEBSOCKET_EVENTS).routeId("FromClientWebsocketEvents").choice().when(header(WebsocketConstants.SESSION_OPEN)).process(exchange -> {
            // Do nothing except stop the exchanges
            }).stop().when(or(header(WebsocketConstants.SESSION_CLOSE), header(WebsocketConstants.SESSION_CLOSE_ERROR))).process(exchange -> {
                String sessionKey = getSessionKey(exchange);
                eventSubscriptions.cancelAll(sessionKey);
            }).stop().end().choice().when(bodyAs(String.class).startsWith(EventSubscription.MESSAGE_PREFIX)).convertBodyTo(EventSubscription.class).process(exchange -> {
                String sessionKey = getSessionKey(exchange);
                EventSubscription subscription = exchange.getIn().getBody(EventSubscription.class);
                AuthContext authContext = exchange.getIn().getHeader(Constants.AUTH_CONTEXT, AuthContext.class);
                if (eventSubscriptionAuthorizers.stream().anyMatch(authorizer -> authorizer.apply(authContext, subscription))) {
                    boolean restrictedUser = identityService.getIdentityProvider().isRestrictedUser(authContext.getUserId());
                    eventSubscriptions.update(sessionKey, restrictedUser, subscription);
                } else {
                    LOG.warning("Unauthorized subscription from '" + authContext.getUsername() + "' in realm '" + authContext.getAuthenticatedRealm() + "': " + subscription);
                    sendToSession(sessionKey, new UnauthorizedEventSubscription(subscription.getEventType()));
                }
            }).when(bodyAs(String.class).startsWith(CancelEventSubscription.MESSAGE_PREFIX)).convertBodyTo(CancelEventSubscription.class).process(exchange -> {
                String sessionKey = getSessionKey(exchange);
                eventSubscriptions.cancel(sessionKey, exchange.getIn().getBody(CancelEventSubscription.class));
            }).when(bodyAs(String.class).startsWith(SharedEvent.MESSAGE_PREFIX)).convertBodyTo(SharedEvent.class).process(exchange -> {
                SharedEvent event = exchange.getIn().getBody(SharedEvent.class);
                // If there is no timestamp in event, set to system time
                if (event.getTimestamp() <= 0) {
                    event.setTimestamp(timerService.getCurrentTimeMillis());
                }
            }).to(ClientEventService.CLIENT_EVENT_TOPIC).otherwise().process(exchange -> LOG.fine("Unsupported message body: " + exchange.getIn().getBody())).end();
            from(ClientEventService.CLIENT_EVENT_QUEUE).routeId("ToClientWebsocketEvents").choice().when(body().isInstanceOf(SharedEvent.class)).split(method(eventSubscriptions, "splitForSubscribers")).to("websocket://" + WEBSOCKET_EVENTS).end();
        }
    });
}
Also used : MessageBrokerService(org.openremote.container.message.MessageBrokerService) ManagerIdentityService(org.openremote.manager.security.ManagerIdentityService) AuthContext(org.openremote.container.security.AuthContext) Collection(java.util.Collection) CancelEventSubscription(org.openremote.model.event.shared.CancelEventSubscription) Exchange(org.apache.camel.Exchange) Constants(org.openremote.model.Constants) CopyOnWriteArraySet(java.util.concurrent.CopyOnWriteArraySet) Logger(java.util.logging.Logger) MessageBrokerSetupService(org.openremote.container.message.MessageBrokerSetupService) Container(org.openremote.container.Container) WebsocketConstants(org.openremote.container.web.socket.WebsocketConstants) SyslogEvent(org.openremote.model.syslog.SyslogEvent) RouteBuilder(org.apache.camel.builder.RouteBuilder) ContainerService(org.openremote.container.ContainerService) TimerService(org.openremote.container.timer.TimerService) UnauthorizedEventSubscription(org.openremote.model.event.shared.UnauthorizedEventSubscription) PredicateBuilder.or(org.apache.camel.builder.PredicateBuilder.or) ManagerExecutorService(org.openremote.manager.concurrent.ManagerExecutorService) EventSubscription(org.openremote.model.event.shared.EventSubscription) SharedEvent(org.openremote.model.event.shared.SharedEvent) Collections(java.util.Collections) CancelEventSubscription(org.openremote.model.event.shared.CancelEventSubscription) MessageBrokerSetupService(org.openremote.container.message.MessageBrokerSetupService) RouteBuilder(org.apache.camel.builder.RouteBuilder) AuthContext(org.openremote.container.security.AuthContext) UnauthorizedEventSubscription(org.openremote.model.event.shared.UnauthorizedEventSubscription) TimerService(org.openremote.container.timer.TimerService) ManagerIdentityService(org.openremote.manager.security.ManagerIdentityService) CancelEventSubscription(org.openremote.model.event.shared.CancelEventSubscription) UnauthorizedEventSubscription(org.openremote.model.event.shared.UnauthorizedEventSubscription) EventSubscription(org.openremote.model.event.shared.EventSubscription) SharedEvent(org.openremote.model.event.shared.SharedEvent) MessageBrokerService(org.openremote.container.message.MessageBrokerService)

Example 5 with Container

use of org.openremote.container.Container in project openremote by openremote.

the class SchemaExporter method main.

public static void main(String[] args) throws Exception {
    if (args.length == 0) {
        throw new IllegalArgumentException("Missing target file path argument");
    }
    File schemaFile = new File(args[0]);
    Container container = new Container(new ManagerExecutorService(), new ManagerPersistenceService() {

        @Override
        protected void openDatabase(Container container, Database database) {
        // Ignore, we don't want to connect to the database when exporting schema
        }

        @Override
        public void start(Container container) throws Exception {
            Map<String, Object> createSchemaProperties = new HashMap<>(persistenceUnitProperties);
            createSchemaProperties.put("javax.persistence.schema-generation.scripts.action", "create");
            createSchemaProperties.put("javax.persistence.schema-generation.scripts.create-target", schemaFile.getAbsolutePath());
            if (schemaFile.exists()) {
                LOG.info("Deleting existing schema file: " + schemaFile.getAbsolutePath());
                schemaFile.delete();
            }
            LOG.info("Exporting database schema for persistence unit: " + persistenceUnitName);
            Persistence.generateSchema(persistenceUnitName, createSchemaProperties);
            LOG.fine("Schema export complete: " + schemaFile.getAbsolutePath());
        }
    });
    container.start();
}
Also used : Container(org.openremote.container.Container) ManagerPersistenceService(org.openremote.manager.persistence.ManagerPersistenceService) Database(org.openremote.container.persistence.Database) ManagerExecutorService(org.openremote.manager.concurrent.ManagerExecutorService) File(java.io.File) Map(java.util.Map) HashMap(java.util.HashMap)

Aggregations

Container (org.openremote.container.Container)6 Logger (java.util.logging.Logger)3 ContainerService (org.openremote.container.ContainerService)3 MessageBrokerService (org.openremote.container.message.MessageBrokerService)3 MessageBrokerSetupService (org.openremote.container.message.MessageBrokerSetupService)3 TimerService (org.openremote.container.timer.TimerService)3 ManagerExecutorService (org.openremote.manager.concurrent.ManagerExecutorService)3 java.util (java.util)2 RouteBuilder (org.apache.camel.builder.RouteBuilder)2 ManagerPersistenceService (org.openremote.manager.persistence.ManagerPersistenceService)2 ManagerIdentityService (org.openremote.manager.security.ManagerIdentityService)2 Coordinate (com.vividsolutions.jts.geom.Coordinate)1 GeometryFactory (com.vividsolutions.jts.geom.GeometryFactory)1 Point (com.vividsolutions.jts.geom.Point)1 Undertow (io.undertow.Undertow)1 HttpHandler (io.undertow.server.HttpHandler)1 PathHandler (io.undertow.server.handlers.PathHandler)1 RedirectHandler (io.undertow.server.handlers.RedirectHandler)1 RequestDumpingHandler (io.undertow.server.handlers.RequestDumpingHandler)1 Servlets (io.undertow.servlet.Servlets)1