/** implemented. */
  public void test_propertyNames() {
    th.checkPoint("propertyNames()java.util.Enumeration");
    Properties p = new Properties();
    try {
      p.load(bin);
    } catch (Exception e) {
    }

    Enumeration en = p.propertyNames();
    Enumeration ek = p.keys();
    boolean ok = true;
    Vector v = new Vector();
    Enumeration ek2 = p.keys();
    while (ek2.hasMoreElements()) {
      v.add(ek2.nextElement());
    }
    while (ek.hasMoreElements() && en.hasMoreElements()) {
      ek.nextElement();
      Object next = en.nextElement();
      if (!v.contains(next)) {
        ok = false;
        th.debug(next + " not in " + v);
      }
    }
    th.check(ok, "all elements are the same");
    th.check(
        !ek.hasMoreElements() && !en.hasMoreElements(), "make sure both enumerations are empty");
    p = new Properties(defProps);
    resetStreams();
    try {
      p.load(bin);
    } catch (Exception e) {
    }
    v.add("Smart");
    v.add("animal");
    en = p.propertyNames();
    ok = true;
    Object o;
    while (en.hasMoreElements()) {
      o = en.nextElement();
      if (v.contains(o)) v.removeElement(o);
      else {
        ok = false;
        th.debug("got extra element: " + o);
      }
    }
    th.check(ok, "see if no double were generated");
    th.check(v.isEmpty(), "check if all names were mentioned -- got:" + v);
  }
  @TestTargetNew(
      level = TestLevel.COMPLETE,
      notes = "",
      method = "storeToXML",
      args = {java.io.OutputStream.class, java.lang.String.class})
  public void test_storeToXMLLjava_io_OutputStreamLjava_lang_String() throws IOException {
    Properties myProps = new Properties();
    myProps.put("Property A", "value 1");
    myProps.put("Property B", "value 2");
    myProps.put("Property C", "value 3");

    Properties myProps2 = new Properties();
    ByteArrayOutputStream out = new ByteArrayOutputStream();
    myProps.storeToXML(out, "A Header");
    out.close();

    ByteArrayInputStream in = new ByteArrayInputStream(out.toByteArray());
    myProps2.loadFromXML(in);
    in.close();

    Enumeration e = myProps.propertyNames();
    while (e.hasMoreElements()) {
      String nextKey = (String) e.nextElement();
      assertTrue(
          "Stored property list not equal to original",
          myProps2.getProperty(nextKey).equals(myProps.getProperty(nextKey)));
    }

    try {
      myProps.storeToXML(null, "String");
      fail("NullPointerException expected");
    } catch (NullPointerException ee) {
      // expected
    }
  }
  public static Map<String, String> readProperties(InputStream inputStream) {
    Map<String, String> propertiesMap = null;
    try {
      propertiesMap = new LinkedHashMap<String, String>();

      Properties properties = new Properties();
      properties.load(inputStream);

      Enumeration<?> enumeration = properties.propertyNames();
      while (enumeration.hasMoreElements()) {
        String key = (String) enumeration.nextElement();
        String value = (String) properties.get(key);
        propertiesMap.put(key, value);
      }
    } catch (FileNotFoundException e) {
      e.printStackTrace();
    } catch (IOException e) {
      e.printStackTrace();
    } finally {
      if (inputStream != null) {
        try {
          inputStream.close();
        } catch (IOException e) {
          e.printStackTrace();
        }
      }
    }
    return propertiesMap;
  }
  @Inject
  public MicromailerVelocityComponent(Logger logger) {
    this.logger = logger;

    engine = new VelocityEngine();

    // avoid "unable to find resource 'VM_global_library.vm' in any resource loader."
    engine.setProperty("velocimacro.library", "");

    engine.setProperty(RuntimeConstants.RUNTIME_LOG_LOGSYSTEM, this);

    if (properties != null) {
      for (Enumeration e = properties.propertyNames(); e.hasMoreElements(); ) {
        String key = e.nextElement().toString();

        String value = properties.getProperty(key);

        engine.setProperty(key, value);

        logger.debug("Setting property: " + key + " => '" + value + "'.");
      }
    }

    try {
      engine.init();
    } catch (Exception e) {
      logger.error("Cannot start the velocity engine: ", e);
    }
  }
 public static void readStringPropertyInfo() {
   String proInfo = "性别=性别:男=男性,女=女性\n民族=民族:汉=汉族";
   HashMap<String, String> domainMap = new HashMap<String, String>();
   HashMap<String, HashMap<String, String>> dictMap =
       new HashMap<String, HashMap<String, String>>();
   Properties ppt = new Properties();
   BufferedReader bf;
   try {
     bf =
         new BufferedReader(
             new InputStreamReader(new ByteArrayInputStream(proInfo.getBytes()), "utf-8"));
     ppt.load(bf);
     for (Enumeration<?> names = ppt.propertyNames(); names.hasMoreElements(); ) {
       String name = names.nextElement().toString();
       String val = ppt.getProperty(name);
       String[] keyAndVal = val.split(":");
       domainMap.put(name, keyAndVal[0]);
       String[] valMaps = keyAndVal[1].split(",");
       if (dictMap.get(name) == null) {
         dictMap.put(name, new HashMap<String, String>());
       }
       HashMap<String, String> tempMap = dictMap.get(name);
       for (int i = 0; i < valMaps.length; i++) {
         String[] valMap = valMaps[i].split("=");
         tempMap.put(valMap[0], valMap[1]);
       }
     }
   } catch (IOException e) {
     e.printStackTrace();
   }
 }
  /**
   * Parses the specified properties as a mapping from IANA registered SASL mechanism names to
   * implementing client factories. If the client factories cannot be instantiated or do not
   * implement SaslClientFactory then the properties refering to them are ignored.
   *
   * @param props The properties to scan for Sasl client factory implementations.
   * @return A map from SASL mechanism names to implementing client factory classes.
   * @todo Why tree map here? Do really want mechanisms in alphabetical order? Seems more likely
   *     that the declared order of the mechanisms is intended to be preserved, so that they are
   *     registered in the declared order of preference. Consider LinkedHashMap instead.
   */
  private static Map<String, Class<? extends SaslClientFactory>> parseProperties(Properties props) {
    Enumeration e = props.propertyNames();

    TreeMap<String, Class<? extends SaslClientFactory>> factoriesToRegister =
        new TreeMap<String, Class<? extends SaslClientFactory>>();

    while (e.hasMoreElements()) {
      String mechanism = (String) e.nextElement();
      String className = props.getProperty(mechanism);
      try {
        Class<?> clazz = Class.forName(className);
        if (!(SaslClientFactory.class.isAssignableFrom(clazz))) {
          _logger.error(
              "Class " + clazz + " does not implement " + SaslClientFactory.class + " - skipping");

          continue;
        }

        _logger.debug("Found class " + clazz.getName() + " for mechanism " + mechanism);
        factoriesToRegister.put(mechanism, (Class<? extends SaslClientFactory>) clazz);
      } catch (Exception ex) {
        _logger.error("Error instantiating SaslClientFactory class " + className + " - skipping");
      }
    }

    return factoriesToRegister;
  }
Beispiel #7
0
  public static void load(Properties properties, String s) throws IOException {

    if (Validator.isNotNull(s)) {
      s = UnicodeFormatter.toString(s);

      s = StringUtil.replace(s, "\\u003d", "=");
      s = StringUtil.replace(s, "\\u000a", "\n");
      s = StringUtil.replace(s, "\\u0021", "!");
      s = StringUtil.replace(s, "\\u0023", "#");
      s = StringUtil.replace(s, "\\u0020", " ");
      s = StringUtil.replace(s, "\\u005c", "\\");

      properties.load(new UnsyncByteArrayInputStream(s.getBytes()));

      List<String> propertyNames =
          Collections.list((Enumeration<String>) properties.propertyNames());

      for (int i = 0; i < propertyNames.size(); i++) {
        String key = propertyNames.get(i);

        String value = properties.getProperty(key);

        // Trim values because it may leave a trailing \r in certain
        // Windows environments. This is a known case for loading SQL
        // scripts in SQL Server.

        if (value != null) {
          value = value.trim();

          properties.setProperty(key, value);
        }
      }
    }
  }
 protected void mergeProperties(Properties into, Properties from) {
   Enumeration<?> e = from.propertyNames();
   while (e.hasMoreElements()) {
     String s = (String) e.nextElement();
     into.setProperty(s, from.getProperty(s));
   }
 }
  private static void readPropertyFile() {
    Properties prop = new Properties();
    InputStream input = null;

    try {
      input = new FileInputStream("config.properties");
      // load the properties file from class path
      prop.load(input);

      // get a property value and print it out
      System.out.println(prop.getProperty("user"));

      // get all properties
      Enumeration<?> e = prop.propertyNames();
      while (e.hasMoreElements()) {
        String key = (String) e.nextElement();
        String value = prop.getProperty(key);
        System.out.println("Key : " + key + ", Value : " + value);
      }

    } catch (IOException ex) {
      ex.printStackTrace();
    } finally {
      try {
        input.close();
      } catch (IOException e) {
        e.printStackTrace();
      }
    }
  }
  /**
   * Load the model from the given file, if possible.
   *
   * @param modelFile The IFile which contains the persisted model
   */
  @SuppressWarnings("unchecked")
  private synchronized Properties updateModel(IFile modelFile) {

    if (PROPERTIES_EXT.equals(modelFile.getFileExtension())) {
      Properties model = new Properties();
      if (modelFile.exists()) {
        try {
          model.load(modelFile.getContents());

          String propertyName;
          List properties = new ArrayList();
          for (Enumeration names = model.propertyNames(); names.hasMoreElements(); ) {
            propertyName = (String) names.nextElement();
            properties.add(
                new PropertiesTreeData(propertyName, model.getProperty(propertyName), modelFile));
          }
          PropertiesTreeData[] propertiesTreeData =
              (PropertiesTreeData[]) properties.toArray(new PropertiesTreeData[properties.size()]);

          cachedModelMap.put(modelFile, propertiesTreeData);
          return model;
        } catch (IOException e) {
        } catch (CoreException e) {
        }
      } else {
        cachedModelMap.remove(modelFile);
      }
    }
    return null;
  }
Beispiel #11
0
  private static Properties getGVCodes() {
    Properties ret = new Properties();
    Properties bpd = passport.getBPD();

    for (Enumeration e = bpd.propertyNames(); e.hasMoreElements(); ) {
      String key = (String) e.nextElement();

      if (key.startsWith("Params") && key.endsWith(".SegHead.code")) {
        String gvcode = bpd.getProperty(key);

        int dotPos = key.indexOf('.');
        int dotPos2 = key.indexOf('.', dotPos + 1);

        String gvname = key.substring(dotPos + 1, dotPos2);
        int len = gvname.length();
        int versionPos = -1;

        for (int i = len - 1; i >= 0; i--) {
          char ch = gvname.charAt(i);
          if (!(ch >= '0' && ch <= '9')) {
            versionPos = i + 1;
            break;
          }
        }

        String version = gvname.substring(versionPos);
        if (version.length() != 0) {
          gvname = gvname.substring(0, versionPos - 3); // remove version and "Par"
        }
        ret.setProperty(gvcode, gvname);
      }
    }

    return ret;
  }
  @Override
  public void afterPropertiesSet() {
    super.afterPropertiesSet();

    this.credentialTokens = new HashMap<String, String>(1);
    this.principalTokens = new HashMap<String, String>(1);

    try {
      String key;
      // We retrieve the tokens representing the credential and principal
      // parameters from the security properties file.
      Properties props =
          ResourceLoader.getResourceAsProperties(getClass(), "/properties/security.properties");
      Enumeration propNames = props.propertyNames();
      while (propNames.hasMoreElements()) {
        String propName = (String) propNames.nextElement();
        String propValue = props.getProperty(propName);
        if (propName.startsWith("credentialToken.")) {
          key = propName.substring(16);
          this.credentialTokens.put(key, propValue);
        }
        if (propName.startsWith("principalToken.")) {
          key = propName.substring(15);
          this.principalTokens.put(key, propValue);
        }
      }
    } catch (PortalException pe) {
      logger.error("LoginServlet::static ", pe);
    } catch (IOException ioe) {
      logger.error("LoginServlet::static ", ioe);
    }
  }
  private String formatSystemProperties(Properties properties) {
    StringBuilder text = new StringBuilder(200);
    List keys = new ArrayList();
    Enumeration en = properties.propertyNames();
    Iterator keyIt;

    while (en.hasMoreElements()) {
      keys.add(en.nextElement());
    }
    Collections.sort(keys);
    keyIt = keys.iterator();

    while (keyIt.hasNext()) {
      String key = (String) keyIt.next();
      String val = properties.getProperty(key);

      if ("line.separator".equals(key) && val != null) { // NOI18N
        val = val.replace("\n", "\\n"); // NOI18N
        val = val.replace("\r", "\\r"); // NOI18N
      }

      text.append("<nobr>&nbsp;&nbsp;&nbsp;&nbsp;<b>"); // NOI18N
      text.append(key);
      text.append("</b>="); // NOI18N
      text.append(val);
      text.append("</nobr><br>"); // NOI18N
    }

    return text.toString();
  }
  /**
   * Set the parameters to the supplied value. The supplied parameters value may suppliment or
   * replace the existing parameters value.
   *
   * @param parameters the supplied parameters
   * @param merge if TRUE the supplied parameters are merged with existing parameters otherwise the
   *     supplied parameters replace any existing parameters
   * @exception IllegalStateException if the component type backing the model does not implement the
   *     parameteriazable interface
   * @exception NullPointerException if the supplied parameters are null
   */
  public void setParameters(Parameters parameters, boolean merge) throws IllegalStateException {
    if (!isParameterizable()) {
      final String error =
          REZ.getString(
              "deployment.parameters.irrational", getDeploymentClass().getName(), this.toString());
      throw new IllegalStateException(error);
    }

    if (parameters == null) {
      throw new NullPointerException("parameters");
    }

    if (merge) {
      Properties props = Parameters.toProperties(m_parameters);
      Properties suppliment = Parameters.toProperties(parameters);
      Enumeration list = suppliment.propertyNames();
      while (list.hasMoreElements()) {
        String name = (String) list.nextElement();
        String value = suppliment.getProperty(name);
        if (value == null) {
          props.remove(name);
        } else {
          props.setProperty(name, value);
        }
      }
      m_parameters = Parameters.fromProperties(props);
    } else {
      m_parameters = parameters;
    }
  }
Beispiel #15
0
  /**
   * Factory method for ResultsPruners (used to load ConfigurationManager properties.
   *
   * @param props
   * @throws FileNotFoundException
   */
  public static ResultsPruner getPruner(Context context, Properties props)
      throws FileNotFoundException {

    ResultsPruner rp = new ResultsPruner(context);
    Pattern retentionPattern = Pattern.compile("checker\\.retention\\.(.*)");
    for (Enumeration<String> en = (Enumeration<String>) props.propertyNames();
        en.hasMoreElements(); ) {
      String name = en.nextElement();
      Matcher matcher = retentionPattern.matcher(name);
      if (!matcher.matches()) {
        continue;
      }
      String resultCode = matcher.group(1);
      long duration;
      try {
        duration = Utils.parseDuration(props.getProperty(name));
      } catch (ParseException e) {
        throw new IllegalStateException("Problem parsing duration: " + e.getMessage(), e);
      }
      ChecksumResultCode code = ChecksumResultCode.valueOf(resultCode);
      if (code == null) {
        throw new IllegalStateException("Checksum result code not found: " + resultCode);
      }
      if ("default".equals(resultCode)) {
        rp.setDefaultDuration(duration);
      } else {
        rp.addInterested(code, duration);
      }
    }
    return rp;
  }
	// 根据指定属性创建连接池实例.
	private void createPools(Properties props) {
		Enumeration propNames = props.propertyNames();
		while (propNames.hasMoreElements()) {
			String name = (String) propNames.nextElement();
			if (name.endsWith(".url")) {
				String poolName = name.substring(0, name.lastIndexOf("."));
				String url = props.getProperty(poolName + ".url");
				if (url == null) {
					log("没有为连接池" + poolName + "指定URL");
					continue;
				}
				// String user = props.getProperty(poolName + ".user");
				// String password = props.getProperty(poolName + ".password");
				String maxconn = props.getProperty(poolName + ".maxconn", "0");
				int max;
				try {
					max = Integer.valueOf(maxconn).intValue();
				} catch (NumberFormatException e) {
					log("错误的最大连接数限制: " + maxconn + " .连接池: " + poolName);
					max = 0;
				}
				DBConnectionPool pool = new DBConnectionPool(poolName, url, max);
				pools.put(poolName, pool);
				log("成功创建连接池" + poolName);
			}
		}
	}
Beispiel #17
0
  /**
   * Controls if result of reparsing contains certain parameters
   *
   * @param model
   * @param params
   */
  public static void controlModelParams(ModelNode node, Properties params) {
    String str;

    StringBuffer sb = new StringBuffer();
    String par, child;
    Enumeration e = params.propertyNames();

    while (e.hasMoreElements()) {
      str = (String) e.nextElement();
      par = params.getProperty(str);
      if (node.get(str) == null)
        sb.append("Parameter <" + str + "> is not set, but must be set to '" + par + "' \n");
      else {
        child = node.get(str).asString();
        if (!child.equals(par))
          sb.append(
              "Parameter <"
                  + str
                  + "> is set to '"
                  + child
                  + "', but must be set to '"
                  + par
                  + "' \n");
      }
    }
    if (sb.length() > 0)
      Assert.fail("There are parsing errors:\n" + sb.toString() + "Parsed configuration:\n" + node);
  }
Beispiel #18
0
 /**
  * Add set of properties to this object. This method will replace the value of any properties that
  * already existed.
  */
 public void setProperties(Properties props) {
   Enumeration names = props.propertyNames();
   while (names.hasMoreElements()) {
     String name = (String) names.nextElement();
     setProperty(name, props.getProperty(name));
   }
 }
  private void generateSvrReport(String path) {
    if (loadConfig(path)) {
      ssoToken = getAdminSSOToken();
      if (ssoToken != null) {
        // All the properties should be loaded at this point
        Properties prop = SystemProperties.getAll();
        Properties amProp = new Properties();
        Properties sysProp = new Properties();

        for (Enumeration e = prop.propertyNames(); e.hasMoreElements(); ) {
          String key = (String) e.nextElement();
          String val = (String) prop.getProperty(key);
          if (key.startsWith(AM_PROP_SUN_SUFFIX)
              || key.startsWith(AM_PROP_SUFFIX)
              || key.startsWith(ENC_PWD_PROPERTY)) {
            amProp.put(key, val);
          } else {
            sysProp.put(key, val);
          }
        }
        printProperties(amProp, DEF_PROP);
        printProperties(sysProp, SYS_PROP);
        getInstanceProperties(ssoToken);
      } else {
        toolOutWriter.printError("rpt-auth-msg");
      }
    } else {
      toolOutWriter.printStatusMsg(false, "rpt-svr-gen");
    }
  }
Beispiel #20
0
  private static void initializeProperties() throws IOException, FileNotFoundException {
    {
      // Default properties are in resource 'one-jar.properties'.
      Properties properties = new Properties();
      String props = "one-jar.properties";
      InputStream is = Boot.class.getResourceAsStream("/" + props);
      if (is != null) {
        LOGGER.info("loading properties from " + props);
        properties.load(is);
      }

      // Merge in anything in a local file with the same name.
      if (new File(props).exists()) {
        is = new FileInputStream(props);
        if (is != null) {
          LOGGER.info("merging properties from " + props);
          properties.load(is);
        }
      }

      // Set system properties only if not already specified.
      Enumeration _enum = properties.propertyNames();
      while (_enum.hasMoreElements()) {
        String name = (String) _enum.nextElement();
        if (System.getProperty(name) == null) {
          System.setProperty(name, properties.getProperty(name));
        }
      }
    }
  }
Beispiel #21
0
  public static String toString(Properties properties) {
    SafeProperties safeProperties = null;

    if (properties instanceof SafeProperties) {
      safeProperties = (SafeProperties) properties;
    }

    StringBundler sb = null;

    if (properties.isEmpty()) {
      sb = new StringBundler();
    } else {
      sb = new StringBundler(properties.size() * 4);
    }

    Enumeration<String> enu = (Enumeration<String>) properties.propertyNames();

    while (enu.hasMoreElements()) {
      String key = enu.nextElement();

      sb.append(key);
      sb.append(StringPool.EQUAL);

      if (safeProperties != null) {
        sb.append(safeProperties.getEncodedProperty(key));
      } else {
        sb.append(properties.getProperty(key));
      }

      sb.append(StringPool.NEW_LINE);
    }

    return sb.toString();
  }
  protected List /*<Exception>*/ installBundles(Properties uploads, boolean start)
      throws IllegalArgumentException {
    if (uploads == null || uploads.isEmpty())
      throw new IllegalArgumentException(
          "Bundle installation request must include at least one uploaded file.");
    List bundles = new LinkedList();
    List errors = new LinkedList();

    for (Enumeration names = uploads.propertyNames(); names.hasMoreElements(); ) {
      try {
        String name = (String) names.nextElement();
        Bundle bundle =
            context.installBundle(
                "uploaded:" + name, new FileInputStream(uploads.getProperty(name)));
        bundles.add(bundle);
      } catch (FileNotFoundException e) {
        errors.add(e);
      } catch (BundleException e) {
        errors.add(e);
      }
    }

    if (start) {
      for (Iterator iter = bundles.iterator(); iter.hasNext(); ) {
        try {
          Bundle bundle = (Bundle) iter.next();
          bundle.start();
        } catch (BundleException e) {
          errors.add(e);
        }
      }
    }

    return errors;
  }
 /**
  * Loads the properties in the system property file associated with the framework installation
  * into <tt>System.setProperty()</tt>. These properties are not directly used by the framework in
  * anyway. By default, the system property file is located in the <tt>conf/</tt> directory and is
  * called "<tt>system.properties</tt>".
  */
 protected void loadSystemProperties(JsonValue configuration, URI projectDirectory) {
   JsonValue systemProperties = configuration.get(SYSTEM_PROPERTIES_PROP);
   if (systemProperties.isMap()) {
     for (Map.Entry<String, Object> entry : systemProperties.copy().asMap().entrySet()) {
       // The user.dir MUST not be overwritten!!!
       if (entry.getValue() instanceof String && !"user.dir".equals(entry.getKey())) {
         System.setProperty(entry.getKey(), (String) entry.getValue());
       }
     }
   } else {
     Properties props =
         loadPropertyFile(
             projectDirectory,
             systemProperties
                 .expect(String.class)
                 .defaultTo(SYSTEM_PROPERTIES_FILE_VALUE)
                 .asString());
     if (props == null) return;
     // Perform variable substitution on specified properties.
     for (Enumeration e = props.propertyNames(); e.hasMoreElements(); ) {
       String name = (String) e.nextElement();
       if (!"user.dir".equals(name)) {
         Object newValue = ConfigurationUtil.substVars(props.getProperty(name), propertyAccessor);
         if (newValue instanceof String) {
           System.setProperty(name, (String) newValue);
         }
       }
     }
   }
 }
 @Override
 protected void initializeInstance() throws Persistence.PersistenceException {
   properties = new Properties();
   indexFile = new File(getStorageDirectoryPath(), CACHE_INDEX_FILE_NAME);
   // We make sure that the parent directory exists
   final File storageDirectory = indexFile.getParentFile();
   storageDirectory.mkdirs();
   if (storageDirectory.exists() == false) {
     if (log.isErrorEnabled()) {
       log.error(
           "The back-end directory '"
               + storageDirectory.getAbsolutePath()
               + "' is not available: will not cache the streams");
     }
     throw new Persistence.PersistenceException(
         "Cannot initialize properly: the back-end directory '"
             + storageDirectory.getAbsolutePath()
             + "' is not available");
   }
   if (indexFile.exists() == false) {
     // There is no index file yet
     setStorageBackendAvailable(true);
     return;
   }
   if (log.isInfoEnabled()) {
     log.info("Reading the index file '" + indexFile.getAbsolutePath() + "'");
   }
   FileInputStream inputStream = null;
   try {
     inputStream = new FileInputStream(indexFile);
     properties.load(inputStream);
     final Enumeration<?> propertyNames = properties.propertyNames();
     while (propertyNames.hasMoreElements() == true) {
       final String uri = (String) propertyNames.nextElement();
       if (uri.equals(FilePersistence.INDEX_KEY) == true) {
         uriUsages.setIndex(Integer.parseInt(properties.getProperty(uri)));
       } else {
         uriUsages.put(uri, new Persistence.UriUsage(properties.getProperty(uri), uri));
       }
     }
   } catch (Exception exception) {
     if (log.isErrorEnabled()) {
       log.error(
           "Cannot properly read the index file at '" + indexFile.getAbsolutePath() + "'",
           exception);
     }
     throw new Persistence.PersistenceException(
         "Cannot initialize properly: the index file at '" + indexFile.getAbsolutePath() + "'",
         exception);
   } finally {
     if (inputStream != null) {
       try {
         inputStream.close();
       } catch (IOException exception) {
         // Does not matter
       }
     }
   }
   setStorageBackendAvailable(true);
 }
  /**
   * Reads a property file, resolving all internal variables.
   *
   * @param propfile The property file to load
   * @return the loaded and fully resolved Properties object
   */
  public static Properties loadPropertyFile(File propfile) {
    if (!propfile.exists()) {
      throw new PropertiesException(
          "unable to locate spercified prop file [" + propfile.toString() + "]");
    }

    Properties props = new Properties();
    if (propfile.exists()) {
      try {
        FileInputStream inStream = new FileInputStream(propfile);
        try {
          props.load(inStream);
        } finally {
          IOUtil.close(inStream);
        }
      } catch (IOException ioe) {
        throw new PropertiesException("unable to load properties file [" + propfile + "]");
      }
    }

    for (Enumeration n = props.propertyNames(); n.hasMoreElements(); ) {
      String k = (String) n.nextElement();
      props.setProperty(k, PropertiesHelper.getInterpolatedPropertyValue(k, props));
    }

    return props;
  }
 /**
  * Creates a process builder for the application, using the config, logging, and system
  * properties.
  */
 ProcessBuilder createProcessBuilder() throws Exception {
   /* Create the application configuration file */
   File configFile = File.createTempFile("SimpleApp", "config");
   OutputStream configOut = new FileOutputStream(configFile);
   config.store(configOut, null);
   configOut.close();
   /* Create the logging configuration file */
   File loggingFile = File.createTempFile("SimpleApp", "logging");
   OutputStream loggingOut = new FileOutputStream(loggingFile);
   logging.store(loggingOut, null);
   loggingOut.close();
   /* Create the command line for running the Kernel */
   List<String> command = new ArrayList<String>();
   command.add(System.getProperty("java.home") + "/bin/java");
   command.add("-cp");
   command.add(System.getProperty("java.class.path"));
   command.add("-Djava.util.logging.config.file=" + loggingFile);
   command.add("-Djava.library.path=" + System.getProperty("java.library.path"));
   Enumeration<?> names = system.propertyNames();
   while (names.hasMoreElements()) {
     Object name = names.nextElement();
     command.add("-D" + name + "=" + system.get(name));
   }
   command.add("com.sun.sgs.impl.kernel.Kernel");
   command.add(configFile.toURI().toURL().getPath());
   /* Return the process builder */
   return new ProcessBuilder(command);
 }
Beispiel #27
0
 public static void storeDevices(Hashtable devices, String selected) {
   File cf = getConfigFile();
   if (cf == null) {
     return;
   }
   FileWriter fw = null;
   try {
     fw = new FileWriter(cf, false);
     for (Enumeration i = devices.keys(); i.hasMoreElements(); ) {
       String addr = (String) i.nextElement();
       DeviceInfo di = (DeviceInfo) devices.get(addr);
       fw.write(devicePrefix + di.saveAsLine() + "\n");
     }
     if (selected != null) {
       fw.write(selectedPrefix + selected + "\n");
     }
     for (Enumeration en = properties.propertyNames(); en.hasMoreElements(); ) {
       String name = (String) en.nextElement();
       fw.write(name + "=" + properties.getProperty(name) + "\n");
     }
     fw.flush();
   } catch (Throwable e) {
     Logger.debug(e);
     return;
   } finally {
     if (fw != null) {
       try {
         fw.close();
       } catch (IOException e) {
       }
     }
   }
 }
 /** Sets Tesseract's internal parameters. */
 private void setTessVariables() {
   Enumeration<?> em = prop.propertyNames();
   while (em.hasMoreElements()) {
     String key = (String) em.nextElement();
     api.TessBaseAPISetVariable(handle, key, prop.getProperty(key));
   }
 }
  @Test
  public void create_map_from_properties_java() {

    Properties properties = new Properties();
    properties.put("database.username", "yourname");
    properties.put("database.password", "encrypted_password");
    properties.put("database.driver", "com.mysql.jdbc.Driver");
    properties.put("database.url", "jdbc:mysql://localhost:3306/sakila?profileSQL=true");

    Map<String, String> mapOfProperties = new HashMap<String, String>();

    Enumeration<?> propertyNames = properties.propertyNames();

    while (propertyNames.hasMoreElements()) {
      String key = (String) propertyNames.nextElement();
      mapOfProperties.put(key, properties.getProperty(key));
    }

    logger.info(mapOfProperties);

    assertThat(
        mapOfProperties.keySet(),
        containsInAnyOrder(
            "database.username", "database.password", "database.driver", "database.url"));
  }
  /**
   * @throws IOException
   * @tests java.util.Properties#save(java.io.OutputStream, java.lang.String)
   */
  @TestTargetNew(
      level = TestLevel.COMPLETE,
      notes = "",
      method = "save",
      args = {java.io.OutputStream.class, java.lang.String.class})
  public void test_saveLjava_io_OutputStreamLjava_lang_String() throws IOException {
    Properties myProps = new Properties();
    myProps.setProperty("Property A", "aye");
    myProps.setProperty("Property B", "bee");
    myProps.setProperty("Property C", "see");

    ByteArrayOutputStream out = new ByteArrayOutputStream();
    myProps.save(out, "A Header");
    out.close();

    Properties myProps2 = new Properties();
    ByteArrayInputStream in = new ByteArrayInputStream(out.toByteArray());
    myProps2.load(in);
    in.close();

    Enumeration e = myProps.propertyNames();
    while (e.hasMoreElements()) {
      String nextKey = (String) e.nextElement();
      assertTrue(
          "Stored property list not equal to original",
          myProps2.getProperty(nextKey).equals(myProps.getProperty(nextKey)));
    }
  }