List of usage examples for java.sql PreparedStatement setString
void setString(int parameterIndex, String x) throws SQLException;
String
value. From source file:com.l2jfree.loginserver.tools.L2AccountManager.java
/** * Launches the interactive account manager. * //from w ww. j a v a2 s . com * @param args ignored */ public static void main(String[] args) { // LOW rework this crap Util.printSection("Account Management"); _log.info("Please choose:"); //_log.info("list - list registered accounts"); _log.info("reg - register a new account"); _log.info("rem - remove a registered account"); _log.info("prom - promote a registered account"); _log.info("dem - demote a registered account"); _log.info("ban - ban a registered account"); _log.info("unban - unban a registered account"); _log.info("quit - exit this application"); BufferedReader br = new BufferedReader(new InputStreamReader(System.in)); L2AccountManager acm = new L2AccountManager(); String line; try { while ((line = br.readLine()) != null) { line = line.trim(); Connection con = null; switch (acm.getState()) { case USER_NAME: line = line.toLowerCase(); try { con = L2Database.getConnection(); PreparedStatement ps = con .prepareStatement("SELECT superuser FROM account WHERE username LIKE ?"); ps.setString(1, line); ResultSet rs = ps.executeQuery(); if (!rs.next()) { acm.setUser(line); _log.info("Desired password:"); acm.setState(ManagerState.PASSWORD); } else { _log.info("User name already in use."); acm.setState(ManagerState.INITIAL_CHOICE); } rs.close(); ps.close(); } catch (SQLException e) { _log.error("Could not access database!", e); acm.setState(ManagerState.INITIAL_CHOICE); } finally { L2Database.close(con); } break; case PASSWORD: try { MessageDigest sha = MessageDigest.getInstance("SHA"); byte[] pass = sha.digest(line.getBytes("US-ASCII")); acm.setPass(HexUtil.bytesToHexString(pass)); } catch (NoSuchAlgorithmException e) { _log.fatal("SHA1 is not available!", e); Shutdown.exit(TerminationStatus.ENVIRONMENT_MISSING_COMPONENT_OR_SERVICE); } catch (UnsupportedEncodingException e) { _log.fatal("ASCII is not available!", e); Shutdown.exit(TerminationStatus.ENVIRONMENT_MISSING_COMPONENT_OR_SERVICE); } _log.info("Super user: [y/n]"); acm.setState(ManagerState.SUPERUSER); break; case SUPERUSER: try { if (line.length() != 1) throw new IllegalArgumentException("One char required."); else if (line.charAt(0) == 'y') acm.setSuper(true); else if (line.charAt(0) == 'n') acm.setSuper(false); else throw new IllegalArgumentException("Invalid choice."); _log.info("Date of birth: [yyyy-mm-dd]"); acm.setState(ManagerState.DOB); } catch (IllegalArgumentException e) { _log.info("[y/n]?"); } break; case DOB: try { Date d = Date.valueOf(line); if (d.after(new Date(System.currentTimeMillis()))) throw new IllegalArgumentException("Future date specified."); acm.setDob(d); _log.info("Ban reason ID or nothing:"); acm.setState(ManagerState.SUSPENDED); } catch (IllegalArgumentException e) { _log.info("[yyyy-mm-dd] in the past:"); } break; case SUSPENDED: try { if (line.length() > 0) { int id = Integer.parseInt(line); acm.setBan(L2BanReason.getById(id)); } else acm.setBan(null); try { con = L2Database.getConnection(); PreparedStatement ps = con.prepareStatement( "INSERT INTO account (username, password, superuser, birthDate, banReason) VALUES (?, ?, ?, ?, ?)"); ps.setString(1, acm.getUser()); ps.setString(2, acm.getPass()); ps.setBoolean(3, acm.isSuper()); ps.setDate(4, acm.getDob()); L2BanReason lbr = acm.getBan(); if (lbr == null) ps.setNull(5, Types.INTEGER); else ps.setInt(5, lbr.getId()); ps.executeUpdate(); _log.info("Account " + acm.getUser() + " has been registered."); ps.close(); } catch (SQLException e) { _log.error("Could not register an account!", e); } finally { L2Database.close(con); } acm.setState(ManagerState.INITIAL_CHOICE); } catch (NumberFormatException e) { _log.info("Ban reason ID or nothing:"); } break; case REMOVE: acm.setUser(line.toLowerCase()); try { con = L2Database.getConnection(); PreparedStatement ps = con.prepareStatement("DELETE FROM account WHERE username LIKE ?"); ps.setString(1, acm.getUser()); int cnt = ps.executeUpdate(); if (cnt > 0) _log.info("Account " + acm.getUser() + " has been removed."); else _log.info("Account " + acm.getUser() + " does not exist!"); ps.close(); } catch (SQLException e) { _log.error("Could not remove an account!", e); } finally { L2Database.close(con); } acm.setState(ManagerState.INITIAL_CHOICE); break; case PROMOTE: acm.setUser(line.toLowerCase()); try { con = L2Database.getConnection(); PreparedStatement ps = con .prepareStatement("UPDATE account SET superuser = ? WHERE username LIKE ?"); ps.setBoolean(1, true); ps.setString(2, acm.getUser()); int cnt = ps.executeUpdate(); if (cnt > 0) _log.info("Account " + acm.getUser() + " has been promoted."); else _log.info("Account " + acm.getUser() + " does not exist!"); ps.close(); } catch (SQLException e) { _log.error("Could not promote an account!", e); } finally { L2Database.close(con); } acm.setState(ManagerState.INITIAL_CHOICE); break; case DEMOTE: acm.setUser(line.toLowerCase()); try { con = L2Database.getConnection(); PreparedStatement ps = con .prepareStatement("UPDATE account SET superuser = ? WHERE username LIKE ?"); ps.setBoolean(1, false); ps.setString(2, acm.getUser()); int cnt = ps.executeUpdate(); if (cnt > 0) _log.info("Account " + acm.getUser() + " has been demoted."); else _log.info("Account " + acm.getUser() + " does not exist!"); ps.close(); } catch (SQLException e) { _log.error("Could not demote an account!", e); } finally { L2Database.close(con); } acm.setState(ManagerState.INITIAL_CHOICE); break; case UNBAN: acm.setUser(line.toLowerCase()); try { con = L2Database.getConnection(); PreparedStatement ps = con .prepareStatement("UPDATE account SET banReason = ? WHERE username LIKE ?"); ps.setNull(1, Types.INTEGER); ps.setString(2, acm.getUser()); int cnt = ps.executeUpdate(); if (cnt > 0) _log.info("Account " + acm.getUser() + " has been unbanned."); else _log.info("Account " + acm.getUser() + " does not exist!"); ps.close(); } catch (SQLException e) { _log.error("Could not demote an account!", e); } finally { L2Database.close(con); } acm.setState(ManagerState.INITIAL_CHOICE); break; case BAN: line = line.toLowerCase(); try { con = L2Database.getConnection(); PreparedStatement ps = con .prepareStatement("SELECT superuser FROM account WHERE username LIKE ?"); ps.setString(1, line); ResultSet rs = ps.executeQuery(); if (rs.next()) { acm.setUser(line); _log.info("Ban reason ID:"); acm.setState(ManagerState.REASON); } else { _log.info("Account does not exist."); acm.setState(ManagerState.INITIAL_CHOICE); } rs.close(); ps.close(); } catch (SQLException e) { _log.error("Could not access database!", e); acm.setState(ManagerState.INITIAL_CHOICE); } finally { L2Database.close(con); } break; case REASON: try { int ban = Integer.parseInt(line); con = L2Database.getConnection(); PreparedStatement ps = con .prepareStatement("UPDATE account SET banReason = ? WHERE username LIKE ?"); ps.setInt(1, ban); ps.setString(2, acm.getUser()); ps.executeUpdate(); _log.info("Account " + acm.getUser() + " has been banned."); ps.close(); } catch (NumberFormatException e) { _log.info("Ban reason ID:"); } catch (SQLException e) { _log.error("Could not ban an account!", e); } finally { L2Database.close(con); } acm.setState(ManagerState.INITIAL_CHOICE); break; default: line = line.toLowerCase(); if (line.equals("reg")) { _log.info("Desired user name:"); acm.setState(ManagerState.USER_NAME); } else if (line.equals("rem")) { _log.info("User name:"); acm.setState(ManagerState.REMOVE); } else if (line.equals("prom")) { _log.info("User name:"); acm.setState(ManagerState.PROMOTE); } else if (line.equals("dem")) { _log.info("User name:"); acm.setState(ManagerState.DEMOTE); } else if (line.equals("unban")) { _log.info("User name:"); acm.setState(ManagerState.UNBAN); } else if (line.equals("ban")) { _log.info("User name:"); acm.setState(ManagerState.BAN); } 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:com.intelius.iap4.TigerLineHit.java
public static void main(String[] args) { String _tigerDs = "jdbc:h2:/home/sxu/playground/tiger"; ResultSet rs = null;//ww w.j av a2s . c o 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:Batch.java
static public void main(String[] args) { Connection conn = null;/* w ww . ja va2 s . com*/ try { ArrayList breakable = new ArrayList(); PreparedStatement stmt; Iterator users; ResultSet rs; Class.forName(args[0]).newInstance(); conn = DriverManager.getConnection(args[1], args[2], args[3]); stmt = conn.prepareStatement("SELECT user_id, password " + "FROM user"); rs = stmt.executeQuery(); while (rs.next()) { String uid = rs.getString(1); String pw = rs.getString(2); // Assume PasswordCracker is some class that provides // a single static method called crack() that attempts // to run password cracking routines on the password // if( PasswordCracker.crack(uid, pw) ) { // breakable.add(uid); // } } stmt.close(); if (breakable.size() < 1) { return; } stmt = conn.prepareStatement("UPDATE user " + "SET bad_password = 'Y' " + "WHERE uid = ?"); users = breakable.iterator(); while (users.hasNext()) { String uid = (String) users.next(); stmt.setString(1, uid); stmt.addBatch(); } stmt.executeBatch(); } catch (Exception e) { e.printStackTrace(); } finally { if (conn != null) { try { conn.close(); } catch (Exception e) { } } } }
From source file:TransactionPairs.java
public static void main(String args[]) { String url = "jdbc:mySubprotocol:myDataSource"; Connection con = null;//from www .jav a2 s .c om Statement stmt; PreparedStatement updateSales; PreparedStatement updateTotal; String updateString = "update COFFEES " + "set SALES = ? where COF_NAME = ?"; String updateStatement = "update COFFEES " + "set TOTAL = TOTAL + ? where COF_NAME = ?"; String query = "select COF_NAME, SALES, TOTAL from COFFEES"; 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"); updateSales = con.prepareStatement(updateString); updateTotal = con.prepareStatement(updateStatement); int[] salesForWeek = { 175, 150, 60, 155, 90 }; String[] coffees = { "Colombian", "French_Roast", "Espresso", "Colombian_Decaf", "French_Roast_Decaf" }; int len = coffees.length; con.setAutoCommit(false); for (int i = 0; i < len; i++) { updateSales.setInt(1, salesForWeek[i]); updateSales.setString(2, coffees[i]); updateSales.executeUpdate(); updateTotal.setInt(1, salesForWeek[i]); updateTotal.setString(2, coffees[i]); updateTotal.executeUpdate(); con.commit(); } con.setAutoCommit(true); updateSales.close(); updateTotal.close(); stmt = con.createStatement(); ResultSet rs = stmt.executeQuery(query); while (rs.next()) { String c = rs.getString("COF_NAME"); int s = rs.getInt("SALES"); int t = rs.getInt("TOTAL"); System.out.println(c + " " + s + " " + t); } stmt.close(); con.close(); } catch (SQLException ex) { System.err.println("SQLException: " + ex.getMessage()); if (con != null) { try { System.err.print("Transaction is being "); System.err.println("rolled back"); con.rollback(); } catch (SQLException excep) { System.err.print("SQLException: "); System.err.println(excep.getMessage()); } } } }
From source file:TransactionPairs.java
public static void main(String args[]) { String url = "jdbc:mySubprotocol:myDataSource"; Connection con = null;/*from w ww . j a va2 s. c o m*/ Statement stmt; PreparedStatement updateSales; PreparedStatement updateTotal; String updateString = "update COFFEES " + "set SALES = ? where COF_NAME like ?"; String updateStatement = "update COFFEES " + "set TOTAL = TOTAL + ? where COF_NAME like ?"; String query = "select COF_NAME, SALES, TOTAL from COFFEES"; 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"); updateSales = con.prepareStatement(updateString); updateTotal = con.prepareStatement(updateStatement); int[] salesForWeek = { 175, 150, 60, 155, 90 }; String[] coffees = { "Colombian", "French_Roast", "Espresso", "Colombian_Decaf", "French_Roast_Decaf" }; int len = coffees.length; con.setAutoCommit(false); for (int i = 0; i < len; i++) { updateSales.setInt(1, salesForWeek[i]); updateSales.setString(2, coffees[i]); updateSales.executeUpdate(); updateTotal.setInt(1, salesForWeek[i]); updateTotal.setString(2, coffees[i]); updateTotal.executeUpdate(); con.commit(); } con.setAutoCommit(true); updateSales.close(); updateTotal.close(); stmt = con.createStatement(); ResultSet rs = stmt.executeQuery(query); while (rs.next()) { String c = rs.getString("COF_NAME"); int s = rs.getInt("SALES"); int t = rs.getInt("TOTAL"); System.out.println(c + " " + s + " " + t); } stmt.close(); con.close(); } catch (SQLException ex) { System.err.println("SQLException: " + ex.getMessage()); if (con != null) { try { System.err.print("Transaction is being "); System.err.println("rolled back"); con.rollback(); } catch (SQLException excep) { System.err.print("SQLException: "); System.err.println(excep.getMessage()); } } } }
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 {//from w w w .jav a 2 s . 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:examples.KafkaStreamsDemo.java
public static void main(String[] args) throws InterruptedException, SQLException { /**//from w w w . j a va2 s .com * 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.l2jfree.loginserver.tools.L2GameServerRegistrar.java
/** * Launches the interactive game server registration. * /* w w w .j a va 2 s .c o m*/ * @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:Main.java
public static long writeJavaObject(Connection conn, Object object) throws Exception { String className = object.getClass().getName(); PreparedStatement pstmt = conn.prepareStatement(WRITE_OBJECT_SQL); pstmt.setString(1, className); pstmt.setObject(2, object);/* w ww . j a va 2 s. c o m*/ pstmt.executeUpdate(); ResultSet rs = pstmt.getGeneratedKeys(); int id = -1; if (rs.next()) { id = rs.getInt(1); } rs.close(); pstmt.close(); return id; }
From source file:com.xpfriend.fixture.runner.example.ExampleJob.java
/** * ??/*w w w . java 2 s .c o m*/ * @param id ?ID * @param name?NAME * @param connection ? */ private static void updateDatabase(int id, String name, Connection connection) throws SQLException { PreparedStatement statement = connection.prepareStatement(SQL); try { statement.setString(1, name); statement.setInt(2, id); statement.executeUpdate(); } finally { statement.close(); } }