List of usage examples for org.apache.commons.configuration HierarchicalConfiguration getBoolean
public boolean getBoolean(String key, boolean defaultValue)
From source file:edu.isi.wings.portal.classes.domains.Domain.java
private void initializeDomain() { try {//from w w w . j a v a 2 s .c o m PropertyListConfiguration config = new PropertyListConfiguration(this.domainConfigFile); this.useSharedTripleStore = config.getBoolean("useSharedTripleStore", true); this.planEngine = config.getString("executions.engine.plan", "Local"); this.stepEngine = config.getString("executions.engine.step", "Local"); this.templateLibrary = new DomainLibrary(config.getString("workflows.library.url"), config.getString("workflows.library.map")); this.newTemplateDirectory = new UrlMapPrefix(config.getString("workflows.prefix.url"), config.getString("workflows.prefix.map")); this.executionLibrary = new DomainLibrary(config.getString("executions.library.url"), config.getString("executions.library.map")); this.newExecutionDirectory = new UrlMapPrefix(config.getString("executions.prefix.url"), config.getString("executions.prefix.map")); this.dataOntology = new DomainOntology(config.getString("data.ontology.url"), config.getString("data.ontology.map")); this.dataLibrary = new DomainLibrary(config.getString("data.library.url"), config.getString("data.library.map")); this.dataLibrary.setStorageDirectory(config.getString("data.library.storage")); this.componentLibraryNamespace = config.getString("components.namespace"); this.abstractComponentLibrary = new DomainLibrary(config.getString("components.abstract.url"), config.getString("components.abstract.map")); String concreteLibraryName = config.getString("components.concrete"); List<HierarchicalConfiguration> clibs = config.configurationsAt("components.libraries.library"); for (HierarchicalConfiguration clib : clibs) { String url = clib.getString("url"); String map = clib.getString("map"); String name = clib.getString("name"); String codedir = clib.getString("storage"); DomainLibrary concreteLib = new DomainLibrary(url, map, name, codedir); this.concreteComponentLibraries.add(concreteLib); if (name.equals(concreteLibraryName)) this.concreteComponentLibrary = concreteLib; } List<HierarchicalConfiguration> perms = config.configurationsAt("permissions.permission"); for (HierarchicalConfiguration perm : perms) { String userid = perm.getString("userid"); boolean canRead = perm.getBoolean("canRead", false); boolean canWrite = perm.getBoolean("canWrite", false); boolean canExecute = perm.getBoolean("canExecute", false); Permission permission = new Permission(userid, canRead, canWrite, canExecute); this.permissions.add(permission); } } catch (ConfigurationException e) { e.printStackTrace(); } }
From source file:com.vmware.qe.framework.datadriven.impl.DDHelper.java
private static final List<HierarchicalConfiguration> getData(String className, HierarchicalConfiguration context) throws DDException { log.info("Getting data for '{}'", className); // selecting supplier and getting data String supplierType = context.getString(TAG_SUPPLIER_TYPE, null); supplierType = supplierType == null//w w w .ja v a2 s . c om ? DDConfig.getSingleton().getData().getString(TAG_SUPPLIER_DEFAULT, null) : supplierType; DataSupplier supplier = null; if (supplierType != null) { if (ddCoreConfig.getDataSupplierMap().containsKey(supplierType)) { supplier = ddCoreConfig.getDataSupplierMap().get(supplierType); } else { throw new IllegalArgumentException("Given supplier with name = " + supplierType + " not found"); } } else { if (ddCoreConfig.getDataSupplierMap().containsKey(KEY_DEFAULT)) { supplier = ddCoreConfig.getDataSupplierMap().get(KEY_DEFAULT); } else { log.warn( "no supplier selected. could not find default supplier. Using the first avaliable supplier"); supplier = ddCoreConfig.getDataSuppliers().iterator().next(); } } log.info("Supplier used: {}", supplier.getClass().getName()); final HierarchicalConfiguration testData; testData = supplier.getData(className, context); if (testData == null) { log.warn("no test data found for the given test class = " + className); return null; } // selecting generator and generating dynamic data along with static data. List<HierarchicalConfiguration> datas = null; boolean dynamicGeneration = context.getBoolean(TAG_GENERATOR_DYNAMIC, false); dynamicGeneration = dynamicGeneration ? dynamicGeneration : DDConfig.getSingleton().getData().getBoolean(TAG_GENERATOR_DYNAMIC, false); if (dynamicGeneration) { log.info("Dynamic data generation selected!"); String generatorType = context.getString(TAG_GENERATOR_TYPE, null); generatorType = generatorType == null ? DDConfig.getSingleton().getData().getString(TAG_GENERATOR_DEFAULT, null) : generatorType; DataGenerator dataGenerator = null; if (generatorType != null) { if (ddCoreConfig.getDataGeneratorMap().containsKey(generatorType)) { dataGenerator = ddCoreConfig.getDataGeneratorMap().get(generatorType); } else { throw new IllegalArgumentException( "Given generator with name = " + generatorType + " not found"); } } else { if (ddCoreConfig.getDataGeneratorMap().containsKey(KEY_DEFAULT)) { dataGenerator = ddCoreConfig.getDataGeneratorMap().get(KEY_DEFAULT); } else { log.warn("Could not find default generator, using the first avaliable generator"); dataGenerator = ddCoreConfig.getDataGenerators().iterator().next(); } } log.info("Generator Used: {}", dataGenerator.getClass().getName()); datas = dataGenerator.generate(testData, context); List<HierarchicalConfiguration> staticData = testData.configurationsAt(TAG_DATA); for (HierarchicalConfiguration aStaticData : staticData) { if (!aStaticData.getBoolean(TAG_AUTOGEN_ATTR, false)) { datas.add(aStaticData); } } } else { log.info("No Dynamic data generation."); datas = testData.configurationsAt(TAG_DATA); } log.info("Applying filters..."); List<HierarchicalConfiguration> filteredData = new ArrayList<>(); for (int i = 0; i < datas.size(); i++) {// for each data we create // new test instance. HierarchicalConfiguration aTestData = datas.get(i); boolean canRun = true; for (DataFilter filter : ddCoreConfig.getDataFilters()) { if (!filter.canRun(className, aTestData, context)) { canRun = false; break; } } if (canRun) { filteredData.add(aTestData); } } return filteredData; }
From source file:com.eyeq.pivot4j.ui.AbstractPivotRenderer.java
/** * @see com.eyeq.pivot4j.state.Configurable#restoreSettings(org.apache.commons.configuration.HierarchicalConfiguration) *///from www. j a va2 s .c o m @Override public void restoreSettings(HierarchicalConfiguration configuration) { if (configuration == null) { throw new NullArgumentException("configuration"); } this.showDimensionTitle = configuration.getBoolean("showDimensionTitle", true); this.showParentMembers = configuration.getBoolean("showParentMembers", false); this.hideSpans = configuration.getBoolean("hideSpans", false); List<HierarchicalConfiguration> aggregationSettings = configuration .configurationsAt("aggregations.aggregation"); this.aggregatorNames.clear(); for (HierarchicalConfiguration aggConfig : aggregationSettings) { String name = aggConfig.getString("[@name]"); if (name != null) { Axis axis = Axis.Standard.valueOf(aggConfig.getString("[@axis]")); AggregatorPosition position = AggregatorPosition.valueOf(aggConfig.getString("[@position]")); AggregatorKey key = new AggregatorKey(axis, position); List<String> names = aggregatorNames.get(key); if (names == null) { names = new LinkedList<String>(); aggregatorNames.put(key, names); } if (!names.contains(name)) { names.add(name); } } } initializeProperties(); if (cellProperties != null) { try { cellProperties.restoreSettings(configuration.configurationAt("properties.cell")); } catch (IllegalArgumentException e) { } } if (headerProperties != null) { try { headerProperties.restoreSettings(configuration.configurationAt("properties.header")); } catch (IllegalArgumentException e) { } } }
From source file:at.ac.tuwien.auto.iotsys.gateway.connectors.knx.KNXDeviceLoaderImpl.java
public ArrayList<Connector> initDevices(ObjectBroker objectBroker) { setConfiguration(devicesConfig);//from w w w.j a va2 s. co m 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:com.gs.obevo.db.api.factory.DbEnvironmentXmlEnricher.java
@Override public DeploySystem<DbEnvironment> readSystem(FileObject sourcePath) { HierarchicalConfiguration sysCfg = getConfig(sourcePath); DbPlatform systemDbPlatform = dbPlatformConfiguration.valueOf(sysCfg.getString("[@type]")); MutableList<String> sourceDirs = ListAdapter.adapt(sysCfg.getList("[@sourceDirs]")); ImmutableSet<String> acceptedExtensions = ListAdapter.adapt(sysCfg.getList("[@acceptedExtensions]")).toSet() .toImmutable();/*w ww . j a v a 2 s. c o m*/ MutableList<DbEnvironment> envList = Lists.mutable.empty(); for (HierarchicalConfiguration envCfg : iterConfig(sysCfg, "environments.dbEnvironment")) { DbEnvironment dbEnv = new DbEnvironment(); FileObject rootDir = sourcePath.getType() == FileType.FILE ? sourcePath.getParent() : sourcePath; // Use coreSourcePath and additionalSourceDirs here (instead of setSourceDirs) to facilitate any external integrations dbEnv.setCoreSourcePath(rootDir); dbEnv.setAdditionalSourceDirs(sourceDirs); dbEnv.setAcceptedExtensions(acceptedExtensions); dbEnv.setCleanBuildAllowed(envCfg.getBoolean("[@cleanBuildAllowed]", false)); dbEnv.setDbHost(envCfg.getString("[@dbHost]")); dbEnv.setDbPort(envCfg.getInt("[@dbPort]", 0)); dbEnv.setDbServer(envCfg.getString("[@dbServer]")); dbEnv.setDbSchemaPrefix(envCfg.getString("[@dbSchemaPrefix]")); dbEnv.setDbSchemaSuffix(envCfg.getString("[@dbSchemaSuffix]")); dbEnv.setDbDataSourceName(envCfg.getString("[@dbDataSourceName]")); dbEnv.setJdbcUrl(envCfg.getString("[@jdbcUrl]")); MutableMap<String, String> tokens = Maps.mutable.empty(); for (HierarchicalConfiguration tok : iterConfig(envCfg, "tokens.token")) { tokens.put(tok.getString("[@key]"), tok.getString("[@value]")); } dbEnv.setTokens(tokens.toImmutable()); // Allow the groups + users to be tokenized upfront for compatibility w/ the EnvironmentInfraSetup classes Tokenizer tokenizer = new Tokenizer(dbEnv.getTokens(), dbEnv.getTokenPrefix(), dbEnv.getTokenSuffix()); dbEnv.setGroups(iterConfig(sysCfg, "groups.group").collect(convertCfgToGroup(tokenizer))); dbEnv.setUsers(iterConfig(sysCfg, "users.user").collect(convertCfgToUser(tokenizer))); if (envCfg.getString("[@driverClass]") != null) { dbEnv.setDriverClassName(envCfg.getString("[@driverClass]")); } dbEnv.setName(envCfg.getString("[@name]")); dbEnv.setDefaultUserId(envCfg.getString("[@defaultUserId]")); dbEnv.setDefaultPassword(envCfg.getString("[@defaultPassword]")); dbEnv.setDefaultTablespace(envCfg.getString("[@defaultTablespace]")); // TODO add include/exclude schemas functionality MutableList<Schema> schemaObjs = Lists.mutable.withAll(iterConfig(sysCfg, "schemas.schema")) .collect(convertCfgToSchema(systemDbPlatform)); MutableSet<String> schemasToInclude = iterString(envCfg, "includeSchemas").toSet(); MutableSet<String> schemasToExclude = iterString(envCfg, "excludeSchemas").toSet(); if (!schemasToInclude.isEmpty() && !schemasToExclude.isEmpty()) { throw new IllegalArgumentException("Environment " + dbEnv.getName() + " has includeSchemas [" + schemasToInclude + "] and excludeSchemas [" + schemasToExclude + "] defined; please only specify one of them"); } else if (!schemasToInclude.isEmpty()) { schemaObjs = schemaObjs.select(Predicates.attributeIn(Schema.TO_NAME, schemasToInclude)); } else if (!schemasToExclude.isEmpty()) { schemaObjs = schemaObjs.reject(Predicates.attributeIn(Schema.TO_NAME, schemasToExclude)); } MutableMap<String, String> schemaNameOverrides = Maps.mutable.empty(); MutableSet<String> schemaNames = schemaObjs.collect(Schema.TO_NAME).toSet(); for (HierarchicalConfiguration schemaOverride : iterConfig(envCfg, "schemaOverrides.schemaOverride")) { String schema = schemaOverride.getString("[@schema]"); if (schemaObjs.collect(Schema.TO_NAME).contains(schema)) { schemaNameOverrides.put(schema, schemaOverride.getString("[@overrideValue]")); } else { throw new IllegalArgumentException( "Schema override definition value " + schema + " is not defined in the schema list " + schemaNames + " for environment " + dbEnv.getName()); } } dbEnv.setSchemaNameOverrides(schemaNameOverrides.toImmutable()); // ensure that we only store the unique schema names here dbEnv.setSchemas(UnifiedSetWithHashingStrategy .newSet(HashingStrategies.fromFunction(Schema.TO_NAME), schemaObjs).toImmutable()); dbEnv.setPersistToFile(envCfg.getBoolean("[@persistToFile]", false)); dbEnv.setDisableAuditTracking(envCfg.getBoolean("[@disableAuditTracking]", false)); dbEnv.setRollbackDetectionEnabled(envCfg.getBoolean("[@rollbackDetectionEnabled]", sysCfg.getBoolean("[@rollbackDetectionEnabled]", true))); dbEnv.setAutoReorgEnabled( envCfg.getBoolean("[@autoReorgEnabled]", sysCfg.getBoolean("[@autoReorgEnabled]", true))); dbEnv.setInvalidObjectCheckEnabled(envCfg.getBoolean("[@invalidObjectCheckEnabled]", sysCfg.getBoolean("[@invalidObjectCheckEnabled]", true))); dbEnv.setReorgCheckEnabled( envCfg.getBoolean("[@reorgCheckEnabled]", sysCfg.getBoolean("[@reorgCheckEnabled]", true))); dbEnv.setChecksumDetectionEnabled(envCfg.getBoolean("[@checksumDetectionEnabled]", sysCfg.getBoolean("[@checksumDetectionEnabled]", false))); dbEnv.setMetadataLineReaderVersion( envCfg.getInt("[@metadataLineReaderVersion]", sysCfg.getInt("[@metadataLineReaderVersion]", dbPlatformConfiguration.getFeatureToggleVersion("metadataLineReaderVersion")))); dbEnv.setCsvVersion(envCfg.getInt("[@csvVersion]", sysCfg.getInt("[@csvVersion]", dbPlatformConfiguration.getFeatureToggleVersion("csvVersion")))); int legacyDirectoryStructureEnabledValue = envCfg.getInt("[@legacyDirectoryStructureEnabled]", sysCfg.getInt("[@legacyDirectoryStructureEnabled]", dbPlatformConfiguration.getFeatureToggleVersion("legacyDirectoryStructureEnabled"))); dbEnv.setLegacyDirectoryStructureEnabled(legacyDirectoryStructureEnabledValue == 1); // 1 == legacy, 2 == new MutableMap<String, String> extraEnvAttrs = Maps.mutable.empty(); for (String extraEnvAttr : dbPlatformConfiguration.getExtraEnvAttrs()) { String attrStr = "[@" + extraEnvAttr + "]"; extraEnvAttrs.put(extraEnvAttr, envCfg.getString(attrStr, sysCfg.getString(attrStr))); } dbEnv.setExtraEnvAttrs(extraEnvAttrs.toImmutable()); ImmutableList<HierarchicalConfiguration> envPermissions = iterConfig(envCfg, "permissions.permission"); ImmutableList<HierarchicalConfiguration> sysPermissions = iterConfig(sysCfg, "permissions.permission"); if (!envPermissions.isEmpty()) { dbEnv.setPermissions(envPermissions.collect(convertCfgToPermission(tokenizer))); } else if (!sysPermissions.isEmpty()) { dbEnv.setPermissions(sysPermissions.collect(convertCfgToPermission(tokenizer))); } DbPlatform platform; if (envCfg.getString("[@inMemoryDbType]") != null) { platform = dbPlatformConfiguration.valueOf(envCfg.getString("[@inMemoryDbType]")); } else { platform = systemDbPlatform; } dbEnv.setSystemDbPlatform(systemDbPlatform); dbEnv.setPlatform(platform); String delim = sysCfg.getString("[@dataDelimiter]"); if (delim != null) { if (delim.length() == 1) { dbEnv.setDataDelimiter(delim.charAt(0)); } else { throw new IllegalArgumentException( "dataDelimiter must be 1 character long. instead, got [" + delim + "]"); } } String nullToken = sysCfg.getString("[@nullToken]"); if (nullToken != null) { dbEnv.setNullToken(nullToken); } dbEnv.setAuditTableSql(getProperty(sysCfg, envCfg, "auditTableSql")); envList.add(dbEnv); } CollectionUtil.verifyNoDuplicates(envList, DbEnvironment.TO_NAME, "Invalid configuration from " + sourcePath + "; not expecting duplicate env names"); return new DeploySystem<DbEnvironment>(envList); }
From source file:com.intuit.tank.vm.settings.VmManagerConfig.java
/** * /*from w ww . ja v a2 s.c o m*/ * @param config */ @SuppressWarnings("unchecked") public VmManagerConfig(@Nonnull HierarchicalConfiguration config) { this.config = config; if (this.config != null) { List<HierarchicalConfiguration> creds = config.configurationsAt("credentials"); if (creds != null) { for (HierarchicalConfiguration credentialsConfig : creds) { CloudCredentials cloudCredentials = new CloudCredentials(credentialsConfig); credentialsMap.put(cloudCredentials.getType(), cloudCredentials); } } List<HierarchicalConfiguration> tags = config.configurationsAt("tags/tag"); if (tags != null) { for (HierarchicalConfiguration tagsConfig : tags) { InstanceTag tag = new InstanceTag(tagsConfig.getString("@name"), tagsConfig.getString("")); if (tag.isValid()) { tagList.add(tag); } } } HierarchicalConfiguration defaultInstance = config.configurationAt("default-instance-description"); List<HierarchicalConfiguration> regionConfigs = config.configurationsAt("instance-descriptions"); if (regionConfigs != null) { for (HierarchicalConfiguration regionConfig : regionConfigs) { VMRegion region = VMRegion.valueOf(regionConfig.getString("@region")); Map<VMImageType, InstanceDescription> instanceMap = new HashMap<VMImageType, InstanceDescription>(); regionMap.put(region, instanceMap); List<HierarchicalConfiguration> instanceConfigs = regionConfig .configurationsAt("instance-descripion"); for (HierarchicalConfiguration instanceConfig : instanceConfigs) { InstanceDescription description = new InstanceDescription(instanceConfig, defaultInstance); instanceMap.put(description.getType(), description); } } } // get reserved elastic ips List<HierarchicalConfiguration> eipConfig = config.configurationsAt("reserved-elastic-ips/eip"); if (eipConfig != null) { for (HierarchicalConfiguration eip : eipConfig) { reservedElasticIps.add(eip.getString("")); } } // get instance type definitions List<HierarchicalConfiguration> instanceTypesConfig = config.configurationsAt("instance-types/type"); instanceTypes = new ArrayList<VmInstanceType>(); if (instanceTypesConfig != null) { for (HierarchicalConfiguration instanceTypeConfig : instanceTypesConfig) { // example: <type name="c3.large" cost=".105" users="500" cpus="2" ecus="7" mem="3.75" /> VmInstanceType type = VmInstanceType.builder().withName(instanceTypeConfig.getString("@name")) .withCost(instanceTypeConfig.getDouble("@cost", 0D)) .withMemory(instanceTypeConfig.getDouble("@mem", 0D)) .withJvmArgs(instanceTypeConfig.getString("@jvmArgs")) .withEcus(instanceTypeConfig.getInt("@ecus", 0)) .withCpus(instanceTypeConfig.getInt("@cpus", 0)) .withDefault(instanceTypeConfig.getBoolean("@default", false)) .withUsers(instanceTypeConfig.getInt("@users", 0)).build(); instanceTypes.add(type); } } } }
From source file:at.ac.tuwien.auto.iotsys.gateway.connectors.bacnet.BacnetDeviceLoaderImpl.java
public ArrayList<Connector> initDevices(ObjectBroker objectBroker) { setConfiguration(devicesConfig);/*w w w . j a v a 2 s . com*/ 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:at.ac.tuwien.auto.iotsys.gateway.connectors.knx.KNXDeviceLoaderETSImpl.java
public ArrayList<Connector> initDevices(ObjectBroker objectBroker) { log.info("KNX ETS device loader starting. - connectorsConfig: " + connectorsConfig); setConfiguration(connectorsConfig);/*from w ww. j av a2 s . co m*/ ArrayList<Connector> connectors = new ArrayList<Connector>(); log.info("connectors config now: " + connectorsConfig); Object knxConnectors = connectorsConfig.getProperty("knx-ets.connector.name"); int connectorsSize = 0; if (knxConnectors != null) { connectorsSize = 1; } if (knxConnectors instanceof Collection<?>) { connectorsSize = ((Collection<?>) knxConnectors).size(); } // Networks List networks = new List(); networks.setName("networks"); networks.setOf(new Contract(Network.CONTRACT)); networks.setHref(new Uri("/networks")); boolean networkEnabled = false; for (int connector = 0; connector < connectorsSize; connector++) { HierarchicalConfiguration subConfig = connectorsConfig .configurationAt("knx-ets.connector(" + connector + ")"); // 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); Boolean forceRefresh = subConfig.getBoolean("forceRefresh", false); String knxProj = subConfig.getString("knx-proj"); Boolean enableGroupComm = subConfig.getBoolean("groupCommEnabled", false); Boolean enableHistories = subConfig.getBoolean("historyEnabled", false); if (enabled) { if (!networkEnabled) { objectBroker.addObj(networks, true); networkEnabled = true; } File file = new File(knxProj); if (!file.exists() || file.isDirectory() || !file.getName().endsWith(".knxproj") || file.getName().length() < 8) { log.warning("KNX project file " + knxProj + " is not a valid KNX project file."); continue; } String projDirName = knxProj.substring(0, knxProj.length() - 8); File projDir = new File(projDirName); if (!projDir.exists() || forceRefresh) { log.info("Expanding " + knxProj + " into directory " + projDirName); unZip(knxProj, projDirName); } String directory = "./" + knxProj.substring(knxProj.indexOf("/") + 1).replaceFirst(".knxproj", ""); // now the unpacked ETS project should be available in the directory String transformFileName = knxProj.replaceFirst(".knxproj", "") + "/" + file.getName().replaceFirst(".knxproj", "") + ".xml"; File transformFile = new File(transformFileName); if (!transformFile.exists() || forceRefresh) { log.info("Transforming ETS configuration."); // System.setProperty("javax.xml.transform.TransformerFactory", "net.sf.saxon.TransformerFactoryImpl"); // Create a transform factory instance. TransformerFactory tfactory = TransformerFactory.newInstance(); // Create a transformer for the stylesheet. Transformer transformer; try { transformer = tfactory.newTransformer(new StreamSource("knx-config/stylesheet_knx.xsl")); Collection<File> listFiles = FileUtils.listFiles(projDir, FileFilterUtils.nameFileFilter("0.xml"), new IOFileFilter() { @Override public boolean accept(File file) { return true; } @Override public boolean accept(File dir, String name) { return true; } }); if (listFiles.size() != 1) { log.severe("Found no or more than one 0.xml file in " + projDirName); continue; } log.info("Transforming with directory parameter set to " + directory); transformer.setParameter("directory", directory); transformer.transform(new StreamSource(listFiles.iterator().next().getAbsoluteFile()), new StreamResult(transformFileName)); log.info("Transformation completed and result written to: " + transformFileName); } catch (TransformerConfigurationException e) { e.printStackTrace(); } catch (TransformerException e) { e.printStackTrace(); } } try { devicesConfig = new XMLConfiguration(transformFileName); } catch (Exception e) { log.log(Level.SEVERE, e.getMessage(), e); } KNXConnector knxConnector = new KNXConnector(routerIP, routerPort, localIP); connect(knxConnector); initNetworks(knxConnector, objectBroker, networks, enableGroupComm, enableHistories); connectors.add(knxConnector); } } return connectors; }
From source file:net.datenwerke.sandbox.util.SandboxParser.java
protected SandboxContext loadSandbox(String name, HierarchicalConfiguration conf, HierarchicalConfiguration contextConf, HashSet<String> basedOnProcessed) { SandboxContext context = new SandboxContext(); String basedOn = contextConf.getString("[@basedOn]"); if (null != basedOn) { if (basedOnProcessed.contains(basedOn)) throw new IllegalStateException( "Loop detected: there seems to be a loop in the sandbox configuration at" + basedOn + " and " + name); basedOnProcessed.add(basedOn);/*w ww. ja v a 2 s .c om*/ HierarchicalConfiguration baseConf = null; for (HierarchicalConfiguration c : conf.configurationsAt("security.sandbox")) { if (name.equals(contextConf.getString("[@name]"))) { baseConf = c; break; } } if (null == baseConf) throw new IllegalStateException("Could not find config for " + basedOn); SandboxContext basis = loadSandbox(name, conf, baseConf, basedOnProcessed); context = basis.clone(); } Boolean allAccess = contextConf.getBoolean("[@allowAll]", false); if (allAccess) context.setPassAll(allAccess); boolean bypassClassAccesss = contextConf.getBoolean("[@bypassClassAccess]", false); context.setBypassClassAccessChecks(bypassClassAccesss); boolean bypassPackageAccesss = contextConf.getBoolean("[@bypassPackageAccess]", false); context.setBypassPackageAccessChecks(bypassPackageAccesss); Boolean debug = contextConf.getBoolean("[@debug]", false); if (debug) context.setDebug(debug); String codesource = contextConf.getString("[@codesource]", null); if (null != codesource && !"".equals(codesource.trim())) context.setCodesource(codesource); /* run in */ Boolean runInThread = contextConf.getBoolean("[@runInThread]", false); if (runInThread) context.setRunInThread(runInThread); Boolean runRemote = contextConf.getBoolean("[@runRemote]", false); if (runRemote) context.setRunRemote(runRemote); /* finalizers */ Boolean removeFinalizers = contextConf.getBoolean("[@removeFinalizers]", false); if (removeFinalizers) context.setRemoveFinalizers(removeFinalizers); /* thread */ configureThreadRestrictions(context, contextConf); /* packages */ configurePackages(context, contextConf); /* class access */ try { configureClasses(context, contextConf); /* application loader */ configureClassesForApplicationLoader(context, contextConf); } catch (MalformedURLException e) { throw new IllegalArgumentException("Could not generate URL", e); } /* permissions */ configurePermissions(context, contextConf); /* file access */ configureFileAccess(context, contextConf); return context; }
From source file:com.eyeq.pivot4j.impl.PivotModelImpl.java
/** * @see com.eyeq.pivot4j.state.Configurable#restoreSettings(org.apache.commons.configuration.HierarchicalConfiguration) *//*from www . ja v a2 s. co m*/ @Override public synchronized void restoreSettings(HierarchicalConfiguration configuration) { if (configuration == null) { throw new NullArgumentException("configuration"); } String mdx = configuration.getString("mdx"); setMdx(mdx); if (mdx == null) { if (logger.isWarnEnabled()) { logger.warn("The configuration does not contain valid MDX query."); } 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); this.cellSet = null; }