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

The following are top voted examples for showing how to use org.apache.commons.configuration.Configuration. 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: incubator-servicecomb-java-chassis   File: RestServletInitializer.java   Source Code and License 7 votes vote down vote up
@Override
public void onStartup(ServletContext servletContext) throws ServletException {
  if (getPort() == 0) {
    LOGGER.warn(
        "spring boot embed web container listen port is 0, serviceComb will not use container's port to handler RESTful request.");
    return;
  }

  // web container did not did listen now.
  // so mock to listen, and then close.
  try (ServerSocket ss = new ServerSocket(getPort(), 0, getAddress())) {
    if (StringUtils.isEmpty(ServletConfig.getServletUrlPattern())) {
      // ensure the servlet will be instantiated
      Configuration configuration = (Configuration) DynamicPropertyFactory.getBackingConfigurationSource();
      configuration.setProperty(ServletConfig.KEY_SERVLET_URL_PATTERN, ServletConfig.DEFAULT_URL_PATTERN);
    }
    RestServletInjector.defaultInject(servletContext);
    ServletUtils.saveUrlPrefix(servletContext);
  } catch (IOException e) {
    throw new ServletException(e);
  }
}
 
Example 2
Project: incubator-servicecomb-java-chassis   File: TestRestServletInitializer.java   Source Code and License 7 votes vote down vote up
@Test
public void testOnStartup() throws Exception {
  Configuration configuration = (Configuration) DynamicPropertyFactory.getBackingConfigurationSource();
  String urlPattern = "/rest/*";
  configuration.setProperty(ServletConfig.KEY_SERVLET_URL_PATTERN, urlPattern);

  ServletContext servletContext = mock(ServletContext.class);
  Dynamic dynamic = mock(Dynamic.class);
  when(servletContext.addServlet(RestServletInjector.SERVLET_NAME, RestServlet.class)).thenReturn(dynamic);

  RestServletInitializer restServletInitializer = new RestServletInitializer();
  restServletInitializer.setPort(TEST_PORT);
  restServletInitializer.onStartup(servletContext);

  verify(dynamic).setAsyncSupported(true);
  verify(dynamic).addMapping(urlPattern);
  verify(dynamic).setLoadOnStartup(0);
}
 
Example 3
Project: incubator-servicecomb-java-chassis   File: TestServiceRegistryConfig.java   Source Code and License 7 votes vote down vote up
@Test
public void getMicroserviceVersionFactory() {
  DynamicPropertyFactory.getInstance();
  Configuration config = (Configuration) DynamicPropertyFactory.getBackingConfigurationSource();
  config.addProperty(ServiceRegistryConfig.MICROSERVICE_VERSION_FACTORY, "test");

  Assert.assertEquals("test", ServiceRegistryConfig.INSTANCE.getMicroserviceVersionFactory());

  config.clearProperty(ServiceRegistryConfig.MICROSERVICE_VERSION_FACTORY);
}
 
Example 4
Project: incubator-servicecomb-java-chassis   File: EdgeBootListener.java   Source Code and License 7 votes vote down vote up
@Override
public void onBootEvent(BootEvent event) {
  if (!EventType.BEFORE_PRODUCER_PROVIDER.equals(event.getEventType())) {
    return;
  }

  String defaultExecutor = DynamicPropertyFactory.getInstance()
      .getStringProperty(ExecutorManager.KEY_EXECUTORS_DEFAULT, null)
      .get();
  if (defaultExecutor != null) {
    LOGGER.info("Edge service default executor is {}.", defaultExecutor);
    return;
  }

  // change default to reactive mode
  Configuration configuration = (Configuration) DynamicPropertyFactory.getBackingConfigurationSource();
  configuration.setProperty(ExecutorManager.KEY_EXECUTORS_DEFAULT, ExecutorManager.EXECUTOR_REACTIVE);
  LOGGER.info("Set ReactiveExecutor to be edge service default executor.");
}
 
Example 5
Project: incubator-servicecomb-java-chassis   File: TestServletConfig.java   Source Code and License 7 votes vote down vote up
@Test
public void testGetServletUrlPattern() {
  DynamicPropertyFactory.getInstance();
  Configuration configuration = (Configuration) DynamicPropertyFactory.getBackingConfigurationSource();
  configuration.setProperty(ServletConfig.KEY_SERVLET_URL_PATTERN, "/*");
  Assert.assertEquals("/*", ServletConfig.getServletUrlPattern());
}
 
Example 6
Project: obevo   File: DbMergeInfo.java   Source Code and License 7 votes vote down vote up
public static MutableCollection<DbMergeInfo> parseFromProperties(Configuration config) {
    Set<String> dbs = new HashSet<String>(config.getList("instances"));

    MutableList<DbMergeInfo> dbMergeInfos = Lists.mutable.empty();
    for (String db : dbs) {
        Configuration subset = config.subset(db);
        if (subset.containsKey("inputDir")) {
            File inputDir = new File(subset.getString("inputDir"));
            DbMergeInfo mergeInfo = new DbMergeInfo(db, inputDir);
            if (subset.containsKey("driverClassName")) {
                mergeInfo.setDriverClassName(subset.getString("driverClassName"));
                mergeInfo.setUrl(subset.getString("url"));
                mergeInfo.setUsername(subset.getString("username"));
                mergeInfo.setPassword(subset.getString("password"));
                mergeInfo.setPhysicalSchema(subset.getString("physicalSchema"));
            }

            dbMergeInfos.add(mergeInfo);
        }
    }

    return dbMergeInfos;
}
 
Example 7
Project: jbake-rtl-jalaali   File: AsciidoctorEngine.java   Source Code and License 6 votes vote down vote up
private Options getAsciiDocOptionsAndAttributes(ParserContext context) {
    Configuration config = context.getConfig();
    final AttributesBuilder attributes = attributes(config.getStringArray(Keys.ASCIIDOCTOR_ATTRIBUTES));
    if (config.getBoolean(Keys.ASCIIDOCTOR_ATTRIBUTES_EXPORT, false)) {
        final String prefix = config.getString(  Keys.ASCIIDOCTOR_ATTRIBUTES_EXPORT_PREFIX, "");
        for (final Iterator<String> it = config.getKeys(); it.hasNext();) {
            final String key = it.next();
            if (!key.startsWith("asciidoctor")) {
                attributes.attribute(prefix + key.replace(".", "_"), config.getProperty(key));
            }
        }
    }
    final Configuration optionsSubset = config.subset(Keys.ASCIIDOCTOR_OPTION);
    final Options options = options().attributes(attributes.get()).get();
    for (final Iterator<String> iterator = optionsSubset.getKeys(); iterator.hasNext();) {
        final String name = iterator.next();
        if (name.equals(Options.TEMPLATE_DIRS)) {
        	options.setTemplateDirs(optionsSubset.getString(name));
        } else {
        	options.setOption(name,  guessTypeByContent(optionsSubset.getString(name)));
        }
    }
    options.setBaseDir(context.getFile().getParentFile().getAbsolutePath());
    options.setSafe(UNSAFE);
    return options;
}
 
Example 8
Project: jbake-rtl-jalaali   File: TemplateEngines.java   Source Code and License 6 votes vote down vote up
/**
 * This method is used internally to load markup engines. Markup engines are found using descriptor files on
 * classpath, so adding an engine is as easy as adding a jar on classpath with the descriptor file included.
 */
private void loadEngines(final Configuration config, final ContentStore db, final File destination, final File templatesPath) {
    try {
        ClassLoader cl = TemplateEngines.class.getClassLoader();
        Enumeration<URL> resources = cl.getResources("META-INF/org.jbake.parser.TemplateEngines.properties");
        while (resources.hasMoreElements()) {
            URL url = resources.nextElement();
            Properties props = new Properties();
            props.load(url.openStream());
            for (Map.Entry<Object, Object> entry : props.entrySet()) {
                String className = (String) entry.getKey();
                String[] extensions = ((String) entry.getValue()).split(",");
                registerEngine(config, db, destination, templatesPath, className, extensions);
            }
        }
    } catch (IOException e) {
        e.printStackTrace();
    }
}
 
Example 9
Project: incubator-servicecomb-java-chassis   File: TestRestServletInitializer.java   Source Code and License 6 votes vote down vote up
@Before
public void setUp() throws Exception {
  Configuration configuration = (Configuration) DynamicPropertyFactory.getBackingConfigurationSource();
  configuration.clearProperty(ServletConfig.KEY_SERVLET_URL_PATTERN);
  configuration.setProperty(ServletConfig.KEY_CSE_REST_ADDRESS, LISTEN_ADDRESS);

  PowerMockito.mockStatic(NetUtils.class);
  PowerMockito.when(NetUtils.parseIpPortFromURI(anyString())).thenReturn(new IpPort(LISTEN_ADDRESS, TEST_PORT));
  PowerMockito.when(NetUtils.canTcpListen(anyObject(), anyInt())).thenReturn(false);
}
 
Example 10
Project: incubator-servicecomb-java-chassis   File: ArchaiusUtils.java   Source Code and License 6 votes vote down vote up
public static void setProperty(String key, Object value) {
  // ensure have instance
  DynamicPropertyFactory.getInstance();
  Configuration config = (Configuration) DynamicPropertyFactory.getBackingConfigurationSource();
  config.addProperty(key, value);
}
 
Example 11
Project: incubator-servicecomb-java-chassis   File: ConfigUtil.java   Source Code and License 6 votes vote down vote up
public static DynamicWatchedConfiguration createConfigFromConfigCenter(Configuration localConfiguration) {
  if (localConfiguration.getProperty(configCenterUrlKey) == null) {
    LOGGER.info("config center URL is missing, skip to load configuration from config center");
    return null;
  }

  ConfigCenterConfigurationSource configCenterConfigurationSource =
      SPIServiceUtils.getTargetService(ConfigCenterConfigurationSource.class);
  if (null == configCenterConfigurationSource) {
    LOGGER.info(
        "config center SPI service can not find, skip to load configuration from config center");
    return null;
  }

  configCenterConfigurationSource.init(localConfiguration);
  return new DynamicWatchedConfiguration(configCenterConfigurationSource);
}
 
Example 12
Project: incubator-servicecomb-java-chassis   File: TestConfigurationSpringInitializer.java   Source Code and License 6 votes vote down vote up
@Test
public void testAll() {
  ConfigurationSpringInitializer configurationSpringInitializer = new ConfigurationSpringInitializer();

  Assert.assertEquals(Ordered.LOWEST_PRECEDENCE / 2, configurationSpringInitializer.getOrder());
  Assert.assertEquals(true,
      Deencapsulation.getField(configurationSpringInitializer, "ignoreUnresolvablePlaceholders"));

  Object o = ConfigUtil.getProperty("zq");
  @SuppressWarnings("unchecked")
  List<Map<String, Object>> listO = (List<Map<String, Object>>) o;
  Assert.assertEquals(3, listO.size());
  Assert.assertEquals(null, ConfigUtil.getProperty("notExist"));

  MicroserviceConfigLoader loader = ConfigUtil.getMicroserviceConfigLoader();
  Assert.assertNotNull(loader);

  Configuration instance = ConfigurationManager.getConfigInstance();
  ConfigUtil.installDynamicConfig();
  // must not reinstall
  Assert.assertEquals(instance, ConfigurationManager.getConfigInstance());
}
 
Example 13
Project: incubator-servicecomb-java-chassis   File: ConfigurePropertyUtils.java   Source Code and License 6 votes vote down vote up
/**
 * 获取key包含prefix前缀的所有配置项
 */
public static Map<String, String> getPropertiesWithPrefix(String prefix) {
  Object config = DynamicPropertyFactory.getBackingConfigurationSource();
  if (!Configuration.class.isInstance(config)) {
    return new HashMap<>();
  }

  return getPropertiesWithPrefix((Configuration) config, prefix);
}
 
Example 14
Project: incubator-servicecomb-java-chassis   File: TestConfigurePropertyUtils.java   Source Code and License 6 votes vote down vote up
@Test
public void testGetPropertiesWithPrefix() {
  Configuration configuration = ConfigUtil.createLocalConfig();

  String prefix = "service_description.properties";
  Map<String, String> expectedMap = new HashMap<>();
  expectedMap.put("key1", "value1");
  expectedMap.put("key2", "value2");
  Assert.assertEquals(expectedMap, ConfigurePropertyUtils.getPropertiesWithPrefix(configuration, prefix));

  List<BasePath> paths = ConfigurePropertyUtils.getMicroservicePaths(configuration);
  Assert.assertEquals(2, paths.size());
  Assert.assertEquals(paths.get(0).getPath(), "/test1/testpath");
  Assert.assertEquals(paths.get(0).getProperty().get("checksession"), false);

  System.setProperty(Const.URL_PREFIX, "/webroot");
  paths = ConfigurePropertyUtils.getMicroservicePaths(configuration);
  Assert.assertEquals(2, paths.size());
  Assert.assertEquals(paths.get(0).getPath(), "/webroot/test1/testpath");
  Assert.assertEquals(paths.get(0).getProperty().get("checksession"), false);
}
 
Example 15
Project: AthenaX   File: ValidatorTest.java   Source Code and License 6 votes vote down vote up
@Test
public void testSetOptions() throws IOException, ParseException {
  String sql = Joiner.on(";\n").join(
      "SET spam = 1",
      "SET foo = 'bar'",
      "RESET foo",
      "ALTER SESSION SET bar = OFF"
  );
  SqlNodeList nodes = Planner.parse(sql);
  Validator validator = new Validator();
  validator.extract(nodes);
  Configuration options = validator.options();
  assertEquals(1, options.getInt("spam"));
  assertNull(options.getString("foo", null));
  assertEquals("OFF", options.getString("bar"));
}
 
Example 16
Project: tinkergraph-gremlin   File: TinkerGraph.java   Source Code and License 6 votes vote down vote up
/**
 * An empty private constructor that initializes {@link TinkerGraph}.
 */
private TinkerGraph(final Configuration configuration, boolean usesSpecializedElements) {
    this.configuration = configuration;
    this.usesSpecializedElements = usesSpecializedElements;
    vertexIdManager = selectIdManager(configuration, GREMLIN_TINKERGRAPH_VERTEX_ID_MANAGER, Vertex.class);
    edgeIdManager = selectIdManager(configuration, GREMLIN_TINKERGRAPH_EDGE_ID_MANAGER, Edge.class);
    vertexPropertyIdManager = selectIdManager(configuration, GREMLIN_TINKERGRAPH_VERTEX_PROPERTY_ID_MANAGER, VertexProperty.class);
    defaultVertexPropertyCardinality = VertexProperty.Cardinality.valueOf(
            configuration.getString(GREMLIN_TINKERGRAPH_DEFAULT_VERTEX_PROPERTY_CARDINALITY, VertexProperty.Cardinality.single.name()));

    graphLocation = configuration.getString(GREMLIN_TINKERGRAPH_GRAPH_LOCATION, null);
    graphFormat = configuration.getString(GREMLIN_TINKERGRAPH_GRAPH_FORMAT, null);

    if ((graphLocation != null && null == graphFormat) || (null == graphLocation && graphFormat != null))
        throw new IllegalStateException(String.format("The %s and %s must both be specified if either is present",
                GREMLIN_TINKERGRAPH_GRAPH_LOCATION, GREMLIN_TINKERGRAPH_GRAPH_FORMAT));

    if (graphLocation != null) loadGraph();
}
 
Example 17
Project: tinkergraph-gremlin   File: TinkerIoRegistryV3d0.java   Source Code and License 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 18
Project: tinkergraph-gremlin   File: TinkerIoRegistryV2d0.java   Source Code and License 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 19
Project: tinkergraph-gremlin   File: TinkerGraphTest.java   Source Code and License 6 votes vote down vote up
@Test
public void shouldPersistToGraphSON() {
    final String graphLocation = TestHelper.makeTestDataDirectory(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 20
Project: tinkergraph-gremlin   File: TinkerGraphTest.java   Source Code and License 6 votes vote down vote up
@Test
public void shouldPersistToGryo() {
    final String graphLocation = TestHelper.makeTestDataDirectory(TinkerGraphTest.class) + "shouldPersistToGryo.kryo";
    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, "gryo");
    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 21
Project: tinkergraph-gremlin   File: TinkerGraphTest.java   Source Code and License 6 votes vote down vote up
@Test
public void shouldPersistToGryoAndHandleMultiProperties() {
    final String graphLocation = TestHelper.makeTestDataDirectory(TinkerGraphTest.class) + "shouldPersistToGryoMulti.kryo";
    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, "gryo");
    conf.setProperty(TinkerGraph.GREMLIN_TINKERGRAPH_GRAPH_LOCATION, graphLocation);
    final TinkerGraph graph = TinkerGraph.open(conf);
    TinkerFactory.generateTheCrew(graph);
    graph.close();

    conf.setProperty(TinkerGraph.GREMLIN_TINKERGRAPH_DEFAULT_VERTEX_PROPERTY_CARDINALITY, VertexProperty.Cardinality.list.toString());
    final TinkerGraph reloadedGraph = TinkerGraph.open(conf);
    IoTest.assertCrewGraph(reloadedGraph, false);
    reloadedGraph.close();
}
 
Example 22
Project: tinkergraph-gremlin   File: TinkerGraphTest.java   Source Code and License 6 votes vote down vote up
@Test
public void shouldPersistWithRelativePath() {
    final String graphLocation = TestHelper.convertToRelative(TinkerGraphTest.class,
            new File(TestHelper.makeTestDataDirectory(TinkerGraphTest.class)))  + "shouldPersistToGryoRelative.kryo";
    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, "gryo");
    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 23
Project: bitsy   File: BitsyGraph.java   Source Code and License 6 votes vote down vote up
/** 
 * Constructor with a Configuration object with String dbPath, boolean allowFullGraphScans, long txLogThreshold and double reorgFactor 
 */
public BitsyGraph(Configuration configuration) {
	this(Paths.get(configuration.getString(DB_PATH_KEY)),
		configuration.getBoolean(ALLOW_FULL_GRAPH_SCANS_KEY, Boolean.TRUE),
		configuration.getLong(TX_LOG_THRESHOLD_KEY, DEFAULT_TX_LOG_THRESHOLD),
		configuration.getDouble(REORG_FACTOR_KEY, DEFAULT_REORG_FACTOR),
		configuration.getBoolean(CREATE_DIR_IF_MISSING_KEY, false));
	String isoLevelStr = configuration.getString(DEFAULT_ISOLATION_LEVEL_KEY);
	if (isoLevelStr != null) {
		setDefaultIsolationLevel(BitsyIsolationLevel.valueOf(isoLevelStr));
	}
	String vertexIndices = configuration.getString(VERTEX_INDICES_KEY);
	if (vertexIndices != null) {
		createIndices(Vertex.class, vertexIndices);
	}
	String edgeIndices = configuration.getString(EDGE_INDICES_KEY);
	if (edgeIndices != null) {
		createIndices(Edge.class, edgeIndices);
	}
	this.origConfig = configuration;
}
 
Example 24
Project: bitsy   File: BitsyTestGraphProvider.java   Source Code and License 6 votes vote down vote up
@Override
	public void clear(Graph graph, Configuration configuration) throws Exception {
        if (graph != null) {
        	if (graph.tx().isOpen()) graph.tx().close();
        	graph.tx().onReadWrite(READ_WRITE_BEHAVIOR.MANUAL);
        	graph.tx().open();
        	System.out.println("Clearing graph");
        	graph.vertices().forEachRemaining(v -> v.remove());
        	graph.tx().commit();
        	System.out.println("Shutting down graph " + graph);
            graph.close();
        }

//		Thread.sleep(10);
//        File directory = new File(configuration.getString(BitsyGraph.DB_PATH_KEY));
//        wipeOut(directory);
//		Thread.sleep(10);
	}
 
Example 25
Project: hadoop   File: MetricsConfig.java   Source Code and License 6 votes vote down vote up
/**
 * Load configuration from a list of files until the first successful load
 * @param conf  the configuration object
 * @param files the list of filenames to try
 * @return  the configuration object
 */
static MetricsConfig loadFirst(String prefix, String... fileNames) {
  for (String fname : fileNames) {
    try {
      Configuration cf = new PropertiesConfiguration(fname)
          .interpolatedConfiguration();
      LOG.info("loaded properties from "+ fname);
      LOG.debug(toString(cf));
      MetricsConfig mc = new MetricsConfig(cf, prefix);
      LOG.debug(mc);
      return mc;
    }
    catch (ConfigurationException e) {
      if (e.getMessage().startsWith("Cannot locate configuration")) {
        continue;
      }
      throw new MetricsConfigException(e);
    }
  }
  LOG.warn("Cannot locate configuration: tried "+
           Joiner.on(",").join(fileNames));
  // default to an empty configuration
  return new MetricsConfig(new PropertiesConfiguration(), prefix);
}
 
Example 26
Project: jbake-rtl-jalaali   File: ParserContext.java   Source Code and License 5 votes vote down vote up
public ParserContext(
        File file,
        List<String> fileLines,
        Configuration config,
        String contentPath,
        boolean hasHeader,
        Map<String, Object> contents) {
    this.file = file;
    this.fileLines = fileLines;
    this.config = config;
    this.contentPath = contentPath;
    this.hasHeader = hasHeader;
    this.contents = contents;
}
 
Example 27
Project: obevo   File: DbDataComparisonConfigFactory.java   Source Code and License 5 votes vote down vote up
public static DbDataComparisonConfig createFromProperties(final Configuration config) {
    Properties propsView = ConfigurationConverter.getProperties(config);  // config.getString() automatically parses
    // for commas...would like to avoid this
    DbDataComparisonConfig compConfig = new DbDataComparisonConfig();
    compConfig.setInputTables(Lists.mutable.with(propsView.getProperty("tables.include").split(",")));
    compConfig.setExcludedTables(Lists.mutable.with(propsView.getProperty("tables.exclude").split(",")).toSet());
    String comparisonsStr = propsView.getProperty("comparisons");

    MutableList<Pair<String, String>> compCmdPairs = Lists.mutable.empty();
    MutableSet<String> dsNames = UnifiedSet.newSet();
    for (String compPairStr : comparisonsStr.split(";")) {
        String[] pairParts = compPairStr.split(",");
        compCmdPairs.add(Tuples.pair(pairParts[0], pairParts[1]));

        // note - if I knew where the Pair.TO_ONE TO_TWO selectors were, I'd use those
        dsNames.add(pairParts[0]);
        dsNames.add(pairParts[1]);
    }

    compConfig.setComparisonCommandNamePairs(compCmdPairs);

    MutableList<DbDataSource> dbDataSources = dsNames.toList().collect(new Function<String, DbDataSource>() {
        @Override
        public DbDataSource valueOf(String dsName) {
            Configuration dsConfig = config.subset(dsName);

            DbDataSource dbDataSource = new DbDataSource();
            dbDataSource.setName(dsName);
            dbDataSource.setUrl(dsConfig.getString("url"));
            dbDataSource.setSchema(dsConfig.getString("schema"));
            dbDataSource.setUsername(dsConfig.getString("username"));
            dbDataSource.setPassword(dsConfig.getString("password"));
            dbDataSource.setDriverClassName(dsConfig.getString("driverClass"));

            return dbDataSource;
        }
    });
    compConfig.setDbDataSources(dbDataSources);
    return compConfig;
}
 
Example 28
Project: jbake-rtl-jalaali   File: MarkupEngine.java   Source Code and License 5 votes vote down vote up
/**
 * Process the header of the file.
 * @param config 
 *
 * @param contents Contents of file
 * @param content
 */
private void processHeader(Configuration config, List<String> contents, final Map<String, Object> content) {
    for (String line : contents) {
        if (line.equals(HEADER_SEPARATOR)) {
            break;
        }

        if (line.isEmpty()) {
        	continue;
        }
        
        String[] parts = line.split("=",2);
        if (parts.length != 2) {
            continue;
        }

        String key = parts[0].trim();
        String value = parts[1].trim();

        if (key.equalsIgnoreCase(Crawler.Attributes.DATE)) {
            DateFormat df = new SimpleDateFormat(config.getString(Keys.DATE_FORMAT));
            Date date = null;
            try {
                date = df.parse(value);
                content.put(key, date);
            } catch (ParseException e) {
                e.printStackTrace();
            }
        } else if (key.equalsIgnoreCase(Crawler.Attributes.TAGS)) {
            content.put(key, getTags(value));
        } else if (isJson(value)) {
            content.put(key, JSONValue.parse(value));
        } else {
            content.put(key, value);
        }
    }
}
 
Example 29
Project: jbake-rtl-jalaali   File: TemplateEngines.java   Source Code and License 5 votes vote down vote up
private void registerEngine(final Configuration config, final ContentStore db, final File destination, final File templatesPath, String className, String... extensions) {
    AbstractTemplateEngine engine = tryLoadEngine(config, db, destination, templatesPath, className);
    if (engine != null) {
        for (String extension : extensions) {
            registerEngine(extension, engine);
        }
    }
}
 
Example 30
Project: KantaCDA-API   File: MaarittelyKonfiguraatio.java   Source Code and License 5 votes vote down vote up
private void kasitteleTyyppi(Configuration config, String templateId) {
    MaarittelyLuokka luokka = MaarittelyLuokka.VANHA;
    for (String token : config.getStringArray(templateId)) {
        if ( (token == null) || "".equals(token) ) {
            continue;
        }
        token = token.trim().toUpperCase();
        if ( "NYKYINEN".equals(token) ) {
            luokka = MaarittelyLuokka.NYKYINEN;
        }
        else if ( "TULEVA".equals(token) ) {
            luokka = MaarittelyLuokka.TULEVA;
        }
        else if ( "VANHA".equals(token) ) {
            luokka = MaarittelyLuokka.VANHA;
        }
        else if ( "EI_TUETTU".equals(token) ) {
            luokka = MaarittelyLuokka.EI_TUETTU;
        }
        else if ( "*".equals(token) ) {
            kasitteleKoodi(templateId, luokka);
        }
        else {
            kasitteleKoodi(templateId + "..." + token, luokka);
        }
    }
}
 
Example 31
Project: incubator-servicecomb-java-chassis   File: ConfigUtil.java   Source Code and License 5 votes vote down vote up
public static Object getProperty(Object config, String key) {
  if (null != config && Configuration.class.isInstance(config)) {
    Configuration configuration = (Configuration) config;
    return configuration.getProperty(key);
  }
  return null;
}
 
Example 32
Project: hadoop   File: TestMetricsConfig.java   Source Code and License 5 votes vote down vote up
/**
 * Common use cases
 * @throws Exception
 */
@Test public void testCommon() throws Exception {
  String filename = getTestFilename("test-metrics2");
  new ConfigBuilder()
      .add("*.foo", "default foo")
      .add("p1.*.bar", "p1 default bar")
      .add("p1.t1.*.bar", "p1.t1 default bar")
      .add("p1.t1.i1.name", "p1.t1.i1.name")
      .add("p1.t1.42.bar", "p1.t1.42.bar")
      .add("p1.t2.i1.foo", "p1.t2.i1.foo")
      .add("p2.*.foo", "p2 default foo")
      .save(filename);

  MetricsConfig mc = MetricsConfig.create("p1", filename);
  LOG.debug("mc:"+ mc);

  Configuration expected = new ConfigBuilder()
      .add("*.bar", "p1 default bar")
      .add("t1.*.bar", "p1.t1 default bar")
      .add("t1.i1.name", "p1.t1.i1.name")
      .add("t1.42.bar", "p1.t1.42.bar")
      .add("t2.i1.foo", "p1.t2.i1.foo")
      .config;

  assertEq(expected, mc);

  testInstances(mc);
}
 
Example 33
Project: redirector   File: ServiceInfo.java   Source Code and License 5 votes vote down vote up
public ServiceInfo(Configuration config) {
    // read the maven properties
    projectName = getString(config, PROJECT_NAME_KEY);
    projectVersion = getString(config, "ProjectVersion");

    // read the sub-version properties
    rev = getString(config, REVISION_KEY);
    source = config.getString(SOURCE_KEY);
    if (source != null && !source.isEmpty()) {
        try {
            URI uri = new URI(source);
            source = uri.getPath();
        } catch (Exception e) {
            log.warn("An error occurs while process source URI " + source, e);
            source = NA;
        }
    } else {
        source = NA;
    }

    // read the git properties
    gitBranch = getString(config, "git.branch");
    gitBuildTime = getString(config, "git.build.time");
    gitCommitId = getString(config, "git.commit.id");
    gitCommitTime = getString(config, "git.commit.time");

    // read the serviceName and serviceVersion set in wrapper.sh
    serviceName = System.getProperty("serviceName", NA);
    serviceVersion = System.getProperty("serviceVersion", NA);
}
 
Example 34
Project: incubator-servicecomb-java-chassis   File: MicroserviceDefinition.java   Source Code and License 5 votes vote down vote up
private void initCombinedFrom(List<ConfigModel> configModels) {
  for (ConfigModel model : configModels) {
    Configuration conf = ConfigUtil.createLocalConfig(Arrays.asList(model));
    String name =
        conf.getString(CONFIG_QUALIFIED_MICROSERVICE_NAME_KEY, DEFAULT_MICROSERVICE_NAME);
    if (!StringUtils.isEmpty(name)) {
      checkMicroserviceName(name);
      combinedFrom.add(name);
    }
  }

  combinedFrom.remove(microserviceName);
}
 
Example 35
Project: NGB-master   File: ConfigurationLoader.java   Source Code and License 5 votes vote down vote up
/**
 * Loads XML configuration file with application commands. This file contains
 * information required for initializing and running commands: type of the command,
 * type of request and URL (for NGB server commands) and any supplementary data
 * @param fullCommand name of the command to load configuration for
 * @return configuration for the specifies command
 */
public CommandConfiguration loadCommandConfiguration(String fullCommand) {
    Configuration configuration = loadXmlConfiguration(COMMAND_XML_CONFIG);
    String name = configuration.getString(fullCommand + COMMAND_NAME_PROPERTY);
    String url = configuration.getString(fullCommand + COMMAND_URL_PROPERTY);
    String type = configuration.getString(fullCommand + COMMAND_TYPE_PROPERTY);
    boolean secure = false;
    if (configuration.getString(fullCommand + COMMAND_SECURE_PROPERTY) != null) {
        secure = configuration.getBoolean(fullCommand + COMMAND_SECURE_PROPERTY);
    }
    return new CommandConfiguration(name, url, type, secure);
}
 
Example 36
Project: incubator-servicecomb-java-chassis   File: ConfigurePropertyUtils.java   Source Code and License 5 votes vote down vote up
public static Map<String, String> getPropertiesWithPrefix(Configuration configuration, String prefix) {
  Map<String, String> propertiesMap = new HashMap<>();

  Iterator<String> keysIterator = configuration.getKeys(prefix);
  while (keysIterator.hasNext()) {
    String key = keysIterator.next();
    propertiesMap.put(key.substring(prefix.length() + 1), String.valueOf(configuration.getProperty(key)));
  }
  return propertiesMap;
}
 
Example 37
Project: incubator-servicecomb-java-chassis   File: ConfigurePropertyUtils.java   Source Code and License 5 votes vote down vote up
@SuppressWarnings("unchecked")
public static List<BasePath> getMicroservicePaths(Configuration configuration) {
  List<BasePath> basePaths = new ArrayList<>();
  for (Object path : configuration.getList("service_description.paths")) {
    BasePath basePath = new BasePath();
    Map<String, ?> pathMap = (Map<String, ?>) path;
    basePath.setPath(buildPath((String) pathMap.get("path")));
    basePath.setProperty((Map<String, String>) pathMap.get("property"));
    basePaths.add(basePath);
  }
  return basePaths;
}
 
Example 38
Project: incubator-servicecomb-java-chassis   File: AbstractPropertiesLoader.java   Source Code and License 5 votes vote down vote up
public Map<String, String> loadProperties(Configuration configuration) {
  Map<String, String> propertiesMap = new HashMap<>();
  loadPropertiesFromConfigMap(configuration, propertiesMap);
  loadPropertiesFromExtendedClass(configuration, propertiesMap);

  return propertiesMap;
}
 
Example 39
Project: incubator-servicecomb-java-chassis   File: TestPropertiesLoader.java   Source Code and License 5 votes vote down vote up
@Test
public void testExtendedClassCompatible() {
  Configuration configuration = new DynamicConfiguration();
  configuration.setProperty(CONFIG_SERVICE_DESCRIPTION_KEY + AbstractPropertiesLoader.EXTENDED_CLASS, "invalidClass");

  AbstractPropertiesLoader loader = MicroservicePropertiesLoader.INSTANCE;
  try {
    loader.loadProperties(configuration);
    Assert.fail("Must throw exception");
  } catch (Error e) {
    Assert.assertEquals(ClassNotFoundException.class, e.getCause().getClass());
    Assert.assertEquals("invalidClass", e.getCause().getMessage());
  }
}
 
Example 40
Project: java-market-maker   File: MarketMakerConfiguration.java   Source Code and License 5 votes vote down vote up
public static MarketMakerConfiguration fromPropertiesFile(final String fileName) throws ConfigurationException {
    final Configuration configuration = new PropertiesConfiguration(fileName);
    return new MarketMakerConfiguration(
        configuration.getInt(ConfigKey.TIME_SLEEP_SECONDS.getKey()),
        new BigDecimal(configuration.getString(ConfigKey.SPREAD_FRACTION.getKey())),
        configuration.getDouble(ConfigKey.FAIR_VOLATILITY.getKey()),
        configuration.getDouble(ConfigKey.VOLATILITY_SPREAD_FRACTION.getKey()),
        configuration.getInt(ConfigKey.NUM_LEVELS.getKey()),
        configuration.getInt(ConfigKey.QUANTITY_ON_LEVEL.getKey()),
        configuration.getDouble(ConfigKey.DELTA_LIMIT.getKey()),
        configuration.getDouble(ConfigKey.VEGA_LIMIT.getKey())
    );
}
 
Example 41
Project: hadoop-oss   File: MetricsConfig.java   Source Code and License 5 votes vote down vote up
/**
 * Load configuration from a list of files until the first successful load
 * @param conf  the configuration object
 * @param files the list of filenames to try
 * @return  the configuration object
 */
static MetricsConfig loadFirst(String prefix, String... fileNames) {
  for (String fname : fileNames) {
    try {
      Configuration cf = new PropertiesConfiguration(fname)
          .interpolatedConfiguration();
      LOG.info("loaded properties from "+ fname);
      LOG.debug(toString(cf));
      MetricsConfig mc = new MetricsConfig(cf, prefix);
      LOG.debug(mc);
      return mc;
    } catch (ConfigurationException e) {
      if (e.getMessage().startsWith("Cannot locate configuration")) {
        continue;
      }
      throw new MetricsConfigException(e);
    }
  }
  LOG.warn("Cannot locate configuration: tried "+
           Joiner.on(",").join(fileNames));
  // default to an empty configuration
  return new MetricsConfig(new PropertiesConfiguration(), prefix);
}
 
Example 42
Project: hadoop-oss   File: MetricsConfig.java   Source Code and License 5 votes vote down vote up
static String toString(Configuration c) {
  ByteArrayOutputStream buffer = new ByteArrayOutputStream();
  try {
    PrintStream ps = new PrintStream(buffer, false, "UTF-8");
    PropertiesConfiguration tmp = new PropertiesConfiguration();
    tmp.copy(c);
    tmp.save(ps);
    return buffer.toString("UTF-8");
  } catch (Exception e) {
    throw new MetricsConfigException(e);
  }
}
 
Example 43
Project: hadoop-oss   File: ConfigUtil.java   Source Code and License 5 votes vote down vote up
static void dump(String header, Configuration c, PrintStream out) {
  PropertiesConfiguration p = new PropertiesConfiguration();
  p.copy(c);
  if (header != null) {
    out.println(header);
  }
  try { p.save(out); }
  catch (Exception e) {
    throw new RuntimeException("Error saving config", e);
  }
}
 
Example 44
Project: hadoop-oss   File: TestMetricsConfig.java   Source Code and License 5 votes vote down vote up
/**
 * Common use cases
 * @throws Exception
 */
@Test public void testCommon() throws Exception {
  String filename = getTestFilename("test-metrics2");
  new ConfigBuilder()
      .add("*.foo", "default foo")
      .add("p1.*.bar", "p1 default bar")
      .add("p1.t1.*.bar", "p1.t1 default bar")
      .add("p1.t1.i1.name", "p1.t1.i1.name")
      .add("p1.t1.42.bar", "p1.t1.42.bar")
      .add("p1.t2.i1.foo", "p1.t2.i1.foo")
      .add("p2.*.foo", "p2 default foo")
      .save(filename);

  MetricsConfig mc = MetricsConfig.create("p1", filename);
  LOG.debug("mc:"+ mc);

  Configuration expected = new ConfigBuilder()
      .add("*.bar", "p1 default bar")
      .add("t1.*.bar", "p1.t1 default bar")
      .add("t1.i1.name", "p1.t1.i1.name")
      .add("t1.42.bar", "p1.t1.42.bar")
      .add("t2.i1.foo", "p1.t2.i1.foo")
      .config;

  assertEq(expected, mc);

  testInstances(mc);
}
 
Example 45
Project: hadoop-oss   File: TestMetricsConfig.java   Source Code and License 5 votes vote down vote up
/**
 * Test the config file load order
 * @throws Exception
 */
@Test public void testLoadFirst() throws Exception {
  String filename = getTestFilename("hadoop-metrics2-p1");
  new ConfigBuilder().add("p1.foo", "p1foo").save(filename);

  MetricsConfig mc = MetricsConfig.create("p1");
  MetricsConfig mc2 = MetricsConfig.create("p1", "na1", "na2", filename);
  Configuration expected = new ConfigBuilder().add("foo", "p1foo").config;

  assertEq(expected, mc);
  assertEq(expected, mc2);
}
 
Example 46
Project: newblog   File: HttpHelper.java   Source Code and License 5 votes vote down vote up
/**
 * 描述:创建httpClient连接池,并初始化httpclient
 */
private void initHttpClient() throws ConfigurationException {
    Configuration configuration = new PropertiesConfiguration(CONFIG_FILE);
    //创建httpclient连接池
    PoolingHttpClientConnectionManager httpClientConnectionManager = new PoolingHttpClientConnectionManager();
    httpClientConnectionManager.setMaxTotal(configuration.getInt("http.max.total"));    //设置连接池线程最大数量
    httpClientConnectionManager.setDefaultMaxPerRoute(configuration.getInt("http.max.route"));    //设置单个路由最大的连接线程数量
    //创建http request的配置信息
    RequestConfig requestConfig = RequestConfig.custom()
            .setConnectionRequestTimeout(configuration.getInt("http.request.timeout"))
            .setSocketTimeout(configuration.getInt("http.socket.timeout"))
            .setCookieSpec(CookieSpecs.DEFAULT).build();
    //设置重定向策略
    LaxRedirectStrategy redirectStrategy = new LaxRedirectStrategy() {
        /**
         * false 禁止重定向  true 允许
         */
        @Override
        public boolean isRedirected(HttpRequest request,
                                    HttpResponse response, HttpContext context)
                throws ProtocolException {
            // TODO Auto-generated method stub
            return isRediect ? super.isRedirected(request, response, context) : isRediect;
        }
    };
    //初始化httpclient客户端
    httpClient = HttpClients.custom().setConnectionManager(httpClientConnectionManager)
            .setDefaultRequestConfig(requestConfig)
            //.setUserAgent(NewsConstant.USER_AGENT)
            .setRedirectStrategy(redirectStrategy)
            .build();
}
 
Example 47
Project: redirector   File: DataServiceInfo.java   Source Code and License 5 votes vote down vote up
public ServiceInfo(Configuration config) {
    // read the maven properties
    projectName = getString(config, PROJECT_NAME_KEY);
    projectVersion = getString(config, "ProjectVersion");

    // read the sub-version properties
    rev = getString(config, REVISION_KEY);
    source = config.getString(SOURCE_KEY);
    if (source != null && !source.isEmpty()) {
        try {
            URI uri = new URI(source);
            source = uri.getPath();
        } catch (Exception e) {
            log.warn("An error occurs while process source URI " + source, e);
            source = NA;
        }
    } else {
        source = NA;
    }

    // read the git properties
    gitBranch = getString(config, "git.branch");
    gitBuildTime = getString(config, "git.build.time");
    gitCommitId = getString(config, "git.commit.id");
    gitCommitTime = getString(config, "git.commit.time");

    // read the serviceName and serviceVersion set in wrapper.sh
    serviceName = System.getProperty("serviceName", NA);
    serviceVersion = System.getProperty("serviceVersion", NA);
}
 
Example 48
Project: spring-configuration-support   File: DatabaseConfigurationPropertiesFactoryBean.java   Source Code and License 5 votes vote down vote up
/**
 * Creates a properties instance with the key/value pairs specified within the passed configuration object.
 *
 * @param configuration the configuration
 * @return the populated properties instance
 */
protected Properties createPropertiesForConfiguration(Configuration configuration){

	Properties properties = new Properties();

	final Iterator keys = configuration.getKeys();
	while (keys.hasNext()) {
		String key = (String) keys.next();
		List list = configuration.getList(key);
		properties.setProperty(key, (String) list.get(0));
	}

	return properties;
}
 
Example 49
Project: gremzeppelin   File: GremlinInterpreter.java   Source Code and License 5 votes vote down vote up
@Override
public void open() {
    logger.info("init gremlin client via {}", property);
    Configuration configuration = new BaseConfiguration();
    property.keySet().forEach(key -> configuration.setProperty(key.toString(), property.get(key)));
    //transform hosts
    String hosts = configuration.getString(GREMLIN_SERVER_HOSTS, DEFAULT_GREMLIN_SERVER_HOSTS);
    configuration.clearProperty(GREMLIN_SERVER_HOSTS);
    configuration.setProperty(GREMLIN_SERVER_HOSTS, Arrays.asList(hosts.split(",")));

    cluster = Cluster.open(configuration.subset("gremlin.server"));
    client = cluster.connect();
}
 
Example 50
Project: tinkergraph-gremlin   File: TinkerGraph.java   Source Code and License 5 votes vote down vote up
public static TinkerGraph open(final Configuration configuration,
                               List<SpecializedElementFactory.ForVertex<?, ?>> vertexFactories,
                               List<SpecializedElementFactory.ForEdge<?, ?>> edgeFactories) {
    boolean usesSpecializedElements = !vertexFactories.isEmpty() || !edgeFactories.isEmpty();
    TinkerGraph tg =  new TinkerGraph(configuration, usesSpecializedElements);
    vertexFactories.forEach(factory -> tg.specializedVertexFactoryByLabel.put(factory.forLabel(), factory));
    edgeFactories.forEach(factory -> tg.specializedEdgeFactoryByLabel.put(factory.forLabel(), factory));
    return tg;
}
 
Example 51
Project: tinkergraph-gremlin   File: TinkerGraph.java   Source Code and License 5 votes vote down vote up
/**
 * Construct an {@link TinkerGraph.IdManager} from the TinkerGraph {@code Configuration}.
 */
private static IdManager<?> selectIdManager(final Configuration config, final String configKey, final Class<? extends Element> clazz) {
    final String vertexIdManagerConfigValue = config.getString(configKey, DefaultIdManager.ANY.name());
    try {
        return DefaultIdManager.valueOf(vertexIdManagerConfigValue);
    } catch (IllegalArgumentException iae) {
        try {
            return (IdManager) Class.forName(vertexIdManagerConfigValue).newInstance();
        } catch (Exception ex) {
            throw new IllegalStateException(String.format("Could not configure TinkerGraph %s id manager with %s", clazz.getSimpleName(), vertexIdManagerConfigValue));
        }
    }
}
 
Example 52
Project: tinkergraph-gremlin   File: TinkerFactory.java   Source Code and License 5 votes vote down vote up
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 53
Project: tinkergraph-gremlin   File: TinkerFactory.java   Source Code and License 5 votes vote down vote up
public static TinkerGraph createTheCrew() {
    final Configuration conf = getNumberIdManagerConfiguration();
    conf.setProperty(TinkerGraph.GREMLIN_TINKERGRAPH_DEFAULT_VERTEX_PROPERTY_CARDINALITY, VertexProperty.Cardinality.list.name());
    final TinkerGraph g = TinkerGraph.open(conf);
    generateTheCrew(g);
    return g;
}
 
Example 54
Project: tinkergraph-gremlin   File: TinkerFactory.java   Source Code and License 5 votes vote down vote up
private static Configuration getNumberIdManagerConfiguration() {
    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.LONG.name());
    return conf;
}
 
Example 55
Project: my-spring-boot-project   File: GenUtils.java   Source Code and License 5 votes vote down vote up
/**
 * 获取配置信息
 */
public static Configuration getConfig() {
    try {
        return new PropertiesConfiguration("generator.properties");
    } catch (ConfigurationException e) {
        throw new RRException("获取配置文件失败,", e);
    }
}
 
Example 56
Project: tinkergraph-gremlin   File: TinkerIoRegistryV3d0.java   Source Code and License 5 votes vote down vote up
@Override
public TinkerGraph read(final Kryo kryo, final Input input, final Class<TinkerGraph> tinkerGraphClass) {
    final Configuration conf = new BaseConfiguration();
    conf.setProperty("gremlin.tinkergraph.defaultVertexPropertyCardinality", "list");
    final TinkerGraph graph = TinkerGraph.open(conf);
    final int len = input.readInt();
    final byte[] bytes = input.readBytes(len);
    try (final ByteArrayInputStream stream = new ByteArrayInputStream(bytes)) {
        GryoReader.build().mapper(() -> kryo).create().readGraph(stream, graph);
    } catch (Exception io) {
        throw new RuntimeException(io);
    }

    return graph;
}
 
Example 57
Project: tinkergraph-gremlin   File: TinkerIoRegistryV2d0.java   Source Code and License 5 votes vote down vote up
@Override
public TinkerGraph read(final Kryo kryo, final Input input, final Class<TinkerGraph> tinkerGraphClass) {
    final Configuration conf = new BaseConfiguration();
    conf.setProperty("gremlin.tinkergraph.defaultVertexPropertyCardinality", "list");
    final TinkerGraph graph = TinkerGraph.open(conf);
    final int len = input.readInt();
    final byte[] bytes = input.readBytes(len);
    try (final ByteArrayInputStream stream = new ByteArrayInputStream(bytes)) {
        GryoReader.build().mapper(() -> kryo).create().readGraph(stream, graph);
    } catch (Exception io) {
        throw new RuntimeException(io);
    }

    return graph;
}
 
Example 58
Project: BUbiNG   File: StartupConfiguration.java   Source Code and License 5 votes vote down vote up
/** Takes two configuration and returns their union, with the second overriding the first.
 *
 * @param base the base configuration.
 * @param additional the additional set of properties, some of which may override those specified in <code>base</code>.
 * @return the union of the two configurations, as specified above.
 */
private static Configuration append(Configuration base, Configuration additional) {
	final CompositeConfiguration result = new CompositeConfiguration();
	result.addConfiguration(additional);
	result.addConfiguration(base);
	return result;
}
 
Example 59
Project: tinkergraph-gremlin   File: TinkerGraphTest.java   Source Code and License 5 votes vote down vote up
@Test
public void shouldPersistToAnyGraphFormat() {
    final String graphLocation = TestHelper.makeTestDataDirectory(TinkerGraphTest.class) + "shouldPersistToAnyGraphFormat.dat";
    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, TestIoBuilder.class.getName());
    conf.setProperty(TinkerGraph.GREMLIN_TINKERGRAPH_GRAPH_LOCATION, graphLocation);
    final TinkerGraph graph = TinkerGraph.open(conf);
    TinkerFactory.generateModern(graph);

    //Test write graph
    graph.close();
    assertEquals(TestIoBuilder.calledOnMapper, 1);
    assertEquals(TestIoBuilder.calledGraph, 1);
    assertEquals(TestIoBuilder.calledCreate, 1);

    try (BufferedOutputStream os = new BufferedOutputStream(new FileOutputStream(f))){
        os.write("dummy string".getBytes());
    } catch (Exception e) {
        e.printStackTrace();
    }

    //Test read graph
    final TinkerGraph readGraph = TinkerGraph.open(conf);
    assertEquals(TestIoBuilder.calledOnMapper, 1);
    assertEquals(TestIoBuilder.calledGraph, 1);
    assertEquals(TestIoBuilder.calledCreate, 1);
}
 
Example 60
Project: unitimes   File: MessageResources.java   Source Code and License 5 votes vote down vote up
private Configuration getConfiguration(String name) {
	Configuration configuration = null;
	URL url = Thread.currentThread().getContextClassLoader().getResource(name);
	if (url != null) {
		PropertiesConfiguration pc = new PropertiesConfiguration();
		pc.setURL(url);
		
		// Set reloading strategy 
		String dynamicReload = ApplicationProperties.getProperty("tmtbl.properties.dynamic_reload", null);
		if (dynamicReload!=null && dynamicReload.equalsIgnoreCase("true")) {
			long refreshDelay = Constants.getPositiveInteger(
					ApplicationProperties.getProperty("tmtbl.properties.dynamic_reload_interval"), 15000 );
			
			FileChangedReloadingStrategy strategy = new FileChangedReloadingStrategy();
			strategy.setRefreshDelay(refreshDelay); 
			pc.setReloadingStrategy(strategy);
			
			pc.addConfigurationListener(new MessageResourcesCfgListener(pc.getBasePath()));
		}			
		
		try {
			pc.load();
			configuration = pc;
		} catch (ConfigurationException e) {
			Debug.error("Message Resources configuration exception: " + e.getMessage());
		}
	}

	return configuration;
}