Example usage for java.sql ResultSet getObject

List of usage examples for java.sql ResultSet getObject

Introduction

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

Prototype

Object getObject(String columnLabel) throws SQLException;

Source Link

Document

Gets the value of the designated column in the current row of this ResultSet object as an Object in the Java programming language.

Usage

From source file:org.mayocat.attachment.store.jdbi.mapper.AttachmentMapper.java

@Override
public Attachment map(int i, ResultSet resultSet, StatementContext statementContext) throws SQLException {
    Attachment attachment = new Attachment();
    attachment.setId((UUID) resultSet.getObject("id"));
    attachment.setTitle(resultSet.getString("title"));
    attachment.setDescription(resultSet.getString("description"));
    attachment.setSlug(resultSet.getString("slug"));
    attachment.setExtension(resultSet.getString("extension"));
    attachment.setParentId((UUID) resultSet.getObject("parent_id"));

    ObjectMapper mapper = new ObjectMapper();
    if (!Strings.isNullOrEmpty(resultSet.getString("metadata"))) {
        try {//from   w w w.  j a va  2s . c  o m

            Map<String, Map<String, Object>> metadata = mapper.readValue(resultSet.getString("metadata"),
                    new TypeReference<Map<String, Map<String, Object>>>() {
                    });
            attachment.setMetadata(metadata);
        } catch (IOException e) {
            throw new SQLException("Failed to de-serialize localization JSON data", e);
        }
    }

    if (MapperUtils.hasColumn("localization_data", resultSet)
            && !Strings.isNullOrEmpty(resultSet.getString("localization_data"))) {
        try {
            Map<Locale, Map<String, Object>> localizedVersions = Maps.newHashMap();
            Map[] data = mapper.readValue(resultSet.getString("localization_data"), Map[].class);
            for (Map map : data) {
                localizedVersions.put(LocaleUtils.toLocale((String) map.get("locale")),
                        (Map) map.get("entity"));
            }
            attachment.setLocalizedVersions(localizedVersions);
        } catch (IOException e) {
            throw new SQLException("Failed to de-serialize localization JSON data", e);
        }
    }

    return attachment;

}

From source file:org.mayocat.attachment.store.jdbi.mapper.LoadedAttachmentMapper.java

@Override
public LoadedAttachment map(int index, ResultSet resultSet, StatementContext ctx) throws SQLException {
    LoadedAttachment attachment = new LoadedAttachment();
    attachment.setId((UUID) resultSet.getObject("id"));
    attachment.setTitle(resultSet.getString("title"));
    attachment.setDescription(resultSet.getString("description"));
    attachment.setSlug(resultSet.getString("slug"));
    attachment.setData(new AttachmentData(resultSet.getBinaryStream("data")));
    attachment.setExtension(resultSet.getString("extension"));
    attachment.setParentId((UUID) resultSet.getObject("parent_id"));

    ObjectMapper mapper = new ObjectMapper();

    if (!Strings.isNullOrEmpty(resultSet.getString("metadata"))) {
        try {/*  ww  w  .  jav  a2  s  .  co  m*/

            Map<String, Map<String, Object>> metadata = mapper.readValue(resultSet.getString("metadata"),
                    new TypeReference<Map<String, Map<String, Object>>>() {
                    });
            attachment.setMetadata(metadata);
        } catch (IOException e) {
            throw new SQLException("Failed to de-serialize localization JSON data", e);
        }
    }

    if (MapperUtils.hasColumn("localization_data", resultSet)
            && !Strings.isNullOrEmpty(resultSet.getString("localization_data"))) {
        try {
            Map<Locale, Map<String, Object>> localizedVersions = Maps.newHashMap();
            Map[] data = mapper.readValue(resultSet.getString("localization_data"), Map[].class);
            for (Map map : data) {
                localizedVersions.put(LocaleUtils.toLocale((String) map.get("locale")),
                        (Map) map.get("entity"));
            }
            attachment.setLocalizedVersions(localizedVersions);
        } catch (IOException e) {
            throw new SQLException("Failed to de-serialize localization JSON data", e);
        }
    }

    return attachment;
}

From source file:com.viettel.ws.client.JDBCUtil.java

/**
 * Create document using DOM api/*  www  .  java 2 s .c  om*/
 *
 * @param rs a result set
 * @return A document of a result set
 * @throws ParserConfigurationException - If error when parse string
 * @throws SQLException - If error when read data from database
 */
public static Document toDocument(ResultSet rs) throws ParserConfigurationException, SQLException {
    DocumentBuilderFactory factory = DocumentBuilderFactory.newInstance();
    factory.setFeature(FEATURE_GENERAL_ENTITIES, false);
    factory.setFeature(FEATURE_PARAMETER_ENTITIES, false);
    factory.setXIncludeAware(false);
    factory.setExpandEntityReferences(false);
    DocumentBuilder builder = factory.newDocumentBuilder();
    Document doc = builder.newDocument();

    Element results = doc.createElement("Results");
    doc.appendChild(results);

    ResultSetMetaData rsmd = rs.getMetaData();
    int colCount = rsmd.getColumnCount();

    while (rs.next()) {
        Element row = doc.createElement("Row");
        results.appendChild(row);

        for (int i = 1; i <= colCount; i++) {
            String columnName = rsmd.getColumnName(i);
            Object value = rs.getObject(i);

            Element node = doc.createElement(columnName);
            node.appendChild(doc.createTextNode(value.toString()));
            row.appendChild(node);
        }
    }
    return doc;
}

From source file:springobjectmapper.FieldPropertyRowMapper.java

@Override
public T mapRow(ResultSet rs, int rowNum) throws SQLException {
    try {/*w  w w  .  ja v a  2  s. c o m*/
        T result = newObject(typeClass);
        for (Entry<String, Field> entry : fieldMapping.entrySet()) {
            Object value = rs.getObject(entry.getKey());
            ReflectionUtils.setField(entry.getValue(), result, value);
        }
        return result;
    } catch (Exception e) {
        throw new RuntimeException(e);
    }
}

From source file:com.azaptree.services.domain.entity.dao.VersionedEntityRowMapperSupport.java

@Override
public T mapRow(final ResultSet rs, final int rowNum) throws SQLException {
    final T entity = createEntity(rs, rowNum);
    final DomainVersionedEntity domainEntity = (DomainVersionedEntity) entity;
    domainEntity.setEntityId((UUID) rs.getObject("entity_id"));
    domainEntity.setEntityVersion(rs.getLong("entity_version"));
    domainEntity.setEntityCreatedOn(rs.getTimestamp("entity_created_on").getTime());
    domainEntity.setCreatedBy((UUID) rs.getObject("entity_created_by"));
    domainEntity.setEntityUpdatedOn(rs.getTimestamp("entity_updated_on").getTime());
    domainEntity.setUpdatedBy((UUID) rs.getObject("entity_updated_by"));
    return mapRow(entity, rs, rowNum);
}

From source file:io.github.benas.jql.shell.PrintStreamRowCallbackHandler.java

@Override
public void processRow(ResultSet resultSet) throws SQLException {
    int columnCount = resultSet.getMetaData().getColumnCount();
    StringBuilder stringBuilder = new StringBuilder();
    int i = 1;//from w w  w.ja  va2  s  . com
    while (i <= columnCount) {
        stringBuilder.append(resultSet.getObject(i));
        if (i < columnCount) {
            stringBuilder.append(" | ");
        }
        i++;
    }
    printStream.println(stringBuilder.toString());
}

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 w w  . j a 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.webbfontaine.valuewebb.model.util.Utils.java

public static List<Object[]> transformToList(ResultSet rs) throws SQLException {
    ResultSetMetaData rsMetaData = rs.getMetaData();

    int numberOfColumns = rsMetaData.getColumnCount();

    List<Object[]> result = new ArrayList<>(numberOfColumns);

    while (rs.next()) {
        Object[] row = new Object[numberOfColumns];
        for (int i = 0; i < numberOfColumns; i++) {
            if (rsMetaData.getColumnType(i + 1) == Types.TIMESTAMP) {
                row[i] = rs.getDate(i + 1);
            } else {
                row[i] = rs.getObject(i + 1);
            }//www. ja  v a 2  s. c  om
        }
        result.add(row);
    }

    return result;
}

From source file:net.orpiske.ssps.common.repository.search.cache.MultiRsHandler.java

@Override
protected PackageInfo handleRow(ResultSet rs) throws SQLException {
    PackageInfo dto = new PackageInfo();

    ResultSetMetaData meta = rs.getMetaData();

    for (int i = 1; i <= meta.getColumnCount(); i++) {
        Object value = rs.getObject(i);
        String name = meta.getColumnName(i);

        try {//w w w. ja v  a 2s  .  co m
            /*
             * We convert the column name to a more appropriate and java like name 
             * because some columns are usually named as some_thing whereas Java 
             * properties are named someThing. This call does this conversion.
             */
            String javaProperty = NameConverter.sqlToProperty(name);

            if (javaProperty.equals("version")) {
                Version version = Version.toVersion((String) value);

                PropertyUtils.setSimpleProperty(dto, javaProperty, version);
            } else {
                PropertyUtils.setSimpleProperty(dto, javaProperty, value);
            }
        } catch (Exception e) {
            throw new SQLException("Unable to set property " + name + " for bean" + dto.getClass(), e);
        }
    }

    return dto;
}

From source file:net.lightbody.bmp.proxy.jetty.http.JDBCUserRealm.java

private void loadUser(String username) {
    try {/*from  w  ww .  j  a  va 2  s .  c  o  m*/
        if (null == _con)
            connectDatabase();

        if (null == _con)
            throw new SQLException("Can't connect to database");

        PreparedStatement stat = _con.prepareStatement(_userSql);
        stat.setObject(1, username);
        ResultSet rs = stat.executeQuery();

        if (rs.next()) {
            Object key = rs.getObject(_userTableKey);
            put(username, rs.getString(_userTablePasswordField));
            stat.close();

            stat = _con.prepareStatement(_roleSql);
            stat.setObject(1, key);
            rs = stat.executeQuery();

            while (rs.next())
                addUserToRole(username, rs.getString(_roleTableRoleField));

            stat.close();
        }
    } catch (SQLException e) {
        log.warn("UserRealm " + getName() + " could not load user information from database", e);
        connectDatabase();
    }
}