List of usage examples for java.lang.reflect Method getModifiers
@Override public int getModifiers()
From source file:org.evosuite.testcase.TestFactory.java
private boolean insertRandomReflectionCall(TestCase test, int position, int recursionDepth) throws ConstructionFailedException { logger.debug("Recursion depth: " + recursionDepth); if (recursionDepth > Properties.MAX_RECURSION) { logger.debug("Max recursion depth reached"); throw new ConstructionFailedException("Max recursion depth reached"); }/* w w w . j a v a2s. com*/ int length = test.size(); List<VariableReference> parameters = null; Statement st = null; if (reflectionFactory.nextUseField()) { Field field = reflectionFactory.nextField(); parameters = satisfyParameters(test, null, //we need a reference to the SUT, and one to a variable of same type of chosen field Arrays.asList((Type) reflectionFactory.getReflectedClass(), (Type) field.getType()), position, recursionDepth + 1, true, false, true); try { st = new PrivateFieldStatement(test, reflectionFactory.getReflectedClass(), field.getName(), parameters.get(0), parameters.get(1)); } catch (NoSuchFieldException e) { logger.error("Reflection problem: " + e, e); throw new ConstructionFailedException("Reflection problem"); } } else { //method Method method = reflectionFactory.nextMethod(); List<Type> list = new ArrayList<>(); list.add(reflectionFactory.getReflectedClass()); list.addAll(Arrays.asList(method.getGenericParameterTypes())); parameters = satisfyParameters(test, null, list, position, recursionDepth + 1, true, false, true); VariableReference callee = parameters.remove(0); st = new PrivateMethodStatement(test, reflectionFactory.getReflectedClass(), method, callee, parameters, Modifier.isStatic(method.getModifiers())); } int newLength = test.size(); position += (newLength - length); test.addStatement(st, position); return true; }
From source file:org.apache.openjpa.meta.FieldMetaData.java
/** * Convert the given field value to its external value through the * provided externalizer, or return the value as-is if no externalizer. *///from w ww .ja v a2s .c o m public Object getExternalValue(Object val, StoreContext ctx) { Map extValues = getExternalValueMap(); if (extValues != null) { Object foundVal = extValues.get(val); if (foundVal == null) { throw new UserException( _loc.get("bad-externalized-value", new Object[] { val, extValues.keySet(), this })) .setFatal(true).setFailedObject(val); } else { return foundVal; } } Method externalizer = getExternalizerMethod(); if (externalizer == null) return val; // special case for queries: allow the given value to pass through // as-is if it is already in externalized form if (val != null && getType().isInstance(val) && (!getDeclaredType().isInstance(val) || getDeclaredType() == Object.class)) return val; try { // either invoke the static toExternal(val[, ctx]) method, or the // non-static val.toExternal([ctx]) method if (Modifier.isStatic(externalizer.getModifiers())) { if (externalizer.getParameterTypes().length == 1) return externalizer.invoke(null, new Object[] { val }); return externalizer.invoke(null, new Object[] { val, ctx }); } if (val == null) return null; if (externalizer.getParameterTypes().length == 0) return externalizer.invoke(val, (Object[]) null); return externalizer.invoke(val, new Object[] { ctx }); } catch (OpenJPAException ke) { throw ke; } catch (Exception e) { throw new MetaDataException(_loc.get("externalizer-err", this, Exceptions.toString(val), e.toString())) .setCause(e); } }
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 */// ww w. j a v a2 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:com.github.helenusdriver.driver.tools.Tool.java
/** * Finds an initial objects factory method and its dependent classes from the * specified object creator class./* w w w. j ava 2 s . com*/ * * @author paouelle * * @param clazz the non-<code>null</code> object creator class * @return the initial objects factory method and its set of dependenc classes * or <code>null</code> if none configured * @throws IllegalArgumentException if the initial objects method is not * properly defined */ private static Pair<Method, Class<?>[]> findInitial(Class<?> clazz) { final InitialObjects io = clazz.getAnnotation(InitialObjects.class); if (io != null) { final String mname = io.staticMethod(); try { Method m; try { // first look for one with a map for suffixes m = clazz.getMethod(mname, Map.class); // validate that if suffixes are defined, the method expects a Map<String, String> // to provide the values for the suffixes when initializing objects final Class<?>[] cparms = m.getParameterTypes(); // should always be 1 as we used only 1 class in getMethod() if (cparms.length != 1) { throw new IllegalArgumentException( "expecting one Map<String, String> parameter for initial objects method '" + mname + "' in class: " + clazz.getSimpleName()); } // should always be a map as we used a Map to find the method if (!Map.class.isAssignableFrom(cparms[0])) { throw new IllegalArgumentException("expecting parameter for initial objects method '" + mname + "' to be of type Map<String, String> in class: " + clazz.getSimpleName()); } final Type[] tparms = m.getGenericParameterTypes(); // should always be 1 as we used only 1 class in getMethod() if (tparms.length != 1) { // should always be 1 as it was already tested above throw new IllegalArgumentException( "expecting one Map<String, String> parameter for initial objects method '" + mname + "' in class: " + clazz.getSimpleName()); } if (tparms[0] instanceof ParameterizedType) { final ParameterizedType ptype = (ParameterizedType) tparms[0]; // maps will always have 2 arguments for (final Type atype : ptype.getActualTypeArguments()) { final Class<?> aclazz = ReflectionUtils.getRawClass(atype); if (String.class != aclazz) { throw new IllegalArgumentException( "expecting a Map<String, String> parameter for initial objects method '" + mname + "' in class: " + clazz.getSimpleName()); } } } else { throw new IllegalArgumentException( "expecting a Map<String, String> parameter for initial objects method '" + mname + "' in class: " + clazz.getSimpleName()); } } catch (NoSuchMethodException e) { // fallback to one with no map m = clazz.getMethod(mname); } // validate the method is static if (!Modifier.isStatic(m.getModifiers())) { throw new IllegalArgumentException("initial objects method '" + mname + "' is not static in class: " + clazz.getSimpleName()); } // validate the return type is an array final Class<?> type = m.getReturnType(); if (!type.isArray()) { throw new IllegalArgumentException("initial objects method '" + mname + "' doesn't return an array in class: " + clazz.getSimpleName()); } return Pair.of(m, io.dependsOn()); } catch (NoSuchMethodException e) { throw new IllegalArgumentException( "missing initial objects method '" + mname + "' in class: " + clazz.getSimpleName(), e); } } return null; }
From source file:org.evosuite.setup.TestClusterGenerator.java
public static boolean canUse(Method m, Class<?> ownerClass) { if (m.isBridge()) { logger.debug("Excluding bridge method: {}", m.toString()); return false; }/*from w w w . ja v a 2s .c om*/ if (m.isSynthetic()) { logger.debug("Excluding synthetic method: {}", m.toString()); return false; } if (!Properties.USE_DEPRECATED && m.isAnnotationPresent(Deprecated.class)) { logger.debug("Excluding deprecated method {}", m.getName()); return false; } if (m.isAnnotationPresent(Test.class)) { logger.debug("Excluding test method {}", m.getName()); return false; } if (m.isAnnotationPresent(EvoSuiteExclude.class)) { logger.debug("Excluding method with exclusion annotation {}", m.getName()); return false; } if (m.getDeclaringClass().equals(java.lang.Object.class)) { return false; } if (!m.getReturnType().equals(String.class) && !canUse(m.getReturnType())) { return false; } if (m.getDeclaringClass().equals(Enum.class)) { return false; /* if (m.getName().equals("valueOf") || m.getName().equals("values") || m.getName().equals("ordinal")) { logger.debug("Excluding valueOf for Enum " + m.toString()); return false; } // Skip compareTo on enums (like Randoop) if (m.getName().equals("compareTo") && m.getParameterTypes().length == 1 && m.getParameterTypes()[0].equals(Enum.class)) return false; */ } if (m.getDeclaringClass().equals(java.lang.Thread.class)) return false; // Hashcode only if we need to cover it if (m.getName().equals("hashCode") && !m.getDeclaringClass().equals(Properties.getTargetClass())) return false; // Randoop special case: just clumps together a bunch of hashCodes, so skip it if (m.getName().equals("deepHashCode") && m.getDeclaringClass().equals(Arrays.class)) return false; // Randoop special case: differs too much between JDK installations if (m.getName().equals("getAvailableLocales")) return false; if (m.getName().equals(ClassResetter.STATIC_RESET)) { logger.debug("Ignoring static reset class"); return false; } if (isForbiddenNonDeterministicCall(m)) { return false; } if (!Properties.CONSIDER_MAIN_METHODS && m.getName().equals("main") && Modifier.isStatic(m.getModifiers()) && Modifier.isPublic(m.getModifiers())) { logger.debug("Ignoring static main method "); return false; } /* if(m.getTypeParameters().length > 0) { logger.debug("Cannot handle generic methods at this point"); if(m.getDeclaringClass().equals(Properties.getTargetClass())) { LoggingUtils.getEvoLogger().info("* Skipping method "+m.getName()+": generic methods are not handled yet"); } return false; } */ // If default or if (Modifier.isPublic(m.getModifiers())) { makeAccessible(m); return true; } // If default access rights, then check if this class is in the same package as the target class if (!Modifier.isPrivate(m.getModifiers())) { // && !Modifier.isProtected(m.getModifiers())) { String packageName = ClassUtils.getPackageName(ownerClass); String declaredPackageName = ClassUtils.getPackageName(m.getDeclaringClass()); if (packageName.equals(Properties.CLASS_PREFIX) && packageName.equals(declaredPackageName)) { makeAccessible(m); return true; } } return false; }
From source file:org.evosuite.setup.TestUsageChecker.java
public static boolean canUse(Method m, Class<?> ownerClass) { if (m.isBridge()) { logger.debug("Excluding bridge method: " + m.toString()); return false; }// ww w.java 2 s . c o m if (m.isSynthetic()) { logger.debug("Excluding synthetic method: " + m.toString()); return false; } if (!Properties.USE_DEPRECATED && m.isAnnotationPresent(Deprecated.class)) { final Class<?> targetClass = Properties.getTargetClassAndDontInitialise(); if (Properties.hasTargetClassBeenLoaded() && !m.getDeclaringClass().equals(targetClass)) { logger.debug("Excluding deprecated method " + m.getName()); return false; } } if (m.isAnnotationPresent(Test.class) || m.isAnnotationPresent(Before.class) || m.isAnnotationPresent(BeforeClass.class) || m.isAnnotationPresent(After.class) || m.isAnnotationPresent(AfterClass.class)) { logger.debug("Excluding test method " + m.getName()); return false; } if (m.isAnnotationPresent(EvoSuiteTest.class)) { logger.debug("Excluding EvoSuite test method " + m.getName()); return false; } if (m.isAnnotationPresent(EvoSuiteExclude.class)) { logger.debug("Excluding method with exclusion annotation " + m.getName()); return false; } if (m.getDeclaringClass().equals(java.lang.Object.class)) { return false; } if (!m.getReturnType().equals(String.class) && (!canUse(m.getReturnType()) || !canUse(m.getGenericReturnType()))) { return false; } for (java.lang.reflect.Type paramType : m.getGenericParameterTypes()) { if (!canUse(paramType)) return false; } if (m.getDeclaringClass().equals(Enum.class)) { return false; /* if (m.getName().equals("valueOf") || m.getName().equals("values") || m.getName().equals("ordinal")) { logger.debug("Excluding valueOf for Enum " + m.toString()); return false; } // Skip compareTo on enums (like Randoop) if (m.getName().equals("compareTo") && m.getParameterTypes().length == 1 && m.getParameterTypes()[0].equals(Enum.class)) return false; */ } if (m.getDeclaringClass().equals(java.lang.Thread.class)) return false; // Hashcode only if we need to cover it if (m.getName().equals("hashCode")) { final Class<?> targetClass = Properties.getTargetClassAndDontInitialise(); if (!m.getDeclaringClass().equals(targetClass)) return false; else { if (GraphPool.getInstance(ownerClass.getClassLoader()).getActualCFG(Properties.TARGET_CLASS, m.getName() + Type.getMethodDescriptor(m)) == null) { // Don't cover generated hashCode // TODO: This should work via annotations return false; } } } // Randoop special case: just clumps together a bunch of hashCodes, so skip it if (m.getName().equals("deepHashCode") && m.getDeclaringClass().equals(Arrays.class)) return false; // Randoop special case: differs too much between JDK installations if (m.getName().equals("getAvailableLocales")) return false; if (m.getName().equals(ClassResetter.STATIC_RESET)) { logger.debug("Ignoring static reset method"); return false; } if (isForbiddenNonDeterministicCall(m)) { return false; } if (!Properties.CONSIDER_MAIN_METHODS && m.getName().equals("main") && Modifier.isStatic(m.getModifiers()) && Modifier.isPublic(m.getModifiers())) { logger.debug("Ignoring static main method "); return false; } /* if(m.getTypeParameters().length > 0) { logger.debug("Cannot handle generic methods at this point"); if(m.getDeclaringClass().equals(Properties.getTargetClass())) { LoggingUtils.getEvoLogger().info("* Skipping method "+m.getName()+": generic methods are not handled yet"); } return false; } */ // If default or if (Modifier.isPublic(m.getModifiers())) { TestClusterUtils.makeAccessible(m); return true; } // If default access rights, then check if this class is in the same package as the target class if (!Modifier.isPrivate(m.getModifiers())) { // && !Modifier.isProtected(m.getModifiers())) { String packageName = ClassUtils.getPackageName(ownerClass); String declaredPackageName = ClassUtils.getPackageName(m.getDeclaringClass()); if (packageName.equals(Properties.CLASS_PREFIX) && packageName.equals(declaredPackageName)) { TestClusterUtils.makeAccessible(m); return true; } } return false; }
From source file:lucee.runtime.config.ConfigWebFactory.java
/** * @param configServer/*from w w w . ja v a 2s. c o m*/ * @param config * @param doc */ private static void loadCache(ConfigServerImpl configServer, ConfigImpl config, Document doc) { boolean hasCS = configServer != null; Map<String, CacheConnection> caches = new HashMap<String, CacheConnection>(); boolean hasAccess = ConfigWebUtil.hasAccess(config, SecurityManagerImpl.TYPE_CACHE); // print.o("LOAD CACHE:"+hasAccess+":"+hasCS); Element eCache = getChildByName(doc.getDocumentElement(), "cache"); // has changes String md5 = getMD5(eCache, hasCS ? configServer.getCacheMD5() : ""); if (md5.equals(config.getCacheMD5())) return; config.setCacheMD5(md5); // default query String defaultResource = eCache.getAttribute("default-resource"); if (hasAccess && !StringUtil.isEmpty(defaultResource)) { config.setCacheDefaultConnectionName(ConfigImpl.CACHE_DEFAULT_RESOURCE, defaultResource); } else if (hasCS) { if (eCache.hasAttribute("default-resource")) config.setCacheDefaultConnectionName(ConfigImpl.CACHE_DEFAULT_RESOURCE, ""); else config.setCacheDefaultConnectionName(ConfigImpl.CACHE_DEFAULT_RESOURCE, configServer.getCacheDefaultConnectionName(ConfigImpl.CACHE_DEFAULT_RESOURCE)); } else config.setCacheDefaultConnectionName(ConfigImpl.CACHE_DEFAULT_RESOURCE, ""); // default function String defaultUDF = eCache.getAttribute("default-function"); if (hasAccess && !StringUtil.isEmpty(defaultUDF)) { config.setCacheDefaultConnectionName(ConfigImpl.CACHE_DEFAULT_FUNCTION, defaultUDF); } else if (hasCS) { if (eCache.hasAttribute("default-function")) config.setCacheDefaultConnectionName(ConfigImpl.CACHE_DEFAULT_FUNCTION, ""); else config.setCacheDefaultConnectionName(ConfigImpl.CACHE_DEFAULT_FUNCTION, configServer.getCacheDefaultConnectionName(ConfigImpl.CACHE_DEFAULT_FUNCTION)); } else config.setCacheDefaultConnectionName(ConfigImpl.CACHE_DEFAULT_FUNCTION, ""); // default include String defaultInclude = eCache.getAttribute("default-include"); if (hasAccess && !StringUtil.isEmpty(defaultInclude)) { config.setCacheDefaultConnectionName(ConfigImpl.CACHE_DEFAULT_INCLUDE, defaultInclude); } else if (hasCS) { if (eCache.hasAttribute("default-include")) config.setCacheDefaultConnectionName(ConfigImpl.CACHE_DEFAULT_INCLUDE, ""); else config.setCacheDefaultConnectionName(ConfigImpl.CACHE_DEFAULT_INCLUDE, configServer.getCacheDefaultConnectionName(ConfigImpl.CACHE_DEFAULT_INCLUDE)); } else config.setCacheDefaultConnectionName(ConfigImpl.CACHE_DEFAULT_INCLUDE, ""); // default query String defaultQuery = eCache.getAttribute("default-query"); if (hasAccess && !StringUtil.isEmpty(defaultQuery)) { config.setCacheDefaultConnectionName(ConfigImpl.CACHE_DEFAULT_QUERY, defaultQuery); } else if (hasCS) { if (eCache.hasAttribute("default-query")) config.setCacheDefaultConnectionName(ConfigImpl.CACHE_DEFAULT_QUERY, ""); else config.setCacheDefaultConnectionName(ConfigImpl.CACHE_DEFAULT_QUERY, configServer.getCacheDefaultConnectionName(ConfigImpl.CACHE_DEFAULT_QUERY)); } else config.setCacheDefaultConnectionName(ConfigImpl.CACHE_DEFAULT_QUERY, ""); // default template String defaultTemplate = eCache.getAttribute("default-template"); if (hasAccess && !StringUtil.isEmpty(defaultTemplate)) { config.setCacheDefaultConnectionName(ConfigImpl.CACHE_DEFAULT_TEMPLATE, defaultTemplate); } else if (hasCS) { if (eCache.hasAttribute("default-template")) config.setCacheDefaultConnectionName(ConfigImpl.CACHE_DEFAULT_TEMPLATE, ""); else config.setCacheDefaultConnectionName(ConfigImpl.CACHE_DEFAULT_TEMPLATE, configServer.getCacheDefaultConnectionName(ConfigImpl.CACHE_DEFAULT_TEMPLATE)); } else config.setCacheDefaultConnectionName(ConfigImpl.CACHE_DEFAULT_TEMPLATE, ""); // default object String defaultObject = eCache.getAttribute("default-object"); if (hasAccess && !StringUtil.isEmpty(defaultObject)) { config.setCacheDefaultConnectionName(ConfigImpl.CACHE_DEFAULT_OBJECT, defaultObject); } else if (hasCS) { if (eCache.hasAttribute("default-object")) config.setCacheDefaultConnectionName(ConfigImpl.CACHE_DEFAULT_OBJECT, ""); else config.setCacheDefaultConnectionName(ConfigImpl.CACHE_DEFAULT_OBJECT, configServer.getCacheDefaultConnectionName(ConfigImpl.CACHE_DEFAULT_OBJECT)); } else config.setCacheDefaultConnectionName(ConfigImpl.CACHE_DEFAULT_OBJECT, ""); // cache connections Element[] eConnections = getChildren(eCache, "connection"); // if(hasAccess) { String name, clazzName; CacheConnection cc; Class cacheClazz; // caches if (hasAccess) for (int i = 0; i < eConnections.length; i++) { Element eConnection = eConnections[i]; name = eConnection.getAttribute("name"); clazzName = deRailo(eConnection.getAttribute("class")); if (clazzName != null) clazzName = clazzName.trim(); // try { Struct custom = toStruct(eConnection.getAttribute("custom")); // Workaround for old EHCache class defintions if (clazzName != null && clazzName.endsWith(".EHCacheLite")) { cacheClazz = EHCache.class; if (!custom.containsKey("distributed")) custom.setEL("distributed", "off"); if (!custom.containsKey("asynchronousReplicationIntervalMillis")) custom.setEL("asynchronousReplicationIntervalMillis", "1000"); if (!custom.containsKey("maximumChunkSizeBytes")) custom.setEL("maximumChunkSizeBytes", "5000000"); } else if (clazzName != null && clazzName.endsWith(".extension.io.cache.eh.EHCache")) cacheClazz = EHCache.class; else cacheClazz = ClassUtil.loadClass(config.getClassLoader(), clazzName); cc = new CacheConnectionImpl(config, name, cacheClazz, custom, Caster.toBooleanValue(eConnection.getAttribute("read-only"), false), Caster.toBooleanValue(eConnection.getAttribute("storage"), false)); if (!StringUtil.isEmpty(name)) { caches.put(name.toLowerCase(), cc); } else SystemOut.print(config.getErrWriter(), "missing cache name"); } catch (ClassException ce) { SystemOut.print(config.getErrWriter(), ExceptionUtil.getStacktrace(ce, true)); } catch (IOException e) { SystemOut.print(config.getErrWriter(), ExceptionUtil.getStacktrace(e, true)); } } // } // call static init once per driver { // group by classes final Map<Class<?>, List<CacheConnection>> _caches = new HashMap<Class<?>, List<CacheConnection>>(); { Iterator<Entry<String, CacheConnection>> it = caches.entrySet().iterator(); Entry<String, CacheConnection> entry; List<CacheConnection> list; while (it.hasNext()) { entry = it.next(); cc = entry.getValue(); list = _caches.get(cc.getClazz()); if (list == null) { list = new ArrayList<CacheConnection>(); _caches.put(cc.getClazz(), list); } list.add(cc); } } // call Iterator<Entry<Class<?>, List<CacheConnection>>> it = _caches.entrySet().iterator(); Entry<Class<?>, List<CacheConnection>> entry; Class<?> clazz; List<CacheConnection> list; while (it.hasNext()) { entry = it.next(); list = entry.getValue(); clazz = entry.getKey(); try { Method m = clazz.getMethod("init", new Class[] { Config.class, String[].class, Struct[].class }); if (Modifier.isStatic(m.getModifiers())) m.invoke(null, new Object[] { config, _toCacheNames(list), _toArguments(list) }); else SystemOut.print(config.getErrWriter(), "method [init(Config,String[],Struct[]):void] for class [" + clazz.getName() + "] is not static"); } catch (InvocationTargetException e) { e.getTargetException().printStackTrace(); } catch (RuntimeException e) { e.printStackTrace(); } catch (NoSuchMethodException e) { SystemOut.print(config.getErrWriter(), "missing method [public static init(Config,String[],Struct[]):void] for class [" + clazz.getName() + "] "); } catch (Throwable e) { e.printStackTrace(); } } } // Copy Parent caches as readOnly if (hasCS) { Map<String, CacheConnection> ds = configServer.getCacheConnections(); Iterator<Entry<String, CacheConnection>> it = ds.entrySet().iterator(); Entry<String, CacheConnection> entry; while (it.hasNext()) { entry = it.next(); cc = entry.getValue(); if (!caches.containsKey(entry.getKey())) caches.put(entry.getKey(), new ServerCacheConnection(configServer, cc)); } } config.setCaches(caches); }
From source file:lucee.runtime.config.XMLConfigWebFactory.java
/** * @param configServer// w w w . j a v a 2 s. c om * @param config * @param doc */ private static void loadCache(ConfigServerImpl configServer, ConfigImpl config, Document doc, Log log) { boolean hasCS = configServer != null; Map<String, CacheConnection> caches = new HashMap<String, CacheConnection>(); boolean hasAccess = ConfigWebUtil.hasAccess(config, SecurityManagerImpl.TYPE_CACHE); // print.o("LOAD CACHE:"+hasAccess+":"+hasCS); Element eCache = getChildByName(doc.getDocumentElement(), "cache"); // has changes String md5 = getMD5(eCache, hasCS ? configServer.getCacheMD5() : ""); if (md5.equals(config.getCacheMD5())) return; config.setCacheMD5(md5); String[] typeNames = new String[] { "resource", "function", "include", "query", "template", "object", "file", "http", "webservice" }; int[] types = new int[] { ConfigImpl.CACHE_TYPE_RESOURCE, ConfigImpl.CACHE_TYPE_FUNCTION, ConfigImpl.CACHE_TYPE_INCLUDE, ConfigImpl.CACHE_TYPE_QUERY, ConfigImpl.CACHE_TYPE_TEMPLATE, ConfigImpl.CACHE_TYPE_OBJECT, ConfigImpl.CACHE_TYPE_FILE, ConfigImpl.CACHE_TYPE_HTTP, ConfigImpl.CACHE_TYPE_WEBSERVICE }; // default cache for (int i = 0; i < types.length; i++) { String def = eCache.getAttribute("default-" + typeNames[i]); if (hasAccess && !StringUtil.isEmpty(def)) { config.setCacheDefaultConnectionName(types[i], def); } else if (hasCS) { if (eCache.hasAttribute("default-" + typeNames[i])) config.setCacheDefaultConnectionName(types[i], ""); else config.setCacheDefaultConnectionName(types[i], configServer.getCacheDefaultConnectionName(types[i])); } else config.setCacheDefaultConnectionName(+types[i], ""); } // cache connections Element[] eConnections = getChildren(eCache, "connection"); // if(hasAccess) { ClassDefinition cd; String name; CacheConnection cc; //Class cacheClazz; // caches if (hasAccess) for (int i = 0; i < eConnections.length; i++) { Element eConnection = eConnections[i]; name = eConnection.getAttribute("name"); cd = getClassDefinition(eConnection, "", config.getIdentification()); try { Struct custom = toStruct(eConnection.getAttribute("custom")); // Workaround for old EHCache class defintions if (cd.getClassName() != null && cd.getClassName().endsWith(".EHCacheLite")) { cd = new ClassDefinitionImpl(EHCache.class); if (!custom.containsKey("distributed")) custom.setEL("distributed", "off"); if (!custom.containsKey("asynchronousReplicationIntervalMillis")) custom.setEL("asynchronousReplicationIntervalMillis", "1000"); if (!custom.containsKey("maximumChunkSizeBytes")) custom.setEL("maximumChunkSizeBytes", "5000000"); } else if (cd.getClassName() != null && cd.getClassName().endsWith(".extension.io.cache.eh.EHCache")) cd = new ClassDefinitionImpl(EHCache.class); // else cacheClazz = cd.getClazz(); cc = new CacheConnectionImpl(config, name, cd, custom, Caster.toBooleanValue(eConnection.getAttribute("read-only"), false), Caster.toBooleanValue(eConnection.getAttribute("storage"), false)); if (!StringUtil.isEmpty(name)) { caches.put(name.toLowerCase(), cc); } else SystemOut.print(config.getErrWriter(), "missing cache name"); } catch (ClassException ce) { log.error("Cache", ce); //SystemOut.print(config.getErrWriter(), ExceptionUtil.getStacktrace(ce, true)); } catch (BundleException be) { log.error("Cache", be); //SystemOut.print(config.getErrWriter(), ExceptionUtil.getStacktrace(be, true)); } catch (IOException e) { log.error("Cache", e); //SystemOut.print(config.getErrWriter(), ExceptionUtil.getStacktrace(e, true)); } } // } // call static init once per driver { // group by classes final Map<ClassDefinition, List<CacheConnection>> _caches = new HashMap<ClassDefinition, List<CacheConnection>>(); { Iterator<Entry<String, CacheConnection>> it = caches.entrySet().iterator(); Entry<String, CacheConnection> entry; List<CacheConnection> list; while (it.hasNext()) { entry = it.next(); cc = entry.getValue(); if (cc == null) continue;// Jira 3196 ?! list = _caches.get(cc.getClassDefinition()); if (list == null) { list = new ArrayList<CacheConnection>(); _caches.put(cc.getClassDefinition(), list); } list.add(cc); } } // call Iterator<Entry<ClassDefinition, List<CacheConnection>>> it = _caches.entrySet().iterator(); Entry<ClassDefinition, List<CacheConnection>> entry; List<CacheConnection> list; ClassDefinition _cd; while (it.hasNext()) { entry = it.next(); list = entry.getValue(); _cd = entry.getKey(); try { Method m = _cd.getClazz().getMethod("init", new Class[] { Config.class, String[].class, Struct[].class }); if (Modifier.isStatic(m.getModifiers())) m.invoke(null, new Object[] { config, _toCacheNames(list), _toArguments(list) }); else SystemOut.print(config.getErrWriter(), "method [init(Config,String[],Struct[]):void] for class [" + _cd.toString() + "] is not static"); } catch (InvocationTargetException e) { log.error("Cache", e.getTargetException()); //e.getTargetException().printStackTrace(); } catch (RuntimeException e) { log.error("Cache", e); //e.printStackTrace(); } catch (NoSuchMethodException e) { log.error("Cache", "missing method [public static init(Config,String[],Struct[]):void] for class [" + _cd.toString() + "] "); //SystemOut.print(config.getErrWriter(), "missing method [public static init(Config,String[],Struct[]):void] for class [" + _cd.toString() + "] "); } catch (Throwable e) { log.error("Cache", e); //e.printStackTrace(); } } } // Copy Parent caches as readOnly if (hasCS) { Map<String, CacheConnection> ds = configServer.getCacheConnections(); Iterator<Entry<String, CacheConnection>> it = ds.entrySet().iterator(); Entry<String, CacheConnection> entry; while (it.hasNext()) { entry = it.next(); cc = entry.getValue(); if (!caches.containsKey(entry.getKey())) caches.put(entry.getKey(), new ServerCacheConnection(configServer, cc)); } } config.setCaches(caches); }
From source file:org.apache.openjpa.enhance.PCEnhancer.java
private ArrayList<Integer> optimizeIdCopy(Class<?> oidType, FieldMetaData[] fmds) { // collect all object id fields and verify they // a) have a private field // b) do not have a public setter ArrayList<Integer> pkFields = new ArrayList<Integer>(); // build list of primary key fields for (int i = 0; i < fmds.length; i++) { if (!fmds[i].isPrimaryKey()) continue; // optimizing copy with PC type not (yet) supported if (fmds[i].getDeclaredTypeCode() == JavaTypes.PC) { return null; }/*from w ww. j av a 2s.c o m*/ String name = fmds[i].getName(); Field fld = Reflection.findField(oidType, name, false); if (fld == null || Modifier.isPublic(fld.getModifiers())) { return null; } Method setter = Reflection.findSetter(oidType, name, false); if (setter == null || !Modifier.isPublic(setter.getModifiers())) { pkFields.add(i); } else { return null; } } return pkFields.size() > 0 ? pkFields : null; }