@SuppressWarnings("unchecked") public static <T> T coerceClassic(Class<T> clz, Object value) { if (clz == null || value == null) { return null; } if (clz == value.getClass()) { return (T) value; } if (clz == Typ.string || clz == Typ.chars) { return (T) value.toString(); } else if (clz == Typ.integer || clz == Typ.intgr) { Integer i = toInt(value); return (T) i; } else if (clz == Typ.longWrapper || clz == Typ.lng) { Long l = toLong(value); return (T) l; } else if (clz == Typ.doubleWrapper || clz == Typ.dbl) { Double i = toDouble(value); return (T) i; } else if (clz == Typ.date) { return (T) toDate(value); } else if (clz == Typ.bigInteger) { return (T) toBigInteger(value); } else if (clz == Typ.bigDecimal) { return (T) toBigDecimal(value); } else if (clz == Typ.calendar) { return (T) toCalendar(toDate(value)); } else if (clz == Typ.floatWrapper || clz == Typ.flt) { Float i = toFloat(value); return (T) i; } else if (clz == Typ.stringArray) { die("Need to fix this"); return null; } else if (clz == Typ.bool || clz == Typ.bln) { Boolean b = toBoolean(value); return (T) b; } else if (Typ.isMap(clz)) { return (T) toMap(value); } else if (clz.isArray()) { return toPrimitiveArrayIfPossible(clz, value); } else if (Typ.isCollection(clz)) { return toCollection(clz, value); } else if (clz.getPackage() != null && !clz.getPackage().getName().startsWith("java") && Typ.isMap(value.getClass()) && Typ.doesMapHaveKeyTypeString(value)) { return (T) MapObjectConversion.fromMap((Map<String, Object>) value); } else if (clz.isEnum()) { return (T) toEnum((Class<? extends Enum>) clz, value); } else { return null; } }
private List<String> dependenciesOf(Package source) { List<String> result = new ArrayList<>(); if (source.isAnnotationPresent(DependsUpon.class)) for (Class<?> target : source.getAnnotation(DependsUpon.class).packagesOf()) result.add(target.getPackage().getName()); return result; }
/** * Returns the correct implementation instance for the interface <code>type</code>. For convention * the implentation is named <code>InterfaceName + Impl</code>. * * @param type The interface type * @return The correct ModelProxy subclass (if exists), a ModelProxy instance otherwise * @throws MalformedModelException is the interface or the implementation are not well formed * (they don't respect the conventions). * @throws ModelRuntimeException is any error occurs during the instantiation */ protected ModelProxy createInstance(Class type) { Class backClass; if (implementations.containsKey(type)) backClass = implementations.get(type); else { /* type never seen */ try { Package pkg = type.getPackage(); String pkgN = pkg == null ? "" : pkg.getName(); backClass = Class.forName(pkgN + tableName(type) + CommonStatic.getImplementationSuffix()); } catch (Exception e) { backClass = ModelProxy.class; } Validator.validateModel(type, backClass); initFieldsTypes(type); implementations.put(type, backClass); } ModelProxy impl = null; try { impl = (ModelProxy) backClass.newInstance(); } catch (Exception e) { throw new ModelRuntimeException(e.getMessage()); } return impl; }
// // Find all the java.sql interfaces implemented by a class and find // the methods in those interfaces which raise // SQLFeatureNotSupportedException when called on the passed-in candidate object. // private void vetInterfaces( Object candidate, Class myClass, HashSet<String> unsupportedList, HashSet<String> notUnderstoodList) throws Exception { Class superClass = myClass.getSuperclass(); if (superClass != null) { vetInterfaces(candidate, superClass, unsupportedList, notUnderstoodList); } // // The contract for Class.getInterfaces() states that the interfaces // come back in a deterministic order, namely, in the order that // they were declared in the "extends" clause. // Class<?>[] interfaces = myClass.getInterfaces(); int interfaceCount = interfaces.length; for (int i = 0; i < interfaceCount; i++) { Class<?> iface = interfaces[i]; if (iface.getPackage().getName().equals(SQL_PACKAGE_NAME)) { vetInterfaceMethods(candidate, iface, unsupportedList, notUnderstoodList); } vetInterfaces(candidate, iface, unsupportedList, notUnderstoodList); } }
public void apply() throws IllegalAccessException, InvocationTargetException, InstantiationException { if (type.isEnum()) { for (T instance : type.getEnumConstants()) { assertThat( instance.toString(), is( type.getCanonicalName().substring(type.getPackage().getName().length() + 1) + "." + ((Enum<?>) instance).name())); } return; } for (Constructor<?> constructor : type.getDeclaredConstructors()) { if (constructor.isSynthetic() && skipSynthetic) { continue; } constructor.setAccessible(true); Class<?>[] parameterTypes = constructor.getParameterTypes(); Object[] actualArguments = new Object[parameterTypes.length]; Object[] otherArguments = new Object[parameterTypes.length]; int index = 0; for (Class<?> parameterType : parameterTypes) { putInstance(parameterType, actualArguments, otherArguments, index++); } int testIndex = 0; @SuppressWarnings("unchecked") T instance = (T) constructor.newInstance(actualArguments); assertThat(instance, is(instance)); assertThat(instance, not(is((Object) null))); assertThat(instance, not(is(new Object()))); Object similarInstance = constructor.newInstance(actualArguments); assertThat(instance.hashCode(), is(similarInstance.hashCode())); assertThat(instance, is(similarInstance)); if (skipToString) { assertThat(instance.toString(), notNullValue()); } else if (optionalToStringRegex == null) { checkString(instance); } else { assertThat(instance.toString(), new RegexMatcher(optionalToStringRegex)); } for (Object otherArgument : otherArguments) { Object[] compareArguments = new Object[actualArguments.length]; int argumentIndex = 0; for (Object actualArgument : actualArguments) { if (argumentIndex == testIndex) { compareArguments[argumentIndex] = otherArgument; } else { compareArguments[argumentIndex] = actualArgument; } argumentIndex++; } Object unlikeInstance = constructor.newInstance(compareArguments); assertThat(instance.hashCode(), not(is(unlikeInstance))); assertThat(instance, not(is(unlikeInstance))); testIndex++; } } }
/** * Create MBean for Object. Attempts to create an MBean for the object by searching the package * and class name space. For example an object of the type * * <PRE> * class com.acme.MyClass extends com.acme.util.BaseClass * </PRE> * * Then this method would look for the following classes: * * <UL> * <LI>com.acme.MyClassMBean * <LI>com.acme.jmx.MyClassMBean * <LI>com.acme.util.BaseClassMBean * <LI>com.acme.util.jmx.BaseClassMBean * </UL> * * @param o The object * @return A new instance of an MBean for the object or null. */ public static ModelMBean mbeanFor(Object o) { try { Class oClass = o.getClass(); ClassLoader loader = oClass.getClassLoader(); ModelMBean mbean = null; boolean jmx = false; Class[] interfaces = null; int i = 0; while (mbean == null && oClass != null) { Class focus = interfaces == null ? oClass : interfaces[i]; String pName = focus.getPackage().getName(); String cName = focus.getName().substring(pName.length() + 1); String mName = pName + (jmx ? ".jmx." : ".") + cName + "MBean"; try { Class mClass = loader.loadClass(mName); if (log.isTraceEnabled()) log.trace("mbeanFor " + o + " mClass=" + mClass); mbean = (ModelMBean) mClass.newInstance(); mbean.setManagedResource(o, "objectReference"); if (log.isDebugEnabled()) log.debug("mbeanFor " + o + " is " + mbean); return mbean; } catch (ClassNotFoundException e) { if (e.toString().endsWith("MBean")) { if (log.isTraceEnabled()) log.trace(e.toString()); } else log.warn(LogSupport.EXCEPTION, e); } catch (Error e) { log.warn(LogSupport.EXCEPTION, e); mbean = null; } catch (Exception e) { log.warn(LogSupport.EXCEPTION, e); mbean = null; } if (jmx) { if (interfaces != null) { i++; if (i >= interfaces.length) { interfaces = null; oClass = oClass.getSuperclass(); } } else { interfaces = oClass.getInterfaces(); i = 0; if (interfaces == null || interfaces.length == 0) { interfaces = null; oClass = oClass.getSuperclass(); } } } jmx = !jmx; } } catch (Exception e) { LogSupport.ignore(log, e); } return null; }
@Test public void testLoading() throws Exception { Class<?> type = classLoader.loadClass(Foo.class.getName()); assertThat(type.getClassLoader(), is(classLoader)); assertEquals(classLoader.loadClass(Foo.class.getName()), type); assertNotEquals(Foo.class, type); assertThat(type.getPackage(), notNullValue(Package.class)); assertThat(type.getPackage(), is(Foo.class.getPackage())); }
/** * Method updates existing Spring bean definitions in a XML application context file. Bean * definition is identified by its type defining class. * * @param project * @param type * @param jaxbElement */ public void updateBeanDefinitions( File configFile, Project project, Class<?> type, Object jaxbElement) { Source xsltSource; Source xmlSource; try { xsltSource = new StreamSource( new ClassPathResource("transform/update-bean-type.xsl").getInputStream()); xsltSource.setSystemId("update-bean"); List<File> configFiles = new ArrayList<>(); configFiles.add(configFile); configFiles.addAll(getConfigImports(configFile, project)); LSParser parser = XMLUtils.createLSParser(); GetSpringBeansFilter getBeanFilter = new GetSpringBeansFilter(type, null); parser.setFilter(getBeanFilter); for (File file : configFiles) { parser.parseURI(file.toURI().toString()); if (!CollectionUtils.isEmpty(getBeanFilter.getBeanDefinitions())) { xmlSource = new StringSource(FileUtils.readToString(new FileInputStream(file))); String beanElement = type.getAnnotation(XmlRootElement.class).name(); String beanNamespace = type.getPackage().getAnnotation(XmlSchema.class).namespace(); // create transformer Transformer transformer = transformerFactory.newTransformer(xsltSource); transformer.setParameter("bean_element", beanElement); transformer.setParameter("bean_namespace", beanNamespace); transformer.setParameter( "bean_content", getXmlContent(jaxbElement) .replaceAll("(?m)^(\\s<)", getTabs(1, project.getSettings().getTabSize()) + "$1") .replaceAll("(?m)^(</)", getTabs(1, project.getSettings().getTabSize()) + "$1")); // transform StringResult result = new StringResult(); transformer.transform(xmlSource, result); FileUtils.writeToFile( format(result.toString(), project.getSettings().getTabSize()), file); return; } } } catch (IOException e) { throw new ApplicationRuntimeException(UNABLE_TO_READ_TRANSFORMATION_SOURCE, e); } catch (TransformerException e) { throw new ApplicationRuntimeException(FAILED_TO_UPDATE_BEAN_DEFINITION, e); } }
protected static void convertUnsupportedToAsciidocTable( Properties props, List<Class<?>> clazzes, String title) throws ParserConfigurationException, TransformerException { List<String[]> rows = new ArrayList<>(clazzes.size() + 1); rows.add(new String[] {"Package", "Class"}); // add column titles first for (Class<?> clazz : clazzes) rows.add(new String[] {clazz.getPackage().getName(), clazz.getSimpleName()}); String tmp = createAsciidocTable(rows, title, "[align=\"left\",width=\"50%\",options=\"header\"]"); // do we have more than one property (superclass Protocol has only one property (stats)) if (clazzes.size() > 1) { props.put(title, tmp); } }
private void checkString(T instance) { assertThat( instance.toString(), CoreMatchers.startsWith( type.getCanonicalName().substring(type.getPackage().getName().length() + 1) + "{")); assertThat(instance.toString(), endsWith("}")); Class<?> currentType = type; do { for (Field field : type.getDeclaredFields()) { if (!field.isSynthetic() && !Modifier.isStatic(field.getModifiers()) && !ignoredFields.contains(field.getName())) { assertThat(instance.toString(), containsString(field.getName())); } } } while ((currentType = currentType.getSuperclass()) != Object.class); }
/** * Method removes all Spring bean definitions of given type from the XML application context file. * * @param project * @param type */ public void removeBeanDefinitions(File configFile, Project project, Class<?> type) { Source xsltSource; Source xmlSource; try { xsltSource = new StreamSource( new ClassPathResource("transform/delete-bean-type.xsl").getInputStream()); xsltSource.setSystemId("delete-bean"); List<File> configFiles = new ArrayList<>(); configFiles.add(configFile); configFiles.addAll(getConfigImports(configFile, project)); for (File file : configFiles) { xmlSource = new StringSource(FileUtils.readToString(new FileInputStream(configFile))); String beanElement = type.getAnnotation(XmlRootElement.class).name(); String beanNamespace = type.getPackage().getAnnotation(XmlSchema.class).namespace(); // create transformer Transformer transformer = transformerFactory.newTransformer(xsltSource); transformer.setParameter("bean_element", beanElement); transformer.setParameter("bean_namespace", beanNamespace); // transform StringResult result = new StringResult(); transformer.transform(xmlSource, result); FileUtils.writeToFile(format(result.toString(), project.getSettings().getTabSize()), file); return; } } catch (IOException e) { throw new ApplicationRuntimeException(UNABLE_TO_READ_TRANSFORMATION_SOURCE, e); } catch (TransformerException e) { throw new ApplicationRuntimeException(FAILED_TO_UPDATE_BEAN_DEFINITION, e); } }
/** * ** Returns an I18N instance based on the specified package name and Locale ** @param pkgClz The * class from which the class package is derived ** @param loc The Locale resource from with the * localized text is loaded */ public static I18N getI18N(Class pkgClz, Locale loc) { return I18N.getI18N(pkgClz.getPackage().getName(), loc); }
/** * ** Returns an I18N.Text instance used for lazy localization ** @param clazz The class from * which the package is derived ** @param key The localization key ** @param dft The default * localized text ** @return An I18N.Text instance used for lazy localization */ public static I18N.Text getString(Class clazz, String key, String dft) { // i18n 'key' is separately specified String pkg = (clazz != null) ? clazz.getPackage().getName() : null; return I18N.parseText(pkg, key, dft); }
public Text(Class clazz, String key, String dft) { this.pkg = (clazz != null) ? clazz.getPackage().getName() : null; this.key = (key != null) ? key : ""; this.dft = (dft != null) ? dft : ""; // Print.logInfo("I18N Text: key=" + key + " default=" + dft); }
public String getPublicMethodsForClasses(String classNames[]) { StringBuilder result = new StringBuilder(); String className = null; result.append("<classDefinitions>"); if (classNames != null && classNames.length > 0) { for (int i = 0; i < classNames.length; i++) { className = classNames[i]; if (className != null) { result.append("<classDefinition>"); try { Class c = Class.forName(className); result.append( (new StringBuilder("<classSimpleName>")) .append(c.getSimpleName()) .append("</classSimpleName>") .toString()); result.append( (new StringBuilder("<classFullName>")) .append(c.getName()) .append("</classFullName>") .toString()); Package pack = c.getPackage(); String packStr = ""; if (pack != null) packStr = pack.getName(); result.append( (new StringBuilder("<packageName>")) .append(packStr) .append("</packageName>") .toString()); Method methods[] = c.getMethods(); Method method = null; result.append("<methods>"); if (methods != null) { for (int j = 0; j < methods.length; j++) { method = methods[j]; if (method != null && !methodsExclude.contains(method.getName())) { result.append("<method>"); result.append( (new StringBuilder("<methodSignature>")) .append(method.toString()) .append("</methodSignature>") .toString()); result.append( (new StringBuilder("<methodName>")) .append(method.getName()) .append("</methodName>") .toString()); result.append( (new StringBuilder("<returnType>")) .append(method.getReturnType().getName()) .append("</returnType>") .toString()); Class paramClasses[] = method.getParameterTypes(); result.append("<params>"); if (paramClasses != null) { for (int l = 0; l < paramClasses.length; l++) if (paramClasses[l] != null) result.append( (new StringBuilder("<param>")) .append(paramClasses[l].getName()) .append("</param>") .toString()); } result.append("</params>"); result.append("</method>"); } } } result.append("</methods>"); } catch (ClassNotFoundException e) { result.append( (new StringBuilder("<classFullName>")) .append(className) .append("</classFullName>") .toString()); result.append( (new StringBuilder("<error>Problem retrieving ")) .append(className) .append(" information</error>") .toString()); System.out.println(e.getMessage()); } result.append("</classDefinition>"); } } } result.append("</classDefinitions>"); return result.toString(); }
public String getPublicPropertiesForClasses(String classNames[]) { StringBuilder result = new StringBuilder(); String className = null; ArrayList publicFields = new ArrayList(); result.append("<classDefinitions>"); if (classNames != null && classNames.length > 0) { for (int i = 0; i < classNames.length; i++) { className = classNames[i]; if (className != null) { result.append("<classDefinition>"); try { Class c = Class.forName(className); Field fields[] = c.getFields(); Field field = null; if (fields != null) { for (int k = 0; k < fields.length; k++) { field = fields[k]; if (field != null) publicFields.add( (new StringBuilder(String.valueOf(field.getName()))) .append(",") .append(field.getType().getName()) .toString()); } } try { BeanInfo b = Introspector.getBeanInfo(c); result.append( (new StringBuilder("<classSimpleName>")) .append(c.getSimpleName()) .append("</classSimpleName>") .toString()); result.append( (new StringBuilder("<classFullName>")) .append(c.getName()) .append("</classFullName>") .toString()); Package pack = c.getPackage(); String packStr = ""; if (pack != null) packStr = pack.getName(); result.append( (new StringBuilder("<packageName>")) .append(packStr) .append("</packageName>") .toString()); PropertyDescriptor pds[] = b.getPropertyDescriptors(); if (pds != null) { for (int propCount = 0; propCount < pds.length; propCount++) { PropertyDescriptor pd = pds[propCount]; String propertyName = pd.getName(); Method readMethod = pd.getReadMethod(); Method writeMethod = pd.getWriteMethod(); if (readMethod != null && isPublicAccessor(readMethod.getModifiers()) && writeMethod != null && isPublicAccessor(writeMethod.getModifiers())) publicFields.add( (new StringBuilder(String.valueOf(propertyName))) .append(",") .append(pd.getPropertyType().getName()) .toString()); } } } catch (Exception e) { e.printStackTrace(); } if (publicFields != null && publicFields.size() > 0) { String temp = null; result.append("<publicFields>"); for (int counter = 0; counter < publicFields.size(); counter++) { temp = (String) publicFields.get(counter); if (temp != null) { String pubTemp[] = temp.split(","); if (pubTemp.length == 2) { result.append("<publicField>"); result.append( (new StringBuilder("<publicFieldName>")) .append(pubTemp[0]) .append("</publicFieldName>") .toString()); result.append( (new StringBuilder("<publicFieldType>")) .append(pubTemp[1]) .append("</publicFieldType>") .toString()); result.append("</publicField>"); } } } result.append("</publicFields>"); } } catch (ClassNotFoundException e) { result.append( (new StringBuilder("<classFullName>")) .append(className) .append("</classFullName>") .toString()); result.append( (new StringBuilder("<error>Problem retrieving ")) .append(className) .append(" information</error>") .toString()); System.out.println(e.getMessage()); } result.append("</classDefinition>"); } } } result.append("</classDefinitions>"); return result.toString(); }