use of org.openremote.model.Container in project openremote by openremote.
the class SNMPProtocol method doStart.
@Override
protected void doStart(Container container) throws Exception {
String snmpBindHost = agent.getBindHost().orElseThrow(() -> {
String msg = "No SNMP bind host provided for protocol: " + this;
LOG.info(msg);
return new IllegalArgumentException(msg);
});
Integer snmpBindPort = agent.getBindPort().orElse(162);
SNMPAgent.SNMPVersion snmpVersion = agent.getSNMPVersion().orElse(SNMPAgent.SNMPVersion.V2c);
String snmpUri = String.format("snmp:%s:%d?protocol=udp&type=TRAP&snmpVersion=%d", snmpBindHost, snmpBindPort, snmpVersion.getVersion());
messageBrokerContext.addRoutes(new RouteBuilder() {
@Override
public void configure() {
from(snmpUri).routeId(getProtocolName() + getAgent().getId()).process(exchange -> {
SnmpMessage msg = exchange.getIn(SnmpMessage.class);
LOG.fine(String.format("Message received: %s", msg));
PDU pdu = msg.getSnmpMessage();
AttributeRef wildCardAttributeRef;
if ((wildCardAttributeRef = oidMap.get("*")) != null) {
ObjectNode wildCardValue = ValueUtil.createJsonObject();
pdu.getVariableBindings().forEach(variableBinding -> {
wildCardValue.put(variableBinding.getOid().format(), variableBinding.toValueString());
});
updateLinkedAttribute(new AttributeState(wildCardAttributeRef, wildCardValue));
}
pdu.getVariableBindings().forEach(variableBinding -> {
AttributeRef attributeRef = oidMap.get(variableBinding.getOid().format());
if (attributeRef != null) {
updateLinkedAttribute(new AttributeState(attributeRef, variableBinding.toValueString()));
}
});
});
}
});
setConnectionStatus(ConnectionStatus.CONNECTED);
}
use of org.openremote.model.Container in project openremote by openremote.
the class AbstractProtocol method start.
@Override
public void start(Container container) throws Exception {
timerService = container.getService(TimerService.class);
executorService = container.getExecutorService();
assetService = container.getService(ProtocolAssetService.class);
predictedAssetService = container.getService(ProtocolPredictedAssetService.class);
messageBrokerContext = container.getService(MessageBrokerService.class).getContext();
withLock(getProtocolName() + "::start", () -> {
try {
messageBrokerContext.addRoutes(new RouteBuilder() {
@Override
public void configure() throws Exception {
from(ACTUATOR_TOPIC).routeId("Actuator-" + getProtocolName() + getAgent().getId()).process(exchange -> {
Protocol<?> protocolInstance = exchange.getIn().getHeader(ACTUATOR_TOPIC_TARGET_PROTOCOL, Protocol.class);
if (protocolInstance != AbstractProtocol.this) {
return;
}
AttributeEvent event = exchange.getIn().getBody(AttributeEvent.class);
Attribute<?> linkedAttribute = getLinkedAttributes().get(event.getAttributeRef());
if (linkedAttribute == null) {
LOG.info("Attempt to write to attribute that is not actually linked to this protocol '" + AbstractProtocol.this + "': " + linkedAttribute);
return;
}
processLinkedAttributeWrite(event);
});
}
});
doStart(container);
} catch (Exception ex) {
throw new RuntimeException(ex);
}
});
this.producerTemplate = container.getService(MessageBrokerService.class).getProducerTemplate();
}
use of org.openremote.model.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);
gatewayService = container.getService(GatewayService.class);
eventSubscriptions = new EventSubscriptions(container.getService(TimerService.class));
messageBrokerService.getContext().getTypeConverterRegistry().addTypeConverters(new EventTypeConverters());
// TODO: Remove prefix and just use event type then use a subscription wrapper to pass subscription ID around
messageBrokerService.getContext().addRoutes(new RouteBuilder() {
@Override
public void configure() throws Exception {
from("websocket://" + WEBSOCKET_EVENTS).routeId("FromClientWebsocketEvents").process(exchange -> exchange.getIn().setHeader(HEADER_CONNECTION_TYPE, HEADER_CONNECTION_TYPE_WEBSOCKET)).to(ClientEventService.CLIENT_EVENT_QUEUE).end();
from(ClientEventService.CLIENT_EVENT_QUEUE).routeId("ClientEvents").choice().when(header(ConnectionConstants.SESSION_OPEN)).process(exchange -> {
String sessionKey = getSessionKey(exchange);
sessionKeyInfoMap.put(sessionKey, createSessionInfo(sessionKey, exchange));
passToInterceptors(exchange);
}).stop().when(or(header(ConnectionConstants.SESSION_CLOSE), header(ConnectionConstants.SESSION_CLOSE_ERROR))).process(exchange -> {
String sessionKey = getSessionKey(exchange);
sessionKeyInfoMap.remove(sessionKey);
eventSubscriptions.cancelAll(sessionKey);
passToInterceptors(exchange);
}).stop().end().process(exchange -> {
// Do basic formatting of exchange
EventRequestResponseWrapper<?> requestResponse = null;
if (exchange.getIn().getBody() instanceof EventRequestResponseWrapper) {
requestResponse = exchange.getIn().getBody(EventRequestResponseWrapper.class);
} else if (exchange.getIn().getBody() instanceof String && exchange.getIn().getBody(String.class).startsWith(EventRequestResponseWrapper.MESSAGE_PREFIX)) {
requestResponse = exchange.getIn().getBody(EventRequestResponseWrapper.class);
}
if (requestResponse != null) {
SharedEvent event = requestResponse.getEvent();
exchange.getIn().setHeader(HEADER_REQUEST_RESPONSE_MESSAGE_ID, requestResponse.getMessageId());
exchange.getIn().setBody(event);
}
if (exchange.getIn().getBody() instanceof String) {
String bodyStr = exchange.getIn().getBody(String.class);
if (bodyStr.startsWith(EventSubscription.SUBSCRIBE_MESSAGE_PREFIX)) {
exchange.getIn().setBody(exchange.getIn().getBody(EventSubscription.class));
} else if (bodyStr.startsWith(CancelEventSubscription.MESSAGE_PREFIX)) {
exchange.getIn().setBody(exchange.getIn().getBody(CancelEventSubscription.class));
} else if (bodyStr.startsWith(SharedEvent.MESSAGE_PREFIX)) {
exchange.getIn().setBody(exchange.getIn().getBody(SharedEvent.class));
}
}
if (exchange.getIn().getBody() instanceof SharedEvent) {
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());
}
}
}).process(exchange -> passToInterceptors(exchange)).choice().when(body().isInstanceOf(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);
boolean restrictedUser = identityService.getIdentityProvider().isRestrictedUser(authContext);
boolean anonymousUser = authContext == null;
String username = authContext == null ? "anonymous" : authContext.getUsername();
String realm = exchange.getIn().getHeader(Constants.REALM_PARAM_NAME, String.class);
if (authorizeEventSubscription(realm, authContext, subscription)) {
eventSubscriptions.createOrUpdate(sessionKey, restrictedUser, anonymousUser, subscription);
subscription.setSubscribed(true);
sendToSession(sessionKey, subscription);
} else {
LOG.warning("Unauthorized subscription from '" + username + "' in realm '" + realm + "': " + subscription);
sendToSession(sessionKey, new UnauthorizedEventSubscription<>(subscription));
}
}).stop().when(body().isInstanceOf(CancelEventSubscription.class)).process(exchange -> {
String sessionKey = getSessionKey(exchange);
eventSubscriptions.cancel(sessionKey, exchange.getIn().getBody(CancelEventSubscription.class));
}).stop().when(body().isInstanceOf(SharedEvent.class)).choice().when(// Inbound messages from clients
header(HEADER_CONNECTION_TYPE).isNotNull()).to(ClientEventService.CLIENT_EVENT_TOPIC).stop().when(// Outbound message to clients
header(HEADER_CONNECTION_TYPE).isNull()).split(method(eventSubscriptions, "splitForSubscribers")).process(exchange -> {
String sessionKey = getSessionKey(exchange);
sendToSession(sessionKey, exchange.getIn().getBody());
}).stop().endChoice().otherwise().process(exchange -> LOG.info("Unsupported message body: " + exchange.getIn().getBody())).end();
}
});
// Add pending internal subscriptions
if (!pendingInternalSubscriptions.isEmpty()) {
pendingInternalSubscriptions.forEach(subscription -> eventSubscriptions.createOrUpdate(INTERNAL_SESSION_KEY, false, false, subscription));
}
pendingInternalSubscriptions = null;
}
use of org.openremote.model.Container in project openremote by openremote.
the class GatewayService method start.
@Override
public void start(Container container) throws Exception {
if (!active) {
return;
}
List<GatewayAsset> gateways = assetStorageService.findAll(new AssetQuery().types(GatewayAsset.class)).stream().map(asset -> (GatewayAsset) asset).collect(Collectors.toList());
List<String> gatewayIds = gateways.stream().map(Asset::getId).collect(Collectors.toList());
gateways = gateways.stream().filter(gateway -> Arrays.stream(gateway.getPath()).noneMatch(p -> !p.equals(gateway.getId()) && gatewayIds.contains(p))).collect(Collectors.toList());
if (!gateways.isEmpty()) {
LOG.info("Directly registered gateways found = " + gateways.size());
gateways.forEach(gateway -> {
// Check if client has been created
boolean hasClientId = gateway.getClientId().isPresent();
boolean hasClientSecret = gateway.getClientSecret().isPresent();
if (!hasClientId || !hasClientSecret) {
createUpdateGatewayServiceUser(gateway);
}
// Create connector
GatewayConnector connector = new GatewayConnector(assetStorageService, assetProcessingService, executorService, gateway);
gatewayConnectorMap.put(gateway.getId().toLowerCase(Locale.ROOT), connector);
// Get IDs of all assets under this gateway
List<Asset<?>> gatewayAssets = assetStorageService.findAll(new AssetQuery().parents(gateway.getId()).select(new AssetQuery.Select().excludeAttributes()).recursive(true));
gatewayAssets.forEach(asset -> assetIdGatewayIdMap.put(asset.getId(), gateway.getId()));
});
}
}
use of org.openremote.model.Container in project openremote by openremote.
the class AgentService method startAgent.
protected void startAgent(Agent<?, ?, ?> agent) {
withLock(getClass().getSimpleName() + "::startAgent", () -> {
Protocol<?> protocol = null;
try {
protocol = agent.getProtocolInstance();
protocolInstanceMap.put(agent.getId(), protocol);
LOG.fine("Starting protocol instance: " + protocol);
protocol.start(container);
LOG.fine("Started protocol instance:" + protocol);
LOG.finer("Linking attributes to protocol instance: " + protocol);
// Get all assets that have attributes with agent link meta for this agent
List<Asset<?>> assets = assetStorageService.findAll(new AssetQuery().attributes(new AttributePredicate().meta(new NameValuePredicate(AGENT_LINK, new StringPredicate(agent.getId()), false, new NameValuePredicate.Path("id")))));
LOG.finer("Found '" + assets.size() + "' asset(s) with attributes linked to this protocol instance: " + protocol);
assets.forEach(asset -> getGroupedAgentLinkAttributes(asset.getAttributes().stream(), assetAttribute -> assetAttribute.getMetaValue(AGENT_LINK).map(agentLink -> agentLink.getId().equals(agent.getId())).orElse(false)).forEach((agnt, attributes) -> linkAttributes(agnt, asset.getId(), attributes)));
} catch (Exception e) {
if (protocol != null) {
try {
protocol.stop(container);
} catch (Exception ignored) {
}
}
protocolInstanceMap.remove(agent.getId());
LOG.log(Level.SEVERE, "Failed to start protocol instance for agent: " + agent, e);
sendAttributeEvent(new AttributeEvent(agent.getId(), Agent.STATUS.getName(), ConnectionStatus.ERROR));
}
});
}
Aggregations