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.ikanow.aleph2.enrichment.utils.services.JsScriptEngineTestService.java

/** Entry point
 * @param args//from   ww w. j a  va 2 s. com
 * @throws IOException 
 */
public static void main(String[] args) throws IOException {
    if (args.length < 3) {
        System.out
                .println("ARGS: <script-file> <input-file> <output-prefix> [{[len: <LEN>], [group: <GROUP>]}]");
    }

    // STEP 1: load script file

    final String user_script = Files.toString(new File(args[0]), Charsets.UTF_8);

    // STEP 2: get a stream for the JSON file

    final InputStream io_stream = new FileInputStream(new File(args[1]));

    // STEP 3: set up control if applicable

    Optional<JsonNode> json = Optional.of("").filter(__ -> args.length > 3).map(__ -> args[3])
            .map(Lambdas.wrap_u(j -> _mapper.readTree(j)));

    // STEP 4: set up the various objects

    final DataBucketBean bucket = Mockito.mock(DataBucketBean.class);

    final JsScriptEngineService service_under_test = new JsScriptEngineService();

    final LinkedList<ObjectNode> emitted = new LinkedList<>();
    final LinkedList<JsonNode> grouped = new LinkedList<>();
    final LinkedList<JsonNode> externally_emitted = new LinkedList<>();

    final IEnrichmentModuleContext context = Mockito.mock(IEnrichmentModuleContext.class, new Answer<Void>() {
        @SuppressWarnings("unchecked")
        public Void answer(InvocationOnMock invocation) {
            try {
                Object[] args = invocation.getArguments();
                if (invocation.getMethod().getName().equals("emitMutableObject")) {
                    final Optional<JsonNode> grouping = (Optional<JsonNode>) args[3];
                    if (grouping.isPresent()) {
                        grouped.add(grouping.get());
                    }
                    emitted.add((ObjectNode) args[1]);
                } else if (invocation.getMethod().getName().equals("externalEmit")) {
                    final DataBucketBean to = (DataBucketBean) args[0];
                    final Either<JsonNode, Map<String, Object>> out = (Either<JsonNode, Map<String, Object>>) args[1];
                    externally_emitted
                            .add(((ObjectNode) out.left().value()).put("__a2_bucket", to.full_name()));
                }
            } catch (Exception e) {
                e.printStackTrace();
            }
            return null;
        }
    });

    final EnrichmentControlMetadataBean control = BeanTemplateUtils.build(EnrichmentControlMetadataBean.class)
            .with(EnrichmentControlMetadataBean::config,
                    new LinkedHashMap<String, Object>(
                            ImmutableMap.<String, Object>builder().put("script", user_script).build()))
            .done().get();

    service_under_test.onStageInitialize(context, bucket, control,
            Tuples._2T(ProcessingStage.batch, ProcessingStage.grouping), Optional.empty());

    final BeJsonParser json_parser = new BeJsonParser();

    // Run the file through

    final Stream<Tuple2<Long, IBatchRecord>> json_stream = StreamUtils
            .takeUntil(Stream.generate(() -> json_parser.getNextRecord(io_stream)), i -> null == i)
            .map(j -> Tuples._2T(0L, new BatchRecord(j)));

    service_under_test.onObjectBatch(json_stream, json.map(j -> j.get("len")).map(j -> (int) j.asLong(0L)),
            json.map(j -> j.get("group")));

    System.out.println("RESULTS: ");
    System.out.println("emitted: " + emitted.size());
    System.out.println("grouped: " + grouped.size());
    System.out.println("externally emitted: " + externally_emitted.size());
    Files.write(emitted.stream().map(j -> j.toString()).collect(Collectors.joining(";")),
            new File(args[2] + "emit.json"), Charsets.UTF_8);
    Files.write(grouped.stream().map(j -> j.toString()).collect(Collectors.joining(";")),
            new File(args[2] + "group.json"), Charsets.UTF_8);
    Files.write(externally_emitted.stream().map(j -> j.toString()).collect(Collectors.joining(";")),
            new File(args[2] + "external_emit.json"), Charsets.UTF_8);
}

From source file:com.google.appinventor.yailgenerator.YailGenerator.java

/**
 * Entry point for YailGenerator binary.
 * Command-line argumesnt://from  w ww .  jav a 2 s .  c  o  m
 * <ol>
 * <li>the path of a file containing the form properties source</li>
 * <li>the path of a file containing the codeblocks source</li>
 * <li>the yail path</li>
 * </ol>
 *
 * <p>The generated YAIL is printed to stdout.</p>
 */
public static void main(String[] args) {
    if (args.length != 3) {
        System.err.println("YailGenerator error - expected exactly 3 command line arguments");
        System.exit(-1);
    }

    // Save the original System.out and System.err and redirect output from codeblocks.
    PrintStream saveSystemOut = System.out;
    System.setOut(new PrintStream(new ByteArrayOutputStream()));
    PrintStream saveSystemErr = System.err;
    System.setErr(new PrintStream(new ByteArrayOutputStream()));

    try {
        String formPropertiesSource = Files.toString(new File(args[0]), Charset.forName(DEFAULT_CHARSET));
        String codeblocksSource = Files.toString(new File(args[1]), Charset.forName(DEFAULT_CHARSET));
        String yailPath = args[2];

        try {
            String yail = generateYail(formPropertiesSource, codeblocksSource, yailPath);
            saveSystemOut.print(yail);
            System.exit(0);
        } catch (YailGenerationException e) {
            saveSystemErr.println(e.getMessage());
            System.exit(1);
        }

    } catch (Throwable e) {
        e.printStackTrace(saveSystemErr);
        System.exit(-1);
    }
}

From source file:org.jclouds.examples.google.computeengine.CreateServer.java

/**
 * To get a service account and its private key see [TODO: write some
 * documentation on the website and put a link to it]
 *
 * The first argument (args[0]) is your service account email address
 *    (https://developers.google.com/console/help/new/#serviceaccounts).
 * The second argument (args[1]) is a path to your service account private key PEM file without a password. It is
 *    used for server-to-server interactions (https://developers.google.com/console/help/new/#serviceaccounts).
 *    The key is not transmitted anywhere.
 *
 * Example:/*from   w ww .  jav  a 2  s  .  c  o m*/
 *
 * java org.jclouds.examples.google.computeengine.CreateServer \
 *    somecrypticname@developer.gserviceaccount.com \
 *    /home/planetnik/Work/Cloud/OSS/certificate/gcp-oss.pem
 */
public static void main(final String[] args) {
    String serviceAccountEmailAddress = args[0];
    String serviceAccountKey = null;
    try {
        serviceAccountKey = Files.toString(new File(args[1]), Charset.defaultCharset());
    } catch (IOException e) {
        System.err.println(
                "Cannot open service account private key PEM file: " + args[1] + "\n" + e.getMessage());
        System.exit(1);
    }
    String userName = System.getProperty("user.name");
    String sshPublicKey = null;
    String sshPrivateKey = null;
    String sshPublicKeyFileName = System.getProperty("user.home") + File.separator + ".ssh" + File.separator
            + "google_compute_engine.pub";
    String sshPrivateKeyFileName = System.getProperty("user.home") + File.separator + ".ssh" + File.separator
            + "google_compute_engine";
    try {
        sshPublicKey = Files.toString(new File(sshPublicKeyFileName), Charset.defaultCharset());
        sshPrivateKey = Files.toString(new File(sshPrivateKeyFileName), Charset.defaultCharset());
    } catch (IOException e) {
        System.err.println("Unable to load your SSH keys.\n" + e.getMessage()
                + "\nYour public key, which is required to authorize your access to the machine is expected to be at "
                + sshPublicKeyFileName + " , and your private key, which is required to perform any operations "
                + "on your machine via SSH, is expected to be at " + sshPrivateKeyFileName
                + " .\nSee https://developers.google.com/compute/docs/instances#sshkeys for more details.\n"
                + e.getMessage());
        System.exit(1);
    }

    CreateServer createServer = new CreateServer(serviceAccountEmailAddress, serviceAccountKey);

    try {
        createServer.createServer(userName, sshPublicKey, sshPrivateKey);
    } catch (Exception e) {
        e.printStackTrace();
    } finally {
        try {
            createServer.close();
        } catch (IOException e) {
            e.printStackTrace();
            System.exit(1);
        }
    }
}

From source file:org.jclouds.examples.google.computeengine.ExecuteCommand.java

/**
 * Prerequisites://from ww w.j  a  v a  2s . c  o m
 * - service account created and its private key available on the local machine (see README.txt).
 * - a VM created and SSH access enabled.
 *
 * The first argument (args[0]) is your service account email address
 *    (https://developers.google.com/console/help/new/#serviceaccounts).
 * The second argument (args[1]) is a path to your service account private key PEM file without a password
 *    (https://developers.google.com/console/help/new/#serviceaccounts).
 * The third argument (args[2]) is the name of your instance
 *    (https://developers.google.com/compute/docs/instances#start_vm).
 * The fourth argument (args[3]) is the zone where your instance is located
 *    (https://developers.google.com/compute/docs/zones).
 *
 * Example:
 *
 * java org.jclouds.examples.google.computeengine.ExecuteCommand \
 *    somecrypticname@developer.gserviceaccount.com \
 *    /home/planetnik/Work/Cloud/OSS/certificate/gcp-oss.pem \
 *    planetnik-main \
 *    europe-west1-a
 */
public static void main(final String[] args) {
    String serviceAccountEmailAddress = args[0];
    String serviceAccountKey = null;
    try {
        serviceAccountKey = Files.toString(new File(args[1]), Charset.defaultCharset());
    } catch (IOException e) {
        System.err.println(
                "Cannot open service account private key PEM file: " + args[1] + "\n" + e.getMessage());
        System.exit(1);
    }
    String instanceName = args[2];
    String zone = args[3];
    String userName = System.getProperty("user.name");
    String sshPrivateKeyFileName = System.getProperty("user.home") + File.separator + ".ssh" + File.separator
            + "google_compute_engine";
    String sshPrivateKey = null;
    try {
        sshPrivateKey = Files.toString(new File(sshPrivateKeyFileName), Charset.defaultCharset());
    } catch (IOException e) {
        System.err.println("Unable to load your SSH private key at " + sshPrivateKeyFileName
                + "\nIt is required to perform any operations on your machine via SSH.\n"
                + "See https://developers.google.com/compute/docs/instances#sshkeys for more details.\n"
                + e.getMessage());
        System.exit(1);
    }

    ExecuteCommand executeApplication = new ExecuteCommand(serviceAccountEmailAddress, serviceAccountKey);

    try {
        NodeMetadata instance = executeApplication.locateInstance(instanceName, zone);
        if (instance != null) {
            String publicAddress = instance.getPublicAddresses().iterator().next();
            System.out.format("Instance %s found with IP %s%n", instance.getName(), publicAddress);
        } else {
            System.err.format("Error: Instance %s could not be located in zone %s.%n", instanceName, zone);
            System.exit(1);
        }
        executeApplication.executeSimpleCommand(instance, userName, sshPrivateKey);
    } catch (Exception e) {
        e.printStackTrace();
    } finally {
        try {
            executeApplication.close();
        } catch (IOException e) {
            e.printStackTrace();
            System.exit(1);
        }
    }
}

From source file:org.jclouds.examples.google.lb.MainApp.java

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

    String jsonKeyFile = args[0];
    Action action = Action.valueOf(args[1].toUpperCase());

    // Read in JSON key.
    String fileContents = null;//from  w w  w  .j av  a2  s.  co m
    try {
        fileContents = Files.toString(new File(jsonKeyFile), Charset.defaultCharset());
    } catch (IOException ex) {
        System.out.println("Error Reading the Json key file. Please check the provided path is correct.");
        System.exit(1);
    }

    Supplier<Credentials> credentialSupplier = new GoogleCredentialsFromJson(fileContents);

    // This demonstrates how to initialize a ComputeServiceContext using json key files.
    ComputeServiceContext context = ContextBuilder.newBuilder("google-compute-engine")
            .credentialsSupplier(credentialSupplier).buildView(ComputeServiceContext.class);

    Credentials credentials = credentialSupplier.get();

    GoogleComputeEngineApi googleApi = createGoogleComputeEngineApi(credentials.identity,
            credentials.credential);

    String project_name = googleApi.project().get().name();
    System.out.printf("Sucessfully Authenticated to project %s\n", project_name);

    InstanceApi instanceApi = googleApi.instancesInZone(DEFAULT_ZONE);

    switch (action) {
    case CREATE: {
        Metadata metadata = googleApi.project().get().commonInstanceMetadata();
        if (metadata.get("startup-script") != null && metadata.get("startup-script") != STARTUP_SCRIPT) {

            System.out.println("Project already has a startup script, exiting to avoid overwriting it.");
            System.exit(1);
        }
        System.out.println("Updating startup script");
        metadata.put("startup-script", STARTUP_SCRIPT);
        Operation operation = googleApi.project().setCommonInstanceMetadata(metadata);
        OperationApi operationsApi = googleApi.operations();
        WaitForOperation(operationsApi, operation);

        URI networkURL = googleApi.networks().get("default").selfLink();
        if (networkURL == null) {
            System.out.println(
                    "Your project does not have a default network. Please recreate the default network or try again with a new project");
            System.exit(1);
        }
        System.out.println("Creating:");

        // Add firewall rule to allow TCP on port 80
        FirewallOptions options = new FirewallOptions()
                .addAllowedRule(Firewall.Rule.create("tcp", ImmutableList.of("80")))
                .sourceRanges(ImmutableList.of("0.0.0.0/0"));
        //.addTargetTag(FIREWALL_TAG);
        operation = googleApi.firewalls().createInNetwork("jclouds-lb-firewall-tcp-80", networkURL, options);
        System.out.println(" - firewall");
        WaitForOperation(operationsApi, operation);

        URI machineTypeURL = googleApi.machineTypesInZone(DEFAULT_ZONE).get(DEFAULT_MACHINE_TYPE).selfLink();

        // Make requests to create instances.
        ArrayList<Operation> operations = new ArrayList<Operation>();
        for (int i = 0; i < NUM_INSTANCES; i++) {
            Operation o = instanceApi.create(NewInstance.create("jclouds-lb-instance-" + i, machineTypeURL,
                    networkURL, DEFAULT_IMAGE_URL));
            System.out.println(" - instance");
            operations.add(o);
        }

        ArrayList<URI> instances = new ArrayList<URI>();
        for (Operation op : operations) {
            WaitForOperation(operationsApi, op);
            instances.add(op.targetLink());
        }

        // Create Health Check
        HttpHealthCheckCreationOptions healthCheckOptions = new HttpHealthCheckCreationOptions.Builder()
                .checkIntervalSec(1).timeoutSec(1).buildWithDefaults();
        operation = googleApi.httpHeathChecks().insert("jclouds-lb-healthcheck", healthCheckOptions);
        System.out.println(" - http health check");
        WaitForOperation(operationsApi, operation);
        URI healthCheckURI = googleApi.httpHeathChecks().get("jclouds-lb-healthcheck").selfLink();

        // Create Target Pool
        TargetPoolCreationOptions targetPoolOptions = new TargetPoolCreationOptions.Builder(
                "jclouds-lb-target-pool").healthChecks(ImmutableList.of(healthCheckURI)).instances(instances)
                        .build();
        Operation targetPoolOperation = googleApi.targetPoolsInRegion(DEFAULT_REGION).create(targetPoolOptions);
        System.out.println(" - target pool");
        WaitForOperation(operationsApi, targetPoolOperation);

        // Create Forwarding Rule
        ForwardingRuleCreationOptions forwardingOptions = new ForwardingRuleCreationOptions.Builder()
                .ipProtocol(ForwardingRule.IPProtocol.TCP).target(targetPoolOperation.targetLink()).build();
        operation = googleApi.forwardingRulesInRegion(DEFAULT_REGION).create("jclouds-lb-forwarding",
                forwardingOptions);
        System.out.println(" - forwarding rule");
        WaitForOperation(operationsApi, operation);

        String ipAddress = googleApi.forwardingRulesInRegion(DEFAULT_REGION).get("jclouds-lb-forwarding")
                .ipAddress();
        System.out.println("Ready to recieve traffic at " + ipAddress);

        break;
    }
    case REQUEST: {
        // Find the created forwarding rule.
        ForwardingRule forwardingRule = googleApi.forwardingRulesInRegion(DEFAULT_REGION)
                .get("jclouds-lb-forwarding");
        if (forwardingRule == null) {
            System.out.println("jclouds-lb-forwarding rule does not exist. Have you successfully run create?");
            System.exit(1);
        }
        String ipAddress = googleApi.forwardingRulesInRegion(DEFAULT_REGION).get("jclouds-lb-forwarding")
                .ipAddress();
        System.out.printf("Found the forwarding rule! Try executing 'while true; do curl -m1 %s; done'\n",
                ipAddress);

        break;
    }
    case DELETE_STARTUP_SCRIPT: {
        System.out.println("removing startup script from project metadata");
        DeleteStartupScript(googleApi);
        break;
    }
    case DESTROY: {
        // Delete Forwarding Rule
        googleApi.forwardingRulesInRegion(DEFAULT_REGION).delete("jclouds-lb-forwarding");

        // Delete Target Pool
        googleApi.targetPoolsInRegion(DEFAULT_REGION).delete("jclouds-lb-target-pool");

        // Delete Health Check
        googleApi.httpHeathChecks().delete("jclouds-lb-healthcheck");

        // Delete Instances
        ArrayList<Operation> operations = new ArrayList<Operation>();
        for (int i = 0; i < NUM_INSTANCES; i++) {
            Operation o = instanceApi.delete("jclouds-lb-instance-" + i);
            operations.add(o);
        }

        // Delete Firewall Rule
        googleApi.firewalls().delete("jclouds-lb-firewall-tcp-80");

        // Delete Startup Script
        DeleteStartupScript(googleApi);

        System.out.println("ran cleanup");
        break;
    }
    }
}

From source file:org.ldp4j.xml.Generator.java

public static void main(final String... args) throws IOException {
    final String data = Files.toString(new File(args[0]), Charsets.UTF_8);
    final String methodName = args[1];
    System.out.println(new Generator().generate(methodName, data));
}

From source file:org.opendaylight.controller.netconf.test.tool.client.stress.StressClient.java

public static void main(final String[] args) {

    final Parameters params = parseArgs(args, Parameters.getParser());
    params.validate();//from   w w w  . ja v a 2s.co m

    final ch.qos.logback.classic.Logger root = (ch.qos.logback.classic.Logger) LoggerFactory
            .getLogger(Logger.ROOT_LOGGER_NAME);
    root.setLevel(params.debug ? Level.DEBUG : Level.INFO);

    final int threadAmount = params.threadAmount;
    LOG.info("thread amount: " + threadAmount);
    final int requestsPerThread = params.editCount / params.threadAmount;
    LOG.info("requestsPerThread: " + requestsPerThread);
    final int leftoverRequests = params.editCount % params.threadAmount;
    LOG.info("leftoverRequests: " + leftoverRequests);

    LOG.info("Preparing messages");
    // Prepare all msgs up front
    final List<List<NetconfMessage>> allPreparedMessages = new ArrayList<>(threadAmount);
    for (int i = 0; i < threadAmount; i++) {
        if (i != threadAmount - 1) {
            allPreparedMessages.add(new ArrayList<NetconfMessage>(requestsPerThread));
        } else {
            allPreparedMessages.add(new ArrayList<NetconfMessage>(requestsPerThread + leftoverRequests));
        }
    }

    final String editContentString;
    try {
        editContentString = Files.toString(params.editContent, Charsets.UTF_8);
    } catch (final IOException e) {
        throw new IllegalArgumentException("Cannot read content of " + params.editContent);
    }

    for (int i = 0; i < threadAmount; i++) {
        final List<NetconfMessage> preparedMessages = allPreparedMessages.get(i);
        int padding = 0;
        if (i == threadAmount - 1) {
            padding = leftoverRequests;
        }
        for (int j = 0; j < requestsPerThread + padding; j++) {
            LOG.debug("id: " + (i * requestsPerThread + j));
            preparedMessages.add(prepareMessage(i * requestsPerThread + j, editContentString));
        }
    }

    final NioEventLoopGroup nioGroup = new NioEventLoopGroup();
    final Timer timer = new HashedWheelTimer();

    final NetconfClientDispatcherImpl netconfClientDispatcher = configureClientDispatcher(params, nioGroup,
            timer);

    final List<StressClientCallable> callables = new ArrayList<>(threadAmount);
    for (final List<NetconfMessage> messages : allPreparedMessages) {
        callables.add(new StressClientCallable(params, netconfClientDispatcher, messages));
    }

    final ExecutorService executorService = Executors.newFixedThreadPool(threadAmount);

    LOG.info("Starting stress test");
    final Stopwatch started = Stopwatch.createStarted();
    try {
        final List<Future<Boolean>> futures = executorService.invokeAll(callables);
        for (final Future<Boolean> future : futures) {
            try {
                future.get(4L, TimeUnit.MINUTES);
            } catch (ExecutionException | TimeoutException e) {
                throw new RuntimeException(e);
            }
        }
        executorService.shutdownNow();
    } catch (final InterruptedException e) {
        throw new RuntimeException("Unable to execute requests", e);
    }
    started.stop();

    LOG.info("FINISHED. Execution time: {}", started);
    LOG.info("Requests per second: {}", (params.editCount * 1000.0 / started.elapsed(TimeUnit.MILLISECONDS)));

    // Cleanup
    timer.stop();
    try {
        nioGroup.shutdownGracefully().get(20L, TimeUnit.SECONDS);
    } catch (InterruptedException | ExecutionException | TimeoutException e) {
        LOG.warn("Unable to close executor properly", e);
    }
    //stop the underlying ssh thread that gets spawned if we use ssh
    if (params.ssh) {
        AsyncSshHandler.DEFAULT_CLIENT.stop();
    }
}

From source file:org.apache.drill.common.logical.LogicalPlan.java

public static void main(String[] args) throws Exception {
    DrillConfig config = DrillConfig.create();
    String externalPlan = Files.toString(new File("src/test/resources/simple_plan.json"), Charsets.UTF_8);
    LogicalPlan plan = parse(config, externalPlan);
}

From source file:org.opendaylight.netconf.test.tool.client.stress.StressClient.java

public static void main(final String[] args) {

    params = parseArgs(args, Parameters.getParser());
    params.validate();//w ww  . ja va  2  s.  c  o m

    final ch.qos.logback.classic.Logger root = (ch.qos.logback.classic.Logger) LoggerFactory
            .getLogger(Logger.ROOT_LOGGER_NAME);
    root.setLevel(params.debug ? Level.DEBUG : Level.INFO);

    final int threadAmount = params.threadAmount;
    LOG.info("thread amount: " + threadAmount);
    final int requestsPerThread = params.editCount / params.threadAmount;
    LOG.info("requestsPerThread: " + requestsPerThread);
    final int leftoverRequests = params.editCount % params.threadAmount;
    LOG.info("leftoverRequests: " + leftoverRequests);

    LOG.info("Preparing messages");
    // Prepare all msgs up front
    final List<List<NetconfMessage>> allPreparedMessages = new ArrayList<>(threadAmount);
    for (int i = 0; i < threadAmount; i++) {
        if (i != threadAmount - 1) {
            allPreparedMessages.add(new ArrayList<NetconfMessage>(requestsPerThread));
        } else {
            allPreparedMessages.add(new ArrayList<NetconfMessage>(requestsPerThread + leftoverRequests));
        }
    }

    final String editContentString;
    try {
        editContentString = Files.toString(params.editContent, Charsets.UTF_8);
    } catch (final IOException e) {
        throw new IllegalArgumentException("Cannot read content of " + params.editContent);
    }

    for (int i = 0; i < threadAmount; i++) {
        final List<NetconfMessage> preparedMessages = allPreparedMessages.get(i);
        int padding = 0;
        if (i == threadAmount - 1) {
            padding = leftoverRequests;
        }
        for (int j = 0; j < requestsPerThread + padding; j++) {
            LOG.debug("id: " + (i * requestsPerThread + j));
            preparedMessages.add(prepareMessage(i * requestsPerThread + j, editContentString));
        }
    }

    final NioEventLoopGroup nioGroup = new NioEventLoopGroup();
    final Timer timer = new HashedWheelTimer();

    final NetconfClientDispatcherImpl netconfClientDispatcher = configureClientDispatcher(params, nioGroup,
            timer);

    final List<StressClientCallable> callables = new ArrayList<>(threadAmount);
    for (final List<NetconfMessage> messages : allPreparedMessages) {
        callables.add(new StressClientCallable(params, netconfClientDispatcher, messages));
    }

    final ExecutorService executorService = Executors.newFixedThreadPool(threadAmount);

    LOG.info("Starting stress test");
    final Stopwatch started = Stopwatch.createStarted();
    try {
        final List<Future<Boolean>> futures = executorService.invokeAll(callables);
        for (final Future<Boolean> future : futures) {
            try {
                future.get(4L, TimeUnit.MINUTES);
            } catch (ExecutionException | TimeoutException e) {
                throw new RuntimeException(e);
            }
        }
        executorService.shutdownNow();
    } catch (final InterruptedException e) {
        throw new RuntimeException("Unable to execute requests", e);
    }
    started.stop();

    LOG.info("FINISHED. Execution time: {}", started);
    LOG.info("Requests per second: {}", (params.editCount * 1000.0 / started.elapsed(TimeUnit.MILLISECONDS)));

    // Cleanup
    timer.stop();
    try {
        nioGroup.shutdownGracefully().get(20L, TimeUnit.SECONDS);
    } catch (InterruptedException | ExecutionException | TimeoutException e) {
        LOG.warn("Unable to close executor properly", e);
    }
    //stop the underlying ssh thread that gets spawned if we use ssh
    if (params.ssh) {
        AsyncSshHandler.DEFAULT_CLIENT.stop();
    }
}

From source file:de.monticore.cli.MontiCoreCLI.java

/**
 * Main method.// w w w  .  j a v  a2  s .  c o  m
 * 
 * @param args the CLI arguments
 */
public static void main(String[] args) {
    if (args.length == 0) {
        // the only required input are the grammar file(s)/directories
        System.out.println("MontiCore CLI Usage: java -jar monticore-cli.jar <grammar files> <options>");
        return;
    }
    // check if the input model(s) are specified without option and add it for
    // further processing
    if (!args[0].startsWith("-")) {
        ArrayList<String> fixedArgs = new ArrayList<String>(Arrays.asList(args));
        fixedArgs.add(0, "-" + MontiCoreConfiguration.Options.GRAMMARS_SHORT.toString());
        args = fixedArgs.toArray(new String[fixedArgs.size()]);
    }

    CLIArguments arguments = CLIArguments.forArguments(args);
    MontiCoreCLIConfiguration configuration = MontiCoreCLIConfiguration.fromArguments(arguments);

    // this will be CLI's default model path if none is specified
    Iterable<String> mp = Arrays.asList("monticore-cli.jar");
    Iterable<String> mpArg = arguments.asMap().get(MontiCoreConfiguration.Options.MODELPATH.toString());
    Iterable<String> mpShortArg = arguments.asMap()
            .get(MontiCoreConfiguration.Options.MODELPATH_SHORT.toString());
    if ((mpArg == null || Iterables.isEmpty(mpArg)) && (mpShortArg == null || Iterables.isEmpty(mpShortArg))) {
        // prepare args which contain the fixed model path
        Map<String, Iterable<String>> wrappedArgs = new HashMap<>();
        wrappedArgs.put(MontiCoreConfiguration.Options.MODELPATH.toString(), mp);
        wrappedArgs.putAll(arguments.asMap());
        // use this fixed configuration
        configuration = MontiCoreCLIConfiguration.fromMap(wrappedArgs);
    }

    // we store the requested output directory as a system variable such that we
    // can inject it into the logback configuration
    System.setProperty(MC_OUT, configuration.getInternal().getOut().getAbsolutePath());

    // this should always happen first in order to use any custom configurations
    if (System.getProperty(LOGBACK_CONFIGURATIONFILE) == null) {
        initLogging(configuration);
    }

    // this needs to be called after the statement above; otherwise logback will
    // ignore custom configurations supplied via system property
    Slf4jLog.init();

    if (System.getProperty(LOGBACK_CONFIGURATIONFILE) != null) {
        Log.debug(
                "Using system property logback configuration " + System.getProperty(LOGBACK_CONFIGURATIONFILE),
                MontiCoreCLI.class.getName());
    }

    // before we launch MontiCore we check if there are any ".mc4" files in the
    // input argument (source path)
    Iterator<Path> inputPaths = configuration.getInternal().getGrammars().getResolvedPaths();
    if (!inputPaths.hasNext()) {
        System.clearProperty(MC_OUT);
        Log.error("0xA1000 There are no \".mc4\" files to parse. Please check the \"grammars\" option.");
        return;
    }

    try {
        // since this is the default we load the default script
        ClassLoader l = MontiCoreScript.class.getClassLoader();
        String script = Resources
                .asCharSource(l.getResource("de/monticore/monticore_emf.groovy"), Charset.forName("UTF-8"))
                .read();

        // BUT if the user specifies another script to use, we check if it is
        // there and load its content
        if (configuration.getScript().isPresent()) {
            if (!configuration.getScript().get().exists()) {
                System.clearProperty(MC_OUT);
                Log.error("0xA1001 Custom script \"" + configuration.getScript().get().getPath()
                        + "\" not found!");
                return;
            }
            script = Files.toString(configuration.getScript().get(), Charset.forName("UTF-8"));
        }

        // execute the scripts (either default or custom)
        new MontiCoreScript().run(script, configuration.getInternal());
    } catch (IOException e) {
        System.clearProperty(MC_OUT);
        Log.error("0xA1002 Failed to load Groovy script.", e);
    }
}