List of usage examples for java.lang Class getModifiers
@HotSpotIntrinsicCandidate public native int getModifiers();
From source file:org.apache.jackrabbit.ocm.manager.objectconverter.impl.ObjectConverterImpl.java
/** * @see org.apache.jackrabbit.ocm.manager.objectconverter.ObjectConverter#getObject(javax.jcr.Session, * java.lang.Class, java.lang.String) *//*from w ww .j av a2 s . co m*/ public Object getObject(Session session, Class clazz, String path) { try { if (!session.itemExists(path)) { return null; } if (requestObjectCache.isCached(path)) { return requestObjectCache.getObject(path); } ClassDescriptor classDescriptor = getClassDescriptor(clazz); checkNodeType(session, classDescriptor); Node node = (Node) session.getItem(path); if (!classDescriptor.isInterface()) { node = getActualNode(session, node); checkCompatiblePrimaryNodeTypes(session, node, classDescriptor, true); } ClassDescriptor alternativeDescriptor = null; if (classDescriptor.usesNodeTypePerHierarchyStrategy()) { if (node.hasProperty(ManagerConstant.DISCRIMINATOR_CLASS_NAME_PROPERTY)) { String className = node.getProperty(ManagerConstant.DISCRIMINATOR_CLASS_NAME_PROPERTY) .getValue().getString(); alternativeDescriptor = getClassDescriptor(ReflectionUtils.forName(className)); } } else { if (classDescriptor.usesNodeTypePerConcreteClassStrategy()) { String nodeType = node.getPrimaryNodeType().getName(); if (!nodeType.equals(classDescriptor.getJcrType())) { alternativeDescriptor = classDescriptor.getDescendantClassDescriptor(nodeType); // in case we an alternative could not be found by walking // the class descriptor hierarchy, check whether we would // have a descriptor for the node type directly (which // may the case if the class descriptor hierarchy is // incomplete due to missing configuration. See JCR-1145 // for details. if (alternativeDescriptor == null) { alternativeDescriptor = mapper.getClassDescriptorByNodeType(nodeType); } } } } // if we have an alternative class descriptor, check whether its // extends (or is the same) as the requested class. if (alternativeDescriptor != null) { Class alternativeClazz = ReflectionUtils.forName(alternativeDescriptor.getClassName()); if (clazz.isAssignableFrom(alternativeClazz)) { clazz = alternativeClazz; classDescriptor = alternativeDescriptor; } } // ensure class is concrete (neither interface nor abstract) if (clazz.isInterface() || Modifier.isAbstract(clazz.getModifiers())) { throw new JcrMappingException("Cannot instantiate non-concrete class " + clazz.getName() + " for node " + path + " of type " + node.getPrimaryNodeType().getName()); } Object object = ReflectionUtils.newInstance(classDescriptor.getClassName()); if (!requestObjectCache.isCached(path)) { requestObjectCache.cache(path, object); } simpleFieldsHelp.retrieveSimpleFields(session, classDescriptor, node, object); retrieveBeanFields(session, classDescriptor, node, path, object, false); retrieveCollectionFields(session, classDescriptor, node, object, false); return object; } catch (PathNotFoundException pnfe) { // HINT should never get here throw new ObjectContentManagerException("Impossible to get the object at " + path, pnfe); } catch (RepositoryException re) { throw new org.apache.jackrabbit.ocm.exception.RepositoryException( "Impossible to get the object at " + path, re); } }
From source file:mondrian.olap.Util.java
/** * Creates a new udf instance from the given udf class. * * @param udfClass the class to create new instance for * @param functionName Function name, or null * @return an instance of UserDefinedFunction *///from ww w . j av a2 s. com public static UserDefinedFunction createUdf(Class<? extends UserDefinedFunction> udfClass, String functionName) { // Instantiate class with default constructor. UserDefinedFunction udf; String className = udfClass.getName(); String functionNameOrEmpty = functionName == null ? "" : functionName; // Find a constructor. Constructor<?> constructor; Object[] args = {}; // 0. Check that class is public and top-level or static. // Before JDK 1.5, inner classes are impossible; retroweaver cannot // handle the getEnclosingClass method, so skip the check. if (!Modifier.isPublic(udfClass.getModifiers()) || (!PreJdk15 && udfClass.getEnclosingClass() != null && !Modifier.isStatic(udfClass.getModifiers()))) { throw MondrianResource.instance().UdfClassMustBePublicAndStatic.ex(functionName, className); } // 1. Look for a constructor "public Udf(String name)". try { constructor = udfClass.getConstructor(String.class); if (Modifier.isPublic(constructor.getModifiers())) { args = new Object[] { functionName }; } else { constructor = null; } } catch (NoSuchMethodException e) { constructor = null; } // 2. Otherwise, look for a constructor "public Udf()". if (constructor == null) { try { constructor = udfClass.getConstructor(); if (Modifier.isPublic(constructor.getModifiers())) { args = new Object[] {}; } else { constructor = null; } } catch (NoSuchMethodException e) { constructor = null; } } // 3. Else, no constructor suitable. if (constructor == null) { throw MondrianResource.instance().UdfClassWrongIface.ex(functionNameOrEmpty, className, UserDefinedFunction.class.getName()); } // Instantiate class. try { udf = (UserDefinedFunction) constructor.newInstance(args); } catch (InstantiationException e) { throw MondrianResource.instance().UdfClassWrongIface.ex(functionNameOrEmpty, className, UserDefinedFunction.class.getName()); } catch (IllegalAccessException e) { throw MondrianResource.instance().UdfClassWrongIface.ex(functionName, className, UserDefinedFunction.class.getName()); } catch (ClassCastException e) { throw MondrianResource.instance().UdfClassWrongIface.ex(functionNameOrEmpty, className, UserDefinedFunction.class.getName()); } catch (InvocationTargetException e) { throw MondrianResource.instance().UdfClassWrongIface.ex(functionName, className, UserDefinedFunction.class.getName()); } return udf; }
From source file:ca.sqlpower.object.annotation.SPAnnotationProcessor.java
/** * Generates the Java source file that is a helper of {@link SPPersisterHelper}. * These helpers are not true {@link SPPersisterHelper}s because they only do * part of a helper's job. They also do not implement the interface because nothing * outside of the {@link SPPersisterHelper}s should be using them directly. * /*from w ww. j av a 2 s . c o m*/ * @param visitedClass * The {@link SPObject} class that is being visited by the * annotation processor. * @param constructorImports * The {@link Set} of imports that the generated persister helper * requires for calling the {@link Constructor} annotated * constructor. * @param constructorParameters * The {@link List} of {@link ConstructorParameterObject}s that * contain information about what the parameter should be used * for. * @param propertiesToAccess * The {@link Map} of getter method names of persistable * properties to its property type. * @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 mutatorImports * The {@link Multimap} of setter methods to imports that the * generated persister helper requires for calling the * {@link Mutator} annotated setters. * @param propertiesToMutate * The {@link Map} of setter method names of persistable * properties to its property type. * @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 {@link Exception}s thrown by each * persistable property setter. * @param propertiesToPersistOnlyIfNonNull * The {@link Set} of persistable properties that can only be * persisted if its value is not null. */ private void generateAbstractPersisterHelperFile(Class<? extends SPObject> visitedClass, Set<String> constructorImports, Map<String, Class<?>> propertiesToAccess, Multimap<String, String> accessorAdditionalInfo, Multimap<String, String> mutatorImports, Map<String, Class<?>> propertiesToMutate, Multimap<String, MutatorParameterObject> mutatorExtraParameters, Multimap<String, Class<? extends Exception>> mutatorThrownTypes, Set<String> propertiesToPersistOnlyIfNonNull) { try { final String helperPackage = visitedClass.getPackage().getName() + "." + PersisterHelperFinder.GENERATED_PACKAGE_NAME; final String simpleClassName = visitedClass.getSimpleName() + "PersisterHelper"; final Class<?> superclass = visitedClass.getSuperclass(); int tabs = 0; Filer f = environment.getFiler(); PrintWriter pw = new PrintWriter( f.createSourceFile(helperPackage + "." + simpleClassName).openOutputStream()); tabs++; final String commitPropertyMethod = generateCommitPropertyMethod(visitedClass, propertiesToMutate, mutatorExtraParameters, mutatorThrownTypes, tabs); final String findPropertyMethod = generateFindPropertyMethod(visitedClass, propertiesToAccess, accessorAdditionalInfo, tabs); final String persistObjectMethodHelper = generatePersistObjectMethodHelper(visitedClass, propertiesToAccess, propertiesToMutate, propertiesToPersistOnlyIfNonNull, tabs); final String getPersistedPropertiesMethod = generateGetPersistedPropertyListMethod(visitedClass, propertiesToMutate, tabs); tabs--; if (superclass == Object.class) { importedClassNames.add(AbstractSPPersisterHelper.class.getName()); } else { importedClassNames.add(PersisterHelperFinder.getPersisterHelperClassName(superclass.getName())); } final String generateImports = generateImports(visitedClass, constructorImports, mutatorImports); pw.print(generateWarning()); pw.print("\n"); pw.print(generateLicense()); pw.print("\n"); pw.print("package " + helperPackage + ";\n"); pw.print("\n"); pw.print(generateImports); pw.print("\n"); if (superclass == Object.class) { pw.print(String.format("public abstract class %s<%s extends %s> extends %s<%s> {\n", simpleClassName, TYPE_GENERIC_PARAMETER, visitedClass.getSimpleName(), AbstractSPPersisterHelper.class.getSimpleName(), TYPE_GENERIC_PARAMETER)); } else if (Modifier.isAbstract(superclass.getModifiers())) { pw.print(String.format("public abstract class %s<%s extends %s> extends %s<%s> {\n", simpleClassName, TYPE_GENERIC_PARAMETER, visitedClass.getSimpleName(), superclass.getSimpleName() + "PersisterHelper", TYPE_GENERIC_PARAMETER)); } else { pw.print(String.format("public abstract class %s<%s extends %s> extends %s {\n", simpleClassName, TYPE_GENERIC_PARAMETER, visitedClass.getSimpleName() + "PersisterHelper", superclass.getName())); } pw.print("\n"); pw.print(commitPropertyMethod); pw.print("\n"); pw.print(findPropertyMethod); pw.print("\n"); pw.print(persistObjectMethodHelper); pw.print("\n"); pw.print(getPersistedPropertiesMethod); pw.print("\n"); pw.print("}\n"); pw.close(); } catch (IOException e) { throw new RuntimeException(e); } }
From source file:ca.sqlpower.object.annotation.SPAnnotationProcessor.java
/** * Generates the Java source file for an {@link SPPersisterHelper} class * that is to be used by a session {@link SPPersister} or workspace * persister listener. This generated persister helper class should deal * with creating new objects and applying persisted properties to a given * {@link SPObject}, or persisting objects and properties from an * {@link SPObject} to an {@link SPPersister}. * //from w w w. j ava2 s.co m * @param visitedClass * The {@link SPObject} class that is being visited by the * annotation processor. * @param constructorImports * The {@link Set} of imports that the generated persister helper * requires for calling the {@link Constructor} annotated * constructor. * @param constructorParameters * The {@link List} of {@link ConstructorParameterObject}s that * contain information about what the parameter should be used * for. * @param propertiesToAccess * The {@link Map} of getter method names of persistable * properties to its property type. * @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 mutatorImports * The {@link Multimap} of setter methods to imports that the * generated persister helper requires for calling the * {@link Mutator} annotated setters. * @param propertiesToMutate * The {@link Map} of setter method names of persistable * properties to its property type. * @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 {@link Exception}s thrown by each * persistable property setter. * @param propertiesToPersistOnlyIfNonNull * The {@link Set} of persistable properties that can only be * persisted if its value is not null. */ private void generatePersisterHelperFile(Class<? extends SPObject> visitedClass, Set<String> constructorImports, List<ConstructorParameterObject> constructorParameters, Map<String, Class<?>> propertiesToAccess, Multimap<String, String> accessorAdditionalInfo, Multimap<String, String> mutatorImports, Map<String, Class<?>> propertiesToMutate, Multimap<String, MutatorParameterObject> mutatorExtraParameters, Multimap<String, Class<? extends Exception>> mutatorThrownTypes, Set<String> propertiesToPersistOnlyIfNonNull) { try { final String helperPackage = visitedClass.getPackage().getName() + "." + PersisterHelperFinder.GENERATED_PACKAGE_NAME; final String simpleClassName = visitedClass.getSimpleName() + "PersisterHelper"; final Class<?> superclass = visitedClass.getSuperclass(); int tabs = 0; Filer f = environment.getFiler(); PrintWriter pw = new PrintWriter( f.createSourceFile(helperPackage + "." + simpleClassName).openOutputStream()); tabs++; final String commitObjectMethod = generateCommitObjectMethod(visitedClass, constructorParameters, tabs); final String commitPropertyMethod = generateCommitPropertyMethod(visitedClass, propertiesToMutate, mutatorExtraParameters, mutatorThrownTypes, tabs); final String findPropertyMethod = generateFindPropertyMethod(visitedClass, propertiesToAccess, accessorAdditionalInfo, tabs); final String persistObjectMethod = generatePersistObjectMethod(visitedClass, constructorParameters, propertiesToAccess, propertiesToPersistOnlyIfNonNull, tabs); final String PersistObjectMethodHelper = generatePersistObjectMethodHelper(visitedClass, propertiesToAccess, propertiesToMutate, propertiesToPersistOnlyIfNonNull, tabs); final String getPersistedPropertiesMethod = generateGetPersistedPropertyListMethod(visitedClass, propertiesToMutate, tabs); tabs--; if (superclass == Object.class) { importedClassNames.add(AbstractSPPersisterHelper.class.getName()); } else { importedClassNames.add(PersisterHelperFinder.getPersisterHelperClassName(superclass.getName())); } final String imports = generateImports(visitedClass, constructorImports, mutatorImports); pw.print(generateWarning()); pw.print("\n"); pw.print(generateLicense()); pw.print("\n"); pw.print("package " + helperPackage + ";\n"); pw.print("\n"); pw.print(imports); pw.print("\n"); if (superclass == Object.class) { pw.print(String.format("public class %s extends %s<%s> {\n", simpleClassName, AbstractSPPersisterHelper.class.getSimpleName(), visitedClass.getSimpleName())); } else if (Modifier.isAbstract(superclass.getModifiers())) { pw.print(String.format("public class %s extends %s<%s> {\n", simpleClassName, superclass.getSimpleName() + "PersisterHelper", visitedClass.getSimpleName())); } else { pw.print(String.format("public class %s extends %s {\n", simpleClassName, superclass.getSimpleName() + "PersisterHelper")); } pw.print("\n"); pw.print(commitObjectMethod); pw.print("\n"); pw.print(commitPropertyMethod); pw.print("\n"); pw.print(findPropertyMethod); pw.print("\n"); pw.print(persistObjectMethod); pw.print("\n"); pw.print(PersistObjectMethodHelper); pw.print("\n"); pw.print(getPersistedPropertiesMethod); pw.print("\n"); pw.print("}\n"); pw.close(); } catch (IOException e) { throw new RuntimeException(e); } }
From source file:org.apache.openjpa.kernel.StateManagerImpl.java
public void initialize(Class cls, PCState state) { // check to see if our current object id instance is the // correct id type for the specified class; this is for cases // when we have an application id hierarchy and we had set the // metadata to a superclass id -- the subclass' id may be a // different class, so we need to reset it if (_meta.getDescribedType() != cls) { ClassMetaData sub = _meta.getRepository().getMetaData(cls, _broker.getClassLoader(), true); if (_oid != null) { if (_meta.getIdentityType() == ClassMetaData.ID_DATASTORE) _oid = _broker.getStoreManager().copyDataStoreId(_oid, sub); else if (_meta.isOpenJPAIdentity()) _oid = ApplicationIds.copy(_oid, sub); else if (sub.getObjectIdType() != _meta.getObjectIdType()) { Object[] pkFields = ApplicationIds.toPKValues(_oid, _meta); _oid = ApplicationIds.fromPKValues(pkFields, sub); }//from www. j ava2 s. c o m } _meta = sub; } PersistenceCapable inst = PCRegistry.newInstance(cls, this, _oid, true); if (inst == null) { // the instance was null: check to see if the instance is // abstract (as can sometimes be the case when the // class discriminator strategy is not configured correctly) if (Modifier.isAbstract(cls.getModifiers())) throw new UserException(_loc.get("instantiate-abstract", cls.getName(), _oid)); throw new InternalException(); } initialize(inst, state); }
From source file:org.apache.openjpa.kernel.BrokerImpl.java
public Object newInstance(Class cls) { assertOpen();//from w ww . j av a 2s.c o m if (!cls.isInterface() && Modifier.isAbstract(cls.getModifiers())) throw new UnsupportedOperationException(_loc.get("new-abstract", cls).getMessage()); // 1.5 doesn't initialize classes without a true Class.forName if (!PCRegistry.isRegistered(cls)) { try { Class.forName(cls.getName(), true, AccessController.doPrivileged(J2DoPrivHelper.getClassLoaderAction(cls))); } catch (Throwable t) { } } if (_repo.getMetaData(cls, getClassLoader(), false) == null) throw new IllegalArgumentException(_loc.get("no-interface-metadata", cls.getName()).getMessage()); try { return PCRegistry.newInstance(cls, null, false); } catch (IllegalStateException ise) { IllegalArgumentException iae = new IllegalArgumentException(ise.getMessage()); iae.setStackTrace(ise.getStackTrace()); throw iae; } }
From source file:org.kchine.r.server.DirectJNI.java
public static void generateMaps(URL jarUrl, boolean rawClasses) { try {//w ww. j ava2 s.c om _mappingClassLoader = new URLClassLoader(new URL[] { jarUrl }, DirectJNI.class.getClassLoader()); Vector<String> list = new Vector<String>(); JarURLConnection jarConnection = (JarURLConnection) jarUrl.openConnection(); JarFile jarfile = jarConnection.getJarFile(); Enumeration<JarEntry> enu = jarfile.entries(); while (enu.hasMoreElements()) { String entry = enu.nextElement().toString(); if (entry.endsWith(".class")) list.add(entry.replace('/', '.').substring(0, entry.length() - ".class".length())); } log.info(list); for (int i = 0; i < list.size(); ++i) { String className = list.elementAt(i); if (className.startsWith("org.kchine.r.packages.") && !className.startsWith("org.kchine.r.packages.rservices")) { Class<?> c_ = _mappingClassLoader.loadClass(className); if (c_.getSuperclass() != null && c_.getSuperclass().equals(RObject.class) && !Modifier.isAbstract(c_.getModifiers())) { if (c_.equals(RLogical.class) || c_.equals(RInteger.class) || c_.equals(RNumeric.class) || c_.equals(RComplex.class) || c_.equals(RChar.class) || c_.equals(RMatrix.class) || c_.equals(RArray.class) || c_.equals(RList.class) || c_.equals(RDataFrame.class) || c_.equals(RFactor.class) || c_.equals(REnvironment.class) || c_.equals(RVector.class) || c_.equals(RUnknown.class)) { } else { String rclass = DirectJNI.getRClassForBean(jarfile, className); _s4BeansHash.put(className, c_); _s4BeansMapping.put(rclass, className); _s4BeansMappingRevert.put(className, rclass); } } else if ((rawClasses && c_.getSuperclass() != null && c_.getSuperclass().equals(Object.class)) || (!rawClasses && RPackage.class.isAssignableFrom(c_) && (c_.isInterface()))) { String shortClassName = className.substring(className.lastIndexOf('.') + 1); _packageNames.add(shortClassName); Vector<Class<?>> v = _rPackageInterfacesHash.get(className); if (v == null) { v = new Vector<Class<?>>(); _rPackageInterfacesHash.put(className, v); } v.add(c_); } else { String nameWithoutPackage = className.substring(className.lastIndexOf('.') + 1); if (nameWithoutPackage.indexOf("Factory") != -1 && c_.getMethod("setData", new Class[] { RObject.class }) != null) { // if // (DirectJNI._factoriesMapping.get(nameWithoutPackage // ) // != null) throw new Exception("Factories Names // Conflict : two " + nameWithoutPackage); _factoriesMapping.put(nameWithoutPackage, className); if (Modifier.isAbstract(c_.getModifiers())) _abstractFactories.add(className); } } } } // log.info("s4Beans:" +s4Beans); log.info("rPackageInterfaces:" + _packageNames); log.info("s4Beans MAP :" + _s4BeansMapping); log.info("s4Beans Revert MAP :" + _s4BeansMappingRevert); log.info("factories :" + _factoriesMapping); log.info("r package interface hash :" + _rPackageInterfacesHash); } catch (Exception ex) { ex.printStackTrace(); } }
From source file:ca.sqlpower.object.annotation.SPAnnotationProcessor.java
/** * Generates and returns source code for persisting the remaining state not * done by {@link #generatePersistObjectMethod(Class, List, Map, Set, int)}. * This is for classes to allow properties that are not defined in a * sub-class to be persisted./*from w w w. j av a 2 s . c o m*/ * <p> * In the future we may want to have the parent classes persist properties * first and children to persist properties later. We can pool the property * changes in {@link PersistedSPOProperty} objects and persist them at the * end of the method call. * * @param visitedClass * The {@link SPObject} class that is being visited by the * annotation processor. * @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 generatePersistObjectMethodHelper(Class<? extends SPObject> visitedClass, Map<String, Class<?>> accessors, Map<String, Class<?>> mutators, Set<String> propertiesToPersistOnlyIfNonNull, int tabs) { StringBuilder sb = new StringBuilder(); final String genericObjectField = "o"; final String objectField = "castedObject"; final String persisterField = "persister"; final String converterField = "converter"; final String uuidField = "uuid"; final String exceptionField = "e"; //These are the properties on the sub-class helper calling this abstract //helper that have already been persisted by the current persistObject //call. These properties do not have to be persisted again. final String preProcessedPropField = "preProcessedProps"; final String staticPreProcessedPropField = "staticPreProcessedProps"; // persistObject method header. // public void persistObjectProperties( // SPObject o, // SPPersister persister, // SessionPersisterSuperConverter converter, // List<String> staticPreProcessedProps) // throws SPPersistenceException { println(sb, tabs, String.format("public void %s(%s %s, %s %s, %s %s, %s<%s> %s) throws %s {", PERSIST_OBJECT_PROPERTIES_METHOD_NAME, SPObject.class.getSimpleName(), genericObjectField, SPPersister.class.getSimpleName(), persisterField, SessionPersisterSuperConverter.class.getSimpleName(), converterField, List.class.getSimpleName(), String.class.getSimpleName(), staticPreProcessedPropField, SPPersistenceException.class.getSimpleName())); tabs++; // final List<String> preProcessedProperties = new ArrayList<String>(staticPreProcessedProps); println(sb, tabs, String.format("final %s<%s> %s = new %s<%s>(%s);", List.class.getSimpleName(), String.class.getSimpleName(), preProcessedPropField, ArrayList.class.getSimpleName(), String.class.getSimpleName(), staticPreProcessedPropField)); if (!accessors.isEmpty()) { boolean lastEntryInIfBlock = false; boolean variablesInitialized = false; Set<String> getterPropertyNames = new HashSet<String>(); for (Entry<String, Class<?>> e : mutators.entrySet()) { getterPropertyNames.add(SPAnnotationProcessorUtils.convertMethodToProperty(e.getKey())); } // Persist all of its persistable properties. for (Entry<String, Class<?>> e : accessors.entrySet()) { String propertyName = SPAnnotationProcessorUtils.convertMethodToProperty(e.getKey()); if (!getterPropertyNames.contains(propertyName)) continue; if (!variablesInitialized) { // final String uuid = o.getUUID(); println(sb, tabs, String.format("final %s %s = %s.%s();\n", String.class.getSimpleName(), uuidField, genericObjectField, GET_UUID_METHOD_NAME)); // 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)); } // try { println(sb, tabs, "try {"); tabs++; variablesInitialized = true; } // Persist the property only if it has not been persisted yet // and (if required) persist if the value is not null. // // if (preProcessedProperties.contains("<property>")) { println(sb, tabs, String.format("if (!%s.contains(\"%s\")) {", preProcessedPropField, propertyName)); tabs++; boolean persistOnlyIfNonNull = propertiesToPersistOnlyIfNonNull.contains(propertyName); String propertyField = objectField + "." + e.getKey() + "()"; if (lastEntryInIfBlock) { niprintln(sb, ""); } if (persistOnlyIfNonNull) { // <getter type> <property> = castedObject.<getter>(); println(sb, tabs, String.format("%s %s = %s.%s();", e.getValue().getSimpleName(), propertyName, propertyField)); propertyField = propertyName; // if (castedObject.<getter>() != null) { println(sb, tabs, String.format("if (%s != null) {", propertyField)); tabs++; } final String dataTypeField = "dataType"; // DataType dataType; println(sb, tabs, String.format("%s %s;", DataType.class.getSimpleName(), dataTypeField)); String getPersistedProperty = objectField + "." + e.getKey() + "()"; if (e.getValue() == 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(e.getValue()).name())); } // persister.persistProperty(uuid, "<property>", dataType, converter.convertToBasicType(castedObject.<getter>())); println(sb, tabs, String.format("%s.%s(%s, \"%s\", %s, %s.%s(%s));", persisterField, PERSIST_PROPERTY_METHOD_NAME, uuidField, propertyName, dataTypeField, converterField, CONVERT_TO_BASIC_TYPE_METHOD_NAME, getPersistedProperty)); // preProcessedProperties.add("<property>"); println(sb, tabs, String.format("%s.add(\"%s\");", preProcessedPropField, propertyName)); importedClassNames.add(DataType.class.getName()); if (persistOnlyIfNonNull) { tabs--; println(sb, tabs, "}"); lastEntryInIfBlock = true; } else { lastEntryInIfBlock = false; } tabs--; println(sb, tabs, "}"); } if (variablesInitialized) { 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, "}"); } } if (SPObject.class.isAssignableFrom(visitedClass.getSuperclass())) { Class<?> superclass = visitedClass.getSuperclass(); // super.persistObjectProperties(o, persister, converter, preProcessedProperties); println(sb, tabs, String.format("super.%s(%s, %s, %s, %s);", PERSIST_OBJECT_PROPERTIES_METHOD_NAME, genericObjectField, persisterField, converterField, preProcessedPropField)); } tabs--; println(sb, tabs, "}"); return sb.toString(); }
From source file:org.apache.axis2.description.java2wsdl.DefaultSchemaGenerator.java
/** * Generate schema construct for given type * * @param javaType : Class to whcih need to generate Schema * @return : Generated QName/* w w w . java 2 s . com*/ */ protected QName generateSchema(Class<?> javaType) throws Exception { String name = getClassName(javaType); QName schemaTypeName = typeTable.getComplexSchemaType(name); if (schemaTypeName == null) { String simpleName = getSimpleClassName(javaType); String packageName = getQualifiedName(javaType.getPackage()); String targetNameSpace = resolveSchemaNamespace(packageName); XmlSchema xmlSchema = getXmlSchema(targetNameSpace); String targetNamespacePrefix = targetNamespacePrefixMap.get(targetNameSpace); if (targetNamespacePrefix == null) { targetNamespacePrefix = generatePrefix(); targetNamespacePrefixMap.put(targetNameSpace, targetNamespacePrefix); } XmlSchemaComplexType complexType = new XmlSchemaComplexType(xmlSchema); XmlSchemaSequence sequence = new XmlSchemaSequence(); XmlSchemaComplexContentExtension complexExtension = new XmlSchemaComplexContentExtension(); XmlSchemaElement eltOuter = new XmlSchemaElement(); schemaTypeName = new QName(targetNameSpace, simpleName, targetNamespacePrefix); eltOuter.setName(simpleName); eltOuter.setQName(schemaTypeName); Class<?> sup = javaType.getSuperclass(); if ((sup != null) && (!"java.lang.Object".equals(sup.getName())) && (!"java.lang.Exception".equals(sup.getName())) && !getQualifiedName(sup.getPackage()).startsWith("org.apache.axis2") && !getQualifiedName(sup.getPackage()).startsWith("java.util")) { String superClassName = sup.getName(); String superclassname = getSimpleClassName(sup); String tgtNamespace; String tgtNamespacepfx; QName qName = typeTable.getSimpleSchemaTypeName(superClassName); if (qName != null) { tgtNamespace = qName.getNamespaceURI(); tgtNamespacepfx = qName.getPrefix(); } else { tgtNamespace = resolveSchemaNamespace(getQualifiedName(sup.getPackage())); tgtNamespacepfx = targetNamespacePrefixMap.get(tgtNamespace); QName superClassQname = generateSchema(sup); if (superClassQname != null) { tgtNamespacepfx = superClassQname.getPrefix(); tgtNamespace = superClassQname.getNamespaceURI(); } } if (tgtNamespacepfx == null) { tgtNamespacepfx = generatePrefix(); targetNamespacePrefixMap.put(tgtNamespace, tgtNamespacepfx); } //if the parent class package name is differ from the child if (!((NamespaceMap) xmlSchema.getNamespaceContext()).values().contains(tgtNamespace)) { XmlSchemaImport importElement = new XmlSchemaImport(); importElement.setNamespace(tgtNamespace); xmlSchema.getItems().add(importElement); ((NamespaceMap) xmlSchema.getNamespaceContext()).put(generatePrefix(), tgtNamespace); } QName basetype = new QName(tgtNamespace, superclassname, tgtNamespacepfx); complexExtension.setBaseTypeName(basetype); complexExtension.setParticle(sequence); XmlSchemaComplexContent contentModel = new XmlSchemaComplexContent(); contentModel.setContent(complexExtension); complexType.setContentModel(contentModel); } else { complexType.setParticle(sequence); } complexType.setName(simpleName); if (Modifier.isAbstract(javaType.getModifiers())) { complexType.setAbstract(true); } // xmlSchema.getItems().add(eltOuter); xmlSchema.getElements().add(schemaTypeName, eltOuter); eltOuter.setSchemaTypeName(complexType.getQName()); xmlSchema.getItems().add(complexType); xmlSchema.getSchemaTypes().add(schemaTypeName, complexType); // adding this type to the table typeTable.addComplexSchema(name, eltOuter.getQName()); // adding this type's package to the table, to support inheritance. typeTable.addComplexSchema(getQualifiedName(javaType.getPackage()), eltOuter.getQName()); typeTable.addClassNameForQName(eltOuter.getQName(), name); BeanExcludeInfo beanExcludeInfo = null; if (service.getExcludeInfo() != null) { beanExcludeInfo = service.getExcludeInfo().getBeanExcludeInfoForClass(getClassName(javaType)); } // we need to get properties only for this bean. hence ignore the super // class properties BeanInfo beanInfo = Introspector.getBeanInfo(javaType, javaType.getSuperclass()); for (PropertyDescriptor property : beanInfo.getPropertyDescriptors()) { String propertyName = property.getName(); if (!property.getName().equals("class") && (property.getPropertyType() != null)) { if ((beanExcludeInfo == null) || !beanExcludeInfo.isExcludedProperty(propertyName)) { Type genericFieldType = null; try { Field field = javaType.getDeclaredField(propertyName); genericFieldType = field.getGenericType(); } catch (Exception e) { //log.info(e.getMessage()); } if (genericFieldType instanceof ParameterizedType) { ParameterizedType aType = (ParameterizedType) genericFieldType; Type[] fieldArgTypes = aType.getActualTypeArguments(); try { generateSchemaforGenericFields(xmlSchema, sequence, fieldArgTypes[0], propertyName); } catch (Exception e) { generateSchemaforFieldsandProperties(xmlSchema, sequence, property.getPropertyType(), propertyName, property.getPropertyType().isArray()); } } else { generateSchemaforFieldsandProperties(xmlSchema, sequence, property.getPropertyType(), propertyName, property.getPropertyType().isArray()); } } } } } return schemaTypeName; }
From source file:org.apache.flink.api.java.typeutils.TypeExtractor.java
@SuppressWarnings({ "unchecked", "rawtypes" }) private <OUT, IN1, IN2> TypeInformation<OUT> privateGetForClass(Class<OUT> clazz, ArrayList<Type> typeHierarchy, ParameterizedType parameterizedType, TypeInformation<IN1> in1Type, TypeInformation<IN2> in2Type) { checkNotNull(clazz);/*w w w . j a v a2s . c o m*/ // check if type information can be produced using a factory final TypeInformation<OUT> typeFromFactory = createTypeInfoFromFactory(clazz, typeHierarchy, in1Type, in2Type); if (typeFromFactory != null) { return typeFromFactory; } // Object is handled as generic type info if (clazz.equals(Object.class)) { return new GenericTypeInfo<>(clazz); } // Class is handled as generic type info if (clazz.equals(Class.class)) { return new GenericTypeInfo<OUT>(clazz); } // recursive types are handled as generic type info if (countTypeInHierarchy(typeHierarchy, clazz) > 1) { return new GenericTypeInfo<>(clazz); } // check for arrays if (clazz.isArray()) { // primitive arrays: int[], byte[], ... PrimitiveArrayTypeInfo<OUT> primitiveArrayInfo = PrimitiveArrayTypeInfo.getInfoFor(clazz); if (primitiveArrayInfo != null) { return primitiveArrayInfo; } // basic type arrays: String[], Integer[], Double[] BasicArrayTypeInfo<OUT, ?> basicArrayInfo = BasicArrayTypeInfo.getInfoFor(clazz); if (basicArrayInfo != null) { return basicArrayInfo; } // object arrays else { TypeInformation<?> componentTypeInfo = createTypeInfoWithTypeHierarchy(typeHierarchy, clazz.getComponentType(), in1Type, in2Type); return ObjectArrayTypeInfo.getInfoFor(clazz, componentTypeInfo); } } // check for writable types if (isHadoopWritable(clazz)) { return createHadoopWritableTypeInfo(clazz); } // check for basic types TypeInformation<OUT> basicTypeInfo = BasicTypeInfo.getInfoFor(clazz); if (basicTypeInfo != null) { return basicTypeInfo; } // check for SQL time types TypeInformation<OUT> timeTypeInfo = SqlTimeTypeInfo.getInfoFor(clazz); if (timeTypeInfo != null) { return timeTypeInfo; } // check for subclasses of Value if (Value.class.isAssignableFrom(clazz)) { Class<? extends Value> valueClass = clazz.asSubclass(Value.class); return (TypeInformation<OUT>) ValueTypeInfo.getValueTypeInfo(valueClass); } // check for subclasses of Tuple if (Tuple.class.isAssignableFrom(clazz)) { if (clazz == Tuple0.class) { return new TupleTypeInfo(Tuple0.class); } throw new InvalidTypesException( "Type information extraction for tuples (except Tuple0) cannot be done based on the class."); } // check for Enums if (Enum.class.isAssignableFrom(clazz)) { return new EnumTypeInfo(clazz); } // special case for POJOs generated by Avro. if (SpecificRecordBase.class.isAssignableFrom(clazz)) { return new AvroTypeInfo(clazz); } if (Modifier.isInterface(clazz.getModifiers())) { // Interface has no members and is therefore not handled as POJO return new GenericTypeInfo<OUT>(clazz); } try { TypeInformation<OUT> pojoType = analyzePojo(clazz, new ArrayList<Type>(typeHierarchy), parameterizedType, in1Type, in2Type); if (pojoType != null) { return pojoType; } } catch (InvalidTypesException e) { if (LOG.isDebugEnabled()) { LOG.debug("Unable to handle type " + clazz + " as POJO. Message: " + e.getMessage(), e); } // ignore and create generic type info } // return a generic type return new GenericTypeInfo<OUT>(clazz); }