Search in sources :

Example 86 with BeanWrapper

use of org.springframework.beans.BeanWrapper in project opennms by OpenNMS.

the class ListenerFactory method buildListener.

public static Listener buildListener(ListenerDefinition listenerDef, AsyncDispatcher<TelemetryMessage> dispatcher) throws Exception {
    // Instantiate the associated class
    final Object listenerInstance;
    try {
        final Class<?> clazz = Class.forName(listenerDef.getClassName());
        final Constructor<?> ctor = clazz.getConstructor();
        listenerInstance = ctor.newInstance();
    } catch (Exception e) {
        throw new RuntimeException(String.format("Failed to instantiate listener with class name '%s'.", listenerDef.getClassName(), e));
    }
    // Cast
    if (!(listenerInstance instanceof Listener)) {
        throw new IllegalArgumentException(String.format("%s must implement %s", listenerDef.getClassName(), Listener.class.getCanonicalName()));
    }
    final Listener listener = (Listener) listenerInstance;
    // Apply the parameters
    final BeanWrapper wrapper = PropertyAccessorFactory.forBeanPropertyAccess(listener);
    wrapper.setPropertyValues(listenerDef.getParameterMap());
    // Update the name
    // The one given in the definition wins over any that may be set by the parameters
    listener.setName(listenerDef.getName());
    // Use the given dispatcher
    listener.setDispatcher(dispatcher);
    return listener;
}
Also used : BeanWrapper(org.springframework.beans.BeanWrapper) Listener(org.opennms.netmgt.telemetry.listeners.api.Listener)

Example 87 with BeanWrapper

use of org.springframework.beans.BeanWrapper in project opennms by OpenNMS.

the class TelemetryMessageConsumer method buildAdapter.

private Adapter buildAdapter(org.opennms.netmgt.telemetry.config.model.Adapter adapterDef) throws Exception {
    Adapter adapter = adapterRegistry.getAdapter(adapterDef.getClassName(), protocolDef, adapterDef.getParameterMap());
    if (adapter == null) {
        final Object adapterInstance;
        try {
            final Class<?> clazz = Class.forName(adapterDef.getClassName());
            final Constructor<?> ctor = clazz.getConstructor();
            adapterInstance = ctor.newInstance();
        } catch (Exception e) {
            throw new RuntimeException(String.format("Failed to instantiate adapter with class name '%s'.", adapterDef.getClassName(), e));
        }
        // Cast
        if (!(adapterInstance instanceof Adapter)) {
            throw new IllegalArgumentException(String.format("%s must implement %s", adapterDef.getClassName(), Adapter.class.getCanonicalName()));
        }
        adapter = (Adapter) adapterInstance;
        // Apply the parameters
        final BeanWrapper wrapper = PropertyAccessorFactory.forBeanPropertyAccess(adapter);
        wrapper.setPropertyValues(adapterDef.getParameterMap());
        // Autowire!
        final AutowireCapableBeanFactory beanFactory = applicationContext.getAutowireCapableBeanFactory();
        beanFactory.autowireBean(adapter);
        beanFactory.initializeBean(adapter, "adapter");
        // Set the protocol reference
        adapter.setProtocol(protocolDef);
    }
    return adapter;
}
Also used : BeanWrapper(org.springframework.beans.BeanWrapper) Adapter(org.opennms.netmgt.telemetry.adapters.api.Adapter) AutowireCapableBeanFactory(org.springframework.beans.factory.config.AutowireCapableBeanFactory)

Example 88 with BeanWrapper

use of org.springframework.beans.BeanWrapper in project opennms by OpenNMS.

the class JtiAdapterFactory method createAdapter.

public Adapter createAdapter(Protocol protocol, Map<String, String> properties) {
    final JtiGpbAdapter adapter = new JtiGpbAdapter();
    adapter.setProtocol(protocol);
    adapter.setCollectionAgentFactory(getCollectionAgentFactory());
    adapter.setInterfaceToNodeCache(getInterfaceToNodeCache());
    adapter.setNodeDao(getNodeDao());
    adapter.setTransactionTemplate(getTransactionTemplate());
    adapter.setFilterDao(getFilterDao());
    adapter.setPersisterFactory(getPersisterFactory());
    adapter.setBundleContext(getBundleContext());
    final BeanWrapper wrapper = PropertyAccessorFactory.forBeanPropertyAccess(adapter);
    wrapper.setPropertyValues(properties);
    return adapter;
}
Also used : BeanWrapper(org.springframework.beans.BeanWrapper)

Example 89 with BeanWrapper

use of org.springframework.beans.BeanWrapper in project opennms by OpenNMS.

the class XmlTest method assertDepthEquals.

private static void assertDepthEquals(final int depth, final String propertyName, final Object expected, Object actual) {
    if (expected == null && actual == null) {
        return;
    } else if (expected == null) {
        fail("expected " + propertyName + " was null but actual was not!");
    } else if (actual == null) {
        fail("actual " + propertyName + " was null but expected was not!");
    }
    final String assertionMessage = propertyName == null ? ("Top-level objects (" + expected.getClass().getName() + ") do not match.") : ("Properties " + propertyName + " do not match.");
    if (expected.getClass().getName().startsWith("java") || actual.getClass().getName().startsWith("java")) {
        // java primitives, just do assertEquals
        if (expected instanceof Object[] || actual instanceof Object[]) {
            assertTrue(assertionMessage, Arrays.equals((Object[]) expected, (Object[]) actual));
        } else {
            assertEquals(assertionMessage, expected, actual);
        }
        return;
    }
    final BeanWrapper expectedWrapper = new BeanWrapperImpl(expected);
    final BeanWrapper actualWrapper = new BeanWrapperImpl(actual);
    final Set<String> properties = new TreeSet<>();
    for (final PropertyDescriptor descriptor : expectedWrapper.getPropertyDescriptors()) {
        properties.add(descriptor.getName());
    }
    for (final PropertyDescriptor descriptor : actualWrapper.getPropertyDescriptors()) {
        properties.add(descriptor.getName());
    }
    properties.remove("class");
    for (final String property : properties) {
        final PropertyDescriptor expectedDescriptor = expectedWrapper.getPropertyDescriptor(property);
        final PropertyDescriptor actualDescriptor = actualWrapper.getPropertyDescriptor(property);
        if (expectedDescriptor != null && actualDescriptor != null) {
            // both have descriptors, so walk the sub-objects
            Object expectedValue = null;
            Object actualValue = null;
            try {
                expectedValue = expectedWrapper.getPropertyValue(property);
            } catch (final Exception e) {
            }
            try {
                actualValue = actualWrapper.getPropertyValue(property);
            } catch (final Exception e) {
            }
            assertDepthEquals(depth + 1, property, expectedValue, actualValue);
        } else if (expectedDescriptor != null) {
            fail("Should have '" + property + "' property on actual object, but there was none!");
        } else if (actualDescriptor != null) {
            fail("Should have '" + property + "' property on expected object, but there was none!");
        }
    }
    if (expected instanceof Object[] || actual instanceof Object[]) {
        final Object[] expectedArray = (Object[]) expected;
        final Object[] actualArray = (Object[]) actual;
        assertTrue(assertionMessage, Arrays.equals(expectedArray, actualArray));
    } else if (expected instanceof long[] || actual instanceof long[]) {
        final long[] expectedArray = (long[]) expected;
        final long[] actualArray = (long[]) actual;
        assertTrue(assertionMessage, Arrays.equals(expectedArray, actualArray));
    } else if (expected instanceof int[] || actual instanceof int[]) {
        final int[] expectedArray = (int[]) expected;
        final int[] actualArray = (int[]) actual;
        assertTrue(assertionMessage, Arrays.equals(expectedArray, actualArray));
    } else if (expected instanceof byte[] || actual instanceof byte[]) {
        final byte[] expectedArray = (byte[]) expected;
        final byte[] actualArray = (byte[]) actual;
        assertTrue(assertionMessage, Arrays.equals(expectedArray, actualArray));
    } else {
        expected.getClass().isPrimitive();
        assertEquals(assertionMessage, expected, actual);
    }
}
Also used : BeanWrapper(org.springframework.beans.BeanWrapper) BeanWrapperImpl(org.springframework.beans.BeanWrapperImpl) PropertyDescriptor(java.beans.PropertyDescriptor) TreeSet(java.util.TreeSet) XPathExpressionException(javax.xml.xpath.XPathExpressionException) IOException(java.io.IOException)

Example 90 with BeanWrapper

use of org.springframework.beans.BeanWrapper in project opennms by OpenNMS.

the class SnmpAssetProvisioningAdapter method doUpdateNode.

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

        @Override
        public InetAddress doInTransaction(final TransactionStatus arg0) {
            return getIpForNode(node);
        }
    });
    final String locationName = node.getLocation() != null ? node.getLocation().getLocationName() : null;
    final SnmpAgentConfig agentConfig = m_snmpConfigDao.getAgentConfig(ipaddress, locationName);
    final OnmsAssetRecord asset = node.getAssetRecord();
    m_config.getReadLock().lock();
    try {
        for (AssetField field : m_config.getAssetFieldsForAddress(ipaddress, node.getSysObjectId())) {
            try {
                String value = fetchSnmpAssetString(m_locationAwareSnmpClient, agentConfig, locationName, field.getMibObjs(), field.getFormatString());
                LOG.debug("doUpdate: Setting asset field \" {} \" to value: {}", value, field.getName());
                // Use Spring bean-accessor classes to set the field value
                BeanWrapper wrapper = PropertyAccessorFactory.forBeanPropertyAccess(asset);
                try {
                    wrapper.setPropertyValue(field.getName(), value);
                } catch (BeansException e) {
                    LOG.warn("doUpdate: Could not set property \" {} \" on asset object: {}", field.getName(), e.getMessage(), e);
                }
            } catch (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("doUpdate: 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)

Aggregations

BeanWrapper (org.springframework.beans.BeanWrapper)144 BeanWrapperImpl (org.springframework.beans.BeanWrapperImpl)79 Test (org.junit.jupiter.api.Test)31 NumberTestBean (org.springframework.beans.testfixture.beans.NumberTestBean)21 BooleanTestBean (org.springframework.beans.testfixture.beans.BooleanTestBean)20 MutablePropertyValues (org.springframework.beans.MutablePropertyValues)19 ITestBean (org.springframework.beans.testfixture.beans.ITestBean)18 IndexedTestBean (org.springframework.beans.testfixture.beans.IndexedTestBean)18 TestBean (org.springframework.beans.testfixture.beans.TestBean)18 Consumes (javax.ws.rs.Consumes)16 PUT (javax.ws.rs.PUT)16 Path (javax.ws.rs.Path)16 PropertyEditorSupport (java.beans.PropertyEditorSupport)14 Assertions.assertThatIllegalArgumentException (org.assertj.core.api.Assertions.assertThatIllegalArgumentException)14 HashSet (java.util.HashSet)12 BeansException (org.springframework.beans.BeansException)12 PropertyDescriptor (java.beans.PropertyDescriptor)11 OnmsNode (org.opennms.netmgt.model.OnmsNode)9 Test (org.junit.Test)6 BigDecimal (java.math.BigDecimal)5