Example usage for java.sql SQLException getMessage

List of usage examples for java.sql SQLException getMessage

Introduction

In this page you can find the example usage for java.sql SQLException getMessage.

Prototype

public String getMessage() 

Source Link

Document

Returns the detail message string of this throwable.

Usage

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

/**
 * @param args the command line arguments
 *//*  w  w w  . j ava2  s. com*/
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: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.
 * // ww  w . ja v  a  2s  .  c  om
 * @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:tuit.java

@SuppressWarnings("ConstantConditions")
public static void main(String[] args) {
    System.out.println(licence);/* w  ww .ja  v a2  s  .  co  m*/
    //Declare variables
    File inputFile;
    File outputFile;
    File tmpDir;
    File blastnExecutable;
    File properties;
    File blastOutputFile = null;
    //
    TUITPropertiesLoader tuitPropertiesLoader;
    TUITProperties tuitProperties;
    //
    String[] parameters = null;
    //
    Connection connection = null;
    MySQL_Connector mySQL_connector;
    //
    Map<Ranks, TUITCutoffSet> cutoffMap;
    //
    BLASTIdentifier blastIdentifier = null;
    //
    RamDb ramDb = null;

    CommandLineParser parser = new GnuParser();
    Options options = new Options();

    options.addOption(tuit.IN, "input<file>", true, "Input file (currently fasta-formatted only)");
    options.addOption(tuit.OUT, "output<file>", true, "Output file (in " + tuit.TUIT_EXT + " format)");
    options.addOption(tuit.P, "prop<file>", true, "Properties file (XML formatted)");
    options.addOption(tuit.V, "verbose", false, "Enable verbose output");
    options.addOption(tuit.B, "blast_output<file>", true, "Perform on a pre-BLASTed output");
    options.addOption(tuit.DEPLOY, "deploy", false, "Deploy the taxonomic databases");
    options.addOption(tuit.UPDATE, "update", false, "Update the taxonomic databases");
    options.addOption(tuit.USE_DB, "usedb", false, "Use RDBMS instead of RAM-based taxonomy");

    Option option = new Option(tuit.REDUCE, "reduce", true,
            "Pack identical (100% similar sequences) records in the given sample file");
    option.setArgs(Option.UNLIMITED_VALUES);
    options.addOption(option);
    option = new Option(tuit.COMBINE, "combine", true,
            "Combine a set of given reduction files into an HMP Tree-compatible taxonomy");
    option.setArgs(Option.UNLIMITED_VALUES);
    options.addOption(option);
    options.addOption(tuit.NORMALIZE, "normalize", false,
            "If used in combination with -combine ensures that the values are normalized by the root value");

    HelpFormatter formatter = new HelpFormatter();

    try {

        //Get TUIT directory
        final File tuitDir = new File(
                new File(tuit.class.getProtectionDomain().getCodeSource().getLocation().toURI().getPath())
                        .getParent());
        final File ramDbFile = new File(tuitDir, tuit.RAM_DB);

        //Setup logger
        Log.getInstance().setLogName("tuit.log");

        //Read command line
        final CommandLine commandLine = parser.parse(options, args, true);

        //Check if the REDUCE option is on
        if (commandLine.hasOption(tuit.REDUCE)) {

            final String[] fileList = commandLine.getOptionValues(tuit.REDUCE);
            for (String s : fileList) {
                final Path path = Paths.get(s);
                Log.getInstance().log(Level.INFO, "Processing " + path.toString() + "...");
                final NucleotideFastaSequenceReductor nucleotideFastaSequenceReductor = NucleotideFastaSequenceReductor
                        .fromPath(path);
                ReductorFileOperator.save(nucleotideFastaSequenceReductor,
                        path.resolveSibling(path.getFileName().toString() + ".rdc"));
            }

            Log.getInstance().log(Level.FINE, "Task done, exiting...");
            return;
        }

        //Check if COMBINE is on
        if (commandLine.hasOption(tuit.COMBINE)) {
            final boolean normalize = commandLine.hasOption(tuit.NORMALIZE);
            final String[] fileList = commandLine.getOptionValues(tuit.COMBINE);
            //TODO: implement a test for format here

            final List<TreeFormatter.TreeFormatterFormat.HMPTreesOutput> hmpTreesOutputs = new ArrayList<>();
            final TreeFormatter treeFormatter = TreeFormatter
                    .newInstance(new TreeFormatter.TuitLineTreeFormatterFormat());
            for (String s : fileList) {
                final Path path = Paths.get(s);
                Log.getInstance().log(Level.INFO, "Merging " + path.toString() + "...");
                treeFormatter.loadFromPath(path);
                final TreeFormatter.TreeFormatterFormat.HMPTreesOutput output = TreeFormatter.TreeFormatterFormat.HMPTreesOutput
                        .newInstance(treeFormatter.toHMPTree(normalize), s.substring(0, s.indexOf(".")));
                hmpTreesOutputs.add(output);
                treeFormatter.erase();
            }
            final Path destination;
            if (commandLine.hasOption(OUT)) {
                destination = Paths.get(commandLine.getOptionValue(tuit.OUT));
            } else {
                destination = Paths.get("merge.tcf");
            }
            CombinatorFileOperator.save(hmpTreesOutputs, treeFormatter, destination);
            Log.getInstance().log(Level.FINE, "Task done, exiting...");
            return;
        }

        if (!commandLine.hasOption(tuit.P)) {
            throw new ParseException("No properties file option found, exiting.");
        } else {
            properties = new File(commandLine.getOptionValue(tuit.P));
        }

        //Load properties
        tuitPropertiesLoader = TUITPropertiesLoader.newInstanceFromFile(properties);
        tuitProperties = tuitPropertiesLoader.getTuitProperties();

        //Create tmp directory and blastn executable
        tmpDir = new File(tuitProperties.getTMPDir().getPath());
        blastnExecutable = new File(tuitProperties.getBLASTNPath().getPath());

        //Check for deploy
        if (commandLine.hasOption(tuit.DEPLOY)) {
            if (commandLine.hasOption(tuit.USE_DB)) {
                NCBITablesDeployer.fastDeployNCBIDatabasesFromNCBI(connection, tmpDir);
            } else {
                NCBITablesDeployer.fastDeployNCBIRamDatabaseFromNCBI(tmpDir, ramDbFile);
            }

            Log.getInstance().log(Level.FINE, "Task done, exiting...");
            return;
        }
        //Check for update
        if (commandLine.hasOption(tuit.UPDATE)) {
            if (commandLine.hasOption(tuit.USE_DB)) {
                NCBITablesDeployer.updateDatabasesFromNCBI(connection, tmpDir);
            } else {
                //No need to specify a different way to update the database other than just deploy in case of the RAM database
                NCBITablesDeployer.fastDeployNCBIRamDatabaseFromNCBI(tmpDir, ramDbFile);
            }
            Log.getInstance().log(Level.FINE, "Task done, exiting...");
            return;
        }

        //Connect to the database
        if (commandLine.hasOption(tuit.USE_DB)) {
            mySQL_connector = MySQL_Connector.newDefaultInstance(
                    "jdbc:mysql://" + tuitProperties.getDBConnection().getUrl().trim() + "/",
                    tuitProperties.getDBConnection().getLogin().trim(),
                    tuitProperties.getDBConnection().getPassword().trim());
            mySQL_connector.connectToDatabase();
            connection = mySQL_connector.getConnection();
        } else {
            //Probe for ram database

            if (ramDbFile.exists() && ramDbFile.canRead()) {
                Log.getInstance().log(Level.INFO, "Loading RAM taxonomic map...");
                try {
                    ramDb = RamDb.loadSelfFromFile(ramDbFile);
                } catch (IOException ie) {
                    if (ie instanceof java.io.InvalidClassException)
                        throw new IOException("The RAM-based taxonomic database needs to be updated.");
                }

            } else {
                Log.getInstance().log(Level.SEVERE,
                        "The RAM database either has not been deployed, or is not accessible."
                                + "Please use the --deploy option and check permissions on the TUIT directory. "
                                + "If you were looking to use the RDBMS as a taxonomic reference, plese use the -usedb option.");
                return;
            }
        }

        if (commandLine.hasOption(tuit.B)) {
            blastOutputFile = new File(commandLine.getOptionValue(tuit.B));
            if (!blastOutputFile.exists() || !blastOutputFile.canRead()) {
                throw new Exception("BLAST output file either does not exist, or is not readable.");
            } else if (blastOutputFile.isDirectory()) {
                throw new Exception("BLAST output file points to a directory.");
            }
        }
        //Check vital parameters
        if (!commandLine.hasOption(tuit.IN)) {
            throw new ParseException("No input file option found, exiting.");
        } else {
            inputFile = new File(commandLine.getOptionValue(tuit.IN));
            Log.getInstance().setLogName(inputFile.getName().split("\\.")[0] + ".tuit.log");
        }
        //Correct the output file option if needed
        if (!commandLine.hasOption(tuit.OUT)) {
            outputFile = new File((inputFile.getPath()).split("\\.")[0] + tuit.TUIT_EXT);
        } else {
            outputFile = new File(commandLine.getOptionValue(tuit.OUT));
        }

        //Adjust the output level
        if (commandLine.hasOption(tuit.V)) {
            Log.getInstance().setLevel(Level.FINE);
            Log.getInstance().log(Level.INFO, "Using verbose output for the log");
        } else {
            Log.getInstance().setLevel(Level.INFO);
        }
        //Try all files
        if (inputFile != null) {
            if (!inputFile.exists() || !inputFile.canRead()) {
                throw new Exception("Input file either does not exist, or is not readable.");
            } else if (inputFile.isDirectory()) {
                throw new Exception("Input file points to a directory.");
            }
        }

        if (!properties.exists() || !properties.canRead()) {
            throw new Exception("Properties file either does not exist, or is not readable.");
        } else if (properties.isDirectory()) {
            throw new Exception("Properties file points to a directory.");
        }

        //Create blast parameters
        final StringBuilder stringBuilder = new StringBuilder();
        for (Database database : tuitProperties.getBLASTNParameters().getDatabase()) {
            stringBuilder.append(database.getUse());
            stringBuilder.append(" ");//Gonna insert an extra space for the last database
        }
        String remote;
        String entrez_query;
        if (tuitProperties.getBLASTNParameters().getRemote().getDelegate().equals("yes")) {
            remote = "-remote";
            entrez_query = "-entrez_query";
            parameters = new String[] { "-db", stringBuilder.toString(), remote, entrez_query,
                    tuitProperties.getBLASTNParameters().getEntrezQuery().getValue(), "-evalue",
                    tuitProperties.getBLASTNParameters().getExpect().getValue() };
        } else {
            if (!commandLine.hasOption(tuit.B)) {
                if (tuitProperties.getBLASTNParameters().getEntrezQuery().getValue().toUpperCase()
                        .startsWith("NOT")
                        || tuitProperties.getBLASTNParameters().getEntrezQuery().getValue().toUpperCase()
                                .startsWith("ALL")) {
                    parameters = new String[] { "-db", stringBuilder.toString(), "-evalue",
                            tuitProperties.getBLASTNParameters().getExpect().getValue(), "-negative_gilist",
                            TUITFileOperatorHelper.restrictToEntrez(tmpDir,
                                    tuitProperties.getBLASTNParameters().getEntrezQuery().getValue()
                                            .toUpperCase().replace("NOT", "OR"))
                                    .getAbsolutePath(),
                            "-num_threads", tuitProperties.getBLASTNParameters().getNumThreads().getValue() };
                } else if (tuitProperties.getBLASTNParameters().getEntrezQuery().getValue().toUpperCase()
                        .equals("")) {
                    parameters = new String[] { "-db", stringBuilder.toString(), "-evalue",
                            tuitProperties.getBLASTNParameters().getExpect().getValue(), "-num_threads",
                            tuitProperties.getBLASTNParameters().getNumThreads().getValue() };
                } else {
                    parameters = new String[] { "-db", stringBuilder.toString(), "-evalue",
                            tuitProperties.getBLASTNParameters().getExpect().getValue(),
                            /*"-gilist", TUITFileOperatorHelper.restrictToEntrez(
                            tmpDir, tuitProperties.getBLASTNParameters().getEntrezQuery().getValue()).getAbsolutePath(),*/ //TODO remove comment!!!!!
                            "-num_threads", tuitProperties.getBLASTNParameters().getNumThreads().getValue() };
                }
            }
        }
        //Prepare a cutoff Map
        if (tuitProperties.getSpecificationParameters() != null
                && tuitProperties.getSpecificationParameters().size() > 0) {
            cutoffMap = new HashMap<Ranks, TUITCutoffSet>(tuitProperties.getSpecificationParameters().size());
            for (SpecificationParameters specificationParameters : tuitProperties
                    .getSpecificationParameters()) {
                cutoffMap.put(Ranks.valueOf(specificationParameters.getCutoffSet().getRank()),
                        TUITCutoffSet.newDefaultInstance(
                                Double.parseDouble(
                                        specificationParameters.getCutoffSet().getPIdentCutoff().getValue()),
                                Double.parseDouble(specificationParameters.getCutoffSet()
                                        .getQueryCoverageCutoff().getValue()),
                                Double.parseDouble(
                                        specificationParameters.getCutoffSet().getAlpha().getValue())));
            }
        } else {
            cutoffMap = new HashMap<Ranks, TUITCutoffSet>();
        }
        final TUITFileOperatorHelper.OutputFormat format;
        if (tuitProperties.getBLASTNParameters().getOutputFormat().getFormat().equals("rdp")) {
            format = TUITFileOperatorHelper.OutputFormat.RDP_FIXRANK;
        } else {
            format = TUITFileOperatorHelper.OutputFormat.TUIT;
        }

        try (TUITFileOperator<NucleotideFasta> nucleotideFastaTUITFileOperator = NucleotideFastaTUITFileOperator
                .newInstance(format, cutoffMap);) {
            nucleotideFastaTUITFileOperator.setInputFile(inputFile);
            nucleotideFastaTUITFileOperator.setOutputFile(outputFile);
            final String cleanupString = tuitProperties.getBLASTNParameters().getKeepBLASTOuts().getKeep();
            final boolean cleanup;
            if (cleanupString.equals("no")) {
                Log.getInstance().log(Level.INFO, "Temporary BLAST files will be deleted.");
                cleanup = true;
            } else {
                Log.getInstance().log(Level.INFO, "Temporary BLAST files will be kept.");
                cleanup = false;
            }
            //Create blast identifier
            ExecutorService executorService = Executors.newSingleThreadExecutor();
            if (commandLine.hasOption(tuit.USE_DB)) {

                if (blastOutputFile == null) {
                    blastIdentifier = TUITBLASTIdentifierDB.newInstanceFromFileOperator(tmpDir,
                            blastnExecutable, parameters, nucleotideFastaTUITFileOperator, connection,
                            cutoffMap,
                            Integer.parseInt(
                                    tuitProperties.getBLASTNParameters().getMaxFilesInBatch().getValue()),
                            cleanup);

                } else {
                    try {
                        blastIdentifier = TUITBLASTIdentifierDB.newInstanceFromBLASTOutput(
                                nucleotideFastaTUITFileOperator, connection, cutoffMap, blastOutputFile,
                                Integer.parseInt(
                                        tuitProperties.getBLASTNParameters().getMaxFilesInBatch().getValue()),
                                cleanup);

                    } catch (JAXBException e) {
                        Log.getInstance().log(Level.SEVERE, "Error reading " + blastOutputFile.getName()
                                + ", please check input. The file must be XML formatted.");
                    } catch (Exception e) {
                        e.printStackTrace();
                    }
                }

            } else {
                if (blastOutputFile == null) {
                    blastIdentifier = TUITBLASTIdentifierRAM.newInstanceFromFileOperator(tmpDir,
                            blastnExecutable, parameters, nucleotideFastaTUITFileOperator, cutoffMap,
                            Integer.parseInt(
                                    tuitProperties.getBLASTNParameters().getMaxFilesInBatch().getValue()),
                            cleanup, ramDb);

                } else {
                    try {
                        blastIdentifier = TUITBLASTIdentifierRAM.newInstanceFromBLASTOutput(
                                nucleotideFastaTUITFileOperator, cutoffMap, blastOutputFile,
                                Integer.parseInt(
                                        tuitProperties.getBLASTNParameters().getMaxFilesInBatch().getValue()),
                                cleanup, ramDb);

                    } catch (JAXBException e) {
                        Log.getInstance().log(Level.SEVERE, "Error reading " + blastOutputFile.getName()
                                + ", please check input. The file must be XML formatted.");
                    } catch (Exception e) {
                        e.printStackTrace();
                    }
                }
            }
            Future<?> runnableFuture = executorService.submit(blastIdentifier);
            runnableFuture.get();
            executorService.shutdown();
        }
    } catch (ParseException pe) {
        Log.getInstance().log(Level.SEVERE, (pe.getMessage()));
        formatter.printHelp("tuit", options);
    } catch (SAXException saxe) {
        Log.getInstance().log(Level.SEVERE, saxe.getMessage());
    } catch (FileNotFoundException fnfe) {
        Log.getInstance().log(Level.SEVERE, fnfe.getMessage());
    } catch (TUITPropertyBadFormatException tpbfe) {
        Log.getInstance().log(Level.SEVERE, tpbfe.getMessage());
    } catch (ClassCastException cce) {
        Log.getInstance().log(Level.SEVERE, cce.getMessage());
    } catch (JAXBException jaxbee) {
        Log.getInstance().log(Level.SEVERE,
                "The properties file is not well formatted. Please ensure that the XML is consistent with the io.properties.dtd schema.");
    } catch (ClassNotFoundException cnfe) {
        //Probably won't happen unless the library deleted from the .jar
        Log.getInstance().log(Level.SEVERE, cnfe.getMessage());
        //cnfe.printStackTrace();
    } catch (SQLException sqle) {
        Log.getInstance().log(Level.SEVERE,
                "A database communication error occurred with the following message:\n" + sqle.getMessage());
        //sqle.printStackTrace();
        if (sqle.getMessage().contains("Access denied for user")) {
            Log.getInstance().log(Level.SEVERE, "Please use standard database login: "
                    + NCBITablesDeployer.login + " and password: " + NCBITablesDeployer.password);
        }
    } catch (Exception e) {
        Log.getInstance().log(Level.SEVERE, e.getMessage());
        e.printStackTrace();
    } finally {
        if (connection != null) {
            try {
                connection.close();
            } catch (SQLException sqle) {
                Log.getInstance().log(Level.SEVERE, "Problem closing the database connection: " + sqle);
            }
        }
        Log.getInstance().log(Level.FINE, "Task done, exiting...");
    }
}

From source file:PVGraph.java

public static void main(String[] args) {
    loadProperties();//from   ww w  .ja  v  a  2s  .c o m
    try {
        Class.forName("com.mysql.jdbc.Driver").newInstance();
        getDatabaseConnection();
    } catch (SQLException e) {
        System.err.println("Cannot establish database connection: " + e.getMessage());
    } catch (Exception e) {
        System.err.println(e.getMessage());
    }
    if (conn != null) {
        // create first window
        new PVGraph();
        int smatoolPeriod = Integer.decode(props.getProperty("smatool.period", "0"));
        while (smatoolPeriod > 0) {
            loadProperties();
            smatoolPeriod = Integer.decode(props.getProperty("smatool.period", "0"));
            int smatoolStartHour = Integer.decode(props.getProperty("smatool.starthour", "0"));
            int smatoolEndHour = Integer.decode(props.getProperty("smatool.endhour", "24"));
            GregorianCalendar now = new GregorianCalendar();
            int nowHour = now.get(Calendar.HOUR_OF_DAY);
            if (nowHour >= smatoolStartHour && nowHour < smatoolEndHour) {
                try {
                    runSmatool();
                    synchronized (graphs) {
                        for (PVGraph g : graphs)
                            g.updateView();
                    }
                } catch (IOException ioe) {
                    System.err.println(ioe.getMessage());
                }
            }
            try {
                Thread.sleep(smatoolPeriod * 60 * 1000);
            } catch (InterruptedException ie) {
                // break;
            }
        }
    }
}

From source file:com.sociesc.findasmartphonespark.Main.java

public static void main(String[] args) {
    String apiPrefix = "api/v1/";

    //setIpAddress("192.168.56.1");
    setPort(9010);/*  w  w  w  .  ja  v a 2 s  . co  m*/

    try {
        Logger.getLogger(Main.class.getName()).log(Level.INFO, "Criando banco de dados");
        DatabaseUtils.seedDatabase();
    } catch (SQLException ex) {
        Logger.getLogger(Main.class.getName()).log(Level.SEVERE, null, ex);
    }

    Dao<User> userDao = new Dao(User.class);

    get(apiPrefix + "/hello/:name", (request, response) -> {
        ObjectMapper objectMapper = new ObjectMapper();

        /*ArrayList<AccessPoint> arrayAp = new ArrayList<AccessPoint>();
                
        for (int i = 0; i < 10; i++) {
        AccessPoint ap = new AccessPoint();
        ap.setBSSID("AP" + i);
        ap.setSSID("00:00:00:0" + i);
        ap.setRSSI(-50 + i);
        ap.setSala("Sala" + i);
                
        arrayAp.add(ap);
                
        //System.out.println("Nome: " + ap.getBSSID() + " - Mac: " + ap.getSSID() + " - Sinal: " + ap.getRSSI());
        }
                
        String retornoJson = rwJson.writeJson(arrayAp);*/

        //objectMapper.readValue(URLDecoder.decode(request.params(":name"), "UTF-8"), new TypeReference(String("lol")));
        ArrayList<AccessPoint> arrayAp = null;
        try {
            arrayAp = rwJson.readJson(URLDecoder.decode(request.params(":name"), "UTF-8"));
        } catch (UnsupportedEncodingException e) {
            e.printStackTrace();
        }
        return arrayAp.get(0).getBSSID();

        //return "Hello: " + request.params(":name");
        //return arrayAp[0].get;
    });

    post(apiPrefix + "/findUser/:data", (request, response) -> {
        String userId = request.params(":data");

        ArrayList<AccessPoint> aps = rwJson.readJson(userId.toString());

        /*JsonObject json = new JsonObject();
                
        try {
        json = JsonObject.readFrom(request.params(":data"));
        } catch (Exception ex) {
        System.out.println("erro no json:\n" + ex.getMessage());
        Logger.getLogger(Main.class.getName()).log(Level.SEVERE, null, ex);
        json.add("error", ex.getMessage());
        response.status(500);
        }*/
        try {
            for (int i = 0; i < aps.size(); i++) {
                System.out.println("Nome: " + aps.get(i).getBSSID() + " - Mac: " + aps.get(i).getSSID()
                        + " - Sinal: " + aps.get(i).getRSSI() + " - Sala: " + aps.get(i).getSala());
            }
        } catch (Exception ex) {
            System.out.println("erro no json:\n" + ex.getMessage());
            Logger.getLogger(Main.class.getName()).log(Level.SEVERE, null, ex);
            //json.add("error", ex.getMessage());
            response.status(500);
            return ex.getMessage();
        }

        return userId.toString();
    });

    /*post(apiPrefix + "/findUser/", (request, response) ->{
     JsonObject json = new JsonObject();
            
    // Informaes do roteador/AP
    String[] BSSID; // basic service set identifier - nome da conexo
    String[] SSID; // service set identifier - identificador nico da conexo
    int[]    RSSI; // received signal strength indicator - potencia do sinal (-87 a -32)
    String   sala;
            
    String jsonBody = request.body();
    JsonObject reqJson = JsonObject.readFrom(jsonBody);
    JsonObject wifiJson = reqJson.get("wifi").asObject();
            
    System.out.println("reqJson.size()" + reqJson.size() + "\nwifiJson.size()" + wifiJson.size());
            
    RSSI = new int[wifiJson.size()];
    BSSID = new String[wifiJson.size()];
    SSID = new String[wifiJson.size()];
            
    try{
        for (int i = 0; i < wifiJson.size(); i++) {
            // recebe informaes das conexes encontradas
            BSSID[i] = wifiJson.get("BSSID").asString();
            SSID[i] = wifiJson.get("SSID").asString();
            RSSI[i] = wifiJson.get("RSSI").asInt();
        }
            
        return json.toString();
    }catch(Exception ex){
        System.out.println("erro no json:\n" + ex.getMessage());
        Logger.getLogger(Main.class.getName()).log(Level.SEVERE, null, ex);
        json.add("error", ex.getMessage());
        response.status(500);
    }
    return json.toString();
    });*/

    get(apiPrefix + "/users", (request, response) -> {
        JsonObject json = new JsonObject();

        request.params();

        try {
            List<User> users = userDao.findAll();
            JsonArray usersJson = new JsonArray();
            for (User u : users) {
                JsonObject uJson = new JsonObject();
                uJson.add("id", u.getId());
                uJson.add("name", u.getName());
                uJson.add("email", u.getEmail());
                usersJson.add(uJson);
            }
            json.add("users", usersJson);

        } catch (SQLException ex) {
            Logger.getLogger(Main.class.getName()).log(Level.SEVERE, null, ex);
            json.add("error", ex.getMessage());
            response.status(500);
        }

        return json.toString();
    });

    /*get(apiPrefix + "/users/:id", (request, response) -> {
    Long userId = Long.parseLong(request.params(":id"));
    JsonObject json = new JsonObject();
    try{
        User user = userDao.findById(userId);
        if(user == null){
            json.add("error", "user not found");
            response.status(404);
            return json.toString();
        }
                
        JsonObject userJson = new JsonObject();
        userJson.add("id", user.getId());
        userJson.add("name", user.getName());
        userJson.add("email", user.getEmail());
        json.add("user", userJson);
        return json.toString();
                
    }catch(Exception ex){
        Logger.getLogger(Main.class.getName()).log(Level.SEVERE, null, ex);
        json.add("error", ex.getMessage());
        response.status(500);
    }
            
    return json.toString();
    });*/

    delete(apiPrefix + "/users/:id", (request, response) -> {
        Long userId = Long.parseLong(request.params(":id"));
        JsonObject json = new JsonObject();
        try {
            userDao.removeById(userId);
            json.add("message", "user removed");
            response.status(200);
            return json.toString();
        } catch (Exception ex) {
            Logger.getLogger(Main.class.getName()).log(Level.SEVERE, null, ex);
            json.add("error", ex.getMessage());
            response.status(500);
        }

        return json.toString();
    });

    put(apiPrefix + "/users/:id", (request, response) -> {
        Long userId = Long.parseLong(request.params(":id"));
        JsonObject json = new JsonObject();
        try {
            String jsonBody = request.body();
            JsonObject reqJson = JsonObject.readFrom(jsonBody);
            JsonObject userJson = reqJson.get("user").asObject();
            String name = userJson.get("name") != null ? userJson.get("name").asString() : null;
            String email = userJson.get("email") != null ? userJson.get("email").asString() : null;
            String password = userJson.get("password") != null ? userJson.get("password").asString() : null;

            User user = userDao.findById(userId);

            if (name != null)
                user.setName(name);

            if (email != null)
                user.setEmail(email);

            if (password != null) {
                String passwordDigest = DatabaseUtils.criptPass(password);
                user.setPasswordDigest(passwordDigest);
            }

            userDao.update(user);

            JsonObject resUserJson = new JsonObject();
            resUserJson.add("id", user.getId());
            resUserJson.add("name", user.getName());
            resUserJson.add("email", user.getEmail());

            json.add("user", resUserJson);
            return json.toString();

        } catch (Exception ex) {
            Logger.getLogger(Main.class.getName()).log(Level.SEVERE, null, ex);
            json.add("error", ex.getMessage());
            response.status(500);
        }
        return json.toString();
    });

    post(apiPrefix + "/users", (request, response) -> {
        JsonObject json = new JsonObject();
        try {
            String jsonBody = request.body();
            JsonObject reqJson = JsonObject.readFrom(jsonBody);
            JsonObject userJson = reqJson.get("user").asObject();
            User user = new User();
            user.setName(userJson.get("name").asString());
            user.setEmail(userJson.get("email").asString());
            user.setPasswordDigest(DatabaseUtils.criptPass("tempPass"));
            userDao.create(user);

            JsonObject resUserJson = new JsonObject();
            resUserJson.add("id", user.getId());
            resUserJson.add("name", user.getName());
            resUserJson.add("email", user.getEmail());
            resUserJson.add("passwordDigest", user.getPasswordDigest());

            json.add("user", resUserJson);
            return json.toString();
        } catch (Exception ex) {
            Logger.getLogger(Main.class.getName()).log(Level.SEVERE, null, ex);
            json.add("error", ex.getMessage());
            response.status(500);
        }
        return json.toString();
    });

}

From source file:TerminalMonitor.java

static public void main(String args[]) {
    DriverPropertyInfo[] required;
    StringBuffer buffer = new StringBuffer();
    Properties props = new Properties();
    boolean connected = false;
    Driver driver;// w  w  w.jav a 2  s  .  c  om
    String url;
    int line = 1; // Mark current input line

    if (args.length < 1) {
        System.out.println("Syntax: <java -Djdbc.drivers=DRIVER_NAME " + "TerminalMonitor JDBC_URL>");
        return;
    }
    url = args[0];
    // We have to get a reference to the driver so we can
    // find out what values to prompt the user for in order
    // to make a connection.
    try {
        driver = DriverManager.getDriver(url);
    } catch (SQLException e) {
        e.printStackTrace();
        System.err.println("Unable to find a driver for the specified " + "URL.");
        System.err.println("Make sure you passed the jdbc.drivers " + "property on the command line to specify "
                + "the driver to be used.");
        return;
    }
    try {
        required = driver.getPropertyInfo(url, props);
    } catch (SQLException e) {
        e.printStackTrace();
        System.err.println("Unable to get driver property information.");
        return;
    }
    input = new BufferedReader(new InputStreamReader(System.in));
    // some drivers do not implement this properly
    // if that is the case, prompt for user name and password
    try {
        if (required.length < 1) {
            props.put("user", prompt("user: "));
            props.put("password", prompt("password: "));
        } else {
            // for each required attribute in the driver property info
            // prompt the user for the value
            for (int i = 0; i < required.length; i++) {
                if (!required[i].required) {
                    continue;
                }
                props.put(required[i].name, prompt(required[i].name + ": "));
            }
        }
    } catch (IOException e) {
        e.printStackTrace();
        System.err.println("Unable to read property info.");
        return;
    }
    // Make the connection.
    try {
        connection = DriverManager.getConnection(url, props);
    } catch (SQLException e) {
        e.printStackTrace();
        System.err.println("Unable to connect to the database.");
    }
    connected = true;
    System.out.println("Connected to " + url);
    // Enter into a user input loop
    while (connected) {
        String tmp, cmd;

        // Print a prompt
        if (line == 1) {
            System.out.print("TM > ");
        } else {
            System.out.print(line + " -> ");
        }
        System.out.flush();
        // Get the next line of input
        try {
            tmp = input.readLine();
        } catch (java.io.IOException e) {
            e.printStackTrace();
            return;
        }
        // Get rid of extra space in the command
        cmd = tmp.trim();
        // The user wants to commit pending transactions
        if (cmd.equals("commit")) {
            try {
                connection.commit();
                System.out.println("Commit successful.");
            } catch (SQLException e) {
                System.out.println("Error in commit: " + e.getMessage());
            }
            buffer = new StringBuffer();
            line = 1;
        }
        // The user wants to execute the current buffer
        else if (cmd.equals("go")) {
            if (!buffer.equals("")) {
                try {
                    executeStatement(buffer);
                } catch (SQLException e) {
                    System.out.println(e.getMessage());
                }
            }
            buffer = new StringBuffer();
            line = 1;
            continue;
        }
        // The user wants to quit
        else if (cmd.equals("quit")) {
            connected = false;
            continue;
        }
        // The user wants to clear the current buffer
        else if (cmd.equals("reset")) {
            buffer = new StringBuffer();
            line = 1;
            continue;
        }
        // The user wants to abort a pending transaction
        else if (cmd.equals("rollback")) {
            try {
                connection.rollback();
                System.out.println("Rollback successful.");
            } catch (SQLException e) {
                System.out.println("An error occurred during rollback: " + e.getMessage());
            }
            buffer = new StringBuffer();
            line = 1;
        }
        // The user wants version info
        else if (cmd.startsWith("show")) {
            DatabaseMetaData meta;

            try {
                meta = connection.getMetaData();
                cmd = cmd.substring(5, cmd.length()).trim();
                if (cmd.equals("version")) {
                    showVersion(meta);
                } else {
                    System.out.println("show version"); // Bad arg
                }
            } catch (SQLException e) {
                System.out.println("Failed to load meta data: " + e.getMessage());
            }
            buffer = new StringBuffer();
            line = 1;
        }
        // The input that is not a keyword should appended be to the buffer
        else {
            buffer.append(" " + tmp);
            line++;
            continue;
        }
    }
    try {
        connection.close();
    } catch (SQLException e) {
        System.out.println("Error closing connection: " + e.getMessage());
    }
    System.out.println("Connection closed.");
}

From source file:com.peewah.distribuidosfinal.EntryPoint.java

public static void main(String[] args) {
    //1. Conexin con la base de datos
    String dbUrl = "jdbc:postgresql://localhost:5432/distribuidosfinal";
    try {/*www.j av a 2 s  .  c o m*/
        connectionSource = new JdbcConnectionSource(dbUrl);
        ((JdbcConnectionSource) connectionSource).setUsername("csacanam");
        ((JdbcConnectionSource) connectionSource).setPassword("12345678");
    } catch (SQLException ex) {
        System.out.println("Error en la conexin a la base de datos");
    }

    // 2. Data Acces Object (DAO) pattern
    usuarioDao = null;
    sistemaOperativoDao = null;
    maquinaVirtualDao = null;
    maquinaAppDao = null;
    appDao = null;
    cookbookDao = null;
    cookbookAppDao = null;
    nodoDao = null;

    if (connectionSource != null) {
        try {
            usuarioDao = DaoManager.createDao(connectionSource, Usuario.class);
            sistemaOperativoDao = DaoManager.createDao(connectionSource, SistemaOperativo.class);
            maquinaVirtualDao = DaoManager.createDao(connectionSource, MaquinaVirtual.class);
            maquinaAppDao = DaoManager.createDao(connectionSource, MaquinaApp.class);
            appDao = DaoManager.createDao(connectionSource, App.class);
            cookbookDao = DaoManager.createDao(connectionSource, Cookbook.class);
            cookbookAppDao = DaoManager.createDao(connectionSource, CookbookApp.class);
            nodoDao = DaoManager.createDao(connectionSource, Nodo.class);

        } catch (SQLException ex) {
            System.out.println("Error en la creacin del DAO");
            System.err.println(ex.getMessage());
        }
    }

    // 3. Crear tabla Usuario si no existe
    try {
        TableUtils.createTableIfNotExists(connectionSource, Usuario.class);
        TableUtils.createTableIfNotExists(connectionSource, SistemaOperativo.class);
        TableUtils.createTableIfNotExists(connectionSource, MaquinaVirtual.class);
        TableUtils.createTableIfNotExists(connectionSource, App.class);
        TableUtils.createTableIfNotExists(connectionSource, MaquinaApp.class);
        TableUtils.createTableIfNotExists(connectionSource, Cookbook.class);
        TableUtils.createTableIfNotExists(connectionSource, CookbookApp.class);
        TableUtils.createTableIfNotExists(connectionSource, Nodo.class);

    } catch (SQLException ex) {
        System.out.println("Error creando las tablas");
    }

    //4. Asignacin de puerto
    ProcessBuilder process = new ProcessBuilder();
    Integer puerto;
    if (process.environment().get("PORT") != null) {
        puerto = Integer.parseInt(process.environment().get("PORT"));
    } else {
        puerto = 8080;
    }
    spark.SparkBase.port(puerto);

    //5. Habilitar Cross-origin resource sharing (CORS)
    options("/*", (Request rqst, Response rspns) -> {
        String accessControlRequestHeaders = rqst.headers("Access-Control-Request-Headers");
        if (accessControlRequestHeaders != null) {
            rspns.header("Access-Control-Allow-Headers", accessControlRequestHeaders);
        }

        String accessControlRequestMethod = rqst.headers("Access-Control-Request-Method");
        if (accessControlRequestMethod != null) {
            rspns.header("Access-Control-Allow-Methods", accessControlRequestMethod);
        }
        return "OK";
    });

    before((Request rqst, Response rspns) -> {
        rspns.header("Access-Control-Allow-Origin", "*");
    });

    after((Request rqst, Response rspns) -> {
        rspns.type("application/json");
    });

    //6. Web services
    //Crear usuario
    post("/new-user", (Request rqst, Response rspns) -> {
        //Obtener datos como parmetros
        String nombre = rqst.queryParams("name");
        String username = rqst.queryParams("username");
        String password = rqst.queryParams("password");

        //Validar si no hay datos vacos
        if (nombre != null && !nombre.equals("") && username != null && !username.equals("") && password != null
                && !password.equals("")) {
            //Crear objeto usuario
            Usuario usuario = new Usuario();
            usuario.setNombre(nombre);
            usuario.setPassword(password);
            usuario.setUsername(username);

            //Crear objeto en base de datos
            try {
                usuarioDao.create(usuario);

                //Crear carpeta
                File file = new File("/tmp/" + username);
                if (!file.exists()) {
                    boolean success = file.mkdir();
                    if (!success) {
                        System.out.println("La carpeta no pudo ser creada");
                    }
                }

            } catch (SQLException ex) {
                System.out.println("Error creando el usuario");
                return false;
            }

        } else {
            System.out.println("No debes dejar campos vacos");
            return false;
        }

        System.out.println("Usuario creado");
        return true;
    });

    //Autenticar usuario
    post("/auth-user", (Request rqst, Response rspns) -> {
        //Obtener datos como parmetros
        String username = rqst.queryParams("username");
        String password = rqst.queryParams("password");

        //Validar si no hay datos vacos
        if (username != null && !username.equals("") && password != null && !password.equals("")) {

            //Validar la dupla usuario-password
            try {
                Usuario usuario = usuarioDao.queryForId(username);
                if (usuario != null && usuario.getPassword().equals(password)) {
                    return true;
                }

            } catch (SQLException ex) {
            }

        }

        return false;

    });

    //Listar sistemas operativos disponibles
    get("/list-so", (Request rqst, Response rspns) -> {
        List<SistemaOperativo> sistemasOperativos = new ArrayList<>();
        try {
            sistemasOperativos = sistemaOperativoDao.queryForAll();
        } catch (SQLException ex) {
            System.out.println("Error listando los sistemas operativos");
        }

        return sistemasOperativos;
    }, new JsonTransformer());

    //Crear mquina virtual
    post("/create-machine", (Request rqst, Response rspns) -> {
        try {
            //Obtener parmetros
            String username = rqst.queryParams("username");
            String nombreMaquina = rqst.queryParams("nombreMaquina");
            String nombreSO = rqst.queryParams("nombreSO");

            Usuario user = usuarioDao.queryForId(username);
            SistemaOperativo so = sistemaOperativoDao.queryForId(nombreSO);

            if (user != null && so != null) {
                //Crear mquina virtual
                MaquinaVirtual maquinaVirtual = new MaquinaVirtual();
                maquinaVirtual.setNombre(nombreMaquina);
                maquinaVirtual.setSistemaOperativo(sistemaOperativoDao.queryForId(nombreSO));
                maquinaVirtual.setUsername(usuarioDao.queryForId(username));

                maquinaVirtualDao.create(maquinaVirtual);

                //Crear carpeta
                String path = "/tmp/" + username + "/" + nombreMaquina;
                File file = new File(path);
                if (!file.exists()) {
                    boolean success = file.mkdir();

                    if (!success) {
                        System.out.println("No se pudo crear la carpeta para la mquina");
                    } else {

                        //Crear Vagrantfile
                        try (Writer writer = new BufferedWriter(
                                new OutputStreamWriter(new FileOutputStream(path + "/Vagrantfile"), "UTF-8"))) {
                            writer.write("VAGRANTFILE_API_VERSION = \"2\"\n");
                            writer.write("Vagrant.configure(VAGRANTFILE_API_VERSION) do |config|\n");
                            writer.write("\n");
                            writer.write("end\n");
                        }

                    }
                }

                return true;
            } else {
                return false;
            }

        } catch (SQLException ex) {
            System.out.println("Error creando la mquina virtual");
            return false;
        }
    });

    //Eliminar usuario y sus mquinas virtuales asociadas
    post("/delete-user", (Request rqst, Response rspns) -> {
        String userLogged = rqst.queryParams("usernameLogged");
        String nombreUsuario = rqst.queryParams("usernameToDelete");

        if (userLogged != null && !userLogged.equals("") && nombreUsuario != null && !userLogged.equals("")
                && userLogged.equals("admin")) {
            try {
                Usuario user = usuarioDao.queryForId(nombreUsuario);

                if (user != null) {
                    //Eliminar mquinas virtuales del usuario
                    Collection<MaquinaVirtual> maquinasUsuario = user.getMaquinasVirtuales();
                    for (MaquinaVirtual maquina : maquinasUsuario) {
                        //Eliminar apps de las mquinas virtuales del usuario
                        QueryBuilder<MaquinaApp, String> queryBuilder = maquinaAppDao.queryBuilder();
                        queryBuilder.where().eq(MaquinaApp.MACHINE_FIELD, maquina.getId());
                        PreparedQuery<MaquinaApp> preparedQuery = queryBuilder.prepare();

                        Collection<MaquinaApp> maquinasApps = maquinaAppDao.query(preparedQuery);
                        maquinaAppDao.delete(maquinasApps);

                        //Eliminar la mquina virtual
                        maquinaVirtualDao.delete(maquina);
                    }

                    //Eliminar usuario
                    usuarioDao.delete(user);

                    //Eliminar carpeta del usuario
                    FileUtils.deleteDirectory(new File("/tmp/" + nombreUsuario));

                    return true;
                } else {
                    return false;
                }

            } catch (SQLException ex) {
                System.out.println("Error eliminando el usuario");
                return false;
            }

        } else {
            System.out.println("No tiene permisos para realizar esta accin");
            return false;
        }
    });

    //Listar mquinas virtuales de un usuario
    get("/list-machines", (Request rqst, Response rspns) -> {
        String username = rqst.queryParams("username");
        return listMachines(username);
    }, new JsonTransformer());

    //Listar usuarios
    get("/list-users", (Request rqst, Response rspns) -> {
        String username = rqst.queryParams("usernameLogged");

        if (username.equals("admin")) {
            List<Usuario> usuarios = new ArrayList<>();
            try {
                usuarios = usuarioDao.queryForAll();
            } catch (SQLException ex) {
                System.out.println("Error listando los usuarios");
            }

            return usuarios;
        } else {
            System.out.println("No tiene permisos para realizar esta accin");
            return "No tiene permisos para realizar esta accin";
        }
    }, new JsonTransformer());

    // Agregar nodo a una mquina virtual
    post("/add-node", (Request rqst, Response rspns) -> {
        String nombreNodo = rqst.queryParams("nombreNodo");
        String ipPrivada = rqst.queryParams("ipPrivada");
        String ipPublica = rqst.queryParams("ipPublica");
        String mascaraRed = rqst.queryParams("mascaraRed");
        String cantidadMemoria = rqst.queryParams("cantidadMemoria");
        String cantidadCPU = rqst.queryParams("cantidadCPU");
        String interfazPuente = rqst.queryParams("interfazPuente");
        String parametrosJSON = rqst.queryParams("parametrosJSON");
        String nombreMaquina = rqst.queryParams("nombreMaquina");
        String userLogged = rqst.queryParams("userLogged");

        Usuario user = usuarioDao.queryForId(userLogged);

        if (user != null) {
            //Buscar mquina
            QueryBuilder<MaquinaVirtual, Integer> queryBuilder = maquinaVirtualDao.queryBuilder();
            queryBuilder.where().eq(MaquinaVirtual.USERNAME_FIELD, userLogged);
            queryBuilder.where().eq(MaquinaVirtual.NOMBRE_FIELD, nombreMaquina);
            PreparedQuery<MaquinaVirtual> preparedQuery = queryBuilder.prepare();
            List<MaquinaVirtual> maquinasUser = maquinaVirtualDao.query(preparedQuery);

            //Existe la mquina
            if (maquinasUser.size() > 0 && maquinasUser.get(0).getNombre().equals(nombreMaquina)) {
                //Crear nodo
                Nodo nodo = new Nodo();
                nodo.setNombre(nombreNodo);
                nodo.setCantidadCPU(cantidadCPU);
                nodo.setCantidadMemoria(cantidadMemoria);
                nodo.setInterfazPuente(interfazPuente);
                nodo.setIpPrivada(ipPrivada);
                nodo.setIpPublica(ipPublica);
                nodo.setMascaraRed(mascaraRed);
                nodo.setParametrosJSON(parametrosJSON);
                nodo.setMaquinaVirtual(maquinasUser.get(0));
                nodoDao.create(nodo);

                //Crear nodo en Vagrantfile
                insertarNodoEnVagrantFile("/tmp/" + userLogged + "/" + nombreMaquina, nodo);

                return true;

            }
        }

        return false;

    });

    //Listar apps para un SO
    get("/list-apps", (Request rqst, Response rspns) -> {
        String nameSO = rqst.queryParams("nombreSO");

        SistemaOperativo buscado = sistemaOperativoDao.queryForId(nameSO);

        if (buscado != null) {

            QueryBuilder<App, String> queryBuilder = appDao.queryBuilder();
            queryBuilder.where().eq(App.SO_FIELD, buscado.getNombre());
            PreparedQuery<App> preparedQuery = queryBuilder.prepare();

            Collection<App> aplicaciones = appDao.query(preparedQuery);

            return aplicaciones;
        } else {
            return "El SO buscado no existe";
        }

    }, new JsonTransformer());

    //Listar apps para una maquina virtual
    get("/list-app-installed", (Request rqst, Response rspns) -> {
        String userLogged = rqst.queryParams("userLogged");
        String machineName = rqst.queryParams("nombreMaquina");

        List<MaquinaApp> maquinaApp;
        List<App> apps = new ArrayList<>();

        //Buscar si el usuario loggeado existe
        Usuario buscado;
        MaquinaVirtual buscada = null;
        try {
            buscado = usuarioDao.queryForId(userLogged);

            if (buscado != null) {
                //Lista de maquinas virtuales del usuario
                Collection<MaquinaVirtual> maquinasVirtuales = listMachines(userLogged);

                //Revisar si la maquina virtual buscada pertenece al usuario loggeado
                for (MaquinaVirtual maquina : maquinasVirtuales) {
                    if (maquina.getNombre().equals(machineName)) {
                        buscada = maquina;
                        break;
                    }
                }

                if (buscada != null) {
                    //Obtener la lista de aplicaciones de la maquina virtual
                    QueryBuilder<MaquinaApp, String> queryBuilderN = maquinaAppDao.queryBuilder();
                    queryBuilderN.where().eq(MaquinaApp.MACHINE_FIELD, buscada.getId());
                    PreparedQuery<MaquinaApp> preparedQueryN = queryBuilderN.prepare();

                    maquinaApp = maquinaAppDao.query(preparedQueryN);

                    if (maquinaApp.size() > 0) {
                        for (MaquinaApp m : maquinaApp) {
                            apps.add(m.getApp());
                        }
                    }

                } else {
                    System.out.println("La maquina no existe para el usuario buscado");
                }
            } else {
                System.out.println("El usuario loggeado no existe");
            }

        } catch (SQLException ex) {
            System.out.println("Error listando las apps instaladas");
        }
        return apps;

    }, new JsonTransformer());

    //Listar nodos de una maquina virtual
    get("/list-node", (Request rqst, Response rspns) -> {
        String userLogged = rqst.queryParams("userLogged");
        String nombreMaquina = rqst.queryParams("nombreMaquina");

        //Inicializar la lista de nodos que se va a retornar
        Collection<Nodo> nodos = new ArrayList<>();

        //Validar que no hayan campos vacios
        if (userLogged != null && !userLogged.equals("") && nombreMaquina != null
                && !nombreMaquina.equals("")) {
            //Buscar el usuario loggeado
            Usuario user = usuarioDao.queryForId(userLogged);

            //Verificar que el usuario existe
            if (user != null) {
                //Obtener las maquinas virtuales del usuario
                List<MaquinaVirtual> maquinasVirtuales = listMachines(userLogged);

                for (MaquinaVirtual m : maquinasVirtuales) {
                    if (m.getNombre().equals(nombreMaquina)) {
                        nodos = m.getNodos();
                    }
                }

            } else {
                System.out.println("El usuario loggeado no existe");
            }
        } else {
            System.out.println("No pueden haber parametros vacios");
        }

        return nodos;
    }, new JsonTransformer());

    //Eliminar maquina virtual y aplicaciones asociadas
    post("/delete-vm", (Request rqst, Response rspns) -> {
        String usernameLogged = rqst.queryParams("usernameLogged");
        String nombreMaquina = rqst.queryParams("nombreMaquina");

        MaquinaVirtual buscada = null;
        List<MaquinaApp> maquinaApp;

        //Verificar que los parametros recibidos no son null
        if (usernameLogged != null && !usernameLogged.equals("") && nombreMaquina != null
                && !nombreMaquina.equals("")) {

            Usuario user = usuarioDao.queryForId(usernameLogged);

            if (user != null) {
                //Obtener las maquinas virtuales del usuario
                List<MaquinaVirtual> maquinasVirtuales = listMachines(usernameLogged);

                //Buscar la maquina virtual a eliminar dentro de las maquinas del usuario
                for (MaquinaVirtual m : maquinasVirtuales) {
                    if (m.getNombre().equals(nombreMaquina)) {
                        buscada = m;
                        break;
                    }
                }

                //Verificar que la maquina buscada pertenece al usuario en cuestion
                if (buscada != null) {
                    //Obtener la lista de aplicaciones de la maquina virtual
                    QueryBuilder<MaquinaApp, String> queryBuilder = maquinaAppDao.queryBuilder();
                    queryBuilder.where().eq(MaquinaApp.MACHINE_FIELD, buscada.getId());
                    PreparedQuery<MaquinaApp> preparedQuery = queryBuilder.prepare();

                    maquinaApp = maquinaAppDao.query(preparedQuery);

                    if (maquinaApp.size() > 0) {
                        //Eliminar las aplicaciones 
                        for (MaquinaApp i : maquinaApp) {
                            maquinaAppDao.delete(i);
                        }

                    } else {
                        System.out.println("No existen aplicaciones para la maquina virtual en cuestion");
                    }

                    //Eliminar mquina virtual
                    maquinaVirtualDao.delete(buscada);

                    //Eliminar carpeta de la maquina virtual
                    FileUtils.deleteDirectory(new File("/tmp/" + usernameLogged + "/" + nombreMaquina));
                    return true;

                }
            } else {
                System.out.println("EL usuario loggeado no existe");
            }

        } else {
            System.out.println("No pueden haber campos vacios");
        }

        return false;
    });

    //Correr mquina virtual
    post("/run-vm", (Request rqst, Response rspns) -> {

        String username = rqst.queryParams("userLogged");
        String nombreMaquina = rqst.queryParams("nombreMaquina");

        MaquinaVirtual maquinaBuscada = null;

        if (username != null && nombreMaquina != null && !nombreMaquina.equals("")
                && !nombreMaquina.equals("")) {
            Usuario user = usuarioDao.queryForId(username);

            if (user != null) {
                //Listar mquinas virtuales del usuario
                List<MaquinaVirtual> maquinasVirtuales = listMachines(username);

                for (MaquinaVirtual maquina : maquinasVirtuales) {
                    if (maquina.getNombre().equals(nombreMaquina)) {
                        maquinaBuscada = maquina;
                        break;
                    }
                }

                if (maquinaBuscada != null) {
                    try {
                        //Comando para ejecutar el comando vagrant up en el shell 
                        ProcessBuilder pb = new ProcessBuilder("vagrant up");
                        Process p;
                        String path = "/tmp/" + username + "/" + nombreMaquina;
                        File file = new File(path);

                        //Validar si es un directorio
                        if (file.exists() && file.isDirectory()) {
                            pb.directory(file);
                            p = pb.start();
                            return true;
                        }

                    } catch (IOException ex) {
                    }
                }

            }

        }

        return false;
    });

    //Destruir mquina virtual
    post("/destroy-vm", (Request rqst, Response rspns) -> {

        String username = rqst.queryParams("userLogged");
        String nombreMaquina = rqst.queryParams("nombreMaquina");

        MaquinaVirtual maquinaBuscada = null;

        if (username != null && nombreMaquina != null && !nombreMaquina.equals("")
                && !nombreMaquina.equals("")) {
            Usuario user = usuarioDao.queryForId(username);

            if (user != null) {
                //Listar mquinas virtuales del usuario
                List<MaquinaVirtual> maquinasVirtuales = listMachines(username);

                for (MaquinaVirtual maquina : maquinasVirtuales) {
                    if (maquina.getNombre().equals(nombreMaquina)) {
                        maquinaBuscada = maquina;
                        break;
                    }
                }

                if (maquinaBuscada != null) {
                    try {
                        //Comando para ejecutar el comando vagrant up en el shell 
                        ProcessBuilder pb = new ProcessBuilder("vagrant destroy -f");
                        Process p;
                        String path = "/tmp/" + username + "/" + nombreMaquina;
                        File file = new File(path);

                        //Validar si es un directorio
                        if (file.exists() && file.isDirectory()) {
                            pb.directory(file);
                            p = pb.start();
                            return true;
                        }

                    } catch (IOException ex) {
                    }
                }

            }

        }

        return false;
    });

    //Reanudar mquina virtual
    post("/resume-vm", (Request rqst, Response rspns) -> {

        String username = rqst.queryParams("userLogged");
        String nombreMaquina = rqst.queryParams("nombreMaquina");

        MaquinaVirtual maquinaBuscada = null;

        if (username != null && nombreMaquina != null && !nombreMaquina.equals("")
                && !nombreMaquina.equals("")) {
            Usuario user = usuarioDao.queryForId(username);

            if (user != null) {
                //Listar mquinas virtuales del usuario
                List<MaquinaVirtual> maquinasVirtuales = listMachines(username);

                for (MaquinaVirtual maquina : maquinasVirtuales) {
                    if (maquina.getNombre().equals(nombreMaquina)) {
                        maquinaBuscada = maquina;
                        break;
                    }
                }

                if (maquinaBuscada != null) {
                    try {
                        //Comando para ejecutar el comando vagrant up en el shell 
                        ProcessBuilder pb = new ProcessBuilder("vagrant resume");
                        Process p;
                        String path = "/tmp/" + username + "/" + nombreMaquina;
                        File file = new File(path);

                        //Validar si es un directorio
                        if (file.exists() && file.isDirectory()) {
                            pb.directory(file);
                            p = pb.start();
                            return true;
                        }

                    } catch (IOException ex) {
                    }
                }

            }

        }

        return false;
    });

    //Asociar app a una mquina virtual
    post("/associate-app", (Request rqst, Response rspns) -> {
        String username = rqst.queryParams("username");
        String nombreMaquina = rqst.queryParams("nombreMaquina");
        String nombreApp = rqst.queryParams("nombreApp");

        Usuario user = usuarioDao.queryForId(username);

        if (user != null) {
            //Verificar si el usuario tiene la mquina
            List<MaquinaVirtual> maquinas = listMachines(username);

            MaquinaVirtual buscada = null;

            for (MaquinaVirtual maquina : maquinas) {
                if (maquina.getNombre().equals(nombreMaquina)) {
                    buscada = maquina;
                    break;
                }
            }

            if (buscada != null) {
                App app = appDao.queryForId(nombreApp);

                //Verificar si la app existe y si est para el mismo sistema operativo que tiene la mquina
                if (app != null && app.getSistemaOperativo().getNombre()
                        .equals(buscada.getSistemaOperativo().getNombre())) {
                    //Agregar a la base de datos
                    MaquinaApp maquinaApp = new MaquinaApp(buscada, app);
                    maquinaAppDao.create(maquinaApp);

                    //Crear registro en el Vagrantfile
                    String path = "/tmp/" + username + "/" + nombreMaquina;
                    insertarCookbooksANodos(new ArrayList(buscada.getNodos()), app, path);

                    return true;
                } else {
                    System.out.println("La app no existe");
                }
            } else {
                System.out.println("No se encontr la mquina en la lista del usuario");
            }
        } else {
            System.out.println("El usuario no existe");
        }

        return false;

    });

    //Listar todas las aplicaciones
    get("/list-apps-all", (Request rqst, Response rspns) -> {
        return appDao.queryForAll();
    }, new JsonTransformer());

    // Cargar datos de prueba
    get("/add-testdata", (Request rqst, Response rspns) -> {
        try {
            if (connectionSource != null) {
                TableUtils.createTableIfNotExists(connectionSource, Usuario.class);
                TableUtils.createTableIfNotExists(connectionSource, SistemaOperativo.class);
                TableUtils.createTableIfNotExists(connectionSource, MaquinaVirtual.class);
                TableUtils.createTableIfNotExists(connectionSource, App.class);
                TableUtils.createTableIfNotExists(connectionSource, MaquinaApp.class);
                TableUtils.createTableIfNotExists(connectionSource, Cookbook.class);
                TableUtils.createTableIfNotExists(connectionSource, CookbookApp.class);
                TableUtils.createTableIfNotExists(connectionSource, Nodo.class);
            }
            testData();
        } catch (SQLException ex) {
            return "Error agregando informacin de prueba";
        }

        return "OK";
    });

    //Eliminar datos de prueba
    get("/delete-testdata", (Request rqst, Response rspns) -> {
        try {
            TableUtils.dropTable(connectionSource, Usuario.class, true);
            TableUtils.dropTable(connectionSource, MaquinaVirtual.class, true);
            TableUtils.dropTable(connectionSource, SistemaOperativo.class, true);
            TableUtils.dropTable(connectionSource, App.class, true);
            TableUtils.dropTable(connectionSource, Cookbook.class, true);
            TableUtils.dropTable(connectionSource, MaquinaApp.class, true);
            TableUtils.dropTable(connectionSource, CookbookApp.class, true);
            TableUtils.dropTable(connectionSource, Nodo.class, true);
        } catch (SQLException ex) {
            return "Error eliminando la informacin";
        }

        return "OK";
    });

}

From source file:jp.massbank.spectrumsearch.SearchPage.java

public static void main(String[] args) {
    LOGGER.info("Application start!");
    LOGGER.info("Spectrum Search version " + SearchPage.class.getPackage().getImplementationVersion());

    SearchPage appli = new SearchPage();
    appli.setDefaultCloseOperation(WindowConstants.EXIT_ON_CLOSE);
    appli.setTitle(APPLICATION_TITLE);//  ww  w .  j  av a  2s .com
    appli.setSize(1200, 700);

    try {
        appli.init();
        appli.setVisible(true);
    } catch (SQLException e) {
        LOGGER.error(e.getMessage(), e);
        System.exit(-1);
    }
}

From source file:com.l2jfree.gameserver.datatables.PetNameTable.java

public static boolean doesPetNameExist(String name, int petNpcId) {
    boolean result = true;
    Connection con = null;//w  w  w.j a  va  2  s . c  o  m

    try {
        con = L2DatabaseFactory.getInstance().getConnection(con);
        PreparedStatement statement = con.prepareStatement(
                "SELECT name FROM pets p, items i WHERE p.item_obj_id = i.object_id AND name=? AND i.item_id=?");
        statement.setString(1, name);
        statement.setString(2, Integer.toString(PetDataTable.getItemIdByPetId(petNpcId)));
        ResultSet rset = statement.executeQuery();
        result = rset.next();
        rset.close();
        statement.close();
    } catch (SQLException e) {
        _log.warn("could not check existing petname:" + e.getMessage(), e);
    } finally {
        L2DatabaseFactory.close(con);
    }

    return result;
}

From source file:com.app.util.DatabaseUtil.java

public static Connection getDatabaseConnection() throws DatabaseConnectionException {

    if (!_isPropertiesSet) {
        _log.error("The database properties are not set");

        throw new DatabaseConnectionException();
    }// w  w w  .j a v a  2  s. c o  m

    try {
        return DriverManager.getConnection(_databaseURL, _databaseUsername, _databasePassword);
    } catch (SQLException sqle) {
        _log.error(sqle.getMessage(), sqle);

        throw new DatabaseConnectionException(sqle);
    }
}