Search in sources :

Example 1 with Asset

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);
}
Also used : AssetAttribute(org.openremote.model.asset.AssetAttribute) Asset(org.openremote.model.asset.Asset)

Example 2 with 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();
            }
        }
    }
}
Also used : TransformerFactory(javax.xml.transform.TransformerFactory) Transformer(javax.xml.transform.Transformer) DatapointMap(tuwien.auto.calimero.datapoint.DatapointMap) StreamResult(javax.xml.transform.stream.StreamResult) ZipEntry(java.util.zip.ZipEntry) StreamSource(javax.xml.transform.stream.StreamSource) ByteArrayOutputStream(java.io.ByteArrayOutputStream) XmlReader(tuwien.auto.calimero.xml.XmlReader) KNXMLException(tuwien.auto.calimero.xml.KNXMLException) IOException(java.io.IOException) KNXMLException(tuwien.auto.calimero.xml.KNXMLException) KNXFormatException(tuwien.auto.calimero.KNXFormatException) IOException(java.io.IOException) KNXException(tuwien.auto.calimero.KNXException) ZipInputStream(java.util.zip.ZipInputStream) ByteArrayInputStream(java.io.ByteArrayInputStream) StateDP(tuwien.auto.calimero.datapoint.StateDP) Asset(org.openremote.model.asset.Asset)

Example 3 with Asset

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());
    }
}
Also used : AttributeRef(org.openremote.model.attribute.AttributeRef) ServerAsset(org.openremote.manager.asset.ServerAsset) Asset(org.openremote.model.asset.Asset)

Example 4 with Asset

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);
    }
}
Also used : ServerAsset(org.openremote.manager.asset.ServerAsset) ServerAsset(org.openremote.manager.asset.ServerAsset) Asset(org.openremote.model.asset.Asset)

Example 5 with Asset

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);
}
Also used : TimerService(org.openremote.container.timer.TimerService) AttributeEvent(org.openremote.model.attribute.AttributeEvent) ManagerIdentityService(org.openremote.manager.security.ManagerIdentityService) PersistenceService(org.openremote.container.persistence.PersistenceService) AssetDatapointService(org.openremote.manager.datapoint.AssetDatapointService) AgentService(org.openremote.manager.agent.AgentService) RulesService(org.openremote.manager.rules.RulesService) Asset(org.openremote.model.asset.Asset) ClientEventService(org.openremote.manager.event.ClientEventService) MessageBrokerService(org.openremote.container.message.MessageBrokerService)

Aggregations

Asset (org.openremote.model.asset.Asset)45 Logger (java.util.logging.Logger)20 java.util (java.util)18 Level (java.util.logging.Level)18 Collectors (java.util.stream.Collectors)18 AssetQuery (org.openremote.model.query.AssetQuery)15 AssetStorageService (org.openremote.manager.asset.AssetStorageService)14 ManagerIdentityService (org.openremote.manager.security.ManagerIdentityService)14 MessageBrokerService (org.openremote.container.message.MessageBrokerService)13 TimerService (org.openremote.container.timer.TimerService)13 Container (org.openremote.model.Container)13 RouteBuilder (org.apache.camel.builder.RouteBuilder)12 ContainerService (org.openremote.model.ContainerService)11 PersistenceEvent (org.openremote.model.PersistenceEvent)11 Attribute (org.openremote.model.attribute.Attribute)11 ScheduledExecutorService (java.util.concurrent.ScheduledExecutorService)10 ClientEventService (org.openremote.manager.event.ClientEventService)10 EntityManager (javax.persistence.EntityManager)9 Tenant (org.openremote.model.security.Tenant)9 Pair (org.openremote.model.util.Pair)9