Example usage for java.util UUID randomUUID

List of usage examples for java.util UUID randomUUID

Introduction

In this page you can find the example usage for java.util UUID randomUUID.

Prototype

public static UUID randomUUID() 

Source Link

Document

Static factory to retrieve a type 4 (pseudo randomly generated) UUID.

Usage

From source file:boa.compiler.BoaCompiler.java

public static void main(final String[] args) throws IOException {
    CommandLine cl = processCommandLineOptions(args);
    if (cl == null)
        return;//from www. j  av a  2s . co m
    final ArrayList<File> inputFiles = BoaCompiler.inputFiles;

    // get the name of the generated class
    final String className = getGeneratedClass(cl);

    // get the filename of the jar we will be writing
    final String jarName;
    if (cl.hasOption('o'))
        jarName = cl.getOptionValue('o');
    else
        jarName = className + ".jar";

    // make the output directory
    File outputRoot = null;
    if (cl.hasOption("cd")) {
        outputRoot = new File(cl.getOptionValue("cd"));
    } else {
        outputRoot = new File(new File(System.getProperty("java.io.tmpdir")), UUID.randomUUID().toString());
    }
    final File outputSrcDir = new File(outputRoot, "boa");
    if (!outputSrcDir.mkdirs())
        throw new IOException("unable to mkdir " + outputSrcDir);

    // find custom libs to load
    final List<URL> libs = new ArrayList<URL>();
    if (cl.hasOption('l'))
        for (final String lib : cl.getOptionValues('l'))
            libs.add(new File(lib).toURI().toURL());

    final File outputFile = new File(outputSrcDir, className + ".java");
    final BufferedOutputStream o = new BufferedOutputStream(new FileOutputStream(outputFile));
    try {
        final List<String> jobnames = new ArrayList<String>();
        final List<String> jobs = new ArrayList<String>();
        boolean isSimple = true;

        final List<Program> visitorPrograms = new ArrayList<Program>();

        SymbolTable.initialize(libs);

        final int maxVisitors;
        if (cl.hasOption('v'))
            maxVisitors = Integer.parseInt(cl.getOptionValue('v'));
        else
            maxVisitors = Integer.MAX_VALUE;

        for (int i = 0; i < inputFiles.size(); i++) {
            final File f = inputFiles.get(i);
            try {
                final BoaLexer lexer = new BoaLexer(new ANTLRFileStream(f.getAbsolutePath()));
                lexer.removeErrorListeners();
                lexer.addErrorListener(new LexerErrorListener());

                final CommonTokenStream tokens = new CommonTokenStream(lexer);
                final BoaParser parser = new BoaParser(tokens);
                parser.removeErrorListeners();
                parser.addErrorListener(new BaseErrorListener() {
                    @Override
                    public void syntaxError(Recognizer<?, ?> recognizer, Object offendingSymbol, int line,
                            int charPositionInLine, String msg, RecognitionException e)
                            throws ParseCancellationException {
                        throw new ParseCancellationException(e);
                    }
                });

                final BoaErrorListener parserErrorListener = new ParserErrorListener();
                final Start p = parse(tokens, parser, parserErrorListener);
                if (cl.hasOption("ast"))
                    new ASTPrintingVisitor().start(p);

                final String jobName = "" + i;

                try {
                    if (!parserErrorListener.hasError) {
                        new TypeCheckingVisitor().start(p, new SymbolTable());

                        final TaskClassifyingVisitor simpleVisitor = new TaskClassifyingVisitor();
                        simpleVisitor.start(p);

                        LOG.info(f.getName() + ": task complexity: "
                                + (!simpleVisitor.isComplex() ? "simple" : "complex"));
                        isSimple &= !simpleVisitor.isComplex();

                        new ShadowTypeEraser().start(p);
                        new InheritedAttributeTransformer().start(p);

                        new LocalAggregationTransformer().start(p);

                        // if a job has no visitor, let it have its own method
                        // also let jobs have own methods if visitor merging is disabled
                        if (!simpleVisitor.isComplex() || maxVisitors < 2 || inputFiles.size() == 1) {
                            new VisitorOptimizingTransformer().start(p);

                            if (cl.hasOption("pp"))
                                new PrettyPrintVisitor().start(p);
                            if (cl.hasOption("ast2"))
                                new ASTPrintingVisitor().start(p);
                            final CodeGeneratingVisitor cg = new CodeGeneratingVisitor(jobName);
                            cg.start(p);
                            jobs.add(cg.getCode());

                            jobnames.add(jobName);
                        }
                        // if a job has visitors, fuse them all together into a single program
                        else {
                            p.getProgram().jobName = jobName;
                            visitorPrograms.add(p.getProgram());
                        }
                    }
                } catch (final TypeCheckException e) {
                    parserErrorListener.error("typecheck", lexer, null, e.n.beginLine, e.n.beginColumn,
                            e.n2.endColumn - e.n.beginColumn + 1, e.getMessage(), e);
                }
            } catch (final Exception e) {
                System.err.print(f.getName() + ": compilation failed: ");
                e.printStackTrace();
            }
        }

        if (!visitorPrograms.isEmpty())
            try {
                for (final Program p : new VisitorMergingTransformer().mergePrograms(visitorPrograms,
                        maxVisitors)) {
                    new VisitorOptimizingTransformer().start(p);

                    if (cl.hasOption("pp"))
                        new PrettyPrintVisitor().start(p);
                    if (cl.hasOption("ast2"))
                        new ASTPrintingVisitor().start(p);
                    final CodeGeneratingVisitor cg = new CodeGeneratingVisitor(p.jobName);
                    cg.start(p);
                    jobs.add(cg.getCode());

                    jobnames.add(p.jobName);
                }
            } catch (final Exception e) {
                System.err.println("error fusing visitors - falling back: " + e);
                e.printStackTrace();

                for (final Program p : visitorPrograms) {
                    new VisitorOptimizingTransformer().start(p);

                    if (cl.hasOption("pp"))
                        new PrettyPrintVisitor().start(p);
                    if (cl.hasOption("ast2"))
                        new ASTPrintingVisitor().start(p);
                    final CodeGeneratingVisitor cg = new CodeGeneratingVisitor(p.jobName);
                    cg.start(p);
                    jobs.add(cg.getCode());

                    jobnames.add(p.jobName);
                }
            }

        if (jobs.size() == 0)
            throw new RuntimeException("no files compiled without error");

        final ST st = AbstractCodeGeneratingVisitor.stg.getInstanceOf("Program");

        st.add("name", className);
        st.add("numreducers", inputFiles.size());
        st.add("jobs", jobs);
        st.add("jobnames", jobnames);
        st.add("combineTables", CodeGeneratingVisitor.combineAggregatorStrings);
        st.add("reduceTables", CodeGeneratingVisitor.reduceAggregatorStrings);
        st.add("splitsize", isSimple ? 64 * 1024 * 1024 : 10 * 1024 * 1024);
        if (DefaultProperties.localDataPath != null) {
            st.add("isLocal", true);
        }

        o.write(st.render().getBytes());
    } finally {
        o.close();
    }

    compileGeneratedSrc(cl, jarName, outputRoot, outputFile);
}

From source file:eu.roschi.obdkinesis.HttpReferrerCounterApplication.java

/**
 * Start the Kinesis Client application.
 * /*from  w  ww .ja  v  a 2 s.c  om*/
 * @param args Expecting 4 arguments: Application name to use for the Kinesis Client Application, Stream name to
 *        read from, DynamoDB table name to persist counts into, and the AWS region in which these resources
 *        exist or should be created.
 */
public static void main(String[] args) throws UnknownHostException {

    if (args.length != 2) {
        System.err.println("Using default values");
        COMPUTE_RANGE_FOR_COUNTS_IN_MILLIS = 30000;
        COMPUTE_INTERVAL_IN_MILLIS = 2000;
    } else {
        COMPUTE_RANGE_FOR_COUNTS_IN_MILLIS = Integer.parseInt(args[0]);
        COMPUTE_INTERVAL_IN_MILLIS = Integer.parseInt(args[1]);
        System.err.println(
                "Using values " + Integer.parseInt(args[0]) + " width " + Integer.parseInt(args[1]) + " rate");
    }
    String applicationName = "obd_kinesis";
    String streamName = "obd_input_stream";
    String countsTableName = "obd_kinesis_count";
    Region region = SampleUtils.parseRegion("us-west-2");

    AWSCredentialsProvider credentialsProvider = new DefaultAWSCredentialsProviderChain();
    ClientConfiguration clientConfig = SampleUtils.configureUserAgentForSample(new ClientConfiguration());
    AmazonKinesis kinesis = new AmazonKinesisClient(credentialsProvider, clientConfig);
    kinesis.setRegion(region);
    AmazonDynamoDB dynamoDB = new AmazonDynamoDBClient(credentialsProvider, clientConfig);
    dynamoDB.setRegion(region);

    // Creates a stream to write to, if it doesn't exist
    StreamUtils streamUtils = new StreamUtils(kinesis);
    streamUtils.createStreamIfNotExists(streamName, 2);
    LOG.info(String.format("%s stream is ready for use", streamName));

    DynamoDBUtils dynamoDBUtils = new DynamoDBUtils(dynamoDB);
    dynamoDBUtils.createCountTableIfNotExists(countsTableName);
    LOG.info(String.format("%s DynamoDB table is ready for use", countsTableName));

    String workerId = String.valueOf(UUID.randomUUID());
    LOG.info(String.format("Using working id: %s", workerId));
    KinesisClientLibConfiguration kclConfig = new KinesisClientLibConfiguration(applicationName, streamName,
            credentialsProvider, workerId);
    kclConfig.withCommonClientConfig(clientConfig);
    kclConfig.withRegionName(region.getName());
    kclConfig.withInitialPositionInStream(InitialPositionInStream.LATEST);

    // Persist counts to DynamoDB
    DynamoDBCountPersister persister = new DynamoDBCountPersister(
            dynamoDBUtils.createMapperForTable(countsTableName));

    IRecordProcessorFactory recordProcessor = new CountingRecordProcessorFactory<HttpReferrerPair>(
            HttpReferrerPair.class, persister, COMPUTE_RANGE_FOR_COUNTS_IN_MILLIS, COMPUTE_INTERVAL_IN_MILLIS);

    Worker worker = new Worker(recordProcessor, kclConfig);

    int exitCode = 0;
    try {
        worker.run();
    } catch (Throwable t) {
        LOG.error("Caught throwable while processing data.", t);
        exitCode = 1;
    }
    System.exit(exitCode);
}

From source file:com.bachelor.boulmier.workmaster.WorkMaster.java

public static void main(String[] args) throws IOException, InterruptedException {
    defineOptions();//from w ww  .  ja va  2 s. c o m
    CommandLineParser parser = new BasicParser();
    CommandLine cmd;
    try {
        cmd = parser.parse(options, args);

        if (cmd.hasOption(MasterConfig.CMD.CLILONGOPT)) {
            cliEnabled = true;
        }
        if (cmd.hasOption(MasterConfig.CMD.DEBUGLONGOPT)) {
            debug = true;
        }
        if (cmd.hasOption(MasterConfig.CMD.MAXVMLONGOPT)) {
            maxVM = Integer.valueOf(cmd.getOptionValue(MasterConfig.CMD.MAXVMLONGOPT));
        }
        if (cmd.hasOption(MasterConfig.CMD.VERBOSELONGOPT)) {
            verbose = true;
        }
        if (cmd.hasOption(MasterConfig.CMD.REMOTEWSLONGOPT)) {
            webServer = cmd.getOptionValue(MasterConfig.CMD.REMOTEWSLONGOPT);
            if (!MasterConfig.DEFAULT.IP_PORT_PATTERN.matcher(webServer).matches()) {
                throw new ParseException("Given IP:PORT does not match pattern");
            }
        }

        if (cmd.hasOption(MasterConfig.CMD.HELPLONGOPT)) {
            printHelp();
        }

        logger = LoggerFactory.getLogger();

        QueuingService.get()
                .send(RequestBuilder.builder().withExecutableName(ExecutableName.CAT)
                        .with(RequestProperty.CLIENT_EMAIL, "anthony.boulmier.cfpt@gmail.com")
                        .with(RequestProperty.JOB_IDENTIFIER, UUID.randomUUID().toString())
                        .with(RequestProperty.ARGS, "JobExecutor.log").create());
        Thread.sleep(3000);

    } catch (ParseException pe) {
        logger.error(pe.getMessage());
        printHelp();
    }

}

From source file:awskinesis.AmazonKinesisApplicationSample.java

public static void main(String[] args) throws Exception {
    init();/*from   w  ww  .j  a  v a2s .  co  m*/

    if (args.length == 1 && "delete-resources".equals(args[0])) {
        deleteResources();
        return;
    }

    String workerId = InetAddress.getLocalHost().getCanonicalHostName() + ":" + UUID.randomUUID();
    KinesisClientLibConfiguration kinesisClientLibConfiguration = new KinesisClientLibConfiguration(
            SAMPLE_APPLICATION_NAME, SAMPLE_APPLICATION_STREAM_NAME, credentialsProvider, workerId)
                    .withRegionName("cn-north-1");
    kinesisClientLibConfiguration.withInitialPositionInStream(SAMPLE_APPLICATION_INITIAL_POSITION_IN_STREAM);

    IRecordProcessorFactory recordProcessorFactory = new AmazonKinesisApplicationRecordProcessorFactory();
    final Worker worker = new Worker(recordProcessorFactory, kinesisClientLibConfiguration);

    System.out.printf("Running %s to process stream %s as worker %s...\n", SAMPLE_APPLICATION_NAME,
            SAMPLE_APPLICATION_STREAM_NAME, workerId);

    int exitCode = 0;
    try {
        worker.run();
    } catch (Throwable t) {
        System.err.println("Caught throwable while processing data.");
        t.printStackTrace();
        exitCode = 1;
    }

    // add a shutdown hook to stop the server
    Runtime.getRuntime().addShutdownHook(new Thread(new Runnable() {
        @Override
        public void run() {
            LOG.info("########### shoutdown begin....");
            worker.shutdown();

            try {
                Thread.sleep(10000);
            } catch (InterruptedException e) {
                e.printStackTrace();
            }
            LOG.info("########### shoutdown end....");
        }
    }));

    System.exit(exitCode);
}

From source file:fr.inria.atlanmod.kyanos.benchmarks.KyanosGraphQueryRenameAllMethods.java

public static void main(String[] args) {
    Options options = new Options();

    Option inputOpt = OptionBuilder.create(IN);
    inputOpt.setArgName("INPUT");
    inputOpt.setDescription("Input Kyanos resource directory");
    inputOpt.setArgs(1);/* w w w  .  ja  va  2 s . c  om*/
    inputOpt.setRequired(true);

    Option inClassOpt = OptionBuilder.create(EPACKAGE_CLASS);
    inClassOpt.setArgName("CLASS");
    inClassOpt.setDescription("FQN of EPackage implementation class");
    inClassOpt.setArgs(1);
    inClassOpt.setRequired(true);

    Option optFileOpt = OptionBuilder.create(OPTIONS_FILE);
    optFileOpt.setArgName("FILE");
    optFileOpt.setDescription("Properties file holding the options to be used in the Kyanos Resource");
    optFileOpt.setArgs(1);

    options.addOption(inputOpt);
    options.addOption(inClassOpt);
    options.addOption(optFileOpt);

    CommandLineParser parser = new PosixParser();

    try {
        PersistenceBackendFactoryRegistry.getFactories().put(NeoBlueprintsURI.NEO_GRAPH_SCHEME,
                new BlueprintsPersistenceBackendFactory());

        CommandLine commandLine = parser.parse(options, args);

        URI uri = NeoBlueprintsURI.createNeoGraphURI(new File(commandLine.getOptionValue(IN)));

        Class<?> inClazz = KyanosGraphQueryRenameAllMethods.class.getClassLoader()
                .loadClass(commandLine.getOptionValue(EPACKAGE_CLASS));
        inClazz.getMethod("init").invoke(null);

        ResourceSet resourceSet = new ResourceSetImpl();
        resourceSet.getResourceFactoryRegistry().getProtocolToFactoryMap()
                .put(NeoBlueprintsURI.NEO_GRAPH_SCHEME, PersistentResourceFactory.eINSTANCE);

        Resource resource = resourceSet.createResource(uri);

        Map<String, Object> loadOpts = new HashMap<String, Object>();

        if (commandLine.hasOption(OPTIONS_FILE)) {
            Properties properties = new Properties();
            properties.load(new FileInputStream(new File(commandLine.getOptionValue(OPTIONS_FILE))));
            for (final Entry<Object, Object> entry : properties.entrySet()) {
                loadOpts.put((String) entry.getKey(), (String) entry.getValue());
            }
        }
        resource.load(loadOpts);
        String name = UUID.randomUUID().toString();
        {
            LOG.log(Level.INFO, "Start query");
            long begin = System.currentTimeMillis();
            JavaQueries.renameAllMethods(resource, name);
            long end = System.currentTimeMillis();
            resource.save(Collections.emptyMap());
            LOG.log(Level.INFO, "End query");
            LOG.log(Level.INFO, MessageFormat.format("Time spent: {0}", MessageUtil.formatMillis(end - begin)));
        }

        if (resource instanceof PersistentResourceImpl) {
            PersistentResourceImpl.shutdownWithoutUnload((PersistentResourceImpl) resource);
        } else {
            resource.unload();
        }

    } catch (ParseException e) {
        MessageUtil.showError(e.toString());
        MessageUtil.showError("Current arguments: " + Arrays.toString(args));
        HelpFormatter formatter = new HelpFormatter();
        formatter.printHelp("java -jar <this-file.jar>", options, true);
    } catch (Throwable e) {
        MessageUtil.showError(e.toString());
    }
}

From source file:co.turnus.analysis.partitioning.CommunicationCostPartitioningCli.java

public static void main(String[] args) {
    try {//  w w w . j a  va  2 s .  c o  m
        CommandLineParser parser = new GnuParser();
        CommandLine cmd = parser.parse(cliOptions, args);
        Configuration config = parseCommandLine(cmd);

        // init models
        AnalysisActivator.init();

        // init models
        AnalysisActivator.init();

        // set logger verbosity
        if (config.getBoolean(VERBOSE, false)) {
            TurnusLogger.setLevel(TurnusLevel.ALL);
        }

        // load trace project
        File tDir = new File(config.getString(TRACE_PROJECT));
        TraceProject project = TraceProject.load(tDir);

        CommunicationCostPartitioning ccp = new CommunicationCostPartitioning(project);
        ccp.setConfiguration(config);
        PartitioningData data = ccp.run();

        TurnusLogger.info("Storing results...");
        File outPath = new File(config.getString(OUTPUT_PATH));

        // store the analysis report
        String uuid = UUID.randomUUID().toString();
        File rFile = new File(outPath, uuid + "." + TurnusExtension.REPORT);
        Report report = DataFactory.eINSTANCE.createReport();
        report.setDate(new Date());
        report.setComment("Report with only Communication cost partitioning results analysis");
        report.getDataSet().add(data);
        EcoreHelper.storeEObject(report, new ResourceSetImpl(), rFile);
        TurnusLogger.info("TURNUS report stored in " + rFile);

        // store formatted reports
        String xlsName = config.getString(XLS, "");
        if (!xlsName.isEmpty()) {
            File xlsFile = new File(outPath, xlsName + ".xls");
            new XlsPartitioningDataWriter().write(data, xlsFile);
            TurnusLogger.info("XLS report stored in " + xlsFile);
        }

        String bxdfName = config.getString(XCF, "");
        if (!bxdfName.isEmpty()) {
            File xcfFile = new File(outPath, bxdfName + ".xcf");
            new XmlPartitioningDataWriter().write(data, xcfFile);
            TurnusLogger.info("XCF files (one for each configuration) " + "stored in " + outPath);
        }

        TurnusLogger.info("Analysis Done!");

    } catch (ParseException e) {
        TurnusLogger.error(e.getMessage());
        HelpFormatter formatter = new HelpFormatter();
        formatter.printHelp(CommunicationCostPartitioningCli.class.getSimpleName(), cliOptions);
    } catch (Exception e) {
        TurnusLogger.error(e.getMessage());
    }

}

From source file:cn.org.citycloud.srdz.utils.StringUtils.java

public static void main(String[] args) {
    System.out.println(UUID.randomUUID());
}

From source file:co.turnus.analysis.buffers.BoundedBufferSchedulingCliLauncher.java

public static void main(String[] args) {
    try {/*  w  ww.  j  a  v a  2  s  . com*/
        CommandLineParser parser = new GnuParser();
        CommandLine cmd = parser.parse(cliOptions, args);
        Configuration config = parseCommandLine(cmd);

        // init models
        AnalysisActivator.init();

        // set logger verbosity
        if (config.getBoolean(VERBOSE, false)) {
            TurnusLogger.setLevel(TurnusLevel.ALL);
        }

        File tDir = new File(config.getString(TRACE_PROJECT));
        TraceProject project = TraceProject.load(tDir);

        BoundedBufferScheduling bbs = new BoundedBufferScheduling(project);
        bbs.setConfiguration(config);

        BufferMinimizationData data = bbs.run();

        TurnusLogger.info("Storing results...");
        File outPath = new File(config.getString(OUTPUT_PATH));

        // store the analysis report
        String uuid = UUID.randomUUID().toString();
        File rFile = new File(outPath, uuid + "." + TurnusExtension.REPORT);
        Report report = DataFactory.eINSTANCE.createReport();
        report.setDate(new Date());
        report.setComment("Report with only Bounded Buffer Scheduling results analysis");
        report.getDataSet().add(data);
        EcoreHelper.storeEObject(report, new ResourceSetImpl(), rFile);
        TurnusLogger.info("TURNUS report stored in " + rFile);

        // store formatted reports
        String xlsName = config.getString(XLS, "");
        if (!xlsName.isEmpty()) {
            File xlsFile = new File(outPath, xlsName + ".xls");
            new XlsBufferMinimizationDataWriter().write(data, xlsFile);
            TurnusLogger.info("XLS report stored in " + xlsFile);
        }

        String bxdfName = config.getString(BXDF, "");
        if (!bxdfName.isEmpty()) {
            File bxdfFile = new File(outPath, bxdfName + ".bxdf");
            new XmlBufferMinimizationDataWriter().write(data, bxdfFile);
            TurnusLogger.info("BXDF files (one for each configuration) " + "stored in " + outPath);
        }

        TurnusLogger.info("Analysis Done!");

    } catch (ParseException e) {
        TurnusLogger.error(e.getMessage());
        HelpFormatter formatter = new HelpFormatter();
        formatter.printHelp(BoundedBufferSchedulingCliLauncher.class.getSimpleName(), cliOptions);
    } catch (Exception e) {
        TurnusLogger.error(e.getCause().toString());
    }
}

From source file:de.huberlin.cuneiform.main.Main.java

public static void main(String[] args)
        throws ParseException, IOException, NotDerivableException, InterruptedException, JSONException {

    GnuParser gnuParser;/*from w  ww .j  a v a 2  s  . c om*/
    CommandLine cmdline;
    Options opt;
    String value;
    int platform;
    File outputDir;
    String[] fileList;
    StringBuffer buf;
    String line;
    String dagid;
    File logFile;

    opt = new Options();

    opt.addOption("p", "platform", true, "The platform to perform the Cuneiform script's interpretation. "
            + "Possible platforms are: 'dot', 'local', and 'debug'. Default is 'local'.");

    opt.addOption("d", "directory", true,
            "The output directory, to put the interpretation intermediate and output result as well as the default location to store the log.");

    opt.addOption("c", "clean", false,
            "If set, the execution engine ignores all cached results and starts a clean workflow run.");

    opt.addOption("r", "runid", true,
            "If set, a custom id is set for this workflow run. By default a UUID string is used.");

    opt.addOption("f", "file", true,
            "Override the default location of the log file and use the specified filename instead. If the platform is 'dot', this option sets the name of the output dot-file.");

    opt.addOption("h", "help", false, "Print help text.");

    gnuParser = new GnuParser();
    cmdline = gnuParser.parse(opt, args);

    if (cmdline.hasOption("help")) {

        System.out.println("CUNEIFORM - A Functional Workflow Language\n" + LABEL_VERSION);
        new HelpFormatter().printHelp("java -jar cuneiform.jar [OPTION]*", opt);

        return;
    }

    if (cmdline.hasOption("platform")) {

        value = cmdline.getOptionValue("platform");

        if (value.equals("dot"))
            platform = PLATFORM_DOT;
        else if (value.equals("local"))
            platform = PLATFORM_LOCAL;
        else if (value.equals("debug"))
            platform = PLATFORM_DEBUG;
        else
            throw new RuntimeException("Specified platform '" + value + "' not recognized.");

    } else
        platform = PLATFORM_LOCAL;

    if (cmdline.hasOption('d')) {

        value = cmdline.getOptionValue('d');
    } else
        value = "build";

    outputDir = new File(value);

    if (outputDir.exists()) {

        if (!outputDir.isDirectory())
            throw new IOException(
                    "Output directory '" + outputDir.getAbsolutePath() + "' exists but is not a directory.");

        else if (cmdline.hasOption('c')) {

            FileUtils.deleteDirectory(outputDir);

            if (!outputDir.mkdirs())
                throw new IOException(
                        "Could not create output directory '" + outputDir.getAbsolutePath() + "'");
        }
    } else if (!outputDir.mkdirs())
        throw new IOException("Could not create output directory '" + outputDir.getAbsolutePath() + "'");

    if (cmdline.hasOption('r'))
        dagid = cmdline.getOptionValue('r');
    else
        dagid = UUID.randomUUID().toString();

    if (cmdline.hasOption('f'))
        logFile = new File(cmdline.getOptionValue('f'));
    else
        logFile = null;

    fileList = cmdline.getArgs();
    buf = new StringBuffer();
    if (fileList.length == 0) {

        try (BufferedReader reader = new BufferedReader(new InputStreamReader(System.in))) {

            while ((line = reader.readLine()) != null)
                buf.append(line).append('\n');
        }

        switch (platform) {

        case PLATFORM_DOT:
            createDot(buf.toString(), outputDir, logFile);
            break;
        case PLATFORM_LOCAL:
            runLocal(buf.toString(), outputDir, logFile, dagid);
            break;
        case PLATFORM_DEBUG:
            runDebug(buf.toString(), outputDir, logFile, dagid);
            break;
        default:
            throw new RuntimeException("Platform not recognized.");
        }
    } else

        switch (platform) {

        case PLATFORM_DOT:
            createDot(fileList, outputDir, logFile);
            break;
        case PLATFORM_LOCAL:
            runLocal(fileList, outputDir, logFile, dagid);
            break;
        case PLATFORM_DEBUG:
            runDebug(fileList, outputDir, logFile, dagid);
            break;
        default:
            throw new RuntimeException("Platform not recognized.");
        }

}

From source file:co.turnus.analysis.bottlenecks.AlgorithmicBottlenecksCliLauncher.java

public static void main(String[] args) {
    try {//from  w  ww.  j  a v  a2  s  .  c  om
        CommandLineParser parser = new GnuParser();
        CommandLine cmd = parser.parse(cliOptions, args);
        Configuration config = parseCommandLine(cmd);

        // init models
        AnalysisActivator.init();

        // set logger verbosity
        if (config.getBoolean(VERBOSE, false)) {
            TurnusLogger.setLevel(TurnusLevel.ALL);
        }

        // load trace project
        File tDir = new File(config.getString(TRACE_PROJECT));
        TraceProject project = TraceProject.load(tDir);

        // load profiling weights
        File wFile = new File(config.getString(PROFILING_WEIGHTS));
        ProfilingWeights weights = new XmlProfilingWeightsReader().read(project.getNetwork(), wFile);

        // build the trace weighter
        StatisticalTraceWeighter tw = new StatisticalTraceWeighter();
        tw.configure(weights, ActionWeightsDistribution.class);

        // run the analysis
        AlgorithmicBottlenecks ab = new AlgorithmicBottlenecks(project, tw);
        ab.setConfiguration(config);
        AlgoBottlenecksData data = ab.run();

        TurnusLogger.info("Storing results...");
        File outPath = new File(config.getString(OUTPUT_PATH));

        // store the analysis report
        String uuid = UUID.randomUUID().toString();
        File rFile = new File(outPath, uuid + "." + TurnusExtension.REPORT);
        Report report = DataFactory.eINSTANCE.createReport();
        report.setDate(new Date());
        report.setComment("Report with only Algorithmic Bottlenecks results analysis");
        report.getDataSet().add(data);
        EcoreHelper.storeEObject(report, new ResourceSetImpl(), rFile);
        TurnusLogger.info("TURNUS report stored in " + rFile);

        // store formatted reports
        String xlsName = config.getString(XLS, "");
        if (!xlsName.isEmpty()) {
            File xlsFile = new File(outPath, xlsName + ".xls");
            new XlsAlgoBottlenecksDataWriter().write(data, xlsFile);
            TurnusLogger.info("XLS report stored in " + xlsFile);
        }

        TurnusLogger.info("Analysis Done!");

    } catch (ParseException e) {
        TurnusLogger.error(e.getMessage());
        HelpFormatter formatter = new HelpFormatter();
        formatter.printHelp(AlgorithmicBottlenecksCliLauncher.class.getSimpleName(), cliOptions);
    } catch (Exception e) {
        TurnusLogger.error(e.getMessage());
    }
}