Java Code Examples for org.apache.commons.configuration.XMLConfiguration#getString()

The following examples show how to use org.apache.commons.configuration.XMLConfiguration#getString() . 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: Driver2.java    From JavaDesignPattern with Apache License 2.0 6 votes vote down vote up
public static void main(String[] args) throws ConfigurationException {
	XMLConfiguration config = new XMLConfiguration("car.xml");
	String name = config.getString("driver2.name");
	Car car;

	switch (name) {
	case "Land Rover":
		car = new LandRoverCar();
		break;
	case "BMW":
		car = new BMWCar();
		break;
	case "Benz":
		car = new BenzCar();
		break;
	default:
		car = null;
		break;
	}
	LOG.info("Created car name is {}", name);
	car.drive();
}
 
Example 2
Source File: ProxySettingsImpl.java    From swift-explorer with Apache License 2.0 6 votes vote down vote up
public synchronized void setConfig (XMLConfiguration config) 
{
	this.config = config ;
	if (this.config == null)
	{
		logger.info("Proxy cannot be set because the config parameter is null");
		return ;
	}
	// TODO: when the commom-configuration 2.0 will be released
	// Lock config
	// ...
	port = this.config.getInt(baseProperty + ".port", defaultPort) ;
	isActive = config.getBoolean(baseProperty + ".active", false) ; 
	user = config.getString(baseProperty + ".user") ;
	password = config.getString(baseProperty + ".password") ;
	host = config.getString(baseProperty + ".host") ;
}
 
Example 3
Source File: IdentityApplicationManagementServiceClient.java    From attic-stratos with Apache License 2.0 6 votes vote down vote up
private String getIdToken(String compositeAppId, String consumerKey, String consumerSecret) throws OAuthSystemException, OAuthProblemException {
    XMLConfiguration conf = ConfUtil.getInstance(null).getConfiguration();
    String hostname = conf.getString("autoscaler.identity.hostname", "localhost");
    int port = conf.getInt("autoscaler.cloudController.port", AutoscalerConstants.IS_DEFAULT_PORT);
    String tokenEndpoint = "https://" + hostname + ":" + port + "/" + AutoscalerConstants.TOKEN_ENDPOINT_SFX;
    OAuthClientRequest accessRequest = OAuthClientRequest.tokenLocation(tokenEndpoint)
            .setGrantType(GrantType.CLIENT_CREDENTIALS)
            .setClientId(consumerKey)
            .setClientSecret(consumerSecret)
            .setScope(compositeAppId)
            .buildBodyMessage();
    OAuthClient oAuthClient = new OAuthClient(new URLConnectionClient());

    OAuthClientResponse oAuthResponse = oAuthClient.accessToken(accessRequest);
    return oAuthResponse.getParam(ID_TOKEN);
}
 
Example 4
Source File: InternalMetaAnalysisSettings.java    From systemsgenetics with GNU General Public License v3.0 6 votes vote down vote up
public void parse(String settings, String texttoreplace, String replacetextwith) {
    try {
        config = new XMLConfiguration(settings);

        nrPermutations = config.getInt("defaults.permutations", 0);
        startPermutations = config.getInt("defaults.startpermutation", 0);
        output = config.getString("defaults.output");
        probeToFeature = config.getString("defaults.probeToFeature");
        datasetname = config.getString("defaults.dataset.name");  // see if a dataset is defined
        datasetPrefix = config.getString("defaults.dataset.prefix");  // see if a dataset is defined
        zScoreMergeOption = config.getString("defaults.zScoreMerge").toLowerCase();
        if (datasetPrefix == null) {
            datasetPrefix = "Dataset";
        }
        String datasetloc = config.getString("defaults.dataset.location");  // see if a dataset is defined
        if (texttoreplace != null && replacetextwith != null && datasetloc.contains(texttoreplace)) {
            datasetloc = datasetloc.replace(texttoreplace, replacetextwith);
        }
        datasetlocation = datasetloc;
        
        // parse datasets
    } catch (ConfigurationException e) {
    
    }
}
 
Example 5
Source File: MonetaConfiguration.java    From moneta with Apache License 2.0 5 votes vote down vote up
protected void gatherKeyFields(XMLConfiguration config, Topic topic) {
	int nbrKeyFields = 0;
	Object temp = config.getList("Topics.Topic.PrimaryKey.Field[@name]");
	if (temp instanceof Collection) {
		nbrKeyFields = ((Collection)temp).size();
	}
	
	String name, typeStr;
	TopicKeyField.DataType dataType;
	TopicKeyField keyField;
	for (int i = 0; i < nbrKeyFields; i++) {
		name=config.getString("Topics.Topic.PrimaryKey.Field(" + i + ")[@name]");
		typeStr=config.getString("Topics.Topic.PrimaryKey.Field(" + i + ")[@type]");
		if (StringUtils.isEmpty(name) || StringUtils.isEmpty(typeStr)) {
			throw new MonetaException("Topic Primary Key Fields fields must have both name and type specified")
				.addContextValue("topic", topic.getTopicName())
				.addContextValue("name", name)
				.addContextValue("type", typeStr);
		}
		try {dataType = TopicKeyField.DataType.valueOf(typeStr.toUpperCase());}
		catch (Exception e) {
			throw new MonetaException("Datatype not supported", e)
				.addContextValue("topic", topic.getTopicName())
				.addContextValue("key field", name)
				.addContextValue("dataType", typeStr);
		}
		
		keyField = new TopicKeyField();
		topic.getKeyFieldList().add(keyField);
		keyField.setColumnName(name);
		keyField.setDataType(dataType);
	}
}
 
Example 6
Source File: IdentityApplicationManagementServiceClient.java    From attic-stratos with Apache License 2.0 5 votes vote down vote up
public static IdentityApplicationManagementServiceClient getServiceClient() throws AxisFault {
    if (serviceClient == null) {
        synchronized (IdentityApplicationManagementServiceClient.class) {
            if (serviceClient == null) {
                XMLConfiguration conf = ConfUtil.getInstance(null).getConfiguration();
                String hostname = conf.getString("autoscaler.identity.hostname", "localhost");
                int port = conf.getInt("autoscaler.cloudController.port", AutoscalerConstants.IS_DEFAULT_PORT);
                String epr = "https://" + hostname + ":" + port + "/" + AutoscalerConstants.IDENTITY_APPLICATION_SERVICE_SFX;
                serviceClient = new IdentityApplicationManagementServiceClient(epr);
            }
        }
    }
    return serviceClient;
}
 
Example 7
Source File: ZtePortStatisticsDiscovery.java    From onos with Apache License 2.0 5 votes vote down vote up
private int getInteger(XMLConfiguration cfg, String item) {
    String numString = cfg.getString("interfaces.interface.state.counters." + item);
    if (Strings.isNullOrEmpty(numString)) {
        LOG.debug("Cannot get port statistic data for {}, set 0 as default.", item);
        return 0;
    }

    try {
        return Integer.parseInt(numString);
    } catch (NumberFormatException e) {
        LOG.warn("Cannot convert data for {}", item);
        return 0;
    }
}
 
Example 8
Source File: OAuthAdminServiceClient.java    From attic-stratos with Apache License 2.0 5 votes vote down vote up
public static OAuthAdminServiceClient getServiceClient() throws AxisFault {
    if (serviceClient == null) {
        synchronized (OAuthAdminServiceClient.class) {
            if (serviceClient == null) {
                XMLConfiguration conf = ConfUtil.getInstance(null).getConfiguration();
                String hostname = conf.getString("autoscaler.identity.hostname", "localhost");
                int port = conf.getInt("autoscaler.cloudController.port", AutoscalerConstants.IS_DEFAULT_PORT);
                String epr = "https://" + hostname + ":" + port + "/" + AutoscalerConstants.OAUTH_SERVICE_SFX;
                serviceClient = new OAuthAdminServiceClient(epr);
            }
        }
    }
    return serviceClient;
}
 
Example 9
Source File: OAuthAdminServiceClient.java    From attic-stratos with Apache License 2.0 5 votes vote down vote up
public OAuthAdminServiceClient(String epr) throws AxisFault {

        XMLConfiguration conf = ConfUtil.getInstance(null).getConfiguration();
        int autosclaerSocketTimeout = conf.getInt("autoscaler.identity.clientTimeout", 180000);

        try {
            ServerConfiguration serverConfig = CarbonUtils.getServerConfiguration();
            String trustStorePath = serverConfig.getFirstProperty("Security.TrustStore.Location");
            String trustStorePassword = serverConfig.getFirstProperty("Security.TrustStore.Password");
            String type = serverConfig.getFirstProperty("Security.TrustStore.Type");
            System.setProperty("javax.net.ssl.trustStore", trustStorePath);
            System.setProperty("javax.net.ssl.trustStorePassword", trustStorePassword);
            System.setProperty("javax.net.ssl.trustStoreType", type);

            stub = new OAuthAdminServiceStub(epr);
            stub._getServiceClient().getOptions().setProperty(HTTPConstants.SO_TIMEOUT, autosclaerSocketTimeout);
            stub._getServiceClient().getOptions().setProperty(HTTPConstants.CONNECTION_TIMEOUT, autosclaerSocketTimeout);
            //String username = CarbonContext.getThreadLocalCarbonContext().getUsername();
            //TODO StratosAuthenticationHandler does not set to carbon context, thus user name becomes null.
            // For the moment username is hardcoded since above is fixed.
            String username = conf.getString("autoscaler.identity.adminUser", "admin");
            Utility.setAuthHeaders(stub._getServiceClient(), username);

        } catch (AxisFault axisFault) {
            String msg = "Failed to initiate identity service client. " + axisFault.getMessage();
            log.error(msg, axisFault);
            throw new AxisFault(msg, axisFault);
        }
    }
 
Example 10
Source File: ZteDeviceDiscoveryImpl.java    From onos with Apache License 2.0 5 votes vote down vote up
@Override
public DeviceDescription discoverDeviceDetails() {
    DeviceId deviceId = handler().data().deviceId();
    log.info("Discovering ZTE device {}", deviceId);

    NetconfController controller = handler().get(NetconfController.class);
    NetconfSession session = controller.getDevicesMap().get(deviceId).getSession();

    String hwVersion = "ZTE hw";
    String swVersion = "ZTE sw";
    String serialNumber = "000000000000";

    try {
        String reply = session.requestSync(buildDeviceInfoRequest());
        XMLConfiguration cfg = (XMLConfiguration) XmlConfigParser.loadXmlString(getDataOfRpcReply(reply));
        hwVersion = cfg.getString("components.component.state.hardware-version");
        swVersion = cfg.getString("components.component.state.software-version");
        serialNumber = cfg.getString("components.component.state.serial-no");
    } catch (NetconfException e) {
        log.error("ZTE device discovery error.", e);
    }

    return new DefaultDeviceDescription(deviceId.uri(),
            Device.Type.OTN,
            "ZTE",
            hwVersion,
            swVersion,
            serialNumber,
            new ChassisId(1));
}
 
Example 11
Source File: RORClient.java    From development with Apache License 2.0 5 votes vote down vote up
/**
 * @param instanceName
 * @param descriptorId
 * @return the ID of the created LPlatform
 * @throws RORException
 */
public String createLPlatform(String instanceName, String descriptorId)
		throws IaasException {
	HashMap<String, String> request = getBasicParameters();
	request.put(LParameter.ACTION, LOperation.CREATE_LPLATFORM);
	request.put(LParameter.LPLATFORM_NAME, instanceName);
	request.put(LParameter.LPLATFORM_DESCR_ID, descriptorId);
	XMLConfiguration result = execute(request);
	return result.getString("lplatformId");
}
 
Example 12
Source File: CarFactory1.java    From JavaDesignPattern with Apache License 2.0 5 votes vote down vote up
public static Car newCar() {
	Car car = null;
	String name = null;
	try {
		XMLConfiguration config = new XMLConfiguration("car.xml");
		name = config.getString("factory1.name");
	} catch (ConfigurationException ex) {
		LOG.error("parse xml configuration file failed", ex);
	}

	switch (name) {
	case "Land Rover":
		car = new LandRoverCar();
		break;
	case "BMW":
		car = new BMWCar();
		break;
	case "Benz":
		car = new BenzCar();
		break;
	default:
		car = null;
		break;
	}
	LOG.info("Created car name is {}", name);
	return car;
}
 
Example 13
Source File: TestSettings.java    From sailfish-core with Apache License 2.0 4 votes vote down vote up
@Test
public void testServerSettings()
{
	try
	{
		String configFilePath = new File(".").getCanonicalPath();

		String fileFQN = configFilePath + File.separator
		+ "cfg" + File.separator
		+ "config.xml";

		if(new File(fileFQN).exists())
		{
			XMLConfiguration config = new XMLConfiguration( fileFQN );
			config.load();

			Object servers = config.getProperty("Environment.ConnectionManager.Services.Service[@name]");

			if(servers instanceof Collection<?>)
			{
				for(int i = 0 ; i < ((Collection<?>) servers).size(); i++)
				{
					String key = String.format( "Environment.ConnectionManager.Services.Service(%d)[@type]", i );
					String keyValue = config.getString(key );

                       if("NTG-Server".equals(keyValue))
					{
						String instIdKey = String.format( "Environment.ConnectionManager.Services.Service(%d).strategies.strategy.instrumentID", i );
						Object prop = config.getList(instIdKey);

						if(prop instanceof Collection<?>)
						{
                               NTGServerSettings serverSettings = new NTGServerSettings();
                               Map<String, NTGServerStrategy> strategy = new HashMap<String, NTGServerStrategy>();

							int j = 0 ;

							for(Object instrValue : (Collection<?>)prop)
							{
								//String symbol = config.getString(String.format( "Environment.ConnectionManager.Services.Service(%d).strategies.strategy(%d).instrumentID", i, j));
								String symbol = instrValue.toString();

								if(! strategy.containsKey( symbol ))
								{
									String strategyValueString = config.getString(String.format( "Environment.ConnectionManager.Services.Service(%d).strategies.strategy(%d).strategyValue", i, j));
                                       NTGServerStrategy strategyValue =
                                               Enum.valueOf(NTGServerStrategy.class, strategyValueString);
									strategy.put( symbol, strategyValue );
								}
								++j;
							}

							int heartbeatTimeout = config.getInt(String.format("Environment.ConnectionManager.Services.Service(%d).heartbeatTimeout", i ));
							int maxMissedHeartbeats = config.getInt(String.format("Environment.ConnectionManager.Services.Service(%d).maxMissedHeartbeats", i ));
							int serverPort = config.getInt( String.format("Environment.ConnectionManager.Services.Service(%d).serverPort", i ));
							String serverIP = config.getString(String.format("Environment.ConnectionManager.Services.Service(%d).serverIP", i ));

							serverSettings.setHeartbeatTimeout( heartbeatTimeout );
							serverSettings.setMaxMissedHeartbeats( maxMissedHeartbeats );
							serverSettings.setServerPort( serverPort ) ;
							serverSettings.setServerIP( serverIP ) ;

							serverSettings.setStrategy( strategy );
						}
						break;
					}
					Assert.fail();
				}
			}
		}
	}
	catch(Exception ex)
	{
		ex.printStackTrace();
		Assert.fail();
	}
}
 
Example 14
Source File: OpenRoadmDeviceDescription.java    From onos with Apache License 2.0 4 votes vote down vote up
/**
 * Returns a DeviceDescription with Device info.
 *
 * @return DeviceDescription or null
 */
@Override
public DeviceDescription discoverDeviceDetails() {
    boolean defaultAvailable = true;
    NetconfDevice ncDevice = getNetconfDevice();
    if (ncDevice == null) {
        log.error("ONOS Error: Device reachable, deviceID {} is not in Map", did());
        return null;
    }
    DefaultAnnotations.Builder annotationsBuilder =
      DefaultAnnotations.builder();

    // Some defaults
    String vendor = "UNKNOWN";
    String hwVersion = "2.2.0";
    String swVersion = "2.2.0";
    String serialNumber = "0x0000";
    String chassisId = "0";
    String nodeType = "rdm";

    // Get the session, if null, at least we can use the defaults.
    NetconfSession session = getNetconfSession(did());
    if (session != null) {
        try {
            String reply = session.rpc(getDeviceDetailsBuilder()).get();
            XMLConfiguration xconf =
              (XMLConfiguration) XmlConfigParser.loadXmlString(reply);
            String nodeId =
              xconf.getString("data.org-openroadm-device.info.node-id", "");
            if (nodeId.equals("")) {
                log.error("[OPENROADM] {} org-openroadm-device node-id undefined, returning", did());
                return null;
            }
            annotationsBuilder.set(AnnotationKeys.OPENROADM_NODEID, nodeId);
            nodeType = xconf.getString("data.org-openroadm-device.info.node-type", "");
            if (nodeType.equals("")) {
                log.error("[OPENROADM] {} empty node-type", did());
                return null;
            }
            vendor = xconf.getString(
              "data.org-openroadm-device.info.vendor", vendor);
            hwVersion = xconf.getString(
              "data.org-openroadm-device.info.model", hwVersion);
            swVersion = xconf.getString(
              "data.org-openroadm-device.info.softwareVersion", swVersion);
            serialNumber = xconf.getString(
              "data.org-openroadm-device.info.serial-id", serialNumber);
            chassisId = xconf.getString(
              "data.org-openroadm-device.info.node-number", chassisId);

            // GEOLOCATION
            String longitudeStr = xconf.getString(
              "data.org-openroadm-device.info.geoLocation.longitude");
            String latitudeStr = xconf.getString(
              "data.org-openroadm-device.info.geoLocation.latitude");
            if (longitudeStr != null && latitudeStr != null) {
                annotationsBuilder
                  .set(org.onosproject.net.AnnotationKeys.LONGITUDE,
                       longitudeStr)
                  .set(org.onosproject.net.AnnotationKeys.LATITUDE,
                       latitudeStr);
            }
        } catch (NetconfException | InterruptedException | ExecutionException e) {
            log.error("[OPENROADM] {} exception", did());
            return null;
        }
    } else {
        log.debug("[OPENROADM] - No  session {}", did());
    }

    log.debug("[OPENROADM] {} - VENDOR {} HWVERSION {} SWVERSION {} SERIAL {} CHASSIS {}",
            did(), vendor, hwVersion, swVersion, serialNumber, chassisId);
    ChassisId cid = new ChassisId(Long.valueOf(chassisId, 10));
    /*
     * OpenROADM defines multiple devices (node types). This driver has been tested with
     * ROADMS, (node type, "rdm"). Other devices can also be discovered, and this code is here
     * for future developments - untested - it is likely that the XML documents
     * are model specific.
     */
    org.onosproject.net.Device.Type type;
    if (nodeType.equals("rdm")) {
        type = org.onosproject.net.Device.Type.ROADM;
    } else if (nodeType.equals("ila")) {
        type = org.onosproject.net.Device.Type.OPTICAL_AMPLIFIER;
    } else if (nodeType.equals("xpdr")) {
        type = org.onosproject.net.Device.Type.TERMINAL_DEVICE;
    } else if (nodeType.equals("extplug")) {
        type = org.onosproject.net.Device.Type.OTHER;
    } else {
        log.error("[OPENROADM] {} unsupported node-type", did());
        return null;
    }
    DeviceDescription desc = new DefaultDeviceDescription(
            did().uri(), type, vendor, hwVersion, swVersion, serialNumber, cid,
            defaultAvailable, annotationsBuilder.build());
    return desc;
}
 
Example 15
Source File: LServerClient.java    From development with Apache License 2.0 4 votes vote down vote up
/**
 * @return the status
 * @throws RORException
 */
public String getStatus() throws IaasException {
    XMLConfiguration result = executeLServerAction(LOperation.GET_LSERVER_STATUS);
    return result.getString("lserverStatus");
}
 
Example 16
Source File: LServerClient.java    From development with Apache License 2.0 4 votes vote down vote up
/**
 * @return the password
 * @throws RORException
 */
public String getInitialPassword() throws IaasException {
    XMLConfiguration result = executeLServerAction(LOperation.GET_LSERVER_INIT_PASSWD);
    return result.getString("initialPassword");
}
 
Example 17
Source File: MetaSettings.java    From systemsgenetics with GNU General Public License v3.0 4 votes vote down vote up
public void parse(String settings, String texttoreplace, String replacetextwith) {
		try {
			config = new XMLConfiguration(settings);

			nrPermutations = config.getInt("defaults.permutations", 0);

			useAbsoluteZscore = config.getBoolean("defaults.absolutezscore", false);
			finalEQTLBufferMaxLength = config.getInt("defaults.finalnreqtls", 100000);
			fdrthreshold = config.getDouble("defaults.fdrthreshold", 0.05);
			cisdistance = config.getInt("defaults.cisprobedistance", 250000);
			transdistance = config.getInt("defaults.transprobedistance", 5000000);
			includeProbesWithoutProperMapping = config.getBoolean("defaults.includeprobeswithoutmapping", true);
			includeSNPsWithoutProperMapping = config.getBoolean("defaults.includesnpswithoutmapping", true);
			makezscoreplot = config.getBoolean("defaults.makezscoreplot", true);
			makezscoretable = config.getBoolean("defaults.makezscoretable", false);
			probetranslationfile = config.getString("defaults.probetranslationfile");
			String outputStr = config.getString("defaults.output");

			System.out.println("outputstr: " + outputStr);

			if (texttoreplace != null && replacetextwith != null && outputStr.contains(texttoreplace)) {
				outputStr = outputStr.replaceAll(texttoreplace, replacetextwith);
				System.out.println("outputstr: " + outputStr);
			}
			output = outputStr;
			System.out.println("outputstr: " + outputStr);
//			System.exit(-1);


			probeDatasetPresenceThreshold = config.getInt("defaults.minimalnumberofdatasetsthatcontainprobe", 0);
			snpDatasetPresenceThreshold = config.getInt("defaults.minimalnumberofdatasetsthatcontainsnp", 0);
			probeAndSNPPresenceFilterSampleThreshold = config.getInt("defaults.snpprobeselectsamplesizethreshold", -1);

			runonlypermutation = config.getInt("defaults.runonlypermutation", -1);
			nrThresds = config.getInt("defaults.threads", 0);
			cis = config.getBoolean("defaults.cis", false);
			trans = config.getBoolean("defaults.trans", false);

			probeselection = config.getString("defaults.probeselection");

			if (probeselection != null && probeselection.trim().length() == 0) {
				probeselection = null;
			}
			snpselection = config.getString("defaults.snpselection");

			if (snpselection != null && snpselection.trim().length() == 0) {
				snpselection = null;
			}

			if (texttoreplace != null && replacetextwith != null && snpselection.contains(texttoreplace)) {
				snpselection = snpselection.replaceAll(texttoreplace, replacetextwith);
			}

			snpprobeselection = config.getString("defaults.snpprobeselection");

			if (snpprobeselection != null && snpprobeselection.trim().length() == 0) {
				snpprobeselection = null;
			} else {
				System.out.println("SNP PROBE SELECTION: " + snpprobeselection);
			}


			int i = 0;

			String dataset = "";
			datasetnames = new ArrayList<String>();
			datasetlocations = new ArrayList<String>();
			datasetannotations = new ArrayList<String>();
			datasetPrefix = new ArrayList<String>();

			while (dataset != null) {
				dataset = config.getString("datasets.dataset(" + i + ").name");  // see if a dataset is defined
				if (dataset != null) {

					datasetnames.add(dataset);
					String prefix = config.getString("datasets.dataset(" + i + ").prefix");  // see if a dataset is defined

					if (prefix == null) {
						prefix = "Dataset";
					}
					datasetPrefix.add(prefix);
					String datasetlocation = config.getString("datasets.dataset(" + i + ").location");  // see if a dataset is defined
					if (texttoreplace != null && replacetextwith != null && datasetlocation.contains(texttoreplace)) {
						datasetlocation = datasetlocation.replace(texttoreplace, replacetextwith);
					}
					String datasetannotation = config.getString("datasets.dataset(" + i + ").expressionplatform");  // see if a dataset is defined

					datasetlocations.add(datasetlocation);
					datasetannotations.add(datasetannotation);
				}
				i++;
			}


			// parse datasets
		} catch (ConfigurationException e) {
			e.printStackTrace();
		}
	}
 
Example 18
Source File: ClientLineTerminalDeviceDiscovery.java    From onos with Apache License 2.0 4 votes vote down vote up
/**
 * Returns a DeviceDescription with Device info.
 *
 * @return DeviceDescription or null
 *
 * //CHECKSTYLE:OFF
 * <pre>{@code
 * <data>
 * <components xmlns="http://openconfig.net/yang/platform">
 *  <component>
 *   <state>
 *     <name>FIRMWARE</name>
 *     <type>oc-platform-types:OPERATING_SYSTEM</type>
 *     <description>CTTC METRO-HAUL Emulated OpenConfig TerminalDevice</description>
 *     <version>0.0.1</version>
 *   </state>
 *  </component>
 * </components>
 * </data>
 *}</pre>
 * //CHECKSTYLE:ON
 */
@Override
public DeviceDescription discoverDeviceDetails() {
    boolean defaultAvailable = true;
    SparseAnnotations annotations = DefaultAnnotations.builder().build();

    log.debug("ClientLineTerminalDeviceDiscovery::discoverDeviceDetails device {}", did());

    // Other option "OTN" or "OTHER", we use TERMINAL_DEVICE
    org.onosproject.net.Device.Type type =
        Device.Type.TERMINAL_DEVICE;

    // Some defaults
    String vendor       = "NOVENDOR";
    String serialNumber = "0xCAFEBEEF";
    String hwVersion    = "0.2.1";
    String swVersion    = "0.2.1";
    String chassisId    = "128";

    // Get the session,
    NetconfSession session = getNetconfSession(did());
    try {
        String reply = session.get(getDeviceDetailsBuilder());
        log.debug("REPLY to DeviceDescription {}", reply);

        // <rpc-reply> as root node, software hardare version requires openconfig >= 2018
        XMLConfiguration xconf = (XMLConfiguration) XmlConfigParser.loadXmlString(reply);
        vendor       = xconf.getString("data.components.component.state.mfg-name", vendor);
        serialNumber = xconf.getString("data.components.component.state.serial-no", serialNumber);
        swVersion    = xconf.getString("data.components.component.state.software-version", swVersion);
        hwVersion    = xconf.getString("data.components.component.state.hardware-version", hwVersion);
    } catch (Exception e) {
            log.error("ClientLineTerminalDeviceDiscovery::discoverDeviceDetails - Failed to retrieve session {}",
                    did());
            throw new IllegalStateException(new NetconfException("Failed to retrieve version info.", e));
    }

    ChassisId cid = new ChassisId(Long.valueOf(chassisId, 10));

    log.info("Device retrieved details");
    log.info("VENDOR    {}", vendor);
    log.info("HWVERSION {}", hwVersion);
    log.info("SWVERSION {}", swVersion);
    log.info("SERIAL    {}", serialNumber);
    log.info("CHASSISID {}", chassisId);

    return new DefaultDeviceDescription(did().uri(),
                type, vendor, hwVersion, swVersion, serialNumber,
                cid, defaultAvailable, annotations);
}
 
Example 19
Source File: TerminalDeviceDiscovery.java    From onos with Apache License 2.0 4 votes vote down vote up
/**
 * Returns a DeviceDescription with Device info.
 *
 * @return DeviceDescription or null
 *
 * //CHECKSTYLE:OFF
 * <pre>{@code
 * <data>
 * <components xmlns="http://openconfig.net/yang/platform">
 *  <component>
 *   <state>
 *     <name>FIRMWARE</name>
 *     <type>oc-platform-types:OPERATING_SYSTEM</type>
 *     <description>CTTC METRO-HAUL Emulated OpenConfig TerminalDevice</description>
 *     <version>0.0.1</version>
 *   </state>
 *  </component>
 * </components>
 * </data>
 *}</pre>
 * //CHECKSTYLE:ON
 */
@Override
public DeviceDescription discoverDeviceDetails() {
    log.info("TerminalDeviceDiscovery::discoverDeviceDetails device {}", did());
    boolean defaultAvailable = true;
    SparseAnnotations annotations = DefaultAnnotations.builder().build();

    // Other option "OTHER", we use ROADM for now
    org.onosproject.net.Device.Type type =
        Device.Type.TERMINAL_DEVICE;

    // Some defaults
    String vendor       = "NOVENDOR";
    String hwVersion    = "0.2.1";
    String swVersion    = "0.2.1";
    String serialNumber = "0xCAFEBEEF";
    String chassisId    = "128";

    // Get the session,
    NetconfSession session = getNetconfSession(did());
    if (session != null) {
        try {
            String reply = session.get(getDeviceDetailsBuilder());
            // <rpc-reply> as root node
            XMLConfiguration xconf = (XMLConfiguration) XmlConfigParser.loadXmlString(reply);
            vendor       = xconf.getString("data/components/component/state/mfg-name", vendor);
            serialNumber = xconf.getString("data/components/component/state/serial-no", serialNumber);
            // Requires OpenConfig >= 2018
            swVersion    = xconf.getString("data/components/component/state/software-version", swVersion);
            hwVersion    = xconf.getString("data/components/component/state/hardware-version", hwVersion);
        } catch (Exception e) {
            throw new IllegalStateException(new NetconfException("Failed to retrieve version info.", e));
        }
    } else {
        log.info("TerminalDeviceDiscovery::discoverDeviceDetails - No netconf session for {}", did());
    }
    log.info("VENDOR    {}", vendor);
    log.info("HWVERSION {}", hwVersion);
    log.info("SWVERSION {}", swVersion);
    log.info("SERIAL    {}", serialNumber);
    log.info("CHASSISID {}", chassisId);
    ChassisId cid = new ChassisId(Long.valueOf(chassisId, 10));
    return new DefaultDeviceDescription(did().uri(),
                type, vendor, hwVersion, swVersion, serialNumber,
                cid, defaultAvailable, annotations);
    }
 
Example 20
Source File: LPlatformClient.java    From development with Apache License 2.0 2 votes vote down vote up
/**
 * @return the status of the LPlatform
 * @throws SuspendException
 * @throws RORException
 */
public String getStatus() throws IaasException, SuspendException {
    XMLConfiguration result = executeLPlatformAction(LOperation.GET_LPLATFORM_STATUS);
    return result.getString("lplatformStatus");
}