All Downloads are FREE. Search and download functionalities are using the official Maven repository.

automately.core.data.UserData Maven / Gradle / Ivy

package automately.core.data;

import automately.core.data.Job;
import automately.core.data.Meta;
import automately.core.data.User;
import automately.core.data.comparators.JobComparator;
import automately.core.data.predicates.KeyStartsWithPredicate;
import com.hazelcast.core.ICountDownLatch;
import com.hazelcast.core.ILock;
import com.hazelcast.core.IMap;
import com.hazelcast.core.ISet;
import com.hazelcast.query.*;
import io.jcluster.JCluster;
import io.jcluster.core.Cluster;
import io.jsync.utils.CryptoUtils;

import java.util.Collection;
import java.util.Iterator;

/**
 * UserData is a utility that can be used to access data in the Cluster
 * and do certain operations.
 */
public class UserData {

    /**
     * Begin static code initialization.
     */

    static {
        if(JCluster.activeInstance() == null){
            throw new Error("Could not initialize JobUtil because the JCluster instance does not seem to be active.");
        }
    }

    private static Cluster cluster = JCluster.activeInstance().cluster();
    private static IMap users = cluster.data().persistentMap("users");
    private static IMap userMeta = cluster.data().persistentMap("users.meta");
    private static IMap jobs = cluster.data().persistentMap("jobs");

    /**
     * End static code initialization.
     */

    private UserData() {}

    /**
     * createUser allows you to quickly create a new User and store it in the Cluster.
     * it calls setUserPassword and setUserMetaDefaults.
     *
     * @param username the username you want to use
     * @param password the password you want to use
     *
     * @return returns the new User after it has been stored in the cluster
     */
    public static User createUser(String username, String password) {
        if (getUserByUsername(username) == null) {
            User user = new User();
            user.username = username;
            user.enabled = true;
            users.set(user.token(), user);
            setUserPassword(user, password);
            setMetaDefaults(user);
            return user;
        }
        return null;
    }

    /**
     * deleteUser allows you to delete a User from the Cluster
     * @param user the user you want to delete from the Cluster
     * @param purgeAll true if you want to delete all data associated with the user such as files, jobs, etc
     * @return returns true if the deletion of the User was successful
     */
    public static boolean deleteUser(User user, boolean purgeAll){
        if(getUserByToken(user.token()) != null){
            if(purgeAll){

                //Deletes all users files userMeta and databus and jobs
                // We probably need to clear the clustered hosts

                // First we must delete the user's meta information
                Predicate p = Predicates.equal("userToken", user.token());

                // Delete Meta
                Collection metaKeys = userMeta.keySet(p);
                for (String key : metaKeys) {
                    userMeta.remove(key);
                }

                // We must delete all user information
                // Delete DataBus stuff
                IMap dataBus = cluster.data().persistentMap("dataBus");
                String baseIdentifier = "internal.private_..." + user.token() + "_job_dataBus_internal_";
                Collection dataBusKeys = dataBus.keySet(new KeyStartsWithPredicate(baseIdentifier));
                for (String key : dataBusKeys) {
                    dataBus.remove(key);
                }

                IMap files = cluster.data().persistentMap("files");
                // Delete Files
                Collection fileKeys = files.keySet(p);
                for (String key : fileKeys) {
                    files.remove(key);
                }

                // Delete Files
                Collection jobKeys = jobs.keySet(p);
                for (String key : jobKeys) {
                    jobs.remove(key);
                }
            }

            users.remove(user.token());
        }
        return !users.containsKey(user.token());
    }

    /**
     * getUser is used to retrieve a User from the Cluster.
     * This just calls getUserByToken.
     * 
     * @param token the token for the User you want to retrieve
     * @return returns the User or null if the User does not exist
     */
    public static User getUser(String token) {
        return getUserByToken(token);
    }

    /**
     * getUserByToken is used to retrieve a User from the Cluster
     * via it's token.
     * 
     * @param token the token of the User you want to retrieve
     * @return returns the User or null if the User does not exist
     */
    public static User getUserByToken(String token) {
        return users.get(token);
    }
    
    /**
     * getUserByUsername is used to retrieve a User from the Cluster
     * via it's username.
     *
     * @param username the username of the User you want to retrieve
     * @return returns the User or null if the User does not exist
     */
    public static User getUserByUsername(String username) {
        EntryObject e = new PredicateBuilder().getEntryObject();
        // We check the value to be equal to true to ensure that this friendship is active.
        // Then we check to see if the parentToken was the postUser and the key is the currently
        // logged in user
        // Or we check if the parentToken is equal to the current user and the username is equal to the post user.
        //Predicate p = e.get("value").equal(true).and()

        Predicate predicate = e.get("username").equal(username);

        for (User user : users.values(predicate)) {
            if (user.username.equals(username))
                return user;
        }
        // If we have a value more than 0 we know that the friendship is active.
        return null;
    }

    /**
     * setUserPassword is used to set a User's password.
     * 
     * @param user the User you wish to set the password for
     * @param password the new password for the User
     */
    public static void setUserPassword(User user, String password) {
        if (getUserByToken(user.token()) != null) {
            String hashedPassword = CryptoUtils.calculateHmacSHA1(password.trim(), user.username);
            setMeta(user, "password", hashedPassword);
        }
    }

    /**
     * validateUserPassword is used to easily validate a User's password.
     *
     * @param user the User you wish to validate the password for
     * @param password the password you are trying to validate
     * @return returns true if it was successful
     */
    public static boolean validateUserPassword(User user, String password) {
        String hashedPassword = CryptoUtils.calculateHmacSHA1(password.trim(), user.username);
        return hashedPassword.equals(getMeta(user, "password").value.toString());
    }

    /**
     * getMeta is used to retrieve a Collection of Meta objects from the Cluster.
     *
     * @param key the key you wish to search for
     * @param value the value of the key you are searching for
     * @return returns a Collection with the values matching the key and value
     */
    public static Collection getMeta(String key, String value) {
        EntryObject e = new PredicateBuilder().getEntryObject();
        Predicate p = e.get("key").equal(key.trim()).and(e.get("value").equal(value));
        return userMeta.values(p);
    }

    /**
     * getMeta is used to retrieve a Collection of Meta objects from the Cluster.
     *
     * @param key the key you wish to search for
     * @return returns a Collection with the values matching the key
     */
    public static Collection getMeta(String key) {
        EntryObject e = new PredicateBuilder().getEntryObject();
        Predicate p = e.get("key").equal(key.trim());
        return userMeta.values(p);
    }

    /**
     * getUserMeta is used to retrieve a Collection of Meta objects for a User from the Cluster.
     *
     * @param user the User of the Meta objects
     * @return returns a Collection with the values matching the User
     */
    public static Collection getMeta(User user) {
        EntryObject e = new PredicateBuilder().getEntryObject();
        Predicate p = e.get("userToken").equal(user.token());
        return userMeta.values(p);
    }

    /**
     * delteUserMeta is used to delete a Meta object for a User from the Cluster.
     *
     * @param user the User you are deleting the Meta object for.
     * @param key the key for the Meta object
     */
    public static void deleteUserMeta(User user, String key) {
        EntryObject e = new PredicateBuilder().getEntryObject();
        Predicate p = e.get("userToken").equal(user.token()).and(e.get("key").equal(key));
        Collection values = userMeta.values(p);
        for (Meta meta : values) {
            userMeta.remove(meta.token());
        }
    }

    /**
     * getUserMeta is used to retrieve a Meta object for a User matching
     * the given key.
     *
     * @param user the User you are trying to find the Meta object for
     * @param key the key you are attempting to match
     * @return returns a Meta object otherwise null if it does not exist
     */
    public static Meta getMeta(User user, String key) {
        EntryObject e = new PredicateBuilder().getEntryObject();
        Predicate p = e.get("userToken").equal(user.token()).and(e.get("key").equal(key));
        Collection values = userMeta.values(p);
        Iterator iterator = values.iterator();

        Meta metaValue = null;
        if (iterator.hasNext()) {
            metaValue = iterator.next();
        }
        // Remove copies
        while (iterator.hasNext()) {
            userMeta.remove(iterator.next().token());
        }
        return metaValue;
    }

    /**
     * setUserMeta is used to store a specific key and value as a Meta object for
     * the specified User.
     *
     * @param user the User you wish to store the Meta object for
     * @param key the key for the Meta object
     * @param value the value for the Meta object
     */
    public static void setMeta(User user, String key, Object value) {
        Meta meta = new Meta();
        meta.key = key;
        meta.value = value;
        setMeta(user, meta);
    }

    /**
     * setUserMEta allows you to store a Meta object for the specified User.
     *
     * @param user the User you are storing the Meta object for
     * @param meta the Meta object you wish to store
     */
    public static void setMeta(User user, Meta meta) {
        Meta existingMeta = getMeta(user, meta.key);
        if (existingMeta != null) {
            existingMeta.value = meta.value;
            existingMeta.userToken = user.token();
            userMeta.set(existingMeta.token(), existingMeta);
        } else {
            meta.userToken = user.token();
            userMeta.set(meta.token(), meta);
        }
    }

    /**
     * containsUserMeta is used to check if there is a certain key stored
     * under the specified User's Meta data.
     *
     * @param user the User you wish to check
     * @param key the key you are searching for
     * @return returns true if it contains the key you are looing for
     */
    public static boolean containsMeta(User user, String key) {
        EntryObject e = new PredicateBuilder().getEntryObject();
        Predicate p = e.get("userToken").equal(user.token()).and(e.get("key").equal(key));
        Collection values = userMeta.values(p);
        return values.size() > 0;
    }

    /**
     * setUserMetaDefaults is a useful method that allows you to set all the
     * default values for a User such as quotas,
     * @param user
     */
    public static void setMetaDefaults(User user) {

        if (!containsMeta(user, "max_service_jobs")) {
            // This is the number of jobs we can run as a service.
            setMeta(user, new Meta("max_service_jobs", 25));
        }
        if (!containsMeta(user, "max_jobs")) {
            // max_service_jobs is affected by this.
            setMeta(user, new Meta("max_jobs", 250));
        }

        if (!containsMeta(user, "max_lite_jobs")) {
            // max_lite_jobs determines how many lite jobs can be ran at once
            // max_concurrent_jobs do not affect that
            setMeta(user, new Meta("max_lite_jobs", 2500));
        }
        if (!containsMeta(user, "max_lite_timers")) {
            // Timers per lite jobs
            setMeta(user, new Meta("max_lite_timers", 15));
        }
        if (!containsMeta(user, "max_service_timers")) {
            // Timers per service jobs
            setMeta(user, new Meta("max_service_timers", 50));
        }
        if (!containsMeta(user, "max_timers")) {
            // Timers per jobs - includes service jobs unless max_service_timers provided
            setMeta(user, new Meta("max_timers", 25));
        }

        // Please note these are used for asyncExecution
        if (!containsMeta(user, "max_lite_threads")) {
            // Threads per lite jobs
            setMeta(user, new Meta("max_lite_threads", 5));
        }
        if (!containsMeta(user, "max_service_threads")) {
            // Threads per service jobs
            setMeta(user, new Meta("max_service_threads", 150));
        }
        if (!containsMeta(user, "max_threads")) {
            // Threads per jobs - includes service jobs unless max_service_timers provided
            setMeta(user, new Meta("max_threads", 50));
        }
    }
}





© 2015 - 2025 Weber Informatics LLC | Privacy Policy