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:com.bol.crazypigs.HBaseStorage15.java

private JobConf initializeLocalJobConfig(Job job) {
    Properties udfProps = getUDFProperties();
    Configuration jobConf = job.getConfiguration();
    JobConf localConf = new JobConf(jobConf);
    if (udfProps.containsKey(HBASE_CONFIG_SET)) {
        for (Entry<Object, Object> entry : udfProps.entrySet()) {
            localConf.set((String) entry.getKey(), (String) entry.getValue());
        }/*w  w  w  . j  av  a  2 s. c  o m*/
    } else {
        Configuration hbaseConf = HBaseConfiguration.create();
        for (Entry<String, String> entry : hbaseConf) {
            // JobConf may have some conf overriding ones in hbase-site.xml
            // So only copy hbase config not in job config to UDFContext
            // Also avoids copying core-default.xml and core-site.xml
            // props in hbaseConf to UDFContext which would be redundant.
            if (jobConf.get(entry.getKey()) == null) {
                udfProps.setProperty(entry.getKey(), entry.getValue());
                localConf.set(entry.getKey(), entry.getValue());
            }
        }
        udfProps.setProperty(HBASE_CONFIG_SET, "true");
    }
    return localConf;
}

From source file:org.apache.click.service.VelocityTemplateService.java

/**
 * Return the Velocity Engine initialization properties.
 *
 * @return the Velocity Engine initialization properties
 * @throws MalformedURLException if a resource cannot be loaded
 *///w w  w. ja  v  a 2  s. c om
@SuppressWarnings("unchecked")
protected Properties getInitProperties() throws MalformedURLException {

    final Properties velProps = new Properties();

    // Set default velocity runtime properties.

    velProps.setProperty(RuntimeConstants.RESOURCE_LOADER, "webapp, class");
    velProps.setProperty("webapp.resource.loader.class", WebappResourceLoader.class.getName());
    velProps.setProperty("class.resource.loader.class", ClasspathResourceLoader.class.getName());

    if (configService.isProductionMode() || configService.isProfileMode()) {
        velProps.put("webapp.resource.loader.cache", "true");
        velProps.put("webapp.resource.loader.modificationCheckInterval", "0");
        velProps.put("class.resource.loader.cache", "true");
        velProps.put("class.resource.loader.modificationCheckInterval", "0");
        velProps.put("velocimacro.library.autoreload", "false");

    } else {
        velProps.put("webapp.resource.loader.cache", "false");
        velProps.put("class.resource.loader.cache", "false");
        velProps.put("velocimacro.library.autoreload", "true");
    }

    velProps.put(RuntimeConstants.RUNTIME_LOG_LOGSYSTEM_CLASS, LogChuteAdapter.class.getName());

    velProps.put("directive.if.tostring.nullcheck", "false");

    // Use 'macro.vm' exists set it as default VM library
    ServletContext servletContext = configService.getServletContext();
    URL macroURL = servletContext.getResource("/" + MACRO_VM_FILE_NAME);
    if (macroURL != null) {
        velProps.put("velocimacro.library", "/" + MACRO_VM_FILE_NAME);

    } else {
        // Else use '/click/VM_global_library.vm' if available.
        URL globalMacroURL = servletContext.getResource(VM_FILE_PATH);
        if (globalMacroURL != null) {
            velProps.put("velocimacro.library", VM_FILE_PATH);

        } else {
            // Else use '/WEB-INF/classes/macro.vm' if available.
            String webInfMacroPath = "/WEB-INF/classes/macro.vm";
            URL webInfMacroURL = servletContext.getResource(webInfMacroPath);
            if (webInfMacroURL != null) {
                velProps.put("velocimacro.library", webInfMacroPath);
            }
        }
    }

    // Set the character encoding
    String charset = configService.getCharset();
    if (charset != null) {
        velProps.put("input.encoding", charset);
    }

    // Load user velocity properties.
    Properties userProperties = new Properties();

    String filename = DEFAULT_TEMPLATE_PROPS;

    InputStream inputStream = servletContext.getResourceAsStream(filename);

    if (inputStream != null) {
        try {
            userProperties.load(inputStream);

        } catch (IOException ioe) {
            String message = "error loading velocity properties file: " + filename;
            configService.getLogService().error(message, ioe);

        } finally {
            try {
                inputStream.close();
            } catch (IOException ioe) {
                // ignore
            }
        }
    }

    // Add user properties.
    Iterator iterator = userProperties.entrySet().iterator();
    while (iterator.hasNext()) {
        Map.Entry entry = (Map.Entry) iterator.next();

        Object pop = velProps.put(entry.getKey(), entry.getValue());

        LogService logService = configService.getLogService();
        if (pop != null && logService.isDebugEnabled()) {
            String message = "user defined property '" + entry.getKey() + "=" + entry.getValue()
                    + "' replaced default property '" + entry.getKey() + "=" + pop + "'";
            logService.debug(message);
        }
    }

    ConfigService configService = ClickUtils.getConfigService(servletContext);
    LogService logger = configService.getLogService();
    if (logger.isTraceEnabled()) {
        TreeMap sortedPropMap = new TreeMap();

        Iterator i = velProps.entrySet().iterator();
        while (i.hasNext()) {
            Map.Entry entry = (Map.Entry) i.next();
            sortedPropMap.put(entry.getKey(), entry.getValue());
        }

        logger.trace("velocity properties: " + sortedPropMap);
    }

    return velProps;
}

From source file:org.paxml.core.Context.java

/**
 * Add properties to this level of context.
 * /*w ww.  j av a2s  .  c o  m*/
 * @param properties
 *            the properties where string keys will be taken as constants,
 *            object keys will be global internal objects
 */
public void addProperties(Properties properties) {
    if (properties == null) {
        return;
    }
    for (Map.Entry<Object, Object> entry : properties.entrySet()) {
        Object key = entry.getKey();
        if (key instanceof String) {
            addConst((String) key, (String) key, entry.getValue(), true);
        } else {
            setInternalObject(key, entry.getValue(), true);
        }
    }
}

From source file:de.juwimm.cms.Main.java

/**
 * Transfer properties from arguments string to property object 
 * @param prop will contain mail appender log properties
 * @param arguments //from   w ww  .j  av a 2s. c  o  m
 * @return message to be print in log 
 */
private String initMailAppender(Properties prop, String[] arguments) {
    if (arguments == null || arguments.length == 0) {
        return "no mail appender log properties specified";
    }
    String log4jArguments = null;
    for (String argument : arguments) {
        if (argument.contains(LOG4J_PROPERTIES_ARGUMENT)) {
            log4jArguments = argument.replace(LOG4J_PROPERTIES_ARGUMENT + "=", "");
            log4jArguments = log4jArguments.replace("\"", "");
            log4jArguments = log4jArguments.replace(";", "\n");
            break;
        }
    }

    if (log4jArguments == null || log4jArguments.isEmpty()) {
        return "no mail appender log properties specified from server";
    }

    //loads all the log4j properties into Properties object
    //log4jArguments has format "v1=k1\nv2=k2\n ..."
    InputStream is = new ByteArrayInputStream(log4jArguments.getBytes());
    try {
        prop.load(is);
    } catch (IOException e) {
        return "can not load mail appender log properties";
    }
    if (prop.entrySet().size() > 0) {
        prop.setProperty("log4j.appender.email", "org.apache.log4j.net.SMTPAppender");
        prop.setProperty("log4j.appender.email.bufferSize", "3");
        prop.setProperty("log4j.appender.email.layout", "org.apache.log4j.SimpleLayout");
        prop.setProperty("log4j.appender.email.subject", "CQ Richclient Errors");
        prop.setProperty("log4j.rootLogger", "email");
        return "mail appender log properties loaded";
    } else {
        return "no mail appender log properties specified from server";
    }

}

From source file:com.agiletec.ConfigTestUtils.java

protected SimpleNamingContextBuilder createNamingContext() {
    SimpleNamingContextBuilder builder = null;
    try {// www.  j a v a2 s .c o m
        builder = SimpleNamingContextBuilder.emptyActivatedContextBuilder();
        InputStream in = new FileInputStream("target/test/conf/contextTestParams.properties");
        Properties testConfig = new Properties();
        testConfig.load(in);
        in.close();

        builder.bind("java:comp/env/logName", testConfig.getProperty("logName"));
        builder.bind("java:comp/env/logFilePrefix", testConfig.getProperty("logFilePrefix"));
        builder.bind("java:comp/env/logLevel", testConfig.getProperty("logLevel"));
        builder.bind("java:comp/env/logFileSize", testConfig.getProperty("logFileSize"));
        builder.bind("java:comp/env/logFilesCount", testConfig.getProperty("logFilesCount"));

        builder.bind("java:comp/env/configVersion", testConfig.getProperty("configVersion"));

        builder.bind("java:comp/env/applicationBaseURL", testConfig.getProperty("applicationBaseURL"));
        builder.bind("java:comp/env/resourceRootURL", testConfig.getProperty("resourceRootURL"));
        builder.bind("java:comp/env/protectedResourceRootURL",
                testConfig.getProperty("protectedResourceRootURL"));
        builder.bind("java:comp/env/resourceDiskRootFolder", testConfig.getProperty("resourceDiskRootFolder"));
        builder.bind("java:comp/env/protectedResourceDiskRootFolder",
                testConfig.getProperty("protectedResourceDiskRootFolder"));

        builder.bind("java:comp/env/indexDiskRootFolder", testConfig.getProperty("indexDiskRootFolder"));

        Iterator<Entry<Object, Object>> configIter = testConfig.entrySet().iterator();
        while (configIter.hasNext()) {
            Entry<Object, Object> entry = configIter.next();
            builder.bind("java:comp/env/" + (String) entry.getKey(), (String) entry.getValue());
        }

        this.createDatasources(builder, testConfig);
    } catch (Throwable t) {
        t.printStackTrace();
        throw new RuntimeException("Error on creation naming context", t);
    }
    return builder;
}

From source file:com.safi.asterisk.handler.SafletEngine.java

public void updateServiceClasspath() {
    try {/*from  w  ww  .j a va  2s .c o m*/
        URL url = ClassLoader.getSystemResource("wrapper.conf");
        Properties props = new Properties();
        props.load(new FileInputStream(new File(url.toURI())));
        String patt = "^wrapper\\.java\\.classpath\\.[0-9]{1,3}\\s*=%ROOT_DIR%/lib/([a-zA-Z0-9\\.\\-_])*(\\*)?.jar$";
        Pattern pattern = Pattern.compile(patt);
        List<Map.Entry<Object, Object>> cpEntries = new LinkedList<Map.Entry<Object, Object>>();
        for (Map.Entry<Object, Object> entry : props.entrySet()) {
            String key = (String) entry.getKey();
            Matcher matcher = pattern.matcher(key);
            if (matcher.matches()) {
                matcher.group(1);
            }
            if (key.matches(patt)) {
                cpEntries.add(entry);
            }
        }

    } catch (Exception exe) {
        log.error("Couldn't udpate service classpath", exe);
    }
}

From source file:nl.minbzk.dwr.zoeken.enricher.settings.EnricherSettings.java

/**
 * Default constructor./* w ww. ja  v  a2  s .c o  m*/
 * 
 * @param extraProperties
 * @throws Exception
 */
public EnricherSettings(final Properties extraProperties) throws Exception {
    if (StringUtils.hasText(System.getProperty(PROPERTY_LOGLEVEL)))
        ((Logger) LoggerFactory.getLogger(Logger.ROOT_LOGGER_NAME))
                .setLevel(Level.toLevel(System.getProperty(PROPERTY_LOGLEVEL)));

    // Fetch the initial properties

    try {
        InputStream internalStream = getClass().getClassLoader().getResourceAsStream("enricher.properties");

        properties.load(internalStream);

        internalStream.close();

        // Load the external properties as an addition to the internal ones

        if (extraProperties != null)
            for (Entry<Object, Object> extraProperty : extraProperties.entrySet())
                properties.setProperty(extraProperty.getKey().toString(), extraProperty.getValue().toString());
    } catch (IOException e) {
        logger.error("Could not initialize settings from the given properties files", e);
    }

    databaseMatch = properties.getProperty(KEY_ENVELOPE_MATCH_DB).trim();
    encodingMatch = properties.getProperty(KEY_ENVELOPE_MATCH_ENCODING).trim();

    if (properties.containsKey(KEY_PROCESSOR_TIKA_DETECTORS))
        for (String detector : properties.getProperty(KEY_PROCESSOR_TIKA_DETECTORS).split(","))
            tikaDetectors.add(detector.trim());
    if (properties.containsKey(KEY_PROCESSOR_TIKA_PARSERS))
        for (String parser : properties.getProperty(KEY_PROCESSOR_TIKA_PARSERS).split(","))
            tikaParsers.add(parser.trim());

    aciAddUri = properties.getProperty(KEY_GENERATOR_ACI_ADD_URI).trim();
    aciCommitUri = properties.getProperty(KEY_GENERATOR_ACI_COMMIT_URI).trim();
    aciDeleteReferenceUri = properties.getProperty(KEY_GENERATOR_ACI_DELETE_REFERENCE_URI).trim();
    aciDeleteDocIdUri = properties.getProperty(KEY_GENERATOR_ACI_DELETE_DOCID_URI).trim();
    aciUserAgent = properties.getProperty(KEY_GENERATOR_ACI_USER_AGENT).trim();

    solrUri = properties.getProperty(KEY_GENERATOR_SOLR_URI).trim();
    solrCloudUri = properties.getProperty(KEY_GENERATOR_SOLR_CLOUD_URI).trim();
    solrUniqueKeyComposition = properties.getProperty(KEY_GENERATOR_SOLR_UNIQUE_KEY_COMPOSITION).trim();

    elasticSearchUri = properties.getProperty(KEY_GENERATOR_ELASTIC_SEARCH_URI).trim();
    elasticSearchClusterName = properties.getProperty(KEY_GENERATOR_ELASTIC_SEARCH_CLUSTER_NAME).trim();
    elasticSearchUniqueKeyComposition = properties
            .getProperty(KEY_GENERATOR_ELASTIC_SEARCH_UNIQUE_KEY_COMPOSITION).trim();

    if (properties.containsKey(KEY_GENERATOR_DOCUMENTS_PER_UPLOAD))
        documentsPerUpload = new Integer(properties.getProperty(KEY_GENERATOR_DOCUMENTS_PER_UPLOAD));

    if (properties.containsKey(KEY_LANGUAGE_ANALYSIS_THRESHOLD))
        languageAnalysisThreshold = new Integer(properties.getProperty(KEY_LANGUAGE_ANALYSIS_THRESHOLD));

    if (properties.containsKey(KEY_LANGUAGE_ANALYSIS_MAXIMUM_INSTANCES))
        languageAnalysisMaximumInstances = new Integer(
                properties.getProperty(KEY_LANGUAGE_ANALYSIS_MAXIMUM_INSTANCES));
    if (properties.containsKey(KEY_LANGUAGE_ANALYSIS_WAITING_TIMEOUT))
        languageAnalysisWaitingTimeout = new Integer(
                properties.getProperty(KEY_LANGUAGE_ANALYSIS_WAITING_TIMEOUT));

    if (properties.containsKey(KEY_LANGUAGE_DETECTION_PROFILES))
        languageDetectionProfiles = properties.getProperty(KEY_LANGUAGE_DETECTION_PROFILES);

    if (properties.containsKey(KEY_ATTENDER_MEMORY_INDEX_CONFIGURATION))
        attenderMemoryIndexConfiguration = properties.getProperty(KEY_ATTENDER_MEMORY_INDEX_CONFIGURATION);

    if (properties.containsKey(KEY_ENVELOPE_WORD_BREAK_MIN)
            && properties.containsKey(KEY_ENVELOPE_WORD_BREAK_MAX)) {
        wordBreakMin = new Integer(properties.getProperty(KEY_ENVELOPE_WORD_BREAK_MIN));
        wordBreakMax = new Integer(properties.getProperty(KEY_ENVELOPE_WORD_BREAK_MAX));
    }

    for (Entry<Object, Object> property : properties.entrySet()) {
        String name = (String) property.getKey();

        if (name.startsWith(KEY_ENVELOPE_JOB)) {
            String jobName = name.substring(KEY_ENVELOPE_JOB.length() + 1,
                    name.indexOf('.', KEY_ENVELOPE_JOB.length() + 1));

            if (!jobs.containsKey(jobName)) {
                EnricherJob job = new EnricherJob();

                job.setName(jobName);
                job.setProcessedPath(retrieveJobProperty(jobName, KEY_ENVELOPE_JOB_RESULT));

                job.setDatabaseName(retrieveJobProperty(jobName, KEY_ENVELOPE_JOB_DB_NAME));
                job.setDatabaseNamePrerequisitesExpression(
                        retrieveJobProperty(jobName, KEY_ENVELOPE_JOB_DB_NAME_PREREQUISITES));
                job.setDatabaseNameComposition(
                        retrieveJobProperty(jobName, KEY_ENVELOPE_JOB_DB_NAME_COMPOSITION));

                job.setDatabaseType(retrieveJobProperty(jobName, KEY_ENVELOPE_JOB_DB_TYPE));

                job.setGeneratorTypes(StringUtils.tokenizeToStringArray(
                        retrieveJobProperty(jobName, KEY_ENVELOPE_JOB_GENERATOR_TYPE), ",", true, true));
                job.setGeneratorMapping(retrieveJobProperty(jobName, KEY_ENVELOPE_JOB_GENERATOR_MAPPING));

                job.setBoilerpipeExtractor(retrieveJobProperty(jobName, KEY_ENVELOPE_BOILERPIPE_EXTRACTOR));
                job.setBoilerpipeExclusionField(
                        retrieveJobProperty(jobName, KEY_ENVELOPE_BOILERPIPE_EXCLUSION_FIELD));
                job.setBoilerpipeExclusionValues(
                        retrieveJobProperty(jobName, KEY_ENVELOPE_BOILERPIPE_EXCLUSION_VALUES));

                String[] stripTags = StringUtils.tokenizeToStringArray(
                        retrieveJobProperty(jobName, KEY_ENVELOPE_JOB_STRIP_TAGS), ",", true, true);

                job.setStripTags(stripTags != null ? Arrays.asList(stripTags) : new ArrayList<String>());

                job.setFormatDetectionParameter(
                        retrieveJobProperty(jobName, KEY_ENVELOPE_JOB_FORMAT_DETECTION_PARAMETER));
                job.setFormatDetectionDefault(
                        retrieveJobProperty(jobName, KEY_ENVELOPE_JOB_FORMAT_DETECTION_DEFAULT));

                job.setLanguageDetectionParameter(
                        retrieveJobProperty(jobName, KEY_ENVELOPE_JOB_LANGUAGE_DETECTION_PARAMETER));
                job.setLanguageDetectionSupported(
                        retrieveJobProperty(jobName, KEY_ENVELOPE_JOB_LANGUAGE_DETECTION_SUPPORTED));
                job.setLanguageDetectionDefault(
                        retrieveJobProperty(jobName, KEY_ENVELOPE_JOB_LANGUAGE_DETECTION_DEFAULT));

                job.setEntityDetectionLanguages(
                        retrieveJobProperty(jobName, KEY_ENVELOPE_JOB_ENTITY_DETECTION_LANGUAGES));
                job.setEntityDetectionDescriptors(
                        retrieveJobProperty(jobName, KEY_ENVELOPE_JOB_ENTITY_DETECTION_DESCRIPTORS));
                job.setEntityDetectionScanTypes(
                        retrieveJobProperty(jobName, KEY_ENVELOPE_JOB_ENTITY_DETECTION_SCAN_TYPES));
                job.setEntityDetectionFieldPrefix(
                        retrieveJobProperty(jobName, KEY_ENVELOPE_JOB_ENTITY_DETECTION_FIELD_PREFIX));

                job.setGeoSpatialFieldPrefix(
                        retrieveJobProperty(jobName, KEY_ENVELOPE_JOB_GEO_SPATIAL_FIELD_PREFIX));

                job.setTikaResourceKeyPriority(
                        retrieveJobProperty(jobName, KEY_ENVELOPE_JOB_TIKA_RESOURCE_KEY_PRIORITY));

                job.setFieldConverters(deriveFieldConverters(jobName));

                jobs.put(jobName, job);
            }
        }
    }
}

From source file:com.adito.server.DefaultAditoServerFactory.java

private void displaySystemInfo() throws SocketException {

    if (useDevConfig) {
        LOG.warn("Development environment enabled. Do not use this on a production server.");
    }//www . j a v a2 s.co  m

    if (LOG.isInfoEnabled()) {
        LOG.info("Version is " + ContextHolder.getContext().getVersion());
        LOG.info("Java version is " + SystemProperties.get("java.version"));
        LOG.info("Server is installed on " + hostname + "/" + hostAddress);
        LOG.info("Configuration: " + CONF_DIR.getAbsolutePath());
    }

    if (SystemProperties.get("java.vm.name", "").indexOf("GNU") > -1
            || SystemProperties.get("java.vm.name", "").indexOf("libgcj") > -1) {
        System.out.println("********** WARNING **********");
        System.out.println("The system has detected that the Java runtime is GNU/GCJ");
        System.out.println("Adito does not work correctly with this Java runtime");
        System.out.println("you should reconfigure with a different runtime");
        System.out.println("*****************************");

        LOG.warn("********** WARNING **********");
        LOG.warn("The system has detected that the Java runtime is GNU/GCJ");
        LOG.warn("Adito may not work correctly with this Java runtime");
        LOG.warn("you should reconfigure with a different runtime");
        LOG.warn("*****************************");

    }

    Enumeration e = NetworkInterface.getNetworkInterfaces();

    while (e.hasMoreElements()) {
        NetworkInterface netface = (NetworkInterface) e.nextElement();
        if (LOG.isInfoEnabled()) {
            LOG.info("Net interface: " + netface.getName());
        }

        Enumeration e2 = netface.getInetAddresses();

        while (e2.hasMoreElements()) {
            InetAddress ip = (InetAddress) e2.nextElement();
            if (LOG.isInfoEnabled()) {
                LOG.info("IP address: " + ip.toString());
            }
        }
    }

    if (LOG.isInfoEnabled()) {
        LOG.info("System properties follow:");
    }
    Properties sysProps = System.getProperties();
    for (Map.Entry entry : sysProps.entrySet()) {
        int idx = 0;
        String val = (String) entry.getValue();
        while (true) {
            if (entry.getKey().equals("java.class.path")) {
                StringTokenizer t = new StringTokenizer(entry.getValue().toString(),
                        SystemProperties.get("path.separator", ","));
                while (t.hasMoreTokens()) {
                    String s = t.nextToken();
                    if (LOG.isInfoEnabled()) {
                        LOG.info("java.class.path=" + s);
                    }
                }
                break;
            } else {
                if ((val.length() - idx) > 256) {
                    if (LOG.isInfoEnabled()) {
                        LOG.info("  " + entry.getKey() + "=" + val.substring(idx, idx + 256));
                    }
                    idx += 256;
                } else {
                    if (LOG.isInfoEnabled()) {
                        LOG.info("  " + entry.getKey() + "=" + val.substring(idx));
                    }
                    break;
                }
            }
        }
    }
}

From source file:erwins.util.repack.xml.XMLBuilder.java

/**
 * Serialize either the specific Element wrapped by this XMLBuilder, or its entire
 * XML document, to the given writer using the default {@link TransformerFactory}
 * and {@link Transformer} classes./*from   w  w w.j  ava 2 s.c om*/
 * If output options are provided, these options are provided to the
 * {@link Transformer} serializer.
 *
 * @param wholeDocument
 * if true the whole XML document (i.e. the document root) is serialized,
 * if false just the current Element and its descendants are serialized.
 * @param writer
 * a writer to which the serialized document is written.
 * @param outputProperties
 * settings for the {@link Transformer} serializer. This parameter may be
 * null or an empty Properties object, in which case the default output
 * properties will be applied.
 *
 * @throws TransformerException
 */
public void toWriter(boolean wholeDocument, Writer writer, Properties outputProperties)
        throws TransformerException {
    StreamResult streamResult = new StreamResult(writer);

    DOMSource domSource = null;
    if (wholeDocument) {
        domSource = new DOMSource(getDocument());
    } else {
        domSource = new DOMSource(getElement());
    }

    TransformerFactory tf = TransformerFactory.newInstance();
    Transformer serializer = tf.newTransformer();

    if (outputProperties != null) {
        Iterator iter = outputProperties.entrySet().iterator();
        while (iter.hasNext()) {
            Entry entry = (Entry) iter.next();
            serializer.setOutputProperty((String) entry.getKey(), (String) entry.getValue());
        }
    }
    serializer.transform(domSource, streamResult);
}

From source file:com.icesoft.net.messaging.jms.JMSAdapter.java

private void initialize() throws NamingException {
    Properties _environmentProperties = new Properties();
    String _initialContextFactory;
    for (int i = 0; i < jmsProviderConfigurations.length; i++) {
        _initialContextFactory = jmsProviderConfigurations[i].getInitialContextFactory();
        if (_initialContextFactory != null) {
            _environmentProperties.setProperty(JMSProviderConfiguration.INITIAL_CONTEXT_FACTORY,
                    _initialContextFactory);
        }// www  .  j a v  a2  s .  co  m
        String _providerUrl = jmsProviderConfigurations[i].getProviderURL();
        if (_providerUrl != null) {
            _environmentProperties.setProperty(JMSProviderConfiguration.PROVIDER_URL, _providerUrl);
        }
        String _urlPackagePrefixes = jmsProviderConfigurations[i].getURLPackagePrefixes();
        if (_urlPackagePrefixes != null) {
            _environmentProperties.setProperty(JMSProviderConfiguration.URL_PACKAGE_PREFIXES,
                    _urlPackagePrefixes);
        }
        if (LOG.isDebugEnabled()) {
            StringBuffer _environment = new StringBuffer();
            _environment.append("Trying JMS Environment:\r\n");
            Iterator _properties = _environmentProperties.entrySet().iterator();
            while (_properties.hasNext()) {
                Map.Entry _property = (Map.Entry) _properties.next();
                _environment.append("        ");
                _environment.append(_property.getKey());
                _environment.append(" = ");
                _environment.append(_property.getValue());
                _environment.append("\r\n");
            }
            LOG.debug(_environment.toString());
        }
        try {
            // throws NamingException.
            initialContext = new InitialContext(_environmentProperties);
            // throws NamingException.
            topicConnectionFactory = (TopicConnectionFactory) initialContext
                    .lookup(jmsProviderConfigurations[i].getTopicConnectionFactoryName());
            index = i;
            if (LOG.isDebugEnabled()) {
                StringBuffer _environment = new StringBuffer();
                _environment.append("Using JMS Environment:\r\n");
                Iterator _properties = _environmentProperties.entrySet().iterator();
                while (_properties.hasNext()) {
                    Map.Entry _property = (Map.Entry) _properties.next();
                    _environment.append("        ");
                    _environment.append(_property.getKey());
                    _environment.append(" = ");
                    _environment.append(_property.getValue());
                    _environment.append("\r\n");
                }
                LOG.debug(_environment.toString());
            }
            break;
        } catch (NamingException exception) {
            if (LOG.isDebugEnabled()) {
                LOG.debug("Failed JMS Environment: " + exception.getMessage());
            }
            if (initialContext != null) {
                try {
                    initialContext.close();
                } catch (NamingException e) {
                    // ignoring this one.
                }
            }
            if ((i + 1) == jmsProviderConfigurations.length) {
                throw exception;
            }
        }
    }
}