Example usage for java.sql Blob length

List of usage examples for java.sql Blob length

Introduction

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

Prototype

long length() throws SQLException;

Source Link

Document

Returns the number of bytes in the BLOB value designated by this Blob object.

Usage

From source file:org.sakaiproject.mailarchive.impl.conversion.ExtractXMLToColumns.java

public Object getValidateSource(String id, ResultSet rs) throws SQLException {
    ResultSetMetaData metadata = rs.getMetaData();
    byte[] rv = null;
    switch (metadata.getColumnType(1)) {
    case Types.BLOB:
        Blob blob = rs.getBlob(1);
        if (blob != null) {
            rv = blob.getBytes(1L, (int) blob.length());
        } else {//ww  w.  j a va2s .com
            System.out.println("getValidateSource(" + id + ") blob ==  null");
        }
        break;
    case Types.CLOB:
        Clob clob = rs.getClob(1);
        if (clob != null) {
            rv = clob.getSubString(1L, (int) clob.length()).getBytes();
        }
        break;
    case Types.CHAR:
    case Types.LONGVARCHAR:
    case Types.VARCHAR:
        rv = rs.getString(1).getBytes();
        break;
    case Types.BINARY:
    case Types.VARBINARY:
    case Types.LONGVARBINARY:
        rv = rs.getBytes(1);
        break;
    }
    // System.out.println("getValidateSource(" + id + ") \n" + rv + "\n");
    return rv;
}

From source file:org.sakaiproject.mailarchive.impl.conversion.ExtractXMLToColumns.java

public Object getSource(String id, ResultSet rs) throws SQLException {
    ResultSetMetaData metadata = rs.getMetaData();
    String rv = null;// www. ja  va2s.c  o m
    switch (metadata.getColumnType(1)) {
    case Types.BLOB:
        Blob blob = rs.getBlob(1);
        if (blob != null) {
            rv = new String(blob.getBytes(1L, (int) blob.length()));
        }
        break;
    case Types.CLOB:
        Clob clob = rs.getClob(1);
        if (clob != null) {
            rv = clob.getSubString(1L, (int) clob.length());
        }
        break;
    case Types.CHAR:
    case Types.LONGVARCHAR:
    case Types.VARCHAR:
    case Types.BINARY:
    case Types.VARBINARY:
    case Types.LONGVARBINARY:
        byte[] bytes = rs.getBytes(1);
        if (bytes != null) {
            rv = new String(bytes);
        }
        break;
    }
    // System.out.println("getSource(" + id + ") \n" + rv + "\n");
    return rv;
}

From source file:org.fao.geonet.arcgis.ArcSDEJdbcConnection.java

@Override
public Map<String, String> retrieveMetadata(AtomicBoolean cancelMonitor, String arcSDEVersion)
        throws Exception {
    Map<String, String> results = new HashMap<>();

    ArcSDEVersionFactory arcSDEVersionFactory = new ArcSDEVersionFactory();
    String metadataTable = arcSDEVersionFactory.getTableName(arcSDEVersion);
    String columnName = arcSDEVersionFactory.getMetadataColumnName(arcSDEVersion);

    String sqlQuery = "SELECT " + columnName + ", UUID FROM " + metadataTable;

    getJdbcTemplate().query(sqlQuery, new RowCallbackHandler() {
        @Override/*from  w ww .  ja v  a 2 s. c  o m*/
        public void processRow(ResultSet rs) throws SQLException {
            // Cancel processing
            if (cancelMonitor.get()) {
                Log.warning(ARCSDE_LOG_MODULE_NAME,
                        "Cancelling metadata retrieve using " + "ArcSDE connection (via JDBC)");
                rs.getStatement().cancel();
                results.clear();
            }

            String document = "";
            int colId = rs.findColumn(columnName);
            int colIdUuid = rs.findColumn("UUID");
            // very simple type check:
            if (rs.getObject(colId) != null) {
                if (rs.getMetaData().getColumnType(colId) == Types.BLOB) {
                    Blob blob = rs.getBlob(columnName);
                    byte[] bdata = blob.getBytes(1, (int) blob.length());
                    document = new String(bdata);

                } else if (rs.getMetaData().getColumnType(colId) == Types.LONGVARBINARY) {
                    byte[] byteData = rs.getBytes(colId);
                    document = new String(byteData);

                } else if (rs.getMetaData().getColumnType(colId) == Types.LONGNVARCHAR
                        || rs.getMetaData().getColumnType(colId) == Types.LONGVARCHAR
                        || rs.getMetaData().getColumnType(colId) == Types.VARCHAR
                        || rs.getMetaData().getColumnType(colId) == Types.SQLXML) {
                    document = rs.getString(colId);

                } else {
                    throw new SQLException("Trying to harvest from a column with an invalid datatype: "
                            + rs.getMetaData().getColumnTypeName(colId));
                }

                String uuid = rs.getString(colIdUuid);
                ;
                results.put(uuid, document);
            }

        }
    });

    Log.info(ARCSDE_LOG_MODULE_NAME,
            "Finished retrieving metadata, found: #" + results.size() + " metadata records");

    return results;
}

From source file:org.sakaiproject.content.impl.serialize.impl.conversion.Type1BlobCollectionConversionHandler.java

public Object getSource(String id, ResultSet rs) throws SQLException {
    ResultSetMetaData metadata = rs.getMetaData();
    String rv = null;/*  w w w  .  j  a va2s.  co  m*/
    switch (metadata.getColumnType(1)) {
    case Types.BLOB:
        Blob blob = rs.getBlob(1);
        if (blob != null) {
            rv = new String(blob.getBytes(1L, (int) blob.length()));
        }
        break;
    case Types.CLOB:
        Clob clob = rs.getClob(1);
        if (clob != null) {
            rv = clob.getSubString(1L, (int) clob.length());
        }
        break;
    case Types.CHAR:
    case Types.LONGVARCHAR:
    case Types.VARCHAR:
    case Types.BINARY:
    case Types.VARBINARY:
    case Types.LONGVARBINARY:
        byte[] bytes = rs.getBytes(1);
        if (bytes != null) {
            rv = new String(bytes);
        }
        break;
    }
    //System.out.println("getSource(" + id + ") \n" + rv + "\n");
    return rv;
}

From source file:com.sr.controller.MahasiswaController.java

@RequestMapping("/lihatfoto")
public void lihatfoto(@RequestParam("nim") String nim, HttpServletRequest request,
        HttpServletResponse response) {//w ww.j  a  va  2s  .  co  m
    try {
        Blob blob = mhs.getFotoByNim(nim);
        response.setContentType("image/jpg");
        response.setContentLength((int) blob.length());
        InputStream inputStream = blob.getBinaryStream();
        OutputStream os = response.getOutputStream();
        byte buf[] = new byte[(int) blob.length()];
        inputStream.read(buf);
        os.write(buf);
        os.close();
    } catch (IOException ex) {
        System.out.println("IOException " + ex.getMessage());
    } catch (SQLException ex) {
        System.out.println("SQLException " + ex.getMessage());
    } catch (NullPointerException ex) {
        System.out.println("NullPointerException " + ex.getMessage());
        //buat custom 404 kalau bisa hahahahaha
    }
}

From source file:org.pentaho.reporting.engine.classic.core.filter.DrawableLoadFilter.java

/**
 * Reads this filter's datasource and if the source returned an URL, tries to form a imagereference. If the image is
 * loaded in a previous run and is still in the cache, no new reference is created and the previously loaded reference
 * is returned./*  w w w .  ja va  2  s  . c om*/
 *
 * @param runtime
 *          the expression runtime that is used to evaluate formulas and expressions when computing the value of this
 *          filter.
 * @param element
 * @return the current value for this filter.
 */
public Object getValue(final ExpressionRuntime runtime, final ReportElement element) {
    final DataSource ds = getDataSource();
    if (ds == null) {
        return null;
    }
    final Object o = ds.getValue(runtime, element);
    if (o == null) {
        return null;
    }

    if (o instanceof URL) {

        // a valid url is found, lookup the url in the cache, maybe the image is loaded and
        // still there.
        final URL url = (URL) o;
        final String urlString = String.valueOf(url);
        if (failureCache.contains(urlString)) {
            return null;
        }
        try {
            final ResourceManager resManager = runtime.getProcessingContext().getResourceManager();
            final Resource resource = resManager.createDirectly(url, DrawableWrapper.class);
            return resource.getResource();
        } catch (ResourceException e) {
            if (DrawableLoadFilter.logger.isDebugEnabled()) {
                DrawableLoadFilter.logger.debug("Error while loading the drawable from " + url, e);
            } else if (DrawableLoadFilter.logger.isWarnEnabled()) {
                DrawableLoadFilter.logger
                        .warn("Error while loading the drawable from " + url + ": " + e.getMessage());
            }
            failureCache.add(urlString);
            return null;
        }
    } else if (o instanceof byte[]) {
        try {
            final ResourceManager resManager = runtime.getProcessingContext().getResourceManager();
            final Resource resource = resManager.createDirectly(o, DrawableWrapper.class);
            return resource.getResource();
        } catch (ResourceException e) {
            if (DrawableLoadFilter.logger.isDebugEnabled()) {
                DrawableLoadFilter.logger.debug("Error while loading the drawable from byte[]", e);
            } else if (DrawableLoadFilter.logger.isWarnEnabled()) {
                DrawableLoadFilter.logger
                        .warn("Error while loading the drawable from byte[]: " + e.getMessage());
            }
            return null;
        }
    } else if (o instanceof Blob) {
        try {
            final Blob b = (Blob) o;
            final byte[] data = b.getBytes(1, (int) b.length());
            final ResourceManager resManager = runtime.getProcessingContext().getResourceManager();
            final Resource resource = resManager.createDirectly(data, DrawableWrapper.class);
            return resource.getResource();
        } catch (Exception e) {
            if (DrawableLoadFilter.logger.isDebugEnabled()) {
                DrawableLoadFilter.logger.warn("Error while loading the drawable from an blob", e);
            } else if (DrawableLoadFilter.logger.isWarnEnabled()) {
                DrawableLoadFilter.logger.warn("Error while loading the drawable from an blob: " + e);
            }
            return null;
        }
    } else {
        return null;
    }
}

From source file:org.wso2.carbon.das.jobmanager.core.impl.RDBMSServiceImpl.java

public ResourcePool getResourcePool(String groupId) throws ResourceManagerException {
    Connection connection = null;
    PreparedStatement preparedStatement = null;
    ResultSet resultSet = null;/*w  ww. j a  va2 s  . c o  m*/
    ResourcePool resourcePool = null;
    try {
        connection = getConnection();
        preparedStatement = connection
                .prepareStatement(ResourceManagerConstants.PS_SELECT_RESOURCE_MAPPING_ROW);
        preparedStatement.setString(1, groupId);
        resultSet = preparedStatement.executeQuery();
        if (resultSet.next()) {
            Blob blob = resultSet.getBlob(2);
            if (blob != null) {
                int blobLength = (int) blob.length();
                byte[] bytes = blob.getBytes(1, blobLength);
                ByteArrayInputStream bis = new ByteArrayInputStream(bytes);
                ObjectInputStream ois = new ObjectInputStream(bis);
                Object blobObject = ois.readObject();
                if (blobObject instanceof ResourcePool) {
                    resourcePool = (ResourcePool) blobObject;
                }
            }
        }
        connection.commit();
    } catch (SQLException | ClassNotFoundException | IOException e) {
        throw new ResourceManagerException(
                "Error occurred while " + ResourceManagerConstants.TASK_GET_RESOURCE_MAPPING, e);
    } finally {
        close(resultSet, ResourceManagerConstants.TASK_GET_RESOURCE_MAPPING);
        close(preparedStatement, ResourceManagerConstants.TASK_GET_RESOURCE_MAPPING);
        close(connection, ResourceManagerConstants.TASK_GET_RESOURCE_MAPPING);
    }
    return resourcePool;
}

From source file:org.wso2.carbon.event.processor.core.internal.persistence.DBPersistenceStore.java

private byte[] getRevision(String executionPlanId, String revision, String tenantId) {
    PreparedStatement stmt = null;
    Connection con = null;//from  ww  w . j  a  v  a 2 s .c om
    byte[] blobAsBytes = null;
    try {
        try {
            con = dataSource.getConnection();
        } catch (SQLException e) {
            log.error("Cannot establish connection to the data source" + dataSourceName, e);
        }

        stmt = con.prepareStatement(executionInfo.getPreparedSelectStatement());
        stmt.setString(1, revision);
        stmt.setString(2, tenantId);
        stmt.setString(3, executionPlanId);
        ResultSet resultSet = stmt.executeQuery();
        if (resultSet.next()) {
            Blob blobSnapshot = resultSet.getBlob("snapshot");
            int blobLength = (int) blobSnapshot.length();
            blobAsBytes = blobSnapshot.getBytes(1, blobLength);
        }

    } catch (SQLException e) {
        log.error("Error while retrieving revision " + revision + "of execution plan:" + executionPlanId
                + "from the database", e);
    } finally {
        cleanupConnections(stmt, con);
    }
    return blobAsBytes;
}

From source file:org.executequery.gui.resultset.TableCellData.java

private Object readBlob() {

    if (lobValue != null) {

        return lobValue;
    }/*from   www .j a v  a 2s  .c om*/

    Blob blob = (Blob) value;

    InputStream binaryStream = null;

    try {

        lobValue = blob.getBytes(1, (int) blob.length());

    } catch (SQLException e) {

        if (Log.isDebugEnabled()) {

            Log.debug("Error reading BLOB data", e);
        }

        return e.getMessage();

    } finally {

        try {

            if (binaryStream != null) {

                binaryStream.close();
            }

        } catch (IOException e) {
        }

    }

    return lobValue;
}

From source file:com.bjtct.controller.BaseController.java

@RequestMapping(value = "/home", method = RequestMethod.GET)
public String printWelcome(ModelMap model) throws SQLException {

    // got all team list
    List<Team> teamList = TeamDataDAO.getAllTeams();
    List<TeamForm> teamFormList = new ArrayList<TeamForm>();
    TeamForm tf = null;/*from   w ww  .  j  a  v  a 2 s  .c  om*/
    try {
        // preparing team form
        if (null != teamList && teamList.size() > 0) {

            for (Team t : teamList) {
                tf = new TeamForm();
                Blob b = t.getLogo();
                byte[] blobAsBytes = b.getBytes(1, (int) b.length());
                byte[] encoded = Base64.encodeBase64(blobAsBytes);
                String pic = new String(encoded);

                tf.setId(t.getId());
                tf.setLogo(pic);
                teamFormList.add(tf);
                // model.addAttribute(t.getId().toString(), pic);
            }
        }
    } catch (Exception e) {
        e.printStackTrace();
    }
    model.addAttribute(teamFormList);
    System.out.println(teamList.size());
    return "teams/home";

}