Example usage for java.sql PreparedStatement setBinaryStream

List of usage examples for java.sql PreparedStatement setBinaryStream

Introduction

In this page you can find the example usage for java.sql PreparedStatement setBinaryStream.

Prototype

void setBinaryStream(int parameterIndex, java.io.InputStream x, long length) throws SQLException;

Source Link

Document

Sets the designated parameter to the given input stream, which will have the specified number of bytes.

Usage

From source file:de.whs.poodle.repositories.ImageRepository.java

public void uploadImage(UploadedImage image, InputStream in, long length) {
    KeyHolder keyHolder = new GeneratedKeyHolder();
    jdbc.update(con -> {//  w w  w .ja va  2  s .  com
        PreparedStatement ps = con.prepareStatement(
                "INSERT INTO uploaded_image(filename,mimetype,data,instructor_id,course_id) VALUES(?,?,?,?,?)",
                new String[] { "id" });

        ps.setString(1, image.getFilename());
        ps.setString(2, image.getMimeType());
        ps.setBinaryStream(3, in, length);
        ps.setInt(4, image.getInstructor().getId());
        ps.setInt(5, image.getCourseId());
        return ps;
    }, keyHolder);

    int id = keyHolder.getKey().intValue();
    image.setId(id);
}

From source file:org.wso2.carbon.identity.application.mgt.dao.impl.ApplicationTemplateDAOImpl.java

/**
 * Set given string as Blob for the given index into the prepared-statement.
 *
 * @param value string value to be converted to blob
 * @param prepStmt Prepared statement//ww  w .j a v  a  2  s  .c  o m
 * @param index column index
 * @throws SQLException
 * @throws IOException
 */
private void setBlobValue(String value, PreparedStatement prepStmt, int index)
        throws SQLException, IOException {

    if (value != null) {
        InputStream inputStream = new ByteArrayInputStream(value.getBytes());
        prepStmt.setBinaryStream(index, inputStream, inputStream.available());
    } else {
        prepStmt.setBinaryStream(index, new ByteArrayInputStream(new byte[0]), 0);
    }
}

From source file:com.sun.licenseserver.License.java

public void addToDatabase() throws LicenseServerException {
    m_log.finer("Entering Function...");
    if (id != null && !"".equals(id.trim())) {
        m_log.severe("Trying to add an already existing license to the database");
        throw new LicenseServerException(LicenseServerException.EC_NO_ERROR_CODE,
                "Trying to add an already existing license to the database");
    }/*  w  w  w . j a  v  a2s.c  o m*/
    verifyLicenseFields();
    id = String.valueOf(System.currentTimeMillis());
    m_log.fine("Adding to database a license bject with id=[" + id + "]&shopId=[" + shopId + "]&contentId=["
            + contentId + "]&userId=[" + userId + "]&license=[" + license + "]");
    String sql = "insert into sunLsLicenses (id, contentId, shopId, userId, mime, license) values" + "(" + "'"
            + id + "', " + "'" + contentId + "', " + "'" + shopId + "', " + "'" + userId + "', " + "'" + mime
            + "', " + "?" + ")";
    DatabaseHelper dh = DatabaseHelper.getDatabaseHelper();
    PreparedStatement ps = null;
    Connection con = null;
    con = dh.getConnection();
    try {
        ps = con.prepareStatement(sql);
        ps.setBinaryStream(1, license, (int) licSize);
        ps.executeUpdate();
    } catch (SQLException e) {
        e.printStackTrace();
        new LicenseServerException(LicenseServerException.EC_DATABASE_ERROR,
                "Error in executing the SQL statement to add a license");
    }
    m_log.finer("Leaving Function...");
    return;
}

From source file:com.flexive.core.storage.genericSQL.GenericBinarySQLOutputStream.java

/**
 * {@inheritDoc}/*from   www.j a va  2  s .co m*/
 */
@Override
public void run() {
    PreparedStatement ps = null;
    Connection con = null;
    try {
        con = Database.getNonTXDataSource(divisionId).getConnection();
        ps = con.prepareStatement("INSERT INTO " + DatabaseConst.TBL_BINARY_TRANSIT
                + " (BKEY,MIMETYPE,FBLOB,TFER_DONE,EXPIRE) VALUES(?,?,?,?,?)");
        ps.setString(1, handle);
        ps.setString(2, mimeType);
        ps.setBinaryStream(3, pipe, (int) expectedSize);
        ps.setBoolean(4, false);
        ps.setLong(5, System.currentTimeMillis() + ttl);
        long time = System.currentTimeMillis();
        ps.executeUpdate();
        if (LOG.isDebugEnabled())
            LOG.debug("Stored " + count + "/" + expectedSize + " bytes in "
                    + (System.currentTimeMillis() - time) + "[ms] in DB");
        try {
            pipe.close();
        } catch (IOException e) {
            LOG.error("IO error closing pipe: " + e.getMessage(), e);
        }
    } catch (SQLException e) {
        LOG.error("SQL error storing binary: " + e.getMessage(), e);
    } finally {
        Database.closeObjects(GenericBinarySQLOutputStream.class, con, ps);
    }
}

From source file:org.dcache.chimera.H2FsSqlDriver.java

@Override
long createTagInode(int uid, int gid, int mode, byte[] value) {
    final String CREATE_TAG_INODE_WITH_VALUE = "INSERT INTO t_tags_inodes (imode, inlink, iuid, igid, isize, "
            + "ictime, iatime, imtime, ivalue) VALUES (?,1,?,?,?,?,?,?,?)";

    Timestamp now = new Timestamp(System.currentTimeMillis());
    KeyHolder keyHolder = new GeneratedKeyHolder();
    int rc = _jdbc.update(con -> {
        PreparedStatement ps = con.prepareStatement(CREATE_TAG_INODE_WITH_VALUE,
                Statement.RETURN_GENERATED_KEYS);
        ps.setInt(1, mode | UnixPermission.S_IFREG);
        ps.setInt(2, uid);/*from w ww  .j  av a 2s.  com*/
        ps.setInt(3, gid);
        ps.setLong(4, value.length);
        ps.setTimestamp(5, now);
        ps.setTimestamp(6, now);
        ps.setTimestamp(7, now);
        ps.setBinaryStream(8, new ByteArrayInputStream(value), value.length);
        return ps;
    }, keyHolder);
    if (rc != 1) {
        throw new JdbcUpdateAffectedIncorrectNumberOfRowsException(CREATE_TAG_INODE_WITH_VALUE, 1, rc);
    }
    /* H2 uses weird names for the column with the auto-generated key, so we cannot use the code
     * in the base class.
     */
    return (Long) keyHolder.getKey();
}

From source file:org.quartz.impl.jdbcjobstore.PointbaseDelegate.java

/**
 * <p>/*from  ww  w  . j  a v a  2s  .c  o m*/
 * Update the job data map for the given job.
 * </p>
 * 
 * @param conn
 *          the DB Connection
 * @param job
 *          the job to update
 * @return the number of rows updated
 */
public int updateJobData(Connection conn, JobDetail job) throws IOException, SQLException {
    //log.debug( "Updating Job Data for Job " + job );
    ByteArrayOutputStream baos = serializeJobData(job.getJobDataMap());
    int len = baos.toByteArray().length;
    ByteArrayInputStream bais = new ByteArrayInputStream(baos.toByteArray());
    PreparedStatement ps = null;

    try {
        ps = conn.prepareStatement(rtp(UPDATE_JOB_DATA));
        ps.setBinaryStream(1, bais, len);
        ps.setString(2, job.getName());
        ps.setString(3, job.getGroup());

        return ps.executeUpdate();
    } finally {
        closeStatement(ps);
    }
}

From source file:org.quartz.impl.jdbcjobstore.PointbaseDelegate.java

/**
 * <p>/* w ww .j a v a  2 s .  c  o  m*/
 * Update a calendar.
 * </p>
 * 
 * @param conn
 *          the DB Connection
 * @param calendarName
 *          the name for the new calendar
 * @param calendar
 *          the calendar
 * @return the number of rows updated
 * @throws IOException
 *           if there were problems serializing the calendar
 */
public int updateCalendar(Connection conn, String calendarName, Calendar calendar)
        throws IOException, SQLException {
    //log.debug( "Updating calendar " + calendarName + " : " + calendar );
    ByteArrayOutputStream baos = serializeObject(calendar);
    byte buf[] = baos.toByteArray();
    ByteArrayInputStream bais = new ByteArrayInputStream(buf);

    PreparedStatement ps = null;

    try {
        ps = conn.prepareStatement(rtp(UPDATE_CALENDAR));
        ps.setBinaryStream(1, bais, buf.length);
        ps.setString(2, calendarName);

        return ps.executeUpdate();
    } finally {
        closeStatement(ps);
    }
}

From source file:no.sintef.jarfter.PostgresqlInteractor.java

public int addFileEntry_havahol(String h_id, String filename) throws SQLException, IOException {
    checkConnection();/* ww  w  .ja  v  a2s .c om*/

    File file = new File(filename);
    if (!file.exists()) {
        throw new IOException("File " + filename + " does not exist");
    }
    FileInputStream fis = new FileInputStream(file);
    PreparedStatement pst = conn
            .prepareStatement("INSERT INTO havahol (h_id, visual_name, file) VALUES (?, ?, ?)");
    pst.setString(1, h_id);
    pst.setString(2, filename);
    pst.setBinaryStream(3, fis, (int) file.length());
    int rowsUpdated = pst.executeUpdate();
    pst.close();
    fis.close();
    log("addFileEntry_havahol - End of method");
    return rowsUpdated;
}

From source file:no.sintef.jarfter.PostgresqlInteractor.java

public int addFilesEntry(String fileid, String filename, String rawDataFilename) throws JarfterException {
    checkConnection();/*from w  ww  .jav a  2  s  . c o  m*/

    File rawDataFile = null;
    FileInputStream rawDataStream = null;
    try {
        rawDataFile = new File(rawDataFilename);
        rawDataStream = new FileInputStream(rawDataFile); // this constructor throws exception if file not exist
    } catch (FileNotFoundException nofile) {
        log("addFilesEntry - Did not find rawDataFile");
        error(nofile);
        throw new JarfterException(JarfterException.Error.IO_NO_TEMP_RAWDATA);
    }

    int rowsUpdated;
    try {
        PreparedStatement pst = conn
                .prepareStatement("INSERT INTO files (fileid, filename, file) VALUES (?, ?, ?)");
        pst.setString(1, fileid);
        pst.setString(2, filename);
        pst.setBinaryStream(3, rawDataStream, (int) rawDataFile.length());
        rowsUpdated = pst.executeUpdate();
        pst.close();
        log("addFilesEntry - End of method");
        return rowsUpdated;
    } catch (SQLException sqle) {
        log("addFilesEntry - got SQLException...");
        error(sqle);
        if (sqle.getLocalizedMessage().contains("duplicate key value")) {
            throw new JarfterException(JarfterException.Error.SQL_DUPLICATED_KEY);
        }
        throw new JarfterException(JarfterException.Error.SQL_UNKNOWN_ERROR, sqle.getLocalizedMessage());
    }
}

From source file:org.quartz.impl.jdbcjobstore.PointbaseDelegate.java

/**
 * <p>/*  ww  w  .jav  a  2 s  .co m*/
 * Insert a new calendar.
 * </p>
 * 
 * @param conn
 *          the DB Connection
 * @param calendarName
 *          the name for the new calendar
 * @param calendar
 *          the calendar
 * @return the number of rows inserted
 * @throws IOException
 *           if there were problems serializing the calendar
 */
public int insertCalendar(Connection conn, String calendarName, Calendar calendar)
        throws IOException, SQLException {
    //log.debug( "Inserting Calendar " + calendarName + " : " + calendar
    // );
    ByteArrayOutputStream baos = serializeObject(calendar);
    byte buf[] = baos.toByteArray();
    ByteArrayInputStream bais = new ByteArrayInputStream(buf);

    PreparedStatement ps = null;

    try {
        ps = conn.prepareStatement(rtp(INSERT_CALENDAR));
        ps.setString(1, calendarName);
        ps.setBinaryStream(2, bais, buf.length);

        return ps.executeUpdate();
    } finally {
        closeStatement(ps);
    }
}