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(Writer writer) throws ConfigurationException 

Source Link

Document

Save the configuration to the specified stream.

Usage

From source file:edu.usc.goffish.gofs.tools.GoFSFormat.java

public static void main(String[] args) throws IOException {
    if (args.length < REQUIRED_ARGS) {
        PrintUsageAndQuit(null);//from   ww  w . java2  s  .c o m
    }

    if (args.length == 1 && args[0].equals("-help")) {
        PrintUsageAndQuit(null);
    }

    Path executableDirectory;
    try {
        executableDirectory = Paths
                .get(GoFSFormat.class.getProtectionDomain().getCodeSource().getLocation().toURI()).getParent();
    } catch (URISyntaxException e) {
        throw new RuntimeException("Unexpected error retrieving executable location", e);
    }
    Path configPath = executableDirectory.resolve(DEFAULT_CONFIG).normalize();

    boolean copyBinaries = false;

    // parse optional arguments
    int i = 0;
    OptArgLoop: for (i = 0; i < args.length - REQUIRED_ARGS; i++) {
        switch (args[i]) {
        case "-config":
            i++;

            try {
                configPath = Paths.get(args[i]);
            } catch (InvalidPathException e) {
                PrintUsageAndQuit("Config file - " + e.getMessage());
            }

            break;
        case "-copyBinaries":
            copyBinaries = true;
            break;
        default:
            break OptArgLoop;
        }
    }

    if (args.length - i < REQUIRED_ARGS) {
        PrintUsageAndQuit(null);
    }

    // finished parsing args
    if (i < args.length) {
        PrintUsageAndQuit("Unrecognized argument \"" + args[i] + "\"");
    }

    // parse config

    System.out.println("Parsing config...");

    PropertiesConfiguration config = new PropertiesConfiguration();
    config.setDelimiterParsingDisabled(true);
    try {
        config.load(Files.newInputStream(configPath));
    } catch (ConfigurationException e) {
        throw new IOException(e);
    }

    // retrieve data nodes
    ArrayList<URI> dataNodes;
    {
        String[] dataNodesArray = config.getStringArray(GOFS_DATANODES_KEY);
        if (dataNodesArray.length == 0) {
            throw new ConversionException("Config must contain key " + GOFS_DATANODES_KEY);
        }

        dataNodes = new ArrayList<>(dataNodesArray.length);

        if (dataNodesArray.length == 0) {
            throw new ConversionException("Config key " + GOFS_DATANODES_KEY
                    + " has invalid format - must define at least one data node");
        }

        try {
            for (String node : dataNodesArray) {
                URI dataNodeURI = new URI(node);

                if (!"file".equalsIgnoreCase(dataNodeURI.getScheme())) {
                    throw new ConversionException("config key " + GOFS_DATANODES_KEY + " value \"" + dataNodeURI
                            + "\" has invalid format - data node urls must have 'file' scheme");
                } else if (dataNodeURI.getPath() == null || dataNodeURI.getPath().isEmpty()) {
                    throw new ConversionException("config key " + GOFS_DATANODES_KEY + " value \"" + dataNodeURI
                            + "\" has invalid format - data node urls must have an absolute path specified");
                }

                // ensure uri ends with a slash, so we know it is a directory
                if (!dataNodeURI.getPath().endsWith("/")) {
                    dataNodeURI = dataNodeURI.resolve(dataNodeURI.getPath() + "/");
                }

                dataNodes.add(dataNodeURI);
            }
        } catch (URISyntaxException e) {
            throw new ConversionException(
                    "Config key " + GOFS_DATANODES_KEY + " has invalid format - " + e.getMessage());
        }
    }

    // validate serializer type
    Class<? extends ISliceSerializer> serializerType;
    {
        String serializerTypeName = config.getString(GOFS_SERIALIZER_KEY);
        if (serializerTypeName == null) {
            throw new ConversionException("Config must contain key " + GOFS_SERIALIZER_KEY);
        }

        try {
            serializerType = SliceSerializerProvider.loadSliceSerializerType(serializerTypeName);
        } catch (ReflectiveOperationException e) {
            throw new ConversionException(
                    "Config key " + GOFS_SERIALIZER_KEY + " has invalid format - " + e.getMessage());
        }
    }

    // retrieve name node
    IInternalNameNode nameNode;
    try {
        nameNode = NameNodeProvider.loadNameNodeFromConfig(config, GOFS_NAMENODE_TYPE_KEY,
                GOFS_NAMENODE_LOCATION_KEY);
    } catch (ReflectiveOperationException e) {
        throw new RuntimeException("Unable to load name node", e);
    }

    System.out.println("Contacting name node...");

    // validate name node
    if (!nameNode.isAvailable()) {
        throw new IOException("Name node at " + nameNode.getURI() + " is not available");
    }

    System.out.println("Contacting data nodes...");

    // validate data nodes
    for (URI dataNode : dataNodes) {
        // only attempt ssh if host exists
        if (dataNode.getHost() != null) {
            try {
                SSHHelper.SSH(dataNode, "true");
            } catch (IOException e) {
                throw new IOException("Data node at " + dataNode + " is not available", e);
            }
        }
    }

    // create temporary directory
    Path workingDir = Files.createTempDirectory("gofs_format");
    try {
        // create deploy directory
        Path deployDirectory = Files.createDirectory(workingDir.resolve(DATANODE_DIR_NAME));

        // create empty slice directory
        Files.createDirectory(deployDirectory.resolve(DataNode.DATANODE_SLICE_DIR));

        // copy binaries
        if (copyBinaries) {
            System.out.println("Copying binaries...");
            FileUtils.copyDirectory(executableDirectory.toFile(),
                    deployDirectory.resolve(executableDirectory.getFileName()).toFile());
        }

        // write config file
        Path dataNodeConfigFile = deployDirectory.resolve(DataNode.DATANODE_CONFIG);
        try {
            // create config for every data node and scp deploy folder into place
            for (URI dataNodeParent : dataNodes) {
                URI dataNode = dataNodeParent.resolve(DATANODE_DIR_NAME);

                PropertiesConfiguration datanode_config = new PropertiesConfiguration();
                datanode_config.setDelimiterParsingDisabled(true);
                datanode_config.setProperty(DataNode.DATANODE_INSTALLED_KEY, true);
                datanode_config.setProperty(DataNode.DATANODE_NAMENODE_TYPE_KEY,
                        config.getString(GOFS_NAMENODE_TYPE_KEY));
                datanode_config.setProperty(DataNode.DATANODE_NAMENODE_LOCATION_KEY,
                        config.getString(GOFS_NAMENODE_LOCATION_KEY));
                datanode_config.setProperty(DataNode.DATANODE_LOCALHOSTURI_KEY, dataNode.toString());

                try {
                    datanode_config.save(Files.newOutputStream(dataNodeConfigFile));
                } catch (ConfigurationException e) {
                    throw new IOException(e);
                }

                System.out.println("Formatting data node " + dataNode.toString() + "...");

                // scp everything into place on the data node
                SCPHelper.SCP(deployDirectory, dataNodeParent);

                // update name node
                nameNode.addDataNode(dataNode);
            }

            // update name node
            nameNode.setSerializer(serializerType);
        } catch (Exception e) {
            System.out.println(
                    "ERROR: data node formatting interrupted - name node and data nodes are in an inconsistent state and require clean up");
            throw e;
        }

        System.out.println("GoFS format complete");

    } finally {
        FileUtils.deleteQuietly(workingDir.toFile());
    }
}

From source file:com.zavakid.mushroom.impl.ConfigUtil.java

static void dump(String header, Configuration c, PrintStream out) {
    PropertiesConfiguration p = new PropertiesConfiguration();
    p.copy(c);//from  w  w  w .ja va2s  .  c o m
    if (header != null) {
        out.println(header);
    }
    try {
        p.save(out);
    } catch (Exception e) {
        throw new RuntimeException("Error saving config", e);
    }
}

From source file:cross.io.PropertyFileGenerator.java

/**
 * Creates a property file for the given class, containing those fields,
 * which are annotated by {@link cross.annotations.Configurable}.
 *
 * @param className//from  www. j a va  2  s.  c o  m
 * @param basedir
 */
public static void createProperties(String className, File basedir) {
    Class<?> c;
    try {
        c = PropertyFileGenerator.class.getClassLoader().loadClass(className);
        LoggerFactory.getLogger(PropertyFileGenerator.class).info("Class: {}", c.getName());
        PropertiesConfiguration pc = createProperties(c);
        if (!basedir.exists()) {
            basedir.mkdirs();
        }
        try {
            pc.save(new File(basedir, c.getSimpleName() + ".properties"));
        } catch (ConfigurationException ex) {
            LoggerFactory.getLogger(PropertyFileGenerator.class).warn("{}", ex.getLocalizedMessage());
        }
    } catch (ClassNotFoundException e) {
        LoggerFactory.getLogger(PropertyFileGenerator.class).warn("{}", e.getLocalizedMessage());
    }
}

From source file:com.carmatech.maven.utils.MergeUtils.java

public static void savePropertiesTo(final File targetFile, final PropertiesConfiguration properties,
        final String comment) throws IOException {
    properties.setHeader(comment);//from w  w w. j  a v a  2 s  .  co m
    try {
        Files.createParentDirs(targetFile);
        properties.save(targetFile);
    } catch (ConfigurationException e) {
        throw new IOException("Unable to save properties file " + targetFile);
    }
}

From source file:io.coala.config.ConfigTest.java

@Test
public void testConfigCommons() throws Exception {
    final PropertiesConfiguration config = new PropertiesConfiguration(ConfigUtil.PROPERTIES_FILE);
    config.save(System.out);
}

From source file:fr.jetoile.hadoopunit.HadoopBootstrapRemoteStarter.java

private void editHadoopUnitConfFile() {
    Path hadoopPropertiesPath = Paths.get(hadoopUnitPath, "conf", "hadoop.properties");
    Path hadoopPropertiesBackupPath = Paths.get(hadoopUnitPath, "conf", "hadoop.properties.old");
    if (hadoopPropertiesBackupPath.toFile().exists() && hadoopPropertiesBackupPath.toFile().canWrite()) {
        hadoopPropertiesBackupPath.toFile().delete();
    }/*from  w w  w  . ja va2 s  . c  o  m*/
    hadoopPropertiesPath.toFile().renameTo(hadoopPropertiesBackupPath.toFile());

    PropertiesConfiguration configuration = new PropertiesConfiguration();

    values.forEach(v -> configuration.addProperty(v.toLowerCase(), "true"));
    try {
        configuration.save(new FileWriter(hadoopPropertiesPath.toFile()));
    } catch (ConfigurationException | IOException e) {
        getLog().error("unable to find or modifying hadoop.properties. Check user rights", e);

    }
}

From source file:com.bluelotussoftware.example.apache.commons.Application.java

/**
 * <p>Sets a property called <code>colors.background</code> to the value provided, or assigns a color
 * value{@literal #000000} if none is provided .</p>
 * @param backgroundColor//  w w  w .j a v  a 2s  . co m
 * @throws ConfigurationException if an <code>Exception</code> is encountered. 
 */
public void setBackground(String backgroundColor) throws ConfigurationException {

    PropertiesConfiguration config = ConfigManager.instance().getConfig();
    if (backgroundColor == null) {
        config.setProperty("colors.background", "#000000");
    } else {
        config.setProperty("colors.background", backgroundColor);
    }
    config.save(PROPERTIES_FILE_NAME);
}

From source file:com.zavakid.mushroom.impl.MetricsConfig.java

String toString(Configuration c) {
    ByteArrayOutputStream buffer = new ByteArrayOutputStream();
    PrintStream ps = new PrintStream(buffer);
    PropertiesConfiguration tmp = new PropertiesConfiguration();
    tmp.copy(c);/*from  w  w w  .ja  v  a2s  .c o  m*/
    try {
        tmp.save(ps);
    } catch (Exception e) {
        throw new MetricsConfigException(e);
    }
    return buffer.toString();
}

From source file:net.sf.mpaxs.spi.server.MpaxsImpl.java

@Override
public void startMasterServer(Configuration config, Container c) {
    if (master != null) {
        throw new IllegalStateException("Master server was already started!");
    }//from  ww w.  java2s.c o m
    if (config == null) {
        System.out.println("Configuration is null, starting master with default parameters!");
        startMasterServer();
        return;
    }
    try {
        File f = File.createTempFile(UUID.randomUUID().toString(), ".properties");
        PropertiesConfiguration pc;
        try {
            pc = new PropertiesConfiguration(f);
            ConfigurationUtils.copy(config, pc);
            pc.save(f);
            System.out.println(ConfigurationUtils.toString(pc));
            master = StartUp.start(f.getAbsolutePath(), c);
        } catch (ConfigurationException ex) {
            Logger.getLogger(MpaxsImpl.class.getName()).log(Level.SEVERE, null, ex);
        }
    } catch (IOException ex) {
        Logger.getLogger(MpaxsImpl.class.getName()).log(Level.SEVERE, null, ex);
    }

}

From source file:io.fluo.core.mini.MiniFluoImpl.java

private void startMiniAccumulo() {
    try {/*from www. java  2  s  . c o  m*/
        // start mini accumulo cluster
        MiniAccumuloConfig cfg = new MiniAccumuloConfig(new File(config.getMiniDataDir()), PASSWORD);
        cluster = new MiniAccumuloCluster(cfg);
        cluster.start();

        log.debug("Started MiniAccumulo(accumulo=" + cluster.getInstanceName() + " zk="
                + cluster.getZooKeepers() + ")");

        // configuration that must overridden
        config.setAccumuloInstance(cluster.getInstanceName());
        config.setAccumuloUser(USER);
        config.setAccumuloPassword(PASSWORD);
        config.setAccumuloZookeepers(cluster.getZooKeepers());
        config.setInstanceZookeepers(cluster.getZooKeepers() + "/fluo");

        // configuration that only needs to be set if not by user
        if ((config.containsKey(FluoConfiguration.ADMIN_ACCUMULO_TABLE_PROP) == false)
                || config.getAccumuloTable().trim().isEmpty()) {
            config.setAccumuloTable("fluo");
        }

        InitOpts opts = new InitOpts();
        try (FluoAdmin admin = FluoFactory.newAdmin(config)) {
            admin.initialize(opts);
        }

        File miniProps = new File(clientPropsPath(config));
        PropertiesConfiguration connConfig = new PropertiesConfiguration();
        connConfig.append(config.getClientConfiguration());
        connConfig.save(miniProps);

        log.debug("Wrote MiniFluo client properties to {}", miniProps.getAbsolutePath());

    } catch (Exception e) {
        throw new RuntimeException(e);
    }
}