List of usage examples for java.sql Blob getBinaryStream
java.io.InputStream getBinaryStream() throws SQLException;
From source file:org.ralasafe.entitle.BackupManagerImpl.java
public void exportBackup(int id, OutputStream out) { Connection conn = null;/*from w w w . j a v a 2s .c om*/ PreparedStatement pstmt = null; try { conn = DBPower.getConnection(table.getId()); conn.setAutoCommit(false); pstmt = conn.prepareStatement(SELECT_CONTENT_SQL); pstmt.setInt(1, id); ResultSet rs = pstmt.executeQuery(); if (rs.next()) { Blob blob = rs.getBlob(1); InputStream in = blob.getBinaryStream(); byte[] buf = new byte[1024]; int len = 0; while ((len = in.read(buf)) != -1) { out.write(buf, 0, len); } in.close(); } conn.commit(); } catch (Exception e) { log.error("", e); } finally { DBUtil.close(pstmt, conn); } }
From source file:org.rhq.enterprise.server.content.ContentManagerBean.java
/** For Testing only<br><br> * /* w w w .j a v a2 s . c om*/ * Writes the contents of a the Blob out to the stream passed in. * * @param stream non null stream where contents to be written to. */ public void writeBlobOutToStream(OutputStream stream, PackageBits bits, boolean closeStreams) { if (stream == null) { return; // no locate to write to } if ((bits == null) || (bits.getId() <= 0)) { //then PackageBits instance passed in is insufficiently initialized. log.warn("PackageBits insufficiently initialized. No data to write out."); return; } try { //open connection Connection conn = dataSource.getConnection(); //prepared statement for retrieval of Blob.bits PreparedStatement ps = conn .prepareStatement("SELECT BITS FROM " + PackageBits.TABLE_NAME + " WHERE ID = ?"); try { ps.setInt(1, bits.getId()); ResultSet results = ps.executeQuery(); try { if (results.next()) { //retrieve the Blob Blob blob = results.getBlob(1); //now copy the contents to the stream passed in StreamUtil.copy(blob.getBinaryStream(), stream, closeStreams); } } finally { results.close(); } } finally { ps.close(); } } catch (Exception ex) { log.error("An error occurred while writing Blob contents out to stream :" + ex.getMessage()); ex.printStackTrace(); } }
From source file:org.rhq.enterprise.server.content.ContentSourceManagerBean.java
@SuppressWarnings("unchecked") private long outputPackageVersionBitsRangeHelper(int resourceId, PackageDetailsKey packageDetailsKey, OutputStream outputStream, long startByte, long endByte, int packageVersionId) { // TODO: Should we make sure the resource is subscribed/allowed to receive the the package version? // Or should we not bother to perform this check? if the caller knows the PV ID, it // probably already got it through its repos Query query = entityManager// w ww . ja va2 s. c o m .createNamedQuery(PackageBits.QUERY_PACKAGE_BITS_LOADED_STATUS_PACKAGE_VERSION_ID); query.setParameter("id", packageVersionId); LoadedPackageBitsComposite composite = (LoadedPackageBitsComposite) query.getSingleResult(); boolean packageBitsAreAvailable = composite.isPackageBitsAvailable(); if (packageBitsAreAvailable) { // it says the package bits are available, but if its stored on the filesystem, we should // make sure no one deleted the file. If the file is deleted, let's simply download it again. if (!composite.isPackageBitsInDatabase()) { try { File bitsFile = getPackageBitsLocalFileAndCreateParentDir(composite.getPackageVersionId(), composite.getFileName()); if (!bitsFile.exists()) { log.warn("Package version [" + packageDetailsKey + "] has had its bits file [" + bitsFile + "] deleted. Will attempt to download it again."); packageBitsAreAvailable = false; } } catch (Exception e) { throw new RuntimeException("Package version [" + packageDetailsKey + "] has had its bits file deleted but cannot download it again.", e); } } } PackageVersionContentSource pvcs = null; // will be non-null only if package bits were not originally available if (!packageBitsAreAvailable) { if (resourceId == -1) { throw new IllegalStateException("Package bits must be inserted prior to the agent asking for them " + "during a cotent-based resource creation"); } // if we got here, the package bits have not been downloaded yet. This eliminates the // possibility that the package version were directly uploaded by a user // or auto-discovered by a resource and attached to a repo. So, that leaves // the only possibility - the package version comes from a content source and therefore has // a PackageVersionContentSource mapping. Let's find that mapping. Query q2 = entityManager .createNamedQuery(PackageVersionContentSource.QUERY_FIND_BY_PKG_VER_ID_AND_RES_ID); q2.setParameter("resourceId", resourceId); q2.setParameter("packageVersionId", packageVersionId); List<PackageVersionContentSource> pvcss = q2.getResultList(); // Note that its possible more than one content source can deliver a PV - if a resource is subscribed // to repo(s) that contain multiple content sources that can deliver a PV, we just take // the first one we find. if (pvcss.size() == 0) { throw new RuntimeException("Resource [" + resourceId + "] cannot access package version [" + packageDetailsKey + "] - no content source exists to deliver it"); } pvcs = pvcss.get(0); // Make it a true EJB call so we suspend our tx and get a new tx. // This way, we start with a fresh tx timeout when downloading and this // won't affect the time we are in in this method's tx (I hope that's how it works). // This is because this method itself may take a long time to send the data to the output stream // and we don't want out tx timing out due to the time it takes downloading. PackageBits bits = null; bits = contentSourceManager.downloadPackageBits(subjectManager.getOverlord(), pvcs); if (bits != null) { // rerun the query just to make sure we really downloaded it successfully query.setParameter("id", pvcs.getPackageVersionContentSourcePK().getPackageVersion().getId()); composite = (LoadedPackageBitsComposite) query.getSingleResult(); if (!composite.isPackageBitsAvailable()) { throw new RuntimeException("Failed to download package bits [" + packageDetailsKey + "] for resource [" + resourceId + "]"); } } else { // package bits are not loaded and never will be loaded due to content source's download mode == NEVER composite = null; } } Connection conn = null; PreparedStatement ps = null; ResultSet results = null; InputStream bitsStream = null; try { if (composite == null) { // this is DownloadMode.NEVER and we are really in pass-through mode, stream directly from adapter ContentServerPluginContainer pc = ContentManagerHelper.getPluginContainer(); ContentProviderManager adapterMgr = pc.getAdapterManager(); int contentSourceId = pvcs.getPackageVersionContentSourcePK().getContentSource().getId(); bitsStream = adapterMgr.loadPackageBits(contentSourceId, pvcs.getLocation()); } else { if (composite.isPackageBitsInDatabase()) { // this is DownloadMode.DATABASE - put the bits in the database conn = dataSource.getConnection(); ps = conn.prepareStatement("SELECT BITS FROM " + PackageBits.TABLE_NAME + " WHERE ID = ?"); ps.setInt(1, composite.getPackageBitsId()); results = ps.executeQuery(); results.next(); Blob blob = results.getBlob(1); long bytesRetrieved = 0L; if (endByte < 0L) { if (startByte == 0L) { bytesRetrieved = StreamUtil.copy(blob.getBinaryStream(), outputStream, false); } } else { long length = (endByte - startByte) + 1; //InputStream stream = blob.getBinaryStream(startByte, length); // JDK 6 api InputStream stream = blob.getBinaryStream(); bytesRetrieved = StreamUtil.copy(stream, outputStream, startByte, length); } log.debug("Retrieved and sent [" + bytesRetrieved + "] bytes for [" + packageDetailsKey + "]"); ps.close(); conn.close(); return bytesRetrieved; } else { // this is DownloadMode.FILESYSTEM - put the bits on the filesystem File bitsFile = getPackageBitsLocalFileAndCreateParentDir(composite.getPackageVersionId(), composite.getFileName()); if (!bitsFile.exists()) { throw new RuntimeException( "Package bits at [" + bitsFile + "] are missing for [" + packageDetailsKey + "]"); } bitsStream = new FileInputStream(bitsFile); } } // the magic happens here - outputStream is probably a remote stream down to the agent long bytesRetrieved; if (endByte < 0L) { if (startByte > 0L) { bitsStream.skip(startByte); } bytesRetrieved = StreamUtil.copy(bitsStream, outputStream, false); } else { BufferedInputStream bis = new BufferedInputStream(bitsStream); long length = (endByte - startByte) + 1; bytesRetrieved = StreamUtil.copy(bis, outputStream, startByte, length); } // close our stream but leave the output stream open try { bitsStream.close(); } catch (Exception closeError) { log.warn("Failed to close the bits stream", closeError); } bitsStream = null; log.debug("Retrieved and sent [" + bytesRetrieved + "] bytes for [" + packageDetailsKey + "]"); return bytesRetrieved; } catch (SQLException sql) { throw new RuntimeException( "Did not download the package bits to the DB for [" + packageDetailsKey + "]", sql); } catch (Exception e) { throw new RuntimeException("Could not stream package bits for [" + packageDetailsKey + "]", e); } finally { if (bitsStream != null) { try { bitsStream.close(); } catch (IOException e) { log.warn("Failed to close bits stream for: " + packageDetailsKey); } } if (results != null) { try { results.close(); } catch (SQLException e) { log.warn("Failed to close result set from jdbc blob query for: " + packageDetailsKey); } } if (ps != null) { try { ps.close(); } catch (SQLException e) { log.warn("Failed to close prepared statement from jdbc blob query for: " + packageDetailsKey); } } if (conn != null) { try { conn.close(); } catch (SQLException e) { log.warn("Failed to close prepared statement from jdbc blob query for: " + packageDetailsKey); } } } }
From source file:org.sakaiproject.component.common.edu.person.InetOrgPersonImpl.java
private byte[] toByteArray(Blob fromBlob, ByteArrayOutputStream baos) throws SQLException, IOException { if (LOG.isDebugEnabled()) { LOG.debug("toByteArray(Blob " + fromBlob + ", ByteArrayOutputStream " + baos + ")"); }/*from w w w .jav a2 s . co m*/ if (fromBlob == null || fromBlob.length() < 1 || ServerConfigurationService.getString("profile.photoRepositoryPath", null) != null) { return null; } byte[] buf = new byte[4000]; InputStream is = fromBlob.getBinaryStream(); try { for (;;) { int dataSize = is.read(buf); if (dataSize == -1) break; baos.write(buf, 0, dataSize); } } finally { if (is != null) { try { is.close(); } catch (IOException ex) { LOG.error(ex.getMessage(), ex); } } } return baos.toByteArray(); }
From source file:org.springframework.jdbc.support.lob.DefaultLobHandler.java
@Override @Nullable// w ww . j a va 2 s . co m public InputStream getBlobAsBinaryStream(ResultSet rs, int columnIndex) throws SQLException { logger.debug("Returning BLOB as binary stream"); if (this.wrapAsLob) { Blob blob = rs.getBlob(columnIndex); return blob.getBinaryStream(); } else { return rs.getBinaryStream(columnIndex); } }
From source file:org.springframework.jdbc.support.lob.OracleLobHandler.java
@Override public InputStream getBlobAsBinaryStream(ResultSet rs, int columnIndex) throws SQLException { logger.debug("Returning Oracle BLOB as binary stream"); Blob blob = rs.getBlob(columnIndex); initializeResourcesBeforeRead(rs.getStatement().getConnection(), blob); InputStream retVal = (blob != null ? blob.getBinaryStream() : null); releaseResourcesAfterRead(rs.getStatement().getConnection(), blob); return retVal; }
From source file:org.teiid.translator.odata4.BaseQueryExecution.java
protected InputStream executeQuery(String method, String uri, String payload, String eTag, HttpStatusCode[] expectedStatus) throws TranslatorException { Map<String, List<String>> headers = getDefaultHeaders(); if (eTag != null) { headers.put("If-Match", Arrays.asList(eTag)); //$NON-NLS-1$ }//from w ww . j a va 2s .c o m if (payload != null) { headers.put("Content-Type", Arrays.asList(ContentType.APPLICATION_JSON.toContentTypeString())); //$NON-NLS-1$ //$NON-NLS-2$ } BinaryWSProcedureExecution execution; try { execution = invokeHTTP(method, uri, payload, headers); for (HttpStatusCode status : expectedStatus) { if (status.getStatusCode() == execution.getResponseCode()) { if (execution.getResponseCode() != HttpStatusCode.NO_CONTENT.getStatusCode() && execution.getResponseCode() != HttpStatusCode.NOT_FOUND.getStatusCode()) { Blob blob = (Blob) execution.getOutputParameterValues().get(0); return blob.getBinaryStream(); } // this is success with no-data return null; } } } catch (SQLException e) { throw new TranslatorException(e); } // throw an error throw buildError(execution); }
From source file:org.teiid.translator.odata4.BaseQueryExecution.java
protected TranslatorException buildError(BinaryWSProcedureExecution execution) { // do some error handling try {/*from w ww . j a v a2 s .com*/ Blob blob = (Blob) execution.getOutputParameterValues().get(0); if (blob != null) { JsonDeserializer parser = new JsonDeserializer(false); ODataError error = parser.toError(blob.getBinaryStream()); return new TranslatorException(ODataPlugin.Util.gs(ODataPlugin.Event.TEIID17013, execution.getResponseCode(), error.getCode(), error.getMessage(), error.getInnerError())); } else { return new TranslatorException(ODataPlugin.Util.gs(ODataPlugin.Event.TEIID17031)); } } catch (Throwable t) { return new TranslatorException(t); } }
From source file:org.unitime.commons.hibernate.blob.XmlBlobType.java
public Object nullSafeGet(ResultSet rs, String[] names, SessionImplementor session, Object owner) throws SQLException { Blob blob = rs.getBlob(names[0]); if (blob == null) return null; try {//from ww w . ja v a2 s . c o m SAXReader reader = new SAXReader(); GZIPInputStream gzipInput = new GZIPInputStream(blob.getBinaryStream()); Document document = reader.read(gzipInput); gzipInput.close(); return document; } catch (IOException e) { throw new HibernateException(e.getMessage(), e); } catch (DocumentException e) { throw new HibernateException(e.getMessage(), e); } }
From source file:org.vulpe.commons.util.VulpeStringUtil.java
/** * Convert SQL Blob to String.//from w w w . j ava 2 s . c o m * * @param blob * @return */ public static String blobToString(final Blob blob) { String blobString = null; try { final ByteArrayOutputStream baos = new ByteArrayOutputStream(); final byte[] buffer = new byte[1024]; final InputStream inputStream = blob.getBinaryStream(); int count = 0; while ((count = inputStream.read(buffer)) >= 0) { baos.write(buffer, 0, count); } inputStream.close(); final byte[] bytes = baos.toByteArray(); blobString = new String(bytes); } catch (Exception e) { LOG.error(e.getMessage()); } return blobString; }