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

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

Introduction

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

Prototype

public void save() throws ConfigurationException 

Source Link

Document

Save the configuration.

Usage

From source file:ch.descabato.browser.BackupBrowser.java

public static void main2(final String[] args)
        throws InterruptedException, InvocationTargetException, SecurityException, IOException {
    if (args.length > 1)
        throw new IllegalArgumentException(
                "SYNTAX:  java... " + BackupBrowser.class.getName() + " [initialPath]");

    SwingUtilities.invokeAndWait(new Runnable() {

        @Override//from w  w  w.j a  v a2s .  co  m
        public void run() {
            tryLoadSubstanceLookAndFeel();
            final JFrame f = new JFrame("OtrosVfsBrowser demo");
            f.addWindowListener(finishedListener);
            Container contentPane = f.getContentPane();
            contentPane.setLayout(new BorderLayout());
            DataConfiguration dc = null;
            final PropertiesConfiguration propertiesConfiguration = new PropertiesConfiguration();
            File favoritesFile = new File("favorites.properties");
            propertiesConfiguration.setFile(favoritesFile);
            if (favoritesFile.exists()) {
                try {
                    propertiesConfiguration.load();
                } catch (ConfigurationException e) {
                    e.printStackTrace();
                }
            }
            dc = new DataConfiguration(propertiesConfiguration);
            propertiesConfiguration.setAutoSave(true);
            final VfsBrowser comp = new VfsBrowser(dc, (args.length > 0) ? args[0] : null);
            comp.setSelectionMode(SelectionMode.FILES_ONLY);
            comp.setMultiSelectionEnabled(true);
            comp.setApproveAction(new AbstractAction(Messages.getMessage("demo.showContentButton")) {
                @Override
                public void actionPerformed(ActionEvent e) {
                    FileObject[] selectedFiles = comp.getSelectedFiles();
                    System.out.println("Selected files count=" + selectedFiles.length);
                    for (FileObject selectedFile : selectedFiles) {
                        try {
                            FileSize fileSize = new FileSize(selectedFile.getContent().getSize());
                            System.out.println(selectedFile.getName().getURI() + ": " + fileSize.toString());
                            Desktop.getDesktop()
                                    .open(new File(new URI(selectedFile.getURL().toExternalForm())));
                            //                byte[] bytes = readBytes(selectedFile.getContent().getInputStream(), 150 * 1024l);
                            //                JScrollPane sp = new JScrollPane(new JTextArea(new String(bytes)));
                            //                JDialog d = new JDialog(f);
                            //                d.setTitle("Content of file: " + selectedFile.getName().getFriendlyURI());
                            //                d.getContentPane().add(sp);
                            //                d.setSize(600, 400);
                            //                d.setVisible(true);
                        } catch (Exception e1) {
                            LOGGER.error("Failed to read file", e1);
                            JOptionPane.showMessageDialog(f,
                                    (e1.getMessage() == null) ? e1.toString() : e1.getMessage(), "Error",
                                    JOptionPane.ERROR_MESSAGE);
                        }
                    }
                }
            });

            comp.setCancelAction(new AbstractAction(Messages.getMessage("general.cancelButtonText")) {
                @Override
                public void actionPerformed(ActionEvent e) {
                    f.dispose();
                    try {
                        propertiesConfiguration.save();
                    } catch (ConfigurationException e1) {
                        e1.printStackTrace();
                    }
                    System.exit(0);
                }
            });
            contentPane.add(comp);

            f.pack();
            f.setVisible(true);
            f.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);

        }
    });
    while (!finished)
        Thread.sleep(100);
}

From source file:net.emotivecloud.scheduler.drp4one.DRP4OVF.java

private void writeToFile(String fileName, String vmId) {
    try {//www.ja  v a2s . co  m

        HashMap<String, String> hmap = PRODUCT_PROPS.get(vmId);

        Iterator<String> hmapIter = hmap.keySet().iterator();
        new File(productPropsFolder + PROPS_FILE_NAME).createNewFile();

        PropertiesConfiguration props_config = new PropertiesConfiguration(
                new File(productPropsFolder + PROPS_FILE_NAME));
        props_config.addProperty(vmId, hmap);
        log.debug("saving to properties file..");
        props_config.save();

    } catch (Exception e) {
        log.error(e.getMessage(), e);
    }
}

From source file:com.jaspersoft.buildomatic.crypto.MasterPropertiesObfuscator.java

@Override
public void execute() throws BuildException {
    try {/*from  w w w  .  j  a  v a  2 s.  co m*/
        //load master props
        PropertiesConfiguration config = new PropertiesConfiguration(new File(propsFile));
        PropertiesConfigurationLayout configLayout = config.getLayout();
        configLayout.setGlobalSeparator("=");

        Boolean encFlag = Boolean.parseBoolean(config.getString(ENCRYPT_FLAG));
        Boolean encDoneFlag = Boolean.parseBoolean(config.getString(ENCRYPT_DONE_FLAG));
        if (encFlag && !encDoneFlag) {
            String blockSzStr = config.getString(CRYPTO_BLOCK_SIZE_PARAM);
            EncryptionProperties encProps = new EncryptionProperties(
                    blockSzStr != null ? Integer.parseInt(blockSzStr) : null,
                    config.getString(CRYPTO_TRANSFORMATION_PARAM));
            List<Object> propsToEncryptList = config.getList(PROPS_TO_ENCRYPT_PARAM,
                    Arrays.<Object>asList(PROPS_TO_ENCRYPT_DEF));
            log("Encrypt " + StringUtils.join(propsToEncryptList.toArray(), ','), Project.MSG_INFO);
            log("Encryption block size: " + encProps.getBlockSize(), Project.MSG_DEBUG);
            log("Encryption mode: " + encProps.getCipherTransformation(), Project.MSG_DEBUG);

            //obtain Keystore Manager
            KeystoreManager.init(this.ksp);
            KeystoreManager ksManager = KeystoreManager.getInstance();

            //obtain key
            Key secret = ksManager.getBuildKey();

            Set<String> paramSet = new HashSet<String>(propsToEncryptList.size());
            for (Object prop : propsToEncryptList) {
                String propNameToEnc = prop.toString().trim();
                if (paramSet.contains(propNameToEnc))
                    continue; //was already encrypted once
                paramSet.add(propNameToEnc);

                String pVal = config.getString(propNameToEnc);
                if (pVal != null) {
                    if (EncryptionEngine.isEncrypted(pVal))
                        log("encrypt=true was set, but param " + propNameToEnc
                                + " was found already encrypted. " + " Skipping its encryption.",
                                Project.MSG_WARN);
                    else {
                        String ct = EncryptionEngine.encrypt(secret, pVal, encProps);
                        config.setProperty(propNameToEnc, ct);
                    }
                }
            }

            //set encryption to done
            config.clearProperty(ENCRYPT_FLAG);
            config.setProperty(ENCRYPT_DONE_FLAG, "true");

            //write master props back
            config.save();
        } else if (encDoneFlag) {
            log("The master properties have already been encrypted. To re-enable the encryption, "
                    + "make sure the passwords are in plain text, set master property "
                    + "encrypt to true and remove encrypt.done.", Project.MSG_INFO);
        }
    } catch (Exception e) {
        throw new BuildException(e, getLocation());
    }
}

From source file:es.bsc.servicess.ide.editors.ImplementationFormPage.java

/**
 * Delete a orchestration class from the project metadata 
 * @param classToDelete Orchestration class to be deleted
 * @throws ConfigurationException/*from   w  w w  .  j a v  a  2s  . c om*/
 */
protected void deleteClassFromMetadataFile(String classToDelete) throws ConfigurationException {
    IFile f = ((ServiceFormEditor) getEditor()).getMetadataFile();
    PropertiesConfiguration config = new PropertiesConfiguration(f.getRawLocation().toOSString());
    String[] classes = config.getStringArray("service.class");
    config.clearProperty("service.class");
    for (String c : classes) {
        if (!c.equals(classToDelete)) {
            config.addProperty("service.class", c);
        }
    }
    config.save();
}

From source file:com.mirth.connect.cli.CommandLineInterface.java

private void commandExportMap(Token[] arguments) throws ClientException {
    if (hasInvalidNumberOfArguments(arguments, 1)) {
        return;/*w w  w .  j a v a2s.c o  m*/
    }

    // file path
    String path = arguments[1].getText();
    File file = new File(path);

    if (file != null) {
        try {
            PropertiesConfiguration properties = new PropertiesConfiguration(file);
            properties.clear();
            PropertiesConfigurationLayout layout = properties.getLayout();

            Map<String, ConfigurationProperty> configurationMap = client.getConfigurationMap();
            Map<String, ConfigurationProperty> sortedMap = new TreeMap<String, ConfigurationProperty>(
                    String.CASE_INSENSITIVE_ORDER);
            sortedMap.putAll(configurationMap);

            for (Entry<String, ConfigurationProperty> entry : sortedMap.entrySet()) {
                String key = entry.getKey();
                String value = entry.getValue().getValue();
                String comment = entry.getValue().getComment();

                if (StringUtils.isNotBlank(key)) {
                    properties.setProperty(key, value);
                    layout.setComment(key, StringUtils.isBlank(comment) ? null : comment);
                }
            }

            properties.save();

            out.println("Configuration map export complete.");
        } catch (ConfigurationException e) {
            error("Unable to export configuration map.", e);
        }
    }
}

From source file:com.mirth.connect.server.migration.ServerMigrator.java

private void runConfigurationMigrator(ConfigurationMigrator configurationMigrator,
        PropertiesConfiguration mirthConfig, Version version) {
    configurationMigrator.updateConfiguration(mirthConfig);

    HashMap<String, Object> addedProperties = new LinkedHashMap<String, Object>();
    Map<String, Object> propertiesToAdd = configurationMigrator.getConfigurationPropertiesToAdd();

    if (propertiesToAdd != null) {
        for (Entry<String, Object> propertyToAdd : propertiesToAdd.entrySet()) {
            if (!mirthConfig.containsKey(propertyToAdd.getKey())) {
                PropertiesConfigurationLayout layout = mirthConfig.getLayout();
                String key = propertyToAdd.getKey();
                Object value;/*from   w  w w  .  j  ava 2  s  .  c o m*/
                String comment = "";

                if (propertyToAdd.getValue() instanceof Pair) {
                    // If a pair is used, get both the value and comment
                    Pair<Object, String> pair = (Pair<Object, String>) propertyToAdd.getValue();
                    value = pair.getLeft();
                    comment = pair.getRight();
                } else {
                    // Only the value was specified
                    value = propertyToAdd.getValue();
                }

                mirthConfig.setProperty(key, value);

                // If this is the first added property, add a general comment about the added properties before it
                if (addedProperties.isEmpty()) {
                    if (StringUtils.isNotEmpty(comment)) {
                        comment = "\n\n" + comment;
                    }
                    comment = "The following properties were automatically added on startup for version "
                            + version + comment;
                }

                if (StringUtils.isNotEmpty(comment)) {
                    // When a comment is specified, always put a blank line before it
                    layout.setBlancLinesBefore(key, 1);
                    layout.setComment(key, comment);
                }

                addedProperties.put(key, value);
            }
        }
    }

    List<String> removedProperties = new ArrayList<String>();
    String[] propertiesToRemove = configurationMigrator.getConfigurationPropertiesToRemove();

    if (propertiesToRemove != null) {
        for (String propertyToRemove : propertiesToRemove) {
            if (mirthConfig.containsKey(propertyToRemove)) {
                mirthConfig.clearProperty(propertyToRemove);
                removedProperties.add(propertyToRemove);
            }
        }
    }

    if (!addedProperties.isEmpty() || !removedProperties.isEmpty()) {
        if (!addedProperties.isEmpty()) {
            logger.info("Adding properties in mirth.properties: " + addedProperties);
        }

        if (!removedProperties.isEmpty()) {
            logger.info("Removing properties in mirth.properties: " + removedProperties);
        }

        try {
            mirthConfig.save();
        } catch (ConfigurationException e) {
            logger.error("There was an error updating mirth.properties.", e);

            if (!addedProperties.isEmpty()) {
                logger.error("The following properties should be added to mirth.properties manually: "
                        + addedProperties.toString());
            }

            if (!removedProperties.isEmpty()) {
                logger.error("The following properties should be removed from mirth.properties manually: "
                        + removedProperties.toString());
            }
        }
    }
}

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 ww .  j a  v  a  2s  .c o  m
    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:com.linkedin.pinot.core.segment.creator.impl.SegmentColumnarIndexCreator.java

void writeMetadata() throws ConfigurationException {
    PropertiesConfiguration properties = new PropertiesConfiguration(
            new File(file, V1Constants.MetadataKeys.METADATA_FILE_NAME));

    properties.setProperty(SEGMENT_CREATOR_VERSION, config.getCreatorVersion());
    properties.setProperty(SEGMENT_PADDING_CHARACTER,
            StringEscapeUtils.escapeJava(Character.toString(config.getPaddingCharacter())));
    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_RAW_DOCS, String.valueOf(totalRawDocs));
    properties.setProperty(SEGMENT_TOTAL_AGGREGATE_DOCS, String.valueOf(totalAggDocs));
    properties.setProperty(SEGMENT_TOTAL_DOCS, String.valueOf(totalDocs));
    properties.setProperty(STAR_TREE_ENABLED, String.valueOf(config.isEnableStarTreeIndex()));
    properties.setProperty(SEGMENT_TOTAL_ERRORS, String.valueOf(totalErrors));
    properties.setProperty(SEGMENT_TOTAL_NULLS, String.valueOf(totalNulls));
    properties.setProperty(SEGMENT_TOTAL_CONVERSIONS, String.valueOf(totalConversions));
    properties.setProperty(SEGMENT_TOTAL_NULL_COLS, String.valueOf(totalNullCols));

    StarTreeIndexSpec starTreeIndexSpec = config.getStarTreeIndexSpec();
    if (starTreeIndexSpec != null) {
        properties.setProperty(STAR_TREE_SPLIT_ORDER, starTreeIndexSpec.getDimensionsSplitOrder());
        properties.setProperty(STAR_TREE_MAX_LEAF_RECORDS, starTreeIndexSpec.getMaxLeafRecords());
        properties.setProperty(STAR_TREE_SKIP_STAR_NODE_CREATION_FOR_DIMENSIONS,
                starTreeIndexSpec.getSkipStarNodeCreationForDimensions());
        properties.setProperty(STAR_TREE_SKIP_MATERIALIZATION_CARDINALITY,
                starTreeIndexSpec.getskipMaterializationCardinalityThreshold());
        properties.setProperty(STAR_TREE_SKIP_MATERIALIZATION_FOR_DIMENSIONS,
                starTreeIndexSpec.getskipMaterializationForDimensions());
    }/*  w w w  .  j av  a  2  s.c o  m*/

    HllConfig hllConfig = config.getHllConfig();
    Map<String, String> derivedHllFieldToOriginMap = null;
    if (hllConfig != null) {
        properties.setProperty(SEGMENT_HLL_LOG2M, hllConfig.getHllLog2m());
        derivedHllFieldToOriginMap = hllConfig.getDerivedHllFieldToOriginMap();
    }

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

    if (config.containsCustomProperty(SEGMENT_START_TIME)) {
        properties.setProperty(SEGMENT_START_TIME, config.getStartTime());
    }
    if (config.containsCustomProperty(SEGMENT_END_TIME)) {
        properties.setProperty(SEGMENT_END_TIME, config.getEndTime());
    }
    if (config.containsCustomProperty(TIME_UNIT)) {
        properties.setProperty(TIME_UNIT, config.getSegmentTimeUnit());
    }

    for (Map.Entry<String, String> entry : config.getCustomProperties().entrySet()) {
        properties.setProperty(entry.getKey(), entry.getValue());
    }

    for (Map.Entry<String, ColumnIndexCreationInfo> entry : indexCreationInfoMap.entrySet()) {
        String column = entry.getKey();
        ColumnIndexCreationInfo columnIndexCreationInfo = entry.getValue();
        int dictionaryElementSize = dictionaryCreatorMap.get(column).getStringColumnMaxLength();

        // TODO: after fixing the server-side dependency on HAS_INVERTED_INDEX and deployed, set HAS_INVERTED_INDEX properly
        // The hasInvertedIndex flag in segment metadata is picked up in ColumnMetadata, and will be used during the query
        // plan phase. If it is set to false, then inverted indexes are not used in queries even if they are created via table
        // configs on segment load. So, we set it to true here for now, until we fix the server to update the value inside
        // ColumnMetadata, export information to the query planner that the inverted index available is current and can be used.
        //
        //    boolean hasInvertedIndex = invertedIndexCreatorMap.containsKey();
        boolean hasInvertedIndex = true;

        String hllOriginColumn = null;
        if (derivedHllFieldToOriginMap != null) {
            hllOriginColumn = derivedHllFieldToOriginMap.get(column);
        }

        addColumnMetadataInfo(properties, column, columnIndexCreationInfo, totalDocs, totalRawDocs,
                totalAggDocs, schema.getFieldSpecFor(column), dictionaryElementSize, hasInvertedIndex,
                hllOriginColumn);
    }

    properties.save();
}

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 {//from w w w .j av  a  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:org.apache.cloudstack.network.contrail.management.TestDbSetup.java

public static void updateSqlPort(int port, String propertyFileOverride) throws Exception {

    PropertiesConfiguration config = new PropertiesConfiguration(propertyFileOverride);
    System.out.println("File: " + propertyFileOverride + "; old: db.properties port: "
            + config.getProperty("db.cloud.port") + ", new port: " + port);
    config.setProperty("db.cloud.port", "" + port);
    config.setProperty("db.cloud.username", System.getProperty("user.name"));
    config.setProperty("db.cloud.password", "");

    config.setProperty("db.usage.port", "" + port);
    config.setProperty("db.usage.username", System.getProperty("user.name"));
    config.setProperty("db.usage.password", "");

    config.setProperty("db.simulator.port", "" + port);
    config.setProperty("db.simulator.username", System.getProperty("user.name"));
    config.setProperty("db.simulator.password", "");

    config.save();
}