List of usage examples for org.apache.commons.configuration2.builder FileBasedConfigurationBuilder FileBasedConfigurationBuilder
public FileBasedConfigurationBuilder(final Class<? extends T> resCls)
From source file:com.haulmont.mp2xls.writer.LocalizationBatchFileWriter.java
/** * Writing all changed properties to the passed file. Using apache commons-configuration to write properties, * because it preserves the original file format unlike the java.util.Properties class. * * @param messagesFile - messages file//from w ww . j av a 2 s. co m * @param diffs - differences */ protected void mergeLocalizationProperties(File messagesFile, Collection<LocalizationLog> diffs) { if (diffs == null || diffs.isEmpty()) return; try { Parameters parameters = new Parameters(); FileBasedConfigurationBuilder<FileBasedConfiguration> builder = new FileBasedConfigurationBuilder<FileBasedConfiguration>( PropertiesConfiguration.class) .configure(parameters.properties().setFile(messagesFile).setEncoding("UTF-8") .setIOFactory(new MessagePropertiesIOFactory()) .setLayout(new PropertiesConfigurationLayout())); Configuration configuration = builder.getConfiguration(); for (LocalizationLog diff : diffs) { if (LocalizationLog.Type.CHANGED.equals(diff.getType())) { configuration.setProperty(diff.getParameterName(), diff.getExcelValue()); } } builder.save(); } catch (Exception e) { throw new RuntimeException("Exception during properties file merging", e); } }
From source file:com.rodaxsoft.mailgun.message.tools.MailgunSender.java
/** * Sets the default from email address or <code>sDefaultFromEmail</code> from the * properties file if no <code>-f</code> option exists. * @param cmd Command line arguments//from w w w .j ava 2 s.c o m */ private static void setDefaultFromEmail(CommandLine cmd) throws ContextedException { if (!cmd.hasOption(FROM_EMAIL_ADDRESS_OPT)) { Parameters params = new Parameters(); FileBasedConfigurationBuilder<FileBasedConfiguration> builder; final Class<PropertiesConfiguration> propConfigClass = PropertiesConfiguration.class; builder = new FileBasedConfigurationBuilder<FileBasedConfiguration>(propConfigClass); builder.configure(params.properties().setFileName("config/mailgun-sender.properties")); try { FileBasedConfiguration config = builder.getConfiguration(); sDefaultFromEmail = config.getString(DEFAULT_FROM_EMAIL_PROP_KEY); if (null == sDefaultFromEmail) { throw new ContextedException("Missing " + DEFAULT_FROM_EMAIL_PROP_KEY + " key") .addContextValue(DEFAULT_FROM_EMAIL_PROP_KEY, sDefaultFromEmail).addContextValue("help", "Must set from email address with option -f or in the `mailgun-sender.properties` file"); } LOG.info("Configured mailgun-sender.properties"); } catch (ConfigurationException e) { throw new ContextedException("Error loading `mailgun-sender.properties`", e); } } }
From source file:com.gs.obevo.api.factory.PlatformConfigReader.java
private HierarchicalConfiguration<ImmutableNode> loadPropertiesFromUrl(FileObject file) { try {//from w w w . ja v a2 s . co m return new FileBasedConfigurationBuilder<>(FixedYAMLConfiguration.class) .configure(new Parameters().hierarchical().setURL(file.getURLDa())).getConfiguration(); } catch (ConfigurationException e) { throw new DeployerRuntimeException(e); } }
From source file:at.tfr.securefs.Configuration.java
private void loadSecureFsProperties(boolean initial) { try {//ww w. j av a 2 s . c o m URL url = Thread.currentThread().getContextClassLoader().getResource(SECUREFS_SERVER_PROPERTIES); PropertiesBuilderParameters parameters = new Parameters().properties().setURL(url); FileBasedConfigurationBuilder<FileBasedConfiguration> builder = new FileBasedConfigurationBuilder<FileBasedConfiguration>( PropertiesConfiguration.class).configure(parameters); secConfig = builder.getConfiguration(); if (initial) { log.info("loaded from: " + url); } else { log.debug("reloaded from: " + url); } } catch (Throwable e) { log.warn("failure to read Properties: " + SECUREFS_SERVER_PROPERTIES, e); } }
From source file:com.vmware.loginsightapi.Configuration.java
/** * Builds the Configuration object from the properties file (apache commons * properties file format). <br>/* ww w . ja va 2 s. com*/ * The values provided in the config file will be overwritten environment * variables (if present) * * List of the properties <br> * loginsight.host = host name <br> * loginsight.port = port number <br> * loginsight.user = User name <br> * loginsight.password = password <br> * loginsight.ingestion.agentId = agentId <br> * loginsight.connection.scheme = http protocol scheme <br> * loginsight.ingestion.port = Ingestion port number <br> * * @param configFileName * Name of the config file to read * @return Newly created Configuration object */ public static Configuration buildFromConfig(String configFileName) { try { List<FileLocationStrategy> subs = Arrays.asList(new ProvidedURLLocationStrategy(), new FileSystemLocationStrategy(), new ClasspathLocationStrategy()); FileLocationStrategy strategy = new CombinedLocationStrategy(subs); FileBasedConfigurationBuilder<PropertiesConfiguration> builder = new FileBasedConfigurationBuilder<PropertiesConfiguration>( PropertiesConfiguration.class).configure( new Parameters().fileBased().setLocationStrategy(strategy).setFileName(configFileName)); PropertiesConfiguration propConfig = builder.getConfiguration(); Map<String, String> propMap = new HashMap<String, String>(); Iterator<String> keys = propConfig.getKeys(); keys.forEachRemaining(key -> { logger.info(key + ":" + propConfig.getString(key)); propMap.put(key, propConfig.getString(key)); }); Configuration config = Configuration.buildConfig(propMap); config.loadFromEnv(); return config; } catch (ConfigurationException e1) { throw new RuntimeException("Unable to load config", e1); } }
From source file:com.streamsets.datacollector.cli.sch.SchAdmin.java
/** * Update dpm.properties file with new configuration. */// w ww .j a v a 2 s.c om private static void updateDpmProperties(Context context, String dpmBaseURL, List<String> labels, boolean enableSch) { if (context.skipUpdatingDpmProperties) { return; } try { FileBasedConfigurationBuilder<PropertiesConfiguration> builder = new FileBasedConfigurationBuilder<>( PropertiesConfiguration.class) .configure(new Parameters().properties() .setFileName(context.runtimeInfo.getConfigDir() + "/dpm.properties") .setThrowExceptionOnMissing(true) .setListDelimiterHandler(new DefaultListDelimiterHandler(';')) .setIncludesAllowed(false)); PropertiesConfiguration config = null; config = builder.getConfiguration(); config.setProperty(RemoteSSOService.DPM_ENABLED, Boolean.toString(enableSch)); config.setProperty(RemoteSSOService.DPM_BASE_URL_CONFIG, dpmBaseURL); config.setProperty(RemoteSSOService.SECURITY_SERVICE_APP_AUTH_TOKEN_CONFIG, APP_TOKEN_FILE_PROP_VAL); if (labels != null && labels.size() > 0) { config.setProperty(RemoteEventHandlerTask.REMOTE_JOB_LABELS, StringUtils.join(labels, ',')); } else { config.setProperty(RemoteEventHandlerTask.REMOTE_JOB_LABELS, ""); } builder.save(); } catch (ConfigurationException e) { throw new RuntimeException(Utils.format("Updating dpm.properties file failed: {}", e.getMessage()), e); } }
From source file:com.netcore.hsmart.AppConstants.java
/** * This will load the code constants from application_status_codes.xml and * will push in redis key name: xml_node key value: xml node object *///from w w w . j a v a2s . c o m private static void loadStatusCodeConfig() { final Logger logger = LoggerFactory.getLogger(AppConstants.class); Parameters params = new Parameters(); FileBasedConfigurationBuilder<XMLConfiguration> builder = new FileBasedConfigurationBuilder<>( XMLConfiguration.class) .configure(params.xml().setBasePath(System.getProperty("hsmart-config-path")) .setFileName("application_status_codes.xml") .setExpressionEngine(new XPathExpressionEngine())); try { AppConstants.statusCodeConfig = builder.getConfiguration(); logger.info(AppConstants.getApplicationCodeMessage("HSMART_GEN_1007")); // AppConstants.GEN_STATUS_CODES = // AppConstants.statusCodeConfig.getList("general/data"); // for (Object codes : AppConstants.GEN_STATUS_CODES) { // System.out.println(codes); // } // AppConstants.APP_ERR_CODES = // AppConstants.statusCodeConfig.getList("general/internal_app_error_codes/data"); // AppConstants.DLR_STATUS_CODES = // AppConstants.statusCodeConfig.getList("general/dlr_status_codes/data"); } catch (ConfigurationException cex) { // loading of the configuration file failed } }
From source file:com.github.technosf.posterer.modules.commons.config.CommonsConfiguratorPropertiesImpl.java
/** * Creates a config builder for the given file * <p>/*from www. j a v a 2s . c o m*/ * The builder handles I/O tasks * * @param file * the config file * @return the builder * @throws IOException */ @SuppressWarnings("null") private static FileBasedConfigurationBuilder<XMLConfiguration> createBuilder(File file) throws IOException { XMLBuilderParameters xmlParams = PARAMS.xml().setThrowExceptionOnMissing(true).setValidating(false) .setEncoding("UTF-8").setFileName(file.getCanonicalPath()) .setExpressionEngine(new XPathExpressionEngine()); return new FileBasedConfigurationBuilder<XMLConfiguration>(XMLConfiguration.class).configure(xmlParams); }
From source file:Executable.LinkImputeR.java
private static XMLConfiguration convert(File ini) throws INIException, VCFInputException { FileBasedConfigurationBuilder<INIConfiguration> inibuilder = new FileBasedConfigurationBuilder<>( INIConfiguration.class).configure(new Parameters().fileBased().setFile(ini)); INIConfiguration config;/* w w w . j a v a 2s .c o m*/ try { config = inibuilder.getConfiguration(); } catch (ConfigurationException ex) { throw new INIException( "There's a problem reading the ini file. " + "Does it exist? Is it formatted correctly?", ex); } List<ImmutableNode> xml = new ArrayList<>(); xml.add(new ImmutableNode.Builder().name("mode").value("accuracy").create()); String[] sdepths = config.getString("Global.depth").split(","); int[] depths = new int[sdepths.length]; for (int i = 0; i < sdepths.length; i++) { try { depths[i] = Integer.parseInt(sdepths[i]); } catch (NumberFormatException ex) { throw new INIException("Values for the depth option must be integers"); } if (depths[i] <= 0) { throw new INIException("Values for the depth option must be positive"); } } int maxDepth = NumberUtils.max(depths); int minDepth = NumberUtils.min(depths); double error; try { error = config.getDouble("Global.error", 0.01); } catch (ConversionException ex) { throw new INIException("Values for the error option must be a number"); } if ((error <= 0.0) || (error > 1.0)) { throw new INIException("Values for error must be between 0 and 1"); } File input = new File(config.getString("Input.filename")); List<PositionFilter> inputfilters = new ArrayList<>(); int numSnps = VCF.numberPositionsFromFile(input); for (HierarchicalConfiguration<ImmutableNode> i : config.childConfigurationsAt("InputFilters")) { switch (i.getRootElementName()) { //ADD FILTERS case "maf": double maf; try { maf = i.getDouble(null); } catch (ConversionException ex) { throw new INIException("Parameter for the MAF Filter must be a number"); } if ((maf <= 0) | (maf >= 0.5)) { throw new INIException("Parameter for the MAF filter must be between 0 and 0.5"); } inputfilters.add(new MAFFilter(maf, 8, 100, error)); break; case "hw": double sig; try { sig = i.getDouble(null); } catch (ConversionException ex) { throw new INIException("Parameter for the HW Filter must be a number"); } if ((sig <= 0) | (sig >= 1.0)) { throw new INIException("Parameter for the HWS filter must be between 0 and 1"); } inputfilters.add(new ParalogHWFilter(sig / numSnps, error)); break; case "positionmissing": double missing; try { missing = i.getDouble(null); } catch (ConversionException ex) { throw new INIException("Parameter for the Position Missing filter must be a number"); } if ((missing <= 0) | (missing >= 1.0)) { throw new INIException("Parameter for the Position Missing filter must be between 0 and 1"); } inputfilters.add(new PositionMissing(i.getDouble(null), minDepth)); break; } } String saveString = config.getString("Input.save", null); File save = (saveString == null) ? null : new File(saveString); String readsformat = config.getString("Input.readsformat", null); if ((readsformat != null) && (readsformat.split(",").length > 2)) { throw new INIException("readsformat must be either a single format or two" + "formats comma separated (LinkImputeR currently only works on" + "biallelic SNPs)"); } int maxInDepth; try { maxInDepth = config.getInt("Input.maxdepth", 100); } catch (ConversionException ex) { throw new INIException("Parameter values for the maxdepth option must be an integer."); } Input o = new Input(input, inputfilters, save, maxInDepth, readsformat); xml.add(o.getConfig()); String sampleMethod = config.getString("Accuracy.maskmethod", "all"); Method sm; switch (sampleMethod) { case "bysnp": sm = Method.BYSNP; break; case "bysample": sm = Method.BYSAMPLE; break; case "all": sm = Method.ALL; break; default: throw new INIException("maskmethod must be either \"bysnp\", \"bysample\" or \"all\"."); } int numberMasked; try { numberMasked = config.getInt("Accuracy.numbermasked", 10000); } catch (ConversionException ex) { throw new INIException("Parameter values for the numbermasked option must be an integer."); } int minMaskDepth; try { minMaskDepth = config.getInt("Accuracy.mindepth", 30); } catch (ConversionException ex) { throw new INIException("Parameter values for the maxdepth option must be an integer"); } DepthMaskFactory dmf = new DepthMaskFactory(numberMasked, minMaskDepth, maxDepth, sm); xml.add(dmf.getConfig()); String accuracyMethod = config.getString("Accuracy.accuracymethod", "correct"); AccuracyMethod am; switch (accuracyMethod) { case "correlation": am = AccuracyMethod.CORRELATION; break; case "correct": am = AccuracyMethod.CORRECT; break; default: throw new INIException("accuractymethod must be either \"correlation\" or \"correct\"."); } Caller caller = new BinomialCaller(error); String statsRoot = config.getString("Stats.root"); boolean partial; try { partial = config.getBoolean("Stats.partial", false); } catch (ConversionException ex) { throw new INIException("Stats partial must be convertible to a boolean. Try \"yes\" or \"no\"."); } boolean eachMasked; try { eachMasked = config.getBoolean("Stats.eachmasked", false); } catch (ConversionException ex) { throw new INIException("Stats eachmasked must be convertible to a boolean. Try \"yes\" or \"no\"."); } int casenum = 1; for (int depth : depths) { List<List<VCFFilter>> cases = new ArrayList<>(); cases.add(new ArrayList<>()); for (HierarchicalConfiguration<ImmutableNode> i : config.childConfigurationsAt("CaseFilters")) { List<List<VCFFilter>> newcases = new ArrayList<>(); String[] options = i.getString(null).split(","); for (String opt : options) { VCFFilter f; switch (i.getRootElementName()) { case "maf": double maf; try { maf = Double.parseDouble(opt); } catch (NumberFormatException ex) { throw new INIException("Parameter for the MAF Filter must be a number"); } if ((maf <= 0) | (maf >= 0.5)) { throw new INIException("Parameter for the MAF filter must be between 0 and 0.5"); } f = new MAFFilter(maf, 8, 100, error); for (List<VCFFilter> c : cases) { List<VCFFilter> nc = new ArrayList<>(c); nc.add(f); newcases.add(nc); } break; case "missing": double missing; try { missing = Double.parseDouble(opt); } catch (NumberFormatException ex) { throw new INIException("Parameter for the Missing filter must be a number"); } if ((missing <= 0) | (missing >= 1.0)) { throw new INIException("Parameter for the Missing filter must be between 0 and 1"); } VCFFilter fp = new PositionMissing(missing, depth); VCFFilter fs = new SampleMissing(missing, depth); for (List<VCFFilter> c : cases) { List<VCFFilter> nc = new ArrayList<>(c); nc.add(fp); nc.add(fs); newcases.add(nc); } break; case "samplemissing": double smissing; try { smissing = Double.parseDouble(opt); } catch (NumberFormatException ex) { throw new INIException("Parameter for the Missing filter must be a number"); } if ((smissing <= 0) | (smissing >= 1.0)) { throw new INIException("Parameter for the Missing filter must be between 0 and 1"); } f = new SampleMissing(smissing, depth); for (List<VCFFilter> c : cases) { List<VCFFilter> nc = new ArrayList<>(c); nc.add(f); newcases.add(nc); } break; case "positionmissing": double pmissing; try { pmissing = Double.parseDouble(opt); } catch (NumberFormatException ex) { throw new INIException("Parameter for the Missing filter must be a number"); } if ((pmissing <= 0) | (pmissing >= 1.0)) { throw new INIException("Parameter for the Missing filter must be between 0 and 1"); } f = new PositionMissing(pmissing, depth); for (List<VCFFilter> c : cases) { List<VCFFilter> nc = new ArrayList<>(c); nc.add(f); newcases.add(nc); } break; //NEED TO THINK ABOUT WHAT TO DO WITH SIGNIFICANCE! //POSSIBLY CHANGES IN CASE???? /*case "hw": f = new ParalogHWFilter(Double.parseDouble(opt),error); for (List<VCFFilter> c: cases) { List<VCFFilter> nc = new ArrayList<>(c); nc.add(f); newcases.add(nc); } break; */ } } cases = newcases; } ImputationOption imputer = new ImputationOption(new KnniLDProbOptimizedCalls(depth, am)); CombinerOption combiner = new CombinerOption(new MaxDepthCombinerOptimizedCalls(depth, am)); for (List<VCFFilter> filters : cases) { String name = "Case " + casenum; File prettyStats = null; File genoStats = null; File depthStats = null; File dgStats = null; File eachMaskedFile = null; switch (config.getString("Stats.level", "sum")) { case "sum": break; case "pretty": prettyStats = new File(statsRoot + "pretty_" + casenum + ".dat"); break; case "table": prettyStats = new File(statsRoot + "pretty_" + casenum + ".dat"); genoStats = new File(statsRoot + "geno_" + casenum + ".dat"); depthStats = new File(statsRoot + "depth_" + casenum + ".dat"); dgStats = new File(statsRoot + "dg_" + casenum + ".dat"); break; default: throw new INIException("Stats level must be either \"sum\", \"pretty\" or \"table\"."); } if (eachMasked) { eachMaskedFile = new File(statsRoot + "each_" + casenum + ".dat"); } PrintStats print = new PrintStats(prettyStats, genoStats, depthStats, dgStats, eachMaskedFile, partial); Case cas = new Case(name, filters, caller, imputer, combiner, print, "Depth(" + depth + ")"); xml.add(cas.getConfig()); casenum++; } } File sum = new File(statsRoot + "sum.dat"); File control = new File(config.getString("Output.control")); File table; if (config.getString("Stats.level").equals("table")) { table = new File(statsRoot + "table.dat"); } else { table = null; } Output out = new Output(sum, table, control, partial); xml.add(out.getConfig()); File log; String ls = config.getString("Log.file", null); if (ls != null) { log = new File(ls); } else { log = null; } Level level; switch (config.getString("Log.level", "critical").toLowerCase()) { case "brief": level = Log.Level.BRIEF; break; case "detail": level = Log.Level.DETAIL; break; case "debug": level = Log.Level.DEBUG; break; case "critical": level = Log.Level.CRITICAL; break; default: throw new INIException("log level must be either \"critical\", \"brief\", \"details\" or \"debug\"."); } xml.add(Log.getConfig(level, log)); BasicConfigurationBuilder<ExtendedXMLConfiguration> xmlbuilder = new BasicConfigurationBuilder<>( ExtendedXMLConfiguration.class).configure(new Parameters().xml()); ExtendedXMLConfiguration c; try { c = xmlbuilder.getConfiguration(); } catch (ConfigurationException ex) { throw new ProgrammerException(ex); } c.setRootElementName("linkimputer"); c.addNodes(null, xml); return c; }
From source file:com.gs.obevo.db.api.factory.DbEnvironmentXmlEnricherTest.java
@Test public void yamlTest() throws Exception { ImmutableHierarchicalConfiguration configuration = new FileBasedConfigurationBuilder<>( FixedYAMLConfiguration.class) .configure(new Parameters().hierarchical().setFile( new File("./src/test/resources/DbEnvironmentXmlEnricher/system-config.yaml")) // .setFile(new File("./src/test/resources/DbEnvironmentXmlEnricher/system-config.xml")) ).getConfiguration(); System.out.println(configuration); }