Example usage for java.util Properties entrySet

List of usage examples for java.util Properties entrySet

Introduction

In this page you can find the example usage for java.util Properties entrySet.

Prototype

@Override
    public Set<Map.Entry<Object, Object>> entrySet() 

Source Link

Usage

From source file:hsa.awp.common.naming.DirectoryTest.java

/**
 * This procedure reads <code>fieldMapping</code> from the properties file
 * and reverses it. This is needed because the properties file is in the
 * format [fieldname]=[ldapname] (more convenient to configure) but we need
 * them in format [ldapname]=[fieldname].
 *
 * @param propertyFile - The properties file to read from.
 *//*from  w  w  w .  j  av a 2s . c o  m*/
private void setupFieldMapping(String propertyFile) {
    // loading the properties file in a temporary object
    Properties tmpProps = new Properties();
    try {
        InputStream in = ClassLoader.getSystemResourceAsStream(propertyFile);
        if (in == null) {
            throw new ConfigurationException("PorpertyFile " + propertyFile + " is not in CLASSPATH");
        }
        tmpProps.load(in);
    } catch (IOException e) {
        throw new ConfigurationException("Could not read configuration file: " + propertyFile, e);
    }

    // now we reverse the properties
    mapping = new Properties();
    for (Entry<Object, Object> currentEntry : tmpProps.entrySet()) {
        mapping.put(currentEntry.getValue(), currentEntry.getKey());
    }
}

From source file:edu.cornell.med.icb.goby.alignments.AlignmentWriterImpl.java

public void setStatistics(final Properties statistics) {
    for (final Map.Entry<Object, Object> statistic : statistics.entrySet()) {
        putStatistic(statistic.getKey().toString(), statistic.getValue().toString());
    }/*from   w  w  w .  ja v  a2s  .  c o m*/
}

From source file:com.smartitengineering.util.bean.guice.GuiceUtil.java

private GuiceUtil(Properties properties) {
    String contextNameProp = properties.getProperty(CONTEXT_NAME_PROP);
    if (StringUtils.isBlank(contextNameProp)) {
        throw new IllegalStateException("Bean factory context name can not be blank");
    }//from ww w  .  j a v  a2 s  . c  om
    contextNames = contextNameProp.split(",");
    ignoreMissingDependency = Boolean.parseBoolean(properties.getProperty(IGNORE_MISSING_DEP_PROP));
    final String[] moduleStrs;
    List<String> moduleConfigs = new ArrayList<String>();
    for (Entry<Object, Object> entry : properties.entrySet()) {
        if (entry.getKey().toString().startsWith(MODULES_LIST_PROP)) {
            moduleConfigs.add(entry.getValue().toString());
        }
    }
    moduleStrs = new String[moduleConfigs.size()];
    moduleConfigs.toArray(moduleStrs);
    modules = new List[moduleStrs.length];
    int index = 0;
    for (String modulesStr : moduleStrs) {
        if (StringUtils.isBlank(modulesStr)) {
            throw new IllegalStateException("Modules must be specified in a comma separated list!");
        }
        String[] moduleClassNames = modulesStr.split(",");
        List<Module> moduleSet = new ArrayList<Module>(moduleClassNames.length);
        for (String moduleClassName : moduleClassNames) {
            final Class clazz;
            try {
                clazz = Class.forName(StringUtils.trim(moduleClassName), true,
                        Thread.currentThread().getContextClassLoader());
            } catch (ClassNotFoundException ex) {
                throw new IllegalStateException(ex);
            }
            if (!Module.class.isAssignableFrom(clazz)) {
                throw new IllegalArgumentException("Specified class not instance of Module");
            }
            Class<? extends Module> moduleClass = clazz;
            boolean foundConstructor = false;
            try {
                Constructor<? extends Module> defaultContructor = moduleClass.getConstructor();
                moduleSet.add(defaultContructor.newInstance());
                foundConstructor = true;
            } catch (InstantiationException ex) {
                throw new IllegalStateException(ex);
            } catch (IllegalAccessException ex) {
                throw new IllegalStateException(ex);
            } catch (InvocationTargetException ex) {
                throw new IllegalStateException(ex);
            } catch (NoSuchMethodException ex) {
            } catch (SecurityException ex) {
            }
            if (!foundConstructor) {
                try {
                    Constructor<? extends Module> defaultContructor = moduleClass
                            .getConstructor(Properties.class);
                    moduleSet.add(defaultContructor.newInstance(properties));
                    foundConstructor = true;
                } catch (InstantiationException ex) {
                    throw new IllegalStateException(ex);
                } catch (IllegalAccessException ex) {
                    throw new IllegalStateException(ex);
                } catch (InvocationTargetException ex) {
                    throw new IllegalStateException(ex);
                } catch (NoSuchMethodException ex) {
                } catch (SecurityException ex) {
                }
            }
            if (!foundConstructor) {
                throw new IllegalStateException(
                        "No supported contructors found - no args and with a properties obj!");
            }
        }
        modules[index++] = moduleSet;
    }
}

From source file:edu.amc.sakai.user.SimpleLdapAttributeMapper.java

/**
 * Straightforward {@link LdapUserData} to 
 * {@link org.sakaiproject.user.api.UserEdit} field-to-field mapping, including
 * properties.//w ww  . j a  v a2s.co  m
 */
public void mapUserDataOntoUserEdit(LdapUserData userData, UserEdit userEdit) {

    if (M_log.isDebugEnabled()) {
        M_log.debug("mapUserDataOntoUserEdit(): [userData = " + userData + "]");
    }

    userEdit.setEid(userData.getEid());
    userEdit.setFirstName(userData.getFirstName());
    userEdit.setLastName(userData.getLastName());
    userEdit.setEmail(userData.getEmail());
    userEdit.setType(userData.getType());
    Properties srcProps = userData.getProperties();
    ResourceProperties tgtProps = userEdit.getProperties();
    for (Entry srcProp : srcProps.entrySet()) {
        tgtProps.addProperty((String) srcProp.getKey(), (String) srcProp.getValue());
    }

}

From source file:org.dcm4che3.tool.unvscp.UnvSCP.java

private static void configureRemoteConnections(UnvSCP main, CommandLine cl) throws Exception {
    String file = cl.getOptionValue("ae-config");
    if (file == null) {
        file = "resource:ae.properties";
        UnvSCP.isDynamicAEList = true;//  w  ww .  ja  v a 2 s  .c  o  m
    }
    Properties aeConfig = CLIUtils.loadProperties(file, null);
    for (Map.Entry<Object, Object> entry : aeConfig.entrySet()) {
        String aet = (String) entry.getKey();
        String value = (String) entry.getValue();
        try {
            main.addRemoteConnection(aet, UnvSCP.createAllowedConnection(value));
        } catch (Exception e) {
            throw new IllegalArgumentException("Invalid entry in " + file + ": " + aet + "=" + value);
        }
    }
}

From source file:net.sf.jabb.util.db.impl.DbcpDataSourceProvider.java

public DataSource createDataSource(String source, String config) {
    String[] cfgs = config.split(PropertiesLoader.DELIMITERS, 2);
    if (cfgs.length != 2) {
        log.warn("Wrong configuration format for '" + source + "' : " + config);
        return null;
    }//from   www .ja  v  a  2 s .c  om

    DataSource ds = null;

    try {
        DirectDataSourceConfiguration lowerConfig = new DirectDataSourceConfiguration(cfgs[0]);
        Class.forName(lowerConfig.getDriverClassName());

        Properties props = propLoader.load(cfgs[1]);
        Properties connProps = lowerConfig.getConnectionProperties();
        props.put("username", connProps.get("user"));
        connProps.remove("user");
        props.put("password", connProps.get("password"));
        connProps.remove("password");
        props.put("url", lowerConfig.getUrl());
        props.put("driverClassName", lowerConfig.getDriverClassName());

        StringBuilder sb = new StringBuilder();
        String oldConnProp = props.getProperty("connectionProperties");
        if (oldConnProp != null) {
            sb.append(oldConnProp.trim());
        }
        for (Map.Entry<Object, Object> p : connProps.entrySet()) {
            if (sb.length() > 0 && sb.charAt(sb.length() - 1) != ';') {
                sb.append(';');
            }
            sb.append(p.getKey().toString());
            sb.append('=');
            sb.append(p.getValue().toString());
        }
        props.put("connectionProperties", sb.toString());

        ds = BasicDataSourceFactory.createDataSource(props);

    } catch (InvalidPropertiesFormatException e) {
        log.warn(
                "Wrong configuration properties file format for '" + source + "' with configuration: " + config,
                e);
    } catch (IOException e) {
        log.warn("Error loading configuration file for '" + source + "' with configuration: " + config, e);
    } catch (ClassNotFoundException e) {
        log.warn("Driver class not found for '" + source + "' with configuration: " + config, e);
    } catch (Exception e) {
        log.warn("Error creating data source for '" + source + "' with configuration: " + config, e);
    }

    return ds;
}

From source file:com.bstek.dorado.idesupport.StandaloneRuleSetExporter.java

private void loadConfigureProperties(ConfigureStore configureStore, ResourceLoader resourceLoader,
        String configureLocation, boolean silence) throws IOException {
    // ??/* w  w w .j av a  2 s .c om*/
    ConsoleUtils.outputLoadingInfo("Loading configure from [" + configureLocation + "]...");
    if (StringUtils.isNotEmpty(configureLocation)) {
        Resource resource = resourceLoader.getResource(getRealResourcePath(configureLocation));
        if (!resource.exists()) {
            if (silence) {
                logger.warn("Can not found resource [" + configureLocation + "].");
                return;
            } else {
                throw new IOException("Can not found resource [" + configureLocation + "].");
            }
        }
        InputStream in = resource.getInputStream();
        Properties properties = new Properties();
        try {
            properties.load(in);
        } finally {
            in.close();
        }

        ExpressionHandler expressionHandler = new DefaultExpressionHandler() {
            @Override
            public JexlContext getJexlContext() {
                JexlContext elContext = new MapContext();
                elContext.set("env", System.getenv());
                return elContext;
            }
        };

        for (Map.Entry<?, ?> entry : properties.entrySet()) {
            String text = (String) entry.getValue();
            Object value = text;
            if (StringUtils.isNotEmpty(text)) {
                Expression expression = expressionHandler.compile(text);
                if (expression != null) {
                    value = expression.evaluate();
                }
            }
            configureStore.set((String) entry.getKey(), value);
        }
    }
}

From source file:org.apache.ode.utils.HierarchicalProperties.java

private Map<String, String> collectAliases(Properties props, File file) {
    // gather all aliases
    Map<String, String> nsByAlias = new HashMap<String, String>();

    // replace env variable by their values and collect namespace aliases
    for (Iterator it = props.entrySet().iterator(); it.hasNext();) {
        Map.Entry e = (Map.Entry) it.next();
        String key = (String) e.getKey();
        String value = (String) e.getValue();

        if (key.startsWith("alias.")) {
            // we found an namespace alias
            final String alias = key.substring("alias.".length(), key.length());
            if (log.isDebugEnabled())
                log.debug("Alias found: " + alias + " -> " + value);
            if (nsByAlias.containsKey(alias) && value.equals(nsByAlias.get(alias)))
                throw new RuntimeException(
                        "Same alias used twice for 2 different namespaces! file=" + file + ", alias=" + alias);
            nsByAlias.put(alias, value);
            // remove the pair from the Properties
            it.remove();//from www  . j a  v  a 2 s.  c  om
        }
    }
    return nsByAlias;
}

From source file:org.paxml.bean.PropertiesTag.java

/**
 * {@inheritDoc}// w w  w.ja v  a2  s. co  m
 */
@Override
protected Object doInvoke(Context context) throws Exception {
    final String id = getId(context);
    if (StringUtils.isNotBlank(id) && getParent() instanceof ConstTag) {
        throw new PaxmlRuntimeException(
                "The 'id' attribute cannot be given to a <" + TAG_NAME + "> tag if it is under a data tag.");
    }

    Properties props = loadProperties(context);

    if (props.size() <= 0) {
        if (log.isWarnEnabled()) {
            log.warn("Properties has no content loaded: " + context.getStack().getFirst());
        }
    }
    if (StringUtils.isBlank(id)) {
        final boolean group = AbstractTagFactory.isUnderConst(this);
        if (group) {
            return new PropertiesObjectTree(props);
        } else {
            Context c = context.getCurrentEntityContext();
            // flatten the properties
            for (Map.Entry<Object, Object> entry : props.entrySet()) {
                String key = entry.getKey().toString();
                c.setConst(key, null, entry.getValue(), true);
                c.addPropertyConstId(key);
            }
            return null;
        }
    } else {
        context.getCurrentEntityContext().addPropertyConstId(id);
        // always group it here
        return new PropertiesObjectTree(props);

    }

}

From source file:edu.kit.dama.dataworkflow.util.DataWorkflowHelper.java

/**
 * Schedule the staging process(es) for the data needed by the provided
 * task. The process contains the following points:
 * <ul>/*w w w .  j ava2  s. co  m*/
 * <li>Creation of the task base path including data_in, data_out, working
 * and temp directories.</li>
 * <li>Obtaining selected data organization views of digital objects to
 * stage.</li>
 * <li>Schedule downloads for the content of each digital object.</li>
 * <li>Create symbolic links of the first-level content (all nodes directly
 * below 'root') of each view into 'data_in'. Existing files will be
 * skipped.</li>
 * </ul>
 * As soon as the staging for all digital objects is done, the symbolic
 * links in the data_in directory should point the valid data located inside
 * the different staging locations.
 *
 * @param pTask The task for which the staging should be scheduled.
 *
 * @return A properties object containing the object-transferId mapping.
 * This mapping should be stored in the DataWorkflowTask in order to be able
 * to check the data staging process.
 *
 * @throws StagingPreparationException if anything fails.
 */
public static Properties scheduleStaging(DataWorkflowTask pTask) throws StagingPreparationException {
    Properties objectDownloadMap = new Properties();
    IAuthorizationContext ctx = getTaskContext(pTask);
    File taskBasePath;
    try {
        taskBasePath = getStagingBasePath(pTask);
    } catch (IOException ex) {
        throw new StagingPreparationException("Staging preparation failed.", ex);
    }
    LOGGER.debug("Checking task base path {}", taskBasePath);
    if (taskBasePath.exists()) {
        LOGGER.debug("Task base path at " + taskBasePath + " already exists.");
    } else {
        LOGGER.debug("Task base path does not exist. Creating directory strucute {}", taskBasePath);
        if (!taskBasePath.mkdirs()) {
            throw new StagingPreparationException("Failed to create task base path at " + taskBasePath);
        }
        LOGGER.debug("Task base path structure successfully created.");
    }

    File inputDir = getTaskInputDirectory(taskBasePath);
    File outputDir = getTaskOutputDirectory(taskBasePath);
    File tempDir = getTaskTempDirectory(taskBasePath);
    File workingDir = getTaskWorkingDirectory(taskBasePath);
    LOGGER.debug("Creating directories:");
    LOGGER.debug(" - Input: {}", inputDir);
    LOGGER.debug(" - Output: {}", outputDir);
    LOGGER.debug(" - Working: {}", workingDir);
    LOGGER.debug(" - Temp: {}", tempDir);

    LOGGER.debug("Obtaining object-view list for DataWorkflow task {}", pTask.getId());
    Properties objectViewMap = null;

    try {
        objectViewMap = pTask.getObjectViewMapAsObject();
    } catch (IOException ex) {
        throw new StagingPreparationException(
                "Failed to deserialize object-view list from task " + pTask.getId());
    }

    try {
        TransferClientProperties props = new TransferClientProperties();
        String accessPointId = pTask.getExecutionEnvironment().getStagingAccessPointId();
        AbstractStagingAccessPoint accessPoint = StagingConfigurationManager.getSingleton()
                .getAccessPointById(accessPointId);
        LOGGER.debug("Adding staging acccess point id {} to TransferClientProperties.", accessPointId);
        props.setStagingAccessPointId(accessPointId);
        String mail = getContact(pTask).getEmail();
        LOGGER.debug("Adding contact mail {} to TransferClientProperties.", mail);
        props.setReceiverMail(mail);
        Set<Entry<Object, Object>> entries = objectViewMap.entrySet();

        LOGGER.debug("Scheduling download for {} objects in object-view map", entries.size());
        for (Entry<Object, Object> entry : entries) {
            String objectId = (String) entry.getKey();
            String viewId = (String) entry.getValue();
            DigitalObjectId doid = new DigitalObjectId(objectId);
            IFileTree tree = DataOrganizationServiceLocal.getSingleton().loadFileTree(doid, viewId, ctx);
            LOGGER.debug("Scheduling download for object {} and view {}", objectId, viewId);
            DownloadInformation downloadInfo = DownloadInformationServiceLocal.getSingleton()
                    .scheduleDownload(doid, tree, props, ctx);
            LOGGER.debug("Putting transfer id {} for object {} to object-transfer list.", downloadInfo.getId(),
                    objectId);
            objectDownloadMap.put(doid.getStringRepresentation(), Long.toString(downloadInfo.getId()));

            List<? extends IDataOrganizationNode> firstLevelNodes = tree.getRootNode().getChildren();
            LOGGER.debug("Creating links for {} first level data organization nodes", firstLevelNodes.size());
            for (IDataOrganizationNode node : firstLevelNodes) {
                File linkedFile = new File(inputDir + File.separator + node.getName());
                LOGGER.debug("Creating link for file {}", linkedFile);
                if (linkedFile.exists()) {
                    LOGGER.error("File link " + linkedFile
                            + " already exists. Skipping link creation but processing might fail.");
                } else {
                    LOGGER.debug("Obtaining data path from download information");
                    File dataPath = accessPoint.getLocalPathForUrl(downloadInfo.getDataFolderUrl(), ctx);
                    LOGGER.debug("Obtained data path is '{}'. Creating symbolic link to input dir at '{}'",
                            dataPath, linkedFile);
                    SystemUtils.createSymbolicLink(new File(dataPath, node.getName()), linkedFile);
                    LOGGER.debug("Link successfully created.");
                }
            }
            LOGGER.debug("Staging of object {} for task {} successfully scheduled.", objectId, pTask.getId());
        }
        LOGGER.debug("Scheduling of all objects for task {} successfully finished.", pTask.getId());
    } catch (IOException | EntityNotFoundException | TransferPreparationException ex) {
        //Failed to create link/view not found/transfer preparation has failed
        throw new StagingPreparationException(
                "Failed to prepare task directory structure for task " + pTask.getId(), ex);
    }
    return objectDownloadMap;
}