List of usage examples for java.sql Types BOOLEAN
int BOOLEAN
To view the source code for java.sql Types BOOLEAN.
Click Source Link
BOOLEAN
. From source file:org.apache.syncope.core.util.ImportExport.java
private String getValues(final ResultSet rs, final String columnName, final Integer columnType) throws SQLException { String res = null;//w ww . ja v a 2s. c o m try { switch (columnType) { case Types.BINARY: case Types.VARBINARY: case Types.LONGVARBINARY: final InputStream is = rs.getBinaryStream(columnName); if (is != null) { res = new String(Hex.encode(IOUtils.toByteArray(is))); } break; case Types.BLOB: final Blob blob = rs.getBlob(columnName); if (blob != null) { res = new String(Hex.encode(IOUtils.toByteArray(blob.getBinaryStream()))); } break; case Types.BIT: case Types.BOOLEAN: if (rs.getBoolean(columnName)) { res = "1"; } else { res = "0"; } break; case Types.DATE: case Types.TIME: case Types.TIMESTAMP: final Timestamp timestamp = rs.getTimestamp(columnName); if (timestamp != null) { res = DATE_FORMAT.get().format(new Date(timestamp.getTime())); } break; default: res = rs.getString(columnName); } } catch (IOException e) { LOG.error("Error retrieving hexadecimal string", e); } return res; }
From source file:ch.rgw.tools.JdbcLink.java
public static int generalType(int t) { switch (t) {/*w w w. j ava 2 s . c om*/ case Types.BIGINT: case Types.BIT: case Types.BOOLEAN: case Types.INTEGER: case Types.SMALLINT: case Types.TINYINT: return INTEGRAL; case Types.VARCHAR: case Types.CHAR: case Types.LONGVARCHAR: return TEXT; case Types.BINARY: case Types.BLOB: case Types.CLOB: case Types.LONGVARBINARY: case Types.VARBINARY: return BINARY; default: return OTHER; } }
From source file:org.easyrec.store.dao.core.impl.ItemAssocDAOMysqlImpl.java
/** * updates an item association entry in the database, uses the unique key to retrieve the entry * only changes columns:<br/>/* ww w .ja v a 2s . co m*/ * - assocValue<br/> * - viewType<br/> * - changeDate<br/> * <br/> * unique key: (tenantId, itemFromId, itemToId, itemFromTypeId, itemToTypeId, assocTypeId, sourceTypeId, sourceInfo) */ @Override public int updateItemAssocUsingUniqueKey(ItemAssocVO<Integer, Integer> itemAssoc) { // validate input parameters if (itemAssoc == null) { throw new IllegalArgumentException("missing 'itemAssoc'"); } validateUniqueKey(itemAssoc); validateAssocValue(itemAssoc); validateViewType(itemAssoc); if (logger.isDebugEnabled()) { logger.debug("updating 'itemAssoc' by unique key: " + itemAssoc); } StringBuilder sqlString; sqlString = new StringBuilder("UPDATE "); sqlString.append(DEFAULT_TABLE_NAME); sqlString.append(" SET "); sqlString.append(DEFAULT_ASSOC_VALUE_COLUMN_NAME); sqlString.append("=?, "); sqlString.append(DEFAULT_VIEW_TYPE_COLUMN_NAME); sqlString.append("=?, "); if (itemAssoc.isActive() != null) { sqlString.append(DEFAULT_ACTIVE_COLUMN_NAME); sqlString.append("=?, "); } sqlString.append(DEFAULT_CHANGE_DATE_COLUMN_NAME); if (itemAssoc.getChangeDate() == null) { itemAssoc.setChangeDate(new Date(System.currentTimeMillis())); } sqlString.append("=? WHERE "); sqlString.append(DEFAULT_ITEM_FROM_COLUMN_NAME); sqlString.append("=? AND "); sqlString.append(DEFAULT_ITEM_TO_COLUMN_NAME); sqlString.append("=? AND "); sqlString.append(DEFAULT_ITEM_FROM_TYPE_COLUMN_NAME); sqlString.append("=? AND "); sqlString.append(DEFAULT_ITEM_TO_TYPE_COLUMN_NAME); sqlString.append("=? AND "); sqlString.append(DEFAULT_ASSOC_TYPE_COLUMN_NAME); sqlString.append("=? AND "); sqlString.append(DEFAULT_SOURCE_TYPE_COLUMN_NAME); sqlString.append("=? AND "); sqlString.append(DEFAULT_TENANT_COLUMN_NAME); sqlString.append("=?"); Object[] args; int[] argTypes; if (itemAssoc.isActive() != null) { args = new Object[] { itemAssoc.getAssocValue(), itemAssoc.getViewType(), itemAssoc.isActive(), itemAssoc.getChangeDate(), itemAssoc.getItemFrom().getItem(), itemAssoc.getItemTo().getItem(), itemAssoc.getItemFrom().getType(), itemAssoc.getItemTo().getType(), itemAssoc.getAssocType(), itemAssoc.getSourceType(), itemAssoc.getTenant() }; argTypes = new int[] { Types.DOUBLE, Types.INTEGER, Types.BOOLEAN, Types.TIMESTAMP, Types.INTEGER, Types.INTEGER, Types.INTEGER, Types.INTEGER, Types.INTEGER, Types.INTEGER, Types.INTEGER }; } else { args = new Object[] { itemAssoc.getAssocValue(), itemAssoc.getViewType(), itemAssoc.getChangeDate(), itemAssoc.getItemFrom().getItem(), itemAssoc.getItemTo().getItem(), itemAssoc.getItemFrom().getType(), itemAssoc.getItemTo().getType(), itemAssoc.getAssocType(), itemAssoc.getSourceType(), itemAssoc.getTenant() }; argTypes = new int[] { Types.DOUBLE, Types.INTEGER, Types.TIMESTAMP, Types.INTEGER, Types.INTEGER, Types.INTEGER, Types.INTEGER, Types.INTEGER, Types.INTEGER, Types.INTEGER }; } return getJdbcTemplate().update(sqlString.toString(), args, argTypes); }
From source file:gemlite.core.internal.db.AsyncEventHelper.java
/** * Set column value at given index in a prepared statement. The implementation * tries using the matching underlying type to minimize any data type * conversions, and avoid creating wrapper Java objects (e.g. {@link Integer} * for primitive int).//from w w w.j a v a2 s . c o m * * @param type * the SQL type of the column as specified by JDBC {@link Types} * class * @param ps * the prepared statement where the column value has to be set * @param row * the source row as a {@link ResultSet} from where the value has to * be extracted * @param rowPosition * the 1-based position of the column in the provided * <code>row</code> * @param paramIndex * the 1-based position of the column in the target prepared * statement (provided <code>ps</code> argument) * @param sync * the {@link DBSynchronizer} object, if any; it is used to store * whether the current driver is JDBC4 compliant to enable performing * BLOB/CLOB operations {@link PreparedStatement#setBinaryStream}, * {@link PreparedStatement#setCharacterStream} * * @throws SQLException * in case of an exception in setting parameters */ public final void setColumnInPrepStatement(String type, Object val, PreparedStatement ps, final DBSynchronizer sync, int paramIndex) throws SQLException { switch (type) { case JavaTypes.STRING: if (val == null || StringUtils.isEmpty(val.toString())) ps.setNull(paramIndex, Types.VARCHAR); else { final String realVal = (String) val; ps.setString(paramIndex, realVal); } break; case JavaTypes.INT1: case JavaTypes.INT2: case JavaTypes.INT3: if (val == null || StringUtils.isEmpty(val.toString())) ps.setNull(paramIndex, Types.INTEGER); else { final int realVal = (int) val; ps.setInt(paramIndex, realVal); } break; case JavaTypes.DOUBLE1: case JavaTypes.DOUBLE2: if (val == null || StringUtils.isEmpty(val.toString())) ps.setNull(paramIndex, Types.DOUBLE); else { final double realVal = (double) val; ps.setDouble(paramIndex, realVal); } break; case JavaTypes.FLOAT1: case JavaTypes.FLOAT2: if (val == null || StringUtils.isEmpty(val.toString())) ps.setNull(paramIndex, Types.FLOAT); else { final float realVal = (float) val; ps.setDouble(paramIndex, realVal); } break; case JavaTypes.BOOLEAN1: case JavaTypes.BOOLEAN2: if (val == null || StringUtils.isEmpty(val.toString())) ps.setNull(paramIndex, Types.BOOLEAN); else { final boolean realVal = (boolean) val; ps.setBoolean(paramIndex, realVal); } break; case JavaTypes.DATE_SQL: if (val == null || StringUtils.isEmpty(val.toString())) ps.setNull(paramIndex, Types.DATE); else { final Date realVal = (Date) val; ps.setDate(paramIndex, realVal); } break; case JavaTypes.DATE_UTIL: if (val == null || StringUtils.isEmpty(val.toString())) ps.setNull(paramIndex, Types.DATE); else { final java.util.Date realVal = (java.util.Date) val; ps.setDate(paramIndex, new Date(realVal.getTime())); } break; case JavaTypes.BIGDECIMAL: if (val == null || StringUtils.isEmpty(val.toString())) ps.setNull(paramIndex, Types.DECIMAL); else { final BigDecimal realVal = (BigDecimal) val; ps.setBigDecimal(paramIndex, realVal); } break; case JavaTypes.TIME: if (val == null || StringUtils.isEmpty(val.toString())) ps.setNull(paramIndex, Types.TIME); else { final Time realVal = (Time) val; ps.setTime(paramIndex, realVal); } break; case JavaTypes.TIMESTAMP: if (val == null || StringUtils.isEmpty(val.toString())) ps.setNull(paramIndex, Types.TIMESTAMP); else { final Timestamp realVal = (Timestamp) val; ps.setTimestamp(paramIndex, realVal); } break; case JavaTypes.OBJECT: if (val == null || StringUtils.isEmpty(val.toString())) ps.setNull(paramIndex, Types.JAVA_OBJECT); else { final Object realVal = (Object) val; ps.setObject(paramIndex, realVal); } break; default: throw new UnsupportedOperationException("java.sql.Type = " + type + " not supported"); } }
From source file:at.alladin.rmbt.controlServer.RegistrationResource.java
@Post("json") public String request(final String entity) { long startTime = System.currentTimeMillis(); final String secret = getContext().getParameters().getFirstValue("RMBT_SECRETKEY"); addAllowOrigin();/* w ww . ja v a2 s. c o m*/ JSONObject request = null; final ErrorList errorList = new ErrorList(); final JSONObject answer = new JSONObject(); String answerString; final String clientIpRaw = getIP(); final InetAddress clientAddress = InetAddresses.forString(clientIpRaw); final String clientIpString = InetAddresses.toAddrString(clientAddress); System.out.println(MessageFormat.format(labels.getString("NEW_REQUEST"), clientIpRaw)); final String geoIpCountry = GeoIPHelper.lookupCountry(clientAddress); // public_ip_asn final Long asn = Helperfunctions.getASN(clientAddress); // public_ip_as_name // country_asn (2 digit country code of AS, eg. AT or EU) final String asName; final String asCountry; if (asn == null) { asName = null; asCountry = null; } else { asName = Helperfunctions.getASName(asn); asCountry = Helperfunctions.getAScountry(asn); } if (entity != null && !entity.isEmpty()) // try parse the string to a JSON object try { request = new JSONObject(entity); int typeId = 0; final String lang = request.optString("language"); // Load Language Files for Client final List<String> langs = Arrays .asList(settings.getString("RMBT_SUPPORTED_LANGUAGES").split(",\\s*")); if (langs.contains(lang)) { errorList.setLanguage(lang); labels = ResourceManager.getSysMsgBundle(new Locale(lang)); } // System.out.println(request.toString(4)); if (conn != null) { final Client clientDb = new Client(conn); if (!request.optString("type").isEmpty()) { typeId = clientDb.getTypeId(request.getString("type")); if (clientDb.hasError()) errorList.addError(clientDb.getError()); } final List<String> clientNames = Arrays .asList(settings.getString("RMBT_CLIENT_NAME").split(",\\s*")); final List<String> clientVersions = Arrays .asList(settings.getString("RMBT_VERSION_NUMBER").split(",\\s*")); if (clientNames.contains(request.optString("client")) && clientVersions.contains(request.optString("version")) && typeId > 0) { UUID uuid = null; final String uuidString = request.optString("uuid", ""); if (uuidString.length() != 0) uuid = UUID.fromString(uuidString); final String clientName = request.getString("client"); final String clientVersion = request.getString("version"); String timeZoneId = request.getString("timezone"); // String tmpTimeZoneId = timeZoneId; final long clientTime = request.getLong("time"); final Timestamp clientTstamp = java.sql.Timestamp .valueOf(new Timestamp(clientTime).toString()); final JSONObject location = request.optJSONObject("location"); long geotime = 0; double geolat = 0; double geolong = 0; float geoaccuracy = 0; double geoaltitude = 0; float geobearing = 0; float geospeed = 0; String geoprovider = ""; if (!request.isNull("location")) { geotime = location.optLong("time", 0); geolat = location.optDouble("lat", 0); geolong = location.optDouble("long", 0); geoaccuracy = (float) location.optDouble("accuracy", 0); geoaltitude = location.optDouble("altitude", 0); geobearing = (float) location.optDouble("bearing", 0); geospeed = (float) location.optDouble("speed", 0); geoprovider = location.optString("provider", ""); } Calendar timeWithZone = null; if (timeZoneId.isEmpty()) { timeZoneId = Helperfunctions.getTimezoneId(); timeWithZone = Helperfunctions.getTimeWithTimeZone(timeZoneId); } else timeWithZone = Helperfunctions.getTimeWithTimeZone(timeZoneId); long clientUid = 0; /* * if (uuid == null) { * clientDb.setTimeZone(timeWithZone); * clientDb.setTime(tstamp); * clientDb.setClient_type_id(typeId); uuid = * clientDb.storeClient(); if (clientDb.hasError()) { * errorList.addError(clientDb.getError()); } else { * answer.put("uuid", uuid.toString()); } } */ if (errorList.getLength() == 0 && uuid != null) { clientUid = clientDb.getClientByUuid(uuid); if (clientDb.hasError()) errorList.addError(clientDb.getError()); } if (clientUid > 0) { final String testUuid = UUID.randomUUID().toString(); final String testOpenUuid = UUID.randomUUID().toString(); boolean testServerEncryption = true; // default is // true // hack for android api <= 10 (2.3.x) // using encryption with test doesn't work if (request.has("plattform") && request.optString("plattform").equals("Android")) if (request.has("api_level")) { final String apiLevelString = request.optString("api_level"); try { final int apiLevel = Integer.parseInt(apiLevelString); if (apiLevel <= 10) testServerEncryption = false; } catch (final NumberFormatException e) { } } final String serverType; if (request.optString("client").equals("RMBTws")) serverType = "RMBTws"; else serverType = "RMBT"; final Boolean ipv6; if (clientAddress instanceof Inet6Address) ipv6 = true; else if (clientAddress instanceof Inet4Address) ipv6 = false; else // should never happen, unless ipv > 6 is available ipv6 = null; final TestServer server = getNearestServer(errorList, geolat, geolong, geotime, clientIpString, asCountry, geoIpCountry, serverType, testServerEncryption, ipv6); try { if (server == null) throw new JSONException("could not find server"); if (timeZoneId.isEmpty()) { timeZoneId = Helperfunctions.getTimezoneId(); timeWithZone = Helperfunctions.getTimeWithTimeZone(timeZoneId); } else timeWithZone = Helperfunctions.getTimeWithTimeZone(timeZoneId); answer.put("test_server_address", server.address); answer.put("test_server_port", server.port); answer.put("test_server_name", server.name); answer.put("test_server_encryption", testServerEncryption); answer.put("test_duration", getSetting("rmbt_duration")); answer.put("test_numthreads", getSetting("rmbt_num_threads")); answer.put("test_numpings", getSetting("rmbt_num_pings")); answer.put("client_remote_ip", clientIpString); final String resultUrl = new Reference(getURL(), settings.getString("RMBT_RESULT_PATH")).getTargetRef().toString(); // System.out.println(resultUrl); answer.put("result_url", resultUrl); final String resultQoSUrl = new Reference(getURL(), settings.getString("RMBT_QOS_RESULT_PATH")).getTargetRef().toString(); // System.out.println(resultUrl); answer.put("result_qos_url", resultQoSUrl); } catch (final JSONException e) { System.out.println("Error generating Answer " + e.toString()); errorList.addError("ERROR_RESPONSE_JSON"); } if (errorList.getLength() == 0) try { PreparedStatement st; st = conn.prepareStatement( "INSERT INTO test(time, uuid, open_test_uuid, client_id, client_name, client_version, client_software_version, client_language, client_public_ip, client_public_ip_anonymized, country_geoip, server_id, port, use_ssl, timezone, client_time, duration, num_threads_requested, status, software_revision, client_test_counter, client_previous_test_status, public_ip_asn, public_ip_as_name, country_asn, public_ip_rdns, run_ndt)" + "VALUES(NOW(), ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?)", Statement.RETURN_GENERATED_KEYS); int i = 1; // uuid st.setObject(i++, UUID.fromString(testUuid)); // open_test_uuid st.setObject(i++, UUID.fromString(testOpenUuid)); // client_id st.setLong(i++, clientUid); // client_name st.setString(i++, clientName); // client_version st.setString(i++, clientVersion); // client_software_version st.setString(i++, request.optString("softwareVersion", null)); // client_language st.setString(i++, lang); // client_public_ip st.setString(i++, clientIpString); // client_public_ip_anonymized st.setString(i++, Helperfunctions.anonymizeIp(clientAddress)); // country_geoip (2digit country code derived from public IP of client) st.setString(i++, geoIpCountry); // server_id st.setInt(i++, server.id); // port st.setInt(i++, server.port); // use_ssl st.setBoolean(i++, testServerEncryption); // timezone (of client) st.setString(i++, timeZoneId); // client_time (local time of client) st.setTimestamp(i++, clientTstamp, timeWithZone); // duration (requested) st.setInt(i++, Integer.parseInt(getSetting("rmbt_duration"))); // num_threads_requested st.setInt(i++, Integer.parseInt(getSetting("rmbt_num_threads"))); // status (of test) st.setString(i++, "STARTED"); //was "RUNNING" before // software_revision (of client) st.setString(i++, request.optString("softwareRevision", null)); // client_test_counter (number of tests the client has performed) final int testCounter = request.optInt("testCounter", -1); if (testCounter == -1) // older clients did not support testCounter st.setNull(i++, Types.INTEGER); else st.setLong(i++, testCounter); // client_previous_test_status (outcome of previous test) st.setString(i++, request.optString("previousTestStatus", null)); // AS name if (asn == null) st.setNull(i++, Types.BIGINT); else st.setLong(i++, asn); if (asName == null) st.setNull(i++, Types.VARCHAR); else st.setString(i++, asName); // AS country if (asCountry == null) st.setNull(i++, Types.VARCHAR); else st.setString(i++, asCountry); //public_ip_rdns String reverseDNS = Helperfunctions.reverseDNSLookup(clientAddress); if (reverseDNS == null || reverseDNS.isEmpty()) st.setNull(i++, Types.VARCHAR); else { reverseDNS = reverseDNS.replaceFirst("\\.$", ""); st.setString(i++, reverseDNS); // cut off last dot (#332) } // run_ndt if (request.has("ndt")) st.setBoolean(i++, request.getBoolean("ndt")); else st.setNull(i++, Types.BOOLEAN); final int affectedRows = st.executeUpdate(); if (affectedRows == 0) errorList.addError("ERROR_DB_STORE_TEST"); else { long key = 0; final ResultSet rs = st.getGeneratedKeys(); if (rs.next()) // Retrieve the auto generated // key(s). key = rs.getLong(1); rs.close(); final PreparedStatement getProviderSt = conn .prepareStatement("SELECT rmbt_set_provider_from_as(?)"); getProviderSt.setLong(1, key); String provider = null; if (getProviderSt.execute()) { final ResultSet rs2 = getProviderSt.getResultSet(); if (rs2.next()) provider = rs2.getString(1); } if (provider != null) answer.put("provider", provider); final PreparedStatement testSlotStatement = conn .prepareStatement("SELECT rmbt_get_next_test_slot(?)"); testSlotStatement.setLong(1, key); int testSlot = -1; if (testSlotStatement.execute()) { final ResultSet rs2 = testSlotStatement.getResultSet(); if (rs2.next()) testSlot = rs2.getInt(1); } if (testSlot < 0) errorList.addError("ERROR_DB_STORE_GENERAL"); else { final String data = testUuid + "_" + testSlot; final String hmac = Helperfunctions.calculateHMAC(secret, data); if (hmac.length() == 0) errorList.addError("ERROR_TEST_TOKEN"); final String token = data + "_" + hmac; final PreparedStatement updateSt = conn .prepareStatement("UPDATE test SET token = ? WHERE uid = ?"); updateSt.setString(1, token); updateSt.setLong(2, key); updateSt.executeUpdate(); answer.put("test_token", token); answer.put("test_uuid", testUuid); answer.put("test_id", key); final long now = System.currentTimeMillis(); int wait = testSlot - (int) (now / 1000); if (wait < 0) wait = 0; answer.put("test_wait", wait); if (geotime != 0 && geolat != 0 && geolong != 0) { final GeoLocation clientLocation = new GeoLocation(conn); clientLocation.setTest_id(key); final Timestamp geotstamp = java.sql.Timestamp .valueOf(new Timestamp(geotime).toString()); clientLocation.setTime(geotstamp, timeZoneId); clientLocation.setAccuracy(geoaccuracy); clientLocation.setAltitude(geoaltitude); clientLocation.setBearing(geobearing); clientLocation.setSpeed(geospeed); clientLocation.setProvider(geoprovider); clientLocation.setGeo_lat(geolat); clientLocation.setGeo_long(geolong); clientLocation.storeLocation(); if (clientLocation.hasError()) errorList.addError(clientLocation.getError()); } } } st.close(); } catch (final SQLException e) { errorList.addError("ERROR_DB_STORE_GENERAL"); e.printStackTrace(); } } else errorList.addError("ERROR_CLIENT_UUID"); } else errorList.addError("ERROR_CLIENT_VERSION"); } else errorList.addError("ERROR_DB_CONNECTION"); // System.out.println(answer.toString(4)); } catch (final JSONException e) { errorList.addError("ERROR_REQUEST_JSON"); System.out.println("Error parsing JSDON Data " + e.toString()); } else errorList.addErrorString("Expected request is missing."); try { answer.putOpt("error", errorList.getList()); } catch (final JSONException e) { System.out.println("Error saving ErrorList: " + e.toString()); } answerString = answer.toString(); long elapsedTime = System.currentTimeMillis() - startTime; System.out.println(MessageFormat.format(labels.getString("NEW_REQUEST_SUCCESS"), clientIpRaw, Long.toString(elapsedTime))); return answerString; }
From source file:org.apache.empire.db.codegen.CodeGenParser.java
/** * converts a SQL DataType to a EmpireDataType *//*from ww w . j a v a 2 s.c o m*/ private DataType getEmpireDataType(int sqlType) { DataType empireType = DataType.UNKNOWN; switch (sqlType) { case Types.INTEGER: case Types.SMALLINT: case Types.TINYINT: case Types.BIGINT: empireType = DataType.INTEGER; break; case Types.VARCHAR: empireType = DataType.TEXT; break; case Types.DATE: empireType = DataType.DATE; break; case Types.TIMESTAMP: case Types.TIME: empireType = DataType.DATETIME; break; case Types.CHAR: empireType = DataType.CHAR; break; case Types.DOUBLE: case Types.FLOAT: case Types.REAL: empireType = DataType.FLOAT; break; case Types.DECIMAL: case Types.NUMERIC: empireType = DataType.DECIMAL; break; case Types.BIT: case Types.BOOLEAN: empireType = DataType.BOOL; break; case Types.CLOB: case Types.LONGVARCHAR: empireType = DataType.CLOB; break; case Types.BINARY: case Types.VARBINARY: case Types.LONGVARBINARY: case Types.BLOB: empireType = DataType.BLOB; break; default: empireType = DataType.UNKNOWN; log.warn("SQL column type " + sqlType + " not supported."); } log.debug("Mapping date type " + String.valueOf(sqlType) + " to " + empireType); return empireType; }
From source file:org.nuxeo.ecm.core.storage.sql.db.H2Fulltext.java
protected static String asString(Object data, int type) throws SQLException { if (data == null) { return ""; }/* w ww .j a va2s . co m*/ switch (type) { case Types.BIT: case Types.BOOLEAN: case Types.INTEGER: case Types.BIGINT: case Types.DECIMAL: case Types.DOUBLE: case Types.FLOAT: case Types.NUMERIC: case Types.REAL: case Types.SMALLINT: case Types.TINYINT: case Types.DATE: case Types.TIME: case Types.TIMESTAMP: case Types.LONGVARCHAR: case Types.CHAR: case Types.VARCHAR: return data.toString(); case Types.CLOB: try { if (data instanceof Clob) { data = ((Clob) data).getCharacterStream(); } return IOUtils.readStringAndClose((Reader) data, -1); } catch (IOException e) { throw DbException.convert(e); } case Types.VARBINARY: case Types.LONGVARBINARY: case Types.BINARY: case Types.JAVA_OBJECT: case Types.OTHER: case Types.BLOB: case Types.STRUCT: case Types.REF: case Types.NULL: case Types.ARRAY: case Types.DATALINK: case Types.DISTINCT: throw new SQLException("Unsupported column data type: " + type); default: return ""; } }
From source file:org.jumpmind.db.platform.AbstractDatabasePlatform.java
public String[] getStringValues(BinaryEncoding encoding, Column[] metaData, Row row, boolean useVariableDates, boolean indexByPosition) { String[] values = new String[metaData.length]; Set<String> keys = row.keySet(); int i = 0;/*from w w w. j a v a 2 s . co m*/ for (String key : keys) { Column column = metaData[i]; String name = indexByPosition ? key : column.getName(); int type = column.getJdbcTypeCode(); if (row.get(name) != null) { if (type == Types.BOOLEAN || type == Types.BIT) { values[i] = row.getBoolean(name) ? "1" : "0"; } else if (column.isOfNumericType()) { values[i] = row.getString(name); } else if (!column.isTimestampWithTimezone() && (type == Types.DATE || type == Types.TIMESTAMP || type == Types.TIME)) { values[i] = getDateTimeStringValue(name, type, row, useVariableDates); } else if (column.isOfBinaryType()) { byte[] bytes = row.getBytes(name); if (encoding == BinaryEncoding.NONE) { values[i] = row.getString(name); } else if (encoding == BinaryEncoding.BASE64) { values[i] = new String(Base64.encodeBase64(bytes)); } else if (encoding == BinaryEncoding.HEX) { values[i] = new String(Hex.encodeHex(bytes)); } } else { values[i] = row.getString(name); } } i++; } return values; }
From source file:ca.sqlpower.architect.ddl.LiquibaseDDLGenerator.java
/** * Creates a <column> definition tag *///from www . ja v a2s.co m protected String columnDefinition(String indent, SQLColumn c, boolean tableHasSingleColumnPK) { StringBuilder def = new StringBuilder(50); def.append(indent); def.append("<column name=\""); def.append(getName(c)); GenericTypeDescriptor type = getTypeDescriptor(c); def.append("\" type=\""); def.append(columnType(c)); def.append("\""); if (StringUtils.isNotBlank(c.getRemarks())) { def.append(" remarks="); def.append(escapeAttributeValue(c.getRemarks())); } if (StringUtils.isNotBlank(c.getDefaultValue())) { if (isNumericType(type)) { def.append(" defaultValueNumeric=\""); def.append(c.getDefaultValue()); def.append("\""); } else if (isDateType(type)) { def.append(" defaultValueDate=\""); def.append(c.getDefaultValue()); def.append("\""); } else if (type.getDataType() == Types.BOOLEAN) { def.append(" defaultValueBoolean=\""); def.append(c.getDefaultValue()); def.append("\""); } else { def.append(" defaultValue=\""); def.append(c.getDefaultValue()); def.append("\""); } } if (c.isAutoIncrement()) { def.append(" autoIncrement=\"true\""); } boolean needsConstraint = !c.isDefinitelyNullable() || tableHasSingleColumnPK && c.isPrimaryKey() && !useAddPKSingleColumn; if (needsConstraint) { def.append(">"); def.append(EOL); def.append(indent); def.append(indent); def.append("<constraints"); if (tableHasSingleColumnPK && c.isPrimaryKey() && !useAddPKSingleColumn) { def.append(" primaryKey=\"true\""); SQLTable tbl = c.getParent(); try { SQLIndex pk = tbl.getPrimaryKeyIndex(); def.append(" constraintName=\""); def.append(getName(pk)); def.append("\""); } catch (Exception e) { logger.error("Could not obtain PK index", e); } } if (!c.isDefinitelyNullable()) { def.append(" nullable=\"false\""); } def.append("/>"); def.append(EOL); def.append(indent); def.append("</column>"); } else { def.append("/>"); } return def.toString(); }
From source file:com.streamsets.pipeline.lib.jdbc.JdbcUtil.java
public Field resultToField(ResultSetMetaData md, ResultSet rs, int columnIndex, int maxClobSize, int maxBlobSize, DataType userSpecifiedType, UnknownTypeAction unknownTypeAction, boolean timestampToString) throws SQLException, IOException, StageException { Field field;// w w w . jav a 2 s. c o m if (userSpecifiedType != DataType.USE_COLUMN_TYPE) { // If user specifies the data type, overwrite the column type returned by database. field = Field.create(Field.Type.valueOf(userSpecifiedType.getLabel()), rs.getObject(columnIndex)); } else { // All types as of JDBC 2.0 are here: // https://docs.oracle.com/javase/8/docs/api/constant-values.html#java.sql.Types.ARRAY // Good source of recommended mappings is here: // http://www.cs.mun.ca/java-api-1.5/guide/jdbc/getstart/mapping.html switch (md.getColumnType(columnIndex)) { case Types.BIGINT: field = Field.create(Field.Type.LONG, rs.getObject(columnIndex)); break; case Types.BINARY: case Types.LONGVARBINARY: case Types.VARBINARY: field = Field.create(Field.Type.BYTE_ARRAY, rs.getBytes(columnIndex)); break; case Types.BIT: case Types.BOOLEAN: field = Field.create(Field.Type.BOOLEAN, rs.getObject(columnIndex)); break; case Types.CHAR: case Types.LONGNVARCHAR: case Types.LONGVARCHAR: case Types.NCHAR: case Types.NVARCHAR: case Types.VARCHAR: field = Field.create(Field.Type.STRING, rs.getObject(columnIndex)); break; case Types.CLOB: case Types.NCLOB: field = Field.create(Field.Type.STRING, getClobString(rs.getClob(columnIndex), maxClobSize)); break; case Types.BLOB: field = Field.create(Field.Type.BYTE_ARRAY, getBlobBytes(rs.getBlob(columnIndex), maxBlobSize)); break; case Types.DATE: field = Field.create(Field.Type.DATE, rs.getDate(columnIndex)); break; case Types.DECIMAL: case Types.NUMERIC: field = Field.create(Field.Type.DECIMAL, rs.getBigDecimal(columnIndex)); field.setAttribute(HeaderAttributeConstants.ATTR_SCALE, String.valueOf(rs.getMetaData().getScale(columnIndex))); field.setAttribute(HeaderAttributeConstants.ATTR_PRECISION, String.valueOf(rs.getMetaData().getPrecision(columnIndex))); break; case Types.DOUBLE: field = Field.create(Field.Type.DOUBLE, rs.getObject(columnIndex)); break; case Types.FLOAT: case Types.REAL: field = Field.create(Field.Type.FLOAT, rs.getObject(columnIndex)); break; case Types.INTEGER: field = Field.create(Field.Type.INTEGER, rs.getObject(columnIndex)); break; case Types.ROWID: field = Field.create(Field.Type.STRING, rs.getRowId(columnIndex).toString()); break; case Types.SMALLINT: case Types.TINYINT: field = Field.create(Field.Type.SHORT, rs.getObject(columnIndex)); break; case Types.TIME: field = Field.create(Field.Type.TIME, rs.getObject(columnIndex)); break; case Types.TIMESTAMP: final Timestamp timestamp = rs.getTimestamp(columnIndex); if (timestampToString) { field = Field.create(Field.Type.STRING, timestamp == null ? null : timestamp.toString()); } else { field = Field.create(Field.Type.DATETIME, timestamp); if (timestamp != null) { final long actualNanos = timestamp.getNanos() % NANOS_TO_MILLIS_ADJUSTMENT; if (actualNanos > 0) { field.setAttribute(FIELD_ATTRIBUTE_NANOSECONDS, String.valueOf(actualNanos)); } } } break; // Ugly hack until we can support LocalTime, LocalDate, LocalDateTime, etc. case Types.TIME_WITH_TIMEZONE: OffsetTime offsetTime = rs.getObject(columnIndex, OffsetTime.class); field = Field.create(Field.Type.TIME, Date.from(offsetTime.atDate(LocalDate.MIN).toInstant())); break; case Types.TIMESTAMP_WITH_TIMEZONE: OffsetDateTime offsetDateTime = rs.getObject(columnIndex, OffsetDateTime.class); field = Field.create(Field.Type.ZONED_DATETIME, offsetDateTime.toZonedDateTime()); break; //case Types.REF_CURSOR: // JDK8 only case Types.SQLXML: case Types.STRUCT: case Types.ARRAY: case Types.DATALINK: case Types.DISTINCT: case Types.JAVA_OBJECT: case Types.NULL: case Types.OTHER: case Types.REF: default: if (unknownTypeAction == null) { return null; } switch (unknownTypeAction) { case STOP_PIPELINE: throw new StageException(JdbcErrors.JDBC_37, md.getColumnType(columnIndex), md.getColumnLabel(columnIndex)); case CONVERT_TO_STRING: Object value = rs.getObject(columnIndex); if (value != null) { field = Field.create(Field.Type.STRING, rs.getObject(columnIndex).toString()); } else { field = Field.create(Field.Type.STRING, null); } break; default: throw new IllegalStateException("Unknown action: " + unknownTypeAction); } } } return field; }