Example usage for org.apache.commons.configuration PropertiesConfiguration setProperty

List of usage examples for org.apache.commons.configuration PropertiesConfiguration setProperty

Introduction

In this page you can find the example usage for org.apache.commons.configuration PropertiesConfiguration setProperty.

Prototype

public void setProperty(String key, Object value) 

Source Link

Document

Sets a new value for the specified property.

Usage

From source file:it.geosolutions.opensdi2.configurations.dao.PropertiesDAO.java

@Override
public boolean merge(OSDIConfiguration updatedConfig)
        throws OSDIConfigurationNotFoundException, OSDIConfigurationInternalErrorException {
    boolean outcome = false;
    File configFile = searchConfigurationFile(updatedConfig.getScopeID(), updatedConfig.getInstanceID());
    PropertiesConfiguration oldConfig = loadConfigurationInstance(configFile);
    OSDIConfigurationKVP updatedConfigKVP = (OSDIConfigurationKVP) updatedConfig;
    Iterator<String> iter = updatedConfigKVP.getAllKeys().iterator();
    String tmpKey = "";
    while (iter.hasNext()) {
        tmpKey = iter.next();/*  w  w w  .  ja v a 2s .c o  m*/
        Object newValue = updatedConfigKVP.getValue(tmpKey);
        Object oldValue = oldConfig.getProperty(tmpKey);
        if (newValue != null && !newValue.equals(oldValue)) {
            oldConfig.setProperty(tmpKey, newValue);
            outcome = true;
        }
    }
    try {
        oldConfig.save();
    } catch (ConfigurationException e) {
        throw new OSDIConfigurationInternalErrorException(
                "Error occurred while saving the updated configuration, exception msg is: '" + e.getMessage()
                        + "'");
    }
    return outcome;
}

From source file:com.linkedin.pinot.core.startree.StarTreeSegmentCreator.java

/** Constructs the segment metadata file, and writes in outputDir */
private void writeMetadata(File outputDir, int totalDocs, int totalAggDocs, boolean starTreeEnabled)
        throws ConfigurationException {
    final PropertiesConfiguration properties = new PropertiesConfiguration(
            new File(outputDir, V1Constants.MetadataKeys.METADATA_FILE_NAME));

    properties.setProperty(SEGMENT_NAME, segmentName);
    properties.setProperty(TABLE_NAME, config.getTableName());
    properties.setProperty(DIMENSIONS, config.getDimensions());
    properties.setProperty(METRICS, config.getMetrics());
    properties.setProperty(TIME_COLUMN_NAME, config.getTimeColumnName());
    properties.setProperty(TIME_INTERVAL, "not_there");
    properties.setProperty(SEGMENT_TOTAL_DOCS, String.valueOf(totalDocs));
    properties.setProperty(SEGMENT_TOTAL_AGGREGATE_DOCS, String.valueOf(totalAggDocs));

    // StarTree//from  w  w  w  .  ja  va  2s .com
    Joiner csv = Joiner.on(",");
    properties.setProperty(STAR_TREE_ENABLED, String.valueOf(starTreeEnabled));
    properties.setProperty(SPLIT_ORDER, csv.join(splitOrder));
    properties.setProperty(SPLIT_EXCLUDES, csv.join(starTreeIndexSpec.getSplitExcludes()));
    properties.setProperty(MAX_LEAF_RECORDS, starTreeIndexSpec.getMaxLeafRecords());
    properties.setProperty(EXCLUDED_DIMENSIONS, csv.join(starTreeIndexSpec.getExcludedDimensions()));

    String timeColumn = config.getTimeColumnName();
    if (columnInfo.get(timeColumn) != null) {
        properties.setProperty(SEGMENT_START_TIME, columnInfo.get(timeColumn).getMin());
        properties.setProperty(SEGMENT_END_TIME, columnInfo.get(timeColumn).getMax());
        properties.setProperty(TIME_UNIT, config.getTimeUnitForSegment());
    }

    if (config.containsCustomPropertyWithKey(SEGMENT_START_TIME)) {
        properties.setProperty(SEGMENT_START_TIME, config.getStartTime());
    }
    if (config.containsCustomPropertyWithKey(SEGMENT_END_TIME)) {
        properties.setProperty(SEGMENT_END_TIME, config.getStartTime());
    }
    if (config.containsCustomPropertyWithKey(TIME_UNIT)) {
        properties.setProperty(TIME_UNIT, config.getTimeUnitForSegment());
    }

    for (final String key : config.getAllCustomKeyValuePair().keySet()) {
        properties.setProperty(key, config.getAllCustomKeyValuePair().get(key));
    }

    for (final String column : columnInfo.keySet()) {
        final ColumnIndexCreationInfo columnIndexCreationInfo = columnInfo.get(column);
        final int distinctValueCount = columnIndexCreationInfo.getDistinctValueCount();
        properties.setProperty(V1Constants.MetadataKeys.Column.getKeyFor(column, CARDINALITY),
                String.valueOf(distinctValueCount));
        properties.setProperty(V1Constants.MetadataKeys.Column.getKeyFor(column, TOTAL_DOCS),
                String.valueOf(totalDocs));
        properties.setProperty(V1Constants.MetadataKeys.Column.getKeyFor(column, DATA_TYPE),
                schema.getFieldSpecFor(column).getDataType().toString());
        properties.setProperty(V1Constants.MetadataKeys.Column.getKeyFor(column, BITS_PER_ELEMENT),
                String.valueOf(SingleValueUnsortedForwardIndexCreator.getNumOfBits(distinctValueCount)));

        properties.setProperty(V1Constants.MetadataKeys.Column.getKeyFor(column, DICTIONARY_ELEMENT_SIZE),
                String.valueOf(dictionaryCreatorMap.get(column).getStringColumnMaxLength()));

        properties.setProperty(V1Constants.MetadataKeys.Column.getKeyFor(column, COLUMN_TYPE),
                String.valueOf(schema.getFieldSpecFor(column).getFieldType().toString()));

        properties.setProperty(V1Constants.MetadataKeys.Column.getKeyFor(column, IS_SORTED),
                String.valueOf(columnIndexCreationInfo.isSorted()));

        properties.setProperty(V1Constants.MetadataKeys.Column.getKeyFor(column, HAS_NULL_VALUE),
                String.valueOf(columnIndexCreationInfo.hasNulls()));
        properties.setProperty(
                V1Constants.MetadataKeys.Column.getKeyFor(column,
                        V1Constants.MetadataKeys.Column.HAS_DICTIONARY),
                String.valueOf(columnIndexCreationInfo.isCreateDictionary()));

        properties.setProperty(V1Constants.MetadataKeys.Column.getKeyFor(column, HAS_INVERTED_INDEX),
                String.valueOf(true));

        properties.setProperty(V1Constants.MetadataKeys.Column.getKeyFor(column, IS_SINGLE_VALUED),
                String.valueOf(schema.getFieldSpecFor(column).isSingleValueField()));

        properties.setProperty(V1Constants.MetadataKeys.Column.getKeyFor(column, MAX_MULTI_VALUE_ELEMTS),
                String.valueOf(columnIndexCreationInfo.getMaxNumberOfMutiValueElements()));

        properties.setProperty(V1Constants.MetadataKeys.Column.getKeyFor(column, TOTAL_NUMBER_OF_ENTRIES),
                String.valueOf(columnIndexCreationInfo.getTotalNumberOfEntries()));

    }

    properties.save();
}

From source file:fr.inria.atlanmod.neoemf.data.blueprints.BlueprintsPersistenceBackendFactory.java

private PropertiesConfiguration getOrCreateBlueprintsConfiguration(File directory, Map<?, ?> options)
        throws InvalidDataStoreException {
    PropertiesConfiguration configuration;

    // Try to load previous configurations
    Path path = Paths.get(directory.getAbsolutePath()).resolve(BLUEPRINTS_CONFIG_FILE);
    try {//from ww  w  .  j  a v  a  2 s  .  co m
        configuration = new PropertiesConfiguration(path.toFile());
    } catch (ConfigurationException e) {
        throw new InvalidDataStoreException(e);
    }

    // Initialize value if the config file has just been created
    if (!configuration.containsKey(BlueprintsResourceOptions.GRAPH_TYPE)) {
        configuration.setProperty(BlueprintsResourceOptions.GRAPH_TYPE,
                BlueprintsResourceOptions.GRAPH_TYPE_DEFAULT);
    } else if (options.containsKey(BlueprintsResourceOptions.GRAPH_TYPE)) {
        // The file already existed, check that the issued options are not conflictive
        String savedGraphType = configuration.getString(BlueprintsResourceOptions.GRAPH_TYPE);
        String issuedGraphType = options.get(BlueprintsResourceOptions.GRAPH_TYPE).toString();
        if (!Objects.equals(savedGraphType, issuedGraphType)) {
            NeoLogger.error("Unable to create graph as type {0}, expected graph type was {1})", issuedGraphType,
                    savedGraphType);
            throw new InvalidDataStoreException("Unable to create graph as type " + issuedGraphType
                    + ", expected graph type was " + savedGraphType + ')');
        }
    }

    // Copy the options to the configuration
    for (Entry<?, ?> e : options.entrySet()) {
        configuration.setProperty(e.getKey().toString(), e.getValue().toString());
    }

    // Check we have a valid graph type, it is needed to get the graph name
    String graphType = configuration.getString(BlueprintsResourceOptions.GRAPH_TYPE);
    if (isNull(graphType)) {
        throw new InvalidDataStoreException("Graph type is undefined for " + directory.getAbsolutePath());
    }

    // Define the configuration
    String[] segments = graphType.split("\\.");
    if (segments.length >= 2) {
        String graphName = segments[segments.length - 2];
        String upperCaseGraphName = Character.toUpperCase(graphName.charAt(0)) + graphName.substring(1);
        String configClassName = MessageFormat.format("InternalBlueprints{0}Configuration", upperCaseGraphName);
        String configClassQualifiedName = MessageFormat
                .format("fr.inria.atlanmod.neoemf.data.blueprints.{0}.config.{1}", graphName, configClassName);

        try {
            ClassLoader classLoader = BlueprintsPersistenceBackendFactory.class.getClassLoader();
            Class<?> configClass = classLoader.loadClass(configClassQualifiedName);
            Method configClassInstanceMethod = configClass.getMethod("getInstance");
            InternalBlueprintsConfiguration blueprintsConfig = (InternalBlueprintsConfiguration) configClassInstanceMethod
                    .invoke(configClass);
            blueprintsConfig.putDefaultConfiguration(configuration, directory);
        } catch (ClassNotFoundException e) {
            NeoLogger.warn(e, "Unable to find the configuration class {0}", configClassQualifiedName);
        } catch (NoSuchMethodException e) {
            NeoLogger.warn(e, "Unable to find configuration methods in class {0}", configClassName);
        } catch (InvocationTargetException | IllegalAccessException e) {
            NeoLogger.warn(e, "An error occurs during the execution of a configuration method");
        }
    } else {
        NeoLogger.warn("Unable to compute graph type name from {0}", graphType);
    }

    return configuration;
}

From source file:eu.tango.energymodeller.energypredictor.AveragePowerEnergyPredictor.java

/**
 * This creates a new average power energy predictor. The predictor when
 * running takes the last power reading and makes the assumption no change
 * will occur. An observation time window is used for taking the measurement,
 * which is set via a configuration file.
 */// ww w  .j a v  a  2 s . c  o m
public AveragePowerEnergyPredictor() {
    try {
        if (database == null) {
            database = new DefaultDatabaseConnector();
        }
        PropertiesConfiguration config;
        if (new File(CONFIG_FILE).exists()) {

            config = new PropertiesConfiguration(CONFIG_FILE);
        } else {
            config = new PropertiesConfiguration();
            config.setFile(new File(CONFIG_FILE));
        }
        config.setAutoSave(true); //This will save the configuration file back to disk. In case the defaults need setting.
        powerObservationTimeMin = config.getInt(
                "energy.modeller.energy.predictor.cpu.utilisation.observe_time.min", powerObservationTimeMin);
        config.setProperty("energy.modeller.energy.predictor.cpu.utilisation.observe_time.min",
                powerObservationTimeMin);
        powerObservationTimeSec = config.getInt(
                "energy.modeller.energy.predictor.cpu.utilisation.observe_time.sec", powerObservationTimeSec);
        config.setProperty("energy.modeller.energy.predictor.cpu.utilisation.observe_time.sec",
                powerObservationTimeSec);
        observationTime = powerObservationTimeSec + (int) TimeUnit.MINUTES.toSeconds(powerObservationTimeMin);
    } catch (ConfigurationException ex) {
        Logger.getLogger(AveragePowerEnergyPredictor.class.getName()).log(Level.SEVERE,
                "The average power energy predictor failed to initialise", ex);
    }
}

From source file:eu.tango.energymodeller.energypredictor.AbstractEnergyPredictor.java

/**
 * This takes the settings and reads them into memory and sets defaults as
 * needed.//from  w ww  .ja va  2  s . c om
 *
 * @param config The settings to read.
 */
private void readSettings(PropertiesConfiguration config) {
    String workloadPredictorStr = config.getString("energy.modeller.energy.predictor.workload.predictor",
            "CpuRecentHistoryWorkloadPredictor");
    config.setProperty("energy.modeller.energy.predictor.workload.predictor", workloadPredictorStr);
    setWorkloadPredictor(workloadPredictorStr);
    defaultAssumedCpuUsage = config.getDouble("energy.modeller.energy.predictor.default_load",
            defaultAssumedCpuUsage);
    config.setProperty("energy.modeller.energy.predictor.default_load", defaultAssumedCpuUsage);
    defaultAssumedAcceleratorUsage = config.getDouble("energy.modeller.energy.predictor.default_load_acc",
            defaultAssumedAcceleratorUsage);
    config.setProperty("energy.modeller.energy.predictor.default_load_acc", defaultAssumedAcceleratorUsage);
    String shareRule = config.getString("energy.modeller.energy.predictor.share_rule",
            "DefaultEnergyShareRule");
    config.setProperty("energy.modeller.energy.predictor.share_rule", shareRule);
    setEnergyShareRule(shareRule);
    considerIdleEnergy = config.getBoolean("energy.modeller.energy.predictor.consider_idle_energy",
            considerIdleEnergy);
    config.setProperty("energy.modeller.energy.predictor.consider_idle_energy", considerIdleEnergy);
    defaultPowerOverheadPerHost = config.getDouble("energy.modeller.energy.predictor.overheadPerHostInWatts",
            defaultPowerOverheadPerHost);
    config.setProperty("energy.modeller.energy.predictor.overheadPerHostInWatts", defaultPowerOverheadPerHost);
    if (defaultAssumedCpuUsage == -1) {
        String dataSrcStr = config.getString("energy.modeller.energy.predictor.datasource",
                "SlurmDataSourceAdaptor");
        config.setProperty("energy.modeller.energy.predictor.datasource", dataSrcStr);
        setDataSource(dataSrcStr);
    }
}

From source file:eu.artist.methodology.mpt.webapp.config.ListFileHandlerBean.java

public void save() throws IOException {

    String path_to_properties_file = getMptProperties().getProperty("path_to_reports") + "\\"
            + CurrentSession.getUserName() + "\\mpt" + CurrentSession.getUserName() + ".properties";

    checkPropertiesFile(path_to_properties_file);

    logger.debug("Path to properties file is " + path_to_properties_file);

    try {// w w  w  .  j  a  v a  2  s .c  o m

        File f = new File(path_to_properties_file);

        URL url = f.toURI().toURL();

        logger.debug("File URL is " + url.toString());

        logger.info("Configuration saved");
        logger.debug("Selected file is " + selectedFile);
        PropertiesConfiguration config = new PropertiesConfiguration(url);

        String chosenButton = CurrentSession.getExternalContext().getRequestParameterMap().get("button");
        String propertyToSet = null;

        if ("mat".equalsIgnoreCase(chosenButton)) {
            propertyToSet = "mat_report";
        } else if ("tft".equalsIgnoreCase(chosenButton)) {
            propertyToSet = "tft_report";
        } else if ("bft".equalsIgnoreCase(chosenButton)) {
            propertyToSet = "bft_report";
        } else if ("mig".equalsIgnoreCase(chosenButton)) {
            propertyToSet = "mig_report";
        }

        config.setProperty(propertyToSet, "\\" + selectedFile);
        config.save();

        FacesContext.getCurrentInstance().addMessage(null, new FacesMessage("Configuration saved"));

    } catch (Exception e) {

        FacesContext.getCurrentInstance().addMessage(null, new FacesMessage("Configuration failed"));

        logger.error("Configuration not saved");

        e.printStackTrace();

    }
}

From source file:cross.Factory.java

/**
 * Write current configuration to file./*www  .j  a v  a 2  s . co m*/
 *
 * @param filename the filename to use
 * @param d the date stamp to use
 */
@Override
public void dumpConfig(final String filename, final Date d) {
    //retrieve global, joint configuration
    final Configuration cfg = getConfiguration();
    //retrieve pipeline.properties location
    String configFile = cfg.getString("pipeline.properties");
    if (configFile != null) {
        final File pipelinePropertiesFile = new File(configFile);
        //resolve and retrieve pipeline.xml location
        final File pipelineXml;
        try {
            File configBasedir = pipelinePropertiesFile.getParentFile();
            String pipelineLocation = cfg.getString("pipeline.xml").replace("config.basedir",
                    configBasedir.getAbsolutePath());
            pipelineLocation = pipelineLocation.substring("file:".length());
            pipelineXml = new File(pipelineLocation);
            //setup output location
            final File location = new File(FileTools.prependDefaultDirsWithPrefix("", Factory.class, d),
                    filename);
            //location for pipeline.properties dump
            final File pipelinePropertiesFileDump = new File(location.getParentFile(),
                    pipelinePropertiesFile.getName());

            PropertiesConfiguration pipelineProperties = new PropertiesConfiguration(pipelinePropertiesFile);
            PropertiesConfiguration newPipelineProperties = new PropertiesConfiguration(
                    pipelinePropertiesFileDump);
            //copy configuration to dump configuration
            newPipelineProperties.copy(pipelineProperties);
            //correct pipeline.xml location
            newPipelineProperties.setProperty("pipeline.xml",
                    "file:${config.basedir}/" + pipelineXml.getName());
            newPipelineProperties.save();
            //copy pipeline.xml to dump location
            FileUtils.copyFile(pipelineXml, new File(location.getParentFile(), pipelineXml.getName()));
            if (cfg.containsKey("configLocation")) {
                File configLocation = new File(URI.create(cfg.getString("configLocation")));
                File configLocationNew = new File(location.getParentFile(), configLocation.getName());
                FileUtils.copyFile(configLocation, configLocationNew);
            }
            LoggerFactory.getLogger(Factory.class).error("Saving configuration to: ");
            LoggerFactory.getLogger(Factory.class).error("{}", location.getAbsolutePath());
            saveConfiguration(cfg, location);
        } catch (IOException | ConfigurationException ex) {
            LoggerFactory.getLogger(Factory.class).error("{}", ex);
            //            } catch (URISyntaxException ex) {
            //                Factory.getInstance().log.error("{}", ex);
        }
    } else {
        LoggerFactory.getLogger(Factory.class)
                .warn("Can not save configuration, no pipeline properties file given!");
    }
}

From source file:fr.inria.atlanmod.neoemf.graph.blueprints.datastore.BlueprintsPersistenceBackendFactory.java

@Override
public BlueprintsPersistenceBackend createPersistentBackend(File file, Map<?, ?> options)
        throws InvalidDataStoreException {
    BlueprintsPersistenceBackend graphDB = null;
    PropertiesConfiguration neoConfig = null;
    PropertiesConfiguration configuration = null;
    try {/*  w  w  w .j  a va  2  s  .c om*/
        // Try to load previous configurations
        Path path = Paths.get(file.getAbsolutePath()).resolve(CONFIG_FILE);
        try {
            configuration = new PropertiesConfiguration(path.toFile());
        } catch (ConfigurationException e) {
            throw new InvalidDataStoreException(e);
        }
        // Initialize value if the config file has just been created
        if (!configuration.containsKey(BlueprintsResourceOptions.OPTIONS_BLUEPRINTS_GRAPH_TYPE)) {
            configuration.setProperty(BlueprintsResourceOptions.OPTIONS_BLUEPRINTS_GRAPH_TYPE,
                    BlueprintsResourceOptions.OPTIONS_BLUEPRINTS_GRAPH_TYPE_DEFAULT);
        } else if (options.containsKey(BlueprintsResourceOptions.OPTIONS_BLUEPRINTS_GRAPH_TYPE)) {
            // The file already existed, check that the issued options
            // are not conflictive
            String savedGraphType = configuration
                    .getString(BlueprintsResourceOptions.OPTIONS_BLUEPRINTS_GRAPH_TYPE);
            String issuedGraphType = options.get(BlueprintsResourceOptions.OPTIONS_BLUEPRINTS_GRAPH_TYPE)
                    .toString();
            if (!savedGraphType.equals(issuedGraphType)) {
                NeoLogger.log(NeoLogger.SEVERITY_ERROR, "Unable to create graph as type " + issuedGraphType
                        + ", expected graph type was " + savedGraphType + ")");
                throw new InvalidDataStoreException("Unable to create graph as type " + issuedGraphType
                        + ", expected graph type was " + savedGraphType + ")");
            }
        }

        // Copy the options to the configuration
        for (Entry<?, ?> e : options.entrySet()) {
            configuration.setProperty(e.getKey().toString(), e.getValue().toString());
        }

        // Check we have a valid graph type, it is needed to get the
        // graph name
        String graphType = configuration.getString(BlueprintsResourceOptions.OPTIONS_BLUEPRINTS_GRAPH_TYPE);
        if (graphType == null) {
            throw new InvalidDataStoreException("Graph type is undefined for " + file.getAbsolutePath());
        }

        String[] segments = graphType.split("\\.");
        if (segments.length >= 2) {
            String graphName = segments[segments.length - 2];
            String upperCaseGraphName = Character.toUpperCase(graphName.charAt(0)) + graphName.substring(1);
            String configClassQualifiedName = MessageFormat.format(
                    "fr.inria.atlanmod.neoemf.graph.blueprints.{0}.config.Blueprints{1}Config", graphName,
                    upperCaseGraphName);
            try {
                ClassLoader classLoader = BlueprintsPersistenceBackendFactory.class.getClassLoader();
                Class<?> configClass = classLoader.loadClass(configClassQualifiedName);
                Field configClassInstanceField = configClass.getField("eINSTANCE");
                AbstractBlueprintsConfig configClassInstance = (AbstractBlueprintsConfig) configClassInstanceField
                        .get(configClass);
                Method configMethod = configClass.getMethod("putDefaultConfiguration", Configuration.class,
                        File.class);
                configMethod.invoke(configClassInstance, configuration, file);
                Method setGlobalSettingsMethod = configClass.getMethod("setGlobalSettings");
                setGlobalSettingsMethod.invoke(configClassInstance);
            } catch (ClassNotFoundException e1) {
                NeoLogger.log(NeoLogger.SEVERITY_WARNING,
                        "Unable to find the configuration class " + configClassQualifiedName);
                e1.printStackTrace();
            } catch (NoSuchFieldException e2) {
                NeoLogger.log(NeoLogger.SEVERITY_WARNING,
                        MessageFormat.format(
                                "Unable to find the static field eINSTANCE in class Blueprints{0}Config",
                                upperCaseGraphName));
                e2.printStackTrace();
            } catch (NoSuchMethodException e3) {
                NeoLogger.log(NeoLogger.SEVERITY_ERROR,
                        MessageFormat.format(
                                "Unable to find configuration methods in class Blueprints{0}Config",
                                upperCaseGraphName));
                e3.printStackTrace();
            } catch (InvocationTargetException e4) {
                NeoLogger.log(NeoLogger.SEVERITY_ERROR, MessageFormat.format(
                        "An error occured during the exection of a configuration method", upperCaseGraphName));
                e4.printStackTrace();
            } catch (IllegalAccessException e5) {
                NeoLogger.log(NeoLogger.SEVERITY_ERROR, MessageFormat.format(
                        "An error occured during the exection of a configuration method", upperCaseGraphName));
                e5.printStackTrace();
            }
        } else {
            NeoLogger.log(NeoLogger.SEVERITY_WARNING, "Unable to compute graph type name from " + graphType);
        }

        Graph baseGraph = null;
        try {
            baseGraph = GraphFactory.open(configuration);
        } catch (RuntimeException e) {
            throw new InvalidDataStoreException(e);
        }
        if (baseGraph instanceof KeyIndexableGraph) {
            graphDB = new BlueprintsPersistenceBackend((KeyIndexableGraph) baseGraph);
        } else {
            NeoLogger.log(NeoLogger.SEVERITY_ERROR,
                    "Graph type " + file.getAbsolutePath() + " does not support Key Indices");
            throw new InvalidDataStoreException(
                    "Graph type " + file.getAbsolutePath() + " does not support Key Indices");
        }
        // Save the neoconfig file
        Path neoConfigPath = Paths.get(file.getAbsolutePath()).resolve(NEO_CONFIG_FILE);
        try {
            neoConfig = new PropertiesConfiguration(neoConfigPath.toFile());
        } catch (ConfigurationException e) {
            throw new InvalidDataStoreException(e);
        }
        if (!neoConfig.containsKey(BACKEND_PROPERTY)) {
            neoConfig.setProperty(BACKEND_PROPERTY, BLUEPRINTS_BACKEND);
        }
    } finally {
        if (configuration != null) {
            try {
                configuration.save();
            } catch (ConfigurationException e) {
                // Unable to save configuration, supposedly it's a minor error,
                // so we log it without rising an exception
                NeoLogger.log(NeoLogger.SEVERITY_ERROR, e);
            }
        }
        if (neoConfig != null) {
            try {
                neoConfig.save();
            } catch (ConfigurationException e) {
                NeoLogger.log(NeoLogger.SEVERITY_ERROR, e);
            }
        }
    }
    return graphDB;
}

From source file:fr.insalyon.creatis.vip.vipcoworkapplet.Cowork.java

/** Initializes the applet Main */
@Override// w w w.  j a v  a 2 s  .co  m
public void init() {
    /* Set the Nimbus look and feel */
    //<editor-fold defaultstate="collapsed" desc=" Look and feel setting code (optional) ">
    /* If Nimbus (introduced in Java SE 6) is not available, stay with the default look and feel.
     * For details see http://download.oracle.com/javase/tutorial/uiswing/lookandfeel/plaf.html 
     */
    try {
        for (javax.swing.UIManager.LookAndFeelInfo info : javax.swing.UIManager.getInstalledLookAndFeels()) {
            if ("Nimbus".equals(info.getName())) {
                javax.swing.UIManager.setLookAndFeel(info.getClassName());
                break;
            }
        }
    } catch (ClassNotFoundException ex) {
        java.util.logging.Logger.getLogger(Cowork.class.getName()).log(java.util.logging.Level.SEVERE, null,
                ex);
    } catch (InstantiationException ex) {
        java.util.logging.Logger.getLogger(Cowork.class.getName()).log(java.util.logging.Level.SEVERE, null,
                ex);
    } catch (IllegalAccessException ex) {
        java.util.logging.Logger.getLogger(Cowork.class.getName()).log(java.util.logging.Level.SEVERE, null,
                ex);
    } catch (javax.swing.UnsupportedLookAndFeelException ex) {
        java.util.logging.Logger.getLogger(Cowork.class.getName()).log(java.util.logging.Level.SEVERE, null,
                ex);
    }
    //</editor-fold>

    /* Create and display the applet */
    try {
        java.awt.EventQueue.invokeAndWait(new Runnable() {

            public void run() {
                try {
                    sessionId = getParameter("sessionId");
                    email = getParameter("email");
                    endpoint = getCodeBase().toString() + "/fr.insalyon.creatis.vip.portal.Main/coworkservice";

                    DesignFrame frame = new DesignFrame(true);
                    frame.setAppletParams(endpoint, email, sessionId);

                    String home = System.getProperty("user.home");
                    File config = new File(home + File.separator + ".cowork/config");
                    PropertiesConfiguration pc = new PropertiesConfiguration(config);

                    String password = (String) pc.getProperty("password"),
                            login = (String) pc.getProperty("login");
                    PasswordDialog p = new PasswordDialog(null, "Please login to the knowledge base");
                    while (password == null || login == null) {
                        if (p.showDialog()) {

                            login = p.getName();
                            password = p.getPass();
                        }
                        if (login != null && password != null) {
                            if (JOptionPane.showConfirmDialog(null, "Remember credentials (unencrypted)?",
                                    "Rememeber?", JOptionPane.YES_NO_OPTION) == JOptionPane.YES_OPTION) {
                                pc.setProperty("password", password);
                                pc.setProperty("login", login);
                                pc.save();
                            }
                        }

                    }

                    KnowledgeBase kb = new KnowledgeBase("jdbc:mysql://" + getCodeBase().getHost() + "/cowork",
                            login, password, "http://cowork.i3s.cnrs.fr/");
                    frame.setKB(kb);
                    frame.setVisible(true);
                } catch (ConfigurationException ex) {
                    ex.printStackTrace();

                    JOptionPane.showMessageDialog(null, ExceptionUtils.getStackTrace(ex), "Error",
                            JOptionPane.ERROR_MESSAGE);
                } catch (SQLException ex) {
                    ex.printStackTrace();
                    JOptionPane.showMessageDialog(null, ExceptionUtils.getStackTrace(ex), "Error",
                            JOptionPane.ERROR_MESSAGE);
                }

            }
        });
    } catch (Exception ex) {
        ex.printStackTrace();
        JOptionPane.showMessageDialog(null, ExceptionUtils.getStackTrace(ex), "Error",
                JOptionPane.ERROR_MESSAGE);
    }
}

From source file:eu.ascetic.zabbixdatalogger.datasource.ZabbixDirectDbDataSourceAdaptor.java

/**
 * This creates a new database connector for use. It establishes a database
 * connection immediately ready for use.
 *///from   ww w. ja v  a  2 s .c  om
public ZabbixDirectDbDataSourceAdaptor() {
    HISTORY_TABLES.add("history");
    HISTORY_TABLES.add("history_str");
    HISTORY_TABLES.add("history_uint");
    HISTORY_TABLES.add("history_text");

    try {
        PropertiesConfiguration config;
        if (new File(CONFIG_FILE).exists()) {
            config = new PropertiesConfiguration(CONFIG_FILE);
        } else {
            config = new PropertiesConfiguration();
            config.setFile(new File(CONFIG_FILE));
        }
        config.setAutoSave(true); //This will save the configuration file back to disk. In case the defaults need setting.
        databaseURL = config.getString("data.logger.zabbix.db.url", databaseURL);
        config.setProperty("data.logger.zabbix.db.url", databaseURL);
        databaseDriver = config.getString("data.logger.zabbix.db.driver", databaseDriver);
        try {
            Class.forName(databaseDriver);
        } catch (ClassNotFoundException ex) {
            //If the driver is not found on the class path revert to MariaDB.
            databaseDriver = "org.mariadb.jdbc.Driver";
        }
        config.setProperty("data.logger.zabbix.db.driver", databaseDriver);
        databasePassword = config.getString("data.logger.zabbix.db.password", databasePassword);
        config.setProperty("data.logger.zabbix.db.password", databasePassword);
        databaseUser = config.getString("data.logger.zabbix.db.user", databaseUser);
        config.setProperty("data.logger.zabbix.db.user", databaseUser);
        begins = config.getString("data.logger.filter.begins", begins);
        config.setProperty("data.logger.filter.begins", begins);
        isHost = config.getBoolean("data.logger.filter.isHost", isHost);
        config.setProperty("data.logger.filter.isHost", isHost);
        onlyAvailableHosts = config.getBoolean("data.logger.zabbix.only.available.hosts", onlyAvailableHosts);
        config.setProperty("data.logger.zabbix.only.available.hosts", onlyAvailableHosts);
        if (onlyAvailableHosts) {
            ALL_ZABBIX_HOSTS = ALL_ZABBIX_HOSTS + " AND h.available = 1";
        }

    } catch (ConfigurationException ex) {
        DB_LOGGER.log(Level.SEVERE, "Error loading the configuration of the Zabbix data logger");
    }
    try {
        connection = getConnection();
    } catch (IOException | SQLException | ClassNotFoundException ex) {
        DB_LOGGER.log(Level.SEVERE, "Failed to establish the connection to the Zabbix DB", ex);
    }
}