コード例 #1
0
  public static Configuration instance() {
    if (config == null) {
      try {
        // Default values build into war file, this is last prio used if no of the other sources
        // override this
        boolean allowexternal =
            Boolean.getBoolean(
                new PropertiesConfiguration(
                        ExtraConfiguration.class.getResource("/" + PROPERTY_FILENAME))
                    .getString(CONFIGALLOWEXTERNAL, "false"));

        config = new CompositeConfiguration();

        PropertiesConfiguration pc;
        // Only add these config sources if we allow external configuration
        if (allowexternal) {
          // Override with system properties, this is prio 1 if it exists (java -Dscep.test=foo)
          config.addConfiguration(new SystemConfiguration());
          log.info("Added system properties to configuration source (java -Dfoo.prop=bar).");

          // Override with file in "application server home directory"/conf, this is prio 2
          File f1 = new File("conf/" + PROPERTY_FILENAME);
          pc = new PropertiesConfiguration(f1);
          pc.setReloadingStrategy(new FileChangedReloadingStrategy());
          config.addConfiguration(pc);
          log.info("Added file to configuration source: " + f1.getAbsolutePath());

          // Override with file in "/etc/ejbca/conf/extra, this is prio 3
          File f2 = new File("/etc/ejbca/conf/extra/" + PROPERTY_FILENAME);
          pc = new PropertiesConfiguration(f2);
          pc.setReloadingStrategy(new FileChangedReloadingStrategy());
          config.addConfiguration(pc);
          log.info("Added file to configuration source: " + f2.getAbsolutePath());
        }

        // Default values build into war file, this is last prio used if no of the other sources
        // override this
        URL url = ExtraConfiguration.class.getResource("/" + PROPERTY_FILENAME);
        pc = new PropertiesConfiguration(url);
        config.addConfiguration(pc);
        log.info("Added url to configuration source: " + url);

        log.info("Allow external re-configuration: " + allowexternal);
        // Test
        log.debug("Using keystore path (1): " + config.getString(SCEPKEYSTOREPATH + ".1"));
        // log.debug("Using keystore pwd (1): "+config.getString(SCEPKEYSTOREPWD+".1"));
        // log.debug("Using authPwd: "+config.getString(SCEPAUTHPWD));
        log.debug("Using certificate profile: " + config.getString(SCEPCERTPROFILEKEY));
        log.debug("Using entity profile: " + config.getString(SCEPENTITYPROFILEKEY));
        log.debug("Using default CA: " + config.getString(SCEPDEFAULTCA));
        log.debug("Create or edit user: "******"Mapping for CN=Scep CA,O=EJBCA Sample,C=SE: "
                + config.getString("CN=Scep CA,O=EJBCA Sample,C=SE"));
      } catch (ConfigurationException e) {
        log.error("Error intializing ExtRA Configuration: ", e);
      }
    }
    return config;
  }
コード例 #2
0
ファイル: ConfigUtil.java プロジェクト: CLgithub/jbake
 public static CompositeConfiguration load(File source) throws ConfigurationException {
   CompositeConfiguration config = new CompositeConfiguration();
   config.setListDelimiter(',');
   File customConfigFile = new File(source, LEGACY_CONFIG_FILE);
   if (customConfigFile.exists()) {
     if (!LEGACY_CONFIG_FILE_WARNING_SHOWN) {
       LOGGER.warn(
           String.format(
               "You have defined a part of your JBake configuration in %s located at: %s",
               LEGACY_CONFIG_FILE, customConfigFile.getParent()));
       LOGGER.warn(
           String.format(
               "Usage of this file is being deprecated, please rename this file to: %s to remove this warning",
               CONFIG_FILE));
       LEGACY_CONFIG_FILE_WARNING_SHOWN = true;
     }
     config.addConfiguration(new PropertiesConfiguration(customConfigFile));
   }
   customConfigFile = new File(source, CONFIG_FILE);
   if (customConfigFile.exists()) {
     config.addConfiguration(new PropertiesConfiguration(customConfigFile));
   }
   config.addConfiguration(new PropertiesConfiguration(DEFAULT_CONFIG_FILE));
   return config;
 }
コード例 #3
0
  public boolean connectToMailBox() {
    try {
      Properties props = new Properties();
      props.setProperty("mail.imap.ssl.enable", "true"); // required for Gmail
      props.setProperty("mail.imap.auth.mechanisms", "XOAUTH2");
      props.setProperty("mail.store.protocol", config.getString("imap.protocol"));
      props.setProperty("mail.imaps.fetchsize", "" + fetchSize);
      props.setProperty("mail.imaps.timeout", "" + rTimeout);
      props.setProperty("mail.imaps.writetimeout", "" + rTimeout);
      props.setProperty("mail.imaps.connectiontimeout", "" + cTimeout);
      props.setProperty("mail.imaps.connectionpooltimeout", "" + cTimeout);

      Session session = Session.getInstance(props);
      mailbox = session.getStore(config.getString("imap.protocol"));
      mailbox.connect(
          config.getString("imap.host"),
          config.getString("imap.user"),
          config.getString("imap.access_token"));
      LOG.info("Connected to mailbox");
      return true;
    } catch (MessagingException e) {
      LOG.error("Connection failed", e);
      return false;
    }
  }
コード例 #4
0
  /** Dump out all existing properties to message logging info channel. */
  @Override
  public void dumpProperties() {

    Iterator<String> keyIterator = config.getKeys();

    while (keyIterator.hasNext()) {
      String key = keyIterator.next();

      Object o = config.getProperty(key);
      if (o != null) {
        // Check for multiple setting of properties
        if (o instanceof ArrayList) {
          logger.debug(
              key
                  + " is set multiple times the value used will be the first! This maybe ok if deliberately overridden");
        }
        if (o instanceof String) {
          // Calling getString method ensures value has any
          // processing
          // done by commons config applied - ie string
          // interpolation, etc.
          logger.debug(key + " = " + LocalProperties.get(key));
        } else {
          // Handle non-string objects, eg ArrayList's
          logger.debug(key + " = " + o.toString());
        }
      }
    }
  }
コード例 #5
0
  @Before
  public void setup() throws Exception, IOException, URISyntaxException {
    URL sourceUrl = this.getClass().getResource("/");

    sourceFolder = new File(sourceUrl.getFile());
    if (!sourceFolder.exists()) {
      throw new Exception("Cannot find sample data structure!");
    }

    destinationFolder = folder.getRoot();

    templateFolder = new File(sourceFolder, templateDir);
    if (!templateFolder.exists()) {
      throw new Exception("Cannot find template folder!");
    }

    config = ConfigUtil.load(new File(this.getClass().getResource("/").getFile()));
    Iterator<String> keys = config.getKeys();
    while (keys.hasNext()) {
      String key = keys.next();
      if (key.startsWith("template") && key.endsWith(".file")) {
        String old = (String) config.getProperty(key);
        config.setProperty(key, old.substring(0, old.length() - 4) + "." + templateExtension);
      }
    }
    Assert.assertEquals(".html", config.getString(ConfigUtil.Keys.OUTPUT_EXTENSION));
    db = DBUtil.createDataStore("memory", "documents" + System.currentTimeMillis());
  }
コード例 #6
0
  /** @param args */
  public static void main(String[] args) {
    // TODO Auto-generated method stub

    CompositeConfiguration config = new CompositeConfiguration();
    config.addConfiguration(new SystemConfiguration());
    try {
      config.addConfiguration(new PropertiesConfiguration("storage.properties"));
    } catch (ConfigurationException e) {
      // TODO Auto-generated catch block
      logger.error(e.getMessage());
    }

    String rootFolder = config.getString("bp.root.folder");

    String altpartyid = args[0];

    SqlSession sqlSession = RazorServer.openSession();
    try {
      if (StringUtils.isBlank(altpartyid)) {
        //				altpartyid = "231051"; //NextPax partner GA
        altpartyid = "179795";
      }

      Partner partner = sqlSession.getMapper(PartnerMapper.class).exists(altpartyid);
      if (partner == null) {
        throw new ServiceException(Error.party_id, altpartyid);
      }
      A_Handler handler = new A_Handler(partner);
      handler.downloadImages(rootFolder);
    } catch (Exception e) {
      logger.error(e.getMessage());
    }
  }
コード例 #7
0
 /** Use unicast if not on AWS (most of the cloud providers deny multicast traffic). */
 private static void addDefaultsForUnicast(Cluster cluster, CompositeConfiguration config) {
   List<String> hosts = Lists.newLinkedList();
   for (Cluster.Instance instance :
       cluster.getInstancesMatching(role(ElasticSearchHandler.ROLE))) {
     hosts.add(String.format("\"%s:9300\"", instance.getPrivateIp()));
   }
   config.addProperty("es.discovery.zen.ping.multicast.enabled", "false");
   config.addProperty("es.discovery.zen.ping.unicast.hosts", StringUtils.join(hosts, ","));
 }
コード例 #8
0
  /**
   * Remove all cached property information and reload system properties. User must reload any
   * required property data sources.
   */
  public void ResetProperties() {
    // clear out composite config and add a fresh system config into it
    config.clear();
    Configuration sysConfig = new SystemConfiguration();
    config.addConfiguration(sysConfig);

    // clear out the config map and put system into it
    configMap.clear();
    configMap.put("system", sysConfig);
  }
コード例 #9
0
 @Before
 public void setUp() throws Exception {
   CompositeConfiguration config = new CompositeConfiguration();
   config.addConfiguration(new PropertiesConfiguration("whirr-elasticsearch-test.properties"));
   if (System.getProperty("config") != null) {
     config.addConfiguration(new PropertiesConfiguration(System.getProperty("config")));
   }
   clusterSpec = ClusterSpec.withTemporaryKeys(config);
   controller = new ClusterController();
   cluster = controller.launchCluster(clusterSpec);
 }
コード例 #10
0
ファイル: ApacheTestFactory.java プロジェクト: irenical/jindy
 @Override
 public Config createConfig(String name) {
   try {
     final CompositeConfiguration config = new CompositeConfiguration();
     config.addConfiguration(new SystemConfiguration());
     config.addConfiguration(new PropertiesConfiguration("test.properties"));
     return new ApacheTestConfig(config);
   } catch (ConfigurationException e) {
     throw new RuntimeException(e);
   }
 }
コード例 #11
0
ファイル: ToolBoxUsing.java プロジェクト: jphuang/portal
 static {
   try {
     CompositeConfiguration settings = new CompositeConfiguration();
     settings.addConfiguration(new PropertiesConfiguration("system.properties"));
     Configuration serverConf = settings.subset("service");
     dbReadUrls = serverConf.getString("dbReadUrls");
     dbDriver = serverConf.getString("dbDriver");
     dbClient = new MoDBRW(dbReadUrls, dbDriver);
   } catch (Exception e) {
     logger.error("init database error", e);
   }
 }
コード例 #12
0
ファイル: PaginationTest.java プロジェクト: mohitkanwar/jbake
 @Before
 public void setup() throws Exception, IOException, URISyntaxException {
   config = ConfigUtil.load(new File(this.getClass().getResource("/").getFile()));
   Iterator<String> keys = config.getKeys();
   while (keys.hasNext()) {
     String key = keys.next();
     if (key.startsWith("template") && key.endsWith(".file")) {
       String old = (String) config.getProperty(key);
       config.setProperty(key, old.substring(0, old.length() - 4) + ".ftl");
     }
   }
   config.setProperty(ConfigurationKeys.PAGINATE_INDEX, true);
   config.setProperty(ConfigurationKeys.POSTS_PER_PAGE, 1);
   db = DataBaseUtil.createDataStore("memory", "documents" + System.currentTimeMillis());
 }
コード例 #13
0
  private void _addIncludedPropertiesSources(
      Configuration newConfiguration, CompositeConfiguration loadedCompositeConfiguration) {

    CompositeConfiguration tempCompositeConfiguration = new CompositeConfiguration();

    tempCompositeConfiguration.addConfiguration(_prefixedSystemConfiguration);
    tempCompositeConfiguration.addConfiguration(newConfiguration);
    tempCompositeConfiguration.addConfiguration(_systemConfiguration);
    tempCompositeConfiguration.addProperty(Conventions.COMPANY_ID_PROPERTY, _companyId);
    tempCompositeConfiguration.addProperty(Conventions.COMPONENT_NAME_PROPERTY, _componentName);

    String[] fileNames = tempCompositeConfiguration.getStringArray(Conventions.INCLUDE_PROPERTY);

    for (String fileName : fileNames) {
      URL url = null;

      try {
        url = _classLoader.getResource(fileName);
      } catch (RuntimeException re) {
        if (fileName.startsWith("file:/")) {
          throw re;
        }

        fileName = "file:/".concat(fileName);

        url = _classLoader.getResource(fileName);
      }

      _addPropertiesSource(fileName, url, loadedCompositeConfiguration);
    }
  }
コード例 #14
0
ファイル: Renderer.java プロジェクト: haumacher/jbake
  private Writer createWriter(File file) throws IOException {
    if (!file.exists()) {
      file.getParentFile().mkdirs();
      file.createNewFile();
    }

    return new OutputStreamWriter(
        new FileOutputStream(file), config.getString(ConfigUtil.Keys.RENDER_ENCODING));
  }
コード例 #15
0
ファイル: Renderer.java プロジェクト: haumacher/jbake
  /**
   * Render the supplied content to a file.
   *
   * @param content The content to renderDocument
   * @throws Exception
   */
  public void render(Map<String, Object> content) throws Exception {
    String docType = (String) content.get("type");
    String outputFilename =
        destination.getPath() + File.separatorChar + (String) content.get("uri");
    outputFilename = outputFilename.substring(0, outputFilename.lastIndexOf("."));

    // delete existing versions if they exist in case status has changed either way
    File draftFile =
        new File(
            outputFilename
                + config.getString(Keys.DRAFT_SUFFIX)
                + FileUtil.findExtension(config, docType));
    if (draftFile.exists()) {
      draftFile.delete();
    }

    File publishedFile = new File(outputFilename + FileUtil.findExtension(config, docType));
    if (publishedFile.exists()) {
      publishedFile.delete();
    }

    if (content.get("status").equals("draft")) {
      outputFilename = outputFilename + config.getString(Keys.DRAFT_SUFFIX);
    }

    File outputFile = new File(outputFilename + FileUtil.findExtension(config, docType));
    StringBuilder sb = new StringBuilder();
    sb.append("Rendering [").append(outputFile).append("]... ");
    Map<String, Object> model = new HashMap<String, Object>();
    model.put("content", content);
    model.put("renderer", renderingEngine);

    try {
      Writer out = createWriter(outputFile);
      renderingEngine.renderDocument(model, findTemplateName(docType), out);
      out.close();
      sb.append("done!");
      LOGGER.info(sb.toString());
    } catch (Exception e) {
      sb.append("failed!");
      LOGGER.error(sb.toString(), e);
      throw new Exception("Failed to render file. Cause: " + e.getMessage());
    }
  }
コード例 #16
0
  /**
   * Get a file pathname. Any backslashes found are converted to forward slashes. N.B. We know this
   * is a file pathname. Backslashes can cause problems with Java code expecting forward slashes. So
   * it *should* be safe to convert any backslashes to forward slashes. If any client code needs to
   * fetch properties with backslashes (eg to pass to native JNI code), then either convert the
   * result back to forward slashes, or just call getString instead.
   *
   * @see gda.configuration.properties.PropertiesConfig#getPath(java.lang.String, java.lang.String)
   */
  @Override
  public String getPath(String name, String defaultValue) {
    String value = config.getString(name, defaultValue);

    if (value != null) {
      value = value.replace('\\', '/');
    }

    return value;
  }
コード例 #17
0
ファイル: IndexRenderer.java プロジェクト: mohitkanwar/jbake
 @Override
 public int render(
     Renderer renderer,
     ContentStore db,
     File destination,
     File templatesPath,
     CompositeConfiguration config)
     throws RenderingException {
   if (config.getBoolean(ConfigurationKeys.RENDER_INDEX)) {
     try {
       renderer.renderIndex(config.getString(ConfigurationKeys.INDEX_FILE), db);
       return 1;
     } catch (Exception e) {
       throw new RenderingException(e);
     }
   } else {
     return 0;
   }
 }
コード例 #18
0
 public boolean getBoolean(String key, boolean defaultValue) {
   try {
     String value = config.getString(key);
     if (value == null) {
       return defaultValue;
     }
     return Boolean.valueOf(value.trim());
   } catch (RuntimeException e) {
     return defaultValue;
   }
 }
コード例 #19
0
  private Long _getReloadDelay(
      CompositeConfiguration loadedCompositeConfiguration, FileConfiguration newFileConfiguration) {

    Long delay = newFileConfiguration.getLong(Conventions.RELOAD_DELAY_PROPERTY, null);

    if (delay == null) {
      delay = loadedCompositeConfiguration.getLong(Conventions.RELOAD_DELAY_PROPERTY, null);
    }

    return delay;
  }
コード例 #20
0
 public int getInt(String key, int defaultValue) {
   try {
     String value = config.getString(key);
     if (value == null) {
       return defaultValue;
     }
     return Integer.parseInt(value.trim());
   } catch (NumberFormatException e) {
     return defaultValue;
   }
 }
コード例 #21
0
ファイル: InitTest.java プロジェクト: mohitkanwar/jbake
 @Before
 public void setup() throws Exception {
   URL sourceUrl = this.getClass().getResource("/");
   rootPath = new File(sourceUrl.getFile());
   if (!rootPath.exists()) {
     throw new Exception("Cannot find base path for test!");
   }
   config = ConfigUtil.load(rootPath);
   // override base template config option
   config.setProperty("example.project.freemarker", "test.zip");
 }
コード例 #22
0
  @Before
  public void setup() throws Exception {
    currentLocale = Locale.getDefault();
    Locale.setDefault(Locale.ENGLISH);

    ModelExtractorsDocumentTypeListener listener = new ModelExtractorsDocumentTypeListener();
    DocumentTypes.addListener(listener);

    URL sourceUrl = this.getClass().getResource("/");

    sourceFolder = new File(sourceUrl.getFile());
    if (!sourceFolder.exists()) {
      throw new Exception("Cannot find sample data structure!");
    }

    destinationFolder = folder.getRoot();

    templateFolder = new File(sourceFolder, templateDir);
    if (!templateFolder.exists()) {
      throw new Exception("Cannot find template folder!");
    }

    config = ConfigUtil.load(new File(this.getClass().getResource("/").getFile()));
    Iterator<String> keys = config.getKeys();
    while (keys.hasNext()) {
      String key = keys.next();
      if (key.startsWith("template") && key.endsWith(".file")) {
        String old = (String) config.getProperty(key);
        config.setProperty(key, old.substring(0, old.length() - 4) + "." + templateExtension);
      }
    }
    Assert.assertEquals(".html", config.getString(ConfigUtil.Keys.OUTPUT_EXTENSION));
    db = DBUtil.createDataStore("memory", "documents" + System.currentTimeMillis());

    crawler = new Crawler(db, sourceFolder, config);
    crawler.crawl(new File(sourceFolder.getPath() + File.separator + "content"));
    parser = new Parser(config, sourceFolder.getPath());
    renderer = new Renderer(db, destinationFolder, templateFolder, config);

    setupExpectedOutputStrings();
  }
コード例 #23
0
ファイル: Sprockets.java プロジェクト: danielwalker/sprockets
 static {
   sConfig.addConfiguration(new SystemConfiguration());
   /* on the file system, if user specified */
   String key = "sprockets.config.file";
   String config = System.getProperty(key);
   if (config != null) {
     File file = new File(config);
     if (file.isFile() && file.canRead()) {
       try {
         sConfig.addConfiguration(new XMLConfiguration(config));
       } catch (ConfigurationException e) {
         throw new RuntimeException("loading " + key + ": " + config, e);
       }
     } else {
       sLog.log(WARNING, "can''t read {0}: {1}", new String[] {key, config});
     }
   }
   /* in the class path; if not user specified then check for default */
   key = "sprockets.config.resource";
   config = System.getProperty(key);
   String defConfig = "sprockets.xml";
   URL url = Sprockets.class.getClassLoader().getResource(config != null ? config : defConfig);
   if (url != null) {
     try {
       sConfig.addConfiguration(new XMLConfiguration(url));
     } catch (ConfigurationException e) {
       throw new RuntimeException("loading " + key + ": " + url, e);
     }
   } else if (config != null) {
     sLog.log(WARNING, "can''t read {0}: {1}", new String[] {key, config});
   }
   /* in this package */
   url = Sprockets.class.getResource(defConfig);
   if (url != null) {
     try {
       sConfig.addConfiguration(new XMLConfiguration(url));
     } catch (ConfigurationException e) {
       throw new RuntimeException("loading sprockets default config: " + defConfig, e);
     }
   }
 }
コード例 #24
0
ファイル: ProjectConfigTest.java プロジェクト: jelycom/pss
 @Test
 public void testCompositeConfiguration() throws URISyntaxException {
   CompositeConfiguration configuration = new CompositeConfiguration();
   try {
     PropertiesConfiguration propertiesConfiguration =
         new PropertiesConfiguration("conf/pss-settings.properties");
     //
     //	propertiesConfiguration.setFileName("E:/study/jelyworkspace/jelypss/pss-core/target/test-classes/conf/pss-settings.properties");
     propertiesConfiguration.load(
         "E:/study/jelyworkspace/jelypss/pss-core/target/test-classes/conf/pss-settings.properties");
     configuration.addConfiguration(propertiesConfiguration);
     //			propertiesConfiguration.setProperty("haha", 1235);
     configuration.setProperty("asdf", "aaaaaaaaa");
     System.out.println(configuration.getInt("haha"));
     System.out.println(this.getClass().getClassLoader().getResource("").toURI().toString());
     System.out.println(this.getClass().getClassLoader().getResource("").toString());
     propertiesConfiguration.save();
   } catch (ConfigurationException e) {
     e.printStackTrace();
   }
 }
コード例 #25
0
ファイル: PolicyService.java プロジェクト: Kiichi77/FromSVN
 /**
  * 判断是否超出策略阀值
  *
  * @param policyType 1:系统功耗,2:CPU功耗,3:内存功耗,4:进风口温度
  * @param policyLimt 阀值
  * @return
  * @author zhangjh 新增日期:2012-9-5
  * @since ipmi_task
  */
 private boolean overPolicyLimit(SerInfo ser, int policyType, int policyLimt) {
   int current = 0;
   if (policyType == 4) {
     CompositeConfiguration conf = Config.getConfig();
     GobblerServer gobblerServer =
         new GobblerServer(
             conf.getString("gobbler.host"),
             conf.getString("gobbler.user"),
             conf.getString("gobbler.passwd"));
     current = ipmiSensor.getTempSensorReading(ser, gobblerServer, Parameter.InletTemp);
   } else {
     PowerReading p = ipmiPower.getPlatformPowerReading(ser, policyType2Domain(policyType));
     current = p.getCurrent();
   }
   if (current >= policyLimt) {
     logger.info(
         "4.["
             + ser.getHost()
             + "]的当前"
             + policyType2Name(policyType)
             + "为<"
             + current
             + ">,阀值为<"
             + policyLimt
             + ">,已超过阀值.");
     return true;
   } else {
     logger.info(
         "4.["
             + ser.getHost()
             + "]的当前"
             + policyType2Name(policyType)
             + "为<"
             + current
             + ">,阀值为<"
             + policyLimt
             + ">,未超过阀值,退出.");
     return false;
   }
 }
コード例 #26
0
  /** Build a configuration by adding the expected defaults */
  public static Configuration buildConfig(ClusterSpec spec, Cluster cluster) {
    CompositeConfiguration config = new CompositeConfiguration();

    config.addConfiguration(spec.getConfiguration());
    try {
      config.addConfiguration(
          new PropertiesConfiguration("whirr-elasticsearch-default.properties"));
    } catch (ConfigurationException e) {
      LOG.error("Configuration error", e); // this should never happen
    }

    if ("aws-ec2".equals(spec.getProvider()) || "ec2".equals(spec.getProvider())) {
      addDefaultsForEC2(spec, config);
    } else {
      addDefaultsForUnicast(cluster, config);
    }
    if (!config.containsKey("es.cluster.name")) {
      config.addProperty("es.cluster.name", spec.getClusterName());
    }

    return config;
  }
コード例 #27
0
 /** Use the native EC2 discovery module on AWS */
 private static void addDefaultsForEC2(ClusterSpec spec, CompositeConfiguration config) {
   config.addProperty("es.discovery.type", "ec2");
   if (!config.containsKey("es.cloud.aws.access_key")) {
     config.addProperty("es.cloud.aws.access_key", spec.getIdentity());
   }
   if (!config.containsKey("es.cloud.aws.secret_key")) {
     config.addProperty("es.cloud.aws.secret_key", spec.getCredential());
   }
   if (!config.getList("es.plugins", Lists.newLinkedList()).contains("cloud-aws")) {
     config.addProperty("es.plugins", "cloud-aws");
   }
 }
コード例 #28
0
  /**
   * Constructor for JakartaPropertiesConfig objects. Creates a new composite configuration and adds
   * a system configuration to it.
   */
  public JakartaPropertiesConfig() {
    // create global composite to store all loaded property config data
    config = new CompositeConfiguration();

    // create a system properties configuration - grabs all system
    // properties.
    Configuration sysConfig = new SystemConfiguration();
    config.addConfiguration(sysConfig);

    // create map to store individual configs
    configMap = new HashMap<String, Configuration>();

    // put system properties in the map
    configMap.put("system", sysConfig);
  }
コード例 #29
0
  private Configuration _addPropertiesSource(
      String sourceName, URL url, CompositeConfiguration loadedCompositeConfiguration) {

    try {
      Configuration newConfiguration = null;

      if (DatasourceURL.isDatasource(sourceName)) {
        newConfiguration = _addDatasourceProperties(sourceName);
      } else if (JndiURL.isJndi(sourceName)) {
        newConfiguration = _addJNDIProperties(sourceName);
      } else if (url != null) {
        newConfiguration = _addURLProperties(url, loadedCompositeConfiguration);
      } else {
        newConfiguration = _addFileProperties(sourceName, loadedCompositeConfiguration);
      }

      if (newConfiguration == null) {
        return newConfiguration;
      }

      loadedCompositeConfiguration.addConfiguration(newConfiguration);

      super.addConfiguration(newConfiguration);

      if (newConfiguration instanceof AbstractFileConfiguration) {
        AbstractFileConfiguration abstractFileConfiguration =
            (AbstractFileConfiguration) newConfiguration;

        URL abstractFileConfigurationURL = abstractFileConfiguration.getURL();

        _loadedSources.add(abstractFileConfigurationURL.toString());
      } else {
        _loadedSources.add(sourceName);
      }

      return newConfiguration;
    } catch (Exception e) {
      if (_log.isDebugEnabled()) {
        _log.debug("Configuration source " + sourceName + " ignored: " + e.getMessage());
      }

      return null;
    }
  }
コード例 #30
0
ファイル: InitTest.java プロジェクト: mohitkanwar/jbake
 @Test
 public void initFailDestinationContainsContent() throws IOException {
   Init init = new Init(config);
   File initPath = folder.newFolder("init");
   File contentFolder =
       new File(
           initPath.getPath()
               + File.separatorChar
               + config.getString(ConfigurationKeys.CONTENT_FOLDER));
   contentFolder.mkdir();
   try {
     init.run(initPath, rootPath, "freemarker");
     fail("Shouldn't be able to initialise folder with content folder within it!");
   } catch (Exception e) {
     e.printStackTrace();
   }
   File testFile = new File(initPath, "testfile.txt");
   assertThat(testFile).doesNotExist();
 }