Ejemplo n.º 1
0
 public void testTranslationKeyExistence() throws IOException {
   // use English version as the reference:
   final File englishFile = getEnglishTranslationFile();
   final Properties enProps = new Properties();
   enProps.load(new FileInputStream(englishFile));
   final Set<Object> englishKeys = enProps.keySet();
   for (Language lang : Language.REAL_LANGUAGES) {
     if (lang.getShortName().equals("en")) {
       continue;
     }
     final Properties langProps = new Properties();
     final File langFile = getTranslationFile(lang);
     if (!langFile.exists()) {
       continue;
     }
     try (FileInputStream stream = new FileInputStream(langFile)) {
       langProps.load(stream);
       final Set<Object> langKeys = langProps.keySet();
       for (Object englishKey : englishKeys) {
         if (!langKeys.contains(englishKey)) {
           System.err.println("***** No key '" + englishKey + "' in file " + langFile);
         }
       }
     }
   }
 }
Ejemplo n.º 2
0
  /** 读取配置文件中的全局参数的配置,存到缓存中 */
  private static void initProperties() {
    try {

      logger.debug("加载属性配置文件开始!");
      String propUrl = getSysPath() + "config.properties";
      logger.debug("系统全局参数的路径是:" + propUrl);
      FileInputStream fis = new FileInputStream(propUrl); // 属性文件流
      Properties prop = new Properties(); // 属性集合对象
      prop.load(fis); // 将属性文件流装载到Properties对象中
      logger.debug("属性的长度:" + prop.size());

      Map<String, String> paramMap = new HashMap<String, String>();
      Iterator<Object> it = prop.keySet().iterator();
      while (it.hasNext()) {
        String key = (String) (it.next());
        String value = prop.getProperty(key);
        logger.debug(key + "=" + value);
        // global.ip=192.168.0.242的格式
        // map.put(key, prop.getProperty(key));
        paramMap.put(key, value);
      }
      logger.debug("加载属性配置文件结束!");
      setConfigMap(paramMap);

    } catch (FileNotFoundException e) {
      logger.error("文件未找到!");
      e.printStackTrace();
    } catch (IOException e) {
      logger.error("读取文件的时候异常!");
      e.printStackTrace();
    } catch (Exception e) {
      logger.error("其它异常!");
      e.printStackTrace();
    }
  }
  public static Properties getSystemProperties() {
    Properties res = ourSystemProperties;
    if (res == null) {
      res = new Properties();
      res.putAll(System.getProperties());

      for (Iterator<Object> itr = res.keySet().iterator(); itr.hasNext(); ) {
        final String propertyName = itr.next().toString();
        if (propertyName.startsWith("idea.")) {
          itr.remove();
        }
      }

      for (Map.Entry<String, String> entry : System.getenv().entrySet()) {
        String key = entry.getKey();
        if (key.startsWith("=")) {
          continue;
        }
        if (SystemInfo.isWindows) {
          key = key.toUpperCase();
        }
        res.setProperty("env." + key, entry.getValue());
      }

      ourSystemProperties = res;
    }
    return res;
  }
Ejemplo n.º 4
0
  private static Map<String, String> createAuthorizationAttributeMap(
      String snaaName, Properties props) {
    Map<String, String> attributes = new HashMap<String, String>();

    List<String> keys = new LinkedList<String>();
    // getting keys from properties
    for (Object o : props.keySet()) {
      if (((String) o).startsWith(snaaName + authorizationAtt)
          && ((String) o).endsWith(authorizationKeyAtt)) {
        keys.add((String) o);
      }
    }

    for (String k : keys) {
      String key = props.getProperty(k);
      // getting plain key-number from properties
      String plainKeyProperty = k.replaceAll(snaaName + authorizationAtt + ".", "");
      plainKeyProperty = plainKeyProperty.replaceAll(authorizationKeyAtt, "");

      String keyPrefix = snaaName + authorizationAtt + "." + plainKeyProperty;

      // building value-property-string
      String value = props.getProperty(keyPrefix + authorizationValAtt);

      // finally put key and values
      attributes.put(key, value);
    }

    return attributes;
  }
Ejemplo n.º 5
0
  private static AuthorizationDataSource getAuthorizationDataSource(
      String snaaName, Properties props)
      throws ClassNotFoundException, IllegalAccessException, InstantiationException {
    for (Object o : props.keySet()) {
      String dataSourceName = snaaName + authorizationAtt + authorizationDataSource;
      if (o.equals(dataSourceName)) {
        AuthorizationDataSource dataSource =
            (AuthorizationDataSource) Class.forName(props.getProperty((String) o)).newInstance();

        String dataSourceUsername =
            props.getProperty(dataSourceName + authorizationDataSourceUsername);
        String dataSourcePassword =
            props.getProperty(dataSourceName + authorizationDataSourcePassword);
        String dataSourceUrl = props.getProperty(dataSourceName + authorizationDataSourceUrl);

        if (dataSourceUsername != null) {
          dataSource.setUsername(dataSourceUsername);
        }
        if (dataSourcePassword != null) {
          dataSource.setPassword(dataSourcePassword);
        }
        if (dataSourceUrl != null) {
          dataSource.setUrl(dataSourceUrl);
        }

        return dataSource;
      }
    }
    // set default
    return new ShibbolethDataSource();
  }
Ejemplo n.º 6
0
 /**
  * Return a list of resource model configuration
  *
  * @param props properties
  * @return List of Maps, each map containing "type": String, "props":Properties
  */
 public static List<Map<String, Object>> listResourceModelConfigurations(final Properties props) {
   final ArrayList<Map<String, Object>> list = new ArrayList<Map<String, Object>>();
   int i = 1;
   boolean done = false;
   while (!done) {
     final String prefix = RESOURCES_SOURCE_PROP_PREFIX + "." + i;
     if (props.containsKey(prefix + ".type")) {
       final String providerType = props.getProperty(prefix + ".type");
       final Properties configProps = new Properties();
       final int len = (prefix + ".config.").length();
       for (final Object o : props.keySet()) {
         final String key = (String) o;
         if (key.startsWith(prefix + ".config.")) {
           configProps.setProperty(key.substring(len), props.getProperty(key));
         }
       }
       final HashMap<String, Object> map = new HashMap<String, Object>();
       map.put("type", providerType);
       map.put("props", configProps);
       list.add(map);
     } else {
       done = true;
     }
     i++;
   }
   return list;
 }
Ejemplo n.º 7
0
  public static void main(String[] args) {

    Properties prop = System.getProperties();

    // 因为Properties是Hashtable的子类,也就是Map集合的一个子类对象。
    // 那么可以通过map的方法取出该集合中的元素。
    // 该集合中存储的都是字符串。没有泛型定义。

    // 如何在系统中自定义一些系统信息

    System.setProperty("mykey", "myvalue");

    // 获取指定属性信息

    String osvalue = System.getProperty("os.name");

    System.out.println("value=" + osvalue);

    // 可不可以在JVM启动时,动态地加载一些属性信息
    // -D<name>=<value>  设置系统属性

    // 获取所有属性信息

    for (Object obj : prop.keySet()) {
      String value = (String) prop.get(obj);

      System.out.println(obj + "::" + value);
    }
  }
Ejemplo n.º 8
0
  public static void main(String args[]) {
    Properties defList = new Properties();
    defList.put("Florida", "Tallahassee");
    defList.put("Wisconsin", "Madison");

    Properties capitals = new Properties(defList);

    capitals.put("Illinois", "Springfield");
    capitals.put("Missouri", "Jefferson City");
    capitals.put("Washington", "Olympia");
    capitals.put("California", "Sacramento");
    capitals.put("Indiana", "Indianapolis");

    // Get a set-view of the keys.
    Set<?> states = capitals.keySet();

    // Show all of the states and capitals.
    for (Object name : states)
      System.out.println(
          "The capital of " + name + " is " + capitals.getProperty((String) name) + ".");
    System.out.println();

    // Florida will now be found in the default.
    String str = capitals.getProperty("Florida", "Not found.");
    System.out.println("The capital of Florida is " + str + ".");
    str = capitals.getProperty("California");
    System.out.println("The capital of California is " + str + ".");
    str = capitals.getProperty("Texas");
    System.out.println("The capital of Texas is " + str + ".");
  }
Ejemplo n.º 9
0
 public NanoHTTPD.Response serve(NanoHTTPD server, Properties args, RequestType type) {
   // Needs to be done also for help to initialize or argument records
   String query = checkArguments(args, type);
   switch (type) {
     case help:
       return wrap(server, build(Response.done(serveHelp())));
     case json:
     case www:
       if (log()) {
         String log = getClass().getSimpleName();
         for (Object arg : args.keySet()) {
           String value = args.getProperty((String) arg);
           if (value != null && value.length() != 0) log += " " + arg + "=" + value;
         }
         Log.debug(Sys.HTTPD, log);
       }
       if (query != null) return wrap(server, query, type);
       long time = System.currentTimeMillis();
       Response response = serve();
       response.setTimeStart(time);
       if (type == RequestType.json) return wrap(server, response.toJson());
       return wrap(server, build(response));
     case debug:
       response = serve_debug();
       return wrap(server, build(response));
     case query:
       return wrap(server, query);
     default:
       throw new RuntimeException("Invalid request type " + type.toString());
   }
 }
 void propRemove(Properties props, Bundle bundle) throws Exception {
   for (Iterator<Object> iterator = props.keySet().iterator(); iterator.hasNext(); ) {
     if (iterator.next().toString().startsWith(propKeyPrefix(bundle))) {
       iterator.remove();
     }
   }
 }
Ejemplo n.º 11
0
  /**
   * Method to obtain the custom UI media types.
   *
   * @param configSystemRegistry a configuration system registry instance.
   * @return a String of custom UI media types, in the format name:type,name:type,...
   * @throws RegistryException if the operation failed.
   */
  public static String getCustomUIMediaTypeMappings(Registry configSystemRegistry)
      throws RegistryException {

    RegistryContext registryContext = configSystemRegistry.getRegistryContext();

    if (getCustomUIMediaTypeMappings(registryContext) != null) {
      return getCustomUIMediaTypeMappings(registryContext);
    }

    Resource resource;
    String mediaTypeString = null;

    String resourcePath =
        MIME_TYPE_COLLECTION + RegistryConstants.PATH_SEPARATOR + RESOURCE_MIME_TYPE_INDEX;

    // TODO: Adding the media types should ideally be done by the handler associated with the
    // media type
    if (!configSystemRegistry.resourceExists(resourcePath)) {
      getResourceMediaTypeMappings(configSystemRegistry);
    }
    if (!configSystemRegistry.resourceExists(
        resourcePath + RegistryConstants.PATH_SEPARATOR + CUSTOM_UI_MIME_TYPE_INDEX)) {
      resource = configSystemRegistry.newResource();
      resource.setProperty("profiles", "application/vnd.wso2-profiles+xml");
      // resource.setProperty("service", "application/vnd.wso2-service+xml");
      resource.setDescription(
          "This resource contains the media Types associated with "
              + "custom user interfaces on the Registry. Add, Edit or Delete properties to "
              + "Manage Media Types.");
      configSystemRegistry.put(
          resourcePath + RegistryConstants.PATH_SEPARATOR + CUSTOM_UI_MIME_TYPE_INDEX, resource);
    } else {
      resource =
          configSystemRegistry.get(
              resourcePath + RegistryConstants.PATH_SEPARATOR + CUSTOM_UI_MIME_TYPE_INDEX);
    }
    Properties properties = resource.getProperties();
    if (properties.size() > 0) {
      Set<Object> keySet = properties.keySet();
      for (Object key : keySet) {
        if (key instanceof String) {
          String ext = (String) key;
          if (RegistryUtils.isHiddenProperty(ext)) {
            continue;
          }
          String value = resource.getProperty(ext);
          String mediaTypeMapping = ext + ":" + value;
          if (mediaTypeString == null) {
            mediaTypeString = mediaTypeMapping;
          } else {
            mediaTypeString = mediaTypeString + "," + mediaTypeMapping;
          }
        }
      }
    }
    registryContext.setCustomUIMediaTypes(mediaTypeString);
    return mediaTypeString;
  }
Ejemplo n.º 12
0
  /**
   * Returns true iff all the files listed in this tracker's dependency list exist and are at the
   * same version as when they were recorded.
   *
   * @return a boolean
   */
  boolean isUpToDate(Properties properties) {
    Iterator e;

    // fixes bug 962
    {
      if (mProperties.size() != properties.size()) {
        mLogger.debug(
            /* (non-Javadoc)
             * @i18n.test
             * @org-mes="my size " + p[0]
             */
            org.openlaszlo.i18n.LaszloMessages.getMessage(
                DependencyTracker.class.getName(),
                "051018-181",
                new Object[] {new Integer(mProperties.size())}));
        mLogger.debug(
            /* (non-Javadoc)
             * @i18n.test
             * @org-mes="new size " + p[0]
             */
            org.openlaszlo.i18n.LaszloMessages.getMessage(
                DependencyTracker.class.getName(),
                "051018-189",
                new Object[] {new Integer(properties.size())}));
        return false;
      }

      for (e = mProperties.keySet().iterator(); e.hasNext(); ) {
        String key = (String) e.next();
        String val0 = mProperties.getProperty(key);
        String val1 = properties.getProperty(key);

        // val0 can't be null; properties don't allow that
        if (val1 == null || !val0.equals(val1)) {
          mLogger.debug(
              /* (non-Javadoc)
               * @i18n.test
               * @org-mes="Missing or changed property: " + p[0]
               */
              org.openlaszlo.i18n.LaszloMessages.getMessage(
                  DependencyTracker.class.getName(), "051018-207", new Object[] {val0}));
          return false;
        }
      }
    }

    for (e = mDependencies.iterator(); e.hasNext(); ) {
      FileInfo saved = (FileInfo) e.next();
      FileInfo current = new FileInfo(saved.mPathname);
      if (!saved.isUpToDate(current)) {
        mLogger.debug(saved.mPathname + " has changed");
        mLogger.debug("was " + saved.mLastMod);
        mLogger.debug(" is " + current.mLastMod);
        return false;
      }
    }
    return true;
  }
Ejemplo n.º 13
0
 /**
  * Puts all the properties with keys starting with the provided <tt>prefix</tt>.
  *
  * @param prefix The prefix to filter property key by
  * @param properties The properties to put
  * @return The builder
  */
 public Builder putProperties(String prefix, Properties properties) {
   for (Object key1 : properties.keySet()) {
     String key = (String) key1;
     String value = properties.getProperty(key);
     if (key.startsWith(prefix)) {
       map.put(key.substring(prefix.length()), value);
     }
   }
   return this;
 }
Ejemplo n.º 14
0
  /**
   * Load the Configuration file with the values from the command line and config files, and place
   * stuff in the DistrubutedCacheService as needed
   *
   * @param conf The Configuration to populate
   * @param args The command line arguments
   * @throws Exception
   */
  public static void initalizeConf(Configuration conf, String[] args) throws Exception {
    // Parse the arguments and make sure the required args are there
    final CommandLine commandLine;
    final Options options = constructGnuOptions();
    try {
      commandLine = new GnuParser().parse(options, args);
    } catch (MissingOptionException ex) {
      HelpFormatter help = new HelpFormatter();
      help.printHelp("hadoop jar <jarFile> " + FrameworkDriver.class.getCanonicalName(), options);
      return;
    } catch (Exception ex) {
      ex.printStackTrace();
      return;
    }

    final String userConfFilePath = commandLine.getOptionValue("amino_config_file_path", "");
    final String aminoDefaultConfigPath = commandLine.getOptionValue("amino_default_config_path");
    final String baseDir = commandLine.getOptionValue("base_dir");

    stopOnFirstPhase = commandLine.hasOption("stop");

    // Set the base dir config value if it was provided.
    if (StringUtils.isNotEmpty(baseDir)) {
      conf.set(AminoConfiguration.BASE_DIR, baseDir);
    }

    conf.set(AminoConfiguration.DEFAULT_CONFIGURATION_PATH_KEY, aminoDefaultConfigPath);

    // create a single DistributedCacheService so that multiple cache entries are deduped.
    // Cache files are added after each config is loaded in case the the property value changes.
    final DistributedCacheService distributedCacheService = new DistributedCacheService();

    // 1. load AminoDefaults
    AminoConfiguration.loadAndMergeWithDefault(conf, true);
    distributedCacheService.addFilesToDistributedCache(conf);

    // 2. load user config files, allowing them to overwrite
    if (!StringUtils.isEmpty(userConfFilePath)) {
      for (String path : getUserConfigFiles(userConfFilePath)) {
        Configuration userConf = new Configuration(false);
        logger.info("Grabbing configuration information from: " + path);
        userConf.addResource(new FileInputStream(path));
        HadoopConfigurationUtils.mergeConfs(conf, userConf);
      }
    }
    distributedCacheService.addFilesToDistributedCache(conf);

    // 3. load command line arguments as properties, allowing them to overwrite
    final Properties propertyOverrides = commandLine.getOptionProperties("property_override");
    for (Object key : propertyOverrides.keySet()) {
      conf.set((String) key, (String) propertyOverrides.get(key));
    }
    distributedCacheService.addFilesToDistributedCache(conf);
  }
    protected propertyWrapper(Properties _props) {
      Iterator it = _props.keySet().iterator();

      while (it.hasNext()) {

        Object key = it.next();

        put(key, _props.get(key));
      }

      initialising = false;
    }
  @Override
  public void open() {
    out = new ByteArrayOutputStream();
    flinkConf = new org.apache.flink.configuration.Configuration();
    Properties intpProperty = getProperty();
    for (Object k : intpProperty.keySet()) {
      String key = (String) k;
      String val = toString(intpProperty.get(key));
      flinkConf.setString(key, val);
    }

    if (localMode()) {
      startFlinkMiniCluster();
    }

    flinkIloop =
        new FlinkILoop(
            getHost(), getPort(), flinkConf, (BufferedReader) null, new PrintWriter(out));

    flinkIloop.settings_$eq(createSettings());
    flinkIloop.createInterpreter();

    imain = flinkIloop.intp();

    org.apache.flink.api.scala.ExecutionEnvironment benv = flinkIloop.scalaBenv();
    // new ExecutionEnvironment(remoteBenv)
    org.apache.flink.streaming.api.scala.StreamExecutionEnvironment senv = flinkIloop.scalaSenv();

    senv.getConfig().disableSysoutLogging();
    benv.getConfig().disableSysoutLogging();

    // prepare bindings
    imain.interpret("@transient var _binder = new java.util.HashMap[String, Object]()");
    Map<String, Object> binder = (Map<String, Object>) getLastObject();

    // import libraries
    imain.interpret("import scala.tools.nsc.io._");
    imain.interpret("import Properties.userHome");
    imain.interpret("import scala.compat.Platform.EOL");

    imain.interpret("import org.apache.flink.api.scala._");
    imain.interpret("import org.apache.flink.api.common.functions._");

    binder.put("benv", benv);
    imain.interpret(
        "val benv = _binder.get(\"benv\").asInstanceOf[" + benv.getClass().getName() + "]");

    binder.put("senv", senv);
    imain.interpret(
        "val senv = _binder.get(\"senv\").asInstanceOf[" + senv.getClass().getName() + "]");
  }
Ejemplo n.º 17
0
  public static void dumpSystemProperties() {
    out("System Properties:");

    Properties props = System.getProperties();

    Iterator it = props.keySet().iterator();

    while (it.hasNext()) {

      String name = (String) it.next();

      out("\t".concat(name).concat(" = '").concat(props.get(name).toString()).concat("'"));
    }
  }
  private void saveNewProperties(String path, Properties oldProps) throws Exception {
    File newPropsFile = new File(path + FileSystemPage.propertiesFilename);
    WikiPageProperties newProps = new WikiPageProperties();

    for (Iterator iterator = oldProps.keySet().iterator(); iterator.hasNext(); ) {
      String key = (String) iterator.next();
      String value = (String) oldProps.get(key);
      if (!"false".equals(value)) newProps.set(key, value);
    }

    FileOutputStream os = new FileOutputStream(newPropsFile);
    newProps.save(os);
    os.close();
  }
Ejemplo n.º 19
0
 /** Concatenate params for URL string */
 String concatParams(Properties props) {
   if (props == null) {
     return null;
   }
   java.util.List list = new ArrayList();
   for (Iterator iter = props.keySet().iterator(); iter.hasNext(); ) {
     String key = (String) iter.next();
     String val = props.getProperty(key);
     if (!StringUtil.isNullString(val)) {
       list.add(key + "=" + urlEncode(val));
     }
   }
   return StringUtil.separatedString(list, "&");
 }
Ejemplo n.º 20
0
  private Map<String, Pack> loadInstallationInformation(boolean modifyInstallation) {
    Map<String, Pack> installedpacks = new HashMap<String, Pack>();
    if (!modifyInstallation) {
      return installedpacks;
    }

    // installation shall be modified
    // load installation information
    ObjectInputStream oin = null;
    try {
      FileInputStream fin =
          new FileInputStream(
              new File(
                  installData.getInstallPath()
                      + File.separator
                      + InstallData.INSTALLATION_INFORMATION));
      oin = new ObjectInputStream(fin);
      List<Pack> packsinstalled = (List<Pack>) oin.readObject();
      for (Pack installedpack : packsinstalled) {
        installedpacks.put(installedpack.getName(), installedpack);
      }
      this.removeAlreadyInstalledPacks(installData.getSelectedPacks());
      logger.fine("Found " + packsinstalled.size() + " installed packs");

      Properties variables = (Properties) oin.readObject();

      for (Object key : variables.keySet()) {
        installData.setVariable((String) key, (String) variables.get(key));
      }
    } catch (FileNotFoundException e) {
      // TODO Auto-generated catch block
      e.printStackTrace();
    } catch (IOException e) {
      // TODO Auto-generated catch block
      e.printStackTrace();
    } catch (ClassNotFoundException e) {
      // TODO Auto-generated catch block
      e.printStackTrace();
    } finally {
      if (oin != null) {
        try {
          oin.close();
        } catch (IOException e) {
        }
      }
    }
    return installedpacks;
  }
Ejemplo n.º 21
0
  /** Start the JobTracker process, listen on the indicated port */
  JobTracker(Configuration conf) throws IOException {
    //
    // Grab some static constants
    //
    maxCurrentTasks = conf.getInt("mapred.tasktracker.tasks.maximum", 2);
    RETIRE_JOB_INTERVAL = conf.getLong("mapred.jobtracker.retirejob.interval", 24 * 60 * 60 * 1000);
    RETIRE_JOB_CHECK_INTERVAL = conf.getLong("mapred.jobtracker.retirejob.check", 60 * 1000);
    TASK_ALLOC_EPSILON = conf.getFloat("mapred.jobtracker.taskalloc.loadbalance.epsilon", 0.2f);
    PAD_FRACTION = conf.getFloat("mapred.jobtracker.taskalloc.capacitypad", 0.1f);
    MIN_SLOTS_FOR_PADDING = 3 * maxCurrentTasks;

    // This is a directory of temporary submission files.  We delete it
    // on startup, and can delete any files that we're done with
    this.conf = conf;
    JobConf jobConf = new JobConf(conf);
    this.systemDir = jobConf.getSystemDir();
    this.fs = FileSystem.get(conf);
    FileUtil.fullyDelete(fs, systemDir);
    fs.mkdirs(systemDir);

    // Same with 'localDir' except it's always on the local disk.
    jobConf.deleteLocalFiles(SUBDIR);

    // Set ports, start RPC servers, etc.
    InetSocketAddress addr = getAddress(conf);
    this.localMachine = addr.getHostName();
    this.port = addr.getPort();
    this.interTrackerServer = RPC.getServer(this, addr.getPort(), 10, false, conf);
    this.interTrackerServer.start();
    Properties p = System.getProperties();
    for (Iterator it = p.keySet().iterator(); it.hasNext(); ) {
      String key = (String) it.next();
      String val = (String) p.getProperty(key);
      LOG.info("Property '" + key + "' is " + val);
    }

    this.infoPort = conf.getInt("mapred.job.tracker.info.port", 50030);
    this.infoServer = new JobTrackerInfoServer(this, infoPort);
    this.infoServer.start();

    this.startTime = System.currentTimeMillis();

    new Thread(this.expireTrackers).start();
    new Thread(this.retireJobs).start();
    new Thread(this.initJobs).start();
  }
	private static void loadApplicationDefaultsFromProperties(String properties, MappedConfiguration<String, String> contributions)
	{
		Properties prop = new Properties();

		try
		{
			prop.load(AppModule.class.getResource(properties).openStream());
		} catch (IOException ioe)
		{
			throw new RuntimeException("Unable to load " + properties, ioe);
		}

		for (Object key : prop.keySet())
		{
			String value = prop.getProperty(key.toString());
			contributions.add(key.toString(), value);
		}
	}
Ejemplo n.º 23
0
 /**
  * Creates a URL from the passed in parameters. It has the following look:<br>
  * webpage?param1=value1&param2=value2......
  *
  * @param webpage - the destination we are headed to
  * @param params - the parameters we append to the Destination, note the order of these parameters
  *     is random
  * @return String - the constructed Destination
  */
 public static String constructURL(String webpage, Properties params) {
   final String METHOD_NAME = "constructURL(): ";
   StringBuffer sb = new StringBuffer();
   sb.append(webpage);
   sb.append("?");
   Iterator iter = params.keySet().iterator();
   while (iter.hasNext()) {
     String key = (String) iter.next();
     String value = (String) params.get(key);
     sb.append(key);
     sb.append("=");
     sb.append(value);
     if (iter.hasNext()) {
       sb.append("&");
     }
   }
   return sb.toString();
 }
  public static void main(String args[]) {
    String file = System.getProperty("user.dir") + "/src/StaticLimits.properties";
    Properties props =
        new Properties() {
          private final Map<Object, Object> linkMap = new LinkedHashMap<>();

          @Override
          public int size() {
            return linkMap.size();
          }

          @Override
          public synchronized Object put(Object key, Object value) {
            return linkMap.put(key, value);
          }

          @Override
          public synchronized Object get(Object key) {
            return linkMap.get(key);
          }

          @Override
          public synchronized boolean containsKey(Object key) {
            return linkMap.containsKey(key);
          }

          @Override
          public Set<Object> keySet() {
            return linkMap.keySet();
          }
        };

    try {
      props.load(new FileInputStream(file));
    } catch (IOException e) {
      e.printStackTrace();
    }

    Iterator<Object> iterator = props.keySet().iterator();

    while (iterator.hasNext()) {
      System.out.println(iterator.next());
    }
  }
Ejemplo n.º 25
0
 public Map<String, String> getProperties() {
   assertIsFile();
   Properties properties = new Properties();
   try {
     FileInputStream inStream = new FileInputStream(this);
     try {
       properties.load(inStream);
     } finally {
       inStream.close();
     }
   } catch (IOException e) {
     throw new RuntimeException(e);
   }
   Map<String, String> map = new HashMap<String, String>();
   for (Object key : properties.keySet()) {
     map.put(key.toString(), properties.getProperty(key.toString()));
   }
   return map;
 }
Ejemplo n.º 26
0
  protected void addPropertiesWithPrefix(
      Properties properties, String prefix, Properties suffixProperties) {
    if (properties != null) {
      if (prefix != null) {
        if (suffixProperties != null) {
          Set<Object> keys = suffixProperties.keySet();
          if (keys != null) {
            for (Object key : keys) {
              String k = key.toString();
              String v = suffixProperties.getProperty(k);

              String pk = prefix + k;
              properties.put(pk, v);
            }
          }
        }
      }
    }
  }
Ejemplo n.º 27
0
 /**
  * Puts all the properties with keys starting with the provided <tt>prefix</tt>.
  *
  * @param prefix The prefix to filter property key by
  * @param properties The properties to put
  * @return The builder
  */
 public Builder putProperties(String prefix, Properties properties, String[] ignorePrefixes) {
   for (Object key1 : properties.keySet()) {
     String key = (String) key1;
     String value = properties.getProperty(key);
     if (key.startsWith(prefix)) {
       boolean ignore = false;
       for (String ignorePrefix : ignorePrefixes) {
         if (key.startsWith(ignorePrefix)) {
           ignore = true;
           break;
         }
       }
       if (!ignore) {
         map.put(key.substring(prefix.length()), value);
       }
     }
   }
   return this;
 }
Ejemplo n.º 28
0
 public Map<File, Boolean> getSavedFpPaths() {
   Map<File, Boolean> savedFileList = new HashMap<>();
   try {
     Properties prop = getProperties();
     prop.keySet()
         .stream()
         .filter(propName -> !propName.equals(AUTOLOAD))
         .forEach(
             path -> {
               String pathString = path.toString();
               savedFileList.put(
                   new File(pathString), Boolean.valueOf(prop.getProperty(pathString)));
             });
   } catch (Exception Ex) {
     Logger.getLogger(FManager.class.getName())
         .log(Level.SEVERE, "FManager was not able to load fps");
   }
   return savedFileList;
 }
  @Override
  public void execute(Properties props) {
    super.execute(props);

    HashMap<String, Object> jsonObj = new HashMap<String, Object>();
    for (Object k : props.keySet()) {
      String key = (String) k;
      String value = props.getProperty(key);
      jsonObj.put(key, value);
    }

    try {
      File runFile = new File(root, "run.json");
      JSONEncoder encoder = new JSONEncoder();
      BufferedWriter writer = new BufferedWriter(new FileWriter(runFile));
      encoder.encode(jsonObj, writer);
      writer.close();
    } catch (Exception exp) {
      throw new IllegalArgumentException("Unable to save run properties in root folder.");
    }
  }
Ejemplo n.º 30
0
  /**
   * Processes the given runtime arguments, using the specified properties list as default. All
   * arguments which could not be matched will be returned.
   *
   * <p>Arguments are expected to either take the form
   *
   * <pre>-<paramName> <paramValue></pre>
   *
   * or
   *
   * <pre>-<paramName>=<paramValue></pre>
   *
   * @param properties a list of default values, may be null.
   * @param arguments the list of arguments to process.
   * @return the list of unmatched runtime arguments.
   * @throws ParameterValueException If one of the parameter values was illegal.
   */
  public Collection<String> processArguments(final Properties properties, final String... arguments)
      throws ParameterValueException {
    final LinkedList<String> unmatchedArguments = new LinkedList<String>();
    if (properties != null) {
      /* Process the property file */
      for (Object o : properties.keySet()) {
        final String s = (String) o;
        final ApplicationParameter param = getParameter(s);
        if (param == null) continue;
        param.setValueAsString(properties.getProperty(s));
      }
    }

    /* Process the runtime arguments */
    for (int i = 0; i < arguments.length; i++) {
      final String s = arguments[i];
      /* Check if this argument should be processed or passed down to the application */
      if (!s.startsWith("-")) unmatchedArguments.add(s);
      else {
        final boolean directAssignment = s.contains("=");
        final String key = directAssignment ? s.substring(1, s.indexOf('=')) : s.substring(1);
        final ApplicationParameter parameter = _parameterKeyMap.get(key);
        if (parameter == null) {
          unmatchedArguments.add(s);
          continue;
        }

        final String value;
        if (parameter.getType() == ApplicationParameter.Type.BOOLEAN)
          value = directAssignment ? s.substring(s.indexOf('=') + 1, s.length()) : "true";
        else
          value = directAssignment ? s.substring(s.indexOf('=') + 1, s.length()) : arguments[++i];

        parameter.setValueAsString(value);
        parameter.setPresent(true);
      }
    }

    return unmatchedArguments;
  }