List of usage examples for org.apache.commons.configuration MapConfiguration MapConfiguration
public MapConfiguration(Map map)
From source file:at.gv.egiz.bku.spring.ConfigurationFactoryBean.java
protected Configuration getVersionConfiguration() throws IOException { Map<String, Object> map = new HashMap<String, Object>(); map.put(MOCCA_IMPLEMENTATIONNAME_PROPERTY, "MOCCA"); // implementation version String version = null;/* w w w . j a va 2 s .c o m*/ try { Resource resource = resourceLoader.getResource("META-INF/MANIFEST.MF"); Manifest properties = new Manifest(resource.getInputStream()); Attributes attributes = properties.getMainAttributes(); // TODO: replace by Implementation-Version ? version = attributes.getValue("Implementation-Build"); } catch (Exception e) { log.warn("Failed to get implemenation version from manifest. {}", e.getMessage()); } if (version == null) { version = "UNKNOWN"; } map.put(MOCCA_IMPLEMENTATIONVERSION_PROPERTY, version); // signature layout try { String classContainer = JarLocation.get(CreateXMLSignatureCommandImpl.class); URL manifestUrl = new URL("jar:" + classContainer + "!/META-INF/MANIFEST.MF"); log.debug(manifestUrl.toString()); Manifest manifest = new Manifest(manifestUrl.openStream()); Attributes attributes = manifest.getMainAttributes(); String signatureLayout = attributes.getValue("SignatureLayout"); if (signatureLayout != null) { map.put(SIGNATURE_LAYOUT_PROPERTY, signatureLayout); } } catch (Exception e) { log.warn("Failed to get signature layout from manifest.", e); } return new MapConfiguration(map); }
From source file:com.dm.estore.common.config.Cfg.java
private Configuration createConfiguration() { try {//from w w w .jav a 2 s. c o m final CompositeConfiguration compositeConfig = new CompositeConfiguration(); String configuredHome = null; if (overrideProperties != null) { MapConfiguration initialConfig = new MapConfiguration(overrideProperties); compositeConfig.addConfiguration(initialConfig); if (overrideProperties.containsKey(CommonConstants.Cfg.CFG_HOME_FOLDER)) { configuredHome = overrideProperties.getProperty(CommonConstants.Cfg.CFG_HOME_FOLDER); } } configurationHome = getOrCreateHomeFolder(configuredHome); final DefaultConfigurationBuilder builder = new DefaultConfigurationBuilder( configurationHome + File.separator + ROOT_CONFIG_NAME); final CombinedConfiguration reloadableConfig = builder.getConfiguration(true); ConfigurationLogListener listener = new ConfigurationLogListener(); reloadableConfig.addConfigurationListener(listener); reloadableConfig.addErrorListener(listener); // reloadableConfig.setForceReloadCheck(true); compositeConfig.addConfiguration(reloadableConfig); lastReloadTime = new Date(); return compositeConfig; } catch (ConfigurationException e) { LOG.error("Unable to load configuration", e); } return null; }
From source file:com.intel.mtwilson.fs.ConfigurableFilesystem.java
@Override public FeatureFilesystem getBootstrapFilesystem() { // return new BasicFeatureFilesystem(getApplicationPath()); HashMap<String, Object> map = new HashMap<>(); map.put("fs.feature.root", getApplicationPath()); map.put("fs.feature.java", getString("fs.java", getApplicationPath() + File.separator + "java")); map.put("fs.feature.hypertext", getString("fs.hypertext", getApplicationPath() + File.separator + "hypertext")); map.put("fs.feature.license_d", getString("fs.license_d", getApplicationPath() + File.separator + "license.d")); map.put("fs.feature.sql", getString("fs.sql", getApplicationPath() + File.separator + "sql")); map.put("fs.feature.bin", getString("fs.bin", getApplicationPath() + File.separator + "bin")); map.put("fs.feature.var", getString("fs.var", getApplicationPath() + File.separator + "var")); ConfigurableFeatureFilesystem featureFilesystem = new ConfigurableFeatureFilesystem( new MapConfiguration(map)); return featureFilesystem; }
From source file:com.comcast.viper.flume2storm.sink.StormSinkConfiguration.java
/** * Copy constructor//from w w w. ja v a 2s. com * * @param other * the configuration to copy */ public StormSinkConfiguration(final StormSinkConfiguration other) { batchSize = other.batchSize; locationServiceFactoryClassName = other.locationServiceFactoryClassName; serviceProviderSerializationClassName = other.serviceProviderSerializationClassName; connectionParametersFactoryClassName = other.connectionParametersFactoryClassName; eventSenderFactoryClassName = other.eventSenderFactoryClassName; configuration = new MapConfiguration(ConfigurationConverter.getMap(other.configuration)); }
From source file:com.cloudera.csd.tools.MetricDescriptorGeneratorTool.java
private MapConfiguration generateAndValidateConfig(CommandLine cmdLine) throws ParseException { Preconditions.checkNotNull(cmdLine); MapConfiguration ret = new MapConfiguration(Maps.<String, Object>newHashMap()); for (Option option : cmdLine.getOptions()) { ret.addProperty(option.getLongOpt(), option.getValue()); }/*from ww w. j ava 2 s . c o m*/ if (null == ret.getProperty(OPT_INPUT_MDL.getLongOpt())) { throw new ParseException("MetricGeneratorTool missing mdl file " + "location"); } else { String fileName = ret.getString(OPT_INPUT_MDL.getLongOpt()); File file = new File(fileName); if (!file.exists()) { throw new ParseException("MDL file '" + fileName + "' does not " + "exist"); } else if (!file.isFile()) { throw new ParseException("MDL file '" + fileName + "' is not a " + "file"); } } if (null == ret.getProperty(OPT_INPUT_FIXTURE.getLongOpt())) { throw new ParseException("MetricGeneratorTool missing fixture file " + "location"); } else { String fileName = ret.getString(OPT_INPUT_FIXTURE.getLongOpt()); File file = new File(fileName); if (!file.exists()) { throw new ParseException("Fixture file '" + fileName + "' does not " + "exist"); } else if (!file.isFile()) { throw new ParseException("Fixture file '" + fileName + "' is not a " + "file"); } } if (null != ret.getProperty(OPT_INPUT_CONVENTIONS.getLongOpt())) { String fileName = ret.getString(OPT_INPUT_CONVENTIONS.getLongOpt()); File file = new File(fileName); if (!file.exists()) { throw new ParseException("Conventions file '" + fileName + "' does " + "not exist"); } else if (!file.isFile()) { throw new ParseException("Conventions file '" + fileName + "' is " + "not a file"); } } if (null == ret.getProperty(OPT_ADAPTER_CLASS.getLongOpt())) { throw new ParseException("MetricGeneratorTool missing adapter class"); } else { String className = ret.getString(OPT_ADAPTER_CLASS.getLongOpt()); try { Class<?> adapterClass = this.getClass().getClassLoader().loadClass(className); if (!MetricFixtureAdapter.class.isAssignableFrom(adapterClass)) { throw new ParseException("Adapter class " + className + "is of the " + "wrong type"); } ret.addProperty(ADAPTER_CLASS_CONFIG, adapterClass); } catch (ClassNotFoundException e) { throw new ParseException("Unknown metric adapter " + className); } } return ret; }
From source file:com.senseidb.servlet.AbstractSenseiClientServlet.java
private void handleSenseiRequest(HttpServletRequest req, HttpServletResponse resp, Broker<SenseiRequest, SenseiResult> broker) throws ServletException, IOException { long time = System.currentTimeMillis(); int numHits = 0, totalDocs = 0; String query = null;/* ww w.j a v a 2s .co m*/ SenseiRequest senseiReq = null; try { JSONObject jsonObj = null; String content = null; if ("post".equalsIgnoreCase(req.getMethod())) { BufferedReader reader = req.getReader(); content = readContent(reader); if (content == null || content.length() == 0) content = "{}"; try { jsonObj = new JSONObject(content); } catch (JSONException jse) { String contentType = req.getHeader("Content-Type"); if (contentType != null && contentType.indexOf("json") >= 0) { logger.error("JSON parsing error", jse); writeEmptyResponse(req, resp, new SenseiError(jse.getMessage(), ErrorType.JsonParsingError)); return; } logger.warn("Old client or json error", jse); // Fall back to the old REST API. In the future, we should // consider reporting JSON exceptions here. senseiReq = DefaultSenseiJSONServlet.convertSenseiRequest( new DataConfiguration(new MapConfiguration(getParameters(content)))); query = content; } } else { content = req.getParameter("json"); if (content != null) { if (content.length() == 0) content = "{}"; try { jsonObj = new JSONObject(content); } catch (JSONException jse) { logger.error("JSON parsing error", jse); writeEmptyResponse(req, resp, new SenseiError(jse.getMessage(), ErrorType.JsonParsingError)); return; } } else { senseiReq = buildSenseiRequest(req); query = URLEncodedUtils.format(HttpRestSenseiServiceImpl.convertRequestToQueryParams(senseiReq), "UTF-8"); } } if (jsonObj != null) { String bqlStmt = jsonObj.optString(BQL_STMT); JSONObject templatesJson = jsonObj.optJSONObject(JsonTemplateProcessor.TEMPLATE_MAPPING_PARAM); JSONObject compiledJson = null; if (bqlStmt.length() > 0) { try { if (jsonObj.length() == 1) query = "bql=" + bqlStmt; else query = "json=" + content; compiledJson = _compiler.compile(bqlStmt); } catch (RecognitionException e) { String errMsg = _compiler.getErrorMessage(e); if (errMsg == null) { errMsg = "Unknown parsing error."; } logger.error("BQL parsing error: " + errMsg + ", BQL: " + bqlStmt); writeEmptyResponse(req, resp, new SenseiError(errMsg, ErrorType.BQLParsingError)); return; } // Handle extra BQL filter if it exists String extraFilter = jsonObj.optString(BQL_EXTRA_FILTER); JSONObject predObj = null; if (extraFilter.length() > 0) { String bql2 = "SELECT * WHERE " + extraFilter; try { predObj = _compiler.compile(bql2); } catch (RecognitionException e) { String errMsg = _compiler.getErrorMessage(e); if (errMsg == null) { errMsg = "Unknown parsing error."; } logger.error("BQL parsing error for additional preds: " + errMsg + ", BQL: " + bql2); writeEmptyResponse(req, resp, new SenseiError( "BQL parsing error for additional preds: " + errMsg + ", BQL: " + bql2, ErrorType.BQLParsingError)); return; } // Combine filters JSONArray filter_list = new JSONArray(); JSONObject currentFilter = compiledJson.optJSONObject("filter"); if (currentFilter != null) { filter_list.put(currentFilter); } JSONArray selections = predObj.optJSONArray("selections"); if (selections != null) { for (int i = 0; i < selections.length(); ++i) { JSONObject pred = selections.getJSONObject(i); if (pred != null) { filter_list.put(pred); } } } JSONObject additionalFilter = predObj.optJSONObject("filter"); if (additionalFilter != null) { filter_list.put(additionalFilter); } if (filter_list.length() > 1) { compiledJson.put("filter", new JSONObject().put("and", filter_list)); } else if (filter_list.length() == 1) { compiledJson.put("filter", filter_list.get(0)); } } JSONObject metaData = compiledJson.optJSONObject("meta"); if (metaData != null) { JSONArray variables = metaData.optJSONArray("variables"); if (variables != null) { for (int i = 0; i < variables.length(); ++i) { String var = variables.getString(i); if (templatesJson == null || templatesJson.opt(var) == null) { writeEmptyResponse(req, resp, new SenseiError("[line:0, col:0] Variable " + var + " is not found.", ErrorType.BQLParsingError)); return; } } } } } else { // This is NOT a BQL statement query = "json=" + content; compiledJson = jsonObj; } if (templatesJson != null) { compiledJson.put(JsonTemplateProcessor.TEMPLATE_MAPPING_PARAM, templatesJson); } senseiReq = SenseiRequest.fromJSON(compiledJson, _facetInfoMap); } SenseiResult res = broker.browse(senseiReq); numHits = res.getNumHits(); totalDocs = res.getTotalDocs(); sendResponse(req, resp, senseiReq, res); } catch (JSONException e) { try { writeEmptyResponse(req, resp, new SenseiError(e.getMessage(), ErrorType.JsonParsingError)); } catch (Exception ex) { throw new ServletException(e); } } catch (Exception e) { try { logger.error(e.getMessage(), e); if (e.getCause() != null && e.getCause() instanceof JSONException) { writeEmptyResponse(req, resp, new SenseiError(e.getMessage(), ErrorType.JsonParsingError)); } else { writeEmptyResponse(req, resp, new SenseiError(e.getMessage(), ErrorType.InternalError)); } } catch (Exception ex) { throw new ServletException(e); } } finally { if (queryLogger.isInfoEnabled() && query != null) { queryLogger.info(String.format("hits(%d/%d) took %dms: %s", numHits, totalDocs, System.currentTimeMillis() - time, query)); } } }
From source file:com.comcast.viper.flume2storm.spout.FlumeSpoutConfiguration.java
/** * @see com.google.common.base.Supplier#get() * @return This object as a {@link Configuration} *//* ww w . ja v a 2s . c o m*/ public Configuration get() { return new MapConfiguration(configuration); }
From source file:com.intel.mtwilson.MyConfiguration.java
private Configuration gatherConfiguration(Properties customProperties) { CompositeConfiguration composite = new CompositeConfiguration(); // first priority: custom properties take priority over any other source if (customProperties != null) { MapConfiguration customconfig = new MapConfiguration(customProperties); logConfiguration("custom", customconfig); composite.addConfiguration(customconfig); }// ww w . j av a 2 s .c o m // second priority are properties defined on the current JVM (-D switch // or through web container) SystemConfiguration system = new SystemConfiguration(); logConfiguration("system", system); composite.addConfiguration(system); // third priority: environment variables (regular and also converted from dot-notation to all-caps) EnvironmentConfiguration env = new EnvironmentConfiguration(); logConfiguration("environment", env); composite.addConfiguration(env); // AllCapsEnvironmentConfiguration envAllCaps = new AllCapsEnvironmentConfiguration(); // logConfiguration("environment_allcaps", envAllCaps); // composite.addConfiguration(envAllCaps); List<File> files = listConfigurationFiles(); // add all the files we found so far, in the priority order for (File f : files) { // System.out.println("Looking for "+f.getAbsolutePath()); try { if (f.exists() && f.canRead()) { // first check if the file is encrypted... if it is, we need to decrypt it before loading! try (FileInputStream in = new FileInputStream(f)) { String content = IOUtils.toString(in); if (Pem.isPem(content)) { // starts with something like -----BEGIN ENCRYPTED DATA----- and ends with -----END ENCRYPTED DATA----- // a pem-format file indicates it's encrypted... we could check for "ENCRYPTED DATA" in the header and footer too. String password = getApplicationConfigurationPassword(); if (password == null) { log.warn( "Found encrypted configuration file, but no password was found in system properties or environment"); } if (password != null) { ExistingFileResource resource = new ExistingFileResource(f); PasswordEncryptedFile encryptedFile = new PasswordEncryptedFile(resource, password); String decryptedContent = encryptedFile.loadString(); Properties p = new Properties(); p.load(new StringReader(decryptedContent)); MapConfiguration encrypted = new MapConfiguration(p); logConfiguration("encrypted-file:" + f.getAbsolutePath(), encrypted); composite.addConfiguration(encrypted); } } else { log.debug("FILE {} IS IN REGULAR PROPERTIES FORMAT", f.getAbsolutePath()); PropertiesConfiguration standard = new PropertiesConfiguration(f); logConfiguration("file:" + f.getAbsolutePath(), standard); composite.addConfiguration(standard); } } } } catch (FileNotFoundException ex) { // shouldn't happen since we check for f.exists() first, but must handle it because FileInputStream can throw it log.error("File not found: " + f.getAbsolutePath(), ex); } catch (IOException ex) { log.error("Cannot load configuration: " + f.getAbsolutePath(), ex); } catch (ConfigurationException ex) { log.error("Cannot load configuration from " + f.getAbsolutePath(), ex); } } // seventh priority are properties defined on the classpath (for example defaults provided with the application, or placed in the web server container) String propertiesFilename = "mtwilson.properties"; InputStream in = getClass().getResourceAsStream("/" + propertiesFilename); try { // user's home directory (assuming it's on the classpath!) if (in != null) { Properties properties = new Properties(); properties.load(in); MapConfiguration classpath = new MapConfiguration(properties); logConfiguration("classpath:" + propertiesFilename, classpath); composite.addConfiguration(classpath); } } catch (IOException ex) { log.debug("Did not find [" + propertiesFilename + "] properties on classpath", ex); } finally { if (in != null) { try { in.close(); } catch (IOException e) { log.error("Failed to close input stream for " + propertiesFilename); } } } return composite; }
From source file:com.nesscomputing.testing.IntegrationTestRuleBuilder.java
/** * Builds the rule so that JUnit may run it. * * If the testcase module requires the configuration object use {@link IntegrationTestRuleBuilder#build(Object)} and * install the module with// w w w .j a v a 2 s. c om * * <pre> addTweakedModule(TweakedModule.forTestModule(<name or class or instance of test module>)); </pre> * * @param testCaseItself pass in the test case object so that Guice may perform field injection * @param testCaseModule any extra modules you would like injected into your test case * @return * */ public IntegrationTestRule build(final Object testCaseItself, @Nonnull final Module testCaseModule) { // // Override the test case config with the tweaks exposed by the tweaked services. // final Map<String, String> testCaseConfigTweaks = Maps.newHashMap(); final Map<String, String> serviceConfigTweaks = Maps.newHashMap(); for (final TweakedModule tweakedModule : tweakedModules) { testCaseConfigTweaks.putAll(tweakedModule.getTestCaseConfigTweaks()); serviceConfigTweaks.putAll(tweakedModule.getServiceConfigTweaks()); } // // Build the test case module. // final Config testCaseConfig = Config.getOverriddenConfig(baseConfig, new MapConfiguration(testCaseConfigTweaks), new MapConfiguration(configKeys)); final Module module = new Module() { @Override public void configure(final Binder binder) { for (TweakedModule tweakedModule : tweakedModules) { binder.install(tweakedModule.getTestCaseModule(testCaseConfig)); } binder.install(new ConfigModule(testCaseConfig)); binder.install(testCaseModule); } }; // // Build the service modules. // final Map<String, Module> serviceModules = Maps.newHashMap(); addServiceDefinitions(serviceDefinitions, serviceConfigTweaks, serviceModules); addServiceModules(serviceTweakedModules, serviceConfigTweaks, serviceModules); return new IntegrationTestRule(serviceModules, startStage, stopStage, module, testCaseItself); }
From source file:com.comcast.viper.flume2storm.IntegrationTest.java
/** * Integration test with the Dynamic Location Service and the KryoNet * Connection API// w w w . j a v a 2s .c o m * * @throws Exception * If anything went wrong */ @Test public void testDynamicLocationServiceWithKryoNet() throws Exception { // // Flume Configuration // // Base storm sink configuration BaseConfiguration sinkBaseConfig = new BaseConfiguration(); sinkBaseConfig.addProperty(StormSinkConfiguration.LOCATION_SERVICE_FACTORY_CLASS, DynamicLocationServiceFactory.class.getName()); sinkBaseConfig.addProperty(StormSinkConfiguration.SERVICE_PROVIDER_SERIALIZATION_CLASS, KryoNetServiceProviderSerialization.class.getName()); sinkBaseConfig.addProperty(StormSinkConfiguration.EVENT_SENDER_FACTORY_CLASS, KryoNetEventSenderFactory.class.getName()); sinkBaseConfig.addProperty(StormSinkConfiguration.CONNECTION_PARAMETERS_FACTORY_CLASS, KryoNetConnectionParametersFactory.class.getName()); // Location Service configuration BaseConfiguration locationServiceConfig = new BaseConfiguration(); locationServiceConfig.addProperty(DynamicLocationServiceConfiguration.CONNECTION_STRING, // zkServer.getConnectString()); "127.0.0.1:" + ZK_PORT); locationServiceConfig.addProperty(DynamicLocationServiceConfiguration.SESSION_TIMEOUT, 2000); locationServiceConfig.addProperty(DynamicLocationServiceConfiguration.CONNECTION_TIMEOUT, 500); locationServiceConfig.addProperty(DynamicLocationServiceConfiguration.RECONNECTION_DELAY, 1000); locationServiceConfig.addProperty(DynamicLocationServiceConfiguration.TERMINATION_TIMEOUT, 2000); locationServiceConfig.addProperty(DynamicLocationServiceConfiguration.BASE_PATH, "/unitTest"); locationServiceConfig.addProperty(DynamicLocationServiceConfiguration.SERVICE_NAME, "ut"); // First storm sink configuration BaseConfiguration sink1ConnectionParameters = new BaseConfiguration(); sink1ConnectionParameters.addProperty(KryoNetConnectionParameters.ADDRESS, KryoNetConnectionParameters.ADDRESS_DEFAULT); sink1ConnectionParameters.addProperty(KryoNetConnectionParameters.PORT, TestUtils.getAvailablePort()); CombinedConfiguration sink1Config = new CombinedConfiguration(); sink1Config.addConfiguration(sinkBaseConfig); sink1Config.addConfiguration(sink1ConnectionParameters, "connectionParams", KryoNetConnectionParametersFactory.CONFIG_BASE_NAME); sink1Config.addConfiguration(locationServiceConfig, "Location Service Configuration", DynamicLocationServiceFactory.CONFIG_BASE_NAME); config.addConfiguration(sink1Config, SINK1_CONFIG); // Second storm sink configuration BaseConfiguration sink2ConnectionParameters = new BaseConfiguration(); sink2ConnectionParameters.addProperty(KryoNetConnectionParameters.ADDRESS, KryoNetConnectionParameters.ADDRESS_DEFAULT); sink2ConnectionParameters.addProperty(KryoNetConnectionParameters.PORT, TestUtils.getAvailablePort()); CombinedConfiguration sink2Config = new CombinedConfiguration(); sink2Config.addConfiguration(sinkBaseConfig); sink2Config.addConfiguration(sink2ConnectionParameters, "connectionParams", KryoNetConnectionParametersFactory.CONFIG_BASE_NAME); sink2Config.addConfiguration(locationServiceConfig, "Location Service Configuration", DynamicLocationServiceFactory.CONFIG_BASE_NAME); config.addConfiguration(sink2Config, SINK2_CONFIG); // // Storm Configuration // // Global KryoNet configuration MapConfiguration kryoConfig = new MapConfiguration(new HashMap<String, Object>()); kryoConfig.addProperty(KryoNetParameters.CONNECTION_TIMEOUT, 500); kryoConfig.addProperty(KryoNetParameters.RECONNECTION_DELAY, 1000); kryoConfig.addProperty(KryoNetParameters.TERMINATION_TO, 2000); // Flume-spout base configuration CombinedConfiguration flumeSpoutBaseConfig = new CombinedConfiguration(); flumeSpoutBaseConfig.addProperty(FlumeSpoutConfiguration.LOCATION_SERVICE_FACTORY_CLASS, DynamicLocationServiceFactory.class.getName()); flumeSpoutBaseConfig.addProperty(FlumeSpoutConfiguration.SERVICE_PROVIDER_SERIALIZATION_CLASS, KryoNetServiceProviderSerialization.class.getName()); flumeSpoutBaseConfig.addProperty(FlumeSpoutConfiguration.EVENT_RECEPTOR_FACTORY_CLASS, KryoNetEventReceptorFactory.class.getName()); // Final flume-spout configuration CombinedConfiguration flumeSpoutConfig = new CombinedConfiguration(); flumeSpoutConfig.addConfiguration(flumeSpoutBaseConfig); flumeSpoutConfig.addConfiguration(kryoConfig, "Kryo Configuration", KryoNetParameters.CONFIG_BASE_NAME); flumeSpoutConfig.addConfiguration(locationServiceConfig, "Location Service Configuration", DynamicLocationServiceFactory.CONFIG_BASE_NAME); config.addConfiguration(flumeSpoutConfig, SPOUT_CONFIG); testAll(); }