List of usage examples for java.sql SQLException getMessage
public String getMessage()
From source file:TaskManager.java
public static String readException(SQLException sqlX) { StringBuffer msg = new StringBuffer(1024); SQLException nextX;/*from w w w . java 2s . co m*/ int exceptionNumber = 0; do { ++exceptionNumber; msg.append("Exception " + exceptionNumber + ": \n"); msg.append(" Message: " + sqlX.getMessage() + "\n"); msg.append(" State : " + sqlX.getSQLState() + "\n"); msg.append(" Code : " + sqlX.getErrorCode() + "\n"); } while ((nextX = sqlX.getNextException()) != null); return (msg.toString()); }
From source file:com.wso2telco.dbUtil.DataBaseConnectUtils.java
/** * Close PreparedStatement/*from w ww . ja v a 2 s . c o m*/ * * @param preparedStatement PreparedStatement */ private static void closeStatement(PreparedStatement preparedStatement) { if (preparedStatement != null) { try { preparedStatement.close(); } catch (SQLException e) { log.error("Database error. Could not close PreparedStatement. Continuing with others. - " + e.getMessage(), e); } } }
From source file:com.wso2telco.dbUtil.DataBaseConnectUtils.java
/** * Close Connection/*w ww. j av a 2 s . c o m*/ * * @param dbConnection Connection */ private static void closeConnection(Connection dbConnection) { if (dbConnection != null) { try { dbConnection.close(); } catch (SQLException e) { log.error("Database error. Could not close database connection. Continuing with others. - " + e.getMessage(), e); } } }
From source file:db_classes.DBManager.java
public static void shutdown() { try {/*from w ww . j ava 2 s. co m*/ DriverManager.getConnection("jdbc:postgresql:;shutdown=true"); } catch (SQLException ex) { Logger.getLogger(DBManager.class.getName()).info(ex.getMessage()); } }
From source file:com.wso2telco.proxy.util.DBUtils.java
/** * Get a map of parameters mapped to a scope * * @return map of scope vs parameters//from ww w. j a v a 2s . com * @throws AuthenticatorException on errors */ public static Map<String, ScopeParam> getScopeParams(String scope) throws AuthenticatorException { Connection conn = null; PreparedStatement ps = null; ResultSet results = null; String[] scopeValues = scope.split("\\s+|\\+"); StringBuilder params = new StringBuilder("?"); for (int i = 1; i < scopeValues.length; i++) { params.append(",?"); } String sql = "SELECT * FROM `scope_parameter` WHERE scope in (" + params + ")"; if (log.isDebugEnabled()) { log.debug("Executing the query " + sql); } Map scopeParamsMap = new HashMap(); try { conn = getConnectDBConnection(); ps = conn.prepareStatement(sql); for (int i = 0; i < scopeValues.length; i++) { ps.setString(i + 1, scopeValues[i]); } results = ps.executeQuery(); Boolean mainScopeFound = false; List<String> scopeValuesFromDatabase = new ArrayList<>(); while (results.next()) { Boolean isMultiscope = results.getBoolean("is_multiscope"); scopeValuesFromDatabase.add(results.getString("scope")); if (!isMultiscope) { //throw error if multiple main scopes found if (mainScopeFound) { throw new ConfigurationException("Multiple main scopes found"); } //mark as main scope found mainScopeFound = true; scopeParamsMap.put("scope", results.getString("scope")); ScopeParam parameters = new ScopeParam(); parameters.setScope(results.getString("scope")); parameters.setLoginHintMandatory(results.getBoolean("is_login_hint_mandatory")); parameters.setHeaderMsisdnMandatory(results.getBoolean("is_header_msisdn_mandatory")); parameters.setMsisdnMismatchResult(ScopeParam.msisdnMismatchResultTypes .valueOf(results.getString("msisdn_mismatch_result"))); parameters.setHeFailureResult( ScopeParam.heFailureResults.valueOf(results.getString("he_failure_result"))); parameters.setTncVisible(results.getBoolean("is_tnc_visible")); parameters.setLoginHintFormat(getLoginHintFormatTypeDetails(results.getInt("param_id"), conn)); scopeParamsMap.put("params", parameters); } } //validate all scopes and compare with scopes fetched from database for (String scopeToValidate : scopeValues) { if (!scopeValuesFromDatabase.contains(scopeToValidate)) { throw new ConfigurationException("One or more scopes are not valid"); } } } catch (SQLException e) { handleException("Error occurred while getting scope parameters from the database", e); } catch (ConfigurationException e) { handleException(e.getMessage(), e); } catch (NamingException e) { log.error("Naming exception ", e); } finally { closeAllConnections(ps, conn, results); } return scopeParamsMap; }
From source file:com.flexive.core.security.FxDBAuthentication.java
/** * Login a user using flexive's database * * @param loginname name of the user//from ww w.ja v a 2 s . c om * @param password plaintext password * @param callback callback providing datasource, ejb context and "take over" * @return Authenticated UserTicket * @throws FxAccountInUseException on errors * @throws FxLoginFailedException on errors * @throws FxAccountExpiredException on errors */ public static UserTicket login(String loginname, String password, FxCallback callback) throws FxAccountInUseException, FxLoginFailedException, FxAccountExpiredException { final long SYS_UP = CacheAdmin.getInstance().getSystemStartTime(); FxContext inf = FxContext.get(); // Avoid null pointer exceptions if (password == null) password = ""; if (loginname == null) loginname = ""; final String applicationId = StringUtils.defaultString(inf.getApplicationId()); if (StringUtils.isBlank(applicationId)) { LOG.warn("Login: application ID is not set"); } String curSql; PreparedStatement ps = null; Connection con = null; try { // Obtain a database connection con = callback.getDataSource().getConnection(); // 1-6 7 8 9 10 11 12 13 14 15 16 curSql = "SELECT d.*,a.ID,a.IS_ACTIVE,a.IS_VALIDATED,a.ALLOW_MULTILOGIN,a.VALID_FROM,a.VALID_TO,NOW(),a.PASSWORD,a.MANDATOR,a.LOGIN_NAME " + "FROM " + TBL_ACCOUNTS + " a " + "LEFT JOIN " + " (SELECT ID,ISLOGGEDIN,LAST_LOGIN,LAST_LOGIN_FROM,FAILED_ATTEMPTS,AUTHSRC FROM " + TBL_ACCOUNT_DETAILS + " WHERE APPLICATION=? ORDER BY LAST_LOGIN DESC) d ON a.ID=d.ID WHERE UPPER(a.LOGIN_NAME)=UPPER(?)"; ps = con.prepareStatement(curSql); ps.setString(1, applicationId); ps.setString(2, loginname); final ResultSet rs = ps.executeQuery(); // Anything found? if (rs == null || !rs.next()) throw new FxLoginFailedException("Login failed (invalid user or password)", FxLoginFailedException.TYPE_USER_OR_PASSWORD_NOT_DEFINED); // check if the hashed password matches the hash stored in the database final long id = rs.getLong(7); final String dbLoginName = rs.getString(16); // use DB login name for non-lowercase login names final String dbPassword = rs.getString(14); boolean passwordMatches = FxSharedUtils.hashPassword(id, dbLoginName, password).equals(dbPassword); if (!passwordMatches && "supervisor".equalsIgnoreCase(loginname)) { // before 3.2.0 the default supervisor password was incorrectly hashed against the lower-cased login name passwordMatches = FxSharedUtils.hashPassword(id, "supervisor", password).equals(dbPassword); } if (!passwordMatches && !callback.isCalledAsGlobalSupervisor()) { increaseFailedLoginAttempts(con, id); throw new FxLoginFailedException("Login failed (invalid user or password)", FxLoginFailedException.TYPE_USER_OR_PASSWORD_NOT_DEFINED); } // Read data final boolean loggedIn = rs.getBoolean(2); final Date lastLogin = new Date(rs.getLong(3)); final String lastLoginFrom = rs.getString(4); final long failedAttempts = rs.getLong(5); final boolean active = rs.getBoolean(8); final boolean validated = rs.getBoolean(9); final boolean allowMultiLogin = rs.getBoolean(10); final Date validFrom = new Date(rs.getLong(11)); final Date validTo = new Date(rs.getLong(12)); final Date dbNow = rs.getTimestamp(13); final long mandator = rs.getLong(15); // Account active? if (!active || !validated || (CacheAdmin.isEnvironmentLoaded() && !CacheAdmin.getEnvironment().getMandator(mandator).isActive())) { if (LOG.isDebugEnabled()) LOG.debug("Login for user [" + loginname + "] failed, account is inactive. Active=" + active + ", Validated=" + validated + ", Mandator active: " + CacheAdmin.getEnvironment().getMandator(mandator).isActive()); increaseFailedLoginAttempts(con, id); throw new FxLoginFailedException("Login failed, account is inactive.", FxLoginFailedException.TYPE_INACTIVE_ACCOUNT); } // Account date from-to valid? //Compute the day AFTER the dValidTo Calendar endDate = Calendar.getInstance(); endDate.setTime(validTo); endDate.add(Calendar.DAY_OF_MONTH, 1); if (validFrom.getTime() > dbNow.getTime() || endDate.getTimeInMillis() < dbNow.getTime()) { SimpleDateFormat sdf = new SimpleDateFormat("dd-MM-yyyy"); if (LOG.isDebugEnabled()) LOG.debug("Login for user [" + loginname + "] failed, from/to date not valid. from='" + sdf.format(validFrom) + "' to='" + validTo + "'"); increaseFailedLoginAttempts(con, id); throw new FxAccountExpiredException(loginname, dbNow); } // Check 'Account in use and takeOver false' if (!allowMultiLogin && !callback.getTakeOverSession() && loggedIn && lastLogin != null) { // Only if the last login time was AFTER the system started if (lastLogin.getTime() >= SYS_UP) { FxAccountInUseException aiu = new FxAccountInUseException(loginname, lastLoginFrom, lastLogin); if (LOG.isInfoEnabled()) LOG.info(aiu); // don't log this as an invalid login attempt - this happens routinely when a session times // out and the cached session data has not been evicted by the maintenance task yet //increaseFailedLoginAttempts(con, id); throw aiu; } } // Clear any old data curSql = "DELETE FROM " + TBL_ACCOUNT_DETAILS + " WHERE ID=? AND APPLICATION=?"; ps.close(); ps = con.prepareStatement(curSql); ps.setLong(1, id); ps.setString(2, applicationId); ps.executeUpdate(); // Mark user as active in the database // This can lead to duplicate rows for a user/application for concurrent logins (e.g. WebDAV clients), // but we prefer this to actually locking the complete table before updates. (FX-868) curSql = "INSERT INTO " + TBL_ACCOUNT_DETAILS + " (ID,APPLICATION,ISLOGGEDIN,LAST_LOGIN,LAST_LOGIN_FROM,FAILED_ATTEMPTS,AUTHSRC) " + "VALUES (?,?,?,?,?,?,?)"; ps.close(); ps = con.prepareStatement(curSql); ps.setLong(1, id); ps.setString(2, applicationId); ps.setBoolean(3, true); ps.setLong(4, System.currentTimeMillis()); ps.setString(5, inf.getRemoteHost()); ps.setLong(6, 0); //reset failed attempts ps.setString(7, AuthenticationSource.Database.name()); ps.executeUpdate(); // Load the user and construct a user ticket try { final UserTicketImpl ticket = (UserTicketImpl) UserTicketStore.getUserTicket(loginname); ticket.setFailedLoginAttempts(failedAttempts); ticket.setAuthenticationSource(AuthenticationSource.Database); return ticket; } catch (FxApplicationException e) { if (callback.getSessionContext() != null) callback.getSessionContext().setRollbackOnly(); throw new FxLoginFailedException( e.getExceptionMessage().getLocalizedMessage( CacheAdmin.getEnvironment().getLanguage(FxLanguage.DEFAULT_ID)), FxLoginFailedException.TYPE_UNKNOWN_ERROR); } } catch (SQLException exc) { if (callback.getSessionContext() != null) callback.getSessionContext().setRollbackOnly(); throw new FxLoginFailedException("Database error: " + exc.getMessage(), FxLoginFailedException.TYPE_SQL_ERROR); } finally { Database.closeObjects(FxDBAuthentication.class, con, ps); } }
From source file:es.tekniker.framework.ktek.questionnaire.mng.db.QuestionnaireLoadFile.java
public static boolean loadData(List<String> data) { boolean boolOK = true; PersistentSession session = null;//from ww w . j av a 2 s . c o m PersistentTransaction tr = null; Statement st; StringBuffer sql = null; String[] dataline = null; String tablename = null; try { session = KTEKPersistentManager.instance().getSession(); tr = session.beginTransaction(); try { st = session.connection().createStatement(); System.out.println(data.size()); for (int i = 0; i < data.size(); i++) { dataline = data.get(i).split(";"); log.debug("data by line " + data.get(i) + " num items " + dataline.length + " data line 0 " + dataline[0]); tablename = dataline[0]; tablename = tablename.trim(); sql = null; if (tablename.equals(TABLE_ktek_questionnaire)) sql = getSQL4_Table_Questionnaire(dataline); else if (dataline[0].equals(TABLE_ktek_formatquestionnaire)) sql = getSQL4_Table_Formatquestionnaire(dataline); else if (dataline[0].equals(TABLE_ktek_questionnairesection)) sql = getSQL4_Table_Questionnairesection(dataline); else if (dataline[0].equals(TABLE_ktek_questionnaireitem)) sql = getSQL4_Table_Questionnaireitem(dataline); else if (dataline[0].equals(TABLE_ktek_question)) sql = getSQL4_Table_Question(dataline); else if (dataline[0].equals(TABLE_ktek_answer)) sql = getSQL4_Table_Answer(dataline); else if (dataline[0].equals(TABLE_ktek_answerset)) sql = getSQL4_Table_Answerset(dataline); else if (dataline[0].equals(TABLE_ktek_answerset_answer)) sql = getSQL4_Table_Answerset_answer(dataline); else if (dataline[0].equals(TABLE_ktek_qitem_section)) sql = getSQL4_Table_Qitemsection(dataline); else if (dataline[0].equals(TABLE_ktek_qsection_questionnaire)) sql = getSQL4_Table_Qsectionquestionnaire(dataline); else if (dataline[0].equals(TABLE_ktek_parameter)) sql = getSQL4_Table_Parameter(dataline); else if (dataline[0].equals(TABLE_ktek_unit)) sql = getSQL4_Table_Unit(dataline); else if (dataline[0].equals(TABLE_ktek_unit_parameter)) sql = getSQL4_Table_Unit_parameter(dataline); else if (dataline[0].equals(TABLE_ktek_questionnaireconfiguration)) sql = getSQL4_Table_Questionnaireconfiguration(dataline); else { log.debug("table name not found " + dataline[0]); } log.debug("i : " + i + " SQL : " + sql); if (sql != null) st.execute(sql.toString()); } } catch (SQLException e) { // TODO Auto-generated catch block e.printStackTrace(); log.debug(" SQLException " + e.getMessage()); boolOK = false; } tr.commit(); session.close(); } catch (PersistentException e) { // TODO Auto-generated catch block e.printStackTrace(); } return boolOK; }
From source file:com.healthmarketscience.jackcess.ImportUtil.java
/** * Copy a delimited text file into a new (or optionally exixsting) table in * this database.//from w ww. ja v a 2 s . c o m * * @param name Name of the new table to create * @param in Source reader to import * @param delim Regular expression representing the delimiter string. * @param quote the quote character * @param filter valid import filter * @param useExistingTable if {@code true} use current table if it already * exists, otherwise, create new table with unique * name * @param header if {@code false} the first line is not a header row, only * valid if useExistingTable is {@code true} * * @return the name of the imported table * * @see Builder */ public static String importReader(BufferedReader in, Database db, String name, String delim, char quote, ImportFilter filter, boolean useExistingTable, boolean header) throws IOException { String line = in.readLine(); if (line == null || line.trim().length() == 0) { return null; } Pattern delimPat = Pattern.compile(delim); try { name = Database.escapeIdentifier(name); Table table = null; if (!useExistingTable || ((table = db.getTable(name)) == null)) { List<Column> columns = new LinkedList<Column>(); Object[] columnNames = splitLine(line, delimPat, quote, in, 0); for (int i = 0; i < columnNames.length; i++) { columns.add(new ColumnBuilder((String) columnNames[i], DataType.TEXT).escapeName() .setLength((short) DataType.TEXT.getMaxSize()).toColumn()); } table = createUniqueTable(db, name, columns, null, filter); // the first row was a header row header = true; } List<Object[]> rows = new ArrayList<Object[]>(COPY_TABLE_BATCH_SIZE); int numColumns = table.getColumnCount(); if (!header) { // first line is _not_ a header line Object[] data = splitLine(line, delimPat, quote, in, numColumns); data = filter.filterRow(data); if (data != null) { rows.add(data); } } while ((line = in.readLine()) != null) { Object[] data = splitLine(line, delimPat, quote, in, numColumns); data = filter.filterRow(data); if (data == null) { continue; } rows.add(data); if (rows.size() == COPY_TABLE_BATCH_SIZE) { table.addRows(rows); rows.clear(); } } if (rows.size() > 0) { table.addRows(rows); } return table.getName(); } catch (SQLException e) { throw (IOException) new IOException(e.getMessage()).initCause(e); } }
From source file:com.qpark.eip.core.failure.BaseFailureHandler.java
/** * @param e/* ww w . j av a2 s .c o m*/ * {@link SQLException} * @param defaultCode * @param log * @param data * @return */ public static FailureDescription handleSQLException(final SQLException e, final String defaultCode, final Logger log, final Object... data) { FailureDescription fd = null; String code = defaultCode; if (code == null) { code = DEFAULT_DATABASE; } fd = getFailure(code, e); log.error(e.getMessage(), e); return fd; }
From source file:com.healthmarketscience.jackcess.util.ImportUtil.java
/** * Copy a delimited text file into a new (or optionally exixsting) table in * this database.//from w ww . java 2s .c om * * @param name Name of the new table to create * @param in Source reader to import * @param delim Regular expression representing the delimiter string. * @param quote the quote character * @param filter valid import filter * @param useExistingTable if {@code true} use current table if it already * exists, otherwise, create new table with unique * name * @param header if {@code false} the first line is not a header row, only * valid if useExistingTable is {@code true} * * @return the name of the imported table * * @see Builder */ public static String importReader(BufferedReader in, Database db, String name, String delim, char quote, ImportFilter filter, boolean useExistingTable, boolean header) throws IOException { String line = in.readLine(); if (line == null || line.trim().length() == 0) { return null; } Pattern delimPat = Pattern.compile(delim); try { name = TableBuilder.escapeIdentifier(name); Table table = null; if (!useExistingTable || ((table = db.getTable(name)) == null)) { List<ColumnBuilder> columns = new LinkedList<ColumnBuilder>(); Object[] columnNames = splitLine(line, delimPat, quote, in, 0); for (int i = 0; i < columnNames.length; i++) { columns.add(new ColumnBuilder((String) columnNames[i], DataType.TEXT).escapeName() .setLength((short) DataType.TEXT.getMaxSize()).toColumn()); } table = createUniqueTable(db, name, columns, null, filter); // the first row was a header row header = true; } List<Object[]> rows = new ArrayList<Object[]>(COPY_TABLE_BATCH_SIZE); int numColumns = table.getColumnCount(); if (!header) { // first line is _not_ a header line Object[] data = splitLine(line, delimPat, quote, in, numColumns); data = filter.filterRow(data); if (data != null) { rows.add(data); } } while ((line = in.readLine()) != null) { Object[] data = splitLine(line, delimPat, quote, in, numColumns); data = filter.filterRow(data); if (data == null) { continue; } rows.add(data); if (rows.size() == COPY_TABLE_BATCH_SIZE) { table.addRows(rows); rows.clear(); } } if (rows.size() > 0) { table.addRows(rows); } return table.getName(); } catch (SQLException e) { throw (IOException) new IOException(e.getMessage()).initCause(e); } }