use of org.openremote.model.asset.Asset in project openremote by openremote.
the class KNXProtocol method createAsset.
protected void createAsset(StateDP datapoint, boolean isStatusGA, MetaItem agentLink, Map<String, Asset> createdAssets) throws KNXException {
String name = datapoint.getName().substring(0, datapoint.getName().length() - 3);
String assetName = name.replaceAll(" -.*-", "");
Asset asset;
if (createdAssets.containsKey(assetName)) {
asset = createdAssets.get(assetName);
} else {
asset = new Asset(assetName, AssetType.THING);
}
String attrName = assetName.replaceAll(" ", "");
AttributeType type = TypeMapper.toAttributeType(datapoint);
AssetAttribute attr = asset.getAttribute(attrName).orElse(new AssetAttribute(attrName, type).setMeta(new MetaItem(AssetMeta.LABEL, Values.create(name)), new MetaItem(KNXProtocol.META_KNX_DPT, Values.create(datapoint.getDPT())), agentLink));
if (isStatusGA) {
attr.addMeta(new MetaItem(KNXProtocol.META_KNX_STATUS_GA, Values.create(datapoint.getMainAddress().toString())));
} else {
attr.addMeta(new MetaItem(KNXProtocol.META_KNX_ACTION_GA, Values.create(datapoint.getMainAddress().toString())));
}
if (!asset.hasAttribute(attrName)) {
asset.addAttributes(attr);
}
createdAssets.put(assetName, asset);
}
use of org.openremote.model.asset.Asset in project openremote by openremote.
the class KNXProtocol method discoverLinkedAssetAttributes.
@Override
public Asset[] discoverLinkedAssetAttributes(AssetAttribute protocolConfiguration, FileInfo fileInfo) throws IllegalStateException {
ZipInputStream zin = null;
try {
boolean fileFound = false;
byte[] data = CodecUtil.decodeBase64(fileInfo.getContents());
zin = new ZipInputStream(new ByteArrayInputStream(data));
ZipEntry zipEntry = zin.getNextEntry();
while (zipEntry != null) {
if (zipEntry.getName().endsWith("/0.xml")) {
fileFound = true;
break;
}
zipEntry = zin.getNextEntry();
}
if (!fileFound) {
String msg = "Failed to find '0.xml' in project file";
LOG.info(msg);
throw new IllegalStateException(msg);
}
// Create a transform factory instance.
System.setProperty("javax.xml.transform.TransformerFactory", "net.sf.saxon.TransformerFactoryImpl");
TransformerFactory tfactory = TransformerFactory.newInstance();
// Create a transformer for the stylesheet.
Transformer transformer = tfactory.newTransformer(new StreamSource(this.getClass().getResourceAsStream("/org/openremote/agent/protocol/knx/ets_calimero_group_name.xsl")));
// Set the URIResolver
transformer.setURIResolver(new EtsFileUriResolver(data));
// Transform the source XML into byte array
ByteArrayOutputStream bos = new ByteArrayOutputStream();
transformer.transform(new StreamSource(zin), new StreamResult(bos));
byte[] result = bos.toByteArray();
// we use a map of state-based datapoints and read from the transformed xml
final DatapointMap<StateDP> datapoints = new DatapointMap<>();
try (final XmlReader r = XmlInputFactory.newInstance().createXMLStreamReader(new ByteArrayInputStream(result))) {
datapoints.load(r);
} catch (final KNXMLException e) {
String msg = "Error loading parsed ETS file: " + e.getMessage();
LOG.warning(msg);
throw new IllegalStateException(msg, e);
}
MetaItem agentLink = AgentLink.asAgentLinkMetaItem(protocolConfiguration.getReferenceOrThrow());
Map<String, Asset> createdAssets = new HashMap<>();
for (StateDP dp : datapoints.getDatapoints()) {
if (dp.getName().endsWith("#A")) {
createAsset(dp, false, agentLink, createdAssets);
} else if (dp.getName().endsWith("#S")) {
createAsset(dp, true, agentLink, createdAssets);
} else if (dp.getName().endsWith("#SA") || dp.getName().endsWith("#AS")) {
createAsset(dp, false, agentLink, createdAssets);
createAsset(dp, true, agentLink, createdAssets);
} else {
LOG.info("Only group addresses ending on #A, #S, #AS or #SA will be imported. Ignoring: " + dp.getName());
}
}
return createdAssets.values().toArray(new Asset[createdAssets.values().size()]);
} catch (Exception e) {
throw new IllegalStateException("ETS import error", e);
} finally {
if (zin != null) {
try {
zin.close();
} catch (IOException e) {
e.printStackTrace();
}
}
}
}
use of org.openremote.model.asset.Asset in project openremote by openremote.
the class AgentResourceImpl method importLinkedAttributes.
@Override
public Asset[] importLinkedAttributes(RequestParams requestParams, String agentId, String protocolConfigurationName, String parentId, String realmId, FileInfo fileInfo) {
AttributeRef protocolConfigRef = new AttributeRef(agentId, protocolConfigurationName);
if (fileInfo == null || fileInfo.getContents() == null) {
throw new BadRequestException("A file must be provided for import");
}
Pair<Asset, String> parentAndRealmId = getParentAssetAndRealmId(parentId, realmId);
Asset[] assets = withAgentConnector(agentId, agentConnector -> {
LOG.finer("Asking connector '" + agentConnector.value.getClass().getSimpleName() + "' to do linked attribute discovery using uploaded file for protocol configuration: " + protocolConfigRef);
return agentConnector.value.getDiscoveredLinkedAttributes(protocolConfigRef, fileInfo);
});
try {
// TODO: Allow user to select which assets/attributes are actually added to the DB
persistAssets(assets, parentAndRealmId.key, parentAndRealmId.value);
return assets;
} catch (IllegalArgumentException e) {
LOG.log(Level.WARNING, e.getMessage(), e);
throw new NotFoundException(e.getMessage());
} catch (UnsupportedOperationException e) {
LOG.log(Level.WARNING, e.getMessage(), e);
throw new NotSupportedException(e.getMessage());
} catch (IllegalStateException e) {
LOG.log(Level.SEVERE, e.getMessage(), e);
throw new InternalServerErrorException(e.getMessage());
}
}
use of org.openremote.model.asset.Asset in project openremote by openremote.
the class AgentResourceImpl method persistAssets.
protected void persistAssets(Asset[] assets, Asset parentAsset, String realmId) {
if (assets == null || assets.length == 0) {
LOG.info("No assets to import");
return;
}
for (int i = 0; i < assets.length; i++) {
Asset asset = assets[i];
asset.setId(null);
asset.setParent(parentAsset);
asset.setRealmId(realmId);
ServerAsset serverAsset = ServerAsset.map(asset, new ServerAsset());
assets[i] = assetStorageService.merge(serverAsset);
}
}
use of org.openremote.model.asset.Asset in project openremote by openremote.
the class AssetProcessingService method init.
@Override
public void init(Container container) throws Exception {
timerService = container.getService(TimerService.class);
identityService = container.getService(ManagerIdentityService.class);
persistenceService = container.getService(PersistenceService.class);
rulesService = container.getService(RulesService.class);
agentService = container.getService(AgentService.class);
assetStorageService = container.getService(AssetStorageService.class);
assetDatapointService = container.getService(AssetDatapointService.class);
assetAttributeLinkingService = container.getService(AssetAttributeLinkingService.class);
messageBrokerService = container.getService(MessageBrokerService.class);
clientEventService = container.getService(ClientEventService.class);
clientEventService.addSubscriptionAuthorizer((auth, subscription) -> {
if (!subscription.isEventType(AttributeEvent.class)) {
return false;
}
// Always must have a filter, as you can't subscribe to ALL asset attribute events
if (subscription.getFilter() != null && subscription.getFilter() instanceof AttributeEvent.EntityIdFilter) {
AttributeEvent.EntityIdFilter filter = (AttributeEvent.EntityIdFilter) subscription.getFilter();
// Superuser can get attribute events for any asset
if (auth.isSuperUser())
return true;
// Regular user must have role
if (!auth.hasResourceRole(ClientRole.READ_ASSETS.getValue(), Constants.KEYCLOAK_CLIENT_ID)) {
return false;
}
boolean isRestrictedUser = identityService.getIdentityProvider().isRestrictedUser(auth.getUserId());
// Client can subscribe to several assets
for (String assetId : filter.getEntityId()) {
Asset asset = assetStorageService.find(assetId);
// If the asset doesn't exist, subscription must fail
if (asset == null)
return false;
if (isRestrictedUser) {
// Restricted users can only get attribute events for their linked assets
if (!assetStorageService.isUserAsset(auth.getUserId(), assetId))
return false;
// TODO Restricted clients should only receive events for RESTRICTED_READ attributes!
} else {
// Regular users can only get attribute events for assets in their realm
if (!asset.getTenantRealm().equals(auth.getAuthenticatedRealm()))
return false;
}
}
return true;
}
return false;
});
processors.add(agentService);
processors.add(rulesService);
processors.add(assetDatapointService);
processors.add(assetAttributeLinkingService);
container.getService(MessageBrokerSetupService.class).getContext().addRoutes(this);
}
Aggregations