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

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

Introduction

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

Prototype

public String getString(String key) 

Source Link

Usage

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

private void parseTopologyView(HierarchicalConfiguration areaConfig, Obj parent, Network n,
        ObjectBroker objectBroker, Hashtable<String, EntityImpl> entityById,
        Hashtable<String, DatapointImpl> datapointById, Hashtable<String, String> resourceById) {
    for (int areaIdx = 0; areaIdx < sizeOfConfiguration(areaConfig.getProperty("area.[@id]")); areaIdx++) {
        String areaId = areaConfig.getString("area(" + areaIdx + ").[@id]");
        String areaName = arrayToString(areaConfig.getStringArray("area(" + areaIdx + ").[@name]"));
        String areaDescription = arrayToString(
                areaConfig.getStringArray("area(" + areaIdx + ").[@description]"));
        String areaMediaTypeId = areaConfig.getString("area(" + areaIdx + ").[@mediaTypeId]");
        long areaAddress = areaConfig.getLong("area(" + areaIdx + ").[@address]");

        String areaMediaType = null;
        if (areaMediaTypeId != null) {
            areaMediaType = resourceById.get(areaMediaTypeId);
        }/* w w w .  jav a  2s .  co  m*/

        AreaImpl area = new AreaImpl(areaId, areaName, areaDescription, areaAddress, areaMediaType);

        // add part to parent part
        if (parent instanceof ViewTopologyImpl)
            ((ViewTopologyImpl) parent).addArea(area);
        else if (parent instanceof DomainImpl)
            ((AreaImpl) parent).addArea(area);
        else
            parent.add(area);

        objectBroker.addObj(area, true);

        // add instances to part
        HierarchicalConfiguration concreteArea = areaConfig.configurationAt("area(" + areaIdx + ")");

        for (int instanceIdx = 0; instanceIdx < sizeOfConfiguration(
                concreteArea.getProperty("instance.[@id]")); instanceIdx++) {
            String instanceId = concreteArea.getString("instance(" + instanceIdx + ").[@id]");
            long address = concreteArea.getLong("instance(" + instanceIdx + ").[@address]");

            Obj addInstance = area.addInstance(entityById.get(instanceId), address);
            objectBroker.addObj(addInstance, true);

        }

        // recursively add more domains
        parseTopologyView(concreteArea, area, n, objectBroker, entityById, datapointById, resourceById);
    }
}

From source file:edu.hawaii.soest.hioos.isus.ISUSSource.java

/**
 * A method that processes the data object passed and flushes the
 * data to the DataTurbine given the sensor properties in the XMLConfiguration
 * passed in.//  w w w . j a  va 2s. c  om
 *
 * @param xmlConfig - the XMLConfiguration object containing the list of
 *                    sensor properties
 * @param frameMap  - the parsed data as a HierarchicalMap object
 */
public boolean process(XMLConfiguration xmlConfig, HierarchicalMap frameMap) {

    logger.debug("ISUSSource.process() called.");
    // do not execute the stream if there is no connection
    if (!isConnected())
        return false;

    boolean success = false;

    try {

        // add channels of data that will be pushed to the server.  
        // Each sample will be sent to the Data Turbine as an rbnb frame.  Information
        // on each channel is found in the XMLConfiguration file (email.account.properties.xml)
        // and the StorXParser object (to get the data string)
        ChannelMap rbnbChannelMap = new ChannelMap(); // used to flush channels
        ChannelMap registerChannelMap = new ChannelMap(); // used to register channels
        int channelIndex = 0;

        String sensorName = null;
        String sensorSerialNumber = null;
        String sensorDescription = null;
        boolean isImmersed = false;
        String[] calibrationURLs = null;
        String calibrationURL = null;
        String type = null;

        List sensorList = xmlConfig.configurationsAt("account.logger.sensor");

        for (Iterator sIterator = sensorList.iterator(); sIterator.hasNext();) {
            //  
            HierarchicalConfiguration sensorConfig = (HierarchicalConfiguration) sIterator.next();
            sensorSerialNumber = sensorConfig.getString("serialNumber");

            // find the correct sensor configuration properties
            if (sensorSerialNumber.equals(frameMap.get("serialNumber"))) {

                sensorName = sensorConfig.getString("name");
                sensorDescription = sensorConfig.getString("description");
                isImmersed = new Boolean(sensorConfig.getString("isImmersed")).booleanValue();
                calibrationURLs = sensorConfig.getStringArray("calibrationURL");
                type = (String) frameMap.get("type");

                // find the correct calibrationURL from the list given the type
                for (String url : calibrationURLs) {

                    if (url.indexOf(type) > 0) {
                        calibrationURL = url;
                        break;

                    } else {
                        logger.debug("There was no match for " + type);
                    }
                }

                // get a Calibration instance to interpret raw sensor values
                Calibration calibration = new Calibration();

                if (calibration.parse(calibrationURL)) {

                    // Build the RBNB channel map 

                    // get the sample date and convert it to seconds since the epoch
                    Date frameDate = (Date) frameMap.get("date");
                    Calendar frameDateTime = Calendar.getInstance();
                    frameDateTime.setTime(frameDate);
                    double sampleTimeAsSecondsSinceEpoch = (double) (frameDateTime.getTimeInMillis() / 1000);
                    // and create a string formatted date for the given time zone
                    DATE_FORMAT.setTimeZone(TZ);
                    String frameDateAsString = DATE_FORMAT.format(frameDate).toString();

                    // get the sample data from the frame map
                    ByteBuffer rawFrame = (ByteBuffer) frameMap.get("rawFrame");
                    ISUSFrame isusFrame = (ISUSFrame) frameMap.get("parsedFrameObject");
                    String serialNumber = isusFrame.getSerialNumber();
                    String sampleDate = isusFrame.getSampleDate();
                    String sampleTime = isusFrame.getSampleTime();
                    SimpleDateFormat dtFormat = new SimpleDateFormat();
                    Date sampleDateTime = isusFrame.getSampleDateTime();
                    dtFormat.setTimeZone(TimeZone.getTimeZone("UTC"));
                    dtFormat.applyPattern("MM/dd/yy");
                    String sampleDateUTC = dtFormat.format(sampleDateTime);
                    dtFormat.applyPattern("HH:mm:ss");
                    String sampleTimeUTC = dtFormat.format(sampleDateTime);
                    dtFormat.setTimeZone(TimeZone.getTimeZone("HST"));
                    dtFormat.applyPattern("MM/dd/yy");
                    String sampleDateHST = dtFormat.format(sampleDateTime);
                    dtFormat.applyPattern("HH:mm:ss");
                    String sampleTimeHST = dtFormat.format(sampleDateTime);
                    dtFormat.applyPattern("dd-MMM-yy HH:mm");
                    String sampleDateTimeHST = dtFormat.format(sampleDateTime);

                    double rawNitrogenConcentration = isusFrame.getNitrogenConcentration();
                    double rawAuxConcentration1 = isusFrame.getAuxConcentration1();
                    double rawAuxConcentration2 = isusFrame.getAuxConcentration2();
                    double rawAuxConcentration3 = isusFrame.getAuxConcentration3();
                    double rawRmsError = isusFrame.getRmsError();
                    double rawInsideTemperature = isusFrame.getInsideTemperature();
                    double rawSpectrometerTemperature = isusFrame.getSpectrometerTemperature();
                    double rawLampTemperature = isusFrame.getLampTemperature();
                    int rawLampTime = isusFrame.getLampTime();
                    double rawHumidity = isusFrame.getHumidity();
                    double rawLampVoltage12 = isusFrame.getLampVoltage12();
                    double rawInternalPowerVoltage5 = isusFrame.getInternalPowerVoltage5();
                    double rawMainPowerVoltage = isusFrame.getMainPowerVoltage();
                    double rawReferenceAverage = isusFrame.getReferenceAverage();
                    double rawReferenceVariance = isusFrame.getReferenceVariance();
                    double rawSeaWaterDarkCounts = isusFrame.getSeaWaterDarkCounts();
                    double rawSpectrometerAverage = isusFrame.getSpectrometerAverage();
                    int checksum = isusFrame.getChecksum();

                    //// apply calibrations to the observed data
                    double nitrogenConcentration = calibration.apply(rawNitrogenConcentration, isImmersed,
                            "NITRATE");
                    double auxConcentration1 = calibration.apply(rawAuxConcentration1, isImmersed, "AUX1");
                    double auxConcentration2 = calibration.apply(rawAuxConcentration2, isImmersed, "AUX2");
                    double auxConcentration3 = calibration.apply(rawAuxConcentration3, isImmersed, "AUX3");
                    double rmsError = calibration.apply(rawRmsError, isImmersed, "RMSe");
                    double insideTemperature = calibration.apply(rawInsideTemperature, isImmersed, "T_INT");
                    double spectrometerTemperature = calibration.apply(rawSpectrometerTemperature, isImmersed,
                            "T_SPEC");
                    double lampTemperature = calibration.apply(rawLampTemperature, isImmersed, "T_LAMP");
                    int lampTime = rawLampTime;
                    double humidity = calibration.apply(rawHumidity, isImmersed, "HUMIDITY");
                    double lampVoltage12 = calibration.apply(rawLampVoltage12, isImmersed, "VOLT_12");
                    double internalPowerVoltage5 = calibration.apply(rawInternalPowerVoltage5, isImmersed,
                            "VOLT_5");
                    double mainPowerVoltage = calibration.apply(rawMainPowerVoltage, isImmersed, "VOLT_MAIN");
                    double referenceAverage = calibration.apply(rawReferenceAverage, isImmersed, "REF_AVG");
                    double referenceVariance = calibration.apply(rawReferenceVariance, isImmersed, "REF_STD");
                    double seaWaterDarkCounts = calibration.apply(rawSeaWaterDarkCounts, isImmersed, "SW_DARK");
                    double spectrometerAverage = calibration.apply(rawSpectrometerAverage, isImmersed,
                            "SPEC_AVG");

                    // iterate through the individual wavelengths
                    List<String> variableNames = calibration.getVariableNames();
                    TreeMap<String, Double> wavelengthsMap = new TreeMap<String, Double>();
                    Collections.sort(variableNames);
                    int rawWavelengthCounts = 0;
                    int count = 1;

                    for (String name : variableNames) {

                        // just handle the wavelength channels
                        if (name.startsWith("UV_")) {
                            rawWavelengthCounts = isusFrame.getChannelWavelengthCounts(count);

                            double value = calibration.apply(rawWavelengthCounts, isImmersed, name);
                            count++;
                            wavelengthsMap.put(name, new Double(value));

                        }

                    }

                    String sampleString = "";
                    sampleString += sampleDate + "\t";
                    sampleString += sampleDateUTC + "\t";
                    sampleString += sampleTime + "\t";
                    sampleString += sampleTimeUTC + "\t";
                    sampleString += sampleDateHST + "\t";
                    sampleString += sampleTimeHST + "\t";
                    sampleString += sampleDateTimeHST + "\t";
                    sampleString += String.format("%-15.11f", nitrogenConcentration) + "\t";
                    //sampleString += String.format("%15.11f", auxConcentration1)     + "\t";
                    //sampleString += String.format("%15.11f", auxConcentration2)     + "\t";
                    //sampleString += String.format("%15.11f", auxConcentration3)     + "\t";
                    sampleString += String.format("%15.11f", rmsError) + "\t";
                    sampleString += String.format("%15.11f", insideTemperature) + "\t";
                    sampleString += String.format("%15.11f", spectrometerTemperature) + "\t";
                    sampleString += String.format("%15.11f", lampTemperature) + "\t";
                    sampleString += String.format("%6d", lampTime) + "\t";
                    sampleString += String.format("%15.11f", humidity) + "\t";
                    sampleString += String.format("%15.11f", lampVoltage12) + "\t";
                    sampleString += String.format("%15.11f", internalPowerVoltage5) + "\t";
                    sampleString += String.format("%15.11f", mainPowerVoltage) + "\t";
                    sampleString += String.format("%15.11f", referenceAverage) + "\t";
                    sampleString += String.format("%15.11f", referenceVariance) + "\t";
                    sampleString += String.format("%15.11f", seaWaterDarkCounts) + "\t";
                    sampleString += String.format("%15.11f", spectrometerAverage) + "\t";

                    Set<String> wavelengths = wavelengthsMap.keySet();
                    Iterator wIterator = wavelengths.iterator();

                    while (wIterator.hasNext()) {
                        String name = (String) wIterator.next();
                        Double wavelengthValue = (Double) wavelengthsMap.get(name);
                        sampleString += String.format("%6d", wavelengthValue.intValue()) + "\t";
                        channelIndex = registerChannelMap.Add(name);
                        registerChannelMap.PutUserInfo(channelIndex, "units=counts");
                        channelIndex = rbnbChannelMap.Add(name);
                        rbnbChannelMap.PutMime(channelIndex, "application/octet-stream");
                        rbnbChannelMap.PutDataAsFloat64(channelIndex,
                                new double[] { wavelengthValue.doubleValue() });

                    }

                    sampleString += String.format("%03d", checksum);
                    sampleString += "\n";

                    // add the sample timestamp to the rbnb channel map
                    //registerChannelMap.PutTime(sampleTimeAsSecondsSinceEpoch, 0d);
                    rbnbChannelMap.PutTime(sampleTimeAsSecondsSinceEpoch, 0d);

                    // add the BinaryRawSatlanticFrameData channel to the channelMap
                    channelIndex = registerChannelMap.Add("BinaryRawSatlanticFrameData");
                    registerChannelMap.PutUserInfo(channelIndex, "units=none");
                    channelIndex = rbnbChannelMap.Add("BinaryRawSatlanticFrameData");
                    rbnbChannelMap.PutMime(channelIndex, "application/octet-stream");
                    rbnbChannelMap.PutDataAsByteArray(channelIndex, rawFrame.array());

                    // add the DecimalASCIISampleData channel to the channelMap
                    channelIndex = registerChannelMap.Add(getRBNBChannelName());
                    registerChannelMap.PutUserInfo(channelIndex, "units=none");
                    channelIndex = rbnbChannelMap.Add(getRBNBChannelName());
                    rbnbChannelMap.PutMime(channelIndex, "text/plain");
                    rbnbChannelMap.PutDataAsString(channelIndex, sampleString);

                    // add the serialNumber channel to the channelMap
                    channelIndex = registerChannelMap.Add("serialNumber");
                    registerChannelMap.PutUserInfo(channelIndex, "units=none");
                    channelIndex = rbnbChannelMap.Add("serialNumber");
                    rbnbChannelMap.PutMime(channelIndex, "text/plain");
                    rbnbChannelMap.PutDataAsString(channelIndex, serialNumber);

                    // add the sampleDateUTC channel to the channelMap
                    channelIndex = registerChannelMap.Add("sampleDateUTC");
                    registerChannelMap.PutUserInfo(channelIndex, "units=YYYYDDD");
                    channelIndex = rbnbChannelMap.Add("sampleDateUTC");
                    rbnbChannelMap.PutMime(channelIndex, "text/plain");
                    rbnbChannelMap.PutDataAsString(channelIndex, sampleDate);

                    // add the sampleTimeUTC channel to the channelMap
                    channelIndex = registerChannelMap.Add("sampleTimeUTC");
                    registerChannelMap.PutUserInfo(channelIndex, "units=hh.hhhhhh");
                    channelIndex = rbnbChannelMap.Add("sampleTimeUTC");
                    rbnbChannelMap.PutMime(channelIndex, "text/plain");
                    rbnbChannelMap.PutDataAsString(channelIndex, sampleTimeUTC);

                    // add the nitrogenConcentration channel to the channelMap
                    channelIndex = registerChannelMap.Add("nitrogenConcentration");
                    registerChannelMap.PutUserInfo(channelIndex, "units=uM");
                    channelIndex = rbnbChannelMap.Add("nitrogenConcentration");
                    rbnbChannelMap.PutMime(channelIndex, "application/octet-stream");
                    rbnbChannelMap.PutDataAsFloat64(channelIndex, new double[] { nitrogenConcentration });

                    // add the auxConcentration1 channel to the channelMap
                    channelIndex = registerChannelMap.Add("auxConcentration1");
                    registerChannelMap.PutUserInfo(channelIndex, "units=none");
                    channelIndex = rbnbChannelMap.Add("auxConcentration1");
                    rbnbChannelMap.PutMime(channelIndex, "application/octet-stream");
                    rbnbChannelMap.PutDataAsFloat64(channelIndex, new double[] { auxConcentration1 });

                    // add the auxConcentration3 channel to the channelMap
                    channelIndex = registerChannelMap.Add("auxConcentration2");
                    registerChannelMap.PutUserInfo(channelIndex, "units=none");
                    channelIndex = rbnbChannelMap.Add("auxConcentration2");
                    rbnbChannelMap.PutMime(channelIndex, "application/octet-stream");
                    rbnbChannelMap.PutDataAsFloat64(channelIndex, new double[] { auxConcentration2 });

                    // add the serialNumber channel to the channelMap
                    channelIndex = registerChannelMap.Add("auxConcentration3");
                    registerChannelMap.PutUserInfo(channelIndex, "units=none");
                    channelIndex = rbnbChannelMap.Add("auxConcentration3");
                    rbnbChannelMap.PutMime(channelIndex, "application/octet-stream");
                    rbnbChannelMap.PutDataAsFloat64(channelIndex, new double[] { auxConcentration3 });

                    // add the rmsError channel to the channelMap
                    channelIndex = registerChannelMap.Add("rmsError");
                    registerChannelMap.PutUserInfo(channelIndex, "units=none");
                    channelIndex = rbnbChannelMap.Add("rmsError");
                    rbnbChannelMap.PutMime(channelIndex, "application/octet-stream");
                    rbnbChannelMap.PutDataAsFloat64(channelIndex, new double[] { rmsError });

                    // add the insideTemperature channel to the channelMap
                    channelIndex = registerChannelMap.Add("insideTemperature");
                    registerChannelMap.PutUserInfo(channelIndex, "units=Celsius");
                    channelIndex = rbnbChannelMap.Add("insideTemperature");
                    rbnbChannelMap.PutMime(channelIndex, "application/octet-stream");
                    rbnbChannelMap.PutDataAsFloat64(channelIndex, new double[] { insideTemperature });

                    // add the spectrometerTemperature channel to the channelMap
                    channelIndex = registerChannelMap.Add("spectrometerTemperature");
                    registerChannelMap.PutUserInfo(channelIndex, "units=Celsius");
                    channelIndex = rbnbChannelMap.Add("spectrometerTemperature");
                    rbnbChannelMap.PutMime(channelIndex, "application/octet-stream");
                    rbnbChannelMap.PutDataAsFloat64(channelIndex, new double[] { spectrometerTemperature });

                    // add the lampTemperature channel to the channelMap
                    channelIndex = registerChannelMap.Add("lampTemperature");
                    registerChannelMap.PutUserInfo(channelIndex, "units=Celsius");
                    channelIndex = rbnbChannelMap.Add("lampTemperature");
                    rbnbChannelMap.PutMime(channelIndex, "application/octet-stream");
                    rbnbChannelMap.PutDataAsFloat64(channelIndex, new double[] { lampTemperature });

                    // add the lampTime channel to the channelMap
                    channelIndex = registerChannelMap.Add("lampTime");
                    registerChannelMap.PutUserInfo(channelIndex, "units=seconds");
                    channelIndex = rbnbChannelMap.Add("lampTime");
                    rbnbChannelMap.PutMime(channelIndex, "application/octet-stream");
                    rbnbChannelMap.PutDataAsInt32(channelIndex, new int[] { lampTime });

                    // add the humidity channel to the channelMap
                    channelIndex = registerChannelMap.Add("humidity");
                    registerChannelMap.PutUserInfo(channelIndex, "units=%");
                    channelIndex = rbnbChannelMap.Add("humidity");
                    rbnbChannelMap.PutMime(channelIndex, "application/octet-stream");
                    rbnbChannelMap.PutDataAsFloat64(channelIndex, new double[] { humidity });

                    // add the lampVoltage12 channel to the channelMap
                    channelIndex = registerChannelMap.Add("lampVoltage12");
                    registerChannelMap.PutUserInfo(channelIndex, "units=V");
                    channelIndex = rbnbChannelMap.Add("lampVoltage12");
                    rbnbChannelMap.PutMime(channelIndex, "application/octet-stream");
                    rbnbChannelMap.PutDataAsFloat64(channelIndex, new double[] { lampVoltage12 });

                    // add the internalPowerVoltage5 channel to the channelMap
                    channelIndex = registerChannelMap.Add("internalPowerVoltage5");
                    registerChannelMap.PutUserInfo(channelIndex, "units=V");
                    channelIndex = rbnbChannelMap.Add("internalPowerVoltage5");
                    rbnbChannelMap.PutMime(channelIndex, "application/octet-stream");
                    rbnbChannelMap.PutDataAsFloat64(channelIndex, new double[] { internalPowerVoltage5 });

                    // add the mainPowerVoltage channel to the channelMap
                    channelIndex = registerChannelMap.Add("mainPowerVoltage");
                    registerChannelMap.PutUserInfo(channelIndex, "units=V");
                    channelIndex = rbnbChannelMap.Add("mainPowerVoltage");
                    rbnbChannelMap.PutMime(channelIndex, "application/octet-stream");
                    rbnbChannelMap.PutDataAsFloat64(channelIndex, new double[] { mainPowerVoltage });

                    // add the referenceAverage channel to the channelMap
                    channelIndex = registerChannelMap.Add("referenceAverage");
                    registerChannelMap.PutUserInfo(channelIndex, "units=count");
                    channelIndex = rbnbChannelMap.Add("referenceAverage");
                    rbnbChannelMap.PutMime(channelIndex, "application/octet-stream");
                    rbnbChannelMap.PutDataAsFloat64(channelIndex, new double[] { referenceAverage });

                    // add the referenceVariance channel to the channelMap
                    channelIndex = registerChannelMap.Add("referenceVariance");
                    registerChannelMap.PutUserInfo(channelIndex, "units=count");
                    channelIndex = rbnbChannelMap.Add("referenceVariance");
                    rbnbChannelMap.PutMime(channelIndex, "application/octet-stream");
                    rbnbChannelMap.PutDataAsFloat64(channelIndex, new double[] { referenceVariance });

                    // add the seaWaterDarkCounts channel to the channelMap
                    channelIndex = registerChannelMap.Add("seaWaterDarkCounts");
                    registerChannelMap.PutUserInfo(channelIndex, "units=count");
                    channelIndex = rbnbChannelMap.Add("seaWaterDarkCounts");
                    rbnbChannelMap.PutMime(channelIndex, "application/octet-stream");
                    rbnbChannelMap.PutDataAsFloat64(channelIndex, new double[] { seaWaterDarkCounts });

                    // add the spectrometerAverage channel to the channelMap
                    channelIndex = registerChannelMap.Add("spectrometerAverage");
                    registerChannelMap.PutUserInfo(channelIndex, "units=count");
                    channelIndex = rbnbChannelMap.Add("averageWavelength");
                    rbnbChannelMap.PutMime(channelIndex, "application/octet-stream");
                    rbnbChannelMap.PutDataAsFloat64(channelIndex, new double[] { spectrometerAverage });

                    // Now register the RBNB channels, and flush the rbnbChannelMap to the
                    // DataTurbine
                    getSource().Register(registerChannelMap);
                    getSource().Flush(rbnbChannelMap);
                    logger.info(frameDateAsString + " " + "Sample sent to the DataTurbine: (" + serialNumber
                            + ") " + sampleString);

                    registerChannelMap.Clear();
                    rbnbChannelMap.Clear();

                } else {

                    logger.info("Couldn't apply the calibration coefficients. " + "Skipping this sample.");

                } // end if()

            } // end if()

        } // end for()                                             

        //getSource.Detach();

        success = true;
    } catch (ParseException pe) {
        // parsing of the calibration file failed.  Log the exception, return false
        success = false;
        logger.debug("There was a problem parsing the calibration file. The " + "error message was: "
                + pe.getMessage());
        return success;

    } catch (SAPIException sapie) {
        // In the event of an RBNB communication  exception, log the exception, 
        // and allow execute() to return false, which will prompt a retry.
        success = false;
        sapie.printStackTrace();
        return success;

    }

    return success;
}

From source file:com.termmed.statistics.db.importer.ImportManager.java

/**
 * Execute.//from   www .j  a va2 s .  c o m
 *
 * @throws IOException Signals that an I/O exception has occurred.
 * @throws Exception the exception
 */
public void execute() throws IOException, Exception {
    logger.info("Starting import manager process");

    createFolders();
    importer = new Importer();
    if (!existingTables()) {
        DbSetup dbSetup = new DbSetup(connection);
        dbSetup.execute();
        dbSetup = null;
    }
    XMLConfiguration xmlConfig;
    try {
        xmlConfig = new XMLConfiguration(configFile);
    } catch (ConfigurationException e) {
        logger.error("ClassificationRunner - Error happened getting params configFile." + e.getMessage());
        throw e;
    }

    refsetId = xmlConfig.getString("refsetId");
    releaseDependencies = CurrentFile.get().getReleaseDependenciesFullFolders() != null
            && CurrentFile.get().getReleaseDependenciesFullFolders().size() > 0;
    this.releaseDate = xmlConfig.getString("releaseDate");
    this.previousReleaseDate = xmlConfig.getString("previousReleaseDate");

    this.reducedSnapshotFolder = new File("reducedSnapshotFolder");
    if (!reducedSnapshotFolder.exists()) {
        reducedSnapshotFolder.mkdirs();
    }
    this.previousReducedSnapshotFolder = new File("previousReducedSnapshotFolder");
    if (!previousReducedSnapshotFolder.exists()) {
        previousReducedSnapshotFolder.mkdirs();
    }
    if (DependentFile.get() != null) {
        CurrentFile.get().setSnapshotExtensionLanguage(DependentFile.get().getSnapshotLanguageFile());
    } else {
        CurrentFile.get().setSnapshotExtensionLanguage(xmlConfig.getString("extensionLanguageSnapshotFile"));
    }
    List<HierarchicalConfiguration> fields = xmlConfig.configurationsAt("reports.reportDescriptor");

    if (fields != null) {
        for (HierarchicalConfiguration sub : fields) {

            String report = sub.getString("filename");
            String value = sub.getString("execute");

            if (value.toLowerCase().equals("true")) {
                logger.info("Getting config for report " + report);
                ReportConfig reportCfg = ResourceUtils.getReportConfig(report);

                for (TABLE table : reportCfg.getInputFile()) {
                    switch (table) {
                    case STATEDROOTDESC:
                        if (rootDesc) {
                            continue;
                        }
                        rootDesc = true;
                        break;
                    case CONCEPTS:
                        if (concepts) {
                            continue;
                        }
                        concepts = true;
                        break;
                    case DESCRIPTIONS:
                        if (descriptions) {
                            continue;
                        }
                        descriptions = true;
                        break;
                    case DESCRIPTIONS_PREVIOUS:
                        if (descriptions_pre) {
                            continue;
                        }
                        descriptions_pre = true;
                        break;
                    case EXT_LANGUAGE:
                        if (extLanguage) {
                            continue;
                        }
                        extLanguage = true;

                        break;
                    case RELATIONSHIPS:
                        if (relationships) {
                            continue;
                        }
                        relationships = true;
                        break;
                    case STATEDRELS:
                        if (statedRels) {
                            continue;
                        }
                        statedRels = true;
                        break;
                    case TCLOSUREINFERRED:
                        if (tClosureInferred) {
                            continue;
                        }
                        tClosureInferred = true;
                        break;
                    case TCLOSURESTATED:
                        if (tClosureStated) {
                            continue;
                        }
                        tClosureStated = true;
                        break;
                    case CONCEPTS_PREVIOUS:
                        if (concepts_pre) {
                            continue;
                        }
                        concepts_pre = true;
                        break;
                    case RELATIONSHIPS_PREVIOUS:
                        if (relationships_pre) {
                            continue;
                        }
                        relationships_pre = true;
                        break;
                    case STATEDRELS_PREVIOUS:
                        if (statedRels_pre) {
                            continue;
                        }
                        statedRels_pre = true;
                        break;
                    case LANGUAGE_PREVIOUS:
                        if (refsetId != null && !refsetId.equals("")) {
                            Integer[] newfields = new Integer[] { 2, 4, 6 };
                            String[] newValues = new String[] { "1", refsetId, "900000000000548007" };
                            table.setFieldFilter(newfields);
                            table.setFieldFilterValue(newValues);
                        }
                        if (lang_pre) {
                            continue;
                        }
                        lang_pre = true;
                        break;
                    case LANGUAGE:
                        if (refsetId != null && !refsetId.equals("")) {
                            Integer[] newfields = new Integer[] { 2, 4, 6 };
                            String[] newValues = new String[] { "1", refsetId, "900000000000548007" };
                            table.setFieldFilter(newfields);
                            table.setFieldFilterValue(newValues);
                        }
                        if (lang) {
                            continue;
                        }
                        lang = true;
                        break;
                    case TCLOSURESTATED_PREVIOUS:
                        if (tClosureStated_pre) {
                            continue;
                        }
                        tClosureStated_pre = true;
                        break;
                    case SAME_AS_ASSOCIATIONS:
                        if (same_associations) {
                            continue;
                        }
                        same_associations = true;
                        break;
                    }
                    ImportRf2Table(table);
                }
                System.out.println(report + " " + value);
            }
        }
    }
    logger.info("Updating date to " + releaseDate);
    saveNewDate(I_Constants.RELEASE_DATE, releaseDate);

    logger.info("Updating previous date to " + previousReleaseDate);
    saveNewDate(I_Constants.PREVIOUS_RELEASE_DATE, previousReleaseDate);

    fields = xmlConfig.configurationsAt("sp_params.param");

    params = new HashMap<String, String>();
    if (fields != null) {
        for (HierarchicalConfiguration sub : fields) {
            String paramName = sub.getString("name");
            String value = sub.getString("value");
            if (value.equals("$param")) {
                value = xmlConfig.getString(paramName);
            }
            params.put(paramName, value);
        }
    }
    logger.info("End of import manager process");
}

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

private void parseFunctionalView(HierarchicalConfiguration groupConfig, Obj parent, Network n,
        ObjectBroker objectBroker, Hashtable<String, EntityImpl> entityById,
        Hashtable<String, DatapointImpl> datapointById, KNXConnector knxConnector,
        Hashtable<String, String> groupAddressByDatapointId) {
    for (int groupsIdx = 0; groupsIdx < sizeOfConfiguration(
            groupConfig.getProperty("group.[@id]")); groupsIdx++) {
        String groupId = groupConfig.getString("group(" + groupsIdx + ").[@id]");
        String groupName = arrayToString(groupConfig.getStringArray("group(" + groupsIdx + ").[@name]"));
        String groupDescription = arrayToString(
                groupConfig.getStringArray("group(" + groupsIdx + ").[@description]"));
        long groupAddress = groupConfig.getLong("group(" + groupsIdx + ").[@address]");

        GroupImpl group = new GroupImpl(groupId, groupName, groupDescription, groupAddress);

        // add part to parent part
        if (parent instanceof ViewFunctionalImpl)
            ((ViewFunctionalImpl) parent).addGroup(group);
        else if (parent instanceof GroupImpl)
            ((GroupImpl) parent).addGroup(group);
        else/*ww w  .j a va  2 s. co m*/
            parent.add(group);

        objectBroker.addObj(group, true);

        // add instances to part
        HierarchicalConfiguration concreteGroup = groupConfig.configurationAt("group(" + groupsIdx + ")");

        for (int instanceIdx = 0; instanceIdx < sizeOfConfiguration(
                concreteGroup.getProperty("instance.[@id]")); instanceIdx++) {
            String instanceId = concreteGroup.getString("instance(" + instanceIdx + ").[@id]");
            String connector = concreteGroup.getString("instance(" + instanceIdx + ").[@connector]");

            try {
                DatapointImpl dp = datapointById.get(instanceId);
                if (dp == null) {
                    log.warning("No datapoint type found for instance: " + instanceId);
                    continue;
                }
                Class<?> clazz = dp.getClass();

                if (clazz != null) {
                    Constructor<?> constructor = clazz.getConstructor(KNXConnector.class, DataPointInit.class);
                    Object[] object = new Object[2];
                    object[0] = knxConnector;

                    DataPointInit dptInit = new DataPointInit();
                    dptInit.setName("function");
                    dptInit.setReadable(dp.isValueReadable());
                    dptInit.setWritable(dp.isValueWritable());
                    dptInit.setGroupAddress(
                            new GroupAddress(Integer.parseInt(groupAddressByDatapointId.get(instanceId))));

                    object[1] = dptInit;
                    DatapointImpl dataPoint = (DatapointImpl) constructor.newInstance(object);

                    group.addFunction(dataPoint);
                    objectBroker.addObj(dataPoint, true);
                }
            } catch (Exception e) {
                e.printStackTrace();
            }

            group.addInstance(datapointById.get(instanceId), connector);
        }

        // recursively add more parts
        parseFunctionalView(concreteGroup, group, n, objectBroker, entityById, datapointById, knxConnector,
                groupAddressByDatapointId);
    }
}

From source file:com.eyeq.pivot4j.impl.PivotModelImpl.java

/**
 * @see com.eyeq.pivot4j.state.Configurable#restoreSettings(org.apache.commons.configuration.HierarchicalConfiguration)
 *///w  w w . ja v  a  2  s .  c  om
@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;
}

From source file:com.processpuzzle.application.domain.Application.java

@SuppressWarnings("unchecked")
private DataLoader instantitateDataLoader(String className, HierarchicalConfiguration dataLoaderConfig)
        throws ApplicationException {
    DataLoader dataLoader = null;//from   w w w.ja  v a2  s.  c  o m
    Constructor<DataLoader> dataLoaderConstructor;

    List<HierarchicalConfiguration> arguments = dataLoaderConfig
            .configurationsAt(INSTANTIATION_ARGUMENTS_SELECTOR);
    Class<?>[] parameterTypes = new Class[arguments.size()];
    Object[] parameterValues = new Object[arguments.size()];

    try {
        for (int j = 0; j < arguments.size(); j++) {
            String selectorBase = INSTANTIATION_ARGUMENTS_SELECTOR + PropertyContext.PROPERTY_ARRAY_BEGIN
                    + String.valueOf(j) + PropertyContext.PROPERTY_ARRAY_END;
            String typeSelector = selectorBase + PropertyContext.ATTRIBUTE_BEGIN
                    + PropertyContext.ATTRIBUTE_SIGNER + PARAMETER_TYPE_ELEMENT_NAME
                    + PropertyContext.ATTRIBUTE_END;
            String paremeterType = dataLoaderConfig.getString(typeSelector);
            parameterTypes[j] = Class.forName(paremeterType);

            //String nameSelector = selectorBase + PropertyContext.ATTRIBUTE_BEGIN + PropertyContext.ATTRIBUTE_SIGNER + PARAMETER_NAME_ELEMENT_NAME + PropertyContext.ATTRIBUTE_END;

            String parameterValue = dataLoaderConfig.getString(selectorBase);
            parameterValues[j] = parameterValue;
        }

        Class<DataLoader> dataLoaderClass = (Class<DataLoader>) Class.forName(className);
        dataLoaderConstructor = dataLoaderClass.getConstructor(parameterTypes);
        dataLoader = (DataLoader) dataLoaderConstructor.newInstance(parameterValues);
    } catch (SecurityException e) {
        throw new ApplicationStartException(this, e);
    } catch (NoSuchMethodException e) {
        throw new ApplicationStartException(this, e);
    } catch (IllegalArgumentException e) {
        throw new ApplicationStartException(this, e);
    } catch (InstantiationException e) {
        throw new ApplicationStartException(this, e);
    } catch (IllegalAccessException e) {
        throw new ApplicationStartException(this, e);
    } catch (InvocationTargetException e) {
        throw new ApplicationStartException(this, e);
    } catch (ClassNotFoundException e) {
        throw new ApplicationStartException(this, e);
    }

    return dataLoader;
}

From source file:com.houghtonassociates.bamboo.plugins.GerritRepositoryAdapter.java

@Override
public void populateFromConfig(HierarchicalConfiguration config) {
    super.populateFromConfig(config);

    hostname = StringUtils.trimToEmpty(config.getString(REPOSITORY_GERRIT_REPOSITORY_HOSTNAME));
    username = config.getString(REPOSITORY_GERRIT_USERNAME);
    userEmail = config.getString(REPOSITORY_GERRIT_EMAIL);
    sshKey = config.getString(REPOSITORY_GERRIT_SSH_KEY, "");
    sshPassphrase = encryptionService.decrypt(config.getString(REPOSITORY_GERRIT_SSH_PASSPHRASE));
    port = config.getInt(REPOSITORY_GERRIT_REPOSITORY_PORT, 29418);
    project = config.getString(REPOSITORY_GERRIT_PROJECT);

    String strDefBranch = config.getString(REPOSITORY_GERRIT_DEFAULT_BRANCH, "");
    String strCustBranch = config.getString(REPOSITORY_GERRIT_CUSTOM_BRANCH, "");

    if (strDefBranch.equals(MASTER_BRANCH.getName()) || strDefBranch.equals(ALL_BRANCH.getName())) {
        vcsBranch = new VcsBranchImpl(strDefBranch);
    } else {//www  . j  ava2 s.  c  o m
        vcsBranch = new VcsBranchImpl(strCustBranch);
    }

    useShallowClones = config.getBoolean(REPOSITORY_GERRIT_USE_SHALLOW_CLONES);
    useSubmodules = config.getBoolean(REPOSITORY_GERRIT_USE_SUBMODULES);
    commandTimeout = config.getInt(REPOSITORY_GERRIT_COMMAND_TIMEOUT, DEFAULT_COMMAND_TIMEOUT_IN_MINUTES);
    verboseLogs = config.getBoolean(REPOSITORY_GERRIT_VERBOSE_LOGS, false);

    String gitRepoUrl = "ssh://" + username + "@" + hostname + ":" + port + "/" + project;

    String tmpCP = config.getString(REPOSITORY_GERRIT_CONFIG_DIR);

    if (tmpCP == null || tmpCP.isEmpty()) {
        tmpCP = GerritService.SYSTEM_DIRECTORY + File.separator + GerritService.CONFIG_DIRECTORY;
    }

    relativeConfigPath = tmpCP.replace("\\", "/");

    absConfigPath = prepareConfigDir(relativeConfigPath).getAbsolutePath();

    String tmpSSHKFP = config.getString(REPOSITORY_GERRIT_SSH_KEY_FILE);

    if (tmpSSHKFP == null || tmpSSHKFP.isEmpty()) {
        tmpSSHKFP = GerritService.SYSTEM_DIRECTORY + File.separator + GerritService.CONFIG_DIRECTORY;
    }

    relativeSSHKeyFilePath = tmpSSHKFP.replace("\\", "/");

    String decryptedKey = encryptionService.decrypt(sshKey);

    sshKeyFile = prepareSSHKeyFile(relativeSSHKeyFilePath, decryptedKey);

    gc.setHost(hostname);
    gc.setPort(port);
    gc.setRepositoryUrl(gitRepoUrl);
    gc.setWorkingDirectory(absConfigPath);
    gc.setSshKeyFile(sshKeyFile);
    gc.setSshKey(decryptedKey);
    gc.setSshPassphrase(sshPassphrase);
    gc.setUsername(username);
    gc.setUserEmail(userEmail);
    gc.setUseShallowClones(useShallowClones);
    gc.setUseSubmodules(useSubmodules);
    gc.setVerboseLogs(verboseLogs);
    gc.setCommandTimeout(commandTimeout);

    try {
        initializeGerritService();
        if (this.isOnLocalAgent()) {
            if (isRemoteTriggeringReop()) {
                getGerritDAO().addListener(this);
            } else {
                getGerritDAO().removeListener(this);
            }
        }
    } catch (RepositoryException e) {
        log.error(e.getMessage());
    }
}

From source file:net.jradius.example.LocalUsersHandler.java

public void setConfig(ConfigurationItem cfg) {
    super.setConfig(cfg);
    HierarchicalConfiguration.Node root = cfg.getRoot();
    HierarchicalConfiguration xmlCfg = cfg.getXMLConfig();

    /*/* w  w w.  j  av a 2s  . c  o  m*/
     * Look for <users> ... </users> in the configuration
     */
    List usersList = root.getChildren("users");
    HierarchicalConfiguration.Node node;

    for (Iterator l = usersList.iterator(); l.hasNext();) {
        /*
         * Iterate the <user> ... </user> blocks
         */
        node = (HierarchicalConfiguration.Node) l.next();
        List children = node.getChildren("user");
        for (Iterator i = children.iterator(); i.hasNext();) {
            node = (HierarchicalConfiguration.Node) i.next();
            root = xmlCfg.getRoot();
            xmlCfg.setRoot(node);

            LocalUser user = new LocalUser();

            /*
             * A user is defined in the configuration with the following XML syntax example:
             * 
             * <users>
             *   <user username="test" password="test">
             *       Reply-Message = Hello test user!
             *   </user>
             * </users>
             * 
             * The contents of the <user>...</user> block are the attributes to use in the
             * AccessAccept reply.
             */
            user.username = xmlCfg.getString("[@username]");
            user.realm = xmlCfg.getString("[@realm]");
            user.password = xmlCfg.getString("[@password]");
            Object v = node.getValue();

            if (v != null) {
                user.attributes = v.toString();
            }

            RadiusLog.debug("        -> Configured local user: " + user.getUserName());
            users.put(user.getUserName(), user);
            xmlCfg.setRoot(root);
        }
    }
}

From source file:com.bytelightning.opensource.pokerface.PokerFace.java

/**
 * Configures all the needed components, but does not actually start the server.
 * @param config   Contains all information needed to fully wire up the http, https, and httpclient components of this reverse proxy.
 * @throws Exception   Yeah, a lot can go wrong here, but at least it will be caught immediately :-)
 *///  w  w  w .  jav  a2  s.  c  o  m
public void config(HierarchicalConfiguration config) throws Exception {
    List<HierarchicalConfiguration> lconf;
    HttpAsyncRequester executor = null;
    BasicNIOConnPool connPool = null;
    ObjectPool<ByteBuffer> byteBufferPool = null;
    LinkedHashMap<String, TargetDescriptor> mappings = null;
    ConcurrentMap<String, HttpHost> hosts = null;

    handlerRegistry = new UriHttpAsyncRequestHandlerMapper();

    // Initialize the keystore (if one was specified)
    KeyStore keystore = null;
    char[] keypass = null;
    String keystoreUri = config.getString("keystore");
    if ((keystoreUri != null) && (keystoreUri.trim().length() > 0)) {
        Path keystorePath = Utils.MakePath(keystoreUri);
        if (!Files.exists(keystorePath))
            throw new ConfigurationException("Keystore does not exist.");
        if (Files.isDirectory(keystorePath))
            throw new ConfigurationException("Keystore is not a file");
        String storepass = config.getString("storepass");
        if ((storepass != null) && "null".equals(storepass))
            storepass = null;
        keystore = KeyStore.getInstance(KeyStore.getDefaultType());
        try (InputStream keyStoreStream = Files.newInputStream(keystorePath)) {
            keystore.load(keyStoreStream, storepass == null ? null : storepass.trim().toCharArray());
        } catch (IOException ex) {
            Logger.error("Unable to load https server keystore from " + keystoreUri);
            return;
        }
        keypass = config.getString("keypass").trim().toCharArray();
    }

    // Wire up the listening reactor
    lconf = config.configurationsAt("server");
    if ((lconf == null) || (lconf.size() != 1))
        throw new ConfigurationException("One (and only one) server configuration element is allowed.");
    else {
        Builder builder = IOReactorConfig.custom();
        builder.setIoThreadCount(ComputeReactorProcessors(config.getDouble("server[@cpu]", 0.667)));
        builder.setSoTimeout(config.getInt("server[@soTimeout]", 0));
        builder.setSoLinger(config.getInt("server[@soLinger]", -1));
        builder.setSoReuseAddress(true);
        builder.setTcpNoDelay(false);
        builder.setSelectInterval(100);

        IOReactorConfig rconfig = builder.build();
        Logger.info("Configuring server with options: " + rconfig.toString());
        listeningReactor = new DefaultListeningIOReactor(rconfig);

        lconf = config.configurationsAt("server.listen");
        InetSocketAddress addr;
        boolean hasNonWildcardSecure = false;
        LinkedHashMap<SocketAddress, SSLContext> addrSSLContext = new LinkedHashMap<SocketAddress, SSLContext>();
        if ((lconf == null) || (lconf.size() == 0)) {
            addr = new InetSocketAddress("127.0.0.1", 8080);
            ListenerEndpoint ep = listeningReactor.listen(addr);
            Logger.warn("Configured " + ep.getAddress());
        } else {
            TrustManager[] trustManagers = null;
            KeyManagerFactory kmf = null;
            // Create all the specified listeners.
            for (HierarchicalConfiguration hc : lconf) {
                String addrStr = hc.getString("[@address]");
                if ((addrStr == null) || (addrStr.length() == 0))
                    addrStr = "0.0.0.0";
                String alias = hc.getString("[@alias]");
                int port = hc.getInt("[@port]", alias != null ? 443 : 80);
                addr = new InetSocketAddress(addrStr, port);
                ListenerEndpoint ep = listeningReactor.listen(addr);
                String protocol = hc.containsKey("[@protocol]") ? hc.getString("[@protocol]") : null;
                Boolean secure = hc.containsKey("[@secure]") ? hc.getBoolean("[@secure]") : null;
                if ((alias != null) && (secure == null))
                    secure = true;
                if ((protocol != null) && (secure == null))
                    secure = true;
                if ((secure != null) && secure) {
                    if (protocol == null)
                        protocol = "TLS";
                    if (keystore == null)
                        throw new ConfigurationException(
                                "An https listening socket was requested, but no keystore was specified.");
                    if (kmf == null) {
                        kmf = KeyManagerFactory.getInstance(KeyManagerFactory.getDefaultAlgorithm());
                        kmf.init(keystore, keypass);
                    }
                    // Are we going to trust all clients or just specific ones?
                    if (hc.getBoolean("[@trustAny]", true))
                        trustManagers = new TrustManager[] { new X509TrustAllManager() };
                    else {
                        TrustManagerFactory instance = TrustManagerFactory
                                .getInstance(TrustManagerFactory.getDefaultAlgorithm());
                        instance.init(keystore);
                        trustManagers = instance.getTrustManagers();
                    }
                    KeyManager[] keyManagers = kmf.getKeyManagers();
                    if (alias != null)
                        for (int i = 0; i < keyManagers.length; i++) {
                            if (keyManagers[i] instanceof X509ExtendedKeyManager)
                                keyManagers[i] = new PokerFaceKeyManager(alias,
                                        (X509ExtendedKeyManager) keyManagers[i]);
                        }
                    SSLContext sslCtx = SSLContext.getInstance(protocol);
                    sslCtx.init(keyManagers, trustManagers, new SecureRandom());
                    if (addr.getAddress().isAnyLocalAddress()) {
                        // This little optimization helps us respond faster for every connection as we don't have to extrapolate a local connection address to wild card.
                        for (Enumeration<NetworkInterface> en = NetworkInterface.getNetworkInterfaces(); en
                                .hasMoreElements();) {
                            NetworkInterface intf = en.nextElement();
                            for (Enumeration<InetAddress> enumIpAddr = intf.getInetAddresses(); enumIpAddr
                                    .hasMoreElements();) {
                                addr = new InetSocketAddress(enumIpAddr.nextElement(), port);
                                addrSSLContext.put(addr, sslCtx);
                            }
                        }
                    } else {
                        addrSSLContext.put(addr, sslCtx);
                        hasNonWildcardSecure = true;
                    }
                }
                Logger.warn("Configured " + (alias == null ? "" : (protocol + " on")) + ep.getAddress());
            }
        }
        // We will need an HTTP protocol processor for the incoming connections
        String serverAgent = config.getString("server.serverAgent", "PokerFace/" + Utils.Version);
        HttpProcessor inhttpproc = new ImmutableHttpProcessor(
                new HttpResponseInterceptor[] { new ResponseDateInterceptor(), new ResponseServer(serverAgent),
                        new ResponseContent(), new ResponseConnControl() });
        HttpAsyncService serviceHandler = new HttpAsyncService(inhttpproc, new DefaultConnectionReuseStrategy(),
                null, handlerRegistry, null) {
            public void exception(final NHttpServerConnection conn, final Exception cause) {
                Logger.warn(cause.getMessage());
                super.exception(conn, cause);
            }
        };
        if (addrSSLContext.size() > 0) {
            final SSLContext defaultCtx = addrSSLContext.values().iterator().next();
            final Map<SocketAddress, SSLContext> sslMap;
            if ((!hasNonWildcardSecure) || (addrSSLContext.size() == 1))
                sslMap = null;
            else
                sslMap = addrSSLContext;
            listeningDispatcher = new DefaultHttpServerIODispatch(serviceHandler,
                    new SSLNHttpServerConnectionFactory(defaultCtx, null, ConnectionConfig.DEFAULT) {
                        protected SSLIOSession createSSLIOSession(IOSession iosession, SSLContext sslcontext,
                                SSLSetupHandler sslHandler) {
                            SSLIOSession retVal;
                            SSLContext sktCtx = sslcontext;
                            if (sslMap != null) {
                                SocketAddress la = iosession.getLocalAddress();
                                if (la != null) {
                                    sktCtx = sslMap.get(la);
                                    if (sktCtx == null)
                                        sktCtx = sslcontext;
                                }
                                retVal = new SSLIOSession(iosession, SSLMode.SERVER, sktCtx, sslHandler);
                            } else
                                retVal = super.createSSLIOSession(iosession, sktCtx, sslHandler);
                            if (sktCtx != null)
                                retVal.setAttribute("com.bytelightning.opensource.pokerface.secure", true);
                            return retVal;
                        }
                    });
        } else
            listeningDispatcher = new DefaultHttpServerIODispatch(serviceHandler, ConnectionConfig.DEFAULT);
    }

    // Configure the httpclient reactor that will be used to do reverse proxing to the specified targets.
    lconf = config.configurationsAt("targets");
    if ((lconf != null) && (lconf.size() > 0)) {
        HierarchicalConfiguration conf = lconf.get(0);
        Builder builder = IOReactorConfig.custom();
        builder.setIoThreadCount(ComputeReactorProcessors(config.getDouble("targets[@cpu]", 0.667)));
        builder.setSoTimeout(conf.getInt("targets[@soTimeout]", 0));
        builder.setSoLinger(config.getInt("targets[@soLinger]", -1));
        builder.setConnectTimeout(conf.getInt("targets[@connectTimeout]", 0));
        builder.setSoReuseAddress(true);
        builder.setTcpNoDelay(false);
        connectingReactor = new DefaultConnectingIOReactor(builder.build());

        final int bufferSize = conf.getInt("targets[@bufferSize]", 1024) * 1024;
        byteBufferPool = new SoftReferenceObjectPool<ByteBuffer>(new BasePooledObjectFactory<ByteBuffer>() {
            @Override
            public ByteBuffer create() throws Exception {
                return ByteBuffer.allocateDirect(bufferSize);
            }

            @Override
            public PooledObject<ByteBuffer> wrap(ByteBuffer buffer) {
                return new DefaultPooledObject<ByteBuffer>(buffer);
            }
        });

        KeyManager[] keyManagers = null;
        TrustManager[] trustManagers = null;

        if (keystore != null) {
            KeyManagerFactory kmf = KeyManagerFactory.getInstance(KeyManagerFactory.getDefaultAlgorithm());
            kmf.init(keystore, keypass);
            keyManagers = kmf.getKeyManagers();
        }
        // Will the httpclient's trust any remote target, or only specific ones.
        if (conf.getBoolean("targets[@trustAny]", false))
            trustManagers = new TrustManager[] { new X509TrustAllManager() };
        else if (keystore != null) {
            TrustManagerFactory instance = TrustManagerFactory
                    .getInstance(TrustManagerFactory.getDefaultAlgorithm());
            instance.init(keystore);
            trustManagers = instance.getTrustManagers();
        }
        SSLContext clientSSLContext = SSLContext.getInstance(conf.getString("targets[@protocol]", "TLS"));
        clientSSLContext.init(keyManagers, trustManagers, new SecureRandom());

        // Setup an SSL capable connection pool for the httpclients.
        connPool = new BasicNIOConnPool(connectingReactor,
                new BasicNIOConnFactory(clientSSLContext, null, ConnectionConfig.DEFAULT),
                conf.getInt("targets[@connectTimeout]", 0));
        connPool.setMaxTotal(conf.getInt("targets[@connMaxTotal]", 1023));
        connPool.setDefaultMaxPerRoute(conf.getInt("targets[@connMaxPerRoute]", 1023));

        // Set up HTTP protocol processor for outgoing connections
        String userAgent = conf.getString("targets.userAgent", "PokerFace/" + Utils.Version);
        HttpProcessor outhttpproc = new ImmutableHttpProcessor(new HttpRequestInterceptor[] {
                new RequestContent(), new RequestTargetHost(), new RequestConnControl(),
                new RequestUserAgent(userAgent), new RequestExpectContinue(true) });
        executor = new HttpAsyncRequester(outhttpproc, new DefaultConnectionReuseStrategy());

        // Now set up all the configured targets.
        mappings = new LinkedHashMap<String, TargetDescriptor>();
        hosts = new ConcurrentHashMap<String, HttpHost>();
        String[] scheme = { null };
        String[] host = { null };
        int[] port = { 0 };
        String[] path = { null };
        int[] stripPrefixCount = { 0 };
        for (HierarchicalConfiguration targetConfig : conf.configurationsAt("target")) {
            String match = targetConfig.getString("[@pattern]");
            if ((match == null) || (match.trim().length() < 1)) {
                Logger.error("Unable to configure target;  Invalid url match pattern");
                continue;
            }
            String key = RequestForTargetConsumer.UriToTargetKey(targetConfig.getString("[@url]"), scheme, host,
                    port, path, stripPrefixCount);
            if (key == null) {
                Logger.error("Unable to configure target");
                continue;
            }
            HttpHost targetHost = hosts.get(key);
            if (targetHost == null) {
                targetHost = new HttpHost(host[0], port[0], scheme[0]);
                hosts.put(key, targetHost);
            }
            TargetDescriptor desc = new TargetDescriptor(targetHost, path[0], stripPrefixCount[0]);
            mappings.put(match, desc);
        }
        connectionDispatcher = new DefaultHttpClientIODispatch(new HttpAsyncRequestExecutor(),
                ConnectionConfig.DEFAULT);
    }
    // Allocate the script map which will be populated by it's own executor thread.
    if (config.containsKey("scripts.rootDirectory")) {
        Path tmp = Utils.MakePath(config.getProperty("scripts.rootDirectory"));
        if (!Files.exists(tmp))
            throw new FileNotFoundException("Scripts directory does not exist.");
        if (!Files.isDirectory(tmp))
            throw new FileNotFoundException("'scripts' path is not a directory.");
        scripts = new ConcurrentSkipListMap<String, ScriptObjectMirror>();
        boolean watch = config.getBoolean("scripts.dynamicWatch", false);
        List<Path> jsLibs;
        Object prop = config.getProperty("scripts.library");
        if (prop != null) {
            jsLibs = new ArrayList<Path>();
            if (prop instanceof Collection<?>) {
                @SuppressWarnings("unchecked")
                Collection<Object> oprop = (Collection<Object>) prop;
                for (Object obj : oprop)
                    jsLibs.add(Utils.MakePath(obj));
            } else {
                jsLibs.add(Utils.MakePath(prop));
            }
        } else
            jsLibs = null;

        lconf = config.configurationsAt("scripts.scriptConfig");
        if (lconf != null) {
            if (lconf.size() > 1)
                throw new ConfigurationException("Only one scriptConfig element is allowed.");
            if (lconf.size() == 0)
                lconf = null;
        }

        HierarchicalConfiguration scriptConfig;
        if (lconf == null)
            scriptConfig = new HierarchicalConfiguration();
        else
            scriptConfig = lconf.get(0);
        scriptConfig.setProperty("pokerface.scripts.rootDirectory", tmp.toString());

        configureScripts(jsLibs, scriptConfig, tmp, watch);
        if (watch)
            ScriptDirectoryWatcher = new DirectoryWatchService();
    }

    // Configure the static file directory (if any)
    Path staticFilesPath = null;
    if (config.containsKey("files.rootDirectory")) {
        Path tmp = Utils.MakePath(config.getProperty("files.rootDirectory"));
        if (!Files.exists(tmp))
            throw new FileNotFoundException("Files directory does not exist.");
        if (!Files.isDirectory(tmp))
            throw new FileNotFoundException("'files' path is not a directory.");
        staticFilesPath = tmp;
        List<HierarchicalConfiguration> mimeEntries = config.configurationsAt("files.mime-entry");
        if (mimeEntries != null) {
            for (HierarchicalConfiguration entry : mimeEntries) {
                entry.setDelimiterParsingDisabled(true);
                String type = entry.getString("[@type]", "").trim();
                if (type.length() == 0)
                    throw new ConfigurationException("Invalid mime type entry");
                String extensions = entry.getString("[@extensions]", "").trim();
                if (extensions.length() == 0)
                    throw new ConfigurationException("Invalid mime extensions for: " + type);
                ScriptHelperImpl.AddMimeEntry(type, extensions);
            }
        }
    }

    handlerRegistry.register("/*",
            new RequestHandler(executor, connPool, byteBufferPool, staticFilesPath, mappings,
                    scripts != null ? Collections.unmodifiableNavigableMap(scripts) : null,
                    config.getBoolean("scripts.allowScriptsToSpecifyDynamicHosts", false) ? hosts : null));
}

From source file:io.datalayer.conf.XmlConfigurationTest.java

/**
 * Tests if reloads are recognized by configurationAt().
 *//*from w  ww . jav a  2 s . c o m*/
@Test
public void testConfigurationAtWithReload() throws ConfigurationException {
    XMLConfiguration c = setUpReloadTest();
    HierarchicalConfiguration sub = c.configurationAt("test(0)");
    assertEquals("New value not read", "newValue", sub.getString("entity"));
}