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(String reason, Throwable cause) 

Source Link

Document

Constructs a SQLException object with a given reason and cause.

Usage

From source file:org.mayocat.shop.catalog.store.jdbi.mapper.ProductMapper.java

@Override
public Product map(int index, ResultSet resultSet, StatementContext statementContext) throws SQLException {
    try {/*from  w ww  .  ja  v a2 s  .  c o m*/
        Product product = new Product((UUID) resultSet.getObject("id"));
        product.setTenantId((UUID) resultSet.getObject("tenant_id"));
        if (resultSet.getObject("parent_id") != null) {
            product.setParentId((UUID) resultSet.getObject("parent_id"));
        }
        product.setSlug(resultSet.getString("slug"));
        product.setTitle(resultSet.getString("title"));
        product.setDescription(resultSet.getString("description"));
        product.setCreationDate(resultSet.getTimestamp("creation_date"));
        if (resultSet.getObject("on_shelf") != null) {
            product.setOnShelf(resultSet.getBoolean("on_shelf"));
        }
        product.setPrice(resultSet.getBigDecimal("price"));

        if (!Strings.isNullOrEmpty(resultSet.getString("taxes"))) {
            ObjectMapper mapper = new ObjectMapper();
            Map<String, String> taxes = mapper.readValue(resultSet.getString("taxes"),
                    new TypeReference<Map<String, String>>() {
                    });
            if (taxes.containsKey("vat")) {
                product.setVatRateId(taxes.get("vat"));
            }
        }

        product.setWeight(resultSet.getBigDecimal("weight"));
        if (resultSet.getObject("stock") != null) {
            product.setStock(resultSet.getInt("stock"));
        }
        product.setVirtual(resultSet.getBoolean("virtual"));
        UUID featuredImageId = (UUID) resultSet.getObject("featured_image_id");
        if (featuredImageId != null) {
            product.setFeaturedImageId(featuredImageId);
        }

        if (MapperUtils.hasColumn("localization_data", resultSet)
                && !Strings.isNullOrEmpty(resultSet.getString("localization_data"))) {
            ObjectMapper mapper = new ObjectMapper();
            Map<Locale, Map<String, Object>> localizedVersions = Maps.newHashMap();
            Map[] data = mapper.readValue(resultSet.getString("localization_data"), Map[].class);
            for (Map map : data) {

                localizedVersions.put(Locale.forLanguageTag((String) map.get("locale")),
                        (Map) map.get("entity"));
            }
            product.setLocalizedVersions(localizedVersions);
        }

        String model = resultSet.getString("model");
        if (!Strings.isNullOrEmpty(model)) {
            product.setModel(model);
        }
        String type = resultSet.getString("product_type");
        if (!Strings.isNullOrEmpty(type)) {
            product.setType(type);
        }

        if (resultSet.getArray("features") != null) {
            // There's no support for getting the pg uuid array as a Java UUID array (or even String array) at the time
            // this is written, we have to iterate over the array own result set and construct the Java array ourselves
            List<UUID> ids = new ArrayList<>();
            Array array = resultSet.getArray("features");
            if (array != null) {
                ResultSet featuresResultSet = array.getResultSet();
                while (featuresResultSet.next()) {
                    ids.add((UUID) featuresResultSet.getObject("value"));
                }
                product.setFeatures(ids);
            }
        }

        return product;
    } catch (IOException e) {
        throw new SQLException("Failed to de-serialize JSON data", e);
    }
}

From source file:com.googlecode.fascinator.sequences.SequenceService.java

public void init(JsonSimple config) throws IOException, SQLException {

    // Find data directory
    derbyHome = config.getString(null, "database-service", "derbyHome");
    String oldHome = System.getProperty("derby.system.home");

    // Derby's data directory has already been configured
    if (oldHome != null) {
        if (derbyHome != null) {
            // Use the existing one, but throw a warning
            log.warn("Using previously specified data directory:"
                    + " '{}', provided value has been ignored: '{}'", oldHome, derbyHome);
        } else {/*from  ww w.  jav a2s.  c  o m*/
            // This is ok, no configuration conflicts
            log.info("Using existing data directory: '{}'", oldHome);
        }

        // We don't have one, config MUST have one
    } else {
        if (derbyHome == null) {
            log.error("No database home directory configured!");
            return;
        } else {
            // Establish its validity and existance, create if necessary
            File file = new File(derbyHome);
            if (file.exists()) {
                if (!file.isDirectory()) {
                    throw new IOException("Database home '" + derbyHome + "' is not a directory!");
                }
            } else {
                file.mkdirs();
                if (!file.exists()) {
                    throw new IOException(
                            "Database home '" + derbyHome + "' does not exist and could not be created!");
                }
            }
            System.setProperty("derby.system.home", derbyHome);
        }
    }

    // Database prep work
    try {
        checkTable(SEQUENCE_TABLE);
    } catch (SQLException ex) {
        log.error("Error during database preparation:", ex);
        throw new SQLException("Error during database preparation:", ex);
    }
    log.debug("Derby security database online!");
}

From source file:com.reactivetechnologies.analytics.store.ModelJdbcRepository.java

@Override
public RegressionModel findOne(String id) {
    final List<RegressionModel> models = new ArrayList<>();
    jdbcTemplate.query(SELECT_MODEL.replaceFirst("@", id), new RowCallbackHandler() {

        @Override//w  w w  . j  av  a  2 s .  c  o m
        public void processRow(ResultSet rs) throws SQLException {
            RegressionModel m = new RegressionModel();
            try {
                m.deserializeClassifierFromJson(rs.getString(1));
                //m.setLongId(rs.getLong(2));
                m.setStringId(rs.getString(2));
                m.setGeneratedOn(rs.getDate(3).getTime());
                models.add(m);
            } catch (IOException e) {
                throw new SQLException("Unable to deserialze model from string", e);
            }

        }
    });
    return models.isEmpty() ? null : models.get(0);
}

From source file:com.act.lcms.db.model.Plate.java

protected static Plate expectOneResult(ResultSet resultSet, String queryErrStr) throws SQLException {
    List<Plate> results = platesFromResultSet(resultSet);
    if (results.size() > 1) {
        throw new SQLException("Found multiple results where one or zero expected: %s", queryErrStr);
    }/*from  w ww. jav  a 2 s . c o m*/
    if (results.size() == 0) {
        return null;
    }
    return results.get(0);
}

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

/**
 * Moves the cursor down one row from its current position.
 *
 * @throws SQLException if a database access error occurs.
 * @see java.sql.ResultSet#next()//from  w  w  w  .j  a v  a 2 s  .c o m
 */
public boolean next() throws SQLException {
    try {
        if (fetchedRows == null) {
            fetchedRows = fetchRows();
            fetchedRowsItr = fetchedRows.getUnpacker().iterator();
        }

        if (!fetchedRowsItr.hasNext()) {
            return false;
        }

        ArrayValue vs = (ArrayValue) fetchedRowsItr.next();
        row = new ArrayList<Object>(vs.size());
        for (int i = 0; i < vs.size(); i++) {
            row.add(i, vs.get(i));
        }
        rowsFetched++;

        if (LOG.isLoggable(Level.FINE)) {
            LOG.fine(String.format("fetched row(%d): %s", rowsFetched, row));
        }
    } catch (Exception e) {
        if (e instanceof SQLException) {
            throw (SQLException) e;
        } else {
            throw new SQLException("Error retrieving next row", e);
        }
    }
    // NOTE: fetchOne dosn't throw new SQLException("Method not supported").
    return true;
}

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

/**
 * @see com.cws.esolutions.core.dao.interfaces.IApplicationDataDAO#removeApplication(java.lang.String)
 *//*from  w  w w. j a v a  2s.  c om*/
public synchronized void removeApplication(final String value) throws SQLException {
    final String methodName = IApplicationDataDAO.CNAME
            + "#removeApplication(final String value) throws SQLException";

    if (DEBUG) {
        DEBUGGER.debug(methodName);
        DEBUGGER.debug("Value: {}", value);
    }

    Map<Integer, Object> params = new HashMap<Integer, Object>();
    params.put(1, value);

    try {
        SQLUtils.addOrDeleteData("{CALL removeApplicationData(?)}", params);
    } catch (UtilityException ux) {
        throw new SQLException(ux.getMessage(), ux);
    }
}

From source file:com.wso2telco.util.DBConnection.java

/**
 * Check the availability of the clients for a given clientID .
 *
 * @param msisdn mobile number/*from   ww  w . ja v a  2 s .c o m*/
 * @return boolean indicating the transaction is success ,failure or error
 * @throws SQLException    SQLException
 * @throws DBUtilException DBUtilsException
 */
public boolean isClientExist(String msisdn) throws SQLException, DBUtilException {

    Connection connection = null;
    PreparedStatement statement = null;
    ResultSet resultSet = null;

    String query = "SELECT * FROM clients where msisdn=?;";
    try {
        connection = getConnection();
        statement = connection.prepareStatement(query);
        statement.setString(1, msisdn);
        resultSet = statement.executeQuery();

        if (resultSet.next()) {
            return true;
        } else {
            return false;
        }
    } catch (SQLException e) {
        logger.error("Error occurred while checking the MSISDN : " + msisdn + ".Error:" + e);
        throw new SQLException(e.getMessage(), e);
    } catch (DBUtilException e) {
        logger.error("Error occurred while checking the MSISDN : " + msisdn + ".Error:" + e);
        throw new DBUtilException(e.getMessage(), e);
    } finally {
        close(connection, statement, resultSet);
    }
}

From source file:com.act.lcms.db.model.ConstructEntry.java

@Override
protected ConstructEntry expectOneResult(ResultSet resultSet, String queryErrStr) throws SQLException {
    List<ConstructEntry> results = fromResultSet(resultSet);
    if (results.size() > 1) {
        throw new SQLException("Found multiple results where one or zero expected: %s", queryErrStr);
    }/*  www .  j  ava  2s . co m*/
    if (results.size() == 0) {
        return null;
    }
    return results.get(0);
}

From source file:com.frameworkset.commons.dbcp2.PoolingDataSource.java

/**
 * Return a {@link java.sql.Connection} from my pool,
 * according to the contract specified by {@link ObjectPool#borrowObject}.
 *//*from ww  w  . ja  v a 2 s  . c  o m*/
@Override
public Connection getConnection() throws SQLException {
    try {
        C conn = _pool.borrowObject();
        if (conn == null) {
            return null;
        }
        return new PoolGuardConnectionWrapper<C>(conn);
    } catch (SQLException e) {
        throw e;
    } catch (NoSuchElementException e) {
        throw new SQLException("Cannot get a connection, pool error " + e.getMessage(), e);
    } catch (RuntimeException e) {
        throw e;
    } catch (Exception e) {
        throw new SQLException("Cannot get a connection, general error", e);
    }
}

From source file:azkaban.executor.ExecutionLogsDao.java

private void uploadLogFile(final DatabaseTransOperator transOperator, final int execId, final String name,
        final int attempt, final File[] files, final EncodingType encType) throws SQLException {
    // 50K buffer... if logs are greater than this, we chunk.
    // However, we better prevent large log files from being uploaded somehow
    final byte[] buffer = new byte[50 * 1024];
    int pos = 0;/*  ww  w. ja  va2 s . c om*/
    int length = buffer.length;
    int startByte = 0;
    try {
        for (int i = 0; i < files.length; ++i) {
            final File file = files[i];

            final BufferedInputStream bufferedStream = new BufferedInputStream(new FileInputStream(file));
            try {
                int size = bufferedStream.read(buffer, pos, length);
                while (size >= 0) {
                    if (pos + size == buffer.length) {
                        // Flush here.
                        uploadLogPart(transOperator, execId, name, attempt, startByte,
                                startByte + buffer.length, encType, buffer, buffer.length);

                        pos = 0;
                        length = buffer.length;
                        startByte += buffer.length;
                    } else {
                        // Usually end of file.
                        pos += size;
                        length = buffer.length - pos;
                    }
                    size = bufferedStream.read(buffer, pos, length);
                }
            } finally {
                IOUtils.closeQuietly(bufferedStream);
            }
        }

        // Final commit of buffer.
        if (pos > 0) {
            uploadLogPart(transOperator, execId, name, attempt, startByte, startByte + pos, encType, buffer,
                    pos);
        }
    } catch (final SQLException e) {
        logger.error("Error writing log part.", e);
        throw new SQLException("Error writing log part", e);
    } catch (final IOException e) {
        logger.error("Error chunking.", e);
        throw new SQLException("Error chunking", e);
    }
}