Example usage for java.lang Class isEnum

List of usage examples for java.lang Class isEnum

Introduction

In this page you can find the example usage for java.lang Class isEnum.

Prototype

public boolean isEnum() 

Source Link

Document

Returns true if and only if this class was declared as an enum in the source code.

Usage

From source file:org.apache.hadoop.hbase.security.access.HbaseObjectWritableFor96Migration.java

/**
 * Write a {@link Writable}, {@link String}, primitive type, or an array of
 * the preceding./* w  w w .j a v  a 2  s . co m*/
 * @param out
 * @param instance
 * @param declaredClass
 * @param conf
 * @throws IOException
 */
@SuppressWarnings("unchecked")
static void writeObject(DataOutput out, Object instance, Class declaredClass, Configuration conf)
        throws IOException {

    Object instanceObj = instance;
    Class declClass = declaredClass;

    if (instanceObj == null) { // null
        instanceObj = new NullInstance(declClass, conf);
        declClass = Writable.class;
    }
    writeClassCode(out, declClass);
    if (declClass.isArray()) { // array
        // If bytearray, just dump it out -- avoid the recursion and
        // byte-at-a-time we were previously doing.
        if (declClass.equals(byte[].class)) {
            Bytes.writeByteArray(out, (byte[]) instanceObj);
        } else {
            //if it is a Generic array, write the element's type
            if (getClassCode(declaredClass) == GENERIC_ARRAY_CODE) {
                Class<?> componentType = declaredClass.getComponentType();
                writeClass(out, componentType);
            }

            int length = Array.getLength(instanceObj);
            out.writeInt(length);
            for (int i = 0; i < length; i++) {
                Object item = Array.get(instanceObj, i);
                writeObject(out, item, item.getClass(), conf);
            }
        }
    } else if (List.class.isAssignableFrom(declClass)) {
        List list = (List) instanceObj;
        int length = list.size();
        out.writeInt(length);
        for (int i = 0; i < length; i++) {
            Object elem = list.get(i);
            writeObject(out, elem, elem == null ? Writable.class : elem.getClass(), conf);
        }
    } else if (declClass == String.class) { // String
        Text.writeString(out, (String) instanceObj);
    } else if (declClass.isPrimitive()) { // primitive type
        if (declClass == Boolean.TYPE) { // boolean
            out.writeBoolean(((Boolean) instanceObj).booleanValue());
        } else if (declClass == Character.TYPE) { // char
            out.writeChar(((Character) instanceObj).charValue());
        } else if (declClass == Byte.TYPE) { // byte
            out.writeByte(((Byte) instanceObj).byteValue());
        } else if (declClass == Short.TYPE) { // short
            out.writeShort(((Short) instanceObj).shortValue());
        } else if (declClass == Integer.TYPE) { // int
            out.writeInt(((Integer) instanceObj).intValue());
        } else if (declClass == Long.TYPE) { // long
            out.writeLong(((Long) instanceObj).longValue());
        } else if (declClass == Float.TYPE) { // float
            out.writeFloat(((Float) instanceObj).floatValue());
        } else if (declClass == Double.TYPE) { // double
            out.writeDouble(((Double) instanceObj).doubleValue());
        } else if (declClass == Void.TYPE) { // void
        } else {
            throw new IllegalArgumentException("Not a primitive: " + declClass);
        }
    } else if (declClass.isEnum()) { // enum
        Text.writeString(out, ((Enum) instanceObj).name());
    } else if (Message.class.isAssignableFrom(declaredClass)) {
        Text.writeString(out, instanceObj.getClass().getName());
        ((Message) instance).writeDelimitedTo(DataOutputOutputStream.constructOutputStream(out));
    } else if (Writable.class.isAssignableFrom(declClass)) { // Writable
        Class<?> c = instanceObj.getClass();
        Integer code = CLASS_TO_CODE.get(c);
        if (code == null) {
            out.writeByte(NOT_ENCODED);
            Text.writeString(out, c.getName());
        } else {
            writeClassCode(out, c);
        }
        ((Writable) instanceObj).write(out);
    } else if (Serializable.class.isAssignableFrom(declClass)) {
        Class<?> c = instanceObj.getClass();
        Integer code = CLASS_TO_CODE.get(c);
        if (code == null) {
            out.writeByte(NOT_ENCODED);
            Text.writeString(out, c.getName());
        } else {
            writeClassCode(out, c);
        }
        ByteArrayOutputStream bos = null;
        ObjectOutputStream oos = null;
        try {
            bos = new ByteArrayOutputStream();
            oos = new ObjectOutputStream(bos);
            oos.writeObject(instanceObj);
            byte[] value = bos.toByteArray();
            out.writeInt(value.length);
            out.write(value);
        } finally {
            if (bos != null)
                bos.close();
            if (oos != null)
                oos.close();
        }
    } else if (Scan.class.isAssignableFrom(declClass)) {
        Scan scan = (Scan) instanceObj;
        byte[] scanBytes = ProtobufUtil.toScan(scan).toByteArray();
        out.writeInt(scanBytes.length);
        out.write(scanBytes);
    } else {
        throw new IOException("Can't write: " + instanceObj + " as " + declClass);
    }
}

From source file:com.evolveum.midpoint.prism.marshaller.BeanUnmarshaller.java

private <T> T unmarshalInternal(@NotNull XNode xnode, @NotNull Class<T> beanClass, @NotNull ParsingContext pc)
        throws SchemaException {
    if (beanClass == null) {
        throw new IllegalStateException("No bean class for node: " + xnode.debugDump());
    }/*from   ww  w  .  ja  v a 2  s  .  c  o m*/
    if (xnode instanceof RootXNode) {
        XNode subnode = ((RootXNode) xnode).getSubnode();
        if (subnode == null) {
            throw new IllegalStateException("Couldn't parse " + beanClass
                    + " from a root node with a null content: " + xnode.debugDump());
        } else {
            return unmarshal(subnode, beanClass, pc);
        }
    } else if (!(xnode instanceof MapXNode) && !(xnode instanceof PrimitiveXNode)
            && !xnode.isHeterogeneousList()) {
        throw new IllegalStateException("Couldn't parse " + beanClass
                + " from non-map/non-primitive/non-hetero-list node: " + xnode.debugDump());
    }

    // only maps and primitives and heterogeneous lists after this point

    if (xnode instanceof PrimitiveXNode) {
        PrimitiveXNode<T> prim = (PrimitiveXNode) xnode;
        if (XmlTypeConverter.canConvert(beanClass)) {
            QName xsdType = XsdTypeMapper.toXsdType(beanClass);
            Object parsedValue = prim.getParsedValue(xsdType, beanClass);
            return postConvertUnmarshal(parsedValue, pc);
        } else if (beanClass.isEnum()) {
            return unmarshalEnumFromPrimitive(prim, beanClass, pc);
        }
        @SuppressWarnings("unchecked")
        PrimitiveUnmarshaller<T> unmarshaller = specialPrimitiveUnmarshallers.get(beanClass);
        if (unmarshaller != null) {
            return unmarshaller.unmarshal(prim, beanClass, pc);
        } else {
            return unmarshallPrimitive(prim, beanClass, pc);
        }
    } else {

        if (beanClass.getPackage() == null || beanClass.getPackage().getName().equals("java.lang")) {
            // We obviously have primitive data type, but we are asked to unmarshall from map xnode
            // NOTE: this may happen in XML when we have "empty" element, but it has some whitespace in it
            //       such as those troublesome newlines. This also happens if there is "empty" element
            //       but it contains an expression (so it is not PrimitiveXNode but MapXNode).
            // TODO: more robust implementation
            // TODO: look for "value" subnode with primitive value and try that.
            // This is most likely attempt to parse primitive value with dynamic expression.
            // Therefore just ignore entire map content.
            return null;
        }

        @SuppressWarnings("unchecked")
        MapUnmarshaller<T> unmarshaller = specialMapUnmarshallers.get(beanClass);
        if (xnode instanceof MapXNode && unmarshaller != null) { // TODO: what about special unmarshaller + hetero list?
            return unmarshaller.unmarshal((MapXNode) xnode, beanClass, pc);
        }
        return unmarshalFromMapOrHeteroList(xnode, beanClass, pc);
    }
}

From source file:com.cloudera.sqoop.SqoopOptions.java

@SuppressWarnings("unchecked")
/**//from  www .  j  av a2  s  .  c o  m
 * Given a set of properties, load this into the current SqoopOptions
 * instance.
 */
public void loadProperties(Properties props) {

    try {
        Field[] fields = getClass().getDeclaredFields();
        for (Field f : fields) {
            if (f.isAnnotationPresent(StoredAsProperty.class)) {
                Class typ = f.getType();
                StoredAsProperty storedAs = f.getAnnotation(StoredAsProperty.class);
                String propName = storedAs.value();

                if (typ.equals(int.class)) {
                    f.setInt(this, getIntProperty(props, propName, f.getInt(this)));
                } else if (typ.equals(boolean.class)) {
                    f.setBoolean(this, getBooleanProperty(props, propName, f.getBoolean(this)));
                } else if (typ.equals(long.class)) {
                    f.setLong(this, getLongProperty(props, propName, f.getLong(this)));
                } else if (typ.equals(String.class)) {
                    f.set(this, props.getProperty(propName, (String) f.get(this)));
                } else if (typ.equals(Integer.class)) {
                    String value = props.getProperty(propName,
                            f.get(this) == null ? "null" : f.get(this).toString());
                    f.set(this, value.equals("null") ? null : new Integer(value));
                } else if (typ.isEnum()) {
                    f.set(this, Enum.valueOf(typ, props.getProperty(propName, f.get(this).toString())));
                } else {
                    throw new RuntimeException("Could not retrieve property " + propName + " for type: " + typ);
                }
            }
        }
    } catch (IllegalAccessException iae) {
        throw new RuntimeException("Illegal access to field in property setter", iae);
    }

    // Now load properties that were stored with special types, or require
    // additional logic to set.

    if (getBooleanProperty(props, "db.require.password", false)) {
        // The user's password was stripped out from the metastore.
        // Require that the user enter it now.
        setPasswordFromConsole();
    } else {
        this.password = props.getProperty("db.password", this.password);
    }

    if (this.jarDirIsAuto) {
        // We memoized a user-specific nonce dir for compilation to the data
        // store.  Disregard that setting and create a new nonce dir.
        String localUsername = System.getProperty("user.name", "unknown");
        this.jarOutputDir = getNonceJarDir(tmpDir + "sqoop-" + localUsername + "/compile");
    }

    String colListStr = props.getProperty("db.column.list", null);
    if (null != colListStr) {
        this.columns = listToArray(colListStr);
    }

    this.inputDelimiters = getDelimiterProperties(props, "codegen.input.delimiters", this.inputDelimiters);
    this.outputDelimiters = getDelimiterProperties(props, "codegen.output.delimiters", this.outputDelimiters);

    this.extraArgs = getArgArrayProperty(props, "tool.arguments", this.extraArgs);

    // Delimiters were previously memoized; don't let the tool override
    // them with defaults.
    this.areDelimsManuallySet = true;
}

From source file:com.sun.socialsite.util.DebugBeanJsonConverter.java

@SuppressWarnings("boxing")
private <T> void callSetterWithValue(T pojo, Method method, JSONObject jsonObject, String fieldName)
        throws IllegalAccessException, InvocationTargetException, NoSuchFieldException, JSONException {

    log.debug("Calling setter [" + method.getName() + "]");

    Class<?> expectedType = method.getParameterTypes()[0];
    Object value = null;/*from  ww w  .  j a v a  2s.c  o m*/

    if (!jsonObject.has(fieldName)) {
        // Skip
    } else if (expectedType.equals(List.class)) {
        ParameterizedType genericListType = (ParameterizedType) method.getGenericParameterTypes()[0];
        Type type = genericListType.getActualTypeArguments()[0];
        Class<?> rawType;
        Class<?> listElementClass;
        if (type instanceof ParameterizedType) {
            listElementClass = (Class<?>) ((ParameterizedType) type).getActualTypeArguments()[0];
            rawType = (Class<?>) ((ParameterizedType) type).getRawType();
        } else {
            listElementClass = (Class<?>) type;
            rawType = listElementClass;
        }

        List<Object> list = Lists.newArrayList();
        JSONArray jsonArray = jsonObject.getJSONArray(fieldName);
        for (int i = 0; i < jsonArray.length(); i++) {
            if (org.apache.shindig.protocol.model.Enum.class.isAssignableFrom(rawType)) {
                list.add(convertEnum(listElementClass, jsonArray.getJSONObject(i)));
            } else {
                list.add(convertToObject(jsonArray.getString(i), listElementClass));
            }
        }

        value = list;

    } else if (expectedType.equals(Map.class)) {
        ParameterizedType genericListType = (ParameterizedType) method.getGenericParameterTypes()[0];
        Type[] types = genericListType.getActualTypeArguments();
        Class<?> valueClass = (Class<?>) types[1];

        // We only support keys being typed as Strings.
        // Nothing else really makes sense in json.
        Map<String, Object> map = Maps.newHashMap();
        JSONObject jsonMap = jsonObject.getJSONObject(fieldName);

        Iterator<?> keys = jsonMap.keys();
        while (keys.hasNext()) {
            String keyName = (String) keys.next();
            map.put(keyName, convertToObject(jsonMap.getString(keyName), valueClass));
        }

        value = map;

    } else if (org.apache.shindig.protocol.model.Enum.class.isAssignableFrom(expectedType)) {
        // TODO Need to stop using Enum as a class name :(
        value = convertEnum((Class<?>) ((ParameterizedType) method.getGenericParameterTypes()[0])
                .getActualTypeArguments()[0], jsonObject.getJSONObject(fieldName));
    } else if (expectedType.isEnum()) {
        if (jsonObject.has(fieldName)) {
            for (Object v : expectedType.getEnumConstants()) {
                if (v.toString().equals(jsonObject.getString(fieldName))) {
                    value = v;
                    break;
                }
            }
            if (value == null) {
                throw new IllegalArgumentException("No enum value  '" + jsonObject.getString(fieldName)
                        + "' in " + expectedType.getName());
            }
        }
    } else if (expectedType.equals(String.class)) {
        value = jsonObject.getString(fieldName);
    } else if (expectedType.equals(Date.class)) {
        // Use JODA ISO parsing for the conversion
        value = new DateTime(jsonObject.getString(fieldName)).toDate();
    } else if (expectedType.equals(Long.class) || expectedType.equals(Long.TYPE)) {
        value = jsonObject.getLong(fieldName);
    } else if (expectedType.equals(Integer.class) || expectedType.equals(Integer.TYPE)) {
        value = jsonObject.getInt(fieldName);
    } else if (expectedType.equals(Boolean.class) || expectedType.equals(Boolean.TYPE)) {
        value = jsonObject.getBoolean(fieldName);
    } else if (expectedType.equals(Float.class) || expectedType.equals(Float.TYPE)) {
        value = ((Double) jsonObject.getDouble(fieldName)).floatValue();
    } else if (expectedType.equals(Double.class) || expectedType.equals(Double.TYPE)) {
        value = jsonObject.getDouble(fieldName);
    } else {
        // Assume its an injected type
        value = convertToObject(jsonObject.getJSONObject(fieldName).toString(), expectedType);
    }

    if (value != null) {
        method.invoke(pojo, value);
    }
}

From source file:org.tinygroup.beanwrapper.TypeConverterDelegate.java

/**
 * Convert the value to the required type (if necessary from a String),
 * for the specified property.//w w  w  .  ja v  a2  s . com
 * @param propertyName name of the property
 * @param oldValue the previous value, if available (may be <code>null</code>)
 * @param newValue the proposed new value
 * @param requiredType the type we must convert to
 * (or <code>null</code> if not known, for example in case of a collection element)
 * @param descriptor the JavaBeans descriptor for the property
 * @param methodParam the method parameter that is the target of the conversion
 * (may be <code>null</code>)
 * @return the new value, possibly the result of type conversion
 * @throws IllegalArgumentException if type conversion failed
 */
protected Object convertIfNecessary(String propertyName, Object oldValue, Object newValue, Class requiredType,
        PropertyDescriptor descriptor, MethodParameter methodParam) throws IllegalArgumentException {

    Object convertedValue = newValue;

    // Custom editor for this type?
    PropertyEditor editor = this.propertyEditorRegistry.findCustomEditor(requiredType, propertyName);

    // Value not of required type?
    if (editor != null
            || (requiredType != null && !ClassUtils.isAssignableValue(requiredType, convertedValue))) {
        if (editor == null) {
            editor = findDefaultEditor(requiredType, descriptor);
        }
        convertedValue = doConvertValue(oldValue, convertedValue, requiredType, editor);
    }

    if (requiredType != null) {
        // Try to apply some standard type conversion rules if appropriate.

        if (convertedValue != null) {
            if (String.class.equals(requiredType)
                    && ClassUtils.isPrimitiveOrWrapper(convertedValue.getClass())) {
                // We can stringify any primitive value...
                return convertedValue.toString();
            } else if (requiredType.isArray()) {
                // Array required -> apply appropriate conversion of elements.
                return convertToTypedArray(convertedValue, propertyName, requiredType.getComponentType());
            } else if (convertedValue instanceof Collection
                    && CollectionFactory.isApproximableCollectionType(requiredType)) {
                // Convert elements to target type, if determined.
                convertedValue = convertToTypedCollection((Collection) convertedValue, propertyName,
                        methodParam);
            } else if (convertedValue instanceof Map && CollectionFactory.isApproximableMapType(requiredType)) {
                // Convert keys and values to respective target type, if determined.
                convertedValue = convertToTypedMap((Map) convertedValue, propertyName, methodParam);
            } else if (convertedValue instanceof String && !requiredType.isInstance(convertedValue)) {
                String strValue = ((String) convertedValue).trim();
                if (JdkVersion.isAtLeastJava15() && requiredType.isEnum() && "".equals(strValue)) {
                    // It's an empty enum identifier: reset the enum value to null.
                    return null;
                }
                // Try field lookup as fallback: for JDK 1.5 enum or custom enum
                // with values defined as static fields. Resulting value still needs
                // to be checked, hence we don't return it right away.
                try {
                    Field enumField = requiredType.getField(strValue);
                    convertedValue = enumField.get(null);
                } catch (Exception ex) {
                    if (logger.isTraceEnabled()) {
                        logger.trace("Field [" + convertedValue + "] isn't an enum value", ex);
                    }
                }
            }
        }

        if (!ClassUtils.isAssignableValue(requiredType, convertedValue)) {
            // Definitely doesn't match: throw IllegalArgumentException.
            StringBuffer msg = new StringBuffer();
            msg.append("Cannot convert value of type [").append(ClassUtils.getDescriptiveType(newValue));
            msg.append("] to required type [").append(ClassUtils.getQualifiedName(requiredType)).append("]");
            if (propertyName != null) {
                msg.append(" for property '" + propertyName + "'");
            }
            if (editor != null) {
                msg.append(
                        ": PropertyEditor [" + editor.getClass().getName() + "] returned inappropriate value");
            } else {
                msg.append(": no matching editors or conversion strategy found");
            }
            throw new IllegalArgumentException(msg.toString());
        }
    }

    return convertedValue;
}

From source file:org.pushio.webapp.helper.json.SerializeConfig.java

public ObjectSerializer getObjectWriter(Class<?> clazz) {
    ObjectSerializer writer = get(clazz);

    if (writer == null) {
        try {//from   w  w  w .  j  a v  a  2  s.  c  o m
            final ClassLoader classLoader = Thread.currentThread().getContextClassLoader();
            for (Object o : ServiceLoader.load(AutowiredObjectSerializer.class, classLoader)) {
                if (!(o instanceof AutowiredObjectSerializer)) {
                    continue;
                }
                AutowiredObjectSerializer autowired = (AutowiredObjectSerializer) o;
                for (Type forType : autowired.getAutowiredFor()) {
                    put(forType, autowired);
                }
            }
        } catch (ClassCastException ex) {
            // skip
        }
        writer = get(clazz);
    }

    if (writer == null) {
        final ClassLoader classLoader = JSON.class.getClassLoader();
        if (classLoader != Thread.currentThread().getContextClassLoader()) {
            try {
                for (Object o : ServiceLoader.load(AutowiredObjectSerializer.class, classLoader)) {

                    if (!(o instanceof AutowiredObjectSerializer)) {
                        continue;
                    }

                    AutowiredObjectSerializer autowired = (AutowiredObjectSerializer) o;
                    for (Type forType : autowired.getAutowiredFor()) {
                        put(forType, autowired);
                    }
                }
            } catch (ClassCastException ex) {
                // skip
            }

            writer = get(clazz);
        }
    }

    if (writer == null) {
        if (Map.class.isAssignableFrom(clazz)) {
            put(clazz, MapSerializer.instance);
        } else if (List.class.isAssignableFrom(clazz)) {
            put(clazz, MyListSerializer.instance);
        } else if (Collection.class.isAssignableFrom(clazz)) {
            put(clazz, MyCollectionSerializer.instance);
        } else if (Date.class.isAssignableFrom(clazz)) {
            put(clazz, DateSerializer.instance);
        } else if (JSONAware.class.isAssignableFrom(clazz)) {
            put(clazz, JSONAwareSerializer.instance);
        } else if (JSONSerializable.class.isAssignableFrom(clazz)) {
            put(clazz, JSONSerializableSerializer.instance);
        } else if (JSONStreamAware.class.isAssignableFrom(clazz)) {
            put(clazz, JSONStreamAwareSerializer.instance);
        } else if (clazz.isEnum() || (clazz.getSuperclass() != null && clazz.getSuperclass().isEnum())) {
            put(clazz, EnumSerializer.instance);
        } else if (clazz.isArray()) {
            Class<?> componentType = clazz.getComponentType();
            ObjectSerializer compObjectSerializer = getObjectWriter(componentType);
            put(clazz, new ArraySerializer(componentType, compObjectSerializer));
        } else if (Throwable.class.isAssignableFrom(clazz)) {
            put(clazz, new ExceptionSerializer(clazz));
        } else if (TimeZone.class.isAssignableFrom(clazz)) {
            put(clazz, TimeZoneCodec.instance);
        } else if (Appendable.class.isAssignableFrom(clazz)) {
            put(clazz, AppendableSerializer.instance);
        } else if (Charset.class.isAssignableFrom(clazz)) {
            put(clazz, CharsetCodec.instance);
        } else if (Enumeration.class.isAssignableFrom(clazz)) {
            put(clazz, EnumerationSeriliazer.instance);
        } else if (Calendar.class.isAssignableFrom(clazz)) {
            put(clazz, CalendarCodec.instance);
        } else if (Clob.class.isAssignableFrom(clazz)) {
            put(clazz, ClobSeriliazer.instance);
        } else {
            boolean isCglibProxy = false;
            boolean isJavassistProxy = false;
            for (Class<?> item : clazz.getInterfaces()) {
                if (item.getName().equals("net.sf.cglib.proxy.Factory")
                        || item.getName().equals("org.springframework.cglib.proxy.Factory")) {
                    isCglibProxy = true;
                    break;
                } else if (item.getName().equals("javassist.util.proxy.ProxyObject")) {
                    isJavassistProxy = true;
                    break;
                }
            }

            if (isCglibProxy || isJavassistProxy) {
                Class<?> superClazz = clazz.getSuperclass();

                ObjectSerializer superWriter = getObjectWriter(superClazz);
                put(clazz, superWriter);

                return superWriter;
            }

            if (Proxy.isProxyClass(clazz)) {
                put(clazz, createJavaBeanSerializer(clazz));
            } else {
                put(clazz, createJavaBeanSerializer(clazz));
            }

        }

        writer = get(clazz);
    }
    return writer;
}

From source file:org.apache.hadoop.hbase.io.HbaseObjectWritable.java

/**
 * Write a {@link Writable}, {@link String}, primitive type, or an array of
 * the preceding./*w w  w. j  a  va 2 s  .  c  o  m*/
 * @param out
 * @param instance
 * @param declaredClass
 * @param conf
 * @throws IOException
 */
@SuppressWarnings("unchecked")
public static void writeObject(DataOutput out, Object instance, Class declaredClass, Configuration conf)
        throws IOException {

    Object instanceObj = instance;
    Class declClass = declaredClass;

    if (instanceObj == null) { // null
        instanceObj = new NullInstance(declClass, conf);
        declClass = Writable.class;
    }
    writeClassCode(out, declClass);
    if (declClass.isArray()) { // array
        // If bytearray, just dump it out -- avoid the recursion and
        // byte-at-a-time we were previously doing.
        if (declClass.equals(byte[].class)) {
            Bytes.writeByteArray(out, (byte[]) instanceObj);
        } else if (declClass.equals(Result[].class)) {
            Result.writeArray(out, (Result[]) instanceObj);
        } else {
            //if it is a Generic array, write the element's type
            if (getClassCode(declaredClass) == GENERIC_ARRAY_CODE) {
                Class<?> componentType = declaredClass.getComponentType();
                writeClass(out, componentType);
            }

            int length = Array.getLength(instanceObj);
            out.writeInt(length);
            for (int i = 0; i < length; i++) {
                Object item = Array.get(instanceObj, i);
                writeObject(out, item, item.getClass(), conf);
            }
        }
    } else if (List.class.isAssignableFrom(declClass)) {
        List list = (List) instanceObj;
        int length = list.size();
        out.writeInt(length);
        for (int i = 0; i < length; i++) {
            Object elem = list.get(i);
            writeObject(out, elem, elem == null ? Writable.class : elem.getClass(), conf);
        }
    } else if (declClass == String.class) { // String
        Text.writeString(out, (String) instanceObj);
    } else if (declClass.isPrimitive()) { // primitive type
        if (declClass == Boolean.TYPE) { // boolean
            out.writeBoolean(((Boolean) instanceObj).booleanValue());
        } else if (declClass == Character.TYPE) { // char
            out.writeChar(((Character) instanceObj).charValue());
        } else if (declClass == Byte.TYPE) { // byte
            out.writeByte(((Byte) instanceObj).byteValue());
        } else if (declClass == Short.TYPE) { // short
            out.writeShort(((Short) instanceObj).shortValue());
        } else if (declClass == Integer.TYPE) { // int
            out.writeInt(((Integer) instanceObj).intValue());
        } else if (declClass == Long.TYPE) { // long
            out.writeLong(((Long) instanceObj).longValue());
        } else if (declClass == Float.TYPE) { // float
            out.writeFloat(((Float) instanceObj).floatValue());
        } else if (declClass == Double.TYPE) { // double
            out.writeDouble(((Double) instanceObj).doubleValue());
        } else if (declClass == Void.TYPE) { // void
        } else {
            throw new IllegalArgumentException("Not a primitive: " + declClass);
        }
    } else if (declClass.isEnum()) { // enum
        Text.writeString(out, ((Enum) instanceObj).name());
    } else if (Message.class.isAssignableFrom(declaredClass)) {
        Text.writeString(out, instanceObj.getClass().getName());
        ((Message) instance).writeDelimitedTo(DataOutputOutputStream.constructOutputStream(out));
    } else if (Writable.class.isAssignableFrom(declClass)) { // Writable
        Class<?> c = instanceObj.getClass();
        Integer code = CLASS_TO_CODE.get(c);
        if (code == null) {
            out.writeByte(NOT_ENCODED);
            Text.writeString(out, c.getName());
        } else {
            writeClassCode(out, c);
        }
        ((Writable) instanceObj).write(out);
    } else if (Serializable.class.isAssignableFrom(declClass)) {
        Class<?> c = instanceObj.getClass();
        Integer code = CLASS_TO_CODE.get(c);
        if (code == null) {
            out.writeByte(NOT_ENCODED);
            Text.writeString(out, c.getName());
        } else {
            writeClassCode(out, c);
        }
        ByteArrayOutputStream bos = null;
        ObjectOutputStream oos = null;
        try {
            bos = new ByteArrayOutputStream();
            oos = new ObjectOutputStream(bos);
            oos.writeObject(instanceObj);
            byte[] value = bos.toByteArray();
            out.writeInt(value.length);
            out.write(value);
        } finally {
            if (bos != null)
                bos.close();
            if (oos != null)
                oos.close();
        }
    } else {
        throw new IOException("Can't write: " + instanceObj + " as " + declClass);
    }
}

From source file:org.apache.sqoop.SqoopOptions.java

/**
 * Return a Properties instance that encapsulates all the "sticky"
 * state of this SqoopOptions that should be written to a metastore
 * to restore the job later.//from  w ww .  j  a v a 2  s.c  o m
 */
public Properties writeProperties() {
    Properties props = new Properties();

    try {
        Field[] fields = SqoopOptions.class.getDeclaredFields();
        for (Field f : fields) {
            if (f.isAnnotationPresent(StoredAsProperty.class)) {
                Class typ = f.getType();
                StoredAsProperty storedAs = f.getAnnotation(StoredAsProperty.class);
                String propName = storedAs.value();

                if (typ.equals(int.class)) {
                    putProperty(props, propName, Integer.toString(f.getInt(this)));
                } else if (typ.equals(boolean.class)) {
                    putProperty(props, propName, Boolean.toString(f.getBoolean(this)));
                } else if (typ.equals(long.class)) {
                    putProperty(props, propName, Long.toString(f.getLong(this)));
                } else if (typ.equals(String.class)) {
                    putProperty(props, propName, (String) f.get(this));
                } else if (typ.equals(Integer.class)) {
                    putProperty(props, propName, f.get(this) == null ? "null" : f.get(this).toString());
                } else if (typ.isEnum()) {
                    putProperty(props, propName, f.get(this).toString());
                } else {
                    throw new RuntimeException("Could not set property " + propName + " for type: " + typ);
                }
            }
        }
    } catch (IllegalAccessException iae) {
        throw new RuntimeException("Illegal access to field in property setter", iae);
    }

    if (this.getConf().getBoolean(METASTORE_PASSWORD_KEY, METASTORE_PASSWORD_DEFAULT)) {
        // If the user specifies, we may store the password in the metastore.
        putProperty(props, "db.password", this.password);
        putProperty(props, "db.require.password", "false");
    } else if (this.password != null) {
        // Otherwise, if the user has set a password, we just record
        // a flag stating that the password will need to be reentered.
        putProperty(props, "db.require.password", "true");
    } else {
        // No password saved or required.
        putProperty(props, "db.require.password", "false");
    }

    putProperty(props, "db.column.list", arrayToList(this.columns));
    setDelimiterProperties(props, "codegen.input.delimiters", this.inputDelimiters);
    setDelimiterProperties(props, "codegen.output.delimiters", this.outputDelimiters);
    setArgArrayProperties(props, "tool.arguments", this.extraArgs);

    setPropertiesAsNestedProperties(props, "db.connect.params", this.connectionParams);

    setPropertiesAsNestedProperties(props, "map.column.hive", this.mapColumnHive);
    setPropertiesAsNestedProperties(props, "map.column.java", this.mapColumnJava);
    return props;
}

From source file:cn.afterturn.easypoi.excel.imports.CellValueService.java

/**
 * ??/*from w  ww . j a  va 2 s .c o m*/
 *
 * @param classFullName
 * @param result
 * @param entity
 * @param clazz
 * @return
 */
private Object getValueByType(String classFullName, Object result, ExcelImportEntity entity, Class clazz) {
    try {
        //,null,??
        if (result == null || StringUtils.isBlank(result.toString())) {
            return null;
        }
        if ("class java.util.Date".equals(classFullName) && result instanceof String) {
            return DateUtils.parseDate(result.toString(), entity.getFormat());
        }
        if ("class java.lang.Boolean".equals(classFullName) || "boolean".equals(classFullName)) {
            return Boolean.valueOf(String.valueOf(result));
        }
        if ("class java.lang.Double".equals(classFullName) || "double".equals(classFullName)) {
            return Double.valueOf(String.valueOf(result));
        }
        if ("class java.lang.Long".equals(classFullName) || "long".equals(classFullName)) {
            try {
                return Long.valueOf(String.valueOf(result));
            } catch (Exception e) {
                //?,double,??Int
                return Double.valueOf(String.valueOf(result)).longValue();
            }
        }
        if ("class java.lang.Float".equals(classFullName) || "float".equals(classFullName)) {
            return Float.valueOf(String.valueOf(result));
        }
        if ("class java.lang.Integer".equals(classFullName) || "int".equals(classFullName)) {
            try {
                return Integer.valueOf(String.valueOf(result));
            } catch (Exception e) {
                //?,double,??Int
                return Double.valueOf(String.valueOf(result)).intValue();
            }
        }
        if ("class java.math.BigDecimal".equals(classFullName)) {
            return new BigDecimal(String.valueOf(result));
        }
        if ("class java.lang.String".equals(classFullName)) {
            //String ,Excel????String,Double,
            if (result instanceof String) {
                return result;
            }
            // double
            if (result instanceof Double) {
                return PoiPublicUtil.doubleToString((Double) result);
            }
            return String.valueOf(result);
        }
        if (clazz != null && clazz.isEnum()) {
            if (StringUtils.isNotEmpty(entity.getEnumImportMethod())) {
                return PoiReflectorUtil.fromCache(clazz).execEnumStaticMethod(entity.getEnumImportMethod(),
                        result);
            } else {
                return Enum.valueOf(clazz, result.toString());
            }
        }
        return result;
    } catch (Exception e) {
        LOGGER.error(e.getMessage(), e);
        throw new ExcelImportException(ExcelImportEnum.GET_VALUE_ERROR);
    }
}

From source file:com.evolveum.midpoint.prism.parser.PrismBeanConverter.java

private <T> T unmarshallPrimitive(PrimitiveXNode<?> xprim, Class<T> classType) throws SchemaException {
    if (XmlAsStringType.class.equals(classType)) {
        return (T) new XmlAsStringType((String) xprim.getParsedValue(DOMUtil.XSD_STRING));
    }// w  w w  .  jav  a2 s . c o  m
    if (XmlTypeConverter.canConvert(classType)) {
        // Trivial case, direct conversion
        QName xsdType = XsdTypeMapper.toXsdType(classType);
        T primValue = postConvertUnmarshall(xprim.getParsedValue(xsdType));
        return primValue;
    }

    if (RawType.class.isAssignableFrom(classType)) {
        RawType rawType = new RawType(xprim, prismContext);
        return (T) rawType;
    }

    if (PolyStringType.class.isAssignableFrom(classType)) {
        String value = (String) xprim.getParsedValue(DOMUtil.XSD_STRING);
        PolyString polyString = new PolyString(value);
        if (value != null) {
            if (prismContext != null) { // actually this should be always so [med]
                // TODO should we always use default normalizer?
                polyString.recompute(prismContext.getDefaultPolyStringNormalizer());
            }
        }
        return (T) new PolyStringType(polyString);
    }

    if (ItemPathType.class.isAssignableFrom(classType)) {
        Object parsedValue = xprim.getParsedValue(ItemPathType.COMPLEX_TYPE);
        T primValue = postConvertUnmarshall(parsedValue);
        return (T) primValue;
    }

    if (SearchFilterType.class.isAssignableFrom(classType)) {
        throw new SchemaException("Cannot unmarshall search filter from " + xprim);
    }

    if (xprim.isEmpty() && !classType.isEnum()) {
        // Special case. Just return empty object
        try {
            return classType.newInstance();
        } catch (InstantiationException | IllegalAccessException e) {
            throw new SystemException("Cannot instantiate " + classType + ": " + e.getMessage(), e);
        }
    }

    if (!classType.isEnum()) {
        throw new SchemaException("Cannot convert primitive value to non-enum bean of type " + classType);
    }
    // Assume string, maybe TODO extend later
    String primValue = (String) xprim.getParsedValue(DOMUtil.XSD_STRING);
    if (StringUtils.isBlank(primValue)) {
        return null;
    }
    primValue = StringUtils.trim(primValue);

    String javaEnumString = inspector.findEnumFieldName(classType, primValue);
    //      for (Field field: classType.getDeclaredFields()) {
    //         XmlEnumValue xmlEnumValue = field.getAnnotation(XmlEnumValue.class);
    //         if (xmlEnumValue != null && xmlEnumValue.value() != null && xmlEnumValue.value().equals(primValue)) {
    //            javaEnumString = field.getName();
    //            break;
    //         }
    //      }

    if (javaEnumString == null) {
        for (Field field : classType.getDeclaredFields()) {
            if (field.getName().equals(primValue)) {
                javaEnumString = field.getName();
                break;
            }
        }
    }

    if (javaEnumString == null) {
        throw new SchemaException("Cannot find enum value for string '" + primValue + "' in " + classType);
    }

    T bean = (T) Enum.valueOf((Class<Enum>) classType, javaEnumString);

    return bean;
}