List of usage examples for java.lang Class isEnum
public boolean isEnum()
From source file:com.oembedler.moon.graphql.engine.dfs.GraphQLSchemaDfsTraversal.java
public GraphQLType createGraphQLObjectTypeRecursively(DfsContext dfsContext, final Class<?> implClass) { ResolvableTypeAccessor resolvableTypeAccessor = ResolvableTypeAccessor.forClass(implClass); String objectName = resolvableTypeAccessor.getName(); String objectDescription = resolvableTypeAccessor.getDescription(); GraphQLType graphQLObjectType = objectTypeResolverMap.get(implClass); if (!objectTypeNameReferenceMap.containsKey(implClass)) { objectTypeNameReferenceMap.put(implClass, objectName); objectNameTypeReferenceMap.put(objectName, implClass); final List<GraphQLFieldDefinition> graphQLFieldDefinitions = new ArrayList<>(); if (implClass.isEnum()) { graphQLObjectType = buildGraphQLEnumType(dfsContext, resolvableTypeAccessor); } else {/*from ww w .j a v a 2 s. c o m*/ ReflectionUtils.getAllFields(implClass).forEach(field -> { GraphQLFieldDefinition definition = getFieldDefinition(dfsContext, implClass, field); if (definition != null) graphQLFieldDefinitions.add(definition); }); ReflectionUtils.getAllMethods(implClass).forEach(method -> { GraphQLFieldDefinition definition = getMethodDefinition(dfsContext, implClass, method); if (definition != null) graphQLFieldDefinitions.add(definition); }); List<GraphQLType> graphQLInterfaceTypes = Lists.newArrayList(); if (implClass.isInterface()) { if (resolvableTypeAccessor.isGraphQLUnion()) { List<GraphQLType> possibleTypes = new ArrayList<>(); for (Class<?> possibleType : resolvableTypeAccessor.getGraphQLUnionPossibleTypes()) { possibleTypes.add(createGraphQLObjectTypeRecursively(dfsContext, possibleType)); } graphQLObjectType = GraphQLUnionType.newUnionType().name(resolvableTypeAccessor.getName()) .possibleTypes(possibleTypes.toArray(new GraphQLObjectType[possibleTypes.size()])) .typeResolver(new CompleteObjectTreeTypeResolver(objectTypeResolverMap)) .description(resolvableTypeAccessor.getDescription()).build(); graphQLUnionTypeMap.add((GraphQLUnionType) graphQLObjectType); } else { graphQLObjectType = newInterface().name(objectName).description(objectDescription) .fields(graphQLFieldDefinitions) .typeResolver(new CompleteObjectTreeTypeResolver(objectTypeResolverMap)).build(); } } else { ClassUtils.getAllInterfacesForClassAsSet(implClass).forEach(aClass -> { if (isAcceptableInterface(dfsContext, aClass)) { GraphQLType graphQLType = createGraphQLObjectTypeRecursively(dfsContext, aClass); graphQLInterfaceTypes.add(graphQLType); } }); graphQLObjectType = newObject().name(objectName).description(objectDescription) .fields(graphQLFieldDefinitions) .withInterfaces(resolveInterfaceReferences(dfsContext, graphQLInterfaceTypes)).build(); } } objectTypeResolverMap.put(implClass, graphQLObjectType); } else { // reference //if (!implClass.isInterface()) graphQLObjectType = new GraphQLTypeReference(objectName); } return graphQLObjectType; }
From source file:com.github.helenusdriver.driver.impl.DataTypeImpl.java
/** * Infers the data type for the specified field once it has already been * processed for optional and collections. * * @author paouelle/*from w ww .ja v a 2 s. c om*/ * * @param field the non-<code>null</code> field to infer the CQL data type for * @param clazz the non-<code>null</code> class for which to infer the CQL * data type for the field * @param types the non-<code>null</code> list where to add the inferred type and * its arguments * @param persisted the persisted annotation to consider for the field * @throws IllegalArgumentException if the data type cannot be inferred from * the field */ private static void inferBasicDataTypeFrom(Field field, Class<?> clazz, List<CQLDataType> types, Persisted persisted) { if (persisted != null) { types.add(persisted.as()); } else if (String.class == clazz) { types.add(DataType.TEXT); } else if (Integer.class == clazz) { types.add(DataType.INT); } else if (Long.class == clazz) { types.add(DataType.BIGINT); } else if (Boolean.class == clazz) { types.add(DataType.BOOLEAN); } else if (Date.class.isAssignableFrom(clazz)) { types.add(DataType.TIMESTAMP); } else if (Double.class == clazz) { types.add(DataType.DOUBLE); } else if (Float.class == clazz) { types.add(DataType.FLOAT); } else if (UUID.class.isAssignableFrom(clazz)) { types.add(DataType.UUID); } else if ((clazz.isArray() && (Byte.TYPE == clazz.getComponentType())) || ByteBuffer.class.isAssignableFrom(clazz)) { types.add(DataType.BLOB); } else if (BigDecimal.class.isAssignableFrom(clazz)) { types.add(DataType.DECIMAL); } else if (BigInteger.class.isAssignableFrom(clazz)) { types.add(DataType.VARINT); } else if (InetAddress.class.isAssignableFrom(clazz)) { types.add(DataType.INET); } else if (AtomicLong.class.isAssignableFrom(clazz)) { types.add(DataType.COUNTER); } else if (clazz.isEnum()) { types.add(DataType.ASCII); } else if (Class.class == clazz) { types.add(DataType.ASCII); } else if (Locale.class == clazz) { types.add(DataType.ASCII); } else if (ZoneId.class.isAssignableFrom(clazz)) { types.add(DataType.ASCII); } else if (Instant.class == clazz) { types.add(DataType.TIMESTAMP); } else { // check if it is a user-defined type try { final ClassInfoImpl<?> cinfo = (ClassInfoImpl<?>) StatementBuilder.getClassInfo(clazz); org.apache.commons.lang3.Validate.isTrue(cinfo instanceof UDTClassInfoImpl, "unable to infer data type in field: %s", field); types.add((UDTClassInfoImpl<?>) cinfo); } catch (Exception e) { throw new IllegalArgumentException("unable to infer data type in field: " + field, e); } } }
From source file:org.sigmah.server.servlet.exporter.models.Realizer.java
/** * Retrieve the value of the given <code>field</code> for the given * <code>source</code> object. * //from w ww . jav a 2s. c o m * @param <T> * Type of the source object. * @param field * Field to extract. * @param clazz * Class of the source object. * @param source * Object to read from. * @param alreadyRealizedObjects * Set of already handled objects (to avoid infinite recursion). * @param ignores * Set of classes to ignore. * @param parent * Parent object. * @return The value of the given field for the given object. * @throws HibernateException * @throws SecurityException * @throws IllegalAccessException * @throws InvocationTargetException * @throws IllegalArgumentException */ private static <T> Object getFieldValue(final Field field, final Class<T> clazz, final T source, final Map<Object, Object> alreadyRealizedObjects, final Set<Class<?>> ignores, final Object parent) throws HibernateException, SecurityException, IllegalAccessException, InvocationTargetException, IllegalArgumentException { // Avoid trying to modify static fields. // Organization should not be exported. if (Modifier.isStatic(field.getModifiers()) || field.getName().equalsIgnoreCase(ORGANIZATION_FIELD)) { return null; } LOG.trace("\tfield " + field.getName()); final Method getterMethod = getGetterMethod(field, clazz); final Object sourceValue = getterMethod.invoke(source); final Object destinationValue; final Class<?> sourceValueClass = sourceValue != null ? sourceValue.getClass() : null; if (sourceValue instanceof PersistentCollection || sourceValue instanceof HibernateProxy) { Hibernate.initialize(sourceValue); } if (sourceValue == null || sourceValueClass == null) { destinationValue = null; } else if (sourceValue instanceof PersistentBag || sourceValue instanceof PersistentList) { // Turning persistent bags into array lists final ArrayList<Object> list = new ArrayList<Object>(); for (Object value : (PersistentBag) sourceValue) { list.add(realize(value, alreadyRealizedObjects, ignores, parent)); } destinationValue = list; } else if (sourceValue instanceof PersistentSet) { // Turning persistent sets into hash sets final HashSet<Object> set = new HashSet<>(); for (Object value : (PersistentSet) sourceValue) { set.add(realize(value, alreadyRealizedObjects, ignores, parent)); } destinationValue = set; } else if (source instanceof ComputationElement && field.getName().equals(FORMULA_FIELD)) { final Collection<FlexibleElementDTO> elements; if (parent instanceof ProjectModel) { elements = ServerComputations.getAllElementsFromModel((ProjectModel) parent); } else if (parent instanceof OrgUnitModel) { elements = ServerComputations.getAllElementsFromModel((OrgUnitModel) parent); } else { elements = Collections.<FlexibleElementDTO>emptyList(); } destinationValue = Computations.formatRuleForEdition(((ComputationElement) source).getRule(), elements); } else if (ignores.contains(sourceValueClass) || sourceValueClass.getName().startsWith("java.") || sourceValueClass.isEnum()) { // Simple copy if the current field is a jdk type or an enum destinationValue = sourceValue; } else { destinationValue = realize(sourceValue, alreadyRealizedObjects, ignores, parent); } return destinationValue; }
From source file:com.evolveum.midpoint.prism.parser.PrismBeanConverter.java
public void visit(Object bean, Handler<Object> handler) { if (bean == null) { return;/*from w w w . j a v a 2 s . c o m*/ } Class<? extends Object> beanClass = bean.getClass(); handler.handle(bean); if (beanClass.isEnum() || beanClass.isPrimitive()) { //nothing more to do return; } // TODO: implement special handling for RawType, if necessary (it has no XmlType annotation any more) XmlType xmlType = beanClass.getAnnotation(XmlType.class); if (xmlType == null) { // no @XmlType annotation, we are not interested to go any deeper return; } List<String> propOrder = inspector.getPropOrder(beanClass); for (String fieldName : propOrder) { Method getter = inspector.findPropertyGetter(beanClass, fieldName); if (getter == null) { throw new IllegalStateException("No getter for field " + fieldName + " in " + beanClass); } Object getterResult; try { getterResult = getter.invoke(bean); } catch (IllegalAccessException | IllegalArgumentException | InvocationTargetException e) { throw new SystemException( "Cannot invoke method for field " + fieldName + " in " + beanClass + ": " + e.getMessage(), e); } if (getterResult == null) { continue; } if (getterResult instanceof Collection<?>) { Collection col = (Collection) getterResult; if (col.isEmpty()) { continue; } for (Object element : col) { visitValue(element, handler); } } else { visitValue(getterResult, handler); } } }
From source file:org.janusgraph.diskstorage.configuration.backend.CommonsConfiguration.java
@Override public <O> O get(String key, Class<O> datatype) { if (!config.containsKey(key)) return null; if (datatype.isArray()) { Preconditions.checkArgument(datatype.getComponentType() == String.class, "Only string arrays are supported: %s", datatype); return (O) config.getStringArray(key); } else if (Number.class.isAssignableFrom(datatype)) { // A properties file configuration returns Strings even for numeric // values small enough to fit inside Integer (e.g. 5000). In-memory // configuration impls seem to be able to store and return actual // numeric types rather than String //// w w w . java 2 s. c o m // We try to handle either case here Object o = config.getProperty(key); if (datatype.isInstance(o)) { return (O) o; } else { return constructFromStringArgument(datatype, o.toString()); } } else if (datatype == String.class) { return (O) config.getString(key); } else if (datatype == Boolean.class) { return (O) new Boolean(config.getBoolean(key)); } else if (datatype.isEnum()) { Enum[] constants = (Enum[]) datatype.getEnumConstants(); Preconditions.checkState(null != constants && 0 < constants.length, "Zero-length or undefined enum"); String estr = config.getProperty(key).toString(); for (Enum ec : constants) if (ec.toString().equals(estr)) return (O) ec; throw new IllegalArgumentException("No match for string \"" + estr + "\" in enum " + datatype); } else if (datatype == Object.class) { return (O) config.getProperty(key); } else if (Duration.class.isAssignableFrom(datatype)) { // This is a conceptual leak; the config layer should ideally only handle standard library types Object o = config.getProperty(key); if (Duration.class.isInstance(o)) { return (O) o; } else { String[] comps = o.toString().split("\\s"); TemporalUnit unit = null; if (comps.length == 1) { //By default, times are in milli seconds unit = ChronoUnit.MILLIS; } else if (comps.length == 2) { unit = Durations.parse(comps[1]); } else { throw new IllegalArgumentException("Cannot parse time duration from: " + o.toString()); } return (O) Duration.of(Long.valueOf(comps[0]), unit); } // Lists are deliberately not supported. List's generic parameter // is subject to erasure and can't be checked at runtime. Someone // could create a ConfigOption<List<Number>>; we would instead return // a List<String> like we always do at runtime, and it wouldn't break // until the client tried to use the contents of the list. // // We could theoretically get around this by adding a type token to // every declaration of a List-typed ConfigOption, but it's just // not worth doing since we only actually use String[] anyway. // } else if (List.class.isAssignableFrom(datatype)) { // return (O) config.getProperty(key); } else throw new IllegalArgumentException("Unsupported data type: " + datatype); }
From source file:com.gatf.generator.core.GatfTestGeneratorMojo.java
@SuppressWarnings({ "unchecked", "rawtypes" }) private Object getObject(Class claz, List<Type> heirarchies) throws Exception { if (claz.isEnum()) return claz.getEnumConstants()[0]; if (isMap(claz)) { return getMapValue(claz, claz.getTypeParameters(), heirarchies); } else if (isCollection(claz)) { return getListSetValue(claz, claz.getTypeParameters(), heirarchies); } else if (claz.isInterface() || Modifier.isAbstract(claz.getModifiers())) { return null; }/*from w w w. j a v a 2 s . c o m*/ if (heirarchies.contains(claz) || heirarchies.size() >= 2) return null; heirarchies.add(claz); Constructor cons = null; try { cons = claz.getConstructor(new Class[] {}); } catch (Exception e) { getLog().error("No public no-args constructor found for class " + claz.getName()); return null; } Object object = cons.newInstance(new Object[] {}); List<Field> allFields = getAllFields(claz); for (Field field : allFields) { if (Modifier.isStatic(field.getModifiers())) continue; if (!field.isAccessible()) { field.setAccessible(true); } List<Type> fheirlst = new ArrayList<Type>(heirarchies); if (isDebugEnabled()) getLog().info("Parsing Class " + getHeirarchyStr(fheirlst) + " field " + field.getName() + " type " + field.getType().equals(boolean.class)); if (isPrimitive(field.getType())) { field.set(object, getPrimitiveValue(field.getType())); } else if (isMap(field.getType())) { ParameterizedType type = (ParameterizedType) field.getGenericType(); field.set(object, getMapValue(field.getType(), type.getActualTypeArguments(), fheirlst)); } else if (isCollection(field.getType())) { ParameterizedType type = (ParameterizedType) field.getGenericType(); field.set(object, getListSetValue(field.getType(), type.getActualTypeArguments(), fheirlst)); } else if (!claz.equals(field.getType())) { Object fieldval = getObject(field.getType(), fheirlst); field.set(object, fieldval); } else if (claz.equals(field.getType())) { if (isDebugEnabled()) getLog().info("Ignoring recursive fields..."); } } return object; }
From source file:wwutil.jsoda.DataUtil.java
/** Caller should handle custom valueType first before calling this. * E.g. DynamoDB's Set<String> and Set<long> fields are encoded as Multi-Value AttributeValue. *//*w ww . ja v a 2s . c om*/ @SuppressWarnings("unchecked") static String encodeValueToAttrStr(Object value, Class valueType) { if (value == null) return null; // Caller needs to handle null correctly, e.g. skip storing AttributeValue. if (valueType == String.class) return value.toString(); // NOTE: Don't change encoding and padding once data have been created. Different encoding will mess up sorting. // Stringify basic type and encode them for sorting. if (valueType == Byte.class || valueType == byte.class) { Byte casted = (Byte) ConvertUtils.convert(value, Byte.class); return SimpleDBUtils.encodeZeroPadding(casted.intValue(), 3); // 0-Padded for sorting } else if (valueType == Short.class || valueType == short.class) { Short casted = (Short) ConvertUtils.convert(value, Short.class); return SimpleDBUtils.encodeZeroPadding(casted.intValue(), 5); // 0-Padded for sorting } else if (valueType == Integer.class || valueType == int.class) { Integer casted = (Integer) ConvertUtils.convert(value, Integer.class); return SimpleDBUtils.encodeZeroPadding(casted.intValue(), 10); // 0-Padded for sorting } else if (valueType == Long.class || valueType == long.class) { Long casted = (Long) ConvertUtils.convert(value, Long.class); return SimpleDBUtils.encodeZeroPadding(casted.longValue(), 19); // 0-Padded for sorting } else if (valueType == Float.class || valueType == float.class) { Float casted = (Float) ConvertUtils.convert(value, Float.class); return SimpleDBUtils.encodeZeroPadding(casted.floatValue(), 16); // 0-Padded for sorting } else if (valueType == Double.class || valueType == double.class) { // SimpleDBUtils has no padding for double. Just convert it to String. return value.toString(); } else if (valueType == Boolean.class || valueType == boolean.class) { return value.toString(); } else if (valueType == Character.class || valueType == char.class) { return value.toString(); } else if (valueType == Date.class) { return SimpleDBUtils.encodeDate((Date) value); } else if (valueType.isEnum()) { return ((Enum) value).name(); } // JSONify the rest. return toJson(value); }
From source file:org.openmrs.util.ReportingcompatibilityUtil.java
/** * Uses reflection to translate a PatientSearch into a PatientFilter *//*from w ww . java 2 s.c o m*/ @SuppressWarnings("unchecked") public static PatientFilter toPatientFilter(PatientSearch search, CohortSearchHistory history, EvaluationContext evalContext) { if (search.isSavedSearchReference()) { PatientSearch ps = ((PatientSearchReportObject) Context.getService(ReportObjectService.class) .getReportObject(search.getSavedSearchId())).getPatientSearch(); return toPatientFilter(ps, history, evalContext); } else if (search.isSavedFilterReference()) { return Context.getService(ReportObjectService.class).getPatientFilterById(search.getSavedFilterId()); } else if (search.isSavedCohortReference()) { Cohort c = Context.getCohortService().getCohort(search.getSavedCohortId()); // to prevent lazy loading exceptions, cache the member ids here if (c != null) { c.getMemberIds().size(); } return new CohortFilter(c); } else if (search.isComposition()) { if (history == null && search.requiresHistory()) { throw new IllegalArgumentException("You can't evaluate this search without a history"); } else { return search.cloneCompositionAsFilter(history, evalContext); } } else { Class clz = search.getFilterClass(); if (clz == null) { throw new IllegalArgumentException( "search must be saved, composition, or must have a class specified"); } log.debug("About to instantiate " + clz); PatientFilter pf = null; try { pf = (PatientFilter) clz.newInstance(); } catch (Exception ex) { log.error("Couldn't instantiate a " + search.getFilterClass(), ex); return null; } Class[] stringSingleton = { String.class }; if (search.getArguments() != null) { for (SearchArgument sa : search.getArguments()) { if (log.isDebugEnabled()) { log.debug("Looking at (" + sa.getPropertyClass() + ") " + sa.getName() + " -> " + sa.getValue()); } PropertyDescriptor pd = null; try { pd = new PropertyDescriptor(sa.getName(), clz); } catch (IntrospectionException ex) { log.error("Error while examining property " + sa.getName(), ex); continue; } Class<?> realPropertyType = pd.getPropertyType(); // instantiate the value of the search argument String valueAsString = sa.getValue(); String testForExpression = search.getArgumentValue(sa.getName()); if (testForExpression != null) { log.debug("Setting " + sa.getName() + " to: " + testForExpression); if (evalContext != null && EvaluationContext.isExpression(testForExpression)) { Object evaluated = evalContext.evaluateExpression(testForExpression); if (evaluated != null) { if (evaluated instanceof Date) { valueAsString = Context.getDateFormat().format((Date) evaluated); } else { valueAsString = evaluated.toString(); } } log.debug("Evaluated " + sa.getName() + " to: " + valueAsString); } } Object value = null; Class<?> valueClass = sa.getPropertyClass(); try { // If there's a valueOf(String) method, just use that // (will cover at least String, Integer, Double, // Boolean) Method valueOfMethod = null; try { valueOfMethod = valueClass.getMethod("valueOf", stringSingleton); } catch (NoSuchMethodException ex) { } if (valueOfMethod != null) { Object[] holder = { valueAsString }; value = valueOfMethod.invoke(pf, holder); } else if (realPropertyType.isEnum()) { // Special-case for enum types List<Enum> constants = Arrays.asList((Enum[]) realPropertyType.getEnumConstants()); for (Enum e : constants) { if (e.toString().equals(valueAsString)) { value = e; break; } } } else if (String.class.equals(valueClass)) { value = valueAsString; } else if (Location.class.equals(valueClass)) { LocationEditor ed = new LocationEditor(); ed.setAsText(valueAsString); value = ed.getValue(); } else if (Concept.class.equals(valueClass)) { ConceptEditor ed = new ConceptEditor(); ed.setAsText(valueAsString); value = ed.getValue(); } else if (Program.class.equals(valueClass)) { ProgramEditor ed = new ProgramEditor(); ed.setAsText(valueAsString); value = ed.getValue(); } else if (ProgramWorkflowState.class.equals(valueClass)) { ProgramWorkflowStateEditor ed = new ProgramWorkflowStateEditor(); ed.setAsText(valueAsString); value = ed.getValue(); } else if (EncounterType.class.equals(valueClass)) { EncounterTypeEditor ed = new EncounterTypeEditor(); ed.setAsText(valueAsString); value = ed.getValue(); } else if (Form.class.equals(valueClass)) { FormEditor ed = new FormEditor(); ed.setAsText(valueAsString); value = ed.getValue(); } else if (Drug.class.equals(valueClass)) { DrugEditor ed = new DrugEditor(); ed.setAsText(valueAsString); value = ed.getValue(); } else if (PersonAttributeType.class.equals(valueClass)) { PersonAttributeTypeEditor ed = new PersonAttributeTypeEditor(); ed.setAsText(valueAsString); value = ed.getValue(); } else if (Cohort.class.equals(valueClass)) { CohortEditor ed = new CohortEditor(); ed.setAsText(valueAsString); value = ed.getValue(); } else if (Date.class.equals(valueClass)) { // TODO: this uses the date format from the current // session, which could cause problems if the user // changes it after searching. DateFormat df = Context.getDateFormat(); // new // SimpleDateFormat(OpenmrsConstants.OPENMRS_LOCALE_DATE_PATTERNS().get(Context.getLocale().toString().toLowerCase()), // Context.getLocale()); CustomDateEditor ed = new CustomDateEditor(df, true, 10); ed.setAsText(valueAsString); value = ed.getValue(); } else if (LogicCriteria.class.equals(valueClass)) { value = Context.getLogicService().parseString(valueAsString); } else { // TODO: Decide whether this is a hack. Currently // setting Object arguments with a String value = valueAsString; } } catch (Exception ex) { log.error("error converting \"" + valueAsString + "\" to " + valueClass, ex); continue; } if (value != null) { if (realPropertyType.isAssignableFrom(valueClass)) { log.debug("setting value of " + sa.getName() + " to " + value); try { pd.getWriteMethod().invoke(pf, value); } catch (Exception ex) { log.error("Error setting value of " + sa.getName() + " to " + sa.getValue() + " -> " + value, ex); continue; } } else if (Collection.class.isAssignableFrom(realPropertyType)) { log.debug(sa.getName() + " is a Collection property"); // if realPropertyType is a collection, add this // value to it (possibly after instantiating) try { Collection collection = (Collection) pd.getReadMethod().invoke(pf, (Object[]) null); if (collection == null) { // we need to instantiate this collection. // I'm going with the following rules, which // should be rethought: // SortedSet -> TreeSet // Set -> HashSet // Otherwise -> ArrayList if (SortedSet.class.isAssignableFrom(realPropertyType)) { collection = new TreeSet(); log.debug("instantiated a TreeSet"); pd.getWriteMethod().invoke(pf, collection); } else if (Set.class.isAssignableFrom(realPropertyType)) { collection = new HashSet(); log.debug("instantiated a HashSet"); pd.getWriteMethod().invoke(pf, collection); } else { collection = new ArrayList(); log.debug("instantiated an ArrayList"); pd.getWriteMethod().invoke(pf, collection); } } collection.add(value); } catch (Exception ex) { log.error("Error instantiating collection for property " + sa.getName() + " whose class is " + realPropertyType, ex); continue; } } else { log.error(pf.getClass() + " . " + sa.getName() + " should be " + realPropertyType + " but is given as " + valueClass); } } } } log.debug("Returning " + pf); return pf; } }
From source file:org.springframework.jdbc.support.JdbcUtils.java
/** * Retrieve a JDBC column value from a ResultSet, using the specified value type. * <p>Uses the specifically typed ResultSet accessor methods, falling back to * {@link #getResultSetValue(java.sql.ResultSet, int)} for unknown types. * <p>Note that the returned value may not be assignable to the specified * required type, in case of an unknown type. Calling code needs to deal * with this case appropriately, e.g. throwing a corresponding exception. * @param rs is the ResultSet holding the data * @param index is the column index/*from w w w. j a v a 2 s.co m*/ * @param requiredType the required value type (may be {@code null}) * @return the value object (possibly not of the specified required type, * with further conversion steps necessary) * @throws SQLException if thrown by the JDBC API * @see #getResultSetValue(ResultSet, int) */ @Nullable public static Object getResultSetValue(ResultSet rs, int index, @Nullable Class<?> requiredType) throws SQLException { if (requiredType == null) { return getResultSetValue(rs, index); } Object value; // Explicitly extract typed value, as far as possible. if (String.class == requiredType) { return rs.getString(index); } else if (boolean.class == requiredType || Boolean.class == requiredType) { value = rs.getBoolean(index); } else if (byte.class == requiredType || Byte.class == requiredType) { value = rs.getByte(index); } else if (short.class == requiredType || Short.class == requiredType) { value = rs.getShort(index); } else if (int.class == requiredType || Integer.class == requiredType) { value = rs.getInt(index); } else if (long.class == requiredType || Long.class == requiredType) { value = rs.getLong(index); } else if (float.class == requiredType || Float.class == requiredType) { value = rs.getFloat(index); } else if (double.class == requiredType || Double.class == requiredType || Number.class == requiredType) { value = rs.getDouble(index); } else if (BigDecimal.class == requiredType) { return rs.getBigDecimal(index); } else if (java.sql.Date.class == requiredType) { return rs.getDate(index); } else if (java.sql.Time.class == requiredType) { return rs.getTime(index); } else if (java.sql.Timestamp.class == requiredType || java.util.Date.class == requiredType) { return rs.getTimestamp(index); } else if (byte[].class == requiredType) { return rs.getBytes(index); } else if (Blob.class == requiredType) { return rs.getBlob(index); } else if (Clob.class == requiredType) { return rs.getClob(index); } else if (requiredType.isEnum()) { // Enums can either be represented through a String or an enum index value: // leave enum type conversion up to the caller (e.g. a ConversionService) // but make sure that we return nothing other than a String or an Integer. Object obj = rs.getObject(index); if (obj instanceof String) { return obj; } else if (obj instanceof Number) { // Defensively convert any Number to an Integer (as needed by our // ConversionService's IntegerToEnumConverterFactory) for use as index return NumberUtils.convertNumberToTargetClass((Number) obj, Integer.class); } else { // e.g. on Postgres: getObject returns a PGObject but we need a String return rs.getString(index); } } else { // Some unknown type desired -> rely on getObject. try { return rs.getObject(index, requiredType); } catch (AbstractMethodError err) { logger.debug("JDBC driver does not implement JDBC 4.1 'getObject(int, Class)' method", err); } catch (SQLFeatureNotSupportedException ex) { logger.debug("JDBC driver does not support JDBC 4.1 'getObject(int, Class)' method", ex); } catch (SQLException ex) { logger.debug("JDBC driver has limited support for JDBC 4.1 'getObject(int, Class)' method", ex); } // Corresponding SQL types for JSR-310 / Joda-Time types, left up // to the caller to convert them (e.g. through a ConversionService). String typeName = requiredType.getSimpleName(); if ("LocalDate".equals(typeName)) { return rs.getDate(index); } else if ("LocalTime".equals(typeName)) { return rs.getTime(index); } else if ("LocalDateTime".equals(typeName)) { return rs.getTimestamp(index); } // Fall back to getObject without type specification, again // left up to the caller to convert the value if necessary. return getResultSetValue(rs, index); } // Perform was-null check if necessary (for results that the JDBC driver returns as primitives). return (rs.wasNull() ? null : value); }
From source file:org.obsidian.test.TestAbstract.java
public <T> void appendDynamicImports(Class<T> classToImport) { boolean shouldBeIgnored = false; //Make sure: not already in dynamic imports for (String s : getDynamicImports()) { if (s.compareToIgnoreCase(classToImport.getName().replaceAll("\\$", ".")) == 0) { shouldBeIgnored = true;/*w w w .j ava2 s . c o m*/ } } if (!classToImport.isPrimitive() && !classToImport.isArray()) { //make sure: not in imports from constants for (String s : Content.IMPORTS) { if (s.compareToIgnoreCase(classToImport.getName()) == 0) { shouldBeIgnored = true; } } //make sure: not in same package if (classToImport.getPackage().toString() .compareToIgnoreCase(classTested.getPackage().toString()) == 0) { //#### Patch Submitted by Michael Cole (micole.3@gmail.com) 2/13/13 if (!(classToImport.isMemberClass() || classToImport.isEnum() || classToImport.isLocalClass())) { shouldBeIgnored = true; } } //make sure not private if (Modifier.isPrivate(classToImport.getModifiers())) { shouldBeIgnored = true; } //make sure: not importing from java.lang unless at least 3 deep //ex)java.lang.reflect String[] packageStructure = classToImport.getPackage().getName().split("\\."); int packageDepth = packageStructure.length; //if dataInputStream java.lang if (packageStructure[0].compareToIgnoreCase("java") == 0 && packageStructure[1].compareToIgnoreCase("lang") == 0) { //and less than three deep if (packageDepth < 3) { shouldBeIgnored = true; classToImport.getName(); } } } else { shouldBeIgnored = true; if (classToImport.isArray() && !classToImport.getComponentType().isPrimitive()) { appendDynamicImports(classToImport.getComponentType()); } } //if: not already in imports and not in same package if (!shouldBeIgnored) { //add to dynamic imports String importName = classToImport.getName(); importName = importName.replaceAll("\\$", "."); getDynamicImports().add(importName); } }