Example usage for java.sql SQLException SQLException

List of usage examples for java.sql SQLException SQLException

Introduction

In this page you can find the example usage for java.sql SQLException SQLException.

Prototype

public SQLException(Throwable cause) 

Source Link

Document

Constructs a SQLException object with a given cause.

Usage

From source file:com.cws.esolutions.core.dao.impl.WebMessagingDAOImpl.java

/**
 * @see com.cws.esolutions.core.dao.interfaces.IWebMessagingDAO#retrieveMessage(String)
 *///from   ww  w . j  ava2s .c o m
public synchronized List<Object> retrieveMessage(final String messageId) throws SQLException {
    final String methodName = IWebMessagingDAO.CNAME
            + "#retrieveMessage(final String messageId) throws SQLException";

    if (DEBUG) {
        DEBUGGER.debug(methodName);
        DEBUGGER.debug(messageId);
    }

    Connection sqlConn = null;
    ResultSet resultSet = null;
    CallableStatement stmt = null;
    List<Object> svcMessage = null;

    try {
        sqlConn = dataSource.getConnection();

        if (sqlConn.isClosed()) {
            throw new SQLException("Unable to obtain application datasource connection");
        }

        sqlConn.setAutoCommit(true);
        stmt = sqlConn.prepareCall("{CALL retrServiceMessage(?)}");
        stmt.setString(1, messageId);

        if (DEBUG) {
            DEBUGGER.debug("CallableStatement: {}", stmt);
        }

        if (stmt.execute()) {
            resultSet = stmt.getResultSet();

            if (resultSet.next()) {
                resultSet.first();
                svcMessage = new ArrayList<Object>();
                svcMessage.add(resultSet.getString(1)); // svc_message_id
                svcMessage.add(resultSet.getString(2)); // svc_message_title
                svcMessage.add(resultSet.getString(3)); // svc_message_txt
                svcMessage.add(resultSet.getString(4)); // svc_message_author
                svcMessage.add(resultSet.getTimestamp(5)); // svc_message_submitdate
                svcMessage.add(resultSet.getBoolean(6)); // svc_message_active
                svcMessage.add(resultSet.getBoolean(7)); // svc_message_alert
                svcMessage.add(resultSet.getBoolean(8)); // svc_message_expires
                svcMessage.add(resultSet.getTimestamp(9)); // svc_message_expirydate
                svcMessage.add(resultSet.getTimestamp(10)); // svc_message_modifiedon
                svcMessage.add(resultSet.getString(11)); // svc_message_modifiedby

                if (DEBUG) {
                    DEBUGGER.debug("svcMessage: {}", svcMessage);
                }
            }
        }
    } catch (SQLException sqx) {
        ERROR_RECORDER.error(sqx.getMessage(), sqx);

        throw new SQLException(sqx.getMessage(), sqx);
    } finally {
        if (resultSet != null) {
            resultSet.close();
        }

        if (stmt != null) {
            stmt.close();
        }

        if ((sqlConn != null) && (!(sqlConn.isClosed()))) {
            sqlConn.close();
        }
    }

    return svcMessage;
}

From source file:com.qubole.quark.fatjdbc.QuarkDriver.java

public Connection connect(String url, Properties info) throws SQLException {
    if (!acceptsURL(url)) {
        return null;
    }//from www. java2  s  .c  om

    final String prefix = getConnectStringPrefix();
    final String urlSuffix = url.substring(prefix.length());

    if (urlSuffix.startsWith(DB_PREFIX)) {
        info.setProperty("schemaFactory", DB_SCHEMA_FACTORY);
        final String path = urlSuffix.substring(DB_PREFIX.length());
        if (!path.isEmpty()) {
            try {
                byte[] encoded = Files.readAllBytes(Paths.get(path));
                ObjectMapper objectMapper = new ObjectMapper();
                CatalogDetail catalogDetail = objectMapper.readValue(encoded, CatalogDetail.class);
                info.setProperty("url", catalogDetail.dbCredentials.url);
                info.setProperty("user", catalogDetail.dbCredentials.username);
                info.setProperty("password", catalogDetail.dbCredentials.password);
                info.setProperty("encryptionKey", catalogDetail.dbCredentials.encryptionKey);
                info.setProperty("encrypt", catalogDetail.dbCredentials.encrypt);
            } catch (IOException e) {
                throw new SQLException(e);
            }
        }
    } else if (urlSuffix.startsWith(JSON_PREFIX)) {
        info.setProperty("schemaFactory", JSON_SCHEMA_FACTORY);
        final String path = urlSuffix.substring(JSON_PREFIX.length());
        if (!path.isEmpty()) {
            try {
                byte[] encoded = Files.readAllBytes(Paths.get(path));
                info.setProperty("model", new String(encoded, StandardCharsets.UTF_8));
            } catch (IOException e) {
                throw new SQLException(e);
            }
        }
    } else {
        throw new SQLException("URL is malformed. Specify catalog type with 'db:' or 'json:'");
    }

    return super.connect(url, info);
}

From source file:com.treasuredata.jdbc.TDDatabaseMetaData.java

public ResultSet getBestRowIdentifier(String catalog, String schema, String table, int scope, boolean nullable)
        throws SQLException {
    throw new SQLException(
            "Unsupported TDDatabaseMetaData#getBestRowIdentifier(String, String, String, int, boolean)");
}

From source file:io.cloudslang.content.database.utils.SQLUtilsTest.java

@Test
public void testProcessLoadException() throws SQLException {

    SQLException sqlException = new SQLException("load is complete") {
        @Override//from  w w w  .  ja va  2 s  . c  om
        public String getSQLState() {
            return SQL_STATE;
        }

    };
    final String loadException = SQLUtils.processLoadException(sqlException);
    assertEquals("load is complete", loadException);
}

From source file:com.softberries.klerk.dao.PeopleDao.java

@Override
public void create(Person c) throws SQLException {
    try {//from  w w w.java  2 s.c o m
        init();
        st = conn.prepareStatement(SQL_INSERT_PERSON, Statement.RETURN_GENERATED_KEYS);
        st.setString(1, c.getFirstName());
        st.setString(2, c.getLastName());
        st.setString(3, c.getTelephone());
        st.setString(4, c.getMobile());
        st.setString(5, c.getEmail());
        st.setString(6, c.getWww());
        // run the query
        int i = st.executeUpdate();
        System.out.println("i: " + i);
        if (i == -1) {
            System.out.println("db error : " + SQL_INSERT_PERSON);
        }
        generatedKeys = st.getGeneratedKeys();
        if (generatedKeys.next()) {
            c.setId(generatedKeys.getLong(1));
        } else {
            throw new SQLException("Creating user failed, no generated key obtained.");
        }
        // if the person creation was successfull, add addresses
        AddressDao adrDao = new AddressDao();
        for (Address adr : c.getAddresses()) {
            adr.setPerson_id(c.getId());
            adrDao.create(adr, run, conn, generatedKeys);
        }
        conn.commit();
    } catch (Exception e) {
        // rollback the transaction but rethrow the exception to the caller
        conn.rollback();
        e.printStackTrace();
        throw new SQLException(e);
    } finally {
        close(conn, st, generatedKeys);
    }
}

From source file:com.rdsic.pcm.service.impl.GenericQueryImpl.java

/**
 * Implementation method for operation AddOrUpdate
 *
 * @param req//from w  ww.  j  av a2  s.  c  om
 * @return
 */
public static AddOrUpdateRes addOrUpdate(AddOrUpdateReq req) {
    String key = UUID.randomUUID().toString();
    String opr = "GenericQuery/AddOrUpdate";
    Logger.LogReq(key, opr, req);

    Date now = new Date();
    AddOrUpdateRes res = new AddOrUpdateRes();
    if (!Util.validateRequest(req, opr, Constant.FUNCTIONALITY_ACTION.WS_INVOKE, res)) {
        Logger.LogRes(key, opr, res);
        return res;
    }

    try {
        List<Object> params = new ArrayList<>();

        if (req.getQuery().getParams() != null) {

            if (req.getQuery().getParams().getDatetimeParam() != null) {
                for (QueryParamType.DatetimeParam dp : req.getQuery().getParams().getDatetimeParam()) {
                    params.add(dp.getName());
                    params.add(Util.toDate(dp.getValue()));
                }
            }

            if (req.getQuery().getParams().getNumericParam() != null) {
                for (QueryParamType.NumericParam np : req.getQuery().getParams().getNumericParam()) {
                    params.add(np.getName());
                    params.add(np.getValue());
                }
            }

            if (req.getQuery().getParams().getStringParam() != null) {
                for (QueryParamType.StringParam np : req.getQuery().getParams().getStringParam()) {
                    params.add(np.getName());
                    params.add(np.getValue());
                }
            }
        }
        String sql = req.getQuery().getSQL().trim().toLowerCase();

        // quick validate the query
        if (!(sql.startsWith("insert") || sql.startsWith("update") || sql.startsWith("delete"))) {
            throw new SQLException(
                    "Invalid SQL string. The input SQL must be started with insert/update/delete");
        }

        String action = sql.substring(0, sql.indexOf(" "));
        int recNum = GenericHql.INSTANCE.updateSQL(sql, true, params.toArray());

        AddOrUpdateQueryResponseType result = new AddOrUpdateQueryResponseType();
        result.setUpdatedAction(action);
        result.setUpdatedRecordCount(recNum);

        res.setResult(result);
        res.setStatus(Constant.STATUS_CODE.OK);

    } catch (Exception e) {
        res.setStatus(Constant.STATUS_CODE.FAIL);
        res.setErrorCode(Constant.STATUS_CODE.ERR_UPDATE_FAIL);
        res.setErrorMessage(e.getMessage());
        e.printStackTrace();
    }

    res.setResponseDateTime(Util.toXmlGregorianCalendar(now));
    Logger.LogRes(key, opr, res);
    return res;
}

From source file:com.iksgmbh.sql.pojomemodb.sqlparser.CreateTableParser.java

private String createPrimaryConstraint(String unparsedRest, TableMetaData tableMetaData) throws SQLException {
    String toReturn = unparsedRest.substring(CONSTRAINT.length()).trim();
    InterimParseResult parseResult = parseNextValue(toReturn, PRIMARY_KEY);

    if (StringUtils.isEmpty(parseResult.delimiter)) {
        throw new SQLException("Cannot parse to Primary Key Constraint: " + unparsedRest
                + " Expected something like 'CONSTRAINT PRIMARY_KEY_ID PRIMARY KEY (COLUMN_NAME)'.");
    }/*  w  ww  .  ja v a 2s  . c  o  m*/

    String primaryKeyId = removeSurroundingQuotes(parseResult.parsedValue);
    parseResult = parseNextValue(parseResult.unparsedRest, COMMA);
    String constraintColumnName = null;

    if (parseResult.delimiter == null) {
        toReturn = "";
        constraintColumnName = parseResult.parsedValue;
    } else {
        toReturn = parseResult.unparsedRest;
        constraintColumnName = parseResult.parsedValue;

        int pos = constraintColumnName.toUpperCase().indexOf(USING_INDEX.toUpperCase());
        if (pos > 0) {
            constraintColumnName = constraintColumnName.substring(0, pos).trim();
        }
    }

    if (constraintColumnName.startsWith(OPENING_PARENTHESIS)) {
        if (constraintColumnName.endsWith(CLOSING_PARENTHESIS)) {
            constraintColumnName = constraintColumnName.substring(1, constraintColumnName.length() - 1);
        } else {
            throw new SQLException("Cannot parse to primary key constraint: " + unparsedRest
                    + ". Expected something like 'CONSTRAINT PRIMARY_KEY_ID PRIMARY KEY (COLUMN_NAME)'.");
        }
    } else {
        if (constraintColumnName.endsWith(CLOSING_PARENTHESIS)) {
            throw new SQLException("Cannot parse to primary key constraint: " + unparsedRest
                    + ". Expected something like 'CONSTRAINT PRIMARY_KEY_ID PRIMARY KEY (COLUMN_NAME)'.");
        }
    }

    constraintColumnName = removeSurroundingQuotes(constraintColumnName);
    Column column = ((Table) tableMetaData).getColumn(constraintColumnName);
    column.setPrimaryKeyId(primaryKeyId);
    column.setNullable(false); // Primary Key column must not be nullable

    return toReturn;
}

From source file:fr.paris.lutece.util.sql.Transaction.java

/**
 * Commit the transaction//from w ww.  j  a  v  a  2s .  c o  m
 */
public void commit() {
    try {
        if (_connection == null) {
            throw new SQLException("Plugin : '" + _strPluginName
                    + "' - Transaction has already been closed and can not be committed");
        }

        _connection.commit();
        _logger.debug("Plugin : '" + _strPluginName + "' - COMMIT TRANSACTION");
        closeTransaction(COMMITTED);
    } catch (SQLException e) {
        rollback(e);
    }
}

From source file:com.taobao.tdhs.jdbc.TDHSPreparedStatement.java

public void setBytes(int parameterIndex, byte[] x) throws SQLException {
    checkclose();//from w w  w.  ja  v a2  s.c  o m
    if (parameterIndex < 1 || parameterIndex > this.parameterNumber) {
        throw new SQLException("parameterIndex is out of range,parameterIndex is " + parameterIndex);
    }
    setString(parameterIndex, x == null ? null : BYTE_PARAMETER_PREFIX + parameterIndex);
    super.byteParameters.put(parameterIndex, x);
}

From source file:com.orange.cepheus.broker.persistence.RegistrationsRepository.java

/**
 * Get all saved registrations/*from  w  w w .  jav a2  s  . c o  m*/
 * @return registrations map
 * @throws RegistrationPersistenceException
 */
public Map<String, Registration> getAllRegistrations() throws RegistrationPersistenceException {
    Map<String, Registration> registrations = new ConcurrentHashMap<>();
    try {
        List<Registration> registrationList = jdbcTemplate.query(
                "select id, expirationDate, registerContext from t_registrations",
                (ResultSet rs, int rowNum) -> {
                    Registration registration = new Registration();
                    try {
                        registration.setExpirationDate(Instant.parse(rs.getString("expirationDate")));
                        registration.setRegisterContext(
                                mapper.readValue(rs.getString("registerContext"), RegisterContext.class));
                    } catch (IOException e) {
                        throw new SQLException(e);
                    }
                    return registration;
                });
        registrationList.forEach(registration -> registrations
                .put(registration.getRegisterContext().getRegistrationId(), registration));
    } catch (DataAccessException e) {
        throw new RegistrationPersistenceException(e);
    }
    return registrations;
}