List of usage examples for java.sql SQLException toString
public String toString()
From source file:dbProcs.Getter.java
/** * The CSRF forum is used in CSRF levels for users to deliver CSRF attacks against each other. URLs are contained in IMG tags * @param ApplicationRoot The current running context of the application * @param classId Identifier of the class to populate the forum with * @param moduleId The module in which to return the forum for * @param bundle The strings package for the language of the user * @return A HTML table of a Class's CSRF Submissions for a specific module */// ww w . j a v a 2 s . co m public static String getCsrfForumWithImg(String ApplicationRoot, String classId, String moduleId, ResourceBundle bundle) { log.debug("*** Getter.getCsrfForum ***"); log.debug("Getting stored messages from class: " + classId); Encoder encoder = ESAPI.encoder(); String htmlOutput = new String(); Connection conn = Database.getCoreConnection(ApplicationRoot); try { if (classId != null) { CallableStatement callstmt = conn.prepareCall("call resultMessageByClass(?, ?)"); log.debug("Gathering resultMessageByClass ResultSet"); callstmt.setString(1, classId); callstmt.setString(2, moduleId); ResultSet resultSet = callstmt.executeQuery(); log.debug("resultMessageByClass executed"); //Table Header htmlOutput = "<table><tr><th>" + bundle.getString("forum.userName") + "</th><th>" + bundle.getString("forum.image") + "</th></tr>"; log.debug("Opening Result Set from resultMessageByClass"); int counter = 0; while (resultSet.next()) { counter++; //Table content htmlOutput += "<tr><td>" + encoder.encodeForHTML(resultSet.getString(1)) + "</td><td><img src=\"" + encoder.encodeForHTMLAttribute(resultSet.getString(2)) + "\"/></td></tr>"; } if (counter > 0) log.debug("Added a " + counter + " row table"); else log.debug("No results from query"); //Table end htmlOutput += "</table>"; } else { log.error("User with Null Class detected"); htmlOutput = "<p><font color='red'>" + bundle.getString("error.noClass") + "</font></p>"; } } catch (SQLException e) { log.error("Could not execute query: " + e.toString()); htmlOutput = "<p>" + bundle.getString("error.occurred") + "</p>"; } catch (Exception e) { log.fatal("Could not return CSRF Forum: " + e.toString()); } Database.closeConnection(conn); log.debug("*** END getCsrfForum ***"); return htmlOutput; }
From source file:dbProcs.Getter.java
/** * Used to present a modules feedback, including averages and raw results. * @param applicationRoot The current running context of the application. * @param moduleId The module identifier * @return A HTML table of the feedback for a specific module *//* w ww . j av a2 s . com*/ public static String getFeedback(String applicationRoot, String moduleId) { log.debug("*** Getter.getFeedback ***"); String result = new String(); Encoder encoder = ESAPI.encoder(); Connection conn = Database.getCoreConnection(applicationRoot); try { log.debug("Preparing userUpdateResult call"); CallableStatement callstmnt = conn.prepareCall("call moduleFeedback(?)"); callstmnt.setString(1, moduleId); log.debug("Executing moduleFeedback"); ResultSet resultSet = callstmnt.executeQuery(); int resultAmount = 0; int before = 0; int after = 0; int difficulty = 0; boolean color = true; while (resultSet.next()) { if (resultSet.getString(1) != null) { resultAmount++; difficulty += resultSet.getInt(3); before += resultSet.getInt(4); after += resultSet.getInt(5); result += "<tr "; if (color) //Alternate row color { color = !color; result += "BGCOLOR='A878EF'"; } else { color = !color; result += "BGCOLOR='D4BCF7'"; } //A row off information result += "><td>" + encoder.encodeForHTML(resultSet.getString(1)) + "</td><td>" + encoder.encodeForHTML(resultSet.getString(2)) + "</td><td>" + resultSet.getInt(3) + "</td><td>" + resultSet.getInt(4) + "</td><td>" + resultSet.getInt(5) + "</td><td>" + encoder.encodeForHTML(resultSet.getString(6)) + "</td></tr>"; } } if (resultAmount > 0)//Table header result = "<table><tr><th>Player</th><th>Time</th><th>Difficulty</th><th>Before</th><th>After</th><th>Comments</th></tr>" + "<tr><td>Average</td><td></td><td>" + difficulty / resultAmount + "</td><td>" + before / resultAmount + "</td><td>" + after / resultAmount + "</td><td></td></tr>" + result + "<table>"; else // If empty, Blank output result = new String(); } catch (SQLException e) { log.error("moduleFeedback Failure: " + e.toString()); result = null; } Database.closeConnection(conn); log.debug("*** END getFeedback ***"); return result; }
From source file:org.castor.cpa.persistence.sql.keygen.HighLowKeyGenerator.java
/** * {@inheritDoc}//from w w w . ja v a2s . c o m */ public synchronized Object generateKey(final Connection conn, final String tableName, final String primKeyName) throws PersistenceException { String intTableName = tableName; if (_global) { intTableName = _globalKey; } HighLowValueHandler<? extends Object> handler = _handlers.get(intTableName); if (handler == null) { if (_sqlType == Types.INTEGER) { KeyGeneratorTypeHandlerInteger typeHandler = new KeyGeneratorTypeHandlerInteger(false); handler = new HighLowValueHandler<Integer>(intTableName, _grabSize, typeHandler); } else if (_sqlType == Types.BIGINT) { KeyGeneratorTypeHandlerLong typeHandler = new KeyGeneratorTypeHandlerLong(false); handler = new HighLowValueHandler<Long>(intTableName, _grabSize, typeHandler); } else { KeyGeneratorTypeHandlerBigDecimal typeHandler = new KeyGeneratorTypeHandlerBigDecimal(false); handler = new HighLowValueHandler<BigDecimal>(intTableName, _grabSize, typeHandler); } _handlers.put(intTableName, handler); } if (!handler.hasNext()) { // Create "SELECT seq_val FROM seq_table WHERE seq_key='table'" // with database-dependent keyword for lock // Note: Some databases (InstantDB, HypersonicSQL) don't support such locks. QueryExpression query = _factory.getQueryExpression(); query.addColumn(_seqTable, _seqValue); query.addCondition(_seqTable, _seqKey, QueryExpression.OP_EQUALS, JDBCSyntax.PARAMETER); String lockSQL = query.getStatement(true); // For the case that "SELECT FOR UPDATE" is not supported, perform dirty checking String updateSQL = "UPDATE " + _seqTable + " SET " + _seqValue + "=" + JDBCSyntax.PARAMETER + JDBCSyntax.WHERE + _seqKey + QueryExpression.OP_EQUALS + JDBCSyntax.PARAMETER + JDBCSyntax.AND + _seqValue + QueryExpression.OP_EQUALS + JDBCSyntax.PARAMETER; String maxSQL = JDBCSyntax.SELECT + "MAX(" + primKeyName + ") " + "FROM " + intTableName; String insertSQL = "INSERT INTO " + _seqTable + " (" + _seqKey + "," + _seqValue + ") VALUES (?, ?)"; PreparedStatement stmt = null; try { // Separate connection should be committed/rolled back at this point if (!_sameConnection) { conn.rollback(); } // Retry 7 times (lucky number) boolean success = false; for (int i = 0; !success && (i < LOCK_TRIALS); i++) { stmt = conn.prepareStatement(lockSQL); handler.bindTable(stmt, 1); ResultSet rs = stmt.executeQuery(); handler.init(rs); boolean found = rs.isFirst(); stmt.close(); if (found) { stmt = conn.prepareStatement(updateSQL); handler.bindMax(stmt, UPDATE_PARAM_MAX); handler.bindTable(stmt, UPDATE_PARAM_TABLE); handler.bindLast(stmt, UPDATE_PARAM_LAST); success = (stmt.executeUpdate() == 1); stmt.close(); } else { if (!_global) { stmt = conn.prepareStatement(maxSQL); rs = stmt.executeQuery(); handler.init(rs); stmt.close(); } stmt = conn.prepareStatement(insertSQL); handler.bindTable(stmt, INSERT_PARAM_TABLE); handler.bindMax(stmt, INSERT_PARAM_MAX); success = (stmt.executeUpdate() == 1); stmt.close(); } } if (success) { if (!_sameConnection) { conn.commit(); } } else { if (!_sameConnection) { conn.rollback(); } throw new PersistenceException(Messages.format("persist.keyGenFailed", getClass().getName())); } } catch (SQLException ex) { try { if (!_sameConnection) { conn.rollback(); } } catch (SQLException ex2) { LOG.warn("Problem rolling back JDBC transaction.", ex2); } throw new PersistenceException( Messages.format("persist.keyGenSQL", getClass().getName(), ex.toString()), ex); } finally { try { if (stmt != null) { stmt.close(); } } catch (SQLException ex) { LOG.warn(Messages.message("persist.stClosingFailed"), ex); } } } return handler.next(); }
From source file:com.strider.datadefender.DatabaseAnonymizer.java
/** * Anonymization function for a single table. * /*from ww w. j av a2 s . co m*/ * Sets up queries, loops over columns and anonymizes columns for the passed * Table. * * @param table */ private void anonymizeTable(final int batchSize, final IDBFactory dbFactory, final Table table) throws DatabaseAnonymizerException { log.info("Table [" + table.getName() + "]. Start ..."); final List<Column> tableColumns = table.getColumns(); // colNames is looked up with contains, and iterated over. Using LinkedHashSet means // duplicate column names won't be added to the query, so a check in the column loop // below was created to ensure a reasonable warning message is logged if that happens. final Set<String> colNames = new LinkedHashSet<>(tableColumns.size()); // keyNames is only iterated over, so no need for a hash set final List<String> keyNames = new LinkedList<>(); fillColumnNames(table, colNames); fillPrimaryKeyNamesList(table, keyNames); // required in this scope for 'catch' block PreparedStatement selectStmt = null; PreparedStatement updateStmt = null; ResultSet rs = null; final Connection updateCon = dbFactory.getUpdateConnection(); try { selectStmt = getSelectQueryStatement(dbFactory, table, keyNames, colNames); rs = selectStmt.executeQuery(); final List<MatchMetaData> columnMetaData = dbFactory.fetchMetaData().getMetaDataForRs(rs); final String updateString = getUpdateQuery(table, colNames, keyNames); updateStmt = updateCon.prepareStatement(updateString); int batchCounter = 0; int rowCount = 0; while (rs.next()) { anonymizeRow(updateStmt, tableColumns, keyNames, updateCon, rs, columnMetaData, dbFactory.getVendorName()); batchCounter++; if (batchCounter == batchSize) { updateStmt.executeBatch(); updateCon.commit(); batchCounter = 0; } rowCount++; } log.debug("Rows processed: " + rowCount); updateStmt.executeBatch(); log.debug("Batch executed"); updateCon.commit(); log.debug("Commit"); selectStmt.close(); updateStmt.close(); rs.close(); log.debug("Closing open resources"); } catch (SQLException | NoSuchMethodException | SecurityException | IllegalAccessException | IllegalArgumentException | InvocationTargetException | DatabaseDiscoveryException ex) { log.error(ex.toString()); if (ex.getCause() != null) { log.error(ex.getCause().toString()); } try { if (selectStmt != null) { selectStmt.close(); } if (updateStmt != null) { updateStmt.close(); } if (rs != null) { rs.close(); } } catch (SQLException sqlex) { log.error(sqlex.toString()); } } finally { try { if (selectStmt != null) { selectStmt.close(); } if (updateStmt != null) { updateStmt.close(); } if (rs != null) { rs.close(); } } catch (SQLException sqlex) { log.error(sqlex.toString()); } } log.info("Table " + table.getName() + ". End ..."); log.info(""); }
From source file:org.kawanfw.sql.servlet.sql.ServerCallableStatement.java
/** * Execute the passed SQL Statement and return: <br> * - The result set as a List of Maps for SELECT statements. <br> * - The return code for other statements * /*from ww w . ja v a 2 s . co m*/ * @param sqlOrder * the qsql order * @param sqlParms * the sql parameters * @param out * the output stream where to write to result set output * * * @throws SQLException */ private void callStatement(OutputStream out) throws SQLException, IOException { String sqlOrder = callableStatementHolder.getSqlOrder(); debug("callableStatementHolder: " + callableStatementHolder.getSqlOrder()); debug("sqlOrder : " + sqlOrder); CallableStatement callableStatement = null; callableStatement = connection.prepareCall(sqlOrder); Map<Integer, Integer> parameterTypes = null; Map<Integer, String> parameterStringValues = null; // Class to set all the statement parameters ServerCallableStatementParameters serverCallableStatementParameters = null; try { ServerSqlUtilCallable.setCallableStatementProperties(callableStatement, callableStatementHolder); parameterTypes = callableStatementHolder.getParameterTypes(); parameterStringValues = callableStatementHolder.getParameterStringValues(); debug("before serverCallableStatementParameters"); serverCallableStatementParameters = new ServerCallableStatementParameters(username, fileConfigurator, callableStatement, callableStatementHolder); serverCallableStatementParameters.setParameters(); // Throws a SQL exception if the order is not authorized: debug("before new SqlSecurityChecker()"); boolean isAllowedAfterAnalysis = true; /* * boolean isAllowedAfterAnalysis = sqlConfigurator * .allowStatementAfterAnalysis(username, connection, sqlOrder, * serverPreparedStatementParameters .getParameterValues()); */ if (!isAllowedAfterAnalysis) { String ipAddress = request.getRemoteAddr(); SqlConfiguratorCall.runIfStatementRefused(sqlConfigurator, username, connection, ipAddress, sqlOrder, serverCallableStatementParameters.getParameterValues()); String message = Tag.PRODUCT_SECURITY + " [" + "{Callable Statement not authorized}" + "{sql order : " + sqlOrder + "}" + "{sql parms : " + parameterTypes + "}" + "{sql values: " + parameterStringValues + "}]"; throw new SecurityException(message); } isAllowedAfterAnalysis = SqlConfiguratorCall.allowResultSetGetMetaData(sqlConfigurator, username, connection); debug("before callableStatement.executeQuery() / execute"); ServerSqlUtil.setMaxRowsToReturn(callableStatement, sqlConfigurator); ResultSet rs = null; boolean hasResultSet = false; if (isExecuteRaw) { hasResultSet = callableStatement.execute(); if (hasResultSet) { rs = callableStatement.getResultSet(); } } else { rs = callableStatement.executeQuery(); } // 1) Update and send back the CallableStatementHolder: updateCallableStatementHolderValues(callableStatement); //out.write(TransferStatus.SEND_OK + CR_LF); ServerSqlManager.writeLine(out, TransferStatus.SEND_OK); String jsonString = CallableStatementHolderTransportJson.toJson(callableStatementHolder); boolean doEncryptCallableStatement = SqlConfiguratorCall.encryptResultSet(sqlConfigurator); if (doEncryptCallableStatement) { jsonString = JsonLineEncrypter.encrypt(jsonString, commonsConfigurator); } //out.write(jsonString + CR_LF); ServerSqlManager.writeLine(out, jsonString); // 2) Send back the result set: if (hasResultSet || !isExecuteRaw) { try { // Horrible hack because ResultSetWriter is in common CE/EE // code and // we can't modify it now (to be clean in next CE version): StatementHolder statementHolder = new StatementHolder(); statementHolder.setHtmlEncodingOn(callableStatementHolder.isHtmlEncodingOn()); ResultSetWriter resultSetWriter = new ResultSetWriter(request, out, commonsConfigurator, fileConfigurator, sqlConfigurator, username, sqlOrder, statementHolder); resultSetWriter.write(rs); } finally { if (rs != null) { rs.close(); } } } else { // Write a line saying there is no Result Set! //out.write(CallableParms.NO_RESULT_SET + CR_LF); ServerSqlManager.writeLine(out, CallableParms.NO_RESULT_SET); } } catch (SQLException e) { ServerLogger.getLogger().log(Level.WARNING, Tag.PRODUCT_EXCEPTION_RAISED + CR_LF + "CallableStatement statement: " + sqlOrder + CR_LF + "- sql order : " + sqlOrder + CR_LF + "- sql parms : " + parameterTypes + CR_LF + "- sql values: " + parameterStringValues + CR_LF + "- exception : " + e.toString()); throw e; } finally { // Close the ServerPreparedStatementParameters if (serverCallableStatementParameters != null) { serverCallableStatementParameters.close(); } if (callableStatement != null) { callableStatement.close(); } // Clean all parameterTypes = null; parameterStringValues = null; serverCallableStatementParameters = null; } }
From source file:edu.ku.brc.specify.datamodel.Division.java
/** * @return a list of title (or names) of the Disciplines that the Division owns. *//* www .j a v a 2 s . c om*/ @Transient public List<String> getDisciplineList() { List<String> list = new Vector<String>(); Connection conn = null; Statement stmt = null; try { conn = DBConnection.getInstance().createConnection(); stmt = conn.createStatement(); String sql = "SELECT Title,Name FROM discipline where DivisionID = " + getId(); ResultSet rs = stmt.executeQuery(sql); while (rs.next()) { String dspTitle = rs.getString(1); if (StringUtils.isEmpty(dspTitle)) { dspTitle = rs.getString(2); } list.add(dspTitle); } rs.close(); Collections.sort(list); return list; } catch (SQLException ex) { edu.ku.brc.af.core.UsageTracker.incrSQLUsageCount(); edu.ku.brc.exceptions.ExceptionTracker.getInstance().capture(Division.class, ex); System.err.println("SQLException: " + ex.toString()); //$NON-NLS-1$ System.err.println(ex.getMessage()); } finally { try { if (stmt != null) { stmt.close(); } if (conn != null) { conn.close(); } } catch (Exception ex) { edu.ku.brc.af.core.UsageTracker.incrHandledUsageCount(); edu.ku.brc.exceptions.ExceptionTracker.getInstance().capture(Division.class, ex); ex.printStackTrace(); } } return list; }
From source file:dbProcs.Getter.java
/** * Use to return the current progress of a class in JSON format with information like userid, user name and score * @param applicationRoot The current running context of the application * @param classId The identifier of the class to use in lookup * @return A JSON representation of a class's score in the order {id, username, userTitle, score, scale, place, order, * goldmedalcount, goldDisplay, silverMedalCount, silverDisplay, bronzeDisplay, bronzeMedalCount} *//* ww w . ja v a2s.c o m*/ @SuppressWarnings("unchecked") public static String getJsonScore(String applicationRoot, String classId) { log.debug("classId: " + classId); String result = new String(); Connection conn = Database.getCoreConnection(applicationRoot); try { Encoder encoder = ESAPI.encoder(); //Returns User's: Name, # of Completed modules and Score CallableStatement callstmnt = null; if (ScoreboardStatus.getScoreboardClass().isEmpty() && !ScoreboardStatus.isClassSpecificScoreboard()) callstmnt = conn.prepareCall("call totalScoreboard()"); //Open Scoreboard not based on a class else { callstmnt = conn.prepareCall("call classScoreboard(?)"); //Class Scoreboard based on classId callstmnt.setString(1, classId); } //log.debug("Executing classScoreboard"); ResultSet resultSet = callstmnt.executeQuery(); JSONArray json = new JSONArray(); JSONObject jsonInner = new JSONObject(); int resultAmount = 0; int prevPlace = 0; int prevScore = 0; int prevGold = 0; int prevSilver = 0; int prevBronze = 0; float baseBarScale = 0; // float tieBreaker = 0; while (resultSet.next()) //For each user in a class { resultAmount++; jsonInner = new JSONObject(); if (resultSet.getString(1) != null) { int place = resultAmount; int score = resultSet.getInt(3); int goldMedals = resultSet.getInt(4); int silverMedals = resultSet.getInt(5); int bronzeMedals = resultSet.getInt(6); if (resultAmount == 1) //First Place is Returned First, so this will be the biggest bar on the scoreboard { int highscore = score; //log.debug("Current Highscore Listing is " + highscore); //Use the high score to scale the width of the bars for the whole scoreboard float maxBarScale = 1.02f; //High Score bar will have a scale of 1 //This will get used when a scale is added to the scoreboard baseBarScale = highscore * maxBarScale; //setting up variables for Tie Scenario Placings prevPlace = 1; prevScore = score; } else { //Does this score line match the one before (Score and Medals)? if so the place shouldnt change if (score == prevScore && goldMedals == prevGold && silverMedals == prevSilver && bronzeMedals == prevBronze) { place = prevPlace; tieBreaker = tieBreaker + 0.01f; } else { prevScore = score; prevPlace = place; prevGold = goldMedals; prevSilver = silverMedals; prevBronze = bronzeMedals; tieBreaker = 0; } } String displayMedal = new String("display: inline;"); String goldDisplayStyle = new String("display: none;"); String silverDisplayStyle = new String("display: none;"); String bronzeDisplayStyle = new String("display: none;"); if (goldMedals > 0) goldDisplayStyle = displayMedal; if (silverMedals > 0) silverDisplayStyle = displayMedal; if (bronzeMedals > 0) bronzeDisplayStyle = displayMedal; int barScale = (int) ((score * 100) / baseBarScale); //bar scale is the percentage the bar should be of the row's context (Highest Possible is depends on scale set in maxBarScale. eg: maxBarScale = 1.1 would mean the max scale would be 91% for a single row) String userMedalString = new String(); if (goldMedals > 0 || silverMedals > 0 || bronzeMedals > 0) { userMedalString += " holding "; if (goldMedals > 0) userMedalString += goldMedals + " gold"; if (silverMedals > 0) { if (goldMedals > 0) //Medals Before, puncuate { if (bronzeMedals > 0) //more medals after silver? Comma { userMedalString += ", "; } else //Say And { userMedalString += " and "; } } userMedalString += silverMedals + " silver"; } if (bronzeMedals > 0) { if (goldMedals > 0 || silverMedals > 0) //Medals Before? { userMedalString += " and "; } userMedalString += bronzeMedals + " bronze"; } //Say Medal(s) at the end of the string userMedalString += " medal"; if (goldMedals + silverMedals + bronzeMedals > 1) userMedalString += "s"; } jsonInner.put("id", new String(encoder.encodeForHTML(resultSet.getString(1)))); //User Id jsonInner.put("username", new String(encoder.encodeForHTML(resultSet.getString(2)))); //User Name jsonInner.put("userTitle", new String(encoder.encodeForHTML(resultSet.getString(2)) + " with " + score + " points" + userMedalString)); //User name encoded for title attribute jsonInner.put("score", new Integer(score)); //Score jsonInner.put("scale", barScale); //Scale of score bar jsonInner.put("place", place); //Place on board jsonInner.put("order", (place + tieBreaker)); //Order on board jsonInner.put("goldMedalCount", new Integer(goldMedals)); jsonInner.put("goldDisplay", goldDisplayStyle); jsonInner.put("silverMedalCount", new Integer(silverMedals)); jsonInner.put("silverDisplay", silverDisplayStyle); jsonInner.put("bronzeMedalCount", new Integer(bronzeMedals)); jsonInner.put("bronzeDisplay", bronzeDisplayStyle); //log.debug("Adding: " + jsonInner.toString()); json.add(jsonInner); } } if (resultAmount > 0) result = json.toString(); else result = new String(); } catch (SQLException e) { log.error("getJsonScore Failure: " + e.toString()); result = null; } catch (Exception e) { log.error("getJsonScore Unexpected Failure: " + e.toString()); result = null; } Database.closeConnection(conn); //log.debug("*** END getJsonScore ***"); return result; }
From source file:org.metis.push.PusherBean.java
/** * Called by Spring after all of this bean's properties have been set. *///from w w w. j a v a 2 s .com public void afterPropertiesSet() throws Exception { // create the session registry setWdsSessions(new Hashtable<String, WdsSocketSession>(getInitCapacity())); // log info for the jdbc driver being used // this will also attempt to open connection // with jdbc driver try { Connection con = getDataSource().getConnection(); if (con != null) { DatabaseMetaData dbmd = con.getMetaData(); setDbConnectionAcquired(true); if (dbmd != null) { setDriverName(dbmd.getDriverName().trim().toLowerCase()); // record the URL to the DB setDbUrl(dbmd.getURL().trim()); isOracle = (getDriverName() != null && getDriverName().indexOf(ORACLE_STR) >= 0) ? true : false; LOG.info(getBeanName() + ":Is Oracle JDBC Driver = " + isOracle); LOG.info(getBeanName() + ":JDBC Driver name = " + getDriverName()); LOG.info(getBeanName() + ":JDBC Driver version = " + dbmd.getDriverVersion().trim()); LOG.info(getBeanName() + ":JDBC Driver product name = " + dbmd.getDatabaseProductName().trim()); LOG.info(getBeanName() + ":JDBC URL = " + getDbUrl()); LOG.info(getBeanName() + ":JDBC Driver database product version = " + dbmd.getDatabaseProductVersion().trim()); con.close(); } else { LOG.info(getBeanName() + ": Unable to get JDBC driver meta data"); } } else { LOG.info(getBeanName() + ": Unable to get JDBC connection"); } } catch (SQLException exc) { LOG.error(getBeanName() + ": got this exception when trying to " + "get driver meta data: " + exc.toString()); LOG.error(getBeanName() + ": exception stack trace follows:"); dumpStackTrace(exc.getStackTrace()); LOG.error(getBeanName() + ": Caused by " + exc.getCause().toString()); LOG.error(getBeanName() + ": causing exception stack trace follows:"); dumpStackTrace(exc.getCause().getStackTrace()); } // bean must be assigned a JDBC DataSource if (getDataSource() == null) { throw new Exception( getBeanName() + ".afterPropertiesSet: this bean has not been " + "assigned a JDBC DataSource"); } // do some validation if (getSqls4Get() == null) { throw new Exception("The PusherBean must be assigned at least one SQL statement"); } // create and validate the injected SQL statements sqlStmnts4Get = new ArrayList<SqlStmnt>(); for (String sql : getSqls4Get()) { // get the frequency settings Map<String, Long> map = Utils.parseTimeInterval(sql); sql = Utils.stripTimeInterval(sql); sql = Utils.stripCall(sql); SqlStmnt stmt = getSQLStmnt(this, sql, getJdbcTemplate()); if (stmt.isEqual(sqlStmnts4Get)) { throw new Exception("Injected SQL statements for GET are not distinct"); } // set the frequency stmt.setIntervalTime(map.get(TIME_INTERVAL)); if (map.get(TIME_INTERVAL_MAX) != null) { stmt.setIntervalMax(map.get(TIME_INTERVAL_MAX)); } if (map.get(TIME_INTERVAL_STEP) != null) { stmt.setIntervalStep(map.get(TIME_INTERVAL_STEP)); } sqlStmnts4Get.add(stmt); } if (LOG.isDebugEnabled()) { for (SqlStmnt sqlstmnt : sqlStmnts4Get) { LOG.debug(getBeanName() + ": SQL for GET = " + sqlstmnt.getOriginal()); LOG.debug(getBeanName() + ": Parameterized SQL for GET = " + sqlstmnt.getPrepared()); } } if (getHazelcastInstance() != null) { LOG.debug(getBeanName() + ": My Hazelcast Instance Name = " + getHazelcastInstance().getName()); ; } }
From source file:com.cloudera.sqoop.manager.SqlManager.java
/** * Get column names for a query statement that we do not modify further. *///from w w w . j av a 2s. c om public String[] getColumnNamesForRawQuery(String stmt) { ResultSet results; try { results = execute(stmt); } catch (SQLException sqlE) { LOG.error("Error executing statement: " + sqlE.toString(), sqlE); release(); return null; } try { int cols = results.getMetaData().getColumnCount(); ArrayList<String> columns = new ArrayList<String>(); ResultSetMetaData metadata = results.getMetaData(); for (int i = 1; i < cols + 1; i++) { String colName = metadata.getColumnName(i); if (colName == null || colName.equals("")) { colName = metadata.getColumnLabel(i); if (null == colName) { colName = "_RESULT_" + i; } } columns.add(colName); } return columns.toArray(new String[0]); } catch (SQLException sqlException) { LOG.error("Error reading from database: " + sqlException.toString(), sqlException); return null; } finally { try { results.close(); getConnection().commit(); } catch (SQLException sqlE) { LOG.warn("SQLException closing ResultSet: " + sqlE.toString(), sqlE); } release(); } }
From source file:com.cloudera.sqoop.manager.SqlManager.java
/** * Get column types for a query statement that we do not modify further. *//*from w w w . ja va2s .c o m*/ protected Map<String, Integer> getColumnTypesForRawQuery(String stmt) { ResultSet results; try { results = execute(stmt); } catch (SQLException sqlE) { LOG.error("Error executing statement: " + sqlE.toString()); release(); return null; } try { Map<String, Integer> colTypes = new HashMap<String, Integer>(); int cols = results.getMetaData().getColumnCount(); ResultSetMetaData metadata = results.getMetaData(); for (int i = 1; i < cols + 1; i++) { int typeId = metadata.getColumnType(i); String colName = metadata.getColumnName(i); if (colName == null || colName.equals("")) { colName = metadata.getColumnLabel(i); } colTypes.put(colName, Integer.valueOf(typeId)); } return colTypes; } catch (SQLException sqlException) { LOG.error("Error reading from database: " + sqlException.toString()); return null; } finally { try { results.close(); getConnection().commit(); } catch (SQLException sqlE) { LOG.warn("SQLException closing ResultSet: " + sqlE.toString()); } release(); } }