List of usage examples for java.lang Class isAnnotationPresent
@Override public boolean isAnnotationPresent(Class<? extends Annotation> annotationClass)
From source file:com.github.jackygurui.vertxredissonrepository.repository.Impl.RedisRepositoryImpl.java
public RedisRepositoryImpl(Vertx vertx, Redisson redissonRead, Redisson redissonWrite, Redisson redissonOther, Class<T> cls, RedisRepositoryFactory factory) { this.vertx = vertx; this.redissonRead = redissonRead; this.redissonWrite = redissonWrite; this.redissonOther = redissonOther; this.schema = cls.isAnnotationPresent(JsonSchemaValid.class) ? schemaFactory.createSchema(cls) : null; this.cls = cls; this.factory = factory; }
From source file:com.github.gekoh.yagen.hst.CreateEntities.java
private String createHistoryEntity(String baseClassPackageName, String hstEntityClassPackageName, String hstEntityClassSimpleName, String historyTableName, String historyTableShortName, Class baseEntity, Reader template, List<FieldInfo> fields) { String hstEntityClassName = hstEntityClassPackageName + "." + hstEntityClassSimpleName; Class baseEntitySuperClass = baseEntity != null && !baseEntity.getSuperclass().equals(Object.class) ? baseEntity.getSuperclass() : null;/*from w ww . ja v a 2s. c om*/ String classAnnotations = ""; VelocityContext context = new VelocityContext(); context.put("baseClassPackageName", baseClassPackageName); context.put("entityClassPackageName", hstEntityClassPackageName); context.put("entityClassSimpleName", hstEntityClassSimpleName); if (historyTableName != null) { context.put("tableName", historyTableName); if (historyTableShortName != null) { context.put("tableShortName", CreateDDL.getHistTableShortNameFromLiveTableShortName(historyTableShortName)); classAnnotations = String.format("@com.github.gekoh.yagen.api.Table(shortName=%s.%s)\n", hstEntityClassSimpleName, CreateDDL.STATIC_FIELD_TABLE_NAME_SHORT); } } context.put("fieldInfoList", fields); if (baseEntity != null && baseEntity.isAnnotationPresent(MappedSuperclass.class)) { context.put("classAnnotation", classAnnotations + "@javax.persistence.MappedSuperclass"); } else if (baseEntity != null && baseEntity.isAnnotationPresent(Entity.class)) { String value = classAnnotations + "@javax.persistence.Entity"; String entityName = ((Entity) baseEntity.getAnnotation(Entity.class)).name(); if (StringUtils.isNotEmpty(entityName)) { value += "(name = \"" + entityName + HISTORY_ENTITY_SUFFIX + "\")"; } context.put("classAnnotation", value); } // Inheritance used, baseEntity is superclass if (baseEntity != null && baseEntity.isAnnotationPresent(Inheritance.class)) { DiscriminatorColumn discriminatorColumn = (DiscriminatorColumn) baseEntity .getAnnotation(DiscriminatorColumn.class); String classAnnotation = context.get("classAnnotation") + "\n" + "@javax.persistence.Inheritance(strategy=javax.persistence.InheritanceType." + ((Inheritance) baseEntity.getAnnotation(Inheritance.class)).strategy().name() + ")"; if (discriminatorColumn != null) { classAnnotation += "\n@javax.persistence.DiscriminatorColumn(name=\"" + discriminatorColumn.name() + "\", length=" + discriminatorColumn.length() + ")"; } context.put("classAnnotation", classAnnotation); } // Inheritance used, baseEntity is subclass else if (baseEntity != null && baseEntity.isAnnotationPresent(DiscriminatorValue.class)) { context.put("classAnnotation", context.get("classAnnotation") + "\n" + "@javax.persistence.DiscriminatorValue(\"" + ((DiscriminatorValue) baseEntity.getAnnotation(DiscriminatorValue.class)).value() + "\")"); } if (baseEntitySuperClass != null) { context.put("entitySuperClassName", baseEntitySuperClass.getName() + "Hst"); } else if (baseEntity != null) { String name; int length; PrimaryKeyJoinColumn pkJC = (PrimaryKeyJoinColumn) baseEntity.getAnnotation(PrimaryKeyJoinColumn.class); if (pkJC != null) { name = pkJC.name(); length = Constants.UUID_LEN; } else { Column column = getUuidColumn(baseEntity); AccessibleObject idFieldOrMethod = FieldInfo.getIdFieldOrMethod(baseEntity); name = MappingUtils.deriveColumnName(column, idFieldOrMethod); length = column.length(); } context.put("baseEntityUuidColumnName", name.toLowerCase()); context.put("baseEntityUuidColumnLength", length); } evaluate2JavaFile(hstEntityClassName, template, context); return hstEntityClassName; }
From source file:edu.ku.brc.specify.tools.datamodelgenerator.DatamodelGenerator.java
/** * @param className/*from ww w .j a v a 2 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:org.kuali.rice.krad.demo.uif.components.ComponentLibraryView.java
/** * Builds out the documentation tab content by auto-generating the content for properties and documentation and * adds it to the tabItems list// w ww . jav a2 s. co m * * @param tabItems list of tab items for component details */ private void processDocumentationTab(List<Component> tabItems) { MessageService messageService = KRADServiceLocatorWeb.getMessageService(); try { Class<?> componentClass = Class.forName(javaFullClassPath); Method methodsArray[] = componentClass.getMethods(); //get top level documentation for this class String classMessage = messageService.getMessageText("KR-SAP", null, javaFullClassPath); if (classMessage == null) { classMessage = "NO DOCUMENTATION AVAILABLE/FOUND... we are working on it!"; } //scrub class message of @link and @code classMessage = classMessage.replaceAll("\\{[@#]link (.*?)\\}", "<i>$1</i>"); classMessage = classMessage.replaceAll("\\{[@#]code (.*?)\\}", "<i>$1</i>"); //Generate schema and bean Id reference table String schemaTable = "<table class='demo-schemaIdDocTable'><tr><th>Schema Name</th>" + "<th>Uif Bean Id</th></tr>"; if (componentClass.isAnnotationPresent(BeanTag.class)) { BeanTag beanTag = componentClass.getAnnotation(BeanTag.class); schemaTable = schemaTable + "<tr><td>" + beanTag.name() + "</td><td>" + beanTag.parent() + "</td></tr>"; schemaTable = schemaTable + "</table>"; } else if (componentClass.isAnnotationPresent(BeanTags.class)) { BeanTags beanTags = componentClass.getAnnotation(BeanTags.class); BeanTag[] beanTagArray = beanTags.value(); for (BeanTag beanTag : beanTagArray) { schemaTable = schemaTable + "<tr><td>" + beanTag.name() + "</td><td>" + beanTag.parent() + "</td></tr>"; } schemaTable = schemaTable + "</table>"; } else { schemaTable = ""; } String componentName = StringUtils.defaultIfBlank(StringUtils.defaultString(getComponentName()) + " ", ""); String javadocTitle = messageService.getMessageText("KR-SAP", null, "componentLibrary.javaDoc"); String kradGuideTitle = messageService.getMessageText("KR-SAP", null, "componentLibrary.kradGuide"); String devDocumentationTitle = messageService.getMessageText("KR-SAP", null, "componentLibrary.devDocumentation"); String beanDefsTitle = messageService.getMessageText("KR-SAP", null, "componentLibrary.beanDefs"); //build documentation links from javadoc address and docbook address/anchor String docLinkDiv = "<div class='demo-docLinks'> " + "<label>Additional Resources:</label><a class='demo-documentationLink'" + " href='" + getRootJavadocAddress() + javaFullClassPath.replace('.', '/') + ".html' target='_blank'>" + javadocTitle + "</a>" + "<a class='demo-documentationLink'" + " href='" + getRootDocBookAddress() + getDocBookAnchor() + "' target='_blank'>" + kradGuideTitle + "</a>" + "</div>"; //initialize the documentation content String documentationMessageContent = "<H3 class=\"uif-documentationHeader\">" + componentName + devDocumentationTitle + "</H3>" + docLinkDiv + classMessage + "<H3>" + beanDefsTitle + "</H3>" + schemaTable; List<String> propertyDescriptions = new ArrayList<String>(); Map<String, List<String>> inheritedProperties = new HashMap<String, List<String>>(); List<Method> methods = Arrays.asList(methodsArray); //alphabetize the methods by name Collections.sort(methods, new Comparator<Method>() { @Override public int compare(Method method1, Method method2) { String name1 = getPropName(method1); String name2 = getPropName(method2); return name1.compareTo(name2); //To change body of implemented methods use File | Settings | File Templates. } }); //Process all methods on this class for (Method method : methods) { BeanTagAttribute attribute = method.getAnnotation(BeanTagAttribute.class); if (attribute != null) { //property variables String name = getPropName(method); String methodClass = method.getDeclaringClass().getName(); String returnType = method.getReturnType().getName(); returnType = returnType.replaceAll("<.*?>", ""); String returnTypeShort = returnType.substring(returnType.lastIndexOf(".") + 1); //get property documentation message String key = methodClass + "|" + name + "|" + returnTypeShort; String propertyMessage = messageService.getMessageText("KR-SAP", null, key); if (propertyMessage == null) { propertyMessage = "NO DOCUMENTATION AVAILABLE... we are working on it!"; } //scrub property message of @link and @code propertyMessage = propertyMessage.replaceAll("\\{[@#]link (.*?)\\}", "<i>$1</i>"); propertyMessage = propertyMessage.replaceAll("\\{[@#]code (.*?)\\}", "<i>$1</i>"); //wrap in link if a kuali type if (returnType.startsWith("org.kuali")) { returnTypeShort = "<a href='" + getRootJavadocAddress() + returnType.replace('.', '/') + ".html' target='_blank'>" + returnTypeShort + "</a>"; } //html propertyMessage content propertyMessage = "<div class='demo-propertyItem'>" + "<h4 class='demo-propertyName'>" + name + "</h4>" + "<div class='demo-propertyType'>" + returnTypeShort + "</div>" + "<div class='demo-propertyDesc'>" + propertyMessage + "</div></div>"; if (!methodClass.equals(javaFullClassPath)) { //if this method comes from a parent and not this class, put it in the inheritedPropertiesMap List<String> classProperties = inheritedProperties.get(methodClass); if (classProperties == null) { classProperties = new ArrayList<String>(); } classProperties.add(propertyMessage); inheritedProperties.put(methodClass, classProperties); } else { propertyDescriptions.add(propertyMessage); } } } documentationMessageContent = documentationMessageContent + "<H3>Properties</H3><div class='demo-propertiesContent'>"; for (String desc : propertyDescriptions) { documentationMessageContent = documentationMessageContent + desc; } documentationMessageContent = documentationMessageContent + "</div>"; Group documentationGroup = ComponentFactory.getVerticalBoxGroup(); //properties header Header documentationHeader = (Header) ComponentFactory.getNewComponentInstance("Uif-SubSectionHeader"); documentationHeader.setHeaderLevel("H3"); documentationHeader .setHeaderText(messageService.getMessageText("KR-SAP", null, "componentLibrary.documentation")); documentationHeader.setRender(false); documentationGroup.setHeader(documentationHeader); List<Component> propertiesItems = new ArrayList<Component>(); Message propertiesMessage = ComponentFactory.getMessage(); propertiesMessage.setParseComponents(false); propertiesMessage.setMessageText(documentationMessageContent); propertiesItems.add(propertiesMessage); //create the inherited properties disclosures if (!inheritedProperties.isEmpty()) { //todo sort alphabetically here? for (String className : inheritedProperties.keySet()) { String messageContent = ""; List<String> inheritedPropertyDescriptions = inheritedProperties.get(className); for (String desc : inheritedPropertyDescriptions) { messageContent = messageContent + desc; } Group iPropertiesGroup = ComponentFactory.getVerticalBoxGroup(); //inherited properties header Header iPropHeader = (Header) ComponentFactory.getNewComponentInstance("Uif-SubSectionHeader"); iPropHeader.setHeaderLevel("H3"); iPropHeader.setHeaderText( messageService.getMessageText("KR-SAP", null, "componentLibrary.inheritedFrom") + " " + className); //iPropHeader.setRender(false); iPropertiesGroup.setHeader(iPropHeader); iPropertiesGroup.getDisclosure().setRender(true); iPropertiesGroup.getDisclosure().setDefaultOpen(false); List<Component> iPropertiesItems = new ArrayList<Component>(); Message iPropertiesMessage = ComponentFactory.getMessage(); iPropertiesMessage.setParseComponents(false); iPropertiesMessage.setMessageText(messageContent); iPropertiesItems.add(iPropertiesMessage); iPropertiesGroup.setItems(iPropertiesItems); propertiesItems.add(iPropertiesGroup); } } documentationGroup.setItems(propertiesItems); tabItems.add(documentationGroup); } catch (Exception e) { throw new RuntimeException("Error loading class: " + javaFullClassPath, e); } }
From source file:it.isislab.dmason.tools.batch.BatchWizard.java
private boolean isThinSimulation(File simFile) { URL url;/*from w ww .j a v a2 s. c om*/ Class c; Object instance; try { url = new URL("file:" + simFile.getAbsolutePath()); JarClassLoader cl = new JarClassLoader(url); cl.addToClassPath(); String main = cl.getMainClassName(); c = cl.loadClass(main); return c.isAnnotationPresent(ThinAnnotation.class); } catch (MalformedURLException e) { // TODO Auto-generated catch block e.printStackTrace(); } catch (NoSuchMethodException e) { // TODO Auto-generated catch block e.printStackTrace(); } catch (IllegalAccessException e) { // TODO Auto-generated catch block e.printStackTrace(); } catch (InvocationTargetException e) { // TODO Auto-generated catch block e.printStackTrace(); } catch (IOException e) { // TODO Auto-generated catch block e.printStackTrace(); } catch (ClassNotFoundException e) { // TODO Auto-generated catch block e.printStackTrace(); } catch (SecurityException e) { // TODO Auto-generated catch block e.printStackTrace(); } return false; }
From source file:com.github.helenusdriver.driver.impl.StatementManagerImpl.java
/** * Gets a class info structure that defines the specified POJO class. * * @author paouelle//from w w w . j av a 2 s .co m * * @param <T> The type of POJO associated with this statement * * @param clazz the class of POJO for which to get a class info object for * @return the non-<code>null</code> class info object representing the given * POJO class * @throws NullPointerException if <code>clazz</code> is <code>null</code> * @throws IllegalArgumentException if <code>clazz</code> doesn't represent * a valid POJO class */ @SuppressWarnings("unchecked") public <T> ClassInfoImpl<T> getClassInfoImpl(Class<T> clazz) { synchronized (classInfoCache) { ClassInfoImpl<T> classInfo = (ClassInfoImpl<T>) classInfoCache.get(clazz); if (classInfo == null) { final Class<? super T> rclazz = ReflectionUtils.findFirstClassAnnotatedWith(clazz, RootEntity.class); if (rclazz != null) { org.apache.commons.lang3.Validate.isTrue(!clazz.isAnnotationPresent(Entity.class), "class '%s' cannot be annotated with both @RootEntity and @Entity", clazz.getSimpleName()); org.apache.commons.lang3.Validate.isTrue(!clazz.isAnnotationPresent(UDTEntity.class), "class '%s' cannot be annotated with both @RootEntity and @UDTEntity", clazz.getSimpleName()); if (rclazz == clazz) { // this is the root element class org.apache.commons.lang3.Validate.isTrue(!clazz.isAnnotationPresent(TypeEntity.class), "class '%s' cannot be annotated with both @RootEntity and @TypeEntity", clazz.getSimpleName()); classInfo = new RootClassInfoImpl<>(this, clazz); } else { if (clazz.isAnnotationPresent(TypeEntity.class)) { // for types, we get it from the root final RootClassInfoImpl<? super T> rcinfo = (RootClassInfoImpl<? super T>) getClassInfoImpl( rclazz); classInfo = rcinfo.getType(clazz); } else { throw new IllegalArgumentException( "class '" + clazz.getSimpleName() + "' is not annotated with @TypeEntity"); } } } else if (clazz.isAnnotationPresent(UDTEntity.class)) { org.apache.commons.lang3.Validate.isTrue(!clazz.isAnnotationPresent(Entity.class), "class '%s' cannot be annotated with both @UDTEntity and @Entity", clazz.getSimpleName()); classInfo = new UDTClassInfoImpl<>(this, clazz); } else if (clazz.isAnnotationPresent(Entity.class)) { classInfo = new ClassInfoImpl<>(this, clazz); } else { throw new IllegalArgumentException( "class '" + clazz.getSimpleName() + "' is not annotated with @Entity"); } classInfoCache.put(clazz, classInfo); } return classInfo; } }
From source file:com.jsmartframework.web.manager.BeanHandler.java
private void initAnnotatedRequestPaths(Reflections reflections) { Set<Class<?>> annotations = reflections.getTypesAnnotatedWith(RequestPath.class); for (Class<?> clazz : annotations) { RequestPath requestPath = clazz.getAnnotation(RequestPath.class); LOGGER.log(Level.INFO, "Mapping RequestPath class: " + clazz); if (!clazz.isAnnotationPresent(Controller.class)) { throw new RuntimeException("Mapped RequestPath class [" + clazz + "] must be annotated with " + "org.springframework.stereotype.Controller from Spring"); }/*from w w w . j a v a 2 s . c om*/ if (!requestPath.value().endsWith("*")) { throw new RuntimeException("Mapped class [" + clazz + "] annotated with @RequestPath must have its " + "path annotation attribute ending with * character"); } HELPER.setBeanFields(clazz); HELPER.setBeanMethods(clazz); requestPaths.put(requestPath.value(), clazz); } if (requestPaths.isEmpty()) { LOGGER.log(Level.INFO, "RequestPaths were not mapped!"); } for (Class<?> pathClazz : requestPaths.values()) { for (Class<?> webClazz : webBeans.values()) { if (webClazz == pathClazz) { LOGGER.log(Level.SEVERE, "@WebBean class [" + webClazz + "] cannot be annotated with @RequestPath"); } } } checkWebBeanConstraint(annotations, "@RequestPath"); checkAuthBeanConstraint(annotations, "@RequestPath"); }
From source file:org.photovault.replication.VersionedClassDesc.java
/** Analyze the annotations in described class and populate this object based on results/*from w w w. j a va 2 s. c om*/ @param cl the clas to analyze */ private void analyzeClass(Class cl) { Class scl = cl.getSuperclass(); if (scl != null) { analyzeClass(scl); } Versioned info = (Versioned) cl.getAnnotation(Versioned.class); if (info != null) { editorIntf = info.editor(); Class csClass = info.changeSerializer(); try { changeSerializer = (ChangeSerializer) csClass.newInstance(); } catch (IllegalAccessException ex) { throw new RuntimeException(ex); } catch (InstantiationException ex) { throw new RuntimeException(ex); } } for (Method m : cl.getDeclaredMethods()) { if (m.isAnnotationPresent(ValueField.class)) { try { ValueFieldDesc f = new ValueFieldDesc(this, m, editorIntf); fields.put(f.name, f); } catch (NoSuchMethodException ex) { log.error("Error analyzing method " + cl.getName() + "." + m.getName(), ex); throw new IllegalArgumentException("Error analyzing method " + cl.getName() + "." + m.getName(), ex); } } else if (m.isAnnotationPresent(SetField.class)) { try { SetFieldDesc f = new SetFieldDesc(this, m, editorIntf); fields.put(f.name, f); } catch (NoSuchMethodException ex) { log.error("Error analyzing method " + cl.getName() + "." + m.getName(), ex); throw new IllegalArgumentException("Error analyzing method " + cl.getName() + "." + m.getName(), ex); } } else if (m.isAnnotationPresent(History.class)) { getHistoryMethod = m; } } if (cl.isAnnotationPresent(Versioned.class) && getHistoryMethod == null) { throw new IllegalStateException( "Versioned class " + cl.getName() + " does not define method for accessing history"); } }
From source file:com.evolveum.midpoint.repo.sql.query2.definition.ClassDefinitionParser.java
private JpaLinkDefinition parseMethod(Method method) { CollectionSpecification collectionSpecification; // non-null if return type is Set<X>, null if it's X Type returnedContentType; // X in return type, which is either X or Set<X> if (Set.class.isAssignableFrom(method.getReturnType())) { // e.g. Set<RObject> or Set<String> or Set<REmbeddedReference<RFocus>> Type returnType = method.getGenericReturnType(); if (!(returnType instanceof ParameterizedType)) { throw new IllegalStateException("Method " + method + " returns a non-parameterized collection"); }/*www. ja v a 2 s. c om*/ returnedContentType = ((ParameterizedType) returnType).getActualTypeArguments()[0]; collectionSpecification = new CollectionSpecification(); } else { returnedContentType = method.getReturnType(); collectionSpecification = null; } ItemPath itemPath = getJaxbName(method); String jpaName = getJpaName(method); Class jpaClass = getClass(returnedContentType); // sanity check if (Set.class.isAssignableFrom(jpaClass)) { throw new IllegalStateException("Collection within collection is not supported: method=" + method); } JpaLinkDefinition<? extends JpaDataNodeDefinition> linkDefinition; Any any = method.getAnnotation(Any.class); if (any != null) { JpaAnyContainerDefinition targetDefinition = new JpaAnyContainerDefinition(jpaClass); QName jaxbNameForAny = new QName(any.jaxbNameNamespace(), any.jaxbNameLocalPart()); linkDefinition = new JpaLinkDefinition<>(jaxbNameForAny, jpaName, collectionSpecification, false, targetDefinition); } else if (ObjectReference.class.isAssignableFrom(jpaClass)) { boolean embedded = method.isAnnotationPresent(Embedded.class); // computing referenced entity type from returned content type like RObjectReference<RFocus> or REmbeddedReference<RRole> Class referencedJpaClass; if (returnedContentType instanceof ParameterizedType) { referencedJpaClass = getClass( ((ParameterizedType) returnedContentType).getActualTypeArguments()[0]); } else { referencedJpaClass = RObject.class; } JpaReferenceDefinition targetDefinition = new JpaReferenceDefinition(jpaClass, referencedJpaClass); linkDefinition = new JpaLinkDefinition<>(itemPath, jpaName, collectionSpecification, embedded, targetDefinition); } else if (isEntity(jpaClass)) { JpaEntityDefinition content = parseClass(jpaClass); boolean embedded = method.isAnnotationPresent(Embedded.class) || jpaClass.isAnnotationPresent(Embeddable.class); linkDefinition = new JpaLinkDefinition<JpaDataNodeDefinition>(itemPath, jpaName, collectionSpecification, embedded, content); } else { boolean lob = method.isAnnotationPresent(Lob.class); boolean enumerated = method.isAnnotationPresent(Enumerated.class); //todo implement also lookup for @Table indexes boolean indexed = method.isAnnotationPresent(Index.class); Class jaxbClass = getJaxbClass(method, jpaClass); if (method.isAnnotationPresent(IdQueryProperty.class)) { if (collectionSpecification != null) { throw new IllegalStateException( "ID property is not allowed to be multivalued; for method " + method); } itemPath = new ItemPath(new IdentifierPathSegment()); } else if (method.isAnnotationPresent(OwnerIdGetter.class)) { if (collectionSpecification != null) { throw new IllegalStateException( "Owner ID property is not allowed to be multivalued; for method " + method); } itemPath = new ItemPath(new ParentPathSegment(), new IdentifierPathSegment()); } JpaPropertyDefinition propertyDefinition = new JpaPropertyDefinition(jpaClass, jaxbClass, lob, enumerated, indexed); // Note that properties are considered to be embedded linkDefinition = new JpaLinkDefinition<JpaDataNodeDefinition>(itemPath, jpaName, collectionSpecification, true, propertyDefinition); } return linkDefinition; }
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. */// w w w.j a v a 2 s . com 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); } } } }