Search in sources :

Example 86 with Properties

use of org.apache.felix.utils.properties.Properties in project fabric8 by jboss-fuse.

the class ProfileUtils method toProperties.

public static Properties toProperties(Map<String, String> source) {
    if (source instanceof Properties) {
        return (Properties) source;
    }
    Properties rc = new Properties(false);
    rc.putAll(source);
    return rc;
}
Also used : Properties(org.apache.felix.utils.properties.Properties)

Example 87 with Properties

use of org.apache.felix.utils.properties.Properties in project fabric8 by jboss-fuse.

the class CreateAction method doExecute.

protected Object doExecute() throws Exception {
    String adminRole = "admin";
    String administratorRole = "administrator";
    String superUserRole = "superuser";
    boolean adminExists = hasRole(adminRole, superUserRole, administratorRole);
    if (!adminExists) {
        System.out.println("The fabric:create command can be executed only by admin user");
        return null;
    }
    Path propsPath = runtimeProperties.getConfPath().resolve("users.properties");
    Properties userProps = new Properties(propsPath.toFile());
    if (!adminExists && !usersPropertiesFileContainsRole(userProps, adminRole, superUserRole, administratorRole)) {
        System.out.println("The etc/user.properties file must contain at least one admin user, if no other admin exists");
        return null;
    }
    // prevent creating fabric if already created
    ServiceReference<FabricService> sref = bundleContext.getServiceReference(FabricService.class);
    FabricService fabricService = sref != null ? bundleContext.getService(sref) : null;
    if (!force && (fabricService != null && fabricService.getCurrentContainer().isEnsembleServer())) {
        System.out.println("Current container " + fabricService.getCurrentContainerName() + " is already in the current fabric ensemble. Cannot create fabric.");
        System.out.println("You can use the --force option, if you want to force re-create the fabric.");
        return null;
    }
    Configuration bootConfiguration = configAdmin.getConfiguration(BootstrapConfiguration.COMPONENT_PID, null);
    Dictionary<String, Object> bootProperties = bootConfiguration.getProperties();
    if (bootProperties == null) {
        bootProperties = new Hashtable<>();
    }
    String runtimeIdentity = runtimeProperties.getRuntimeIdentity();
    CreateEnsembleOptions.Builder<?> builder = CreateEnsembleOptions.builder().zooKeeperServerTickTime(zooKeeperTickTime).zooKeeperServerInitLimit(zooKeeperInitLimit).zooKeeperServerSyncLimit(zooKeeperSyncLimit).zooKeeperServerDataDir(zooKeeperDataDir).zookeeperSnapRetainCount(zookeeperSnapRetainCount).zookeeperPurgeInterval(zookeeperPurgeInterval).fromRuntimeProperties(runtimeProperties).bootstrapTimeout(bootstrapTimeout).waitForProvision(waitForProvisioning).autoImportEnabled(!noImport).clean(clean);
    builder.version(version);
    if (containers == null || containers.isEmpty()) {
        containers = Arrays.asList(runtimeIdentity);
    }
    if (!noImport && importDir != null) {
        builder.autoImportEnabled(true);
        builder.importPath(importDir);
    }
    if (globalResolver != null) {
        if (!isInEnum(globalResolver, ResolverPolicyEnum.class)) {
            System.out.println("The globalResolver value must be one of the following: localip, localhostname, publicip, publichostname, manualip");
            return null;
        }
        builder.globalResolver(globalResolver);
        bootProperties.put(ZkDefs.GLOBAL_RESOLVER_PROPERTY, globalResolver);
    }
    if (resolver != null) {
        if (!isInEnum(resolver, ResolverPolicyEnum.class)) {
            System.out.println("The resolver value must be one of the following: localip, localhostname, publicip, publichostname, manualip");
            return null;
        }
        builder.resolver(resolver);
        bootProperties.put(ZkDefs.LOCAL_RESOLVER_PROPERTY, resolver);
    }
    if (manualIp != null) {
        builder.manualIp(manualIp);
        bootProperties.put(ZkDefs.MANUAL_IP, manualIp);
    }
    if (bindAddress != null) {
        if (!bindAddress.contains(":")) {
            builder.bindAddress(bindAddress);
            bootProperties.put(ZkDefs.BIND_ADDRESS, bindAddress);
        } else {
            String[] parts = bindAddress.split(":");
            builder.bindAddress(parts[0]);
            builder.zooKeeperServerPort(Integer.parseInt(parts[1]));
            bootProperties.put(ZkDefs.BIND_ADDRESS, parts[0]);
        }
    }
    if (zooKeeperServerPort > 0) {
        // --zookeeper-server-port option has higher priority than
        // CreateEnsembleOptions.ZOOKEEPER_SERVER_PORT and CreateEnsembleOptions.ZOOKEEPER_SERVER_CONNECTION_PORT
        // system/runtime properties
        builder.setZooKeeperServerPort(zooKeeperServerPort);
        builder.setZooKeeperServerConnectionPort(zooKeeperServerPort);
    } else {
        int shiftedPort = Ports.mapPortToRange(2181, minimumPort, maximumPort);
        builder.setZooKeeperServerPort(shiftedPort);
        builder.setZooKeeperServerConnectionPort(shiftedPort);
    }
    // Configure External Git Repository.
    if (externalGitUrl != null) {
        builder.dataStoreProperty(Constants.GIT_REMOTE_URL, externalGitUrl);
    }
    if (externalGitUser != null) {
        builder.dataStoreProperty(GIT_REMOTE_USER, externalGitUser);
    }
    if (externalGitPassword != null) {
        builder.dataStoreProperty(GIT_REMOTE_PASSWORD, externalGitPassword);
    }
    if ((externalGitUrl != null) || (externalGitUser != null) || (externalGitPassword != null)) {
        Configuration configuration = configAdmin.getConfiguration(Constants.DATASTORE_PID);
        Dictionary<String, Object> existingProperties = configuration.getProperties();
        Map<String, String> changedProperties = builder.getDataStoreProperties();
        for (String key : changedProperties.keySet()) {
            existingProperties.put(key, changedProperties.get(key));
        }
        configuration.update(existingProperties);
    }
    if (profiles != null && profiles.size() > 0) {
        builder.profiles(profiles);
    }
    if (nonManaged) {
        builder.agentEnabled(false);
    } else {
        builder.agentEnabled(true);
    }
    builder.minimumPort(minimumPort);
    builder.maximumPort(maximumPort);
    bootProperties.put(ZkDefs.MINIMUM_PORT, String.valueOf(minimumPort));
    bootProperties.put(ZkDefs.MAXIMUM_PORT, String.valueOf(maximumPort));
    newUser = newUser != null ? newUser : ShellUtils.retrieveFabricUser(session);
    newUserPassword = newUserPassword != null ? newUserPassword : ShellUtils.retrieveFabricUserPassword(session);
    if (userProps.isEmpty()) {
        String[] credentials = promptForNewUser(newUser, newUserPassword);
        newUser = credentials[0];
        newUserPassword = credentials[1];
    } else {
        if (newUser == null || newUserPassword == null) {
            newUser = "" + userProps.keySet().iterator().next();
            newUserPassword = "" + userProps.get(newUser);
            if (newUserPassword.contains(ROLE_DELIMITER)) {
                newUserPassword = newUserPassword.substring(0, newUserPassword.indexOf(ROLE_DELIMITER));
            }
        }
        String passwordWithroles = userProps.get(newUser);
        if (passwordWithroles != null && passwordWithroles.contains(ROLE_DELIMITER)) {
            String[] infos = passwordWithroles.split(",");
            String oldUserRole = "";
            if (newUserIsAdmin(infos)) {
                newUserRole = "_g_:admin";
                oldUserRole = newUserRole;
            }
            for (int i = 1; i < infos.length; i++) {
                if (infos[i].trim().startsWith(BackingEngine.GROUP_PREFIX)) {
                    // it's a group reference
                    String groupInfo = (String) userProps.get(infos[i].trim());
                    if (groupInfo != null) {
                        String[] roles = groupInfo.split(",");
                        for (int j = 1; j < roles.length; j++) {
                            if (!roles[j].trim().equals(oldUserRole)) {
                                if (!newUserRole.isEmpty()) {
                                    newUserRole = newUserRole + ROLE_DELIMITER + roles[j].trim();
                                } else {
                                    newUserRole = roles[j].trim();
                                }
                            }
                        }
                    }
                } else {
                    // it's an user reference
                    if (!infos[i].trim().equals(oldUserRole)) {
                        if (!newUserRole.isEmpty()) {
                            newUserRole = newUserRole + ROLE_DELIMITER + infos[i].trim();
                        } else {
                            newUserRole = infos[i].trim();
                        }
                    }
                }
            }
        }
    }
    if (Strings.isNullOrEmpty(newUser)) {
        System.out.println("No user specified. Cannot create a new fabric ensemble.");
        return null;
    }
    StringBuilder sb = new StringBuilder();
    // session is unset when this is called from FMC
    if (session != null) {
        ShellUtils.storeFabricCredentials(session, newUser, newUserPassword);
    }
    if (generateZookeeperPassword) {
    // do nothing use the generated password.
    } else if (zookeeperPassword == null) {
        zookeeperPassword = PasswordEncoder.decode(runtimeProperties.getProperty(CreateEnsembleOptions.ZOOKEEPER_PASSWORD, PasswordEncoder.encode(newUserPassword)));
        builder.zookeeperPassword(zookeeperPassword);
    } else {
        builder.zookeeperPassword(zookeeperPassword);
    }
    OsgiUtils.updateCmConfigurationAndWait(bundleContext, bootConfiguration, bootProperties, bootstrapTimeout, TimeUnit.MILLISECONDS);
    String roleToAssign = newUserRole.isEmpty() ? "_g_:admin" : newUserRole;
    CreateEnsembleOptions options = builder.users(userProps).withUser(newUser, newUserPassword, roleToAssign).build();
    if (containers.size() == 1 && containers.contains(runtimeIdentity)) {
        bootstrap.create(options);
    } else {
        ServiceProxy<ZooKeeperClusterService> serviceProxy = ServiceProxy.createServiceProxy(bundleContext, ZooKeeperClusterService.class);
        try {
            serviceProxy.getService().createCluster(containers, options);
        } finally {
            serviceProxy.close();
        }
    }
    ShellUtils.storeZookeeperPassword(session, options.getZookeeperPassword());
    if (zookeeperPassword == null && !generateZookeeperPassword) {
        sb.append("Zookeeper password: (reusing users ").append(newUser).append(" password:").append(options.getZookeeperPassword()).append(")\n");
        sb.append("(You can use the --zookeeper-password / --generate-zookeeper-password option to specify one.)\n");
    } else if (generateZookeeperPassword) {
        sb.append("Generated zookeeper password:").append(options.getZookeeperPassword());
    }
    System.out.println(sb.toString());
    if (!nonManaged && !waitForProvisioning) {
        System.out.println("It may take a couple of seconds for the container to provision...");
        System.out.println("You can use the --wait-for-provisioning option, if you want this command to block until the container is provisioned.");
    }
    return null;
}
Also used : Path(java.nio.file.Path) Configuration(org.osgi.service.cm.Configuration) BootstrapConfiguration(io.fabric8.zookeeper.bootstrap.BootstrapConfiguration) ResolverPolicyEnum(io.fabric8.boot.commands.support.ResolverPolicyEnum) Properties(org.apache.felix.utils.properties.Properties)

Example 88 with Properties

use of org.apache.felix.utils.properties.Properties in project fabric8 by jboss-fuse.

the class JoinAction method persistConfiguration.

/**
 * Persists configuration to storage.
 * Original code code from org.apache.karaf.shell.config.ConfigCommandSupport#persistConfiguration(org.osgi.service.cm.ConfigurationAdmin, java.lang.String, java.util.Dictionary)
 *
 * @param admin
 * @param pid
 * @param props
 * @throws IOException
 */
protected void persistConfiguration(ConfigurationAdmin admin, String pid, Dictionary<String, Object> props) throws IOException {
    File storageFile = new File(System.getProperty("karaf.etc"), pid + ".cfg");
    Configuration cfg = admin.getConfiguration(pid, null);
    if (cfg != null && cfg.getProperties() != null) {
        Object val = cfg.getProperties().get(FILEINSTALL_FILE_NAME);
        try {
            if (val instanceof URL) {
                storageFile = new File(((URL) val).toURI());
            }
            if (val instanceof URI) {
                storageFile = new File((URI) val);
            }
            if (val instanceof String) {
                storageFile = new File(new URL((String) val).toURI());
            }
        } catch (Exception e) {
            throw (IOException) new IOException(e.getMessage()).initCause(e);
        }
    }
    Properties p = new Properties(storageFile);
    for (Enumeration<String> keys = props.keys(); keys.hasMoreElements(); ) {
        String key = keys.nextElement();
        if (!org.osgi.framework.Constants.SERVICE_PID.equals(key) && !ConfigurationAdmin.SERVICE_FACTORYPID.equals(key) && !FILEINSTALL_FILE_NAME.equals(key)) {
            if (props.get(key) != null) {
                p.put(key, props.get(key).toString());
            }
        }
    }
    // remove "removed" properties from the file
    ArrayList<String> propertiesToRemove = new ArrayList<String>();
    for (String key : p.keySet()) {
        if (props.get(key) == null && !org.osgi.framework.Constants.SERVICE_PID.equals(key) && !ConfigurationAdmin.SERVICE_FACTORYPID.equals(key) && !FILEINSTALL_FILE_NAME.equals(key)) {
            propertiesToRemove.add(key);
        }
    }
    for (String key : propertiesToRemove) {
        p.remove(key);
    }
    // save the cfg file
    p.save();
}
Also used : Configuration(org.osgi.service.cm.Configuration) BootstrapConfiguration(io.fabric8.zookeeper.bootstrap.BootstrapConfiguration) ArrayList(java.util.ArrayList) IOException(java.io.IOException) SystemProperties(io.fabric8.api.SystemProperties) RuntimeProperties(io.fabric8.api.RuntimeProperties) Properties(org.apache.felix.utils.properties.Properties) File(java.io.File) URI(java.net.URI) URL(java.net.URL) BundleException(org.osgi.framework.BundleException) KeeperException(org.apache.zookeeper.KeeperException) IOException(java.io.IOException)

Example 89 with Properties

use of org.apache.felix.utils.properties.Properties in project fabric8 by jboss-fuse.

the class BootstrapConfiguration method loadPropertiesFrom.

private void loadPropertiesFrom(Dictionary<String, Object> dictionary, String from) {
    InputStream is = null;
    Properties properties = new Properties();
    try {
        is = new FileInputStream(from);
        properties.load(is);
        for (String key : properties.keySet()) {
            dictionary.put(key, properties.get(key));
        }
    } catch (Exception e) {
    // Ignore
    } finally {
        if (is != null) {
            try {
                is.close();
            } catch (Exception e) {
            // Ignore
            }
        }
    }
}
Also used : FileInputStream(java.io.FileInputStream) InputStream(java.io.InputStream) RuntimeProperties(io.fabric8.api.RuntimeProperties) Properties(org.apache.felix.utils.properties.Properties) FileInputStream(java.io.FileInputStream) IOException(java.io.IOException) UnknownHostException(java.net.UnknownHostException)

Example 90 with Properties

use of org.apache.felix.utils.properties.Properties in project fuse-karaf by jboss-fuse.

the class PropertiesFileResolver method resolve.

@Override
public String resolve(File firstChange, File base, File secondChange, boolean useFirstChangeAsBase, boolean rollback) /*=false*/
{
    try {
        Properties baseProperties = new Properties(false);
        if (base != null) {
            baseProperties.load(base);
        }
        Properties firstProperties = new Properties(false);
        firstProperties.load(firstChange);
        Properties secondProperties = new Properties(secondChange, false);
        secondProperties.load(secondChange);
        Properties result = useFirstChangeAsBase ? firstProperties : secondProperties;
        Properties otherSource = useFirstChangeAsBase ? secondProperties : firstProperties;
        // first let's iterate over what we have in selected base - we may already find new properties in
        // incoming change vs. base version
        Set<String> keys = new HashSet<>();
        for (Enumeration<?> e = result.propertyNames(); e.hasMoreElements(); ) {
            keys.add((String) e.nextElement());
        }
        for (String key : keys) {
            // treat more important properties (result) as "ours"
            Change state = kindOfChange(key, baseProperties, result, otherSource);
            switch(state) {
                case NONE:
                case ADDED_BY_US:
                case MODIFIED_BY_US:
                    // already reflected in "result" properties
                    break;
                case DELETED_BY_US:
                case BOTH_DELETED:
                case ADDED_BY_THEM:
                    // can't happen in this loop
                    break;
                case BOTH_ADDED:
                    result.put(key, specialPropertyMerge(key, firstProperties, secondProperties, rollback));
                    break;
                case BOTH_MODIFIED:
                    // may mean also that we have change vs. removal
                    if (secondProperties.getProperty(key) == null) {
                        result.remove(key);
                    } else {
                        result.put(key, specialPropertyMerge(key, firstProperties, secondProperties, rollback));
                    }
                    break;
                case DELETED_BY_THEM:
                    result.remove(key);
                    break;
                case MODIFIED_BY_THEM:
                    result.put(key, otherSource.getProperty(key));
                    break;
            }
        }
        // then we can have additions in less important change, for example if patch adds new properties
        // but we want to preserve layout of properties file from user (it may have user comments for example)
        // we will handle only properties added in "otherSource"
        keys.clear();
        for (Enumeration<?> e = otherSource.propertyNames(); e.hasMoreElements(); ) {
            keys.add((String) e.nextElement());
        }
        for (Enumeration<?> e = result.propertyNames(); e.hasMoreElements(); ) {
            String key = (String) e.nextElement();
            keys.remove(key);
        }
        for (String key : keys) {
            // treat more important properties (result) as "ours"
            Change state = kindOfChange(key, baseProperties, result, otherSource);
            switch(state) {
                case NONE:
                case BOTH_DELETED:
                case BOTH_ADDED:
                case BOTH_MODIFIED:
                case ADDED_BY_US:
                case MODIFIED_BY_US:
                case DELETED_BY_THEM:
                case DELETED_BY_US:
                    break;
                case ADDED_BY_THEM:
                case MODIFIED_BY_THEM:
                    result.put(key, otherSource.getProperty(key));
                    break;
            }
        }
        ByteArrayOutputStream baos = new ByteArrayOutputStream();
        result.store(baos, null);
        return new String(baos.toByteArray(), "UTF-8");
    } catch (Exception e) {
        Activator.log(LogService.LOG_ERROR, null, "Problem resolving conflict: " + e.getMessage(), e, true);
    }
    return null;
}
Also used : ByteArrayOutputStream(java.io.ByteArrayOutputStream) Properties(org.apache.felix.utils.properties.Properties) HashSet(java.util.HashSet)

Aggregations

Properties (org.apache.felix.utils.properties.Properties)95 IOException (java.io.IOException)35 File (java.io.File)33 Test (org.junit.Test)27 Subject (javax.security.auth.Subject)25 NamePasswordCallbackHandler (org.apache.karaf.jaas.modules.NamePasswordCallbackHandler)21 Path (java.nio.file.Path)13 HashMap (java.util.HashMap)11 ArrayList (java.util.ArrayList)10 Map (java.util.Map)9 FileInputStream (java.io.FileInputStream)8 URL (java.net.URL)8 MalformedURLException (java.net.MalformedURLException)7 HashSet (java.util.HashSet)6 Hashtable (java.util.Hashtable)6 LinkedHashMap (java.util.LinkedHashMap)6 TreeMap (java.util.TreeMap)6 ByteArrayOutputStream (java.io.ByteArrayOutputStream)5 FileNotFoundException (java.io.FileNotFoundException)5 LoginException (javax.security.auth.login.LoginException)5