Example usage for java.io Closeable close

List of usage examples for java.io Closeable close

Introduction

In this page you can find the example usage for java.io Closeable close.

Prototype

public void close() throws IOException;

Source Link

Document

Closes this stream and releases any system resources associated with it.

Usage

From source file:br.edu.ufcg.lsd.oursim.ui.CLI.java

/**
 * Exemplo:/*from   www  . j a v a  2s.co m*/
 * 
 * <pre>
 *   java -jar oursim.jar -w resources/trace_filtrado_primeiros_1000_jobs.txt -m resources/hostinfo_sdsc.dat -synthetic_av -o oursim_trace.txt
 *   -w resources/trace_filtrado_primeiros_1000_jobs.txt -s persistent -nr 20 -md resources/hostinfo_sdsc.dat -av resources/disponibilidade.txt -o oursim_trace.txt
 *   -w resources/new_iosup_workload.txt -s persistent -pd resources/iosup_site_description.txt -wt iosup -nr 1 -synthetic_av -o oursim_trace.txt
 *   -w resources/new_workload.txt -s persistent -pd resources/marcus_site_description.txt -wt marcus -nr 20 -d -o oursim_trace.txt
 *   1 ms + 1 dia = 2678400 segundos
 * </pre>
 * 
 * @param args
 * @throws FileNotFoundException
 */
public static void main(String[] args) throws IOException {

    StopWatch stopWatch = new StopWatch();
    stopWatch.start();
    List<Closeable> closeables = new ArrayList<Closeable>();

    CommandLine cmd = parseCommandLine(args, prepareOptions(), HELP, USAGE, EXECUTION_LINE);

    File outputFile = (File) cmd.getOptionObject(OUTPUT);
    PrintOutput printOutput = new PrintOutput(outputFile, false);
    JobEventDispatcher.getInstance().addListener(printOutput);
    closeables.add(printOutput);
    if (cmd.hasOption(EXTRACT_REMOTE_WORKLOAD)) {
        File remoteWorkloadFile = (File) cmd.getOptionObject(EXTRACT_REMOTE_WORKLOAD);
        Output remoteWorkloadExtractor = new RemoteTasksExtractorOutput(remoteWorkloadFile);
        closeables.add(remoteWorkloadExtractor);
        JobEventDispatcher.getInstance().addListener(remoteWorkloadExtractor);
    }
    Grid grid = prepareGrid(cmd);

    ComputingElementEventCounter computingElementEventCounter = prepareOutputAccounting(cmd,
            cmd.hasOption(VERBOSE));

    Input<? extends AvailabilityRecord> availability = defineAvailability(cmd, grid.getMapOfPeers());

    prepareOptionalOutputFiles(cmd, grid, (SyntheticAvailabilityCharacterizationAbstract) availability,
            closeables);

    long timeOfFirstSubmission = cmd.getOptionValue(WORKLOAD_TYPE).equals("gwa")
            ? GWAFormat.extractSubmissionTimeFromFirstJob(cmd.getOptionValue(WORKLOAD))
            : 0;
    Workload workload = defineWorkloadType(cmd, cmd.getOptionValue(WORKLOAD), grid.getMapOfPeers(),
            timeOfFirstSubmission);

    JobSchedulerPolicy jobScheduler = defineScheduler(cmd, grid.getListOfPeers());

    OurSim oursim = new OurSim(EventQueue.getInstance(), grid, jobScheduler, workload, availability);

    oursim.setActiveEntity(new ActiveEntityImp());

    if (cmd.hasOption(HALT_SIMULATION)) {
        oursim.addHaltEvent(((Number) cmd.getOptionObject(HALT_SIMULATION)).longValue());
    }

    oursim.start();

    for (Closeable c : closeables) {
        c.close();
    }

    EventQueue.getInstance().clear();

    // adiciona mtricas-resumo ao fim do arquivo
    FileWriter fw = new FileWriter(cmd.getOptionValue(OUTPUT), true);
    closeables.add(fw);
    stopWatch.stop();
    fw.write("# Simulation                  duration:" + stopWatch + ".\n");

    double utilization = grid.getUtilization();
    double realUtilization = grid.getTrueUtilization();

    int numberOfResourcesByPeer = Integer.parseInt(cmd.getOptionValue(NUM_RESOURCES_BY_PEER, "0"));
    fw.write(formatSummaryStatistics(computingElementEventCounter, "NA", "NA", false, grid.getPeers().size(),
            numberOfResourcesByPeer, utilization, realUtilization, stopWatch.getTime()) + "\n");
    fw.close();

    System.out.println(
            getSummaryStatistics(computingElementEventCounter, "NA", "NA", false, grid.getPeers().size(),
                    numberOfResourcesByPeer, utilization, realUtilization, stopWatch.getTime()));

}

From source file:de.hpi.fgis.hdrs.tools.Loader.java

public static void main(String[] args) throws IOException {

    if (2 > args.length) {
        System.out.println(usage);
        System.out.println(options);
        System.exit(1);/*w w w  .  j  av a 2s  .co  m*/
    }

    if (0 > args[0].indexOf(':')) {
        args[0] += ":" + Configuration.DEFAULT_RPC_PORT;
    }
    Configuration conf = Configuration.create();
    Client client = new Client(conf, args[0]);

    File[] files;
    String options = "";
    if (args[1].startsWith("-")) {
        options = args[1];
        if (3 > args.length) {
            System.out.println(usage);
            System.exit(1);
        }
        if (0 < options.indexOf('d')) {
            File dir = new File(args[2]);
            if (!dir.isDirectory()) {
                throw new IOException("Directory does not exist.");
            }
            files = dir.listFiles();
        } else {
            files = new File[] { new File(args[2]) };
        }
    } else {
        files = new File[] { new File(args[1]) };
    }

    boolean quiet = 0 < options.indexOf('q');
    boolean context = 0 < options.indexOf('c');

    boolean bench = 0 < options.indexOf('b');
    List<BenchSample> benchSamples = null;
    if (bench) {
        benchSamples = new ArrayList<BenchSample>();
    }

    long timeStalled = 0;
    long timeRouterUpdate = 0;
    long abortedTransactions = 0;

    long nBytesTotal = 0;
    long nTriplesTotal = 0;
    long timeTotal = 0;

    for (int i = 0; i < files.length; ++i) {
        Closeable source = null;
        TripleScanner scanner = null;

        try {
            if (0 < options.indexOf('t')) {
                TripleFileReader reader = new TripleFileReader(files[i]);
                reader.open();
                scanner = reader.getScanner();
                source = reader;
            } else if (0 < options.indexOf('z')) {
                GZIPInputStream stream = new GZIPInputStream(new FileInputStream(files[i]));
                BTCParser parser = new BTCParser();
                parser.setSkipContext(!context);
                scanner = new StreamScanner(stream, parser);
                source = stream;
            } else {
                BTCParser parser = new BTCParser();
                parser.setSkipContext(!context);
                FileSource file = new FileSource(files[i], parser);
                scanner = file.getScanner();
                source = file;
            }
        } catch (IOException ioe) {
            System.out.println("Error: Couldn't open " + files[i] + ". See log for details.");
            LOG.error("Error: Couldn't open " + files[i] + ":", ioe);
            continue;
        }

        long nBytes = 0;
        long nTriples = 0;
        long time = System.currentTimeMillis();

        TripleOutputStream out = client.getOutputStream();

        while (scanner.next()) {
            Triple t = scanner.pop();
            out.add(t);
            nBytes += t.serializedSize();
            nTriples++;

            if (!quiet && 0 == (nTriples % (16 * 1024))) {
                System.out.print(String.format("\rloading... %d triples (%.2f MB, %.2f MB/s)", nTriples,
                        LogFormatUtil.MB(nBytes),
                        LogFormatUtil.MBperSec(nBytes, System.currentTimeMillis() - time)));
            }
        }
        out.close();

        time = System.currentTimeMillis() - time;

        scanner.close();
        source.close();

        if (!quiet) {
            System.out.print("\r");
        }
        System.out.println(String.format("%s: %d triples (%.2f MB) loaded " + "in %.2f seconds (%.2f MB/s)",
                files[i], nTriples, LogFormatUtil.MB(nBytes), time / 1000.0,
                LogFormatUtil.MBperSec(nBytes, time)));

        nBytesTotal += nBytes;
        nTriplesTotal += nTriples;
        timeTotal += time;

        timeStalled += out.getTimeStalled();
        timeRouterUpdate += out.getTimeRouterUpdate();
        abortedTransactions += out.getAbortedTransactions();

        if (bench) {
            benchSamples.add(new BenchSample(time, nTriples, nBytes));
        }
    }

    client.close();

    if (0 == nTriplesTotal) {
        System.out.println("No triples loaded.");
        return;
    }

    System.out.println(
            String.format("Done loading.  Totals: %d triples (%.2f MB) loaded " + "in %.2f seconds (%.2f MB/s)",
                    nTriplesTotal, LogFormatUtil.MB(nBytesTotal), timeTotal / 1000.0,
                    LogFormatUtil.MBperSec(nBytesTotal, timeTotal)));

    System.out.println(String.format(
            "  Client stats.  Stalled: %.2f s  RouterUpdate: %.2f s" + "  AbortedTransactions: %d",
            timeStalled / 1000.0, timeRouterUpdate / 1000.0, abortedTransactions));

    if (bench) {
        System.out.println();
        System.out.println("Benchmark Samples:");
        System.out.println("time\tsum T\tsum MB\tMB/s");
        System.out.println(String.format("%.2f\t%d\t%.2f\t%.2f", 0f, 0, 0f, 0f));
        long time = 0, nTriples = 0, nBytes = 0;
        for (BenchSample sample : benchSamples) {
            time += sample.time;
            nTriples += sample.nTriples;
            nBytes += sample.nBytes;
            System.out.println(String.format("%.2f\t%d\t%.2f\t%.2f", time / 1000.0, nTriples,
                    LogFormatUtil.MB(nBytes), LogFormatUtil.MBperSec(sample.nBytes, sample.time)));
        }
    }
}

From source file:Main.java

public static void close(Closeable close) {
    try {/*from w  w  w.j a va 2s  .c om*/
        close.close();
    } catch (IOException e) {
        e.printStackTrace();
    }
}

From source file:Main.java

private static void closeQuietly(Closeable closeable) {
    try {/* w  w  w .j av  a2  s  . c  om*/
        closeable.close();
    } catch (Exception e) {
    }
}

From source file:Main.java

public static void closeSilently(Closeable closeable) {
    try {//w w  w  .j av a 2  s. c om
        closeable.close();
    } catch (Exception e) {
        // Do nothing
    }
}

From source file:Main.java

public static final void close(Closeable closeable) {
    try {//  www.  j  av a2 s. c om
        closeable.close();
        closeable = null;
    } catch (IOException e) {
        e.printStackTrace();
    }
}

From source file:Main.java

public static void close(Closeable... params) {
    if (null != params) {
        try {/*  w  ww. java  2s.c  o m*/
            for (Closeable closeable : params) {
                closeable.close();
            }
        } catch (IOException e) {
            e.printStackTrace();
        }
    }
}

From source file:Main.java

public static void close(Closeable... closeables) {

    if (closeables == null)
        return;//from  w ww  . j a  va 2 s.c om

    try {
        for (Closeable mCloseable : closeables)
            mCloseable.close();

    } catch (Exception e) {

    }

}

From source file:Main.java

public static void closeResources(Closeable... resources) {
    for (Closeable resource : resources) {
        try {// www.j  a v  a  2  s. com
            resource.close();
        } catch (IOException e) {
            // Ignore
        }
    }
}

From source file:Main.java

/**
 * Closes a resource.//from   w w w.j  a  va2 s. c o m
 * 
 * @param c The {@link Closeable} resource.
 */
public static void close(Closeable c) {
    try {
        c.close();
    } catch (Exception e) {
    }
}