Java tutorial
/* * Copyrights 2002-2013 Webb Fontaine * Date: 03/06/13 * This software is the proprietary information of Webb Fontaine. * Its use is subject to License terms. */ package com.webbfontaine.valuewebb.irms.impl.data; import com.google.common.base.Throwables; import com.webbfontaine.valuewebb.model.util.Utils; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import javax.activation.DataSource; import javax.mail.EncodingAware; import javax.persistence.EntityManager; import java.io.IOException; import java.io.InputStream; import java.io.OutputStream; import java.sql.Blob; import java.sql.SQLException; import static org.apache.commons.lang3.StringUtils.defaultIfEmpty; public class AttachedDocDataSource implements DataSource, EncodingAware { private static final Logger LOGGER = LoggerFactory.getLogger(AttachedDocDataSource.class); private static final String SELECT_QUERY = "SELECT DOC_RES FROM TT_DOC WHERE DOC_ID=?"; private final String type; // = "application/octet-stream"; private final Long docId; private String name = ""; public AttachedDocDataSource(Long docId, String type) { this.type = type; this.docId = docId; } @Override public InputStream getInputStream() throws IOException { EntityManager entityManager = Utils.createEntityManager(); try { // We should always be able to find attached doc for already persisted TT Blob data = (Blob) entityManager.createNativeQuery(SELECT_QUERY).setParameter(1, docId) .getSingleResult(); return stream(data); } catch (Exception e) { throw Throwables.propagate(e); } finally { entityManager.close(); } } private static InputStream stream(Blob data) throws SQLException { if (data != null) { LOGGER.debug("Attached doc LOB data length: {}", data.length()); return data.getBinaryStream(); } return null; } @Override public String getEncoding() { return "base64"; } @Override public OutputStream getOutputStream() throws IOException { throw new UnsupportedOperationException("Only to read InputStream from DB"); } @Override public String getContentType() { return defaultIfEmpty(type, "application/octet-stream"); } @Override public String getName() { return name; } public void setName(String name) { this.name = name; } }