Example usage for com.google.common.collect ImmutableSet of

List of usage examples for com.google.common.collect ImmutableSet of

Introduction

In this page you can find the example usage for com.google.common.collect ImmutableSet of.

Prototype

public static <E> ImmutableSet<E> of(E element) 

Source Link

Usage

From source file:edu.mit.streamjit.util.affinity.Affinity.java

public static void main(String[] args) {
    System.out.println(getThreadAffinity());
    setThreadAffinity(ImmutableSet.of(2));
    System.out.println(getThreadAffinity());
}

From source file:voldemort.store.readonly.swapper.StoreSwapper.java

public static void main(String[] args) throws Exception {
    OptionParser parser = new OptionParser();
    parser.accepts("help", "print usage information");
    parser.accepts("cluster", "[REQUIRED] the voldemort cluster.xml file ").withRequiredArg()
            .describedAs("cluster.xml");
    parser.accepts("name", "[REQUIRED] the name of the store to swap").withRequiredArg()
            .describedAs("store-name");
    parser.accepts("servlet-path", "the path for the read-only management servlet").withRequiredArg()
            .describedAs("path");
    parser.accepts("file", "[REQUIRED] uri of a directory containing the new store files").withRequiredArg()
            .describedAs("uri");
    parser.accepts("timeout", "http timeout for the fetch in ms").withRequiredArg().describedAs("timeout ms")
            .ofType(Integer.class);
    parser.accepts("rollback", "Rollback store to older version");
    parser.accepts("admin", "Use admin services. Default = false");
    parser.accepts("push-version", "[REQUIRED] Version of push to fetch / rollback-to").withRequiredArg()
            .ofType(Long.class);

    OptionSet options = parser.parse(args);
    if (options.has("help")) {
        parser.printHelpOn(System.out);
        System.exit(0);//from   w w w  .  j  a  v a  2s  .co  m
    }

    Set<String> missing = CmdUtils.missing(options, "cluster", "name", "file", "push-version");
    if (missing.size() > 0) {
        if (!(missing.equals(ImmutableSet.of("file")) && (options.has("rollback")))) {
            System.err.println("Missing required arguments: " + Joiner.on(", ").join(missing));
            parser.printHelpOn(System.err);
            System.exit(1);
        }
    }

    String clusterXml = (String) options.valueOf("cluster");
    String storeName = (String) options.valueOf("name");
    String mgmtPath = CmdUtils.valueOf(options, "servlet-path", "read-only/mgmt");
    String filePath = (String) options.valueOf("file");
    int timeoutMs = CmdUtils.valueOf(options, "timeout",
            (int) (3 * Time.SECONDS_PER_HOUR * Time.MS_PER_SECOND));
    boolean useAdminServices = options.has("admin");
    boolean rollbackStore = options.has("rollback");
    Long pushVersion = (Long) options.valueOf("push-version");

    String clusterStr = FileUtils.readFileToString(new File(clusterXml));
    Cluster cluster = new ClusterMapper().readCluster(new StringReader(clusterStr));
    ExecutorService executor = Executors.newFixedThreadPool(cluster.getNumberOfNodes());
    StoreSwapper swapper = null;
    AdminClient adminClient = null;

    DefaultHttpClient httpClient = null;
    if (useAdminServices) {
        adminClient = new AdminClient(cluster, new AdminClientConfig(), new ClientConfig());
        swapper = new AdminStoreSwapper(cluster, executor, adminClient, timeoutMs);
    } else {
        int numConnections = cluster.getNumberOfNodes() + 3;
        ThreadSafeClientConnManager connectionManager = new ThreadSafeClientConnManager();
        httpClient = new DefaultHttpClient(connectionManager);

        HttpParams clientParams = httpClient.getParams();

        connectionManager.setMaxTotal(numConnections);
        connectionManager.setDefaultMaxPerRoute(numConnections);
        HttpConnectionParams.setSoTimeout(clientParams, timeoutMs);

        swapper = new HttpStoreSwapper(cluster, executor, httpClient, mgmtPath);
    }

    try {
        long start = System.currentTimeMillis();
        if (rollbackStore) {
            swapper.invokeRollback(storeName, pushVersion.longValue());
        } else {
            swapper.swapStoreData(storeName, filePath, pushVersion.longValue());
        }
        long end = System.currentTimeMillis();
        logger.info("Succeeded on all nodes in " + ((end - start) / Time.MS_PER_SECOND) + " seconds.");
    } finally {
        if (useAdminServices && adminClient != null)
            adminClient.close();
        executor.shutdownNow();
        executor.awaitTermination(1, TimeUnit.SECONDS);
        VoldemortIOUtils.closeQuietly(httpClient);
    }
    System.exit(0);
}

From source file:MainApp.java

public static void main(String[] args) {
    if (args.length < PARAMETERS)
        throw new IllegalArgumentException(INVALID_SYNTAX);

    String provider = args[0];/*from   w w  w.j  a va  2 s . co  m*/
    String identity = args[1];
    String credential = args[2];
    String groupName = args[3];
    Action action = Action.valueOf(args[4].toUpperCase());
    boolean providerIsGCE = provider.equalsIgnoreCase("google-compute-engine");
    boolean providerIsVsphere = provider.equalsIgnoreCase("vsphere");

    if (action == Action.EXEC && args.length < PARAMETERS + 1)
        throw new IllegalArgumentException("please quote the command to exec as the last parameter");
    String command = (action == Action.EXEC) ? args[5] : "echo hello";

    // For GCE, the credential parameter is the path to the private key file
    if (providerIsGCE)
        credential = getPrivateKeyFromFile(credential);

    if (action == Action.RUN && args.length < PARAMETERS + 1)
        throw new IllegalArgumentException("please pass the local file to run as the last parameter");
    File file = null;
    if (action == Action.RUN) {
        file = new File(args[5]);
        if (!file.exists())
            throw new IllegalArgumentException("file must exist! " + file);
    }

    String minRam = System.getProperty("minRam");
    String loginUser = System.getProperty("loginUser", "toor");

    // note that you can check if a provider is present ahead of time
    checkArgument(contains(allKeys, provider), "provider %s not in supported list: %s", provider, allKeys);

    LoginCredentials login = (action != Action.DESTROY) ? getLoginForCommandExecution(action) : null;

    ComputeService compute = initComputeService(provider, identity, credential);

    try {
        switch (action) {
        case ADD:
            System.out.printf(">> adding node to group %s%n", groupName);

            // Default template chooses the smallest size on an operating system
            // that tested to work with java, which tends to be Ubuntu or CentOS
            TemplateBuilder templateBuilder = compute.templateBuilder();

            if (providerIsGCE)
                templateBuilder.osFamily(OsFamily.CENTOS);

            // If you want to up the ram and leave everything default, you can 
            // just tweak minRam
            if (minRam != null)
                templateBuilder.minRam(Integer.parseInt(minRam));

            // note this will create a user with the same name as you on the
            // node. ex. you can connect via ssh publicip
            Statement bootInstructions = AdminAccess.standard();

            // to run commands as root, we use the runScript option in the template.
            if (provider.equalsIgnoreCase("virtualbox"))
                templateBuilder.options(overrideLoginUser(loginUser).runScript(bootInstructions));
            else
                templateBuilder.options(runScript(bootInstructions));

            if (providerIsVsphere) {
                TemplateOptions o = compute.templateOptions();
                ((VSphereTemplateOptions) o).isoFileName("ISO/UCSInstall_UCOS_3.1.0.0-9914.iso");
                ((VSphereTemplateOptions) o).flpFileName("ISO/image.flp");
                ((VSphereTemplateOptions) o).postConfiguration(false);
                o.tags(ImmutableSet.of("from UnitTest")).nodeNames(ImmutableSet.of("my-clone1"))
                        .runScript("cd /tmp; touch test.txt").networks("Dev Admin Network");
                templateBuilder.imageId("first-vm12-from-template").locationId("default").minRam(6000)
                        .options(o);
                System.out.printf("After ProviderIsVsphere option setting\n");
            }

            NodeMetadata node = getOnlyElement(
                    compute.createNodesInGroup(groupName, 1, templateBuilder.build()));
            System.out.printf("<< node %s: %s%n", node.getId(),
                    concat(node.getPrivateAddresses(), node.getPublicAddresses()));

        case EXEC:
            System.out.printf(">> running [%s] on group %s as %s%n", command, groupName, login.identity);

            // when you run commands, you can pass options to decide whether to
            // run it as root, supply or own credentials vs from cache, and wrap
            // in an init script vs directly invoke
            Map<? extends NodeMetadata, ExecResponse> responses = compute.runScriptOnNodesMatching(//
                    inGroup(groupName), // predicate used to select nodes
                    exec(command), // what you actually intend to run
                    overrideLoginCredentials(login) // use my local user &
                            // ssh key
                            .runAsRoot(false) // don't attempt to run as root (sudo)
                            .wrapInInitScript(false));// run command directly

            for (Entry<? extends NodeMetadata, ExecResponse> response : responses.entrySet()) {
                System.out.printf("<< node %s: %s%n", response.getKey().getId(), concat(
                        response.getKey().getPrivateAddresses(), response.getKey().getPublicAddresses()));
                System.out.printf("<<     %s%n", response.getValue());
            }
            break;
        case RUN:
            System.out.printf(">> running [%s] on group %s as %s%n", file, groupName, login.identity);

            // when running a sequence of commands, you probably want to have jclouds use the default behavior, 
            // which is to fork a background process.
            responses = compute.runScriptOnNodesMatching(//
                    inGroup(groupName), Files.toString(file, Charsets.UTF_8), // passing in a string with the contents of the file
                    overrideLoginCredentials(login).runAsRoot(false)
                            .nameTask("_" + file.getName().replaceAll("\\..*", ""))); // ensuring task name isn't
            // the same as the file so status checking works properly

            for (Entry<? extends NodeMetadata, ExecResponse> response : responses.entrySet()) {
                System.out.printf("<< node %s: %s%n", response.getKey().getId(), concat(
                        response.getKey().getPrivateAddresses(), response.getKey().getPublicAddresses()));
                System.out.printf("<<     %s%n", response.getValue());
            }
            break;
        case DESTROY:
            System.out.printf(">> destroying nodes in group %s%n", groupName);
            // you can use predicates to select which nodes you wish to destroy.
            Set<? extends NodeMetadata> destroyed = compute.destroyNodesMatching(//
                    Predicates.<NodeMetadata>and(not(TERMINATED), inGroup(groupName)));
            System.out.printf("<< destroyed nodes %s%n", destroyed);
            break;
        case LISTIMAGES:
            Set<? extends Image> images = compute.listImages();
            System.out.printf(">> No of images %d%n", images.size());
            for (Image img : images) {
                System.out.println(">>>>  " + img);
            }
            break;
        case LISTNODES:
            Set<? extends ComputeMetadata> nodes = compute.listNodes();
            System.out.printf(">> No of nodes/instances %d%n", nodes.size());
            for (ComputeMetadata nodeData : nodes) {
                System.out.println(">>>>  " + nodeData);
            }
            break;
        }
    } catch (RunNodesException e) {
        System.err.println("error adding node to group " + groupName + ": " + e.getMessage());
        error = 1;
    } catch (RunScriptOnNodesException e) {
        System.err.println("error executing " + command + " on group " + groupName + ": " + e.getMessage());
        error = 1;
    } catch (Exception e) {
        System.err.println("error: " + e.getMessage());
        error = 1;
    } finally {
        compute.getContext().close();
        System.exit(error);
    }
}

From source file:org.opendaylight.controller.md.sal.common.impl.routing.RoutingUtils.java

public static <C, P> RouteChange<C, P> removalChange(C context, P path) {
    final ImmutableMap<C, Set<P>> announcements = ImmutableMap.<C, Set<P>>of();
    final ImmutableMap<C, Set<P>> removals = ImmutableMap.<C, Set<P>>of(context, ImmutableSet.of(path));
    return new RouteChangeImpl<C, P>(announcements, removals);
}

From source file:com.google.caliper.VmFactory.java

public static ImmutableSet<String> defaultVms() {
    String vmName = DalvikVm.isDalvikVm() ? DalvikVm.vmName() : StandardVm.defaultVmName();
    return ImmutableSet.of(vmName);
}

From source file:com.google.template.soy.i18ndirectives.I18nDirectives.java

public static ImmutableSet<SoyPrintDirective> directives(Supplier<String> localeProvider) {
    return ImmutableSet.of(new FormatNumDirective(localeProvider));
}

From source file:com.facebook.presto.spi.testing.InterfaceTestUtils.java

public static <I, C extends I> void assertAllMethodsOverridden(Class<I> iface, Class<C> clazz) {
    assertEquals(ImmutableSet.copyOf(clazz.getInterfaces()), ImmutableSet.of(iface));
    for (Method method : iface.getMethods()) {
        try {//from   w w w  .  ja  v  a2s  .c  o  m
            Method override = clazz.getDeclaredMethod(method.getName(), method.getParameterTypes());
            assertEquals(override.getReturnType(), method.getReturnType());
        } catch (NoSuchMethodException e) {
            fail(format("%s does not override [%s]", clazz.getName(), method));
        }
    }
}

From source file:com.facebook.presto.hive.metastore.HivePrivilege.java

public static Set<HivePrivilege> parsePrivilege(PrivilegeGrantInfo userGrant) {
    String name = userGrant.getPrivilege().toUpperCase(ENGLISH);
    switch (name) {
    case "ALL":
        return ImmutableSet.copyOf(values());
    case "SELECT":
        return ImmutableSet.of(SELECT);
    case "INSERT":
        return ImmutableSet.of(INSERT);
    case "UPDATE":
        return ImmutableSet.of(UPDATE);
    case "DELETE":
        return ImmutableSet.of(DELETE);
    case "OWNERSHIP":
        return ImmutableSet.of(OWNERSHIP);
    }/*w  ww  .  ja v  a2 s  .co  m*/
    return ImmutableSet.of();
}

From source file:com.facebook.buck.util.OptionalCompat.java

/**
 * @see com.google.common.base.Optional#asSet()
 *//* w  w w .  j  a v a2  s.  c  om*/
public static final <T> ImmutableSet<T> asSet(Optional<T> optional) {
    if (optional.isPresent()) {
        return ImmutableSet.of(optional.get());
    } else {
        return ImmutableSet.of();
    }
}

From source file:org.opendaylight.controller.md.sal.common.impl.routing.RoutingUtils.java

public static <C, P> RouteChange<C, P> announcementChange(C context, P path) {
    final ImmutableMap<C, Set<P>> announcements = ImmutableMap.<C, Set<P>>of(context, ImmutableSet.of(path));
    final ImmutableMap<C, Set<P>> removals = ImmutableMap.<C, Set<P>>of();
    return new RouteChangeImpl<C, P>(announcements, removals);
}