List of usage examples for java.sql Date valueOf
@SuppressWarnings("deprecation") public static Date valueOf(LocalDate date)
From source file:org.apache.cocoon.util.JDBCTypeConversions.java
/** * Set the Statement column so that the results are mapped correctly. * * @param statement the prepared statement * @param position the position of the column * @param value the value of the column//from ww w . j a v a2 s. com */ public static void setColumn(PreparedStatement statement, int position, Object value, Integer typeObject) throws Exception { if (value instanceof String) { value = ((String) value).trim(); } if (typeObject == null) { throw new SQLException("Can't set column because the type is unrecognized"); } if (value == null) { /** If the value is null, set the column value null and return **/ statement.setNull(position, typeObject.intValue()); return; } if ("".equals(value)) { switch (typeObject.intValue()) { case Types.CHAR: case Types.CLOB: case Types.VARCHAR: /** If the value is an empty string and the column is a string type, we can continue **/ break; default: /** If the value is an empty string and the column is something else, we treat it as a null value **/ statement.setNull(position, typeObject.intValue()); return; } } File file = null; int length = -1; InputStream asciiStream = null; //System.out.println("========================================================================"); //System.out.println("JDBCTypeConversions: setting type "+typeObject.intValue()); switch (typeObject.intValue()) { case Types.CLOB: //System.out.println("CLOB"); Clob clob = null; if (value instanceof Clob) { clob = (Clob) value; } else if (value instanceof File) { File asciiFile = (File) value; asciiStream = new BufferedInputStream(new FileInputStream(asciiFile)); length = (int) asciiFile.length(); clob = new ClobHelper(asciiStream, length); } else if (value instanceof Part) { Part anyFile = (Part) value; asciiStream = new BufferedInputStream(anyFile.getInputStream()); length = anyFile.getSize(); clob = new ClobHelper(asciiStream, length); } else if (value instanceof JDBCxlobHelper) { asciiStream = ((JDBCxlobHelper) value).inputStream; length = ((JDBCxlobHelper) value).length; clob = new ClobHelper(asciiStream, length); } else if (value instanceof Source) { asciiStream = ((Source) value).getInputStream(); length = (int) ((Source) value).getContentLength(); clob = new ClobHelper(asciiStream, length); } else { String asciiText = value.toString(); asciiStream = new ByteArrayInputStream(asciiText.getBytes()); length = asciiText.length(); clob = new ClobHelper(asciiStream, length); } statement.setClob(position, clob); break; case Types.CHAR: // simple large object, e.g. Informix's TEXT //System.out.println("CHAR"); if (value instanceof File) { File asciiFile = (File) value; asciiStream = new BufferedInputStream(new FileInputStream(asciiFile)); length = (int) asciiFile.length(); } else if (value instanceof JDBCxlobHelper) { asciiStream = ((JDBCxlobHelper) value).inputStream; length = ((JDBCxlobHelper) value).length; } else if (value instanceof Source) { asciiStream = ((Source) value).getInputStream(); length = (int) ((Source) value).getContentLength(); } else if (value instanceof Part) { Part anyFile = (Part) value; asciiStream = new BufferedInputStream(anyFile.getInputStream()); length = anyFile.getSize(); clob = new ClobHelper(asciiStream, length); } else { String asciiText = value.toString(); asciiStream = new BufferedInputStream(new ByteArrayInputStream(asciiText.getBytes())); length = asciiText.length(); } statement.setAsciiStream(position, asciiStream, length); break; case Types.BIGINT: //System.out.println("BIGINT"); BigDecimal bd = null; if (value instanceof BigDecimal) { bd = (BigDecimal) value; } else if (value instanceof Number) { bd = BigDecimal.valueOf(((Number) value).longValue()); } else { bd = new BigDecimal(value.toString()); } statement.setBigDecimal(position, bd); break; case Types.TINYINT: //System.out.println("TINYINT"); Byte b = null; if (value instanceof Byte) { b = (Byte) value; } else if (value instanceof Number) { b = new Byte(((Number) value).byteValue()); } else { b = new Byte(value.toString()); } statement.setByte(position, b.byteValue()); break; case Types.DATE: //System.out.println("DATE"); Date d = null; if (value instanceof Date) { d = (Date) value; } else if (value instanceof java.util.Date) { d = new Date(((java.util.Date) value).getTime()); } else if (value instanceof Calendar) { d = new Date(((Calendar) value).getTime().getTime()); } else { d = Date.valueOf(value.toString()); } statement.setDate(position, d); break; case Types.DOUBLE: //System.out.println("DOUBLE"); double db; if (value instanceof Number) { db = (((Number) value).doubleValue()); } else { db = Double.parseDouble(value.toString()); } statement.setDouble(position, db); break; case Types.FLOAT: //System.out.println("FLOAT"); float f; if (value instanceof Number) { f = (((Number) value).floatValue()); } else { f = Float.parseFloat(value.toString()); } statement.setFloat(position, f); break; case Types.NUMERIC: //System.out.println("NUMERIC"); long l; if (value instanceof Number) { l = (((Number) value).longValue()); } else { l = Long.parseLong(value.toString()); } statement.setLong(position, l); break; case Types.SMALLINT: //System.out.println("SMALLINT"); Short s = null; if (value instanceof Short) { s = (Short) value; } else if (value instanceof Number) { s = new Short(((Number) value).shortValue()); } else { s = new Short(value.toString()); } statement.setShort(position, s.shortValue()); break; case Types.TIME: //System.out.println("TIME"); Time t = null; if (value instanceof Time) { t = (Time) value; } else if (value instanceof java.util.Date) { t = new Time(((java.util.Date) value).getTime()); } else { t = Time.valueOf(value.toString()); } statement.setTime(position, t); break; case Types.TIMESTAMP: //System.out.println("TIMESTAMP"); Timestamp ts = null; if (value instanceof Time) { ts = (Timestamp) value; } else if (value instanceof java.util.Date) { ts = new Timestamp(((java.util.Date) value).getTime()); } else { ts = Timestamp.valueOf(value.toString()); } statement.setTimestamp(position, ts); break; case Types.ARRAY: //System.out.println("ARRAY"); statement.setArray(position, (Array) value); // no way to convert string to array break; case Types.STRUCT: //System.out.println("STRUCT"); case Types.OTHER: //System.out.println("OTHER"); statement.setObject(position, value); break; case Types.LONGVARBINARY: //System.out.println("LONGVARBINARY"); statement.setTimestamp(position, new Timestamp((new java.util.Date()).getTime())); break; case Types.VARCHAR: //System.out.println("VARCHAR"); statement.setString(position, value.toString()); break; case Types.BLOB: //System.out.println("BLOB"); if (value instanceof JDBCxlobHelper) { statement.setBinaryStream(position, ((JDBCxlobHelper) value).inputStream, ((JDBCxlobHelper) value).length); } else if (value instanceof Source) { statement.setBinaryStream(position, ((Source) value).getInputStream(), (int) ((Source) value).getContentLength()); } else { Blob blob = null; if (value instanceof Blob) { blob = (Blob) value; } else if (value instanceof File) { file = (File) value; blob = new BlobHelper(new FileInputStream(file), (int) file.length()); } else if (value instanceof String) { file = new File((String) value); blob = new BlobHelper(new FileInputStream(file), (int) file.length()); } else if (value instanceof Part) { Part anyFile = (Part) value; blob = new BlobHelper(new BufferedInputStream(anyFile.getInputStream()), anyFile.getSize()); } else { throw new SQLException("Invalid type for blob: " + value.getClass().getName()); } //InputStream input = new BufferedInputStream(new FileInputStream(file)); statement.setBlob(position, blob); } break; case Types.VARBINARY: //System.out.println("VARBINARY"); if (value instanceof JDBCxlobHelper) { statement.setBinaryStream(position, ((JDBCxlobHelper) value).inputStream, ((JDBCxlobHelper) value).length); } else if (value instanceof Source) { statement.setBinaryStream(position, ((Source) value).getInputStream(), (int) ((Source) value).getContentLength()); } else if (value instanceof Part) { statement.setBinaryStream(position, ((Part) value).getInputStream(), ((Part) value).getSize()); } else { if (value instanceof File) { file = (File) value; } else if (value instanceof String) { file = new File((String) value); } else { throw new SQLException("Invalid type for blob: " + value.getClass().getName()); } //InputStream input = new BufferedInputStream(new FileInputStream(file)); FileInputStream input = new FileInputStream(file); statement.setBinaryStream(position, input, (int) file.length()); } break; case Types.INTEGER: //System.out.println("INTEGER"); Integer i = null; if (value instanceof Integer) { i = (Integer) value; } else if (value instanceof Number) { i = new Integer(((Number) value).intValue()); } else { i = new Integer(value.toString()); } statement.setInt(position, i.intValue()); break; case Types.BIT: //System.out.println("BIT"); Boolean bo = null; if (value instanceof Boolean) { bo = (Boolean) value; } else if (value instanceof Number) { bo = BooleanUtils.toBooleanObject(((Number) value).intValue() == 1); } else { bo = BooleanUtils.toBooleanObject(value.toString()); } statement.setBoolean(position, bo.booleanValue()); break; default: //System.out.println("default"); throw new SQLException("Impossible exception - invalid type "); } //System.out.println("========================================================================"); }
From source file:org.apache.openjpa.jdbc.schema.Column.java
/** * Return the default value set for this column, if any. If only a default * string has been set, attempts to convert it to the right type based * on the Java type set for this column. *///from www.jav a2s . co m public Object getDefault() { if (_default != null) return _default; if (_defaultStr == null) return null; switch (_javaType) { case JavaTypes.BOOLEAN: case JavaTypes.BOOLEAN_OBJ: _default = ("true".equals(_defaultStr)) ? Boolean.TRUE : Boolean.FALSE; break; case JavaTypes.BYTE: case JavaTypes.BYTE_OBJ: _default = new Byte(_defaultStr); break; case JavaTypes.CHAR: case JavaTypes.CHAR_OBJ: _default = Character.valueOf(_defaultStr.charAt(0)); break; case JavaTypes.DOUBLE: case JavaTypes.DOUBLE_OBJ: _default = new Double(_defaultStr); break; case JavaTypes.FLOAT: case JavaTypes.FLOAT_OBJ: _default = new Float(_defaultStr); break; case JavaTypes.INT: case JavaTypes.INT_OBJ: _default = Integer.parseInt(_defaultStr); break; case JavaTypes.LONG: case JavaTypes.LONG_OBJ: _default = Long.parseLong(_defaultStr); break; case JavaTypes.NUMBER: case JavaTypes.BIGDECIMAL: _default = new BigDecimal(_defaultStr); break; case JavaTypes.SHORT: case JavaTypes.SHORT_OBJ: _default = new Short(_defaultStr); break; case JavaTypes.DATE: _default = new java.util.Date(_defaultStr); break; case JavaTypes.BIGINTEGER: _default = new BigInteger(_defaultStr); break; case JavaSQLTypes.SQL_DATE: _default = Date.valueOf(_defaultStr); break; case JavaSQLTypes.TIMESTAMP: _default = Timestamp.valueOf(_defaultStr); break; case JavaSQLTypes.TIME: _default = Time.valueOf(_defaultStr); break; default: _default = _defaultStr; } return _default; }
From source file:org.ofbiz.core.entity.GenericEntity.java
/** * Sets the named field to the passed value, converting the value from a String to the correct type using * {@code Type.valueOf()} or similar./*from w w w . j a v a 2s .co m*/ * <p> * <strong>WARNING</strong>: calling this for an {@link FieldType#OBJECT OBJECT} field is ambiguous, because * you could mean either that the {@code String} is the Base64-encoded representation of the object and * should be be deserialized or that the {@code String} is the actual object to be stored. Since this * method is intended for use in restoring the entity from an XML export, it assumes that the value is * the Base64-encoding of an arbitrary object and attempts to deserialize it. If this is not what is * intended, then it is up to the caller to use {@link #set(String, Object)} for those fields, instead. * </p> * * @param name The field name to set * @param value The String value to convert and set */ public void setString(String name, String value) { ModelField field = getModelEntity().getField(name); if (field == null) { throw new IllegalArgumentException( "[GenericEntity.setString] \"" + name + "\" is not a field of " + entityName); } final ModelFieldType type = getModelFieldType(field.getType()); final FieldType fieldType = SqlJdbcUtil.getFieldType(type.getJavaType()); switch (fieldType) { case STRING: set(name, value); break; case TIMESTAMP: set(name, Timestamp.valueOf(value)); break; case TIME: set(name, Time.valueOf(value)); break; case DATE: set(name, Date.valueOf(value)); break; case INTEGER: set(name, Integer.valueOf(value)); break; case LONG: set(name, Long.valueOf(value)); break; case FLOAT: set(name, Float.valueOf(value)); break; case DOUBLE: set(name, Double.valueOf(value)); break; case BOOLEAN: set(name, Boolean.valueOf(value)); break; case OBJECT: set(name, deserialize(decodeBase64(value))); break; case CLOB: set(name, value); break; case BLOB: set(name, decodeBase64(value)); break; case BYTE_ARRAY: set(name, decodeBase64(value)); break; default: throw new UnsupportedOperationException("Unsupported type: " + fieldType); } }
From source file:org.apache.hadoop.hive.serde2.lazy.fast.LazySimpleDeserializeRead.java
@Override public boolean readCheckNull() { if (++fieldIndex >= fieldCount) { // Reading beyond the specified field count produces NULL. if (!readBeyondConfiguredFieldsWarned) { // Warn only once. LOG.info("Reading beyond configured fields! Configured " + fieldCount + " fields but " + " reading more (NULLs returned). Ignoring similar problems."); readBeyondConfiguredFieldsWarned = true; }// w ww. ja v a 2s .c o m return true; } if (offset > end) { // We must allow for an empty field at the end, so no strict >= checking. if (!readBeyondBufferRangeWarned) { // Warn only once. int length = end - start; LOG.info("Reading beyond buffer range! Buffer range " + start + " for length " + length + " but reading more (NULLs returned)." + " Ignoring similar problems."); readBeyondBufferRangeWarned = true; } // char[] charsBuffer = new char[end - start]; // for (int c = 0; c < charsBuffer.length; c++) { // charsBuffer[c] = (char) (bytes[start + c] & 0xFF); // } return true; } fieldStart = offset; while (true) { if (offset >= end) { fieldLength = offset - fieldStart; break; } if (bytes[offset] == separator) { fieldLength = (offset++ - fieldStart); break; } if (isEscaped && bytes[offset] == escapeChar && offset + 1 < end) { // Ignore the char after escape char. offset += 2; } else { offset++; } } char[] charField = new char[fieldLength]; for (int c = 0; c < charField.length; c++) { charField[c] = (char) (bytes[fieldStart + c] & 0xFF); } // Is the field the configured string representing NULL? if (nullSequenceBytes != null) { if (fieldLength == nullSequenceBytes.length) { int i = 0; while (true) { if (bytes[fieldStart + i] != nullSequenceBytes[i]) { break; } i++; if (i >= fieldLength) { return true; } } } } switch (primitiveTypeInfos[fieldIndex].getPrimitiveCategory()) { case BOOLEAN: { int i = fieldStart; if (fieldLength == 4) { if ((bytes[i] == 'T' || bytes[i] == 't') && (bytes[i + 1] == 'R' || bytes[i + 1] == 'r') && (bytes[i + 2] == 'U' || bytes[i + 1] == 'u') && (bytes[i + 3] == 'E' || bytes[i + 3] == 'e')) { saveBool = true; } else { // No boolean value match for 5 char field. return true; } } else if (fieldLength == 5) { if ((bytes[i] == 'F' || bytes[i] == 'f') && (bytes[i + 1] == 'A' || bytes[i + 1] == 'a') && (bytes[i + 2] == 'L' || bytes[i + 2] == 'l') && (bytes[i + 3] == 'S' || bytes[i + 3] == 's') && (bytes[i + 4] == 'E' || bytes[i + 4] == 'e')) { saveBool = false; } else { // No boolean value match for 4 char field. return true; } } else if (isExtendedBooleanLiteral && fieldLength == 1) { byte b = bytes[fieldStart]; if (b == '1' || b == 't' || b == 'T') { saveBool = true; } else if (b == '0' || b == 'f' || b == 'F') { saveBool = false; } else { // No boolean value match for extended 1 char field. return true; } } else { // No boolean value match for other lengths. return true; } } break; case BYTE: try { saveByte = LazyByte.parseByte(bytes, fieldStart, fieldLength, 10); } catch (NumberFormatException e) { logExceptionMessage(bytes, fieldStart, fieldLength, "TINYINT"); return true; } // if (!parseLongFast()) { // return true; // } // saveShort = (short) saveLong; // if (saveShort != saveLong) { // return true; // } break; case SHORT: try { saveShort = LazyShort.parseShort(bytes, fieldStart, fieldLength, 10); } catch (NumberFormatException e) { logExceptionMessage(bytes, fieldStart, fieldLength, "SMALLINT"); return true; } // if (!parseLongFast()) { // return true; // } // saveShort = (short) saveLong; // if (saveShort != saveLong) { // return true; // } break; case INT: try { saveInt = LazyInteger.parseInt(bytes, fieldStart, fieldLength, 10); } catch (NumberFormatException e) { logExceptionMessage(bytes, fieldStart, fieldLength, "INT"); return true; } // if (!parseLongFast()) { // return true; // } // saveInt = (int) saveLong; // if (saveInt != saveLong) { // return true; // } break; case LONG: try { saveLong = LazyLong.parseLong(bytes, fieldStart, fieldLength, 10); } catch (NumberFormatException e) { logExceptionMessage(bytes, fieldStart, fieldLength, "BIGINT"); return true; } // if (!parseLongFast()) { // return true; // } break; case FLOAT: { String byteData = null; try { byteData = Text.decode(bytes, fieldStart, fieldLength); saveFloat = Float.parseFloat(byteData); } catch (NumberFormatException e) { LOG.debug("Data not in the Float data type range so converted to null. Given data is :" + byteData, e); return true; } catch (CharacterCodingException e) { LOG.debug("Data not in the Float data type range so converted to null.", e); return true; } } // if (!parseFloat()) { // return true; // } break; case DOUBLE: { String byteData = null; try { byteData = Text.decode(bytes, fieldStart, fieldLength); saveDouble = Double.parseDouble(byteData); } catch (NumberFormatException e) { LOG.debug("Data not in the Double data type range so converted to null. Given data is :" + byteData, e); return true; } catch (CharacterCodingException e) { LOG.debug("Data not in the Double data type range so converted to null.", e); return true; } } // if (!parseDouble()) { // return true; // } break; case STRING: case CHAR: case VARCHAR: if (isEscaped) { LazyUtils.copyAndEscapeStringDataToText(bytes, fieldStart, fieldLength, escapeChar, tempText); saveBytes = tempText.getBytes(); saveBytesStart = 0; saveBytesLength = tempText.getLength(); } else { // if the data is not escaped, simply copy the data. saveBytes = bytes; saveBytesStart = fieldStart; saveBytesLength = fieldLength; } break; case BINARY: { byte[] recv = new byte[fieldLength]; System.arraycopy(bytes, fieldStart, recv, 0, fieldLength); byte[] decoded = LazyBinary.decodeIfNeeded(recv); // use the original bytes in case decoding should fail decoded = decoded.length > 0 ? decoded : recv; saveBytes = decoded; saveBytesStart = 0; saveBytesLength = decoded.length; } break; case DATE: { String s = null; try { s = Text.decode(bytes, fieldStart, fieldLength); saveDate = Date.valueOf(s); } catch (Exception e) { logExceptionMessage(bytes, fieldStart, fieldLength, "DATE"); return true; } } // if (!parseDate()) { // return true; // } break; case TIMESTAMP: { String s = null; try { s = new String(bytes, fieldStart, fieldLength, "US-ASCII"); } catch (UnsupportedEncodingException e) { LOG.error(e); s = ""; } if (s.compareTo("NULL") == 0) { logExceptionMessage(bytes, fieldStart, fieldLength, "TIMESTAMP"); return true; } else { try { if (timestampParser == null) { timestampParser = new TimestampParser(); } saveTimestamp = timestampParser.parseTimestamp(s); } catch (IllegalArgumentException e) { logExceptionMessage(bytes, fieldStart, fieldLength, "TIMESTAMP"); return true; } } } // if (!parseTimestamp()) { // return true; // } break; case INTERVAL_YEAR_MONTH: { String s = null; try { s = Text.decode(bytes, fieldStart, fieldLength); saveIntervalYearMonth = HiveIntervalYearMonth.valueOf(s); } catch (Exception e) { logExceptionMessage(bytes, fieldStart, fieldLength, "INTERVAL_YEAR_MONTH"); return true; } } // if (!parseIntervalYearMonth()) { // return true; // } break; case INTERVAL_DAY_TIME: { String s = null; try { s = Text.decode(bytes, fieldStart, fieldLength); saveIntervalDayTime = HiveIntervalDayTime.valueOf(s); } catch (Exception e) { logExceptionMessage(bytes, fieldStart, fieldLength, "INTERVAL_DAY_TIME"); return true; } } // if (!parseIntervalDayTime()) { // return true; // } break; case DECIMAL: { String byteData = null; try { byteData = Text.decode(bytes, fieldStart, fieldLength); } catch (CharacterCodingException e) { LOG.debug("Data not in the HiveDecimal data type range so converted to null.", e); return true; } saveDecimal = HiveDecimal.create(byteData); saveDecimalTypeInfo = (DecimalTypeInfo) primitiveTypeInfos[fieldIndex]; int precision = saveDecimalTypeInfo.getPrecision(); int scale = saveDecimalTypeInfo.getScale(); saveDecimal = HiveDecimal.enforcePrecisionScale(saveDecimal, precision, scale); if (saveDecimal == null) { LOG.debug("Data not in the HiveDecimal data type range so converted to null. Given data is :" + byteData); return true; } } // if (!parseDecimal()) { // return true; // } break; default: throw new Error( "Unexpected primitive category " + primitiveTypeInfos[fieldIndex].getPrimitiveCategory()); } return false; }
From source file:org.apache.jmeter.protocol.jdbc.AbstractJDBCTestElement.java
private void setArgument(PreparedStatement pstmt, String argument, int targetSqlType, int index) throws SQLException { switch (targetSqlType) { case Types.INTEGER: pstmt.setInt(index, Integer.parseInt(argument)); break;/*from w w w . j a v a 2 s . co m*/ case Types.DECIMAL: case Types.NUMERIC: pstmt.setBigDecimal(index, new BigDecimal(argument)); break; case Types.DOUBLE: case Types.FLOAT: pstmt.setDouble(index, Double.parseDouble(argument)); break; case Types.CHAR: case Types.LONGVARCHAR: case Types.VARCHAR: pstmt.setString(index, argument); break; case Types.BIT: case Types.BOOLEAN: pstmt.setBoolean(index, Boolean.parseBoolean(argument)); break; case Types.BIGINT: pstmt.setLong(index, Long.parseLong(argument)); break; case Types.DATE: pstmt.setDate(index, Date.valueOf(argument)); break; case Types.REAL: pstmt.setFloat(index, Float.parseFloat(argument)); break; case Types.TINYINT: pstmt.setByte(index, Byte.parseByte(argument)); break; case Types.SMALLINT: pstmt.setShort(index, Short.parseShort(argument)); break; case Types.TIMESTAMP: pstmt.setTimestamp(index, Timestamp.valueOf(argument)); break; case Types.TIME: pstmt.setTime(index, Time.valueOf(argument)); break; case Types.BINARY: case Types.VARBINARY: case Types.LONGVARBINARY: pstmt.setBytes(index, argument.getBytes()); break; case Types.NULL: pstmt.setNull(index, targetSqlType); break; default: pstmt.setObject(index, argument, targetSqlType); } }
From source file:org.mifosplatform.infrastructure.dataqueries.service.ReadReportingServiceImpl.java
private void addParametersToReport(final MasterReport report, final Map<String, String> queryParams) { final AppUser currentUser = this.context.authenticatedUser(); try {/*from w ww . java 2s . c om*/ final ReportParameterValues rptParamValues = report.getParameterValues(); final ReportParameterDefinition paramsDefinition = report.getParameterDefinition(); /* * only allow integer, long, date and string parameter types and * assume all mandatory - could go more detailed like Pawel did in * Mifos later and could match incoming and pentaho parameters * better... currently assuming they come in ok... and if not an * error */ for (final ParameterDefinitionEntry paramDefEntry : paramsDefinition.getParameterDefinitions()) { final String paramName = paramDefEntry.getName(); if (!((paramName.equals("tenantdb")) || (paramName.equals("userhierarchy")))) { logger.info("paramName:" + paramName); final String pValue = queryParams.get(paramName); if (StringUtils.isBlank(pValue)) { throw new PlatformDataIntegrityException("error.msg.reporting.error", "Pentaho Parameter: " + paramName + " - not Provided"); } final Class<?> clazz = paramDefEntry.getValueType(); logger.info("addParametersToReport(" + paramName + " : " + pValue + " : " + clazz.getCanonicalName() + ")"); if (clazz.getCanonicalName().equalsIgnoreCase("java.lang.Integer")) { rptParamValues.put(paramName, Integer.parseInt(pValue)); } else if (clazz.getCanonicalName().equalsIgnoreCase("java.lang.Long")) { rptParamValues.put(paramName, Long.parseLong(pValue)); } else if (clazz.getCanonicalName().equalsIgnoreCase("java.sql.Date")) { rptParamValues.put(paramName, Date.valueOf(pValue)); } else { rptParamValues.put(paramName, pValue); } } } // tenant database name and current user's office hierarchy // passed as parameters to allow multitenant penaho reporting // and // data scoping final Connection connection = this.dataSource.getConnection(); String tenantdb; try { tenantdb = connection.getCatalog(); } finally { connection.close(); } final String userhierarchy = currentUser.getOffice().getHierarchy(); logger.info("db name:" + tenantdb + " userhierarchy:" + userhierarchy); rptParamValues.put("tenantdb", tenantdb); rptParamValues.put("userhierarchy", userhierarchy); } catch (final Exception e) { logger.error("error.msg.reporting.error:" + e.getMessage()); throw new PlatformDataIntegrityException("error.msg.reporting.error", e.getMessage()); } }
From source file:org.apache.hive.jdbc.TestJdbcWithMiniLlap.java
@Test(timeout = 60000) public void testDataTypes() throws Exception { createDataTypesTable("datatypes"); RowCollector2 rowCollector = new RowCollector2(); String query = "select * from datatypes"; int rowCount = processQuery(query, 1, rowCollector); assertEquals(3, rowCount);/* w ww . j av a 2 s . co m*/ // Verify schema String[][] colNameTypes = new String[][] { { "datatypes.c1", "int" }, { "datatypes.c2", "boolean" }, { "datatypes.c3", "double" }, { "datatypes.c4", "string" }, { "datatypes.c5", "array<int>" }, { "datatypes.c6", "map<int,string>" }, { "datatypes.c7", "map<string,string>" }, { "datatypes.c8", "struct<r:string,s:int,t:double>" }, { "datatypes.c9", "tinyint" }, { "datatypes.c10", "smallint" }, { "datatypes.c11", "float" }, { "datatypes.c12", "bigint" }, { "datatypes.c13", "array<array<string>>" }, { "datatypes.c14", "map<int,map<int,int>>" }, { "datatypes.c15", "struct<r:int,s:struct<a:int,b:string>>" }, { "datatypes.c16", "array<struct<m:map<string,string>,n:int>>" }, { "datatypes.c17", "timestamp" }, { "datatypes.c18", "decimal(16,7)" }, { "datatypes.c19", "binary" }, { "datatypes.c20", "date" }, { "datatypes.c21", "varchar(20)" }, { "datatypes.c22", "char(15)" }, { "datatypes.c23", "binary" }, }; FieldDesc fieldDesc; assertEquals(23, rowCollector.numColumns); for (int idx = 0; idx < rowCollector.numColumns; ++idx) { fieldDesc = rowCollector.schema.getColumns().get(idx); assertEquals("ColName idx=" + idx, colNameTypes[idx][0], fieldDesc.getName()); assertEquals("ColType idx=" + idx, colNameTypes[idx][1], fieldDesc.getTypeInfo().getTypeName()); } // First row is all nulls Object[] rowValues = rowCollector.rows.get(0); for (int idx = 0; idx < rowCollector.numColumns; ++idx) { assertEquals("idx=" + idx, null, rowValues[idx]); } // Second Row rowValues = rowCollector.rows.get(1); assertEquals(Integer.valueOf(-1), rowValues[0]); assertEquals(Boolean.FALSE, rowValues[1]); assertEquals(Double.valueOf(-1.1d), rowValues[2]); assertEquals("", rowValues[3]); List<?> c5Value = (List<?>) rowValues[4]; assertEquals(0, c5Value.size()); Map<?, ?> c6Value = (Map<?, ?>) rowValues[5]; assertEquals(0, c6Value.size()); Map<?, ?> c7Value = (Map<?, ?>) rowValues[6]; assertEquals(0, c7Value.size()); List<?> c8Value = (List<?>) rowValues[7]; assertEquals(null, c8Value.get(0)); assertEquals(null, c8Value.get(1)); assertEquals(null, c8Value.get(2)); assertEquals(Byte.valueOf((byte) -1), rowValues[8]); assertEquals(Short.valueOf((short) -1), rowValues[9]); assertEquals(Float.valueOf(-1.0f), rowValues[10]); assertEquals(Long.valueOf(-1l), rowValues[11]); List<?> c13Value = (List<?>) rowValues[12]; assertEquals(0, c13Value.size()); Map<?, ?> c14Value = (Map<?, ?>) rowValues[13]; assertEquals(0, c14Value.size()); List<?> c15Value = (List<?>) rowValues[14]; assertEquals(null, c15Value.get(0)); assertEquals(null, c15Value.get(1)); List<?> c16Value = (List<?>) rowValues[15]; assertEquals(0, c16Value.size()); assertEquals(null, rowValues[16]); assertEquals(null, rowValues[17]); assertEquals(null, rowValues[18]); assertEquals(null, rowValues[19]); assertEquals(null, rowValues[20]); assertEquals(null, rowValues[21]); assertEquals(null, rowValues[22]); // Third row rowValues = rowCollector.rows.get(2); assertEquals(Integer.valueOf(1), rowValues[0]); assertEquals(Boolean.TRUE, rowValues[1]); assertEquals(Double.valueOf(1.1d), rowValues[2]); assertEquals("1", rowValues[3]); c5Value = (List<?>) rowValues[4]; assertEquals(2, c5Value.size()); assertEquals(Integer.valueOf(1), c5Value.get(0)); assertEquals(Integer.valueOf(2), c5Value.get(1)); c6Value = (Map<?, ?>) rowValues[5]; assertEquals(2, c6Value.size()); assertEquals("x", c6Value.get(Integer.valueOf(1))); assertEquals("y", c6Value.get(Integer.valueOf(2))); c7Value = (Map<?, ?>) rowValues[6]; assertEquals(1, c7Value.size()); assertEquals("v", c7Value.get("k")); c8Value = (List<?>) rowValues[7]; assertEquals("a", c8Value.get(0)); assertEquals(Integer.valueOf(9), c8Value.get(1)); assertEquals(Double.valueOf(2.2d), c8Value.get(2)); assertEquals(Byte.valueOf((byte) 1), rowValues[8]); assertEquals(Short.valueOf((short) 1), rowValues[9]); assertEquals(Float.valueOf(1.0f), rowValues[10]); assertEquals(Long.valueOf(1l), rowValues[11]); c13Value = (List<?>) rowValues[12]; assertEquals(2, c13Value.size()); List<?> listVal = (List<?>) c13Value.get(0); assertEquals("a", listVal.get(0)); assertEquals("b", listVal.get(1)); listVal = (List<?>) c13Value.get(1); assertEquals("c", listVal.get(0)); assertEquals("d", listVal.get(1)); c14Value = (Map<?, ?>) rowValues[13]; assertEquals(2, c14Value.size()); Map<?, ?> mapVal = (Map<?, ?>) c14Value.get(Integer.valueOf(1)); assertEquals(2, mapVal.size()); assertEquals(Integer.valueOf(12), mapVal.get(Integer.valueOf(11))); assertEquals(Integer.valueOf(14), mapVal.get(Integer.valueOf(13))); mapVal = (Map<?, ?>) c14Value.get(Integer.valueOf(2)); assertEquals(1, mapVal.size()); assertEquals(Integer.valueOf(22), mapVal.get(Integer.valueOf(21))); c15Value = (List<?>) rowValues[14]; assertEquals(Integer.valueOf(1), c15Value.get(0)); listVal = (List<?>) c15Value.get(1); assertEquals(2, listVal.size()); assertEquals(Integer.valueOf(2), listVal.get(0)); assertEquals("x", listVal.get(1)); c16Value = (List<?>) rowValues[15]; assertEquals(2, c16Value.size()); listVal = (List<?>) c16Value.get(0); assertEquals(2, listVal.size()); mapVal = (Map<?, ?>) listVal.get(0); assertEquals(0, mapVal.size()); assertEquals(Integer.valueOf(1), listVal.get(1)); listVal = (List<?>) c16Value.get(1); mapVal = (Map<?, ?>) listVal.get(0); assertEquals(2, mapVal.size()); assertEquals("b", mapVal.get("a")); assertEquals("d", mapVal.get("c")); assertEquals(Integer.valueOf(2), listVal.get(1)); assertEquals(Timestamp.valueOf("2012-04-22 09:00:00.123456789"), rowValues[16]); assertEquals(new BigDecimal("123456789.123456"), rowValues[17]); assertArrayEquals("abcd".getBytes("UTF-8"), (byte[]) rowValues[18]); assertEquals(Date.valueOf("2013-01-01"), rowValues[19]); assertEquals("abc123", rowValues[20]); assertEquals("abc123 ", rowValues[21]); assertArrayEquals("X'01FF'".getBytes("UTF-8"), (byte[]) rowValues[22]); }
From source file:org.eclipse.birt.data.oda.mongodb.impl.MDbResultSet.java
private static Object tryConvertToDataType(Object value, Class<?> toDataType) throws OdaException { if (value == null || toDataType.isInstance(value)) // already in specified data type return value; try {//from w ww. ja v a 2 s. co m if (value instanceof String) { String stringValue = (String) value; if (toDataType == Integer.class) return Integer.valueOf(stringValue); if (toDataType == Double.class) return Double.valueOf(stringValue); if (toDataType == BigDecimal.class) return new BigDecimal(stringValue); if (toDataType == Boolean.class) return Boolean.valueOf(stringValue); if (toDataType == Date.class) return Date.valueOf(stringValue); if (toDataType == Timestamp.class) return Timestamp.valueOf(stringValue); if (toDataType == byte[].class) return tryConvertToBytes(stringValue); } if (value instanceof java.util.Date) // the object type returned by MongoDB for a Date field { long msTime = ((java.util.Date) value).getTime(); if (toDataType == Date.class) return new Date(msTime); if (toDataType == Timestamp.class) return new Timestamp(msTime); } if (value instanceof BSONTimestamp) { long msTime = ((BSONTimestamp) value).getTime() * 1000L; if (toDataType == Date.class) return new Date(msTime); if (toDataType == Timestamp.class) return new Timestamp(msTime); } if (toDataType == Integer.class) return tryConvertToInteger(value); if (toDataType == Double.class) return tryConvertToDouble(value); if (toDataType == Boolean.class) return tryConvertToBoolean(value); } catch (Exception ex) { String errMsg = Messages.bind(Messages.mDbResultSet_cannotConvertFieldData, new Object[] { DriverUtil.EMPTY_STRING, value, value.getClass().getSimpleName(), toDataType.getSimpleName() }); getLogger().severe(errMsg); OdaException odaEx = new OdaException(errMsg); odaEx.initCause(ex); throw odaEx; } // non-handled data type conversion; return value as is return value; }
From source file:org.apache.fineract.infrastructure.dataqueries.service.ReadReportingServiceImpl.java
private void addParametersToReport(final MasterReport report, final Map<String, String> queryParams, final AppUser runReportAsUser, final StringBuilder errorLog) { try {/*ww w.j a v a2s . c o m*/ final ReportParameterValues rptParamValues = report.getParameterValues(); final ReportParameterDefinition paramsDefinition = report.getParameterDefinition(); /* * only allow integer, long, date and string parameter types and * assume all mandatory - could go more detailed like Pawel did in * Fineract later and could match incoming and pentaho parameters * better... currently assuming they come in ok... and if not an * error */ for (final ParameterDefinitionEntry paramDefEntry : paramsDefinition.getParameterDefinitions()) { final String paramName = paramDefEntry.getName(); if (!((paramName.equals("tenantdb")) || (paramName.equals("tenantUrl")) || (paramName.equals("userhierarchy") || (paramName.equals("username")) || (paramName.equals("password") || (paramName.equals("userid") || (paramName.equals("currencyDigit") || (paramName.equals("showCompanyDetails")))))))) { logger.info("paramName:" + paramName); final String pValue = queryParams.get(paramName); if (StringUtils.isBlank(pValue)) { throw new PlatformDataIntegrityException("error.msg.reporting.error", "Pentaho Parameter: " + paramName + " - not Provided"); } final Class<?> clazz = paramDefEntry.getValueType(); logger.info("addParametersToReport(" + paramName + " : " + pValue + " : " + clazz.getCanonicalName() + ")"); if (clazz.getCanonicalName().equalsIgnoreCase("java.lang.Integer")) { rptParamValues.put(paramName, Integer.parseInt(pValue)); } else if (clazz.getCanonicalName().equalsIgnoreCase("java.lang.Long")) { rptParamValues.put(paramName, Long.parseLong(pValue)); } else if (clazz.getCanonicalName().equalsIgnoreCase("java.sql.Date")) { rptParamValues.put(paramName, Date.valueOf(pValue)); } else { rptParamValues.put(paramName, pValue); } } } // tenant database name and current user's office hierarchy // passed as parameters to allow multitenant penaho reporting // and // data scoping final Connection connection = this.dataSource.getConnection(); final FineractPlatformTenant tenant = ThreadLocalContextUtil.getTenant(); final FineractPlatformTenantConnection tenantConnection = tenant.getConnection(); String tenantUrl; String tenantdb; try { tenantUrl = config.constructProtocol(tenantConnection.getSchemaServer(), tenantConnection.getSchemaServerPort(), tenantConnection.getSchemaName()); ; tenantdb = tenantConnection.getSchemaName(); } finally { connection.close(); } final String userhierarchy = runReportAsUser.getOffice().getHierarchy(); logger.info("db URL:" + tenantUrl + " userhierarchy:" + userhierarchy); logger.info("db name:" + tenantdb + " userhierarchy:" + userhierarchy); rptParamValues.put("tenantdb", tenantdb); rptParamValues.put("userhierarchy", userhierarchy); final Long userid = runReportAsUser.getId(); logger.info("db URL:" + tenantUrl + " userid:" + userid); rptParamValues.put("userid", userid); rptParamValues.put("tenantUrl", tenantUrl); rptParamValues.put("username", tenantConnection.getSchemaUsername()); rptParamValues.put("password", tenantConnection.getSchemaPassword()); rptParamValues.put("currencyDigit", this.configurationDomainService.getCurrencyDigits().longValue()); rptParamValues.put("showCompanyDetails", this.configurationDomainService.getShowCompanyDetails().longValue()); } catch (final Exception e) { logger.error("error.msg.reporting.error:" + e.getMessage(), e.getMessage()); errorLog.append("ReadReportingServiceImpl.addParametersToReport method threw an Exception: " + "Invalid or missing report parameter(s) - " + e.getMessage() + " ---------- "); throw new PlatformDataIntegrityException("error.msg.reporting.error", e.getMessage()); } }
From source file:org.rti.zcore.dar.transfer.access.ImportMshData.java
private static EncounterData createCurrentRegimen(Connection conn, Long siteId, MshPatientMaster mshPatientMaster) throws NumberFormatException, Exception { Form formDef = null;/*ww w . j a v a2 s .c om*/ Long formId = (Long) DynaSiteObjects.getFormNameMap().get("ArtRegimen"); formDef = (Form) DynaSiteObjects.getForms().get(new Long(formId)); ArtRegimen formData = new ArtRegimen(); formData.setSiteId(siteId); formData.setCreatedBy("zepadmin"); formData.setFlowId(formDef.getFlowId()); formData.setFormId(formId); formData.setPatientId(mshPatientMaster.getPatientId()); formData.setSessionPatient(mshPatientMaster.getSessionPatient()); formData.setEvent(mshPatientMaster.getEvent()); formData.setEventId(mshPatientMaster.getEventId()); formData.setEventUuid(mshPatientMaster.getEventUuid()); Integer dateOffset = mshPatientMaster.getDaysToNextAppointment(); Date dateVisit = null; Date initialvisit = DateUtils.toDateSql(mshPatientMaster.getDateTherapyStarted()); if ((mshPatientMaster.getDateOfNextAppointment() != null) && (dateOffset != null)) { Date dateNextAppt = DateUtils.toDateSql(mshPatientMaster.getDateOfNextAppointment()); String datePastVisitStr = DateUtils.createFutureDate(dateNextAppt, 0 - dateOffset); Date datePastVisit = Date.valueOf(datePastVisitStr); if (datePastVisit.getTime() > initialvisit.getTime()) { dateVisit = datePastVisit; } else { dateVisit = initialvisit; } } else { dateVisit = initialvisit; } formData.setDateVisit(dateVisit); if (dateVisit != null) { Timestamp ts = new Timestamp(dateVisit.getTime()); formData.setCreated(ts); formData.setLastModified(ts); } formData.setDate_started(dateVisit); String regimen = mshPatientMaster.getCurrentRegimen(); Integer regimenCode = null; boolean importEncounter = true; if (regimen.equals("R01")) { importEncounter = false; } else if (regimen.equals("R02")) { //1A regimenCode = 1; } else if (regimen.equals("R03")) { //R03 2A 3 regimenCode = 3; } else if (regimen.equals("R04")) { //R04 3A 5 regimenCode = 5; } else if (regimen.equals("R05")) { //R05 3B 6 regimenCode = 6; } else if (regimen.equals("R06")) { //R06 4A 7 regimenCode = 7; } else if (regimen.equals("R07")) { //R07 5A 9 regimenCode = 9; } else if (regimen.equals("R08")) { //R08 5B 10 regimenCode = 10; } else if (regimen.equals("R09")) { //R09 6A 11 regimenCode = 11; } else if (regimen.equals("R10")) { //R10 6B 12 regimenCode = 12; } else if (regimen.equals("R12")) { //R12 7A 13 regimenCode = 13; } else if (regimen.equals("R12")) { //R12 7A 13 regimenCode = 13; } else if (regimen.equals("R13")) { //R13 7B 14 7B (TDF/FTC/EFV) regimenCode = 14; } else if (regimen.equals("R21")) { //R21 PEP 1 21 PEP 1 (AZT/3TC) regimenCode = 21; } else if (regimen.equals("R23")) { //R23 PEP 3 24 regimenCode = 24; } else if (regimen.equals("R26")) { //R26 C1A 36 regimenCode = 36; } else if (regimen.equals("R27")) { //R27 C2A 40 regimenCode = 40; } else if (regimen.equals("R28")) { //R28 C3A 44 regimenCode = 44; } else if (regimen.equals("R29")) { //R29 C3B 45 regimenCode = 45; } else if (regimen.equals("R30")) { //R30 C4A 48 regimenCode = 48; } else if (regimen.equals("R31")) { //R31 C4B 49 regimenCode = 49; } else if (regimen.equals("R32")) { //R32 C4C 50 regimenCode = 50; } else { importEncounter = false; log.debug("Unable to import regimen for patient id" + mshPatientMaster.getPatientId() + " Regimen: " + regimen); } formData.setRegimen_1(regimenCode); if ((mshPatientMaster.getReasonsforChanges() != null) && (!mshPatientMaster.getReasonsforChanges().equals(""))) { Integer reasonForChange = mshPatientMaster.getReasonsforChanges(); String reason = null; switch (reasonForChange) { case 1: reason = "Anemia"; break; case 2: reason = "TB"; break; case 3: reason = "Pregnancy"; break; case 4: reason = "Neuropathy"; break; case 5: reason = "Rash"; break; case 6: reason = "Lipodistrophy"; break; case 7: reason = "fluconazole treatment"; break; case 8: reason = "treatment failure"; break; case 9: reason = "Guideline change"; break; default: break; } formData.setRegimen_change_reason(reason); } EncounterData enc = null; if (importEncounter) { enc = FormDAO.create(conn, formData, formData.getCreatedBy(), formData.getSiteId(), formDef, formData.getFlowId(), null); } return enc; }