List of usage examples for java.lang Class isEnum
public boolean isEnum()
From source file:com.alibaba.fastjson.parser.ParserConfig.java
public ObjectDeserializer getDeserializer(Class<?> clazz, Type type) { ObjectDeserializer derializer = deserializers.get(type); if (derializer != null) { return derializer; }// ww w.j ava 2 s . co m if (type == null) { type = clazz; } derializer = deserializers.get(type); if (derializer != null) { return derializer; } { JSONType annotation = TypeUtils.getAnnotation(clazz, JSONType.class); if (annotation != null) { Class<?> mappingTo = annotation.mappingTo(); if (mappingTo != Void.class) { return getDeserializer(mappingTo, mappingTo); } } } if (type instanceof WildcardType || type instanceof TypeVariable || type instanceof ParameterizedType) { derializer = deserializers.get(clazz); } if (derializer != null) { return derializer; } String className = clazz.getName(); className = className.replace('$', '.'); if (className.startsWith("java.awt.") // && AwtCodec.support(clazz)) { if (!awtError) { String[] names = new String[] { "java.awt.Point", "java.awt.Font", "java.awt.Rectangle", "java.awt.Color" }; try { for (String name : names) { if (name.equals(className)) { deserializers.put(Class.forName(name), derializer = AwtCodec.instance); return derializer; } } } catch (Throwable e) { // skip awtError = true; } derializer = AwtCodec.instance; } } if (!jdk8Error) { try { if (className.startsWith("java.time.")) { String[] names = new String[] { "java.time.LocalDateTime", "java.time.LocalDate", "java.time.LocalTime", "java.time.ZonedDateTime", "java.time.OffsetDateTime", "java.time.OffsetTime", "java.time.ZoneOffset", "java.time.ZoneRegion", "java.time.ZoneId", "java.time.Period", "java.time.Duration", "java.time.Instant" }; for (String name : names) { if (name.equals(className)) { deserializers.put(Class.forName(name), derializer = Jdk8DateCodec.instance); return derializer; } } } else if (className.startsWith("java.util.Optional")) { String[] names = new String[] { "java.util.Optional", "java.util.OptionalDouble", "java.util.OptionalInt", "java.util.OptionalLong" }; for (String name : names) { if (name.equals(className)) { deserializers.put(Class.forName(name), derializer = OptionalCodec.instance); return derializer; } } } } catch (Throwable e) { // skip jdk8Error = true; } } if (className.equals("java.nio.file.Path")) { deserializers.put(clazz, derializer = MiscCodec.instance); } if (clazz == Map.Entry.class) { deserializers.put(clazz, derializer = MiscCodec.instance); } final ClassLoader classLoader = Thread.currentThread().getContextClassLoader(); try { for (AutowiredObjectDeserializer autowired : ServiceLoader.load(AutowiredObjectDeserializer.class, classLoader)) { for (Type forType : autowired.getAutowiredFor()) { deserializers.put(forType, autowired); } } } catch (Exception ex) { // skip } if (derializer == null) { derializer = deserializers.get(type); } if (derializer != null) { return derializer; } if (clazz.isEnum()) { Class<?> deserClass = null; JSONType jsonType = clazz.getAnnotation(JSONType.class); if (jsonType != null) { deserClass = jsonType.deserializer(); try { derializer = (ObjectDeserializer) deserClass.newInstance(); deserializers.put(clazz, derializer); return derializer; } catch (Throwable error) { // skip } } derializer = new EnumDeserializer(clazz); } else if (clazz.isArray()) { derializer = ObjectArrayCodec.instance; } else if (clazz == Set.class || clazz == HashSet.class || clazz == Collection.class || clazz == List.class || clazz == ArrayList.class) { derializer = CollectionCodec.instance; } else if (Collection.class.isAssignableFrom(clazz)) { derializer = CollectionCodec.instance; } else if (Map.class.isAssignableFrom(clazz)) { derializer = MapDeserializer.instance; } else if (Throwable.class.isAssignableFrom(clazz)) { derializer = new ThrowableDeserializer(this, clazz); } else if (PropertyProcessable.class.isAssignableFrom(clazz)) { derializer = new PropertyProcessableDeserializer((Class<PropertyProcessable>) clazz); } else { derializer = createJavaBeanDeserializer(clazz, type); } putDeserializer(type, derializer); return derializer; }
From source file:org.openehr.am.validation.ArchetypeValidator.java
private void validateCAttribute(CAttribute cattr, Map<String, Class> rmAttrs, CComplexObject parent, Archetype archetype, List<ValidationError> errors) throws RMInspectionException { String rmAttrName = cattr.getRmAttributeName(); Class rmAttrType = rmAttrs.get(rmAttrName); Set<String> rmAttrNames = rmAttrs.keySet(); ValidationError error = null;/*from ww w.ja va 2s. c o m*/ String parentRmClassName = parent.getRmTypeName(); parentRmClassName = removeGenericTypes(parentRmClassName); String parentGenericTypeName = getGenericType(parent.getRmTypeName()); log.debug("Generic type name: " + parentGenericTypeName); Class parentRmClass = rmInspector.retrieveRMType(parentRmClassName); Class parentGenericType = null; if (parentGenericTypeName != null) { parentGenericType = rmInspector.retrieveRMType(parentGenericTypeName); } // replace primitive types with object types if (int.class.equals(rmAttrType)) { rmAttrType = Integer.class; } else if (double.class.equals(rmAttrType)) { rmAttrType = Double.class; } else if (boolean.class.equals(rmAttrType)) { rmAttrType = Boolean.class; } log.debug("1- validating attribute [" + rmAttrName + "] of type [" + rmAttrType + "]"); if (!rmAttrNames.contains(rmAttrName)) { // if it is a commonly constrained functional property, only show this as information according to validator setting. if (reportConstraintsOnCommonFunctionalPropertiesAsInfo && isCommonFunctionalProperty(rmAttrName, parent.getRmTypeName())) { error = new ValidationError(ErrorType.ICARM, null, rmAttrName, cattr.path(), parent.getRmTypeName()); } else { error = new ValidationError(ErrorType.VCARM, null, rmAttrName, parent.getRmTypeName(), cattr.path()); } errors.add(error); return; } if (cattr instanceof CMultipleAttribute) { CMultipleAttribute cmattr = (CMultipleAttribute) cattr; checkCardinalityConformsToRMCardinality(cmattr, parent, errors); //check Cardinality fits with the minimum and maximum of all occurrences of the children checkCardinalityConformsToChildrenOccurrences(cmattr, errors); } if (cattr.getChildren() == null) { return; } for (CObject cobj : cattr.getChildren()) { if (cattr instanceof CSingleAttribute) { // check rm type String childRMTypeName = cobj.getRmTypeName(); childRMTypeName = removeGenericTypes(childRMTypeName); log.debug("2- validating attribute.child constraint of type: " + cobj.getClass() + ", with rmType: " + childRMTypeName); Class childRMType = rmInspector.retrieveRMType(childRMTypeName); if (childRMType == null) { error = new ValidationError(ErrorType.VCORM, null, childRMTypeName, cobj.path()); errors.add(error); continue; } else if (cobj instanceof CPrimitiveObject) { // need to check the assumed value for primitive objects before skipping if parentRMClass and childRMType are equal (which is the case for SOME, but not all primitive objects) log.debug("validating CPrimitiveObject at: " + cobj.path()); validateCPrimitiveObject((CPrimitiveObject) cobj, archetype, errors); log.debug("skipping unnecessary additional checks on " + parentRmClass); continue; // otherwise this is done twice } else if (parentRmClass.equals(childRMType)) { log.debug("skipping unnecessary check on " + parentRmClass); continue; } else if (!rmAttrType.isEnum() && !(rmAttrType.isAssignableFrom(childRMType))) { log.debug("3- rmAttrType: " + rmAttrType + " with name [" + rmAttrName + "] is NOT assignable from type [" + childRMType + "]"); ErrorType type = ErrorType.VCORMT; if (cobj instanceof ArchetypeInternalRef) { type = ErrorType.VUNT; } error = new ValidationError(type, "NORMAL", childRMTypeName, cobj.path(), rmAttrType.getSimpleName()); if (!errors.contains(error)) { errors.add(error); } continue; } else if (parentGenericType != null && !(parentGenericType.isAssignableFrom(childRMType))) { // the generic type is not assignable from the childRMType, e.g // DV_INTERVAL<DV_TEXT> is wrong as DV_TEXT is a valid RMType, but not one that fits here: must be DV_ORDERED or subclass log.debug("4- rmAttrType: " + rmAttrType + " of name [" + rmAttrName + "] with generic type <" + parentGenericTypeName + "> is NOT assignable from type [" + childRMType + "]"); ErrorType type = ErrorType.VCORMT; if (cobj instanceof ArchetypeInternalRef) { type = ErrorType.VUNT; } error = new ValidationError(type, "PARENT", parentGenericTypeName, parent.path(), childRMType.getSimpleName(), cobj.path()); errors.add(error); continue; } log.debug("5- rmAttrType: " + rmAttrType + " with name " + rmAttrName + " IS assignable from " + childRMType); // check csingle attribute child object occurrences Interval<Integer> occu = cobj.getOccurrences(); if (occu != null && occu.isUpperIncluded() && occu.getUpper() > 1) { error = new ValidationError(ErrorType.VACSO, null, cobj.path()); errors.add(error); } for (CObject cobj2 : cattr.getChildren()) { if (cobj == cobj2) { continue; } // check child uniqueness if (cobj2.getRmTypeName().equals(cobj.getRmTypeName()) && cobj.getNodeId() == null) { error = new ValidationError(ErrorType.VACSU, null, cobj.path()); if (!errors.contains(error)) { errors.add(error); } } // check child identifier if (cobj2.getNodeId() != null && cobj2.getNodeId().equals(cobj.getNodeId())) { error = new ValidationError(ErrorType.VACSI, null, cobj.path()); if (!errors.contains(error)) { errors.add(error); } } /*VASCIT just seems to be a special case of VACSU?? * else if (cobj2.getNodeId() == null && cobj.getRmTypeName().equals(cobj2.getRmTypeName())) { // check for multiple attributes with the same rm type when the nodeId is null for one of them error = new ValidationError(ErrorType.VACSIT, "Cannot add "+cobj.getRmTypeName()+" object with node_id "+cobj.getNodeId()+" to singly-valued attribute "+cattr.getRmAttributeName()+" because attribute already has child with same RM type. (path="+cobj.path()+")"); if( ! errors.contains(error)) { errors.add(error); } } */ } } else { // CMultipleAttribute // checking for cardinality/occurrences validity (VACMC): the interval represented by, (sum of all occurrences minimum values) .. (sum of all occurrences maximum values) must be contained by the interval stated by the cardinality. Interval<Integer> cardinalityInterval = ((CMultipleAttribute) cattr).getCardinality().getInterval(); if (!cardinalityInterval.isUpperUnbounded() && (cobj.getOccurrences().isUpperUnbounded() || cardinalityInterval.getUpper().compareTo(cobj.getOccurrences().getUpper()) < 0)) { error = new ValidationError(ErrorType.VACMC, "CONTAIN", rmInspector.toUnderscoreSeparated(cobj.getClass().getSimpleName()).toUpperCase(), cobj.getRmTypeName(), cobj.getNodeId(), getIntervalFormalString(cardinalityInterval), getIntervalFormalString(cobj.getOccurrences()), cattr.path()); if (!errors.contains(error)) { errors.add(error); } } else if (cobj.getNodeId() == null) { // check missing child identifier // this is only legal (in most cases) if it is a ArchetypeInternalRef i.e. a use_node reference, but not if there is more than one witohut a node id if (cobj instanceof ArchetypeInternalRef) { // TODO if the object id at the target end of the ref happens to be the same as the object id of a sibling member at the source end then an explicit source-end id is needed even for an internal reference. // Could use hasSiblingWithTargetNodeId((ArchetypeInternalRef) cobj, archetype) for this for (CObject cobj2 : cattr.getChildren()) { if (cobj == cobj2) { continue; } if (cobj2.getNodeId() == null && cobj2 instanceof ArchetypeInternalRef && ((ArchetypeInternalRef) cobj).getTargetPath() .equals(((ArchetypeInternalRef) cobj2).getTargetPath())) { error = new ValidationError(ErrorType.VACMM, "INTREF", cobj.path()); if (!errors.contains(error)) { errors.add(error); } } } } else { error = new ValidationError(ErrorType.VACMI, null, cobj.path()); errors.add(error); } } else { // check duplicated child identifier for (CObject cobj2 : cattr.getChildren()) { if (cobj == cobj2) { continue; } if (cobj.getNodeId().equals(cobj2.getNodeId())) { error = new ValidationError(ErrorType.VACMM, "NORMAL", cobj.path()); if (!errors.contains(error)) { errors.add(error); } } } } // how about rmType check for multi-valued attributes? } if (cobj instanceof CDomainType) { // also includes CDVQuantity! log.debug("validating CDomainType of node_id: " + cobj.getNodeId()); validateCDomainType((CDomainType) cobj, archetype, errors); } else if (cobj instanceof CPrimitiveObject) { log.debug("validating CPrimitiveObject at: " + cobj.path()); validateCPrimitiveObject((CPrimitiveObject) cobj, archetype, errors); } else if (cobj instanceof CComplexObject) { log.debug("validating ccobj at: " + cobj.getNodeId()); validateCComplexObject((CComplexObject) cobj, archetype, errors); } else if (cobj instanceof ArchetypeInternalRef) { log.debug("validating Internal Reference: " + cobj.path()); checkArchetypeInternalRef((ArchetypeInternalRef) cobj, archetype, errors); } else if (cobj instanceof ArchetypeSlot) { log.debug("validating ArchetypeSlot: " + cobj.path()); checkArchetypeSlot((ArchetypeSlot) cobj, rmAttrType, archetype, errors); } else { log.debug("not continuing with recursion for class: " + cobj.getClass()); } } }
From source file:org.diorite.cfg.system.ConfigField.java
/** * Construct new config field for given {@link Field}. * * @param field source field./*from w ww . java2 s . c o m*/ * @param index index of field in class. Used to set priority of field. */ public ConfigField(final Field field, final int index) { this.field = field; { getAllPossibleTypes(field).forEach(TemplateCreator::checkTemplate); } this.index = index; final String[] comments = TemplateCreator.readComments(field); this.header = comments[0]; this.footer = comments[1]; { final CfgName annotation = field.getAnnotation(CfgName.class); this.name = (annotation != null) ? annotation.value() : field.getName(); } { final CfgPriority annotation = field.getAnnotation(CfgPriority.class); this.priority = (annotation != null) ? (annotation.value() * -1) : index; } for (final FieldOptions option : FieldOptions.values()) { if (!option.contains(field)) { continue; } this.options.put(option, option.get(this, field)); } final Class<?> type = DioriteReflectionUtils.getPrimitive(field.getType()); Supplier<Object> def = null; annotation: { { final CfgBooleanDefault annotation = field.getAnnotation(CfgBooleanDefault.class); if (annotation != null) { def = annotation::value; break annotation; } } { final CfgBooleanArrayDefault annotation = field.getAnnotation(CfgBooleanArrayDefault.class); if (annotation != null) { def = annotation::value; break annotation; } } { final CfgByteDefault annotation = field.getAnnotation(CfgByteDefault.class); if (annotation != null) { def = annotation::value; break annotation; } } { final CfgShortDefault annotation = field.getAnnotation(CfgShortDefault.class); if (annotation != null) { def = annotation::value; break annotation; } } { final CfgIntDefault annotation = field.getAnnotation(CfgIntDefault.class); if (annotation != null) { def = annotation::value; break annotation; } } { final CfgLongDefault annotation = field.getAnnotation(CfgLongDefault.class); if (annotation != null) { def = annotation::value; break annotation; } } { final CfgFloatDefault annotation = field.getAnnotation(CfgFloatDefault.class); if (annotation != null) { def = annotation::value; break annotation; } } { final CfgDoubleDefault annotation = field.getAnnotation(CfgDoubleDefault.class); if (annotation != null) { def = annotation::value; break annotation; } } { final CfgByteArrayDefault annotation = field.getAnnotation(CfgByteArrayDefault.class); if (annotation != null) { def = annotation::value; break annotation; } } { final CfgCharDefault annotation = field.getAnnotation(CfgCharDefault.class); if (annotation != null) { def = annotation::value; break annotation; } } { final CfgCharArrayDefault annotation = field.getAnnotation(CfgCharArrayDefault.class); if (annotation != null) { def = annotation::value; break annotation; } } { final CfgShortArrayDefault annotation = field.getAnnotation(CfgShortArrayDefault.class); if (annotation != null) { def = annotation::value; break annotation; } } { final CfgIntArrayDefault annotation = field.getAnnotation(CfgIntArrayDefault.class); if (annotation != null) { def = annotation::value; break annotation; } } { final CfgLongArrayDefault annotation = field.getAnnotation(CfgLongArrayDefault.class); if (annotation != null) { def = annotation::value; break annotation; } } { final CfgFloatArrayDefault annotation = field.getAnnotation(CfgFloatArrayDefault.class); if (annotation != null) { def = annotation::value; break annotation; } } { final CfgDoubleArrayDefault annotation = field.getAnnotation(CfgDoubleArrayDefault.class); if (annotation != null) { def = annotation::value; break annotation; } } { final CfgStringDefault annotation = field.getAnnotation(CfgStringDefault.class); if (annotation != null) { def = annotation::value; break annotation; } } { final CfgStringArrayDefault annotation = field.getAnnotation(CfgStringArrayDefault.class); if (annotation != null) { def = annotation::value; break annotation; } } if (type.isEnum()) { for (final Annotation a : field.getAnnotations()) { if (a.annotationType().isAnnotationPresent(CfgCustomDefault.class)) { final Annotation annotation = field.getAnnotation(a.annotationType()); this.invoker = DioriteReflectionUtils.getMethod(annotation.getClass(), "value"); def = () -> this.invoker.invoke(annotation); break annotation; } } } } final CfgDelegateDefault annotation = field.getAnnotation(CfgDelegateDefault.class); if (annotation != null) { final String path = annotation.value(); final Supplier<Object> basicDelegate = getBasicDelegate(path); if (basicDelegate != null) { def = basicDelegate; } else if (path.equalsIgnoreCase("{new}")) { final ConstructorInvoker constructor = DioriteReflectionUtils.getConstructor(field.getType()); def = constructor::invoke; } else { final int sepIndex = path.indexOf("::"); final Class<?> clazz; final String methodName; if (sepIndex == -1) { clazz = field.getDeclaringClass(); methodName = path; } else { try { Class<?> tmpClass = DioriteReflectionUtils .tryGetCanonicalClass(path.substring(0, sepIndex)); if (tmpClass == null) { tmpClass = DioriteReflectionUtils .tryGetCanonicalClass(field.getDeclaringClass().getPackage().getName() + "." + path.substring(0, sepIndex)); if (tmpClass == null) { tmpClass = DioriteReflectionUtils.getNestedClass(field.getDeclaringClass(), path.substring(0, sepIndex)); } } clazz = tmpClass; } catch (final Exception e) { throw new RuntimeException("Can't find class for: " + path, e); } methodName = path.substring(sepIndex + 2); } if (clazz == null) { throw new RuntimeException("Can't find class for delegate: " + path); } final MethodInvoker methodInvoker = DioriteReflectionUtils.getMethod(clazz, methodName, false); if (methodInvoker == null) { final ReflectGetter<Object> reflectGetter = DioriteReflectionUtils.getReflectGetter(methodName, clazz); def = () -> reflectGetter.get(null); } else { def = () -> methodInvoker.invoke(null); } } } this.def = def; }
From source file:org.apache.axis2.datasource.jaxb.JAXBDSContext.java
/** * Marshal objects by type/* w ww . j a v a 2 s .co m*/ * * @param b Object that can be rendered as an element, but the element name is not known to the * schema (i.e. rpc) * @param m Marshaller * @param writer XMLStreamWriter * @param type Class * @param isList true if this is an XmlList * @param ctype CONSTRUCTION_TYPE * @param optimize boolean set to true if optimization directly to * outputstream should be attempted. */ private void marshalByType(final Object b, final Marshaller m, final XMLStreamWriter writer, final Class type, final boolean isList, final JAXBUtils.CONSTRUCTION_TYPE ctype, final boolean optimize) throws WebServiceException { if (log.isDebugEnabled()) { log.debug("Enter marshalByType b=" + getDebugName(b) + " type=" + type + " marshaller=" + m + " writer=" + writer + " isList=" + isList + " ctype=" + ctype + " optimize=" + optimize); } if (isOccurrenceArray(b)) { marshalOccurrenceArray((JAXBElement) b, m, writer); return; } AccessController.doPrivileged(new PrivilegedAction() { public Object run() { try { // NOTE // Example: // <xsd:simpleType name="LongList"> // <xsd:list> // <xsd:simpleType> // <xsd:restriction base="xsd:unsignedInt"/> // </xsd:simpleType> // </xsd:list> // </xsd:simpleType> // <element name="myLong" nillable="true" type="impl:LongList"/> // // LongList will be represented as an int[] // On the wire myLong will be represented as a list of integers // with intervening whitespace // <myLong>1 2 3</myLong> // // Unfortunately, we are trying to marshal by type. Therefore // we want to marshal an element (foo) that is unknown to schema. // If we use the normal marshal code, the wire will look like // this (which is incorrect): // <foo><item>1</item><item>2</item><item>3</item></foo> // // The solution is to detect this situation and marshal the // String instead. Then we get the correct wire format: // <foo>1 2 3</foo> Object jbo = b; if (DEBUG_ENABLED) { log.debug("check if marshalling list or array object, type = " + ((b != null) ? b.getClass().getName() : "null")); } if (isList) { if (DEBUG_ENABLED) { log.debug("marshalling type which is a List"); } // This code assumes that the JAXBContext does not understand // the array or list. In such cases, the contents are converted // to a String and passed directly. if (ctype == JAXBUtils.CONSTRUCTION_TYPE.BY_CONTEXT_PATH) { QName qName = XMLRootElementUtil.getXmlRootElementQNameFromObject(b); String text = XSDListUtils.toXSDListString(getTypeEnabledObject(b)); if (DEBUG_ENABLED) { log.debug("marshalling [context path approach] " + "with xmllist text = " + text); } jbo = new JAXBElement(qName, String.class, text); } else if (ctype == JAXBUtils.CONSTRUCTION_TYPE.BY_CLASS_ARRAY) { // Some versions of JAXB have array/list processing built in. // This code is a safeguard because apparently some versions // of JAXB don't. QName qName = XMLRootElementUtil.getXmlRootElementQNameFromObject(b); String text = XSDListUtils.toXSDListString(getTypeEnabledObject(b)); if (DEBUG_ENABLED) { log.debug("marshalling [class array approach] " + "with xmllist text = " + text); } jbo = new JAXBElement(qName, String.class, text); } } // When JAXBContext is created using a context path, it will not include Enum // classes. // These classes have @XmlEnum annotation but not @XmlType/@XmlElement, so the // user will see MarshallingEx, class not known to ctxt. // // This is a jax-b defect, for now this fix is in place to pass CTS. This only // fixes the // situation where the enum is the top-level object (e.g., message-part in // rpc-lit scenario) // // Sample of what enum looks like: // @XmlEnum public enum EnumString { // @XmlEnumValue("String1") STRING_1("String1"), // @XmlEnumValue("String2") STRING_2("String2"); // ... } if (type.isEnum()) { if (b != null) { if (DEBUG_ENABLED) { log.debug("marshalByType. Marshaling " + type.getName() + " as Enum"); } JAXBElement jbe = (JAXBElement) b; String value = XMLRootElementUtil.getEnumValue((Enum) jbe.getValue()); jbo = new JAXBElement(jbe.getName(), String.class, value); } } // If the output stream is available, marshal directly to it OutputStream os = (optimize) ? getOutputStream(writer, m) : null; if (os == null) { if (DEBUG_ENABLED) { log.debug("Invoking marshalByType. " + "Marshaling to an XMLStreamWriter. Object is " + getDebugName(jbo)); } m.marshal(jbo, writer); } else { if (DEBUG_ENABLED) { log.debug("Invoking marshalByType. " + "Marshaling to an OutputStream. Object is " + getDebugName(jbo)); } m.marshal(jbo, os); } } catch (OMException e) { throw e; } catch (Throwable t) { throw new OMException(t); } return null; } }); }
From source file:net.ceos.project.poi.annotated.core.Engine.java
/** * Apply the base object to cell.//from w ww. ja v a2 s . co m * * @param configCriteria * the {@link XConfigCriteria} * @param o * the object * @param fT * the field type * @param idxC * the position of the cell * @return false if problem otherwise true * @throws WorkbookException * given when a not supported action. */ private boolean toExcel(final XConfigCriteria configCriteria, final Object o, final Class<?> fT, final int idxC) throws WorkbookException { /* flag which define if the cell was updated or not */ boolean isUpdated; /* initialize cell */ Cell cell; /* * check if the cell to be applied the element is empty otherwise one * exception will be launched */ if (configCriteria.getRow().getCell(idxC) != null) { throw new ElementException(ExceptionMessage.ELEMENT_OVERWRITE_CELL.getMessage()); } if (PredicateFactory.isPropagationVertical.test(configCriteria.getPropagation())) { if (ExtensionFileType.XLS.equals(configCriteria.getExtension()) && idxC > 255) { throw new SheetException(ExceptionMessage.SHEET_INVALID_COLUMN_INDEX_XLS.getMessage()); } else if (ExtensionFileType.XLSX.equals(configCriteria.getExtension()) && idxC > 16383) { throw new SheetException(ExceptionMessage.SHEET_INVALID_COLUMN_INDEX_XLSX.getMessage()); } } switch (fT.getName()) { case CellHandler.OBJECT_DATE: cell = configCriteria.getRow().createCell(idxC); isUpdated = CellHandler.dateWriter(configCriteria, o, cell); break; case CellHandler.OBJECT_LOCALDATE: cell = configCriteria.getRow().createCell(idxC); isUpdated = CellHandler.localDateWriter(configCriteria, o, cell); break; case CellHandler.OBJECT_LOCALDATETIME: cell = configCriteria.getRow().createCell(idxC); isUpdated = CellHandler.localDateTimeWriter(configCriteria, o, cell); break; case CellHandler.OBJECT_STRING: cell = configCriteria.getRow().createCell(idxC); isUpdated = CellHandler.stringWriter(configCriteria, o, cell); break; case CellHandler.OBJECT_SHORT: /* falls through */ case CellHandler.PRIMITIVE_SHORT: cell = configCriteria.getRow().createCell(idxC); isUpdated = CellHandler.shortWriter(configCriteria, o, cell); break; case CellHandler.OBJECT_INTEGER: /* falls through */ case CellHandler.PRIMITIVE_INTEGER: cell = configCriteria.getRow().createCell(idxC); isUpdated = CellHandler.integerWriter(configCriteria, o, cell); break; case CellHandler.OBJECT_LONG: /* falls through */ case CellHandler.PRIMITIVE_LONG: cell = configCriteria.getRow().createCell(idxC); isUpdated = CellHandler.longWriter(configCriteria, o, cell); break; case CellHandler.OBJECT_DOUBLE: /* falls through */ case CellHandler.PRIMITIVE_DOUBLE: cell = configCriteria.getRow().createCell(idxC); isUpdated = CellHandler.doubleWriter(configCriteria, o, cell); break; case CellHandler.OBJECT_BIGDECIMAL: cell = configCriteria.getRow().createCell(idxC); isUpdated = CellHandler.bigDecimalWriter(configCriteria, o, cell); break; case CellHandler.OBJECT_FLOAT: /* falls through */ case CellHandler.PRIMITIVE_FLOAT: cell = configCriteria.getRow().createCell(idxC); isUpdated = CellHandler.floatWriter(configCriteria, o, cell); break; case CellHandler.OBJECT_BOOLEAN: /* falls through */ case CellHandler.PRIMITIVE_BOOLEAN: cell = configCriteria.getRow().createCell(idxC); isUpdated = CellHandler.booleanWriter(configCriteria, o, cell); break; default: isUpdated = false; break; } if (!isUpdated && fT.isEnum()) { cell = configCriteria.getRow().createCell(idxC); isUpdated = CellHandler.enumWriter(configCriteria, o, cell); } return isUpdated; }
From source file:com.evolveum.midpoint.prism.util.JavaTypeConverter.java
public static <T> T convert(Class<T> expectedType, Object rawValue) { if (rawValue == null || expectedType.isInstance(rawValue)) { return (T) rawValue; }/*from w w w . j a v a2s .c o m*/ if (rawValue instanceof PrismPropertyValue<?>) { rawValue = ((PrismPropertyValue<?>) rawValue).getValue(); } // This really needs to be checked twice if (rawValue == null || expectedType.isInstance(rawValue)) { return (T) rawValue; } // Primitive types // boolean if (expectedType == boolean.class && rawValue instanceof Boolean) { return (T) ((Boolean) rawValue); } if (expectedType == Boolean.class && rawValue instanceof String) { return (T) (Boolean) Boolean.parseBoolean(((String) rawValue)); } if (expectedType == Boolean.class && rawValue instanceof PolyString) { return (T) (Boolean) Boolean.parseBoolean(((PolyString) rawValue).toString()); } if (expectedType == boolean.class && rawValue instanceof String) { return (T) (Boolean) Boolean.parseBoolean(((String) rawValue)); } if (expectedType == boolean.class && rawValue instanceof PolyString) { return (T) (Boolean) Boolean.parseBoolean(((PolyString) rawValue).toString()); } if (expectedType == String.class && rawValue instanceof Boolean) { return (T) rawValue.toString(); } // int if (expectedType == int.class && rawValue instanceof Integer) { return (T) ((Integer) rawValue); } if (expectedType == Integer.class && rawValue instanceof String) { return (T) (Integer) Integer.parseInt(((String) rawValue)); } if (expectedType == int.class && rawValue instanceof String) { return (T) (Integer) Integer.parseInt(((String) rawValue)); } if (expectedType == String.class && rawValue instanceof Integer) { return (T) rawValue.toString(); } if (expectedType == int.class && rawValue instanceof Long) { return (T) (Integer) ((Long) rawValue).intValue(); } if (expectedType == long.class && rawValue instanceof Long) { return (T) ((Long) rawValue); } if (expectedType == Long.class && rawValue instanceof String) { return (T) (Long) Long.parseLong(((String) rawValue)); } if (expectedType == long.class && rawValue instanceof String) { return (T) (Long) Long.parseLong(((String) rawValue)); } if (expectedType == String.class && rawValue instanceof Long) { return (T) rawValue.toString(); } if (expectedType == float.class && rawValue instanceof Float) { return (T) ((Float) rawValue); } if (expectedType == Float.class && rawValue instanceof String) { return (T) (Float) Float.parseFloat(((String) rawValue)); } if (expectedType == float.class && rawValue instanceof String) { return (T) (Float) Float.parseFloat(((String) rawValue)); } if (expectedType == String.class && rawValue instanceof Float) { return (T) rawValue.toString(); } if (expectedType == double.class && rawValue instanceof Double) { return (T) ((Double) rawValue); } if (expectedType == Double.class && rawValue instanceof String) { return (T) (Double) Double.parseDouble(((String) rawValue)); } if (expectedType == double.class && rawValue instanceof String) { return (T) (Double) Double.parseDouble(((String) rawValue)); } if (expectedType == String.class && rawValue instanceof Float) { return (T) rawValue.toString(); } if (expectedType == byte.class && rawValue instanceof Byte) { return (T) ((Byte) rawValue); } if (expectedType == Byte.class && rawValue instanceof String) { return (T) (Byte) Byte.parseByte(((String) rawValue)); } if (expectedType == byte.class && rawValue instanceof String) { return (T) (Byte) Byte.parseByte(((String) rawValue)); } if (expectedType == String.class && rawValue instanceof Byte) { return (T) rawValue.toString(); } if (expectedType == BigInteger.class && rawValue instanceof String) { return (T) new BigInteger(((String) rawValue)); } if (expectedType == String.class && rawValue instanceof BigInteger) { return (T) ((BigInteger) rawValue).toString(); } if (expectedType == BigDecimal.class && rawValue instanceof String) { return (T) new BigDecimal(((String) rawValue)); } if (expectedType == String.class && rawValue instanceof BigDecimal) { return (T) ((BigDecimal) rawValue).toString(); } if (expectedType == PolyString.class && rawValue instanceof String) { return (T) new PolyString((String) rawValue); } if (expectedType == PolyStringType.class && rawValue instanceof String) { PolyStringType polyStringType = new PolyStringType(); polyStringType.setOrig((String) rawValue); return (T) polyStringType; } if (expectedType == String.class && rawValue instanceof PolyString) { return (T) ((PolyString) rawValue).getOrig(); } if (expectedType == String.class && rawValue instanceof PolyStringType) { return (T) ((PolyStringType) rawValue).getOrig(); } if (expectedType == PolyString.class && rawValue instanceof PolyStringType) { return (T) ((PolyStringType) rawValue).toPolyString(); } if (expectedType == PolyString.class && rawValue instanceof Integer) { return (T) new PolyString(((Integer) rawValue).toString()); } if (expectedType == PolyStringType.class && rawValue instanceof PolyString) { PolyStringType polyStringType = new PolyStringType((PolyString) rawValue); return (T) polyStringType; } if (expectedType == PolyStringType.class && rawValue instanceof Integer) { PolyStringType polyStringType = new PolyStringType(((Integer) rawValue).toString()); return (T) polyStringType; } // Date and time if (expectedType == XMLGregorianCalendar.class && rawValue instanceof Long) { XMLGregorianCalendar xmlCalType = XmlTypeConverter.createXMLGregorianCalendar((Long) rawValue); return (T) xmlCalType; } if (expectedType == XMLGregorianCalendar.class && rawValue instanceof String) { XMLGregorianCalendar xmlCalType = magicDateTimeParse((String) rawValue); return (T) xmlCalType; } if (expectedType == String.class && rawValue instanceof XMLGregorianCalendar) { return (T) ((XMLGregorianCalendar) rawValue).toXMLFormat(); } if (expectedType == Long.class && rawValue instanceof XMLGregorianCalendar) { return (T) (Long) XmlTypeConverter.toMillis((XMLGregorianCalendar) rawValue); } // XML Enums (JAXB) if (expectedType.isEnum() && expectedType.getAnnotation(XmlEnum.class) != null && rawValue instanceof String) { return XmlTypeConverter.toXmlEnum(expectedType, (String) rawValue); } if (expectedType == String.class && rawValue.getClass().isEnum() && rawValue.getClass().getAnnotation(XmlEnum.class) != null) { return (T) XmlTypeConverter.fromXmlEnum(rawValue); } // Java Enums if (expectedType.isEnum() && rawValue instanceof String) { return (T) Enum.valueOf((Class<Enum>) expectedType, (String) rawValue); } if (expectedType == String.class && rawValue.getClass().isEnum()) { return (T) rawValue.toString(); } //QName if (expectedType == QName.class && rawValue instanceof QName) { return (T) rawValue; } if (expectedType == QName.class && rawValue instanceof String) { return (T) QNameUtil.uriToQName((String) rawValue); } throw new IllegalArgumentException("Expected " + expectedType + " type, but got " + rawValue.getClass()); }
From source file:com.clustercontrol.viewer.CommonTableLabelProvider.java
/** * ??//from ww w .j a v a2 s.c o m * * @since 1.0.0 * @see org.eclipse.jface.viewers.ITableLabelProvider#getColumnText(java.lang.Object, * int) */ @Override public String getColumnText(Object element, int columnIndex) { ArrayList<TableColumnInfo> tableColumnList = m_viewer.getTableColumnList(); ArrayList<?> list = (ArrayList<?>) element; if (list.size() <= columnIndex) { m_log.debug("Bad implements. IndexOutOfBoundsException." + " list.size=" + list.size() + ", columnIndex=" + columnIndex); return ""; } Object item = list.get(columnIndex); TableColumnInfo tableColumn = tableColumnList.get(columnIndex); if (item == null || item.equals("")) { return ""; } if (tableColumn.getType() == TableColumnInfo.JOB) { //???? return JobMessage.typeToString(((Number) item).intValue()); } else if (tableColumn.getType() == TableColumnInfo.STATE) { //???? return StatusMessage.typeToString(((Number) item).intValue()); } else if (tableColumn.getType() == TableColumnInfo.PRIORITY) { //?????? return PriorityMessage.typeToString(((Number) item).intValue()); } else if (tableColumn.getType() == TableColumnInfo.VALID) { //?/??? return ValidMessage.typeToString(((Boolean) item).booleanValue()); } else if (tableColumn.getType() == TableColumnInfo.JUDGMENT_OBJECT) { //???? return JudgmentObjectMessage.typeToString(((Number) item).intValue()); } else if (tableColumn.getType() == TableColumnInfo.NOTIFY_TYPE) { //???? return NotifyTypeUtil.typeToString(((Number) item).intValue()); } else if (tableColumn.getType() == TableColumnInfo.WAIT_RULE_VALUE) { //????? Class<?> itemClass = item.getClass(); if (itemClass == Date.class) { //?0??24(??48)?? return TimeStringConverter.formatTime((Date) item); } else if (itemClass == String.class) { return String.valueOf(item); } else if (itemClass.getSuperclass() == Number.class) { return ((Number) item).toString(); } } else if (tableColumn.getType() == TableColumnInfo.SCHEDULE) { //???? Schedule schedule = (Schedule) item; String scheduleString = null; DecimalFormat format = new DecimalFormat("00"); if (schedule.getType() == ScheduleConstant.TYPE_DAY) { if (schedule.getMonth() != null) { scheduleString = format.format(schedule.getMonth()) + "/" + format.format(schedule.getDay()) + " " + format.format(schedule.getHour()) + ":" + format.format(schedule.getMinute()); } else if (schedule.getDay() != null) { scheduleString = format.format(schedule.getDay()) + Messages.getString("monthday") + " " + format.format(schedule.getHour()) + ":" + format.format(schedule.getMinute()); } else if (schedule.getHour() != null) { scheduleString = format.format(schedule.getHour()) + ":" + format.format(schedule.getMinute()); } else if (schedule.getMinute() != null) { scheduleString = format.format(schedule.getMinute()) + Messages.getString("minute"); } } else if (schedule.getType() == ScheduleConstant.TYPE_WEEK) { if (schedule.getHour() != null) { scheduleString = DayOfWeekConstant.typeToString(schedule.getWeek()) + " " + format.format(schedule.getHour()) + ":" + format.format(schedule.getMinute()); } else { scheduleString = DayOfWeekConstant.typeToString(schedule.getWeek()) + " " + format.format(schedule.getMinute()) + Messages.getString("minute"); } } else { // ??????? m_log.warn("CommonTableLabelProvider 165"); } return scheduleString; } else if (tableColumn.getType() == TableColumnInfo.CONFIRM) { //??/???? return ConfirmMessage.typeToString(((Number) item).intValue()); } else if (tableColumn.getType() == TableColumnInfo.WAIT_RULE) { //?????? return YesNoMessage.typeToString(((Boolean) item).booleanValue()); } else if (tableColumn.getType() == TableColumnInfo.PROCESS) { //????? return ProcessMessage.typeToString(((Boolean) item).booleanValue()); } else if (tableColumn.getType() == TableColumnInfo.END_STATUS) { //???? return EndStatusMessage.typeToString(((Number) item).intValue()); } else if (tableColumn.getType() == TableColumnInfo.CHECKBOX) { //????? return ""; } else if (tableColumn.getType() == TableColumnInfo.DAY_OF_WEEK) { //???? return DayOfWeekConstant.typeToString(((Number) item).intValue()); } else if (tableColumn.getType() == TableColumnInfo.SCHEDULE_ON_OFF) { //???? return ""; } else if (tableColumn.getType() == TableColumnInfo.JOB_PARAM_TYPE) { //???? return JobParamTypeMessage.typeToString(((Number) item).intValue()); } else if (tableColumn.getType() == TableColumnInfo.COLLECT_STATUS) { //????? return PerformanceStatusConstant.typeToString(((Boolean) item).booleanValue()); } else if (tableColumn.getType() == TableColumnInfo.JOB_RUNTIME_PARAM_TYPE) { //???? return String.format("%s(%s)", JobParamTypeMessage.STRING_RUNTIME, JobRuntimeParamTypeMessage.typeToString(((Number) item).intValue())); } else if (tableColumn.getType() == TableColumnInfo.JOB_RUNTIME_PARAM_TYPE) { //???? return String.format("%s(%s)", JobParamTypeMessage.STRING_RUNTIME, JobRuntimeParamTypeMessage.typeToString(((Number) item).intValue())); } else if (tableColumn.getType() == TableColumnInfo.JOBMAP_ICON_IMAGE) { //???? return ""; } else if (tableColumn.getType() == TableColumnInfo.APPROVAL_STATUS) { //????? return JobApprovalStatusMessage.typeToString(((Number) item).intValue()); } else if (tableColumn.getType() == TableColumnInfo.APPROVAL_RESULT) { //?????? return JobApprovalResultMessage.typeToString(((Number) item).intValue()); } else if (tableColumn.getType() == TableColumnInfo.DECISION_CONDITION) { //????? return DecisionObjectMessage.typeToString(((Number) item).intValue()); } else { //??? Class<?> itemClass = item.getClass(); if (itemClass == String.class) { return String.valueOf(item); } else if (itemClass == Date.class) { return TimezoneUtil.getSimpleDateFormat().format((Date) item); } else if (itemClass == Time.class) { SimpleDateFormat formatter = new SimpleDateFormat("HH:mm:ss"); formatter.setTimeZone(TimezoneUtil.getTimeZone()); return formatter.format((Time) item); } else if (itemClass.getSuperclass() == Number.class) { return ((Number) item).toString(); } else if (itemClass.isEnum()) { return ((Enum<?>) item).toString(); } else { return item.toString(); } } return ""; }
From source file:org.openTwoFactor.client.util.TwoFactorClientCommonUtils.java
/** * see if a class is a scalar (not bean, not array or list, etc) * @param type/*from ww w. j a v a 2 s. c o m*/ * @return true if scalar */ public static boolean isScalar(Class<?> type) { if (type.isArray()) { return false; } //definitely all primitives if (type.isPrimitive()) { return true; } //Integer, Float, etc if (Number.class.isAssignableFrom(type)) { return true; } //Date, Timestamp if (Date.class.isAssignableFrom(type)) { return true; } if (Character.class.equals(type)) { return true; } //handles strings and string builders if (CharSequence.class.equals(type) || CharSequence.class.isAssignableFrom(type)) { return true; } if (Class.class == type || Boolean.class == type || type.isEnum()) { return true; } //appears not to be a scalar return false; }
From source file:org.openTwoFactor.client.util.TwoFactorClientCommonUtils.java
/** * If necessary, convert an object to another type. if type is Object.class, just return the input * @param <T> is the type to return * @param value/*from w w w . jav a 2 s . c om*/ * @param theClass * @param convertNullToDefaultPrimitive if the value is null, and theClass is primitive, should we * convert the null to a primitive default value * @param useNewInstanceHooks if theClass is not recognized, then honor the string "null", "newInstance", * or get a constructor with one param, and call it * @return the object of that instance converted into something else */ @SuppressWarnings({ "unchecked", "cast" }) public static <T> T typeCast(Object value, Class<T> theClass, boolean convertNullToDefaultPrimitive, boolean useNewInstanceHooks) { if (Object.class.equals(theClass)) { return (T) value; } if (value == null) { if (convertNullToDefaultPrimitive && theClass.isPrimitive()) { if (theClass == boolean.class) { return (T) Boolean.FALSE; } if (theClass == char.class) { return (T) (Object) 0; } //convert 0 to the type return typeCast(0, theClass, false, false); } return null; } if (theClass.isInstance(value)) { return (T) value; } //if array, get the base class if (theClass.isArray() && theClass.getComponentType() != null) { theClass = (Class<T>) theClass.getComponentType(); } Object resultValue = null; //loop through and see the primitive types etc if (theClass.equals(Date.class)) { resultValue = dateValue(value); } else if (theClass.equals(String.class)) { resultValue = stringValue(value); } else if (theClass.equals(Timestamp.class)) { resultValue = toTimestamp(value); } else if (theClass.equals(Boolean.class) || theClass.equals(boolean.class)) { resultValue = booleanObjectValue(value); } else if (theClass.equals(Integer.class) || theClass.equals(int.class)) { resultValue = intObjectValue(value, true); } else if (theClass.equals(Double.class) || theClass.equals(double.class)) { resultValue = doubleObjectValue(value, true); } else if (theClass.equals(Float.class) || theClass.equals(float.class)) { resultValue = floatObjectValue(value, true); } else if (theClass.equals(Long.class) || theClass.equals(long.class)) { resultValue = longObjectValue(value, true); } else if (theClass.equals(Byte.class) || theClass.equals(byte.class)) { resultValue = byteObjectValue(value); } else if (theClass.equals(Character.class) || theClass.equals(char.class)) { resultValue = charObjectValue(value); } else if (theClass.equals(Short.class) || theClass.equals(short.class)) { resultValue = shortObjectValue(value); } else if (theClass.isEnum() && (value instanceof String)) { resultValue = Enum.valueOf((Class) theClass, (String) value); } else if (theClass.equals(Class.class) && (value instanceof String)) { resultValue = forName((String) value); } else if (useNewInstanceHooks && value instanceof String) { String stringValue = (String) value; if (equals("null", stringValue)) { resultValue = null; } else if (equals("newInstance", stringValue)) { resultValue = newInstance(theClass); } else { // instantiate using string //note, we could typecast this to fit whatever is there... right now this is used for annotation try { Constructor constructor = theClass.getConstructor(new Class[] { String.class }); resultValue = constructor.newInstance(new Object[] { stringValue }); } catch (Exception e) { throw new RuntimeException("Cant find constructor with string for class: " + theClass); } } } else { throw new RuntimeException("Cannot convert from type: " + value.getClass() + " to type: " + theClass); } return (T) resultValue; }
From source file:ca.oson.json.Oson.java
private <E> Collection json2Collection(FieldData objectDTO) { Object value = objectDTO.valueToProcess; Collection<E> returnObj = (Collection<E>) objectDTO.returnObj; Class<Collection<E>> returnType = objectDTO.returnType; Collection<E> defaultValue = (Collection<E>) objectDTO.defaultValue; if (returnType == null) { if (returnType == null && returnObj != null) { returnType = (Class<Collection<E>>) returnObj.getClass(); }/*from w w w.ja v a2s . co m*/ if (returnType == null) { returnType = (Class<Collection<E>>) DefaultValue.collection(returnType).getClass(); } objectDTO.returnType = returnType; } // isEmpty if (!StringUtil.isNull(value)) { Collection<E> collection = null; try { collection = (Collection<E>) value; } catch (Exception e) { collection = DefaultValue.collection(returnType); // new ArrayList(); } if (collection.size() > 0) { Function function = objectDTO.getDeserializer(); if (function != null) { try { Object returnedValue = null; // suppose to return String, but in case not, try to process if (function instanceof Json2DataMapperFunction) { DataMapper classData = new DataMapper(returnType, collection, objectDTO.classMapper, objectDTO.level, getPrettyIndentation()); returnedValue = ((Json2DataMapperFunction) function).apply(classData); } else if (function instanceof Json2FieldDataFunction) { Json2FieldDataFunction f = (Json2FieldDataFunction) function; FieldData fieldData = objectDTO.clone(); returnedValue = f.apply(fieldData); } else if (function instanceof Json2CollectionFunction) { return ((Json2CollectionFunction) function).apply(collection); } else { returnedValue = function.apply(collection); } if (returnedValue == null) { return null; } else if (Collection.class.isAssignableFrom(returnedValue.getClass())) { return (Collection) returnedValue; } else if (returnedValue.getClass().isArray()) { return Arrays.asList((Object[]) returnedValue); } else { // do not know what to do } } catch (Exception e) { } } if (returnObj == null) { if (defaultValue != null) { returnObj = defaultValue; } if (EnumSet.class.isAssignableFrom(returnType)) { ComponentType type = getComponentType(); Class enm = type.getComponentType().getClassType(); if (enm.isEnum()) { returnObj = (Collection<E>) EnumSet.allOf(enm); } } if (returnObj == null) { returnObj = newInstance(new HashMap(), returnType); } if (returnObj == null) { returnObj = DefaultValue.collection(returnType); } objectDTO.returnObj = returnObj; } objectDTO.incrLevel(); objectDTO.valueToProcess = collection; //Class<E> componentType = objectDTO.getComponentType(getJsonClassType()); Class<E> componentType = guessComponentType(objectDTO); for (E val : collection) { if (val != null) { FieldData newFieldData = new FieldData(val, objectDTO.returnType, objectDTO.json2Java, objectDTO.level, objectDTO.set); newFieldData.componentType = objectDTO.componentType; if (ObjectUtil.isSameDataType(componentType, val.getClass()) && ObjectUtil.isBasicDataType(val.getClass())) { newFieldData.returnType = componentType; } else { newFieldData.returnType = guessComponentType(newFieldData); } newFieldData.fieldMapper = objectDTO.fieldMapper; returnObj.add(json2Object(newFieldData)); } } if (objectDTO.classMapper.orderArrayAndList) { try { if (!List.class.isAssignableFrom(returnObj.getClass())) { returnObj = new ArrayList(returnObj); } Collections.sort((List) returnObj); } catch (Exception ex) { } } return returnObj; } else { return collection; } } return json2CollectionDefault(objectDTO); }