Example usage for java.io IOException getMessage

List of usage examples for java.io IOException getMessage

Introduction

In this page you can find the example usage for java.io IOException getMessage.

Prototype

public String getMessage() 

Source Link

Document

Returns the detail message string of this throwable.

Usage

From source file:MD5InputStream.java

/**
 * Command line program that will take files as arguments
 * and output the MD5 sum for each file.
 *
 * @param args command line arguments/*from w  ww  .  j  a  va  2s . c  o m*/
 *
 * @since ostermillerutils 1.00.00
 */
public static void main(String[] args) {
    if (args.length == 0) {
        System.err.println("Please specify a file.");
    } else {
        for (String element : args) {
            try {
                System.out.println(MD5.getHashString(new File(element)) + " " + element);
            } catch (IOException x) {
                System.err.println(x.getMessage());
            }
        }
    }
}

From source file:com.shieldsbetter.sbomg.Cli.java

public static void main(String[] args) {
    int result;/*from   www .j  a va2  s . co  m*/

    try {
        Options options = new Options();
        options.addOption("f", false, "Force overwrite of files that already exist.");
        options.addOption("q", false, "Quiet all non-error output.");

        CommandLineParser parser = new DefaultParser();
        CommandLine cmd = parser.parse(options, args);

        try {
            Plan p = makePlan(cmd);

            for (File input : p.files()) {
                if (!cmd.hasOption('q')) {
                    System.out.println("Processing " + input.getPath() + "...");
                }

                String modelName = nameWithoutExtension(input);
                File targetPath = p.getDestinationPath(input);
                try (Scanner inputScan = fileToScanner("input", input);
                        Writer outputWriter = outputPathToWriter(targetPath, modelName, cmd);) {
                    Object modelDesc = parseSbomgV1(inputScan);

                    try {
                        ViewModelGenerator.generate(p.getPackage(input), modelName, modelDesc, outputWriter);
                    } catch (IOException ioe) {
                        throw new FileException(buildOutputFile(targetPath, modelName), "writing to target",
                                ioe.getMessage());
                    }
                } catch (IOException ioe) {
                    throw new FileException(buildOutputFile(targetPath, modelName), "opening target",
                            ioe.getMessage());
                }
            }

            result = 0;
        } catch (OperationException oe) {
            System.err.println();
            System.err.println(oe.getMessage());
            result = 1;
        }
    } catch (FileException fe) {
        System.err.println();
        System.err.println("Error " + fe.getTask() + " file " + fe.getFile().getPath() + ":");
        System.err.println("    " + fe.getMessage());

        result = 1;
    } catch (ParseException pe) {
        throw new RuntimeException(pe);
    }

    System.exit(result);
}

From source file:at.ac.tuwien.inso.subcat.reporter.Reporter.java

public static void main(String[] args) {
    Options options = new Options();
    options.addOption("h", "help", false, "Show this options");
    options.addOption("d", "db", true, "The database to process (required)");
    options.addOption("p", "project", true, "The project ID to process");
    options.addOption("P", "list-projects", false, "List all registered projects");
    options.addOption("C", "config", true, "A configuration file including reports");
    options.addOption("F", "list-formats", false, "List all supported output formats");
    options.addOption("f", "format", true, "Output format");
    options.addOption("R", "list-reports", false, "List all report types");
    options.addOption("r", "report", true, "Report type");
    options.addOption("o", "output", true, "Output path");
    options.addOption("c", "commit-dictionary", true, "The commit dictionary ID to use");
    options.addOption("b", "bug-dictionary", true, "The bug dictionary ID to use");
    options.addOption("D", "list-dictionaries", false, "List all dictionaries");
    options.addOption("v", "verbose", false, "Show details");

    at.ac.tuwien.inso.subcat.utility.Reporter errReporter = new at.ac.tuwien.inso.subcat.utility.Reporter(
            false);/*w ww  .j  a v a 2 s .  c om*/
    Settings settings = new Settings();
    boolean verbose = false;
    ModelPool pool = null;
    Model model = null;

    CommandLineParser parser = new PosixParser();

    try {
        CommandLine cmd = parser.parse(options, args);
        verbose = cmd.hasOption("verbose");

        if (cmd.hasOption("help")) {
            HelpFormatter formatter = new HelpFormatter();
            formatter.printHelp("postprocessor", options);
            return;
        }

        if (cmd.hasOption("db") == false) {
            errReporter.error("reporter", "Option --db is required");
            errReporter.printSummary();
            return;
        }

        if (cmd.hasOption("config") == false) {
            errReporter.error("reporter", "Option --config is required");
            errReporter.printSummary();
            return;
        }

        Configuration config = new Configuration();
        Parser configParser = new Parser();
        try {
            configParser.parse(config, new File(cmd.getOptionValue("config")));
        } catch (IOException e) {
            errReporter.error("reporter", "Could not read configuration file: " + e.getMessage());
            errReporter.printSummary();
            return;
        } catch (ParserException e) {
            errReporter.error("reporter", "Could not parse configuration file: " + e.getMessage());
            errReporter.printSummary();
            return;
        }

        if (cmd.hasOption("list-reports")) {
            int i = 1;

            for (ExporterConfig exconf : config.getExporterConfigs()) {
                System.out.println("  (" + i + ") " + exconf.getName());
                i++;
            }

            return;
        }

        File dbf = new File(cmd.getOptionValue("db"));
        if (dbf.exists() == false || dbf.isFile() == false) {
            errReporter.error("reporter", "Invalid database file path");
            errReporter.printSummary();
            return;
        }

        pool = new ModelPool(cmd.getOptionValue("db"), 2);
        pool.setPrintTemplates(verbose);
        model = pool.getModel();

        if (cmd.hasOption("list-formats")) {
            Reporter exporter = new Reporter(model);
            int i = 1;

            for (ReportWriter formatter : exporter.getWriters()) {
                System.out.println("  (" + i + ") " + formatter.getLabel());
                i++;
            }

            return;
        }

        if (cmd.hasOption("list-projects")) {
            for (Project proj : model.getProjects()) {
                System.out.println("  " + proj.getId() + ": " + proj.getDate());
            }

            return;
        }

        Integer projId = null;
        if (cmd.hasOption("project") == false) {
            errReporter.error("reporter", "Option --project is required");
            errReporter.printSummary();
            return;
        } else {
            try {
                projId = Integer.parseInt(cmd.getOptionValue("project"));
            } catch (NumberFormatException e) {
                errReporter.error("reporter", "Invalid project ID");
                errReporter.printSummary();
                return;
            }
        }

        if (cmd.hasOption("output") == false) {
            errReporter.error("reporter", "Option --output is required");
            errReporter.printSummary();
            return;
        }

        String outputPath = cmd.getOptionValue("output");
        model = pool.getModel();
        Project project = model.getProject(projId);

        if (project == null) {
            errReporter.error("reporter", "Invalid project ID");
            errReporter.printSummary();
            return;
        }

        if (cmd.hasOption("list-dictionaries")) {
            List<at.ac.tuwien.inso.subcat.model.Dictionary> dictionaries = model.getDictionaries(project);
            for (at.ac.tuwien.inso.subcat.model.Dictionary dict : dictionaries) {
                System.out
                        .println("  (" + dict.getId() + ") " + " " + dict.getContext() + " " + dict.getName());
            }
            return;
        }

        int bugDictId = -1;
        if (cmd.hasOption("bug-dictionary")) {
            try {
                bugDictId = Integer.parseInt(cmd.getOptionValue("bug-dictionary"));
                List<at.ac.tuwien.inso.subcat.model.Dictionary> dictionaries = model.getDictionaries(project);
                boolean valid = false;

                for (at.ac.tuwien.inso.subcat.model.Dictionary dict : dictionaries) {
                    if (dict.getId() == bugDictId) {
                        valid = true;
                        break;
                    }
                }

                if (valid == false) {
                    errReporter.error("reporter", "Invalid bug dictionary ID");
                    errReporter.printSummary();
                    return;
                }
            } catch (NumberFormatException e) {
                errReporter.error("reporter", "Invalid bug dictionary ID");
                errReporter.printSummary();
                return;
            }
        }

        int commitDictId = -1;
        if (cmd.hasOption("commit-dictionary")) {
            try {
                commitDictId = Integer.parseInt(cmd.getOptionValue("commit-dictionary"));
                List<at.ac.tuwien.inso.subcat.model.Dictionary> dictionaries = model.getDictionaries(project);
                boolean valid = false;

                for (at.ac.tuwien.inso.subcat.model.Dictionary dict : dictionaries) {
                    if (dict.getId() == commitDictId) {
                        valid = true;
                        break;
                    }
                }

                if (valid == false) {
                    errReporter.error("reporter", "Invalid commit dictionary ID");
                    errReporter.printSummary();
                    return;
                }
            } catch (NumberFormatException e) {
                errReporter.error("reporter", "Invalid commit dictionary ID");
                errReporter.printSummary();
                return;
            }
        }

        if (cmd.hasOption("format") == false) {
            errReporter.error("reporter", "Option --format is required");
            errReporter.printSummary();
            return;
        }

        Reporter exporter = new Reporter(model);
        ReportWriter writer = null;
        try {
            int id = Integer.parseInt(cmd.getOptionValue("format"));
            if (id < 1 || id > exporter.getWriters().size()) {
                errReporter.error("reporter", "Invalid output format");
                errReporter.printSummary();
                return;
            }

            writer = exporter.getWriters().get(id - 1);
        } catch (NumberFormatException e) {
            errReporter.error("reporter", "Invalid output format");
            errReporter.printSummary();
            return;
        }

        ExporterConfig exporterConfig = null;
        if (cmd.hasOption("report") == false) {
            errReporter.error("reporter", "Option --report is required");
            errReporter.printSummary();
            return;
        } else {
            try {
                int id = Integer.parseInt(cmd.getOptionValue("report"));
                if (id < 1 || id > config.getExporterConfigs().size()) {
                    errReporter.error("reporter", "Invalid reporter ID");
                    errReporter.printSummary();
                    return;
                }

                exporterConfig = config.getExporterConfigs().get(id - 1);
            } catch (NumberFormatException e) {
                errReporter.error("reporter", "Invalid reporter ID");
                errReporter.printSummary();
                return;
            }
        }

        exporter.export(exporterConfig, project, commitDictId, bugDictId, settings, writer, outputPath);
    } catch (ParseException e) {
        errReporter.error("reporter", "Parsing failed: " + e.getMessage());
        if (verbose == true) {
            e.printStackTrace();
        }
    } catch (ClassNotFoundException e) {
        errReporter.error("reporter", "Failed to create a database connection: " + e.getMessage());
        if (verbose == true) {
            e.printStackTrace();
        }
    } catch (SQLException e) {
        errReporter.error("reporter", "Failed to create a database connection: " + e.getMessage());
        if (verbose == true) {
            e.printStackTrace();
        }
    } catch (ReporterException e) {
        errReporter.error("reporter", "Reporter Error: " + e.getMessage());
        if (verbose == true) {
            e.printStackTrace();
        }
    } finally {
        if (model != null) {
            model.close();
        }
        if (pool != null) {
            pool.close();
        }
    }

    errReporter.printSummary();
}

From source file:com.mycompany.mavenproject4.web.java

/**
 * @param args the command line arguments
 *//*from  www .j  a  v a  2s . c  o  m*/
public static void main(String[] args) {
    System.out.println("Enter your choice do you want to work with \n 1.PostGreSQL \n 2.Redis \n 3.Mongodb");
    InputStreamReader IORdatabase = new InputStreamReader(System.in);
    BufferedReader BIOdatabase = new BufferedReader(IORdatabase);
    String Str1 = null;
    try {
        Str1 = BIOdatabase.readLine();
    } catch (Exception E7) {
        System.out.println(E7.getMessage());
    }

    // loading data from the CSV file 

    CsvReader data = null;

    try {
        data = new CsvReader("\\data\\Consumer_Complaints.csv");
    } catch (FileNotFoundException EB) {
        System.out.println(EB.getMessage());
    }
    int noofcolumn = 5;
    int noofrows = 100;
    int loops = 0;

    try {
        data = new CsvReader("\\data\\Consumer_Complaints.csv");
    } catch (FileNotFoundException E) {
        System.out.println(E.getMessage());
    }

    String[][] Dataarray = new String[noofrows][noofcolumn];
    try {
        while (data.readRecord()) {
            String v;
            String[] x;
            v = data.getRawRecord();
            x = v.split(",");
            for (int j = 0; j < noofcolumn; j++) {
                String value = null;
                int z = j;
                value = x[z];
                try {
                    Dataarray[loops][j] = value;
                } catch (Exception E) {
                    System.out.println(E.getMessage());
                }
                // System.out.println(Dataarray[iloop][j]);
            }
            loops = loops + 1;
        }
    } catch (IOException Em) {
        System.out.println(Em.getMessage());
    }

    data.close();

    // connection to Database 
    switch (Str1) {
    // postgre code goes here 
    case "1":

        Connection Conn = null;
        Statement Stmt = null;
        URI dbUri = null;
        String choice = null;
        InputStreamReader objin = new InputStreamReader(System.in);
        BufferedReader objbuf = new BufferedReader(objin);
        try {
            Class.forName("org.postgresql.Driver");
        } catch (Exception E1) {
            System.out.println(E1.getMessage());
        }
        String username = "ahkyjdavhedkzg";
        String password = "2f7c3_MBJbIy1uJsFyn7zebkhY";
        String dbUrl = "jdbc:postgresql://ec2-54-83-199-54.compute-1.amazonaws.com:5432/d2l6hq915lp9vi?ssl=true&sslfactory=org.postgresql.ssl.NonValidatingFactory";

        // now update data in the postgress Database 

        /*  for(int i=0;i<RowCount;i++)
           {
                try 
        {
                          
        Conn= DriverManager.getConnection(dbUrl, username, password);    
        Stmt = Conn.createStatement();
                  String Connection_String = "insert into Webdata (Id,Product,state,Submitted,Complaintid) values (' "+ Dataarray[i][0]+" ',' "+ Dataarray[i][1]+" ',' "+ Dataarray[i][2]+" ',' "+ Dataarray[i][3]+" ',' "+ Dataarray[i][4]+" ')";
         Stmt.executeUpdate(Connection_String);
                  Conn.close();
        }
        catch(SQLException E4)
                  {
           System.out.println(E4.getMessage());
        }
           }
           */
        // Quering with the Database 

        System.out.println("1. Display Data ");
        System.out.println("2. Select data based on primary key");
        System.out.println("3. Select data based on Other attributes e.g Name");
        System.out.println("Enter your Choice ");
        try {
            choice = objbuf.readLine();
        } catch (IOException E) {
            System.out.println(E.getMessage());
        }
        switch (choice) {
        case "1":
            try {
                Conn = DriverManager.getConnection(dbUrl, username, password);
                Stmt = Conn.createStatement();
                String Connection_String = " Select * from Webdata;";
                ResultSet objRS = Stmt.executeQuery(Connection_String);
                while (objRS.next()) {
                    System.out.println(" ID: " + objRS.getInt("ID"));
                    System.out.println("Product Name: " + objRS.getString("Product"));
                    System.out.println("Which state: " + objRS.getString("State"));
                    System.out.println("Sumbitted through: " + objRS.getString("Submitted"));
                    System.out.println("Complain Number: " + objRS.getString("Complaintid"));
                    Conn.close();
                }

            } catch (Exception E2) {
                System.out.println(E2.getMessage());
            }

            break;

        case "2":

            System.out.println("Enter Id(Primary Key) :");
            InputStreamReader objkey = new InputStreamReader(System.in);
            BufferedReader objbufkey = new BufferedReader(objkey);
            int key = 0;
            try {
                key = Integer.parseInt(objbufkey.readLine());
            } catch (IOException E) {
                System.out.println(E.getMessage());
            }
            try {
                Conn = DriverManager.getConnection(dbUrl, username, password);
                Stmt = Conn.createStatement();
                String Connection_String = " Select * from Webdata where Id=" + key + ";";
                ResultSet objRS = Stmt.executeQuery(Connection_String);
                while (objRS.next()) {
                    //System.out.println(" ID: " + objRS.getInt("ID"));
                    System.out.println("Product Name: " + objRS.getString("Product"));
                    System.out.println("Which state: " + objRS.getString("State"));
                    System.out.println("Sumbitted through: " + objRS.getString("Submitted"));
                    System.out.println("Complain Number: " + objRS.getString("Complaintid"));
                    Conn.close();
                }

            } catch (Exception E2) {
                System.out.println(E2.getMessage());
            }
            break;

        case "3":
            //String Name=null;
            System.out.println("Enter Complaintid to find the record");

            // Scanner input = new Scanner(System.in);
            //
            int Number = 0;
            try {
                InputStreamReader objname = new InputStreamReader(System.in);
                BufferedReader objbufname = new BufferedReader(objname);

                Number = Integer.parseInt(objbufname.readLine());
            } catch (Exception E10) {
                System.out.println(E10.getMessage());
            }
            //System.out.println(Name);
            try {
                Conn = DriverManager.getConnection(dbUrl, username, password);
                Stmt = Conn.createStatement();
                String Connection_String = " Select * from Webdata where complaintid=" + Number + ";";
                //2
                System.out.println(Connection_String);
                ResultSet objRS = Stmt.executeQuery(Connection_String);
                while (objRS.next()) {
                    int id = objRS.getInt("id");
                    System.out.println(" ID: " + id);
                    System.out.println("Product Name: " + objRS.getString("Product"));
                    String state = objRS.getString("state");
                    System.out.println("Which state: " + state);
                    String Submitted = objRS.getString("submitted");
                    System.out.println("Sumbitted through: " + Submitted);
                    String Complaintid = objRS.getString("complaintid");
                    System.out.println("Complain Number: " + Complaintid);

                }
                Conn.close();
            } catch (Exception E2) {
                System.out.println(E2.getMessage());
            }
            break;
        }
        try {
            Conn.close();
        } catch (SQLException E6) {
            System.out.println(E6.getMessage());
        }
        break;

    // Redis code goes here 

    case "2":
        int Length = 0;
        String ID = null;
        Length = 100;

        // Connection to Redis 
        Jedis jedis = new Jedis("pub-redis-13274.us-east-1-2.1.ec2.garantiadata.com", 13274);
        jedis.auth("rfJ8OLjlv9NjRfry");
        System.out.println("Connected to Redis Database");

        // Storing values in the database 

        /* 
        for(int i=0;i<Length;i++)
        { 
         //Store data in redis 
            int j=i+1;
        jedis.hset("Record:" + j , "Product", Dataarray[i][1]);
        jedis.hset("Record:" + j , "State ", Dataarray[i][2]);
        jedis.hset("Record:" + j , "Submitted", Dataarray[i][3]);
        jedis.hset("Record:" + j , "Complaintid", Dataarray[i][4]);
                
        }
        */
        System.out.println(
                "Search by \n 11.Get records through primary key \n 22.Get Records through Complaintid \n 33.Display ");
        InputStreamReader objkey = new InputStreamReader(System.in);
        BufferedReader objbufkey = new BufferedReader(objkey);
        String str2 = null;
        try {
            str2 = objbufkey.readLine();
        } catch (IOException E) {
            System.out.println(E.getMessage());
        }
        switch (str2) {
        case "11":
            System.out.print("Enter Primary Key : ");
            InputStreamReader IORKey = new InputStreamReader(System.in);
            BufferedReader BIORKey = new BufferedReader(IORKey);
            String ID1 = null;
            try {
                ID1 = BIORKey.readLine();
            } catch (IOException E3) {
                System.out.println(E3.getMessage());
            }

            Map<String, String> properties = jedis.hgetAll("Record:" + Integer.parseInt(ID1));
            for (Map.Entry<String, String> entry : properties.entrySet()) {
                System.out.println("Product:" + jedis.hget("Record:" + Integer.parseInt(ID1), "Product"));
                System.out.println("State:" + jedis.hget("Record:" + Integer.parseInt(ID1), "State"));
                System.out.println("Submitted:" + jedis.hget("Record:" + Integer.parseInt(ID1), "Submitted"));
                System.out
                        .println("Complaintid:" + jedis.hget("Record:" + Integer.parseInt(ID1), "Complaintid"));
            }
            break;

        case "22":
            System.out.print(" Enter Complaintid  : ");
            InputStreamReader IORName1 = new InputStreamReader(System.in);
            BufferedReader BIORName1 = new BufferedReader(IORName1);

            String ID2 = null;
            try {
                ID2 = BIORName1.readLine();
            } catch (IOException E3) {
                System.out.println(E3.getMessage());
            }
            for (int i = 0; i < 100; i++) {
                Map<String, String> properties3 = jedis.hgetAll("Record:" + i);
                for (Map.Entry<String, String> entry : properties3.entrySet()) {
                    String value = entry.getValue();
                    if (entry.getValue().equals(ID2)) {
                        System.out
                                .println("Product:" + jedis.hget("Record:" + Integer.parseInt(ID2), "Product"));
                        System.out.println("State:" + jedis.hget("Record:" + Integer.parseInt(ID2), "State"));
                        System.out.println(
                                "Submitted:" + jedis.hget("Record:" + Integer.parseInt(ID2), "Submitted"));
                        System.out.println(
                                "Complaintid:" + jedis.hget("Record:" + Integer.parseInt(ID2), "Complaintid"));
                    }

                }
            }

            break;

        case "33":
            for (int i = 1; i < 21; i++) {
                Map<String, String> properties3 = jedis.hgetAll("Record:" + i);
                for (Map.Entry<String, String> entry : properties3.entrySet()) {

                    System.out.println("Product:" + jedis.hget("Record:" + i, "Product"));
                    System.out.println("State:" + jedis.hget("Record:" + i, "State"));
                    System.out.println("Submitted:" + jedis.hget("Record:" + i, "Submitted"));
                    System.out.println("Complaintid:" + jedis.hget("Record:" + i, "Complaintid"));

                }
            }
            break;
        }

        break;

    // mongo db 

    case "3":
        MongoClient mongo = new MongoClient(new MongoClientURI(
                "mongodb://naikhpratik:naikhpratik@ds053964.mongolab.com:53964/heroku_6t7n587f"));
        DB db;
        db = mongo.getDB("heroku_6t7n587f");
        // storing values in the database 
        /*for(int i=0;i<100;i++)
         {
             BasicDBObject document = new BasicDBObject();
            document.put("Id", i+1);
            document.put("Product", Dataarray[i][1]);
            document.put("State", Dataarray[i][2]);    
            document.put("Submitted", Dataarray[i][3]);    
            document.put("Complaintid", Dataarray[i][4]); 
            db.getCollection("Naiknaik").insert(document);
                  
         }*/
        System.out.println("Search by \n 1.Enter Primary key \n 2.Enter Complaintid \n 3.Display");
        InputStreamReader objkey6 = new InputStreamReader(System.in);
        BufferedReader objbufkey6 = new BufferedReader(objkey6);
        String str3 = null;
        try {
            str3 = objbufkey6.readLine();
        } catch (IOException E) {
            System.out.println(E.getMessage());
        }
        switch (str3) {
        case "1":
            System.out.println("Enter the Primary Key");
            InputStreamReader IORPkey = new InputStreamReader(System.in);
            BufferedReader BIORPkey = new BufferedReader(IORPkey);
            int Pkey = 0;
            try {
                Pkey = Integer.parseInt(BIORPkey.readLine());
            } catch (IOException E) {
                System.out.println(E.getMessage());
            }
            BasicDBObject inQuery = new BasicDBObject();
            inQuery.put("Id", Pkey);
            DBCursor cursor = db.getCollection("Naiknaik").find(inQuery);
            while (cursor.hasNext()) {
                // System.out.println(cursor.next());
                System.out.println(cursor.next());
            }
            break;
        case "2":
            System.out.println("Enter the Product to Search");
            InputStreamReader objName = new InputStreamReader(System.in);
            BufferedReader objbufName = new BufferedReader(objName);
            String Name = null;
            try {
                Name = objbufName.readLine();
            } catch (IOException E) {
                System.out.println(E.getMessage());
            }
            BasicDBObject inQuery1 = new BasicDBObject();
            inQuery1.put("Product", Name);
            DBCursor cursor1 = db.getCollection("Naiknaik").find(inQuery1);
            while (cursor1.hasNext()) {
                // System.out.println(cursor.next());
                System.out.println(cursor1.next());
            }
            break;

        case "3":
            for (int i = 1; i < 21; i++) {
                BasicDBObject inQuerya = new BasicDBObject();
                inQuerya.put("_id", i);
                DBCursor cursora = db.getCollection("Naiknaik").find(inQuerya);
                while (cursora.hasNext()) {
                    // System.out.println(cursor.next());
                    System.out.println(cursora.next());
                }
            }
            break;
        }
        break;

    }

}

From source file:au.org.ala.layers.intersect.IntersectConfig.java

public static void main(String[] args) {
    StringBuilder sb = new StringBuilder();

    for (int i = 0; i < 100000; i++) {
        if (i > 0) {
            sb.append(',');
        }//from  w w w . ja v  a 2  s . c  o  m
        sb.append(Math.random() * (-12 + 44) - 44).append(',').append(Math.random() * (154 - 112) + 112);
    }
    try {
        FileUtils.writeStringToFile(new File("/data/p.txt"), sb.toString());
    } catch (IOException e) {
        logger.error(e.getMessage(), e);
    }
}

From source file:com.hortonworks.registries.storage.tool.shell.ShellMigrationInitializer.java

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

    options.addOption(Option.builder("s").numberOfArgs(1).longOpt(OPTION_SCRIPT_ROOT_PATH)
            .desc("Root directory of script path").build());

    options.addOption(Option.builder("c").numberOfArgs(1).longOpt(OPTION_CONFIG_FILE_PATH)
            .desc("Config file path").build());

    options.addOption(Option.builder().hasArg(false).longOpt(ShellMigrationOption.MIGRATE.toString())
            .desc("Execute schema migration from last check point").build());

    options.addOption(Option.builder().hasArg(false).longOpt(ShellMigrationOption.INFO.toString())
            .desc("Show the status of the schema migration compared to the target database").build());

    options.addOption(Option.builder().hasArg(false).longOpt(ShellMigrationOption.VALIDATE.toString())
            .desc("Validate the target database changes with the migration scripts").build());

    options.addOption(Option.builder().hasArg(false).longOpt(ShellMigrationOption.REPAIR.toString()).desc(
            "Repairs the SCRIPT_CHANGE_LOG by removing failed migrations and correcting checksum of existing migration script")
            .build());//from  w  ww  .j a v  a 2s.  c  o  m

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

    if (!commandLine.hasOption(OPTION_SCRIPT_ROOT_PATH)) {
        usage(options);
        System.exit(1);
    }

    boolean isShellMigrationOptionSpecified = false;
    ShellMigrationOption shellMigrationOptionSpecified = null;
    for (ShellMigrationOption shellMigrationOption : ShellMigrationOption.values()) {
        if (commandLine.hasOption(shellMigrationOption.toString())) {
            if (isShellMigrationOptionSpecified) {
                System.out.println(
                        "Only one operation can be execute at once, please select one of ',migrate', 'validate', 'info', 'repair'.");
                System.exit(1);
            }
            isShellMigrationOptionSpecified = true;
            shellMigrationOptionSpecified = shellMigrationOption;
        }
    }

    if (!isShellMigrationOptionSpecified) {
        System.out.println(
                "One of the option 'migrate', 'validate', 'info', 'repair' must be specified to execute.");
        System.exit(1);
    }

    String scriptRootPath = commandLine.getOptionValue(OPTION_SCRIPT_ROOT_PATH);
    String confFilePath = commandLine.getOptionValue(OPTION_CONFIG_FILE_PATH);

    StorageProviderConfiguration storageProperties;
    try {
        Map<String, Object> conf = Utils.readConfig(confFilePath);

        StorageProviderConfigurationReader confReader = new StorageProviderConfigurationReader();
        storageProperties = confReader.readStorageConfig(conf);
    } catch (IOException e) {
        System.err.println("Error occurred while reading config file: " + confFilePath);
        System.exit(1);
        throw new IllegalStateException("Shouldn't reach here");
    }

    ShellMigrationHelper schemaMigrationHelper = new ShellMigrationHelper(
            ShellFlywayFactory.get(storageProperties, scriptRootPath));
    try {
        schemaMigrationHelper.execute(shellMigrationOptionSpecified);
        System.out.println(String.format("\"%s\" option successful", shellMigrationOptionSpecified.toString()));
    } catch (Exception e) {
        System.err.println(String.format("\"%s\" option failed : %s", shellMigrationOptionSpecified.toString(),
                e.getMessage()));
        System.exit(1);
    }

}

From source file:edu.uthscsa.ric.papaya.builder.Builder.java

public static void main(final String[] args) {
    final Builder builder = new Builder();

    // process command line
    final CommandLine cli = builder.createCLI(args);
    builder.setUseSample(cli.hasOption(ARG_SAMPLE));
    builder.setUseAtlas(cli.hasOption(ARG_ATLAS));
    builder.setLocal(cli.hasOption(ARG_LOCAL));
    builder.setPrintHelp(cli.hasOption(ARG_HELP));
    builder.setUseImages(cli.hasOption(ARG_IMAGE));
    builder.setSingleFile(cli.hasOption(ARG_SINGLE));
    builder.setUseParamFile(cli.hasOption(ARG_PARAM_FILE));
    builder.setUseTitle(cli.hasOption(ARG_TITLE));

    // print help, if necessary
    if (builder.isPrintHelp()) {
        builder.printHelp();/* w w w .  jav  a 2  s  .  c  o m*/
        return;
    }

    // find project root directory
    if (cli.hasOption(ARG_ROOT)) {
        try {
            builder.projectDir = (new File(cli.getOptionValue(ARG_ROOT))).getCanonicalFile();
        } catch (final IOException ex) {
            System.err.println("Problem finding root directory.  Reason: " + ex.getMessage());
        }
    }

    if (builder.projectDir == null) {
        builder.projectDir = new File(System.getProperty("user.dir"));
    }

    // clean output dir
    final File outputDir = new File(builder.projectDir + "/" + OUTPUT_DIR);
    System.out.println("Cleaning output directory...");
    try {
        builder.cleanOutputDir(outputDir);
    } catch (final IOException ex) {
        System.err.println("Problem cleaning build directory.  Reason: " + ex.getMessage());
    }

    if (builder.isLocal()) {
        System.out.println("Building for local usage...");
    }

    // write JS
    final File compressedFileJs = new File(outputDir, OUTPUT_JS_FILENAME);

    // build properties
    try {
        final File buildFile = new File(builder.projectDir + "/" + BUILD_PROP_FILE);

        builder.readBuildProperties(buildFile);
        builder.buildNumber++; // increment build number
        builder.writeBuildProperties(compressedFileJs, true);
        builder.writeBuildProperties(buildFile, false);
    } catch (final IOException ex) {
        System.err.println("Problem handling build properties.  Reason: " + ex.getMessage());
    }

    String htmlParameters = null;

    if (builder.isUseParamFile()) {
        final String paramFileArg = cli.getOptionValue(ARG_PARAM_FILE);

        if (paramFileArg != null) {
            try {
                System.out.println("Including parameters...");

                final String parameters = FileUtils.readFileToString(new File(paramFileArg), "UTF-8");
                htmlParameters = "var params = " + parameters + ";";
            } catch (final IOException ex) {
                System.err.println("Problem reading parameters file! " + ex.getMessage());
            }
        }
    }

    String title = null;
    if (builder.isUseTitle()) {
        String str = cli.getOptionValue(ARG_TITLE);
        if (str != null) {
            str = str.trim();
            str = str.replace("\"", "");
            str = str.replace("'", "");

            if (str.length() > 0) {
                title = str;
                System.out.println("Using title: " + title);
            }
        }
    }

    try {
        final JSONArray loadableImages = new JSONArray();

        // sample image
        if (builder.isUseSample()) {
            System.out.println("Including sample image...");

            final File sampleFile = new File(builder.projectDir + "/" + SAMPLE_IMAGE_NII_FILE);
            final String filename = Utilities
                    .replaceNonAlphanumericCharacters(Utilities.removeNiftiExtensions(sampleFile.getName()));

            if (builder.isLocal()) {
                loadableImages.put(new JSONObject("{\"nicename\":\"Sample Image\",\"name\":\"" + filename
                        + "\",\"encode\":\"" + filename + "\"}"));
                final String sampleEncoded = Utilities.encodeImageFile(sampleFile);
                FileUtils.writeStringToFile(compressedFileJs,
                        "var " + filename + "= \"" + sampleEncoded + "\";\n", "UTF-8", true);
            } else {
                loadableImages.put(new JSONObject("{\"nicename\":\"Sample Image\",\"name\":\"" + filename
                        + "\",\"url\":\"" + SAMPLE_IMAGE_NII_FILE + "\"}"));
                FileUtils.copyFile(sampleFile, new File(outputDir + "/" + SAMPLE_IMAGE_NII_FILE));
            }
        }

        // atlas
        if (builder.isUseAtlas()) {
            Atlas atlas = null;

            try {
                String atlasArg = cli.getOptionValue(ARG_ATLAS);

                if (atlasArg == null) {
                    atlasArg = (builder.projectDir + "/" + SAMPLE_DEFAULT_ATLAS_FILE);
                }

                final File atlasXmlFile = new File(atlasArg);

                System.out.println("Including atlas " + atlasXmlFile);

                atlas = new Atlas(atlasXmlFile);
                final File atlasJavaScriptFile = atlas.createAtlas(builder.isLocal());
                System.out.println("Using atlas image file " + atlas.getImageFile());

                if (builder.isLocal()) {
                    loadableImages.put(
                            new JSONObject("{\"nicename\":\"Atlas\",\"name\":\"" + atlas.getImageFileNewName()
                                    + "\",\"encode\":\"" + atlas.getImageFileNewName() + "\",\"hide\":true}"));
                } else {
                    final File atlasImageFile = atlas.getImageFile();
                    final String atlasPath = "data/" + atlasImageFile.getName();

                    loadableImages.put(new JSONObject("{\"nicename\":\"Atlas\",\"name\":\""
                            + atlas.getImageFileNewName() + "\",\"url\":\"" + atlasPath + "\",\"hide\":true}"));
                    FileUtils.copyFile(atlasImageFile, new File(outputDir + "/" + atlasPath));
                }

                builder.writeFile(atlasJavaScriptFile, compressedFileJs);
            } catch (final IOException ex) {
                System.err.println("Problem finding atlas file.  Reason: " + ex.getMessage());
            }
        }

        // additional images
        if (builder.isUseImages()) {
            final String[] imageArgs = cli.getOptionValues(ARG_IMAGE);

            if (imageArgs != null) {
                for (final String imageArg : imageArgs) {
                    final File file = new File(imageArg);
                    System.out.println("Including image " + file);

                    final String filename = Utilities
                            .replaceNonAlphanumericCharacters(Utilities.removeNiftiExtensions(file.getName()));

                    if (builder.isLocal()) {
                        loadableImages.put(new JSONObject(
                                "{\"nicename\":\"" + Utilities.removeNiftiExtensions(file.getName())
                                        + "\",\"name\":\"" + filename + "\",\"encode\":\"" + filename + "\"}"));
                        final String sampleEncoded = Utilities.encodeImageFile(file);
                        FileUtils.writeStringToFile(compressedFileJs,
                                "var " + filename + "= \"" + sampleEncoded + "\";\n", "UTF-8", true);
                    } else {
                        final String filePath = "data/" + file.getName();
                        loadableImages.put(new JSONObject(
                                "{\"nicename\":\"" + Utilities.removeNiftiExtensions(file.getName())
                                        + "\",\"name\":\"" + filename + "\",\"url\":\"" + filePath + "\"}"));
                        FileUtils.copyFile(file, new File(outputDir + "/" + filePath));
                    }
                }
            }
        }

        File tempFileJs = null;

        try {
            tempFileJs = builder.createTempFile();
        } catch (final IOException ex) {
            System.err.println("Problem creating temp write file.  Reason: " + ex.getMessage());
        }

        // write image refs
        FileUtils.writeStringToFile(tempFileJs,
                "var " + PAPAYA_LOADABLE_IMAGES + " = " + loadableImages.toString() + ";\n", "UTF-8", true);

        // compress JS
        tempFileJs = builder.concatenateFiles(JS_FILES, "js", tempFileJs);

        System.out.println("Compressing JavaScript... ");
        FileUtils.writeStringToFile(compressedFileJs, "\n", "UTF-8", true);
        builder.compressJavaScript(tempFileJs, compressedFileJs, new YuiCompressorOptions());
        //tempFileJs.deleteOnExit();
    } catch (final IOException ex) {
        System.err.println("Problem concatenating JavaScript.  Reason: " + ex.getMessage());
    }

    // compress CSS
    final File compressedFileCss = new File(outputDir, OUTPUT_CSS_FILENAME);

    try {
        final File concatFile = builder.concatenateFiles(CSS_FILES, "css", null);
        System.out.println("Compressing CSS... ");
        builder.compressCSS(concatFile, compressedFileCss, new YuiCompressorOptions());
        concatFile.deleteOnExit();
    } catch (final IOException ex) {
        System.err.println("Problem concatenating CSS.  Reason: " + ex.getMessage());
    }

    // write HTML
    try {
        System.out.println("Writing HTML... ");
        if (builder.singleFile) {
            builder.writeHtml(outputDir, compressedFileJs, compressedFileCss, htmlParameters, title);
        } else {
            builder.writeHtml(outputDir, htmlParameters, title);
        }
    } catch (final IOException ex) {
        System.err.println("Problem writing HTML.  Reason: " + ex.getMessage());
    }

    System.out.println("Done!  Output files located at " + outputDir);
}

From source file:gov.nih.nci.ncicb.tcga.dcc.QCLiveTestDataGenerator.java

/**
 * Main entry point for the application. Configures the Spring context and calls the {@link QCLiveTestDataGenerator}
 * bean to load and generate test data for a specific archive name.
 * //from w ww.j av a  2 s  . com
 * @param args - list of arguments to be passed to the {@link QCLiveTestDataGenerator} bean
 */
public static void main(final String[] args) {

    // Display help if no arguments are provided, otherwise parse the arguments
    if (args.length == 0)
        displayHelp();
    else {
        try {
            // Parse the command line arguments 
            final CommandLine commandLine = new GnuParser().parse(CommandLineOptionType.getOptions(), args);

            // If the command line instance contains the -? (--help) option display help, otherwise call the QCLiveTestDataGenerator
            // to process the command line arguments
            if (commandLine.hasOption(CommandLineOptionType.HELP.name().toLowerCase())) {
                displayHelp();
            } else {
                final String archiveNameOption = CommandLineOptionType.ARCHIVE_NAME.getOptionValue().getOpt();
                final String sqlScriptFileOption = CommandLineOptionType.SQL_SCRIPT_FILE.getOptionValue()
                        .getOpt();
                final String schemaOption = CommandLineOptionType.SCHEMA.getOptionValue().getOpt();

                // Initialize the Spring context
                final ApplicationContext appCtx = new ClassPathXmlApplicationContext(APP_CONTEXT_FILE_NAME);

                // Retrieve the QCLiveTestDataGenerator from the Spring context
                final QCLiveTestDataGenerator qcLiveTestDataGenerator = (QCLiveTestDataGenerator) appCtx
                        .getBean("qcLiveTestDataGenerator");

                // Get the archive name from the command line argument(s) (if provided) and generate the test data
                if (commandLine.hasOption(archiveNameOption)) {
                    qcLiveTestDataGenerator.generateTestData(commandLine.getOptionValue(archiveNameOption));
                }

                // If the SQL script file and schema options are provided, execute the script
                if (commandLine.hasOption(sqlScriptFileOption)) {
                    if (commandLine.hasOption(schemaOption)) {
                        // Try to resolve the schema type from the provided schema name. If it cannot be resolved, throw an exception that
                        // indicates the supported schema types
                        final String schemaOptionValue = commandLine.getOptionValue(schemaOption);
                        SchemaType schemaTpye = null;
                        try {
                            schemaTpye = SchemaType.valueOf(schemaOptionValue.toUpperCase());
                        } catch (IllegalArgumentException iae) {
                            throw new ParseException("Could not resolve schema name '" + schemaOptionValue
                                    + "' to a supported schema type "
                                    + "when attempting to execute SQL script file '"
                                    + commandLine.getOptionValue(sqlScriptFileOption) + "'. "
                                    + "Supported types are '" + SchemaType.getSupportedSchemaTypes() + "'");
                        }

                        qcLiveTestDataGenerator.executeSQLScriptFile(schemaTpye,
                                new FileSystemResource(commandLine.getOptionValue(sqlScriptFileOption)));
                    } else
                        throw new ParseException(
                                "Setting the -f (or -sql_script_file) option also requires the -s (or -schema) to be set.");
                }
            }
        } catch (ParseException pe) {
            System.err.println("\nParsing failed. Reason: " + pe.getMessage());
            displayHelp();
        } catch (IOException ioe) {
            logger.error(ioe.getMessage());
        } catch (SQLException sqle) {
            logger.error(sqle.getMessage());
        }
    }
}

From source file:HelloSmartsheet.java

public static void main(String[] args) {
    HttpURLConnection connection = null;
    StringBuilder response = new StringBuilder();

    //We are using Jackson JSON parser to deserialize the JSON. See http://wiki.fasterxml.com/JacksonHome
    //Feel free to use which ever library you prefer.
    ObjectMapper mapper = new ObjectMapper();
    mapper.configure(DeserializationFeature.FAIL_ON_UNKNOWN_PROPERTIES, false);

    try {//  w w  w .  j a v  a 2s  .  co m

        System.out.println("STARTING HelloSmartsheet...");
        //Create a BufferedReader to read user input.
        BufferedReader in = new BufferedReader(new InputStreamReader(System.in));

        System.out.print("Enter Smartsheet API access token:");
        String accessToken = in.readLine();
        System.out.println("Fetching list of your sheets...");
        //Create a connection and fetch the list of sheets
        connection = (HttpURLConnection) new URL(GET_SHEETS_URL).openConnection();
        connection.addRequestProperty("Authorization", "Bearer " + accessToken);
        BufferedReader reader = new BufferedReader(new InputStreamReader(connection.getInputStream()));
        String line;
        //Read the response line by line.
        while ((line = reader.readLine()) != null) {
            response.append(line);
        }
        reader.close();
        //Use Jackson to conver the JSON string to a List of Sheets
        List<Sheet> sheets = mapper.readValue(response.toString(), new TypeReference<List<Sheet>>() {
        });
        if (sheets.size() == 0) {
            System.out.println("You don't have any sheets.  Goodbye!");
            return;
        }
        System.out.println("Total sheets: " + sheets.size());
        int i = 1;
        for (Sheet sheet : sheets) {
            System.out.println(i++ + ": " + sheet.name);
        }
        System.out.print("Enter the number of the sheet you want to share: ");

        //Prompt the user to provide the sheet number, the email address, and the access level
        Integer sheetNumber = Integer.parseInt(in.readLine().trim()); //NOTE: for simplicity, error handling and input validation is neglected.
        Sheet chosenSheet = sheets.get(sheetNumber - 1);

        System.out.print("Enter an email address to share " + chosenSheet.getName() + " to: ");
        String email = in.readLine();

        System.out.print("Choose an access level (VIEWER, EDITOR, EDITOR_SHARE, ADMIN) for " + email + ": ");
        String accessLevel = in.readLine();

        //Create a share object
        Share share = new Share();
        share.setEmail(email);
        share.setAccessLevel(accessLevel);

        System.out.println("Sharing " + chosenSheet.name + " to " + email + " as " + accessLevel + ".");

        //Create a connection. Note the SHARE_SHEET_URL uses /sheet as opposed to /sheets (with an 's')
        connection = (HttpURLConnection) new URL(SHARE_SHEET_URL.replace(SHEET_ID, "" + chosenSheet.getId()))
                .openConnection();
        connection.setDoOutput(true);
        connection.addRequestProperty("Authorization", "Bearer " + accessToken);
        connection.addRequestProperty("Content-Type", "application/json");

        OutputStreamWriter writer = new OutputStreamWriter(connection.getOutputStream());
        //Serialize the Share object
        writer.write(mapper.writeValueAsString(share));
        writer.close();

        //Read the response and parse the JSON
        reader = new BufferedReader(new InputStreamReader(connection.getInputStream()));
        response = new StringBuilder();
        while ((line = reader.readLine()) != null) {
            response.append(line);
        }

        Result result = mapper.readValue(response.toString(), Result.class);
        System.out.println("Sheet shared successfully, share ID " + result.result.id);
        System.out.println("Press any key to quit.");
        in.read();

    } catch (IOException e) {
        BufferedReader reader = new BufferedReader(
                new InputStreamReader(((HttpURLConnection) connection).getErrorStream()));
        String line;
        try {
            response = new StringBuilder();
            while ((line = reader.readLine()) != null) {
                response.append(line);
            }
            reader.close();
            Result result = mapper.readValue(response.toString(), Result.class);
            System.out.println(result.message);
        } catch (IOException e1) {
            e1.printStackTrace();
        }

    } catch (Exception e) {
        System.out.println("Something broke: " + e.getMessage());
        e.printStackTrace();
    }

}

From source file:boa.evaluator.BoaEvaluator.java

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

    options.addOption("i", "input", true, "input Boa source file (*.boa)");
    options.addOption("d", "data", true, "path to local data directory");
    options.addOption("o", "output", true, "output directory");

    options.getOption("i").setRequired(true);
    options.getOption("d").setRequired(true);

    try {/*from   w ww  . ja v a 2 s.c om*/
        if (args.length == 0) {
            printHelp(options, null);
            return;
        } else {
            final CommandLine cl = new PosixParser().parse(options, args);

            if (cl.hasOption('i') && cl.hasOption('d')) {
                final BoaEvaluator evaluator;
                try {
                    if (cl.hasOption('o')) {
                        evaluator = new BoaEvaluator(cl.getOptionValue('i'), cl.getOptionValue('d'),
                                cl.getOptionValue('o'));
                    } else {
                        evaluator = new BoaEvaluator(cl.getOptionValue('i'), cl.getOptionValue('d'));
                    }
                } catch (final IOException e) {
                    System.err.print(e);
                    return;
                }

                if (!evaluator.compile()) {
                    System.err.println("Compilation Failed");
                    return;
                }

                final long start = System.currentTimeMillis();
                evaluator.evaluate();
                final long end = System.currentTimeMillis();

                System.out.println("Total Time Taken: " + (end - start));
                System.out.println(evaluator.getResults());
            } else {
                printHelp(options, "missing required options: -i <arg> and -d <arg>");
                return;
            }
        }
    } catch (final org.apache.commons.cli.ParseException e) {
        printHelp(options, e.getMessage());
    }
}