Example usage for java.lang Long TYPE

List of usage examples for java.lang Long TYPE

Introduction

In this page you can find the example usage for java.lang Long TYPE.

Prototype

Class TYPE

To view the source code for java.lang Long TYPE.

Click Source Link

Document

The Class instance representing the primitive type long .

Usage

From source file:org.apache.oodt.cas.cli.util.CmdLineUtils.java

public static List<?> convertToType(List<String> values, Class<?> type)
        throws MalformedURLException, ClassNotFoundException, InstantiationException, IllegalAccessException {
    if (type.equals(File.class)) {
        List<Object> files = new LinkedList<Object>();
        for (String value : values) {
            files.add(new File(value));
        }/*from  w w w . j  a va2s .c  om*/
        return files;
    } else if (type.equals(Boolean.class) || type.equals(Boolean.TYPE)) {
        List<Object> booleans = new LinkedList<Object>();
        for (String value : values) {
            booleans.add(value.toLowerCase().trim().equals("true"));
        }
        return booleans;
    } else if (type.equals(URL.class)) {
        List<Object> urls = new LinkedList<Object>();
        for (String value : values) {
            urls.add(new URL(value));
        }
        return urls;
    } else if (type.equals(Class.class)) {
        List<Object> classes = new LinkedList<Object>();
        for (String value : values) {
            classes.add(Class.forName(value));
        }
        return classes;
    } else if (type.equals(List.class)) {
        List<Object> lists = new LinkedList<Object>();
        lists.add(values);
        return lists;
    } else if (type.equals(Integer.class) || type.equals(Integer.TYPE)) {
        List<Object> ints = new LinkedList<Object>();
        for (String value : values) {
            ints.add(Integer.valueOf(value));
        }
        return ints;
    } else if (type.equals(Long.class) || type.equals(Long.TYPE)) {
        List<Object> longs = new LinkedList<Object>();
        for (String value : values) {
            longs.add(Long.valueOf(value));
        }
        return longs;
    } else if (type.equals(Double.class) || type.equals(Double.TYPE)) {
        List<Object> doubles = new LinkedList<Object>();
        for (String value : values) {
            doubles.add(new Double(value));
        }
        return doubles;
    } else if (type.equals(String.class)) {
        StringBuilder combinedString = new StringBuilder("");
        for (String value : values) {
            combinedString.append(value).append(" ");
        }
        return Lists.newArrayList(combinedString.toString().trim());
    } else {
        List<Object> objects = new LinkedList<Object>();
        for (String value : values) {
            Object object = Class.forName(value).newInstance();
            if (!type.isAssignableFrom(object.getClass())) {
                throw new RuntimeException(
                        object.getClass() + " is not a valid" + " type or sub-type of " + type);
            }
            objects.add(object);
        }
        return objects;
    }
}

From source file:org.apache.sling.models.impl.ModelAdapterFactory.java

private static boolean isAcceptableType(Class<?> type, Type genericType, Object value) {
    if (type.isInstance(value)) {
        if ((type == Collection.class || type == List.class) && genericType instanceof ParameterizedType
                && value instanceof Collection) {
            Iterator<?> it = ((Collection<?>) value).iterator();
            if (!it.hasNext()) {
                // empty collection, so it doesn't really matter
                return true;
            } else {
                // this is not an ideal way to get the actual component type, but erasure...
                Class<?> actualComponentType = it.next().getClass();
                Class<?> desiredComponentType = (Class<?>) ((ParameterizedType) genericType)
                        .getActualTypeArguments()[0];
                return desiredComponentType.isAssignableFrom(actualComponentType);
            }/*from  w w  w .j  a  va2s  .  c  o m*/
        } else {
            return true;
        }
    }

    if (type == Integer.TYPE) {
        return Integer.class.isInstance(value);
    }
    if (type == Long.TYPE) {
        return Long.class.isInstance(value);
    }
    if (type == Boolean.TYPE) {
        return Boolean.class.isInstance(value);
    }
    if (type == Double.TYPE) {
        return Double.class.isInstance(value);
    }
    if (type == Float.TYPE) {
        return Float.class.isInstance(value);
    }
    if (type == Short.TYPE) {
        return Short.class.isInstance(value);
    }
    if (type == Byte.TYPE) {
        return Byte.class.isInstance(value);
    }
    if (type == Character.TYPE) {
        return Character.class.isInstance(value);
    }

    return false;
}

From source file:alice.tuprolog.lib.OOLibrary.java

private boolean parse_arg(Object[] values, Class<?>[] types, int i, PTerm term) {
    try {/*from  w w  w. j  a v a  2  s . c o m*/
        if (term == null) {
            values[i] = null;
            types[i] = null;
        } else if (term.isAtom()) {
            String name = alice.util.Tools.removeApices(term.toString());
            switch (name) {
            case "true":
                values[i] = Boolean.TRUE;
                types[i] = Boolean.TYPE;
                break;
            case "false":
                values[i] = Boolean.FALSE;
                types[i] = Boolean.TYPE;
                break;
            default:
                Object obj = currentObjects.get(name);
                values[i] = obj == null ? name : obj;
                types[i] = values[i].getClass();
                break;
            }
        } else if (term instanceof Number) {
            Number t = (Number) term;
            if (t instanceof Int) {
                values[i] = t.intValue();
                types[i] = java.lang.Integer.TYPE;
            } else if (t instanceof alice.tuprolog.Double) {
                values[i] = t.doubleValue();
                types[i] = java.lang.Double.TYPE;
            } else if (t instanceof alice.tuprolog.Long) {
                values[i] = t.longValue();
                types[i] = java.lang.Long.TYPE;
            } else if (t instanceof alice.tuprolog.Float) {
                values[i] = t.floatValue();
                types[i] = java.lang.Float.TYPE;
            }
        } else if (term instanceof Struct) {
            // argument descriptors
            Struct tc = (Struct) term;
            if (tc.getName().equals("as")) {
                return parse_as(values, types, i, tc.getTerm(0), tc.getTerm(1));
            } else {
                Object obj = currentObjects.get(alice.util.Tools.removeApices(tc.toString()));
                values[i] = obj == null ? alice.util.Tools.removeApices(tc.toString()) : obj;
                types[i] = values[i].getClass();
            }
        } else if (term instanceof Var && !((Var) term).isBound()) {
            values[i] = null;
            types[i] = Object.class;
        } else {
            return false;
        }
    } catch (Exception ex) {
        return false;
    }
    return true;
}

From source file:com.ricemap.spateDB.core.RTree.java

/**
 * Searches the RTree starting from the given start position. This is either
 * a node number or offset of an element. If it's a node number, it performs
 * the search in the subtree rooted at this node. If it's an offset number,
 * it searches only the object found there. It is assumed that the
 * openQuery() has been called before this function and that endQuery() will
 * be called afterwards./*from   w  w  w.  j a va  2s . c  o  m*/
 * 
 * @param query_mbr
 * @param output
 * @param start
 *            - where to start searching
 * @param end
 *            - where to end searching. Only used when start is an offset of
 *            an object.
 * @return
 * @throws IOException
 */
protected int searchColumnar(Shape query_shape, ResultCollector<Writable> output, int start, int end,
        String field) throws IOException {
    if (output == null) {
        throw new RuntimeException("Output is NULL");
    }
    //build search field
    int fieldOffset = 0;
    int fieldSize = -1;
    FIELD_TYPE fieldType = FIELD_TYPE.NULL;
    //get fields
    Field[] fields = stockObject.getClass().getDeclaredFields();

    for (int i = 0; i < fields.length; i++) {
        if (fields[i].getName().equals(field)) {
            if (fields[i].getType().equals(Integer.TYPE)) {
                fieldSize = 4;
                fieldType = FIELD_TYPE.Integer;

            } else if (fields[i].getType().equals(Long.TYPE)) {
                fieldSize = 8;
                fieldType = FIELD_TYPE.Long;
            } else if (fields[i].getType().equals(Double.TYPE)) {
                fieldSize = 8;
                fieldType = FIELD_TYPE.Double;
            } else {
                //throw new RuntimeException("Unsupported type: " + fields[i].getType());
            }
            break;
        } else {
            if (fields[i].getType().equals(Integer.TYPE)) {
                fieldOffset += elementCount * 4;
            } else if (fields[i].getType().equals(Long.TYPE) || fields[i].getType().equals(Double.TYPE)) {
                fieldOffset += elementCount * 8;
            } else {
                //throw new RuntimeException("Unsupported type: " + fields[i].getType());
            }
        }
    }

    Prism query_mbr = query_shape.getMBR();
    int resultSize = 0;
    // Special case for an empty tree
    if (height == 0)
        return 0;

    Stack<Integer> toBeSearched = new Stack<Integer>();
    // Start from the given node
    toBeSearched.push(start);
    if (start >= nodeCount) {
        toBeSearched.push(end);
    }

    Prism node_mbr = new Prism();

    // Holds one data line from tree data
    Text line = new Text2();

    while (!toBeSearched.isEmpty()) {
        int searchNumber = toBeSearched.pop();
        int mbrsToTest = searchNumber == 0 ? 1 : degree;

        if (searchNumber < nodeCount) {
            long nodeOffset = NodeSize * searchNumber;
            structure.seek(nodeOffset);
            int dataOffset = structure.readInt();

            for (int i = 0; i < mbrsToTest; i++) {
                node_mbr.readFields(structure);
                int lastOffset = (searchNumber + i) == nodeCount - 1 ? elementCount - 1 : structure.readInt();
                if (query_mbr.contains(node_mbr)) {
                    // The node is full contained in the query range.
                    // Save the time and do full scan for this node

                    // Checks if this node is the last node in its level
                    // This can be easily detected because the next node in
                    // the level
                    // order traversal will be the first node in the next
                    // level
                    // which means it will have an offset less than this
                    // node
                    if (lastOffset <= dataOffset)
                        lastOffset = elementCount;

                    data.seek(treeStartOffset + TreeHeaderSize + nodeCount * NodeSize
                            + elementCount * IndexUnitSize + fieldOffset + dataOffset * fieldSize);
                    for (int j = 0; j < lastOffset - dataOffset; j++) {
                        switch (fieldType) {
                        case Integer:
                            output.collect(new IntWritable(data.readInt()));
                            break;
                        case Long:
                            output.collect(new LongWritable(data.readLong()));
                            break;
                        case Double:
                            output.collect(new DoubleWritable(data.readDouble()));
                            break;
                        default:
                            output.collect(
                                    new Point3d(data.readDouble(), data.readDouble(), data.readDouble()));
                            break;
                        }
                        resultSize++;
                    }

                } else if (query_mbr.isIntersected(node_mbr)) {
                    // Node partially overlaps with query. Go deep under
                    // this node
                    if (searchNumber < nonLeafNodeCount) {
                        // Search child nodes
                        toBeSearched.push((searchNumber + i) * degree + 1);
                    } else {
                        // Search all elements in this node
                        //toBeSearched.push(dataOffset);
                        // Checks if this node is the last node in its level
                        // This can be easily detected because the next node
                        // in the level
                        // order traversal will be the first node in the
                        // next level
                        // which means it will have an offset less than this
                        // node
                        if (lastOffset <= dataOffset)
                            lastOffset = elementCount;
                        //toBeSearched.push(lastOffset);
                        data.seek(treeStartOffset + TreeHeaderSize + nodeCount * NodeSize
                                + dataOffset * IndexUnitSize);
                        boolean report[] = new boolean[lastOffset - dataOffset];
                        Point3d point = new Point3d();
                        for (int j = 0; j < lastOffset - dataOffset; j++) {
                            point.t = data.readDouble();
                            point.x = data.readDouble();
                            point.y = data.readDouble();
                            if (point.isIntersected(query_shape)) {
                                report[j] = true;
                            } else
                                report[j] = false;
                        }
                        data.seek(treeStartOffset + TreeHeaderSize + nodeCount * NodeSize
                                + elementCount * IndexUnitSize + fieldOffset + dataOffset * fieldSize);
                        for (int j = 0; j < lastOffset - dataOffset; j++) {
                            if (report[j]) {
                                switch (fieldType) {
                                case Integer:
                                    output.collect(new IntWritable(data.readInt()));
                                    break;
                                case Long:
                                    output.collect(new LongWritable(data.readLong()));
                                    break;
                                case Double:
                                    output.collect(new DoubleWritable(data.readDouble()));
                                    break;
                                default:
                                    output.collect(new Point3d(data.readDouble(), data.readDouble(),
                                            data.readDouble()));
                                    break;
                                }
                                resultSize++;
                            }
                        }
                    }
                }
                dataOffset = lastOffset;
            }
        } else {
            LOG.error("searchNumber > nodeCount, something is wrong");
            int firstOffset, lastOffset;
            // Search for data items (records)
            lastOffset = searchNumber;
            firstOffset = toBeSearched.pop();

            data.seek(firstOffset + treeStartOffset);
            LineReader lineReader = new LineReader(data);
            while (firstOffset < lastOffset) {
                firstOffset += lineReader.readLine(line);
                stockObject.fromText(line);
                if (stockObject.isIntersected(query_shape)) {
                    resultSize++;
                    if (output != null)
                        output.collect(stockObject);
                }
            }
        }
    }
    return resultSize;
}

From source file:org.apache.maven.plugin.javadoc.AbstractFixJavadocMojo.java

/**
 * Add a default Javadoc for the given field, i.e.:
 * <br/>/*w ww.  j  a va  2 s .c o m*/
 * <code>
 * <font color="#808080">1</font>&nbsp;<font color="#ffffff">&nbsp;&nbsp;&nbsp;&nbsp;</font>
 * <font color="#3f5fbf">&#47;&#42;&#42;&nbsp;Constant&nbsp;</font><font color="#7f7f9f">&lt;code&gt;</font>
 * <font color="#3f5fbf">MY_STRING_CONSTANT=&#34;value&#34;</font>
 * <font color="#7f7f9f">&lt;/code&gt;&nbsp;</font><font color="#3f5fbf">&#42;&#47;</font><br />
 * <font color="#808080">2</font>&nbsp;<font color="#ffffff">&nbsp;&nbsp;&nbsp;&nbsp;</font>
 * <font color="#7f0055"><b>public&nbsp;static&nbsp;final&nbsp;</b></font>
 * <font color="#000000">String&nbsp;MY_STRING_CONSTANT&nbsp;=&nbsp;</font>
 * <font color="#2a00ff">&#34;value&#34;</font><font color="#000000">;</font>
 * </code>
 *
 * @param stringWriter not null
 * @param field        not null
 * @param indent       not null
 * @throws IOException if any
 */
private void addDefaultFieldComment(final StringWriter stringWriter, final JavaField field, final String indent)
        throws IOException {
    StringBuilder sb = new StringBuilder();

    sb.append(indent).append(START_JAVADOC).append(" ");
    sb.append("Constant <code>").append(field.getName());

    if (StringUtils.isNotEmpty(field.getInitializationExpression())) {
        String qualifiedName = field.getType().getJavaClass().getFullyQualifiedName();

        if (qualifiedName.equals(Byte.TYPE.toString()) || qualifiedName.equals(Short.TYPE.toString())
                || qualifiedName.equals(Integer.TYPE.toString()) || qualifiedName.equals(Long.TYPE.toString())
                || qualifiedName.equals(Float.TYPE.toString()) || qualifiedName.equals(Double.TYPE.toString())
                || qualifiedName.equals(Boolean.TYPE.toString())
                || qualifiedName.equals(Character.TYPE.toString())) {
            sb.append("=");
            sb.append(field.getInitializationExpression().trim());
        }

        if (qualifiedName.equals(String.class.getName())) {
            StringBuilder value = new StringBuilder();
            String[] lines = getLines(field.getInitializationExpression());
            for (String line : lines) {
                StringTokenizer token = new StringTokenizer(line.trim(), "\"\n\r");
                while (token.hasMoreTokens()) {
                    String s = token.nextToken();

                    if (s.trim().equals("+")) {
                        continue;
                    }
                    if (s.trim().endsWith("\\")) {
                        s += "\"";
                    }
                    value.append(s);
                }
            }

            sb.append("=\"");
            // reduce the size
            if (value.length() < 40) {
                sb.append(value.toString()).append("\"");
            } else {
                sb.append(value.toString().substring(0, 39)).append("\"{trunked}");
            }
        }
    }

    sb.append("</code> ").append(END_JAVADOC);
    sb.append(EOL);

    stringWriter.write(sb.toString());
}

From source file:cn.sinobest.jzpt.framework.utils.string.StringUtils.java

/**
 *  obj isArrayJoin//from   w w  w.j a v a  2 s.com
 *
 * @Title: join
 * @return String 
 * @throws
 */
public static String join(Object obj, String dchar) {
    Assert.notNull(obj);
    if (!obj.getClass().isArray()) {
        throw new IllegalArgumentException("The input object to join must be a Array and not null.");
    }
    Class<?> priType = obj.getClass().getComponentType();
    if (priType == Boolean.TYPE) {
        return join((boolean[]) obj, dchar);
    } else if (priType == Byte.TYPE) {
        return join((byte[]) obj, dchar);
    } else if (priType == Character.TYPE) {
        return join((char[]) obj, dchar);
    } else if (priType == Integer.TYPE) {
        return join((int[]) obj, dchar);
    } else if (priType == Long.TYPE) {
        return join((long[]) obj, dchar);
    } else if (priType == Float.TYPE) {
        return join((float[]) obj, dchar);
    } else if (priType == Double.TYPE) {
        return join((double[]) obj, dchar);
    } else if (priType == Short.TYPE) {
        return join((short[]) obj, dchar);
    } else {
        return join((Object[]) obj, dchar);
    }
}

From source file:com.taobao.adfs.util.Utilities.java

public static String getSqlTypeForJavaType(Class<?> type) throws IOException {
    if (type == null)
        throw new IOException("type is null");
    if (type.equals(Byte.TYPE) || type.equals(Byte.class))
        return "TINYINT";
    if (type.equals(Short.TYPE) || type.equals(Short.class))
        return "SMALLINT";
    if (type.equals(Integer.TYPE) || type.equals(Integer.class))
        return "INT";
    if (type.equals(Long.TYPE) || type.equals(Long.class))
        return "BIGINT";
    if (type.equals(Float.TYPE) || type.equals(Float.class))
        return "FLOAT";
    if (type.equals(Double.TYPE) || type.equals(Double.class))
        return "DOUBLE";
    if (type.equals(String.class))
        return "VARCHAR";
    else/*from  w  w  w .ja v  a2s  . c o  m*/
        throw new IOException("unsupportted type=" + type.getSimpleName());
}

From source file:alice.tuprolog.lib.OOLibrary.java

/**
 * /* www  .j a  v  a2 s  .  c o m*/
 * parsing 'as' operator, which makes it possible to define the specific
 * class of an argument
 * 
 */
private boolean parse_as(Object[] values, Class<?>[] types, int i, PTerm castWhat, PTerm castTo) {
    try {
        if (!(castWhat instanceof Number)) {
            String castTo_name = alice.util.Tools.removeApices(((Struct) castTo).getName());
            String castWhat_name = alice.util.Tools.removeApices(castWhat.getTerm().toString());
            // System.out.println(castWhat_name+" "+castTo_name);
            if (castTo_name.equals("java.lang.String") && castWhat_name.equals("true")) {
                values[i] = "true";
                types[i] = String.class;
                return true;
            } else if (castTo_name.equals("java.lang.String") && castWhat_name.equals("false")) {
                values[i] = "false";
                types[i] = String.class;
                return true;
            } else if (castTo_name.endsWith("[]")) {
                switch (castTo_name) {
                case "boolean[]":
                    castTo_name = "[Z";
                    break;
                case "byte[]":
                    castTo_name = "[B";
                    break;
                case "short[]":
                    castTo_name = "[S";
                    break;
                case "char[]":
                    castTo_name = "[C";
                    break;
                case "int[]":
                    castTo_name = "[I";
                    break;
                case "long[]":
                    castTo_name = "[L";
                    break;
                case "float[]":
                    castTo_name = "[F";
                    break;
                case "double[]":
                    castTo_name = "[D";
                    break;
                default:
                    castTo_name = "[L" + castTo_name.substring(0, castTo_name.length() - 2) + ';';
                    break;
                }
            }
            if (!castWhat_name.equals("null")) {
                Object obj_to_cast = currentObjects.get(castWhat_name);
                if (obj_to_cast == null) {
                    if (castTo_name.equals("boolean")) {
                        switch (castWhat_name) {
                        case "true":
                            values[i] = new Boolean(true);
                            break;
                        case "false":
                            values[i] = new Boolean(false);
                            break;
                        default:
                            return false;
                        }
                        types[i] = Boolean.TYPE;
                    } else {
                        // conversion to array
                        return false;
                    }
                } else {
                    values[i] = obj_to_cast;
                    try {
                        types[i] = Class.forName(castTo_name, true, dynamicLoader);
                    } catch (ClassNotFoundException ex) {
                        getEngine().logger.warn("Java class not found: " + castTo_name);
                        return false;
                    }
                }
            } else {
                values[i] = null;
                switch (castTo_name) {
                case "byte":
                    types[i] = Byte.TYPE;
                    break;
                case "short":
                    types[i] = Short.TYPE;
                    break;
                case "char":
                    types[i] = Character.TYPE;
                    break;
                case "int":
                    types[i] = Integer.TYPE;
                    break;
                case "long":
                    types[i] = java.lang.Long.TYPE;
                    break;
                case "float":
                    types[i] = java.lang.Float.TYPE;
                    break;
                case "double":
                    types[i] = java.lang.Double.TYPE;
                    break;
                case "boolean":
                    types[i] = Boolean.TYPE;
                    break;
                default:
                    try {
                        types[i] = Class.forName(castTo_name, true, dynamicLoader);
                    } catch (ClassNotFoundException ex) {
                        getEngine().logger.warn("Java class not found: " + castTo_name);
                        return false;
                    }
                    break;
                }
            }
        } else {
            Number num = (Number) castWhat;
            String castTo_name = ((Struct) castTo).getName();
            switch (castTo_name) {
            case "byte":
                values[i] = new Byte((byte) num.intValue());
                types[i] = Byte.TYPE;
                break;
            case "short":
                values[i] = new Short((short) num.intValue());
                types[i] = Short.TYPE;
                break;
            case "int":
                values[i] = new Integer(num.intValue());
                types[i] = Integer.TYPE;
                break;
            case "long":
                values[i] = new java.lang.Long(num.longValue());
                types[i] = java.lang.Long.TYPE;
                break;
            case "float":
                values[i] = new java.lang.Float(num.floatValue());
                types[i] = java.lang.Float.TYPE;
                break;
            case "double":
                values[i] = new java.lang.Double(num.doubleValue());
                types[i] = java.lang.Double.TYPE;
                break;
            default:
                return false;
            }
        }
    } catch (Exception ex) {
        getEngine().logger.warn("Casting " + castWhat + " to " + castTo + " failed");
        return false;
    }
    return true;
}

From source file:org.fornax.cartridges.sculptor.smartclient.server.ScServlet.java

private void mapRequestToObj(HashMap<String, Object> data, Class expectedClass, Object obj) throws Exception {
    if (obj == null) {
        throw new ApplicationException("mapRequestToObj called on NULL obj", "ERR9001");
    }//from   w  w  w. j a  v a  2s.c om

    try {
        Method versionMethod = expectedClass.getMethod("getVersion", (Class<?>[]) null);
        Long objVersion = (Long) versionMethod.invoke(obj, (Object[]) null);
        String clientVersion = (String) data.get("version");
        if (objVersion != null && clientVersion != null) {
            try {
                long clientVersionLong = Long.parseLong(clientVersion);
                if (!objVersion.equals(clientVersionLong)) {
                    throw makeApplicationException("Can't save object", "ERR9016", (Serializable[]) null);
                }
            } catch (NumberFormatException nfe) {
                // Version from client isn't number - ignore
            }
        }
    } catch (NoSuchMethodException nme) {
        // No version control
    }

    Method[] methods = expectedClass.getMethods();
    for (Method m : methods) {
        Class<?>[] paramTypes = m.getParameterTypes();

        Class persistentClass = null;
        if (paramTypes.length == 1) {
            if (paramTypes[0].getAnnotation(Entity.class) != null) {
                persistentClass = paramTypes[0];
            } else if (paramTypes[0].getAnnotation(Embeddable.class) != null) {
                persistentClass = paramTypes[0];
            }
        }
        ServiceDescription srvParam = paramTypes.length == 1 ? findServiceByClassName(paramTypes[0].getName())
                : null;
        if ((m.getName().startsWith(SET_PREFIX) && paramTypes.length == 1
                && (paramTypes[0].isAssignableFrom(String.class) || paramTypes[0].equals(Integer.class)
                        || paramTypes[0].equals(Integer.TYPE) || paramTypes[0].equals(Long.class)
                        || paramTypes[0].equals(Long.TYPE) || paramTypes[0].equals(Float.class)
                        || paramTypes[0].equals(Float.TYPE) || paramTypes[0].equals(Boolean.class)
                        || paramTypes[0].equals(Boolean.TYPE) || paramTypes[0].equals(Double.class)
                        || paramTypes[0].equals(Double.TYPE) || paramTypes[0].equals(Date.class)
                        || Enum.class.isAssignableFrom(paramTypes[0])
                        || (srvParam != null && srvParam.getFindById() != null) || persistentClass != null))
                || (m.getName().startsWith(GET_PREFIX) && paramTypes.length == 0
                        && (Set.class.isAssignableFrom(m.getReturnType())
                                || List.class.isAssignableFrom(m.getReturnType())))) {
            String fldName;
            if (m.getName().startsWith(GET_TRANSLATE)) {
                fldName = m.getName().substring(GET_TRANSLATE_LENGTH, GET_TRANSLATE_LENGTH + 1).toLowerCase()
                        + m.getName().substring(GET_TRANSLATE_LENGTH + 1);
            } else {
                fldName = m.getName().substring(3, 4).toLowerCase() + m.getName().substring(4);
            }
            Object value = data.get(fldName);
            if (value == null) {
                fldName = m.getName().substring(3);
                value = data.get(fldName);
            }
            if (value != null) {
                Object typedVal;
                String val = null;
                if (value instanceof String) {
                    val = (String) value;
                }
                log.log(Level.FINER, "        value = " + value);
                if (m.getName().startsWith(GET_PREFIX) && paramTypes.length == 0
                        && (Set.class.isAssignableFrom(m.getReturnType())
                                || List.class.isAssignableFrom(m.getReturnType()))) {
                    log.log(Level.FINER, "GET");

                    String attrName = m.getName().substring(3, 4).toLowerCase() + m.getName().substring(4);
                    Type[] actualTypeArguments = null;
                    Class iterClass = expectedClass;
                    while (iterClass != null) {
                        try {
                            Field field = iterClass.getDeclaredField(attrName);
                            ParameterizedType genericType = (ParameterizedType) field.getGenericType();
                            actualTypeArguments = genericType.getActualTypeArguments();
                            break;
                        } catch (NoSuchFieldException nsfe) {
                            // do nothing iterate again
                        }
                        iterClass = iterClass.getSuperclass();
                        iterClass = iterClass.equals(Object.class) ? null : iterClass;
                    }

                    if (actualTypeArguments != null && actualTypeArguments.length == 1
                            && actualTypeArguments[0] instanceof Class) {
                        Class assocClass = (Class) actualTypeArguments[0];
                        ServiceDescription assocService = findServiceByClassName(assocClass.getName());
                        Collection dbValueSet = (Collection) m.invoke(obj, (Object[]) null);
                        if (value == null || !(value instanceof HashMap)) {
                            log.log(Level.FINE, "No data for db property {0}", attrName);
                        } else if (assocService != null) {
                            HashMap<String, Object> guiValueMap = (HashMap<String, Object>) value;

                            ArrayList<Object> removeIt = new ArrayList<Object>();
                            Iterator dbIterator = dbValueSet.iterator();
                            while (dbIterator.hasNext()) {
                                Object dbVal = dbIterator.next();
                                String dbValId = getIdFromObj(dbVal);

                                if (dbValId != null) {
                                    boolean wasMatchingGuiVal = false;
                                    ArrayList<String> removeKeys = new ArrayList<String>();
                                    for (String key : guiValueMap.keySet()) {
                                        Object object = guiValueMap.get(key);
                                        if (object instanceof HashMap) {
                                            Object guiValue = ((HashMap<String, Object>) object).get("id");
                                            if (guiValue.equals(dbValId)) {
                                                removeKeys.add(key);
                                                wasMatchingGuiVal = true;
                                                mapRequestToObj((HashMap<String, Object>) guiValue, assocClass,
                                                        dbVal);
                                                break;
                                            }
                                        } else if (object instanceof String) {
                                            // Association
                                            if (dbValId.equals(object)) {
                                                removeKeys.add(key);
                                                wasMatchingGuiVal = true;
                                            }
                                        } else {
                                            log.log(Level.WARNING, "Wrong object type from GUI under key {0}",
                                                    key);
                                        }
                                    }
                                    // Remove processed elements
                                    // Direct remove is firing concurrent modification exception
                                    for (String removeKey : removeKeys) {
                                        guiValueMap.remove(removeKey);
                                    }

                                    if (!wasMatchingGuiVal) {
                                        // Is not in list comming from GUI - delete
                                        removeIt.add(dbVal);
                                    }
                                } else {
                                    log.log(Level.WARNING, "No ID in object {0}", dbVal);
                                }
                            }
                            dbValueSet.removeAll(removeIt);

                            // Rest are new records
                            for (String key : guiValueMap.keySet()) {
                                Object object = guiValueMap.get(key);
                                if (object instanceof HashMap) {
                                    Object subObj = makeNewInstance(assocClass,
                                            (HashMap<String, Object>) object);
                                    mapRequestToObj((HashMap<String, Object>) object, assocClass, subObj);
                                    dbValueSet.add(subObj);
                                } else if (object instanceof String) {
                                    // Association
                                    try {
                                        Long id = new Long((String) object);
                                        Object assocObj = assocService.getFindById().invoke(
                                                assocService.getInstance(), ServiceContextStore.get(), id);
                                        if (assocObj != null) {
                                            dbValueSet.add(assocObj);
                                        } else {
                                            log.log(Level.WARNING,
                                                    "Object with ID {0} not availabla via service {1}",
                                                    new Object[] { id, assocService.getName() });
                                        }
                                    } catch (Exception ex) {
                                        log.log(Level.WARNING, "No ID parsable from value {0} under key {1}",
                                                new Object[] { object, key });
                                    }
                                } else {
                                    log.log(Level.WARNING, "Wrong sub type {0}", attrName);
                                }
                            }
                        } else if (assocClass != null) {
                            HashMap<String, Object> guiValueMap = (HashMap<String, Object>) value;

                            ArrayList<Object> removeIt = new ArrayList<Object>();
                            Iterator dbIterator = dbValueSet.iterator();
                            while (dbIterator.hasNext()) {
                                Object dbVal = dbIterator.next();
                                String dbValId = getIdFromObj(dbVal);

                                if (dbValId != null) {
                                    Object matchingGuiVal = null;
                                    for (String key : guiValueMap.keySet()) {
                                        Object object = guiValueMap.get(key);
                                        if (object instanceof HashMap) {
                                            HashMap<String, Object> guiVal = (HashMap<String, Object>) object;
                                            if (dbValId.equals(guiVal.get("id"))) {
                                                guiValueMap.remove(key);
                                                matchingGuiVal = guiVal;
                                                break;
                                            }
                                        } else {
                                            log.log(Level.WARNING, "Wrong object type from GUI under key {0}",
                                                    key);
                                        }
                                    }
                                    if (matchingGuiVal != null) {
                                        // Coming from GUI - update
                                        mapRequestToObj((HashMap<String, Object>) matchingGuiVal, assocClass,
                                                dbVal);
                                    } else {
                                        // Not in GUI - delete
                                        removeIt.add(dbVal);
                                    }
                                } else {
                                    log.log(Level.WARNING, "No ID in object {0}", dbVal);
                                }
                            }
                            dbValueSet.removeAll(removeIt);

                            // Rest are new records
                            for (String key : guiValueMap.keySet()) {
                                Object object = guiValueMap.get(key);
                                if (object instanceof HashMap) {
                                    Object subObj = makeNewInstance(assocClass,
                                            (HashMap<String, Object>) object);
                                    mapRequestToObj((HashMap<String, Object>) object, assocClass, subObj);
                                    dbValueSet.add(subObj);
                                } else {
                                    log.log(Level.WARNING, "Wrong sub type {0}", attrName);
                                }
                            }
                        }
                    } else {
                        log.log(Level.WARNING, "No DB mapping or not of collection type: {0}", attrName);
                    }
                    typedVal = null;
                } else if (paramTypes[0].isAssignableFrom(String.class)) {
                    typedVal = val;
                } else if (paramTypes[0].equals(Integer.class) || paramTypes[0].equals(Integer.TYPE)) {
                    typedVal = Integer.parseInt(val);
                } else if (paramTypes[0].equals(Long.class) || paramTypes[0].equals(Long.TYPE)) {
                    typedVal = Long.parseLong(val);
                } else if (paramTypes[0].equals(Double.class) || paramTypes[0].equals(Double.TYPE)) {
                    typedVal = Double.parseDouble(val);
                } else if (paramTypes[0].equals(Float.class) || paramTypes[0].equals(Float.TYPE)) {
                    typedVal = Float.parseFloat(val);
                } else if (paramTypes[0].equals(Boolean.class) || paramTypes[0].equals(Boolean.TYPE)) {
                    typedVal = "true".equalsIgnoreCase(val) || "t".equalsIgnoreCase(val)
                            || "y".equalsIgnoreCase(val);
                } else if (paramTypes[0].isAssignableFrom(Date.class)) {
                    typedVal = dateFormat.parse(val);
                } else if (Enum.class.isAssignableFrom(paramTypes[0])) {
                    try {
                        Method fromValueMethod = paramTypes[0].getMethod("fromValue", String.class);
                        typedVal = fromValueMethod.invoke(null, val);
                    } catch (Exception ex) {
                        typedVal = null;
                    }

                    try {
                        if (typedVal == null) {
                            Method valueOfMethod = paramTypes[0].getMethod("valueOf", String.class);
                            typedVal = valueOfMethod.invoke(null, val);
                        }
                    } catch (Exception ex) {
                        typedVal = null;
                    }
                } else if (persistentClass != null && persistentClass.equals(FileUpload.class)) {
                    FileItem fileItem = uploadServlet.getFileItem(sessionId.get(), fldName, val);
                    if (fileItem != null) {
                        typedVal = fileUploadService.uploadFile(ServiceContextStore.get(), fileItem.getName(),
                                fileItem.getContentType(), fileItem.getInputStream());
                    } else {
                        typedVal = null;
                    }
                } else if (srvParam != null && srvParam.getFindById() != null) {
                    if (value instanceof HashMap) {
                        HashMap<String, Object> embeddedObj = (HashMap<String, Object>) value;
                        typedVal = srvParam.getFindById().invoke(srvParam.getInstance(),
                                ServiceContextStore.get(), new Long((String) embeddedObj.get("id")));
                        mapRequestToObj(embeddedObj, srvParam.getExpectedClass(), typedVal);
                    } else {
                        try {
                            Long parsedId = new Long(val);
                            typedVal = srvParam.getFindById().invoke(srvParam.getInstance(),
                                    ServiceContextStore.get(), parsedId);
                        } catch (NumberFormatException nfe) {
                            // wrong value
                            typedVal = null;
                        }
                    }
                } else if (persistentClass != null) {
                    String getMethodName = "g" + m.getName().substring(1);
                    try {
                        Method getMethod = obj.getClass().getMethod(getMethodName, (Class[]) null);
                        typedVal = getMethod.invoke(obj, (Object[]) null);
                    } catch (NoSuchMethodException nsme) {
                        typedVal = null;
                    }
                    if (typedVal == null) {
                        typedVal = makeNewInstance(persistentClass, (HashMap<String, Object>) value);
                    }
                    mapRequestToObj((HashMap<String, Object>) value, typedVal.getClass(), typedVal);
                } else {
                    log.log(Level.WARNING, "Can't convert value for: {0}.{1} ({2})", new Object[] {
                            expectedClass.getName(), m.getName(),
                            (paramTypes.length == 1 ? paramTypes[0].getName() : paramTypes.toString()) });
                    typedVal = null;
                }
                if (typedVal != null) {
                    m.invoke(obj, typedVal);
                }
            }
        } else if (m.getName().startsWith(SET_PREFIX)) {
            log.log(Level.WARNING, "Unusable setter method: {0}.{1} ({2})",
                    new Object[] { expectedClass.getName(), m.getName(),
                            (paramTypes.length == 1 ? paramTypes[0].getName() : paramTypes.toString()) });
        }
    }
}

From source file:org.structr.core.entity.AbstractNode.java

private Object convert(Object value, Class type) {

    Object convertedObject = null;

    if (type.equals(String.class)) {

        // strings can be returned immediately
        return value.toString();

    } else if (value instanceof Number) {

        Number number = (Number) value;

        if (type.equals(Integer.class) || type.equals(Integer.TYPE)) {
            return number.intValue();

        } else if (type.equals(Long.class) || type.equals(Long.TYPE)) {
            return number.longValue();

        } else if (type.equals(Double.class) || type.equals(Double.TYPE)) {
            return number.doubleValue();

        } else if (type.equals(Float.class) || type.equals(Float.TYPE)) {
            return number.floatValue();

        } else if (type.equals(Short.class) || type.equals(Integer.TYPE)) {
            return number.shortValue();

        } else if (type.equals(Byte.class) || type.equals(Byte.TYPE)) {
            return number.byteValue();

        }//w w  w .j  a  v a2  s .  c om

    } else if (value instanceof List) {

        return value;

    } else if (value instanceof Map) {
        return value;
    }

    // fallback
    try {

        Method valueOf = type.getMethod("valueOf", String.class);
        if (valueOf != null) {

            convertedObject = valueOf.invoke(null, value.toString());

        } else {

            logger.log(Level.WARNING, "Unable to find static valueOf method for type {0}", type);
        }

    } catch (Throwable t) {

        logger.log(Level.WARNING,
                "Unable to deserialize value {0} of type {1}, Class has no static valueOf method.",
                new Object[] { value, type });
    }

    return convertedObject;
}