List of usage examples for java.sql ResultSet getInt
int getInt(String columnLabel) throws SQLException;
ResultSet
object as an int
in the Java programming language. From source file:Main.java
public static void main(String[] args) throws Exception { String driver = "sun.jdbc.odbc.JdbcOdbcDriver"; Connection con;/*from w w w .java 2 s.c o m*/ Statement stmt; ResultSet rs; try { Class.forName(driver); con = DriverManager.getConnection("jdbc:odbc:databaseName", "student", "student"); // Start a transaction con.setAutoCommit(false); stmt = con.createStatement(); stmt.addBatch("UPDATE EMP SET JOB = 1"); // Submit the batch of commands for this statement to the database stmt.executeBatch(); // Commit the transaction con.commit(); // Close the existing to be safe before opening a new one stmt.close(); // Print out the Employees stmt = con.createStatement(); rs = stmt.executeQuery("SELECT * FROM EMP"); // Loop through and print the employee number, job, and hiredate while (rs.next()) { int id = rs.getInt("EMPNO"); int job = rs.getInt("JOB"); String hireDate = rs.getString("HIREDATE"); System.out.println(id + ":" + job + ":" + hireDate); } con.close(); } catch (SQLException ex) { ex.printStackTrace(); } }
From source file:com.mycompany.mavenproject4.web.java
/** * @param args the command line arguments *///from w w w . ja v a 2s. co m public static void main(String[] args) { System.out.println("Enter your choice do you want to work with \n 1.PostGreSQL \n 2.Redis \n 3.Mongodb"); InputStreamReader IORdatabase = new InputStreamReader(System.in); BufferedReader BIOdatabase = new BufferedReader(IORdatabase); String Str1 = null; try { Str1 = BIOdatabase.readLine(); } catch (Exception E7) { System.out.println(E7.getMessage()); } // loading data from the CSV file CsvReader data = null; try { data = new CsvReader("\\data\\Consumer_Complaints.csv"); } catch (FileNotFoundException EB) { System.out.println(EB.getMessage()); } int noofcolumn = 5; int noofrows = 100; int loops = 0; try { data = new CsvReader("\\data\\Consumer_Complaints.csv"); } catch (FileNotFoundException E) { System.out.println(E.getMessage()); } String[][] Dataarray = new String[noofrows][noofcolumn]; try { while (data.readRecord()) { String v; String[] x; v = data.getRawRecord(); x = v.split(","); for (int j = 0; j < noofcolumn; j++) { String value = null; int z = j; value = x[z]; try { Dataarray[loops][j] = value; } catch (Exception E) { System.out.println(E.getMessage()); } // System.out.println(Dataarray[iloop][j]); } loops = loops + 1; } } catch (IOException Em) { System.out.println(Em.getMessage()); } data.close(); // connection to Database switch (Str1) { // postgre code goes here case "1": Connection Conn = null; Statement Stmt = null; URI dbUri = null; String choice = null; InputStreamReader objin = new InputStreamReader(System.in); BufferedReader objbuf = new BufferedReader(objin); try { Class.forName("org.postgresql.Driver"); } catch (Exception E1) { System.out.println(E1.getMessage()); } String username = "ahkyjdavhedkzg"; String password = "2f7c3_MBJbIy1uJsFyn7zebkhY"; String dbUrl = "jdbc:postgresql://ec2-54-83-199-54.compute-1.amazonaws.com:5432/d2l6hq915lp9vi?ssl=true&sslfactory=org.postgresql.ssl.NonValidatingFactory"; // now update data in the postgress Database /* for(int i=0;i<RowCount;i++) { try { Conn= DriverManager.getConnection(dbUrl, username, password); Stmt = Conn.createStatement(); String Connection_String = "insert into Webdata (Id,Product,state,Submitted,Complaintid) values (' "+ Dataarray[i][0]+" ',' "+ Dataarray[i][1]+" ',' "+ Dataarray[i][2]+" ',' "+ Dataarray[i][3]+" ',' "+ Dataarray[i][4]+" ')"; Stmt.executeUpdate(Connection_String); Conn.close(); } catch(SQLException E4) { System.out.println(E4.getMessage()); } } */ // Quering with the Database System.out.println("1. Display Data "); System.out.println("2. Select data based on primary key"); System.out.println("3. Select data based on Other attributes e.g Name"); System.out.println("Enter your Choice "); try { choice = objbuf.readLine(); } catch (IOException E) { System.out.println(E.getMessage()); } switch (choice) { case "1": try { Conn = DriverManager.getConnection(dbUrl, username, password); Stmt = Conn.createStatement(); String Connection_String = " Select * from Webdata;"; ResultSet objRS = Stmt.executeQuery(Connection_String); while (objRS.next()) { System.out.println(" ID: " + objRS.getInt("ID")); System.out.println("Product Name: " + objRS.getString("Product")); System.out.println("Which state: " + objRS.getString("State")); System.out.println("Sumbitted through: " + objRS.getString("Submitted")); System.out.println("Complain Number: " + objRS.getString("Complaintid")); Conn.close(); } } catch (Exception E2) { System.out.println(E2.getMessage()); } break; case "2": System.out.println("Enter Id(Primary Key) :"); InputStreamReader objkey = new InputStreamReader(System.in); BufferedReader objbufkey = new BufferedReader(objkey); int key = 0; try { key = Integer.parseInt(objbufkey.readLine()); } catch (IOException E) { System.out.println(E.getMessage()); } try { Conn = DriverManager.getConnection(dbUrl, username, password); Stmt = Conn.createStatement(); String Connection_String = " Select * from Webdata where Id=" + key + ";"; ResultSet objRS = Stmt.executeQuery(Connection_String); while (objRS.next()) { //System.out.println(" ID: " + objRS.getInt("ID")); System.out.println("Product Name: " + objRS.getString("Product")); System.out.println("Which state: " + objRS.getString("State")); System.out.println("Sumbitted through: " + objRS.getString("Submitted")); System.out.println("Complain Number: " + objRS.getString("Complaintid")); Conn.close(); } } catch (Exception E2) { System.out.println(E2.getMessage()); } break; case "3": //String Name=null; System.out.println("Enter Complaintid to find the record"); // Scanner input = new Scanner(System.in); // int Number = 0; try { InputStreamReader objname = new InputStreamReader(System.in); BufferedReader objbufname = new BufferedReader(objname); Number = Integer.parseInt(objbufname.readLine()); } catch (Exception E10) { System.out.println(E10.getMessage()); } //System.out.println(Name); try { Conn = DriverManager.getConnection(dbUrl, username, password); Stmt = Conn.createStatement(); String Connection_String = " Select * from Webdata where complaintid=" + Number + ";"; //2 System.out.println(Connection_String); ResultSet objRS = Stmt.executeQuery(Connection_String); while (objRS.next()) { int id = objRS.getInt("id"); System.out.println(" ID: " + id); System.out.println("Product Name: " + objRS.getString("Product")); String state = objRS.getString("state"); System.out.println("Which state: " + state); String Submitted = objRS.getString("submitted"); System.out.println("Sumbitted through: " + Submitted); String Complaintid = objRS.getString("complaintid"); System.out.println("Complain Number: " + Complaintid); } Conn.close(); } catch (Exception E2) { System.out.println(E2.getMessage()); } break; } try { Conn.close(); } catch (SQLException E6) { System.out.println(E6.getMessage()); } break; // Redis code goes here case "2": int Length = 0; String ID = null; Length = 100; // Connection to Redis Jedis jedis = new Jedis("pub-redis-13274.us-east-1-2.1.ec2.garantiadata.com", 13274); jedis.auth("rfJ8OLjlv9NjRfry"); System.out.println("Connected to Redis Database"); // Storing values in the database /* for(int i=0;i<Length;i++) { //Store data in redis int j=i+1; jedis.hset("Record:" + j , "Product", Dataarray[i][1]); jedis.hset("Record:" + j , "State ", Dataarray[i][2]); jedis.hset("Record:" + j , "Submitted", Dataarray[i][3]); jedis.hset("Record:" + j , "Complaintid", Dataarray[i][4]); } */ System.out.println( "Search by \n 11.Get records through primary key \n 22.Get Records through Complaintid \n 33.Display "); InputStreamReader objkey = new InputStreamReader(System.in); BufferedReader objbufkey = new BufferedReader(objkey); String str2 = null; try { str2 = objbufkey.readLine(); } catch (IOException E) { System.out.println(E.getMessage()); } switch (str2) { case "11": System.out.print("Enter Primary Key : "); InputStreamReader IORKey = new InputStreamReader(System.in); BufferedReader BIORKey = new BufferedReader(IORKey); String ID1 = null; try { ID1 = BIORKey.readLine(); } catch (IOException E3) { System.out.println(E3.getMessage()); } Map<String, String> properties = jedis.hgetAll("Record:" + Integer.parseInt(ID1)); for (Map.Entry<String, String> entry : properties.entrySet()) { System.out.println("Product:" + jedis.hget("Record:" + Integer.parseInt(ID1), "Product")); System.out.println("State:" + jedis.hget("Record:" + Integer.parseInt(ID1), "State")); System.out.println("Submitted:" + jedis.hget("Record:" + Integer.parseInt(ID1), "Submitted")); System.out .println("Complaintid:" + jedis.hget("Record:" + Integer.parseInt(ID1), "Complaintid")); } break; case "22": System.out.print(" Enter Complaintid : "); InputStreamReader IORName1 = new InputStreamReader(System.in); BufferedReader BIORName1 = new BufferedReader(IORName1); String ID2 = null; try { ID2 = BIORName1.readLine(); } catch (IOException E3) { System.out.println(E3.getMessage()); } for (int i = 0; i < 100; i++) { Map<String, String> properties3 = jedis.hgetAll("Record:" + i); for (Map.Entry<String, String> entry : properties3.entrySet()) { String value = entry.getValue(); if (entry.getValue().equals(ID2)) { System.out .println("Product:" + jedis.hget("Record:" + Integer.parseInt(ID2), "Product")); System.out.println("State:" + jedis.hget("Record:" + Integer.parseInt(ID2), "State")); System.out.println( "Submitted:" + jedis.hget("Record:" + Integer.parseInt(ID2), "Submitted")); System.out.println( "Complaintid:" + jedis.hget("Record:" + Integer.parseInt(ID2), "Complaintid")); } } } break; case "33": for (int i = 1; i < 21; i++) { Map<String, String> properties3 = jedis.hgetAll("Record:" + i); for (Map.Entry<String, String> entry : properties3.entrySet()) { System.out.println("Product:" + jedis.hget("Record:" + i, "Product")); System.out.println("State:" + jedis.hget("Record:" + i, "State")); System.out.println("Submitted:" + jedis.hget("Record:" + i, "Submitted")); System.out.println("Complaintid:" + jedis.hget("Record:" + i, "Complaintid")); } } break; } break; // mongo db case "3": MongoClient mongo = new MongoClient(new MongoClientURI( "mongodb://naikhpratik:naikhpratik@ds053964.mongolab.com:53964/heroku_6t7n587f")); DB db; db = mongo.getDB("heroku_6t7n587f"); // storing values in the database /*for(int i=0;i<100;i++) { BasicDBObject document = new BasicDBObject(); document.put("Id", i+1); document.put("Product", Dataarray[i][1]); document.put("State", Dataarray[i][2]); document.put("Submitted", Dataarray[i][3]); document.put("Complaintid", Dataarray[i][4]); db.getCollection("Naiknaik").insert(document); }*/ System.out.println("Search by \n 1.Enter Primary key \n 2.Enter Complaintid \n 3.Display"); InputStreamReader objkey6 = new InputStreamReader(System.in); BufferedReader objbufkey6 = new BufferedReader(objkey6); String str3 = null; try { str3 = objbufkey6.readLine(); } catch (IOException E) { System.out.println(E.getMessage()); } switch (str3) { case "1": System.out.println("Enter the Primary Key"); InputStreamReader IORPkey = new InputStreamReader(System.in); BufferedReader BIORPkey = new BufferedReader(IORPkey); int Pkey = 0; try { Pkey = Integer.parseInt(BIORPkey.readLine()); } catch (IOException E) { System.out.println(E.getMessage()); } BasicDBObject inQuery = new BasicDBObject(); inQuery.put("Id", Pkey); DBCursor cursor = db.getCollection("Naiknaik").find(inQuery); while (cursor.hasNext()) { // System.out.println(cursor.next()); System.out.println(cursor.next()); } break; case "2": System.out.println("Enter the Product to Search"); InputStreamReader objName = new InputStreamReader(System.in); BufferedReader objbufName = new BufferedReader(objName); String Name = null; try { Name = objbufName.readLine(); } catch (IOException E) { System.out.println(E.getMessage()); } BasicDBObject inQuery1 = new BasicDBObject(); inQuery1.put("Product", Name); DBCursor cursor1 = db.getCollection("Naiknaik").find(inQuery1); while (cursor1.hasNext()) { // System.out.println(cursor.next()); System.out.println(cursor1.next()); } break; case "3": for (int i = 1; i < 21; i++) { BasicDBObject inQuerya = new BasicDBObject(); inQuerya.put("_id", i); DBCursor cursora = db.getCollection("Naiknaik").find(inQuerya); while (cursora.hasNext()) { // System.out.println(cursor.next()); System.out.println(cursora.next()); } } break; } break; } }
From source file:InsertRows.java
public static void main(String args[]) { String url = "jdbc:mySubprotocol:myDataSource"; Connection con;//from w w w.j a va 2 s . co m Statement stmt; try { Class.forName("myDriver.ClassName"); } catch (java.lang.ClassNotFoundException e) { System.err.print("ClassNotFoundException: "); System.err.println(e.getMessage()); } try { con = DriverManager.getConnection(url, "myLogin", "myPassword"); stmt = con.createStatement(ResultSet.TYPE_SCROLL_SENSITIVE, ResultSet.CONCUR_UPDATABLE); ResultSet uprs = stmt.executeQuery("SELECT * FROM COFFEES"); uprs.moveToInsertRow(); uprs.updateString("COF_NAME", "Kona"); uprs.updateInt("SUP_ID", 150); uprs.updateFloat("PRICE", 10.99f); uprs.updateInt("SALES", 0); uprs.updateInt("TOTAL", 0); uprs.insertRow(); uprs.updateString("COF_NAME", "Kona_Decaf"); uprs.updateInt("SUP_ID", 150); uprs.updateFloat("PRICE", 11.99f); uprs.updateInt("SALES", 0); uprs.updateInt("TOTAL", 0); uprs.insertRow(); uprs.beforeFirst(); System.out.println("Table COFFEES after insertion:"); while (uprs.next()) { String name = uprs.getString("COF_NAME"); int id = uprs.getInt("SUP_ID"); float price = uprs.getFloat("PRICE"); int sales = uprs.getInt("SALES"); int total = uprs.getInt("TOTAL"); System.out.print(name + " " + id + " " + price); System.out.println(" " + sales + " " + total); } uprs.close(); stmt.close(); con.close(); } catch (SQLException ex) { System.err.println("SQLException: " + ex.getMessage()); } }
From source file:friendsandfollowers.DBFollowersIDs.java
public static void main(String[] args) throws ClassNotFoundException, SQLException, JSONException, FileNotFoundException, UnsupportedEncodingException { // Check arguments that passed in if ((args == null) || (args.length == 0)) { System.err.println("2 Parameters are required plus one optional " + "parameter to launch a Job."); System.err.println("First: String 'OUTPUT: /output/path/'"); System.err.println("Second: (int) Number of ids to fetch. " + "Provide number which increment by 5000 " + "(5000, 10000, 15000 etc) " + "or -1 to fetch all ids."); System.err.println("Third (optional): 'screen_name / user_id_str'"); System.err.println("If 3rd argument not provided then provide" + " Twitter users through database."); System.exit(-1);/* w ww . j ava 2 s . c o m*/ } MysqlDB DB = new MysqlDB(); AppOAuth AppOAuths = new AppOAuth(); Misc helpers = new Misc(); String endpoint = "/followers/ids"; String OutputDirPath = null; try { OutputDirPath = StringEscapeUtils.escapeJava(args[0]); } catch (Exception e) { System.err.println("Argument" + args[0] + " must be an String."); System.exit(-1); } int IDS_TO_FETCH_INT = -1; try { IDS_TO_FETCH_INT = Integer.parseInt(args[1]); } catch (NumberFormatException e) { System.err.println("Argument" + args[1] + " must be an integer."); System.exit(-1); } int IDS_TO_FETCH = 0; if (IDS_TO_FETCH_INT > 5000) { float IDS_TO_FETCH_F = (float) IDS_TO_FETCH_INT / 5000; IDS_TO_FETCH = (int) Math.ceil(IDS_TO_FETCH_F); } else if ((IDS_TO_FETCH_INT <= 5000) && (IDS_TO_FETCH_INT > 0)) { IDS_TO_FETCH = 1; } String targetedUser = ""; if (args.length == 3) { try { targetedUser = StringEscapeUtils.escapeJava(args[2]); } catch (Exception e) { System.err.println("Argument" + args[2] + " must be an String."); System.exit(-1); } } try { TwitterFactory tf = AppOAuths.loadOAuthUser(endpoint); Twitter twitter = tf.getInstance(); int RemainingCalls = AppOAuths.RemainingCalls; int RemainingCallsCounter = 0; System.out.println("First Time Remianing Calls: " + RemainingCalls); String Screen_name = AppOAuths.screen_name; System.out.println("First Time Loaded OAuth Screen_name: " + Screen_name); IDs ids; System.out.println("Listing followers ids."); // if targetedUser not provided by argument, then look into database. if (StringUtils.isEmpty(targetedUser)) { String selectQuery = "SELECT * FROM `followers_parent` WHERE " + "`targeteduser` != '' AND " + "`nextcursor` != '0' AND " + "`nextcursor` != '2'"; ResultSet results = DB.selectQ(selectQuery); int numRows = DB.numRows(results); if (numRows < 1) { System.err.println("No User in database to get followersIDS"); System.exit(-1); } OUTERMOST: while (results.next()) { int followers_parent_id = results.getInt("id"); targetedUser = results.getString("targeteduser"); long cursor = results.getLong("nextcursor"); System.out.println("Targeted User: " + targetedUser); int idsLoopCounter = 0; int totalIDs = 0; // put idsJSON in a file PrintWriter writer = new PrintWriter(OutputDirPath + "/" + targetedUser, "UTF-8"); // call different functions for screen_name and id_str Boolean chckedNumaric = helpers.isNumeric(targetedUser); do { ids = null; try { if (chckedNumaric) { long LongValueTargetedUser = Long.valueOf(targetedUser).longValue(); ids = twitter.getFollowersIDs(LongValueTargetedUser, cursor); } else { ids = twitter.getFollowersIDs(targetedUser, cursor); } } catch (TwitterException te) { // do not throw if user has protected tweets, // or if they deleted their account if (te.getStatusCode() == HttpResponseCode.UNAUTHORIZED || te.getStatusCode() == HttpResponseCode.NOT_FOUND) { System.out.println(targetedUser + " is protected or account is deleted"); } else { System.out.println("Followers Get Exception: " + te.getMessage()); } // If rate limit reached then switch Auth user RemainingCallsCounter++; if (RemainingCallsCounter >= RemainingCalls) { // load auth user tf = AppOAuths.loadOAuthUser(endpoint); twitter = tf.getInstance(); System.out.println( "New User Loaded OAuth" + " Screen_name: " + AppOAuths.screen_name); RemainingCalls = AppOAuths.RemainingCalls; RemainingCallsCounter = 0; System.out.println("New Remianing Calls: " + RemainingCalls); } // update cursor in "followers_parent" String fieldValues = "`nextcursor` = 2"; String where = "id = " + followers_parent_id; DB.Update("`followers_parent`", fieldValues, where); // If error then switch to next user continue OUTERMOST; } if (ids.getIDs().length > 0) { idsLoopCounter++; totalIDs += ids.getIDs().length; System.out.println(idsLoopCounter + ": IDS length: " + ids.getIDs().length); JSONObject responseDetailsJson = new JSONObject(); JSONArray jsonArray = new JSONArray(); for (long id : ids.getIDs()) { jsonArray.put(id); } Object idsJSON = responseDetailsJson.put("ids", jsonArray); writer.println(idsJSON); } // If rate limit reached then switch Auth user RemainingCallsCounter++; if (RemainingCallsCounter >= RemainingCalls) { // load auth user tf = AppOAuths.loadOAuthUser(endpoint); twitter = tf.getInstance(); System.out.println("New User Loaded OAuth " + "Screen_name: " + AppOAuths.screen_name); RemainingCalls = AppOAuths.RemainingCalls; RemainingCallsCounter = 0; System.out.println("New Remianing Calls: " + RemainingCalls); } if (IDS_TO_FETCH_INT != -1) { if (idsLoopCounter == IDS_TO_FETCH) { break; } } } while ((cursor = ids.getNextCursor()) != 0); writer.close(); System.out.println("Total ids dumped of " + targetedUser + " are: " + totalIDs); System.out.println(); // update cursor in "followers_parent" String fieldValues = "`nextcursor` = " + cursor; String where = "id = " + followers_parent_id; DB.Update("`followers_parent`", fieldValues, where); } // loop through every result found in db } else { // Second Argument Set, so we are here. System.out.println("screen_name / user_id_str passed by argument"); int idsLoopCounter = 0; int totalIDs = 0; // put idsJSON in a file PrintWriter writer = new PrintWriter( OutputDirPath + "/" + targetedUser + "_ids_" + helpers.getUnixTimeStamp(), "UTF-8"); // call different functions for screen_name and id_str Boolean chckedNumaric = helpers.isNumeric(targetedUser); long cursor = -1; do { ids = null; try { if (chckedNumaric) { long LongValueTargetedUser = Long.valueOf(targetedUser).longValue(); ids = twitter.getFollowersIDs(LongValueTargetedUser, cursor); } else { ids = twitter.getFollowersIDs(targetedUser, cursor); } } catch (TwitterException te) { // do not throw if user has protected tweets, or if they deleted their account if (te.getStatusCode() == HttpResponseCode.UNAUTHORIZED || te.getStatusCode() == HttpResponseCode.NOT_FOUND) { System.out.println(targetedUser + " is protected or account is deleted"); } else { System.out.println("Followers Get Exception: " + te.getMessage()); } System.exit(-1); } if (ids.getIDs().length > 0) { idsLoopCounter++; totalIDs += ids.getIDs().length; System.out.println(idsLoopCounter + ": IDS length: " + ids.getIDs().length); JSONObject responseDetailsJson = new JSONObject(); JSONArray jsonArray = new JSONArray(); for (long id : ids.getIDs()) { jsonArray.put(id); } Object idsJSON = responseDetailsJson.put("ids", jsonArray); writer.println(idsJSON); } // If rate limit reach then switch Auth user RemainingCallsCounter++; if (RemainingCallsCounter >= RemainingCalls) { // load auth user tf = AppOAuths.loadOAuthUser(endpoint); twitter = tf.getInstance(); System.out.println("New User Loaded OAuth Screen_name: " + AppOAuths.screen_name); RemainingCalls = AppOAuths.RemainingCalls; RemainingCallsCounter = 0; System.out.println("New Remianing Calls: " + RemainingCalls); } if (IDS_TO_FETCH_INT != -1) { if (idsLoopCounter == IDS_TO_FETCH) { break; } } } while ((cursor = ids.getNextCursor()) != 0); writer.close(); System.out.println("Total ids dumped of " + targetedUser + " are: " + totalIDs); System.out.println(); } } catch (TwitterException te) { // te.printStackTrace(); System.err.println("Failed to get followers' ids: " + te.getMessage()); System.exit(-1); } System.out.println("!!!! DONE !!!!"); }
From source file:friendsandfollowers.DBFriendsIDs.java
public static void main(String[] args) throws ClassNotFoundException, SQLException, JSONException, FileNotFoundException, UnsupportedEncodingException { // Check arguments that passed in if ((args == null) || (args.length == 0)) { System.err.println("2 Parameters are required plus one optional " + "parameter to launch a Job."); System.err.println("First: String 'OUTPUT: /output/path/'"); System.err.println("Second: (int) Number of ids to fetch. " + "Provide number which increment by 5000 " + "(5000, 10000, 15000 etc) " + "or -1 to fetch all ids."); System.err.println("Third (optional): 'screen_name / user_id_str'"); System.err.println("If 3rd argument not provided then provide" + " Twitter users through database."); System.exit(-1);/*from w w w .j a v a 2 s .c om*/ } MysqlDB DB = new MysqlDB(); AppOAuth AppOAuths = new AppOAuth(); Misc helpers = new Misc(); String endpoint = "/friends/ids"; String OutputDirPath = null; try { OutputDirPath = StringEscapeUtils.escapeJava(args[0]); } catch (Exception e) { System.err.println("Argument" + args[0] + " must be an String."); System.exit(-1); } int IDS_TO_FETCH_INT = -1; try { IDS_TO_FETCH_INT = Integer.parseInt(args[1]); } catch (NumberFormatException e) { System.err.println("Argument" + args[1] + " must be an integer."); System.exit(-1); } int IDS_TO_FETCH = 0; if (IDS_TO_FETCH_INT > 5000) { float IDS_TO_FETCH_F = (float) IDS_TO_FETCH_INT / 5000; IDS_TO_FETCH = (int) Math.ceil(IDS_TO_FETCH_F); } else if ((IDS_TO_FETCH_INT <= 5000) && (IDS_TO_FETCH_INT > 0)) { IDS_TO_FETCH = 1; } String targetedUser = ""; if (args.length == 3) { try { targetedUser = StringEscapeUtils.escapeJava(args[2]); } catch (Exception e) { System.err.println("Argument" + args[2] + " must be an String."); System.exit(-1); } } try { TwitterFactory tf = AppOAuths.loadOAuthUser(endpoint); Twitter twitter = tf.getInstance(); int RemainingCalls = AppOAuths.RemainingCalls; int RemainingCallsCounter = 0; System.out.println("First Time Remianing Calls: " + RemainingCalls); String Screen_name = AppOAuths.screen_name; System.out.println("First Time Loaded OAuth Screen_name: " + Screen_name); IDs ids; System.out.println("Listing friends ids."); // if targetedUser not provided by argument, then look into database. if (StringUtils.isEmpty(targetedUser)) { String selectQuery = "SELECT * FROM `followings_parent` WHERE " + "`targeteduser` != '' AND " + "`nextcursor` != '0' AND " + "`nextcursor` != '2'"; ResultSet results = DB.selectQ(selectQuery); int numRows = DB.numRows(results); if (numRows < 1) { System.err.println("No User in database to get friendsIDS"); System.exit(-1); } OUTERMOST: while (results.next()) { int following_parent_id = results.getInt("id"); targetedUser = results.getString("targeteduser"); long cursor = results.getLong("nextcursor"); System.out.println("Targeted User: " + targetedUser); int idsLoopCounter = 0; int totalIDs = 0; // put idsJSON in a file PrintWriter writer = new PrintWriter(OutputDirPath + "/" + targetedUser, "UTF-8"); // call different functions for screen_name and id_str Boolean chckedNumaric = helpers.isNumeric(targetedUser); do { ids = null; try { if (chckedNumaric) { long LongValueTargetedUser = Long.valueOf(targetedUser).longValue(); ids = twitter.getFriendsIDs(LongValueTargetedUser, cursor); } else { ids = twitter.getFriendsIDs(targetedUser, cursor); } } catch (TwitterException te) { // do not throw if user has protected tweets, // or if they deleted their account if (te.getStatusCode() == HttpResponseCode.UNAUTHORIZED || te.getStatusCode() == HttpResponseCode.NOT_FOUND) { System.out.println(targetedUser + " is protected or account is deleted"); } else { System.out.println("Friends Get Exception: " + te.getMessage()); } // If rate limit reached then switch Auth user RemainingCallsCounter++; if (RemainingCallsCounter >= RemainingCalls) { // load auth user tf = AppOAuths.loadOAuthUser(endpoint); twitter = tf.getInstance(); System.out.println( "New User Loaded OAuth" + " Screen_name: " + AppOAuths.screen_name); RemainingCalls = AppOAuths.RemainingCalls; RemainingCallsCounter = 0; System.out.println("New Remianing Calls: " + RemainingCalls); } // update cursor in "followings_parent" String fieldValues = "`nextcursor` = 2"; String where = "id = " + following_parent_id; DB.Update("`followings_parent`", fieldValues, where); // If error then switch to next user continue OUTERMOST; } if (ids.getIDs().length > 0) { idsLoopCounter++; totalIDs += ids.getIDs().length; System.out.println(idsLoopCounter + ": IDS length: " + ids.getIDs().length); JSONObject responseDetailsJson = new JSONObject(); JSONArray jsonArray = new JSONArray(); for (long id : ids.getIDs()) { jsonArray.put(id); } Object idsJSON = responseDetailsJson.put("ids", jsonArray); writer.println(idsJSON); } // If rate limit reached then switch Auth user. RemainingCallsCounter++; if (RemainingCallsCounter >= RemainingCalls) { // load auth user tf = AppOAuths.loadOAuthUser(endpoint); twitter = tf.getInstance(); System.out.println("New User Loaded OAuth " + "Screen_name: " + AppOAuths.screen_name); RemainingCalls = AppOAuths.RemainingCalls; RemainingCallsCounter = 0; System.out.println("New Remianing Calls: " + RemainingCalls); } if (IDS_TO_FETCH_INT != -1) { if (idsLoopCounter == IDS_TO_FETCH) { break; } } } while ((cursor = ids.getNextCursor()) != 0); writer.close(); System.out.println("Total ids dumped of " + targetedUser + " are: " + totalIDs); System.out.println(); // update cursor in "followings_parent" String fieldValues = "`nextcursor` = " + cursor; String where = "id = " + following_parent_id; DB.Update("`followings_parent`", fieldValues, where); } // loop through every result found in db } else { // Second Argument Sets, so we are here. System.out.println("screen_name / user_id_str " + "passed by argument"); int idsLoopCounter = 0; int totalIDs = 0; // put idsJSON in a file PrintWriter writer = new PrintWriter( OutputDirPath + "/" + targetedUser + "_ids_" + helpers.getUnixTimeStamp(), "UTF-8"); // call different functions for screen_name and id_str Boolean chckedNumaric = helpers.isNumeric(targetedUser); long cursor = -1; do { ids = null; try { if (chckedNumaric) { long LongValueTargetedUser = Long.valueOf(targetedUser).longValue(); ids = twitter.getFriendsIDs(LongValueTargetedUser, cursor); } else { ids = twitter.getFriendsIDs(targetedUser, cursor); } } catch (TwitterException te) { // do not throw if user has protected tweets, // or if they deleted their account if (te.getStatusCode() == HttpResponseCode.UNAUTHORIZED || te.getStatusCode() == HttpResponseCode.NOT_FOUND) { System.out.println(targetedUser + " is protected or account is deleted"); } else { System.out.println("Friends Get Exception: " + te.getMessage()); } System.exit(-1); } if (ids.getIDs().length > 0) { idsLoopCounter++; totalIDs += ids.getIDs().length; System.out.println(idsLoopCounter + ": IDS length: " + ids.getIDs().length); JSONObject responseDetailsJson = new JSONObject(); JSONArray jsonArray = new JSONArray(); for (long id : ids.getIDs()) { jsonArray.put(id); } Object idsJSON = responseDetailsJson.put("ids", jsonArray); writer.println(idsJSON); } // If rate limit reach then switch Auth user RemainingCallsCounter++; if (RemainingCallsCounter >= RemainingCalls) { // load auth user tf = AppOAuths.loadOAuthUser(endpoint); twitter = tf.getInstance(); System.out.println("New User Loaded OAuth Screen_name: " + AppOAuths.screen_name); RemainingCalls = AppOAuths.RemainingCalls; RemainingCallsCounter = 0; System.out.println("New Remianing Calls: " + RemainingCalls); } if (IDS_TO_FETCH_INT != -1) { if (idsLoopCounter == IDS_TO_FETCH) { break; } } } while ((cursor = ids.getNextCursor()) != 0); writer.close(); System.out.println("Total ids dumped of " + targetedUser + " are: " + totalIDs); System.out.println(); } } catch (TwitterException te) { // te.printStackTrace(); System.err.println("Failed to get friends' ids: " + te.getMessage()); System.exit(-1); } System.out.println("!!!! DONE !!!!"); }
From source file:Main.java
public static void main(String[] args) throws Exception { Connection conn = getMySqlConnection(); System.out.println("Got Connection."); Statement st = conn.createStatement(); st.executeUpdate("drop table survey;"); st.executeUpdate("create table survey (id int,name varchar(30));"); st.executeUpdate("insert into survey (id,name ) values (1,'nameValue')"); ResultSet indexInformation = null; DatabaseMetaData meta = conn.getMetaData(); // The '_' character represents any single character. // The '%' character represents any sequence of zero // or more characters. indexInformation = meta.getIndexInfo(conn.getCatalog(), null, "survey", true, true); while (indexInformation.next()) { String dbCatalog = indexInformation.getString("TABLE_CATALOG"); String dbSchema = indexInformation.getString("TABLE_SCHEMA"); String dbTableName = indexInformation.getString("TABLE_NAME"); boolean dbNoneUnique = indexInformation.getBoolean("NON_UNIQUE"); String dbIndexQualifier = indexInformation.getString("INDEX_QUALIFIER"); String dbIndexName = indexInformation.getString("INDEX_NAME"); short dbType = indexInformation.getShort("TYPE"); short dbOrdinalPosition = indexInformation.getShort("ORDINAL_POSITION"); String dbColumnName = indexInformation.getString("COLUMN_NAME"); String dbAscOrDesc = indexInformation.getString("ASC_OR_DESC"); int dbCardinality = indexInformation.getInt("CARDINALITY"); int dbPages = indexInformation.getInt("PAGES"); String dbFilterCondition = indexInformation.getString("FILTER_CONDITION"); System.out.println("index name=" + dbIndexName); System.out.println("table=" + dbTableName); System.out.println("column=" + dbColumnName); System.out.println("catalog=" + dbCatalog); System.out.println("schema=" + dbSchema); System.out.println("nonUnique=" + dbNoneUnique); System.out.println("indexQualifier=" + dbIndexQualifier); System.out.println("type=" + dbType); System.out.println("ordinalPosition=" + dbOrdinalPosition); System.out.println("ascendingOrDescending=" + dbAscOrDesc); System.out.println("cardinality=" + dbCardinality); System.out.println("pages=" + dbPages); System.out.println("filterCondition=" + dbFilterCondition); }//from ww w. ja v a2 s .c om st.close(); conn.close(); }
From source file:de.tudarmstadt.ukp.csniper.resbuild.EvaluationItemFixer2.java
public static void main(String[] args) { connect(HOST, DATABASE, USER, PASSWORD); Map<Integer, String> items = new HashMap<Integer, String>(); Map<Integer, String> failed = new HashMap<Integer, String>(); // fetch coveredTexts of dubious items and clean it PreparedStatement select = null; PreparedStatement update = null; try {/*ww w . j a v a2s .c o m*/ StringBuilder selectQuery = new StringBuilder(); selectQuery.append("SELECT * FROM cachedparse WHERE pennTree = 'ERROR' OR pennTree = ''"); select = connection.prepareStatement(selectQuery.toString()); log.info("Running query [" + selectQuery.toString() + "]."); ResultSet rs = select.executeQuery(); // CSVWriter writer; String text; JCas jcas = JCasFactory.createJCas(); String updateQuery = "UPDATE CachedParse SET pennTree = ? WHERE collectionId = ? AND documentId = ? AND beginOffset = ? AND endOffset = ?"; update = connection.prepareStatement(updateQuery); // File base = new File(""); AnalysisEngine sentences = createEngine(DummySentenceSplitter.class); AnalysisEngine tokenizer = createEngine(StanfordSegmenter.class, StanfordSegmenter.PARAM_CREATE_SENTENCES, false, StanfordSegmenter.PARAM_CREATE_TOKENS, true); AnalysisEngine parser = createEngine(StanfordParser.class, StanfordParser.PARAM_WRITE_CONSTITUENT, true, // StanfordParser.PARAM_CREATE_DEPENDENCY_TAGS, true, StanfordParser.PARAM_WRITE_PENN_TREE, true, StanfordParser.PARAM_LANGUAGE, "en", StanfordParser.PARAM_VARIANT, "factored"); while (rs.next()) { String collectionId = rs.getString("collectionId"); String documentId = rs.getString("documentId"); int beginOffset = rs.getInt("beginOffset"); int endOffset = rs.getInt("endOffset"); text = retrieveCoveredText(collectionId, documentId, beginOffset, endOffset); jcas.setDocumentText(text); jcas.setDocumentLanguage("en"); sentences.process(jcas); tokenizer.process(jcas); parser.process(jcas); // writer = new CSVWriter(new FileWriter(new File(base, documentId + ".csv")); System.out.println("Updating " + text); for (PennTree p : JCasUtil.select(jcas, PennTree.class)) { String tree = StringUtils.normalizeSpace(p.getPennTree()); update.setString(1, tree); update.setString(2, collectionId); update.setString(3, documentId); update.setInt(4, beginOffset); update.setInt(5, endOffset); update.executeUpdate(); System.out.println("with tree " + tree); break; } jcas.reset(); } } catch (SQLException e) { log.error("Exception while selecting: " + e.getMessage()); } catch (UIMAException e) { e.printStackTrace(); } finally { closeQuietly(select); closeQuietly(update); } // write logs // BufferedWriter bwf = null; // BufferedWriter bws = null; // try { // bwf = new BufferedWriter(new OutputStreamWriter(new FileOutputStream(new File( // LOG_FAILED)), "UTF-8")); // for (Entry<Integer, String> e : failed.entrySet()) { // bwf.write(e.getKey() + " - " + e.getValue() + "\n"); // } // // bws = new BufferedWriter(new OutputStreamWriter(new FileOutputStream(new File( // LOG_SUCCESSFUL)), "UTF-8")); // for (Entry<Integer, String> e : items.entrySet()) { // bws.write(e.getKey() + " - " + e.getValue() + "\n"); // } // } // catch (IOException e) { // log.error("Got an IOException while writing the log files."); // } // finally { // IOUtils.closeQuietly(bwf); // IOUtils.closeQuietly(bws); // } log.info("Texts for [" + items.size() + "] items need to be cleaned up."); // update the dubious items with the cleaned coveredText // PreparedStatement update = null; // try { // String updateQuery = "UPDATE EvaluationItem SET coveredText = ? WHERE id = ?"; // // update = connection.prepareStatement(updateQuery); // int i = 0; // for (Entry<Integer, String> e : items.entrySet()) { // int id = e.getKey(); // String coveredText = e.getValue(); // // // update item in database // update.setString(1, coveredText); // update.setInt(2, id); // update.executeUpdate(); // log.debug("Updating " + id + " with [" + coveredText + "]"); // // // show percentage of updated items // i++; // int part = (int) Math.ceil((double) items.size() / 100); // if (i % part == 0) { // log.info(i / part + "% finished (" + i + "/" + items.size() + ")."); // } // } // } // catch (SQLException e) { // log.error("Exception while updating: " + e.getMessage()); // } // finally { // closeQuietly(update); // } closeQuietly(connection); }
From source file:com.l2jfree.loginserver.tools.L2GameServerRegistrar.java
/** * Launches the interactive game server registration. * /* ww w .j ava2 s. c om*/ * @param args ignored */ public static void main(String[] args) { // LOW rework this crap Util.printSection("Game Server Registration"); _log.info("Please choose:"); _log.info("list - list registered game servers"); _log.info("reg - register a game server"); _log.info("rem - remove a registered game server"); _log.info("hexid - generate a legacy hexid file"); _log.info("quit - exit this application"); BufferedReader br = new BufferedReader(new InputStreamReader(System.in)); L2GameServerRegistrar reg = new L2GameServerRegistrar(); String line; try { RegistrationState next = RegistrationState.INITIAL_CHOICE; while ((line = br.readLine()) != null) { line = line.trim().toLowerCase(); switch (reg.getState()) { case GAMESERVER_ID: try { int id = Integer.parseInt(line); if (id < 1 || id > 127) throw new IllegalArgumentException("ID must be in [1;127]."); reg.setId(id); reg.setState(next); } catch (RuntimeException e) { _log.info("You must input a number between 1 and 127"); } if (reg.getState() == RegistrationState.ALLOW_BANS) { Connection con = null; try { con = L2Database.getConnection(); PreparedStatement ps = con .prepareStatement("SELECT allowBans FROM gameserver WHERE id = ?"); ps.setInt(1, reg.getId()); ResultSet rs = ps.executeQuery(); if (rs.next()) { _log.info("A game server is already registered on ID " + reg.getId()); reg.setState(RegistrationState.INITIAL_CHOICE); } else _log.info("Allow account bans from this game server? [y/n]:"); ps.close(); } catch (SQLException e) { _log.error("Could not remove a game server!", e); } finally { L2Database.close(con); } } else if (reg.getState() == RegistrationState.REMOVE) { Connection con = null; try { con = L2Database.getConnection(); PreparedStatement ps = con.prepareStatement("DELETE FROM gameserver WHERE id = ?"); ps.setInt(1, reg.getId()); int cnt = ps.executeUpdate(); if (cnt == 0) _log.info("No game server registered on ID " + reg.getId()); else _log.info("Game server removed."); ps.close(); } catch (SQLException e) { _log.error("Could not remove a game server!", e); } finally { L2Database.close(con); } reg.setState(RegistrationState.INITIAL_CHOICE); } else if (reg.getState() == RegistrationState.GENERATE) { Connection con = null; try { con = L2Database.getConnection(); PreparedStatement ps = con .prepareStatement("SELECT authData FROM gameserver WHERE id = ?"); ps.setInt(1, reg.getId()); ResultSet rs = ps.executeQuery(); if (rs.next()) { reg.setAuth(rs.getString("authData")); byte[] b = HexUtil.hexStringToBytes(reg.getAuth()); Properties pro = new Properties(); pro.setProperty("ServerID", String.valueOf(reg.getId())); pro.setProperty("HexID", HexUtil.hexToString(b)); BufferedOutputStream os = new BufferedOutputStream( new FileOutputStream("hexid.txt")); pro.store(os, "the hexID to auth into login"); IOUtils.closeQuietly(os); _log.info("hexid.txt has been generated."); } else _log.info("No game server registered on ID " + reg.getId()); rs.close(); ps.close(); } catch (SQLException e) { _log.error("Could not generate hexid.txt!", e); } finally { L2Database.close(con); } reg.setState(RegistrationState.INITIAL_CHOICE); } break; case ALLOW_BANS: try { if (line.length() != 1) throw new IllegalArgumentException("One char required."); else if (line.charAt(0) == 'y') reg.setTrusted(true); else if (line.charAt(0) == 'n') reg.setTrusted(false); else throw new IllegalArgumentException("Invalid choice."); byte[] auth = Rnd.nextBytes(new byte[BYTES]); reg.setAuth(HexUtil.bytesToHexString(auth)); Connection con = null; try { con = L2Database.getConnection(); PreparedStatement ps = con.prepareStatement( "INSERT INTO gameserver (id, authData, allowBans) VALUES (?, ?, ?)"); ps.setInt(1, reg.getId()); ps.setString(2, reg.getAuth()); ps.setBoolean(3, reg.isTrusted()); ps.executeUpdate(); ps.close(); _log.info("Registered game server on ID " + reg.getId()); _log.info("The authorization string is:"); _log.info(reg.getAuth()); _log.info("Use it when registering this login server."); _log.info("If you need a legacy hexid file, use the 'hexid' command."); } catch (SQLException e) { _log.error("Could not register gameserver!", e); } finally { L2Database.close(con); } reg.setState(RegistrationState.INITIAL_CHOICE); } catch (IllegalArgumentException e) { _log.info("[y/n]?"); } break; default: if (line.equals("list")) { Connection con = null; try { con = L2Database.getConnection(); PreparedStatement ps = con.prepareStatement("SELECT id, allowBans FROM gameserver"); ResultSet rs = ps.executeQuery(); while (rs.next()) _log.info("ID: " + rs.getInt("id") + ", trusted: " + rs.getBoolean("allowBans")); rs.close(); ps.close(); } catch (SQLException e) { _log.error("Could not register gameserver!", e); } finally { L2Database.close(con); } reg.setState(RegistrationState.INITIAL_CHOICE); } else if (line.equals("reg")) { _log.info("Enter the desired ID:"); reg.setState(RegistrationState.GAMESERVER_ID); next = RegistrationState.ALLOW_BANS; } else if (line.equals("rem")) { _log.info("Enter game server ID:"); reg.setState(RegistrationState.GAMESERVER_ID); next = RegistrationState.REMOVE; } else if (line.equals("hexid")) { _log.info("Enter game server ID:"); reg.setState(RegistrationState.GAMESERVER_ID); next = RegistrationState.GENERATE; } else if (line.equals("quit")) Shutdown.exit(TerminationStatus.MANUAL_SHUTDOWN); else _log.info("Incorrect command."); break; } } } catch (IOException e) { _log.fatal("Could not process input!", e); } finally { IOUtils.closeQuietly(br); } }
From source file:ScrollableRs.java
public static void printRow(ResultSet rs) throws SQLException { int ssn = rs.getInt("ssn"); String name = rs.getString("name"); double salary = rs.getDouble("salary"); System.out.print("Row Number=" + rs.getRow()); System.out.print(", SSN: " + ssn); System.out.print(", Name: " + name); System.out.println(", Salary: $" + salary); }
From source file:Main.java
private static void printEmployee(ResultSet resultSet) throws SQLException { System.out.print(resultSet.getInt("employee_id") + ", "); System.out.print(resultSet.getString("last_name") + ", "); System.out.print(resultSet.getString("first_name") + ", "); System.out.println(resultSet.getString("email")); }