/*
@see FieldConversion#sqlToJava(Object)
188210
public Object sqlToJava(Object source)
    {
        if (source instanceof java.sql.Timestamp)
        {
         	return new java.util.Date( ((java.sql.Timestamp) source).getTime());  
        }
        else
        {
         	return source;   
        }
    }
1279608
@Override
	public Object toJdbc(final Enum<?> original, final Connection connection,
			final BindParameterMapperManager parameterMapperManager) {
		return original.toString();
	}
495728
private ByteBuffer toColumnName(Object obj) {
        SimpleCompositeBuilder composite = new SimpleCompositeBuilder(bufferSize, Equality.EQUAL);

        // Iterate through each component and add to a CompositeType structure
        for (FieldMapper<?> mapper : components) {
            try {
                composite.addWithoutControl(mapper.toByteBuffer(obj));
            }
            catch (Exception e) {
                throw new RuntimeException(e);
            }
        }
        return composite.get();
    }
401760
@Override
	public StringBuilder sqlBuilder() {
		StringBuilder builder = this.sqlStringBuilder.get();
		builder.delete(0, builder.length());

		return builder;
	}
642125
@Override
	public void generateSpecializedPart(SQLiteModelMethod method, TypeSpec.Builder classBuilder, MethodSpec.Builder methodBuilder, Set<JQLProjection> fieldList, boolean mapFields) {
		//ASSERT: returnType is a supported type
		
		// no column or too many columns
		AssertKripton.assertTrueOrInvalidMethodSignException(fieldList.size() == 1, method, "only one field can be defined as result for this method");				

		ParameterizedTypeName returnListName = (ParameterizedTypeName) method.getReturnClass();;

		TypeName collectionClass;
		ClassName listClazzName = returnListName.rawType;
		TypeName elementName = returnListName.typeArguments.get(0);

		collectionClass = SqlUtility.defineCollection(listClazzName);

		methodBuilder.addCode("\n");
		
		if (TypeUtility.isTypeEquals(collectionClass, TypeUtility.typeName(ArrayList.class))) {			
			methodBuilder.addStatement("$T<$T> resultList=new $T<$T>(_cursor.getCount())", collectionClass, elementName, collectionClass, elementName);
		} else {			
			methodBuilder.addStatement("$T<$T> resultList=new $T<$T>()", collectionClass, elementName, collectionClass, elementName);
		}
		methodBuilder.addCode("\n");
		
		SQLTransform t=SQLTransformer.lookup(returnListName);

		//@formatter:off
		methodBuilder.addCode("\n");
			methodBuilder.beginControlFlow("if (_cursor.moveToFirst())");
				methodBuilder.addCode("\n");
				methodBuilder.beginControlFlow("do\n");
					methodBuilder.beginControlFlow("if (!_cursor.isNull(0))");
						methodBuilder.addCode("resultList.add(");
						t.generateReadValueFromCursor(methodBuilder, method.getParent(), elementName, "_cursor", "0");
						methodBuilder.addCode(");\n");
					methodBuilder.nextControlFlow("else");
						methodBuilder.addCode("resultList.add(null);\n");		
					methodBuilder.endControlFlow();
				methodBuilder.endControlFlow("while (_cursor.moveToNext())");
			methodBuilder.endControlFlow();
			methodBuilder.addCode("return resultList;\n");
		methodBuilder.endControlFlow();
		//@formatter:on

	}
571136
public static java.sql.Time toTime(final Object value) {
		if (value == null) {
			return null;
		}
		if (value instanceof java.sql.Time) {
			return (java.sql.Time) value;
		}
		if (value instanceof java.util.Date) {
			final Date date = (java.util.Date) value;
			return new java.sql.Time(date.getTime());
		}
		return null;
	}
660038
static SplittedSql generateSQL(final SQLiteModelMethod method, MethodSpec.Builder methodBuilder, final boolean replaceProjectedColumns) {
		JQLChecker jqlChecker = JQLChecker.getInstance();

		final SplittedSql splittedSql = new SplittedSql();

		String sql = convertJQL2SQL(method, false);

		// parameters extracted from JQL converted in SQL
		splittedSql.sqlBasic = jqlChecker.replaceVariableStatements(method, sql, new JQLReplaceVariableStatementListenerImpl() {

			@Override
			public String onWhere(String statement) {
				splittedSql.sqlWhereStatement = statement;
				return "";
			}

			@Override
			public String onOrderBy(String statement) {
				splittedSql.sqlOrderByStatement = statement;
				return "";
			}

			@Override
			public String onOffset(String statement) {
				splittedSql.sqlOffsetStatement = statement;
				return "";
			}

			@Override
			public String onLimit(String statement) {
				splittedSql.sqlLimitStatement = statement;
				return "";
			}

			@Override
			public String onHaving(String statement) {
				splittedSql.sqlHavingStatement = statement;
				return "";
			}

			@Override
			public String onGroup(String statement) {
				splittedSql.sqlGroupStatement = statement;
				return "";
			}

			@Override
			public String onProjectedColumns(String statement) {
				if (replaceProjectedColumns)
					return "%s";
				else
					return null;
			}
		});

		return splittedSql;
	}
1168442
private void setParameterObject(final PreparedStatement preparedStatement, final int parameterIndex,
			final Object param, final BindParameterMapperManager parameterMapperManager) throws SQLException {
		//JDBCの受け付ける型に変換
		Object jdbcParam = parameterMapperManager.toJdbc(param, preparedStatement.getConnection());
		if (Objects.equals(sqlType, SQL_TYPE_NOT_SET)) {
			if (jdbcParam instanceof java.sql.Array) {
				preparedStatement.setArray(parameterIndex, (java.sql.Array) jdbcParam);
			} else {
				preparedStatement.setObject(parameterIndex, jdbcParam);
			}
		} else {
			int targetSqlType = sqlType.getVendorTypeNumber();//各JDBCの対応状況が怪しいのでintで扱う
			if (jdbcParam != null) {
				if (jdbcParam instanceof java.sql.Array) {
					preparedStatement.setArray(parameterIndex, (java.sql.Array) jdbcParam);
				} else {
					preparedStatement.setObject(parameterIndex, jdbcParam, targetSqlType);
				}
			} else {
				preparedStatement.setNull(parameterIndex, targetSqlType);
			}
		}
	}
289405
private void generateQuery(SQLiteDatabaseSchema schema) {
		MethodSpec.Builder methodBuilder = MethodSpec.methodBuilder("query").addModifiers(Modifier.PUBLIC).addAnnotation(Override.class).returns(Cursor.class);
		methodBuilder.addParameter(Uri.class, "uri");
		methodBuilder.addParameter(ParameterSpec.builder(TypeUtility.arrayTypeName(String.class), "projection").build());
		methodBuilder.addParameter(String.class, "selection");
		methodBuilder.addParameter(ParameterSpec.builder(TypeUtility.arrayTypeName(String.class), "selectionArgs").build());
		methodBuilder.addParameter(String.class, "sortOrder");

		boolean hasOperation = hasOperationOfType(schema, methodBuilder, JQLType.SELECT);

		if (!hasOperation) {
			methodBuilder.addStatement("throw new $T(\"Unknown URI for $L operation: \" + uri)", IllegalArgumentException.class, JQLType.SELECT);
			classBuilder.addMethod(methodBuilder.build());
			return;
		}

		methodBuilder.addStatement("$T returnCursor=null", Cursor.class);

		for (SQLiteDaoDefinition daoDefinition : schema.getCollection()) {
			for (SQLiteModelMethod daoMethod : daoDefinition.getCollection()) {
				if (daoMethod.jql.operationType != JQLType.SELECT)
					continue;
				// methodBuilder.addJavadoc("method $L.$L\n",
				// daoDefinition.getName(), daoMethod.getName());
			}
		}

		defineJavadocHeaderForContentOperation(methodBuilder, "query");

		methodBuilder.beginControlFlow("switch (sURIMatcher.match(uri))");
		for (Entry<String, ContentEntry> item : uriSet.entrySet()) {
			if (item.getValue().select == null)
				continue;

			defineJavadocForContentUri(methodBuilder, item.getValue().select);

			// methodBuilder.addJavadoc("uri $L\n", item.getKey());

			methodBuilder.beginControlFlow("case $L:", item.getValue().pathIndex);
			methodBuilder.addCode("// URI: $L\n", item.getValue().select.contentProviderUri());
			methodBuilder.addStatement("returnCursor=dataSource.get$L().$L(uri, projection, selection, selectionArgs, sortOrder)", item.getValue().select.getParent().getName(),
					item.getValue().select.contentProviderMethodName);
			methodBuilder.addStatement("break");
			methodBuilder.endControlFlow();
		}
		methodBuilder.beginControlFlow("default:");
		methodBuilder.addStatement("throw new $T(\"Unknown URI for $L operation: \" + uri)", IllegalArgumentException.class, JQLType.SELECT);
		methodBuilder.endControlFlow();

		methodBuilder.endControlFlow();

		defineJavadocFooterForContentOperation(methodBuilder);

		if (hasOperation) {
			methodBuilder.addStatement("return returnCursor");
		}

		classBuilder.addMethod(methodBuilder.build());
	}
259608
public <FV> FV getFieldValueIfNotDefault(Object object) throws SQLException {
		@SuppressWarnings("unchecked")
		FV fieldValue = (FV) extractJavaFieldValue(object);
		if (isFieldValueDefault(fieldValue)) {
			return null;
		} else {
			return fieldValue;
		}
	}
474879
public Object extractJavaFieldValue(Object object) throws SQLException {

		Object val = extractRawJavaFieldValue(object);

		// if this is a foreign object then we want its reference field
		if (foreignRefField != null && val != null) {
			val = foreignRefField.extractRawJavaFieldValue(val);
		}

		return val;
	}
560048
public Object convertSQLToJavaGMT(SessionInterface session, Object a) {

        long millis;

        switch (typeCode) {

            case Types.SQL_TIME :
            case Types.SQL_TIME_WITH_TIME_ZONE :
                millis = ((TimeData) a).getSeconds() * 1000;

                return new java.sql.Time(millis);

            case Types.SQL_DATE :
                millis = ((TimestampData) a).getSeconds() * 1000;

                return new java.sql.Date(millis);

            case Types.SQL_TIMESTAMP :
            case Types.SQL_TIMESTAMP_WITH_TIME_ZONE :
                millis = ((TimestampData) a).getSeconds() * 1000;

                java.sql.Timestamp value = new java.sql.Timestamp(millis);

                value.setNanos(((TimestampData) a).getNanos());

                return value;

            default :
                throw Error.runtimeError(ErrorCode.U_S0500, "DateTimeType");
        }
    }
365746
@Override
  public Iterable<JsonObject> convertRecord(JsonArray outputSchema, String inputRecord, WorkUnitState workUnit)
      throws DataConversionException {
    try {
      String strDelimiter = workUnit.getProp(ConfigurationKeys.CONVERTER_CSV_TO_JSON_DELIMITER);
      if (Strings.isNullOrEmpty(strDelimiter)) {
        throw new IllegalArgumentException("Delimiter cannot be empty");
      }
      InputStreamCSVReader reader = new InputStreamCSVReader(inputRecord, strDelimiter.charAt(0),
          workUnit.getProp(ConfigurationKeys.CONVERTER_CSV_TO_JSON_ENCLOSEDCHAR, ConfigurationKeys.DEFAULT_CONVERTER_CSV_TO_JSON_ENCLOSEDCHAR).charAt(0));
      List<String> recordSplit;
      recordSplit = Lists.newArrayList(reader.splitRecord());
      JsonObject outputRecord = new JsonObject();

      for (int i = 0; i < outputSchema.size(); i++) {
        if (i < recordSplit.size()) {
          if (recordSplit.get(i) == null) {
            outputRecord.add(outputSchema.get(i).getAsJsonObject().get("columnName").getAsString(), JsonNull.INSTANCE);
          } else if (recordSplit.get(i).isEmpty() || recordSplit.get(i).toLowerCase().equals(NULL)) {
            outputRecord.add(outputSchema.get(i).getAsJsonObject().get("columnName").getAsString(), JsonNull.INSTANCE);
          } else {
            outputRecord.addProperty(outputSchema.get(i).getAsJsonObject().get("columnName").getAsString(), recordSplit.get(i));
          }
        } else {
          outputRecord.add(outputSchema.get(i).getAsJsonObject().get("columnName").getAsString(), JsonNull.INSTANCE);
        }
      }

      return new SingleRecordIterable<>(outputRecord);
    } catch (Exception e) {
      throw new DataConversionException(e);
    }
  }
808616
public Object sqlToJava(Object source)
    {
        try
        {
            ByteArrayInputStream stringIn =
                new ByteArrayInputStream(((String) source).getBytes());
            Base64.InputStream uuIn =
                new Base64.InputStream(stringIn, Base64.DECODE, false);
            GZIPInputStream gzipIn = new GZIPInputStream(uuIn);
            ObjectInputStream objIn = new ObjectInputStream(gzipIn);
            Object result = objIn.readObject();

            objIn.close();
            return result;
        }
        catch (Throwable t)
        {
            throw new ConversionException(t);
        }
    }
767569
public static Object convertToJava(Value value) {
        switch (value.getType()) {
            case STRING:
                return ((StringValue) value).get();
            case BOOLEAN:
                return ((BooleanValue) value).get();
            case NUMBER:
                return ((NumberValue) value).get();
            case DATE:
                return ((DateValue) value).get();
            case NIL:
                return null;
            case OBJECT:
                return value.get();
        }
        throw new CommandExecutionException("Could not convert value " + value + " to an equivalent Java object");
    }
76509
private void convertValue() throws JspException {

        if ((type == null) || (type.equalsIgnoreCase(TIMESTAMP_TYPE))) {
            if (!(value instanceof java.sql.Timestamp)) {
                value = new java.sql.Timestamp(value.getTime());
            }
        } else if (type.equalsIgnoreCase(TIME_TYPE)) {
            if (!(value instanceof java.sql.Time)) {
                value = new java.sql.Time(value.getTime());
            }
        } else if (type.equalsIgnoreCase(DATE_TYPE)) {
            if (!(value instanceof java.sql.Date)) {
                value = new java.sql.Date(value.getTime());
            }
        } else {
            throw new JspException(
                    Resources.getMessage("SQL_DATE_PARAM_INVALID_TYPE", type));
        }
    }
721226
public Object sqlToJava(Object source)
    {
        if (source instanceof Integer)
        {
            if (source.equals(I_TRUE))
            {
                return Boolean.TRUE;
            }
            else
            {
                return Boolean.FALSE;
            }
        }
        else
        {
            return source;
        }
    }