Java Code Examples for org.apache.commons.configuration.CompositeConfiguration

The following are top voted examples for showing how to use org.apache.commons.configuration.CompositeConfiguration. These examples are extracted from open source projects. You can vote up the examples you like and your votes will be used in our system to generate more good examples.
Example 1
Project: laughing-octo-sansa   File: TwitterSparkCrawler.java   Source Code and License 9 votes vote down vote up
private void run(CompositeConfiguration conf) {
    // Spark conf
    SparkConf sparkConf = new SparkConf().setAppName("TwitterSparkCrawler").setMaster(conf.getString("spark.master"))
            .set("spark.serializer", conf.getString("spark.serializer"));
    JavaStreamingContext jssc = new JavaStreamingContext(sparkConf, Durations.seconds(conf.getLong("stream.duration")));

    // Twitter4J
    // IMPORTANT: put keys in twitter4J.properties
    Configuration twitterConf = ConfigurationContext.getInstance();
    Authorization twitterAuth = AuthorizationFactory.getInstance(twitterConf);

    // Create twitter stream
    String[] filters = { "#Car" };
    TwitterUtils.createStream(jssc, twitterAuth, filters).print();
    // Start the computation
    jssc.start();
    jssc.awaitTermination();
}
 
Example 2
Project: jbake-maven-plugin   File: BuildMojo.java   Source Code and License 7 votes vote down vote up
protected CompositeConfiguration createConfiguration() throws ConfigurationException {
    final CompositeConfiguration config = new CompositeConfiguration();

    if (properties != null) {
        config.addConfiguration(new MapConfiguration(properties));
    }
    config.addConfiguration(new MapConfiguration(project.getProperties()));
    config.addConfiguration(ConfigUtil.load(inputDirectory));
    
    if (getLog().isDebugEnabled()) {
        getLog().debug("Configuration:");

        Iterator<String> iter = config.getKeys();
        while (iter.hasNext()) {
            String key = iter.next();
            getLog().debug(key + ": " + config.getString(key));
        }
    }

    return config;
}
 
Example 3
Project: jbake-rtl-jalaali   File: Baker.java   Source Code and License 6 votes vote down vote up
public void bake(final LaunchOptions options, final CompositeConfiguration config) {
    final Oven oven = new Oven(options.getSource(), options.getDestination(), config, options.isClearCache());
    oven.setupPaths();
    oven.bake();

    final List<Throwable> errors = oven.getErrors();
    if (!errors.isEmpty()) {
        final StringBuilder msg = new StringBuilder();
        // TODO: decide, if we want the all errors here
        msg.append( MessageFormat.format("JBake failed with {0} errors:\n", errors.size()));
        int errNr = 1;
        for (final Throwable error : errors) {
            msg.append(MessageFormat.format("{0}. {1}\n", errNr, error.getMessage()));
            ++errNr;
        }
        throw new JBakeException(msg.toString(), errors.get(0));
    }
}
 
Example 4
Project: jbake-rtl-jalaali   File: DocumentsRenderer.java   Source Code and License 6 votes vote down vote up
@Override
public int render(Renderer renderer, ContentStore db, File destination, File templatesPath, CompositeConfiguration config) throws RenderingException {
    int renderedCount = 0;
    final List<String> errors = new LinkedList<String>();
    for (String docType : DocumentTypes.getDocumentTypes()) {
        DocumentList documentList = db.getUnrenderedContent(docType);
        for (Map<String, Object> page : documentList) {
            try {
                renderer.render(page);
                renderedCount++;
            } catch (Exception e) {
                errors.add(e.getMessage());
            }
        }
    }
    if (!errors.isEmpty()) {
        StringBuilder sb = new StringBuilder();
        sb.append("Failed to render documents. Cause(s):");
        for (String error : errors) {
            sb.append("\n").append(error);
        }
        throw new RenderingException(sb.toString());
    } else {
        return renderedCount;
    }
}
 
Example 5
Project: jbake-rtl-jalaali   File: IndexRenderer.java   Source Code and License 6 votes vote down vote up
@Override
public int render(Renderer renderer, ContentStore db, File destination, File templatesPath, CompositeConfiguration config) throws RenderingException {
    if (config.getBoolean(Keys.RENDER_INDEX)) {
        try {
            if (shouldPaginateIndex(config)) {
                renderer.renderIndexPaging(config.getString(Keys.INDEX_FILE));
            } else {
                renderer.renderIndex(config.getString(Keys.INDEX_FILE));
            }
            return 1;
        } catch (Exception e) {
            throw new RenderingException(e);
        }
    } else {
        return 0;
    }
}
 
Example 6
Project: jbake-rtl-jalaali   File: IndexRendererTest.java   Source Code and License 6 votes vote down vote up
@Test(expected = RenderingException.class)
public void propagatesRenderingException() throws Exception {
    IndexRenderer renderer = new IndexRenderer();

    CompositeConfiguration compositeConfiguration = new MockCompositeConfiguration().withDefaultBoolean(true);
    compositeConfiguration.setProperty(PAGINATE_INDEX, false);
    ContentStore contentStore = mock(ContentStore.class);
    Renderer mockRenderer = mock(Renderer.class);

    doThrow(new Exception()).when(mockRenderer).renderIndex(anyString());

    int renderResponse = renderer.render(mockRenderer, contentStore,
            new File("fake"), new File("fake"), compositeConfiguration);

    verify(mockRenderer, never()).renderIndex("random string");
}
 
Example 7
Project: jbake-rtl-jalaali   File: TagsRendererTest.java   Source Code and License 6 votes vote down vote up
@Test
public void returnsOneWhenConfigRendersIndices() throws Exception {
    TagsRenderer renderer = new TagsRenderer();

    CompositeConfiguration compositeConfiguration = new MockCompositeConfiguration().withDefaultBoolean(true);
    ContentStore contentStore = mock(ContentStore.class);
    Renderer mockRenderer = mock(Renderer.class);

    Set<String> tags = new HashSet(Arrays.asList("tag1", "tags2"));
    when(contentStore.getTags()).thenReturn(tags);

    when(mockRenderer.renderTags("random string")).thenReturn(1);

    int renderResponse = renderer.render(mockRenderer, contentStore,
            new File("fake"), new File("fake"), compositeConfiguration);

    assertThat(renderResponse).isEqualTo(1);
}
 
Example 8
Project: jbake-rtl-jalaali   File: TagsRendererTest.java   Source Code and License 6 votes vote down vote up
@Test
public void doesRenderWhenConfigDoesNotRenderIndices() throws Exception {
    TagsRenderer renderer = new TagsRenderer();

    CompositeConfiguration compositeConfiguration = new MockCompositeConfiguration().withDefaultBoolean(true);
    ContentStore contentStore = mock(ContentStore.class);
    Renderer mockRenderer = mock(Renderer.class);

    Set<String> tags = new HashSet(Arrays.asList("tag1", "tags2"));
    when(contentStore.getTags()).thenReturn(tags);

    int renderResponse = renderer.render(mockRenderer, contentStore,
            new File("fake"), new File("fake"), compositeConfiguration);

    verify(mockRenderer, times(1)).renderTags("random string");
}
 
Example 9
Project: jbake-rtl-jalaali   File: CrawlerTest.java   Source Code and License 6 votes vote down vote up
@Test
public void renderWithPrettyUrls() throws Exception {
    Map<String, Object> testProperties = new HashMap<String, Object>();
    testProperties.put(Keys.URI_NO_EXTENSION, true);
    testProperties.put(Keys.URI_NO_EXTENSION_PREFIX, "/blog");

    CompositeConfiguration config = new CompositeConfiguration();
    config.addConfiguration(new MapConfiguration(testProperties));
    config.addConfiguration(ConfigUtil.load(new File(this.getClass().getResource("/").getFile())));

    Crawler crawler = new Crawler(db, sourceFolder, config);
    crawler.crawl(new File(sourceFolder.getPath() + File.separator + config.getString(Keys.CONTENT_FOLDER)));

    Assert.assertEquals(4, db.getDocumentCount("post"));
    Assert.assertEquals(3, db.getDocumentCount("page"));

    DocumentList documents = db.getPublishedPosts();

    for (Map<String, Object> model : documents) {
        String noExtensionUri = "blog/\\d{4}/" + FilenameUtils.getBaseName((String) model.get("file")) + "/";

        Assert.assertThat(model.get("noExtensionUri"), RegexMatcher.matches(noExtensionUri));
        Assert.assertThat(model.get("uri"), RegexMatcher.matches(noExtensionUri + "index\\.html"));
    }
}
 
Example 10
Project: distributedlog   File: TestConfUtils.java   Source Code and License 6 votes vote down vote up
@Test
public void testLoadConfiguration() {
    Configuration conf1 = new CompositeConfiguration();
    conf1.setProperty("key1", "value1");
    conf1.setProperty("key2", "value2");
    conf1.setProperty("key3", "value3");

    Configuration conf2 = new CompositeConfiguration();
    conf2.setProperty("bkc.key1", "bkc.value1");
    conf2.setProperty("bkc.key4", "bkc.value4");

    assertEquals("value1", conf1.getString("key1"));
    assertEquals("value2", conf1.getString("key2"));
    assertEquals("value3", conf1.getString("key3"));
    assertEquals(null, conf1.getString("key4"));

    ConfUtils.loadConfiguration(conf1, conf2, "bkc.");

    assertEquals("bkc.value1", conf1.getString("key1"));
    assertEquals("value2", conf1.getString("key2"));
    assertEquals("value3", conf1.getString("key3"));
    assertEquals("bkc.value4", conf1.getString("key4"));
    assertEquals(null, conf1.getString("bkc.key1"));
    assertEquals(null, conf1.getString("bkc.key4"));
}
 
Example 11
Project: jbakery   File: JbakeConfig.java   Source Code and License 6 votes vote down vote up
@Bean
public Oven jbakeOven() throws Exception {
    log.info("Baking {} -> {}", source, destination);

    File sourceFile = new File(source);
    final CompositeConfiguration config;
    try {
        config = ConfigUtil.load(sourceFile);
    } catch (final ConfigurationException e) {
        throw new JBakeException("Configuration error: " + e.getMessage(), e);
    }

    System.out.println("JBake " + config.getString(ConfigUtil.Keys.VERSION) + " (" + config.getString(ConfigUtil.Keys.BUILD_TIMESTAMP) + ") [http://jbake.org]");
    System.out.println();

    Oven oven = new Oven(sourceFile, new File(destination), true);
    oven.setupPaths();

    return oven;
}
 
Example 12
Project: oiosaml.java   File: FileConfiguration.java   Source Code and License 6 votes vote down vote up
public Configuration getCommonConfiguration() throws IOException {
    CompositeConfiguration conf = new CompositeConfiguration();
    Enumeration<URL> resources = SAMLConfiguration.class.getClassLoader().getResources("oiosaml-common.properties");
    while (resources.hasMoreElements()) {
        URL u = resources.nextElement();
        log.debug("Loading config from " + u);
        try {
            conf.addConfiguration(new PropertiesConfiguration(u));
        } catch (ConfigurationException e) {
            log.error("Cannot load the configuration file", e);
            throw new WrappedException(Layer.DATAACCESS, e);
        }
    }

    return conf;
}
 
Example 13
Project: oiosaml.java   File: FileConfiguration.java   Source Code and License 6 votes vote down vote up
public Configuration getCommonConfiguration() throws IOException {
	CompositeConfiguration conf = new CompositeConfiguration();
	Enumeration<URL> resources = SAMLConfiguration.class.getClassLoader().getResources("oiosaml-common.properties");
	while (resources.hasMoreElements()) {
		URL u = resources.nextElement();
		log.debug("Loading config from " + u);
		try {
			conf.addConfiguration(new PropertiesConfiguration(u));
		} catch (ConfigurationException e) {
			log.error("Cannot load the configuration file", e);
			throw new WrappedException(Layer.DATAACCESS, e);
		}
	}

	return conf;
}
 
Example 14
Project: jindy   File: CommonsSimpleImpl.java   Source Code and License 6 votes vote down vote up
@Override
protected Configuration createConfiguration(String name) throws ConfigurationException {
  CompositeConfiguration config = new CompositeConfiguration();
  config.addConfiguration(new SystemConfiguration());
  try {
    if (ConfigFactory.DEFAULT_CONFIG_NAME.equals(name)) {
      config.addConfiguration(new PropertiesConfiguration("config.properties"));
    } else {
      config.addConfiguration(new PropertiesConfiguration(name));
    }
  } catch (ConfigurationException e) {
    String message = "No properties file found: " + name
        + ". Using an empty BaseConfiguration instead.";
    if (ConfigFactory.DEFAULT_CONFIG_NAME.equals(name)) {
      LOG.info(message);
    } else {
      LOG.warn(message);
    }
    BaseConfiguration base = new BaseConfiguration();
    config.addConfiguration(base);
  }
  return config;
}
 
Example 15
Project: batmass   File: Map2DOptions.java   Source Code and License 6 votes vote down vote up
/**
 * The combined config = current user config + defaults for non-specified properties.
 * TODO: instead of re-reading user config every time, it would be better
 *       to set up Commons Configuration listeners on the userfile.
 * @return even if reading user config fails, will return default config
 */
public CompositeConfiguration getConfig() {

    // try loading user config
    FileConfiguration userConfig = null;
    try {
        userConfig = BmConfig.forClass(BaseMap2D.class);
    } catch (ConfigurationException | IOException ex) {
        Exceptions.printStackTrace(ex);
    }
    CompositeConfiguration compositeConfig = new CompositeConfiguration();
    // the order of adding configurations to combined configuration is important
    // whoever is added first "shadows" the same key in all subsequently added
    // configuraions. Thus, add the DEFAULTs at the very end
    if (userConfig != null) {
        compositeConfig.addConfiguration(userConfig);
    }
    compositeConfig.addConfiguration(defaultConfig);

    return compositeConfig;
}
 
Example 16
Project: batmass   File: Map2DOptionsPanel.java   Source Code and License 6 votes vote down vote up
Map2DOptionsPanel(Map2DOptionsOptionsPanelController controller) {
    this.controller = controller;
    this.config = new CompositeConfiguration();
    initComponents();
    colorList.addListSelectionListener(new ListSelectionListener() {
        @Override
        public void valueChanged(ListSelectionEvent e) {
            if (colorList.getSelectedValuesList().size() > 0) {
                btnChangeColor.setEnabled(true);
                btnMoveColorUp.setEnabled(true);
                btnMoveDown.setEnabled(true);
                btnRemoveColor.setEnabled(true);
            } else {
                btnChangeColor.setEnabled(false);
                btnMoveColorUp.setEnabled(false);
                btnMoveDown.setEnabled(false);
                btnRemoveColor.setEnabled(false);
            }
        }
    });
}
 
Example 17
Project: javamail4ews   File: Util.java   Source Code and License 6 votes vote down vote up
public static Configuration getConfiguration(Session pSession) {
	try {
		PropertiesConfiguration prop = new PropertiesConfiguration();
		for(Object aKey : pSession.getProperties().keySet()) {
			Object aValue = pSession.getProperties().get(aKey);

			prop.addProperty(aKey.toString(), aValue);
		}

		CompositeConfiguration config = new CompositeConfiguration();
		config.addConfiguration(prop);
		URL lURL = Thread.currentThread().getContextClassLoader().getResource("javamail-ews-bridge.default.properties");
		config.addConfiguration(new PropertiesConfiguration(lURL));
		return config;
	} catch (ConfigurationException e) {
		throw new RuntimeException(e.getMessage(), e);
	}
}
 
Example 18
Project: laughing-octo-sansa   File: BiddingLogWorkflow.java   Source Code and License 6 votes vote down vote up
public static void main(String[] args) throws ConfigurationException {
        log.setLevel(Level.DEBUG);

        CompositeConfiguration conf = new CompositeConfiguration();
        conf.addConfiguration(new PropertiesConfiguration("kafka.properties"));
        conf.addConfiguration(new PropertiesConfiguration("cassandra.properties"));
        conf.addConfiguration(new PropertiesConfiguration("spark.properties"));
        conf.addConfiguration(new PropertiesConfiguration("es.properties"));

//        Path filePath = Paths.get("/media/sf_Download/ipinyou/new");
//        Path filePath = Paths.get("/media/sf_Download/data/iPinYou/ipinyou.contest.dataset_unpacked/training2nd/data");


//        Path filePath = Paths.get("/media/sf_Download/data/mors/new");
        Path filePath = Paths.get("/media/sf_Download/data/mors/cassandra_test"); // Cassandra TEST
        String esIdxSuffix = "log_%s/bid";

        BiddingLogWorkflow wf = new BiddingLogWorkflow();

        try {
            wf.runBatch(conf, filePath, esIdxSuffix);
        } catch (Exception e) {
            e.printStackTrace();
        }
    }
 
Example 19
Project: laughing-octo-sansa   File: PredictionFlow.java   Source Code and License 6 votes vote down vote up
public static void main(String[] args) throws ConfigurationException {
    PredictionFlow workflow = new PredictionFlow();
    log.setLevel(Level.DEBUG);

    CompositeConfiguration conf = new CompositeConfiguration();
    conf.addConfiguration(new PropertiesConfiguration("kafka.properties"));
    conf.addConfiguration(new PropertiesConfiguration("spark.properties"));
    conf.addConfiguration(new PropertiesConfiguration("cassandra.properties"));
    conf.addConfiguration(new PropertiesConfiguration("es.properties"));

    try {
        workflow.run(conf);
    } catch (Exception e) {
        e.printStackTrace();
    }
}
 
Example 20
Project: laughing-octo-sansa   File: StreamingUserTypeClassification.java   Source Code and License 6 votes vote down vote up
public static void main(String[] args) throws ConfigurationException {
    StreamingUserTypeClassification workflow = new StreamingUserTypeClassification();
    log.setLevel(Level.DEBUG);

    CompositeConfiguration conf = new CompositeConfiguration();
    conf.addConfiguration(new PropertiesConfiguration("kafka.properties"));
    conf.addConfiguration(new PropertiesConfiguration("spark.properties"));
    conf.addConfiguration(new PropertiesConfiguration("es.properties"));

    try {
        workflow.run(conf);
    } catch (Exception e) {
        e.printStackTrace();
    }

}
 
Example 21
Project: laughing-octo-sansa   File: KafkaSparkCassandraFlow.java   Source Code and License 6 votes vote down vote up
public static void main(String[] args) throws ConfigurationException {
    KafkaSparkCassandraFlow workflow = new KafkaSparkCassandraFlow();
    log.setLevel(Level.DEBUG);

    CompositeConfiguration conf = new CompositeConfiguration();
    conf.addConfiguration(new PropertiesConfiguration("kafka.properties"));
    conf.addConfiguration(new PropertiesConfiguration("spark.properties"));
    conf.addConfiguration(new PropertiesConfiguration("cassandra.properties"));

    try {
        workflow.run(conf);
    } catch (Exception e) {
        e.printStackTrace();
    }

}
 
Example 22
Project: laughing-octo-sansa   File: KafkaSparkEsFlow.java   Source Code and License 6 votes vote down vote up
public static void main(String[] args) throws ConfigurationException {
    KafkaSparkEsFlow workflow = new KafkaSparkEsFlow();
    log.setLevel(Level.DEBUG);

    CompositeConfiguration conf = new CompositeConfiguration();
    conf.addConfiguration(new PropertiesConfiguration("kafka.properties"));
    conf.addConfiguration(new PropertiesConfiguration("spark.properties"));
    conf.addConfiguration(new PropertiesConfiguration("es.properties"));

    try {
        workflow.run(conf);
    } catch (Exception e) {
        e.printStackTrace();
    }

}
 
Example 23
Project: laughing-octo-sansa   File: FacebookSparkCrawler.java   Source Code and License 6 votes vote down vote up
private void run(CompositeConfiguration conf) {
    // Spark conf
    SparkConf sparkConf = new SparkConf().setAppName("TwitterSparkCrawler").setMaster(conf.getString("spark.master"))
            .set("spark.serializer", conf.getString("spark.serializer"))
            .registerKryoClasses(new Class<?>[] { Parameter.class, BatchRequestBuilder.class, BatchRequest.class });
    JavaStreamingContext jssc = new JavaStreamingContext(sparkConf, Durations.seconds(conf.getLong("stream.duration")));

    // Create facebook stream
    Parameter typeParam = Parameter.with("type", "event");
    FacebookUtils
            .createStream(jssc, conf.getString("access.token"),
                    new BatchRequestBuilder[] {
                            new BatchRequestBuilder("search").parameters(new Parameter[] { Parameter.with("q", "car"), typeParam }) })
            .print();

    // Start the computation
    jssc.start();
    jssc.awaitTermination();
}
 
Example 24
Project: kork   File: ArchaiusConfiguration.java   Source Code and License 6 votes vote down vote up
public ArchaiusInitializingBeanPostProcessor(ConfigurableApplicationContext applicationContext, AbstractPollingScheduler pollingScheduler, SpringEnvironmentPolledConfigurationSource polledConfigurationSource, List<ClasspathPropertySource> propertyBindings) {
  this.applicationContext = Objects.requireNonNull(applicationContext, "applicationContext");
  this.pollingScheduler = Objects.requireNonNull(pollingScheduler, "pollingScheduler");
  this.polledConfigurationSource = Objects.requireNonNull(polledConfigurationSource, "polledConfigurationSource");
  this.propertyBindings = propertyBindings != null ? propertyBindings : Collections.emptyList();
  initPropertyBindings();

  configurationInstance = new DynamicConfiguration(polledConfigurationSource, pollingScheduler);
  if (!ConfigurationManager.isConfigurationInstalled()) {
    ConfigurationManager.install(new CompositeConfiguration());
  }
  CompositeConfiguration config = (CompositeConfiguration) ConfigurationManager.getConfigInstance();
  config.addConfiguration(configurationInstance);

  applicationContext.getBeanFactory().registerSingleton("environmentBackedConfig", ConfigurationManager.getConfigInstance());
  applicationContext.getBeanFactory().registerAlias("environmentBackedConfig", "abstractConfiguration");
}
 
Example 25
Project: andes   File: FirewallConfiguration.java   Source Code and License 6 votes vote down vote up
@Override
public void validateConfiguration() throws ConfigurationException
{
    // Valid Configuration either has xml links to new files
    _finalConfig = new CompositeConfiguration(_configuration);
    List subFiles = _configuration.getList("xml[@fileName]");
    for (Object subFile : subFiles)
    {
        _finalConfig.addConfiguration(new XMLConfiguration((String) subFile));
    }

    // all rules must have an access attribute or a default value
    if (_finalConfig.getList("rule[@access]").size() == 0 &&
        _configuration.getString("[@default-action]") == null)
    {
        throw new ConfigurationException("No rules or default-action found in firewall configuration.");
    }
}
 
Example 26
Project: andes   File: VirtualHostConfiguration.java   Source Code and License 6 votes vote down vote up
/**
 * Apply the given configuration to this VirtualHostConfiguration
 *
 * @param config
 *         the config to apply
 * @throws ConfigurationException
 *         if a problem occurs with configuration
 */
public void setConfiguration(Configuration config) throws ConfigurationException {
    setConfiguration("virtualhosts.virtualhost", config);

    Iterator i = getListValue("queues.queue.name").iterator();

    while (i.hasNext()) {
        String queueName = (String) i.next();
        _queues.put(queueName, new QueueConfiguration(queueName, this));
    }

    i = getListValue("exchanges.exchange.name").iterator();
    int count = 0;
    while (i.hasNext()) {
        CompositeConfiguration mungedConf = new CompositeConfiguration();
        mungedConf.addConfiguration(config.subset("exchanges.exchange(" + count++ + ")"));
        mungedConf.addConfiguration(_configuration.subset("exchanges"));
        String exchName = (String) i.next();
        _exchanges.put(exchName, new ExchangeConfiguration(exchName, mungedConf));
    }
}
 
Example 27
Project: andes   File: PrincipalDatabaseAuthenticationManagerTest.java   Source Code and License 6 votes vote down vote up
private ConfigurationPlugin getConfig(final String clazz, final String argName, final String argValue) throws Exception
{
    final ConfigurationPlugin config = new PrincipalDatabaseAuthenticationManager.PrincipalDatabaseAuthenticationManagerConfiguration();

    XMLConfiguration xmlconfig = new XMLConfiguration();
    xmlconfig.addProperty("pd-auth-manager.principal-database.class", clazz);

    if (argName != null)
    {
        xmlconfig.addProperty("pd-auth-manager.principal-database.attributes.attribute.name", argName);
        xmlconfig.addProperty("pd-auth-manager.principal-database.attributes.attribute.value", argValue);
    }

    // Create a CompositeConfiguration as this is what the broker uses
    CompositeConfiguration composite = new CompositeConfiguration();
    composite.addConfiguration(xmlconfig);
    config.setConfiguration("security", xmlconfig);
    return config;
}
 
Example 28
Project: andes   File: SlowConsumerDetectionPolicyConfigurationTest.java   Source Code and License 6 votes vote down vote up
/**
 * Failure Testing:
 *
 * Test that providing a configuration section without the 'name' field
 * causes an exception to be thrown.
 *
 * An empty configuration is provided and the thrown exception message
 * is checked to confirm the right reason. 
 *
 */
public void testConfigLoadingInValidConfig()
{
    SlowConsumerDetectionPolicyConfiguration config = new SlowConsumerDetectionPolicyConfiguration();

    XMLConfiguration xmlconfig = new XMLConfiguration();


    // Create a CompositeConfiguration as this is what the broker uses
    CompositeConfiguration composite = new CompositeConfiguration();
    composite.addConfiguration(xmlconfig);

    try
    {
        config.setConfiguration("", composite);
        fail("Config is invalid so won't validate.");            
    }
    catch (ConfigurationException e)
    {
        e.printStackTrace();
        assertEquals("Exception message not as expected.", "No Slow consumer policy defined.", e.getMessage());
    }
}
 
Example 29
Project: andes   File: SlowConsumerDetectionQueueConfigurationTest.java   Source Code and License 6 votes vote down vote up
/**
 * Test a fully loaded configuration file.
 *
 * It is not an error to have all control values specified.
 * <p>
 * Here we need to catch the {@link ConfigurationException} that ensues due to lack
 * of a policy plugin.
 */
public void testConfigLoadingValidConfig()
{
    SlowConsumerDetectionQueueConfiguration config = new SlowConsumerDetectionQueueConfiguration();

    XMLConfiguration xmlconfig = new XMLConfiguration();

    xmlconfig.addProperty("messageAge", "60000");
    xmlconfig.addProperty("depth", "1024");
    xmlconfig.addProperty("messageCount", "10");

    // Create a CompositeConfiguration as this is what the broker uses
    CompositeConfiguration composite = new CompositeConfiguration();
    composite.addConfiguration(xmlconfig);

    try
    {
        config.setConfiguration("", composite);
        fail("No Policies are avaialbe to load in a unit test");
    }
    catch (ConfigurationException e)
    {
        assertTrue("Exception message incorrect, was: " + e.getMessage(),
                e.getMessage().startsWith("No Slow Consumer Policy specified. Known Policies:["));
    }
}
 
Example 30
Project: andes   File: SlowConsumerDetectionQueueConfigurationTest.java   Source Code and License 6 votes vote down vote up
/**
 * When we do not specify any control value then a {@link ConfigurationException}
 * must be thrown to remind us.
 */
public void testConfigLoadingMissingConfig()
{
    SlowConsumerDetectionQueueConfiguration config = new SlowConsumerDetectionQueueConfiguration();

    XMLConfiguration xmlconfig = new XMLConfiguration();

    // Create a CompositeConfiguration as this is what the broker uses
    CompositeConfiguration composite = new CompositeConfiguration();
    composite.addConfiguration(xmlconfig);

    try
    {
        config.setConfiguration("", composite);
        fail("No Policies are avaialbe to load in a unit test");
    }
    catch (ConfigurationException e)
    {

        assertEquals("At least one configuration property('messageAge','depth'" +
                     " or 'messageCount') must be specified.", e.getMessage());
    }
}
 
Example 31
Project: andes   File: SlowConsumerDetectionQueueConfigurationTest.java   Source Code and License 6 votes vote down vote up
/**
 * Setting messageAge on its own is enough to have a valid configuration
 *
 * Here we need to catch the {@link ConfigurationException} that ensues due to lack
 * of a policy plugin.
 */
public void testConfigLoadingMessageAgeOk()
{
    SlowConsumerDetectionQueueConfiguration config = new SlowConsumerDetectionQueueConfiguration();

    XMLConfiguration xmlconfig = new XMLConfiguration();
    xmlconfig.addProperty("messageAge", "60000");

    // Create a CompositeConfiguration as this is what the broker uses
    CompositeConfiguration composite = new CompositeConfiguration();
    composite.addConfiguration(xmlconfig);

    try
    {
        config.setConfiguration("", composite);
        fail("No Policies are avaialbe to load in a unit test");
    }
    catch (ConfigurationException e)
    {
        assertTrue("Exception message incorrect, was: " + e.getMessage(),
                e.getMessage().startsWith("No Slow Consumer Policy specified. Known Policies:["));
    }
}
 
Example 32
Project: andes   File: SlowConsumerDetectionQueueConfigurationTest.java   Source Code and License 6 votes vote down vote up
/**
 * Setting depth on its own is enough to have a valid configuration.
 *
 * Here we need to catch the {@link ConfigurationException} that ensues due to lack
 * of a policy plugin.
 */
public void testConfigLoadingDepthOk()
{
    SlowConsumerDetectionQueueConfiguration config = new SlowConsumerDetectionQueueConfiguration();

    XMLConfiguration xmlconfig = new XMLConfiguration();
    xmlconfig.addProperty("depth", "1024");

    // Create a CompositeConfiguration as this is what the broker uses
    CompositeConfiguration composite = new CompositeConfiguration();
    composite.addConfiguration(xmlconfig);

    try
    {
        config.setConfiguration("", composite);
        fail("No Policies are avaialbe to load in a unit test");
    }
    catch (ConfigurationException e)
    {
        assertTrue("Exception message incorrect, was: " + e.getMessage(),
                e.getMessage().startsWith("No Slow Consumer Policy specified. Known Policies:["));
    }
}
 
Example 33
Project: andes   File: SlowConsumerDetectionQueueConfigurationTest.java   Source Code and License 6 votes vote down vote up
/**
 * Setting messageCount on its own is enough to have a valid configuration.
 *
 * Here we need to catch the {@link ConfigurationException} that ensues due to lack
 * of a policy plugin.
 */
public void testConfigLoadingMessageCountOk()
{
    SlowConsumerDetectionQueueConfiguration config = new SlowConsumerDetectionQueueConfiguration();

    XMLConfiguration xmlconfig = new XMLConfiguration();
    xmlconfig.addProperty("messageCount", "10");

    // Create a CompositeConfiguration as this is what the broker uses
    CompositeConfiguration composite = new CompositeConfiguration();
    composite.addConfiguration(xmlconfig);

    try
    {
        config.setConfiguration("", composite);
        fail("No Policies are avaialbe to load in a unit test");
    }
    catch (ConfigurationException e)
    {
        assertTrue("Exception message incorrect, was: " + e.getMessage(),
                e.getMessage().startsWith("No Slow Consumer Policy specified. Known Policies:["));
    }
}
 
Example 34
Project: andes   File: TopicDeletePolicyConfigurationTest.java   Source Code and License 6 votes vote down vote up
/**
 * Test that with the correct configuration the deletePersistent option can
 * be enabled.
 *
 * Test creates a new Configuration object and passes in the xml snippet
 * that the ConfigurationPlugin would receive during normal execution.
 * This is the XML that would be matched for this plugin:
 * <topicdelete>
 *   <delete-persistent>
 * <topicdelete>
 *
 * So it would be subset and passed in as just:
 *   <delete-persistent>
 *
 *
 * The property should therefore be enabled. 
 *
 */
public void testConfigDeletePersistent()
{
    TopicDeletePolicyConfiguration config = new TopicDeletePolicyConfiguration();

    XMLConfiguration xmlconfig = new XMLConfiguration();

    xmlconfig.addProperty("delete-persistent","");

    // Create a CompositeConfiguration as this is what the broker uses
    CompositeConfiguration composite = new CompositeConfiguration();
    composite.addConfiguration(xmlconfig);

    try
    {
        config.setConfiguration("",composite);
    }
    catch (ConfigurationException e)
    {
        fail(e.getMessage());
    }

    assertTrue("A configured TopicDelete should delete persistent queues.",
                config.deletePersistent());
}
 
Example 35
Project: andes   File: SlowConsumerDetectionConfigurationTest.java   Source Code and License 6 votes vote down vote up
/**
 * Default Testing:
 *
 * Test Missing TimeUnit value gets default.
 *
 * The TimeUnit value is optional and default to SECONDS.
 *
 * Test that if we do not specify a TimeUnit then we correctly get seconds.
 *
 * Also verify that relying on the default does not impact the setting of
 * the 'delay' value.
 *
 */
public void testConfigLoadingMissingTimeUnitDefaults()
{
    SlowConsumerDetectionConfiguration config = new SlowConsumerDetectionConfiguration();

    XMLConfiguration xmlconfig = new XMLConfiguration();

    long DELAY=10;
    xmlconfig.addProperty("delay", String.valueOf(DELAY));

    // Create a CompositeConfiguration as this is what the broker uses
    CompositeConfiguration composite = new CompositeConfiguration();
    composite.addConfiguration(xmlconfig);
    try
    {
        config.setConfiguration("", composite);
    }
    catch (ConfigurationException e)
    {
        e.printStackTrace();
        fail(e.getMessage());
    }

    assertEquals("Delay not correctly returned.", DELAY, config.getDelay());
    assertEquals("Default TimeUnit incorrect", TimeUnit.SECONDS, config.getTimeUnit());
}
 
Example 36
Project: andes   File: SlowConsumerDetectionConfigurationTest.java   Source Code and License 6 votes vote down vote up
/**
 * Failure Testing:
 *
 * Test that delay must be long not a string value.
 * Provide a delay as a written value not a long. 'ten'.
 *
 * This should throw a configuration exception which is being trapped and
 * verified to be the right exception, a NumberFormatException.
 *
 */
public void testConfigLoadingInValidDelayString()
{
    SlowConsumerDetectionConfiguration config = new SlowConsumerDetectionConfiguration();

    XMLConfiguration xmlconfig = new XMLConfiguration();

    xmlconfig.addProperty("delay", "ten");
    xmlconfig.addProperty("timeunit", TimeUnit.MICROSECONDS.toString());

    // Create a CompositeConfiguration as this is what the broker uses
    CompositeConfiguration composite = new CompositeConfiguration();
    composite.addConfiguration(xmlconfig);

    try
    {
        config.setConfiguration("", composite);
        fail("Configuration should fail to validate");
    }
    catch (ConfigurationException e)
    {
        Throwable cause = e.getCause();

        assertEquals("Cause not correct", NumberFormatException.class, cause.getClass());
    }
}
 
Example 37
Project: andes   File: SlowConsumerDetectionConfigurationTest.java   Source Code and License 6 votes vote down vote up
/**
 * Failure Testing:
 *
 * Test that missing delay fails.
 * If we have no delay then we do not pick a default. So a Configuration
 * Exception is thrown.
 *
 * */
public void testConfigLoadingInValidMissingDelay()
{
    SlowConsumerDetectionConfiguration config = new SlowConsumerDetectionConfiguration();

    XMLConfiguration xmlconfig = new XMLConfiguration();

    xmlconfig.addProperty("timeunit", TimeUnit.SECONDS.toString());

    // Create a CompositeConfiguration as this is what the broker uses
    CompositeConfiguration composite = new CompositeConfiguration();
    composite.addConfiguration(xmlconfig);
    try
    {
        config.setConfiguration("", composite);
        fail("Configuration should fail to validate");
    }
    catch (ConfigurationException e)
    {
        assertEquals("Incorrect message.", "SlowConsumerDetectionConfiguration: unable to configure invalid delay:null", e.getMessage());
    }
}
 
Example 38
Project: andes   File: SlowConsumerDetectionConfigurationTest.java   Source Code and License 6 votes vote down vote up
/**
 * Failure Testing:
 *
 * Test that erroneous TimeUnit fails.
 *
 * Valid TimeUnit values vary based on the JVM version i.e. 1.6 added HOURS/DAYS etc.
 *
 * We don't test the values for TimeUnit are accepted other than MILLISECONDS in the
 * positive testing at the start.
 *
 * Here we ensure that an erroneous for TimeUnit correctly throws an exception.
 *
 * We test with 'foo', which will never be a TimeUnit
 *
 */
public void testConfigLoadingInValidTimeUnit()
{
    SlowConsumerDetectionConfiguration config = new SlowConsumerDetectionConfiguration();

    String TIMEUNIT = "foo";
    XMLConfiguration xmlconfig = new XMLConfiguration();

    xmlconfig.addProperty("delay", "10");
    xmlconfig.addProperty("timeunit", TIMEUNIT);

    // Create a CompositeConfiguration as this is what the broker uses
    CompositeConfiguration composite = new CompositeConfiguration();
    composite.addConfiguration(xmlconfig);
    try
    {
        config.setConfiguration("", composite);
        fail("Configuration should fail to validate");
    }
    catch (ConfigurationException e)
    {
        assertEquals("Incorrect message.", "Unable to configure Slow Consumer Detection invalid TimeUnit:" + TIMEUNIT, e.getMessage());
    }
}
 
Example 39
Project: opennms-provisioning-integration-server   File: GlobalApacheConfiguration.java   Source Code and License 6 votes vote down vote up
private static org.apache.commons.configuration.Configuration createConfig(final Path base) {
    // Load system and file properties
    final org.apache.commons.configuration.SystemConfiguration systemConfig;
    final org.apache.commons.configuration.PropertiesConfiguration propertiesConfig;
    try {
        systemConfig = new org.apache.commons.configuration.SystemConfiguration();
        
        propertiesConfig = new org.apache.commons.configuration.PropertiesConfiguration(base.resolve("global.properties").toFile());
        
    } catch (final ConfigurationException ex) {
        throw new RuntimeException(ex);
    }
    
    // Build composition of system properties and config file
    return new CompositeConfiguration() {{
        addConfiguration(systemConfig);
        addConfiguration(propertiesConfig);

        setThrowExceptionOnMissing(true);
    }};
}
 
Example 40
Project: artifactory_ssh_proxy   File: SshdSettingsBuilder.java   Source Code and License 6 votes vote down vote up
protected Configuration createConfiguration(final String overriddenPath) {
    try {

        if (LOGGER.isDebugEnabled()) {
            LOGGER.debug("got overriddenPath {}", overriddenPath);
        }

        CompositeConfiguration compositeConfig = new CompositeConfiguration();
        // TODO: see how Systems and properties interact.
        compositeConfig.addConfiguration(new SystemConfiguration());
        compositeConfig.addConfiguration(findPropertiesConfiguration(overriddenPath));

        return compositeConfig;
    } catch (ConfigurationException e) {
        throw new RuntimeException(e);
    }
}
 
Example 41
Project: Runway-SDK   File: CommonsConfigurationReader.java   Source Code and License 6 votes vote down vote up
public CommonsConfigurationReader(ConfigGroupIF group, String config, CompositeConfiguration _cconfig)
{
  this.cconfig = _cconfig;
  
  try
  {
    URL resource = ConfigurationManager.getResource(group, config);
    
    cconfig.addConfiguration(new PropertiesConfiguration(resource));
    interpolate();
    CommonsConfigurationResolver.getInMemoryConfigurator().addInterpolateDependency(this);
  }
  catch (ConfigurationException e)
  {
    throw new RunwayConfigurationException(e);
  }
}
 
Example 42
Project: Runway-SDK   File: CommonsConfigurationTest.java   Source Code and License 6 votes vote down vote up
@Test
public void testCommonsConfigOverride()
{
  BaseConfiguration bc = new BaseConfiguration();
  BaseConfiguration bc2 = new BaseConfiguration();

  bc2.addProperty("test.prop", 52);

  CompositeConfiguration cconfig = new CompositeConfiguration();
  cconfig.addConfiguration(bc);
  cconfig.addConfiguration(bc2);

  bc.addProperty("test.prop", 112);

  Assert.assertEquals(112, cconfig.getInt("test.prop"));
}
 
Example 43
Project: Runway-SDK   File: CommonsConfigurationTest.java   Source Code and License 6 votes vote down vote up
@Test
public void testCommonsConfigOverrideSetVsAdd()
{
  BaseConfiguration bc = new BaseConfiguration();
  BaseConfiguration bc2 = new BaseConfiguration();

  bc2.addProperty("test.prop", 52);

  CompositeConfiguration cconfig = new CompositeConfiguration();
  cconfig.addConfiguration(bc);
  cconfig.addConfiguration(bc2);

  bc.setProperty("test.prop", 112);

  Assert.assertEquals(112, cconfig.getInt("test.prop"));
}
 
Example 44
Project: appframework   File: ConfigUtil.java   Source Code and License 6 votes vote down vote up
private synchronized static void init() {
    try {
        config = new CompositeConfiguration();
        config.setLogger(log);

        // 1 SystemConfiguration
        SystemConfiguration configSys = new SystemConfiguration();

        cfgMap = new HashMap<String, Configuration>();

        cfgMap.put("system", configSys);
        config.addConfiguration(configSys);
        log.debug("loading System Properties");

    } catch (Exception e) {
        log.error("load config file failed: " + ExceptionUtils.getFullStackTrace(e));
    }
}
 
Example 45
Project: jbake   File: Main.java   Source Code and License 6 votes vote down vote up
private void initStructure(CompositeConfiguration config, String type, String source) {
       Init init = new Init(config);
	try {
           File templateFolder = FileUtil.getRunningLocation();
           File outputFolder;
           if(source != null){
               outputFolder = new File(source);
           } else{
               outputFolder = new File(".");
           }
           init.run(outputFolder, templateFolder, type);
		System.out.println("Base folder structure successfully created.");
	} catch (final Exception e) {
		final String msg = "Failed to initialise structure: " + e.getMessage();
		throw new JBakeException(msg, e);
	}
}
 
Example 46
Project: jbake   File: Baker.java   Source Code and License 6 votes vote down vote up
public void bake(final LaunchOptions options, final CompositeConfiguration config) {
    final Oven oven = new Oven(options.getSource(), options.getDestination(), config, options.isClearCache());
    oven.setupPaths();
    oven.bake();

    final List<Throwable> errors = oven.getErrors();
    if (!errors.isEmpty()) {
        final StringBuilder msg = new StringBuilder();
        // TODO: decide, if we want the all errors here
        msg.append( MessageFormat.format("JBake failed with {0} errors:\n", errors.size()));
        int errNr = 1;
        for (final Throwable error : errors) {
            msg.append(MessageFormat.format("{0}. {1}\n", errNr, error.getMessage()));
            ++errNr;
        }
        throw new JBakeException(msg.toString(), errors.get(0));
    }
}
 
Example 47
Project: jbake   File: BakeWatcher.java   Source Code and License 6 votes vote down vote up
/**
 * Starts watching the file system for changes to trigger a bake.
 *
 * @param res Commandline options
 * @param config Configuration settings
 */
public void start(final LaunchOptions res, CompositeConfiguration config) {
    try {
        FileSystemManager fsMan = VFS.getManager();
        FileObject listenPath = fsMan.resolveFile(res.getSource(), config.getString( ConfigUtil.Keys.CONTENT_FOLDER));
        FileObject templateListenPath = fsMan.resolveFile(res.getSource(), config.getString( ConfigUtil.Keys.TEMPLATE_FOLDER));
        FileObject assetPath = fsMan.resolveFile(res.getSource(), config.getString( ConfigUtil.Keys.ASSET_FOLDER));


        System.out.println("Watching for (content, template, asset) changes in [" + res.getSource() + "]");
        DefaultFileMonitor monitor = new DefaultFileMonitor(new CustomFSChangeListener(res, config));
        monitor.setRecursive(true);
        monitor.addFile(listenPath);
        monitor.addFile(templateListenPath);
        monitor.addFile(assetPath);
        monitor.start();
    } catch (FileSystemException e) {
        e.printStackTrace();
    }
}
 
Example 48
Project: jbake   File: IndexRenderer.java   Source Code and License 6 votes vote down vote up
@Override
public int render(Renderer renderer, ContentStore db, File destination, File templatesPath, CompositeConfiguration config) throws RenderingException {
    if (config.getBoolean(Keys.RENDER_INDEX)) {
        try {
            if (shouldPaginateIndex(config)) {
                renderer.renderIndexPaging(config.getString(Keys.INDEX_FILE));
            } else {
                renderer.renderIndex(config.getString(Keys.INDEX_FILE));
            }
            return 1;
        } catch (Exception e) {
            throw new RenderingException(e);
        }
    } else {
        return 0;
    }
}
 
Example 49
Project: jbake   File: ConfigUtil.java   Source Code and License 6 votes vote down vote up
public static CompositeConfiguration load(File source, boolean isRunServer) throws ConfigurationException {
      CompositeConfiguration config = new CompositeConfiguration();
      config.setListDelimiter(',');
      File customConfigFile = new File(source, LEGACY_CONFIG_FILE);
      if (customConfigFile.exists()) {
      	LEGACY_CONFIG_FILE_EXISTS = true;
          config.addConfiguration(new PropertiesConfiguration(customConfigFile));
      }
      customConfigFile = new File(source, CONFIG_FILE);
      if (customConfigFile.exists()) {
          config.addConfiguration(new PropertiesConfiguration(customConfigFile));
      }
      config.addConfiguration(new PropertiesConfiguration(DEFAULT_CONFIG_FILE));
      config.addConfiguration(new SystemConfiguration());
      if (isRunServer) {
	String port = config.getString(Keys.SERVER_PORT);
	config.setProperty(Keys.SITE_HOST, "http://localhost:"+port);
}
      return config;
  }
 
Example 50
Project: jbake   File: IndexRendererTest.java   Source Code and License 6 votes vote down vote up
@Test(expected = RenderingException.class)
public void propagatesRenderingException() throws Exception {
    IndexRenderer renderer = new IndexRenderer();

    CompositeConfiguration compositeConfiguration = new MockCompositeConfiguration().withDefaultBoolean(true);
    compositeConfiguration.setProperty(PAGINATE_INDEX, false);
    ContentStore contentStore = mock(ContentStore.class);
    Renderer mockRenderer = mock(Renderer.class);

    doThrow(new Exception()).when(mockRenderer).renderIndex(anyString());

    int renderResponse = renderer.render(mockRenderer, contentStore,
            new File("fake"), new File("fake"), compositeConfiguration);

    verify(mockRenderer, never()).renderIndex("random string");
}
 
Example 51
Project: jbake   File: TagsRendererTest.java   Source Code and License 6 votes vote down vote up
@Test
public void returnsOneWhenConfigRendersIndices() throws Exception {
    TagsRenderer renderer = new TagsRenderer();

    CompositeConfiguration compositeConfiguration = new MockCompositeConfiguration().withDefaultBoolean(true);
    ContentStore contentStore = mock(ContentStore.class);
    Renderer mockRenderer = mock(Renderer.class);

    Set<String> tags = new HashSet<String>(Arrays.asList("tag1", "tags2"));
    when(contentStore.getTags()).thenReturn(tags);

    when(mockRenderer.renderTags("random string")).thenReturn(1);

    int renderResponse = renderer.render(mockRenderer, contentStore,
            new File("fake"), new File("fake"), compositeConfiguration);

    assertThat(renderResponse).isEqualTo(1);
}
 
Example 52
Project: jbake   File: TagsRendererTest.java   Source Code and License 6 votes vote down vote up
@Test
public void doesRenderWhenConfigDoesNotRenderIndices() throws Exception {
    TagsRenderer renderer = new TagsRenderer();

    CompositeConfiguration compositeConfiguration = new MockCompositeConfiguration().withDefaultBoolean(true);
    ContentStore contentStore = mock(ContentStore.class);
    Renderer mockRenderer = mock(Renderer.class);

    Set<String> tags = new HashSet<String>(Arrays.asList("tag1", "tags2"));
    when(contentStore.getTags()).thenReturn(tags);

    int renderResponse = renderer.render(mockRenderer, contentStore,
            new File("fake"), new File("fake"), compositeConfiguration);

    verify(mockRenderer, times(1)).renderTags("random string");
}
 
Example 53
Project: glados-wiki   File: GroovyConfigurer.java   Source Code and License 6 votes vote down vote up
private Optional<String> getUserConfigFilename() throws NamingException {
    CompositeConfiguration cc = new CompositeConfiguration();
    JNDIConfiguration jndi = new JNDIConfiguration();
    EnvironmentConfiguration env = new EnvironmentConfiguration();
    SystemConfiguration jvm = new SystemConfiguration();
    cc.addConfiguration(jvm);
    cc.addConfiguration(env);
    cc.addConfiguration(jndi);
    //
    final String CONFIG_FILENAME = (String) cc.getProperty("gladosWiki_configFile");
    if (false == Strings.isNullOrEmpty(CONFIG_FILENAME)) {
        LOG.debug(String.format("LOCAL-CONFIG CONFIG_FILENAME = %s", CONFIG_FILENAME));
        return Optional.of(CONFIG_FILENAME);
    } else {
        return Optional.absent();
    }
}
 
Example 54
Project: jbake-rtl-jalaali   File: Main.java   Source Code and License 5 votes vote down vote up
protected void run(String[] args) {
	SLF4JBridgeHandler.removeHandlersForRootLogger();
	SLF4JBridgeHandler.install();
	LaunchOptions res = parseArguments( args );

	final CompositeConfiguration config;
	try {
		config = ConfigUtil.load( res.getSource() );
	} catch( final ConfigurationException e ) {
		throw new JBakeException( "Configuration error: " + e.getMessage(), e );
	}

	run(res, config);
}
 
Example 55
Project: jbake-rtl-jalaali   File: BakeWatcher.java   Source Code and License 5 votes vote down vote up
/**
 * Starts watching the file system for changes to trigger a bake.
 *
 * @param res Commandline options
 * @param config Configuration settings
 */
public void start(final LaunchOptions res, CompositeConfiguration config) {
    try {
        FileSystemManager fsMan = VFS.getManager();
        FileObject listenPath = fsMan.resolveFile(res.getSource(), config.getString( ConfigUtil.Keys.CONTENT_FOLDER));

        System.out.println("Watching for changes in [" + res.getSource() + "]");
        DefaultFileMonitor monitor = new DefaultFileMonitor(new CustomFSChangeListener(res, config));
        monitor.setRecursive(true);
        monitor.addFile(listenPath);
        monitor.start();
    } catch (FileSystemException e) {
        e.printStackTrace();
    }
}
 
Example 56
Project: jbake-rtl-jalaali   File: SitemapRenderer.java   Source Code and License 5 votes vote down vote up
@Override
public int render(Renderer renderer, ContentStore db, File destination, File templatesPath, CompositeConfiguration config) throws RenderingException {
	if (config.getBoolean(Keys.RENDER_SITEMAP)) {
		try {
			renderer.renderSitemap(config.getString(Keys.SITEMAP_FILE));
			return 1;
		} catch (Exception e) {
			throw new RenderingException(e);
		}
	} else {
		return 0;
	}
}
 
Example 57
Project: jbake-rtl-jalaali   File: ArchiveRenderer.java   Source Code and License 5 votes vote down vote up
@Override
public int render(Renderer renderer, ContentStore db, File destination, File templatesPath, CompositeConfiguration config) throws RenderingException {
	if (config.getBoolean(Keys.RENDER_ARCHIVE)) {
		try {
			renderer.renderArchive(config.getString(Keys.ARCHIVE_FILE));
			return 1;
		} catch (Exception e) {
			throw new RenderingException(e);
		}
	} else {
		return 0;
	}
}
 
Example 58
Project: jbake-rtl-jalaali   File: FeedRenderer.java   Source Code and License 5 votes vote down vote up
@Override
public int render(Renderer renderer, ContentStore db, File destination, File templatesPath, CompositeConfiguration config) throws RenderingException {
	if (config.getBoolean(Keys.RENDER_FEED)) {
		try {
			renderer.renderFeed(config.getString(Keys.FEED_FILE));
			return 1;
		} catch (Exception e) {
			throw new RenderingException(e);
		}
	} else {
		return 0;
	}
}
 
Example 59
Project: jbake-rtl-jalaali   File: TagsRenderer.java   Source Code and License 5 votes vote down vote up
@Override
public int render(Renderer renderer, ContentStore db, File destination, File templatesPath, CompositeConfiguration config) throws RenderingException {
	if (config.getBoolean(Keys.RENDER_TAGS)) {
		try {
			return renderer.renderTags(config.getString(Keys.TAG_PATH));
		} catch (Exception e) {
			throw new RenderingException(e);
		}
	} else {
		return 0;
	}
}
 
Example 60
Project: jbake-rtl-jalaali   File: Crawler.java   Source Code and License 5 votes vote down vote up
/**
 * Creates new instance of Crawler.
 */
public Crawler(ContentStore db, File source, CompositeConfiguration config) {
    this.db = db;
    this.config = config;
    this.contentPath = source.getPath() + separator + config.getString(ConfigUtil.Keys.CONTENT_FOLDER);
    this.parser = new Parser(config, contentPath);
}