List of usage examples for java.lang Class getModifiers
@HotSpotIntrinsicCandidate public native int getModifiers();
From source file:org.apache.axis.encoding.ser.BeanSerializer.java
/** * Return XML schema for the specified type, suitable for insertion into * the <types> element of a WSDL document, or underneath an * <element> or <attribute> declaration. * * @param javaType the Java Class we're writing out schema for * @param types the Java2WSDL Types object which holds the context * for the WSDL being generated. * @return a type element containing a schema simpleType/complexType * @see org.apache.axis.wsdl.fromJava.Types */// w w w .j a v a2s . co m public Element writeSchema(Class javaType, Types types) throws Exception { // ComplexType representation of bean class Element complexType = types.createElement("complexType"); // See if there is a super class, stop if we hit a stop class Element e = null; Class superClass = javaType.getSuperclass(); BeanPropertyDescriptor[] superPd = null; List stopClasses = types.getStopClasses(); if (superClass != null && superClass != java.lang.Object.class && superClass != java.lang.Exception.class && superClass != java.lang.Throwable.class && superClass != java.lang.RuntimeException.class && superClass != java.rmi.RemoteException.class && superClass != org.apache.axis.AxisFault.class && (stopClasses == null || !(stopClasses.contains(superClass.getName())))) { // Write out the super class String base = types.writeType(superClass); Element complexContent = types.createElement("complexContent"); complexType.appendChild(complexContent); Element extension = types.createElement("extension"); complexContent.appendChild(extension); extension.setAttribute("base", base); e = extension; // Get the property descriptors for the super class TypeDesc superTypeDesc = TypeDesc.getTypeDescForClass(superClass); if (superTypeDesc != null) { superPd = superTypeDesc.getPropertyDescriptors(); } else { superPd = BeanUtils.getPd(superClass, null); } } else { e = complexType; } // Add fields under sequence element. // Note: In most situations it would be okay // to put the fields under an all element. // However it is illegal schema to put an // element with minOccurs=0 or maxOccurs>1 underneath // an all element. This is the reason why a sequence // element is used. Element all = types.createElement("sequence"); e.appendChild(all); if (Modifier.isAbstract(javaType.getModifiers())) { complexType.setAttribute("abstract", "true"); } // Serialize each property for (int i = 0; i < propertyDescriptor.length; i++) { String propName = propertyDescriptor[i].getName(); // Don't serializer properties named class boolean writeProperty = true; if (propName.equals("class")) { writeProperty = false; } // Don't serialize the property if it is present // in the super class property list if (superPd != null && writeProperty) { for (int j = 0; j < superPd.length && writeProperty; j++) { if (propName.equals(superPd[j].getName())) { writeProperty = false; } } } if (!writeProperty) { continue; } // If we have type metadata, check to see what we're doing // with this field. If it's an attribute, skip it. If it's // an element, use whatever qname is in there. If we can't // find any of this info, use the default. if (typeDesc != null) { Class fieldType = propertyDescriptor[i].getType(); FieldDesc field = typeDesc.getFieldByName(propName); if (field != null) { QName qname = field.getXmlName(); QName fieldXmlType = field.getXmlType(); boolean isAnonymous = fieldXmlType != null && fieldXmlType.getLocalPart().startsWith(">"); if (qname != null) { // FIXME! // Check to see if this is in the right namespace - // if it's not, we need to use an <element ref=""> // to represent it!!! // Use the default... propName = qname.getLocalPart(); } if (!field.isElement()) { writeAttribute(types, propName, fieldType, fieldXmlType, complexType); } else { writeField(types, propName, fieldXmlType, fieldType, propertyDescriptor[i].isIndexed(), field.isMinOccursZero(), all, isAnonymous, ((ElementDesc) field).getItemQName()); } } else { writeField(types, propName, null, fieldType, propertyDescriptor[i].isIndexed(), false, all, false, null); } } else { boolean done = false; if (propertyDescriptor[i] instanceof FieldPropertyDescriptor) { FieldPropertyDescriptor fpd = (FieldPropertyDescriptor) propertyDescriptor[i]; Class clazz = fpd.getField().getType(); if (types.getTypeQName(clazz) != null) { writeField(types, propName, null, clazz, false, false, all, false, null); done = true; } } if (!done) { writeField(types, propName, null, propertyDescriptor[i].getType(), propertyDescriptor[i].isIndexed(), false, all, false, null); } } } // done return complexType; }
From source file:org.apache.click.util.ClickUtils.java
/** * Invoke the named method on the given target object and return the result. * * @param target the target object with the method to invoke * @param method the name of the method to invoke * @return Object the target method result */// w w w .java 2 s . c om private static Object invokeMethod(Object target, String method) { if (target == null) { throw new IllegalArgumentException("Null target parameter"); } if (method == null) { throw new IllegalArgumentException("Null method parameter"); } Method targetMethod = null; boolean isAccessible = true; try { Class<?> targetClass = target.getClass(); targetMethod = targetClass.getMethod(method); // Change accessible for anonymous inner classes public methods // only. Conditional checks: // #1 - Target method is not accessible // #2 - Anonymous inner classes are not public // #3 - Only modify public methods // #4 - Anonymous inner classes have no declaring class // #5 - Anonymous inner classes have $ in name if (!targetMethod.isAccessible() && !Modifier.isPublic(targetClass.getModifiers()) && Modifier.isPublic(targetMethod.getModifiers()) && targetClass.getDeclaringClass() == null && targetClass.getName().indexOf('$') != -1) { isAccessible = false; targetMethod.setAccessible(true); } return targetMethod.invoke(target); } catch (InvocationTargetException ite) { Throwable e = ite.getTargetException(); if (e instanceof RuntimeException) { throw (RuntimeException) e; } else if (e instanceof Exception) { String msg = "Exception occurred invoking public method: " + targetMethod; throw new RuntimeException(msg, e); } else if (e instanceof Error) { String msg = "Error occurred invoking public method: " + targetMethod; throw new RuntimeException(msg, e); } else { String msg = "Error occurred invoking public method: " + targetMethod; throw new RuntimeException(msg, e); } } catch (Exception e) { String msg = "Exception occurred invoking public method: " + targetMethod; throw new RuntimeException(msg, e); } finally { if (targetMethod != null && !isAccessible) { targetMethod.setAccessible(false); } } }
From source file:org.deeplearning4j.nn.conf.NeuralNetConfiguration.java
private static synchronized void registerSubtypes(ObjectMapper mapper) { //Register concrete subtypes for JSON serialization List<Class<?>> classes = Arrays.<Class<?>>asList(InputPreProcessor.class, ILossFunction.class, IActivation.class, Layer.class, GraphVertex.class, ReconstructionDistribution.class); List<String> classNames = new ArrayList<>(6); for (Class<?> c : classes) classNames.add(c.getName());/* w w w . j a va 2 s.c o m*/ // First: scan the classpath and find all instances of the 'baseClasses' classes if (subtypesClassCache == null) { //Check system property: String prop = System.getProperty(CUSTOM_FUNCTIONALITY); if (prop != null && !Boolean.parseBoolean(prop)) { subtypesClassCache = Collections.emptySet(); } else { List<Class<?>> interfaces = Arrays.<Class<?>>asList(InputPreProcessor.class, ILossFunction.class, IActivation.class, ReconstructionDistribution.class); List<Class<?>> classesList = Arrays.<Class<?>>asList(Layer.class, GraphVertex.class); Collection<URL> urls = ClasspathHelper.forClassLoader(); List<URL> scanUrls = new ArrayList<>(); for (URL u : urls) { String path = u.getPath(); if (!path.matches(".*/jre/lib/.*jar")) { //Skip JRE/JDK JARs scanUrls.add(u); } } Reflections reflections = new Reflections( new ConfigurationBuilder().filterInputsBy(new FilterBuilder().exclude("^(?!.*\\.class$).*$") //Consider only .class files (to avoid debug messages etc. on .dlls, etc //Exclude the following: the assumption here is that no custom functionality will ever be present // under these package name prefixes. These are all common dependencies for DL4J .exclude("^org.nd4j.*").exclude("^org.datavec.*").exclude("^org.bytedeco.*") //JavaCPP .exclude("^com.fasterxml.*")//Jackson .exclude("^org.apache.*") //Apache commons, Spark, log4j etc .exclude("^org.projectlombok.*").exclude("^com.twelvemonkeys.*") .exclude("^org.joda.*").exclude("^org.slf4j.*").exclude("^com.google.*") .exclude("^org.reflections.*").exclude("^ch.qos.*") //Logback ).addUrls(scanUrls).setScanners(new DL4JSubTypesScanner(interfaces, classesList))); org.reflections.Store store = reflections.getStore(); Iterable<String> subtypesByName = store.getAll(DL4JSubTypesScanner.class.getSimpleName(), classNames); Set<? extends Class<?>> subtypeClasses = Sets.newHashSet(ReflectionUtils.forNames(subtypesByName)); subtypesClassCache = new HashSet<>(); for (Class<?> c : subtypeClasses) { if (Modifier.isAbstract(c.getModifiers()) || Modifier.isInterface(c.getModifiers())) { //log.info("Skipping abstract/interface: {}",c); continue; } subtypesClassCache.add(c); } } } //Second: get all currently registered subtypes for this mapper Set<Class<?>> registeredSubtypes = new HashSet<>(); for (Class<?> c : classes) { AnnotatedClass ac = AnnotatedClass.construct(c, mapper.getSerializationConfig().getAnnotationIntrospector(), null); Collection<NamedType> types = mapper.getSubtypeResolver().collectAndResolveSubtypes(ac, mapper.getSerializationConfig(), mapper.getSerializationConfig().getAnnotationIntrospector()); for (NamedType nt : types) { registeredSubtypes.add(nt.getType()); } } //Third: register all _concrete_ subtypes that are not already registered List<NamedType> toRegister = new ArrayList<>(); for (Class<?> c : subtypesClassCache) { //Check if it's concrete or abstract... if (Modifier.isAbstract(c.getModifiers()) || Modifier.isInterface(c.getModifiers())) { //log.info("Skipping abstract/interface: {}",c); continue; } if (!registeredSubtypes.contains(c)) { String name; if (ClassUtils.isInnerClass(c)) { Class<?> c2 = c.getDeclaringClass(); name = c2.getSimpleName() + "$" + c.getSimpleName(); } else { name = c.getSimpleName(); } toRegister.add(new NamedType(c, name)); if (log.isDebugEnabled()) { for (Class<?> baseClass : classes) { if (baseClass.isAssignableFrom(c)) { log.debug("Registering class for JSON serialization: {} as subtype of {}", c.getName(), baseClass.getName()); break; } } } } } mapper.registerSubtypes(toRegister.toArray(new NamedType[toRegister.size()])); }
From source file:com.clarkparsia.empire.annotation.RdfGenerator.java
@SuppressWarnings("unchecked") private static <T> Class<T> determineClass(Class<T> theOrigClass, T theObj, DataSource theSource, boolean instanceClass) throws InvalidRdfException, DataSourceException { Class aResult = theOrigClass; final SupportsRdfId aTmpSupportsRdfId = asSupportsRdfId(theObj); // ExtGraph aGraph = new ExtGraph(DataSourceUtil.describe(theSource, theObj)); // ======================================== start speedup PATCH ================================================== // get class from uri without quering db // final Collection<Value> aTypes = DataSourceUtil.getValues(theSource, EmpireUtil.asResource(EmpireUtil.asSupportsRdfId(theObj)), RDF.TYPE); String rdfId = EmpireUtil.asSupportsRdfId(theObj).getRdfId().toString(); final Collection<Value> aTypes = Collections .singletonList(new URIImpl(StringUtils.substringBeforeLast(rdfId, ":"))); // ======================================== end speedup PATCH ======================================== // right now, our best match is the original class (we will refine later) // final Resource aTmpRes = EmpireUtil.asResource(aTmpSupportsRdfId); // iterate for all rdf:type triples in the data // There may be multiple rdf:type triples, which can then translate onto multiple candidate Java classes // some of the Java classes may belong to the same class hierarchy, whereas others can have no common // super class (other than java.lang.Object) for (Value aValue : aTypes) { if (!(aValue instanceof URI)) { // there is no URI in the object position of rdf:type // ignore that data continue; }/*from w w w . j a va 2s. c om*/ URI aType = (URI) aValue; for (Class aCandidateClass : TYPE_TO_CLASS.get(aType)) { if (aCandidateClass.equals(aResult)) { // it is mapped to the same Java class, that we have; ignore continue; } // at this point we found an rdf:type triple that resolves to a different Java class than we have // we are only going to accept this candidate class if it is a subclass of the current Java class // (doing otherwise, may cause class cast exceptions) if (aResult.isAssignableFrom(aCandidateClass)) { aResult = aCandidateClass; } } } try { if (instanceClass) { if (aResult.isInterface() || Modifier.isAbstract(aResult.getModifiers()) || !EmpireGenerated.class.isAssignableFrom(aResult)) { aResult = com.clarkparsia.empire.codegen.InstanceGenerator.generateInstanceClass(aResult); } } } catch (Exception e) { throw new InvalidRdfException("Cannot generate a class for a bean", e); } return aResult; }
From source file:com.openddal.test.BaseTestCase.java
/** * Verify the next method call on the object will throw an exception. * * @param <T> the class of the object * @param verifier the result verifier to call * @param obj the object to wrap/* ww w . j a v a 2s . co m*/ * @return a proxy for the object */ @SuppressWarnings("unchecked") protected <T> T assertThrows(final ResultVerifier verifier, final T obj) { Class<?> c = obj.getClass(); InvocationHandler ih = new InvocationHandler() { private Exception called = new Exception("No method called"); @Override protected void finalize() { if (called != null) { called.printStackTrace(System.err); } } @Override public Object invoke(Object proxy, Method method, Object[] args) throws Exception { try { called = null; Object ret = method.invoke(obj, args); verifier.verify(ret, null, method, args); return ret; } catch (InvocationTargetException e) { verifier.verify(null, e.getTargetException(), method, args); Class<?> retClass = method.getReturnType(); if (!retClass.isPrimitive()) { return null; } if (retClass == boolean.class) { return false; } else if (retClass == byte.class) { return (byte) 0; } else if (retClass == char.class) { return (char) 0; } else if (retClass == short.class) { return (short) 0; } else if (retClass == int.class) { return 0; } else if (retClass == long.class) { return 0L; } else if (retClass == float.class) { return 0F; } else if (retClass == double.class) { return 0D; } return null; } } }; if (!ProxyCodeGenerator.isGenerated(c)) { Class<?>[] interfaces = c.getInterfaces(); if (Modifier.isFinal(c.getModifiers()) || (interfaces.length > 0 && getClass() != c)) { // interface class proxies if (interfaces.length == 0) { throw new RuntimeException("Can not create a proxy for the class " + c.getSimpleName() + " because it doesn't implement any interfaces and is final"); } return (T) Proxy.newProxyInstance(c.getClassLoader(), interfaces, ih); } } try { Class<?> pc = ProxyCodeGenerator.getClassProxy(c); Constructor<?> cons = pc.getConstructor(InvocationHandler.class); return (T) cons.newInstance(ih); } catch (Exception e) { throw new RuntimeException(e); } }
From source file:ca.sqlpower.object.annotation.SPAnnotationProcessor.java
/** * Generates and returns source code for an * {@link SPPersisterHelper#findProperty(SPObject, String, SessionPersisterSuperConverter)} * method based on getter methods annotated with {@link Accessor} used in a * given {@link SPObject} class. The purpose of this findProperty method is * to allow a session {@link SPPersister} to get the value of a given * property in an {@link SPObject} and compare it with the expected value. * This helper method will be called by the session * {@link SPPersister#persistProperty(String, String, ca.sqlpower.dao.SPPersister.DataType, Object, Object)} * method.//from ww w . java 2 s . c om * * @param visitedClass * The {@link SPObject} class that is being visited by the * annotation processor. * @param getters * The {@link Map} of accessor method names to their property * types, where each property can be persisted by an * {@link SPPersister} into an {@link SPSession}. * @param accessorAdditionalInfo * The {@link Multimap} of getter methods mapped to additional * properties a session {@link SPPersister} requires to convert * the getter's returned value from a complex to basic * persistable type. * @param tabs * The number of tab characters to use to indent this generated * method block. * @return The source code for the generated findProperty method. * @see SPPersisterHelper#findProperty(SPObject, String, * SessionPersisterSuperConverter) * @see SPPersister#persistProperty(String, String, * ca.sqlpower.dao.SPPersister.DataType, Object, Object) */ private String generateFindPropertyMethod(Class<? extends SPObject> visitedClass, Map<String, Class<?>> getters, Multimap<String, String> accessorAdditionalInfo, int tabs) { StringBuilder sb = new StringBuilder(); final String genericObjectField = "o"; final String objectField = "castedObject"; final String propertyNameField = "propertyName"; final String converterField = "converter"; boolean firstIf = true; // findProperty method header. // public Object findProperty( // SPObject o, // String propertyName, // SessionPersisterSuperConverter converter) // throws SPPersistenceException { println(sb, tabs, String.format("public %s %s(%s %s, %s %s, %s %s) throws %s {", Object.class.getSimpleName(), FIND_PROPERTY_METHOD_NAME, SPObject.class.getSimpleName(), genericObjectField, String.class.getSimpleName(), propertyNameField, SessionPersisterSuperConverter.class.getSimpleName(), converterField, SPPersistenceException.class.getSimpleName())); tabs++; if (!getters.isEmpty()) { // If the SPObject class this persister helper handles is abstract, // use the type generic defined in the class header. // Otherwise, use the SPObject class directly. if (Modifier.isAbstract(visitedClass.getModifiers())) { // T castedObject = (T) o; println(sb, tabs, String.format("%s %s = (%s) %s;", TYPE_GENERIC_PARAMETER, objectField, TYPE_GENERIC_PARAMETER, genericObjectField)); } else { // <visitedClass> castedObject = (<visitedClass>) o; println(sb, tabs, String.format("%s %s = (%s) %s;", visitedClass.getSimpleName(), objectField, visitedClass.getSimpleName(), genericObjectField)); } // Search for the matching property name and return the value. for (Entry<String, Class<?>> e : getters.entrySet()) { String methodName = e.getKey(); print(sb, tabs, ""); if (!firstIf) { niprint(sb, "} else "); } // if (propertyName.equals("<method to property name>") { niprintln(sb, String.format("if (%s.equals(\"%s\")) {", propertyNameField, SPAnnotationProcessorUtils.convertMethodToProperty(methodName))); tabs++; // return converter.convertToBasicType(castedObject.<getter>()); print(sb, tabs, String.format("return %s.%s(%s.%s()", converterField, CONVERT_TO_BASIC_TYPE_METHOD_NAME, objectField, methodName)); for (String additionalProperty : accessorAdditionalInfo.get(methodName)) { niprint(sb, String.format(", %s.%s()", objectField, SPAnnotationProcessorUtils .convertPropertyToAccessor(additionalProperty, visitedClass))); } niprintln(sb, ");"); tabs--; firstIf = false; } if (!firstIf) { println(sb, tabs, "} else {"); tabs++; } } if (SPObject.class.isAssignableFrom(visitedClass.getSuperclass())) { Class<?> superclass = visitedClass.getSuperclass(); // return super.findProperty(o, propertyName, converter); println(sb, tabs, String.format("return super.%s(%s, %s, %s);", FIND_PROPERTY_METHOD_NAME, genericObjectField, propertyNameField, converterField)); } else { // Throw an SPPersistenceException if the property is not persistable or unrecognized. // throw new SPPersistenceException( // castedObject.getUUID(), // createSPPersistenceExceptionMessage( // castedObject, // propertyName)); println(sb, tabs, String.format("throw new %s(%s.%s(), %s(%s, %s));", SPPersistenceException.class.getSimpleName(), objectField, GET_UUID_METHOD_NAME, CREATE_EXCEPTION_MESSAGE_METHOD_NAME, objectField, propertyNameField)); } if (!firstIf) { tabs--; println(sb, tabs, "}"); } tabs--; println(sb, tabs, "}"); return sb.toString(); }
From source file:jp.co.acroquest.jsonic.JSON.java
protected <T> T create(Context context, Class<? extends T> c) throws Exception { Object instance = null;/* w ww .j av a 2s . c o m*/ JSONHint hint = context.getHint(); if (hint != null && hint.type() != Object.class) c = hint.type().asSubclass(c); if (c.isInterface()) { if (SortedMap.class.equals(c)) { instance = new TreeMap<Object, Object>(); } else if (Map.class.equals(c)) { instance = new LinkedHashMap<Object, Object>(); } else if (SortedSet.class.equals(c)) { instance = new TreeSet<Object>(); } else if (Set.class.equals(c)) { instance = new LinkedHashSet<Object>(); } else if (List.class.equals(c)) { instance = new ArrayList<Object>(); } else if (Collection.class.equals(c)) { instance = new ArrayList<Object>(); } else if (Appendable.class.equals(c)) { instance = new StringBuilder(); } } else if (Modifier.isAbstract(c.getModifiers())) { if (Calendar.class.equals(c)) { instance = Calendar.getInstance(); } } else if ((c.isMemberClass() || c.isAnonymousClass()) && !Modifier.isStatic(c.getModifiers())) { Class<?> eClass = c.getEnclosingClass(); Constructor<?> con = c.getDeclaredConstructor(eClass); con.setAccessible(true); if (context.contextObject != null && eClass.isAssignableFrom(context.contextObject.getClass())) { instance = con.newInstance(context.contextObject); } else { instance = con.newInstance((Object) null); } } else { if (Date.class.isAssignableFrom(c)) { try { Constructor<?> con = c.getDeclaredConstructor(long.class); con.setAccessible(true); instance = con.newInstance(0l); } catch (NoSuchMethodException e) { // no handle } } if (instance == null) { Constructor<?> con = c.getDeclaredConstructor(); con.setAccessible(true); instance = con.newInstance(); } } return c.cast(instance); }
From source file:eu.crisis_economics.abm.dashboard.Page_Parameters.java
ClassElement[] fetchPossibleTypes(final SubmodelInfo parameterInfo) throws ComboBoxIsTooFullException { List<Class<?>> possibleTypes = possibleTypesCache.get(parameterInfo.getName()); if (possibleTypes == null) possibleTypes = parameterInfo.getPossibleTypes(); if (possibleTypes == null || possibleTypes.isEmpty()) { possibleTypes = new ArrayList<Class<?>>(); possibleTypes.add(parameterInfo.getJavaType()); possibleTypes.addAll(getSubtypes(parameterInfo.getJavaType())); // delete all interfaces and abstract classes for (final Iterator<Class<?>> iter = possibleTypes.iterator(); iter.hasNext();) { final Class<?> clazz = iter.next(); if (Modifier.isAbstract(clazz.getModifiers()) || Modifier.isInterface(clazz.getModifiers())) iter.remove();//from w w w . ja v a 2 s.c o m } } possibleTypesCache.put(parameterInfo.getName(), possibleTypes); Collections.sort(possibleTypes, new Comparator<Class<?>>() { public int compare(final Class<?> class1, final Class<?> class2) { return class1.getName().compareTo(class2.getName()); } }); final ClassElement[] result = new ClassElement[possibleTypes.size() + 1]; result[0] = new ClassElement(null, null); for (int i = 0; i < possibleTypes.size(); ++i) { if (possibleTypes.get(i).equals(parameterInfo.getActualType())) { result[i + 1] = new ClassElement(possibleTypes.get(i), parameterInfo.getInstance()); } else { result[i + 1] = new ClassElement(possibleTypes.get(i), null); } } return result; }
From source file:ca.sqlpower.object.annotation.SPAnnotationProcessor.java
/** * Generates and returns source code for a persistObject method based on the * constructor annotated with {@link Constructor} with its constructor * parameters annotated with {@link ConstructorParameter}, as well as the * persistable properties with their getters/setters annotated with * {@link Accessor} and {@link Mutator}. This generated method should * persist the entire state of an {@link SPObject} to an {@link SPPersister} * and should be called from a workspace persister {@link SPListener}. This * means that the union of the constructor parameter properties and * persistable properties must be persisted. * /* w w w . j a v a2s .c o m*/ * @param visitedClass * The {@link SPObject} class that is being visited by the * annotation processor. * @param constructorParameters * The {@link Map} of property names to constructor parameters, * where values passed into the constructor will set those * respective properties. The order of this map must absolutely * be guaranteed to follow the order of the constructor * parameters. These properties may or may not be persistable, so * it is entirely possible that not all of the properties in this * map exists in the given {@link Set} of persistable properties. * @param accessors * The {@link Map} of accessor method names to their property * types which should be persisted into an {@link SPPersister} by * a workspace persister {@link SPListener}. * @param propertiesToPersistOnlyIfNonNull * The {@link Set} of persistable properties that can only be * persisted if its value is not null. * @param tabs * The number of tab characters to use to indent this generated * method block. * @return The source code for the generated persistObject method. */ private String generatePersistObjectMethod(Class<? extends SPObject> visitedClass, List<ConstructorParameterObject> constructorParameters, Map<String, Class<?>> accessors, Set<String> propertiesToPersistOnlyIfNonNull, int tabs) { StringBuilder sb = new StringBuilder(); final String genericObjectField = "o"; final String objectField = "castedObject"; final String indexField = "index"; final String persisterField = "persister"; final String converterField = "converter"; final String uuidField = "uuid"; final String parentUUIDField = "parentUUID"; final String exceptionField = "e"; //Properties already processed by the constructor, to be skipped //by the helper persisters that are parent classes to this object class. final String preProcessedProps = "preProcessedProperties"; // persistObject method header. // public void persistObject(SPObject o, int index, SPPersister persister, SessionPersisterSuperConverter converter) throws SPPersistenceException { println(sb, tabs, String.format("public void %s(%s %s, int %s, %s %s, %s %s) throws %s {", PERSIST_OBJECT_METHOD_NAME, SPObject.class.getSimpleName(), genericObjectField, indexField, SPPersister.class.getSimpleName(), persisterField, SessionPersisterSuperConverter.class.getSimpleName(), converterField, SPPersistenceException.class.getSimpleName())); tabs++; // If the SPObject class this persister helper handles is abstract, // use the type generic defined in the class header. // Otherwise, use the SPObject class directly. if (Modifier.isAbstract(visitedClass.getModifiers())) { // T castedObject = (T) o; println(sb, tabs, String.format("%s %s = (%s) %s;", TYPE_GENERIC_PARAMETER, objectField, TYPE_GENERIC_PARAMETER, genericObjectField)); } else { // <visitedClass> castedObject = (<visitedClass>) o; println(sb, tabs, String.format("%s %s = (%s) %s;", visitedClass.getSimpleName(), objectField, visitedClass.getSimpleName(), genericObjectField)); } // final String uuid = castedObject.getUUID(); println(sb, tabs, String.format("final %s %s = %s.%s();", String.class.getSimpleName(), uuidField, objectField, GET_UUID_METHOD_NAME)); // String parentUUID = null; println(sb, tabs, String.format("%s %s = null;", String.class.getSimpleName(), parentUUIDField)); // if (castedObject.getParent() != null) { println(sb, tabs, String.format("if (%s.%s() != null) {", objectField, GET_PARENT_METHOD_NAME)); tabs++; // parentUUID = castedObject.getParent().getUUID(); println(sb, tabs, String.format("%s = %s.%s().%s();", parentUUIDField, objectField, GET_PARENT_METHOD_NAME, GET_UUID_METHOD_NAME)); tabs--; println(sb, tabs, "}\n"); // Persist the object. // persister.persistObject(parentUUID, "<visitedClass name>", uuid, index);" println(sb, tabs, String.format("%s.%s(%s, \"%s\", %s, %s);", persisterField, PERSIST_OBJECT_METHOD_NAME, parentUUIDField, visitedClass.getName(), uuidField, indexField)); //TODO pass in the actual exception types on any accessors //then replace this blanket try/catch with specifics for any accessor //that throws an exception. // List<String> preProcessedProperties = new ArrayList<String>(); println(sb, tabs, String.format("%s<%s> %s = new %s<%s>();", List.class.getSimpleName(), String.class.getSimpleName(), preProcessedProps, ArrayList.class.getSimpleName(), String.class.getSimpleName())); importedClassNames.add(ArrayList.class.getName()); println(sb, tabs, "try {"); tabs++; if (constructorParameters.isEmpty()) { println(sb, tabs, "// No constructor arguments"); } else { println(sb, tabs, "// Constructor arguments"); final String dataTypeField = "dataType"; // DataType dataType; println(sb, tabs, String.format("%s %s;", DataType.class.getSimpleName(), dataTypeField)); // Persist all of its constructor argument properties. for (ConstructorParameterObject cpo : constructorParameters) { //XXX Should this only be properties? if (ParameterType.PROPERTY.equals(cpo.getProperty()) || ParameterType.CHILD.equals(cpo.getProperty())) { String getPersistedProperty = objectField + "." + SPAnnotationProcessorUtils.convertPropertyToAccessor(cpo.getName(), visitedClass) + "()"; if (cpo.getType() == Object.class) { // if (castedObject.<getter>() == null) { println(sb, tabs, String.format("if (%s == null) {", getPersistedProperty)); tabs++; // dataType = PersisterUtils.getDataType(null); println(sb, tabs, String.format("%s = %s.getDataType(null);", dataTypeField, PersisterUtils.class.getSimpleName())); tabs--; println(sb, tabs, "} else {"); tabs++; // dataType = PersisterUtils.getDataType(castedObject.<getter>().getClass()); println(sb, tabs, String.format("%s = %s.getDataType(%s.getClass());", dataTypeField, PersisterUtils.class.getSimpleName(), getPersistedProperty)); tabs--; println(sb, tabs, "}"); importedClassNames.add(PersisterUtils.class.getName()); } else { // dataType = DataType.<type>; println(sb, tabs, String.format("%s = %s.%s;", dataTypeField, DataType.class.getSimpleName(), PersisterUtils.getDataType(cpo.getType()).name())); } // persister.persistProperty(uuid, "<property>", dataType, converter, convertToBasicType(castedObject.<getter>())); println(sb, tabs, String.format("%s.%s(%s, \"%s\", %s, %s.%s(%s.%s()));", persisterField, PERSIST_PROPERTY_METHOD_NAME, uuidField, cpo.getName(), //XXX we should convert this name as the constructor parameter name may be different than the property name defined by the accessor. dataTypeField, converterField, CONVERT_TO_BASIC_TYPE_METHOD_NAME, objectField, SPAnnotationProcessorUtils.convertPropertyToAccessor(cpo.getName(), visitedClass))); // preProcessedProperties.add("<propertyName>"); println(sb, tabs, String.format("%s.add(\"%s\");", preProcessedProps, cpo.getName())); importedClassNames.add(DataType.class.getName()); } } } niprintln(sb, ""); // persistObjectProperties(o, persister, converter, preProcessedProperties); println(sb, tabs, String.format("%s(%s, %s, %s, %s);", PERSIST_OBJECT_PROPERTIES_METHOD_NAME, genericObjectField, persisterField, converterField, preProcessedProps)); tabs--; // } catch (Exception e) { println(sb, tabs, String.format("} catch (%s %s) {", Exception.class.getSimpleName(), exceptionField)); tabs++; // throw new SPPersistenceException(uuid, e); println(sb, tabs, String.format("throw new %s(%s, %s);", SPPersistenceException.class.getSimpleName(), uuidField, exceptionField)); tabs--; println(sb, tabs, "}"); tabs--; println(sb, tabs, "}"); return sb.toString(); }
From source file:ca.sqlpower.object.annotation.SPAnnotationProcessor.java
/** * Generates and returns source code for a commitProperty method based on * setter methods annotated with {@link Mutator} used in a given * {@link SPObject} class. The purpose of this commitProperty method is to * allow a session {@link SPPersister} to commit a persisted property change * into an {@link SPSession}. This helper method will be called by the * session {@link SPPersister#commit()} method. * //ww w .ja va 2 s.c o m * @param visitedClass * The {@link SPObject} class that is being visited by the * annotation processor. * @param setters * The {@link Map} of property setter methods to their property * types that can be used by an {@link SPPersister} to persist * properties into an {@link SPSession}. * @param mutatorExtraParameters * The {@link Multimap} of setter methods mapped to each of its * extra parameters (second parameter and onwards). * @param mutatorThrownTypes * The {@link Multimap} of property setter methods to their * thrown exceptions. * @param tabs * The number of tab characters to use to indent this generated * method block. * @return The source code for the generated commitProperty method. * @see SPPersister#persistProperty(String, String, * ca.sqlpower.dao.SPPersister.DataType, Object) * @see SPPersister#commit() */ private String generateCommitPropertyMethod(Class<? extends SPObject> visitedClass, Map<String, Class<?>> setters, Multimap<String, MutatorParameterObject> mutatorExtraParameters, Multimap<String, Class<? extends Exception>> mutatorThrownTypes, int tabs) { StringBuilder sb = new StringBuilder(); final String genericObjectField = "o"; final String objectField = "castedObject"; final String propertyNameField = "propertyName"; final String newValueField = "newValue"; final String converterField = "converter"; final String exceptionField = "e"; final String dataTypeField = "dataType"; boolean firstIf = true; // commitProperty method header. // public void commitProperty( // SPObject o, // String propertyName, // Object newValue, // DataType dataType, // SessionPersisterSuperConverter converter) // throws SPPersistenceException { println(sb, tabs, String.format("public void %s(%s %s, %s %s, %s %s, %s %s, %s %s) throws %s {", COMMIT_PROPERTY_METHOD_NAME, SPObject.class.getSimpleName(), genericObjectField, String.class.getSimpleName(), propertyNameField, Object.class.getSimpleName(), newValueField, DataType.class.getSimpleName(), dataTypeField, SessionPersisterSuperConverter.class.getSimpleName(), converterField, SPPersistenceException.class.getSimpleName())); tabs++; if (!setters.isEmpty()) { // If the SPObject class this persister helper handles is abstract, // use the type generic defined in the class header. // Otherwise, use the SPObject class directly. if (Modifier.isAbstract(visitedClass.getModifiers())) { // T castedObject = (T) o; println(sb, tabs, String.format("%s %s = (%s) %s;", TYPE_GENERIC_PARAMETER, objectField, TYPE_GENERIC_PARAMETER, genericObjectField)); } else { // <visitedClass> castedObject = (<visitedClass>) o; println(sb, tabs, String.format("%s %s = (%s) %s;", visitedClass.getSimpleName(), objectField, visitedClass.getSimpleName(), genericObjectField)); } // Search for the matching property name and set the value. for (Entry<String, Class<?>> e : setters.entrySet()) { String methodName = e.getKey(); Class<?> type = e.getValue(); print(sb, tabs, ""); if (!firstIf) { niprint(sb, "} else "); } // if (propertyName.equals("<method to property name>") { niprintln(sb, String.format("if (%s.equals(\"%s\")) {", propertyNameField, SPAnnotationProcessorUtils.convertMethodToProperty(methodName))); tabs++; boolean throwsExceptions = mutatorThrownTypes.containsKey(e.getKey()); if (throwsExceptions) { println(sb, tabs, "try {"); tabs++; } // Assign each extra argument value of setter methods to variables // to pass into the call to the setter afterwards. for (MutatorParameterObject extraParam : mutatorExtraParameters.get(methodName)) { // <extraParam type> <extraParam name> = // <extraParam type>.valueOf("<extraParam name>"); println(sb, tabs, String.format("%s %s = %s.valueOf(\"%s\");", extraParam.getType().getSimpleName(), extraParam.getName(), extraParam.getType().getSimpleName(), extraParam.getValue())); } // Pass in the actual property value as the first argument to the setter. String conversionType; if (type == Object.class) { conversionType = dataTypeField + ".getRepresentation()"; } else { conversionType = type.getSimpleName() + ".class"; } // castedObject.<setter>( // (<type>) converter.convertToComplexType( // newValue, <dataType.getRepresentation | type.class>); print(sb, tabs, String.format("%s.%s((%s) %s.%s(%s, %s)", objectField, methodName, type.getSimpleName(), converterField, CONVERT_TO_COMPLEX_TYPE_METHOD_NAME, newValueField, conversionType)); // Pass in the variables holding the extra argument values. for (MutatorParameterObject extraParam : mutatorExtraParameters.get(methodName)) { // , <extraParam name> niprint(sb, ", " + extraParam.getName()); } niprintln(sb, ");"); tabs--; // Catch any exceptions that the setter throws. if (throwsExceptions) { for (Class<? extends Exception> thrownType : mutatorThrownTypes.get(methodName)) { // } catch (<Exception type> e) { println(sb, tabs, String.format("} catch (%s %s) {", thrownType.getSimpleName(), exceptionField)); tabs++; // throw new SPPersistenceException( // castedObject.getUUID(), // createSPPersistenceExceptionMessage( // castedObject, // propertyName), // e); println(sb, tabs, String.format("throw new %s(%s.%s(), %s(%s, %s), %s);", SPPersistenceException.class.getSimpleName(), objectField, GET_UUID_METHOD_NAME, CREATE_EXCEPTION_MESSAGE_METHOD_NAME, objectField, propertyNameField, exceptionField)); tabs--; } println(sb, tabs, "}"); tabs--; } firstIf = false; } if (!firstIf) { println(sb, tabs, "} else {"); tabs++; } } if (SPObject.class.isAssignableFrom(visitedClass.getSuperclass())) { // super.commitProperty(o, <property>, newValue, dataType, converter); println(sb, tabs, String.format("super.%s(%s, %s, %s, %s, %s);", COMMIT_PROPERTY_METHOD_NAME, genericObjectField, propertyNameField, newValueField, dataTypeField, converterField)); } else { // Throw an SPPersistenceException if the property is not persistable or unrecognized. // throw new SPPersistenceException( // castedObject.getUUID(), // createSPPersistenceExceptionMessage( // castedObject, // propertyName)); println(sb, tabs, String.format("throw new %s(%s.%s(), %s(%s, %s));", SPPersistenceException.class.getSimpleName(), objectField, GET_UUID_METHOD_NAME, CREATE_EXCEPTION_MESSAGE_METHOD_NAME, objectField, propertyNameField)); } if (!firstIf) { tabs--; println(sb, tabs, "}"); } tabs--; println(sb, tabs, "}"); return sb.toString(); }