Example usage for java.sql Blob length

List of usage examples for java.sql Blob length

Introduction

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

Prototype

long length() throws SQLException;

Source Link

Document

Returns the number of bytes in the BLOB value designated by this Blob object.

Usage

From source file:org.zaproxy.zap.extension.websocket.db.TableWebSocket.java

/**
 * @param rs//from  w w w. j a  va 2s .co m
 * @param interpretLiteralBytes
 * @param payloadLength
 * @return
 * @throws HttpMalformedHeaderException
 * @throws SQLException
 * @throws DatabaseException
 */
private List<WebSocketMessageDTO> buildMessageDTOs(ResultSet rs, boolean interpretLiteralBytes,
        int payloadLength) throws SQLException, DatabaseException {
    ArrayList<WebSocketMessageDTO> messages = new ArrayList<>();
    try {
        while (rs.next()) {
            WebSocketMessageDTO message;

            int channelId = rs.getInt("channel_id");
            WebSocketChannelDTO channel = getChannel(channelId);

            if (rs.getInt("fuzz_id") != 0) {
                WebSocketFuzzMessageDTO fuzzMessage = new WebSocketFuzzMessageDTO(channel);
                fuzzMessage.fuzzId = rs.getInt("fuzz_id");
                fuzzMessage.state = WebSocketFuzzMessageDTO.State.valueOf(rs.getString("state"));
                fuzzMessage.fuzz = rs.getString("fuzz");

                message = fuzzMessage;
            } else {
                message = new WebSocketMessageDTO(channel);
            }

            message.id = rs.getInt("message_id");
            message.setTime(rs.getTimestamp("timestamp"));
            message.opcode = rs.getInt("opcode");
            message.readableOpcode = WebSocketMessage.opcode2string(message.opcode);

            // read payload
            if (message.opcode == WebSocketMessage.OPCODE_BINARY) {
                if (payloadLength == -1) {
                    // load all bytes
                    message.payload = rs.getBytes("payload_bytes");
                } else {
                    Blob blob = rs.getBlob("payload_bytes");
                    int length = Math.min(payloadLength, (int) blob.length());
                    message.payload = blob.getBytes(1, length);
                    blob.free();
                }

                if (message.payload == null) {
                    message.payload = new byte[0];
                }
            } else {
                if (payloadLength == -1) {
                    // load all characters
                    message.payload = rs.getString("payload_utf8");
                } else {
                    Clob clob = rs.getClob("payload_utf8");
                    int length = Math.min(payloadLength, (int) clob.length());
                    message.payload = clob.getSubString(1, length);
                    clob.free();
                }

                if (message.payload == null) {
                    message.payload = "";
                }
            }

            message.isOutgoing = rs.getBoolean("is_outgoing");
            message.payloadLength = rs.getInt("payload_length");

            messages.add(message);
        }
    } finally {
        rs.close();
    }

    messages.trimToSize();

    return messages;
}

From source file:org.ebayopensource.winder.quartz.QuartzSchedulerManager.java

private Object getObjectFromBlob(ResultSet rs, String colName)
        throws ClassNotFoundException, IOException, SQLException {
    Object obj = null;/*from  w  w  w  . j  a  v a  2  s  .c  om*/

    Blob blobLocator = rs.getBlob(colName);
    if (blobLocator != null && blobLocator.length() != 0) {
        InputStream binaryInput = blobLocator.getBinaryStream();

        if (null != binaryInput) {
            if (binaryInput instanceof ByteArrayInputStream
                    && ((ByteArrayInputStream) binaryInput).available() == 0) {
                //do nothing
            } else {
                ObjectInputStream in = new ObjectInputStream(binaryInput);
                try {
                    obj = in.readObject();
                } finally {
                    in.close();
                }
            }
        }

    }
    return obj;
}

From source file:com.eryansky.common.utils.SysUtils.java

/**
  * Blobbyte[]/*w  ww. ja  v a  2  s .com*/
  * 
  * @param blob
  * @return
  * @author &Eryan eryanwcp@gmail.com
  */
 public static byte[] blobToBytes(Blob blob) {
     BufferedInputStream is = null;
     try {
         is = new BufferedInputStream(blob.getBinaryStream());
         byte[] bytes = new byte[(int) blob.length()];
         int len = bytes.length;
         int offset = 0;
         int read = 0;

         while (offset < len && (read = is.read(bytes, offset, len - offset)) >= 0) {
             offset += read;
         }
         return bytes;
     } catch (Exception e) {
         return null;
     } finally {
         try {
             is.close();
             is = null;
         } catch (IOException e) {
             return null;
         }
     }
 }

From source file:org.apache.james.mailrepository.jdbc.JDBCMailRepository.java

/**
 * @see org.apache.james.mailrepository.api.MailRepository#retrieve(String)
 *//*from   ww w . java  2s  .c  o m*/
@SuppressWarnings("unchecked")
public Mail retrieve(String key) throws MessagingException {
    if (DEEP_DEBUG) {
        System.err.println("retrieving " + key);
    }
    Connection conn = null;
    PreparedStatement retrieveMessage = null;
    ResultSet rsMessage = null;
    try {
        conn = datasource.getConnection();
        if (DEEP_DEBUG) {
            System.err.println("got a conn " + key);
        }

        retrieveMessage = conn.prepareStatement(sqlQueries.getSqlString("retrieveMessageSQL", true));
        retrieveMessage.setString(1, key);
        retrieveMessage.setString(2, repositoryName);
        rsMessage = retrieveMessage.executeQuery();
        if (DEEP_DEBUG) {
            System.err.println("ran the query " + key);
        }
        if (!rsMessage.next()) {
            if (getLogger().isDebugEnabled()) {
                String debugBuffer = "Did not find a record " + key + " in " + repositoryName;
                getLogger().debug(debugBuffer);
            }
            return null;
        }
        // Determine whether attributes are used and retrieve them
        PreparedStatement retrieveMessageAttr = null;
        HashMap<String, Object> attributes = null;
        if (jdbcMailAttributesReady) {
            String retrieveMessageAttrSql = sqlQueries.getSqlString("retrieveMessageAttributesSQL", false);
            ResultSet rsMessageAttr = null;
            try {
                retrieveMessageAttr = conn.prepareStatement(retrieveMessageAttrSql);

                retrieveMessageAttr.setString(1, key);
                retrieveMessageAttr.setString(2, repositoryName);
                rsMessageAttr = retrieveMessageAttr.executeQuery();

                if (rsMessageAttr.next()) {
                    try {
                        byte[] serialized_attr;
                        String getAttributesOption = sqlQueries.getDbOption("getAttributes");
                        if (getAttributesOption != null && (getAttributesOption.equalsIgnoreCase("useBlob")
                                || getAttributesOption.equalsIgnoreCase("useBinaryStream"))) {
                            Blob b = rsMessageAttr.getBlob(1);
                            serialized_attr = b.getBytes(1, (int) b.length());
                        } else {
                            serialized_attr = rsMessageAttr.getBytes(1);
                        }
                        // this check is for better backwards compatibility
                        if (serialized_attr != null) {
                            ByteArrayInputStream bais = new ByteArrayInputStream(serialized_attr);
                            ObjectInputStream ois = new ObjectInputStream(bais);
                            attributes = (HashMap<String, Object>) ois.readObject();
                            ois.close();
                        }
                    } catch (IOException ioe) {
                        if (getLogger().isDebugEnabled()) {
                            String debugBuffer = "Exception reading attributes " + key + " in "
                                    + repositoryName;
                            getLogger().debug(debugBuffer, ioe);
                        }
                    }
                } else {
                    if (getLogger().isDebugEnabled()) {
                        String debugBuffer = "Did not find a record (attributes) " + key + " in "
                                + repositoryName;
                        getLogger().debug(debugBuffer);
                    }
                }
            } catch (SQLException sqle) {
                String errorBuffer = "Error retrieving message" + sqle.getMessage() + sqle.getErrorCode()
                        + sqle.getSQLState() + sqle.getNextException();
                getLogger().error(errorBuffer);
            } finally {
                theJDBCUtil.closeJDBCResultSet(rsMessageAttr);
                theJDBCUtil.closeJDBCStatement(retrieveMessageAttr);
            }
        }

        MailImpl mc = new MailImpl();
        mc.setAttributesRaw(attributes);
        mc.setName(key);
        mc.setState(rsMessage.getString(1));
        mc.setErrorMessage(rsMessage.getString(2));
        String sender = rsMessage.getString(3);
        if (sender == null) {
            mc.setSender(null);
        } else {
            mc.setSender(new MailAddress(sender));
        }
        StringTokenizer st = new StringTokenizer(rsMessage.getString(4), "\r\n", false);
        Set<MailAddress> recipients = new HashSet<MailAddress>();
        while (st.hasMoreTokens()) {
            recipients.add(new MailAddress(st.nextToken()));
        }
        mc.setRecipients(recipients);
        mc.setRemoteHost(rsMessage.getString(5));
        mc.setRemoteAddr(rsMessage.getString(6));
        mc.setLastUpdated(rsMessage.getTimestamp(7));

        MimeMessageJDBCSource source = new MimeMessageJDBCSource(this, key, sr);
        MimeMessageCopyOnWriteProxy message = new MimeMessageCopyOnWriteProxy(source);
        mc.setMessage(message);
        return mc;
    } catch (SQLException sqle) {
        String errorBuffer = "Error retrieving message" + sqle.getMessage() + sqle.getErrorCode()
                + sqle.getSQLState() + sqle.getNextException();
        getLogger().error(errorBuffer);
        getLogger().debug("Failed to retrieve mail", sqle);
        throw new MessagingException("Exception while retrieving mail: " + sqle.getMessage(), sqle);
    } catch (Exception me) {
        throw new MessagingException("Exception while retrieving mail: " + me.getMessage(), me);
    } finally {
        theJDBCUtil.closeJDBCResultSet(rsMessage);
        theJDBCUtil.closeJDBCStatement(retrieveMessage);
        theJDBCUtil.closeJDBCConnection(conn);
    }
}

From source file:com.cloudera.sqoop.testutil.ManagerCompatTestCase.java

protected void verifyBlob(String insertVal, byte[] returnVal, String seqFileVal) {
    String[] types = { "INTEGER NOT NULL", getBlobType() };
    String[] vals = { "1", insertVal };
    String[] checkCols = { "DATA_COL0", "DATA_COL1" };

    createTableWithColTypes(types, vals);

    // Verify readback of the data.
    ResultSet results = null;/*from w  w  w . ja v  a2s  .com*/
    try {
        results = getManager().readTable(getTableName(), getColNames());
        assertNotNull("Null results from readTable()!", results);
        assertTrue("Expected at least one row returned", results.next());
        Blob blob = results.getBlob(2);
        byte[] databaseBytes = blob.getBytes(1, (int) blob.length());
        log.info("Verifying readback of bytes from " + getTableName());

        assertEquals("byte arrays differ in size", returnVal.length, databaseBytes.length);
        for (int i = 0; i < returnVal.length; i++) {
            assertEquals("bytes differ at position " + i + ". Expected " + returnVal[i] + "; got "
                    + databaseBytes[i], returnVal[i], databaseBytes[i]);
        }

        assertFalse("Expected at most one row returned", results.next());
    } catch (SQLException sqlE) {
        fail("Got SQLException: " + sqlE.toString());
    } finally {
        if (null != results) {
            try {
                results.close();
            } catch (SQLException sqlE) {
                fail("Got SQLException in resultset.close(): " + sqlE.toString());
            }
        }

        // Free internal resources after the readTable.
        getManager().release();
    }

    // Now verify that we can use the Sqoop import mechanism on this data.
    verifyImport("1," + seqFileVal, checkCols);
}

From source file:org.wso2.carbon.identity.certificateauthority.dao.CsrDAO.java

/**
 * constructs and returns a Csr array from a resultSet
 *
 * @param resultSet result set/*from   w  w  w  . j  a v  a  2  s .co  m*/
 * @return array of CsrFiles
 */
private Csr[] getCsrArray(ResultSet resultSet) throws CaException, SQLException, IOException {
    ArrayList<Csr> csrList = new ArrayList<Csr>();
    int count = 0;
    while (resultSet.next()) {
        String serialNo = resultSet.getString(Constants.SERIAL_NO_LABEL);
        String status = resultSet.getString(Constants.CSR_STATUS_LABEL);
        String commonName = resultSet.getString(Constants.CSR_COMMON_NAME_LABEL);
        String organization = resultSet.getString(Constants.CSR_ORGANIZATION_LABEL);
        Csr csrFile;
        String country = null;
        String department = null;
        String city = null;
        String state = null;
        Blob csrBlob = resultSet.getBlob(Constants.CSR_CONTENT_LABEL);
        Date requestedDate = resultSet.getTimestamp(Constants.CSR_REQUESTED_DATE);
        String username = resultSet.getString(Constants.CSR_REQUESTER_USERNAME_LABEL);
        int tenantID = resultSet.getInt(Constants.TENANT_ID_LABEL);
        String userStoreDomain = resultSet.getString(Constants.USER_STORE_DOMAIN_LABEL);
        PKCS10CertificationRequest csr = new PKCS10CertificationRequest(
                csrBlob.getBytes(1, (int) csrBlob.length()));
        HashMap decodedContent = CsrUtils.getSubjectInfo(csr);
        if (decodedContent.containsKey("C")) {
            country = decodedContent.get("C").toString();
        }
        if (decodedContent.containsKey("L")) {
            city = decodedContent.get("L").toString();
        }
        if (decodedContent.containsKey("OU")) {
            department = decodedContent.get("OU").toString();
        }
        if (decodedContent.containsKey("ST")) {
            state = decodedContent.get("ST").toString();
        }
        csrFile = new Csr(commonName, department, organization, city, state, country, csr, serialNo, status,
                username, tenantID, userStoreDomain, requestedDate);
        csrList.add(csrFile);
    }
    Csr[] csrs = new Csr[csrList.size()];
    csrs = csrList.toArray(csrs);
    return csrs;
}

From source file:it.greenvulcano.gvesb.datahandling.dbo.utils.ExtendedRowSetBuilder.java

public int build(Document doc, String id, ResultSet rs, Set<Integer> keyField,
        Map<String, FieldFormatter> fieldNameToFormatter, Map<String, FieldFormatter> fieldIdToFormatter)
        throws Exception {
    if (rs == null) {
        return 0;
    }//from  w  ww .java 2s.co m
    int rowCounter = 0;
    Element docRoot = doc.getDocumentElement();
    ResultSetMetaData metadata = rs.getMetaData();
    buildFormatterAndNamesArray(metadata, fieldNameToFormatter, fieldIdToFormatter);

    boolean noKey = ((keyField == null) || keyField.isEmpty());
    boolean isKeyCol = false;

    boolean isNull = false;
    Element data = null;
    Element row = null;
    Element col = null;
    Text text = null;
    String textVal = null;
    String precKey = null;
    String colKey = null;
    Map<String, Element> keyCols = new TreeMap<String, Element>();
    while (rs.next()) {
        if (rowCounter % 10 == 0) {
            ThreadUtils.checkInterrupted(getClass().getSimpleName(), name, logger);
        }
        row = parser.createElementNS(doc, AbstractDBO.ROW_NAME, NS);

        parser.setAttribute(row, AbstractDBO.ID_NAME, id);
        for (int j = 1; j <= metadata.getColumnCount(); j++) {
            FieldFormatter fF = fFormatters[j];
            String colName = colNames[j];

            isKeyCol = (!noKey && keyField.contains(new Integer(j)));
            isNull = false;
            col = parser.createElementNS(doc, colName, NS);
            if (isKeyCol) {
                parser.setAttribute(col, AbstractDBO.ID_NAME, String.valueOf(j));
            }
            switch (metadata.getColumnType(j)) {
            case Types.DATE:
            case Types.TIME:
            case Types.TIMESTAMP: {
                parser.setAttribute(col, AbstractDBO.TYPE_NAME, AbstractDBO.TIMESTAMP_TYPE);
                Timestamp dateVal = rs.getTimestamp(j);
                isNull = dateVal == null;
                parser.setAttribute(col, AbstractDBO.NULL_NAME, String.valueOf(isNull));
                if (isNull) {
                    parser.setAttribute(col, AbstractDBO.FORMAT_NAME, AbstractDBO.DEFAULT_DATE_FORMAT);
                    textVal = "";
                } else {
                    if (fF != null) {
                        parser.setAttribute(col, AbstractDBO.FORMAT_NAME, fF.getDateFormat());
                        textVal = fF.formatDate(dateVal);
                    } else {
                        parser.setAttribute(col, AbstractDBO.FORMAT_NAME, AbstractDBO.DEFAULT_DATE_FORMAT);
                        textVal = dateFormatter.format(dateVal);
                    }
                }
            }
                break;
            case Types.DOUBLE:
            case Types.FLOAT:
            case Types.REAL: {
                parser.setAttribute(col, AbstractDBO.TYPE_NAME, AbstractDBO.FLOAT_TYPE);
                float numVal = rs.getFloat(j);
                parser.setAttribute(col, AbstractDBO.NULL_NAME, "false");
                if (fF != null) {
                    parser.setAttribute(col, AbstractDBO.FORMAT_NAME, fF.getNumberFormat());
                    parser.setAttribute(col, AbstractDBO.GRP_SEPARATOR_NAME, fF.getGroupSeparator());
                    parser.setAttribute(col, AbstractDBO.DEC_SEPARATOR_NAME, fF.getDecSeparator());
                    textVal = fF.formatNumber(numVal);
                } else {
                    parser.setAttribute(col, AbstractDBO.FORMAT_NAME, numberFormat);
                    parser.setAttribute(col, AbstractDBO.GRP_SEPARATOR_NAME, groupSeparator);
                    parser.setAttribute(col, AbstractDBO.DEC_SEPARATOR_NAME, decSeparator);
                    textVal = numberFormatter.format(numVal);
                }
            }
                break;
            case Types.BIGINT:
            case Types.INTEGER:
            case Types.NUMERIC:
            case Types.SMALLINT:
            case Types.TINYINT: {
                BigDecimal bigdecimal = rs.getBigDecimal(j);
                isNull = bigdecimal == null;
                parser.setAttribute(col, AbstractDBO.NULL_NAME, String.valueOf(isNull));
                if (isNull) {
                    if (metadata.getScale(j) > 0) {
                        parser.setAttribute(col, AbstractDBO.TYPE_NAME, AbstractDBO.FLOAT_TYPE);
                    } else {
                        parser.setAttribute(col, AbstractDBO.TYPE_NAME, AbstractDBO.NUMERIC_TYPE);
                    }
                    textVal = "";
                } else {
                    if (fF != null) {
                        parser.setAttribute(col, AbstractDBO.TYPE_NAME, AbstractDBO.FLOAT_TYPE);
                        parser.setAttribute(col, AbstractDBO.FORMAT_NAME, fF.getNumberFormat());
                        parser.setAttribute(col, AbstractDBO.GRP_SEPARATOR_NAME, fF.getGroupSeparator());
                        parser.setAttribute(col, AbstractDBO.DEC_SEPARATOR_NAME, fF.getDecSeparator());
                        textVal = fF.formatNumber(bigdecimal);
                    } else if (metadata.getScale(j) > 0) {
                        parser.setAttribute(col, AbstractDBO.TYPE_NAME, AbstractDBO.FLOAT_TYPE);
                        parser.setAttribute(col, AbstractDBO.FORMAT_NAME, numberFormat);
                        parser.setAttribute(col, AbstractDBO.GRP_SEPARATOR_NAME, groupSeparator);
                        parser.setAttribute(col, AbstractDBO.DEC_SEPARATOR_NAME, decSeparator);
                        textVal = numberFormatter.format(bigdecimal);
                    } else {
                        parser.setAttribute(col, AbstractDBO.TYPE_NAME, AbstractDBO.NUMERIC_TYPE);
                        textVal = bigdecimal.toString();
                    }
                }
            }
                break;
            case Types.NCHAR:
            case Types.NVARCHAR: {
                parser.setAttribute(col, AbstractDBO.TYPE_NAME, AbstractDBO.NSTRING_TYPE);
                textVal = rs.getNString(j);
                isNull = textVal == null;
                parser.setAttribute(col, AbstractDBO.NULL_NAME, String.valueOf(isNull));
                if (isNull) {
                    textVal = "";
                }
            }
                break;
            case Types.CHAR:
            case Types.VARCHAR: {
                parser.setAttribute(col, AbstractDBO.TYPE_NAME, AbstractDBO.STRING_TYPE);
                textVal = rs.getString(j);
                isNull = textVal == null;
                parser.setAttribute(col, AbstractDBO.NULL_NAME, String.valueOf(isNull));
                if (isNull) {
                    textVal = "";
                }
            }
                break;
            case Types.NCLOB: {
                parser.setAttribute(col, AbstractDBO.TYPE_NAME, AbstractDBO.LONG_NSTRING_TYPE);
                NClob clob = rs.getNClob(j);
                isNull = clob == null;
                parser.setAttribute(col, AbstractDBO.NULL_NAME, String.valueOf(isNull));
                if (isNull) {
                    textVal = "";
                } else {
                    Reader is = clob.getCharacterStream();
                    StringWriter str = new StringWriter();

                    IOUtils.copy(is, str);
                    is.close();
                    textVal = str.toString();
                }
            }
                break;
            case Types.CLOB: {
                parser.setAttribute(col, AbstractDBO.TYPE_NAME, AbstractDBO.LONG_STRING_TYPE);
                Clob clob = rs.getClob(j);
                isNull = clob == null;
                parser.setAttribute(col, AbstractDBO.NULL_NAME, String.valueOf(isNull));
                if (isNull) {
                    textVal = "";
                } else {
                    Reader is = clob.getCharacterStream();
                    StringWriter str = new StringWriter();

                    IOUtils.copy(is, str);
                    is.close();
                    textVal = str.toString();
                }
            }
                break;
            case Types.BLOB: {
                parser.setAttribute(col, AbstractDBO.TYPE_NAME, AbstractDBO.BASE64_TYPE);
                Blob blob = rs.getBlob(j);
                isNull = blob == null;
                parser.setAttribute(col, AbstractDBO.NULL_NAME, String.valueOf(isNull));
                if (isNull) {
                    textVal = "";
                } else {
                    InputStream is = blob.getBinaryStream();
                    ByteArrayOutputStream baos = new ByteArrayOutputStream();
                    IOUtils.copy(is, baos);
                    is.close();
                    try {
                        byte[] buffer = Arrays.copyOf(baos.toByteArray(), (int) blob.length());
                        textVal = Base64.getEncoder().encodeToString(buffer);
                    } catch (SQLFeatureNotSupportedException exc) {
                        textVal = Base64.getEncoder().encodeToString(baos.toByteArray());
                    }
                }
            }
                break;
            default: {
                parser.setAttribute(col, AbstractDBO.TYPE_NAME, AbstractDBO.DEFAULT_TYPE);
                textVal = rs.getString(j);
                isNull = textVal == null;
                parser.setAttribute(col, AbstractDBO.NULL_NAME, String.valueOf(isNull));
                if (isNull) {
                    textVal = "";
                }
            }
            }
            if (textVal != null) {
                text = doc.createTextNode(textVal);
                col.appendChild(text);
            }
            if (isKeyCol) {
                if (textVal != null) {
                    if (colKey == null) {
                        colKey = textVal;
                    } else {
                        colKey += "##" + textVal;
                    }
                    keyCols.put(String.valueOf(j), col);
                }
            } else {
                row.appendChild(col);
            }
        }
        if (noKey) {
            if (data == null) {
                data = parser.createElementNS(doc, AbstractDBO.DATA_NAME, NS);
                parser.setAttribute(data, AbstractDBO.ID_NAME, id);
            }
        } else if ((colKey != null) && !colKey.equals(precKey)) {
            if (data != null) {
                docRoot.appendChild(data);
            }
            data = parser.createElementNS(doc, AbstractDBO.DATA_NAME, NS);
            parser.setAttribute(data, AbstractDBO.ID_NAME, id);
            Element key = parser.createElementNS(doc, AbstractDBO.KEY_NAME, NS);
            data.appendChild(key);
            for (Entry<String, Element> keyColsEntry : keyCols.entrySet()) {
                key.appendChild(keyColsEntry.getValue());
            }
            keyCols.clear();
            precKey = colKey;
        }
        colKey = null;
        data.appendChild(row);
        rowCounter++;
    }
    if (data != null) {
        docRoot.appendChild(data);
    }

    return rowCounter;
}

From source file:de.hska.ld.content.controller.DocumentController.java

/**
 * This resource allows downloading a file attachment.
 * <p>/*w  w  w  .j ava 2s  .c  o  m*/
 * <pre>
 *     <b>Required roles:</b> ROLE_USER
 *     <b>Path</b> GET /api/documents/{documentId}/download/{attachmentId}
 * </pre>
 *
 * @param documentId   the ID of the document that contains the needed attachment
 * @param attachmentId the attachment id of the attachment that shall be retrieved
 * @param response     <b>FILE DOWNLOAD INITIATED</b> if the attachment could be found, and the download is starting<br>
 *                     <b>400 BAD REQUEST</b><br>
 *                     <b>403 FORBIDDEN</b> if the access to this attachment has been denied<br>
 *                     <b>404 NOT FOUND</b> if no attachment has been found for the given document ID or attachment position<br>
 *                     <b>500 Internal Server Error</b> if there occurred any other server side issue
 */
@Secured(Core.ROLE_USER)
@RequestMapping(method = RequestMethod.GET, value = "/{documentId}/download/{attachmentId}")
@Transactional(readOnly = true)
public Callable downloadFile(@PathVariable Long documentId, @PathVariable Long attachmentId,
        HttpServletResponse response) {
    return () -> {
        try {
            Attachment attachment = documentService.getAttachmentByAttachmentId(documentId, attachmentId);
            try {
                LoggingContext.put("user_email",
                        EscapeUtil.escapeJsonForLogging(Core.currentUser().getEmail()));
                LoggingContext.put("attachmentId",
                        EscapeUtil.escapeJsonForLogging(attachment.getId().toString()));
                Logger.trace("User downloads file (2).");
            } catch (Exception e) {
                Logger.error(e);
            } finally {
                LoggingContext.clear();
            }
            InputStream is = null;
            if (attachment.getFileBlobBean() != null && attachment.getFileBlobBean().getSourceBlob() != null) {
                Blob blob = attachment.getFileBlobBean().getSourceBlob();
                is = blob.getBinaryStream();
                response.setContentLength((int) blob.length());
            } else {
                byte[] source = attachment.getSource();
                if (source != null) {
                    is = new ByteArrayInputStream(source);
                } else {
                    throw new NotFoundException("source");
                }
            }
            response.setContentType(attachment.getMimeType());
            String fileName = URLEncoder.encode(attachment.getName(), "UTF-8");
            fileName = URLDecoder.decode(fileName, "ISO8859_1");
            //response.setContentType("application/x-msdownload");
            response.setHeader("Content-disposition", "attachment; filename=" + fileName);
            OutputStream outputStream = response.getOutputStream();
            IOUtils.copy(is, outputStream);
        } catch (IOException e) {
            response.setStatus(HttpServletResponse.SC_INTERNAL_SERVER_ERROR);
        }
        return null;
    };
}

From source file:DisplayBlobServlet.java

public void doGet(HttpServletRequest request, HttpServletResponse response)
        throws IOException, ServletException {
    Blob photo = null;
    Connection conn = null;//from  ww w  .  ja  v a  2s.  c  o m
    Statement stmt = null;
    ResultSet rs = null;

    String query = "select photo from MyPictures where  id = '001'";
    ServletOutputStream out = response.getOutputStream();

    try {
        conn = getHSQLConnection();
    } catch (Exception e) {
        response.setContentType("text/html");
        out.println("<html><head><title>Person Photo</title></head>");
        out.println("<body><h1>Database Connection Problem.</h1></body></html>");
        return;
    }

    try {
        stmt = conn.createStatement();
        rs = stmt.executeQuery(query);
        if (rs.next()) {
            photo = rs.getBlob(1);
        } else {
            response.setContentType("text/html");
            out.println("<html><head><title>Person Photo</title></head>");
            out.println("<body><h1>No photo found for id= 001 </h1></body></html>");
            return;
        }

        response.setContentType("image/gif");
        InputStream in = photo.getBinaryStream();
        int length = (int) photo.length();

        int bufferSize = 1024;
        byte[] buffer = new byte[bufferSize];

        while ((length = in.read(buffer)) != -1) {
            System.out.println("writing " + length + " bytes");
            out.write(buffer, 0, length);
        }

        in.close();
        out.flush();
    } catch (SQLException e) {
        response.setContentType("text/html");
        out.println("<html><head><title>Error: Person Photo</title></head>");
        out.println("<body><h1>Error=" + e.getMessage() + "</h1></body></html>");
        return;
    } finally {
        try {
            rs.close();
            stmt.close();
            conn.close();
        } catch (SQLException e) {
            e.printStackTrace();
        }
    }
}

From source file:gobblin.source.extractor.extract.jdbc.JdbcExtractor.java

private String readBlobAsString(Blob logBlob) throws SQLException {
    if (logBlob == null) {
        return StringUtils.EMPTY;
    }//from w  w  w.ja  v  a  2  s  .c  o  m

    byte[] ba = logBlob.getBytes(1L, (int) (logBlob.length()));

    if (ba == null) {
        return StringUtils.EMPTY;
    }
    String baString = Base64.encodeBase64String(ba);
    return baString;
}