@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); } }
@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); }
@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); }
@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."); }
@Test public void testGetServletUrlPattern() { DynamicPropertyFactory.getInstance(); Configuration configuration = (Configuration) DynamicPropertyFactory.getBackingConfigurationSource(); configuration.setProperty(ServletConfig.KEY_SERVLET_URL_PATTERN, "/*"); Assert.assertEquals("/*", ServletConfig.getServletUrlPattern()); }
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; }
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; }
/** * 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(); } }
@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); }
public static void setProperty(String key, Object value) { // ensure have instance DynamicPropertyFactory.getInstance(); Configuration config = (Configuration) DynamicPropertyFactory.getBackingConfigurationSource(); config.addProperty(key, value); }
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); }
@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()); }
/** * 获取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); }
@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); }
/** * 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); }
@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")); }
/** * 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(); }
@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; }
@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(); }
@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(); }
@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(); }
@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(); }
/** * 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; }
@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); }
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; }
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; }
/** * 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); } } }
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); } } }
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); } } }
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; }
/** * 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); }
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); }
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); }
/** * 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); }
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; }
@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; }
public Map<String, String> loadProperties(Configuration configuration) { Map<String, String> propertiesMap = new HashMap<>(); loadPropertiesFromConfigMap(configuration, propertiesMap); loadPropertiesFromExtendedClass(configuration, propertiesMap); return propertiesMap; }
@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()); } }