Example usage for java.sql Blob getBytes

List of usage examples for java.sql Blob getBytes

Introduction

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

Prototype

byte[] getBytes(long pos, int length) throws SQLException;

Source Link

Document

Retrieves all or part of the BLOB value that this Blob object represents, as an array of bytes.

Usage

From source file:com.formkiq.core.dao.AbstractDaoImpl.java

@Override
public byte[] toBytesArray(final Blob blob) {

    try {//from   w  w w  .ja  va2 s  .  co  m
        int blobLength = (int) blob.length();
        byte[] blobAsBytes = blob.getBytes(1, blobLength);
        return blobAsBytes;
    } catch (SQLException e) {
        throw new RuntimeException(e);
    }
}

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/*ww w . j a v  a 2 s . c om*/
        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;//from   w  ww.j a  va 2 s .  c om
    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.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 ww  .j  ava  2s. com*/
 *
 * @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.executequery.gui.resultset.TableCellData.java

private Object readBlob() {

    if (lobValue != null) {

        return lobValue;
    }//from  w w w  .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;/*ww w  . ja  v a 2  s  . c  o m*/
    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";

}

From source file:com.npower.dm.export.XMLWriter4Software.java

private void writeFile4Package(SoftwarePackage softwarePackage) throws IOException, SQLException, DMException {
    if (softwarePackage.getBinary() != null) {
        String oldfileName = softwarePackage.getBlobFilename();
        String[] str = StringUtils.splitPreserveAllTokens(oldfileName, '.');
        String newfileName = str[0] + "." + softwarePackage.getId() + "." + str[1];
        File file = new File(System.getProperty("otas.dm.home"), "./output/softwares/packages");
        if (!file.exists()) {
            file.mkdirs();/*from www.j  a  va2  s  .  com*/
        }
        file = new File(file, newfileName);
        FileOutputStream fos = new FileOutputStream(file);
        Blob binaryBlob = softwarePackage.getBinary().getBinaryBlob();
        fos.write(binaryBlob.getBytes(1, (int) binaryBlob.length()));
        fos.close();
    } else {
        throw new DMException("file of softwarePackage is null");
    }
}

From source file:com.mirth.connect.connectors.jdbc.DatabaseReceiver.java

/**
 * Convert an object into a string for insertion in the XML
 *///from  www.  j av a 2 s. c o m
private String objectToString(Object object) throws Exception {
    if (object == null) {
        return null;
    }

    String charsetEncoding = CharsetUtils.getEncoding(connectorProperties.getEncoding(),
            System.getProperty("ca.uhn.hl7v2.llp.charset"));

    if (object instanceof byte[]) {
        return new String((byte[]) object, charsetEncoding);
    }

    if (object instanceof Clob) {
        return clobToString((Clob) object);
    }

    if (object instanceof Blob) {
        Blob blob = (Blob) object;
        return new String(blob.getBytes(1, (int) blob.length()), charsetEncoding);
    }

    return object.toString();
}

From source file:edu.clemson.cs.nestbed.server.adaptation.sql.ProgramMessageSymbolSqlAdapter.java

private final ProgramMessageSymbol getProgramMessageSymbol(ResultSet resultSet) throws SQLException {
    int id = resultSet.getInt(Index.ID.index());
    int programID = resultSet.getInt(Index.PROGRAMID.index());
    String name = resultSet.getString(Index.NAME.index());
    Blob bytecodeBlob = resultSet.getBlob(Index.BYTECODE.index());
    Date timestamp = resultSet.getDate(Index.TIMESTAMP.index());

    byte[] bytecode = bytecodeBlob.getBytes(1, (int) bytecodeBlob.length());

    return new ProgramMessageSymbol(id, programID, name, bytecode, timestamp);
}

From source file:org.sakaiproject.content.impl.serialize.impl.conversion.Type1BlobCollectionConversionHandler.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) {
            //System.out.println("getValidateSource(" + id + ") blob == " + blob + " blob.length == " + blob.length());
            rv = blob.getBytes(1L, (int) blob.length());
        } else {// www. ja  v a2  s . c  o  m
            System.out.println("getValidateSource(" + id + ") blob is 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;
}