Example usage for java.util Properties propertyNames

List of usage examples for java.util Properties propertyNames

Introduction

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

Prototype

public Enumeration<?> propertyNames() 

Source Link

Document

Returns an enumeration of all the keys in this property list, including distinct keys in the default property list if a key of the same name has not already been found from the main properties list.

Usage

From source file:org.unitime.commons.hibernate.util.HibernateUtil.java

public static void configureHibernate(Properties properties) throws Exception {
    if (sSessionFactory != null) {
        sSessionFactory.close();//from  w w  w.  j  a  va2  s . com
        sSessionFactory = null;
    }

    if (!NamingManager.hasInitialContextFactoryBuilder())
        NamingManager.setInitialContextFactoryBuilder(new LocalContext(null));

    sLog.info("Connecting to " + getProperty(properties, "connection.url"));
    ClassLoader classLoader = HibernateUtil.class.getClassLoader();
    sLog.debug("  -- class loader retrieved");

    DocumentBuilderFactory factory = DocumentBuilderFactory.newInstance();
    sLog.debug("  -- document factory created");
    DocumentBuilder builder = factory.newDocumentBuilder();
    builder.setEntityResolver(new EntityResolver() {
        public InputSource resolveEntity(String publicId, String systemId) {
            if (publicId.equals("-//Hibernate/Hibernate Mapping DTD 3.0//EN")) {
                return new InputSource(HibernateUtil.class.getClassLoader()
                        .getResourceAsStream("org/hibernate/hibernate-mapping-3.0.dtd"));
            } else if (publicId.equals("-//Hibernate/Hibernate Mapping DTD//EN")) {
                return new InputSource(HibernateUtil.class.getClassLoader()
                        .getResourceAsStream("org/hibernate/hibernate-mapping-3.0.dtd"));
            } else if (publicId.equals("-//Hibernate/Hibernate Configuration DTD 3.0//EN")) {
                return new InputSource(HibernateUtil.class.getClassLoader()
                        .getResourceAsStream("org/hibernate/hibernate-configuration-3.0.dtd"));
            } else if (publicId.equals("-//Hibernate/Hibernate Configuration DTD//EN")) {
                return new InputSource(HibernateUtil.class.getClassLoader()
                        .getResourceAsStream("org/hibernate/hibernate-configuration-3.0.dtd"));
            }
            return null;
        }
    });
    sLog.debug("  -- document builder created");
    Document document = builder.parse(classLoader.getResource("hibernate.cfg.xml").openStream());
    sLog.debug("  -- hibernate.cfg.xml parsed");

    String dialect = getProperty(properties, "dialect");
    if (dialect != null)
        setProperty(document, "dialect", dialect);

    String idgen = getProperty(properties, "tmtbl.uniqueid.generator");
    if (idgen != null)
        setProperty(document, "tmtbl.uniqueid.generator", idgen);

    if (ApplicationProperty.HibernateClusterEnabled.isFalse())
        setProperty(document, "net.sf.ehcache.configurationResourceName", "ehcache-nocluster.xml");

    // Remove second level cache
    setProperty(document, "hibernate.cache.use_second_level_cache", "false");
    setProperty(document, "hibernate.cache.use_query_cache", "false");
    removeProperty(document, "hibernate.cache.region.factory_class");

    for (Enumeration e = properties.propertyNames(); e.hasMoreElements();) {
        String name = (String) e.nextElement();
        if (name.startsWith("hibernate.") || name.startsWith("connection.")
                || name.startsWith("tmtbl.hibernate.")) {
            String value = properties.getProperty(name);
            if ("NULL".equals(value))
                removeProperty(document, name);
            else
                setProperty(document, name, value);
            if (!name.equals("connection.password"))
                sLog.debug("  -- set " + name + ": " + value);
            else
                sLog.debug("  -- set " + name + ": *****");
        }
    }

    String default_schema = getProperty(properties, "default_schema");
    if (default_schema != null)
        setProperty(document, "default_schema", default_schema);

    sLog.debug("  -- hibernate.cfg.xml altered");

    Configuration cfg = new Configuration();
    sLog.debug("  -- configuration object created");

    cfg.setEntityResolver(new EntityResolver() {
        public InputSource resolveEntity(String publicId, String systemId) {
            if (publicId.equals("-//Hibernate/Hibernate Mapping DTD 3.0//EN")) {
                return new InputSource(HibernateUtil.class.getClassLoader()
                        .getResourceAsStream("org/hibernate/hibernate-mapping-3.0.dtd"));
            } else if (publicId.equals("-//Hibernate/Hibernate Mapping DTD//EN")) {
                return new InputSource(HibernateUtil.class.getClassLoader()
                        .getResourceAsStream("org/hibernate/hibernate-mapping-3.0.dtd"));
            } else if (publicId.equals("-//Hibernate/Hibernate Configuration DTD 3.0//EN")) {
                return new InputSource(HibernateUtil.class.getClassLoader()
                        .getResourceAsStream("org/hibernate/hibernate-configuration-3.0.dtd"));
            } else if (publicId.equals("-//Hibernate/Hibernate Configuration DTD//EN")) {
                return new InputSource(HibernateUtil.class.getClassLoader()
                        .getResourceAsStream("org/hibernate/hibernate-configuration-3.0.dtd"));
            }
            return null;
        }
    });
    sLog.debug("  -- added entity resolver");

    cfg.configure(document);
    sLog.debug("  -- hibernate configured");

    fixSchemaInFormulas(cfg);

    UniqueIdGenerator.configure(cfg);

    (new _BaseRootDAO() {
        void setConf(Configuration cfg) {
            _BaseRootDAO.sConfiguration = cfg;
        }

        protected Class getReferenceClass() {
            return null;
        }
    }).setConf(cfg);
    sLog.debug("  -- configuration set to _BaseRootDAO");

    sSessionFactory = cfg.buildSessionFactory();
    sLog.debug("  -- session factory created");

    (new _BaseRootDAO() {
        void setSF(SessionFactory fact) {
            _BaseRootDAO.sSessionFactory = fact;
        }

        protected Class getReferenceClass() {
            return null;
        }
    }).setSF(sSessionFactory);
    sLog.debug("  -- session factory set to _BaseRootDAO");

    addBitwiseOperationsToDialect();
    sLog.debug("  -- bitwise operation added to the dialect if needed");

    DatabaseUpdate.update();
}

From source file:org.wso2.carbon.device.mgt.core.service.DeviceManagementProviderServiceImpl.java

@Override
public void sendEnrolmentInvitation(String templateName, EmailMetaInfo metaInfo)
        throws DeviceManagementException, ConfigurationManagementException {
    if (metaInfo == null) {
        String msg = "Received incomplete data to method sendEnrolmentInvitation";
        log.error(msg);/*from w  w w . j a  v a2s . c  om*/
        throw new DeviceManagementException(msg);
    }
    if (log.isDebugEnabled()) {
        log.debug("Send enrollment invitation, templateName '" + templateName + "'");
    }
    Map<String, TypedValue<Class<?>, Object>> params = new HashMap<>();
    Properties props = metaInfo.getProperties();
    Enumeration e = props.propertyNames();
    while (e.hasMoreElements()) {
        String key = (String) e.nextElement();
        params.put(key, new TypedValue<>(String.class, props.getProperty(key)));
    }
    params.put(org.wso2.carbon.device.mgt.core.DeviceManagementConstants.EmailAttributes.SERVER_BASE_URL_HTTPS,
            new TypedValue<>(String.class, DeviceManagerUtil.getServerBaseHttpsUrl()));
    params.put(org.wso2.carbon.device.mgt.core.DeviceManagementConstants.EmailAttributes.SERVER_BASE_URL_HTTP,
            new TypedValue<>(String.class, DeviceManagerUtil.getServerBaseHttpUrl()));
    try {
        EmailContext ctx = new EmailContext.EmailContextBuilder(new ContentProviderInfo(templateName, params),
                metaInfo.getRecipients()).build();
        DeviceManagementDataHolder.getInstance().getEmailSenderService().sendEmail(ctx);
    } catch (EmailSendingFailedException ex) {
        String msg = "Error occurred while sending enrollment invitation";
        log.error(msg, ex);
        throw new DeviceManagementException(msg, ex);
    } catch (EmailTransportNotConfiguredException ex) {
        String msg = "Mail Server is not configured.";
        throw new ConfigurationManagementException(msg, ex);
    } catch (Exception ex) {
        String msg = "Error occurred in setEnrollmentInvitation";
        log.error(msg, ex);
        throw new DeviceManagementException(msg, ex);
    }
}

From source file:com.ibm.cics.ca1y.Emit.java

/**
 * Emit a message using configuration from a set of properties, and data from the CICS channel.
 *
 * @param props/*  www . j  a  v  a  2 s  .  c o  m*/
 *            - properties to use
 * @param cicsChannel
 *            - CICS channel
 * @param isStartedWithEPAdpter
 *            - true if the CICS current channel is the architected EP adapter channel
 * @return true if emission was successful
 */
public static boolean emit(EmitProperties props, Channel cicsChannel, boolean isStartedWithEPAdpter) {
    // Maximum number of nested imports
    final int MAX_NESTED_IMPORTS = 10;

    boolean emissionSuccessful = true;
    try {
        // Create a compiled regex from either the default pattern or the specified override
        Pattern pattern = getPattern(props);

        if (System.getProperties().containsKey(CA1Y_IMPORT)) {
            // Merge properties from the JVM system property ca1y.import
            if (logger.isLoggable(Level.FINE)) {
                logger.fine(messages.getString("LoadingPropertiesFromImport") + " " + CA1Y_IMPORT);
            }

            props.setProperty(CA1Y_IMPORT, System.getProperties().getProperty(CA1Y_IMPORT));

            resolveTokensInKey(CA1Y_IMPORT, pattern, props, cicsChannel, isStartedWithEPAdpter, false);

            if (!Util.loadProperties(props, props.getProperty(CA1Y_IMPORT))) {
                logger.warning(Emit.messages.getString("InvalidImportProperties") + " " + CA1Y_IMPORT);
            }

            // Remove the IMPORT property otherwise it will go through unnecessary token processing
            props.remove(CA1Y_IMPORT);

            // Re-evaluate token regex as the imported properties may have changed it
            pattern = getPattern(props);
        }

        int nestedImports = 0;
        while ((props.containsKey(IMPORT)) && (nestedImports <= MAX_NESTED_IMPORTS)) {
            // Merge properties from the supplied property import
            if (logger.isLoggable(Level.FINE)) {
                logger.fine(messages.getString("LoadingPropertiesFromImport") + " " + IMPORT);
            }

            resolveTokensInKey(IMPORT, pattern, props, cicsChannel, isStartedWithEPAdpter, false);

            String importString = props.getProperty(IMPORT);

            // Remove the IMPORT property to allow for nested IMPORTs
            props.remove(IMPORT);
            props.setPropertyResolved(IMPORT, false);

            if (!Util.loadProperties(props, importString)) {
                logger.warning(
                        Emit.messages.getString("InvalidImportProperties") + " " + IMPORT + "=" + importString);
            }

            // Re-evaluate token regex as the imported properties may have changed it
            pattern = getPattern(props);

            nestedImports++;
        }

        if (props.containsKey(IMPORT_PRIVATE)) {
            // Merge properties from the import.private location, marking each of the merged properties as private
            if (logger.isLoggable(Level.FINE)) {
                logger.fine(messages.getString("LoadingPropertiesFromImport") + " " + IMPORT_PRIVATE);
            }

            props.setPropertyPrivacy(IMPORT_PRIVATE, true);

            resolveTokensInKey(IMPORT_PRIVATE, pattern, props, cicsChannel, isStartedWithEPAdpter, false);

            // Use a temporary object to load IMPORT_PRIVATE into as this is the only way to then set the privacy
            // for each property
            Properties privateProperties = new Properties();

            if (!Util.loadProperties(privateProperties, props.getProperty(IMPORT_PRIVATE))) {
                logger.warning(Emit.messages.getString("InvalidImportProperties") + " " + IMPORT_PRIVATE);
            }

            // Remove IMPORT_PRIVATE property otherwise it will be logged and will go through unnecessary token
            // processing.
            props.setPropertyPrivacy(IMPORT_PRIVATE, false);
            props.remove(IMPORT_PRIVATE);

            // Copy each property (note putAll method is discouraged) and set the privacy attribute to true
            Enumeration<?> e = privateProperties.propertyNames();
            while (e.hasMoreElements()) {
                String key = (String) e.nextElement();
                props.setProperty(key, privateProperties.getProperty(key));
                props.setPropertyPrivacy(key, true);
            }
        }

        if (isStartedWithEPAdpter) {
            // Load properties from CICS event containers
            addPropertiesFromDFHEP_DESCRIPTOR(props, cicsChannel);
            addPropertiesFromDFHEP_CONTEXT(props, cicsChannel);
            addPropertiesFromDFHEP_ADAPTPARM(props, cicsChannel);
        }

        // Resolve tokens in each property value in property name order as this is likely to be easier to predict
        Enumeration<?> e = props.propertyNamesOrdered();
        while (e.hasMoreElements()) {
            String key = (String) e.nextElement();
            resolveTokensInKey(key, pattern, props, cicsChannel, isStartedWithEPAdpter, true);
        }

        // Convert property values from one MIME type to another
        e = props.propertyNamesOrdered();
        while (e.hasMoreElements()) {
            String key = (String) e.nextElement();

            if ((props.getPropertyAlternateName(key) != null)
                    && (props.getProperty(props.getPropertyAlternateName(key)) != null)) {
                props.setPropertyAlternateName(key, props.getProperty(key));
            }

            if ((props.getPropertyMime(key) != null) && (props.getPropertyMimeTo(key) != null)) {
                emissionSuccessful = convertProperty(key, props);

                if (!emissionSuccessful) {
                    break;
                }

                if ((logger.isLoggable(Level.FINE)) && (!props.getPropertyPrivacy(key))) {
                    logger.fine(messages.getString("AfterConversion") + " "
                            + EmitProperties.getPropertySummary(props, key));
                }
            }
        }

        // Create zip files
        e = props.propertyNamesOrdered();
        while (e.hasMoreElements()) {
            String key = (String) e.nextElement();

            if (props.getPropertyZip(key) != null) {
                props.setPropertyAttachment(key, createZip(props.getPropertyZipInclude(key), props));
                props.setPropertyAlternateName(key, props.getPropertyZip(key));
                props.setPropertyMime(key, MIME_ZIP);

                if (!emissionSuccessful) {
                    break;
                }

                if ((logger.isLoggable(Level.FINE)) && (!props.getPropertyPrivacy(key))) {
                    logger.fine(messages.getString("AfterZip") + " "
                            + EmitProperties.getPropertySummary(props, key));
                }
            }
        }

    } catch (Exception e) {
        e.printStackTrace();
        emissionSuccessful = false;
    }

    if (emissionSuccessful) {
        emissionSuccessful = callAdapters(props);
    }

    return emissionSuccessful;
}

From source file:net.wastl.webmail.server.WebMailServlet.java

public void init(ServletConfig config) throws ServletException {
    final ServletContext sc = config.getServletContext();
    log.debug("Init");
    final String depName = (String) sc.getAttribute("deployment.name");
    final Properties rtProps = (Properties) sc.getAttribute("meta.properties");
    log.debug("RT configs retrieved for application '" + depName + "'");
    srvlt_config = config;//from   w  ww .j  a  v  a2  s.  c o m
    this.config = new Properties();
    final Enumeration enumVar = config.getInitParameterNames();
    while (enumVar.hasMoreElements()) {
        final String s = (String) enumVar.nextElement();
        this.config.put(s, config.getInitParameter(s));
        log.debug(s + ": " + config.getInitParameter(s));
    }

    /*
     * Issue a warning if webmail.basepath and/or webmail.imagebase are not
     * set.
     */
    if (config.getInitParameter("webmail.basepath") == null) {
        log.warn("webmail.basepath initArg should be set to the WebMail " + "Servlet's base path");
        basepath = "";
    } else {
        basepath = config.getInitParameter("webmail.basepath");
    }
    if (config.getInitParameter("webmail.imagebase") == null) {
        log.error("webmail.basepath initArg should be set to the WebMail " + "Servlet's base path");
        imgbase = "";
    } else {
        imgbase = config.getInitParameter("webmail.imagebase");
    }

    /*
     * Try to get the pathnames from the URL's if no path was given in the
     * initargs.
     */
    if (config.getInitParameter("webmail.data.path") == null) {
        this.config.put("webmail.data.path", sc.getRealPath("/data"));
    }
    if (config.getInitParameter("webmail.lib.path") == null) {
        this.config.put("webmail.lib.path", sc.getRealPath("/lib"));
    }
    if (config.getInitParameter("webmail.template.path") == null) {
        this.config.put("webmail.template.path", sc.getRealPath("/lib/templates"));
    }
    if (config.getInitParameter("webmail.xml.path") == null) {
        this.config.put("webmail.xml.path", sc.getRealPath("/lib/xml"));
    }
    if (config.getInitParameter("webmail.log.facility") == null) {
        this.config.put("webmail.log.facility", "net.wastl.webmail.logger.ServletLogger");
    }

    // Override settings with webmail.* meta.properties
    final Enumeration rte = rtProps.propertyNames();
    int overrides = 0;
    String k;
    while (rte.hasMoreElements()) {
        k = (String) rte.nextElement();
        if (!k.startsWith("webmail.")) {
            continue;
        }
        overrides++;
        this.config.put(k, rtProps.getProperty(k));
    }
    log.debug(Integer.toString(overrides) + " settings passed to WebMailServer, out of " + rtProps.size()
            + " RT properties");

    /*
     * Call the WebMailServer's initialization method and forward all
     * Exceptions to the ServletServer
     */
    try {
        doInit();
    } catch (final Exception e) {
        log.error("Could not intialize", e);
        throw new ServletException("Could not intialize: " + e.getMessage(), e);
    }
    Helper.logThreads("Bottom of WebMailServlet.init()");
}

From source file:org.sonatype.flexmojos.compiler.AbstractCompilerMojo.java

private Map<String, String> getLicenses() throws MojoExecutionException {
    File licensePropertyFile = null;
    for (File lpl : licensePropertiesLocations) {
        if (lpl.exists()) {
            licensePropertyFile = lpl;/* www.  j a v a2s .  c  om*/
            break;
        }
    }

    if (licensePropertyFile == null) {
        return null;
    }

    Properties props = new Properties();
    try {
        props.load(new FileInputStream(licensePropertyFile));
    } catch (IOException e) {
        getLog().warn("Unable to read license files " + licensePropertyFile.getAbsolutePath(), e);
        return null;
    }

    Map<String, String> licenses = new HashMap<String, String>();

    Enumeration<?> names = props.propertyNames();
    while (names.hasMoreElements()) {
        String name = (String) names.nextElement();
        String value = props.getProperty(name);
        licenses.put(name, value);
    }

    return licenses;
}

From source file:com.inverse2.ajaxtoaster.AjaxToasterServlet.java

/**
 * Perform initialisation necessary to setup AjaxToaster database pools...
 *//* w  ww  .j  a v  a 2 s . c o m*/
private void initDBPools(Properties servletProperties, ServletContext context) {

    // Read the default JNDI name or connection pool name to use when creating database connections.
    // held in AjaxToaster.properties as the "default_db_jndi_name" property.
    // This is used if there is no properties file with an overriding "db_jndi_name" property supplied for a toaster script.

    default_db_jndi_name = servletProperties.getProperty(PROP_DEFAULT_JNDI_DATABASE);
    default_db_jdbc_name = servletProperties.getProperty(PROP_DEFAULT_JDBC_POOL);

    println("**** Default JDBC pool = " + default_db_jdbc_name);
    println("**** Default JNDI name = " + default_db_jndi_name);

    /**
     *  Create any jdbc connection pools
     *
     * Properties file format for connection pools is :
     *        jdbc.class.[poolId]    = [driver classname]
     *        jdbc.database.[poolId] = [database to connect to]
     *        jdbc.username.[poolId] = [user to connect as]
     *        jdbc.password.[poolId] = [password]
       *
     * ...Where [id] is a unique identifier for the pool. It can be anything as long as it's unique per pool.
     *
     * There is no restriction on the number of connection pools that can be defined.
       */

    for (Enumeration e = servletProperties.propertyNames(); e.hasMoreElements();) {

        String propertyName = (String) e.nextElement();

        println("**** checking property.... " + propertyName);

        if (propertyName.startsWith("jdbc.database.")) {

            String poolId = propertyName.substring(propertyName.lastIndexOf("."));

            poolId = poolId.replaceFirst("\\.", "");

            String driver = servletProperties.getProperty("jdbc.driver." + poolId);
            String url = servletProperties.getProperty("jdbc.database." + poolId);
            String username = servletProperties.getProperty("jdbc.username." + poolId);
            String password = servletProperties.getProperty("jdbc.password." + poolId);

            // Not using a container managed database connection pool.... lets make our own!
            // Create a database connection pool...

            println("**** INFO: JDBC CONNECTION PROPERTIES FOR " + poolId + " - ("
                    + servletProperties.getProperty(propertyName) + ")");
            println("****       driver=" + driver);
            println("****       url=" + url);
            println("****       username=" + username);
            println("****       password=" + password);

            try {
                String contextDirectory = context.getRealPath("/");
                DBConnectionPool dbpool = new DBConnectionPool(poolId, driver, url, username, password,
                        contextDirectory);
                String attr = ATTRIB_JDBC_CONN_POOL + "." + poolId;

                println("Storing JDBC pool in " + attr);

                context.setAttribute(attr, dbpool);
            } catch (Exception ex) {
                println("**** ERROR: Exception creating a database connection pool: " + ex.toString());
                // continue... some pools might be ok...
            }

        }

    }

}

From source file:edu.harvard.i2b2.eclipse.login.LoginDialog.java

/**
 * Creates the dialog's contents/*  w w  w  . j  a va2  s  .  c o m*/
 * 
 * @param shell
 *            the dialog window
 */
private void createContents(final Shell shell) {
    shell.setLayout(null);

    ///Cancel the reaunthentication timer while dialog is showing
    //           Timer t=UserInfoBean.getReauthenticationTimer();
    //         if(t!=null)
    //               t.cancel(); 

    // row for login message
    final Label labelMsg = new Label(shell, SWT.CENTER | SWT.SHADOW_NONE | SWT.WRAP);
    labelMsg.setText(Messages.getString("HiveLoginDialog.EnterCredential")); //$NON-NLS-1$
    if (OS.startsWith("mac")) //$NON-NLS-1$
        labelMsg.setBounds(new Rectangle(18, 5, 267, 35));
    else
        labelMsg.setBounds(new Rectangle(18, 5, 260, 30));

    // row for project label/prompt
    Label projectLabel = new Label(shell, SWT.NULL);
    projectLabel.setText(Messages.getString("LoginDialog.8")); //$NON-NLS-1$
    projectLabel.setBounds(new Rectangle(18, 42, 85, 18));
    //
    // The properties are read from the properties file and stored in system properties
    //
    String filename = Messages.getString("Application.PropertiesFile"); //$NON-NLS-1$
    Properties properties = new Properties();
    //Boolean demoFlag = false;
    //String[] projectNames = null;
    //ArrayList<Project> projectName = new ArrayList<Project>();
    try {
        // properties are read from the file
        properties.load(new FileInputStream(filename));
        appName = properties.getProperty("applicationName"); //$NON-NLS-1$

        if (appName == null || appName.equals("")) //$NON-NLS-1$
        {
            MessageBox messageBox = new MessageBox(shell, SWT.OK | SWT.ICON_ERROR);
            messageBox.setMessage(Messages.getString("LoginDialog.12")); //$NON-NLS-1$
            messageBox.open();
            log.info(Messages.getString("LoginDialog.13")); //$NON-NLS-1$
            System.exit(0);
        }

        System.setProperty("applicationName", appName); //$NON-NLS-1$

        String demoUserFlag = properties.getProperty("demoUser"); //$NON-NLS-1$
        if (demoUserFlag == null)
            System.setProperty("demoUser", "no"); //$NON-NLS-1$ //$NON-NLS-2$
        else
            System.setProperty("demoUser", demoUserFlag); //$NON-NLS-1$

        // A new timeout parameter can be read from the properties file here:

        String sTimeoutInMilliseconds = properties.getProperty("timeout");
        if (sTimeoutInMilliseconds == null)
            System.setProperty("iTimeoutInMilliseconds", "1800000");
        //else if (sTimeoutInMilliseconds  String.valueOf(i) )
        //   System.setProperty("iTimeoutInMilliseconds", "1800000");            
        else
            System.setProperty("iTimeoutInMilliseconds", sTimeoutInMilliseconds);

        //String projects = properties.propertyNames(); //.getProperty(appName + ".1"); //"projects");

        Enumeration propertyNames = properties.propertyNames();

        while (propertyNames.hasMoreElements()) {

            String propertyName = (String) propertyNames.nextElement();

            if (propertyName.toUpperCase().startsWith(appName.toUpperCase())) {
                try {
                    String[] propertyValue = properties.getProperty(propertyName).split(","); //$NON-NLS-1$
                    if (propertyValue.length > 2) {
                        Project prj = new Project();
                        prj.setId(propertyName);
                        prj.setName(propertyValue[0].trim());
                        prj.setMethod(propertyValue[1].trim());
                        prj.setUrl(propertyValue[2].trim());
                        projects.add(prj);
                        if (currentPrj == null)
                            currentPrj = projects.get(0);

                    } else {
                        MessageBox messageBox = new MessageBox(shell, SWT.OK | SWT.ICON_ERROR);
                        messageBox.setMessage(Messages.getString("LoginDialog.PMLocation1") + propertyName //$NON-NLS-1$
                                + Messages.getString("LoginDialog.PMLocation2")); //$NON-NLS-1$
                        messageBox.open();
                        log.info("PM Target location " + propertyName + " not specified properly"); //$NON-NLS-1$ //$NON-NLS-2$
                        System.exit(0);
                    }
                } catch (Exception ee) {
                    ee.printStackTrace();

                }
            }

        }
        if (currentPrj == null) {
            MessageBox messageBox = new MessageBox(shell, SWT.OK | SWT.ICON_ERROR);
            messageBox.setMessage(Messages.getString("LoginDialog.NOPMProvided") + appName); //$NON-NLS-1$
            messageBox.open();
            log.info("No PM target locations were provided that have prefix of " + appName); //$NON-NLS-1$
            System.exit(0);
        }
    } catch (IOException e) {
        MessageBox messageBox = new MessageBox(shell, SWT.OK | SWT.ICON_ERROR);
        messageBox.setMessage(e.getMessage());
        messageBox.open();
        log.error(e.getMessage());
        System.exit(0);
    }

    final Combo projectCombo = new Combo(shell, SWT.SINGLE | SWT.BORDER | SWT.READ_ONLY);
    for (Project project : projects) {
        projectCombo.add(project.getName());
        //projectC

    }
    /*
    for(int i=0; i<projectNames.length; i++) {
       if(projectNames[i].toUpperCase().indexOf(appName.toUpperCase()) >= 0) {
    if (defaultProject == null)
       defaultProject = projectNames[i].substring(projectNames[i].indexOf(" ")+1, 
             projectNames[i].lastIndexOf(" "));
            
    projectCombo.add(projectNames[i].substring(projectNames[i].indexOf(" ")+1, 
          projectNames[i].lastIndexOf(" ")));
    pmAddresses.put(projectNames[i].substring(projectNames[i].indexOf(" ")+1, 
          projectNames[i].lastIndexOf(" ")), 
          projectNames[i].substring(projectNames[i].indexOf("[")+1, projectNames[i].indexOf("]")));
       }
    }
     */
    projectCombo.setText(projectCombo.getItem(0));
    System.setProperty("projectName", projectCombo.getText()); //$NON-NLS-1$
    //if(projectCombo.getItem(0).equalsIgnoreCase("rpdr")) {

    //   }

    projectCombo.setBounds(new Rectangle(104, 38, 170, 21));
    projectCombo.addSelectionListener(new org.eclipse.swt.events.SelectionListener() {
        public void widgetSelected(org.eclipse.swt.events.SelectionEvent e) {
            //String selected = projectCombo.getText();
            int index = projectCombo.getSelectionIndex();
            currentPrj = getProject(index);

            statusMsg.setText(currentPrj.getUrl());

            //      (String) pmAddresses.get(projectCombo.getText()));   //index));
            System.setProperty("projectName", projectCombo.getText()); //$NON-NLS-1$

            if (projectCombo.getItem(0).equalsIgnoreCase("rpdr")) { //$NON-NLS-1$
                textUser.setText("partners\\" + userid); //$NON-NLS-1$
            }
        }

        public void widgetDefaultSelected(org.eclipse.swt.events.SelectionEvent e) {
        }
    });

    // row for user label/prompt
    Label labelUser = new Label(shell, SWT.NULL);
    labelUser.setText(Messages.getString("LoginDialog.UserName")); //$NON-NLS-1$
    labelUser.setBounds(new Rectangle(18, 68, 62, 13));

    textUser = new Text(shell, SWT.SINGLE | SWT.BORDER);
    textUser.setText(userid);
    if (projectCombo.getItem(0).equalsIgnoreCase("rpdr")) { //$NON-NLS-1$
        textUser.setText("partners\\" + userid); //$NON-NLS-1$
    }
    if (OS.startsWith("mac")) //$NON-NLS-1$
        textUser.setBounds(new Rectangle(104, 65, 170, 27));
    else
        textUser.setBounds(new Rectangle(104, 65, 170, 21));

    // row for password label/prompt
    Label labelPassword = new Label(shell, SWT.NULL);
    labelPassword.setText(Messages.getString("LoginDialog.Password")); //$NON-NLS-1$
    labelPassword.setBounds(new Rectangle(18, 92, 59, 16));

    textPassword = new Text(shell, SWT.SINGLE | SWT.BORDER);
    if (OS.startsWith("mac")) //$NON-NLS-1$
        textPassword.setBounds(new Rectangle(104, 93, 170, 25));
    else
        textPassword.setBounds(new Rectangle(104, 91, 170, 21));

    textPassword.setText(password);
    textPassword.setEchoChar('*');
    textPassword.setFocus();

    demoOnly = new Button(shell, SWT.CHECK);
    demoOnly.setText(Messages.getString("LoginDialog.StartInDemo")); //$NON-NLS-1$
    if (OS.startsWith("mac")) //$NON-NLS-1$
        demoOnly.setBounds(new Rectangle(18, 118, 210, 19));
    else
        demoOnly.setBounds(new Rectangle(18, 118, 180, 19));

    if (System.getProperty("demoUser").equals("no")) { //$NON-NLS-1$ //$NON-NLS-2$
        demoOnly.setEnabled(false);
    }

    demoOnly.addSelectionListener(new org.eclipse.swt.events.SelectionAdapter() {
        @Override
        public void widgetSelected(org.eclipse.swt.events.SelectionEvent e) {
            if (demoOnly.getSelection() == true) {
                textUser.setEditable(false);
                textUser.setText(Messages.getString("LoginDialog.DemoUserText")); //$NON-NLS-1$
                textPassword.setEditable(false);
                textPassword.setText(""); //$NON-NLS-1$
            } else {
                textUser.setEditable(true);
                textUser.setText(System.getProperty("user.name")); //$NON-NLS-1$
                textPassword.setEditable(true);
            }
        }
    });

    final Button help = new Button(shell, SWT.PUSH);
    if (OS.startsWith("mac")) //$NON-NLS-1$
        help.setBounds(new Rectangle(230, 117, 40, 25));
    else
        help.setBounds(new Rectangle(230, 117, 21, 18));

    help.setText("?"); //$NON-NLS-1$
    help.setFont(new Font(Display.getDefault(), "Tahoma", 10, SWT.BOLD)); //$NON-NLS-1$
    help.addSelectionListener(new org.eclipse.swt.events.SelectionAdapter() {
        @Override
        public void widgetSelected(org.eclipse.swt.events.SelectionEvent e) {
            MessageBox mBox = new MessageBox(help.getShell(), SWT.ICON_INFORMATION | SWT.OK);
            mBox.setText(Messages.getString("LoginDialog.HelpPopup")); //$NON-NLS-1$
            mBox.setMessage(Messages.getString("LoginDialog.HelpPopupText")); //$NON-NLS-1$
            mBox.open();
        }
    });

    // create ok button and add handler
    // pressing it will set userid and start login query
    final Button ok = new Button(shell, SWT.PUSH);
    ok.setText(Messages.getString("LoginDialog.ButtonLogin")); //$NON-NLS-1$
    if (OS.startsWith("mac")) //$NON-NLS-1$
        ok.setBounds(new Rectangle(87, 144, 94, 30));
    else
        ok.setBounds(new Rectangle(147, 144, 54, 23));

    // add selection handler
    ok.addSelectionListener(new SelectionAdapter() {
        @Override
        public void widgetSelected(SelectionEvent event) {
            labelMsg.setText(Messages.getString("LoginDialog.LogginIn")); //$NON-NLS-1$
            currentPrj = getProject(projectCombo.getSelectionIndex());
            //pmAddress = getProject(projectCombo.getText()).getUrl();
            System.setProperty("webServiceMethod", currentPrj.getMethod()); //$NON-NLS-1$
            //(String) pmAddresses.get(projectCombo.getText());

            //
            // This supplies hardcoded values for a demo login, no actual web
            // services are called.
            //
            if (demoOnly.getSelection() == true) {

                //labelMsg.setText("Logging in ...");
                PasswordType ptype = new PasswordType();
                ptype.setValue(textPassword.getText());
                ptype.setIsToken(false);
                // ptype.setTokenMsTimeout(System.getProperty(key))

                LoginThread loginThread = new LoginThread(textUser.getText().trim(), ptype, currentPrj.getUrl(),
                        // (String) pmAddresses.get(projectCombo.getText()),
                        projectCombo.getText(), true);
                // shows busy caret, spawns thread and blocks until return
                BusyIndicator.showWhile(ok.getDisplay(), loginThread);
                System.setProperty("projectName", loginThread.getUserBean().getUserDomain()); //$NON-NLS-1$
                String userName = loginThread.getUserBean().getUserName();
                log.debug("Login name for userId=" + textUser.getText() //$NON-NLS-1$
                        .trim() + ", userName=" + userName); //$NON-NLS-1$
                // if login fails, set message text and return to dialog
                if (userName == null) {
                    log.debug("Login Fail for userid=" + textUser.getText().trim()); //$NON-NLS-1$
                    //log.info("Login Fail for userid="+textUser.getText().trim());
                    labelMsg.setForeground(
                            labelMsg.getParent().getDisplay().getSystemColor(SWT.COLOR_DARK_RED));
                    labelMsg.setText(loginThread.getMsg());
                    //LOGIN_FAILED_MSG + " " +System.getProperty("statusMessage"));
                    textUser.setText(textUser.getText().trim());

                } else {
                    //login succeeded, return userInfoBean and close dialog
                    labelMsg.setText(Messages.getString("LoginDialog.LoginOK") + userName); //$NON-NLS-1$
                    textUser.setText(textUser.getText().trim());
                    //return UserInfo object
                    userInfo = loginThread.getUserBean();
                    shell.close();
                }
            }

            //
            // This is the actual login process where actual web
            // services are called.
            //
            else {
                //
                // #1 = Web Service to get Message Version
                //
                // value from i2b2workbench.properties file is returned next...
                String workbenchversion = getWorkbenchMessageVersion();
                // web service call to obtain Message version is returned next ...
                String hiveversion = getHiveMessageVersion();
                // exit if properties file does not have message version
                if (workbenchversion == null) {
                    MessageBox messageBox = new MessageBox(shell, SWT.OK | SWT.ICON_ERROR);
                    messageBox.setMessage(Messages.getString("LoginDialog.messageVersionNotInProperty")); //$NON-NLS-1$
                    messageBox.open();
                    log.info("messageversion is missing from properties file"); //$NON-NLS-1$
                    System.exit(0);
                }
                // return if the web service didn't work after painting login box with error
                if (hiveversion == null) {
                    labelMsg.setForeground(
                            labelMsg.getParent().getDisplay().getSystemColor(SWT.COLOR_DARK_RED));
                    labelMsg.setText(Messages.getString("LoginDialog.PMServerError"));
                    // OLD ENGLISH = labelMsg.setText("Unable to connect to server.");
                    textUser.setText(textUser.getText().trim());
                    return;
                    // only if user wants, exit if the message versions do not match
                } else if (!workbenchversion.equalsIgnoreCase(hiveversion)) {
                    Shell activeShell = shell;
                    MessageBox mBox = new MessageBox(activeShell,
                            SWT.ICON_INFORMATION | SWT.ON_TOP | SWT.RETRY | SWT.CANCEL);
                    mBox.setText(Messages.getString("LoginDialog.VersionConflictPopup")); //$NON-NLS-1$
                    mBox.setMessage(Messages.getString("LoginDialog.VersionConflictPopupText1") + appName //$NON-NLS-1$
                            + Messages.getString("LoginDialog.VersionConflictPopupText2") + workbenchversion //$NON-NLS-1$
                            + Messages.getString("LoginDialog.VersionConflictPopupText3") + appName //$NON-NLS-1$
                            + Messages.getString("LoginDialog.VersionConflictPopupText4")); //$NON-NLS-1$
                    int returnVal = mBox.open();
                    //      log.info(returnVal);
                    log.info("Workbench message version " + workbenchversion //$NON-NLS-1$
                            + " does not match hive message version " + hiveversion); //$NON-NLS-1$
                    if (returnVal == 256) {
                        System.exit(0);
                    }
                }
                //
                // #2 Create thread for web call - populates UserInfo object
                //
                // Password is set from Dialog
                PasswordType ptype = new PasswordType();
                ptype.setValue(textPassword.getText());
                ptype.setIsToken(false);
                // TimeoutInMiliseconds is set from properties file
                ptype.setTokenMsTimeout(getWorkbenchTimeoutInMiliseconds());
                // Login web service is called with user string, passowrd object, and URL of domain
                LoginThread loginThread = new LoginThread(textUser.getText().trim(), ptype, currentPrj.getUrl(),
                        //(String) pmAddresses.get(projectCombo.getText()), 
                        projectCombo.getText(), false);
                // shows busy caret, spawns thread and blocks until return
                BusyIndicator.showWhile(ok.getDisplay(), loginThread);
                String userName = loginThread.getUserBean().getUserName();
                log.debug("Login name for userId=" + textUser.getText() //$NON-NLS-1$
                        .trim() + ", userName=" + userName); //$NON-NLS-1$
                // if login fails, set message text and return to dialog
                if (userName == null) {
                    log.debug("Login Fail for userid=" + textUser.getText().trim()); //$NON-NLS-1$
                    //log.info("Login Fail for userid="+textUser.getText().trim());
                    labelMsg.setForeground(
                            labelMsg.getParent().getDisplay().getSystemColor(SWT.COLOR_DARK_RED));
                    //labelMsg.setText("Logging in ...");
                    if (loginThread.getMsg() != null)
                        labelMsg.setText(loginThread.getMsg());

                    //labelMsg.setText("Unable to connect to server.");
                    //LOGIN_FAILED_MSG + " " +System.getProperty("statusMessage"));
                    textUser.setText(textUser.getText().trim());

                } else {
                    //login succeeded, return userInfoBean and close dialog
                    labelMsg.setText(Messages.getString("LoginDialog.LoginOK") + userName); //$NON-NLS-1$
                    textUser.setText(textUser.getText().trim());
                    //return UserInfo object
                    userInfo = loginThread.getUserBean();

                    /*************Set the reauthentication timer running******************
                            
                    final long INTERVAL=1000*60*2; //20 minutes
                    //Create a new one
                    Timer t=new Timer();
                    //Create a task to schedule
                    ReauthenticateTask rt=new ReauthenticateTask();
                    //Schedule the task
                    t.scheduleAtFixedRate(rt, INTERVAL, INTERVAL);
                    UserInfoBean.setReauthenticationTimer(t);
                    */
                    /**********************************************************************/

                    shell.close();
                }
            }
        }
    });

    // Create the cancel button and add a handler
    // so that pressing it will set input to null and close window
    Button cancel = new Button(shell, SWT.PUSH);
    cancel.setText("Cancel"); //$NON-NLS-1$
    if (OS.startsWith("mac")) //$NON-NLS-1$
        cancel.setBounds(new Rectangle(187, 144, 90, 30));
    else
        cancel.setBounds(new Rectangle(217, 144, 50, 23));
    cancel.addSelectionListener(new SelectionAdapter() {
        @Override
        public void widgetSelected(SelectionEvent event) {
            // do something here- return null
            userInfo = null;
            shell.close();
            System.exit(0);
        }
    });

    statusMsg = new Label(shell, SWT.BORDER | SWT.LEFT | SWT.WRAP);
    statusMsg.setText(currentPrj.getUrl());
    //(String) pmAddresses.get(defaultProject.getName()));
    Font font = statusMsg.getFont();
    //font.size = 10; //only for mac
    statusMsg.setFont(font);
    statusMsg.setBounds(new Rectangle(4, 182, 281, 27));

    // Set the OK button as the default
    shell.setDefaultButton(ok);
}

From source file:pl.otros.logview.parser.log4j.Log4jPatternMultilineLogParser.java

@Override
public void init(Properties properties) throws InitializationException {
    String rePattern = properties.getProperty(PROPERTY_REPATTERN);
    logFormat = properties.getProperty(PROPERTY_PATTERN);
    if (!StringUtils.isBlank(logFormat) && rePattern != null) {
        throw new InitializationException(String.format("Conflicting log patterns set (properties %s and %s)",
                PROPERTY_PATTERN, PROPERTY_REPATTERN));
    }//from  w w  w .jav  a  2s  .com
    if (StringUtils.isBlank(logFormat) && rePattern == null) {
        throw new InitializationException(
                String.format("Log pattern not set (property %s or %s)", PROPERTY_PATTERN, PROPERTY_REPATTERN));
    }
    timestampFormat = properties.getProperty(PROPERTY_DATE_FORMAT);
    if (StringUtils.isBlank(timestampFormat)) {
        throw new InitializationException(
                String.format("Date format not set (property %s)", PROPERTY_DATE_FORMAT));
    }
    customLevelDefinitions = properties.getProperty(PROPERTY_CUSTOM_LEVELS);
    parserDescription.setDisplayName(properties.getProperty(PROPERTY_NAME, "?"));
    parserDescription.setDescription(properties.getProperty(PROPERTY_DESCRIPTION, "?"));
    parserDescription.setCharset(properties.getProperty(PROPERTY_CHARSET, "UTF-8"));
    if (timestampFormat != null) {
        // dateFormat = new SimpleDateFormat(quoteTimeStampChars(timestampFormat));
        timestampPatternText = convertTimestamp();
    }

    if (rePattern == null) {
        initializePatterns();
        createPattern();
    } else {
        try {
            regexpPattern = Pattern.compile(rePattern);
        } catch (PatternSyntaxException pse) {
            throw new InitializationException(String.format("Malformatted regex pattern for '%s' (%s): %s",
                    PROPERTY_REPATTERN, rePattern, pse.getDescription()));
        }
        // if custom level definitions exist, parse them
        updateCustomLevelDefinitionMap();

        Map<Integer, String> groupMap = new HashMap<Integer, String>();
        Enumeration<String> e = (Enumeration<String>) properties.propertyNames();
        String key = null, val = null;
        int keyLen, dotGrouplen;
        int dotGroupLen = ".group".length();
        while (e.hasMoreElements())
            try {
                key = e.nextElement();
                keyLen = key.length();
                if (keyLen <= dotGroupLen || !key.endsWith(".group"))
                    continue;
                val = properties.getProperty(key);
                groupMap.put(Integer.valueOf(val), key.substring(0, keyLen - dotGroupLen));
            } catch (NumberFormatException ne) {
                throw new InitializationException(
                        String.format("Group property '%s.group' set to non-integer: %s", key, val));
            }
        if (groupMap.size() < 1)
            throw new InitializationException(PROPERTY_REPATTERN + " set but no group properties set.  "
                    + "Set group indexes like 'TIMESTAMP.group=1', " + "starting with index 1");
        for (int i = 1; i <= groupMap.size(); i++) {
            if (!groupMap.containsKey(Integer.valueOf(i)))
                throw new InitializationException("Group property numbers not consecutive starting at 1");
            matchingKeywords.add(groupMap.get(Integer.valueOf(i)));
        }
        if (matchingKeywords.contains(Log4jPatternMultilineLogParser.MESSAGE) && !matchingKeywords
                .get(matchingKeywords.size() - 1).equals(Log4jPatternMultilineLogParser.MESSAGE))
            throw new InitializationException("If MESSAGE group is present, it must be last");
    }

}

From source file:davmail.exchange.ExchangeSession.java

/**
 * Convert keyword value to IMAP flag.//w w  w . j  a  v a  2  s. com
 *
 * @param value keyword value
 * @return IMAP flag
 */
public String convertKeywordToFlag(String value) {
    // first test for keyword in settings
    Properties flagSettings = Settings.getSubProperties("davmail.imapFlags");
    Enumeration flagSettingsEnum = flagSettings.propertyNames();
    while (flagSettingsEnum.hasMoreElements()) {
        String key = (String) flagSettingsEnum.nextElement();
        if (value.equalsIgnoreCase(flagSettings.getProperty(key))) {
            return key;
        }
    }

    ResourceBundle flagBundle = ResourceBundle.getBundle("imapflags");
    Enumeration<String> flagBundleEnum = flagBundle.getKeys();
    while (flagBundleEnum.hasMoreElements()) {
        String key = flagBundleEnum.nextElement();
        if (value.equalsIgnoreCase(flagBundle.getString(key))) {
            return key;
        }
    }

    // fall back to raw value
    return value;
}

From source file:Install.java

public void processFile(String sourceFileStr, String destFileStr, Properties p_properties) throws IOException {
    File sourceFile = new File(sourceFileStr);
    File destFile = new File(destFileStr);

    System.out.print("\nProcessing " + sourceFile.getName() + "...");
    fireActionEvent(sourceFile.getName());

    destFile.getParentFile().mkdirs();/*w w w.j  a  va  2  s .c o  m*/
    destFile.createNewFile();

    try {
        InputStream inputstream = getResource(sourceFileStr);
        BufferedReader in = new BufferedReader(new InputStreamReader(inputstream));
        BufferedWriter out = new BufferedWriter(new FileWriter(destFile));

        String str, newstr;

        while ((str = in.readLine()) != null) {
            if (str.startsWith("#")) // It's a comment
            {
                newstr = str;
            } else {
                newstr = str;

                // deal with the case of "log4j.proterties.template"
                if (str.indexOf("%%Jboss_JNDI_prefix%%") != -1) // has match
                {
                    newstr = replace(str, "%%Jboss_JNDI_prefix%%", "topic/");
                }
                // deal with the case of "log4j.proterties.template"
                else if (str.indexOf("%%ldap_user_password%%") != -1) // has
                // match
                {
                    newstr = replace(str, "%%ldap_user_password%%",
                            encodeMD5(p_properties.getProperty("ldap_password")));
                } else if (str.indexOf("%%super_admin_password%%") != -1) // has
                // match
                {
                    newstr = replace(str, "%%super_admin_password%%",
                            encodeMD5(p_properties.getProperty("system4_admin_password")));
                } else {
                    // Iterate over the array to see if the string matches
                    // *any* of the install keys
                    for (Enumeration<?> e = p_properties.propertyNames(); e.hasMoreElements();) {
                        String key = (String) e.nextElement();
                        String pattern = "%%" + key + "%%";
                        Object replaceObj = p_properties.get(key);
                        String replace = replaceObj.toString();

                        if (str.indexOf(pattern) == -1) // no match
                        {
                            continue;
                        }

                        newstr = replace(str, pattern, replacePathSlash(replace));
                        str = newstr;
                    }
                }
            }

            out.write(newstr);
            out.newLine();
        }

        in.close();
        out.close();
    } catch (IOException e) {
        System.out.println("Error processing file.");
        throw e;
    }

    System.out.println("done.");
}