Search in sources :

Example 11 with OnmsAssetRecord

use of org.opennms.netmgt.model.OnmsAssetRecord in project opennms by OpenNMS.

the class SnmpAssetProvisioningAdapter method doAddNode.

/**
 * <p>doAdd</p>
 *
 * @param nodeId a int.
 * @param retry a boolean.
 * @throws org.opennms.netmgt.provision.ProvisioningAdapterException if any.
 */
@Override
public void doAddNode(final int nodeId) throws ProvisioningAdapterException {
    LOG.debug("doAdd: adding nodeid: {}", nodeId);
    final OnmsNode node = m_nodeDao.get(nodeId);
    Assert.notNull(node, "doAdd: failed to return node for given nodeId:" + nodeId);
    InetAddress ipaddress = m_template.execute(new TransactionCallback<InetAddress>() {

        @Override
        public InetAddress doInTransaction(TransactionStatus arg0) {
            return getIpForNode(node);
        }
    });
    SnmpAgentConfig agentConfig = null;
    String locationName = node.getLocation() != null ? node.getLocation().getLocationName() : null;
    agentConfig = m_snmpConfigDao.getAgentConfig(ipaddress, locationName);
    final OnmsAssetRecord asset = node.getAssetRecord();
    m_config.getReadLock().lock();
    try {
        for (final AssetField field : m_config.getAssetFieldsForAddress(ipaddress, node.getSysObjectId())) {
            try {
                final String value = fetchSnmpAssetString(m_locationAwareSnmpClient, agentConfig, locationName, field.getMibObjs(), field.getFormatString());
                LOG.debug("doAdd: Setting asset field \" {} \" to value: {}", field.getName(), value);
                // Use Spring bean-accessor classes to set the field value
                final BeanWrapper wrapper = PropertyAccessorFactory.forBeanPropertyAccess(asset);
                try {
                    wrapper.setPropertyValue(field.getName(), value);
                } catch (final BeansException e) {
                    LOG.warn("doAdd: Could not set property \" {} \" on asset object {}", field.getName(), e.getMessage(), e);
                }
            } catch (final Throwable t) {
                // This exception is thrown if the SNMP operation fails or an incorrect number of
                // parameters is returned by the agent or because of a misconfiguration.
                LOG.warn("doAdd: Could not set value for asset field \" {} \": {}", field.getName(), t.getMessage(), t);
            }
        }
    } finally {
        m_config.getReadLock().unlock();
    }
    node.setAssetRecord(asset);
    m_nodeDao.saveOrUpdate(node);
    m_nodeDao.flush();
}
Also used : SnmpAgentConfig(org.opennms.netmgt.snmp.SnmpAgentConfig) BeanWrapper(org.springframework.beans.BeanWrapper) OnmsNode(org.opennms.netmgt.model.OnmsNode) OnmsAssetRecord(org.opennms.netmgt.model.OnmsAssetRecord) AssetField(org.opennms.netmgt.config.snmpAsset.adapter.AssetField) TransactionStatus(org.springframework.transaction.TransactionStatus) InetAddress(java.net.InetAddress) BeansException(org.springframework.beans.BeansException)

Example 12 with OnmsAssetRecord

use of org.opennms.netmgt.model.OnmsAssetRecord in project opennms by OpenNMS.

the class BSFNotificationStrategy method declareBeans.

private static void declareBeans(BSFNotificationStrategy obj) throws BSFException {
    // Retrieve the parameters before accessing them
    obj.retrieveParams();
    Integer nodeId;
    try {
        nodeId = Integer.valueOf(obj.m_notifParams.get(NotificationManager.PARAM_NODE));
    } catch (NumberFormatException nfe) {
        nodeId = null;
    }
    OnmsNode node = null;
    OnmsAssetRecord assets = null;
    final List<String> categories = new ArrayList<>();
    String nodeLabel = null;
    String foreignSource = null;
    String foreignId = null;
    if (nodeId != null) {
        final BeanFactoryReference bf = BeanUtils.getBeanFactory("notifdContext");
        final NodeDao nodeDao = BeanUtils.getBean(bf, "nodeDao", NodeDao.class);
        final TransactionTemplate transTemplate = BeanUtils.getBean(bf, "transactionTemplate", TransactionTemplate.class);
        try {
            // Redeclare the node id as final
            final int theNodeId = nodeId;
            node = transTemplate.execute(new TransactionCallback<OnmsNode>() {

                @Override
                public OnmsNode doInTransaction(final TransactionStatus status) {
                    final OnmsNode node = nodeDao.get(theNodeId);
                    // Retrieve the categories in the context of the transaction
                    if (node != null) {
                        for (OnmsCategory cat : node.getCategories()) {
                            categories.add(cat.getName());
                        }
                    }
                    return node;
                }
            });
            if (node == null) {
                LOG.error("Could not find a node with id: {}", theNodeId);
            } else {
                nodeLabel = node.getLabel();
                assets = node.getAssetRecord();
                foreignSource = node.getForeignSource();
                foreignId = node.getForeignId();
            }
        } catch (final RuntimeException e) {
            LOG.error("Error while retrieving node with id {}", nodeId, e);
        }
    }
    s_bsfManager.declareBean("bsf_notif_strategy", obj, BSFNotificationStrategy.class);
    s_bsfManager.declareBean("logger", LOG, Logger.class);
    s_bsfManager.declareBean("notif_params", obj.m_notifParams, Map.class);
    s_bsfManager.declareBean("node_label", nodeLabel, String.class);
    s_bsfManager.declareBean("foreign_source", foreignSource, String.class);
    s_bsfManager.declareBean("foreign_id", foreignId, String.class);
    s_bsfManager.declareBean("node_assets", assets, OnmsAssetRecord.class);
    s_bsfManager.declareBean("node_categories", categories, List.class);
    s_bsfManager.declareBean("node", node, OnmsNode.class);
    for (Argument arg : obj.m_arguments) {
        if (NotificationManager.PARAM_TEXT_MSG.equals(arg.getSwitch()))
            s_bsfManager.declareBean("text_message", arg.getValue(), String.class);
        if (NotificationManager.PARAM_NUM_MSG.equals(arg.getSwitch()))
            s_bsfManager.declareBean("numeric_message", arg.getValue(), String.class);
        if (NotificationManager.PARAM_NODE.equals(arg.getSwitch()))
            s_bsfManager.declareBean("node_id", arg.getValue(), String.class);
        if (NotificationManager.PARAM_INTERFACE.equals(arg.getSwitch()))
            s_bsfManager.declareBean("ip_addr", arg.getValue(), String.class);
        if (NotificationManager.PARAM_SERVICE.equals(arg.getSwitch()))
            s_bsfManager.declareBean("svc_name", arg.getValue(), String.class);
        if (NotificationManager.PARAM_SUBJECT.equals(arg.getSwitch()))
            s_bsfManager.declareBean("subject", arg.getValue(), String.class);
        if (NotificationManager.PARAM_EMAIL.equals(arg.getSwitch()))
            s_bsfManager.declareBean("email", arg.getValue(), String.class);
        if (NotificationManager.PARAM_PAGER_EMAIL.equals(arg.getSwitch()))
            s_bsfManager.declareBean("pager_email", arg.getValue(), String.class);
        if (NotificationManager.PARAM_XMPP_ADDRESS.equals(arg.getSwitch()))
            s_bsfManager.declareBean("xmpp_address", arg.getValue(), String.class);
        if (NotificationManager.PARAM_TEXT_PAGER_PIN.equals(arg.getSwitch()))
            s_bsfManager.declareBean("text_pin", arg.getValue(), String.class);
        if (NotificationManager.PARAM_NUM_PAGER_PIN.equals(arg.getSwitch()))
            s_bsfManager.declareBean("numeric_pin", arg.getValue(), String.class);
        if (NotificationManager.PARAM_WORK_PHONE.equals(arg.getSwitch()))
            s_bsfManager.declareBean("work_phone", arg.getValue(), String.class);
        if (NotificationManager.PARAM_HOME_PHONE.equals(arg.getSwitch()))
            s_bsfManager.declareBean("home_phone", arg.getValue(), String.class);
        if (NotificationManager.PARAM_MOBILE_PHONE.equals(arg.getSwitch()))
            s_bsfManager.declareBean("mobile_phone", arg.getValue(), String.class);
        if (NotificationManager.PARAM_TUI_PIN.equals(arg.getSwitch()))
            s_bsfManager.declareBean("phone_pin", arg.getValue(), String.class);
        if (NotificationManager.PARAM_MICROBLOG_USERNAME.equals(arg.getSwitch()))
            s_bsfManager.declareBean("microblog_username", arg.getValue(), String.class);
    }
}
Also used : OnmsNode(org.opennms.netmgt.model.OnmsNode) Argument(org.opennms.netmgt.model.notifd.Argument) OnmsAssetRecord(org.opennms.netmgt.model.OnmsAssetRecord) ArrayList(java.util.ArrayList) TransactionTemplate(org.springframework.transaction.support.TransactionTemplate) TransactionStatus(org.springframework.transaction.TransactionStatus) BeanFactoryReference(org.springframework.beans.factory.access.BeanFactoryReference) NodeDao(org.opennms.netmgt.dao.api.NodeDao) TransactionCallback(org.springframework.transaction.support.TransactionCallback) OnmsCategory(org.opennms.netmgt.model.OnmsCategory)

Example 13 with OnmsAssetRecord

use of org.opennms.netmgt.model.OnmsAssetRecord in project opennms by OpenNMS.

the class OnmsAlarmOssjMapper method populateOssjAlarmFromOpenNMSAlarm.

/**
 * This method maps OpenNMS alarm to an OSS/J alarms and adds additional information
 *
 * @param _openNMSalarm data to use to populate the OSS/J alarm
 * @param alarmValueSpecification AlarmValue object to be populated - Invariant (Specifcation) values should be already populated
 * @return the _av OSS/J AlarmValue populated with opennms data
 * @throws java.lang.IllegalArgumentException if any.
 * @throws javax.oss.UnsupportedAttributeException if any.
 */
public AlarmValue populateOssjAlarmFromOpenNMSAlarm(AlarmValue alarmValueSpecification, OnmsAlarm _openNMSalarm) throws IllegalArgumentException, UnsupportedAttributeException {
    String logheader = this.getClass().getSimpleName() + "populateOssjAlarmFromOpenNMSAlarm():";
    // Node node = null;
    OnmsNode node = null;
    // Asset asset = null;
    OnmsAssetRecord asset = null;
    // true if alarm is received from Qosdrx
    boolean isQoSDrxAlarm = false;
    LOG.debug("{} Populating alarm", logheader);
    // come from Qosdrx.
    if ((_openNMSalarm.getManagedObjectInstance() != null) && (_openNMSalarm.getManagedObjectType() != null) && (!_openNMSalarm.getManagedObjectInstance().equals("")) && (!_openNMSalarm.getManagedObjectType().equals(""))) {
        isQoSDrxAlarm = true;
        LOG.debug("{} isQoSDrxAlarm TRUE - because OpenNMS alarm has ManagedObjectInstance and ManagedObjectType", logheader);
    } else {
        isQoSDrxAlarm = false;
        LOG.debug("{} isQoSDrxAlarm FALSE - because OpenNMS alarm NOT POPULATED ManagedObjectInstance and ManagedObjectType", logheader);
    }
    try {
        // in the OSS/J alarm
        if ((null != _openNMSalarm.getAlarmAckTime()) && (null != _openNMSalarm.getAlarmAckUser())) {
            alarmValueSpecification.setAckUserId(_openNMSalarm.getAlarmAckUser());
            // OnmsAlarm can contain java.sql.Timestamp - convert to Date
            alarmValueSpecification.setAckTime(new Date(_openNMSalarm.getAlarmAckTime().getTime()));
            alarmValueSpecification.setAlarmAckState(AlarmAckState.ACKNOWLEDGED);
        } else {
            alarmValueSpecification.setAlarmAckState(AlarmAckState.UNACKNOWLEDGED);
        }
        // the clear occured.
        if (_openNMSalarm.getSeverity() == OnmsSeverity.CLEARED) {
            // OnmsAlarm can contain java.sql.Timestamp - convert to Date
            alarmValueSpecification.setAlarmClearedTime(new Date(_openNMSalarm.getLastEventTime().getTime()));
        } else {
            alarmValueSpecification.setAlarmClearedTime(null);
        }
        // OnmsAlarm can contain java.sql.Timestamp - convert to Date
        if (null != _openNMSalarm.getFirstEventTime()) {
            alarmValueSpecification.setAlarmRaisedTime(new Date(_openNMSalarm.getFirstEventTime().getTime()));
        }
        if (null != _openNMSalarm.getLastEventTime()) {
            alarmValueSpecification.setAlarmChangedTime(new Date(_openNMSalarm.getLastEventTime().getTime()));
        }
    } catch (Throwable e) {
        LOG.error("{} Problem getting ACK time information", logheader, e);
    }
    Matcher matcher = null;
    String _uei_no_html = "NOT_SET";
    try {
        String uei = _openNMSalarm.getUei();
        if (null != uei) {
            matcher = p.matcher(uei);
            // remove any HTML tags from uei
            _uei_no_html = matcher.replaceAll(" ");
        }
        alarmValueSpecification.setAlarmType((_openNMSalarm.getX733AlarmType() == null) ? javax.oss.fm.monitor.AlarmType.EQUIPMENT_ALARM : _openNMSalarm.getX733AlarmType());
    } catch (Throwable e) {
        LOG.error("{} Problem getting  X733AlarmType or Uei", logheader, e);
    }
    // Get some local node information as to where the alarm came from
    // This includes, what type of managed element the node is
    // and what its node id and label are.*/
    // String mftr = "NOT_SET"; // FIXME: Not read
    // String modelNo = "NOT_SET"; // FIXME: Not read
    // String assetserno = "NOT_SET"; // FIXME: Not read
    // String nodelabel = "NOT_SET"; // FIXME: Not read
    // String alarmIP = "NOT_SET"; // FIXME: Not read
    String managedObjectType = "NOT_SET";
    String managedObjectInstance = "NOT_SET";
    String assetManagedObjectType = "NOT_SET";
    String assetManagedObjectInstance = "NOT_SET";
    String assetDescription = "NOT_SET";
    String assetAddress2 = "NOT_SET";
    if (!isQoSDrxAlarm) {
        // if is locally generated alarm
        try {
            // set default values if no node information present
            if (_openNMSalarm.getNode() != null) {
                node = ossDao.findNodeByID(_openNMSalarm.getNode().getId());
                asset = node.getAssetRecord();
                // }
                if (asset != null) {
                    // TODO was used for managed object class as is 128 char long
                    if (asset.getDescription() != null)
                        assetDescription = asset.getDescription();
                    // TODO was used for managed object instance - as is 256 char long string
                    if (asset.getAddress2() != null)
                        assetAddress2 = asset.getAddress2();
                    if (asset.getManagedObjectInstance() != null)
                        assetManagedObjectInstance = asset.getManagedObjectInstance();
                    if (asset.getManagedObjectType() != null)
                        assetManagedObjectType = asset.getManagedObjectType();
                }
                managedObjectInstance = assetManagedObjectInstance;
                managedObjectType = assetManagedObjectType;
                LOG.debug("{} isQoSDrxAlarm=FALSE  OpenNMS type and instance not set. Using from Node Asset record: ManagedObjectInstance: {} ManagedObjectType:{}", logheader, managedObjectInstance, managedObjectType);
            }
        } catch (Throwable ex) {
            LOG.error("{} Problem getting node and asset information", logheader, ex);
        }
    } else {
        // is a received alarm
        try {
            managedObjectInstance = _openNMSalarm.getManagedObjectInstance();
            managedObjectType = _openNMSalarm.getManagedObjectType();
            LOG.debug("{} isQoSDrxAlarm=FALSE  OpenNMS type and instance not set. Using from Node Asset record: ManagedObjectInstance: {} ManagedObjectType:{}", logheader, managedObjectInstance, managedObjectType);
        } catch (Throwable ex) {
            LOG.error("{} Problem managedObjectInstance or managedObjectType", logheader, ex);
        }
    }
    alarmValueSpecification.setManagedObjectClass(managedObjectType);
    LOG.debug("{} _av.setManagedObjectClass set to: ", logheader, managedObjectType);
    alarmValueSpecification.setManagedObjectInstance(managedObjectInstance);
    LOG.debug("{} _av.setManagedObjectInstance set to: ", logheader, managedObjectInstance);
    // set severity and probable cause
    try {
        alarmValueSpecification.setPerceivedSeverity(onmsSeverityToOssjSeverity(_openNMSalarm.getSeverity()));
        // alarmValueSpecification.setProbableCause((short)-1); // OSS/J set to -1  then text contains description
        alarmValueSpecification.setProbableCause((short) _openNMSalarm.getX733ProbableCause());
    } catch (Throwable e) {
        LOG.error("{} Problem getting severity or probable cause: ", logheader, e);
    }
    if (!isQoSDrxAlarm) {
        try {
            String _opinstr = _openNMSalarm.getOperInstruct();
            if (null != _opinstr) {
                matcher = p.matcher(_opinstr);
                // remove all HTML tags from operator instructions
                _opinstr = matcher.replaceAll(" ");
            } else
                _opinstr = "NOT_SET";
            alarmValueSpecification.setProposedRepairActions(_opinstr);
            String _logmsg = _openNMSalarm.getLogMsg();
            if (null != _logmsg) {
                matcher = p.matcher(_logmsg);
                // remove all HTML tags from operator instructions
                _logmsg = matcher.replaceAll(" ");
            } else
                _logmsg = "NOT_SET";
            String _description = _openNMSalarm.getDescription();
            if (null != _description) {
                matcher = p.matcher(_description);
                // remove all HTML tags from description
                _description = matcher.replaceAll(" ");
            } else
                _description = "NOT_SET";
            // using manufacturers own definition of specific problem here ( OSS/J )
            alarmValueSpecification.setSpecificProblem(_logmsg);
            Integer alarmid = _openNMSalarm.getId();
            Integer counter = _openNMSalarm.getCounter();
            String reductionkey = _openNMSalarm.getReductionKey();
            // note some OnmsAlarms can have null nodes - we use a default value of 0 for ID
            Integer nodeid = 0;
            String onmsnodelabel = "";
            if (_openNMSalarm.getNode() != null) {
                nodeid = _openNMSalarm.getNode().getId();
                onmsnodelabel = _openNMSalarm.getNode().getLabel();
            }
            InetAddress ipaddress = _openNMSalarm.getIpAddr();
            String x733AlarmType = _openNMSalarm.getX733AlarmType();
            String x733ProbableCause;
            try {
                x733ProbableCause = OOSSProbableCause.getStringforEnum((short) _openNMSalarm.getX733ProbableCause());
            } catch (Throwable e) {
                x733ProbableCause = "X733 Probable Cause Incorrectly Defined";
            }
            alarmValueSpecification.setAdditionalText("<alarmid>" + alarmid + "</alarmid>" + "\n            " + "<logmsg>" + _logmsg + "</logmsg>" + "\n            " + "<uei>" + _uei_no_html + "<uei>" + "\n            " + "<x733AlarmType>" + x733AlarmType + "</x733AlarmType>" + "\n            " + "<x733ProbableCause>" + x733ProbableCause + "</x733ProbableCause>" + "\n            " + "<counter>" + counter + "</counter>" + "\n            " + "<reductionkey>" + reductionkey + "</reductionkey>" + "\n            " + "<nodeid>" + nodeid + "</nodeid>" + "\n            " + "<nodelabel>" + onmsnodelabel + "</nodelabel>" + "\n            " + "<ipaddress>" + InetAddressUtils.toIpAddrString(ipaddress) + "</ipaddress>" + "\n            " + "<description>" + _description + "</description>" + "\n            " + "<opinstr>" + _opinstr + "</opinstr>" + "\n            " + "<asset.managedobjectinstance>" + assetManagedObjectInstance + "</asset.managedobjectinstance>" + // TODO - was used for object instance
            "\n            " + "<asset.managedobjecttype>" + assetManagedObjectType + "</asset.managedobjecttype>" + "\n            " + "<asset.address2>" + assetAddress2 + "</asset.address2>" + // TODO - was used for object instance
            "\n            " + "<asset.description>" + assetDescription + "</asset.description>" + // TODO - was used for object instancetype
            "\n");
        } catch (Throwable e) {
            LOG.error("{} Problem setting description, logmessage or operator instrctions: ", logheader, e);
        }
    } else {
        // is a received alarm
        try {
            String _opinstr = _openNMSalarm.getOperInstruct();
            if (null == _opinstr)
                _opinstr = "NOT_SET";
            alarmValueSpecification.setProposedRepairActions(_opinstr);
            String _logmsg = _openNMSalarm.getLogMsg();
            if (null == _logmsg)
                _logmsg = "NOT_SET";
            // using manufacturers own definition of specific problem here ( OSS/J )
            alarmValueSpecification.setSpecificProblem(_logmsg);
            String _description = _openNMSalarm.getDescription();
            if (null == _description)
                _description = "NOT_SET";
            alarmValueSpecification.setAdditionalText(_description);
        } catch (Throwable e) {
            LOG.error("{} Problem setting description, logmessage or operator instrctions: ", logheader, e);
        }
    }
    // TODO replacement method to populate the alarm key
    try {
        // populate alarm key
        // TODO was AlarmKey ak = new OOSSAlarmKey(Integer.toString(_openNMSalarm.getId()));
        AlarmKey ak = alarmValueSpecification.getAlarmKey();
        ak.setAlarmPrimaryKey(Integer.toString(_openNMSalarm.getId()));
        ak.setPrimaryKey(ak.getAlarmPrimaryKey());
    } catch (Throwable e) {
        LOG.error("{} Problem setting AlarmKey: ", logheader, e);
    }
    LOG.debug("{} Alarm Populated", logheader);
    return alarmValueSpecification;
}
Also used : AlarmKey(javax.oss.fm.monitor.AlarmKey) OnmsNode(org.opennms.netmgt.model.OnmsNode) Matcher(java.util.regex.Matcher) OnmsAssetRecord(org.opennms.netmgt.model.OnmsAssetRecord) InetAddress(java.net.InetAddress) Date(java.util.Date)

Example 14 with OnmsAssetRecord

use of org.opennms.netmgt.model.OnmsAssetRecord in project opennms by OpenNMS.

the class OssDaoOpenNMSImpl method localUpdateNodeCaches.

/**
 * Update the node cache from the OpenNMS database
 * This must be run at least once to ensure that node data is available
 * Not Thread Safe - only to be called from within the synchronised methods
 */
private void localUpdateNodeCaches() {
    try {
        nodeCacheByID.clear();
        nodeCacheByLabel.clear();
        nodeCacheByUniqueID.clear();
        LOG.debug("OssDaoOpenNMSImpl().updateNodeCaches - Updating Node Caches");
        Collection<OnmsNode> c = _nodeDao.findAll();
        OnmsNode[] nodelist = (OnmsNode[]) c.toArray(new OnmsNode[c.size()]);
        for (int i = 0; i < nodelist.length; i++) {
            OnmsNode node = (OnmsNode) nodelist[i];
            try {
                // update node by ID cache
                this.nodeCacheByID.put((Integer) node.getId(), node);
                // update node by Label cache
                if (node.getLabel() != null) {
                    if (nodeCacheByLabel.get((String) node.getLabel()) != null) {
                        LOG.info("OssDaoOpenNMSImpl().updateNodeCaches WARNING node.getId():{} Node Label:{} is duplicated", node.getId(), node.getId());
                    } else {
                        nodeCacheByLabel.put((String) node.getLabel(), node);
                    }
                } else {
                    LOG.info("OssDaoOpenNMSImpl().updateNodeCaches WARNING node.getId():{} Node Label is NULL. Not putting node in nodeCacheByLabel", node.getId());
                }
                // update node by Unique ID -managedObjectInstance+ManagedObjectType
                final OnmsAssetRecord assetRecord = node.getAssetRecord();
                if (assetRecord == null) {
                    LOG.info("OssDaoOpenNMSImpl().updateNodeCaches WARNING node.getId():{} assetRecord is NULL. Not putting node in nodeCacheByUniqueID", node.getId());
                    continue;
                } else {
                    // Note that the node asset record data for instance and type are only filled
                    // given default values once - subsequently changes must be explicitly set directly
                    // in the database
                    String moi = assetRecord.getManagedObjectInstance();
                    if ((moi == null) || ("".equals(moi))) {
                        String fid = (node.getForeignId() == null) ? "" : node.getForeignId();
                        String fsrc = (node.getForeignSource() == null) ? "" : node.getForeignSource();
                        String label = (node.getLabel() == null) ? "" : node.getLabel();
                        moi = "Label:" + label + ":ForeignSource:" + fsrc + ":ForeignId():" + fid;
                        LOG.info("OssDaoOpenNMSImpl().updateNodeCaches WARNING node.getId():{} ManagedObjectInstance is NULL. Setting  ManagedObjectInstance to: {}", node.getId(), moi);
                        assetRecord.setManagedObjectInstance(moi);
                    }
                    String mot = assetRecord.getManagedObjectType();
                    if ((mot == null) || ("".equals(mot))) {
                        mot = "UNSPECIFIED_TYPE";
                        LOG.info("OssDaoOpenNMSImpl().updateNodeCaches WARNING node.getId():{} ManagedObjectType was NULL. Setting ManagedObjectType to: {}", node.getId(), mot);
                        assetRecord.setManagedObjectType(mot);
                    }
                    // save asset data back with new node information
                    // (Note - data may not have changed)
                    transTemplate.execute(new TransactionCallbackWithoutResult() {

                        @Override
                        public void doInTransactionWithoutResult(TransactionStatus status) {
                            _assetRecordDao.update(assetRecord);
                        }
                    });
                    // update nodeCacheByUniqueID
                    String uniqueid = assetRecord.getManagedObjectInstance() + assetRecord.getManagedObjectType();
                    if (nodeCacheByUniqueID.get((String) uniqueid) != null) {
                        LOG.info("OssDaoOpenNMSImpl().updateNodeCaches WARNING node.getId():{} Unique ID is duplicated. Unique ID = ManagedObjectInstance:{} ManagedObjectType:{}", node.getId(), assetRecord.getManagedObjectInstance(), assetRecord.getManagedObjectType());
                    } else {
                        nodeCacheByUniqueID.put(uniqueid, node);
                    }
                }
            } catch (Throwable ex) {
                LOG.error("OssDaoOpenNMSImpl().updateNodeCaches Error updating node caches: ERROR", ex);
            }
        }
        if (LOG.isDebugEnabled()) {
            LOG.debug("OssDaoOpenNMSImpl().updateNodeCaches - Updated nodeCacheByID : contents :");
            try {
                for (Integer id : nodeCacheByID.keySet()) {
                    OnmsNode node = (OnmsNode) nodeCacheByID.get(id);
                    LOG.debug("\tKey: Node ID:{} NodeLabel:{}", id, node.getLabel());
                }
            } catch (Exception e) {
                LOG.error("OssDaoOpenNMSImpl().updateNodeCaches: Problem listing nodeCacheByLabel contents Error:", e);
            }
            LOG.debug("OssDaoOpenNMSImpl().updateNodeCaches - Updated nodeCacheByLabel : contents :");
            try {
                for (String label : nodeCacheByLabel.keySet()) {
                    OnmsNode node = (OnmsNode) nodeCacheByLabel.get(label);
                    LOG.debug("\tKey: Label:{} NodeID: {}", label, node.getId());
                }
            } catch (Exception e) {
                LOG.error("OssDaoOpenNMSImpl().updateNodeCaches: Problem listing nodeCacheByLabel contents. Error:", e);
            }
            try {
                LOG.debug("OssDaoOpenNMSImpl().updateNodeCaches - Updated nodeCacheByUniqueID : contents :");
                for (String uniqueID : nodeCacheByUniqueID.keySet()) {
                    OnmsNode node = (OnmsNode) nodeCacheByUniqueID.get(uniqueID);
                    LOG.debug("\tKey: uniqueID:{} NodeID:{}", uniqueID, node.getId());
                }
            } catch (Exception e) {
                LOG.error("OssDaoOpenNMSImpl().updateNodeCaches: Problem listing nodeCacheByUniqueID contents Error:", e);
            }
        }
    } catch (Throwable ex) {
        LOG.error("OssDaoOpenNMSImpl().updateNodeCaches ERROR : ", ex);
    }
}
Also used : OnmsNode(org.opennms.netmgt.model.OnmsNode) OnmsAssetRecord(org.opennms.netmgt.model.OnmsAssetRecord) TransactionStatus(org.springframework.transaction.TransactionStatus) TransactionCallbackWithoutResult(org.springframework.transaction.support.TransactionCallbackWithoutResult) UndeclaredThrowableException(java.lang.reflect.UndeclaredThrowableException)

Example 15 with OnmsAssetRecord

use of org.opennms.netmgt.model.OnmsAssetRecord in project opennms by OpenNMS.

the class AbstractXmlCollectionHandlerTest method testParseString.

/**
 * Test parse string.
 *
 * @throws Exception the exception
 */
@Test
public void testParseString() throws Exception {
    OnmsNode node = new OnmsNode();
    node.setId(1);
    node.setLabel("mynode.local");
    OnmsAssetRecord asset = new OnmsAssetRecord();
    asset.setSerialNumber("1001");
    node.setAssetRecord(asset);
    Map<String, String> parameters = new HashMap<>();
    parameters.put("port", "80");
    String url = AbstractXmlCollectionHandler.parseString("URL", "http://{nodeLabel}:{parameter:port}/{ipAddress}/serial/{serialNumber}/{step}", node, "127.0.0.1", 300, parameters);
    Assert.assertEquals("http://mynode.local:80/127.0.0.1/serial/1001/300", url);
    String multiline = "<data>\n   <source label='{nodeLabel}'/>\n</data>";
    String xml = AbstractXmlCollectionHandler.parseString("Content", multiline, node, "127.0.0.1", 300, parameters);
    Assert.assertEquals("<data>\n   <source label='mynode.local'/>\n</data>", xml);
}
Also used : OnmsNode(org.opennms.netmgt.model.OnmsNode) HashMap(java.util.HashMap) OnmsAssetRecord(org.opennms.netmgt.model.OnmsAssetRecord) Test(org.junit.Test)

Aggregations

OnmsAssetRecord (org.opennms.netmgt.model.OnmsAssetRecord)23 OnmsNode (org.opennms.netmgt.model.OnmsNode)18 Test (org.junit.Test)8 OnmsGeolocation (org.opennms.netmgt.model.OnmsGeolocation)5 Transactional (org.springframework.transaction.annotation.Transactional)5 BeanWrapper (org.springframework.beans.BeanWrapper)4 InetAddress (java.net.InetAddress)3 NodeDao (org.opennms.netmgt.dao.api.NodeDao)3 OnmsCategory (org.opennms.netmgt.model.OnmsCategory)3 TransactionStatus (org.springframework.transaction.TransactionStatus)3 List (java.util.List)2 Matcher (java.util.regex.Matcher)2 Before (org.junit.Before)2 MockCollectionAgent (org.opennms.core.collection.test.MockCollectionAgent)2 RrdPersisterFactory (org.opennms.netmgt.collection.persistence.rrd.RrdPersisterFactory)2 DefaultDataCollectionConfigDao (org.opennms.netmgt.config.DefaultDataCollectionConfigDao)2 AssetField (org.opennms.netmgt.config.snmpAsset.adapter.AssetField)2 FilesystemResourceStorageDao (org.opennms.netmgt.dao.support.FilesystemResourceStorageDao)2 JRobinRrdStrategy (org.opennms.netmgt.rrd.jrobin.JRobinRrdStrategy)2 SnmpAgentConfig (org.opennms.netmgt.snmp.SnmpAgentConfig)2