List of usage examples for java.sql Blob length
long length() throws SQLException;
From source file:com.algomedica.service.LicenseManagerServiceImpl.java
@Override public Map<String, Object> getLicenseDetail(String id) { Map<String, Object> map; if (StringUtils.isEmpty(id)) { throw new ApplicationException(ErrorCodesConstants.INVALID_LICENSE_ID_CODE, ErrorCodesConstants.INVALID_LICENSE_ID); }//from w w w . j a v a 2 s .c o m LicenseDetail licenseDetail = licenseDao.getLicenseById(Long.parseLong(id)); if (licenseDetail == null || licenseDetail.getBlobkey() == null) { throw new ApplicationException(ErrorCodesConstants.INVALID_LICENSE_ID_CODE, ErrorCodesConstants.INVALID_LICENSE_ID); } // release the blob and free up memory. (since JDBC 4.0) try { java.sql.Blob blob = licenseDetail.getBlobkey(); int blobLength = (int) blob.length(); byte[] blobAsBytes = blob.getBytes(1, blobLength); blobAsBytes = zipBytes(licenseDetail.getLsMacAddress() + ".key", blobAsBytes); map = new HashMap<>(); map.put("data", blobAsBytes); map.put("filename", licenseDetail.getLsMacAddress()); blob.free(); } catch (SQLException | IOException e) { LOGGER.error("During getting License detail exception occured "); throw new ApplicationException(ErrorCodesConstants.INTERNAL_SYSTEM_ERROR_CODE, ErrorCodesConstants.INTERNAL_SYSTEM_ERROR, e); } return map; }
From source file:com.cosmosource.common.action.CALicenseAction.java
public String getImg() throws Exception { String caid = getParameter("caid"); TAcCaapply entitys = camgrManager.findById(Long.parseLong(caid)); Blob blob = entitys.getHandlerstamp(); if (blob != null) { getResponse().setContentType("image/jpg"); OutputStream outs = getResponse().getOutputStream(); InputStream pi = blob.getBinaryStream(); int blobsize = (int) blob.length(); byte[] blobbytes = new byte[blobsize]; int bytesRead = 0; while ((bytesRead = pi.read(blobbytes)) != -1) { outs.write(blobbytes, 0, bytesRead); }/*from w w w . j a va 2 s .c om*/ pi.close(); outs.flush(); } return null; }
From source file:org.mifos.framework.image.service.ClientPhotoServiceDatabase.java
@Override public boolean create(Long clientId, InputStream in) { boolean transactionStarted = false; if (in == null) { return false; }/*from w w w .jav a 2 s.co m*/ try { //create blob final Blob blob = this.createBlob(in); //create picture final ImageInfo imageInfo = new ImageInfo(); imageInfo.setContentType(this.determineContentType(in)); imageInfo.setLength(blob.length()); CustomerPictureEntity picture = new CustomerPictureEntity(blob); imageInfo.setPicture(picture); final ClientPhoto clientPhoto = new ClientPhoto(); clientPhoto.setClientId(clientId); clientPhoto.setImageInfo(imageInfo); //save hibernateTransactionHelper.startTransaction(); transactionStarted = true; this.genericDao.createOrUpdate(clientPhoto); hibernateTransactionHelper.commitTransaction(); } catch (Exception ex) { if (transactionStarted) { hibernateTransactionHelper.rollbackTransaction(); } LOG.error("Unable to create picture", ex); return false; } return true; }
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 w w . j a v a 2 s . c om*/ * @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:edu.wustl.bulkoperator.action.BulkHandler.java
/** * This method call to write Job message. * @param jobMessage jobMessage/*from ww w .j a v a2 s.c o m*/ * @param response HttpServletResponse * @throws IOException IOException * @throws SQLException SQLException */ private void writeJobMessage(JobMessage jobMessage, HttpServletResponse response) throws IOException, SQLException { OutputStream ost = response.getOutputStream(); ObjectOutputStream objOutputStream = new ObjectOutputStream(ost); JobDetails jobDetails = jobMessage.getJobData(); if (jobDetails != null && jobDetails.getLogFile() != null) { Blob blob = jobDetails.getLogFile(); InputStream inputStream = blob.getBinaryStream(); int count = 0; final byte[] buf = new byte[Long.valueOf(blob.length()).intValue()]; while (count > -1) { count = inputStream.read(buf); } (jobMessage.getJobData()).setLogFilesBytes(buf); } objOutputStream.writeObject(jobMessage); }
From source file:org.broad.igv.dev.db.SQLCodecSource.java
/** * Convert a the current line to an array of strings * * @param rs/* w w w . j av a2s . c om*/ * @return * @throws SQLException */ protected String[] lineToArray(ResultSet rs) throws SQLException { int colCount = Math.min(rs.getMetaData().getColumnCount(), endColIndex) - startColIndex + 1; String[] tokens = new String[colCount]; String s; int sqlCol; for (int cc = 0; cc < colCount; cc++) { //SQL indexes from 1 //Have to parse blobs specially, otherwise we get the pointer as a string sqlCol = cc + startColIndex; String clazz = rs.getMetaData().getColumnClassName(sqlCol).toLowerCase(); if (clazz.contains("blob") || clazz.equalsIgnoreCase("[b")) { Blob b = rs.getBlob(sqlCol); s = new String(b.getBytes(1l, (int) b.length())); } else { s = rs.getString(sqlCol); } tokens[cc] = s; } return tokens; }
From source file:org.mifos.framework.image.service.ClientPhotoServiceDatabase.java
@Override public byte[] getData(ClientPhoto clientPhoto) { byte[] output; if (clientPhoto == null || clientPhoto.getImageInfo() == null) { output = getStaticImage(NO_PHOTO_PNG); } else {//from ww w. j a va 2 s. co m final Blob picture = clientPhoto.getImageInfo().getCustomerPictureEntity().getPicture(); if (picture == null) { output = getStaticImage(NO_PHOTO_PNG); } else { try { output = picture.getBytes((long) 1, (int) picture.length()); } catch (SQLException ex) { output = getStaticImage(SYSERROR_PNG); } } } return output; }
From source file:org.mifos.framework.image.service.ClientPhotoServiceDatabase.java
@Override public boolean update(Long clientId, InputStream in) { boolean transactionStarted = false; if (in == null) { return false; }/*from w w w .ja v a 2 s . c om*/ try { final ClientPhoto clientPhoto = this.read(clientId); if (clientPhoto == null) { return this.create(clientId, in); //create new picture } else { //get picture final Blob blob = this.createBlob(in); final String contentType = this.determineContentType(in); //update data final ImageInfo imageInfo = clientPhoto.getImageInfo(); imageInfo.setContentType(contentType); imageInfo.setLength(blob.length()); imageInfo.getCustomerPictureEntity().setPicture(blob); this.hibernateTransactionHelper.startTransaction(); transactionStarted = true; this.genericDao.createOrUpdate(clientPhoto); this.hibernateTransactionHelper.commitTransaction(); } } catch (Exception ex) { if (transactionStarted) { hibernateTransactionHelper.rollbackTransaction(); } LOG.error("Unable to update picture", ex); return false; } return true; }
From source file:com.playright.servlet.DataController.java
/** * Handles the HTTP <code>POST</code> method. * * @param request servlet request//from w w w. jav a2 s .co 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:org.wso2.carbon.identity.sts.store.dao.DBStsDAO.java
/** * This is to get Token from token id/* www . j av a 2 s. c o m*/ * * @param tokenId tokenId * @return Token */ public Token getToken(String tokenId) throws TrustException { Connection connection = IdentityDatabaseUtil.getDBConnection(); PreparedStatement prepStmt = null; ResultSet rs = null; Token token = null; String query = DBQueries.GET_TOKEN; try { prepStmt = connection.prepareStatement(query); prepStmt.setString(1, tokenId); rs = prepStmt.executeQuery(); if (rs != null) { while (rs.next()) { Blob tokenContent = rs.getBlob(STSMgtConstants.TOKEN_CONTENT); byte[] tokenContentBytes = tokenContent.getBytes(1, (int) tokenContent.length()); token = getToken(tokenContentBytes); } } } catch (Exception e) { String msg = "Failed to get token"; throw new TrustException(msg, e); } finally { IdentityDatabaseUtil.closeAllConnections(connection, rs, prepStmt); } return token; }