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

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

Introduction

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

Prototype

public void setProperty(String key, Object value) 

Source Link

Usage

From source file:org.apache.bookkeeper.stream.cluster.StandaloneStarter.java

static int doMain(String[] args) throws Exception {
    StarterArgs starterArgs = new StarterArgs();

    JCommander commander = new JCommander();
    try {//w  w  w.ja va  2s  . co  m
        commander.setProgramName("standalone-starter");
        commander.addObject(starterArgs);
        commander.parse(args);
        if (starterArgs.help) {
            commander.usage();
            return 0;
        }
    } catch (Exception e) {
        commander.usage();
        return -1;
    }

    StreamClusterSpec.StreamClusterSpecBuilder specBuilder = StreamClusterSpec.builder();
    if (starterArgs.metadataServiceUri == null) {
        specBuilder = specBuilder.zkPort(starterArgs.zkPort).shouldStartZooKeeper(true);
    } else {
        ServiceURI serviceURI = ServiceURI.create(starterArgs.metadataServiceUri);
        specBuilder = specBuilder.metadataServiceUri(serviceURI).shouldStartZooKeeper(false);
    }

    CompositeConfiguration conf = new CompositeConfiguration();
    if (null != starterArgs.configFile) {
        PropertiesConfiguration propsConf = new PropertiesConfiguration(starterArgs.configFile);
        conf.addConfiguration(propsConf);
    }

    checkArgument(starterArgs.numBookies > 0, "Invalid number of bookies : " + starterArgs.numBookies);
    if (starterArgs.numBookies == 1) {
        conf.setProperty("dlog.bkcEnsembleSize", 1);
        conf.setProperty("dlog.bkcWriteQuorumSize", 1);
        conf.setProperty("dlog.bkcAckQuorumSize", 1);
    } else {
        conf.setProperty("dlog.bkcEnsembleSize", starterArgs.numBookies);
        conf.setProperty("dlog.bkcWriteQuorumSize", starterArgs.numBookies);
        conf.setProperty("dlog.bkcAckQuorumSize", starterArgs.numBookies - 1);
    }

    StreamClusterSpec spec = specBuilder.baseConf(conf).numServers(starterArgs.numBookies)
            .initialBookiePort(starterArgs.initialBookiePort).initialGrpcPort(starterArgs.initialBookieGrpcPort)
            .storageRootDir(new File(starterArgs.dataDir)).build();

    CountDownLatch liveLatch = new CountDownLatch(1);

    StreamCluster cluster = StreamCluster.build(spec);
    Runtime.getRuntime().addShutdownHook(new Thread(() -> {
        cluster.stop();
        cluster.close();
        liveLatch.countDown();
    }, "Standalone-Shutdown-Thread"));

    cluster.start();

    try {
        liveLatch.await();
    } catch (InterruptedException e) {
        log.error("The standalone cluster is interrupted : ", e);
    }
    return 0;
}

From source file:org.apache.bookkeeper.stream.storage.conf.TestStorageConfiguration.java

@Test(timeout = 60000)
public void testGetStorageSettings() {
    CompositeConfiguration conf = new CompositeConfiguration();
    conf.setProperty("xxx.key", "xxx.value");
    conf.setProperty("storage.key", "storage.value");
    conf.setProperty("storage-key", "storage-value");

    StorageConfiguration storageConf = new StorageConfiguration(conf);
    assertEquals("storage.value", storageConf.getString("key"));
    assertTrue(storageConf.containsKey("key"));
    assertFalse(storageConf.containsKey("xxx.key"));
    assertFalse(storageConf.containsKey("storage.key"));
    assertFalse(storageConf.containsKey("storage-key"));
}

From source file:org.apache.whirr.compute.BootstrapTemplateTest.java

private ClusterSpec buildClusterSpecWith(Map<String, String> overrides) throws Exception {
    CompositeConfiguration config = new CompositeConfiguration();
    config.setProperty("whirr.image-id", "us-east-1/ami-123");
    for (String key : overrides.keySet()) {
        config.setProperty(key, overrides.get(key));
    }//from  ww  w .  j av a 2 s .c  om
    return ClusterSpec.withTemporaryKeys(config);
}

From source file:org.apache.whirr.service.DryRunModuleTest.java

@Test
public void testExecuteOnlyBootstrapForNoop() throws Exception {
    CompositeConfiguration config = new CompositeConfiguration();
    config.setProperty("whirr.provider", "stub");
    config.setProperty("whirr.cluster-name", "stub-test");
    config.setProperty("whirr.instance-templates", "1 noop");
    config.setProperty("whirr.state-store", "memory");

    ClusterSpec clusterSpec = ClusterSpec.withTemporaryKeys(config);
    ClusterController controller = new ClusterController();

    DryRun dryRun = getDryRunInControllerForCluster(controller, clusterSpec);
    dryRun.reset();/*from w w  w.  j  a  v a2s  .c  om*/

    controller.launchCluster(clusterSpec);
    controller.destroyCluster(clusterSpec);

    ListMultimap<NodeMetadata, Statement> perNodeExecutions = dryRun.getExecutions();

    for (Entry<NodeMetadata, Collection<Statement>> entry : perNodeExecutions.asMap().entrySet()) {
        assertSame("An incorrect number of scripts was executed in the node " + entry, entry.getValue().size(),
                1);
    }
}

From source file:org.apache.whirr.service.DryRunModuleTest.java

/**
 * Simple test that tests dry run module and at the same time enforces clear
 * separation of script execution phases.
 *//*  w ww . jav  a  2  s  .c o  m*/
@Test
public void testNoInitScriptsAfterConfigurationStartedAndNoConfigScriptsAfterDestroy()
        throws ConfigurationException, JSchException, IOException, InterruptedException {

    final List<String> expectedExecutionOrder = ImmutableList.of("bootstrap", "configure", "start", "destroy");

    CompositeConfiguration config = new CompositeConfiguration();
    config.setProperty("whirr.provider", "stub");
    config.setProperty("whirr.cluster-name", "stub-test");
    config.setProperty("whirr.instance-templates", "10 noop+noop3,10 noop2+noop,10 noop3+noop2");
    config.setProperty("whirr.state-store", "memory");

    ClusterSpec clusterSpec = ClusterSpec.withTemporaryKeys(config);
    ClusterController controller = new ClusterController();

    DryRun dryRun = getDryRunInControllerForCluster(controller, clusterSpec);
    dryRun.reset();

    controller.launchCluster(clusterSpec);
    controller.destroyCluster(clusterSpec);

    ListMultimap<NodeMetadata, Statement> perNodeExecutions = dryRun.getExecutions();
    List<StatementOnNode> totalExecutions = dryRun.getTotallyOrderedExecutions();

    // Assert that all nodes executed all three phases and in the right order

    for (Entry<NodeMetadata, Collection<Statement>> entry : perNodeExecutions.asMap().entrySet()) {
        assertSame("An incorrect number of scripts was executed in the node: " + entry.getValue(),
                entry.getValue().size(), expectedExecutionOrder.size());
        List<Statement> asList = Lists.newArrayList(entry.getValue());

        int count = 0;
        for (String phase : expectedExecutionOrder) {
            String scriptName = getScriptName(asList.get(count));
            assertTrue("The '" + phase + "' script was executed in the wrong order, found: " + scriptName,
                    scriptName.startsWith(phase));
            count += 1;
        }
    }

    // This tests the barrier by making sure that once a configure
    // script is executed no more setup scripts are executed

    Stack<String> executedPhases = new Stack<String>();
    for (StatementOnNode script : totalExecutions) {
        String[] parts = getScriptName(script.getStatement()).split("-");
        if ((!executedPhases.empty() && !executedPhases.peek().equals(parts[0])) || executedPhases.empty()) {
            executedPhases.push(parts[0]);
        }
    }

    // Assert that all scripts executed in the right order with no overlaps

    assertEquals(expectedExecutionOrder.size(), executedPhases.size());
    for (String phaseName : Lists.reverse(expectedExecutionOrder)) {
        assertEquals(executedPhases.pop(), phaseName);
    }
}

From source file:org.apereo.lap.services.ConfigurationService.java

@PostConstruct
public void init() throws IOException {
    logger.info("INIT started");
    logger.info("App Home: " + appHome().getAbsolutePath());

    CompositeConfiguration config = new CompositeConfiguration();
    // load internal config defaults first
    config.setProperty("app.name", "LAP");
    File dbDefaults = resourceLoader.getResource("classpath:db.properties").getFile();
    try {/*w  w  w.  j  av a  2 s .c o m*/
        config.addConfiguration(new PropertiesConfiguration(dbDefaults));
    } catch (ConfigurationException e) {
        logger.error("Unable to load default db.properties file");
    }
    File appDefaults = resourceLoader.getResource("classpath:app.properties").getFile();
    try {
        config.addConfiguration(new PropertiesConfiguration(appDefaults));
        logger.info("Default app configuration loaded from: " + appDefaults.getAbsolutePath());
    } catch (ConfigurationException e) {
        logger.error("Unable to load default app.properties file");
    }

    // now try to load external config settings
    config.addConfiguration(new SystemConfiguration());
    File lapConfigProps = new File(appHome(), "lap.properties");
    if (lapConfigProps.exists() && lapConfigProps.canRead()) {
        try {
            config.addConfiguration(new PropertiesConfiguration(lapConfigProps));
        } catch (ConfigurationException e) {
            logger.warn("Unable to load lap.properties file");
        }
    } else {
        IOUtils.copy(
                SampleCSVInputHandlerService.class.getClassLoader()
                        .getResourceAsStream("config" + SLASH + "lap.properties"),
                new FileOutputStream(new File(appHome(), "lap.properties")));
        logger.info("No external LAP config found: " + lapConfigProps.getAbsolutePath()
                + ", copied default sample lap.properties");
    }
    this.config = config;

    // verify the existence of the various dirs
    pipelinesDirectory = verifyDir("dir.pipelines", "piplines");
    inputDirectory = verifyDir("dir.inputs", "inputs");
    outputDirectory = verifyDir("dir.outputs", "outputs");

    pipelineConfigs = new ConcurrentHashMap<>();
    // first load the internal ones (must be listed explicitly for now)
    Resource pipelineSample = resourceLoader.getResource("classpath:pipelines" + SLASH + "sample.xml");
    PipelineConfig plcfg = processPipelineConfigFile(pipelineSample.getFile());
    if (plcfg != null) {
        pipelineConfigs.put(plcfg.getType(), plcfg);
    }
    // then try to load the external ones
    File[] pipelineFiles = pipelinesDirectory.listFiles();
    if (pipelineFiles != null && pipelineFiles.length > 0) {
        for (final File fileEntry : pipelineFiles) {
            if (fileEntry.isFile()) {
                PipelineConfig filePLC = processPipelineConfigFile(pipelineSample.getFile());
                if (filePLC != null) {
                    pipelineConfigs.put(filePLC.getType(), filePLC);
                }
            }
        }
    }

    logger.info("INIT complete: " + config.getString("app.name") + ", home="
            + applicationHomeDirectory.getAbsolutePath());
}

From source file:org.freeeed.main.ParameterProcessing.java

/**
 * Custom configuration / processing parameters
 *
 * @param customParametersFile file path of properties file
 * @return/*from w ww  .  j  a v  a2  s. co m*/
 */
public static Configuration collectProcessingParameters(String customParametersFile) {

    // apache.commons configuration class
    CompositeConfiguration cc = new CompositeConfiguration();

    try {
        // custom parameter file is first priority
        if (customParametersFile != null) {
            // read file
            Configuration customProperties = new FreeEedConfiguration(customParametersFile);
            // add to configuration
            cc.addConfiguration(customProperties);
        }

        // default parameter file is last priority

        // read file
        Configuration defaults = new FreeEedConfiguration(DEFAULT_PARAMETER_FILE);
        // add to configuration
        cc.addConfiguration(defaults);

        // set project file name
        cc.setProperty(PROJECT_FILE_NAME, customParametersFile);
    } catch (Exception e) {
        e.printStackTrace(System.out);
        // follow the "fail-fast" design pattern
        System.exit(0);
    }
    return cc;
}

From source file:org.rdswicthboard.utils.rdf.oai.App.java

public static void main(String[] args) {
    // create the command line parser
    CommandLineParser parser = new DefaultParser();

    // create the Options
    Options options = new Options();
    options.addOption("i", PROPERTY_INPUT_FILE, true, "input RDF file");
    options.addOption("o", PROPERTY_OUTPUT_FILE, true,
            "output OAI-PMH XML file (default is " + DEFAULT_OUTPUT_FILE + ")");
    options.addOption("c", PROPERTY_CONFIG_FILE, true, "configuration file (" + PROPERTIES_FILE + ")");
    options.addOption("s", PROPERTY_SET_SPEC, true, "set spec value (default is " + DEFAULT_SET_SPEC + ")");
    options.addOption("I", PROPERTY_INPUT_ENCODING, true,
            "input file encoding (default is " + DEFAULT_ENCODING + ")");
    options.addOption("O", PROPERTY_OUTPUT_ENCODING, true,
            "output file encoding (default is " + DEFAULT_ENCODING + ")");
    options.addOption("f", PROPERTY_FORMAT_OUTPUT, false, "format output encoding");
    options.addOption("h", PROPERTY_HELP, false, "print this message");

    try {/*from   w  w w  .  jav  a 2s . c  om*/
        // parse the command line arguments
        CommandLine line = parser.parse(options, args);

        if (line.hasOption(PROPERTY_HELP)) {
            HelpFormatter formatter = new HelpFormatter();
            formatter.printHelp("java -jar rdf2oai-[verion].jar [PARAMETERS] [INPUT FILE] [OUTPUT FILE]",
                    options);

            System.exit(0);
        }

        // variables to store program properties
        CompositeConfiguration config = new CompositeConfiguration();
        config.setProperty(PROPERTY_OUTPUT_FILE, DEFAULT_OUTPUT_FILE);
        config.setProperty(PROPERTY_INPUT_ENCODING, DEFAULT_ENCODING);
        config.setProperty(PROPERTY_OUTPUT_ENCODING, DEFAULT_ENCODING);
        config.setProperty(PROPERTY_SET_SPEC, DEFAULT_SET_SPEC);
        config.setProperty(PROPERTY_FORMAT_OUTPUT, DEFAULT_FORMAT_OUTPUT);

        // check if arguments has input file properties 
        if (line.hasOption(PROPERTY_CONFIG_FILE)) {
            // if it does, load the specified configuration file
            Path defaultConfig = Paths.get(line.getOptionValue(PROPERTY_CONFIG_FILE));
            if (Files.isRegularFile(defaultConfig) && Files.isReadable(defaultConfig)) {
                config.addConfiguration(new PropertiesConfiguration(defaultConfig.toFile()));
            } else
                throw new Exception("Invalid configuration file: " + defaultConfig.toString());
        } else {
            // if it not, try to load default configurationfile
            Path defaultConfig = Paths.get(PROPERTIES_FILE);
            if (Files.isRegularFile(defaultConfig) && Files.isReadable(defaultConfig)) {
                config.addConfiguration(new PropertiesConfiguration(defaultConfig.toFile()));
            }
        }

        // check if arguments has input file 
        if (line.hasOption(PROPERTY_INPUT_FILE))
            config.setProperty(PROPERTY_INPUT_FILE, line.getOptionValue(PROPERTY_INPUT_FILE));

        // check if arguments has output file
        if (line.hasOption(PROPERTY_OUTPUT_FILE))
            config.setProperty(PROPERTY_OUTPUT_FILE, line.getOptionValue(PROPERTY_OUTPUT_FILE));

        // check if arguments has set spec name
        if (line.hasOption(PROPERTY_SET_SPEC))
            config.setProperty(PROPERTY_SET_SPEC, line.getOptionValue(PROPERTY_SET_SPEC));

        // check if arguments has input encoding
        if (line.hasOption(PROPERTY_INPUT_ENCODING))
            config.setProperty(PROPERTY_INPUT_ENCODING, line.getOptionValue(PROPERTY_INPUT_ENCODING));

        // check if arguments has output encoding
        if (line.hasOption(PROPERTY_OUTPUT_ENCODING))
            config.setProperty(PROPERTY_OUTPUT_ENCODING, line.getOptionValue(PROPERTY_OUTPUT_ENCODING));

        // check if arguments has output encoding
        if (line.hasOption(PROPERTY_FORMAT_OUTPUT))
            config.setProperty(PROPERTY_FORMAT_OUTPUT, "yes");

        // check if arguments has input file without a key
        if (line.getArgs().length > 0) {
            config.setProperty(PROPERTY_INPUT_FILE, line.getArgs()[0]);

            // check if arguments has output file without a key
            if (line.getArgs().length > 1) {
                config.setProperty(PROPERTY_OUTPUT_FILE, line.getArgs()[1]);

                // check if there is too many arguments
                if (line.getArgs().length > 2)
                    throw new Exception("Too many arguments");
            }
        }

        // The program has default output file, but input file must be presented
        if (!config.containsKey(PROPERTY_INPUT_FILE))
            throw new Exception("Please specify input file");

        // extract input file
        String inputFile = config.getString(PROPERTY_INPUT_FILE);

        // extract output file
        String outputFile = config.getString(PROPERTY_OUTPUT_FILE);

        // extract set spec
        String setSpecName = config.getString(PROPERTY_SET_SPEC);

        // extract encoding
        String inputEncoding = config.getString(PROPERTY_INPUT_ENCODING);
        String outputEncoding = config.getString(PROPERTY_OUTPUT_ENCODING);

        boolean formatOutput = config.getBoolean(PROPERTY_FORMAT_OUTPUT);

        // test if source is an regular file and it is readable
        Path source = Paths.get(inputFile);
        if (!Files.isRegularFile(source))
            throw new Exception("The input file: " + source.toString() + " is not an regular file");
        if (!Files.isReadable(source))
            throw new Exception("The input file: " + source.toString() + " is not readable");

        Path target = Paths.get(outputFile);
        if (Files.exists(target)) {
            if (!Files.isRegularFile(target))
                throw new Exception("The output file: " + target.toString() + " is not an regular file");
            if (!Files.isWritable(target))
                throw new Exception("The output file: " + target.toString() + " is not writable");
        }

        // create and setup document builder factory
        DocumentBuilderFactory factory = DocumentBuilderFactory.newInstance();
        factory.setNamespaceAware(true);

        // create new document builder
        DocumentBuilder builder = factory.newDocumentBuilder();

        // create oai document
        Document oai = builder.newDocument();

        // set document version
        oai.setXmlVersion("1.0");
        oai.setXmlStandalone(true);

        // create root OAI-PMH element
        Element oaiPmh = oai.createElement("OAI-PMH");

        // set document namespaces
        oaiPmh.setAttribute("xmlns", "http://www.openarchives.org/OAI/2.0/");
        oaiPmh.setAttributeNS("http://www.w3.org/2000/xmlns/", "xmlns:xsi",
                "http://www.w3.org/2001/XMLSchema-instance");
        oaiPmh.setAttribute("xsi:schemaLocation",
                "http://www.openarchives.org/OAI/2.0/ http://www.openarchives.org/OAI/2.0/OAI-PMH.xsd");

        // append root node
        oai.appendChild(oaiPmh);

        // create responseDate element
        Element responseDate = oai.createElement("responseDate");

        // create simple date format
        DateFormat dateFormat = new SimpleDateFormat(TIME_FORMAT);

        // generate date
        String date = dateFormat.format(new Date());

        // set current date and time
        responseDate.setTextContent(date);

        oaiPmh.appendChild(responseDate);

        Element listRecords = oai.createElement("ListRecords");
        oaiPmh.appendChild(listRecords);

        // create xpath factory
        XPathFactory xPathfactory = XPathFactory.newInstance();

        // create namespace context
        NamespaceContext namespaceContext = new NamespaceContext() {
            public String getNamespaceURI(String prefix) {
                if (prefix.equals("rdf"))
                    return RDF_NAMESPACE;
                else if (prefix.equals("rns"))
                    return RNF_NAMESPACE;
                else
                    return null;
            }

            @Override
            public Iterator<?> getPrefixes(String val) {
                throw new IllegalAccessError("Not implemented!");
            }

            @Override
            public String getPrefix(String uri) {
                throw new IllegalAccessError("Not implemented!");
            }
        };

        // create xpath object
        XPath xpath = xPathfactory.newXPath();
        // set namespace contex
        xpath.setNamespaceContext(namespaceContext);

        // create XPath expressions
        XPathExpression idExpr = xpath.compile("/rdf:RDF/rns:Researcher/@rdf:about");
        XPathExpression emptyExpr = xpath.compile("//text()[normalize-space(.) = '']");

        // create RegEx patterns  
        Pattern pattern = Pattern.compile(
                "<\\?xml\\s+version=\"[\\d\\.]+\"\\s*\\?>\\s*<\\s*rdf:RDF[^>]*>[\\s\\S]*?<\\s*\\/\\s*rdf:RDF\\s*>");

        // read file into a string
        String content = new String(Files.readAllBytes(source), inputEncoding);

        Matcher matcher = pattern.matcher(content);
        // process all records
        while (matcher.find()) {
            // convert string to input stream
            ByteArrayInputStream input = new ByteArrayInputStream(
                    matcher.group().getBytes(StandardCharsets.UTF_8.toString()));

            // parse the xml document
            Document doc = builder.parse(input);

            // remove all spaces
            NodeList emptyNodes = (NodeList) emptyExpr.evaluate(doc, XPathConstants.NODESET);
            // Remove each empty text node from document.
            for (int i = 0; i < emptyNodes.getLength(); i++) {
                Node emptyTextNode = emptyNodes.item(i);
                emptyTextNode.getParentNode().removeChild(emptyTextNode);
            }

            // obtain researcher id
            String id = (String) idExpr.evaluate(doc, XPathConstants.STRING);
            if (StringUtils.isEmpty(id))
                throw new Exception("The record identifier can not be empty");

            // create record element
            Element record = oai.createElement("record");
            listRecords.appendChild(record);

            // create header element
            Element header = oai.createElement("header");
            record.appendChild(header);

            // create identifier element
            Element identifier = oai.createElement("identifier");
            identifier.setTextContent(id);
            header.appendChild(identifier);

            // create datestamp element
            Element datestamp = oai.createElement("datestamp");
            datestamp.setTextContent(date);
            header.appendChild(datestamp);

            // create set spec element if it exists
            if (!StringUtils.isEmpty(setSpecName)) {
                Element setSpec = oai.createElement("setSpec");
                setSpec.setTextContent(setSpecName);
                header.appendChild(setSpec);
            }

            // create metadata element
            Element metadata = oai.createElement("metadata");
            record.appendChild(metadata);

            // import the record
            metadata.appendChild(oai.importNode(doc.getDocumentElement(), true));
        }

        // create transformer factory
        TransformerFactory transformerFactory = TransformerFactory.newInstance();

        // create transformer
        Transformer transformer = transformerFactory.newTransformer();
        transformer.setOutputProperty(OutputKeys.ENCODING, outputEncoding);

        if (formatOutput) {
            transformer.setOutputProperty(OutputKeys.INDENT, "yes");
            transformer.setOutputProperty("{http://xml.apache.org/xslt}indent-amount", "2");
        } else
            transformer.setOutputProperty(OutputKeys.INDENT, "no");

        // create dom source
        DOMSource oaiSource = new DOMSource(oai);

        // create stream result
        StreamResult result = new StreamResult(target.toFile());

        // stream xml to file
        transformer.transform(oaiSource, result);

        // optional stream xml to console for testing
        //StreamResult consoleResult = new StreamResult(System.out);
        //transformer.transform(oaiSource, consoleResult);

    } catch (Exception e) {
        System.err.println("Error: " + e.getMessage());

        //e.printStackTrace();

        System.exit(1);
    }
}

From source file:org.rdswicthboard.utils.xml.split.Properties.java

public static Configuration fromArgs(String[] args) throws Exception {
    CommandLineParser parser = new DefaultParser();

    // create the Options
    Options options = new Options();
    options.addOption("i", PROPERTY_INPUT_FILE, true, "input RDF file");
    options.addOption("P", PROPERTY_OUTPUT_PREFIX, true,
            "output files prefix (default is " + DEFAULT_OUTPUT_PREFIX + "N.xml)");
    options.addOption("c", PROPERTY_CONFIG_FILE, true, "configuration file (optional)");
    options.addOption("I", PROPERTY_INPUT_ENCODING, true,
            "input file encoding (default is " + DEFAULT_ENCODING + ")");
    options.addOption("O", PROPERTY_OUTPUT_ENCODING, true,
            "output file encoding (default is " + DEFAULT_ENCODING + ")");
    options.addOption("r", PROPERTY_ROOT_NODE, true, "root node (with namespace if needed)");
    options.addOption("f", PROPERTY_FORMAT_OUTPUT, false, "format output encoding");
    options.addOption("h", PROPERTY_HELP, false, "print this message");

    // parse the command line arguments
    CommandLine line = parser.parse(options, args);

    if (line.hasOption(PROPERTY_HELP)) {
        HelpFormatter formatter = new HelpFormatter();
        formatter.printHelp("java -jar oai-combine-[verion].jar [PARAMETERS]", options);

        System.exit(0);//from w  w w  . ja va 2  s . c om
    }

    // variables to store program properties
    CompositeConfiguration config = new CompositeConfiguration();
    config.setProperty(PROPERTY_INPUT_FILE, "publications.xml");
    config.setProperty(PROPERTY_ROOT_NODE, "OAI-PMH");
    config.setProperty(PROPERTY_OUTPUT_PREFIX, "nii/oai_");
    //      config.setProperty( PROPERTY_OUTPUT_PREFIX, DEFAULT_OUTPUT_PREFIX );
    config.setProperty(PROPERTY_INPUT_ENCODING, DEFAULT_ENCODING);
    config.setProperty(PROPERTY_OUTPUT_ENCODING, DEFAULT_ENCODING);
    config.setProperty(PROPERTY_FORMAT_OUTPUT, DEFAULT_FORMAT_OUTPUT);

    // check if arguments has input file properties 
    if (line.hasOption(PROPERTY_CONFIG_FILE)) {
        // if it does, load the specified configuration file
        Path defaultConfig = Paths.get(line.getOptionValue(PROPERTY_CONFIG_FILE));
        if (Files.isRegularFile(defaultConfig) && Files.isReadable(defaultConfig)) {
            config.addConfiguration(new PropertiesConfiguration(defaultConfig.toFile()));
        } else
            throw new Exception("Invalid configuration file: " + defaultConfig.toString());
    }

    // copy properties from the command line
    for (String property : new String[] { PROPERTY_INPUT_FILE, PROPERTY_OUTPUT_PREFIX, PROPERTY_INPUT_ENCODING,
            PROPERTY_OUTPUT_ENCODING, PROPERTY_ROOT_NODE }) {
        if (line.hasOption(property))
            config.setProperty(property, line.getOptionValue(property));
    }

    // check if arguments has output encoding
    if (line.hasOption(PROPERTY_FORMAT_OUTPUT))
        config.setProperty(PROPERTY_FORMAT_OUTPUT, "yes");

    // the program has default output file, but input file must be presented
    if (!config.containsKey(PROPERTY_INPUT_FILE))
        throw new Exception("Please specify input file");

    // the program has default output file, but input file must be presented
    if (!config.containsKey(PROPERTY_ROOT_NODE))
        throw new Exception("Please specify root node");

    return config;
}