List of usage examples for java.sql SQLException toString
public String toString()
From source file:org.etudes.component.app.jforum.JforumDataServiceImpl.java
private int createForum(Connection connection, String forumName, int catgId, String forumDescription, int forumType, int accessType, boolean forumModerated, int gradeType, Date startDate, Date endDate, int lockEndDate) throws SQLException { if (logger.isDebugEnabled()) logger.debug("creating forum with forumName :" + forumName + " for categoryId : " + catgId); if (logger.isDebugEnabled()) logger.debug("Entering createForum......"); int forumId = -1; try {/*from w ww . ja v a 2 s.c om*/ String forumGetMaxOrder = "SELECT MAX(forum_order) FROM jforum_forums"; PreparedStatement p = connection.prepareStatement(forumGetMaxOrder); ResultSet rs = p.executeQuery(); int order = 1; if (rs.next()) { order = rs.getInt(1) + 1; } rs.close(); p.close(); //if (logger.isInfoEnabled()) logger.info("forum order : "+ order); String forumAddNew = null; if (sqlService.getVendor().equals("oracle")) { forumAddNew = "INSERT INTO jforum_forums (forum_id, categories_id, forum_name, " + "forum_desc, forum_order, forum_type, forum_access_type, forum_grade_type, start_date, end_date, lock_end_date) " + "VALUES (jforum_forums_seq.nextval, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?)"; p = connection.prepareStatement(forumAddNew); p.setInt(1, catgId); p.setString(2, forumName); p.setString(3, forumDescription); p.setInt(4, order); p.setInt(5, forumType); p.setInt(6, accessType); if (gradeType == GRADE_BY_FORUM || gradeType == GRADE_BY_TOPIC) p.setInt(7, gradeType); else p.setInt(7, GRADE_DISABLED); if (startDate == null) { p.setTimestamp(8, null); } else { p.setTimestamp(8, new Timestamp(startDate.getTime())); } if (endDate == null) { p.setTimestamp(9, null); p.setInt(10, 0); } else { p.setTimestamp(9, new Timestamp(endDate.getTime())); p.setInt(10, lockEndDate); } p.executeUpdate(); p.close(); String forumLastGeneratedForumId = "SELECT jforum_forums_seq.currval FROM DUAL"; p = connection.prepareStatement(forumLastGeneratedForumId); rs = p.executeQuery(); if (rs.next()) { forumId = rs.getInt(1); } rs.close(); p.close(); } else if (sqlService.getVendor().equalsIgnoreCase("mysql")) { forumAddNew = "INSERT INTO jforum_forums (categories_id, forum_name, forum_desc, " + "forum_order, forum_type, forum_access_type, forum_grade_type, start_date, end_date, lock_end_date) VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?, ?)"; p = connection.prepareStatement(forumAddNew, Statement.RETURN_GENERATED_KEYS); p.setInt(1, catgId); p.setString(2, forumName); p.setString(3, forumDescription); p.setInt(4, order); p.setInt(5, forumType); p.setInt(6, accessType); if (gradeType == GRADE_BY_FORUM || gradeType == GRADE_BY_TOPIC) p.setInt(7, gradeType); else p.setInt(7, GRADE_DISABLED); if (startDate == null) { p.setTimestamp(8, null); } else { p.setTimestamp(8, new Timestamp(startDate.getTime())); } if (endDate == null) { p.setTimestamp(9, null); p.setInt(10, 0); } else { p.setTimestamp(9, new Timestamp(endDate.getTime())); p.setInt(10, lockEndDate); } p.executeUpdate(); rs = p.getGeneratedKeys(); if (rs.next()) { forumId = rs.getInt(1); rs.close(); p.close(); } } if (logger.isDebugEnabled()) logger.debug("Exiting createForum......"); } catch (SQLException e) { if (logger.isErrorEnabled()) logger.error("createForum():Error while creating forum : " + e.toString()); e.printStackTrace(); throw e; } return forumId; }
From source file:controlador.Peticiones.java
/** * Processes requests for both HTTP <code>GET</code> and <code>POST</code> * methods./*from w ww .j av a 2s .c o m*/ * * @param request servlet request * @param response servlet response * @throws ServletException if a servlet-specific error occurs * @throws IOException if an I/O error occurs */ protected void processRequest(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { //response.setContentType("text/html;charset=UTF-8"); String target, op, action, view; target = request.getParameter("target"); op = request.getParameter("op"); if (target.equals("login")) { bd = new ControlDB(); bd.cargarDriver(); bd.conectar(); String login = request.getParameter("login"); String pass = request.getParameter("password"); ResultSet r = bd.ejecutarSelect("SELECT * FROM roles WHERE nombreRol='" + login + "' AND passRol='" + Auxiliar.encriptarPass(pass) + "'"); JSONObject objetoJSON = new JSONObject(); response.setContentType("application/json; charset=utf-8"); response.setCharacterEncoding("UTF-8"); PrintWriter out = response.getWriter(); try { if (r != null && r.next()) { objetoJSON.put("r", "1"); out.print(objetoJSON); } else { objetoJSON.put("r", "0"); out.print(objetoJSON); } } catch (SQLException ex) { } catch (JSONException ex) { } } else { if (target.equals("pedido")) { bd = new ControlDB(); bd.cargarDriver(); bd.conectar(); String s = request.getParameter("datos"); JSONTokener token = new JSONTokener(s); JSONArray ar = null; ArrayList<Producto> productos = new ArrayList(); try { ar = new JSONArray(token); for (int i = 0; i < ar.length(); i++) { agregarProducto(ar.getJSONObject(i).getInt("idMesa"), ar.getJSONObject(i).getInt("idProducto")); ResultSet rs = bd.ejecutarSelect("SELECT nombreProducto from productos where idProducto = " + ar.getJSONObject(i).getInt("idProducto")); rs.next(); String nombre = rs.getString("nombreProducto"); Producto pr = new Producto(nombre); if (productos.contains(pr)) { int pos = productos.indexOf(pr); productos.get(pos).sumaCantidad(); } else { productos.add(new Producto(nombre)); } } ResultSet nombreMesa = bd.ejecutarSelect( "SELECT nombreMesa, nombreZona from mesas inner join zona on idZona=Zona_Idzona where idmesa=" + ar.getJSONObject(0).getInt("idMesa")); nombreMesa.next(); String nombre = nombreMesa.getString("nombreMesa") + " " + nombreMesa.getString("nombreZona"); Comanda comanda = new Comanda(productos, nombre); System.out.println("Ticket: \n" + comanda.contenidoComanda); Auxiliar.imprimir(comanda.contenidoComanda); } catch (JSONException ex) { System.out.println("Error JSON " + ex.toString()); } catch (SQLException ex) { System.out.println("Error SQL " + ex.toString()); } // Crear un el objeto para enviar a comanda para imprimir, implementar response.setHeader("Content-Type", "application/json"); response.setContentType("application/json"); response.setCharacterEncoding("UTF-8"); PrintWriter out = response.getWriter(); JSONObject obj = new JSONObject(); try { obj.put("r", "recibido"); } catch (JSONException ex) { } out.print(obj); out.flush(); } else { if (target.equals("mesas")) { bd = new ControlDB(); bd.cargarDriver(); bd.conectar(); ResultSet r = bd.ejecutarSelect( "SELECT mesas.idMesa, nombreMesa, nombreZona FROM mesas inner join zona on idzona = Zona_idZona"); JSONArray array = new JSONArray(); ResultSetMetaData rsMetaData = null; int columns = 0; try { rsMetaData = r.getMetaData(); columns = rsMetaData.getColumnCount(); } catch (SQLException ex) { } try { while (r.next()) { JSONObject objetoJSON = new JSONObject(); for (int i = 1; i <= columns; i++) { objetoJSON.put(rsMetaData.getColumnLabel(i), r.getString(i)); } System.out.println(objetoJSON + "\n"); array.put(objetoJSON); } } catch (SQLException ex) { } catch (JSONException ex) { } response.setHeader("Content-Type", "application/json"); response.setContentType("application/json"); response.setCharacterEncoding("UTF-8"); PrintWriter out = response.getWriter(); out.print(array); out.flush(); } else { if (target.equals("familias")) { bd = new ControlDB(); bd.cargarDriver(); bd.conectar(); ResultSet r = bd.ejecutarSelect( "SELECT idFamilia, nombreFamilia FROM `familias` order by idFamilia"); JSONArray array = new JSONArray(); ResultSetMetaData rsMetaData = null; int columns = 0; try { rsMetaData = r.getMetaData(); columns = rsMetaData.getColumnCount(); } catch (SQLException ex) { } try { while (r.next()) { JSONObject objetoJSON = new JSONObject(); for (int i = 1; i <= columns; i++) { objetoJSON.put(rsMetaData.getColumnLabel(i), r.getString(i)); } array.put(objetoJSON); } } catch (SQLException ex) { } catch (JSONException ex) { ; } response.setHeader("Content-Type", "application/json"); response.setContentType("application/json"); response.setCharacterEncoding("UTF-8"); PrintWriter out = response.getWriter(); out.print(array); out.flush(); } else { if (target.equals("productos")) { bd = new ControlDB(); bd.cargarDriver(); bd.conectar(); ResultSet r = bd.ejecutarSelect( "SELECT idProducto, nombreProducto,fotoProducto , precioProducto, Familias_idFamilias FROM productos order by idProducto"); JSONArray array = new JSONArray(); ResultSetMetaData rsMetaData = null; int columns = 0; try { rsMetaData = r.getMetaData(); columns = rsMetaData.getColumnCount(); } catch (SQLException ex) { } try { while (r.next()) { JSONObject objetoJSON = new JSONObject(); for (int i = 1; i <= columns; i++) { objetoJSON.put(rsMetaData.getColumnLabel(i), r.getString(i)); } array.put(objetoJSON); } } catch (SQLException ex) { } catch (JSONException ex) { } response.setHeader("Content-Type", "application/json"); response.setContentType("application/json"); response.setCharacterEncoding("UTF-8"); PrintWriter out = response.getWriter(); out.print(array); out.flush(); } } } } } }
From source file:org.etudes.component.app.jforum.JforumDataServiceImpl.java
/** * create topic/*from w w w . j a v a 2s . c om*/ * @param connection connection * @param forumId forum id * @param topicTitle topic title * @param userId user id * @param topicType topic type * @param firstPostId first post id * @return */ private int createTopic(Connection connection, String toContextId, int fromForumId, int fromTopicId, int forumId, String topicTitle, int userId, int topicType, int topicGrade, int firstPostId, Date startDate, Date endDate, int lockEndDate, Date gradebookEndDate) { if (logger.isDebugEnabled()) logger.debug("creating topic with topicName :" + topicTitle + " for forum_id : " + forumId); if (logger.isDebugEnabled()) logger.debug("Entering createTopic......"); int topicId = -1; try { PreparedStatement p = null; ResultSet rs = null; String topicAddNew = null; if (sqlService.getVendor().equals("oracle")) { topicAddNew = "INSERT INTO jforum_topics (topic_id, forum_id, topic_title, " + "user_id, topic_time, topic_first_post_id, topic_last_post_id, " + "topic_type, moderated, topic_grade, topic_export, start_date, end_date, lock_end_date)" + "VALUES (jforum_topics_seq.nextval, ?, ?, ?, ?, SYSDATE, ?, ?, ?, ?, ?, ?, ?, ?)"; p = connection.prepareStatement(topicAddNew); p.setInt(1, forumId); p.setString(2, topicTitle); p.setInt(3, userId); //p.setTimestamp(4, new Timestamp(System.currentTimeMillis())); p.setInt(4, 0); p.setInt(5, 0); p.setInt(6, topicType); p.setInt(7, 0); if (topicGrade == GRADE_YES) p.setInt(8, topicGrade); else p.setInt(8, GRADE_NO); p.setInt(9, EXPORT_YES); if (startDate == null) { p.setTimestamp(10, null); } else { p.setTimestamp(10, new Timestamp(startDate.getTime())); } if (endDate == null) { p.setTimestamp(11, null); p.setInt(12, 0); } else { p.setTimestamp(11, new Timestamp(endDate.getTime())); p.setInt(12, lockEndDate); } p.executeUpdate(); p.close(); String forumLastGeneratedTopicId = "SELECT jforum_topics_seq.currval FROM DUAL"; p = connection.prepareStatement(forumLastGeneratedTopicId); rs = p.executeQuery(); if (rs.next()) { topicId = rs.getInt(1); } rs.close(); p.close(); } else if (sqlService.getVendor().equalsIgnoreCase("mysql")) { topicAddNew = "INSERT INTO jforum_topics (forum_id, topic_title, user_id, " + "topic_time, topic_first_post_id, topic_last_post_id, topic_type, moderated, topic_grade, topic_export, start_date, end_date, lock_end_date)" + "VALUES (?, ?, ?, NOW(), ?, ?, ?, ?, ?, ?, ?, ?, ?)"; p = connection.prepareStatement(topicAddNew, Statement.RETURN_GENERATED_KEYS); p.setInt(1, forumId); p.setString(2, topicTitle); p.setInt(3, userId); //p.setTimestamp(4, new Timestamp(System.currentTimeMillis())); p.setInt(4, 0); p.setInt(5, 0); p.setInt(6, topicType); p.setInt(7, 0); if (topicGrade == GRADE_YES) p.setInt(8, topicGrade); else p.setInt(8, GRADE_NO); p.setInt(9, EXPORT_YES); if (startDate == null) { p.setTimestamp(10, null); } else { p.setTimestamp(10, new Timestamp(startDate.getTime())); } if (endDate == null) { p.setTimestamp(11, null); p.setInt(12, 0); } else { p.setTimestamp(11, new Timestamp(endDate.getTime())); p.setInt(12, lockEndDate); } p.executeUpdate(); rs = p.getGeneratedKeys(); if (rs.next()) { topicId = rs.getInt(1); rs.close(); p.close(); } } //create grade for grade topic if (topicGrade == GRADE_YES) { String gradeModelSelectByForumTopicId = "SELECT grade_id, context, grade_type, forum_id, topic_id, points, add_to_gradebook, categories_id, min_posts, min_posts_required " + "FROM jforum_grade WHERE forum_id = ? and topic_id = ?"; PreparedStatement gradePrepStmnt = connection.prepareStatement(gradeModelSelectByForumTopicId); gradePrepStmnt.setInt(1, fromForumId); gradePrepStmnt.setInt(2, fromTopicId); ResultSet rsGrade = gradePrepStmnt.executeQuery(); float gradePoints = 0f; if (rsGrade.next()) { gradePoints = rsGrade.getFloat("points"); } int addToGradebook = rsGrade.getInt("add_to_gradebook"); boolean minPostsRequired = false; int minPosts = 0; if (rsGrade.getInt("min_posts_required") == 1) { minPostsRequired = true; minPosts = rsGrade.getInt("min_posts"); } rsGrade.close(); gradePrepStmnt.close(); int gradeId = createGrade(connection, toContextId, GRADE_BY_TOPIC, forumId, topicId, 0, gradePoints, addToGradebook, minPostsRequired, minPosts, topicTitle); if (startDate != null || endDate != null) { } else if (gradebookEndDate != null) { endDate = gradebookEndDate; } if ((gradeId > 0) && (addToGradebook == 1)) { createGradebookEntry(gradeId, topicTitle, gradePoints, endDate); } } } catch (SQLException e) { if (logger.isErrorEnabled()) logger.error("createTopic():Error while creating topic : " + e.toString()); e.printStackTrace(); } if (logger.isDebugEnabled()) logger.debug("Exiting createTopic......"); return topicId; }
From source file:com.FFLive.MySQLConnection.java
public void updatePlayers(int gw, boolean namesOnly) { Main.log.log(5, "Updating All Player Info... \r"); try {// w w w . j a va 2 s. c o m PreparedStatement SelPID = conn.prepareStatement("SELECT playerID FROM playersGW?"); SelPID.setInt(1, gw); ResultSet playerList = SelPID.executeQuery(); //statement.executeQuery("SELECT playerID FROM playersGW" + gw); int counter = 0; while (playerList.next()) { if (counter % 30 == 0) { Main.log.log(5, "Updating All Player Info. \r"); } else if (counter % 30 == 10) { Main.log.log(5, "Updating All Player Info.. \r"); } else if (counter % 30 == 20) { Main.log.log(5, "Updating All Player Info... \r"); } counter++; try { Player player = new Player(Integer.toString(playerList.getInt("playerID")), gw); player.getPlayer(); if (!namesOnly || player.playerID.equals("-1")) { PreparedStatement UpPGw = conn.prepareStatement("UPDATE playersGW? set " + "firstName =?, " + "lastName =?, " + "webName = ?, " + "score = ?, " + "gameweekBreakdown = ?, " + "teamID = ?, " + "teamName = ?, " + "currentFixture = ?, " + "nextFixture = ?, " + "status = ?, " + "news = ?, " + "photo = ? " + "WHERE playerID = ?"); UpPGw.setInt(1, gw); UpPGw.setString(2, player.firstName); UpPGw.setString(3, player.lastName); UpPGw.setString(4, player.playerName); UpPGw.setInt(5, player.playerScore); UpPGw.setString(6, player.gameweekBreakdown); UpPGw.setInt(7, player.teamNumber); UpPGw.setString(8, player.playerTeam); UpPGw.setString(9, player.currentFixture); UpPGw.setString(10, player.nextFixture); UpPGw.setString(11, player.status); UpPGw.setString(12, player.news); UpPGw.setString(13, player.photo); UpPGw.setInt(14, Integer.parseInt(player.playerID)); UpPGw.executeUpdate(); UpPGw.close(); } else { PreparedStatement UpPGw = conn.prepareStatement( "UPDATE playersGW? set " + "firstName =?, " + "lastName =?, " + "webName = ?, " + "teamID = ?, " + "teamName = ?, " + "photo = ? " + "WHERE playerID = ?"); UpPGw.setInt(1, gw); UpPGw.setString(2, player.firstName); UpPGw.setString(3, player.lastName); UpPGw.setString(4, player.playerName); UpPGw.setInt(5, player.teamNumber); UpPGw.setString(6, player.playerTeam); UpPGw.setString(7, player.photo); UpPGw.setInt(8, Integer.parseInt(player.playerID)); UpPGw.executeUpdate(); UpPGw.close(); } } catch (MysqlDataTruncation g) { Main.log.ln(4); Main.log.log(4, g + " - while updating Players, Skipping Player\n"); } catch (SQLException f) { Main.log.ln(2); Main.log.log(2, "Error Updating Players, Skipping Player\n"); Main.log.log(2, f.toString()); Main.log.log(9, f); } catch (NumberFormatException n) { Main.log.ln(2); Main.log.log(2, "Invalid Player ID, Skipping Player\n"); Main.log.log(2, n.toString()); Main.log.log(9, n); } } } catch (Exception e) { Main.log.ln(1); Main.log.log(1, "Critical Error Updating Players\n"); Main.log.log(1, e.toString()); Main.log.log(9, e); System.exit(1097); } Main.log.log(5, "Updating All Player Info... Done! \r"); }
From source file:com.FFLive.MySQLConnection.java
public void rebuildLeague(H2HLeague h2h) { Main.log.log(5, "Rebuilding League " + h2h.leagueID + "\r"); h2h.loadH2HLeague();//w w w . j a v a2s . co m storeLeaguesData(h2h); Main.log.log(4, "Rebuilding League " + h2h.leagueID + " - Fetching Fixtures \r"); //Fill in all the fixtures Map<Integer, Map<String, String>> allFixtures = h2h.loadAllFixtures(h2h.gameweek); try { for (Entry<Integer, Map<String, String>> gwFixtures : allFixtures.entrySet()) { int x = 0; for (Entry<String, String> gwFixture : gwFixtures.getValue().entrySet()) { x++; PreparedStatement insertFixtures = conn.prepareStatement( "INSERT INTO h2hGW? (leagueID, home, away, fixtureNo) VALUES (?,?,?,?) ON DUPLICATE KEY UPDATE fixtureNo = ?"); insertFixtures.setInt(1, gwFixtures.getKey()); insertFixtures.setInt(2, h2h.leagueID); insertFixtures.setString(3, gwFixture.getKey()); insertFixtures.setString(4, gwFixture.getValue()); insertFixtures.setInt(5, x); insertFixtures.setInt(6, x); insertFixtures.executeUpdate(); insertFixtures.close(); } } } catch (SQLException sql) { Main.log.ln(2); Main.log.log(2, "Error Processing Fixtures while Rebuilding League:" + h2h.leagueID + "\n"); Main.log.log(2, sql.toString()); Main.log.log(9, sql); } //Process GW Scores and work out points for (int gw = h2h.startingGameweek; gw < h2h.gameweek; gw++) { //Create Required Gameweek Tables createGWTables(gw); createGWTables(gw + 1); //Fetch GW Scores and add them to Live LP try { for (String manIDs : h2h.managerMap.keySet()) { PreparedStatement getTeam = conn .prepareStatement("SELECT managerID, gw FROM teamsGW? WHERE managerID = ?"); getTeam.setInt(1, gw); getTeam.setInt(2, Integer.parseInt(manIDs)); ResultSet teamData = getTeam.executeQuery(); while (teamData.next()) { //Set This Week PreparedStatement ltgw = conn.prepareStatement( "INSERT INTO leagues_teamsGW? (leagueID, managerID, liveLP) VALUES (?, ?, lp + ?) ON DUPLICATE KEY UPDATE liveLP = lp + ?"); ltgw.setInt(1, gw); ltgw.setInt(2, h2h.leagueID); ltgw.setInt(3, teamData.getInt("managerID")); ltgw.setInt(4, teamData.getInt("gw")); ltgw.setInt(5, teamData.getInt("gw")); ltgw.executeUpdate(); ltgw.close(); } teamData.close(); getTeam.close(); } Main.log.log(4, "Rebuilding League " + h2h.leagueID + " GW:" + gw + "/" + h2h.gameweek + " Updating Scores... \r"); fixtureScores(gw, h2h.leagueID); Main.log.log(4, "Rebuilding League " + h2h.leagueID + " GW:" + gw + "/" + h2h.gameweek + " Updating Positions... \r"); updatePositions(gw, h2h.leagueID); //Set Next Week Including wins, position and LP PreparedStatement ltgwNextWeek = conn.prepareStatement( "INSERT INTO leagues_teamsGW? (leagueID, managerID, lp, position, wins, loss, draw, points) SELECT leagueID, managerID, liveLP, livePosition, liveWin, liveLoss, LiveDraw, livePoints FROM leagues_teamsGW? WHERE leagueID = ? ON DUPLICATE KEY UPDATE lp = leagues_teamsGW?.liveLP, position = leagues_teamsGW?.livePosition, wins = leagues_teamsGW?.liveWin, loss = leagues_teamsGW?.liveLoss, draw = leagues_teamsGW?.liveDraw, points =leagues_teamsGW?.livePoints"); ltgwNextWeek.setInt(1, gw + 1); ltgwNextWeek.setInt(2, gw); ltgwNextWeek.setInt(3, h2h.leagueID); ltgwNextWeek.setInt(4, gw); ltgwNextWeek.setInt(5, gw); ltgwNextWeek.setInt(6, gw); ltgwNextWeek.setInt(7, gw); ltgwNextWeek.setInt(8, gw); ltgwNextWeek.setInt(9, gw); ltgwNextWeek.executeUpdate(); ltgwNextWeek.close(); } catch (SQLException sql) { Main.log.ln(2); Main.log.log(2, "Error Passing Gameweek Scores... " + sql + "\n"); Main.log.log(9, sql); } } Main.log.log(4, "Rebuilding League " + h2h.leagueID + " - Updated! \n"); }
From source file:gemlite.core.internal.db.DBSynchronizer.java
/** * Returns an {@link SqlExceptionHandler} for the given {@link SQLException} * ./*from w w w . j a va2 s . co m*/ */ protected SqlExceptionHandler handleSQLException(SQLException sqle) { String sqlState = sqle.getSQLState(); // What to do if SQLState is null? Checking through the exception // message for common strings for now but DB specific errorCode and // other // such checks will be better. // Below was due to a bug in wrapper OracleDriver being used and // normally // this can never be null. if (sqlState == null) { // no SQLState so fallback to string matching in the message // for BatchUpdateException it will look at the nextException if (sqle instanceof BatchUpdateException && sqle.getNextException() != null) { // "42Y96" represents an unknown exception but batch exception // will // look at the nextException in any case sqlState = "42Y96"; } else { // if connection has been closed then refresh it try { synchronized (this) { if (this.conn == null || this.conn.isClosed()) { return SqlExceptionHandler.REFRESH; } } } catch (Exception e) { return SqlExceptionHandler.REFRESH; } // treat like a connection failure by default return checkExceptionString(sqle.toString().toLowerCase(), SqlExceptionHandler.REFRESH); } } // check for exception type first SqlExceptionHandler handler = checkExceptionType(sqle); if (handler != null) { return handler; } // next check SQLStates //about SQLStates see http://blog.csdn.net/cangyingaoyou/article/details/7402243 if (sqlState.startsWith("25") || sqlState.startsWith("42")) { // constraint violations can happen in retries, so default action is // to // IGNORE them; when errorFile is provided then it will be logged to // that in XML format in any case return SqlExceptionHandler.IGNORE; } else if (sqlState.startsWith("22") || sqlState.startsWith("23")) { // if numErrorTries is defined, then retry some number of times else // ignore after having logged warning since retry is not likely to // help return this.numErrorTries > 0 ? SqlExceptionHandler.IGNORE_BREAK_LOOP : SqlExceptionHandler.IGNORE; } else if (sqlState.startsWith("08")) { return SqlExceptionHandler.REFRESH; } else if (sqlState.startsWith("40")) { // these are transient transaction/lock exceptions so retry whole // batch return SqlExceptionHandler.IGNORE_BREAK_LOOP; } else { if (sqle instanceof BatchUpdateException && sqle.getNextException() != null) { return handleSQLException(sqle.getNextException()); } // if connection has been closed then refresh it try { synchronized (this) { if (this.conn == null || this.conn.isClosed()) { //return SqlExceptionHandler.REFRESH; //,?,??TODO ?? return SqlExceptionHandler.IGNORE; } } } catch (Exception e) { return SqlExceptionHandler.REFRESH; } return checkExceptionString(sqle.toString().toLowerCase(), SqlExceptionHandler.REFRESH); } }
From source file:com.FFLive.MySQLConnection.java
public MySQLConnection(String ipAddress, String userName, String password, String database) { try {/*w w w . j av a2 s . co m*/ // this will load the MySQL driver, each DB has its own driver Class.forName("com.mysql.jdbc.Driver"); // setup the connection with the DB. Main.log.log(4, "Connecting to your MySQL Database... "); conn = DriverManager.getConnection("jdbc:mysql://" + ipAddress + "/?user=" + userName + "&password=" + password + "&useUnicode=true&characterEncoding=utf8"); Statement statement = conn.createStatement(); statement.executeUpdate("CREATE DATABASE IF NOT EXISTS " + database); statement.executeUpdate("USE " + database); statement.executeUpdate( "CREATE TABLE IF NOT EXISTS leagues (ID INT NOT NULL UNIQUE, name VARCHAR(30) NOT NULL, type VARCHAR(10) NOT NULL)"); statement.executeUpdate( "CREATE TABLE IF NOT EXISTS status (LeagueID INT NOT NULL, Gameweek INT NOT NULL, starts VARCHAR(20), kickOff VARCHAR(20), started VARCHAR(2) DEFAULT 'N', ends VARCHAR(20) , ended VARCHAR(2) DEFAULT 'N', teamsStored VARCHAR(2) DEFAULT 'N', postGwUpdate VARCHAR(2) DEFAULT 'N', UNIQUE (leagueID, Gameweek))"); statement.executeUpdate( "CREATE TABLE IF NOT EXISTS webFront (page VARCHAR(50) UNIQUE, status VARCHAR(300), currGameweek INT)"); statement.executeUpdate( "INSERT INTO webFront (page, status) values ('index', 'Loading...') ON DUPLICATE KEY UPDATE status = 'loading'"); Main.log.log(4, "Connected!\n", 0); statement.close(); } catch (ClassNotFoundException c) { Main.log.ln(1); Main.log.log(1, "Critical Program Failure!\n" + c + "\n"); Main.log.log(9, c); System.exit(1001); } catch (SQLException sql) { Main.log.ln(1); Main.log.log(1, "MySQL Error Encountered, Check that your details are correct and that your user has permissions to edit DB " + database + "\n"); Main.log.log(1, sql.toString()); Main.log.log(9, sql); System.exit(1002); } }
From source file:com.gtwm.pb.model.manageData.DataManagement.java
public int globalEdit(HttpServletRequest request, TableInfo table, LinkedHashMap<BaseField, BaseValue> dataToSave, SessionDataInfo sessionData, List<FileItem> multipartItems) throws InputRecordException, ObjectNotFoundException, SQLException, CodingErrorException, CantDoThatException, DisallowedException, MissingParametersException { int affectedFieldCount = dataToSave.size(); for (BaseField affectedField : dataToSave.keySet()) { if (affectedField.getFieldName().equals(HiddenFields.LAST_MODIFIED.getFieldName())) { affectedFieldCount--;/*from w ww. j ava 2 s . c o m*/ } if (affectedField.getFieldName().equals(HiddenFields.MODIFIED_BY.getFieldName())) { affectedFieldCount--; } } if (affectedFieldCount > 1) { throw new CantDoThatException( "Global edits can only apply changes to one field at a time. Requested field changes were " + dataToSave); } Connection conn = null; Set<Integer> rowIds = new HashSet<Integer>(); BaseReportInfo sessionReport = sessionData.getReport(); BaseField primaryKey = table.getPrimaryKey(); try { conn = this.dataSource.getConnection(); conn.setAutoCommit(false); ReportDataInfo reportData = new ReportData(conn, sessionReport, false, false); // Generates a SELECT DISTINCT on the primary key including // filterValues & rowLimits in the WHERE clause Map<BaseField, Boolean> emptySorts = new HashMap<BaseField, Boolean>(); Map<BaseField, String> filterValues = sessionData.getReportFilterValues(); PreparedStatement statement = reportData.getReportSqlPreparedStatement(conn, filterValues, false, emptySorts, -1, primaryKey, QuickFilterType.AND, false); ResultSet results = statement.executeQuery(); while (results.next()) { Integer item = results.getInt(1); if (item != null) { rowIds.add(item); } } results.close(); statement.close(); } catch (SQLException sqlex) { // catch exception where field is not included // within report and simply return an empty tree logger.warn(sqlex.toString() + ". Probably occurred because field " + this + " isn't in report " + sessionReport + ", in which case it's nothing to worry about"); } finally { if (conn != null) { conn.close(); } } this.saveRecord(request, table, dataToSave, false, rowIds, sessionData, multipartItems); return rowIds.size(); }
From source file:fi.helsinki.lib.simplerest.BundleResource.java
@Put public Representation editBundle(InputRepresentation rep) { Context c = null;//from w w w . j a v a 2s .c o m Bundle bundle = null; try { c = getAuthenticatedContext(); bundle = Bundle.find(c, this.bundleId); if (bundle == null) { return errorNotFound(c, "Could not find the bundle."); } } catch (SQLException e) { return errorInternal(c, "SQLException"); } DomRepresentation dom = new DomRepresentation(rep); Node attributesNode = dom.getNode("//dl[@id='attributes']"); if (attributesNode == null) { return error(c, "Did not find dl tag with a id 'attributes'.", Status.CLIENT_ERROR_BAD_REQUEST); } int nameFound = 0; int primarybitstreamidFound = 0; NodeList nodes = attributesNode.getChildNodes(); LinkedList<String> dtList = new LinkedList(); LinkedList<String> ddList = new LinkedList(); int nNodes = nodes.getLength(); for (int i = 0; i < nNodes; i++) { Node node = nodes.item(i); String nodeName = node.getNodeName(); if (nodeName.equals("dt")) { dtList.add(node.getTextContent()); } else if (nodeName.equals("dd")) { ddList.add(node.getTextContent()); } } if (dtList.size() != ddList.size()) { return error(c, "The number of <dt> and <dd> elements do not match.", Status.CLIENT_ERROR_BAD_REQUEST); } int size = dtList.size(); for (int i = 0; i < size; i++) { String dt = dtList.get(i); String dd = ddList.get(i); if (dt.equals("name")) { nameFound = 1; bundle.setName(dd); } else if (dt.equals("primarybitstreamid")) { primarybitstreamidFound = 1; Integer id = Integer.parseInt(dd); boolean validBitstreamId = false; Bitstream[] bitstreams = bundle.getBitstreams(); if (id == -1) { // -1 means that we do not want to validBitstreamId = true; // specify the primary bitstream. } else { for (Bitstream bitstream : bitstreams) { if (id == bitstream.getID()) { validBitstreamId = true; break; } } } if (!validBitstreamId) { return error(c, "Invalid primarybitstreamid.", Status.CLIENT_ERROR_UNPROCESSABLE_ENTITY); } if (id == -1) { bundle.unsetPrimaryBitstreamID(); } else { bundle.setPrimaryBitstreamID(id); } } else { return error(c, "Unexpected data in attributes: " + dt, Status.CLIENT_ERROR_BAD_REQUEST); } } // If the was data missing, report it: String[] problems = { "'nameFound' and 'primarybitstreamid'", "'nameFound'", "'primarybitstreamid'", "" }; String problem = problems[primarybitstreamidFound + 2 * nameFound]; if (!problem.equals("")) { return error(c, problem + " was not found from the request.", Status.CLIENT_ERROR_BAD_REQUEST); } try { bundle.update(); c.complete(); } catch (AuthorizeException ae) { return error(c, "Unauthorized", Status.CLIENT_ERROR_UNAUTHORIZED); } catch (Exception e) { return errorInternal(c, e.toString()); } return successOk("Bundle updated."); }
From source file:org.apache.jcs.auxiliary.disk.jdbc.JDBCDiskCache.java
public void doUpdate(ICacheElement ce) { incrementUpdateCount();//from w ww .ja va 2 s . c om if (log.isDebugEnabled()) { log.debug("updating, ce = " + ce); } Connection con; try { con = poolAccess.getConnection(); } catch (SQLException e) { log.error("Problem getting conenction.", e); return; } try { // TEST Statement sStatement = null; try { sStatement = con.createStatement(); alive = true; } catch (SQLException e) { log.error("Problem creating statement.", e); alive = false; } finally { try { sStatement.close(); } catch (SQLException e) { log.error("Problem closing statement.", e); } } if (!alive) { if (log.isInfoEnabled()) { log.info("Disk is not alive, aborting put."); } return; } if (log.isDebugEnabled()) { log.debug("Putting [" + ce.getKey() + "] on disk."); } byte[] element; try { element = serialize(ce); } catch (IOException e) { log.error("Could not serialize element", e); return; } boolean exists = false; // First do a query to determine if the element already exists if (this.getJdbcDiskCacheAttributes().isTestBeforeInsert()) { exists = doesElementExist(ce); } // If it doesn't exist, insert it, otherwise update if (!exists) { try { String sqlI = "insert into " + getJdbcDiskCacheAttributes().getTableName() + " (CACHE_KEY, REGION, ELEMENT, MAX_LIFE_SECONDS, IS_ETERNAL, CREATE_TIME, CREATE_TIME_SECONDS, SYSTEM_EXPIRE_TIME_SECONDS) " + " values (?, ?, ?, ?, ?, ?, ?, ?)"; PreparedStatement psInsert = con.prepareStatement(sqlI); psInsert.setString(1, (String) ce.getKey()); psInsert.setString(2, this.getCacheName()); psInsert.setBytes(3, element); psInsert.setLong(4, ce.getElementAttributes().getMaxLifeSeconds()); if (ce.getElementAttributes().getIsEternal()) { psInsert.setString(5, "T"); } else { psInsert.setString(5, "F"); } Date createTime = new Date(ce.getElementAttributes().getCreateTime()); psInsert.setDate(6, createTime); long now = System.currentTimeMillis() / 1000; psInsert.setLong(7, now); long expireTime = now + ce.getElementAttributes().getMaxLifeSeconds(); psInsert.setLong(8, expireTime); psInsert.execute(); psInsert.close(); } catch (SQLException e) { if (e.toString().indexOf("Violation of unique index") != -1 || e.getMessage().indexOf("Violation of unique index") != -1 || e.getMessage().indexOf("Duplicate entry") != -1) { exists = true; } else { log.error("Could not insert element", e); } // see if it exists, if we didn't already if (!exists && !this.getJdbcDiskCacheAttributes().isTestBeforeInsert()) { exists = doesElementExist(ce); } } } // update if it exists. if (exists) { String sqlU = null; try { sqlU = "update " + getJdbcDiskCacheAttributes().getTableName() + " set ELEMENT = ?, CREATE_TIME = ?, CREATE_TIME_SECONDS = ?, " + " SYSTEM_EXPIRE_TIME_SECONDS = ? " + " where CACHE_KEY = ? and REGION = ?"; PreparedStatement psUpdate = con.prepareStatement(sqlU); psUpdate.setBytes(1, element); Date createTime = new Date(ce.getElementAttributes().getCreateTime()); psUpdate.setDate(2, createTime); long now = System.currentTimeMillis() / 1000; psUpdate.setLong(3, now); long expireTime = now + ce.getElementAttributes().getMaxLifeSeconds(); psUpdate.setLong(4, expireTime); psUpdate.setString(5, (String) ce.getKey()); psUpdate.setString(6, this.getCacheName()); psUpdate.execute(); psUpdate.close(); if (log.isDebugEnabled()) { log.debug("ran update " + sqlU); } } catch (SQLException e2) { log.error("e2 sql [" + sqlU + "] Exception: ", e2); } } } finally { try { con.close(); } catch (SQLException e) { log.error("Problem closing connection.", e); } } if (log.isInfoEnabled()) { if (updateCount % LOG_INTERVAL == 0) { // TODO make a log stats method log.info("Update Count [" + updateCount + "]"); } } }