Example usage for java.util Properties keys

List of usage examples for java.util Properties keys

Introduction

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

Prototype

@Override
    public Enumeration<Object> keys() 

Source Link

Usage

From source file:com.aurel.track.admin.customize.localize.LocalizeBL.java

/**
 * Update the resources based on the properties
 * @param properties/*from   w w w.ja v a  2  s .c o m*/
 * @param strLocale
 * @param overwrite whether to overwrite the edited resources
 * @param withPrimaryKey whether the used to be BoxResources are imported or the ApplicationResources 
 */
static synchronized void uploadResources(Properties properties, String strLocale, boolean overwrite,
        boolean withPrimaryKey, boolean initBoxResources) {
    List<TLocalizedResourcesBean> resourceBeans = getResourcesForLocale(strLocale, withPrimaryKey);
    SortedMap<String, List<TLocalizedResourcesBean>> existingLabels = new TreeMap<String, List<TLocalizedResourcesBean>>();
    for (TLocalizedResourcesBean localizedResourcesBean : resourceBeans) {
        String key = localizedResourcesBean.getFieldName();
        if (withPrimaryKey) {
            if (key.startsWith(LocalizationKeyPrefixes.FIELD_LABEL_KEY_PREFIX)
                    || key.startsWith(LocalizationKeyPrefixes.FIELD_TOOLTIP_KEY_PREFIX)) {
                key += ".";
            }
            key = key + localizedResourcesBean.getPrimaryKeyValue();
        }
        List<TLocalizedResourcesBean> localizedResources = existingLabels.get(key);
        if (localizedResources == null) {
            localizedResources = new LinkedList<TLocalizedResourcesBean>();
            existingLabels.put(key, localizedResources);
        }
        localizedResources.add(localizedResourcesBean);
    }
    Enumeration propertyNames = properties.keys();
    Connection connection = null;
    try {
        connection = Transaction.begin();
        connection.setAutoCommit(false);
        while (propertyNames.hasMoreElements()) {
            String key = (String) propertyNames.nextElement();
            String localizedText = LocalizeBL.correctString(properties.getProperty(key));
            Integer primaryKey = null;
            String fieldName = null;
            if (withPrimaryKey) {
                int primaryKeyIndex = key.lastIndexOf(".");
                if (primaryKeyIndex != -1) {
                    try {
                        primaryKey = Integer.valueOf(key.substring(primaryKeyIndex + 1));
                    } catch (Exception e) {
                        LOGGER.warn("The last part after . can't be converted to integer " + e.getMessage());
                        LOGGER.debug(ExceptionUtils.getStackTrace(e));
                    }
                    fieldName = key.substring(0, primaryKeyIndex + 1);
                    if (fieldName.startsWith(LocalizationKeyPrefixes.FIELD_LABEL_KEY_PREFIX)
                            || fieldName.startsWith(LocalizationKeyPrefixes.FIELD_TOOLTIP_KEY_PREFIX)) {
                        //do not have . at the end (legacy)
                        fieldName = fieldName.substring(0, fieldName.length() - 1);
                    }
                }
            } else {
                fieldName = key;
            }
            List<TLocalizedResourcesBean> localizedResources = existingLabels.get(key);
            if (localizedResources != null && localizedResources.size() > 1) {
                //remove all duplicates (as a consequence of previous erroneous imports)
                localizedResourcesDAO.deleteLocalizedResourcesForFieldNameAndKeyAndLocale(fieldName, primaryKey,
                        strLocale);
                localizedResources = null;
            }
            if (localizedResources == null || localizedResources.isEmpty()) {
                //new resource
                TLocalizedResourcesBean localizedResourcesBean = new TLocalizedResourcesBean();
                localizedResourcesBean.setFieldName(fieldName);
                localizedResourcesBean.setPrimaryKeyValue(primaryKey);
                localizedResourcesBean.setLocalizedText(localizedText);
                localizedResourcesBean.setLocale(strLocale);
                localizedResourcesDAO.insert(localizedResourcesBean);
            } else {
                //existing resource
                if (localizedResources.size() == 1) {
                    TLocalizedResourcesBean localizedResourcesBean = localizedResources.get(0);
                    if (EqualUtils.notEqual(localizedText, localizedResourcesBean
                            .getLocalizedText()) /*&& locale.equals(localizedResourcesBean.getLocale())*/) {
                        //text changed locally by the customer
                        boolean textChanged = localizedResourcesBean.getTextChangedBool();
                        if ((textChanged == false && !initBoxResources) || (textChanged && overwrite)) {
                            localizedResourcesBean.setLocalizedText(localizedText);
                            localizedResourcesDAO.save(localizedResourcesBean);
                        }
                    } else {
                    }
                }
            }
        }
        Transaction.commit(connection);
        if (!connection.isClosed()) {
            connection.close();
        }
    } catch (Exception e) {
        LOGGER.error("Problem filling locales: " + e.getMessage());
        LOGGER.debug(ExceptionUtils.getStackTrace(e));
        if (connection != null) {
            Transaction.safeRollback(connection);
        }
    }
    //delete the existing ones not found in the properties
    Locale locale;
    if (strLocale != null) {
        locale = LocaleHandler.getLocaleFromString(strLocale);
    } else {
        locale = Locale.getDefault();
    }
    if (withPrimaryKey) {
        //not sure that all is needed but to be sure we do not miss imported localizations
        LookupContainer.resetLocalizedLookupMap(SystemFields.INTEGER_ISSUETYPE, locale);
        LookupContainer.resetLocalizedLookupMap(SystemFields.INTEGER_STATE, locale);
        LookupContainer.resetLocalizedLookupMap(SystemFields.INTEGER_PRIORITY, locale);
        LookupContainer.resetLocalizedLookupMap(SystemFields.INTEGER_SEVERITY, locale);
    }
    ResourceBundle.clearCache();
}

From source file:org.soaplab.services.storage.FileStorage.java

/**************************************************************************
 *
 **************************************************************************/
public Map<String, Object> getResults(String jobId) throws SoaplabException {
    File jobDir = getJobDir(jobId);
    Properties jobProps = loadJobProperties(jobDir);
    int prefixLen = JOB_PROP_RESULT_PREFIX.length();
    Map<String, Object> results = new HashMap<String, Object>();
    for (Enumeration en = jobProps.keys(); en.hasMoreElements();) {
        String key = (String) en.nextElement();
        if (key.startsWith(JOB_PROP_RESULT_PREFIX)) {
            String type = jobProps.getProperty(key);
            String resultName = key.substring(prefixLen);
            Object result = getResult(jobDir, resultName, type);
            if (result != null)
                results.put(resultName, result);
        }/*w ww .  j a  v  a2 s.c  om*/
    }
    return results;
}

From source file:plugspud.PluginManager.java

/**
 * Load a plugins.properties property sheet into separate property sheets,
 * one for each plugin/*from   ww  w  . j  a  va  2 s .c o  m*/
 * 
 * @param url
 *            location of plugins.properties resource
 * @return <code>HashMap</code> of properties
 */
public HashMap loadPluginProperties(URL url) throws PluginException {

    HashMap props = new HashMap();
    InputStream in = null;
    try {
        in = url.openStream();
        Properties p = new Properties();
        p.load(in);
        for (Enumeration e = p.keys(); e.hasMoreElements();) {
            String key = (String) e.nextElement();
            int idx = key.indexOf('.');

            if (idx == -1)
                throw new PluginException("Invalid property name in " + url.toExternalForm() + ". Must be "
                        + "<pluginName>.<property>=<value>");

            String name = key.substring(0, idx);
            String property = key.substring(idx + 1);

            if (property.length() == 0)
                throw new PluginException("Invalid property name in " + url.toExternalForm() + ". Must be "
                        + "<pluginName>.<property>=<value>");

            Properties h = (Properties) props.get(name);

            if (h == null) {
                h = new Properties();
                props.put(name, h);
            }

            h.put(property, p.getProperty(key));
        }
    } catch (IOException ioe) {
        throw new PluginException("Could not load plugins from " + url.toExternalForm(), ioe);
    } finally {
        PluginUtil.closeStream(in);
    }
    return props;
}

From source file:org.soaplab.services.storage.FileStorage.java

/**************************************************************************
 *
 *************************************************************************/
@SuppressWarnings("unchecked")
public Map<String, String>[] getResultsInfo(String jobId) throws SoaplabException {

    File jobDir = getJobDir(jobId);
    Properties jobProps = loadJobProperties(jobDir);
    int prefixLen = JOB_PROP_RESULT_PREFIX.length();

    ArrayList<Map<String, String>> infos = new ArrayList<Map<String, String>>();

    for (Enumeration en = jobProps.keys(); en.hasMoreElements();) {
        String key = (String) en.nextElement();
        if (key.startsWith(JOB_PROP_RESULT_PREFIX)) {
            Map<String, String> anInfo = getResultInfo(jobDir, key.substring(prefixLen),
                    jobProps.getProperty(key));
            if (anInfo != null)
                infos.add(anInfo);/*from  ww w  .  jav a 2  s. com*/
        }
    }
    return infos.toArray(new Map[] {});
}

From source file:org.pegadi.client.ApplicationLauncher.java

void prefsMenuItem_actionPerformed(ActionEvent e) {
    PreferencesDialog d = new PreferencesDialog(this, prefs);
    d.setLocationRelativeTo(this);
    d.setVisible(true);//from www.j av a 2s  .  c  o m
    if (d.okResult()) {
        Properties changed = d.getChangedPreferences();

        Enumeration en = changed.keys();
        while (en.hasMoreElements()) {
            String pkey = en.nextElement().toString();
            String pvalue = changed.getProperty(pkey);
            prefs.put(pkey, pvalue);
            try {
                LoginContext.server.savePreference(PREF_DOMAIN, pkey, pvalue, LoginContext.sessionKey);
            } catch (Exception ex) {
                log.error("Can't save preference '{}' with value '{}'", new Object[] { pkey, pvalue, ex });
            }

            if (pkey.equals(PREF_LOCALE)) {
                setLocale(pvalue);
                pack();
            } else if (pkey.equals(PREF_THEME)) {
                setTheme(pvalue);
            }
        }
    }
}

From source file:org.webdavaccess.LocalFileSystemStorage.java

private Properties getPropertiesFor(String uri) {
    uri = normalize(uri);//from   w w w . j  av a2s  .  co m
    File file = getPropertiesFile(uri);
    if (file == null || !file.exists()) {
        return null;
    }
    InputStream in = null;
    Properties persisted = new Properties();
    try {
        in = new FileInputStream(file);
        persisted.loadFromXML(in);
    } catch (Exception e) {
        log.warn("Failed to get properties from cache for " + uri);
        return null;
    } finally {
        if (in != null)
            try {
                in.close();
            } catch (Exception e) {
            }
    }
    Enumeration en = persisted.keys();
    Properties props = new Properties();
    while (en.hasMoreElements()) {
        String key = (String) en.nextElement();
        if (isResourceProperty(uri, key)) {
            String newKey = getPropertyKey(uri, key);
            props.setProperty(newKey, persisted.getProperty(key));
        }
    }
    return (props.size() == 0) ? null : props;
}

From source file:net.iiit.siel.analysis.lang.LanguageIdentifier.java

/**
 * Constructs a new Language Identifier.
 *
 * @param conf the conf/* w w w  .j a v  a2  s.  c om*/
 */
private LanguageIdentifier(Configuration conf) {

    // Gets ngram sizes to take into account from the Nutch Config
    minLength = conf.getInt("lang.ngram.min.length", NGramProfile.DEFAULT_MIN_NGRAM_LENGTH);
    maxLength = conf.getInt("lang.ngram.max.length", NGramProfile.DEFAULT_MAX_NGRAM_LENGTH);
    // Ensure the min and max values are in an acceptale range
    // (ie min >= DEFAULT_MIN_NGRAM_LENGTH and max <=
    // DEFAULT_MAX_NGRAM_LENGTH)
    maxLength = Math.min(maxLength, NGramProfile.ABSOLUTE_MAX_NGRAM_LENGTH);
    maxLength = Math.max(maxLength, NGramProfile.ABSOLUTE_MIN_NGRAM_LENGTH);
    minLength = Math.max(minLength, NGramProfile.ABSOLUTE_MIN_NGRAM_LENGTH);
    minLength = Math.min(minLength, maxLength);

    // Gets the value of the maximum size of data to analyze
    analyzeLength = conf.getInt("lang.analyze.max.length", DEFAULT_ANALYSIS_LENGTH);
    System.out.println("Analysis Length is " + analyzeLength);
    String resourceDir = conf.get("resources.indianlangidentifier.dir");
    System.out.println("Resource Directory is " + resourceDir);
    Properties p = new Properties();
    try {

        p.load(new FileInputStream(new File(resourceDir + File.separator + "LanguageMappings.properties")));

        Enumeration alllanguages = p.keys();

        if (LOG.isInfoEnabled()) {
            LOG.info(new StringBuffer().append("Language identifier configuration [").append(minLength)
                    .append("-").append(maxLength).append("/").append(analyzeLength).append("]").toString());
        }

        StringBuffer list = new StringBuffer("Language identifier plugin supports:");
        HashMap tmpIdx = new HashMap();
        while (alllanguages.hasMoreElements()) {
            String lang = (String) (alllanguages.nextElement());

            InputStream is = new FileInputStream(
                    new File(resourceDir + File.separator + lang + "." + NGramProfile.FILE_EXTENSION));

            if (is != null) {
                NGramProfile profile = new NGramProfile(lang, minLength, maxLength);
                try {
                    profile.load(is);
                    languages.add(profile);
                    supportedLanguages.add(lang);
                    List ngrams = profile.getSorted();
                    for (int i = 0; i < ngrams.size(); i++) {
                        NGramEntry entry = (NGramEntry) ngrams.get(i);
                        List registered = (List) tmpIdx.get(entry);
                        if (registered == null) {
                            registered = new ArrayList();
                            tmpIdx.put(entry, registered);
                        }
                        registered.add(entry);
                        entry.setProfile(profile);
                    }
                    list.append(" " + lang + "(" + ngrams.size() + ")");
                    is.close();
                } catch (IOException e1) {
                    if (LOG.isFatalEnabled()) {
                        LOG.fatal(e1.toString());
                    }
                }
            }
        }
        // transform all ngrams lists to arrays for performances
        Iterator keys = tmpIdx.keySet().iterator();
        while (keys.hasNext()) {
            NGramEntry entry = (NGramEntry) keys.next();
            List l = (List) tmpIdx.get(entry);
            if (l != null) {
                NGramEntry[] array = (NGramEntry[]) l.toArray(new NGramEntry[l.size()]);
                ngramsIdx.put(entry.getSeq(), array);
            }
        }
        if (LOG.isInfoEnabled()) {
            LOG.info(list.toString());
        }
        // Create the suspect profile
        suspect = new NGramProfile("suspect", minLength, maxLength);
        System.out.println("Suspect is " + suspect.getName());
    } catch (Exception e) {
        if (LOG.isFatalEnabled()) {
            LOG.fatal(e.toString());
        }
        e.printStackTrace();
    }
}

From source file:org.pentaho.reporting.ui.datasources.jdbc.ui.JdbcDataSourceDialog.java

private SQLReportDataFactory createDataFactory(final JdbcConnectionDefinition connectionDefinition) {
    final ConnectionProvider connectionProvider;
    if (connectionDefinition instanceof JndiConnectionDefinition) {
        final JndiConnectionDefinition jcd = (JndiConnectionDefinition) connectionDefinition;
        final JndiConnectionProvider provider = new JndiConnectionProvider();
        provider.setConnectionPath(jcd.getJndiName());
        provider.setUsername(jcd.getUsername());
        provider.setPassword(jcd.getPassword());
        connectionProvider = provider;//from  w  ww  .j a va 2  s.co m
    } else if (connectionDefinition instanceof DriverConnectionDefinition) {
        final DriverConnectionDefinition dcd = (DriverConnectionDefinition) connectionDefinition;
        final DriverConnectionProvider provider = new DriverConnectionProvider();
        provider.setDriver(dcd.getDriverClass());
        provider.setUrl(dcd.getConnectionString());

        final Properties properties = dcd.getProperties();
        final Enumeration keys = properties.keys();
        while (keys.hasMoreElements()) {
            final String key = (String) keys.nextElement();
            provider.setProperty(key, properties.getProperty(key));
        }
        connectionProvider = provider;
    } else {
        return null;
    }

    final SQLReportDataFactory newDataFactory = new SQLReportDataFactory(connectionProvider);
    newDataFactory.setPasswordField(dialogModel.getJdbcPasswordField());
    newDataFactory.setUserField(dialogModel.getJdbcUserField());
    newDataFactory.setGlobalScriptLanguage(getGlobalScriptingLanguage());
    if (StringUtils.isEmpty(globalScriptTextArea.getText()) == false) {
        newDataFactory.setGlobalScript(globalScriptTextArea.getText());
    }

    final DataSetComboBoxModel<String> queries = dialogModel.getQueries();
    for (int i = 0; i < queries.getSize(); i++) {
        final DataSetQuery<String> query = queries.getQuery(i);
        newDataFactory.setQuery(query.getQueryName(), query.getQuery(), query.getScriptLanguage(),
                query.getScript());
    }
    return newDataFactory;
}

From source file:com.yoncabt.ebr.executor.jasper.JasperReport.java

@Override
public void exportTo(ReportRequest request, ReportOutputFormat outputFormat, EBRConnection connection,
        ReportDefinition reportDefinition) throws ReportException, IOException {
    Map<String, Object> params = request.getReportParams();
    String locale = request.getLocale();
    String uuid = request.getUuid();

    // nce genel parametreleri dolduralm. logo_path falan gibi
    EBRConf.INSTANCE.getMap().entrySet().stream().forEach((es) -> {
        String key = es.getKey();
        if (key.startsWith("report.jrproperties.")) {
            key = key.substring("report.jrproperties.".length());
            String value = es.getValue();
            DefaultJasperReportsContext.getInstance().setProperty(key, value);
        }/*from  www  .  j  a  v a 2  s  . c om*/
        if (key.startsWith("report.params.")) {
            key = key.substring("report.params.".length());
            String value = es.getValue();
            params.put(key, value);
        }
    });
    params.put("__extension", outputFormat.name());
    params.put("__start_time", System.currentTimeMillis());
    params.put(JRParameter.REPORT_LOCALE, LocaleUtils.toLocale(locale));

    File jrxmlFile = reportDefinition.getFile();
    //alttaki satr tehlikeli olabilir mi ?
    String resourceFileName = "messages_" + locale + ".properties";
    try {
        File resourceFile = new File(jrxmlFile.getParentFile(), resourceFileName);
        Properties properties = new Properties();
        try (FileInputStream fis = new FileInputStream(resourceFile)) {
            properties.load(fis);
        }
        ResourceBundle rb = new ResourceBundle() {

            @Override
            protected Object handleGetObject(String key) {
                return properties.get(key);
            }

            @Override
            public Enumeration<String> getKeys() {
                return (Enumeration<String>) ((Enumeration<?>) properties.keys());
            }
        };
        // FIXME yerelletime dosyalar buradan okunacak
        params.put(JRParameter.REPORT_RESOURCE_BUNDLE, rb);
    } catch (FileNotFoundException e) {
        logManager.info(resourceFileName + " file does not found!");
    }

    String virtDir = EBRConf.INSTANCE.getValue(EBRParams.REPORTS_VIRTUALIZER_DIRECTORY, "/tmp/ebr/virtualizer");
    int maxSize = EBRConf.INSTANCE.getValue(EBRParams.REPORTS_VIRTUALIZER_MAXSIZE, Integer.MAX_VALUE);
    JRAbstractLRUVirtualizer virtualizer = new JRFileVirtualizer(maxSize, virtDir);
    params.put(JRParameter.REPORT_VIRTUALIZER, virtualizer);

    net.sf.jasperreports.engine.JasperReport jasperReport;
    try {
        jasperReport = (net.sf.jasperreports.engine.JasperReport) JRLoader
                .loadObject(com.yoncabt.ebr.executor.jasper.JasperReport.compileIfRequired(jrxmlFile));
    } catch (JRException ex) {
        throw new ReportException(ex);
    }
    for (JRParameter param : jasperReport.getParameters()) {
        Object val = params.get(param.getName());
        if (val == null) {
            continue;
        }
        params.put(param.getName(), Convert.to(val, param.getValueClass()));
    }
    reportLogger.logReport(request, outputFormat, new ByteArrayInputStream(new byte[0]));

    JasperPrint jasperPrint;
    try {
        jasperPrint = JasperFillManager.fillReport(jasperReport,
                /*jasper parametreleri deitiriyor*/ new HashMap<>(params), connection);
    } catch (JRException ex) {
        throw new ReportException(ex);
    }

    File outBase = new File(EBRConf.INSTANCE.getValue(EBRParams.REPORTS_OUT_PATH, "/usr/local/reports/out"));
    outBase.mkdirs();
    File exportReportFile = new File(outBase, uuid + "." + outputFormat.name());
    Exporter exporter;
    ExporterOutput output;
    switch (outputFormat) {
    case pdf:
        exporter = new JRPdfExporter();
        output = new SimpleOutputStreamExporterOutput(exportReportFile);
        break;
    case html:
        exporter = new HtmlExporter();
        output = new SimpleHtmlExporterOutput(exportReportFile);
        break;
    case xls:
        exporter = new JRXlsExporter();
        output = new SimpleOutputStreamExporterOutput(exportReportFile);
        break;
    case xlsx:
        exporter = new JRXlsxExporter();
        output = new SimpleOutputStreamExporterOutput(exportReportFile);
        break;
    case rtf:
        exporter = new JRRtfExporter();
        output = new SimpleWriterExporterOutput(exportReportFile);
        break;
    case csv:
        exporter = new JRCsvExporter();
        output = new SimpleWriterExporterOutput(exportReportFile);
        break;
    case xml:
        exporter = new JRXmlExporter();
        output = new SimpleOutputStreamExporterOutput(exportReportFile);
        break;
    case docx:
        exporter = new JRDocxExporter();
        output = new SimpleOutputStreamExporterOutput(exportReportFile);
        break;
    case odt:
        exporter = new JROdtExporter();
        output = new SimpleOutputStreamExporterOutput(exportReportFile);
        break;
    case ods:
        exporter = new JROdsExporter();
        output = new SimpleOutputStreamExporterOutput(exportReportFile);
        break;
    case jprint:
    case txt:
        exporter = new JRTextExporter();
        output = new SimpleWriterExporterOutput(exportReportFile);
        putTextParams((JRTextExporter) exporter, params, reportDefinition.getTextTemplate());
        break;
    default:
        throw new AssertionError(outputFormat.toString() + " not supported");
    }
    exporter.setExporterInput(new SimpleExporterInput(jasperPrint));

    exporter.setExporterOutput(output);
    try {
        exporter.exportReport();
    } catch (JRException ex) {
        throw new ReportException(ex);
    }
    if (outputFormat.isText() && !"utf-8".equals(reportDefinition.getTextEncoding())) {
        String reportData = FileUtils.readFileToString(exportReportFile, "utf-8");
        if ("ascii".equals(reportDefinition.getTextEncoding())) {
            FileUtils.write(exportReportFile, ASCIIFier.ascii(reportData));
        } else {
            FileUtils.write(exportReportFile, reportData, reportDefinition.getTextEncoding());
        }
    }

    try (FileInputStream fis = new FileInputStream(exportReportFile)) {
        reportLogger.logReport(request, outputFormat, fis);
    }
    exportReportFile.delete();
}

From source file:org.alfresco.reporting.processor.PropertyProcessor.java

/**
 * Given the input string, replace all namespaces where possible. 
 * @param namespace//from  w  w  w.j  av  a  2 s .c  o m
 * @return string whith replaced full namespaces into short namespace definitions
 */
public String replaceNameSpaces(final String namespace) {
    // use regular expressions to do a global replace of the full namespace into the short version.
    Properties p = getNamespaces();
    String returnSpace = namespace;
    //logger.debug("namespaces:" + p);
    Enumeration<Object> keys = p.keys();
    while (keys.hasMoreElements()) {
        String into = (String) keys.nextElement();
        String from = p.getProperty(into);
        returnSpace = returnSpace.replace(from, into);
    }
    returnSpace = returnSpace.replace("-", "_");

    return returnSpace;
}