Example usage for com.google.common.io Files toString

List of usage examples for com.google.common.io Files toString

Introduction

In this page you can find the example usage for com.google.common.io Files toString.

Prototype

public static String toString(File file, Charset charset) throws IOException 

Source Link

Usage

From source file:com.google.cloud.genomics.dataflow.pipelines.IdentifyPrivateVariants.java

public static void main(String[] args) throws IOException, GeneralSecurityException {
    // Register the options so that they show up via --help
    PipelineOptionsFactory.register(Options.class);
    Options options = PipelineOptionsFactory.fromArgs(args).withValidation().as(Options.class);
    // Option validation is not yet automatic, we make an explicit call here.
    Options.Methods.validateOptions(options);

    OfflineAuth auth = GenomicsOptions.Methods.getGenomicsAuth(options);

    // Grab and parse the list of callset IDs.
    String fileContents = Files.toString(new File(options.getCallSetIdsFilepath()), Charset.defaultCharset());
    ImmutableSet<String> callSetIds = ImmutableSet.<String>builder().addAll(
            Splitter.on(CharMatcher.BREAKING_WHITESPACE).omitEmptyStrings().trimResults().split(fileContents))
            .build();//from  w  ww  .  j ava  2s .c  om
    LOG.info("The pipeline will identify and write to Cloud Storage variants " + "private to "
            + callSetIds.size() + " genomes with callSetIds: " + callSetIds);
    if (options.getIdentifyVariantsWithoutCalls()) {
        LOG.info("* The pipeline will also identify variants with no callsets. *");
    }

    List<StreamVariantsRequest> shardRequests = options.isAllReferences()
            ? ShardUtils.getVariantRequests(options.getVariantSetId(),
                    ShardUtils.SexChromosomeFilter.INCLUDE_XY, options.getBasesPerShard(), auth)
            : ShardUtils.getVariantRequests(options.getVariantSetId(), options.getReferences(),
                    options.getBasesPerShard());

    Pipeline p = Pipeline.create(options);
    PCollection<Variant> variants = p.begin().apply(Create.of(shardRequests))
            .apply(new VariantStreamer(auth, ShardBoundary.Requirement.STRICT, VARIANT_FIELDS)).apply(ParDo
                    .of(new PrivateVariantsFilterFn(callSetIds, options.getIdentifyVariantsWithoutCalls())));

    variants.apply(ParDo.named("FormatResults").of(new DoFn<Variant, String>() {
        @Override
        public void processElement(ProcessContext c) {
            Variant v = c.element();
            c.output(Joiner.on("\t").join(v.getId(), v.getReferenceName(), v.getStart(), v.getEnd(),
                    v.getReferenceBases(), Joiner.on(",").join(v.getAlternateBasesList())));
        }
    })).apply(TextIO.Write.to(options.getOutput()));

    p.run();
}

From source file:org.pshdl.model.types.builtIn.busses.memorymodel.v4.MemoryModelAST.java

public static void main(String[] args) throws FileNotFoundException, RecognitionException, IOException {
    final Set<Problem> problems = Sets.newHashSet();
    final String string = Files.toString(new File(args[0]), Charsets.UTF_8);
    final Unit parseUnit = parseUnit(string, problems, 0);
    for (final Problem problem : problems) {
        System.err.println("MemoryModelAST.main()" + problem);
    }// w  ww  .  j a  v  a2s  . co m
    System.out.println("MemorModelAST.main()" + parseUnit);
}

From source file:org.jclouds.examples.compute.basics.MainApp.java

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

    String provider = args[0];//from  ww w .j a  v  a  2  s. c o  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");

    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 = getCredentialFromJsonKeyFile(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");

    // 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 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.
            templateBuilder.options(runScript(bootInstructions));

            Template template = templateBuilder.build();

            NodeMetadata node = getOnlyElement(compute.createNodesInGroup(groupName, 1, template));
            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:co.mitro.core.crypto.KeyczarKeyFactory.java

/** Test program to load a key from disk and decrypt a file. */
public static void main(String[] arguments) throws IOException, CryptoError {
    String privateKeyPath = arguments[0];
    String password = arguments[1];
    String encryptedPath = arguments[2];

    String privateKeyData = Files.toString(new File(privateKeyPath), Charsets.UTF_8);
    KeyczarKeyFactory keyFactory = new KeyczarKeyFactory();
    PrivateKeyInterface key = keyFactory.loadEncryptedPrivateKey(privateKeyData, password);

    String encryptedData = Files.toString(new File(encryptedPath), Charsets.UTF_8);
    System.out.println(key.decrypt(encryptedData));
}

From source file:org.aegis.app.sample.ec2.computer1.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  av  a2  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");

    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));

            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:com.diskoverorta.legal.LegalManager.java

public static void main(String args[]) {
    logger.error("This is a Err");
    logger.debug("This is a debug msg");
    logger.info("This is info message");
    LegalManager lobj = new LegalManager();
    String content = "";
    try {/* ww w  .ja  v  a  2s  .  c  o  m*/
        content = Files.toString(
                new File("/home/itachi/Serendio /RestAPIexample/tmp_kreiger1.txtssplit.txt.trimmed.txt"),
                Charsets.UTF_8);
        content = content.replace("\n", " ");
        content = content.replace("\r", " ");
    } catch (IOException ex) {
        ex.printStackTrace();
    }
    Map<String, String> config1 = new TreeMap<String, String>();
    config1.put("chunksize", "5");
    String s = lobj.tagLegalTextAnalyticsComponents(content, config1);
    /*System.out.println(s);*/
}

From source file:com.diskoverorta.tamanager.TextManager.java

public static void main(String args[]) {
    TAConfig config = new TAConfig();
    TextManager temp = new TextManager();
    CmdLineParser parser = new CmdLineParser(temp);
    String sample = "Sachin Tendulkar won the Man of the Match award at Sydney in the year 2012:). Dhoni won the Man of the series award at Melbourne.";

    String trialtext = "";
    try {/*from   w  w w. j  a v a 2 s. c om*/
        parser.parseArgument(args);
    } catch (CmdLineException ex) {
        ex.printStackTrace();
    }
    System.out.println("Command line API :");
    parser.printUsage(System.out);
    config.entityConfig.put("person", "TRUE");
    config.entityConfig.put("organization", "TRUE");
    config.entityConfig.put("location", "TRUE");
    config.entityConfig.put("date", "TRUE");
    config.entityConfig.put("time", "TRUE");
    config.entityConfig.put("currency", "TRUE");
    config.entityConfig.put("percent", "TRUE");

    if ((temp.text == null) && (temp.fileName == null)) {
        trialtext = "Sachin Tendulkar won the Man of the Match award at Sydney in the year 2012:). Dhoni won the Man of the series award at Melbourne.";
        System.out.println("No Text source provided considering this default text for analysis : " + trialtext);
    } else if ((temp.text != null) && (temp.fileName != null)) {
        System.out.println("Command line text input considered for Text Analytics : " + temp.text);
        trialtext = temp.text;
    } else if ((temp.text != null)) {
        System.out.println("Command line text input considered for Text Analytics : " + temp.text);
        trialtext = temp.text;
    } else if ((temp.fileName != null)) {
        System.out.println("Command line text input considered for Text Analytics");
        try {
            trialtext = Files.toString(new File(temp.fileName), Charsets.UTF_8);
        } catch (IOException ex) {
            ex.printStackTrace();
        }
        System.out.println("File input considered for Text Analytics : " + trialtext);
    }

    if ((temp.analysis != null) && (temp.analysis.equalsIgnoreCase("Entity") == true)) {
        config.analysisConfig.put("Entity", "TRUE");
        System.out.println("Analyzing Entity in given text");
    } else if ((temp.analysis != null) && (temp.analysis.equalsIgnoreCase("Sentiment") == true)) {
        config.analysisConfig.put("Sentiment", "TRUE");
        System.out.println("Analyzing Sentiment in given text");
    } else if ((temp.analysis != null) && (temp.analysis.equalsIgnoreCase("Topic") == true)) {
        config.analysisConfig.put("Topic", "TRUE");
        System.out.println("Analyzing Topic in given text");
    } else if ((temp.analysis != null) && (temp.analysis.equalsIgnoreCase("Keyword") == true)) {
        config.analysisConfig.put("Keyword", "TRUE");
        System.out.println("Extracting keywords in given text");
    } else if ((temp.analysis != null) && (temp.analysis.equalsIgnoreCase("All") == true)) {
        System.out.println("Analyzing Entity, Sentiment, Topic and Keywords");
        config.analysisConfig.put("Entity", "TRUE");
        config.analysisConfig.put("Sentiment", "TRUE");
        config.analysisConfig.put("Topic", "TRUE");
        config.analysisConfig.put("Keyword", "TRUE");
    } else {
        System.out.println(
                "Analysis options not specified. Possible values : Entity, Sentiment, Topic, Kaeyword, All");
        System.out.println("Choosing All by default");
        config.analysisConfig.put("Entity", "TRUE");
        config.analysisConfig.put("Sentiment", "TRUE");
        config.analysisConfig.put("Topic", "TRUE");
        config.analysisConfig.put("Keyword", "TRUE");
    }
    System.out.println("Text Analytics output : ");

    System.out.println(temp.tagUniqueTextAnalyticsComponentsINJSON(trialtext, config));

}

From source file:jaredbgreat.dldungeons.pieces.chests.loothack.FileTable.java

public static FileTable load(File file, Gson gson, int level) {
    String content;// w w w  .  j  a  v  a 2  s .  c o  m

    try {
        content = Files.toString(file, Charsets.UTF_8);
    } catch (IOException e1) {
        throw new RuntimeException("Error while loading " + file.getName() + ":", e1);
    }

    FileTable table = null;
    try {
        table = gson.fromJson(content, FileTable.class);
    } catch (Exception ex) {
        throw new RuntimeException("Error while parsing " + file.getName() + ":", ex);
    }

    if (table == null) {
        throw new RuntimeException("File " + file.getName() + " parsed to null.");
    }
    table.postLoadProcess(level);
    return table;
}

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   www . ja 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:eu.numberfour.n4js.antlr.internal.AntlrCodeQualityHelper.java

/**
 * Remove all unnecessary comments from the java code that was produced by Antlr
 *//*  www. j  av  a 2s.  c  om*/
public static void stripUnnecessaryComments(String javaFile, Charset encoding) throws IOException {
    String content = Files.toString(new File(javaFile), encoding);
    content = new NewlineNormalizer().toUnixLineDelimiter(content);
    content = content.replaceAll("(?m)^(\\s+)// .*/(\\w+\\.g:.*)$", "$1// $2");
    content = content.replaceAll("(public String getGrammarFileName\\(\\) \\{ return \").*/(\\w+\\.g)(\"; \\})",
            "$1$2$3");
    Files.write(content, new File(javaFile), encoding);
}