org.apache.commons.configuration2.Configuration Java Examples

The following examples show how to use org.apache.commons.configuration2.Configuration. You can vote up the ones you like or vote down the ones you don't like, and go to the original project or source file by following the links above each example. You may check out the related API usage on the sidebar.
Example #1
Source File: DriverRemoteConnection.java    From tinkerpop with Apache License 2.0 6 votes vote down vote up
public DriverRemoteConnection(final Configuration conf) {
    final boolean hasClusterConf = IteratorUtils.anyMatch(conf.getKeys(), k -> k.startsWith("clusterConfiguration"));
    if (conf.containsKey(GREMLIN_REMOTE_DRIVER_CLUSTERFILE) && hasClusterConf)
        throw new IllegalStateException(String.format("A configuration should not contain both '%s' and 'clusterConfiguration'", GREMLIN_REMOTE_DRIVER_CLUSTERFILE));

    remoteTraversalSourceName = conf.getString(GREMLIN_REMOTE_DRIVER_SOURCENAME, DEFAULT_TRAVERSAL_SOURCE);

    try {
        final Cluster cluster;
        if (!conf.containsKey(GREMLIN_REMOTE_DRIVER_CLUSTERFILE) && !hasClusterConf)
            cluster = Cluster.open();
        else
            cluster = conf.containsKey(GREMLIN_REMOTE_DRIVER_CLUSTERFILE) ?
                    Cluster.open(conf.getString(GREMLIN_REMOTE_DRIVER_CLUSTERFILE)) : Cluster.open(conf.subset("clusterConfiguration"));

        client = cluster.connect(Client.Settings.build().create()).alias(remoteTraversalSourceName);
    } catch (Exception ex) {
        throw new IllegalStateException(ex);
    }

    attachElements = false;

    tryCloseCluster = true;
    tryCloseClient = true;
    this.conf = Optional.of(conf);
}
 
Example #2
Source File: Config.java    From bireme with Apache License 2.0 6 votes vote down vote up
/**
 * Get DebeziumSource configuration.
 *
 * @param debeziumConf An empty {@code SourceConfig}
 * @throws BiremeException miss some required configuration
 */
protected void fetchDebeziumConfig(SourceConfig debeziumConf) throws BiremeException {
  Configuration subConfig = new SubsetConfiguration(config, debeziumConf.name, ".");

  String prefix = subConfig.getString("namespace");
  if (prefix == null) {
    String messages = "Please designate your namespace.";
    logger.fatal(messages);
    throw new BiremeException(messages);
  }

  debeziumConf.type = SourceType.DEBEZIUM;
  debeziumConf.server = subConfig.getString("kafka.server");
  debeziumConf.topic = prefix;
  debeziumConf.groupID = subConfig.getString("kafka.groupid", "bireme");

  if (debeziumConf.server == null) {
    String message = "Please designate server for " + debeziumConf.name + ".";
    logger.fatal(message);
    throw new BiremeException(message);
  }
}
 
Example #3
Source File: TestCombinedConfigurationBuilder.java    From commons-configuration with Apache License 2.0 6 votes vote down vote up
/**
 * Tests a reset of the builder. The configuration instance should be
 * created anew.
 */
@Test
public void testResetBuilder() throws ConfigurationException
{
    final Map<String, Object> attrs = new HashMap<>();
    final BasicConfigurationBuilder<? extends HierarchicalConfiguration<ImmutableNode>> defBuilder =
            prepareSubBuilderTest(attrs);
    final CombinedConfiguration cc = builder.getConfiguration();
    final ConfigurationBuilder<? extends Configuration> subBuilder =
            builder.getNamedBuilder(BUILDER_NAME);
    defBuilder.reset();
    final CombinedConfiguration cc2 = builder.getConfiguration();
    assertNotSame("No new configuration instance", cc, cc2);
    final ConfigurationBuilder<? extends Configuration> subBuilder2 =
            builder.getNamedBuilder(BUILDER_NAME);
    assertNotSame("No new sub builder instance", subBuilder, subBuilder2);
}
 
Example #4
Source File: IoTest.java    From tinkerpop with Apache License 2.0 6 votes vote down vote up
@Test
@FeatureRequirement(featureClass = Graph.Features.EdgeFeatures.class, feature = Graph.Features.EdgeFeatures.FEATURE_ADD_EDGES)
@FeatureRequirement(featureClass = EdgePropertyFeatures.class, feature = FEATURE_STRING_VALUES)
@FeatureRequirement(featureClass = Graph.Features.VertexFeatures.class, feature = Graph.Features.VertexFeatures.FEATURE_ADD_VERTICES)
public void shouldReadWriteSelfLoopingEdges() throws Exception {
    final GraphSONMapper mapper = graph.io(graphson).mapper().version(GraphSONVersion.V3_0).create();
    final Graph source = graph;
    final Vertex v1 = source.addVertex();
    final Vertex v2 = source.addVertex();
    v1.addEdge("CONTROL", v2);
    v1.addEdge("SELFLOOP", v1);

    final Configuration targetConf = graphProvider.newGraphConfiguration("target", this.getClass(), name.getMethodName(), null);
    final Graph target = graphProvider.openTestGraph(targetConf);
    try (ByteArrayOutputStream os = new ByteArrayOutputStream()) {
        source.io(IoCore.graphson()).writer().mapper(mapper).create().writeGraph(os, source);
        try (ByteArrayInputStream is = new ByteArrayInputStream(os.toByteArray())) {
            target.io(IoCore.graphson()).reader().mapper(mapper).create().readGraph(is, target);
        }
    } catch (IOException ioe) {
        throw new RuntimeException(ioe);
    }

    assertEquals(IteratorUtils.count(source.vertices()), IteratorUtils.count(target.vertices()));
    assertEquals(IteratorUtils.count(source.edges()), IteratorUtils.count(target.edges()));
}
 
Example #5
Source File: BlobExportMechanismModule.java    From james-project with Apache License 2.0 6 votes vote down vote up
@VisibleForTesting
@Provides
@Singleton
BlobExportImplChoice provideChoice(PropertiesProvider propertiesProvider) throws ConfigurationException {
    try {
        Configuration configuration = propertiesProvider.getConfigurations(ConfigurationComponent.NAMES);
        return BlobExportImplChoice.from(configuration)
            .orElseGet(() -> {
                LOGGER.warn("No blob export mechanism defined. Defaulting to " + BlobExportImplChoice.LOCAL_FILE.getImplName());
                return BlobExportImplChoice.LOCAL_FILE;
            });
    } catch (FileNotFoundException e) {
        LOGGER.warn("Could not find " + ConfigurationComponent.NAME + " configuration file, using localFile blob exporting as the default");
        return BlobExportImplChoice.LOCAL_FILE;
    }
}
 
Example #6
Source File: TinkerIoRegistryV2d0.java    From tinkerpop with Apache License 2.0 6 votes vote down vote up
@Override
public TinkerGraph deserialize(final JsonParser jsonParser, final DeserializationContext deserializationContext) throws IOException, JsonProcessingException {
    final Configuration conf = new BaseConfiguration();
    conf.setProperty("gremlin.tinkergraph.defaultVertexPropertyCardinality", "list");
    final TinkerGraph graph = TinkerGraph.open(conf);

    while (jsonParser.nextToken() != JsonToken.END_OBJECT) {
        if (jsonParser.getCurrentName().equals("vertices")) {
            while (jsonParser.nextToken() != JsonToken.END_ARRAY) {
                if (jsonParser.currentToken() == JsonToken.START_OBJECT) {
                    final DetachedVertex v = (DetachedVertex) deserializationContext.readValue(jsonParser, Vertex.class);
                    v.attach(Attachable.Method.getOrCreate(graph));
                }
            }
        } else if (jsonParser.getCurrentName().equals("edges")) {
            while (jsonParser.nextToken() != JsonToken.END_ARRAY) {
                if (jsonParser.currentToken() == JsonToken.START_OBJECT) {
                    final DetachedEdge e = (DetachedEdge) deserializationContext.readValue(jsonParser, Edge.class);
                    e.attach(Attachable.Method.getOrCreate(graph));
                }
            }
        }
    }

    return graph;
}
 
Example #7
Source File: SubgraphTest.java    From tinkerpop with Apache License 2.0 6 votes vote down vote up
@Test
@LoadGraphWith(CREW)
@FeatureRequirement(featureClass = Graph.Features.VertexFeatures.class, feature = FEATURE_ADD_VERTICES)
@FeatureRequirement(featureClass = Graph.Features.EdgeFeatures.class, feature = FEATURE_ADD_EDGES)
@FeatureRequirement(featureClass = Graph.Features.VertexFeatures.class, feature = FEATURE_USER_SUPPLIED_IDS)
@FeatureRequirement(featureClass = Graph.Features.EdgeFeatures.class, feature = FEATURE_USER_SUPPLIED_IDS)
public void g_withSideEffectXsgX_V_hasXname_danielXout_capXsgX() throws Exception {
    final Configuration config = graphProvider.newGraphConfiguration("subgraph", this.getClass(), name.getMethodName(), CREW);
    graphProvider.clear(config);
    final Graph subgraph = graphProvider.openTestGraph(config);
    /////
    final Traversal<Vertex, Vertex> traversal = get_g_withSideEffectXsgX_V_hasXname_danielX_outE_subgraphXsgX_inV(subgraph);
    printTraversalForm(traversal);
    traversal.iterate();
    assertVertexEdgeCounts(subgraph, 3, 2);

    final List<String> locations = subgraph.traversal().V().has("name", "daniel").<String>values("location").toList();
    assertThat(locations, contains("spremberg", "kaiserslautern", "aachen"));

    graphProvider.clear(subgraph, config);
}
 
Example #8
Source File: TinkerGraphTest.java    From tinkerpop with Apache License 2.0 6 votes vote down vote up
@Test
public void shouldPersistToGraphSON() {
    final String graphLocation = TestHelper.makeTestDataFile(TinkerGraphTest.class, "shouldPersistToGraphSON.json");
    final File f = new File(graphLocation);
    if (f.exists() && f.isFile()) f.delete();

    final Configuration conf = new BaseConfiguration();
    conf.setProperty(TinkerGraph.GREMLIN_TINKERGRAPH_GRAPH_FORMAT, "graphson");
    conf.setProperty(TinkerGraph.GREMLIN_TINKERGRAPH_GRAPH_LOCATION, graphLocation);
    final TinkerGraph graph = TinkerGraph.open(conf);
    TinkerFactory.generateModern(graph);
    graph.close();

    final TinkerGraph reloadedGraph = TinkerGraph.open(conf);
    IoTest.assertModernGraph(reloadedGraph, true, false);
    reloadedGraph.close();
}
 
Example #9
Source File: TestServletRequestConfiguration.java    From commons-configuration with Apache License 2.0 6 votes vote down vote up
/**
 * Returns a new servlet request configuration that is backed by the passed
 * in configuration.
 *
 * @param base the configuration with the underlying values
 * @return the servlet request configuration
 */
private ServletRequestConfiguration createConfiguration(final Configuration base)
{
    final ServletRequest request = new MockHttpServletRequest()
    {
        @Override
        public String[] getParameterValues(final String key)
        {
            return base.getStringArray(key);
        }

        @Override
        public Map<?, ?> getParameterMap()
        {
            return new ConfigurationMap(base);
        }
    };

    final ServletRequestConfiguration config = new ServletRequestConfiguration(request);
    config.setListDelimiterHandler(new DefaultListDelimiterHandler(','));
    return config;
}
 
Example #10
Source File: PersistedOutputRDD.java    From tinkerpop with Apache License 2.0 6 votes vote down vote up
@Override
public void writeGraphRDD(final Configuration configuration, final JavaPairRDD<Object, VertexWritable> graphRDD) {
    if (!configuration.getBoolean(Constants.GREMLIN_SPARK_PERSIST_CONTEXT, false))
        LOGGER.warn("The SparkContext should be persisted in order for the RDD to persist across jobs. To do so, set " + Constants.GREMLIN_SPARK_PERSIST_CONTEXT + " to true");
    if (!configuration.containsKey(Constants.GREMLIN_HADOOP_OUTPUT_LOCATION))
        throw new IllegalArgumentException("There is no provided " + Constants.GREMLIN_HADOOP_OUTPUT_LOCATION + " to write the persisted RDD to");
    SparkContextStorage.open(configuration).rm(configuration.getString(Constants.GREMLIN_HADOOP_OUTPUT_LOCATION));  // this might be bad cause it unpersists the job RDD
    // determine which storage level to persist the RDD as with MEMORY_ONLY being the default cache()
    final StorageLevel storageLevel = StorageLevel.fromString(configuration.getString(Constants.GREMLIN_SPARK_PERSIST_STORAGE_LEVEL, "MEMORY_ONLY"));
    if (!configuration.getBoolean(Constants.GREMLIN_HADOOP_GRAPH_WRITER_HAS_EDGES, true))
        graphRDD.mapValues(vertex -> {
            vertex.get().dropEdges(Direction.BOTH);
            return vertex;
        }).setName(Constants.getGraphLocation(configuration.getString(Constants.GREMLIN_HADOOP_OUTPUT_LOCATION))).persist(storageLevel)
                // call action to eager store rdd
                .count();
    else
        graphRDD.setName(Constants.getGraphLocation(configuration.getString(Constants.GREMLIN_HADOOP_OUTPUT_LOCATION))).persist(storageLevel)
                // call action to eager store rdd
                .count();
    Spark.refresh(); // necessary to do really fast so the Spark GC doesn't clear out the RDD
}
 
Example #11
Source File: DNSRBLHandler.java    From james-project with Apache License 2.0 6 votes vote down vote up
@Override
public void init(Configuration config) throws ConfigurationException {
    boolean validConfig = false;
    HierarchicalConfiguration<ImmutableNode> handlerConfiguration = (HierarchicalConfiguration<ImmutableNode>) config;
    ArrayList<String> rblserverCollection = new ArrayList<>();

    Collections.addAll(rblserverCollection, handlerConfiguration.getStringArray("rblservers.whitelist"));
    if (rblserverCollection.size() > 0) {
        setWhitelist(rblserverCollection.toArray(String[]::new));
        rblserverCollection.clear();
        validConfig = true;
    }
    Collections.addAll(rblserverCollection, handlerConfiguration.getStringArray("rblservers.blacklist"));
    if (rblserverCollection.size() > 0) {
        setBlacklist(rblserverCollection.toArray(String[]::new));
        rblserverCollection.clear();
        validConfig = true;
    }

    // Throw an ConfiigurationException on invalid config
    if (!validConfig) {
        throw new ConfigurationException("Please configure whitelist or blacklist");
    }

    setGetDetail(handlerConfiguration.getBoolean("getDetail", false));
}
 
Example #12
Source File: IoGraphTest.java    From tinkerpop with Apache License 2.0 6 votes vote down vote up
@Test
@LoadGraphWith(LoadGraphWith.GraphData.MODERN)
@FeatureRequirement(featureClass = Graph.Features.EdgeFeatures.class, feature = Graph.Features.EdgeFeatures.FEATURE_ADD_EDGES)
@FeatureRequirement(featureClass = Graph.Features.VertexFeatures.class, feature = Graph.Features.VertexFeatures.FEATURE_ADD_VERTICES)
public void shouldReadWriteModernToFileWithHelpers() throws Exception {
    final File f = TestHelper.generateTempFile(this.graph.getClass(), name.getMethodName(), fileExtension);
    try {
        graph.io(ioBuilderToTest).writeGraph(Storage.toPath(f));

        final Configuration configuration = graphProvider.newGraphConfiguration("readGraph", this.getClass(), name.getMethodName(), LoadGraphWith.GraphData.MODERN);
        final Graph g1 = graphProvider.openTestGraph(configuration);
        g1.io(ioBuilderToTest).readGraph(Storage.toPath(f));

        // modern uses double natively so always assert as such
        IoTest.assertModernGraph(g1, true, lossyForId);

        graphProvider.clear(g1, configuration);
    } catch (Exception ex) {
        f.delete();
        throw ex;
    }
}
 
Example #13
Source File: InputRDDTest.java    From tinkerpop with Apache License 2.0 5 votes vote down vote up
@Test
public void shouldReadFromArbitraryRDD() {
    final Configuration configuration = new BaseConfiguration();
    configuration.setProperty("spark.master", "local[4]");
    configuration.setProperty("spark.serializer", GryoSerializer.class.getCanonicalName());
    configuration.setProperty(Graph.GRAPH, HadoopGraph.class.getName());
    configuration.setProperty(Constants.GREMLIN_HADOOP_GRAPH_READER, ExampleInputRDD.class.getCanonicalName());
    configuration.setProperty(Constants.GREMLIN_HADOOP_GRAPH_WRITER, GryoOutputFormat.class.getCanonicalName());
    configuration.setProperty(Constants.GREMLIN_HADOOP_OUTPUT_LOCATION, TestHelper.makeTestDataDirectory(this.getClass(), "shouldReadFromArbitraryRDD"));
    configuration.setProperty(Constants.GREMLIN_HADOOP_JARS_IN_DISTRIBUTED_CACHE, false);
    ////////
    Graph graph = GraphFactory.open(configuration);
    assertEquals(123l, graph.traversal().withComputer(SparkGraphComputer.class).V().values("age").sum().next());
    assertEquals(Long.valueOf(4l), graph.traversal().withComputer(SparkGraphComputer.class).V().count().next());
}
 
Example #14
Source File: IoTest.java    From tinkerpop with Apache License 2.0 5 votes vote down vote up
/**
 * This is just a serialization check for JSON.
 */
@Test
@FeatureRequirement(featureClass = Graph.Features.VertexFeatures.class, feature = Graph.Features.VertexFeatures.FEATURE_ADD_VERTICES)
@FeatureRequirement(featureClass = Graph.Features.VertexFeatures.class, feature = FEATURE_USER_SUPPLIED_IDS)
@FeatureRequirement(featureClass = Graph.Features.VertexFeatures.class, feature = FEATURE_ANY_IDS)
public void shouldProperlySerializeCustomIdWithGraphSON() throws Exception {
    final UUID id = UUID.fromString("AF4B5965-B176-4552-B3C1-FBBE2F52C305");
    graph.addVertex(T.id, new CustomId("vertex", id));

    final SimpleModule module = new CustomId.CustomIdTinkerPopJacksonModuleV2d0();
    final GraphWriter writer = graph.io(graphson).writer().mapper(
            graph.io(graphson).mapper().version(GraphSONVersion.V2_0).addCustomModule(module).create()).create();

    try (final ByteArrayOutputStream baos = new ByteArrayOutputStream()) {
        writer.writeGraph(baos, graph);

        // reusing the same config used for creation of "g".
        final Configuration configuration = graphProvider.newGraphConfiguration("g2", this.getClass(), name.getMethodName(), null);
        graphProvider.clear(configuration);
        final Graph g2 = graphProvider.openTestGraph(configuration);

        try (final InputStream is = new ByteArrayInputStream(baos.toByteArray())) {
            final GraphReader reader = graph.io(graphson).reader()
                    .mapper(graph.io(graphson).mapper().version(GraphSONVersion.V2_0).addCustomModule(module).create()).create();
            reader.readGraph(is, g2);
        }

        final Vertex v2 = g2.vertices().next();
        final CustomId customId = (CustomId) v2.id();
        assertEquals(id, customId.getElementId());
        assertEquals("vertex", customId.getCluster());

        // need to manually close the "g2" instance
        graphProvider.clear(g2, configuration);
    }
}
 
Example #15
Source File: DSWorkbenchDistanceFrame.java    From dsworkbench with Apache License 2.0 5 votes vote down vote up
@Override
public void restoreCustomProperties(Configuration pConfig) {
    centerPanel.setMenuVisible(pConfig.getBoolean(getPropertyPrefix() + ".menu.visible", true));

    try {
        jAlwaysOnTop.setSelected(pConfig.getBoolean(getPropertyPrefix() + ".alwaysOnTop"));
    } catch (Exception ignored) {
    }

    setAlwaysOnTop(jAlwaysOnTop.isSelected());
}
 
Example #16
Source File: ElasticSearchQuotaSearcherModule.java    From james-project with Apache License 2.0 5 votes vote down vote up
@Provides
@Singleton
private ElasticSearchQuotaConfiguration getElasticSearchQuotaConfiguration(PropertiesProvider propertiesProvider) throws ConfigurationException {
    try {
        Configuration configuration = propertiesProvider.getConfiguration(ELASTICSEARCH_CONFIGURATION_NAME);
        return ElasticSearchQuotaConfiguration.fromProperties(configuration);
    } catch (FileNotFoundException e) {
        LOGGER.warn("Could not find " + ELASTICSEARCH_CONFIGURATION_NAME + " configuration file. Providing a default ElasticSearchQuotaConfiguration");
        return ElasticSearchQuotaConfiguration.DEFAULT_CONFIGURATION;
    }
}
 
Example #17
Source File: TestXMLPropertyListConfiguration.java    From commons-configuration with Apache License 2.0 5 votes vote down vote up
@Test
public void testDictionaryArray()
{
    final String key = "dictionary-array";

    final Object array = config.getProperty(key);

    // root array
    assertNotNull("array not found", array);
    ObjectAssert.assertInstanceOf("the array element is not parsed as a List", List.class, array);
    final List<?> list = config.getList(key);

    assertFalse("empty array", list.isEmpty());
    assertEquals("size", 2, list.size());

    // 1st dictionary
    ObjectAssert.assertInstanceOf("the dict element is not parsed as a Configuration", Configuration.class, list.get(0));
    final Configuration conf1 = (Configuration) list.get(0);
    assertFalse("configuration 1 is empty", conf1.isEmpty());
    assertEquals("configuration element", "bar", conf1.getProperty("foo"));

    // 2nd dictionary
    ObjectAssert.assertInstanceOf("the dict element is not parsed as a Configuration", Configuration.class, list.get(1));
    final Configuration conf2 = (Configuration) list.get(1);
    assertFalse("configuration 2 is empty", conf2.isEmpty());
    assertEquals("configuration element", "value", conf2.getProperty("key"));
}
 
Example #18
Source File: GraphFactoryTest.java    From tinkerpop with Apache License 2.0 5 votes vote down vote up
@Test
public void shouldOpenViaConfiguration() {
    final Configuration conf = new BaseConfiguration();
    conf.setProperty(Graph.GRAPH, MockGraph.class.getName());
    conf.setProperty("keep", "it");
    GraphFactory.open(conf);
    final MockGraph g = (MockGraph) GraphFactory.open(conf);
    assertEquals(MockGraph.class.getName(), g.getConf().getString(Graph.GRAPH));
    assertEquals("it", g.getConf().getString("keep"));
}
 
Example #19
Source File: DSWorkbenchSelectionFrame.java    From dsworkbench with Apache License 2.0 5 votes vote down vote up
@Override
public void restoreCustomProperties(Configuration pConfig) {
    centerPanel.setMenuVisible(pConfig.getBoolean(getPropertyPrefix() + ".menu.visible", true));
    try {
        jAlwaysOnTopBox.setSelected(pConfig.getBoolean(getPropertyPrefix() + ".alwaysOnTop"));
    } catch (Exception ignored) {
    }

    setAlwaysOnTop(jAlwaysOnTopBox.isSelected());
}
 
Example #20
Source File: RabbitMQConfiguration.java    From james-project with Apache License 2.0 5 votes vote down vote up
static ManagementCredentials from(Configuration configuration) {
    String user = configuration.getString(MANAGEMENT_CREDENTIAL_USER_PROPERTY);
    Preconditions.checkState(!Strings.isNullOrEmpty(user), "You need to specify the " +
        MANAGEMENT_CREDENTIAL_USER_PROPERTY + " property as username of rabbitmq management admin account");

    String passwordString = configuration.getString(MANAGEMENT_CREDENTIAL_PASSWORD_PROPERTY);
    Preconditions.checkState(!Strings.isNullOrEmpty(passwordString), "You need to specify the " +
        MANAGEMENT_CREDENTIAL_PASSWORD_PROPERTY + " property as password of rabbitmq management admin account");

    return new ManagementCredentials(user, passwordString.toCharArray());
}
 
Example #21
Source File: DSWorkbenchFormFrame.java    From dsworkbench with Apache License 2.0 5 votes vote down vote up
@Override
public void restoreCustomProperties(Configuration pConfig) {
    centerPanel.setMenuVisible(pConfig.getBoolean(getPropertyPrefix() + ".menu.visible", true));
    
    try {
        jAlwaysOnTop.setSelected(pConfig.getBoolean(getPropertyPrefix() + ".alwaysOnTop"));
    } catch (Exception ignored) {
    }
    
    setAlwaysOnTop(jAlwaysOnTop.isSelected());
    
    PropertyHelper.restoreTableProperties(jFormsTable, pConfig, getPropertyPrefix());
}
 
Example #22
Source File: JPAEntityManagerModule.java    From james-project with Apache License 2.0 5 votes vote down vote up
@Provides
@Singleton
JPAConfiguration provideConfiguration(PropertiesProvider propertiesProvider) throws FileNotFoundException, ConfigurationException {
    Configuration dataSource = propertiesProvider.getConfiguration("james-database");
    return JPAConfiguration.builder()
            .driverName(dataSource.getString("database.driverClassName"))
            .driverURL(dataSource.getString("database.url"))
            .testOnBorrow(dataSource.getBoolean("datasource.testOnBorrow", false))
            .validationQueryTimeoutSec(dataSource.getInteger("datasource.validationQueryTimeoutSec", null))
            .validationQuery(dataSource.getString("datasource.validationQuery", null))
            .username(dataSource.getString("database.username"))
            .password(dataSource.getString("database.password"))
            .build();
}
 
Example #23
Source File: Schema2MarkupConfigBuilder.java    From swagger2markup with Apache License 2.0 5 votes vote down vote up
/**
 * Loads the default properties from the classpath.
 *
 * @return the default properties
 */
public static Configuration getDefaultConfiguration() {
    Configurations configs = new Configurations();
    try {
        return configs.properties(PROPERTIES_DEFAULT);
    } catch (ConfigurationException e) {
        throw new RuntimeException(String.format("Can't load default properties '%s'", PROPERTIES_DEFAULT), e);
    }
}
 
Example #24
Source File: AbstractWarningVerificationStrategy.java    From tinkerpop with Apache License 2.0 5 votes vote down vote up
@Override
public Configuration getConfiguration() {
    final Map<String, Object> m = new HashMap<>(2);
    m.put(THROW_EXCEPTION, this.throwException);
    m.put(LOG_WARNING, this.logWarning);
    return new MapConfiguration(m);
}
 
Example #25
Source File: CombinedConfigurationBuilder.java    From commons-configuration with Apache License 2.0 5 votes vote down vote up
/**
 * Processes the declaration of configuration builder providers, creates
 * the corresponding builder if necessary, obtains configurations, and
 * adds them to the specified result configuration.
 *
 * @param ccResult the result configuration
 * @param srcDecl the collection with the declarations of configuration
 *        sources to process
 * @return a list with configuration builders
 * @throws ConfigurationException if an error occurs
 */
public List<ConfigurationBuilder<? extends Configuration>> createAndAddConfigurations(
        final CombinedConfiguration ccResult,
        final List<ConfigurationDeclaration> srcDecl,
        final List<ConfigurationBuilder<? extends Configuration>> builders)
        throws ConfigurationException
{
    final boolean createBuilders = builders.isEmpty();
    List<ConfigurationBuilder<? extends Configuration>> newBuilders;
    if (createBuilders)
    {
        newBuilders = new ArrayList<>(srcDecl.size());
    }
    else
    {
        newBuilders = builders;
    }

    for (int i = 0; i < srcDecl.size(); i++)
    {
        ConfigurationBuilder<? extends Configuration> b;
        if (createBuilders)
        {
            b = createConfigurationBuilder(srcDecl.get(i));
            newBuilders.add(b);
        }
        else
        {
            b = builders.get(i);
        }
        addChildConfiguration(ccResult, srcDecl.get(i), b);
    }

    return newBuilders;
}
 
Example #26
Source File: TinkerFactory.java    From tinkerpop with Apache License 2.0 5 votes vote down vote up
/**
 * Create the "classic" graph which was the original toy graph from TinkerPop 2.x.
 */
public static TinkerGraph createClassic() {
    final Configuration conf = new BaseConfiguration();
    conf.setProperty(TinkerGraph.GREMLIN_TINKERGRAPH_VERTEX_ID_MANAGER, TinkerGraph.DefaultIdManager.INTEGER.name());
    conf.setProperty(TinkerGraph.GREMLIN_TINKERGRAPH_EDGE_ID_MANAGER, TinkerGraph.DefaultIdManager.INTEGER.name());
    conf.setProperty(TinkerGraph.GREMLIN_TINKERGRAPH_VERTEX_PROPERTY_ID_MANAGER, TinkerGraph.DefaultIdManager.INTEGER.name());
    final TinkerGraph g = TinkerGraph.open(conf);
    generateClassic(g);
    return g;
}
 
Example #27
Source File: AbstractSparkTest.java    From tinkerpop with Apache License 2.0 5 votes vote down vote up
protected Configuration getBaseConfiguration() {
    final BaseConfiguration configuration = new BaseConfiguration();
    configuration.setProperty(SparkLauncher.SPARK_MASTER, "local[4]");
    configuration.setProperty(Constants.SPARK_SERIALIZER, GryoSerializer.class.getCanonicalName());
    configuration.setProperty(Constants.SPARK_KRYO_REGISTRATION_REQUIRED, true);
    configuration.setProperty(Graph.GRAPH, HadoopGraph.class.getName());
    configuration.setProperty(Constants.GREMLIN_HADOOP_JARS_IN_DISTRIBUTED_CACHE, false);
    return configuration;
}
 
Example #28
Source File: GraphFactory.java    From tinkerpop with Apache License 2.0 5 votes vote down vote up
private static org.apache.commons.configuration2.Configuration getConfiguration(final File configurationFile) {
    if (!configurationFile.isFile())
        throw new IllegalArgumentException(String.format("The location configuration must resolve to a file and [%s] does not", configurationFile));

    try {
        final String fileName = configurationFile.getName();
        final String fileExtension = fileName.substring(fileName.lastIndexOf('.') + 1);

        final Configuration conf;
        final Configurations configs = new Configurations();

        switch (fileExtension) {
            case "yml":
            case "yaml":
                final Parameters params = new Parameters();
                final FileBasedConfigurationBuilder<FileBasedConfiguration> builder =
                        new FileBasedConfigurationBuilder<FileBasedConfiguration>(YAMLConfiguration.class).
                                configure(params.fileBased().setFile(configurationFile));

                final org.apache.commons.configuration2.Configuration copy = new org.apache.commons.configuration2.BaseConfiguration();
                ConfigurationUtils.copy(builder.configure(params.fileBased().setFile(configurationFile)).getConfiguration(), copy);
                conf = copy;
                break;
            case "xml":
                conf = configs.xml(configurationFile);
                break;
            default:
                conf = configs.properties(configurationFile);
        }
        return conf;
    } catch (ConfigurationException e) {
        throw new IllegalArgumentException(String.format("Could not load configuration at: %s", configurationFile), e);
    }
}
 
Example #29
Source File: GryoPoolTest.java    From tinkerpop with Apache License 2.0 5 votes vote down vote up
@Test
public void shouldConfigPoolOnConstructionWithCustomIoRegistryInstance() throws Exception {
    final Configuration conf = new BaseConfiguration();
    conf.setProperty(IoRegistry.IO_REGISTRY, IoXIoRegistry.InstanceBased.class.getName());
    final GryoPool pool = GryoPool.build().ioRegistries(conf.getList(IoRegistry.IO_REGISTRY, Collections.emptyList())).create();
    assertReaderWriter(pool.takeWriter(), pool.takeReader(), new IoX("test"), IoX.class);
}
 
Example #30
Source File: SiteProperties.java    From engine with GNU General Public License v3.0 5 votes vote down vote up
/**
 * Returns the list of available target IDs.
 */
public static String[] getAvailableTargetIds() {
    Configuration config = ConfigUtils.getCurrentConfig();
    if (config != null) {
        return config.getStringArray(AVAILABLE_TARGET_IDS_CONFIG_KEY);
    } else {
        return null;
    }
}