List of usage examples for java.lang.reflect Method getGenericReturnType
public Type getGenericReturnType()
From source file:com.vmware.photon.controller.swagger.resources.SwaggerJsonListing.java
/** * Gets all of the operation data for a method, such as http method, documentation, parameters, response class, etc. * * @param models The hashmap of models that are being documented so that they can be referenced by swagger-ui. * @param method The method to document. * @param parentParams The parameters of parent resources, so that they can be documented by subresources. * @return A SwaggerOperation API representation. */// www.ja va 2s . c o m private SwaggerOperation getOperation(HashMap<String, SwaggerModel> models, ResourceMethod method, List<SwaggerParameter> parentParams) { Method definitionMethod = method.getInvocable().getDefinitionMethod(); SwaggerOperation operation = new SwaggerOperation(); // If there is no @ApiOperation on a method we still document it because it's possible that the return class of // this method is a resource class with @Api and @ApiOperation on methods. ApiOperation apiOperation = definitionMethod.getAnnotation(ApiOperation.class); if (apiOperation != null) { operation.setSummary(apiOperation.value()); operation.setNotes(apiOperation.notes()); Class<?> responseClass = apiOperation.response().equals(Void.class) ? definitionMethod.getReturnType() : apiOperation.response(); if (StringUtils.isNotBlank(apiOperation.responseContainer())) { operation.setResponseClass(addListModel(models, responseClass, apiOperation.responseContainer())); } else { operation.setResponseClass( getTypeName(models, responseClass, definitionMethod.getGenericReturnType())); } addModel(models, responseClass); } operation.setHttpMethod(parseHttpOperation(definitionMethod)); operation.setNickname(definitionMethod.getName()); // In this block we get all of the parameters to the method and convert them to SwaggerParameter types. We // introspect the generic types. List<SwaggerParameter> swaggerParameters = new ArrayList<>(); Class[] parameterTypes = definitionMethod.getParameterTypes(); Type[] genericParameterTypes = definitionMethod.getGenericParameterTypes(); Annotation[][] parameterAnnotations = definitionMethod.getParameterAnnotations(); for (int i = 0; i < parameterTypes.length; i++) { Class parameter = parameterTypes[i]; Type genericParameterType = genericParameterTypes[i]; if (genericParameterType instanceof Class && "javax.ws.rs.core.Request".equals(((Class) genericParameterType).getName())) { continue; } SwaggerParameter swaggerParameter = parameterToSwaggerParameter(models, parameter, genericParameterType, parameterAnnotations[i]); swaggerParameters.add(swaggerParameter); // Add this parameter to the list of model documentation. addModel(models, parameter); } swaggerParameters.addAll(parentParams); operation.setParameters(swaggerParameters); return operation; }
From source file:org.romaframework.core.schema.reflection.SchemaClassReflection.java
private void createAction(Method method, ParameterizedType params) { String methodSignature = SchemaAction.getSignature(method.getName(), method.getParameterTypes()); log.debug("[SchemaClassReflection] Class " + getName() + " found method: " + methodSignature); SchemaActionReflection actionInfo = (SchemaActionReflection) getAction(methodSignature); if (actionInfo == null) { List<SchemaParameter> orderedParameters = new ArrayList<SchemaParameter>(); for (int i = 0; i < method.getParameterTypes().length; ++i) { orderedParameters.add(new SchemaParameter("param" + i, i, Roma.schema().getSchemaClassIfExist(method.getParameterTypes()[i]))); }/* w w w. jav a2s . c o m*/ // ACTION NOT EXISTENT: CREATE IT AND INSERT IN THE COLLECTION actionInfo = new SchemaActionReflection(this, methodSignature, orderedParameters); actionInfo.method = method; setAction(methodSignature, actionInfo); } actionInfo.method = method; actionInfo.setReturnType(Roma.schema() .getSchemaClassIfExist(SchemaHelper.resolveClassFromType(method.getGenericReturnType(), params))); }
From source file:org.compass.annotations.config.binding.AnnotationsMappingBinding.java
/** * Recursivly process the class to find all it's annotations. Lower level * class/interfaces with annotations will be added first. *///from w w w .ja va 2 s .c om private void processAnnotatedClass(Class<?> clazz) { if (clazz.equals(Class.class)) { return; } Class<?> superClazz = clazz.getSuperclass(); if (superClazz != null && !superClazz.equals(Object.class)) { processAnnotatedClass(superClazz); } Class<?>[] interfaces = clazz.getInterfaces(); for (Class<?> anInterface : interfaces) { processAnnotatedClass(anInterface); } SearchableConstant searchableConstant = clazz.getAnnotation(SearchableConstant.class); if (searchableConstant != null) { bindConstantMetaData(searchableConstant); } SearchableConstants searchableConstants = clazz.getAnnotation(SearchableConstants.class); if (searchableConstants != null) { for (SearchableConstant metaData : searchableConstants.value()) { bindConstantMetaData(metaData); } } SearchableDynamicMetaData searchableDynamicMetaData = clazz.getAnnotation(SearchableDynamicMetaData.class); if (searchableDynamicMetaData != null) { bindDynamicMetaData(searchableDynamicMetaData); } SearchableDynamicMetaDatas searchableDynamicMetaDatas = clazz .getAnnotation(SearchableDynamicMetaDatas.class); if (searchableDynamicMetaDatas != null) { for (SearchableDynamicMetaData metaData : searchableDynamicMetaDatas.value()) { bindDynamicMetaData(metaData); } } // handles recursive extends and the original extend if (clazz.isAnnotationPresent(Searchable.class)) { Searchable searchable = clazz.getAnnotation(Searchable.class); String[] extend = searchable.extend(); if (extend.length != 0) { ArrayList<String> extendedMappings = new ArrayList<String>(); if (classMapping.getExtendedAliases() != null) { extendedMappings.addAll(Arrays.asList(classMapping.getExtendedAliases())); } for (String extendedAlias : extend) { Alias extendedAliasLookup = valueLookup.lookupAlias(extendedAlias); if (extendedAliasLookup == null) { extendedMappings.add(extendedAlias); } else { extendedMappings.add(extendedAliasLookup.getName()); } } classMapping.setExtendedAliases(extendedMappings.toArray(new String[extendedMappings.size()])); } } // if the super class has Searchable annotation as well, add it to the list of extends ArrayList<Class> extendedClasses = new ArrayList<Class>(); if (clazz.getSuperclass() != null) { extendedClasses.add(clazz.getSuperclass()); } extendedClasses.addAll(Arrays.asList(clazz.getInterfaces())); for (Class<?> superClass : extendedClasses) { if (!superClass.isAnnotationPresent(Searchable.class)) { continue; } Searchable superSearchable = superClass.getAnnotation(Searchable.class); String alias = getAliasFromSearchableClass(superClass, superSearchable); HashSet<String> extendedMappings = new HashSet<String>(); if (classMapping.getExtendedAliases() != null) { extendedMappings.addAll(Arrays.asList(classMapping.getExtendedAliases())); } extendedMappings.add(alias); classMapping.setExtendedAliases(extendedMappings.toArray(new String[extendedMappings.size()])); } for (Field field : clazz.getDeclaredFields()) { for (Annotation annotation : field.getAnnotations()) { processsAnnotatedElement(clazz, field.getName(), "field", field.getType(), field.getGenericType(), annotation, field); } } for (Method method : clazz.getDeclaredMethods()) { if (!method.isSynthetic() && !method.isBridge() && !Modifier.isStatic(method.getModifiers()) && method.getParameterTypes().length == 0 && method.getReturnType() != void.class && (method.getName().startsWith("get") || method.getName().startsWith("is"))) { for (Annotation annotation : method.getAnnotations()) { processsAnnotatedElement(clazz, ClassUtils.getShortNameForMethod(method), "property", method.getReturnType(), method.getGenericReturnType(), annotation, method); } } } }
From source file:com.bstek.dorado.idesupport.initializer.CommonRuleTemplateInitializer.java
protected List<AutoChildTemplate> getChildTemplates(RuleTemplate ruleTemplate, TypeInfo typeInfo, XmlNodeInfo xmlNodeInfo, InitializerContext initializerContext) throws Exception { List<AutoChildTemplate> childTemplates = new ArrayList<AutoChildTemplate>(); if (xmlNodeInfo != null) { for (XmlSubNode xmlSubNode : xmlNodeInfo.getSubNodes()) { TypeInfo propertyTypeInfo = TypeInfo.parse(xmlSubNode.propertyType()); List<AutoChildTemplate> childRulesBySubNode = getChildTemplatesBySubNode(ruleTemplate, typeInfo, xmlSubNode.propertyName(), xmlSubNode, propertyTypeInfo, initializerContext); if (childRulesBySubNode != null) { childTemplates.addAll(childRulesBySubNode); }//from w ww . j a v a 2 s.c o m } } Class<?> type = typeInfo.getType(); PropertyDescriptor[] propertyDescriptors = PropertyUtils.getPropertyDescriptors(type); for (PropertyDescriptor propertyDescriptor : propertyDescriptors) { Method readMethod = propertyDescriptor.getReadMethod(); if (readMethod != null) { if (readMethod.getDeclaringClass() != type) { try { readMethod = type.getDeclaredMethod(readMethod.getName(), readMethod.getParameterTypes()); } catch (NoSuchMethodException e) { continue; } } List<AutoChildTemplate> childTemplatesBySubNode = null; XmlSubNode xmlSubNode = readMethod.getAnnotation(XmlSubNode.class); if (xmlSubNode != null) { TypeInfo propertyTypeInfo; Class<?> propertyType = propertyDescriptor.getPropertyType(); if (Collection.class.isAssignableFrom(propertyType)) { propertyTypeInfo = TypeInfo.parse((ParameterizedType) readMethod.getGenericReturnType(), true); propertyType = propertyTypeInfo.getType(); } else { propertyTypeInfo = new TypeInfo(propertyType, false); } childTemplatesBySubNode = getChildTemplatesBySubNode(ruleTemplate, typeInfo, propertyDescriptor.getName(), xmlSubNode, propertyTypeInfo, initializerContext); } if (childTemplatesBySubNode != null) { IdeSubObject ideSubObject = readMethod.getAnnotation(IdeSubObject.class); if (ideSubObject != null && !ideSubObject.visible()) { for (AutoChildTemplate childTemplate : childTemplatesBySubNode) { childTemplate.setVisible(false); } } childTemplates.addAll(childTemplatesBySubNode); } } } return childTemplates; }
From source file:com.flexoodb.engines.FlexJAXBDBDataEngine2.java
private void reviveObject(String parentid, Object o, Connection conn, String prefix, boolean revivechildren) throws Exception { Vector v = new Vector(); try {/* w ww . j ava 2 s . com*/ Class c = o.getClass(); Method[] methods = c.getMethods(); for (int i = 0; i < methods.length; i++) { Method method = methods[i]; if (method.getName().startsWith("get") && method.getReturnType() != null && !method.getReturnType().getSimpleName().equals("Class")) { Class ret = method.getReturnType(); if (ret.getSimpleName().equals("List")) { Object[] args = null; List list = (ArrayList) method.invoke(o, args); ParameterizedType t = (ParameterizedType) method.getGenericReturnType(); Type type = t.getActualTypeArguments()[0]; String[] s = ("" + type).split(" "); String classname = s[1].substring(s[1].lastIndexOf(".") + 1); String tablename = prefix + classname.toLowerCase(); if (checkTable(tablename, conn, true)) { PreparedStatement ps = (PreparedStatement) conn.prepareStatement( "select id,content from " + tablename + " where parentid='" + parentid + "'"); ResultSet rec = ps.executeQuery(); // check if a record was found while (rec != null && rec.next()) { String id = rec.getString("id"); //Object o2 = _flexutils.getObject(rec.getString("content"),Class.forName(s[1])); Object o2 = _flexutils.getObject(rec.getString("content"), ClassLoader.getSystemClassLoader().loadClass(s[1])); if (id != null && o2 != null && !id.equalsIgnoreCase(parentid)) { list.add(o2); } } } } else if (!ret.getName().startsWith("java") && !ret.getSimpleName().toLowerCase().endsWith("byte[]") && !ret.getSimpleName().toLowerCase().equals("int")) // if complex { String tablename = prefix + ret.getSimpleName().toLowerCase(); if (checkTable(tablename, conn, true)) { PreparedStatement ps = (PreparedStatement) conn .prepareStatement("select distinct id,content from " + tablename + " where parentid='" + parentid + "'"); ResultSet rec = ps.executeQuery(); // check if a record was found if (rec != null && rec.next()) { String id = rec.getString("id"); Object o2 = _flexutils.getObject(rec.getString("content"), ret); if (o2 != null && !id.equalsIgnoreCase(parentid)) { String setmethod = "set" + method.getName().substring(3); Object[] args = new Object[1]; args[0] = o2; Class[] cls = new Class[1]; cls[0] = o2.getClass(); Method met = c.getMethod(setmethod, cls); met.invoke(o, args); if (revivechildren) { reviveObject(id, o2, conn, prefix, revivechildren); } //System.out.println(">>> "+o2+" added!"); } /*if (rec.isLast()) { break; }*/ } } } } } } catch (Exception f) { throw f; } }
From source file:com.flexoodb.engines.FlexJAXBDBDataEngine.java
private void reviveObject(String parentid, Object o, Connection conn, String prefix, boolean revivechildren) throws Exception { Vector v = new Vector(); try {/*from w w w .j av a 2 s . c om*/ Class c = o.getClass(); Method[] methods = c.getMethods(); for (int i = 0; i < methods.length; i++) { Method method = methods[i]; if (method.getName().startsWith("get") && method.getReturnType() != null && !method.getReturnType().getSimpleName().equals("Class")) { Class ret = method.getReturnType(); if (ret.getSimpleName().equals("List")) { Object[] args = null; List list = (ArrayList) method.invoke(o, args); ParameterizedType t = (ParameterizedType) method.getGenericReturnType(); Type type = t.getActualTypeArguments()[0]; String[] s = ("" + type).split(" "); String classname = s[1].substring(s[1].lastIndexOf(".") + 1); String tablename = prefix + classname.toLowerCase(); if (checkTable(tablename, conn, true)) { PreparedStatement ps = (PreparedStatement) conn.prepareStatement( "select id,content from " + tablename + " where parentid='" + parentid + "'"); ResultSet rec = ps.executeQuery(); // check if a record was found while (rec != null && rec.next()) { String id = rec.getString("id"); //Object o2 = _flexutils.getObject(rec.getString("content"),Class.forName(s[1])); Object o2 = _flexutils.getObject(rec.getString("content"), ClassLoader.getSystemClassLoader().loadClass(s[1])); if (id != null && o2 != null && !id.equalsIgnoreCase(parentid)) { list.add(o2); } } } } else if (!ret.getName().startsWith("java") && !ret.getSimpleName().toLowerCase().endsWith("byte[]") && !ret.getSimpleName().toLowerCase().equals("int")) // if complex { String tablename = prefix + ret.getSimpleName().toLowerCase(); if (checkTable(tablename, conn, true)) { PreparedStatement ps = (PreparedStatement) conn .prepareStatement("select distinct id,content from " + tablename + " where parentid='" + parentid + "'"); ResultSet rec = ps.executeQuery(); // check if a record was found if (rec != null && rec.next()) { String id = rec.getString("id"); Object o2 = _flexutils.getObject(rec.getString("content"), ret); if (o2 != null && !id.equalsIgnoreCase(parentid)) { String setmethod = "set" + method.getName().substring(3); Object[] args = new Object[1]; args[0] = o2; Class[] cls = new Class[1]; cls[0] = o2.getClass(); Method met = c.getMethod(setmethod, cls); met.invoke(o, args); if (revivechildren) { reviveObject(id, o2, conn, prefix, revivechildren); } //System.out.println(">>> "+o2+" added!"); } /*if (rec.isLast()) { break; }*/ } } } } } } catch (Exception f) { throw f; } }
From source file:org.apache.hadoop.yarn.api.TestPBImplRecords.java
private <R> Map<String, GetSetPair> getGetSetPairs(Class<R> recordClass) throws Exception { Map<String, GetSetPair> ret = new HashMap<String, GetSetPair>(); Method[] methods = recordClass.getDeclaredMethods(); // get all get methods for (int i = 0; i < methods.length; i++) { Method m = methods[i]; int mod = m.getModifiers(); if (m.getDeclaringClass().equals(recordClass) && Modifier.isPublic(mod) && (!Modifier.isStatic(mod))) { String name = m.getName(); if (name.equals("getProto")) { continue; }/* w ww. jav a 2 s .c o m*/ if ((name.length() > 3) && name.startsWith("get") && (m.getParameterTypes().length == 0)) { String propertyName = name.substring(3); Type valueType = m.getGenericReturnType(); GetSetPair p = ret.get(propertyName); if (p == null) { p = new GetSetPair(); p.propertyName = propertyName; p.type = valueType; p.getMethod = m; ret.put(propertyName, p); } else { Assert.fail("Multiple get method with same name: " + recordClass + p.propertyName); } } } } // match get methods with set methods for (int i = 0; i < methods.length; i++) { Method m = methods[i]; int mod = m.getModifiers(); if (m.getDeclaringClass().equals(recordClass) && Modifier.isPublic(mod) && (!Modifier.isStatic(mod))) { String name = m.getName(); if (name.startsWith("set") && (m.getParameterTypes().length == 1)) { String propertyName = name.substring(3); Type valueType = m.getGenericParameterTypes()[0]; GetSetPair p = ret.get(propertyName); if (p != null && p.type.equals(valueType)) { p.setMethod = m; } } } } // exclude incomplete get/set pair, and generate test value Iterator<Entry<String, GetSetPair>> itr = ret.entrySet().iterator(); while (itr.hasNext()) { Entry<String, GetSetPair> cur = itr.next(); GetSetPair gsp = cur.getValue(); if ((gsp.getMethod == null) || (gsp.setMethod == null)) { LOG.info(String.format("Exclude protential property: %s\n", gsp.propertyName)); itr.remove(); } else { LOG.info(String.format("New property: %s type: %s", gsp.toString(), gsp.type)); gsp.testValue = genTypeValue(gsp.type); LOG.info(String.format(" testValue: %s\n", gsp.testValue)); } } return ret; }
From source file:com.googlecode.jsonrpc4j.JsonRpcServer.java
/** * Invokes the given method on the {@code handler} passing * the given params (after converting them to beans\objects) * to it./*from ww w .j a v a2 s. co m*/ * * @param an optional service name used to locate the target object * to invoke the Method on * @param m the method to invoke * @param params the params to pass to the method * @return the return value (or null if no return) * @throws IOException on error * @throws IllegalAccessException on error * @throws InvocationTargetException on error */ protected JsonNode invoke(Object target, Method m, List<JsonNode> params) throws IOException, IllegalAccessException, InvocationTargetException { // debug log if (LOGGER.isLoggable(Level.FINE)) { LOGGER.log(Level.FINE, "Invoking method: " + m.getName()); } // convert the parameters Object[] convertedParams = new Object[params.size()]; Type[] parameterTypes = m.getGenericParameterTypes(); for (int i = 0; i < parameterTypes.length; i++) { JsonParser paramJsonParser = mapper.treeAsTokens(params.get(i)); JavaType paramJavaType = TypeFactory.defaultInstance().constructType(parameterTypes[i]); convertedParams[i] = mapper.readValue(paramJsonParser, paramJavaType); } // invoke the method Object result = m.invoke(target, convertedParams); return (m.getGenericReturnType() != null) ? mapper.valueToTree(result) : null; }
From source file:edu.ku.brc.specify.tools.datamodelgenerator.DatamodelGenerator.java
/** * @param className/* www .j a va2 s. c o m*/ * @param tableList */ @SuppressWarnings("cast") protected void processClass(final String className, final List<Table> tableList) { try { Class<?> classObj = Class.forName(packageName + "." + className); Table table = null; String tableName = null; if (classObj.isAnnotationPresent(javax.persistence.Table.class)) { Vector<TableIndex> indexes = new Vector<TableIndex>(); javax.persistence.Table tableAnno = (javax.persistence.Table) classObj .getAnnotation(javax.persistence.Table.class); tableName = tableAnno.name(); org.hibernate.annotations.Table hiberTableAnno = (org.hibernate.annotations.Table) classObj .getAnnotation(org.hibernate.annotations.Table.class); if (hiberTableAnno != null) { //System.out.println("Table Indexes: "); for (Index index : hiberTableAnno.indexes()) { //System.out.println(" "+index.name() + " "+ index.columnNames()); indexes.add(new TableIndex(index.name(), index.columnNames())); } } table = createTable(packageName + "." + className, tableName); if (includeDesc) { table.setDesc(getTableDesc(tableName)); table.setNameDesc(getTableNameDesc(tableName)); } table.setIndexes(indexes); tableList.add(table); } if (table != null) { boolean isLob = false; for (Method method : classObj.getMethods()) { String methodName = method.getName(); if (!methodName.startsWith("get")) { continue; } if (DEBUG) { System.out.println(className + " " + method.getName()); } Type type = method.getGenericReturnType(); Class<?> typeClass; if (type instanceof Class<?>) { typeClass = (Class<?>) type; } else if (type instanceof ParameterizedType) { typeClass = null; for (Type t : ((ParameterizedType) type).getActualTypeArguments()) { if (t instanceof Class<?>) { typeClass = (Class<?>) t; } } } else { if (!method.getName().equals("getDataObj") && !method.getName().equals("getTreeRootNode")) { log.warn("Not handled: " + type); } typeClass = null; } // rods 07/10/08 - Used to skip all relationships that point to themselves // that works now and is needed. if (typeClass == null || typeClass == AttributeIFace.class || typeClass == PickListItemIFace.class || typeClass == RecordSetItemIFace.class) { continue; } String thisSideName = getFieldNameFromMethod(method); if (method.isAnnotationPresent(javax.persistence.Lob.class)) { isLob = true; } if (method.isAnnotationPresent(javax.persistence.Column.class)) { if (method.isAnnotationPresent(javax.persistence.Id.class)) { table.addId(createId(method, (javax.persistence.Column) method .getAnnotation(javax.persistence.Column.class))); } else { Field field = createField(method, (javax.persistence.Column) method.getAnnotation(javax.persistence.Column.class), isLob); if (includeDesc) { field.setDesc(getFieldDesc(tableName, field.getName())); field.setNameDesc(getFieldNameDesc(tableName, field.getName())); } if (typeClass == java.util.Calendar.class) { String mName = method.getName() + "Precision"; for (Method mthd : classObj.getMethods()) { if (mthd.getName().equals(mName)) { field.setPartialDate(true); field.setDatePrecisionName(field.getName() + "Precision"); break; } } } table.addField(field); } } else if (method.isAnnotationPresent(javax.persistence.ManyToOne.class)) { javax.persistence.ManyToOne oneToMany = (javax.persistence.ManyToOne) method .getAnnotation(javax.persistence.ManyToOne.class); boolean isSave = false; for (CascadeType ct : oneToMany.cascade()) { if (ct == CascadeType.ALL || ct == CascadeType.PERSIST) { isSave = true; } } isSave = !isSave ? isOKToSave(method) : isSave; String otherSideName = getRightSideForManyToOne(classObj, typeClass, thisSideName); javax.persistence.JoinColumn join = method .isAnnotationPresent(javax.persistence.JoinColumn.class) ? (javax.persistence.JoinColumn) method .getAnnotation(javax.persistence.JoinColumn.class) : null; if (join != null) { //String othersideName = typeClass == null ? "" : getOthersideName(classObj, typeClass, thisSideName, RelType.OneToMany); Relationship rel = createRelationship(method, "many-to-one", join, otherSideName, join != null ? !join.nullable() : false); table.addRelationship(rel); rel.setSave(isSave); if (includeDesc) { rel.setDesc(getFieldDesc(tableName, rel.getRelationshipName())); rel.setNameDesc(getFieldNameDesc(tableName, rel.getRelationshipName())); } } else { log.error("No Join!"); } } else if (method.isAnnotationPresent(javax.persistence.ManyToMany.class)) { javax.persistence.ManyToMany manyToMany = method .getAnnotation(javax.persistence.ManyToMany.class); String othersideName = manyToMany.mappedBy(); if (StringUtils.isEmpty(othersideName)) { othersideName = getRightSideForManyToMany(classObj, typeClass, getFieldNameFromMethod(method)); } boolean isSave = false; for (CascadeType ct : manyToMany.cascade()) { if (ct == CascadeType.ALL || ct == CascadeType.PERSIST) { isSave = true; } } isSave = !isSave ? isOKToSave(method) : isSave; javax.persistence.JoinColumn join = method .isAnnotationPresent(javax.persistence.JoinColumn.class) ? (javax.persistence.JoinColumn) method .getAnnotation(javax.persistence.JoinColumn.class) : null; Relationship rel = createRelationship(method, "many-to-many", join, othersideName, join != null ? !join.nullable() : false); rel.setLikeManyToOne(table.getIsLikeManyToOne(rel.getRelationshipName())); rel.setSave(isSave); table.addRelationship(rel); if (includeDesc) { rel.setDesc(getFieldDesc(tableName, rel.getRelationshipName())); rel.setNameDesc(getFieldNameDesc(tableName, rel.getRelationshipName())); } javax.persistence.JoinTable joinTable = method .getAnnotation(javax.persistence.JoinTable.class); if (joinTable != null) { rel.setJoinTableName(joinTable.name()); } } else if (method.isAnnotationPresent(javax.persistence.OneToMany.class)) { javax.persistence.OneToMany oneToMany = (javax.persistence.OneToMany) method .getAnnotation(javax.persistence.OneToMany.class); String othersideName = oneToMany.mappedBy(); if (StringUtils.isEmpty(othersideName)) { // This Should never happen othersideName = getRightSideForOneToMany(classObj, typeClass, oneToMany.mappedBy()); } boolean isSave = false; for (CascadeType ct : oneToMany.cascade()) { if (ct == CascadeType.ALL || ct == CascadeType.PERSIST) { isSave = true; } } isSave = !isSave ? isOKToSave(method) : isSave; javax.persistence.JoinColumn join = method .isAnnotationPresent(javax.persistence.JoinColumn.class) ? (javax.persistence.JoinColumn) method .getAnnotation(javax.persistence.JoinColumn.class) : null; Relationship rel = createRelationship(method, "one-to-many", join, othersideName, join != null ? !join.nullable() : false); rel.setLikeManyToOne(table.getIsLikeManyToOne(rel.getRelationshipName())); rel.setSave(isSave); table.addRelationship(rel); if (includeDesc) { rel.setDesc(getFieldDesc(tableName, rel.getRelationshipName())); rel.setNameDesc(getFieldNameDesc(tableName, rel.getRelationshipName())); } } else if (method.isAnnotationPresent(javax.persistence.OneToOne.class)) { javax.persistence.OneToOne oneToOne = (javax.persistence.OneToOne) method .getAnnotation(javax.persistence.OneToOne.class); String leftSideVarName = getFieldNameFromMethod(method); boolean isMappedBy = true; String othersideName = oneToOne.mappedBy(); if (StringUtils.isEmpty(othersideName)) { isMappedBy = false; othersideName = getRightSideForOneToOne(classObj, typeClass, leftSideVarName, othersideName, isMappedBy); } boolean isSave = false; for (CascadeType ct : oneToOne.cascade()) { if (ct == CascadeType.ALL || ct == CascadeType.PERSIST) { isSave = true; } } isSave = !isSave ? isOKToSave(method) : isSave; javax.persistence.JoinColumn join = method .isAnnotationPresent(javax.persistence.JoinColumn.class) ? (javax.persistence.JoinColumn) method .getAnnotation(javax.persistence.JoinColumn.class) : null; Relationship rel = createRelationship(method, "one-to-one", join, othersideName, join != null ? !join.nullable() : false); rel.setSave(isSave); table.addRelationship(rel); if (includeDesc) { rel.setDesc(getFieldDesc(tableName, rel.getRelationshipName())); rel.setNameDesc(getFieldNameDesc(tableName, rel.getRelationshipName())); } } isLob = false; } // This updates each field as to whether it is an index table.updateIndexFields(); } } catch (Exception ex) { ex.printStackTrace(); } }
From source file:com.bstek.dorado.idesupport.initializer.CommonRuleTemplateInitializer.java
protected Collection<AutoPropertyTemplate> getProperties(Class<?> type, XmlNodeInfo xmlNodeInfo, InitializerContext initializerContext) throws Exception { HashMap<String, AutoPropertyTemplate> properties = new LinkedHashMap<String, AutoPropertyTemplate>(); RuleTemplateManager ruleTemplateManager = initializerContext.getRuleTemplateManager(); if (xmlNodeInfo != null) { if (xmlNodeInfo.isInheritable()) { AutoPropertyTemplate propertyTemplate = new AutoPropertyTemplate("impl"); propertyTemplate.setPrimitive(true); properties.put(propertyTemplate.getName(), propertyTemplate); propertyTemplate = new AutoPropertyTemplate("parent"); propertyTemplate.setPrimitive(true); properties.put(propertyTemplate.getName(), propertyTemplate); }// w w w .j a va2 s. c om if (xmlNodeInfo.isScopable()) { AutoPropertyTemplate propertyTemplate = new AutoPropertyTemplate("scope"); propertyTemplate.setPrimitive(true); Object[] ecs = Scope.class.getEnumConstants(); String[] enumValues = new String[ecs.length]; for (int i = 0; i < ecs.length; i++) { enumValues[i] = ecs[i].toString(); } propertyTemplate.setEnumValues(enumValues); properties.put(propertyTemplate.getName(), propertyTemplate); } if (StringUtils.isNotEmpty(xmlNodeInfo.getDefinitionType())) { Class<?> definitionType = ClassUtils.forName(xmlNodeInfo.getDefinitionType()); if (ListenableObjectDefinition.class.isAssignableFrom(definitionType)) { AutoPropertyTemplate propertyTemplate = new AutoPropertyTemplate("listener"); propertyTemplate.setPrimitive(true); properties.put(propertyTemplate.getName(), propertyTemplate); } if (InterceptableDefinition.class.isAssignableFrom(definitionType)) { AutoPropertyTemplate propertyTemplate = new AutoPropertyTemplate("interceptor"); propertyTemplate.setPrimitive(true); properties.put(propertyTemplate.getName(), propertyTemplate); } } for (Map.Entry<String, String> entry : xmlNodeInfo.getFixedProperties().entrySet()) { String propertyName = entry.getKey(); String value = entry.getValue(); AutoPropertyTemplate propertyTemplate = new AutoPropertyTemplate(propertyName); propertyTemplate.setDefaultValue(value); propertyTemplate.setPrimitive(true); propertyTemplate.setFixed(true); propertyTemplate.setVisible(false); properties.put(propertyName, propertyTemplate); } for (Map.Entry<String, XmlProperty> entry : xmlNodeInfo.getProperties().entrySet()) { String propertyName = entry.getKey(); XmlProperty xmlProperty = entry.getValue(); TypeInfo propertyTypeInfo = TypeInfo.parse(xmlProperty.propertyType()); Class<?> propertyType = null; if (propertyTypeInfo != null) { propertyType = propertyTypeInfo.getType(); } AutoPropertyTemplate propertyTemplate = new AutoPropertyTemplate(propertyName, xmlProperty); propertyTemplate.setPrimitive(xmlProperty.attributeOnly()); if (propertyType != null && !propertyType.equals(String.class)) { propertyTemplate.setType(propertyType.getName()); } if (xmlProperty.composite()) { initCompositeProperty(propertyTemplate, propertyType, initializerContext); } propertyTemplate.setDeprecated(xmlProperty.deprecated()); properties.put(propertyName, propertyTemplate); } } PropertyDescriptor[] propertyDescriptors = PropertyUtils.getPropertyDescriptors(type); for (PropertyDescriptor propertyDescriptor : propertyDescriptors) { Method readMethod = propertyDescriptor.getReadMethod(); if (readMethod != null && propertyDescriptor.getWriteMethod() != null) { if (readMethod.getDeclaringClass() != type) { try { readMethod = type.getDeclaredMethod(readMethod.getName(), readMethod.getParameterTypes()); } catch (NoSuchMethodException e) { continue; } } String propertyName = propertyDescriptor.getName(); XmlSubNode xmlSubNode = readMethod.getAnnotation(XmlSubNode.class); if (xmlSubNode != null) { continue; } TypeInfo propertyTypeInfo; Class<?> propertyType = propertyDescriptor.getPropertyType(); if (Collection.class.isAssignableFrom(propertyType)) { propertyTypeInfo = TypeInfo.parse((ParameterizedType) readMethod.getGenericReturnType(), true); propertyType = propertyTypeInfo.getType(); } else { propertyTypeInfo = new TypeInfo(propertyType, false); } AutoPropertyTemplate propertyTemplate = null; XmlProperty xmlProperty = readMethod.getAnnotation(XmlProperty.class); if (xmlProperty != null) { if (xmlProperty.unsupported()) { continue; } propertyTemplate = properties.get(propertyName); if (propertyTemplate == null) { propertyTemplate = new AutoPropertyTemplate(propertyName, readMethod, xmlProperty); propertyTemplate.setPrimitive(xmlProperty.attributeOnly()); } if (("dataSet".equals(propertyName) || "dataPath".equals(propertyName) || "property".equals(propertyName)) && DataControl.class.isAssignableFrom(type)) { propertyTemplate.setHighlight(1); } if (xmlProperty.composite()) { initCompositeProperty(propertyTemplate, propertyType, initializerContext); } int clientTypes = ClientType.parseClientTypes(xmlProperty.clientTypes()); if (clientTypes > 0) { propertyTemplate.setClientTypes(clientTypes); } propertyTemplate.setDeprecated(xmlProperty.deprecated()); } else if (EntityUtils.isSimpleType(propertyType) || propertyType.equals(Class.class) || propertyType.isArray() && propertyType.getComponentType().equals(String.class)) { propertyTemplate = new AutoPropertyTemplate(propertyName, readMethod, xmlProperty); } if (propertyTemplate != null) { propertyTemplate.setType(propertyDescriptor.getPropertyType().getName()); if (propertyType.isEnum()) { Object[] ecs = propertyType.getEnumConstants(); String[] enumValues = new String[ecs.length]; for (int i = 0; i < ecs.length; i++) { enumValues[i] = ecs[i].toString(); } propertyTemplate.setEnumValues(enumValues); } ComponentReference componentReference = readMethod.getAnnotation(ComponentReference.class); if (componentReference != null) { ReferenceTemplate referenceTemplate = new LazyReferenceTemplate(ruleTemplateManager, componentReference.value(), "id"); propertyTemplate.setReference(referenceTemplate); } IdeProperty ideProperty = readMethod.getAnnotation(IdeProperty.class); if (ideProperty != null) { propertyTemplate.setVisible(ideProperty.visible()); propertyTemplate.setEditor(ideProperty.editor()); propertyTemplate.setHighlight(ideProperty.highlight()); if (StringUtils.isNotEmpty(ideProperty.enumValues())) { propertyTemplate.setEnumValues(StringUtils.split(ideProperty.enumValues(), ",;")); } } ClientProperty clientProperty = readMethod.getAnnotation(ClientProperty.class); if (clientProperty != null) { propertyTemplate.setDefaultValue(clientProperty.escapeValue()); } properties.put(propertyName, propertyTemplate); } } } return properties.values(); }