Example usage for java.lang Class getPackage

List of usage examples for java.lang Class getPackage

Introduction

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

Prototype

public Package getPackage() 

Source Link

Document

Gets the package of this class.

Usage

From source file:org.apache.drill.jdbc.proxy.InvocationReporterImpl.java

/**
 * Renders a value with its corresponding <em>declared</em> type.
 *
 * @param  declaredType/*from www  .  j av  a  2  s.  c o  m*/
 *         the corresponding declared method parameter or return type
 * @value  value
 *         the value to render
 */
private String formatTypeAndValue(Class<?> declaredType, Object value) {
    final String declaredTypePart = "(" + formatType(declaredType) + ") ";

    final String actualTypePart;
    final String actualValuePart;
    if (null == value) {
        // Null--show no actual type or object ID.
        actualTypePart = "";
        actualValuePart = formatValue(value);
    } else {
        // Non-null value--show at least some representation of value.
        Class<?> rawActualType = value.getClass();
        Class<?> origActualType = declaredType.isPrimitive() ? declaredType : rawActualType;
        if (String.class == rawActualType) {
            // String--show no actual type or object ID.
            actualTypePart = "";
            actualValuePart = formatValue(value);
        } else if (origActualType.isPrimitive()) {
            // Primitive type--show no actual type or object ID.
            actualTypePart = "";
            // (Remember--primitive type is wrapped here.)
            actualValuePart = value.toString();
        } else {
            // Non-primitive, non-String value--include object ID.
            final String idPrefix = "<id=" + getObjectId(value) + "> ";
            if (declaredType.isInterface() && JDBC_PACKAGES.contains(declaredType.getPackage())) {
                // JDBC interface implementation class--show no actual type or value
                // (because object is proxied and therefore all uses will be traced).
                actualTypePart = "";
                actualValuePart = idPrefix + "...";
            } else if (origActualType == declaredType) {
                // Actual type is same as declared--don't show redundant actual type.
                actualTypePart = "";
                actualValuePart = idPrefix + formatValue(value);
            } else {
                // Other--show actual type and (try to) show value.
                actualTypePart = "(" + formatType(rawActualType) + ") ";
                actualValuePart = idPrefix + formatValue(value);
            }
        }
    }
    final String result = declaredTypePart + actualTypePart + actualValuePart;
    return result;
}

From source file:com.amalto.core.metadata.ClassRepository.java

private TypeMetadata loadClass(Class clazz) {
    String typeName = getTypeName(clazz);
    if (getType(typeName) != null) { // If already defined return it.
        return getType(typeName);
    } else if (getNonInstantiableType(StringUtils.EMPTY, typeName) != null) {
        return getNonInstantiableType(StringUtils.EMPTY, typeName);
    }//  w w w  . ja  v a2s .  co m
    entityToJavaClass.put(typeName, clazz);
    if (Map.class.isAssignableFrom(clazz)) {
        return MAP_TYPE;
    }
    if (ArrayListHolder.class.equals(clazz)) {
        typeName = typeName + listCounter++;
    }
    boolean isEntity = typeStack.isEmpty();
    ComplexTypeMetadata classType = new ComplexTypeMetadataImpl(StringUtils.EMPTY, typeName, isEntity);
    addTypeMetadata(classType);
    typeStack.push(classType);
    String keyFieldName = ""; //$NON-NLS-1$
    if (isEntity && ObjectPOJO.class.isAssignableFrom(clazz)) {
        SimpleTypeFieldMetadata keyField = new SimpleTypeFieldMetadata(typeStack.peek(), true, false, true,
                "unique-id", //$NON-NLS-1$
                STRING, Collections.<String>emptyList(), Collections.<String>emptyList(),
                Collections.<String>emptyList(), StringUtils.EMPTY);
        keyField.setData(LINK, "PK/unique-id"); //$NON-NLS-1$
        classType.addField(keyField);
    } else if (isEntity) {
        keyFieldName = "unique-id"; //$NON-NLS-1$
    }
    // Class is abstract / interface: load sub classes
    if (clazz.isInterface() || Modifier.isAbstract(clazz.getModifiers())) {
        Iterable<Class> subClasses = getSubclasses(clazz);
        ComplexTypeMetadata superType = typeStack.peek();
        if (superType.isInstantiable()) {
            typeStack.clear();
        }
        for (Class subClass : subClasses) {
            TypeMetadata typeMetadata = loadClass(subClass);
            typeMetadata.setInstantiable(superType.isInstantiable());
            typeMetadata.addSuperType(superType);
        }
        if (superType.isInstantiable()) {
            typeStack.push(superType);
        }
    }
    // Analyze methods
    Method[] classMethods = getMethods(clazz);
    for (Method declaredMethod : classMethods) {
        if (!Modifier.isStatic(declaredMethod.getModifiers())) {
            if (isBeanMethod(declaredMethod) && isClassMethod(clazz, declaredMethod)) {
                String fieldName = getName(declaredMethod);
                if (typeStack.peek().hasField(fieldName)) {
                    continue; // TODO Avoid override of fields (like PK)
                }
                Class<?> returnType = declaredMethod.getReturnType();
                FieldMetadata newField;
                boolean isMany = false;
                boolean isKey = keyFieldName.equals(fieldName);
                if (Iterable.class.isAssignableFrom(returnType)) {
                    returnType = listItemType != null ? listItemType
                            : getListItemClass(declaredMethod, returnType);
                    listItemType = null;
                    isMany = true;
                } else if (ArrayListHolder.class.isAssignableFrom(returnType)) {
                    listItemType = getListItemClass(declaredMethod, returnType);
                    isMany = false;
                } else if (Map.class.isAssignableFrom(returnType)) {
                    isMany = true;
                } else if (returnType.isArray()) {
                    isMany = true;
                    returnType = ((Class) returnType.getComponentType());
                } else if (returnType.getName().startsWith("org.w3c.")) { //$NON-NLS-1$
                    // TODO Serialized XML to string column
                    continue;
                } else if (Class.class.equals(returnType)) {
                    continue;
                } else if (returnType.getPackage() != null
                        && returnType.getPackage().getName().startsWith("java.io")) { //$NON-NLS-1$
                    continue;
                }
                if (returnType.isPrimitive() || returnType.getName().startsWith(JAVA_LANG_PREFIX)) {
                    String fieldTypeName = returnType.getName().toLowerCase();
                    if (fieldTypeName.startsWith(JAVA_LANG_PREFIX)) {
                        fieldTypeName = StringUtils.substringAfter(fieldTypeName, JAVA_LANG_PREFIX);
                    }
                    TypeMetadata fieldType;
                    if (Types.BYTE.equals(fieldTypeName) && isMany) {
                        fieldType = new SimpleTypeMetadata(XMLConstants.W3C_XML_SCHEMA_NS_URI,
                                Types.BASE64_BINARY);
                    } else {
                        fieldType = new SimpleTypeMetadata(XMLConstants.W3C_XML_SCHEMA_NS_URI, fieldTypeName);
                    }
                    newField = new SimpleTypeFieldMetadata(typeStack.peek(), isKey, isMany, isKey, fieldName,
                            fieldType, Collections.<String>emptyList(), Collections.<String>emptyList(),
                            Collections.<String>emptyList(), StringUtils.EMPTY);
                    LongString annotation = declaredMethod.getAnnotation(LongString.class);
                    if (Types.STRING.equals(fieldTypeName) && annotation != null) {
                        fieldType.setData(MetadataRepository.DATA_MAX_LENGTH,
                                String.valueOf(Integer.MAX_VALUE));
                        if (annotation.preferLongVarchar()) {
                            fieldType.setData(LongString.PREFER_LONGVARCHAR, Boolean.TRUE);
                        }
                    }
                } else {
                    ComplexTypeMetadata fieldType;
                    if (Map.class.isAssignableFrom(returnType)) {
                        fieldType = MAP_TYPE;
                    } else {
                        fieldType = (ComplexTypeMetadata) loadClass(returnType);
                    }
                    if (!isEntity || !fieldType.isInstantiable()) {
                        newField = new ContainedTypeFieldMetadata(typeStack.peek(), isMany, false, fieldName,
                                new SoftTypeRef(this, StringUtils.EMPTY, fieldType.getName(), false),
                                Collections.<String>emptyList(), Collections.<String>emptyList(),
                                Collections.<String>emptyList(), StringUtils.EMPTY);
                    } else {
                        newField = new ReferenceFieldMetadata(typeStack.peek(), false, isMany, false, fieldName,
                                fieldType, fieldType.getField("unique-id"), //$NON-NLS-1$
                                Collections.<FieldMetadata>emptyList(), StringUtils.EMPTY, true, false, STRING,
                                Collections.<String>emptyList(), Collections.<String>emptyList(),
                                Collections.<String>emptyList(), StringUtils.EMPTY, StringUtils.EMPTY);
                    }
                }
                typeStack.peek().addField(newField);
            }
        }
    }

    typeStack.peek().addField(new SimpleTypeFieldMetadata(typeStack.peek(), false, false, false, "digest", //$NON-NLS-1$
            new SimpleTypeMetadata(XMLConstants.W3C_XML_SCHEMA_NS_URI, Types.STRING),
            Collections.<String>emptyList(), Collections.<String>emptyList(), Collections.<String>emptyList(),
            StringUtils.EMPTY));

    return typeStack.pop();
}

From source file:com.puppycrawl.tools.checkstyle.internal.XdocsPagesTest.java

private static void validateErrorSection(String fileName, String sectionName, Node subSection, Object instance)
        throws Exception {
    final Class<?> clss = instance.getClass();
    final Set<Field> fields = CheckUtil.getCheckMessages(clss);
    final Set<String> list = new TreeSet<>();

    for (Field field : fields) {
        // below is required for package/private classes
        if (!field.isAccessible()) {
            field.setAccessible(true);/*from ww  w  .jav  a2s .com*/
        }

        list.add(field.get(null).toString());
    }

    final StringBuilder expectedText = new StringBuilder();

    for (String s : list) {
        expectedText.append(s);
        expectedText.append("\n");
    }

    if (expectedText.length() > 0) {
        expectedText.append("All messages can be customized if the default message doesn't "
                + "suit you.\nPlease see the documentation to learn how to.");
    }

    if (subSection == null) {
        Assert.assertEquals(fileName + " section '" + sectionName + "' should have the expected error keys", "",
                expectedText.toString());
    } else {
        Assert.assertEquals(fileName + " section '" + sectionName + "' should have the expected error keys",
                expectedText.toString().trim(), subSection.getTextContent().replaceAll("\n\\s+", "\n").trim());

        for (Node node : XmlUtil.findChildElementsByTag(subSection, "a")) {
            final String url = node.getAttributes().getNamedItem("href").getTextContent();
            final String linkText = node.getTextContent().trim();
            final String expectedUrl;

            if ("see the documentation".equals(linkText)) {
                expectedUrl = "config.html#Custom_messages";
            } else {
                expectedUrl = "https://github.com/search?q=" + "path%3Asrc%2Fmain%2Fresources%2F"
                        + clss.getPackage().getName().replace(".", "%2F")
                        + "+filename%3Amessages*.properties+repo%3Acheckstyle%2Fcheckstyle+%22" + linkText
                        + "%22";
            }

            Assert.assertEquals(
                    fileName + " section '" + sectionName + "' should have matching url for '" + linkText + "'",
                    expectedUrl, url);
        }
    }
}

From source file:cn.teamlab.wg.framework.struts2.json.PackageBasedActionConfigBuilder.java

protected void buildConfiguration(@SuppressWarnings("rawtypes") Set<Class> classes) {

    for (Class<?> actionClass : classes) {
        Json jsonAnnotation = actionClass.getAnnotation(Json.class);

        // Skip classes that can't be instantiated or don't annotated with
        // @Json/*from w w  w . j  av  a  2s .c  o m*/
        if (cannotInstantiate(actionClass) && jsonAnnotation == null) {
            if (LOG.isTraceEnabled()) {
                LOG.trace("Class [#0] did not pass the instantiation test and will be ignored",
                        actionClass.getName());
            }
            continue;
        }

        if (eagerLoading) {
            // Tell the ObjectFactory about this class
            try {
                objectFactory.getClassInstance(actionClass.getName());
            } catch (ClassNotFoundException e) {
                if (LOG.isErrorEnabled()) {
                    LOG.error("Object Factory was unable to load class [#0]", e, actionClass.getName());
                }
                throw new StrutsException("Object Factory was unable to load class " + actionClass.getName(),
                        e);
            }
        }

        String actionPackage = actionClass.getPackage().getName();
        //String defaultActionName = actionClass.getSimpleName();
        if (LOG.isDebugEnabled()) {
            LOG.debug("Processing class [#0] in package [#1]", actionClass.getName(), actionPackage);
        }

        // Verify that the annotations have no errors and also determine
        // if the default action
        // configuration should still be built or not.
        @SuppressWarnings("unused")
        Map<String, List<Json>> map = getActionAnnotations(actionClass);

        // TODO: Create action config

    }
}

From source file:es.cenobit.struts2.json.PackageBasedActionConfigBuilder.java

protected void buildConfiguration(@SuppressWarnings("rawtypes") Set<Class> classes) {

    for (Class<?> actionClass : classes) {
        Json jsonAnnotation = actionClass.getAnnotation(Json.class);

        // Skip classes that can't be instantiated or don't annotated with
        // @Json//ww w  .j a va 2 s.co  m
        if (cannotInstantiate(actionClass) && jsonAnnotation == null) {
            if (LOG.isTraceEnabled()) {
                LOG.trace("Class [#0] did not pass the instantiation test and will be ignored",
                        actionClass.getName());
            }
            continue;
        }

        if (eagerLoading) {
            // Tell the ObjectFactory about this class
            try {
                objectFactory.getClassInstance(actionClass.getName());
            } catch (ClassNotFoundException e) {
                if (LOG.isErrorEnabled()) {
                    LOG.error("Object Factory was unable to load class [#0]", e, actionClass.getName());
                }
                throw new StrutsException("Object Factory was unable to load class " + actionClass.getName(),
                        e);
            }
        }

        String actionPackage = actionClass.getPackage().getName();
        if (LOG.isDebugEnabled()) {
            LOG.debug("Processing class [#0] in package [#1]", actionClass.getName(), actionPackage);
        }

        String defaultActionName = actionClass.getSimpleName();
        if (LOG.isDebugEnabled()) {
            LOG.debug("Processing defaultActionName [#0] in package [#1]", defaultActionName, actionPackage);
        }

        // Verify that the annotations have no errors and also determine
        // if the default action
        // configuration should still be built or not.
        @SuppressWarnings("unused")
        Map<String, List<Json>> map = getActionAnnotations(actionClass);

        // TODO: Create action config

    }
}

From source file:org.vaadin.testbenchsauce.BaseTestBenchTestCase.java

private void updateRallyTestCase(String testCaseId, ITestResult testResult)
        throws URISyntaxException, IOException {
    //Rally API Setup
    RallyRestApi restApi = new RallyRestApi(new URI(RALLY_SERVER_URL), RALLY_USERNAME, RALLY_PASSWORD);
    restApi.setApplicationName("VaadinTestBench");

    int status = testResult.getStatus();
    String verdict = null;/*from w w w. j a va 2s. c o  m*/
    if (status == ITestResult.FAILURE) {
        verdict = "Fail";
    } else if (status == ITestResult.SUCCESS) {
        verdict = "Pass";
    } else {
        //For now if it's not a failure or success, don't update rally
        return;
    }

    Duration duration = new Duration(testResult.getStartMillis(), testResult.getEndMillis());

    try {
        //Get a reference to the test case
        QueryRequest testCaseRequest = new QueryRequest("TestCase");
        testCaseRequest.setFetch(new Fetch("FormattedID", "Name"));
        testCaseRequest.setQueryFilter(new QueryFilter("FormattedID", "=", testCaseId));
        QueryResponse testCaseResponse = restApi.query(testCaseRequest);
        if (testCaseResponse.getTotalResultCount() <= 0) {
            System.out.println("WARNING: Could not add test result to Rally test case '" + testCaseId
                    + "' because it was not found.");
            return;
        }

        JsonObject testCaseJsonObject = testCaseResponse.getResults().get(0).getAsJsonObject();
        String testCaseRef = testCaseJsonObject.get("_ref").getAsString();

        //Add a test result to that test case
        JsonObject testCaseResult = new JsonObject();
        testCaseResult.addProperty("Verdict", verdict);
        testCaseResult.addProperty("Build", JENKINS_BUILD_NUMBER);
        testCaseResult.addProperty("TestCase", testCaseRef);
        testCaseResult.addProperty("Date", new SimpleDateFormat("yyyy-MM-dd'T'HH:mm:ssZ").format(new Date()));
        testCaseResult.addProperty("Duration", duration.getMillis());

        //rallyTestCaseIntegration(SolutionsTabUiTest)
        String methodName = testResult.getName();
        Class realClass = testResult.getTestClass().getRealClass();

        String jobHref = "<b><a target='_blank' href=\"" + JENKINS_BUILD_URL + "\">Jenkins Job</a></b>";

        //testngreports/<package>/<package>.<Class>/<methodName>/
        String testUrl = JENKINS_BUILD_URL + "testngreports/" + realClass.getPackage().getName() + "/"
                + realClass.getName() + "/" + methodName + "/";
        String testHref = "<a target='_blank' href=\"" + testUrl + "\">" + "Test Method: " + methodName + "("
                + realClass.getSimpleName() + ")" + "</a>";
        String notes = jobHref + "&nbsp" + testHref;

        notes += "<div><b>Release Build Test Output:</b></div>";
        notes += getHtmlTestOutput(testResult);
        if (!testResult.isSuccess()) {
            notes += "<div style='color:red;'><b>Failure Details:</b></div>";

            notes += ExceptionUtils.getStackTrace(testResult.getThrowable());
        }

        testCaseResult.addProperty("Notes", notes);

        CreateRequest createTestResultRequest = new CreateRequest("testcaseresult", testCaseResult);
        CreateResponse createTestResultResponse = restApi.create(createTestResultRequest);

        //Output response
        if (createTestResultResponse.wasSuccessful()) {
            System.out.println("Created test result for Rally test case '" + testCaseId + "' - " + testCaseRef);
        } else {
            String[] createErrors;
            createErrors = createTestResultResponse.getErrors();
            System.out.println(
                    "WARNING: Error occurred creating Rally test case result for '" + testCaseId + "'");
            for (int i = 0; i < createErrors.length; i++) {
                System.out.println(createErrors[i]);
            }
        }
    } finally {
        restApi.close();
    }
}

From source file:org.openconcerto.sql.element.SQLElement.java

public final void setL18nLocation(Class<?> clazz) {
    this.setL18nLocation(clazz.getPackage().getName(), clazz);
}

From source file:org.apache.axis2.description.java2wsdl.DefaultSchemaGenerator.java

/**
 * Generate schema construct for given type
 *
 * @param javaType : Class to whcih need to generate Schema
 * @return : Generated QName/*  ww w.j av  a  2  s. c  o  m*/
 */
protected QName generateSchema(Class<?> javaType) throws Exception {
    String name = getClassName(javaType);
    QName schemaTypeName = typeTable.getComplexSchemaType(name);
    if (schemaTypeName == null) {
        String simpleName = getSimpleClassName(javaType);

        String packageName = getQualifiedName(javaType.getPackage());
        String targetNameSpace = resolveSchemaNamespace(packageName);

        XmlSchema xmlSchema = getXmlSchema(targetNameSpace);
        String targetNamespacePrefix = targetNamespacePrefixMap.get(targetNameSpace);
        if (targetNamespacePrefix == null) {
            targetNamespacePrefix = generatePrefix();
            targetNamespacePrefixMap.put(targetNameSpace, targetNamespacePrefix);
        }

        XmlSchemaComplexType complexType = new XmlSchemaComplexType(xmlSchema);
        XmlSchemaSequence sequence = new XmlSchemaSequence();
        XmlSchemaComplexContentExtension complexExtension = new XmlSchemaComplexContentExtension();

        XmlSchemaElement eltOuter = new XmlSchemaElement();
        schemaTypeName = new QName(targetNameSpace, simpleName, targetNamespacePrefix);
        eltOuter.setName(simpleName);
        eltOuter.setQName(schemaTypeName);

        Class<?> sup = javaType.getSuperclass();
        if ((sup != null) && (!"java.lang.Object".equals(sup.getName()))
                && (!"java.lang.Exception".equals(sup.getName()))
                && !getQualifiedName(sup.getPackage()).startsWith("org.apache.axis2")
                && !getQualifiedName(sup.getPackage()).startsWith("java.util")) {
            String superClassName = sup.getName();
            String superclassname = getSimpleClassName(sup);
            String tgtNamespace;
            String tgtNamespacepfx;
            QName qName = typeTable.getSimpleSchemaTypeName(superClassName);
            if (qName != null) {
                tgtNamespace = qName.getNamespaceURI();
                tgtNamespacepfx = qName.getPrefix();
            } else {
                tgtNamespace = resolveSchemaNamespace(getQualifiedName(sup.getPackage()));
                tgtNamespacepfx = targetNamespacePrefixMap.get(tgtNamespace);
                QName superClassQname = generateSchema(sup);
                if (superClassQname != null) {
                    tgtNamespacepfx = superClassQname.getPrefix();
                    tgtNamespace = superClassQname.getNamespaceURI();
                }
            }
            if (tgtNamespacepfx == null) {
                tgtNamespacepfx = generatePrefix();
                targetNamespacePrefixMap.put(tgtNamespace, tgtNamespacepfx);
            }
            //if the parent class package name is differ from the child
            if (!((NamespaceMap) xmlSchema.getNamespaceContext()).values().contains(tgtNamespace)) {
                XmlSchemaImport importElement = new XmlSchemaImport();
                importElement.setNamespace(tgtNamespace);
                xmlSchema.getItems().add(importElement);
                ((NamespaceMap) xmlSchema.getNamespaceContext()).put(generatePrefix(), tgtNamespace);
            }

            QName basetype = new QName(tgtNamespace, superclassname, tgtNamespacepfx);
            complexExtension.setBaseTypeName(basetype);
            complexExtension.setParticle(sequence);
            XmlSchemaComplexContent contentModel = new XmlSchemaComplexContent();
            contentModel.setContent(complexExtension);
            complexType.setContentModel(contentModel);

        } else {
            complexType.setParticle(sequence);
        }

        complexType.setName(simpleName);

        if (Modifier.isAbstract(javaType.getModifiers())) {
            complexType.setAbstract(true);
        }

        //            xmlSchema.getItems().add(eltOuter);
        xmlSchema.getElements().add(schemaTypeName, eltOuter);
        eltOuter.setSchemaTypeName(complexType.getQName());

        xmlSchema.getItems().add(complexType);
        xmlSchema.getSchemaTypes().add(schemaTypeName, complexType);

        // adding this type to the table
        typeTable.addComplexSchema(name, eltOuter.getQName());
        // adding this type's package to the table, to support inheritance.
        typeTable.addComplexSchema(getQualifiedName(javaType.getPackage()), eltOuter.getQName());

        typeTable.addClassNameForQName(eltOuter.getQName(), name);

        BeanExcludeInfo beanExcludeInfo = null;
        if (service.getExcludeInfo() != null) {
            beanExcludeInfo = service.getExcludeInfo().getBeanExcludeInfoForClass(getClassName(javaType));
        }

        // we need to get properties only for this bean. hence ignore the super
        // class properties
        BeanInfo beanInfo = Introspector.getBeanInfo(javaType, javaType.getSuperclass());

        for (PropertyDescriptor property : beanInfo.getPropertyDescriptors()) {
            String propertyName = property.getName();
            if (!property.getName().equals("class") && (property.getPropertyType() != null)) {
                if ((beanExcludeInfo == null) || !beanExcludeInfo.isExcludedProperty(propertyName)) {
                    Type genericFieldType = null;
                    try {
                        Field field = javaType.getDeclaredField(propertyName);
                        genericFieldType = field.getGenericType();
                    } catch (Exception e) {
                        //log.info(e.getMessage());
                    }

                    if (genericFieldType instanceof ParameterizedType) {
                        ParameterizedType aType = (ParameterizedType) genericFieldType;
                        Type[] fieldArgTypes = aType.getActualTypeArguments();
                        try {
                            generateSchemaforGenericFields(xmlSchema, sequence, fieldArgTypes[0], propertyName);
                        } catch (Exception e) {
                            generateSchemaforFieldsandProperties(xmlSchema, sequence,
                                    property.getPropertyType(), propertyName,
                                    property.getPropertyType().isArray());
                        }
                    } else {
                        generateSchemaforFieldsandProperties(xmlSchema, sequence, property.getPropertyType(),
                                propertyName, property.getPropertyType().isArray());
                    }
                }
            }
        }
    }
    return schemaTypeName;
}

From source file:org.disciple.db.Abatis.java

/**
 *
 * @param sqlId SQLID//from ww  w .ja  v a 2s  .  com
 * @param bindParams sql parameter
 * @param bean bean class of result 
 * 
 * @return List<Map<String, Object>> result
 */
@SuppressWarnings({ "unchecked", "rawtypes" })
public <T> List<T> executeForBeanList(String sqlId, Map<String, Object> bindParams, Class bean) {
    getDbObject();
    int pointer = context.getResources().getIdentifier(sqlId, "string", context.getPackageName());
    if (pointer == 0) {
        Log.e(TAG, "undefined sql id");
        return null;
    }
    String sql = context.getResources().getString(pointer);
    if (bindParams != null) {
        Iterator<String> mapIterator = bindParams.keySet().iterator();
        while (mapIterator.hasNext()) {
            String key = mapIterator.next();
            Object value = bindParams.get(key);
            sql = sql.replaceAll("#" + key.toLowerCase() + "#",
                    value == null ? null : "'" + value.toString() + "'");
        }
    }
    if (sql.indexOf('#') != -1) {
        Log.e(TAG, "undefined parameter");
        return null;
    }
    Cursor cursor = dbObj.rawQuery(sql, null);
    List<T> objectList = new ArrayList<T>();
    if (cursor == null) {
        return null;
    }
    String[] columnNames = cursor.getColumnNames();
    List<String> dataNames = new ArrayList<String>();
    for (String columnName : columnNames) {
        dataNames.add(chgDataName(columnName));
    }
    T beanObj = null;
    // get bean class package
    Package beanPackage = bean.getPackage();
    while (cursor.moveToNext()) {
        Map<String, Object> map = new HashMap<String, Object>();
        int i = 0;
        for (String dataName : dataNames) {
            map.put(dataName, cursor.getString(i));
            i++;
        }
        JSONObject json = new JSONObject(map);
        try {
            beanObj = (T) parse(json.toString(), bean, beanPackage.getName());
        } catch (Exception e) {
            Log.d(TAG, e.toString());
            return null;
        }
        objectList.add(beanObj);
    }
    cursor.close();
    dbObj.close();
    return objectList;
}

From source file:org.disciple.db.Abatis.java

/**
 *
 * @param sqlId SQLID/*from w  w  w .  ja v  a2 s  .c o m*/
 * @param bindParams sql parameter
 * @param bean bean class of result 
 * 
 * @return List<Map<String, Object>> result
 */
@SuppressWarnings({ "unchecked", "rawtypes" })
public <T> T executeForBean(String sqlId, Map<String, Object> bindParams, Class bean) {
    getDbObject();
    int pointer = context.getResources().getIdentifier(sqlId, "string", context.getPackageName());
    if (pointer == 0) {
        Log.e(TAG, "undefined sql id");
        return null;
    }
    String sql = context.getResources().getString(pointer);
    if (bindParams != null) {
        Iterator<String> mapIterator = bindParams.keySet().iterator();
        while (mapIterator.hasNext()) {
            String key = mapIterator.next();
            Object value = bindParams.get(key);
            sql = sql.replaceAll("#" + key.toLowerCase() + "#",
                    value == null ? null : "'" + value.toString() + "'");
        }
    }
    if (sql.indexOf('#') != -1) {
        Log.e(TAG, "undefined parameter");
        return null;
    }
    Cursor cursor = dbObj.rawQuery(sql, null);
    List<T> objectList = new ArrayList<T>();
    if (cursor == null) {
        return null;
    }
    String[] columnNames = cursor.getColumnNames();
    List<String> dataNames = new ArrayList<String>();
    for (String columnName : columnNames) {
        dataNames.add(chgDataName(columnName));
    }
    T beanObj = null;
    // get bean class package
    Package beanPackage = bean.getPackage();
    while (cursor.moveToNext()) {
        Map<String, Object> map = new HashMap<String, Object>();
        int i = 0;
        for (String dataName : dataNames) {
            map.put(dataName, cursor.getString(i));
            i++;
        }
        JSONObject json = new JSONObject(map);
        try {
            beanObj = (T) parse(json.toString(), bean, beanPackage.getName());
        } catch (Exception e) {
            Log.d(TAG, e.toString());
            return null;
        }
        objectList.add(beanObj);
    }
    if (objectList.size() <= 0) {
        return null;
    }
    cursor.close();
    dbObj.close();
    return objectList.get(0);
}