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.playright.servlet.DataController.java

/**
 * Handles the HTTP <code>POST</code> method.
 *
 * @param request servlet request/* ww w. j av  a  2 s  .  c o  m*/
 * @param response servlet response
 * @throws ServletException if a servlet-specific error occurs
 * @throws IOException if an I/O error occurs
 */
@Override
protected void doPost(HttpServletRequest request, HttpServletResponse response)
        throws ServletException, IOException {
    //        processRequest(request, response);
    String action = request.getParameter("action");
    if (action != null) {
        DataDao dataDao = new DataDao();
        Gson gson = new GsonBuilder().setPrettyPrinting().create();
        response.setContentType("application/json");
        String successResponse = "{\"success\":\"true\"}";
        try {
            if (action.equals("listCvgData")) {
                int stPgIdx = Integer.parseInt(request.getParameter("page"));
                int recPerPg = Integer.parseInt(request.getParameter("rows"));
                List<CoverageData> data = dataDao.getPaginatedCoverageData(stPgIdx, recPerPg);
                int dataCount = dataDao.getTableSize("pr_cvg_data");

                // Convert Java Object to Json
                String jsonArray = gson.toJson(data);
                jsonArray = "{\"total\":" + dataCount + ",\"rows\":" + jsonArray + "}";
                response.getWriter().print(jsonArray);
            } else if (action.equals("listEntityMatrix")) {
                Integer cvgDataId = Integer.parseInt(request.getParameter("cvgDataId"));
                List<EntityMatrix> data = dataDao.getEntityMatrixByCvgDataId(cvgDataId);
                String jsonArray = gson.toJson(data);
                response.getWriter().print(jsonArray);
            } else if (action.equals("saveCvgData")) {
                if (request.getParameterMap().size() > 2) {
                    CoverageData cd = getCoverageDateFromRequest(request);
                    if (cd.getId() == null || cd.getId() == 0) {
                        dataDao.addCoverageData(cd);
                    } else {
                        dataDao.updateCoverageData(cd);
                    }
                    response.getWriter().print(successResponse);
                } else {
                    response.setContentType("text/html");
                    response.getWriter().print("Error: Error in multipart initialization");
                }
            } else if (action.equals("updateCvgData")) {
                CoverageData cd = getCoverageDateFromRequest(request);
                dataDao.updateCoverageData(cd);
                response.getWriter().print(successResponse);
            } else if (action.equals("deleteCvgData")) {
                Integer cvgDataId = Integer.parseInt(request.getParameter("cvgDataId"));
                response.setContentType("application/json");
                dataDao.deleteCvgData(cvgDataId);
                response.getWriter().print(successResponse);
            } else if (action.equals("getLanguages")) {
                String jsonArray = gson.toJson(dataDao.getLanguages());
                response.getWriter().print(jsonArray);
            } else if (action.equals("displayImage")) {
                Integer cvgDataId = Integer.parseInt(request.getParameter("cvgDataId"));
                CoverageData cvgData = dataDao.getCoverageDataById(cvgDataId, true);
                Blob img = cvgData.getImageBlob();
                byte[] imgData;
                try {
                    imgData = img.getBytes(1, (int) img.length());
                    response.setHeader("expires", "0");
                    response.setContentType(cvgData.getImageType());
                    //                        response.addHeader("Content-Disposition: attachment", "attachment;filename="+cvgDataId+".jpg");
                    response.getOutputStream().write(imgData);
                    response.setContentLength(imgData.length);
                } catch (SQLException ex) {
                    Logger.getLogger(DataController.class.getName()).log(Level.SEVERE, null, ex);
                }
            } else if (action.equals("saveEntityMatrix")) {
                BufferedReader br = new BufferedReader(new InputStreamReader(request.getInputStream()));
                EntityMatrix em = gson.fromJson(br, EntityMatrix.class);
                if (em.getId() == 0) {
                    dataDao.addEntityMatrix(em);
                } else {
                    dataDao.updateEntityMatrix(em);
                }
                response.getWriter().print(successResponse);
            } else if (action.equals("addKeyword")) {
                Keyword kw = getKeywordFromRequest(request);
                dataDao.addKeyword(kw);
                response.getWriter().print(successResponse);
            } else if (action.equals("updateKeyword")) {
                Keyword kw = getKeywordFromRequest(request);
                dataDao.updateKeyword(kw);
                response.getWriter().print(successResponse);
            } else if (action.equals("listKeywords")) {
                List<Keyword> data = new ArrayList<Keyword>();
                data = dataDao.getAllKeywords();
                String jsonArray = gson.toJson(data);
                jsonArray = "{\"rows\":" + jsonArray + "}";
                response.getWriter().print(jsonArray);
            }

        } catch (NumberFormatException ex) {
            String error = "{\"result\":\"error\",\"errorMsg\":\"" + ex.getMessage() + "\"}";
            response.getWriter().print(error);
        } catch (IOException ex) {
            String error = "{\"result\":\"error\",\"errorMsg\":\"" + ex.getMessage() + "\"}";
            response.getWriter().print(error);
        } catch (ServletException ex) {
            String error = "{\"result\":\"error\",\"errorMsg\":\"" + ex.getMessage() + "\"}";
            response.getWriter().print(error);
        } catch (JsonSyntaxException ex) {
            String error = "{\"result\":\"error\",\"errorMsg\":\"" + ex.getMessage() + "\"}";
            response.getWriter().print(error);
        } catch (JsonIOException ex) {
            String error = "{\"result\":\"error\",\"errorMsg\":\"" + ex.getMessage() + "\"}";
            response.getWriter().print(error);
        } finally {
            dataDao.close();
        }
    }
}

From source file:gobblin.metastore.MysqlStateStore.java

protected List<T> getAll(String storeName, String tableName, boolean useLike) throws IOException {
    List<T> states = Lists.newArrayList();

    try (Connection connection = dataSource.getConnection();
            PreparedStatement queryStatement = connection
                    .prepareStatement(useLike ? SELECT_JOB_STATE_WITH_LIKE_SQL : SELECT_JOB_STATE_SQL)) {
        queryStatement.setString(1, storeName);
        queryStatement.setString(2, tableName);

        try (ResultSet rs = queryStatement.executeQuery()) {
            while (rs.next()) {
                Blob blob = rs.getBlob(1);
                Text key = new Text();

                try (InputStream is = StreamUtils.isCompressed(blob.getBytes(1, 2))
                        ? new GZIPInputStream(blob.getBinaryStream())
                        : blob.getBinaryStream(); DataInputStream dis = new DataInputStream(is)) {
                    // keep deserializing while we have data
                    while (dis.available() > 0) {
                        T state = this.stateClass.newInstance();
                        key.readString(dis);
                        state.readFields(dis);
                        states.add(state);
                    }//  w  w w .  j  a  v  a 2  s .c om
                } catch (EOFException e) {
                    // no more data. GZIPInputStream.available() doesn't return 0 until after EOF.
                }
            }
        }
    } catch (RuntimeException re) {
        throw re;
    } catch (Exception e) {
        throw new IOException(
                "failure retrieving state from storeName " + storeName + " tableName " + tableName, e);
    }

    return states;
}

From source file:gobblin.metastore.MysqlStateStore.java

@Override
public T get(String storeName, String tableName, String stateId) throws IOException {
    try (Connection connection = dataSource.getConnection();
            PreparedStatement queryStatement = connection.prepareStatement(SELECT_JOB_STATE_SQL)) {
        int index = 0;
        queryStatement.setString(++index, storeName);
        queryStatement.setString(++index, tableName);

        try (ResultSet rs = queryStatement.executeQuery()) {
            if (rs.next()) {
                Blob blob = rs.getBlob(1);
                Text key = new Text();

                try (InputStream is = StreamUtils.isCompressed(blob.getBytes(1, 2))
                        ? new GZIPInputStream(blob.getBinaryStream())
                        : blob.getBinaryStream(); DataInputStream dis = new DataInputStream(is)) {
                    // keep deserializing while we have data
                    while (dis.available() > 0) {
                        T state = this.stateClass.newInstance();

                        key.readFields(dis);
                        state.readFields(dis);

                        if (key.toString().equals(stateId)) {
                            return state;
                        }/*from w w w  .j  a va 2 s.  c  om*/
                    }
                } catch (EOFException e) {
                    // no more data. GZIPInputStream.available() doesn't return 0 until after EOF.
                }
            }
        }
    } catch (RuntimeException e) {
        throw e;
    } catch (Exception e) {
        throw new IOException(
                "failure retrieving state from storeName " + storeName + " tableName " + tableName, e);
    }

    return null;
}

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

public Map<Integer, Testbed> readTestbeds() throws AdaptationException {
    Map<Integer, Testbed> testbeds = new HashMap<Integer, Testbed>();
    Connection connection = null;
    Statement statement = null;//from   ww  w  .  ja  v a 2s  .co  m
    ResultSet resultSet = null;

    ProjectAdapter projectAdapter = AdapterFactory.createProjectAdapter(AdapterType.SQL);

    try {
        String query = "SELECT * FROM Testbeds";

        connection = DriverManager.getConnection(CONN_STR);
        statement = connection.createStatement();
        resultSet = statement.executeQuery(query);

        while (resultSet.next()) {
            int id;
            String name;
            String description;
            Blob imageBlob;
            Date timestamp;

            id = resultSet.getInt(Index.ID.index());
            name = resultSet.getString(Index.NAME.index());
            description = resultSet.getString(Index.DESCRIPTION.index());
            imageBlob = resultSet.getBlob(Index.IMAGE.index());
            timestamp = resultSet.getDate(Index.TIMESTAMP.index());

            byte[] image = (imageBlob != null && imageBlob.length() > 0)
                    ? imageBlob.getBytes(0, (int) imageBlob.length())
                    : null;

            Testbed testbed = new Testbed(id, name, description, image, timestamp);
            testbeds.put(id, testbed);
        }
    } catch (SQLException ex) {
        String msg = "SQLException in readTestbeds";
        log.error(msg, ex);
        throw new AdaptationException(msg, ex);
    } finally {
        try {
            resultSet.close();
        } catch (Exception ex) {
        }
        try {
            statement.close();
        } catch (Exception ex) {
        }
        try {
            connection.close();
        } catch (Exception ex) {
        }
    }

    return testbeds;
}

From source file:org.infoglue.calendar.controllers.ResourceController.java

private void dumpResource(Resource resource) {
    if (resource == null) {
        log.warn("Tried to dump event resource to disk but the reference was null");
    }//from  w  w w . ja v a 2 s.c  o  m
    FileOutputStream fos = null;
    try {
        File outputFile = getResourceFile(resource);
        fos = new FileOutputStream(outputFile);

        Blob blob = resource.getResource();
        byte[] bytes = blob.getBytes(1, (int) blob.length());
        fos.write(bytes);
        fos.flush();
        fos.close();
    } catch (FileNotFoundException ex) {
        log.error("FileNotFoundException when dumping calendar resource to disk. " + resource.getFileName()
                + ". Exception message: " + ex.getMessage());
        log.warn("FileNotFoundException when dumping calendar resource to disk. " + resource.getFileName(), ex);
    } catch (SQLException ex) {
        log.error("SQLException when dumping calendar resource to disk. " + resource.getFileName()
                + ". Exception message: " + ex.getMessage());
        log.warn("SQLException when dumping calendar resource to disk. " + resource.getFileName(), ex);
    } catch (IOException ex) {
        log.error("IOException when dumping calendar resource to disk. " + resource.getFileName()
                + ". Exception message: " + ex.getMessage());
        log.warn("IOException when dumping calendar resource to disk. " + resource.getFileName(), ex);
    } finally {
        if (fos != null) {
            try {
                fos.close();
            } catch (IOException ex) {
                log.error(
                        "Could not close file after an exception occured while dumping resource to disk. Resource: "
                                + resource.getFileName() + " . Message: " + ex.getMessage());
            }
        }
    }
}

From source file:org.agnitas.backend.DBase.java

public byte[] asBlob(Object o) {
    if (o == null) {
        return null;
    } else if (o.getClass().getName().equals("[B")) {
        return (byte[]) o;
    } else {//from  w w  w  .j  av a 2 s . c o  m
        Blob blob = (Blob) o;

        try {
            return blob == null ? null : blob.getBytes(1, (int) blob.length());
        } catch (SQLException e) {
            failure("blob parse", e);
        }
        return null;
    }
}

From source file:org.pentaho.di.jdbc.Support.java

/**
 * Convert an existing data object to the specified JDBC type.
 *
 * @param callerReference an object reference to the caller of this method;
 *                        must be a <code>Connection</code>,
 *                        <code>Statement</code> or <code>ResultSet</code>
 * @param x               the data object to convert
 * @param jdbcType        the required type constant from
 *                        <code>java.sql.Types</code>
 * @return the converted data object/*  w  ww  . j  a  v a2 s  .  co m*/
 * @throws SQLException if the conversion is not supported or fails
 */
static Object convert(Object callerReference, Object x, int jdbcType, String charSet) throws SQLException {
    try {
        switch (jdbcType) {
        case java.sql.Types.TINYINT:
        case java.sql.Types.SMALLINT:
        case java.sql.Types.INTEGER:
            if (x == null) {
                return INTEGER_ZERO;
            } else if (x instanceof Integer) {
                return x;
            } else if (x instanceof Byte) {
                return new Integer(((Byte) x).byteValue() & 0xFF);
            } else if (x instanceof Number) {
                return new Integer(((Number) x).intValue());
            } else if (x instanceof String) {
                return new Integer(((String) x).trim());
            } else if (x instanceof Boolean) {
                return ((Boolean) x).booleanValue() ? INTEGER_ONE : INTEGER_ZERO;
            }
            break;

        case java.sql.Types.BIGINT:
            if (x == null) {
                return LONG_ZERO;
            } else if (x instanceof Long) {
                return x;
            } else if (x instanceof Byte) {
                return new Long(((Byte) x).byteValue() & 0xFF);
            } else if (x instanceof Number) {
                return new Long(((Number) x).longValue());
            } else if (x instanceof String) {
                return new Long(((String) x).trim());
            } else if (x instanceof Boolean) {
                return ((Boolean) x).booleanValue() ? LONG_ONE : LONG_ZERO;
            }

            break;

        case java.sql.Types.REAL:
            if (x == null) {
                return FLOAT_ZERO;
            } else if (x instanceof Float) {
                return x;
            } else if (x instanceof Byte) {
                return new Float(((Byte) x).byteValue() & 0xFF);
            } else if (x instanceof Number) {
                return new Float(((Number) x).floatValue());
            } else if (x instanceof String) {
                return new Float(((String) x).trim());
            } else if (x instanceof Boolean) {
                return ((Boolean) x).booleanValue() ? FLOAT_ONE : FLOAT_ZERO;
            }

            break;

        case java.sql.Types.FLOAT:
        case java.sql.Types.DOUBLE:
            if (x == null) {
                return DOUBLE_ZERO;
            } else if (x instanceof Double) {
                return x;
            } else if (x instanceof Byte) {
                return new Double(((Byte) x).byteValue() & 0xFF);
            } else if (x instanceof Number) {
                return new Double(((Number) x).doubleValue());
            } else if (x instanceof String) {
                return new Double(((String) x).trim());
            } else if (x instanceof Boolean) {
                return ((Boolean) x).booleanValue() ? DOUBLE_ONE : DOUBLE_ZERO;
            }

            break;

        case java.sql.Types.NUMERIC:
        case java.sql.Types.DECIMAL:
            if (x == null) {
                return null;
            } else if (x instanceof BigDecimal) {
                return x;
            } else if (x instanceof Number) {
                return new BigDecimal(x.toString());
            } else if (x instanceof String) {
                return new BigDecimal((String) x);
            } else if (x instanceof Boolean) {
                return ((Boolean) x).booleanValue() ? BIG_DECIMAL_ONE : BIG_DECIMAL_ZERO;
            }

            break;

        case java.sql.Types.VARCHAR:
        case java.sql.Types.CHAR:
            if (x == null) {
                return null;
            } else if (x instanceof String) {
                return x;
            } else if (x instanceof Number) {
                return x.toString();
            } else if (x instanceof Boolean) {
                return ((Boolean) x).booleanValue() ? "1" : "0";
            } else if (x instanceof Clob) {
                Clob clob = (Clob) x;
                long length = clob.length();

                if (length > Integer.MAX_VALUE) {
                    throw new SQLException(BaseMessages.getString(PKG, "error.normalize.lobtoobig"), "22000");
                }

                return clob.getSubString(1, (int) length);
            } else if (x instanceof Blob) {
                Blob blob = (Blob) x;
                long length = blob.length();

                if (length > Integer.MAX_VALUE) {
                    throw new SQLException(BaseMessages.getString(PKG, "error.normalize.lobtoobig"), "22000");
                }

                x = blob.getBytes(1, (int) length);
            }

            if (x instanceof byte[]) {
                return toHex((byte[]) x);
            }

            return x.toString(); // Last hope!

        case java.sql.Types.BIT:
        case java.sql.Types.BOOLEAN:
            if (x == null) {
                return Boolean.FALSE;
            } else if (x instanceof Boolean) {
                return x;
            } else if (x instanceof Number) {
                return (((Number) x).intValue() == 0) ? Boolean.FALSE : Boolean.TRUE;
            } else if (x instanceof String) {
                String tmp = ((String) x).trim();

                return ("1".equals(tmp) || "true".equalsIgnoreCase(tmp)) ? Boolean.TRUE : Boolean.FALSE;
            }

            break;

        case java.sql.Types.VARBINARY:
        case java.sql.Types.BINARY:
            if (x == null) {
                return null;
            } else if (x instanceof byte[]) {
                return x;
            } else if (x instanceof Blob) {
                Blob blob = (Blob) x;

                return blob.getBytes(1, (int) blob.length());
            } else if (x instanceof Clob) {
                Clob clob = (Clob) x;
                long length = clob.length();

                if (length > Integer.MAX_VALUE) {
                    throw new SQLException(BaseMessages.getString(PKG, "error.normalize.lobtoobig"), "22000");
                }

                x = clob.getSubString(1, (int) length);
            }

            if (x instanceof String) {
                //
                // Strictly speaking this conversion is not required by
                // the JDBC standard but jTDS has always supported it.
                //
                if (charSet == null) {
                    charSet = "ISO-8859-1";
                }

                try {
                    return ((String) x).getBytes(charSet);
                } catch (UnsupportedEncodingException e) {
                    return ((String) x).getBytes();
                }
            } else if (x instanceof UniqueIdentifier) {
                return ((UniqueIdentifier) x).getBytes();
            }

            break;

        case java.sql.Types.TIMESTAMP:
            if (x == null) {
                return null;
            } else if (x instanceof DateTime) {
                return ((DateTime) x).toTimestamp();
            } else if (x instanceof java.sql.Timestamp) {
                return x;
            } else if (x instanceof java.sql.Date) {
                return new java.sql.Timestamp(((java.sql.Date) x).getTime());
            } else if (x instanceof java.sql.Time) {
                return new java.sql.Timestamp(((java.sql.Time) x).getTime());
            } else if (x instanceof java.lang.String) {
                return java.sql.Timestamp.valueOf(((String) x).trim());
            }

            break;

        case java.sql.Types.DATE:
            if (x == null) {
                return null;
            } else if (x instanceof DateTime) {
                return ((DateTime) x).toDate();
            } else if (x instanceof java.sql.Date) {
                return x;
            } else if (x instanceof java.sql.Time) {
                return DATE_ZERO;
            } else if (x instanceof java.sql.Timestamp) {
                synchronized (cal) {
                    cal.setTime((java.util.Date) x);
                    cal.set(Calendar.HOUR_OF_DAY, 0);
                    cal.set(Calendar.MINUTE, 0);
                    cal.set(Calendar.SECOND, 0);
                    cal.set(Calendar.MILLISECOND, 0);
                    // VM1.4+ only              return new java.sql.Date(cal.getTimeInMillis());
                    return new java.sql.Date(cal.getTime().getTime());
                }
            } else if (x instanceof java.lang.String) {
                return java.sql.Date.valueOf(((String) x).trim());
            }

            break;

        case java.sql.Types.TIME:
            if (x == null) {
                return null;
            } else if (x instanceof DateTime) {
                return ((DateTime) x).toTime();
            } else if (x instanceof java.sql.Time) {
                return x;
            } else if (x instanceof java.sql.Date) {
                return TIME_ZERO;
            } else if (x instanceof java.sql.Timestamp) {
                synchronized (cal) {
                    // VM 1.4+ only             cal.setTimeInMillis(((java.sql.Timestamp)x).getTime());
                    cal.setTime((java.util.Date) x);
                    cal.set(Calendar.YEAR, 1970);
                    cal.set(Calendar.MONTH, 0);
                    cal.set(Calendar.DAY_OF_MONTH, 1);
                    // VM 1.4+ only             return new java.sql.Time(cal.getTimeInMillis());*/
                    return new java.sql.Time(cal.getTime().getTime());
                }
            } else if (x instanceof java.lang.String) {
                return java.sql.Time.valueOf(((String) x).trim());
            }

            break;

        case java.sql.Types.OTHER:
            return x;

        case java.sql.Types.JAVA_OBJECT:
            throw new SQLException(BaseMessages.getString(PKG, "error.convert.badtypes", x.getClass().getName(),
                    getJdbcTypeName(jdbcType)), "22005");

        case java.sql.Types.LONGVARBINARY:
        case java.sql.Types.BLOB:
            if (x == null) {
                return null;
            } else if (x instanceof Blob) {
                return x;
            } else if (x instanceof byte[]) {
                return new BlobImpl(getConnection(callerReference), (byte[]) x);
            } else if (x instanceof Clob) {
                //
                // Convert CLOB to BLOB. Not required by the standard but we will
                // do it anyway.
                //
                Clob clob = (Clob) x;
                try {
                    if (charSet == null) {
                        charSet = "ISO-8859-1";
                    }
                    Reader rdr = clob.getCharacterStream();
                    BlobImpl blob = new BlobImpl(getConnection(callerReference));
                    BufferedWriter out = new BufferedWriter(
                            new OutputStreamWriter(blob.setBinaryStream(1), charSet));
                    // TODO Use a buffer to improve performance
                    int c;
                    while ((c = rdr.read()) >= 0) {
                        out.write(c);
                    }
                    out.close();
                    rdr.close();
                    return blob;
                } catch (UnsupportedEncodingException e) {
                    // Unlikely to happen but fall back on in memory copy
                    x = clob.getSubString(1, (int) clob.length());
                } catch (IOException e) {
                    throw new SQLException(BaseMessages.getString(PKG, "error.generic.ioerror", e.getMessage()),
                            "HY000");
                }
            }

            if (x instanceof String) {
                //
                // Strictly speaking this conversion is also not required by
                // the JDBC standard but jTDS has always supported it.
                //
                BlobImpl blob = new BlobImpl(getConnection(callerReference));
                String data = (String) x;

                if (charSet == null) {
                    charSet = "ISO-8859-1";
                }

                try {
                    blob.setBytes(1, data.getBytes(charSet));
                } catch (UnsupportedEncodingException e) {
                    blob.setBytes(1, data.getBytes());
                }

                return blob;
            }

            break;

        case java.sql.Types.LONGVARCHAR:
        case java.sql.Types.CLOB:
            if (x == null) {
                return null;
            } else if (x instanceof Clob) {
                return x;
            } else if (x instanceof Blob) {
                //
                // Convert BLOB to CLOB
                //
                Blob blob = (Blob) x;
                try {
                    InputStream is = blob.getBinaryStream();
                    ClobImpl clob = new ClobImpl(getConnection(callerReference));
                    Writer out = clob.setCharacterStream(1);
                    // TODO Use a buffer to improve performance
                    int b;
                    // These reads/writes are buffered by the undelying blob buffers
                    while ((b = is.read()) >= 0) {
                        out.write(hex[b >> 4]);
                        out.write(hex[b & 0x0F]);
                    }
                    out.close();
                    is.close();
                    return clob;
                } catch (IOException e) {
                    throw new SQLException(BaseMessages.getString(PKG, "error.generic.ioerror", e.getMessage()),
                            "HY000");
                }
            } else if (x instanceof Boolean) {
                x = ((Boolean) x).booleanValue() ? "1" : "0";
            } else if (!(x instanceof byte[])) {
                x = x.toString();
            }

            if (x instanceof byte[]) {
                ClobImpl clob = new ClobImpl(getConnection(callerReference));
                clob.setString(1, toHex((byte[]) x));

                return clob;
            } else if (x instanceof String) {
                return new ClobImpl(getConnection(callerReference), (String) x);
            }

            break;

        default:
            throw new SQLException(
                    BaseMessages.getString(PKG, "error.convert.badtypeconst", getJdbcTypeName(jdbcType)),
                    "HY004");
        }

        throw new SQLException(BaseMessages.getString(PKG, "error.convert.badtypes", x.getClass().getName(),
                getJdbcTypeName(jdbcType)), "22005");
    } catch (NumberFormatException nfe) {
        throw new SQLException(
                BaseMessages.getString(PKG, "error.convert.badnumber", getJdbcTypeName(jdbcType)), "22000");
    }
}

From source file:org.springframework.jdbc.support.lob.OracleLobHandler.java

@Override
public byte[] getBlobAsBytes(ResultSet rs, int columnIndex) throws SQLException {
    logger.debug("Returning Oracle BLOB as bytes");
    Blob blob = rs.getBlob(columnIndex);
    initializeResourcesBeforeRead(rs.getStatement().getConnection(), blob);
    byte[] retVal = (blob != null ? blob.getBytes(1, (int) blob.length()) : null);
    releaseResourcesAfterRead(rs.getStatement().getConnection(), blob);
    return retVal;
}

From source file:IDlookGetStream.java

private void buildGUI() {
    Container c = getContentPane();
    c.setLayout(new FlowLayout());

    accountNumberList = new JList();
    loadAccounts();/*from   ww  w  .j a  va 2  s .  c o  m*/
    accountNumberList.setVisibleRowCount(2);
    JScrollPane accountNumberListScrollPane = new JScrollPane(accountNumberList);

    //Do Get Account Button
    getAccountButton = new JButton("Get Account");
    getAccountButton.addActionListener(new ActionListener() {
        public void actionPerformed(ActionEvent e) {
            try {
                rs.beforeFirst();
                while (rs.next()) {
                    if (rs.getString("acc_id").equals(accountNumberList.getSelectedValue()))
                        break;
                }
                if (!rs.isAfterLast()) {
                    accountIDText.setText(rs.getString("acc_id"));
                    thumbIDText.setText(rs.getString("thumb_id"));
                    Blob blob = rs.getBlob("pic");

                    int b;
                    InputStream bis = rs.getBinaryStream("pic");
                    FileOutputStream f = new FileOutputStream("pic.jpg");
                    while ((b = bis.read()) >= 0) {
                        f.write(b);
                    }
                    f.close();
                    bis.close();

                    icon = new ImageIcon(blob.getBytes(1L, (int) blob.length()));
                    createThumbnail();
                    photographLabel.setIcon(iconThumbnail);
                }
            } catch (Exception selectException) {
                displaySQLErrors(selectException);
            }
        }
    });

    //Do Update Account Button
    updateAccountButton = new JButton("Update Account");
    updateAccountButton.addActionListener(new ActionListener() {
        public void actionPerformed(ActionEvent e) {
            try {
                byte[] bytes = new byte[50000];
                FileInputStream fs = new FileInputStream(nailFileText.getText());
                BufferedInputStream bis = new BufferedInputStream(fs);
                bis.read(bytes);

                rs.updateBytes("thumbnail.pic", bytes);
                rs.updateRow();
                bis.close();

                accountNumberList.removeAll();
                loadAccounts();
            } catch (SQLException insertException) {
                displaySQLErrors(insertException);
            } catch (Exception generalE) {
                generalE.printStackTrace();
            }
        }
    });

    //Do insert Account Button
    insertAccountButton = new JButton("Insert Account");
    insertAccountButton.addActionListener(new ActionListener() {
        public void actionPerformed(ActionEvent e) {
            try {
                byte[] bytes = new byte[50000];
                FileInputStream fs = new FileInputStream(nailFileText.getText());
                BufferedInputStream bis = new BufferedInputStream(fs);
                bis.read(bytes);

                rs.moveToInsertRow();
                rs.updateInt("thumb_id", Integer.parseInt(thumbIDText.getText()));
                rs.updateInt("acc_id", Integer.parseInt(accountIDText.getText()));
                rs.updateBytes("pic", bytes);
                rs.updateObject("sysobject", null);
                rs.updateTimestamp("ts", new Timestamp(0));
                rs.updateTimestamp("act_ts", new Timestamp(new java.util.Date().getTime()));
                rs.insertRow();
                bis.close();

                accountNumberList.removeAll();
                loadAccounts();
            } catch (SQLException insertException) {
                displaySQLErrors(insertException);
            } catch (Exception generalE) {
                generalE.printStackTrace();
            }
        }
    });

    photographLabel = new JLabel();
    photographLabel.setHorizontalAlignment(JLabel.CENTER);
    photographLabel.setVerticalAlignment(JLabel.CENTER);
    photographLabel.setVerticalTextPosition(JLabel.CENTER);
    photographLabel.setHorizontalTextPosition(JLabel.CENTER);

    JPanel first = new JPanel(new GridLayout(4, 1));
    first.add(accountNumberListScrollPane);
    first.add(getAccountButton);
    first.add(updateAccountButton);
    first.add(insertAccountButton);

    accountIDText = new JTextField(15);
    thumbIDText = new JTextField(15);
    errorText = new JTextArea(5, 15);
    errorText.setEditable(false);

    JPanel second = new JPanel();
    second.setLayout(new GridLayout(2, 1));
    second.add(thumbIDText);
    second.add(accountIDText);

    JPanel third = new JPanel();
    third.add(new JScrollPane(errorText));

    nailFileText = new JTextField(25);

    c.add(first);
    c.add(second);
    c.add(third);
    c.add(nailFileText);
    c.add(photographLabel);

    setSize(500, 500);
    show();
}

From source file:com.p5solutions.core.jpa.orm.oracle.ConversionUtilityImpl.java

/**
 * To blob.//from   w ww .  j av  a2  s.  c  om
 * 
 * @param pb
 *          the pb
 * @param value
 *          the value
 * @param targetType
 *          the target type
 * @return the object
 */
private Object toJavaBlob(ParameterBinder pb, Object value, Class<?> targetType) {

    if (value instanceof Blob) {
        boolean isBlob = ReflectionUtility.isBlob(targetType);
        boolean isInputStream = ReflectionUtility.isInputStream(targetType);
        boolean isByteArray = ReflectionUtility.isByteArray(targetType);
        boolean isString = ReflectionUtility.isStringClass(targetType);

        Blob blob = (Blob) value;

        // if the target entity->property is of blob, return quickly.
        if (isBlob) {
            return blob;
        }

        try {
            // if the target is a string, then convert the buffer
            if (isString) {
                // if the target entity->property is a string
                int length = (int) blob.length();
                byte[] ba = blob.getBytes(0L, length);
                return new String(ba, charset);
            } else if (isByteArray) {
                // if the target entity->property is a byte array
                int length = (int) blob.length();
                byte[] ba = blob.getBytes(0L, length);
                return ba;
            } else if (isInputStream) {
                return blob.getBinaryStream();
            } else if (BlobStream.class.isAssignableFrom(targetType)) {
                BlobStream bs = new BlobStream(blob.getBinaryStream());
                return bs;
            }

        } catch (Exception e) {
            logger.error("Unable to copy data from blob stream into target byte array on entity "
                    + pb.getEntityClass() + " paramater " + pb.getBindingPath() + " and column "
                    + pb.getColumnName());
        }
    }

    return null;
}