org.ini4j.Ini Java Examples

The following examples show how to use org.ini4j.Ini. You can vote up the ones you like or vote down the ones you don't like, and go to the original project or source file by following the links above each example. You may check out the related API usage on the sidebar.
Example #1
Source File: IniModuleConfigParser.java    From nuls-v2 with MIT License 7 votes vote down vote up
@Override
public Map<String, Map<String,ConfigurationLoader.ConfigItem>> parse(String configFile,InputStream inputStream) throws Exception {
    Config cfg = new Config();
    cfg.setMultiSection(true);
    Ini ini = new Ini();
    ini.setConfig(cfg);
    ini.load(inputStream);
    Map<String,Map<String,ConfigurationLoader.ConfigItem>> res = new HashMap<>(ini.size());
    ini.values().forEach(s-> {
        Map<String,ConfigurationLoader.ConfigItem> domainValues = new HashMap<>(s.size());
        s.forEach((key, value) -> domainValues.put(key, new ConfigurationLoader.ConfigItem(configFile, value)));
        res.put(s.getName(),domainValues);
    });
    Log.debug("{},加载配置:{}",configFile,res);
    return res;
}
 
Example #2
Source File: HgConfigFiles.java    From netbeans with Apache License 2.0 6 votes vote down vote up
private void storeIni(Ini ini, String iniFile) {
    assert initException == null;
    BufferedOutputStream bos = null;
    try {
        String filePath;
        if (dir != null) {
            filePath = dir.getAbsolutePath() + File.separator + HG_REPO_DIR + File.separator + iniFile; // NOI18N 
        } else {
            filePath =  getUserConfigPath() + iniFile;
        }
        File file = FileUtil.normalizeFile(new File(filePath));
        file.getParentFile().mkdirs();
        ini.store(bos = new BufferedOutputStream(new FileOutputStream(file)));
    } catch (IOException ex) {
        Mercurial.LOG.log(Level.INFO, null, ex);
    } finally {
        if (bos != null) {
            try {
                bos.close();
            } catch (IOException ex) {
                Mercurial.LOG.log(Level.INFO, null, ex);
            }
        }
    }
}
 
Example #3
Source File: AutoHelper.java    From jolie with GNU Lesser General Public License v2.1 6 votes vote down vote up
public static String getLocationFromIni( String iniLocation )
	throws IOException {
	// Format: "/Section/Key:URL_to_ini"
	String[] ss = iniLocation.split( ":", 2 );
	assertIOException( ss.length < 2, "invalid ini location; the format is /Section/Key:URL_to_ini" );

	String[] iniPath = ss[ 0 ].split( "/", 3 );
	assertIOException( iniPath.length < 3, "path to ini content is not well-formed; the format is /Section/Key" );

	URL iniURL = new URL( ss[ 1 ] );

	try( Reader reader = new InputStreamReader( iniURL.openStream() ) ) {
		Ini ini = new Ini( reader );

		Ini.Section section = ini.get( iniPath[ 1 ] );
		assertIOException( section == null, "could not find section " + iniPath[ 1 ] + " in ini" );

		String retLocation = section.get( iniPath[ 2 ] );
		assertIOException( retLocation == null,
			"could not find key " + iniPath[ 2 ] + " in section " + iniPath[ 1 ] + " in ini" );

		return retLocation;
	}
}
 
Example #4
Source File: WifImporter.java    From Jabit with Apache License 2.0 6 votes vote down vote up
public WifImporter(BitmessageContext ctx, InputStream in, Pubkey.Feature... features) throws IOException {
    this.ctx = ctx;

    Ini ini = new Ini();
    ini.load(in);

    for (Entry<String, Profile.Section> entry : ini.entrySet()) {
        if (!entry.getKey().startsWith("BM-"))
            continue;

        Profile.Section section = entry.getValue();
        BitmessageAddress address = Factory.createIdentityFromPrivateKey(
            entry.getKey(),
            getSecret(section.get("privsigningkey")),
            getSecret(section.get("privencryptionkey")),
            Long.parseLong(section.get("noncetrialsperbyte")),
            Long.parseLong(section.get("payloadlengthextrabytes")),
            Pubkey.Feature.bitfield(features)
        );
        if (section.containsKey("chan")) {
            address.setChan(Boolean.parseBoolean(section.get("chan")));
        }
        address.setAlias(section.get("label"));
        identities.add(address);
    }
}
 
Example #5
Source File: SvnConfigFiles.java    From netbeans with Apache License 2.0 6 votes vote down vote up
private boolean setSSLCert(RepositoryConnection rc, Ini.Section nbGlobalSection) {
    if(rc == null) {
        return false;
    }
    String certFile = rc.getCertFile();
    if(certFile == null || certFile.equals("")) {
        return false;
    }
    char[] certPasswordChars = rc.getCertPassword();
    String certPassword = certPasswordChars == null ? "" : new String(certPasswordChars); //NOI18N
    if(certPassword.equals("")) { // NOI18N
        return false;
    }
    nbGlobalSection.put("ssl-client-cert-file", certFile);
    if (!DO_NOT_SAVE_PASSPHRASE) {
        nbGlobalSection.put("ssl-client-cert-password", certPassword);
        return true;
    }
    return false;
}
 
Example #6
Source File: AuditConfigCommandIntegrationTest.java    From buck with Apache License 2.0 6 votes vote down vote up
@Test
public void testConfigAuditEntireConfig() throws IOException {
  ProjectWorkspace workspace =
      TestDataHelper.createProjectWorkspaceForScenario(this, "audit_config", tmp);
  workspace.setUp();

  ProcessResult result = workspace.runBuckCommand("audit", "config");

  // Use low level ini parser to build config.
  Ini auditIni = Inis.makeIniParser(true);
  auditIni.load(new StringReader(result.getStdout()));
  // Ini object doesn't really provide a good way to compare 2 ini files.
  // Convert that into immutable map so that we can compare sorted maps instead.
  ImmutableMap.Builder<String, ImmutableMap<String, String>> audit_config =
      ImmutableMap.builder();
  auditIni.forEach(
      (section_name, section) -> {
        ImmutableMap.Builder<String, String> section_builder = ImmutableMap.builder();
        section.forEach((k, v) -> section_builder.put(k, v));
        audit_config.put(section_name, section_builder.build());
      });

  assertEquals(workspace.getConfig().getSectionToEntries(), audit_config.build());
}
 
Example #7
Source File: FromHereCredentialsIniStream.java    From here-aaa-java-sdk with Apache License 2.0 6 votes vote down vote up
static Properties getPropertiesFromIni(InputStream inputStream, String sectionName) throws IOException {
    Ini ini = new Ini();
    try (Reader reader = new InputStreamReader(inputStream, OAuthConstants.UTF_8_CHARSET)) {
        ini.load(reader);
        Ini.Section section = ini.get(sectionName);
        Properties properties = new Properties();
        properties.put(OAuth1ClientCredentialsProvider.FromProperties.TOKEN_ENDPOINT_URL_PROPERTY,
                section.get(OAuth1ClientCredentialsProvider.FromProperties.TOKEN_ENDPOINT_URL_PROPERTY));
        properties.put(OAuth1ClientCredentialsProvider.FromProperties.ACCESS_KEY_ID_PROPERTY,
                section.get(OAuth1ClientCredentialsProvider.FromProperties.ACCESS_KEY_ID_PROPERTY));
        properties.put(OAuth1ClientCredentialsProvider.FromProperties.ACCESS_KEY_SECRET_PROPERTY,
                section.get(OAuth1ClientCredentialsProvider.FromProperties.ACCESS_KEY_SECRET_PROPERTY));
        // scope is optional
        String scope = section.get(OAuth1ClientCredentialsProvider.FromProperties.TOKEN_SCOPE_PROPERTY);
        if (null != scope)
            properties.put(OAuth1ClientCredentialsProvider.FromProperties.TOKEN_SCOPE_PROPERTY, scope);

        return properties;
    }
}
 
Example #8
Source File: SdkIniFileReader.java    From xds-ide with Eclipse Public License 1.0 6 votes vote down vote up
/**
   * @param basePath  the base path to attach to, if relative file name is used
   * @param fileName  the name of the file to be loaded 
   * @param enableMultiOption  the state of multi-option configuration flag  
   */
private Ini loadFile ( String basePath, String fileName
                     , boolean enableMultiOption ) throws Exception 
{
    String full_name = FilenameUtils.concat(basePath, fileName);
    File file = new File(full_name); 
       if (file.exists() && file.isFile()) {
           Ini ini = new Wini();
           Config config = ini.getConfig();
           
           config.setMultiSection(true);
           config.setMultiOption(enableMultiOption);
           config.setGlobalSection(true);
           config.setComment(true);

           ini.setFile(file);
           ini.setComment(COMMENT_LINE_CHARS);
           try(InputStreamReader inputStreamReader = TextEncoding.getInputStreamReader(file)){
           	ini.load(inputStreamReader);
           }
           return ini;
       }
    return null;
}
 
Example #9
Source File: SvnConfigFiles.java    From netbeans with Apache License 2.0 6 votes vote down vote up
/**
 * Merges only sections/keys/values into target which are not already present in source
 * 
 * @param source the source ini file
 * @param target the target ini file in which the values from the source file are going to be merged
 */
private void merge(Ini source, Ini target) {
    for (Iterator<String> itSections = source.keySet().iterator(); itSections.hasNext();) {
        String sectionName = itSections.next();
        Ini.Section sourceSection = source.get( sectionName );
        Ini.Section targetSection = target.get( sectionName );

        if(targetSection == null) {
            targetSection = target.add(sectionName);
        }

        for (Iterator<String> itVariables = sourceSection.keySet().iterator(); itVariables.hasNext();) {
            String key = itVariables.next();

            if(!targetSection.containsKey(key)) {
                targetSection.put(key, sourceSection.get(key));
            }
        }            
    }
}
 
Example #10
Source File: SdkIniFileReader.java    From xds-ide with Eclipse Public License 1.0 6 votes vote down vote up
/**
 * Read sdk.ini file (or file tree with includes) from the given location. 
 * @param xdsHomePath - folder to search sdk.ini file
 */
public SdkIniFileReader(String xdsHomePath) {
	aSdk        = new ArrayList<Sdk>();
	sbErrLog    = new StringBuilder();
	
	try {
	    Ini ini = loadFile(xdsHomePath, MAIN_INI_FILE_NAME, true);
	    if (ini != null) {
            Section global = ini.get(Config.DEFAULT_GLOBAL_SECTION_NAME);
            List<String> imports = global.getAll(IMPORT_PROPERTY);
            if ((imports == null) || imports.isEmpty()) {
                processIniFile(xdsHomePath, MAIN_INI_FILE_NAME);
            } else {
                for (String import_file_name: imports) {
                    processIniFile(xdsHomePath, import_file_name);
                }
            }
	    }
       } catch (Exception e) {
           LogHelper.logError(e);
           aSdk.clear();
           setError(e.getMessage());
       }
	
}
 
Example #11
Source File: SvnConfigFiles.java    From netbeans with Apache License 2.0 6 votes vote down vote up
/**
 * Returns the section from the <b>servers</b> config file used by the Subversion module which 
 * is holding the proxy settings for the given host
 *
 * @param host the host
 * @return the section holding the proxy settings for the given host
 */ 
private Ini.Section getServerGroup(String host) {
    if(host == null || host.equals("")) {                                   // NOI18N
        return null;
    }
    Ini.Section groups = svnServers.get(GROUPS_SECTION);
    if(groups != null) {
        for (Iterator<String> it = groups.keySet().iterator(); it.hasNext();) {
            String key = it.next();
            String value = groups.get(key);
            if(value != null) {     
                value = value.trim();                    
                if(value != null && match(value, host)) {
                    return svnServers.get(key);
                }      
            }
        }
    }
    return null;
}
 
Example #12
Source File: SvnConfigFilesTest.java    From netbeans with Apache License 2.0 6 votes vote down vote up
private void isSubsetOf(String sourceIniPath, String expectedIniPath) throws IOException {
    Ini goldenIni = new Ini(new FileInputStream(expectedIniPath));
    Ini sourceIni = new Ini(new FileInputStream(sourceIniPath));
    for(String key : goldenIni.keySet()) {
        if(!sourceIni.containsKey(key) && goldenIni.get(key).size() > 0) {
            fail("missing section " + key + " in file " + sourceIniPath);
        }

        Section goldenSection = goldenIni.get(key);
        Section sourceSection = sourceIni.get(key);

        for(String name : goldenSection.childrenNames()) {
            if(!sourceSection.containsKey(name)) {
                fail("missing name " + name + " in file " + sourceIniPath + " section [" + name + "]");
            }                
            assertEquals(goldenSection.get(name), sourceSection.get(name));
        }                
    }
}
 
Example #13
Source File: PhotatoConfig.java    From Photato with GNU Affero General Public License v3.0 6 votes vote down vote up
public static void init(String configFile) {
    try {
        Ini ini = new Ini(new File(configFile));
        serverPort = Integer.parseInt(ini.get("global", "serverPort"));
        prefixModeOnly = Boolean.parseBoolean(ini.get("index", "prefixModeOnly"));
        indexFolderName = Boolean.parseBoolean(ini.get("index", "indexFolderName"));
        useParallelPicturesGeneration = Boolean.parseBoolean(ini.get("thumbnail", "useParallelPicturesGeneration"));
        forceExifToolsDownload = Boolean.parseBoolean(ini.get("global", "forceExifToolsDownload"));
        forceExifToolsDownload = Boolean.parseBoolean(ini.get("global", "forceExifToolsDownload"));
        addressElementsCount = Integer.parseInt(ini.get("global", "addressElementsCount"));

        fullScreenPictureQuality = Integer.parseInt(ini.get("fullscreen", "fullScreenPictureQuality"));
        maxFullScreenPictureWitdh = Integer.parseInt(ini.get("fullscreen", "maxFullScreenPictureWitdh"));
        maxFullScreenPictureHeight = Integer.parseInt(ini.get("fullscreen", "maxFullScreenPictureHeight"));
        thumbnailHeight = Integer.parseInt(ini.get("thumbnail", "thumbnailHeight"));
        thumbnailQuality = Integer.parseInt(ini.get("thumbnail", "thumbnailQuality"));

    } catch (Exception ex) {
        throw new IllegalArgumentException("Incorrect config file : " + configFile + " - " + ex);
    }
}
 
Example #14
Source File: HgConfigFiles.java    From netbeans with Apache License 2.0 6 votes vote down vote up
/**
 * Merges only sections/keys/values into target which are not already present in source
 * 
 * @param source the source ini file
 * @param target the target ini file in which the values from the source file are going to be merged
 */
private void merge(Ini source, Ini target) {
    for (Iterator<String> itSections = source.keySet().iterator(); itSections.hasNext();) {
        String sectionName = itSections.next();
        Ini.Section sourceSection = source.get( sectionName );
        Ini.Section targetSection = target.get( sectionName );

        if(targetSection == null) {
            targetSection = target.add(sectionName);
        }

        for (Iterator<String> itVariables = sourceSection.keySet().iterator(); itVariables.hasNext();) {
            String key = itVariables.next();

            if(!targetSection.containsKey(key)) {
                targetSection.put(key, sourceSection.get(key));
            }
        }            
    }
}
 
Example #15
Source File: TestDataHelper.java    From buck with Apache License 2.0 6 votes vote down vote up
public static void overrideBuckconfig(
    ProjectWorkspace projectWorkspace,
    Map<String, ? extends Map<String, String>> buckconfigOverrides)
    throws IOException {
  String config = projectWorkspace.getFileContents(".buckconfig");
  Ini ini = Inis.makeIniParser(true);
  ini.load(new StringReader(config));
  for (Map.Entry<String, ? extends Map<String, String>> section :
      buckconfigOverrides.entrySet()) {
    for (Map.Entry<String, String> entry : section.getValue().entrySet()) {
      ini.put(section.getKey(), entry.getKey(), entry.getValue());
    }
  }
  StringWriter writer = new StringWriter();
  ini.store(writer);
  Files.write(projectWorkspace.getPath(".buckconfig"), writer.toString().getBytes(UTF_8));
}
 
Example #16
Source File: Inis.java    From buck with Apache License 2.0 5 votes vote down vote up
@VisibleForTesting
public static Ini makeIniParser(boolean enable_includes) {
  Ini ini = new Ini();
  Config config = new Config();
  config.setEscape(false);
  config.setEscapeNewline(true);
  config.setMultiOption(false);
  config.setInclude(enable_includes);
  ini.setConfig(config);
  return ini;
}
 
Example #17
Source File: GitTortoise.java    From git-as-svn with GNU General Public License v2.0 5 votes vote down vote up
@NotNull
static GitTortoise parseConfig(@NotNull InputStream stream) throws IOException {
  @SuppressWarnings("MismatchedQueryAndUpdateOfCollection") final Ini ini = new Ini(stream);
  final Map<String, String> result = new HashMap<>();
  for (Map.Entry<String, Profile.Section> sectionEntry : ini.entrySet()) {
    for (Map.Entry<String, String> configEntry : sectionEntry.getValue().entrySet()) {
      String value = configEntry.getValue();
      if (value.startsWith("\"") && value.endsWith("\"")) {
        value = value.substring(1, value.length() - 1);
      }
      result.put(sectionEntry.getKey() + ":" + configEntry.getKey(), value);
    }
  }
  return new GitTortoise(result.isEmpty() ? Collections.emptyMap() : result);
}
 
Example #18
Source File: GtConfig.java    From GitToolBox with Apache License 2.0 5 votes vote down vote up
@NotNull
public static GtConfig load(@NotNull File configFile) {
  if (!configFile.exists()) {
    LOG.info("No .git/config file at " + configFile.getPath());
    return EMPTY;
  } else {
    Ini ini = new Ini();
    ini.getConfig().setMultiOption(true);
    ini.getConfig().setTree(false);

    try {
      ini.load(configFile);
    } catch (IOException exception) {
      LOG.warn(new RepoStateException("Couldn\'t load .git/config file at " + configFile.getPath(), exception));
      return EMPTY;
    }
    ImmutableSet.Builder<String> svnRemotes = ImmutableSet.builder();
    for (Entry<String, Section> section : ini.entrySet()) {
      Matcher matcher = SVN_REMOTE_SECTION.matcher(section.getKey());
      if (matcher.matches()) {
        String name = matcher.group(1);
        svnRemotes.add(name);
      }
    }
    return new GtConfig(svnRemotes);
  }
}
 
Example #19
Source File: CreateClustersSample.java    From director-sdk with Apache License 2.0 5 votes vote down vote up
/**
 * Create a new deployment (Cloudera Manager) with data from the configuration file.
 */
private String createDeployment(ApiClient client, String environmentName, Ini config)
    throws ApiException {
  String clusterName = config.get("cluster", "name");

  Map<String, String> cmConfigs = new HashMap<String, String>();
  cmConfigs.put("enable_api_debug", "true");

  Map<String, Map<String, String>> overrides = new HashMap<String, Map<String, String>>();
  overrides.put("CLOUDERA_MANAGER", cmConfigs);

  DeploymentTemplate template = DeploymentTemplate.builder()
      .name(clusterName + " Deployment")
      .managerVirtualInstance(
          createVirtualInstanceWithRandomId(config, "manager"))
      .port(7180)
      .enableEnterpriseTrial(true)
      .configs(overrides)
      .build();

  DeploymentsApi api = new DeploymentsApi(client);
  try {
    api.create(environmentName, template);

  } catch (ApiException e) {
    if (e.getCode() == 409 /* conflict */) {
      System.out.println("Warning: a deployment with the same name already exists");
    } else {
      throw e;
    }
  }

  System.out.printf("Deployments: %s%n", api.list(environmentName));
  return template.getName();
}
 
Example #20
Source File: CreateClustersSample.java    From director-sdk with Apache License 2.0 5 votes vote down vote up
/**
 * Create a new virtual instance object with a random ID and a template from the configuration file.
 */
private VirtualInstance createVirtualInstanceWithRandomId(Ini config, String templateName) {
  return VirtualInstance.builder()
      .id(UUID.randomUUID().toString())
      .template(createInstanceTemplate(config, templateName))
      .build();
}
 
Example #21
Source File: CreateClustersSample.java    From director-sdk with Apache License 2.0 5 votes vote down vote up
/**
 * Create an instance template with data from the configuration file.
 */
private InstanceTemplate createInstanceTemplate(Ini config, String templateName) {
  Map<String, String> configs = new HashMap<String, String>();
  configs.put("subnetId", config.get("instance", "subnetId"));
  configs.put("securityGroupsIds", config.get("instance", "securityGroupId"));
  configs.put("instanceNamePrefix", config.get("instance", "namePrefix"));

  return InstanceTemplate.builder()
      .name(templateName)
      .image(config.get("instance", "image"))
      .type(config.get("instance", "type"))
      .config(configs)
      .build();
}
 
Example #22
Source File: SdkIniFileReader.java    From xds-ide with Eclipse Public License 1.0 5 votes vote down vote up
private void processToolSections(Sdk sdk, Ini ini) {
    List<Section> tools = ini.getAll(TOOL_SECTION_NAME);
    if (tools != null) {
        for (Section toolSection : tools) {
               SdkTool tool = parseTool(sdk, toolSection);
               if (tool.isValid()) {
                   sdk.addTool(tool);
               } else {
                   LogHelper.logError(tool.getErrorMessage());
               }
        }
    }
}
 
Example #23
Source File: PersistentTokenDescriptor.java    From xds-ide with Eclipse Public License 1.0 5 votes vote down vote up
public void preferenciesFromIni(Ini ini) {
    String s = ini.get(Config.DEFAULT_GLOBAL_SECTION_NAME, styleId);
    if (s != null) {
        styleWhenEnabled = Integer.parseInt(s);
    } else {
        styleWhenEnabled = getDefaultStyle();
    }
    
    s = ini.get(Config.DEFAULT_GLOBAL_SECTION_NAME, disabledId);
    if (s != null) {
        isDisabled = (Integer.parseInt(s) != 0);
    } else {
        isDisabled = false;
    }
    
    s = ini.get(Config.DEFAULT_GLOBAL_SECTION_NAME, colorId);
    if (s != null) {
        rgbWhenEnabled = StringConverter.asRGB(s, getDefaultRgb());
    } else {
        rgbWhenEnabled = getDefaultRgb();
    }
    
    if (isDisabled && iTokens != null) {
        PersistentTokenDescriptor pt = iTokens.getDefaultColoring();
        TextAttributeDescriptor ta = pt.getTextAttribute();
        if (ta != null) {
            setTextAttribute(new TextAttributeDescriptor(ta.getForeground(), null, ta.getStyle()));
        }
    } else {
    	setTextAttribute(new TextAttributeDescriptor(rgbWhenEnabled, null, styleWhenEnabled));
    }
}
 
Example #24
Source File: IniTest.java    From buck with Apache License 2.0 5 votes vote down vote up
@Test
public void testSecondaryLoadOverridesOriginalDefs() throws IOException {
  Ini ini = Inis.makeIniParser(false);
  Reader originalInput =
      new StringReader(
          Joiner.on("\n")
              .join(
                  "[alias]",
                  "  buck = //src/com/facebook/buck/cli:cli",
                  "[cache]",
                  "  mode = dir"));
  Reader overrideInput =
      new StringReader(
          Joiner.on("\n")
              .join(
                  "[alias]",
                  "  test_util = //test/com/facebook/buck/util:util",
                  "[cache]",
                  "  mode ="));
  ini.load(originalInput);
  ini.load(overrideInput);

  Section aliasSection = ini.get("alias");
  assertEquals(
      "Should be the union of the two [alias] sections.",
      ImmutableMap.of(
          "buck", "//src/com/facebook/buck/cli:cli",
          "test_util", "//test/com/facebook/buck/util:util"),
      aliasSection);

  Section cacheSection = ini.get("cache");
  assertEquals(
      "Values from overrideInput should supercede those from originalInput, as appropriate.",
      ImmutableMap.of("mode", ""),
      cacheSection);
}
 
Example #25
Source File: ConfigLoader.java    From nuls with MIT License 5 votes vote down vote up
public static IniEntity loadIni(String fileName) throws IOException {
    Config cfg = new Config();
    URL url = ConfigLoader.class.getClassLoader().getResource(fileName);
    cfg.setMultiSection(true);
    Ini ini = new Ini();
    ini.setConfig(cfg);
    ini.load(url);
    return new IniEntity(ini);
}
 
Example #26
Source File: Utilities.java    From NoraUi with GNU Affero General Public License v3.0 5 votes vote down vote up
/**
 * This method read a application descriptor file and return a {@link org.openqa.selenium.By} object (xpath, id, link ...).
 *
 * @param applicationKey
 *            Name of application. Each application has its fair description file.
 * @param code
 *            Name of element on the web Page.
 * @param args
 *            list of description (xpath, id, link ...) for code.
 * @return a {@link org.openqa.selenium.By} object (xpath, id, link ...)
 */
public static By getLocator(String applicationKey, String code, Object... args) {
    By locator = null;
    log.debug("getLocator with this application key : {}", applicationKey);
    log.debug("getLocator with this code : {}", code);
    log.debug("getLocator with this locator file : {}", Context.iniFiles.get(applicationKey));
    final Ini ini = Context.iniFiles.get(applicationKey);
    final Map<String, String> section = ini.get(code);
    if (section != null) {
        final Entry<String, String> entry = section.entrySet().iterator().next();
        final String selector = String.format(entry.getValue(), args);
        if ("css".equals(entry.getKey())) {
            locator = By.cssSelector(selector);
        } else if ("link".equals(entry.getKey())) {
            locator = By.linkText(selector);
        } else if ("id".equals(entry.getKey())) {
            locator = By.id(selector);
        } else if ("name".equals(entry.getKey())) {
            locator = By.name(selector);
        } else if ("xpath".equals(entry.getKey())) {
            locator = By.xpath(selector);
        } else if ("class".equals(entry.getKey())) {
            locator = By.className(selector);
        } else {
            Assert.fail(entry.getKey() + " NOT implemented!");
        }
    } else {
        Assert.fail("[" + code + "] NOT implemented in ini file " + Context.iniFiles.get(applicationKey) + "!");
    }
    return locator;
}
 
Example #27
Source File: Utilities.java    From NoraUi with GNU Affero General Public License v3.0 5 votes vote down vote up
/**
 * @param applicationKey
 *            is key of application
 * @param code
 *            is key of selector (CAUTION: if you use any % char. {@link String#format(String, Object...)})
 * @param args
 *            is list of args ({@link String#format(String, Object...)})
 * @return the selector
 */
public static String getSelectorValue(String applicationKey, String code, Object... args) {
    String selector = "";
    log.debug("getLocator with this application key : {}", applicationKey);
    log.debug("getLocator with this locator file : {}", Context.iniFiles.get(applicationKey));
    final Ini ini = Context.iniFiles.get(applicationKey);

    final Map<String, String> section = ini.get(code);
    if (section != null) {
        final Entry<String, String> entry = section.entrySet().iterator().next();
        selector = String.format(entry.getValue(), args);
    }
    return selector;
}
 
Example #28
Source File: HgConfigFiles.java    From netbeans with Apache License 2.0 5 votes vote down vote up
/**
 * Loads Repository configuration file  <repo>/.hg/hgrc on all platforms
 * */
private Ini loadRepoHgrcFile(File dir) {
    String filePath = dir.getAbsolutePath() + File.separator + HG_REPO_DIR + File.separator + HG_RC_FILE; // NOI18N
    configFileName = HG_RC_FILE;
    File file = FileUtil.normalizeFile(new File(filePath));
    Ini system = null;
    system = createIni(file);
    
    if(system == null) {
        system = createIni();
        Mercurial.LOG.log(Level.FINE, "Could not load the file " + filePath + ". Falling back on hg defaults."); // NOI18N
    }
    return system;
}
 
Example #29
Source File: HgConfigFiles.java    From netbeans with Apache License 2.0 5 votes vote down vote up
/**
 * Loads user and system configuration files 
 * The settings are loaded and merged together in the folowing order:
 * <ol>
 *  <li> The per-user configuration file, Unix: ~/.hgrc, Windows: %USERPROFILE%\Mercurial.ini
 *  <li> The system-wide file, Unix: /etc/mercurial/hgrc, Windows: Mercurial_Install\Mercurial.ini
 * </ol> 
 *
 * @param fileName the file name
 * @return an Ini instance holding the configuration file. 
 */       
private Ini loadSystemAndGlobalFile(String[] fileNames) {
    // config files from userdir
    Ini system = null;
    for (String userConfigFileName : fileNames) {
        String filePath = getUserConfigPath() + userConfigFileName;
        File file = FileUtil.normalizeFile(new File(filePath));
        system = createIni(file);
        if (system != null) {
            configFileName = userConfigFileName;
            break;
        }
        Mercurial.LOG.log(Level.INFO, "Could not load the file {0}.", filePath); //NOI18N
    }
    
    if(system == null) {
        configFileName = fileNames[0];
        system = createIni();
        Mercurial.LOG.log(Level.INFO, "Could not load the user config file. Falling back on hg defaults."); //NOI18N
    }
    
    Ini global = null;
    File gFile = FileUtil.normalizeFile(new File(getGlobalConfigPath() + File.separator + fileNames[0]));
    global = createIni(gFile);   // NOI18N

    if(global != null) {
        merge(global, system);
    }                
    return system;
}
 
Example #30
Source File: Inis.java    From buck with Apache License 2.0 5 votes vote down vote up
@VisibleForTesting
public static ImmutableMap<String, ImmutableMap<String, String>> read(Reader reader)
    throws IOException {
  Ini ini = makeIniParser(/*enable_includes=*/ false);
  ini.load(reader);
  return toMap(ini);
}