Example usage for java.sql DriverManager getConnection

List of usage examples for java.sql DriverManager getConnection

Introduction

In this page you can find the example usage for java.sql DriverManager getConnection.

Prototype

private static Connection getConnection(String url, java.util.Properties info, Class<?> caller)
            throws SQLException 

Source Link

Usage

From source file:JDBCQuery.java

public static void main(String[] av) {
    try {/*from   w w  w  .  j  a  v a2  s.c o m*/
        System.out.println("Loading Driver (with Class.forName)");
        // Load the jdbc-odbc bridge driver
        Class.forName("sun.jdbc.odbc.JdbcOdbcDriver");

        // Enable logging
        // DriverManager.setLogStream(System.err);

        System.out.println("Getting Connection");
        Connection conn = DriverManager.getConnection("jdbc:odbc:Companies", "ian", ""); // user, passwd

        // Any warnings generated by the connect?
        checkForWarning(conn.getWarnings());

        System.out.println("Creating Statement");
        Statement stmt = conn.createStatement();

        System.out.println("Executing Query");
        ResultSet rs = stmt.executeQuery("SELECT * FROM Companies");

        System.out.println("Retrieving Results");
        int i = 0;
        while (rs.next()) {

            System.out.println("Retrieving Company ID");
            int x = rs.getInt("CustNO");
            System.out.println("Retrieving Name");
            String s = rs.getString("Company");

            System.out.println("ROW " + ++i + ": " + x + "; " + s + "; " + ".");

        }

        rs.close(); // All done with that resultset
        stmt.close(); // All done with that statement
        conn.close(); // All done with that DB connection

    } catch (ClassNotFoundException e) {
        System.out.println("Can't load driver " + e);
    } catch (SQLException e) {
        System.out.println("Database access failed " + e);
    }
}

From source file:com.fiveclouds.jasper.JasperRunner.java

public static void main(String[] args) {

    // Set-up the options for the utility
    Options options = new Options();
    Option report = new Option("report", true, "jasper report to run (i.e. /path/to/report.jrxml)");
    options.addOption(report);/*  w w  w.j  a  v  a2 s  .co m*/

    Option driver = new Option("driver", true, "the jdbc driver class (i.e. com.mysql.jdbc.Driver)");
    driver.setRequired(true);
    options.addOption(driver);

    options.addOption("jdbcurl", true, "database jdbc url (i.e. jdbc:mysql://localhost:3306/database)");
    options.addOption("excel", true, "Will override the PDF default and export to Microsoft Excel");
    options.addOption("username", true, "database username");
    options.addOption("password", true, "database password");
    options.addOption("output", true, "the output filename (i.e. path/to/report.pdf");
    options.addOption("help", false, "print this message");

    Option propertyOption = OptionBuilder.withArgName("property=value").hasArgs(2).withValueSeparator()
            .withDescription("use value as report property").create("D");

    options.addOption(propertyOption);

    // Parse the options and build the report
    CommandLineParser parser = new PosixParser();
    try {
        CommandLine cmd = parser.parse(options, args);

        if (cmd.hasOption("help")) {
            HelpFormatter formatter = new HelpFormatter();
            formatter.printHelp("jasper-runner", options);
        } else {

            System.out.println("Building report " + cmd.getOptionValue("report"));
            try {
                Class.forName(cmd.getOptionValue("driver"));
                Connection connection = DriverManager.getConnection(cmd.getOptionValue("jdbcurl"),
                        cmd.getOptionValue("username"), cmd.getOptionValue("password"));
                System.out.println("Connected to " + cmd.getOptionValue("jdbcurl"));
                JasperReport jasperReport = JasperCompileManager.compileReport(cmd.getOptionValue("report"));

                JRPdfExporter pdfExporter = new JRPdfExporter();

                Properties properties = cmd.getOptionProperties("D");
                Map<String, Object> parameters = new HashMap<String, Object>();

                Map<String, JRParameter> reportParameters = new HashMap<String, JRParameter>();

                for (JRParameter param : jasperReport.getParameters()) {
                    reportParameters.put(param.getName(), param);
                }

                for (Object propertyKey : properties.keySet()) {
                    String parameterName = String.valueOf(propertyKey);
                    String parameterValue = String.valueOf(properties.get(propertyKey));
                    JRParameter reportParam = reportParameters.get(parameterName);

                    if (reportParam != null) {
                        if (reportParam.getValueClass().equals(String.class)) {
                            System.out.println(
                                    "Property " + parameterName + " set to String = " + parameterValue);
                            parameters.put(parameterName, parameterValue);
                        } else if (reportParam.getValueClass().equals(Integer.class)) {
                            System.out.println(
                                    "Property " + parameterName + " set to Integer = " + parameterValue);
                            parameters.put(parameterName, Integer.parseInt(parameterValue));
                        } else {
                            System.err.print("Unsupported type for property " + parameterName);
                            System.exit(1);

                        }
                    } else {
                        System.out.println("Property " + parameterName + " not found in the report! IGNORING");

                    }
                }

                JasperPrint print = JasperFillManager.fillReport(jasperReport, parameters, connection);

                pdfExporter.setParameter(JRExporterParameter.JASPER_PRINT, print);
                pdfExporter.setParameter(JRExporterParameter.OUTPUT_FILE_NAME, cmd.getOptionValue("output"));
                System.out.println("Exporting report to " + cmd.getOptionValue("output"));
                pdfExporter.exportReport();
            } catch (JRException e) {
                System.err.print("Unable to parse report file (" + cmd.getOptionValue("r") + ")");
                e.printStackTrace();
                System.exit(1);
            } catch (ClassNotFoundException e) {
                System.err.print("Unable to find the database driver,  is it on the classpath?");
                e.printStackTrace();
                System.exit(1);
            } catch (SQLException e) {
                System.err.print("An SQL exception has occurred (" + e.getMessage() + ")");
                e.printStackTrace();
                System.exit(1);
            }
        }
    } catch (ParseException e) {
        System.err.print("Unable to parse command line options (" + e.getMessage() + ")");
        System.exit(1);
    }
}

From source file:GetDBInfo.java

public static void main(String[] args) {
    Connection c = null; // The JDBC connection to the database server
    try {/*from www  . j av  a 2  s  .c  o m*/
        // Look for the properties file DB.props in the same directory as
        // this program. It will contain default values for the various
        // parameters needed to connect to a database
        Properties p = new Properties();
        try {
            p.load(GetDBInfo.class.getResourceAsStream("DB.props"));
        } catch (Exception e) {
        }

        // Get default values from the properties file
        String driver = p.getProperty("driver"); // Driver class name
        String server = p.getProperty("server", ""); // JDBC URL for server
        String user = p.getProperty("user", ""); // db user name
        String password = p.getProperty("password", ""); // db password

        // These variables don't have defaults
        String database = null; // The db name (appended to server URL)
        String table = null; // The optional name of a table in the db

        // Parse the command-line args to override the default values above
        for (int i = 0; i < args.length; i++) {
            if (args[i].equals("-d"))
                driver = args[++i]; //-d <driver>
            else if (args[i].equals("-s"))
                server = args[++i];//-s <server>
            else if (args[i].equals("-u"))
                user = args[++i]; //-u <user>
            else if (args[i].equals("-p"))
                password = args[++i];
            else if (database == null)
                database = args[i]; // <dbname>
            else if (table == null)
                table = args[i]; // <table>
            else
                throw new IllegalArgumentException("Unknown argument: " + args[i]);
        }

        // Make sure that at least a server or a database were specified.
        // If not, we have no idea what to connect to, and cannot continue.
        if ((server.length() == 0) && (database.length() == 0))
            throw new IllegalArgumentException("No database specified.");

        // Load the db driver, if any was specified.
        if (driver != null)
            Class.forName(driver);

        // Now attempt to open a connection to the specified database on
        // the specified server, using the specified name and password
        c = DriverManager.getConnection(server + database, user, password);

        // Get the DatabaseMetaData object for the connection. This is the
        // object that will return us all the data we're interested in here
        DatabaseMetaData md = c.getMetaData();

        // Display information about the server, the driver, etc.
        System.out.println("DBMS: " + md.getDatabaseProductName() + " " + md.getDatabaseProductVersion());
        System.out.println("JDBC Driver: " + md.getDriverName() + " " + md.getDriverVersion());
        System.out.println("Database: " + md.getURL());
        System.out.println("User: " + md.getUserName());

        // Now, if the user did not specify a table, then display a list of
        // all tables defined in the named database. Note that tables are
        // returned in a ResultSet, just like query results are.
        if (table == null) {
            System.out.println("Tables:");
            ResultSet r = md.getTables("", "", "%", null);
            while (r.next())
                System.out.println("\t" + r.getString(3));
        }

        // Otherwise, list all columns of the specified table.
        // Again, information about the columns is returned in a ResultSet
        else {
            System.out.println("Columns of " + table + ": ");
            ResultSet r = md.getColumns("", "", table, "%");
            while (r.next())
                System.out.println("\t" + r.getString(4) + " : " + r.getString(6));
        }
    }
    // Print an error message if anything goes wrong.
    catch (Exception e) {
        System.err.println(e);
        if (e instanceof SQLException)
            System.err.println(((SQLException) e).getSQLState());
        System.err.println("Usage: java GetDBInfo [-d <driver] " + "[-s <dbserver>]\n"
                + "\t[-u <username>] [-p <password>] <dbname>");
    }
    // Always remember to close the Connection object when we're done!
    finally {
        try {
            c.close();
        } catch (Exception e) {
        }
    }
}

From source file:HSqlPrimerDesign.java

public static void main(String[] args) throws NoSuchFieldException, IllegalAccessException,
        ClassNotFoundException, InstantiationException, SQLException, FileNotFoundException {
    Class.forName(JDBC_DRIVER_HSQL).newInstance();
    conn = DriverManager.getConnection(DB_SERVER_URL, USER, PASS);
    PrintWriter log = new PrintWriter(new File("javalog.log"));
    DpalLoad.main(args);/*from w  ww . ja v a 2  s.  c  o  m*/
    Dpal_Inst = DpalLoad.INSTANCE_WIN64;
    //        int[][] arr =calcHairpin("GGGGGGCCCCCCCCCCCCGGGGGGG",4);
    //        if(arr.length<=1){
    //            System.out.println("No Hairpin's found");
    //        }else{
    //            System.out.println("Hairpin(s) found");
    //        }
    Statement stat = conn.createStatement();
    ResultSet call = stat.executeQuery(
            "Select * From " + "Primerdb.primers where Cluster ='A1' and UniqueP =True and Bp = 20");
    Set<CharSequence> primers = new HashSet<>();
    while (call.next()) {
        primers.add(call.getString("Sequence"));
    }
    //        primers.stream().forEach(x->{
    //            log.println(x);
    //            log.println(complementarity(x, x, Dpal_Inst));
    //            int[][] arr =calcHairpin((String)x,4);
    //            if(arr.length<=1){
    //                log.println("No Hairpin's found");
    //            }else{
    //                log.println("Hairpin(s) found");
    //            }
    //            log.println();
    //            log.flush();
    //        });
}

From source file:gov.nih.nci.ncicb.tcga.dcc.dam.util.TempClinicalDataLoader.java

public static void main(String[] args) {
    // first get the db connection properties
    String url = urlSet.get(args[1]);
    String user = args[2];//from www .  j  av a 2 s. c  o  m
    String word = args[3];

    // make sure we have the Oracle driver somewhere
    try {
        Class.forName("oracle.jdbc.OracleDriver");
        Class.forName("org.postgresql.Driver");
    } catch (Exception x) {
        System.out.println("Unable to load the driver class!");
        System.exit(0);
    }
    // connect to the database
    try {
        dbConnection = DriverManager.getConnection(url, user, word);
        ClinicalBean.setDBConnection(dbConnection);
    } catch (SQLException x) {
        x.printStackTrace();
        System.exit(1);
    }

    final String xmlList = args[0];
    BufferedReader br = null;
    try {
        final Map<String, String> clinicalFiles = new HashMap<String, String>();
        final Map<String, String> biospecimenFiles = new HashMap<String, String>();
        final Map<String, String> fullFiles = new HashMap<String, String>();

        //noinspection IOResourceOpenedButNotSafelyClosed
        br = new BufferedReader(new FileReader(xmlList));

        // read the file list to get all the files to load
        while (br.ready()) {
            final String[] in = br.readLine().split("\\t");
            String xmlfile = in[0];
            String archive = in[1];

            if (xmlfile.contains("_clinical")) {
                clinicalFiles.put(xmlfile, archive);
            } else if (xmlfile.contains("_biospecimen")) {
                biospecimenFiles.put(xmlfile, archive);
            } else {
                fullFiles.put(xmlfile, archive);
            }
        }

        Date dateAdded = Calendar.getInstance().getTime();

        // NOTE!!! This deletes all data before the load starts, assuming we are re-loading everything.
        // a better way would be to figure out what has changed and load that, or to be able to load multiple versions of the data in the schema
        emptyClinicalTables(user);

        // load any "full" files first -- in case some archives aren't split yet
        for (final String file : fullFiles.keySet()) {
            String archive = fullFiles.get(file);
            System.out.println("Full file " + file + " in " + archive);
            // need to re-instantiate the disease-specific beans for each file
            createDiseaseSpecificBeans(xmlList);
            String disease = getDiseaseName(archive);
            processFullXmlFile(file, archive, disease, dateAdded);

            // memory leak or something... have to commit and close all connections and re-get connection
            // after each file to keep from using too much heap space.  this troubles me, but I have never had
            // the time to figure out why it happens
            resetConnections(url, user, word);
        }

        // now process all clinical files, and insert patients and clinical data
        for (final String clinicalFile : clinicalFiles.keySet()) {
            createDiseaseSpecificBeans(xmlList);
            String archive = clinicalFiles.get(clinicalFile);
            System.out.println("Clinical file " + clinicalFile + " in " + archive);
            String disease = getDiseaseName(archive);
            processClinicalXmlFile(clinicalFile, archive, disease, dateAdded);
            resetConnections(url, user, word);
        }

        // now process biospecimen files
        for (final String biospecimenFile : biospecimenFiles.keySet()) {
            createDiseaseSpecificBeans(xmlList);
            String archive = biospecimenFiles.get(biospecimenFile);
            String disease = getDiseaseName(archive);
            System.out.println("Biospecimen file " + biospecimenFile);
            processBiospecimenXmlFile(biospecimenFile, archive, disease, dateAdded);
            resetConnections(url, user, word);
        }

        // this sets relationships between these clinical tables and data browser tables, since we delete
        // and reload every time
        setForeignKeys();
        dbConnection.commit();
        dbConnection.close();
    } catch (Exception e) {
        e.printStackTrace();
        System.exit(-1);
    } finally {
        IOUtils.closeQuietly(br);
    }
}

From source file:examples.KafkaStreamsDemo.java

public static void main(String[] args) throws InterruptedException, SQLException {
    /**/*w w w .ja  va 2 s .  c om*/
     * The example assumes the following SQL schema
     *
     *    DROP DATABASE IF EXISTS beer_sample_sql;
     *    CREATE DATABASE beer_sample_sql CHARACTER SET utf8 COLLATE utf8_general_ci;
     *    USE beer_sample_sql;
     *
     *    CREATE TABLE breweries (
     *       id VARCHAR(256) NOT NULL,
     *       name VARCHAR(256),
     *       description TEXT,
     *       country VARCHAR(256),
     *       city VARCHAR(256),
     *       state VARCHAR(256),
     *       phone VARCHAR(40),
     *       updated_at DATETIME,
     *       PRIMARY KEY (id)
     *    );
     *
     *
     *    CREATE TABLE beers (
     *       id VARCHAR(256) NOT NULL,
     *       brewery_id VARCHAR(256) NOT NULL,
     *       name VARCHAR(256),
     *       category VARCHAR(256),
     *       style VARCHAR(256),
     *       description TEXT,
     *       abv DECIMAL(10,2),
     *       ibu DECIMAL(10,2),
     *       updated_at DATETIME,
     *       PRIMARY KEY (id)
     *    );
     */
    try {
        Class.forName("com.mysql.jdbc.Driver");
    } catch (ClassNotFoundException e) {
        System.err.println("Failed to load MySQL JDBC driver");
    }
    Connection connection = DriverManager.getConnection("jdbc:mysql://localhost:3306/beer_sample_sql", "root",
            "secret");
    final PreparedStatement insertBrewery = connection.prepareStatement(
            "INSERT INTO breweries (id, name, description, country, city, state, phone, updated_at)"
                    + " VALUES (?, ?, ?, ?, ?, ?, ?, ?)" + " ON DUPLICATE KEY UPDATE"
                    + " name=VALUES(name), description=VALUES(description), country=VALUES(country),"
                    + " country=VALUES(country), city=VALUES(city), state=VALUES(state),"
                    + " phone=VALUES(phone), updated_at=VALUES(updated_at)");
    final PreparedStatement insertBeer = connection.prepareStatement(
            "INSERT INTO beers (id, brewery_id, name, description, category, style, abv, ibu, updated_at)"
                    + " VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?)" + " ON DUPLICATE KEY UPDATE"
                    + " brewery_id=VALUES(brewery_id), name=VALUES(name), description=VALUES(description),"
                    + " category=VALUES(category), style=VALUES(style), abv=VALUES(abv),"
                    + " ibu=VALUES(ibu), updated_at=VALUES(updated_at)");

    String schemaRegistryUrl = "http://localhost:8081";

    Properties props = new Properties();
    props.put(StreamsConfig.APPLICATION_ID_CONFIG, "streams-test");
    props.put(StreamsConfig.BOOTSTRAP_SERVERS_CONFIG, "localhost:9092");
    props.put(StreamsConfig.ZOOKEEPER_CONNECT_CONFIG, "localhost:2181");
    props.put(AbstractKafkaAvroSerDeConfig.SCHEMA_REGISTRY_URL_CONFIG, schemaRegistryUrl);
    props.put(StreamsConfig.KEY_SERDE_CLASS_CONFIG, KeyAvroSerde.class);
    props.put(StreamsConfig.VALUE_SERDE_CLASS_CONFIG, ValueAvroSerde.class);

    props.put(ConsumerConfig.AUTO_OFFSET_RESET_CONFIG, "earliest");

    KStreamBuilder builder = new KStreamBuilder();

    KStream<String, GenericRecord> source = builder.stream("streaming-topic-beer-sample");

    KStream<String, JsonNode>[] documents = source.mapValues(new ValueMapper<GenericRecord, JsonNode>() {
        @Override
        public JsonNode apply(GenericRecord value) {
            ByteBuffer buf = (ByteBuffer) value.get("content");
            try {
                JsonNode doc = MAPPER.readTree(buf.array());
                return doc;
            } catch (IOException e) {
                return null;
            }
        }
    }).branch(new Predicate<String, JsonNode>() {
        @Override
        public boolean test(String key, JsonNode value) {
            return "beer".equals(value.get("type").asText()) && value.has("brewery_id") && value.has("name")
                    && value.has("description") && value.has("category") && value.has("style")
                    && value.has("abv") && value.has("ibu") && value.has("updated");
        }
    }, new Predicate<String, JsonNode>() {
        @Override
        public boolean test(String key, JsonNode value) {
            return "brewery".equals(value.get("type").asText()) && value.has("name") && value.has("description")
                    && value.has("country") && value.has("city") && value.has("state") && value.has("phone")
                    && value.has("updated");
        }
    });
    documents[0].foreach(new ForeachAction<String, JsonNode>() {
        @Override
        public void apply(String key, JsonNode value) {
            try {
                insertBeer.setString(1, key);
                insertBeer.setString(2, value.get("brewery_id").asText());
                insertBeer.setString(3, value.get("name").asText());
                insertBeer.setString(4, value.get("description").asText());
                insertBeer.setString(5, value.get("category").asText());
                insertBeer.setString(6, value.get("style").asText());
                insertBeer.setBigDecimal(7, new BigDecimal(value.get("abv").asText()));
                insertBeer.setBigDecimal(8, new BigDecimal(value.get("ibu").asText()));
                insertBeer.setDate(9, new Date(DATE_FORMAT.parse(value.get("updated").asText()).getTime()));
                insertBeer.execute();
            } catch (SQLException e) {
                System.err.println("Failed to insert record: " + key + ". " + e);
            } catch (ParseException e) {
                System.err.println("Failed to insert record: " + key + ". " + e);
            }
        }
    });
    documents[1].foreach(new ForeachAction<String, JsonNode>() {
        @Override
        public void apply(String key, JsonNode value) {
            try {
                insertBrewery.setString(1, key);
                insertBrewery.setString(2, value.get("name").asText());
                insertBrewery.setString(3, value.get("description").asText());
                insertBrewery.setString(4, value.get("country").asText());
                insertBrewery.setString(5, value.get("city").asText());
                insertBrewery.setString(6, value.get("state").asText());
                insertBrewery.setString(7, value.get("phone").asText());
                insertBrewery.setDate(8, new Date(DATE_FORMAT.parse(value.get("updated").asText()).getTime()));
                insertBrewery.execute();
            } catch (SQLException e) {
                System.err.println("Failed to insert record: " + key + ". " + e);
            } catch (ParseException e) {
                System.err.println("Failed to insert record: " + key + ". " + e);
            }
        }
    });

    final KafkaStreams streams = new KafkaStreams(builder, props);
    streams.start();
    Runtime.getRuntime().addShutdownHook(new Thread(new Runnable() {
        @Override
        public void run() {
            streams.close();
        }
    }));
}

From source file:com.intelius.iap4.TigerLineHit.java

public static void main(String[] args) {

    String _tigerDs = "jdbc:h2:/home/sxu/playground/tiger";
    ResultSet rs = null;/*from  w  w w  .  ja  v  a 2 s .co  m*/
    PreparedStatement ps = null;
    List<TigerLineHit> ret = new ArrayList<TigerLineHit>();
    try {
        //      if (_tigerDs instanceof JdbcDataSource) {
        //        JdbcDataSource ds = (JdbcDataSource) _tigerDs;
        //        conn = ds.getPooledConnection().getConnection();
        //      }else{
        //        conn = _tigerDs.getConnection();
        //      }

        //try address "540 westerly parkway, state college, pa 16801"

        Class.forName("org.h2.Driver");
        Connection conn = DriverManager.getConnection(_tigerDs, "sa", "");
        ps = conn.prepareStatement(generateSelectQuery("PA"));
        int i = 1;
        String streetNum = "540";
        String zip = "16801";
        ps.setString(i++, "Westerly");
        ps.setString(i++, streetNum);
        ps.setString(i++, streetNum);
        ps.setString(i++, streetNum);
        ps.setString(i++, streetNum);
        ps.setString(i++, streetNum);
        ps.setString(i++, streetNum);
        ps.setString(i++, streetNum);
        ps.setString(i++, streetNum);
        ps.setString(i++, zip);
        ps.setString(i++, zip);
        rs = ps.executeQuery();
        while (rs.next()) {
            TigerLineHit hit = new TigerLineHit();
            hit.streetNum = streetNum;
            hit.tlid = rs.getLong("tlid");
            hit.frAddL = rs.getString("fraddl");
            hit.frAddR = rs.getString("fraddr");
            hit.toAddL = rs.getString("toaddl");
            hit.toAddR = rs.getString("toaddr");
            hit.zipL = rs.getString("zipL");
            hit.zipR = rs.getString("zipR");
            hit.toLat = rs.getFloat("tolat");
            hit.toLon = rs.getFloat("tolong");
            hit.frLat = rs.getFloat("frlat");
            hit.frLon = rs.getFloat("tolong");
            hit.lat1 = rs.getFloat("lat1");
            hit.lat2 = rs.getFloat("lat2");
            hit.lat3 = rs.getFloat("lat3");
            hit.lat4 = rs.getFloat("lat4");
            hit.lat5 = rs.getFloat("lat5");
            hit.lat6 = rs.getFloat("lat6");
            hit.lat7 = rs.getFloat("lat7");
            hit.lat8 = rs.getFloat("lat8");
            hit.lat9 = rs.getFloat("lat9");
            hit.lat10 = rs.getFloat("lat10");
            hit.lon1 = rs.getFloat("long1");
            hit.lon2 = rs.getFloat("long2");
            hit.lon3 = rs.getFloat("long3");
            hit.lon4 = rs.getFloat("long4");
            hit.lon5 = rs.getFloat("long5");
            hit.lon6 = rs.getFloat("long6");
            hit.lon7 = rs.getFloat("long7");
            hit.lon8 = rs.getFloat("long8");
            hit.lon9 = rs.getFloat("long9");
            hit.lon10 = rs.getFloat("long10");
            hit.fedirp = rs.getString("fedirp");
            hit.fetype = rs.getString("fetype");
            hit.fedirs = rs.getString("fedirs");
            ret.add(hit);

            //            
            System.out.println(ret.toString());
            //
        }
    } catch (Exception e) {
        e.printStackTrace();
    } finally {
        //DbUtils.closeQuietly(conn);
        DbUtils.closeQuietly(rs);
        DbUtils.closeQuietly(ps);
    }
    //return ret;
}

From source file:com.l2jserver.model.template.NPCTemplateConverter.java

public static void main(String[] args) throws SQLException, IOException, ClassNotFoundException, JAXBException {
    controllers.put("L2Teleporter", TeleporterController.class);
    controllers.put("L2CastleTeleporter", TeleporterController.class);
    controllers.put("L2Npc", BaseNPCController.class);
    controllers.put("L2Monster", MonsterController.class);
    controllers.put("L2FlyMonster", MonsterController.class);
    Class.forName("com.mysql.jdbc.Driver");

    final File target = new File("generated/template/npc");

    System.out.println("Scaning legacy HTML files...");
    htmlScannedFiles = FileUtils.listFiles(L2J_HTML_FOLDER, new String[] { "html", "htm" }, true);

    final JAXBContext c = JAXBContext.newInstance(NPCTemplate.class, Teleports.class);

    final Connection conn = DriverManager.getConnection(JDBC_URL, JDBC_USERNAME, JDBC_PASSWORD);
    {//from ww  w . j  ava  2  s  . co  m
        System.out.println("Converting teleport templates...");
        teleportation.teleport = CollectionFactory.newList();

        final Marshaller m = c.createMarshaller();
        m.setProperty(Marshaller.JAXB_FORMATTED_OUTPUT, true);

        final PreparedStatement st = conn.prepareStatement("SELECT * FROM teleport");
        st.execute();
        final ResultSet rs = st.getResultSet();
        while (rs.next()) {
            final TeleportationTemplate template = new TeleportationTemplate();

            template.id = new TeleportationTemplateID(rs.getInt("id"), null);
            template.name = rs.getString("Description");
            TemplateCoordinate coord = new TemplateCoordinate();
            coord.x = rs.getInt("loc_x");
            coord.y = rs.getInt("loc_y");
            coord.z = rs.getInt("loc_z");
            template.point = coord;
            template.price = rs.getInt("price");
            template.item = rs.getInt("itemId");
            if (rs.getBoolean("fornoble")) {
                template.restrictions = new Restrictions();
                template.restrictions.restriction = Arrays.asList("NOBLE");
            }
            teleportation.teleport.add(template);
        }
        m.marshal(teleportation, getXMLSerializer(new FileOutputStream(new File(target, "../teleports.xml"))));
        // System.exit(0);
    }

    System.out.println("Generating template XML files...");
    // c.generateSchema(new SchemaOutputResolver() {
    // @Override
    // public Result createOutput(String namespaceUri,
    // String suggestedFileName) throws IOException {
    // // System.out.println(new File(target, suggestedFileName));
    // // return null;
    // return new StreamResult(new File(target, suggestedFileName));
    // }
    // });

    try {
        final Marshaller m = c.createMarshaller();
        m.setProperty(Marshaller.JAXB_FORMATTED_OUTPUT, true);

        final PreparedStatement st = conn.prepareStatement(
                "SELECT npc.*, npcskills.level AS race " + "FROM npc " + "LEFT JOIN npcskills "
                        + "ON(npc.idTemplate = npcskills.npcid AND npcskills.skillid = ?)");
        st.setInt(1, 4416);
        st.execute();
        final ResultSet rs = st.getResultSet();
        while (rs.next()) {
            Object[] result = fillNPC(rs);
            NPCTemplate t = (NPCTemplate) result[0];
            String type = (String) result[1];

            String folder = createFolder(type);
            if (folder.isEmpty()) {
                m.setProperty(Marshaller.JAXB_SCHEMA_LOCATION, "npc ../npc.xsd");
            } else {
                m.setProperty(Marshaller.JAXB_SCHEMA_LOCATION, "npc ../../npc.xsd");
            }

            final File file = new File(target, "npc/" + folder + "/" + t.getID().getID()
                    + (t.getInfo().getName() != null ? "-" + camelCase(t.getInfo().getName().getValue()) : "")
                    + ".xml");
            file.getParentFile().mkdirs();
            templates.add(t);

            try {
                m.marshal(t, getXMLSerializer(new FileOutputStream(file)));
            } catch (MarshalException e) {
                System.err.println("Could not generate XML template file for "
                        + t.getInfo().getName().getValue() + " - " + t.getID());
                file.delete();
            }
        }

        System.out.println("Generated " + templates.size() + " templates");

        System.gc();
        System.out.println("Free: " + FileUtils.byteCountToDisplaySize(Runtime.getRuntime().freeMemory()));
        System.out.println("Total: " + FileUtils.byteCountToDisplaySize(Runtime.getRuntime().totalMemory()));
        System.out.println("Used: " + FileUtils.byteCountToDisplaySize(
                Runtime.getRuntime().totalMemory() - Runtime.getRuntime().freeMemory()));
        System.out.println("Max: " + FileUtils.byteCountToDisplaySize(Runtime.getRuntime().maxMemory()));
    } finally {
        conn.close();
    }
}

From source file:com.termmed.statistics.runner.Runner.java

/**
 * The main method.//from  w  w w.  ja va2  s  .c  o m
 *
 * @param args the arguments
 */
public static void main(String[] args) {

    logger = new ProcessLogger();
    if (args.length == 0) {
        logger.logInfo("Error happened getting params. Params file doesn't exist");
        System.exit(0);
        //      }else{
        //         args=new String[]{"config/complete_nl-edition11320160930.xml"};
    }
    File infoFolder = new File(I_Constants.PROCESS_INFO_FOLDER);
    if (!infoFolder.exists()) {
        infoFolder.mkdirs();
    }
    OutputInfoFactory.get().setExecutionId(UUID.randomUUID().toString());
    String msg;
    int posIni;
    long start = logger.startTime();
    File file = new File(args[0]);
    Config configFile = getConfig(file);
    OutputInfoFactory.get().setConfig(configFile);
    System.setProperty("textdb.allow_full_path", "true");
    Connection c;
    try {
        boolean clean = false;
        if (args.length >= 2) {
            for (int i = 1; i < args.length; i++) {
                logger.logInfo("Arg " + i + ": " + args[i]);
                if (args[i].toLowerCase().equals("clean")) {
                    clean = true;
                }
            }
        }
        dataFolder = new File(I_Constants.REPO_FOLDER);
        if (!dataFolder.exists()) {
            dataFolder.mkdirs();
        }

        changedDate = true;
        changedPreviousDate = true;
        getParams(file);
        checkDates();
        /*******************************/
        //         changedDate=false;
        //         changedPreviousDate=false;
        /********************************/
        if (clean || changedDate || changedPreviousDate) {
            logger.logInfo("Removing old data");
            removeDBFolder();
            removeRepoFolder();
            removeReducedFolder();
            changedDate = true;
            changedPreviousDate = true;
        }

        Class.forName("org.hsqldb.jdbcDriver");
        logger.logInfo("Connecting to DB. This task can take several minutes... wait please.");
        c = DriverManager.getConnection("jdbc:hsqldb:file:" + I_Constants.DB_FOLDER, "sa", "sa");

        initFileProviders(file);
        //         OutputInfoFactory.get().getStatisticProcess().setOutputFolder(I_Constants.STATS_OUTPUT_FOLDER);

        /*******************************/
        //         DbSetup dbs=new DbSetup(c);
        //         dbs.recreatePath("org/ihtsdo/statistics/db/setup/storedprocedure");
        //         dbs=null;
        /*******************************/

        ImportManager impor = new ImportManager(c, file, changedDate, changedPreviousDate);
        impor.execute();

        impor = null;

        Processor proc = new Processor(c, file);

        proc.execute();

        proc = null;

        msg = logger.endTime(start);
        posIni = msg.indexOf("ProcessingTime:") + 16;
        OutputInfoFactory.get().getStatisticProcess().setTimeTaken(msg.substring(posIni));
        //         OutputInfoFactory.get().getPatternProcess().setOutputFolder(I_Constants.PATTERN_OUTPUT_FOLDER);
        long startPattern = logger.startTime();
        PatternExecutor pe = new PatternExecutor(file);

        pe.execute();

        pe = null;
        msg = logger.endTime(startPattern);
        posIni = msg.indexOf("ProcessingTime:") + 16;
        OutputInfoFactory.get().getPatternProcess().setTimeTaken(msg.substring(posIni));

        OutputInfoFactory.get().setStatus("Complete");
    } catch (Exception e) {
        OutputInfoFactory.get().setStatus("Error: " + e.getMessage() + " - View log for details.");
        e.printStackTrace();
    }
    msg = logger.endTime(start);
    posIni = msg.indexOf("ProcessingTime:") + 16;
    OutputInfoFactory.get().setTimeTaken(msg.substring(posIni));

    try {
        saveInfo();
    } catch (IOException e) {
        e.printStackTrace();
    }

}

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

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

    // loading data from the CSV file 

    CsvReader Employees = null;

    try {
        Employees = new CsvReader("CSVFile\\Employees.csv");
    } catch (FileNotFoundException EB) {
        System.out.println(EB.getMessage());
    }
    int ColumnCount = 3;
    int RowCount = 100;
    int iloop = 0;

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

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

    Employees.close();

    // connection to Database 
    switch (databasechoice) {
    // 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 = "ldoiarosfrzrua";
        String password = "HBkE_pJpK5mMIg3p2q1_odmEFX";
        String dbUrl = "jdbc:postgresql://ec2-54-83-53-120.compute-1.amazonaws.com:5432/d6693oljh5cco4?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 EmployeeDistinct (name,jobtitle,department) values (' "+ Dataarray[i][0]+" ',' "+ Dataarray[i][1]+" ',' "+ Dataarray[i][2]+" ')";
        //         Stmt.executeUpdate(Connection_String);
        //       
        //        }
        //        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 EmployeeDistinct;";
                ResultSet objRS = Stmt.executeQuery(Connection_String);
                while (objRS.next()) {
                    System.out.println("Employee ID: " + objRS.getInt("EmployeeID"));
                    System.out.println("Employee Name: " + objRS.getString("Name"));
                    System.out.println("Employee City: " + objRS.getString("Jobtitle"));
                    System.out.println("Employee City: " + objRS.getString("Department"));
                }

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

            break;

        case "2":

            System.out.println("Enter the 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 EmployeeDistinct where EmployeeID=" + key + ";";
                ResultSet objRS = Stmt.executeQuery(Connection_String);
                while (objRS.next()) {
                    System.out.println("Employee Name: " + objRS.getString("Name"));
                    System.out.println("Employee City: " + objRS.getString("Jobtitle"));
                    System.out.println("Employee City: " + objRS.getString("Department"));
                }

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

        case "3":
            String Name = null;
            System.out.println("Enter Name to find the record");
            InputStreamReader objname = new InputStreamReader(System.in);
            BufferedReader objbufname = new BufferedReader(objname);

            try {
                Name = (objbufname.readLine()).toString();
            } catch (IOException E) {
                System.out.println(E.getMessage());
            }
            try {
                Conn = DriverManager.getConnection(dbUrl, username, password);
                Stmt = Conn.createStatement();
                String Connection_String = " Select * from EmployeeDistinct where Name=" + "'" + Name + "'"
                        + ";";

                ResultSet objRS = Stmt.executeQuery(Connection_String);
                while (objRS.next()) {
                    System.out.println("Employee ID: " + objRS.getInt("EmployeeID"));
                    System.out.println("Employee City: " + objRS.getString("Jobtitle"));
                    System.out.println("Employee City: " + objRS.getString("Department"));
                }

            } 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-18017.us-east-1-4.6.ec2.redislabs.com", 18017);
        jedis.auth("7EFOisRwMu8zvhin");
        System.out.println("Connected to Redis");

        // Storing values in the database 

        //  System.out.println("Storing values in the Database might take a minute ");

        // for(int i=0;i<Length;i++)
        // { 
        // Store data in redis 
        //     int j=i+1;
        //  jedis.hset("Employe:" + j , "Name", Dataarray[i][0]);
        //   jedis.hset("Employe:" + j , "Jobtitle ", Dataarray[i][1]);
        //  jedis.hset("Employe:" + j , "Department", Dataarray[i][2]);

        //  }

        System.out.println("Search by 1.primary key,2.Name 3.display first 20");
        InputStreamReader objkey = new InputStreamReader(System.in);
        BufferedReader objbufkey = new BufferedReader(objkey);
        String interimChoice1 = null;
        try {
            interimChoice1 = objbufkey.readLine();
        } catch (IOException E) {
            System.out.println(E.getMessage());
        }
        switch (interimChoice1) {
        case "1":
            System.out.print("Get details using the 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("Employe:" + Integer.parseInt(ID1));
            for (Map.Entry<String, String> entry : properties.entrySet()) {
                System.out.println("Name:" + jedis.hget("Employee:" + Integer.parseInt(ID1), "Name"));
                System.out.println("Jobtitle:" + jedis.hget("Employee:" + Integer.parseInt(ID1), "Jobtitle"));
                System.out
                        .println("Department:" + jedis.hget("Employee:" + Integer.parseInt(ID1), "Department"));
            }
            break;

        case "2":
            System.out.print("Get details using Department");
            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("Employe:" + i);
                for (Map.Entry<String, String> entry : properties3.entrySet()) {
                    String value = entry.getValue();
                    if (entry.getValue().equals(ID2)) {
                        System.out.println("Name:" + jedis.hget("Employee:" + i, "Name"));
                        System.out.println("Jobtitle:" + jedis.hget("Employee:" + i, "Jobtitle"));
                        System.out.println("Department:" + jedis.hget("Employee:" + i, "Department"));
                    }

                }
            }

            //for (Map.Entry<String, String> entry : properties1.entrySet())
            //{
            //System.out.println(entry.getKey() + "---" + entry.getValue());
            // }
            break;

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

                    // System.out.println(jedis.hget("Employee:" + i,"Name"));
                    System.out.println("Name:" + jedis.hget("Employee:" + i, "Name"));
                    System.out.println("Jobtitle:" + jedis.hget("Employee:" + i, "Jobtitle"));
                    System.out.println("Department:" + jedis.hget("Employee:" + i, "Department"));

                }
            }
            break;
        }

        break;

    // mongo db code goes here 

    case "3":
        MongoClient mongo = new MongoClient(
                new MongoClientURI("mongodb://root2:12345@ds055564.mongolab.com:55564/heroku_766dnj8c"));
        DB db;
        db = mongo.getDB("heroku_766dnj8c");
        // storing values in the database 
        //  for(int i=0;i<100;i++)
        // {
        //     BasicDBObject document = new BasicDBObject();
        //    document.put("_id", i+1);
        //    document.put("Name", Dataarray[i][0]);
        //    document.put("Jobtitle", Dataarray[i][1]);    
        //    document.put("Department", Dataarray[i][2]);    
        //    db.getCollection("EmployeeRaw").insert(document);

        // }
        System.out.println("Search by 1.primary key,2.Name 3.display first 20");
        InputStreamReader objkey6 = new InputStreamReader(System.in);
        BufferedReader objbufkey6 = new BufferedReader(objkey6);
        String interimChoice = null;
        try {
            interimChoice = objbufkey6.readLine();
        } catch (IOException E) {
            System.out.println(E.getMessage());
        }
        switch (interimChoice) {
        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("EmployeeRaw").find(inQuery);
            while (cursor.hasNext()) {
                // System.out.println(cursor.next());
                System.out.println(cursor.next());
            }
            break;
        case "2":
            System.out.println("Enter the Name 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("Name", Name);
            DBCursor cursor1 = db.getCollection("EmployeeRaw").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("EmployeeRaw").find(inQuerya);
                while (cursora.hasNext()) {
                    // System.out.println(cursor.next());
                    System.out.println(cursora.next());
                }
            }
            break;
        }
        break;

    }

}