org.apache.commons.configuration.HierarchicalConfiguration Java Examples

The following examples show how to use org.apache.commons.configuration.HierarchicalConfiguration. You can vote up the ones you like or vote down the ones you don't like, and go to the original project or source file by following the links above each example. You may check out the related API usage on the sidebar.
Example #1
Source File: XmlDriverLoader.java    From onos with Apache License 2.0 6 votes vote down vote up
/**
 * Loads a driver from the supplied hierarchical configuration.
 *
 * @param driverCfg hierarchical configuration containing the driver definition
 * @param resolver  driver resolver
 * @return driver
 */
public DefaultDriver loadDriver(HierarchicalConfiguration driverCfg,
                                DriverResolver resolver) {
    String name = driverCfg.getString(NAME);
    String parentsString = driverCfg.getString(EXTENDS, "");
    List<Driver> parents = Lists.newArrayList();
    if (!"".equals(parentsString)) {
        List<String> parentsNames;
        if (parentsString.contains(",")) {
            parentsNames = Arrays.asList(parentsString.replace(" ", "").split(","));
        } else {
            parentsNames = Lists.newArrayList(parentsString);
        }
        parents = parentsNames.stream().map(parent -> (parent != null) ?
                resolve(parent, resolver) : null).collect(Collectors.toList());
    }
    String manufacturer = driverCfg.getString(MFG, getParentAttribute(parents, MFG));
    String hwVersion = driverCfg.getString(HW, getParentAttribute(parents, HW));
    String swVersion = driverCfg.getString(SW, getParentAttribute(parents, SW));
    return new DefaultDriver(name, parents, manufacturer, hwVersion, swVersion,
                             parseBehaviours(driverCfg),
                             parseProperties(driverCfg));
}
 
Example #2
Source File: EncoderConfig.java    From zap-extensions with Apache License 2.0 6 votes vote down vote up
private static List<TabModel> loadConfig(ZapXmlConfiguration config) {
    List<TabModel> tabs = new ArrayList<>();
    List<HierarchicalConfiguration> tabConfigs = config.configurationsAt(TAB_PATH);
    for (HierarchicalConfiguration tabConfig : tabConfigs) {
        String tabName = tabConfig.getString(TAB_NAME_KEY);
        TabModel tab = new TabModel();
        tab.setName(tabName);

        List<OutputPanelModel> panels = new ArrayList<>();
        List<HierarchicalConfiguration> panelConfigs =
                tabConfig.configurationsAt(OUTPUT_PANEL_PATH);
        for (HierarchicalConfiguration panelConfig : panelConfigs) {
            String panelName = panelConfig.getString(OUTPUT_PANEL_NAME_KEY);
            String script = panelConfig.getString(OUTPUT_PANEL_SCRIPT_KEY);
            OutputPanelModel panel = new OutputPanelModel();
            panel.setName(panelName);
            panel.setProcessorId(script);
            panels.add(panel);
        }

        tab.setOutputPanels(panels);
        tabs.add(tab);
    }
    return tabs;
}
 
Example #3
Source File: ScriptSettings.java    From sailfish-core with Apache License 2.0 6 votes vote down vote up
@Override
public void load(HierarchicalConfiguration config) 
{
	HierarchicalConfiguration testScriptConfig = config.configurationAt(TESTSCRIPT_KEY);
	
	String scriptNamePar = config.getString("TestScript[@name]");

       if(scriptNamePar == null) {
           throw new ScriptRunException("There is no \"name\" attribute at \"TestScript\" element in the script configuration file");
       }
	
	this.scriptName = scriptNamePar;

       if(!testScriptConfig.configurationsAt(PROPERTIES_KEY).isEmpty()) {
           loadProperties(testScriptConfig.configurationAt(PROPERTIES_KEY));
       }

       if(!testScriptConfig.configurationsAt(LOGGING_KEY).isEmpty()) {
           loadLoggingProperties(testScriptConfig.configurationAt(LOGGING_KEY));
       }

       if(!testScriptConfig.configurationsAt(TESTREPORT_KEY).isEmpty()) {
           loadTestReportProperties(testScriptConfig.configurationAt(TESTREPORT_KEY));
       }
}
 
Example #4
Source File: EnvironmentSettings.java    From sailfish-core with Apache License 2.0 6 votes vote down vote up
private static Set<String> parseSet(HierarchicalConfiguration config, String propertyName, String regex, Set<String> defaultValue) {
 List<?> value = config.getList(propertyName);
    if (CollectionUtils.isNotEmpty(value)) {
        Pattern pattern = Pattern.compile(regex);
        Set<String> incorrectNames = new HashSet<>();
        Set<String> result = ImmutableSet.copyOf(value.stream()
                .map(Object::toString)
                .map(String::trim)
                .filter(StringUtils::isNotEmpty)
                .filter(name -> {
                    if (pattern.matcher(name).matches()) {
                        return true;
                    } else {
                        incorrectNames.add(name);
                        return false;
                    }
                })
                .collect(Collectors.toSet()));
        if (!incorrectNames.isEmpty()) {
            logger.error("Property '{}' has incorrect values {}", propertyName, incorrectNames);

        }
        return result;
    }
    return defaultValue;
}
 
Example #5
Source File: JuniperUtilsTest.java    From onos with Apache License 2.0 6 votes vote down vote up
@Test
public void testDeviceDescriptionParsedFromJunos19() throws IOException {

    HierarchicalConfiguration getSystemInfoResp = XmlConfigParser.loadXml(
            getClass().getResourceAsStream("/Junos_get-system-information_response_19.2.xml"));
    String chassisText = CharStreams.toString(
            new InputStreamReader(
                    getClass().getResourceAsStream("/Junos_get-chassis-mac-addresses_response_19.2.xml")));

    DeviceDescription expected =
            new DefaultDeviceDescription(URI.create(DEVICE_ID), ROUTER, "JUNIPER", "acx6360-or",
                    "junos 19.2I-20190228_dev_common.0.2316", "DX004", new ChassisId("f4b52f1f81c0"));

    assertEquals(expected, JuniperUtils.parseJuniperDescription(deviceId, getSystemInfoResp, chassisText));

}
 
Example #6
Source File: ClientLineTerminalDeviceDiscovery.java    From onos with Apache License 2.0 6 votes vote down vote up
/**
 * Checks if a given component has a subcomponent of a given type.
 *
 * @param component subtree to parse looking for subcomponents.
 * @param components the full components tree, to cross-ref in
 *  case we need to check (sub)components' types.
 *
 * @return true or false
 */
private boolean hasSubComponentOfType(
        HierarchicalConfiguration component,
        HierarchicalConfiguration components,
        String type) {
    long count = component.configurationsAt("subcomponents/subcomponent")
        .stream()
        .filter(subcomponent -> {
                    String scName = subcomponent.getString("name");
                    StringBuilder sb = new StringBuilder("component[name='");
                    sb.append(scName);
                    sb.append("']/state/type");
                    String scType = components.getString(sb.toString(), "unknown");
                    return scType.equals(type);
                })
        .count();
    return (count > 0);
}
 
Example #7
Source File: AccumuloRexsterGraphConfiguration.java    From AccumuloGraph with Apache License 2.0 6 votes vote down vote up
@Override
public Graph configureGraphInstance(GraphConfigurationContext context) throws GraphConfigurationException {

  Configuration conf = context.getProperties();
  try {
    conf = ((HierarchicalConfiguration) conf).configurationAt(Tokens.REXSTER_GRAPH_PROPERTIES);
  } catch (IllegalArgumentException iae) {
    throw new GraphConfigurationException("Check graph configuration. Missing or empty configuration element: " + Tokens.REXSTER_GRAPH_PROPERTIES);
  }

  AccumuloGraphConfiguration cfg = new AccumuloGraphConfiguration(conf);
  if (cfg.getInstanceType().equals(InstanceType.Mock)) {
    cfg.setPassword("".getBytes());
    cfg.setUser("root");
  }
  cfg.setGraphName(context.getProperties().getString(Tokens.REXSTER_GRAPH_NAME));
  return GraphFactory.open(cfg.getConfiguration());
}
 
Example #8
Source File: NTGClientSettings.java    From sailfish-core with Apache License 2.0 6 votes vote down vote up
@Override
public void load( HierarchicalConfiguration config ) {
	this.connectTimeout = config.getInt("connectTimeout", 30000);
	this.loginTimeout = config.getInt("loginTimeout", 30000);
	this.logoutTimeout = config.getInt("logoutTimeout", 5000);
	this.heartbeatTimeout = config.getInt("heartbeatTimeout", 30000);
	this.maxMissedHeartbeats = config.getInt("maxMissedHeartbeats", 5);
	this.serverPort = config.getInt( "serverPort", 8181);
	this.serverIP= config.getString("serverIP", "127.0.0.1");
	this.reconnectAttempts = config.getInt("reconnectAttempts", 10);
	this.login = config.getString( "login", "user");
	this.password= config.getString("password", "password");
	this.newPassword = config.getString("newPassword", null);
	this.messageVersion = config.getByte("messageVersion", (byte)1 );
	//this.dictionaryPath = config.getString("dictionaryPath");
	this.lowlevelService = config.getBoolean("lowlevelService");
	this.autosendHeartbeat = config.getBoolean("autosendHeartBeat");

	try {
           this.dictionaryName = SailfishURI.parse(config.getString("dictionaryName"));
       } catch(SailfishURIException e) {
           throw new EPSCommonException(e);
       }
}
 
Example #9
Source File: GrooveOpenConfigDeviceDiscovery.java    From onos with Apache License 2.0 6 votes vote down vote up
/**
 * Returns a list of PortDescriptions for the device.
 *
 * @return a list of descriptions.
 *
 * The RPC reply follows the following pattern:
 * //CHECKSTYLE:OFF
 * <pre>{@code
 * <?xml version="1.0" encoding="UTF-8"?>
 * <rpc-reply xmlns="urn:ietf:params:xml:ns:netconf:base:1.0" message-id="7">
 * <data>
 *   <components xmlns="http://openconfig.net/yang/platform">
 *     <component>....
 *     </component>
 *     <component>....
 *     </component>
 *   </components>
 * </data>
 * </rpc-reply>
 * }</pre>
 * //CHECKSTYLE:ON
 */
@Override
public List<PortDescription> discoverPortDetails() {
    try {
        NetconfSession session = getNetconfSession(did());
        if (session == null) {
            log.error("discoverPortDetails called with null session for {}", did());
            return ImmutableList.of();
        }

        CompletableFuture<String> fut = session.rpc(getTerminalDeviceBuilder());
        String rpcReply = fut.get();

        XMLConfiguration xconf = (XMLConfiguration) XmlConfigParser.loadXmlString(rpcReply);
        xconf.setExpressionEngine(new XPathExpressionEngine());

        HierarchicalConfiguration logicalChannels = xconf.configurationAt("data/terminal-device/logical-channels");
        return parseLogicalChannels(logicalChannels);
    } catch (Exception e) {
        log.error("Exception discoverPortDetails() {}", did(), e);
        return ImmutableList.of();
    }
}
 
Example #10
Source File: JuniperUtils.java    From onos with Apache License 2.0 6 votes vote down vote up
/**
 * Parses device ports configuration and returns a list of
 * port description.
 *
 * @param cfg interface configuration
 * @return list of interface descriptions of the device
 */
public static List<PortDescription> parseJuniperPorts(HierarchicalConfiguration cfg) {
    //This methods ignores some internal ports

    List<PortDescription> portDescriptions = new ArrayList<>();
    List<HierarchicalConfiguration> subtrees =
            cfg.configurationsAt(IF_INFO);
    for (HierarchicalConfiguration interfInfo : subtrees) {
        List<HierarchicalConfiguration> interfaceTree =
                interfInfo.configurationsAt(IF_PHY);
        for (HierarchicalConfiguration phyIntf : interfaceTree) {
            if (phyIntf == null) {
                continue;
            }
            // parse physical Interface
            parsePhysicalInterface(portDescriptions, phyIntf);
        }
    }
    return portDescriptions;
}
 
Example #11
Source File: BeanConfigurator.java    From sailfish-core with Apache License 2.0 6 votes vote down vote up
public static void loadBean(HierarchicalConfiguration context, Object beanObject, ConvertUtilsBean converter)   
{
	PropertyUtilsBean beanUtils = new PropertyUtilsBean(); 
	
	PropertyDescriptor[] descriptors = beanUtils.getPropertyDescriptors(beanObject);

	try
	{
		for ( PropertyDescriptor descr : descriptors )
		{
			//check that setter exists
			if ( descr.getWriteMethod() != null )
			{
				String value = context.getString(descr.getName());

                   if(converter.lookup(descr.getPropertyType()) != null) {
                       BeanUtils.setProperty(beanObject, descr.getName(), converter.convert(value, descr.getPropertyType()));
                   }
			}
		}
	}
	catch ( Exception e )
	{
		throw new EPSCommonException(e);
	}
}
 
Example #12
Source File: CustomPayloadsParam.java    From zap-extensions with Apache License 2.0 6 votes vote down vote up
private void savePayloadsToConfig() {
    ((HierarchicalConfiguration) getConfig()).clearTree(ALL_CATEGORIES_KEY);
    int catIdx = 0;
    for (PayloadCategory category : payloadCategories.values()) {
        String catElementBaseKey = ALL_CATEGORIES_KEY + "(" + catIdx + ")";
        List<CustomPayload> payloads = category.getPayloads();
        getConfig().setProperty(catElementBaseKey + CATEGORY_NAME_KEY, category.getName());
        for (int i = 0, size = payloads.size(); i < size; ++i) {
            String elementBaseKey =
                    catElementBaseKey + ".payloads." + PAYLOAD_KEY + "(" + i + ").";
            CustomPayload payload = payloads.get(i);
            getConfig()
                    .setProperty(
                            elementBaseKey + PAYLOAD_ID_KEY, Integer.valueOf(payload.getId()));
            getConfig()
                    .setProperty(
                            elementBaseKey + PAYLOAD_ENABLED_KEY,
                            Boolean.valueOf(payload.isEnabled()));
            getConfig().setProperty(elementBaseKey + PAYLOAD_KEY, payload.getPayload());
        }
        catIdx++;
    }
}
 
Example #13
Source File: RORClient.java    From development with Apache License 2.0 6 votes vote down vote up
public List<String> listServerTypes() throws IaasException {
	HashMap<String, String> request = getBasicParameters();
	request.put(LParameter.ACTION, LOperation.LIST_SERVER_TYPE);
	XMLConfiguration response = execute(request);
	List<String> result = new LinkedList<String>();
	if (response != null) {
		List<HierarchicalConfiguration> types = response
				.configurationsAt("servertypes.servertype");
		for (HierarchicalConfiguration type : types) {
			String name = type.getString("name");
			if (name != null && name.trim().length() > 0) {
				result.add(name);
			}
		}
	}
	return result;
}
 
Example #14
Source File: CzechLightDiscovery.java    From onos with Apache License 2.0 6 votes vote down vote up
/** Run a <get> NETCONF command with an XPath filter.
 *
 * @param session well, a NETCONF session
 * @param prefix Name of a XML element prefix to use. Can be meaningless, such as "M"
 * @param namespace Full URI of the XML namespace to use. This is the real meat.
 * @param xpathFilter String with a relative XPath filter. This *MUST* start with "/" followed by 'prefix' and ":".
 * @return Result of the <get/> operation via NETCONF as a XmlHierarchicalConfiguration
 * @throws NetconfException exactly as session.doWrappedRpc() would do.
 * */
public static HierarchicalConfiguration doGetXPath(final NetconfSession session, final String prefix,
                                                   final String namespace, final String xpathFilter)
        throws NetconfException {
    final var reply = session.doWrappedRpc("<get xmlns=\"urn:ietf:params:xml:ns:netconf:base:1.0\">"
            + "<filter type=\"xpath\" xmlns:" + prefix + "=\"" + namespace + "\""
            + " select=\"" + xpathFilter.replace("\"", "&quot;") + "\"/>"
            + "</get>");
    log.debug("GET RPC w/XPath {}", reply);
    var data = XmlConfigParser.loadXmlString(reply);
    if (!data.containsKey("data[@xmlns]")) {
        log.error("NETCONF <get> w/XPath returned error: {}", reply);
        return null;
    }
    return data;
}
 
Example #15
Source File: PolatisPowerConfig.java    From onos with Apache License 2.0 6 votes vote down vote up
private Long acquirePortAttenuation(PortNumber port) {
    String filter = getPortAttenuationFilter(port);
    String reply = netconfGet(handler(), filter);
    HierarchicalConfiguration info = configAt(reply, KEY_DATA_VOA_PORT);
    if (info == null) {
        return null;
    }
    long attenuation = 0;
    try {
        attenuation = (long) (info.getDouble(KEY_ATTEN_LEVEL) * VOA_MULTIPLIER);
    } catch (NoSuchElementException e) {
        log.debug("Could not find atten-level for port {}", port);
    }

    return attenuation;
}
 
Example #16
Source File: RORClient.java    From development with Apache License 2.0 6 votes vote down vote up
/**
 * Retrieves a list of templates available for the tenant.
 * 
 * @return the list
 * @throws RORException
 */
public List<LPlatformDescriptor> listLPlatformDescriptors()
		throws IaasException {
	HashMap<String, String> request = getBasicParameters();
	request.put(LParameter.ACTION, LOperation.LIST_LPLATFORM_DESCR);
	XMLConfiguration result = execute(request);

	List<LPlatformDescriptor> resultList = new LinkedList<LPlatformDescriptor>();
	if (result != null) {
		List<HierarchicalConfiguration> descriptors = result
				.configurationsAt("lplatformdescriptors.lplatformdescriptor");
		for (HierarchicalConfiguration descriptor : descriptors) {
			resultList.add(new LPlatformDescriptor(descriptor));
		}
	}
	return resultList;
}
 
Example #17
Source File: RORClient.java    From development with Apache License 2.0 6 votes vote down vote up
/**
 * Retrieves a list of disk images available for the tenant.
 * 
 * @return the list
 * @throws RORException
 */
public List<DiskImage> listDiskImages() throws IaasException {
	HashMap<String, String> request = getBasicParameters();
	request.put(LParameter.ACTION, LOperation.LIST_DISKIMAGE);
	XMLConfiguration result = execute(request);

	List<DiskImage> resultList = new LinkedList<DiskImage>();
	if (result != null) {
		List<HierarchicalConfiguration> images = result
				.configurationsAt("diskimages.diskimage");
		for (HierarchicalConfiguration image : images) {
			resultList.add(new RORDiskImage(image));
		}
	}
	return resultList;
}
 
Example #18
Source File: CienaWaveserverDeviceDescription.java    From onos with Apache License 2.0 6 votes vote down vote up
public static PortDescription parseWaveServerCienaOchPorts(long portNumber,
                                                           HierarchicalConfiguration config,
                                                           SparseAnnotations annotations) {
    final List<String> tunableType = Lists.newArrayList("performance-optimized", "accelerated");
    final String flexGrid = "flex-grid";
    final String state = "properties.transmitter.state";
    final String tunable = "properties.modem.tx-tuning-mode";
    final String spacing = "properties.line-system.wavelength-spacing";
    final String frequency = "properties.transmitter.frequency.value";

    boolean isEnabled = config.getString(state).equals(ENABLED);
    boolean isTunable = tunableType.contains(config.getString(tunable));

    GridType gridType = config.getString(spacing).equals(flexGrid) ? GridType.FLEX : null;
    ChannelSpacing chSpacing = gridType == GridType.FLEX ? ChannelSpacing.CHL_6P25GHZ : null;

    //Working in Ghz //(Nominal central frequency - 193.1)/channelSpacing = spacingMultiplier
    final int baseFrequency = 193100;
    long spacingFrequency = chSpacing == null ? baseFrequency : chSpacing.frequency().asHz();
    int spacingMult = ((int) (toGbps(((int) config.getDouble(frequency) -
            baseFrequency)) / toGbpsFromHz(spacingFrequency))); //FIXME is there a better way ?

    return ochPortDescription(PortNumber.portNumber(portNumber), isEnabled, OduSignalType.ODU4, isTunable,
                              new OchSignal(gridType, chSpacing, spacingMult, 1), annotations);
}
 
Example #19
Source File: OpenRoadmFlowRuleProgrammable.java    From onos with Apache License 2.0 6 votes vote down vote up
/**
 * Get the flow entries that are present on the device, called by
 * FlowRuleDriverProvider. <p> The flow entries must match exactly the
 * FlowRule entries in the ONOS store. If they are not an exact match the
 * device will be requested to remove those flows.
 *
 * @return A collection of Flow Entries
 */
@Override
public Collection<FlowEntry> getFlowEntries() {
    List<HierarchicalConfiguration> conf = getDeviceConnections();
    List<FlowEntry> entries = new ArrayList<>();
    for (HierarchicalConfiguration c : conf) {
        openRoadmLog("Existing connection {}", c);
        FlowRule r = buildFlowrule(c);
        if (r != null) {
            FlowEntry e = new DefaultFlowEntry(r, FlowEntry.FlowEntryState.ADDED, 0, 0, 0);
            openRoadmLog("RULE RETRIEVED {}", r);
            entries.add(e);
        }
    }
    return entries;
}
 
Example #20
Source File: LPlatformConfiguration.java    From development with Apache License 2.0 5 votes vote down vote up
@Override
public List<String> getServerStatus() {
    List<String> result = new LinkedList<String>();
    if (configuration != null) {
        List<HierarchicalConfiguration> servers = configuration
                .configurationsAt("lservers.lserver");
        for (HierarchicalConfiguration server : servers) {
            String status = server.getString("lserverStatus");
            if (status != null && status.trim().length() > 0) {
                result.add(status);
            }
        }
    }
    return result;
}
 
Example #21
Source File: PolatisNetconfUtility.java    From onos with Apache License 2.0 5 votes vote down vote up
/**
 * Retrieves specified node hierarchical configuration from the xml information.
 *
 * @param content the xml information
 * @param key the configuration key node
 * @return the hierarchical configuration, null if exception happens
 */
public static HierarchicalConfiguration configAt(String content, String key) {
    HierarchicalConfiguration info;
    try {
        HierarchicalConfiguration cfg = XmlConfigParser.loadXmlString(content);
        info = cfg.configurationAt(key);
    } catch (IllegalArgumentException e) {
        // Accept null for information polling
        return null;
    }
    return info;
}
 
Example #22
Source File: PolatisPowerConfig.java    From onos with Apache License 2.0 5 votes vote down vote up
private List<PortNumber> acquirePorts() {
    String filter = getPortPowerFilter(null);
    String reply = netconfGet(handler(), filter);
    List<HierarchicalConfiguration> subtrees = configsAt(reply, KEY_DATA_OPM);
    List<PortNumber> ports = new ArrayList<PortNumber>();
    for (HierarchicalConfiguration portConfig : subtrees) {
        ports.add(PortNumber.portNumber(portConfig.getLong(KEY_PORTID)));
    }
    return ports;
}
 
Example #23
Source File: LPlatformConfigurationTest.java    From development with Apache License 2.0 5 votes vote down vote up
@Test
public void getVSystemName() {
    // given
    HierarchicalConfiguration configuration = prepareConfiguration(
            LPLATFORMNAME, LPLATFORMNAME);

    // when
    lPlatformConfiguration = new LPlatformConfiguration(configuration);
    String result = lPlatformConfiguration.getVSystemName();

    // then
    assertEquals(result, LPLATFORMNAME);
}
 
Example #24
Source File: LPlatformConfigurationTest.java    From development with Apache License 2.0 5 votes vote down vote up
@Test
public void getNetworkIds_NetworkIdIsNull() {
    // given
    HierarchicalConfiguration configuration = prepareConfiguration(
            NETWORKID, null);

    // when
    lPlatformConfiguration = new LPlatformConfiguration(configuration);
    List<Network> result = lPlatformConfiguration.getNetworks();

    // then
    assertEquals(0, result.size());
}
 
Example #25
Source File: StorageBalancer.java    From development with Apache License 2.0 5 votes vote down vote up
@Override
public void setConfiguration(HierarchicalConfiguration config) {
    if (config != null) {
        String storages = config.getString("[@storage]");
        if (storages == null || storages.trim().length() == 0) {
            throw new IllegalArgumentException(
                    "No storage reference defined for balancer");
        }
        String[] elms = storages.split(",");
        for (String x : elms) {
            datastoreNames.add(x.toString().trim());
        }
    }
}
 
Example #26
Source File: XMLScenarioFactory.java    From qaf with MIT License 5 votes vote down vote up
@Override
protected Collection<Object[]> parseFile(String xmlFile) {
	ArrayList<Object[]> statements = new ArrayList<Object[]>();
	try {
		HierarchicalConfiguration processor = new XMLConfiguration(xmlFile);
		List<?> definations = processor.getRoot().getChildren();
		for (Object definationObj : definations) {
			ConfigurationNode defination = (ConfigurationNode) definationObj;
			String type = defination.getName();
			String[] entry = new String[3];

			if (type.equalsIgnoreCase("SCENARIO") || type.equalsIgnoreCase("STEP-DEF")) {
				entry[0] = type;

				Map<?, ?> metaData = getMetaData(defination);
				entry[1] = (String) metaData.get("name");
				metaData.remove("name");
				entry[2] = gson.toJson(metaData);
				statements.add(entry);
				System.out.println("META-DATA:" + entry[2]);
				addSteps(defination, statements);
				statements.add(new String[] { "END", "", "" });
			}
		}
	} catch (ConfigurationException e) {
		e.printStackTrace();
	}

	return statements;
}
 
Example #27
Source File: ConfigurableIngestTopology.java    From cognition with Apache License 2.0 5 votes vote down vote up
/**
 * Gets a topology builder and set of storm bolt configurations. Initializes the bolts and sets them with the
 * topology builder.
 *
 * @param builder   storm topology builder
 * @param boltsConf component configurations
 * @param spout     type of storm component being added (spout/bolt)
 * @throws ConfigurationException
 */
void configureBolts(TopologyBuilder builder, SubnodeConfiguration boltsConf, String spout)
    throws ConfigurationException {

  String prevComponent = spout;
  // bolts subscribe to other bolts by number
  HashMap<Integer, String> boltNumberToId = new HashMap<>();

  List<HierarchicalConfiguration> bolts = boltsConf.configurationsAt(BOLT);
  for (HierarchicalConfiguration bolt : bolts) {
    String boltType = bolt.getString(TYPE);
    Configuration boltConf = bolt.configurationAt(CONF);
    int boltNum = bolt.getInt(NUMBER_ATTRIBUTE);

    String boltId = String.format("%02d_%s", boltNum, boltType);
    boltNumberToId.put(boltNum, boltId);
    String subscribingToComponent = getSubscribingToComponent(prevComponent, boltNumberToId, boltConf);
    logger.info("{} subscribing to {}", boltId, subscribingToComponent);

    IComponent baseComponent = buildComponent(boltType, boltConf);

    StormParallelismConfig stormParallelismConfig = getStormParallelismConfig(boltConf);
    BoltDeclarer declarer = buildBoltDeclarer(builder, stormParallelismConfig, boltId, baseComponent);

    configureTickFrequency(boltConf, declarer);

    configureStreamGrouping(subscribingToComponent, boltConf, declarer);

    prevComponent = boltId;

    boltNum++;
  }
}
 
Example #28
Source File: OpenRoadmDeviceDescription.java    From onos with Apache License 2.0 5 votes vote down vote up
/**
 * Get the circuit packs from the device as a list of XML hierarchical configs.
 *  @param session the NETConf session to the OpenROADM device.
 *  @return a list of hierarchical conf. each one circuit pack.
 */
List<HierarchicalConfiguration> getCircuitPacks(NetconfSession session) {
    try {
        String reply = session.rpc(getDeviceCircuitPacksBuilder()).get();
        XMLConfiguration cpConf = //
            (XMLConfiguration) XmlConfigParser.loadXmlString(reply);
        cpConf.setExpressionEngine(new XPathExpressionEngine());
        return cpConf.configurationsAt(
                "/data/org-openroadm-device/circuit-packs");
    } catch (NetconfException | InterruptedException | ExecutionException e) {
        log.error("[OPENROADM] {} exception getting circuit packs", did());
        return ImmutableList.of();
    }
}
 
Example #29
Source File: CassiniTerminalDevicePowerConfigExt.java    From onos with Apache License 2.0 5 votes vote down vote up
/**
 * mirror method in the internal class.
 * @param port port
 * @param component the component
 * @return current input power
 */
Optional<Double> currentInputPower(PortNumber port, Object component) {
    XMLConfiguration xconf = getOpticalChannelState(
            cassini, port, "<input-power><instant/></input-power>");
    try {
        HierarchicalConfiguration config =
                xconf.configurationAt("data/components/component/optical-channel/state/input-power");
        double currentPower = Float.valueOf(config.getString("instant")).doubleValue();
        return Optional.of(currentPower);
    } catch (IllegalArgumentException e) {
        return Optional.empty();
    }
}
 
Example #30
Source File: Config.java    From wings with Apache License 2.0 5 votes vote down vote up
@SuppressWarnings("rawtypes")
private ExeEngine getExeEngine(HierarchicalConfiguration node) {
    String name = node.getString("name");
    String impl = node.getString("implementation");
    ExeEngine.Type type = ExeEngine.Type.valueOf(node.getString("type"));
    ExeEngine engine = new ExeEngine(name, impl, type);
    for (Iterator it = node.getKeys("properties"); it.hasNext(); ) {
        String key = (String) it.next();
        String value = node.getString(key);
        engine.addProperty(key.replace("properties.", ""), value);
    }
    return engine;
}