Example usage for com.google.common.io ByteStreams copy

List of usage examples for com.google.common.io ByteStreams copy

Introduction

In this page you can find the example usage for com.google.common.io ByteStreams copy.

Prototype

public static long copy(ReadableByteChannel from, WritableByteChannel to) throws IOException 

Source Link

Document

Copies all bytes from the readable channel to the writable channel.

Usage

From source file:GenKotlinModule.java

public static void main(String[] args) throws IOException {
    try (JarOutputStream jos = new JarOutputStream(Files.newOutputStream(Paths.get(args[0])))) {
        addEntry(jos, "META-INF/bar.kotlin_module");
        jos.write("hello".getBytes(UTF_8));

        addEntry(jos, "java/lang/String.class");
        ByteStreams.copy(String.class.getResourceAsStream("/java/lang/String.class"), jos);
    }//from   w  w  w .j a v  a 2s. co m
}

From source file:GenModuleInfo.java

public static void main(String[] args) throws IOException {
    try (JarOutputStream jos = new JarOutputStream(Files.newOutputStream(Paths.get(args[0])))) {
        addEntry(jos, "module-info.class");
        jos.write("hello".getBytes(UTF_8));

        addEntry(jos, "foo/module-info.class");
        jos.write("goodbye".getBytes(UTF_8));

        addEntry(jos, "java/lang/String.class");
        ByteStreams.copy(String.class.getResourceAsStream("/java/lang/String.class"), jos);
    }// ww  w  .j av a 2s.  co m
}

From source file:io.kubernetes.client.examples.ExecExample.java

public static void main(String[] args) throws IOException, ApiException, InterruptedException {
    ApiClient client = Config.defaultClient();
    Configuration.setDefaultApiClient(client);

    Exec exec = new Exec();
    boolean tty = System.console() != null;
    //        final Process proc = exec.exec("default", "nginx-2371676037-czqx3", new String[] {"sh", "-c", "echo foo"}, true, tty);
    final Process proc = exec.exec("default", "nginx-2371676037-czqx3", new String[] { "sh" }, true, tty);

    new Thread(new Runnable() {
        public void run() {
            try {
                ByteStreams.copy(System.in, proc.getOutputStream());
            } catch (IOException ex) {
                ex.printStackTrace();// w ww . j  a va  2  s  .c om
            }
        }
    }).start();

    new Thread(new Runnable() {
        public void run() {
            try {
                ByteStreams.copy(proc.getInputStream(), System.out);
            } catch (IOException ex) {
                ex.printStackTrace();
            }
        }
    }).start();

    proc.waitFor();
    try {
        // Wait for buffers to flush.
        Thread.sleep(2000);
    } catch (InterruptedException ex) {
        ex.printStackTrace();
    }

    System.exit(0);
}

From source file:io.kubernetes.client.examples.AttachExample.java

public static void main(String[] args) throws IOException, ApiException, InterruptedException {
    ApiClient client = Config.defaultClient();
    Configuration.setDefaultApiClient(client);

    Attach attach = new Attach();
    final Attach.AttachResult result = attach.attach("default", "nginx-2371676037-czqx3", true);

    new Thread(new Runnable() {
        public void run() {
            BufferedReader in = new BufferedReader(new InputStreamReader(System.in));
            OutputStream output = result.getStandardInputStream();
            try {
                while (true) {
                    String line = in.readLine();
                    output.write(line.getBytes());
                    output.write('\n');
                    output.flush();/*from  ww  w  .j av a  2  s.  c om*/
                }
            } catch (IOException ex) {
                ex.printStackTrace();
            }
        }
    }).start();

    new Thread(new Runnable() {
        public void run() {
            try {
                ByteStreams.copy(result.getStandardOutputStream(), System.out);
            } catch (IOException ex) {
                ex.printStackTrace();
            }
        }
    }).start();

    Thread.sleep(10 * 1000);

    System.exit(0);
}

From source file:GetObjectProgressBar.java

/**
 * MinioClient.getObjectProgressBar() example.
 *//*from ww w. j  a  va  2s.  c  o m*/
public static void main(String[] args)
        throws IOException, NoSuchAlgorithmException, InvalidKeyException, XmlPullParserException {
    try {
        /* play.minio.io for test and development. */
        MinioClient minioClient = new MinioClient("https://play.minio.io:9000", "Q3AM3UQ867SPQQA43P2F",
                "zuf+tfteSlswRu7BJ86wekitnifILbZam1KYY3TG");

        /* Amazon S3: */
        // MinioClient minioClient = new MinioClient("https://s3.amazonaws.com", "YOUR-ACCESSKEYID",
        // "YOUR-SECRETACCESSKEY");

        // Check whether the object exists using statObject(). If the object is not found,
        // statObject() throws an exception. It means that the object exists when statObject()
        // execution is successful.

        // Get object stat information.
        ObjectStat objectStat = minioClient.statObject("testbucket", "resumes/4.original.pdf");

        // Get input stream to have content of 'my-objectname' from 'my-bucketname'
        InputStream is = new ProgressStream("Downloading .. ", ProgressBarStyle.ASCII, objectStat.length(),
                minioClient.getObject("my-bucketname", "my-objectname"));

        Path path = Paths.get("my-filename");
        OutputStream os = Files.newOutputStream(path, StandardOpenOption.CREATE);

        long bytesWritten = ByteStreams.copy(is, os);
        is.close();
        os.close();

        if (bytesWritten != objectStat.length()) {
            throw new IOException(path + ": unexpected data written.  expected = " + objectStat.length()
                    + ", written = " + bytesWritten);
        }

    } catch (MinioException e) {
        System.out.println("Error occurred: " + e);
    }
}

From source file:com.squareup.luhnybin.Main.java

public static void main(String[] args) throws IOException {
    if (!new File("mask.sh").exists()) {
        System.err.println("Couldn't find 'mask.sh' in the current directory.");
        System.exit(1);//from w w  w .j  a v a  2  s .c  o  m
    }

    final int iterations;
    if (args.length > 0) {
        if (args.length > 1) {
            System.err.println("Usage: ./run.sh [iterations]");
            System.exit(1);
        }

        iterations = Integer.parseInt(args[0]);
        if (iterations < 1) {
            System.err.println("Iterations must be >= 1.");
            System.exit(1);
        }
    } else {
        iterations = 1;
    }

    final Executor executor = Executors.newCachedThreadPool(new ThreadFactory() {
        public Thread newThread(Runnable r) {
            Thread thread = new Thread(r);
            thread.setDaemon(true);
            return thread;
        }
    });

    System.out.println("Running tests against mask.sh...");
    System.out.println();

    final LuhnyBinTests luhnyBinTests = new LuhnyBinTests();
    final Process process = new ProcessBuilder("sh", "mask.sh").start();

    // Copy error stream from child process.
    executor.execute(new Runnable() {
        public void run() {
            try {
                ByteStreams.copy(process.getErrorStream(), System.err);
            } catch (IOException e) {
                /* ignore */ }
        }
    });

    // Buffer output for maximum efficiency.
    final ByteArrayOutputStream bout = new ByteArrayOutputStream();
    luhnyBinTests.writeTo(bout);

    final OutputStream out = process.getOutputStream();
    final InputStream in = process.getInputStream();
    long start = System.nanoTime();
    try {
        // Time/iteration in ms.
        long[] times = new long[iterations];

        for (int i = 0; i < iterations; i++) {
            final boolean lastIteration = i == iterations - 1;

            long iterationStart = System.nanoTime();

            // Write in the background. Writing can block if the buffer fills up.
            executor.execute(new Runnable() {
                public void run() {
                    try {
                        bout.writeTo(out);
                        out.flush();
                        if (lastIteration)
                            out.close();
                    } catch (IOException e) {
                        e.printStackTrace();
                        System.exit(1);
                    }
                }
            });

            luhnyBinTests.check(in, new TestCase.Listener() {
                public void testPassed(TestCase test) {
                    System.out.print('.');
                    if (++testsPassed % 80 == 0)
                        System.out.println();
                }

                public void testFailed(TestCase test, String actualInput) {
                    System.out.println('X');
                    System.out.println();
                    System.err.println("Test #" + test.index + " of " + luhnyBinTests.count + " failed:"
                            + "\n  Description:     " + test.description + "\n  Input:           "
                            + showBreaks(test.output) + "\n  Expected result: " + showBreaks(test.expectedInput)
                            + "\n  Actual result:   " + showBreaks(actualInput) + "\n");
                    process.destroy();
                    System.exit(1);
                }
            });
            times[i] = (System.nanoTime() - iterationStart) / 1000;
        }

        long elapsed = (System.nanoTime() - start) / 1000000;

        System.out.println();
        if (testsPassed % 80 != 0)
            System.out.println();
        System.out.println("Tests passed!");
        System.out.println();
        System.out.printf("Total time:   %,dms%n", elapsed);

        if (iterations > 1) {
            long sum = 0;
            for (long time : times)
                sum += time;

            Arrays.sort(times);
            System.out.printf("Mean time:    %,dus%n", sum / times.length);
            System.out.printf("Median time:  %,dus%n", times[times.length / 2]);
            System.out.printf("Fastest time: %,dus%n", times[0]);
        }

        System.out.println();
        process.destroy();
        System.exit(0);
    } catch (EOFException e) {
        System.err.println("Error: mask.sh didn't send the expected amount of output.");
        process.destroy();
        System.exit(1);
    }
}

From source file:com.ibm.og.cli.ObjectFile.java

public static void main(final String[] args) {
    final ObjectFileGetOpt getopt = new ObjectFileGetOpt();
    final Cli cli = Application.cli("object-file", getopt, args);
    if (cli.shouldStop()) {
        if (cli.help()) {
            cli.printUsage();/*from w w  w.  ja  v  a2  s .  com*/
        } else if (cli.version()) {
            cli.printVersion();
        } else if (cli.error()) {
            cli.printErrors();
            cli.printUsage();
            Application.exit(Application.TEST_ERROR);
        }
        Application.exit(0);
    }

    final File input = getopt.getInput();

    final boolean write = getopt.getWrite();
    final boolean read = getopt.getRead();
    final boolean filter = getopt.getFilter();
    final boolean upgrade = getopt.getUpgrade();
    final boolean split = getopt.getSplit();
    final int splitSize = getopt.getSplitSize();
    final String output = getopt.getOutput();
    final long minFilesize = getopt.getMinSize();
    final long maxFilesize = getopt.getMaxSize();
    final int minContainerSuffix = getopt.getMinSuffix();
    final int maxContainerSuffix = getopt.getMaxSuffix();

    final Set<Integer> containerSuffixes = getopt.getContainerSuffixes();

    try {
        final InputStream in = getInputStream(input);
        final OutputStream out;

        if (write) {
            out = getOutputStream(split, splitSize, output);
            write(in, out);
        } else if (read) {
            out = getOutputStream(output);
            read(in, out);
        } else if (filter) {
            out = getOutputStream(split, splitSize, output);
            filter(in, out, minFilesize, maxFilesize, minContainerSuffix, maxContainerSuffix,
                    containerSuffixes);
        } else if (upgrade) {
            out = getOutputStream(split, splitSize, output);
            upgrade(in, out);
        } else if (split) { // Order matters here - write, filter, upgrade must be above
            out = getOutputStream(split, splitSize, output);
            split(in, out);
        } else { // Default case - just output the same file
            out = getOutputStream(output);
            ByteStreams.copy(in, out);
        }

        if (!out.equals(System.out)) {
            out.close();
        }
    } catch (final IOException e) {
        _consoleLogger.error("", e);
        Application.exit(Application.TEST_ERROR);
    }

    Application.exit(0);
}

From source file:net.fabricmc.base.util.mixin.MixinPrebaker.java

public static void main(String[] args) {
    boolean hasMappingsFile = false;

    if (args.length < 3) {
        System.out.println("usage: MixinPrebaker [-m mapping-file] <input-jar> <output-jar> <mod-jars...>");
        return;//from   w  w w.j  a  v  a 2 s .c om
    }

    int argOffset;
    for (argOffset = 0; argOffset < args.length; argOffset++) {
        if ("-m".equals(args[argOffset])) {
            hasMappingsFile = true;
            FabricMixinBootstrap.setMappingFile(new File(args[++argOffset]));
        } else {
            break;
        }
    }

    Set<File> modFiles = new HashSet<>();
    for (int i = argOffset + 2; i < args.length; i++) {
        modFiles.add(new File(args[i]));
    }

    URLClassLoader ucl = (URLClassLoader) MixinPrebaker.class.getClassLoader();
    Launch.classLoader = new LaunchClassLoader(ucl.getURLs());
    Launch.blackboard = new HashMap<>();
    Launch.blackboard.put(Blackboard.Keys.TWEAKS, Collections.emptyList());

    MixinLoader mixinLoader = new MixinLoader();
    mixinLoader.load(modFiles);

    FabricMixinBootstrap.init(Side.UNIVERSAL, mixinLoader);

    MixinEnvironment.EnvironmentStateTweaker tweaker = new MixinEnvironment.EnvironmentStateTweaker();
    tweaker.getLaunchArguments();
    tweaker.injectIntoClassLoader(Launch.classLoader);

    MixinTransformer mixinTransformer = Blackboard.get(Blackboard.Keys.TRANSFORMER);

    try {
        JarInputStream input = new JarInputStream(new FileInputStream(new File(args[argOffset + 0])));
        JarOutputStream output = new JarOutputStream(new FileOutputStream(new File(args[argOffset + 1])));
        JarEntry entry;
        while ((entry = input.getNextJarEntry()) != null) {
            if (entry.getName().equals(FabricMixinBootstrap.APPLIED_MIXIN_CONFIGS_FILENAME)) {
                continue;
            }

            if (hasMappingsFile && entry.getName().equals(FabricMixinBootstrap.MAPPINGS_FILENAME)) {
                continue;
            }

            if (entry.getName().endsWith(".class")) {
                byte[] classIn = ByteStreams.toByteArray(input);
                String className = entry.getName().substring(0, entry.getName().length() - 6).replace('/', '.');
                byte[] classOut = mixinTransformer.transform(className, className, classIn);
                if (classIn != classOut) {
                    System.out.println("Transformed " + className);
                    classOut = desprinkle(classOut);
                }
                JarEntry newEntry = new JarEntry(entry.getName());
                newEntry.setComment(entry.getComment());
                newEntry.setSize(classOut.length);
                newEntry.setLastModifiedTime(FileTime.from(Instant.now()));
                output.putNextEntry(newEntry);
                output.write(classOut);
            } else {
                output.putNextEntry(entry);
                ByteStreams.copy(input, output);
            }
        }

        output.putNextEntry(new JarEntry(FabricMixinBootstrap.APPLIED_MIXIN_CONFIGS_FILENAME));
        output.write(
                Strings.join(FabricMixinBootstrap.getAppliedMixinConfigs(), "\n").getBytes(Charsets.UTF_8));

        if (hasMappingsFile) {
            output.putNextEntry(new JarEntry(FabricMixinBootstrap.MAPPINGS_FILENAME));
            Files.copy(FabricMixinBootstrap.getMappingFile().toPath(), output);
        }

        input.close();
        output.close();
    } catch (IOException e) {
        throw new RuntimeException(e);
    }
}

From source file:com.google.devtools.build.android.ResourceShrinkerAction.java

public static void main(String[] args) throws Exception {
    final Stopwatch timer = Stopwatch.createStarted();
    // Parse arguments.
    OptionsParser optionsParser = OptionsParser.newOptionsParser(Options.class, AaptConfigOptions.class);
    optionsParser.parseAndExitUponError(args);
    aaptConfigOptions = optionsParser.getOptions(AaptConfigOptions.class);
    options = optionsParser.getOptions(Options.class);

    AndroidResourceProcessor resourceProcessor = new AndroidResourceProcessor(stdLogger);
    // Setup temporary working directories.
    try (ScopedTemporaryDirectory scopedTmp = new ScopedTemporaryDirectory("resource_shrinker_tmp")) {
        Path working = scopedTmp.getPath();
        final Path resourceFiles = working.resolve("resource_files");

        final Path shrunkResources = working.resolve("shrunk_resources");

        // Gather package list from manifests.
        Set<String> resourcePackages = getManifestPackages(options.primaryManifest,
                options.dependencyManifests);
        resourcePackages.addAll(options.resourcePackages);

        // Expand resource files zip into working directory.
        try (ZipInputStream zin = new ZipInputStream(new FileInputStream(options.resourcesZip.toFile()))) {
            ZipEntry entry;//from ww w .  java2 s .c o m
            while ((entry = zin.getNextEntry()) != null) {
                if (!entry.isDirectory()) {
                    Path output = resourceFiles.resolve(entry.getName());
                    Files.createDirectories(output.getParent());
                    try (FileOutputStream fos = new FileOutputStream(output.toFile())) {
                        ByteStreams.copy(zin, fos);
                    }
                }
            }
        }

        // Shrink resources.
        ResourceUsageAnalyzer resourceShrinker = new ResourceUsageAnalyzer(resourcePackages, options.rTxt,
                options.shrunkJar, options.primaryManifest, options.proguardMapping,
                resourceFiles.resolve("res"), options.log);

        resourceShrinker.shrink(shrunkResources);
        logger.fine(
                String.format("Shrinking resources finished at %sms", timer.elapsed(TimeUnit.MILLISECONDS)));

        Path generatedSources = null;
        if (options.rTxtOutput != null) {
            generatedSources = working.resolve("generated_resources");
        }

        // Build ap_ with shrunk resources.
        resourceProcessor.processResources(aaptConfigOptions.aapt, aaptConfigOptions.androidJar,
                aaptConfigOptions.buildToolsVersion, VariantType.DEFAULT, aaptConfigOptions.debug,
                null /* packageForR */, new FlagAaptOptions(aaptConfigOptions),
                aaptConfigOptions.resourceConfigs, aaptConfigOptions.splits,
                new MergedAndroidData(shrunkResources, resourceFiles.resolve("assets"),
                        options.primaryManifest),
                ImmutableList.<DependencyAndroidData>of() /* libraries */, generatedSources, options.shrunkApk,
                null /* proguardOutput */, null /* mainDexProguardOutput */, null /* publicResourcesOut */,
                null /* dataBindingInfoOut */);
        if (options.shrunkResources != null) {
            resourceProcessor.createResourcesZip(shrunkResources, resourceFiles.resolve("assets"),
                    options.shrunkResources, false /* compress */);
        }
        if (options.rTxtOutput != null) {
            resourceProcessor.copyRToOutput(generatedSources, options.rTxtOutput,
                    options.packageType == VariantType.LIBRARY);
        }
        logger.fine(String.format("Packing resources finished at %sms", timer.elapsed(TimeUnit.MILLISECONDS)));
    } catch (Exception e) {
        logger.log(Level.SEVERE, "Error shrinking resources", e);
        throw e;
    } finally {
        resourceProcessor.shutdown();
    }
}

From source file:resources.MonitorCLI.java

public static void main(String[] args) {

    String metricName = "AppAvailable";// "CPUUtilization";
    String metricNameForObserver = "AppAvailabilityViolation";// "FrontendCPUUtilization1";
    String appID = "chat-WebApplication_ID";
    String vmID = "tomcat_server_VM_ID";// "frontend1";

    boolean initiated = false, firstTime = true;

    try {/*w  w  w.  j ava  2 s  .c o  m*/

        String msg = null;

        File currentDir = new File(System.getProperty("user.dir"));

        String parentDir = currentDir.getParent();

        System.out.println("\nSeaClouds Monitoring Platform Menu:\n");

        while (true) {

            if (firstTime || !initiated)
                System.out.println("1. Initialize and initiate the monitoring platform");
            System.out.println("2: Install monitoring rules (in XML format)");
            System.out.println("3: Install a deployment model (in JSON format)");
            System.out.println("4: Get all monitoring metrics");
            System.out.println("5: Get running monitoring metrics");
            System.out.println("6: Retrieve the executation file of all data collectors");
            System.out.println(
                    "7: Retrieve the executation file of a data collector (providing the name of a metric)");
            System.out.println("8: Retrieve the installation file of the data collector(s) and install it");
            System.out.println("9: Uninstall monitoring rule");
            System.out.println("10: Add observer");
            System.out.println("11: Send replanning event");
            System.out.println("12: Execute existing installation file of data collector(s)");
            System.out.println("13: Exit");
            System.out.print("\nChoice = ");

            BufferedReader input = new BufferedReader(new InputStreamReader(System.in));

            String answer = input.readLine();

            System.out.println();

            int answerInt = 0;

            if (answer == null || (answer != null && answer.equals("")))
                answerInt = 0;

            else
                answerInt = Integer.parseInt(answer);

            if (answerInt == 1 && !initiated) {

                File initializationFile = new File(INITIALIZATION_CONFIGURATION_FILE);

                if (!initializationFile.exists()) {

                    msg = "[INFO] Monitor REST Service Main: Initialization file does not exist.\n";
                    System.out.println(msg);

                    initiated = false;
                }

                else {

                    msg = RESTGet.httpGet("http://localhost:8080/api/rest/monitor/clear");

                    String configurationFileContent = TxtFileReader.read(initializationFile);

                    msg = RESTPost.httpPost("http://localhost:8080/api/rest/monitor/initialize",
                            configurationFileContent, "text/plain");

                    if (msg != null) {

                        System.err.println(msg);

                        System.exit(-1);
                    }

                    msg = RESTPost.httpPost("http://localhost:8080/api/rest/monitor/initiate", parentDir,
                            "text/plain");

                    if (msg != null) {

                        System.err.println(msg);

                        System.exit(-1);
                    }

                    else
                        initiated = true;
                }
            }

            else if (firstTime) {

                System.out.println(
                        "[ERROR] Monitor REST Service Main: You should firstly initialize and initiate the monitoring platform.\n");

                System.out.println("Have you already initialized and initiated the monitoring platform (0/1)?");
                System.out.print("\nAnswer = ");

                input = new BufferedReader(new InputStreamReader(System.in));

                answer = input.readLine();

                System.out.println();

                int internalAnswerInt = 0;

                if (answer == null || (answer != null && answer.equals("")))
                    internalAnswerInt = 0;

                else
                    internalAnswerInt = Integer.parseInt(answer);

                if (internalAnswerInt == 1)
                    initiated = true;

                else
                    initiated = false;
            }

            firstTime = false;

            if (initiated) {

                if (answerInt == 2) {

                    File monitoringRules = new File(parentDir + MONITORING_RULES_FILE + ".xml");
                    System.out.println("\nmonitoringRules = " + monitoringRules + "\n");

                    String monitoringRulesContent = TxtFileReader.read(monitoringRules);

                    msg = RESTPost.httpPost("http://localhost:8080/api/rest/monitor/installMonitoringRules",
                            monitoringRulesContent, "xml");

                    if (msg != null) {

                        System.err.println(msg);

                        System.exit(-1);
                    }
                }

                else if (answerInt == 3) {

                    File deploymentModel = new File(parentDir + DEPLOYMENT_MODEL_FILE);
                    System.out.println("\ndeploymentModel = " + deploymentModel + "\n");

                    String deploymentModelContent = TxtFileReader.read(deploymentModel);

                    msg = RESTPost.httpPost("http://localhost:8080/api/rest/monitor/installDeploymentModel",
                            deploymentModelContent, "xml");

                    if (msg != null) {

                        System.err.println(msg);

                        System.exit(-1);
                    }
                }

                else if (answerInt == 4) {

                    String response = RESTGet.httpGet("http://localhost:8080/api/rest/monitor/getAllMetrics");

                    String[] metrics = response.split("\n");

                    System.out.println("\n\tMetrics:");

                    for (int i = 0; metrics != null && i < metrics.length; ++i) {

                        int counter = i + 1;

                        System.out.println("\t" + counter + ": " + metrics[i]);
                    }

                    System.out.println();
                }

                else if (answerInt == 5) {

                    String response = RESTGet
                            .httpGet("http://localhost:8080/api/rest/monitor/getRunningMetrics");

                    String[] metrics = response.split("\n");

                    System.out.println("\n\tMetrics:");

                    for (int i = 0; metrics != null && i < metrics.length; ++i) {

                        int counter = i + 1;

                        System.out.println("\t" + counter + ": " + metrics[i]);
                    }

                    System.out.println();
                }

                else if (answerInt == 6) {

                    InputStream data = RESTGet
                            .httpGetResponse("http://localhost:8080/api/rest/monitor/getDataCollectors");

                    OutputStream output = new FileOutputStream(DATA_COLLECTORS_FILE_NAME);

                    ByteStreams.copy(data, output);

                    System.out.println(
                            "[INFO] Monitor REST Service Main: The executation file of data collector has been retrieved.\n");
                }

                else if (answerInt == 7) {

                    String response = RESTGet.httpGet("http://localhost:8080/api/rest/monitor/getAllMetrics");

                    String[] metrics = response.split("\n");

                    System.out.println("\n\tMetrics:");

                    for (int i = 0; metrics != null && i < metrics.length; ++i) {

                        int counter = i + 1;

                        System.out.println("\t" + counter + ": " + metrics[i]);
                    }

                    System.out.print("\n\tMetric name = ");

                    input = new BufferedReader(new InputStreamReader(System.in));

                    answer = input.readLine();

                    System.out.println();

                    if (answer != null && !answer.equals(""))
                        metricName = metrics[Integer.parseInt(answer) - 1];

                    System.out.println(
                            "[INFO] Monitor REST Service Main: Retrieving the executation file of the data collector for the metric '"
                                    + metricName + "'...\n");

                    InputStream data = RESTPost.httpPostResponse(
                            "http://localhost:8080/api/rest/monitor/getDataCollector/" + metricName);

                    OutputStream output = new FileOutputStream(DATA_COLLECTORS_FILE_NAME);

                    ByteStreams.copy(data, output);

                    System.out.println(
                            "[INFO] Monitor REST Service Main: The executation file of the data collector for the metric '"
                                    + metricName + "' has been retrieved.\n");
                }

                else if (answerInt == 8) {

                    String fileContent = RESTPost
                            .httpPost("http://localhost:8080/api/rest/monitor/getDataCollectorInstallationFile/"
                                    + metricName + "/" + appID + "/" + vmID);

                    TxtFileWriter.write(fileContent, DATA_COLLECTORS_INSTALLATION_FILE_NAME);

                    if (!new File(parentDir + LOCAL_SIGAR).exists() && metricName.equals("CPUUtilization")) {

                        System.out.println("Downloading hyperic-sigar-1.6.4.zip...");

                        download("hyperic-sigar-1.6.4.zip",
                                "https://magelan.googlecode.com/files/hyperic-sigar-1.6.4.zip");

                        unzip("lib/hyperic-sigar-1.6.4.zip", "lib");
                    }

                    WindowsBatchFileExecution.execute(DATA_COLLECTORS_INSTALLATION_FILE_NAME);

                    System.out.println(
                            "[INFO] Monitor REST Service Main: The installation file of data collector has been retrieved and executed.\n");
                }

                else if (answerInt == 9) {

                    System.out.println("Provide the id of the monitoring rule");
                    System.out.print("\nID = ");

                    input = new BufferedReader(new InputStreamReader(System.in));

                    answer = input.readLine();

                    System.out.println();

                    msg = RESTPost.httpPost(
                            "http://localhost:8080/api/rest/monitor/uninstallMonitoringRule/" + answer);

                    System.out.println(msg);
                }

                else if (answerInt == 10) {

                    System.out.println("Provide the metric name");
                    System.out.print("\nMetric name = ");

                    input = new BufferedReader(new InputStreamReader(System.in));

                    answer = input.readLine();

                    if (answer != null && !answer.equals(""))
                        metricNameForObserver = answer;

                    System.out.println();

                    String port = "8123";

                    System.out.println("Provide the port of the observer (default = 8123)");
                    System.out.print("\nPort = ");

                    input = new BufferedReader(new InputStreamReader(System.in));

                    answer = input.readLine();

                    if (answer != null && !answer.equals(""))
                        port = answer;

                    System.out.println();

                    String callbackURL = "http://localhost:8123";

                    System.out.println("Provide the callback IP (default = localhost)");
                    System.out.print("\nURL = ");

                    input = new BufferedReader(new InputStreamReader(System.in));

                    answer = input.readLine();

                    if (answer != null && !answer.equals(""))
                        callbackURL = "http://" + answer + ":" + port;

                    System.out.println();

                    msg = RESTPost.httpPost("http://localhost:8080/api/rest/monitor/addObserver/"
                            + metricNameForObserver + "/" + port, callbackURL);

                    if (msg != null) {

                        System.err.println(msg);

                        System.exit(-1);
                    }
                }

                else if (answerInt == 11) {

                    String replanningEvent = "Dummy event";

                    msg = RESTPost.httpPost("http://localhost:8080/api/rest/monitor/sendReplanningEvent",
                            replanningEvent, "xml");

                    System.out.println(msg);
                }

                else if (answerInt == 12) {

                    if (!new File(parentDir + LOCAL_SIGAR).exists() && metricName.equals("CPUUtilization")) {

                        System.out.println("Downloading hyperic-sigar-1.6.4.zip...");

                        download("hyperic-sigar-1.6.4.zip",
                                "https://magelan.googlecode.com/files/hyperic-sigar-1.6.4.zip");

                        unzip("lib/hyperic-sigar-1.6.4.zip", "lib");
                    }

                    WindowsBatchFileExecution.execute(DATA_COLLECTORS_INSTALLATION_FILE_NAME);

                    System.out.println(
                            "[INFO] Monitor REST Service Main: The installation file of data collector has been executed.\n");
                }

                else if (answerInt == 13) {

                    Runtime.getRuntime().exec("taskkill /im cmd.exe");

                    System.out.println(
                            "[INFO] Monitor REST Service Main: The client of the monitoring platform is terminated.\n");

                    System.exit(0);
                }
            }
        }
    }

    catch (Exception ex) {

        ex.printStackTrace();
    }
}