Example usage for org.apache.commons.configuration HierarchicalConfiguration getList

List of usage examples for org.apache.commons.configuration HierarchicalConfiguration getList

Introduction

In this page you can find the example usage for org.apache.commons.configuration HierarchicalConfiguration getList.

Prototype

public List getList(String key) 

Source Link

Usage

From source file:com.github.steveash.typedconfig.resolver.type.container.AbstractContainerValueResolverFactory.java

@Override
public ValueResolver makeForThis(final ConfigBinding containerBinding, final HierarchicalConfiguration config,
        final ConfigFactoryContext context) {
    return new ValueResolver() {
        @Override//  ww w  . ja  v  a  2s. c  o m
        public Object resolve() {
            TypeToken<?> thisType = getContainedType(containerBinding.getDataType());
            ConfigBinding childBinding = containerBinding.withKey("").withDataType(thisType)
                    .withOptions(Option.EmptyOptions);

            ValueResolverFactory childFactory = context.getRegistry().lookup(childBinding);

            switch (childFactory.getValueType()) {
            case Simple:
                return makeForSimpleType(childBinding, childFactory);
            case Nested:
                return makeForNestedType(childBinding, childFactory);
            default:
                throw new InvalidProxyException("The proxy method returning " + containerBinding.getDataType()
                        + " for configuration key " + containerBinding.getConfigKeyToLookup()
                        + " uses a container type " + "which returns " + thisType
                        + " which is also a container type.  You can't have "
                        + "containers of container types.");
            }
        }

        private Object makeForNestedType(ConfigBinding childBinding, ValueResolverFactory childFactory) {
            List<HierarchicalConfiguration> childConfigs = config
                    .configurationsAt(containerBinding.getConfigKeyToLookup());
            Collection<Object> values = makeEmptyCollection(childConfigs.size());
            for (HierarchicalConfiguration childConfig : childConfigs) {
                SubnodeConfiguration childConfigAsSub = (SubnodeConfiguration) childConfig;
                ConfigBinding subBinding = childBinding.withKey(childConfigAsSub.getSubnodeKey());
                ValueResolver r = childFactory.makeForThis(subBinding, childConfig, context);
                values.add(r.resolve());
            }
            return makeReturnValueFrom(values, containerBinding);
        }

        private Object makeForSimpleType(ConfigBinding childBinding, ValueResolverFactory childFactory) {
            ValueResolver childResolver = childFactory.makeForThis(childBinding, config, context);
            List<Object> configValues = config.getList(containerBinding.getConfigKeyToLookup());

            Collection<Object> containedValues = makeEmptyCollection(configValues.size());
            for (Object o : configValues) {
                if (!(o instanceof String))
                    throw new IllegalArgumentException(
                            "Can only use Configuration instances which return string "
                                    + "representations of the values which we will then convert. XMLConfiguration does this");

                containedValues.add(childResolver.convertDefaultValue((String) o));
            }
            return makeReturnValueFrom(containedValues, containerBinding);
        }

        @Override
        public Object convertDefaultValue(String defaultValue) {
            throw new IllegalStateException("cannot specify a defaults for container types");
        }

        @Override
        public String configurationKeyToLookup() {
            return containerBinding.getConfigKeyToLookup();
        }
    };
}

From source file:at.ac.tuwien.auto.iotsys.gateway.connectors.knx.KNXDeviceLoaderImpl.java

public ArrayList<Connector> initDevices(ObjectBroker objectBroker) {
    setConfiguration(devicesConfig);//  w w w . j  av a2s .  c  om
    objectBroker.getConfigDb().prepareDeviceLoader(getClass().getName());

    ArrayList<Connector> connectors = new ArrayList<Connector>();

    List<JsonNode> connectorsFromDb = objectBroker.getConfigDb().getConnectors("knx");
    int connectorsSize = 0;

    if (connectorsFromDb.size() <= 0) {
        Object knxConnectors = devicesConfig.getProperty("knx.connector.name");

        if (knxConnectors != null) {
            connectorsSize = 1;
        }

        if (knxConnectors instanceof Collection<?>) {
            connectorsSize = ((Collection<?>) knxConnectors).size();
        }
    } else
        connectorsSize = connectorsFromDb.size();

    for (int connector = 0; connector < connectorsSize; connector++) {

        HierarchicalConfiguration subConfig = devicesConfig.configurationAt("knx.connector(" + connector + ")");

        Object knxConfiguredDevices = subConfig.getProperty("device.type");// just to get the number of devices
        String connectorId = "";
        String connectorName = subConfig.getString("name");
        String routerIP = subConfig.getString("router.ip");
        int routerPort = subConfig.getInteger("router.port", 3671);
        String localIP = subConfig.getString("localIP");
        Boolean enabled = subConfig.getBoolean("enabled", false);

        try {
            connectorId = connectorsFromDb.get(connector).get("_id").asText();
            connectorName = connectorsFromDb.get(connector).get("name").asText();
            enabled = connectorsFromDb.get(connector).get("enabled").asBoolean();
            routerIP = connectorsFromDb.get(connector).get("routerHostname").asText();
            routerPort = connectorsFromDb.get(connector).get("routerPort").asInt();
            localIP = connectorsFromDb.get(connector).get("localIP").asText();
        } catch (Exception e) {
            log.info("Cannot fetch configuration from Database, using devices.xml");
        }

        if (enabled) {
            try {
                KNXConnector knxConnector = new KNXConnector(routerIP, routerPort, localIP);
                knxConnector.setName(connectorName);
                knxConnector.setTechnology("knx");
                knxConnector.setEnabled(enabled);
                //knxConnector.connect();
                connectors.add(knxConnector);

                int numberOfDevices = 0;
                List<Device> devicesFromDb = objectBroker.getConfigDb().getDevices(connectorId);

                if (connectorsFromDb.size() <= 0) {
                    if (knxConfiguredDevices != null) {
                        numberOfDevices = 1; // there is at least one
                                             // device.
                    }
                    if (knxConfiguredDevices instanceof Collection<?>) {
                        Collection<?> knxDevices = (Collection<?>) knxConfiguredDevices;
                        numberOfDevices = knxDevices.size();
                    }
                } else
                    numberOfDevices = devicesFromDb.size();

                log.info(
                        numberOfDevices + " KNX devices found in configuration for connector " + connectorName);
                for (int i = 0; i < numberOfDevices; i++) {

                    String type = subConfig.getString("device(" + i + ").type");
                    List<Object> address = subConfig.getList("device(" + i + ").address");
                    String addressString = address.toString();

                    String ipv6 = subConfig.getString("device(" + i + ").ipv6");
                    String href = subConfig.getString("device(" + i + ").href");

                    String name = subConfig.getString("device(" + i + ").name");

                    String displayName = subConfig.getString("device(" + i + ").displayName");

                    Boolean historyEnabled = subConfig.getBoolean("device(" + i + ").historyEnabled", false);

                    Boolean groupCommEnabled = subConfig.getBoolean("device(" + i + ").groupCommEnabled",
                            false);

                    Integer historyCount = subConfig.getInt("device(" + i + ").historyCount", 0);

                    Boolean refreshEnabled = subConfig.getBoolean("device(" + i + ").refreshEnabled", false);

                    Device deviceFromDb;
                    try {
                        deviceFromDb = devicesFromDb.get(i);
                        type = deviceFromDb.getType();
                        addressString = deviceFromDb.getAddress();
                        String subAddr[] = addressString.substring(1, addressString.length() - 1).split(", ");
                        address = Arrays.asList((Object[]) subAddr);
                        ipv6 = deviceFromDb.getIpv6();
                        href = deviceFromDb.getHref();
                        name = deviceFromDb.getName();
                        displayName = deviceFromDb.getDisplayName();
                        historyEnabled = deviceFromDb.isHistoryEnabled();
                        groupCommEnabled = deviceFromDb.isGroupcommEnabled();
                        refreshEnabled = deviceFromDb.isRefreshEnabled();
                        historyCount = deviceFromDb.getHistoryCount();
                    } catch (Exception e) {
                    }

                    // Transition step: comment when done
                    Device d = new Device(type, ipv6, addressString, href, name, displayName, historyCount,
                            historyEnabled, groupCommEnabled, refreshEnabled);
                    objectBroker.getConfigDb().prepareDevice(connectorName, d);

                    if (type != null && address != null) {
                        int addressCount = address.size();
                        try {
                            Constructor<?>[] declaredConstructors = Class.forName(type)
                                    .getDeclaredConstructors();
                            for (int k = 0; k < declaredConstructors.length; k++) {
                                if (declaredConstructors[k].getParameterTypes().length == addressCount + 1) { // constructor
                                    // that
                                    // takes
                                    // the
                                    // KNX
                                    // connector
                                    // and
                                    // group
                                    // address
                                    // as
                                    // argument
                                    Object[] args = new Object[address.size() + 1];
                                    // first arg is KNX connector

                                    args[0] = knxConnector;
                                    for (int l = 1; l <= address.size(); l++) {
                                        try {
                                            String adr = (String) address.get(l - 1);
                                            if (adr == null || adr.equals("null")) {
                                                args[l] = null;
                                            } else {
                                                args[l] = new GroupAddress(adr);
                                            }
                                        } catch (KNXFormatException e) {
                                            e.printStackTrace();
                                        }
                                    }
                                    try {
                                        // create a instance of the
                                        // specified KNX device
                                        Obj knxDevice = (Obj) declaredConstructors[k].newInstance(args);

                                        knxDevice.setHref(new Uri(
                                                URLEncoder.encode(connectorName, "UTF-8") + "/" + href));

                                        if (name != null && name.length() > 0) {
                                            knxDevice.setName(name);
                                        }

                                        if (displayName != null && displayName.length() > 0) {
                                            knxDevice.setDisplayName(displayName);
                                        }

                                        if (ipv6 != null) {
                                            objectBroker.addObj(knxDevice, ipv6);
                                        } else {
                                            objectBroker.addObj(knxDevice);
                                        }

                                        myObjects.add(knxDevice);

                                        knxDevice.initialize();

                                        if (historyEnabled != null && historyEnabled) {
                                            if (historyCount != null && historyCount != 0) {
                                                objectBroker.addHistoryToDatapoints(knxDevice, historyCount);
                                            } else {
                                                objectBroker.addHistoryToDatapoints(knxDevice);
                                            }
                                        }

                                        if (groupCommEnabled) {
                                            objectBroker.enableGroupComm(knxDevice);
                                        }

                                        if (refreshEnabled != null && refreshEnabled) {
                                            objectBroker.enableObjectRefresh(knxDevice);
                                        }

                                    } catch (IllegalArgumentException e) {
                                        e.printStackTrace();
                                    } catch (InstantiationException e) {
                                        e.printStackTrace();
                                    } catch (IllegalAccessException e) {
                                        e.printStackTrace();
                                    } catch (InvocationTargetException e) {
                                        e.printStackTrace();
                                    }
                                }
                            }
                        } catch (SecurityException e) {
                            e.printStackTrace();
                        } catch (ClassNotFoundException e) {
                            e.printStackTrace();
                        }
                    }
                }
            } catch (Exception e) {
                e.printStackTrace();
            }

        }
    }

    return connectors;
}

From source file:net.fenyo.gnetwatch.GUI.GUI.java

/**
   * Parses a configuration file to create initial targets.
   * @param filename configuration file.
   * @return void./* ww w .  j a  v  a2s.c om*/
   */
public void createFromXML(final String filename) {
    final GUI gui = this;

    asyncExec(new Runnable() {
        public void run() {
            synchronized (synchro) {
                final Session session = synchro.getSessionFactory().getCurrentSession();
                session.beginTransaction();

                try {
                    final XMLConfiguration initial = new XMLConfiguration(filename);
                    initial.setExpressionEngine(new XPathExpressionEngine());

                    // limitation de l'implmentation : on n'autorise que les parents de type groupe

                    for (final HierarchicalConfiguration subconf : (java.util.List<HierarchicalConfiguration>) initial
                            .configurationsAt("/objects/target")) {
                        if (subconf.getProperty("@targetType").equals("group")) {
                            final String name = subconf.getString("name");

                            final java.util.List<String> parents = (java.util.List<String>) subconf
                                    .getList("parent[@parentType='group']");
                            if (parents.size() == 0) {
                                final TargetGroup target_group = new TargetGroup(
                                        "added by initial configuration", name);
                                target_group.addTarget(gui, user_defined);
                            } else
                                for (final String parent : parents) {
                                    final TargetGroup foo = new TargetGroup("temporary", parent);
                                    final TargetGroup target_parent = (TargetGroup) getCanonicalInstance(foo);
                                    if (target_parent == foo)
                                        log.error("Initial configuration: parent does not exist");
                                    else {
                                        final TargetGroup target_group = new TargetGroup(
                                                "added by initial configuration", name);
                                        target_group.addTarget(gui, target_parent);
                                    }
                                }
                        }

                        if (subconf.getProperty("@targetType").equals("ipv4")) {
                            final String address = subconf.getString("address");

                            java.util.List<String> parents = (java.util.List<String>) subconf
                                    .getList("parent[@parentType='group']");
                            if (parents.size() != 0)
                                for (final String parent : parents) {
                                    final TargetGroup foo = new TargetGroup("temporary", parent);
                                    final TargetGroup target_parent = (TargetGroup) getCanonicalInstance(foo);
                                    if (target_parent == foo)
                                        log.error("Initial configuration: parent does not exist");
                                    else {
                                        final TargetIPv4 target = new TargetIPv4(
                                                "added by initial configuration",
                                                GenericTools.stringToInet4Address(address), snmp_manager);
                                        target.addTarget(gui, target_parent);
                                        if (subconf.getString("snmp/version") != null) {
                                            if (subconf.getString("snmp/version").equals("v1"))
                                                target.getSNMPQuerier().setVersion(0);
                                            if (subconf.getString("snmp/version").equals("v2c"))
                                                target.getSNMPQuerier().setVersion(1);
                                            if (subconf.getString("snmp/version").equals("v3"))
                                                target.getSNMPQuerier().setVersion(2);
                                        }
                                        if (subconf.getString("snmp/community") != null)
                                            target.getSNMPQuerier()
                                                    .setCommunity(subconf.getString("snmp/community"));

                                        // Setting the agent is not possible when creating a target through the GUI
                                        if (subconf.getString("snmp/agent") != null)
                                            target.getSNMPQuerier().setAddress(GenericTools
                                                    .stringToInet4Address(subconf.getString("snmp/agent")));

                                        if (subconf.getString("snmp/password-auth") != null)
                                            target.getSNMPQuerier()
                                                    .setPasswordAuth(subconf.getString("snmp/password-auth"));
                                        if (subconf.getString("snmp/password-priv") != null)
                                            target.getSNMPQuerier()
                                                    .setPasswordPriv(subconf.getString("snmp/password-priv"));
                                        if (subconf.getString("snmp/pdu-max-size") != null)
                                            target.getSNMPQuerier()
                                                    .setPDUMaxSize(subconf.getInt("snmp/pdu-max-size"));
                                        if (subconf.getString("snmp/port") != null)
                                            target.getSNMPQuerier().setPort(subconf.getInt("snmp/port"));
                                        if (subconf.getString("snmp/retries") != null)
                                            target.getSNMPQuerier().setRetries(subconf.getInt("snmp/retries"));
                                        if (subconf.getString("snmp/security") != null
                                                && subconf.getString("snmp/security").equals("NOAUTH_NOPRIV"))
                                            target.getSNMPQuerier().setSec(SecurityLevel.NOAUTH_NOPRIV);
                                        if (subconf.getString("snmp/security") != null
                                                && subconf.getString("snmp/security").equals("AUTH_NOPRIV"))
                                            target.getSNMPQuerier().setSec(SecurityLevel.AUTH_NOPRIV);
                                        if (subconf.getString("snmp/security") != null
                                                && subconf.getString("snmp/security").equals("AUTH_PRIV"))
                                            target.getSNMPQuerier().setSec(SecurityLevel.AUTH_PRIV);
                                        if (subconf.getString("snmp/timeout") != null)
                                            target.getSNMPQuerier().setTimeout(subconf.getInt("snmp/timeout"));
                                        target.getSNMPQuerier().update();
                                    }
                                }
                        }

                        if (subconf.getProperty("@targetType").equals("ipv6")) {
                            final String address = subconf.getString("address");

                            java.util.List<String> parents = (java.util.List<String>) subconf
                                    .getList("parent[@parentType='group']");
                            if (parents.size() != 0)
                                for (final String parent : parents) {
                                    final TargetGroup foo = new TargetGroup("temporary", parent);
                                    final TargetGroup target_parent = (TargetGroup) getCanonicalInstance(foo);
                                    if (target_parent == foo)
                                        log.error("Initial configuration: parent does not exist");
                                    else {
                                        final TargetIPv6 target = new TargetIPv6(
                                                "added by initial configuration",
                                                GenericTools.stringToInet6Address(address), snmp_manager);
                                        target.addTarget(gui, target_parent);
                                    }
                                }
                        }

                        if (subconf.getProperty("@targetType").equals("ipv4range")) {
                            final String begin = subconf.getString("begin");
                            final String end = subconf.getString("end");

                            java.util.List<String> parents = (java.util.List<String>) subconf
                                    .getList("parent[@parentType='group']");
                            if (parents.size() != 0)
                                for (final String parent : parents) {
                                    final TargetGroup foo = new TargetGroup("temporary", parent);
                                    final TargetGroup target_parent = (TargetGroup) getCanonicalInstance(foo);
                                    if (target_parent == foo)
                                        log.error("Initial configuration: parent does not exist");
                                    else {
                                        final TargetIPv4Range target = new TargetIPv4Range(
                                                "added by initial configuration",
                                                GenericTools.stringToInet4Address(begin),
                                                GenericTools.stringToInet4Address(end));
                                        target.addTarget(gui, target_parent);
                                    }
                                }
                        }

                        if (subconf.getProperty("@targetType").equals("ipv4subnet")) {
                            final String network = subconf.getString("network");
                            final String netmask = subconf.getString("netmask");

                            java.util.List<String> parents = (java.util.List<String>) subconf
                                    .getList("parent[@parentType='group']");
                            if (parents.size() != 0)
                                for (final String parent : parents) {
                                    final TargetGroup foo = new TargetGroup("temporary", parent);
                                    final TargetGroup target_parent = (TargetGroup) getCanonicalInstance(foo);
                                    if (target_parent == foo)
                                        log.error("Initial configuration: parent does not exist");
                                    else {
                                        final TargetIPv4Subnet target = new TargetIPv4Subnet(
                                                "added by initial configuration",
                                                GenericTools.stringToInet4Address(network),
                                                GenericTools.stringToInet4Address(netmask));
                                        target.addTarget(gui, target_parent);
                                    }
                                }
                        }
                    }

                    session.getTransaction().commit();
                } catch (final ConfigurationException ex) {
                    log.warn("Exception", ex);
                    session.getTransaction().rollback();
                } catch (final AlgorithmException ex) {
                    log.error("Exception", ex);
                    session.getTransaction().rollback();
                } catch (final UnknownHostException ex) {
                    log.error("Exception", ex);
                    session.getTransaction().rollback();
                }
            }
        }
    });
}

From source file:at.ac.tuwien.auto.iotsys.gateway.connectors.bacnet.BacnetDeviceLoaderImpl.java

public ArrayList<Connector> initDevices(ObjectBroker objectBroker) {
    setConfiguration(devicesConfig);/*from w w  w .  j ava  2 s.co m*/
    objectBroker.getConfigDb().prepareDeviceLoader(getClass().getName());

    ArrayList<Connector> connectors = new ArrayList<Connector>();

    List<JsonNode> connectorsFromDb = objectBroker.getConfigDb().getConnectors("bacnet");
    int connectorsSize = 0;
    // bacnet
    if (connectorsFromDb.size() <= 0) {
        Object bacnetConnectors = devicesConfig.getProperty("bacnet.connector.name");

        if (bacnetConnectors != null) {
            connectorsSize = 1;
        } else {
            connectorsSize = 0;
        }

        if (bacnetConnectors instanceof Collection<?>) {
            connectorsSize = ((Collection<?>) bacnetConnectors).size();
        }
    } else
        connectorsSize = connectorsFromDb.size();

    for (int connector = 0; connector < connectorsSize; connector++) {
        HierarchicalConfiguration subConfig = devicesConfig
                .configurationAt("bacnet.connector(" + connector + ")");

        Object bacnetConfiguredDevices = subConfig.getProperty("device.type");
        String connectorId = "";
        String connectorName = subConfig.getString("name");
        String broadcastAddress = subConfig.getString("broadcastAddress");
        int localPort = subConfig.getInteger("localPort", 3671);
        int localDeviceID = subConfig.getInteger("localDeviceID", 12345);
        boolean enabled = subConfig.getBoolean("enabled", false);
        Boolean groupCommEnabled = subConfig.getBoolean("groupCommEnabled", null);
        Boolean historyEnabled = subConfig.getBoolean("historyEnabled", null);

        try {
            connectorId = connectorsFromDb.get(connector).get("_id").asText();
            connectorName = connectorsFromDb.get(connector).get("name").asText();
            enabled = connectorsFromDb.get(connector).get("enabled").asBoolean();
            groupCommEnabled = connectorsFromDb.get(connector).get("groupCommEnabled").asBoolean();
            historyEnabled = connectorsFromDb.get(connector).get("historyEnabled").asBoolean();
            broadcastAddress = connectorsFromDb.get(connector).get("broadcastAddress").asText();
            localPort = connectorsFromDb.get(connector).get("localPort").asInt();
            localDeviceID = connectorsFromDb.get(connector).get("localDeviceID").asInt();
        } catch (Exception e) {
            log.info("Cannot fetch configuration from Database, using devices.xml");
        }

        if (enabled) {
            try {
                BACnetConnector bacnetConnector = new BACnetConnector(localDeviceID, broadcastAddress,
                        localPort);
                bacnetConnector.setName(connectorName);
                bacnetConnector.setTechnology("bacnet");
                bacnetConnector.setEnabled(enabled);

                Obj bacRoot = bacnetConnector.getRootObj();
                bacRoot.setName(connectorName);
                bacRoot.setHref(new Uri(connectorName.replaceAll("[^a-zA-Z0-9-~\\(\\)]", "")));
                objectBroker.addObj(bacRoot, true);

                // Transition step: Moving configs to DB: all connector enabled, uncomment when done
                //bacnetConnector.connect();

                Boolean discoveryEnabled = subConfig.getBoolean("discovery-enabled", false);
                if (discoveryEnabled)
                    bacnetConnector.discover(
                            new DeviceDiscoveryListener(objectBroker, groupCommEnabled, historyEnabled));

                connectors.add(bacnetConnector);

                int numberOfDevices = 0;
                List<Device> devicesFromDb = objectBroker.getConfigDb().getDevices(connectorId);

                if (connectorsFromDb.size() <= 0) {
                    // TODO: bacnetConfiguredDevices is from devices.xml --> mismatch when a connector does not have any device associated,
                    // e.g., bacnet a-lab (auto) connector
                    // do like this for other device loaders!
                    if (bacnetConfiguredDevices != null) {
                        numberOfDevices = 1; // there is at least one device.
                    }
                    if (bacnetConfiguredDevices instanceof Collection<?>) {
                        Collection<?> bacnetDevices = (Collection<?>) bacnetConfiguredDevices;
                        numberOfDevices = bacnetDevices.size();
                    }
                } else
                    numberOfDevices = devicesFromDb.size();

                log.info(numberOfDevices + " BACnet devices found in configuration for connector "
                        + connectorName);

                // Transition step: comment when done
                for (int i = 0; i < numberOfDevices; i++) {
                    String type = subConfig.getString("device(" + i + ").type");
                    List<Object> address = subConfig.getList("device(" + i + ").address");
                    String addressString = address.toString();
                    String ipv6 = subConfig.getString("device(" + i + ").ipv6");
                    String href = subConfig.getString("device(" + i + ").href");

                    // device specific setting
                    Boolean historyEnabledDevice = subConfig.getBoolean("device(" + i + ").historyEnabled",
                            null);

                    if (historyEnabledDevice != null) {
                        historyEnabled = historyEnabledDevice;
                    }

                    // device specific setting
                    Boolean groupCommEnabledDevice = subConfig.getBoolean("device(" + i + ").groupCommEnabled",
                            null);

                    if (groupCommEnabledDevice != null) {
                        // overwrite general settings
                        groupCommEnabled = groupCommEnabledDevice;
                    }

                    String name = subConfig.getString("device(" + i + ").name");

                    String displayName = subConfig.getString("device(" + i + ").displayName");

                    Boolean refreshEnabled = subConfig.getBoolean("device(" + i + ").refreshEnabled", false);

                    Integer historyCount = subConfig.getInt("device(" + i + ").historyCount", 0);

                    Device deviceFromDb;
                    try {
                        deviceFromDb = devicesFromDb.get(i);
                        type = deviceFromDb.getType();
                        addressString = deviceFromDb.getAddress();
                        String subAddr[] = addressString.substring(1, addressString.length() - 1).split(", ");
                        address = Arrays.asList((Object[]) subAddr);
                        ipv6 = deviceFromDb.getIpv6();
                        href = deviceFromDb.getHref();
                        name = deviceFromDb.getName();
                        displayName = deviceFromDb.getDisplayName();
                        historyEnabled = deviceFromDb.isHistoryEnabled();
                        groupCommEnabled = deviceFromDb.isGroupcommEnabled();
                        refreshEnabled = deviceFromDb.isRefreshEnabled();
                        historyCount = deviceFromDb.getHistoryCount();
                    } catch (Exception e) {
                    }
                    // Transition step: comment when done
                    Device d = new Device(type, ipv6, addressString, href, name, displayName, historyCount,
                            historyEnabled, groupCommEnabled, refreshEnabled);
                    objectBroker.getConfigDb().prepareDevice(connectorName, d);

                    if (type != null && address != null) {

                        // now follow possible multiple data points
                        // identified through
                        // the device Id, object type, the instance number and the
                        // property identifier, which shall be packaged into an BacnetDatapointInfo object

                        ObjectIdentifier[] objectIdentifier = new ObjectIdentifier[(address.size()) / 4];
                        PropertyIdentifier[] propertyIdentifier = new PropertyIdentifier[(address.size()) / 4];

                        BacnetDataPointInfo[] bacnetDataPointInfo = new BacnetDataPointInfo[(address.size())
                                / 4];

                        int q = 0;
                        for (int p = 0; p <= address.size() - 4; p += 4) {
                            int remoteDeviceID = Integer.parseInt((String) address.get(p));
                            ObjectIdentifier objIdentifier = new ObjectIdentifier(
                                    new ObjectType(Integer.parseInt((String) address.get(p + 1))),
                                    Integer.parseInt((String) address.get(p + 2)));
                            PropertyIdentifier propIdentifier = new PropertyIdentifier(
                                    Integer.parseInt((String) address.get(p + 3)));
                            objectIdentifier[q] = objIdentifier;
                            propertyIdentifier[q] = propIdentifier;
                            bacnetDataPointInfo[q] = new BacnetDataPointInfo(remoteDeviceID, objIdentifier,
                                    propIdentifier);
                            q = q + 1;
                        }
                        Object[] args = new Object[q + 1];
                        args[0] = bacnetConnector;
                        //                        args[1] = Integer.parseInt(remoteDeviceID);
                        for (int p = 0; p < bacnetDataPointInfo.length; p++) {
                            args[1 + p] = bacnetDataPointInfo[p];
                        }

                        try {

                            Constructor<?>[] declaredConstructors = Class.forName(type)
                                    .getDeclaredConstructors();
                            for (int k = 0; k < declaredConstructors.length; k++) {
                                if (declaredConstructors[k].getParameterTypes().length == args.length) { // constructor
                                    // that
                                    // takes
                                    // the
                                    // KNX
                                    // connector
                                    // and
                                    // group
                                    // address
                                    // as
                                    // argument
                                    Obj bacnetDevice = (Obj) declaredConstructors[k].newInstance(args); // create
                                    // a
                                    // instance
                                    // of
                                    // the
                                    // specified
                                    // KNX
                                    // device
                                    bacnetDevice.setHref(
                                            new Uri(URLEncoder.encode(connectorName, "UTF-8") + "/" + href));

                                    if (name != null && name.length() > 0) {
                                        bacnetDevice.setName(name);
                                    }

                                    if (displayName != null && displayName.length() > 0) {
                                        bacnetDevice.setDisplayName(displayName);
                                    }

                                    if (ipv6 != null) {
                                        objectBroker.addObj(bacnetDevice, ipv6);
                                    } else {
                                        objectBroker.addObj(bacnetDevice);
                                    }

                                    myObjects.add(bacnetDevice);

                                    bacnetDevice.initialize();

                                    if (historyEnabled != null && historyEnabled) {
                                        if (historyCount != null && historyCount != 0) {
                                            objectBroker.addHistoryToDatapoints(bacnetDevice, historyCount);
                                        } else {
                                            objectBroker.addHistoryToDatapoints(bacnetDevice);
                                        }
                                    }

                                    if (refreshEnabled != null && refreshEnabled) {
                                        objectBroker.enableObjectRefresh(bacnetDevice);
                                    }

                                    if (groupCommEnabled != null && groupCommEnabled) {
                                        objectBroker.enableGroupComm(bacnetDevice);
                                    }
                                }
                            }
                        } catch (SecurityException e) {
                            e.printStackTrace();
                        } catch (ClassNotFoundException e) {
                            e.printStackTrace();
                        }
                    }
                }
            } catch (Exception e) {
                e.printStackTrace();
            }

        }
    }

    return connectors;
}

From source file:nl.knaw.huygens.timbuctoo.config.Configuration.java

/**
 * Returns VRE definitions./*  www.ja  va  2  s.  c om*/
 * TODO return a list of VRE's instead.
 */
public List<VREDef> getVREDefs() {
    List<VREDef> vreDefs = Lists.newArrayList();
    for (HierarchicalConfiguration cfg : xmlConfig.configurationsAt(SETTINGS_PREFIX + "vre-defs.vre")) {
        VREDef vreDef = new VREDef();
        vreDef.id = getString(cfg, "[@id]");
        vreDef.description = getString(cfg, "description");
        vreDef.modelPackage = getString(cfg, "model-package");
        vreDef.receptions = Lists.newArrayList();
        for (Object item : cfg.getList("receptions.reception")) {
            vreDef.receptions.add(item.toString());
        }
        vreDefs.add(vreDef);
    }
    return vreDefs;
}

From source file:org.codesearch.commons.configuration.xml.XmlConfigurationReader.java

/**
 * retrieves all required data about the given repository from the
 * configuration via the HierarchicalConfiguration and returns it as a
 * RepositoryDto/*  w ww .  ja va 2s.c  o m*/
 */
@SuppressWarnings("unchecked")
private RepositoryDto loadRepository(HierarchicalConfiguration hc) throws InvalidConfigurationException {
    RepositoryDto repo;
    //mandatory field
    String name = hc.getString(XmlConfigurationReaderConstants.REPOSITORY_NAME);

    // retrieve the repository blacklisted filenames and add all global filenames
    List<String> blacklistEntries = hc.getList(XmlConfigurationReaderConstants.REPOSITORY_BLACKLIST);
    if (blacklistEntries == null) {
        blacklistEntries = new LinkedList<String>();
    }
    blacklistEntries.addAll(getGlobalBlacklistEntries());

    // retrieve the repository whitelisted filenames and add all global filenames
    List<String> whitelistFileNames = hc
            .getList(XmlConfigurationReaderConstants.REPOSITORY_WHITELIST_FILENAMES);
    if (whitelistFileNames == null) {
        whitelistFileNames = new LinkedList<String>();
    }
    whitelistFileNames.addAll(getGlobalWhitelistEntries());

    String repoGroupString = hc.getString(XmlConfigurationReaderConstants.REPOSITORY_GROUPS);
    List<String> repositoryGroups = Arrays.asList(repoGroupString.split(" "));

    // retrieve the used authentication system and fill it with the required data
    AuthenticationType usedAuthentication = null;
    String authenticationType = hc.getString(XmlConfigurationReaderConstants.REPOSITORY_AUTHENTICATION_DATA);

    if (authenticationType == null || authenticationType.trim().isEmpty()
            || authenticationType.equals("none")) {
        usedAuthentication = new NoAuthentication();
    } else if (authenticationType.equals("basic")) {
        String username = hc.getString(XmlConfigurationReaderConstants.REPOSITORY_AUTHENTICATION_DATA_USERNAME);
        String password = hc.getString(XmlConfigurationReaderConstants.REPOSITORY_AUTHENTICATION_DATA_PASSWORD);
        usedAuthentication = new BasicAuthentication(username, password);
    } else if (authenticationType.equals("ssh")) {
        String sshFilePath = hc
                .getString(XmlConfigurationReaderConstants.REPOSITORY_AUTHENTICATION_DATA_SSH_FILE_PATH);
        String username = hc.getString(XmlConfigurationReaderConstants.REPOSITORY_AUTHENTICATION_DATA_USERNAME);
        String password = hc.getString(XmlConfigurationReaderConstants.REPOSITORY_AUTHENTICATION_DATA_PASSWORD);
        String port = hc.getString(XmlConfigurationReaderConstants.REPOSITORY_AUTHENTICATION_DATA_PORT);
        usedAuthentication = new SshAuthentication(username, password, port, sshFilePath);
    }
    String versionControlSystem = hc.getString(XmlConfigurationReaderConstants.REPOSITORY_VCS);
    repo = new RepositoryDto(name, hc.getString(XmlConfigurationReaderConstants.REPOSITORY_URL),
            usedAuthentication,
            hc.getBoolean(XmlConfigurationReaderConstants.REPOSITORY_CODE_NAVIGATION_ENABLED),
            versionControlSystem, blacklistEntries, whitelistFileNames, repositoryGroups);

    LOG.info("Read repository: " + repo.getName());
    return repo;
}

From source file:org.lable.oss.dynamicconfig.serialization.yaml.YamlDeserializerTest.java

@Test
public void testLoad() throws ConfigurationException, IOException, ClassNotFoundException {
    HierarchicalConfigurationDeserializer deserializer = new YamlDeserializer();
    HierarchicalConfiguration config = deserializer.deserialize(IOUtils.toInputStream(testYaml));

    // Type checking.
    assertThat(config.getString("type.string"), is("Okay"));

    List list = config.getList("type.listOfStrings");
    for (Object o : list) {
        assertThat(o, instanceOf(String.class));
    }//from  ww  w  .j  ava  2s . c o m
    assertThat(list.size(), is(3));
    assertThat(list.get(0), is("One"));
    assertThat(list.get(1), is("Two"));
    assertThat(list.get(2), is(""));

    assertThat(config.getBoolean("type.booleanFalse"), is(false));
    assertThat(config.getBoolean("type.booleanTrue"), is(true));

    list = config.getList("type.listOfIntegers");
    for (Object o : list) {
        assertThat(o, instanceOf(Integer.class));
    }
    assertThat(list.size(), is(5));
    assertThat(list.get(0), is(1));
    assertThat(list.get(4), is(-1));

    assertThat(config.getLong("type.long"), is(1000000000000L));

    // Tree model
    assertThat(config.getString("tree.branchL1a.branchL2a.branchL3a"), is("leaf_a"));
    assertThat(config.getString("tree.branchL1a.branchL2b.branchL3h"), is("leaf_h"));
    // Trim, because this value is defined as a multi-line value.
    assertThat(config.getString("tree.branchL1a.branchL2b.branchL3i").trim(), is("leaf_i"));
}

From source file:org.pivot4j.impl.PivotModelImpl.java

/**
 * @see org.pivot4j.state.Configurable#restoreSettings(org.apache.commons.configuration.HierarchicalConfiguration)
 *///from  www . jav  a  2 s  .c o m
@Override
public synchronized void restoreSettings(HierarchicalConfiguration configuration) {
    if (configuration == null) {
        throw new NullArgumentException("configuration");
    }

    this.defaultNonEmpty = configuration.getBoolean("nonEmpty[@default]", false);

    String mdx = configuration.getString("mdx");

    setMdx(mdx);

    if (mdx == null) {
        return;
    }

    if (!isInitialized()) {
        initialize();
    }

    this.sorting = configuration.getBoolean("sort[@enabled]", false);

    this.sortPosMembers = null;
    this.sortCriteria = SortCriteria.ASC;
    this.topBottomCount = 10;

    Quax quaxToSort = null;

    if (sorting) {
        List<Object> sortPosUniqueNames = configuration.getList("sort.member");
        if (sortPosUniqueNames != null && !sortPosUniqueNames.isEmpty()) {
            try {
                Cube cube = getCube();

                this.sortPosMembers = new ArrayList<Member>(sortPosUniqueNames.size());

                for (Object uniqueName : sortPosUniqueNames) {
                    Member member = cube.lookupMember(
                            IdentifierNode.parseIdentifier(uniqueName.toString()).getSegmentList());
                    if (member == null) {
                        if (logger.isWarnEnabled()) {
                            logger.warn("Sort position member not found " + uniqueName);
                        }

                        break;
                    }

                    sortPosMembers.add(member);
                }
            } catch (OlapException e) {
                throw new PivotException(e);
            }
        }

        this.topBottomCount = configuration.getInt("sort[@topBottomCount]", 10);

        String sortName = configuration.getString("sort[@criteria]");
        if (sortName != null) {
            this.sortCriteria = SortCriteria.valueOf(sortName);
        }

        int ordinal = configuration.getInt("sort[@ordinal]", -1);

        if (ordinal > 0) {
            for (Axis axis : queryAdapter.getAxes()) {
                Quax quax = queryAdapter.getQuax(axis);
                if (quax.getOrdinal() == ordinal) {
                    quaxToSort = quax;
                    break;
                }
            }
        }
    }

    queryAdapter.setQuaxToSort(quaxToSort);

    boolean axesSwapped = configuration.getBoolean("axesSwapped", false);

    queryAdapter.setAxesSwapped(axesSwapped);

    this.cellSet = null;
}

From source file:org.programmatori.domotica.own.emulator.ConfigBus.java

private void loadConfig20(XMLConfiguration config) {
    if (config.getInt("statusSave", 0) == 1) {
        config.setAutoSave(save);/* ww w  .jav a  2 s  .c o m*/
    }

    int pos = 0;
    List<?> areas = config.configurationsAt("area");
    for (Iterator<?> iter = areas.iterator(); iter.hasNext();) {
        HierarchicalConfiguration areaConf = (HierarchicalConfiguration) iter.next();
        String area = config.getString("area(" + pos + ")[@id]");

        int posC = 0;
        List<?> components = areaConf.getList("component");
        for (Iterator<?> iterC = components.iterator(); iterC.hasNext();) {
            String value = (String) iterC.next();

            String type = areaConf.getString("component(" + posC + ")[@type]");
            String lightPoint = areaConf.getString("component(" + posC + ")[@pl]");

            SCSComponent c = null;
            if (type.equals("light")) {
                c = Light.create(this, area, lightPoint, value);
            } else if (type.equals("blind")) {
                c = Blind.create(this, area, lightPoint, value);
            } else if (type.equals("power")) {
                c = PowerUnit.create(this, area, value);
            }
            add(c);
            if (c instanceof Thread) {
                Thread t = (Thread) c;
                t.start();
            }
            posC++;
        }

        //         int posC = 0;
        //         List<?> components = config.configurationsAt("component");
        //         for (Iterator<?> iterC = components.iterator(); iter.hasNext();) {
        //            HierarchicalConfiguration component = (HierarchicalConfiguration ) iter.next();
        //
        //            String type = areaConf.getString("component(" + posC + ")[@type]");
        //            String lightPoint = areaConf.getString("component(" + posC + ")[@pl]");
        //
        //            String value = component.getString("value");

        pos++;
    }
}

From source file:org.yamj.core.tools.CountryXmlTools.java

@PostConstruct
public void init() {
    String countryFileName = PropertyTools.getProperty("yamj3.country.fileName");
    if (StringUtils.isBlank(countryFileName)) {
        LOG.trace("No valid country file name configured");
        return;//from   ww  w  .  j a  v  a2  s.  c o m
    }
    if (!StringUtils.endsWithIgnoreCase(countryFileName, "xml")) {
        LOG.warn("Invalid country file name specified: {}", countryFileName);
        return;
    }

    File xmlFile;
    if (StringUtils.isBlank(FilenameUtils.getPrefix(countryFileName))) {
        // relative path given
        String path = System.getProperty("yamj3.home");
        if (StringUtils.isEmpty(path)) {
            path = ".";
        }
        xmlFile = new File(FilenameUtils.concat(path, countryFileName));
    } else {
        // absolute path given
        xmlFile = new File(countryFileName);
    }

    if (!xmlFile.exists() || !xmlFile.isFile()) {
        LOG.warn("Countries file does not exist: {}", xmlFile.getPath());
        return;
    }
    if (!xmlFile.canRead()) {
        LOG.warn("Countries file not readble: {}", xmlFile.getPath());
        return;
    }

    LOG.debug("Initialize countries from file: {}", xmlFile.getPath());

    try {
        XMLConfiguration c = new XMLConfiguration(xmlFile);

        List<HierarchicalConfiguration> countries = c.configurationsAt("country");
        for (HierarchicalConfiguration country : countries) {
            String masterCountry = country.getString("[@name]");
            List<Object> subCountries = country.getList("subcountry");
            for (Object subCountry : subCountries) {
                LOG.debug("New genre added to map: {} -> {}", subCountry, masterCountry);
                COUNTRIES_MAP.put(((String) subCountry).toLowerCase(), masterCountry);
            }
        }

        try {
            this.commonStorageService.updateCountriesXml(COUNTRIES_MAP);
        } catch (Exception ex) {
            LOG.warn("Failed update countries xml in database", ex);
        }
    } catch (Exception ex) {
        LOG.error("Failed parsing country input file: " + xmlFile.getPath(), ex);
    }
}