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);
}
});
}
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;
}
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();
}
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();
}
});
}
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();
}
Aggregations