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:ddf.security.PropertiesLoader.java

/**
 * Will attempt to load properties from a file using the given classloader. If that fails,
 * several other methods will be tried until the properties file is located.
 *
 * @param propertiesFile// www.  j a va 2  s .c  om
 * @param classLoader
 * @return Properties
 */
public static Properties loadProperties(String propertiesFile, ClassLoader classLoader) {
    boolean error = false;
    Properties properties = new Properties();
    if (propertiesFile != null) {
        try {
            LOGGER.debug("Attempting to load properties from {} with Spring PropertiesLoaderUtils.",
                    propertiesFile);
            properties = PropertiesLoaderUtils.loadAllProperties(propertiesFile);
        } catch (IOException e) {
            error = true;
            LOGGER.error("Unable to load properties using default Spring properties loader.", e);
        }
        if (error || properties.isEmpty()) {
            if (classLoader != null) {
                try {
                    LOGGER.debug(
                            "Attempting to load properties from {} with Spring PropertiesLoaderUtils with class loader.",
                            propertiesFile);
                    properties = PropertiesLoaderUtils.loadAllProperties(propertiesFile, classLoader);
                    error = false;
                } catch (IOException e) {
                    error = true;
                    LOGGER.error("Unable to load properties using default Spring properties loader.", e);
                }
            } else {
                try {
                    LOGGER.debug(
                            "Attempting to load properties from {} with Spring PropertiesLoaderUtils with class loader.",
                            propertiesFile);
                    properties = PropertiesLoaderUtils.loadAllProperties(propertiesFile,
                            PropertiesLoader.class.getClassLoader());
                    error = false;
                } catch (IOException e) {
                    error = true;
                    LOGGER.error("Unable to load properties using default Spring properties loader.", e);
                }
            }
        }

        if (error || properties.isEmpty()) {
            LOGGER.debug("Attempting to load properties from file system: {}", propertiesFile);
            File propFile = new File(propertiesFile);
            // If properties file has fully-qualified absolute path (which
            // the blueprint file specifies) then can load it directly.
            if (propFile.isAbsolute()) {
                LOGGER.debug("propertiesFile {} is absolute", propertiesFile);
                propFile = new File(propertiesFile);
            } else {
                String karafHome = System.getProperty("karaf.home");
                if (karafHome != null && !karafHome.isEmpty()) {
                    propFile = new File(karafHome, propertiesFile);
                } else {
                    karafHome = System.getProperty("ddf.home");
                    if (karafHome != null && !karafHome.isEmpty()) {
                        propFile = new File(karafHome, propertiesFile);
                    } else {
                        propFile = new File(propertiesFile);
                    }
                }
            }
            properties = new Properties();

            try (InputStreamReader reader = new InputStreamReader(new FileInputStream(propertiesFile),
                    StandardCharsets.UTF_8)) {
                properties.load(reader);
            } catch (FileNotFoundException e) {
                error = true;
                LOGGER.error("Could not find properties file: {}", propFile.getAbsolutePath(), e);
            } catch (IOException e) {
                error = true;
                LOGGER.error("Error reading properties file: {}", propFile.getAbsolutePath(), e);
            }
        }
        if (error || properties.isEmpty()) {
            LOGGER.debug("Attempting to load properties as a resource: {}", propertiesFile);
            InputStream ins = PropertiesLoader.class.getResourceAsStream(propertiesFile);
            if (ins != null) {
                try {
                    properties.load(ins);
                    ins.close();
                } catch (IOException e) {
                    LOGGER.error("Unable to load properties: {}", propertiesFile, e);
                } finally {
                    IOUtils.closeQuietly(ins);
                }
            }
        }

        //replace any ${prop} with system properties
        Properties filtered = new Properties();
        for (Map.Entry<?, ?> entry : properties.entrySet()) {
            filtered.put(StrSubstitutor.replaceSystemProperties(entry.getKey()),
                    StrSubstitutor.replaceSystemProperties(entry.getValue()));
        }
        properties = filtered;

    } else {
        LOGGER.debug("Properties file must not be null.");
    }

    return properties;
}

From source file:org.alfresco.bm.tools.BMTestRunner.java

/**
 * Execute the default test against the given MongoDB or an in-memory instance
 * //  w w w .  j ava  2 s. c  o  m
 * @param mongoConfigHost           the MongoDB host to connect to for configuraton data or <tt>null</tt> to use an in-memory version
 * @param mongoTestHost             the MongoDB host to connect to for test data data or <tt>null</tt> to use the same database as the config
 * @param testProperties            any properties to specifically set for the test or <tt>null</tt> if there are none
 */
public void run(String mongoConfigHost, String mongoTestHost, Properties testProperties) throws Exception {
    // Secure the listeners against modification
    List<BMTestRunnerListener> listeners = new ArrayList<BMTestRunnerListener>(this.listeners);

    // If no MongoDB URL is provided, then we have to start one
    MongoDBForTestsFactory mongoDBForTestsFactory = null;
    ClassPathXmlApplicationContext ctx = null;
    try {
        // Ensure that required system properties are present
        System.setProperty(PROP_APP_CONTEXT_PATH, System.getProperty("user.dir"));
        System.setProperty(PROP_APP_DIR, System.getProperty("user.dir"));

        // Create a MongoDB for use if one has not been specified
        if (mongoConfigHost == null) {
            mongoDBForTestsFactory = new MongoDBForTestsFactory();
            String uriWithoutDB = mongoDBForTestsFactory.getMongoURIWithoutDB();
            mongoConfigHost = new MongoClientURI(uriWithoutDB).getHosts().get(0);
        }
        // Fill in the URI for the test MongoDB
        if (mongoTestHost == null) {
            mongoTestHost = mongoConfigHost;
        }

        // Fill in the properties required for the test
        Properties mongoProps = new Properties();
        mongoProps.put(PROP_MONGO_CONFIG_HOST, mongoConfigHost);

        // Construct the application context
        ctx = new ClassPathXmlApplicationContext(new String[] { PATH_APP_CONTEXT }, false);
        // Push cluster properties into the context (must be done AFTER setting parent context)
        ConfigurableEnvironment ctxEnv = ctx.getEnvironment();
        // Mongo properties come first
        ctxEnv.getPropertySources().addFirst(new PropertiesPropertySource("mongo-props", mongoProps));
        // Finally, system properties overrule them all
        ctxEnv.getPropertySources()
                .addFirst(new PropertiesPropertySource("system-props", System.getProperties()));

        // Kick it all off
        try {
            ctx.refresh();
        } catch (Exception e) {
            Throwable root = ExceptionUtils.getRootCause(e);
            if (root != null
                    && (root instanceof MongoSocketException || root instanceof UnknownHostException)) {
                // We deal with this specifically as it's a simple case of not finding the MongoDB
                logger.error("Set the configuration property '" + PROP_MONGO_CONFIG_HOST
                        + "' (<server>:<port>) as required.");
            } else {
                // Log application start failure because test frameworks might not do so nicely
                logger.error("Failed to start application.", e);
            }
            throw new RuntimeException("Failed to start application.", e);
        }

        // Get the test
        Test test = ctx.getBean(Test.class);
        String release = test.getRelease();
        Integer schema = test.getSchema();

        TestRestAPI api = ctx.getBean(TestRestAPI.class);

        // Create a new test
        TestDetails testDetails = new TestDetails();
        String testName = "BMTestRunner_" + System.currentTimeMillis();
        testDetails.setName(testName);
        testDetails.setDescription("Test created by BMTestRunner on " + new Date());
        testDetails.setRelease(release);
        testDetails.setSchema(schema);
        api.createTest(testDetails);

        // We need to tell the test which MongoDB to write data to
        PropSetBean propSet = new PropSetBean();
        propSet.setValue(mongoTestHost);
        propSet.setVersion(0);
        api.setTestProperty(testName, PROP_MONGO_TEST_HOST, propSet);

        // Now set any properties that have been explicitly passed in for the test
        if (testProperties != null) {
            for (Map.Entry<Object, Object> entry : testProperties.entrySet()) {
                String propKey = (String) entry.getKey();
                String propVal = (String) entry.getValue();

                propSet.setValue(propVal);
                propSet.setVersion(0);
                api.setTestProperty(testName, propKey, propSet);
            }
        }

        // Call listeners: the test has been created
        for (BMTestRunnerListener listener : listeners) {
            listener.testReady(ctx, testName);
        }

        // Create a new test run
        TestRunDetails testRunDetails = new TestRunDetails();
        String testRunName = "BMTestRunner_" + System.currentTimeMillis();
        testRunDetails.setName(testRunName);
        testRunDetails.setDescription("Test run created by BMTestRunner on " + new Date());
        api.createTestRun(testDetails.getName(), testRunDetails);

        // Call listeners: the test run has been created
        for (BMTestRunnerListener listener : listeners) {
            listener.testRunReady(ctx, testName, testRunName);
        }

        // Get all the test run properties for logging
        String jsonTestRun = api.getTestRun(testName, testRunName);

        // Start the test run
        logger.info("Starting test run: " + testRunName + "\n" + jsonTestRun);
        TestRunSchedule testRunSchedule = new TestRunSchedule();
        testRunSchedule.setScheduled(System.currentTimeMillis());
        api.scheduleTestRun(testName, testRunName, testRunSchedule);

        // Call listeners: the test run has started
        for (BMTestRunnerListener listener : listeners) {
            listener.testRunStarted(ctx, testName, testRunName);
        }

        // Wait for the test run to complete
        long timeInit = System.currentTimeMillis();
        long timeLastChange = -1L;
        String jsonLastChange = null;
        String testRunStateStr = api.getTestRunState(testName, testRunName);

        // Keep looking until the test run completes
        while (!TestRunState.COMPLETED.toString().equals(testRunStateStr)) {
            long now = System.currentTimeMillis();

            // Check that we have not exceeded the maximum time
            if (now - timeInit > maxTestTime) {
                throw new RuntimeException("Test run failed to complete in " + (int) maxTestTime / 1000 + "s.");
            }

            testRunStateStr = api.getTestRunState(testName, testRunName);

            if (TestRunState.SCHEDULED.toString().equals(testRunStateStr) && (now - timeInit) > 10000L) {
                throw new RuntimeException("Test run failed to start in 10s.");
            }

            // Check that there are updates to the test run
            String jsonNow = api.getTestRunSummary(testName, testRunName);
            if (jsonLastChange != null && jsonLastChange.equals(jsonNow)) {
                if ((now - timeLastChange) > 60000L) {
                    throw new RuntimeException("Test run has not been updated in the last 60s");
                }
            }
            // Store values for next iteration
            timeLastChange = now;
            jsonLastChange = jsonNow;

            synchronized (testRunStateStr) {
                try {
                    testRunStateStr.wait(1000L);
                } catch (InterruptedException e) {
                }
            }
        }
        // Call listeners: the test run has finished
        for (BMTestRunnerListener listener : listeners) {
            listener.testRunFinished(ctx, testName, testRunName);
        }
    } finally {
        // Close the context
        if (ctx != null) {
            try {
                ctx.close();
            } catch (Exception e) {
                logger.error("Failed to shut down application context.", e);
            }
        }
        // Close the local Mongo instance
        if (mongoDBForTestsFactory != null) {
            try {
                mongoDBForTestsFactory.destroy();
            } catch (Exception e) {
                logger.error("Failed to stop in-memory MongoDB instance.", e);
            }
        }
    }
}

From source file:org.cloudifysource.rest.controllers.ServiceController.java

private void setContextProperties(final ElasticDeploymentTopology deployment,
        final Properties contextProperties) {
    final Set<Entry<Object, Object>> contextPropsEntries = contextProperties.entrySet();
    for (final Entry<Object, Object> entry : contextPropsEntries) {
        deployment.addContextProperty((String) entry.getKey(), (String) entry.getValue());
    }//from   w  w  w. java 2s.c o  m
}

From source file:mondrian.rolap.RolapSchemaLoader.java

private void loadResources(String catalogDirUrl, MondrianDef.Schema xmlSchema, Set<Locale> locales) {
    final MondrianDef.Localization localization = xmlSchema.getLocalization();
    if (localization != null) {
        for (MondrianDef.Locale locale : localization.getLocales()) {
            locales.add(Util.parseLocale(locale.locale));
        }//w  ww  . j av a  2 s.  com
        // All into one big hash table.
        for (MondrianDef.Translation t : localization.getTranslations()) {
            for (Locale locale : locales) {
                String path = t.path.replace("${locale}", locale.toString());
                if (isRelative(path)) {
                    path = catalogDirUrl + path;
                }
                try {
                    final InputStream inputStream = Util.readVirtualFile(path);
                    final Properties properties = new Properties();
                    properties.load(inputStream);
                    for (Map.Entry entry : properties.entrySet()) {
                        String key = (String) entry.getKey();
                        LocalizedProperty prop;
                        if (key.endsWith(".caption")) {
                            key = key.substring(0, key.length() - ".caption".length());
                            prop = LocalizedProperty.CAPTION;
                        } else if (key.endsWith(".description")) {
                            key = key.substring(0, key.length() - ".description".length());
                            prop = LocalizedProperty.DESCRIPTION;
                        } else {
                            continue;
                        }
                        Util.putMulti(resourceMap, key,
                                new Larders.Resource(prop, locale, (String) entry.getValue()));
                        if (key.endsWith(".member")) {
                            // Given
                            //   [Sales].[Time].[Weekly].[1997].[23].member
                            // find the hierarchy
                            //   [Sales].[Time].[Weekly]
                            int count = 0;
                            String hierarchyTag = null;
                            for (int i = 0; i < key.length(); i++) {
                                if (key.charAt(i) == '.') {
                                    if (++count == 3) {
                                        hierarchyTag = key.substring(0, i);
                                    }
                                }
                            }
                            // Record level depth. ('All' = 0.)
                            Util.putMulti(resourceHierarchyTags, hierarchyTag, count - 3);
                        }
                    }
                    inputStream.close();
                } catch (Throwable e) {
                    // TODO: should be 'catch IOException' but VFS handler
                    // throws Error (it shouldn't)
                    handler.warning("Error reading resource file '" + path + "'; ignoring", t, "path", e);
                }
            }
        }
    }
}

From source file:com.cloud.hypervisor.xenserver.resource.CitrixResourceBase.java

public boolean setupServer(final Connection conn, final Host host) {
    final String packageVersion = CitrixResourceBase.class.getPackage().getImplementationVersion();
    final String version = this.getClass().getName() + "-"
            + (packageVersion == null ? Long.toString(System.currentTimeMillis()) : packageVersion);

    try {/*from  w ww  .  ja  v  a2  s. co m*/
        /* push patches to XenServer */
        final Host.Record hr = host.getRecord(conn);

        final Iterator<String> it = hr.tags.iterator();

        while (it.hasNext()) {
            final String tag = it.next();
            if (tag.startsWith("vmops-version-")) {
                if (tag.contains(version)) {
                    s_logger.info(logX(host, "Host " + hr.address + " is already setup."));
                    return false;
                } else {
                    it.remove();
                }
            }
        }

        final com.trilead.ssh2.Connection sshConnection = new com.trilead.ssh2.Connection(hr.address, 22);
        try {
            sshConnection.connect(null, 60000, 60000);
            if (!sshConnection.authenticateWithPassword(_username, _password.peek())) {
                throw new CloudRuntimeException("Unable to authenticate");
            }

            final String cmd = "mkdir -p /opt/cloud/bin /var/log/cloud";
            if (!SSHCmdHelper.sshExecuteCmd(sshConnection, cmd)) {
                throw new CloudRuntimeException("Cannot create directory /opt/cloud/bin on XenServer hosts");
            }

            final SCPClient scp = new SCPClient(sshConnection);

            final List<File> files = getPatchFiles();
            if (files == null || files.isEmpty()) {
                throw new CloudRuntimeException("Can not find patch file");
            }
            for (final File file : files) {
                final String path = file.getParentFile().getAbsolutePath() + "/";
                final Properties props = PropertiesUtil.loadFromFile(file);

                for (final Map.Entry<Object, Object> entry : props.entrySet()) {
                    final String k = (String) entry.getKey();
                    final String v = (String) entry.getValue();

                    assert k != null && k.length() > 0 && v != null && v.length() > 0 : "Problems with " + k
                            + "=" + v;

                    final String[] tokens = v.split(",");
                    String f = null;
                    if (tokens.length == 3 && tokens[0].length() > 0) {
                        if (tokens[0].startsWith("/")) {
                            f = tokens[0];
                        } else if (tokens[0].startsWith("~")) {
                            final String homedir = System.getenv("HOME");
                            f = homedir + tokens[0].substring(1) + k;
                        } else {
                            f = path + tokens[0] + '/' + k;
                        }
                    } else {
                        f = path + k;
                    }
                    final String directoryPath = tokens[tokens.length - 1];

                    f = f.replace('/', File.separatorChar);

                    String permissions = "0755";
                    if (tokens.length == 3) {
                        permissions = tokens[1];
                    } else if (tokens.length == 2) {
                        permissions = tokens[0];
                    }

                    if (!new File(f).exists()) {
                        s_logger.warn("We cannot locate " + f);
                        continue;
                    }
                    if (s_logger.isDebugEnabled()) {
                        s_logger.debug("Copying " + f + " to " + directoryPath + " on " + hr.address
                                + " with permission " + permissions);
                    }

                    if (!SSHCmdHelper.sshExecuteCmd(sshConnection, "mkdir -m 700 -p " + directoryPath)) {
                        s_logger.debug("Unable to create destination path: " + directoryPath + " on "
                                + hr.address + ".");
                    }

                    try {
                        scp.put(f, directoryPath, permissions);
                    } catch (final IOException e) {
                        final String msg = "Unable to copy file " + f + " to path " + directoryPath
                                + " with permissions  " + permissions;
                        s_logger.debug(msg);
                        throw new CloudRuntimeException("Unable to setup the server: " + msg, e);
                    }
                }
            }

        } catch (final IOException e) {
            throw new CloudRuntimeException("Unable to setup the server correctly", e);
        } finally {
            sshConnection.close();
        }
        hr.tags.add("vmops-version-" + version);
        host.setTags(conn, hr.tags);
        return true;
    } catch (final XenAPIException e) {
        final String msg = "XenServer setup failed due to " + e.toString();
        s_logger.warn(msg, e);
        throw new CloudRuntimeException("Unable to get host information " + e.toString(), e);
    } catch (final XmlRpcException e) {
        final String msg = "XenServer setup failed due to " + e.getMessage();
        s_logger.warn(msg, e);
        throw new CloudRuntimeException("Unable to get host information ", e);
    }
}

From source file:org.apache.hadoop.hive.metastore.ObjectStore.java

/**
 * Properties specified in hive-default.xml override the properties specified
 * in jpox.properties./*from ww  w  .j  av a  2s.c  om*/
 */
@SuppressWarnings("nls")
private static Properties getDataSourceProps(Configuration conf) {
    Properties prop = new Properties();
    correctAutoStartMechanism(conf);

    Iterator<Map.Entry<String, String>> iter = conf.iterator();
    while (iter.hasNext()) {
        Map.Entry<String, String> e = iter.next();
        if (e.getKey().contains("datanucleus") || e.getKey().contains("jdo")) {
            Object prevVal = prop.setProperty(e.getKey(), conf.get(e.getKey()));
            if (LOG.isDebugEnabled() && !e.getKey().equals(HiveConf.ConfVars.METASTOREPWD.varname)) {
                LOG.debug("Overriding " + e.getKey() + " value " + prevVal + " from  jpox.properties with "
                        + e.getValue());
            }
        }
    }
    // Password may no longer be in the conf, use getPassword()
    try {
        String passwd = ShimLoader.getHadoopShims().getPassword(conf, HiveConf.ConfVars.METASTOREPWD.varname);
        if (passwd != null && !passwd.isEmpty()) {
            prop.setProperty(HiveConf.ConfVars.METASTOREPWD.varname, passwd);
        }
    } catch (IOException err) {
        throw new RuntimeException("Error getting metastore password: " + err.getMessage(), err);
    }

    if (LOG.isDebugEnabled()) {
        for (Entry<Object, Object> e : prop.entrySet()) {
            if (!e.getKey().equals(HiveConf.ConfVars.METASTOREPWD.varname)) {
                LOG.debug(e.getKey() + " = " + e.getValue());
            }
        }
    }

    return prop;
}

From source file:com.cloud.hypervisor.xen.resource.CitrixResourceBase.java

protected boolean setupServer(Connection conn) {
    String packageVersion = CitrixResourceBase.class.getPackage().getImplementationVersion();
    String version = this.getClass().getName() + "-"
            + (packageVersion == null ? Long.toString(System.currentTimeMillis()) : packageVersion);

    try {//  w  w  w.jav a2 s .  co m
        Host host = Host.getByUuid(conn, _host.uuid);
        /* enable host in case it is disabled somehow */
        host.enable(conn);
        /* push patches to XenServer */
        Host.Record hr = host.getRecord(conn);

        Iterator<String> it = hr.tags.iterator();

        while (it.hasNext()) {
            String tag = it.next();
            if (tag.startsWith("vmops-version-")) {
                if (tag.contains(version)) {
                    s_logger.info(logX(host, "Host " + hr.address + " is already setup."));
                    return false;
                } else {
                    it.remove();
                }
            }
        }

        com.trilead.ssh2.Connection sshConnection = new com.trilead.ssh2.Connection(hr.address, 22);
        try {
            sshConnection.connect(null, 60000, 60000);
            if (!sshConnection.authenticateWithPassword(_username, _password.peek())) {
                throw new CloudRuntimeException("Unable to authenticate");
            }

            com.trilead.ssh2.Session session = sshConnection.openSession();
            SCPClient scp = new SCPClient(sshConnection);

            List<File> files = getPatchFiles();
            if (files == null || files.isEmpty()) {
                throw new CloudRuntimeException("Can not find patch file");
            }
            for (File file : files) {
                String path = file.getParentFile().getAbsolutePath() + "/";
                Properties props = new Properties();
                props.load(new FileInputStream(file));

                for (Map.Entry<Object, Object> entry : props.entrySet()) {
                    String k = (String) entry.getKey();
                    String v = (String) entry.getValue();

                    assert (k != null && k.length() > 0 && v != null && v.length() > 0) : "Problems with " + k
                            + "=" + v;

                    String[] tokens = v.split(",");
                    String f = null;
                    if (tokens.length == 3 && tokens[0].length() > 0) {
                        if (tokens[0].startsWith("/")) {
                            f = tokens[0];
                        } else if (tokens[0].startsWith("~")) {
                            String homedir = System.getenv("HOME");
                            f = homedir + tokens[0].substring(1) + k;
                        } else {
                            f = path + tokens[0] + '/' + k;
                        }
                    } else {
                        f = path + k;
                    }
                    String d = tokens[tokens.length - 1];
                    f = f.replace('/', File.separatorChar);

                    String p = "0755";
                    if (tokens.length == 3) {
                        p = tokens[1];
                    } else if (tokens.length == 2) {
                        p = tokens[0];
                    }

                    if (!new File(f).exists()) {
                        s_logger.warn("We cannot locate " + f);
                        continue;
                    }
                    if (s_logger.isDebugEnabled()) {
                        s_logger.debug(
                                "Copying " + f + " to " + d + " on " + hr.address + " with permission " + p);
                    }
                    try {
                        session.execCommand("mkdir -m 700 -p " + d);
                    } catch (IOException e) {
                        s_logger.debug("Unable to create destination path: " + d + " on " + hr.address
                                + " but trying anyway");

                    }
                    scp.put(f, d, p);

                }
            }

        } catch (IOException e) {
            throw new CloudRuntimeException("Unable to setup the server correctly", e);
        } finally {
            sshConnection.close();
        }
        hr.tags.add("vmops-version-" + version);
        host.setTags(conn, hr.tags);
        return true;
    } catch (XenAPIException e) {
        String msg = "Xen setup failed due to " + e.toString();
        s_logger.warn(msg, e);
        throw new CloudRuntimeException("Unable to get host information " + e.toString(), e);
    } catch (XmlRpcException e) {
        String msg = "Xen setup failed due to " + e.getMessage();
        s_logger.warn(msg, e);
        throw new CloudRuntimeException("Unable to get host information ", e);
    }
}

From source file:de.innovationgate.wgpublisher.WGACore.java

public WGDatabase connectPlugin(WGAPlugin plugin, Map domainConfigs, Set connectedPlugins)
        throws Problem, InvalidPluginException, WGIllegalArgumentException, FileSystemException, IOException {

    // Look if already connected to the correct file
    String dbKey = plugin.buildDatabaseKey();
    WGDatabase db = contentdbs.get(dbKey);
    if (db != null) {
        try {/*from  w  ww. j av  a  2s .  c om*/
            Long pluginFileTime = (Long) db.getAttribute(DBATTRIB_PLUGIN_FILETIME);
            Version pluginVersion = (Version) db.getAttribute(DBATTRIB_PLUGIN_VERSION);
            if (pluginVersion.equals(plugin.getPluginID().getVersion()) && (pluginFileTime != null
                    && pluginFileTime.equals(new Long(plugin.getFileLastModified())))) {
                if (!db.isSessionOpen()) {
                    db.openSession();
                }
                return null;
            } else {
                removeContentDB(dbKey);
                db = null;
            }
        } catch (Exception e) {
            throw new InvalidPluginException(plugin, "Error checking existent plugin database " + dbKey, e);
        }
    }

    if (!plugin.isActive()) {
        throw new InvalidPluginException(plugin, "Plugin is deactivated");
    }
    if (!plugin.isValid()) {
        throw new InvalidPluginException(plugin, "Plugin is invalid");
    }

    // First connect all mandatory plugins
    try {

        Iterator mandatoryPlugins = plugin.getMandatoryPlugins().values().iterator();
        while (mandatoryPlugins.hasNext()) {
            WGAPlugin mandatoryPlugin = (WGAPlugin) mandatoryPlugins.next();
            connectPlugin(mandatoryPlugin, domainConfigs, connectedPlugins);
        }
    }
    // A mandatory plugin is invalid. Cancel connect.
    catch (InvalidPluginException e) {
        throw e;
    }

    logCategoryInfo("Plugin " + plugin.getInstallationKey(), 2);

    // Mandatory db options (for plugins)
    Map<String, String> dbOptions = new HashMap<String, String>();
    dbOptions.put(WGDatabase.COPTION_DBREFERENCE, dbKey.toLowerCase());
    dbOptions.put(WGDatabase.COPTION_READERPROFILECREATION, "true");
    putDefaultDbOptions(dbOptions);
    dbOptions.put(WGDatabase.COPTION_CLUSTERED, "false");

    // We try to automatically migrate plugin content stores to CS5 format
    dbOptions.put(WGDatabase.COPTION_CONTENT_STORE_VERSION, String.valueOf(WGDatabase.CSVERSION_WGA5));
    dbOptions.put(Database.OPTION_PATH, plugin.getInstallationKey());

    // Ugly hack to insert DB options for plugin debugging
    File optionsFile = getWGAFile(plugin.getPluginID().getUniqueName() + ".dboptions.properties");
    if (optionsFile != null && optionsFile.exists()) {
        Properties props = new Properties();
        FileInputStream in = new FileInputStream(optionsFile);
        props.load(in);
        in.close();
        for (Map.Entry<Object, Object> option : props.entrySet()) {
            dbOptions.put(String.valueOf(option.getKey()), String.valueOf(option.getValue()));
        }
    }

    // Clear the plugin database before connecting if the plugin is updated and should clear the db on update
    if (plugin.getRuntimeContext().isUpdated()) {
        if (plugin.getCsConfig()
                .getPluginConfig() instanceof de.innovationgate.wga.common.beans.csconfig.v3.PluginConfig) {
            de.innovationgate.wga.common.beans.csconfig.v3.PluginConfig v3Config = (de.innovationgate.wga.common.beans.csconfig.v3.PluginConfig) plugin
                    .getCsConfig().getPluginConfig();
            if (v3Config.isClearDatabaseOnUpdate()) {
                getLog().info("Clearing plugin database for installation key " + plugin.getInstallationKey());
                plugin.getParent().deletePluginDatabase(plugin);
            }
        }
        plugin.getRuntimeContext().setUpdated(false);
    }

    // Optionally add hotpatches path
    String hotPatchesPath = System.getProperty(SYSPROPERTY_JDBC_HOTPATCHES);
    if (hotPatchesPath != null) {
        File hotPatchesFile = getWGAFile(hotPatchesPath);
        if (hotPatchesFile != null) {
            dbOptions.put(WGDatabaseImpl.COPTION_HOTPATCH, hotPatchesFile.getAbsolutePath());
        }
    }

    // Determine WGAPI implementation
    boolean usesDatabase = true;
    if (plugin.getCsConfig()
            .getPluginConfig() instanceof de.innovationgate.wga.common.beans.csconfig.v5.PluginConfig) {
        de.innovationgate.wga.common.beans.csconfig.v5.PluginConfig v5PluginConfig = (de.innovationgate.wga.common.beans.csconfig.v5.PluginConfig) plugin
                .getCsConfig().getPluginConfig();
        if ("true".equals(v5PluginConfig.getOptions()
                .get(de.innovationgate.wga.common.beans.csconfig.v5.PluginConfig.OPTION_NO_DATABASE))) {
            usesDatabase = false;
        }
    }

    Class<? extends WGDatabaseCore> implClass;
    if (usesDatabase) {
        if (!"false".equals(System.getProperty("de.innovationgate.wga.plugin.lazydbs"))) {
            implClass = de.innovationgate.webgate.api.hsql.WGLazyDatabaseImpl.class;
        } else {
            implClass = de.innovationgate.webgate.api.hsql.WGDatabaseImpl.class;
        }
    } else {
        implClass = WGFakeContentStore.class;
    }

    // Connect
    getLog().info("Connecting plugin " + plugin.getPluginID().getUniqueName() + " Version "
            + plugin.getPluginID().getVersion().toString());

    try {
        db = getPluginSet().getDbServer().openDatabase(implClass, dbOptions);
    } catch (Throwable e1) {
        throw new InvalidPluginException(plugin,
                "Could not connect plugin \"" + plugin.getPluginID().getUniqueName() + "\"", e1);
    }

    if (db == null || !db.isSessionOpen()) {
        throw new InvalidPluginException(plugin, "Could not connect plugin \""
                + plugin.getPluginID().getUniqueName() + "\" - Check logged messages above for error details");
    }

    try {
        db.getSessionContext().setTask("Initializing database in WGA");

        // Plugin dbs are always CS5 since they are automatically migrated
        //getLog().info("Database of plugin " + plugin.getPluginID().getUniqueName() + " is content store version " + db.getContentStoreVersion());

        PluginConfig pc = plugin.getCsConfig().getPluginConfig();
        String auth = pc.getAuthentication();
        db.setTitle(pc.getTitle());

        // Set mandatory database attributes
        initializeDBAttributes(db, dbKey, dbKey, new HashSet());

        // Create authentication
        if (auth != null) {
            String authImplClass = null;
            Map<String, String> authOptions = new HashMap<String, String>();

            // Delegate authentication to the default domain
            if (auth.equals(PluginConfig.AUTHSOURCE_DEFAULT_DOMAIN)) {
                authImplClass = WGAAuthModuleFactory.AUTHMODULE_DELEGATE;
                authOptions.put(DelegatingAuthModule.COPTION_DOMAIN, "default");
            }
            // Use some plugin for authentication
            else {
                WGAPlugin authPlugin = plugin.getParent().getPluginByUniqueName(auth);
                if (authPlugin != null) {
                    authImplClass = CSAuthModule.class.getName();
                    authOptions.put(CSAuthModule.COPTION_DBKEY, authPlugin.buildDatabaseKey());
                } else {
                    getLog().error("Unable to find authentication plugin " + auth);
                }
            }

            if (authImplClass != null) {
                AuthenticationModule authModule = WGFactory.getAuthModuleFactory().getAuthModule(authImplClass,
                        authOptions, db);
                db.setAuthenticationModule(authModule);
            }

        }

        // Enforce some plugin settings via db attributes
        if (usesDatabase) {
            db.setAttribute(DBATTRIB_PERSMODE, String.valueOf(pc.getPersonalisationMode()));
        } else {
            db.setAttribute(DBATTRIB_PERSMODE, String.valueOf(Constants.PERSMODE_SESSION));
        }
        db.setAttribute(DBATTRIB_PERSSTATMODE, String.valueOf(Constants.PERSSTATMODE_SESSION));
        db.setAttribute(DBATTRIB_PLUGIN_FILETIME, new Long(plugin.getFileLastModified()));
        db.setAttribute(DBATTRIB_PLUGIN_ID, plugin.getPluginID());
        db.setAttribute(DBATTRIB_PLUGIN_VERSION, plugin.getPluginID().getVersion());

        if (!pc.isUsageAsContentStore()) {
            db.setAttribute(DBATTRIB_ALLOW_PUBLISHING, "false");
        }

        if (!pc.isShowOnStartPage()) {
            db.setAttribute(DBATTRIB_STARTPAGE, "false");
        }

        // Configure design provider
        DesignReference ref = new DesignReference(Constants.DESIGNCOL_PLUGIN, plugin.getInstallationKey(),
                null);
        Map<String, String> options = new HashMap<String, String>();
        db.setDesignProvider(
                new FileSystemDesignProvider(ref, this, db, plugin.getDesignURL().toString(), options));
        db.setAllowDesignModification(false);
        getDesignFileCache().flushGroup(ref.toString());

        // Determine if ACL is empty
        boolean aclEmpty = false;
        try {
            if (db.isConnected() && db.hasFeature(WGDatabase.FEATURE_ACL_MANAGEABLE)
                    && db.getACL().getAllEntries().size() == 0) {
                aclEmpty = true;
            }
        } catch (WGBackendException e1) {
            getLog().error("Error retrieving ACL state of db '" + db.getDbReference() + "'", e1);
        }

        // Process system container
        SystemContainerManager.SystemContainerContext scContext = null;
        try {
            scContext = _systemContainerManager.addDatabase(db, plugin, aclEmpty);
        } catch (Problem p) {
            throw p;
        } catch (Exception e) {
            throw new InvalidPluginException(plugin, "Exception processing system file container for plugin '"
                    + plugin.getPluginID().getUniqueName() + "'", e);
        }

        // Build map of publisher options from wga.xml. We only use gobal options here since plugins have no own options in wga.xml
        // and csconfig.xml options are processed via system container
        Map<String, String> publisherOptions = new HashMap<String, String>();
        // publisherOptions.putAll(_globalPublisherOptions); Plugins should not be influenced by global options of the current configuration
        if (scContext != null) {
            scContext.putPublisherOptions(publisherOptions);
        }

        // Publisher options initialisation which is equal for content dbs and plugins
        processPublisherOptions(db, publisherOptions);

        // Set plugin homepage. The method chooses either the plugin-specific homepage or the publisher option
        // Must be after publisher option initialisation to be able to react on them
        db.setAttribute(DBATTRIB_HOME_PAGE, plugin.getPluginHomepage());

        // check if db is empty before hdb script runs
        boolean isEmptyDB = db.isContentEmpty();

        // Validate default language definition
        if (!isEmptyDB) {
            db.determineDefaultLanguage();
        }

        // Add listeners for events and register embedded event scripts
        db.addDatabaseEventListener(_eventManager);
        db.addContentEventListener(_eventManager);
        db.addWorkflowEventListener(_eventManager);
        if (db.isConnected()) {
            _eventManager.updateDatabaseEvents(db);
        }

        // Add file annotators
        updateFileAnnotators(db);

        // add File Converter
        db.setFileConverter(_fileConverter);

        // System container initialisations
        if (scContext != null) {
            scContext.performInitialisation(new Boolean(isEmptyDB));
            if (isEmptyDB) {
                db.onConnect(new ValidateDefaultLanguageAction());
            }
        }

        // Registering connection
        this.contentdbs.put(db.getDbReference(), db);
        performNewDBOperations(db);

        // Mark this database as fully connected
        db.setAttribute(DBATTRIB_FULLY_CONNECTED, "true");

        // Initially create field mappings. These can only come from csconfig.xml for plugins
        updateFieldMappings(db, null);

        // Add to connected plugins
        connectedPlugins.add(db.getDbReference());

        return db;
    } catch (Throwable e) {
        try {
            db.close();
        } catch (WGAPIException e2) {
            // Silent failure of closing an uninitialized plugin bc. the connection failure is more important
        }
        plugin.setValid(false);
        if (e instanceof Problem) {
            throw (Problem) e;
        } else {
            throw new InvalidPluginException(plugin, "Error connecting plugin", e);
        }
    }

}

From source file:org.rm3l.ddwrt.tiles.admin.nvram.AdminNVRAMTile.java

public AdminNVRAMTile(@NotNull SherlockFragment parentFragment, @NotNull Bundle arguments,
        @Nullable Router router) {//from ww  w  . j av a2 s .co m
    super(parentFragment, arguments, router, R.layout.tile_admin_nvram, R.id.tile_admin_nvram_togglebutton);

    sortIds.put(R.id.tile_admin_nvram_sort_default, 11);
    sortIds.put(R.id.tile_admin_nvram_sort_asc, 12);
    sortIds.put(R.id.tile_admin_nvram_sort_desc, 13);

    this.mNvramInfoDefaultSorting = new NVRAMInfo();
    mRecyclerView = (RecyclerView) layout.findViewById(R.id.tile_admin_nvram_ListView);

    // use this setting to improve performance if you know that changes
    // in content do not change the layout size of the RecyclerView
    // allows for optimizations if all items are of the same size:
    mRecyclerView.setHasFixedSize(true);

    // use a linear layout manager
    mLayoutManager = new LinearLayoutManager(mParentFragmentActivity);
    mLayoutManager.scrollToPosition(0);
    mRecyclerView.setLayoutManager(mLayoutManager);

    // specify an adapter (see also next example)
    mAdapter = new NVRAMDataRecyclerViewAdapter(mParentFragmentActivity, router, mNvramInfoDefaultSorting);
    mRecyclerView.setAdapter(mAdapter);

    //Create Options Menu
    final ImageButton tileMenu = (ImageButton) layout.findViewById(R.id.tile_admin_nvram_menu);

    if (!isThemeLight(mParentFragmentActivity, mRouter.getUuid())) {
        //Set menu background to white
        tileMenu.setImageResource(R.drawable.abs__ic_menu_moreoverflow_normal_holo_dark);
    }

    tileMenu.setOnClickListener(new View.OnClickListener() {
        @Override
        public void onClick(View v) {
            final PopupMenu popup = new PopupMenu(mParentFragmentActivity, v);
            popup.setOnMenuItemClickListener(AdminNVRAMTile.this);
            final MenuInflater inflater = popup.getMenuInflater();

            final Menu menu = popup.getMenu();

            inflater.inflate(R.menu.tile_admin_nvram_options, menu);

            //Disable menu item from preference
            Integer currentSort = null;
            if (mParentFragmentPreferences != null) {
                currentSort = sortIds.inverse().get(mParentFragmentPreferences.getInt(getFormattedPrefKey(SORT),
                        sortIds.get(R.id.tile_admin_nvram_sort_default)));
            }

            if (currentSort == null) {
                currentSort = R.id.tile_admin_nvram_sort_default;
            }

            final MenuItem currentSortMenuItem = menu.findItem(currentSort);
            if (currentSortMenuItem != null) {
                currentSortMenuItem.setEnabled(false);
            }

            // Locate MenuItem with ShareActionProvider
            final MenuItem shareMenuItem = menu.findItem(R.id.tile_admin_nvram_share);

            // Fetch and store ShareActionProvider
            mShareActionProvider = (ShareActionProvider) shareMenuItem.getActionProvider();

            popup.show();
        }

    });

    //Handle for Search EditText
    final EditText filterEditText = (EditText) this.layout.findViewById(R.id.tile_admin_nvram_filter);
    //Initialize with existing search data
    filterEditText.setText(mParentFragmentPreferences != null
            ? mParentFragmentPreferences.getString(getFormattedPrefKey(LAST_SEARCH), EMPTY_STRING)
            : EMPTY_STRING);

    filterEditText.setOnTouchListener(new View.OnTouchListener() {
        @Override
        public boolean onTouch(View v, MotionEvent event) {
            final int DRAWABLE_LEFT = 0;
            final int DRAWABLE_TOP = 1;
            final int DRAWABLE_RIGHT = 2;
            final int DRAWABLE_BOTTOM = 3;

            if (event.getAction() == MotionEvent.ACTION_UP) {
                if (event.getRawX() >= (filterEditText.getRight()
                        - filterEditText.getCompoundDrawables()[DRAWABLE_RIGHT].getBounds().width())) {
                    //'Clear' button - clear data, and reset everything out
                    //Reset everything
                    filterEditText.setText(EMPTY_STRING);

                    final Properties mNvramInfoDefaultSortingData = mNvramInfoDefaultSorting.getData();
                    //Update adapter in the preferences
                    if (mParentFragmentPreferences != null) {
                        final Integer currentSort = sortIds.inverse()
                                .get(mParentFragmentPreferences.getInt(getFormattedPrefKey(SORT), -1));
                        if (currentSort == null || currentSort <= 0) {
                            mNvramInfoToDisplay = new HashMap<>(mNvramInfoDefaultSortingData);
                        } else {
                            switch (currentSort) {
                            case R.id.tile_admin_nvram_sort_asc:
                                //asc
                                mNvramInfoToDisplay = new TreeMap<>(COMPARATOR_STRING_CASE_INSENSITIVE);
                                break;
                            case R.id.tile_admin_nvram_sort_desc:
                                //desc
                                mNvramInfoToDisplay = new TreeMap<>(COMPARATOR_REVERSE_STRING_CASE_INSENSITIVE);
                                break;
                            case R.id.tile_admin_nvram_sort_default:
                            default:
                                mNvramInfoToDisplay = new HashMap<>();
                                break;
                            }
                            mNvramInfoToDisplay.putAll(mNvramInfoDefaultSortingData);
                        }
                    } else {
                        mNvramInfoToDisplay = new HashMap<>(mNvramInfoDefaultSortingData);
                    }

                    ((NVRAMDataRecyclerViewAdapter) mAdapter).setEntryList(mNvramInfoToDisplay);
                    mAdapter.notifyDataSetChanged();

                    if (mParentFragmentPreferences != null) {
                        final SharedPreferences.Editor editor = mParentFragmentPreferences.edit();
                        editor.putString(getFormattedPrefKey(LAST_SEARCH), EMPTY_STRING);
                        editor.apply();
                    }
                    return true;
                }
            }
            return false;
        }
    });

    filterEditText.setOnEditorActionListener(new TextView.OnEditorActionListener() {
        @Override
        public boolean onEditorAction(TextView v, int actionId, KeyEvent event) {

            if (actionId == EditorInfo.IME_ACTION_SEARCH) {
                final String textToFind = filterEditText.getText().toString();
                if (isNullOrEmpty(textToFind)) {
                    //extra-check, even though we can be pretty sure the button is enabled only if textToFind is present
                    return true;
                }
                final String existingSearch = mParentFragmentPreferences != null
                        ? mParentFragmentPreferences.getString(getFormattedPrefKey(LAST_SEARCH), null)
                        : null;

                if (mParentFragmentPreferences != null) {
                    if (textToFind.equalsIgnoreCase(existingSearch)) {
                        //No need to go further as this is already the string we are looking for
                        return true;
                    }
                    final SharedPreferences.Editor editor = mParentFragmentPreferences.edit();
                    editor.putString(getFormattedPrefKey(LAST_SEARCH), textToFind);
                    editor.apply();
                }

                //Filter out (and sort by user-preference)
                final Properties mNvramInfoDefaultSortingData = mNvramInfoDefaultSorting.getData();
                //Update adapter in the preferences
                final Map<Object, Object> mNvramInfoToDisplayCopy;
                if (mParentFragmentPreferences != null) {
                    final Integer currentSort = sortIds.inverse()
                            .get(mParentFragmentPreferences.getInt(getFormattedPrefKey(SORT), -1));
                    if (currentSort == null || currentSort <= 0) {
                        mNvramInfoToDisplayCopy = new HashMap<>(mNvramInfoDefaultSortingData);
                    } else {
                        switch (currentSort) {
                        case R.id.tile_admin_nvram_sort_asc:
                            //asc
                            mNvramInfoToDisplayCopy = new TreeMap<>(COMPARATOR_STRING_CASE_INSENSITIVE);
                            break;
                        case R.id.tile_admin_nvram_sort_desc:
                            //desc
                            mNvramInfoToDisplayCopy = new TreeMap<>(COMPARATOR_REVERSE_STRING_CASE_INSENSITIVE);
                            break;
                        case R.id.tile_admin_nvram_sort_default:
                        default:
                            mNvramInfoToDisplayCopy = new HashMap<>();
                            break;
                        }
                        //noinspection ConstantConditions
                        for (Map.Entry<Object, Object> entry : mNvramInfoDefaultSortingData.entrySet()) {
                            final Object key = entry.getKey();
                            final Object value = entry.getValue();
                            if (key == null) {
                                continue;
                            }
                            if (containsIgnoreCase(key.toString(), textToFind)
                                    || containsIgnoreCase(value.toString(), textToFind)) {
                                mNvramInfoToDisplayCopy.put(key, value);
                            }
                        }
                    }
                } else {
                    mNvramInfoToDisplayCopy = new HashMap<>();
                    //noinspection ConstantConditions
                    for (Map.Entry<Object, Object> entry : mNvramInfoDefaultSortingData.entrySet()) {
                        final Object key = entry.getKey();
                        final Object value = entry.getValue();
                        if (key == null) {
                            continue;
                        }
                        if (containsIgnoreCase(key.toString(), textToFind)
                                || containsIgnoreCase(value.toString(), textToFind)) {
                            mNvramInfoToDisplayCopy.put(key, value);
                        }
                    }
                }

                ((NVRAMDataRecyclerViewAdapter) mAdapter).setEntryList(mNvramInfoToDisplayCopy);
                mAdapter.notifyDataSetChanged();

                return true;
            }
            return false;
        }
    });

}