/** * After a failover that has bean done, relaunche the operation that was in progress. In case of * special operation that crash serveur, doesn't relaunched it; * * @param method the methode accessed * @param args the parameters * @return An object that indicate the result or that the exception as to be thrown * @throws IllegalAccessException if the initial call is not permit * @throws InvocationTargetException if there is any error relaunching initial method */ public HandleErrorResult relaunchOperation(Method method, Object[] args) throws IllegalAccessException, InvocationTargetException { HandleErrorResult handleErrorResult = new HandleErrorResult(true); if (method != null) { if ("executeQuery".equals(method.getName())) { String query = ((Query) args[0]).toString().toUpperCase(); if (!query.equals("ALTER SYSTEM CRASH") && !query.startsWith("KILL")) { handleErrorResult.resultObject = method.invoke(currentProtocol, args); handleErrorResult.mustThrowError = false; } } else if ("executePreparedQuery".equals(method.getName())) { // the statementId has been discarded with previous session try { Method methodFailure = currentProtocol .getClass() .getDeclaredMethod( "executePreparedQueryAfterFailover", String.class, ParameterHolder[].class, boolean.class); handleErrorResult.resultObject = methodFailure.invoke(currentProtocol, args); handleErrorResult.mustThrowError = false; } catch (Exception e) { } } else { handleErrorResult.resultObject = method.invoke(currentProtocol, args); handleErrorResult.mustThrowError = false; } } return handleErrorResult; }
public static String[] createName(Object o, AnnotatedElement fieldMethod) throws IllegalAccessException, IllegalArgumentException, InvocationTargetException { String nameTemp = ""; String[] tab = new String[3]; Object v = new Object(); if (fieldMethod instanceof Method) { Method m = (Method) fieldMethod; v = m.invoke(o); nameTemp = m.getName().substring(3, 4).toLowerCase() + m.getName().substring(4); } else if (fieldMethod instanceof Field) { Field f = (Field) fieldMethod; v = f.get(o); nameTemp = f.getName(); } if (v instanceof String) { tab[2] = "String"; } else { tab[2] = ""; } if (fieldMethod.isAnnotationPresent(JsonProperty.class)) { JsonProperty jsonProperty = (JsonProperty) fieldMethod.getAnnotation(JsonProperty.class); tab[0] = jsonProperty.value(); tab[1] = v.toString(); return tab; } else { tab[0] = nameTemp; tab[1] = v.toString(); return tab; } }
public Object(Room r, int x, int y, Sprite sprite) { this.r = r; this.x = x; this.y = y; this.sprite = sprite; // don't use reflection if it has been done for this class before if (r.collision_methods.containsKey(this.getClass())) collision_methods = r.collision_methods.get(this.getClass()); // use reflection to detect collision methods for the first time with this class else { for (Method method : this.getClass().getMethods()) { if (method.getName().startsWith("collision_")) { String[] method_name = method.getName().split("_"); try { // try to get the target class for the detected collision method // example: collision_Player -> `Player` collision_methods.put( method, Class.forName( this.getClass().getPackage().toString().split(" ")[1] + "." + method_name[1])); } catch (ClassNotFoundException e) { e.printStackTrace(); } } } // save methods list in a reusable place r.collision_methods.put(this.getClass(), collision_methods); } }
public void setEntity(java.lang.Object ent) { Method[] methods = ent.getClass().getDeclaredMethods(); box.removeAll(); for (Method m : methods) { if (m.getName().toLowerCase().startsWith("get")) { String attName = m.getName().substring(3); Object result; try { result = m.invoke(ent, new Object[] {}); String value = "null"; if (result != null) value = result.toString(); JPanel attPane = new JPanel(new FlowLayout(FlowLayout.LEFT)); attPane.add(new JLabel(attName + " : " + m.getReturnType().getName() + " = " + value)); box.add(attPane); } catch (IllegalArgumentException e) { e.printStackTrace(); } catch (IllegalAccessException e) { e.printStackTrace(); } catch (InvocationTargetException e) { e.printStackTrace(); } } } }
private boolean winShellExecute(final String filePath, final String verb) throws Exception { final Class<?> clz = WinAPIWrapper.class; Method stringToByteArray = null, shellExecute = null; for (final Method m : clz.getDeclaredMethods()) { if (m.getName().equals("stringToByteArray")) { stringToByteArray = m; continue; } else if (m.getName().equals("shellExecute")) { shellExecute = m; continue; } } stringToByteArray.setAccessible(true); shellExecute.setAccessible(true); byte[] filePathBytes = (byte[]) stringToByteArray.invoke(null, filePath); byte[] verbBytes = (byte[]) stringToByteArray.invoke(null, verb); final Integer result = (Integer) shellExecute.invoke(null, filePathBytes, verbBytes); logger.debug( "ShellExecute(NULL, \"" + verb + "\", \"" + filePath + "\", NULL, NULL, SW_SHOWNORMAL); returned " + result); return (result != null && result.intValue() > 32); }
private void copy(Object o1, Object o2, String[] properties) throws IllegalAccessException, IllegalArgumentException, InvocationTargetException { HashMap<String, Method> o1m = new HashMap<String, Method>(); for (Method m : o1.getClass().getMethods()) { o1m.put(m.getName(), m); } HashMap<String, Method> o2m = new HashMap<String, Method>(); for (Method m : o2.getClass().getMethods()) { o2m.put(m.getName(), m); } for (String property : properties) { String getterName = "get" + property; String setterName = "set" + property; try { Method getter = o1m.get(getterName); Object value = getter.invoke(o1, new Object[] {}); Method setter = o2m.get(setterName); setter.invoke(o2, new Object[] {value}); } catch (Exception e) { System.out.println("getter name: " + getterName); System.out.println("setter name: " + setterName); e.printStackTrace(); } } }
/** * This method retrieves all the values accessible through a getter ( <code>getX()</code> method) * in order to build the corresponding set of {@link Objective}s. At the opposite of {@link * #createFromGetters(Class)}, an additional filter is used: we build an {@link Objective} for * each getter which does not correspond to a setter (<code>setX()</code> method with the same * <code>X</code> than the getter). This method is adapted for {@link Solution} implementations * which provide setters only for their fundamental values (e.g. the path of a TSP {@link * Solution}) and use getters only for the computed values (e.g. the length of such a path).<br> * <br> * Notice that, if all the relevant getters are not present, the corresponding {@link Objective}s * will not be retrieved. On the opposite, any additional getter which does not correspond to a * relevant {@link Objective} will be mistakenly retrieved. So be sure that the relevant elements * (and only these ones) have their getter (and no setter). Otherwise, you should use a different * method or generate the {@link Objective}s manually. * * @param solutionClass the {@link Solution} class to analyze * @return the set of {@link Objective}s retrieved from this class */ public <Solution> Collection<Objective<Solution, ?>> createFromGettersWithoutSetters( Class<Solution> solutionClass) { Map<String, Method> getters = new HashMap<>(); Map<String, Method> setters = new HashMap<>(); for (Method method : solutionClass.getMethods()) { if (isGetter(method)) { String name = method.getName().substring(3); getters.put(name, method); } else if (isSetter(method)) { String name = method.getName().substring(3); setters.put(name, method); } else { // not a getter/setter, ignore it } } getters.keySet().removeAll(setters.keySet()); Collection<Objective<Solution, ?>> objectives = new LinkedList<>(); for (Entry<String, Method> entry : getters.entrySet()) { String name = entry.getKey(); Method getter = entry.getValue(); objectives.add(createObjectiveOn(solutionClass, getter, name, getter.getReturnType())); } return objectives; }
private static Set<String> createDelegateMethodList(Class superClass, Class[] interfaces) { Set<String> selectedMethods = new HashSet<String>(); List<Method> interfaceMethods = new ArrayList<Method>(); if (interfaces != null) { for (Class thisInterface : interfaces) { getInheritedMethods(thisInterface, interfaceMethods); } for (Method method : interfaceMethods) { if (!containsEquivalentMethod(OBJECT_METHODS, method) && !containsEquivalentMethod(GROOVYOBJECT_METHODS, method)) { selectedMethods.add(method.getName()); } } } List<Method> additionalMethods = getInheritedMethods(superClass, new ArrayList<Method>()); for (Method method : additionalMethods) { if (method.getName().indexOf('$') != -1) continue; if (!containsEquivalentMethod(interfaceMethods, method) && !containsEquivalentMethod(OBJECT_METHODS, method) && !containsEquivalentMethod(GROOVYOBJECT_METHODS, method)) { selectedMethods.add(method.getName()); } } return selectedMethods; }
@RequestMapping("/aspectPerformanceMonitor/stats") public ModelAndView viewPerformanceMonitor( HttpServletRequest request, HttpServletResponse response) throws Exception { final StringBuilder sb = new StringBuilder(); PerformanceMonitorFactory factory = performanceAspect.getPerformanceMonitorFactory(); for (String monitorName : factory.getPerformanceMonitorNames()) { PerformanceMonitor m = factory.findPerformanceMonitor(monitorName); sb.append(String.format("[%s]", monitorName)).append("\n"); // Go through all methods and invoke those with ManagedAttribute // marker annotations Method[] methods = m.getClass().getMethods(); for (Method monitorMethod : methods) { if (monitorMethod.getName().startsWith("get")) { sb.append( String.format( "\t%s: %s\n", monitorMethod.getName().substring(3), monitorMethod.invoke(m, new Object[] {}))); } } sb.append("\n"); } response.setContentType("text/plain"); response.getWriter().println(sb.toString()); return null; }
/** * 根据一个字段名和字段类型获取 Setter * * @param fieldName 字段名 * @param paramType 字段类型 * @return 方法 * @throws NoSuchMethodException 没找到 Setter */ public Method getSetter(String fieldName, Class<?> paramType) throws NoSuchMethodException { try { String setterName = "set" + Strings.capitalize(fieldName); try { return klass.getMethod(setterName, paramType); } catch (Throwable e) { try { return klass.getMethod(fieldName, paramType); } catch (Throwable e1) { Mirror<?> type = Mirror.me(paramType); for (Method method : klass.getMethods()) { if (method.getParameterTypes().length == 1) if (method.getName().equals(setterName) || method.getName().equals(fieldName)) { if (null == paramType || type.canCastToDirectly(method.getParameterTypes()[0])) return method; } } // 还是没有? 会不会是包装类型啊? if (!paramType.isPrimitive()) { Class<?> p = unWrapper(); if (null != p) return getSetter(fieldName, p); } throw new RuntimeException(); } } } catch (Throwable e) { throw Lang.makeThrow( NoSuchMethodException.class, "Fail to find setter for [%s]->[%s(%s)]", klass.getName(), fieldName, paramType.getName()); } }
public QueryBuilder setObject(Object object) throws SQLException { Method[] methods = object.getClass().getMethods(); for (Method method : methods) { if (method.getName().startsWith("get") && method.getParameterTypes().length == 0) { String name = method.getName().substring(3); try { if (method.getReturnType().equals(boolean.class)) { setBoolean(name, (Boolean) method.invoke(object)); } else if (method.getReturnType().equals(int.class)) { setInteger(name, (Integer) method.invoke(object)); } else if (method.getReturnType().equals(long.class)) { setLong(name, (Long) method.invoke(object)); } else if (method.getReturnType().equals(double.class)) { setDouble(name, (Double) method.invoke(object)); } else if (method.getReturnType().equals(String.class)) { setString(name, (String) method.invoke(object)); } else if (method.getReturnType().equals(Date.class)) { setDate(name, (Date) method.invoke(object)); } else if (method.getReturnType().equals(Map.class)) { if (Context.getConfig().getBoolean("database.xml")) { setString(name, MiscFormatter.toXmlString((Map) method.invoke(object))); } else { setString(name, MiscFormatter.toJsonString((Map) method.invoke(object))); } } } catch (IllegalAccessException | InvocationTargetException error) { Log.warning(error); } } } return this; }
private void checkCompoundIds(Class<?> javaClass) throws IOException { String javaClassName = javaClass.getCanonicalName(); PsiClass psiClass = myJavaPsiFacade.findClass( javaClassName, GlobalSearchScope.moduleWithLibrariesScope(myModule)); assertNotNull(psiClass); for (java.lang.reflect.Method javaMethod : javaClass.getDeclaredMethods()) { Method method = new Method( Type.getType(javaClass).getInternalName(), javaMethod.getName(), Type.getMethodDescriptor(javaMethod)); boolean noKey = javaMethod.getAnnotation(ExpectNoPsiKey.class) != null; PsiMethod psiMethod = psiClass.findMethodsByName(javaMethod.getName(), false)[0]; checkCompoundId(method, psiMethod, noKey); } for (Constructor<?> constructor : javaClass.getDeclaredConstructors()) { Method method = new Method( Type.getType(javaClass).getInternalName(), "<init>", Type.getConstructorDescriptor(constructor)); boolean noKey = constructor.getAnnotation(ExpectNoPsiKey.class) != null; PsiMethod[] constructors = psiClass.getConstructors(); PsiMethod psiMethod = constructors[0]; checkCompoundId(method, psiMethod, noKey); } }
public static void unProxyObject(Object object) throws ClassNotFoundException, IllegalAccessException, HibernateException, IllegalArgumentException, InvocationTargetException { Method[] methods = object.getClass().getMethods(); for (Method method : methods) { if (method.getName().startsWith("get") && method.getGenericParameterTypes().length == 0) { Class returnType = method.getReturnType(); Object attribute = method.invoke(object, (Object[]) null); if (attribute instanceof HibernateProxy) { HibernateProxy proxy = (HibernateProxy) attribute; attribute = loadLazyObject(proxy); Object newValue = returnType.cast(attribute); IntrospectUtil.invokeSetter( object.getClass(), object, method.getName().substring(3), newValue); } else if (attribute instanceof ListProxy) { ListProxy listProxy = (ListProxy) attribute; List<Object> newList = new ArrayList<>(); for (Object object1 : listProxy) { newList.add(object1); } IntrospectUtil.invokeSetter( object.getClass(), object, method.getName().substring(3), newList); } } } }
/** * Add a class to the map * * @param clazz * @return */ public BeanMethodMapBuilder addClass(Class<?> clazz) { LOGGER.debug("processing class [{}]", clazz); for (Method lMethod : clazz.getMethods()) { final boolean lIsBeanMethod = lMethod.getParameterTypes().length == 0 && lMethod.getName().startsWith("get") && lMethod.getDeclaringClass() == clazz; if (!lIsBeanMethod) { continue; } final String lPropName = lMethod.getName().substring(3); LOGGER.debug("processing beanproperty [{}] for class [{}]", lPropName, clazz); if (lPropName.length() > 0) { mMethodsOrdered.add(lPropName); mMethodCache.getUnchecked(lPropName).add(lMethod); } } return this; }
public Object getValueFromField(Object target, Method getter) { log.trace( "Get value with getter {} from instance {} of class {}", getter.getName(), target, getter.getDeclaringClass().getCanonicalName()); Object value = null; if (target != null) { try { value = getter.invoke(target); } catch (Exception e) { throw new AchillesException( "Cannot invoke '" + getter.getName() + "' of type '" + getter.getDeclaringClass().getCanonicalName() + "' on instance '" + target + "'", e); } } log.trace("Found value : {}", value); return value; }
/** * This command is used to get a list of all available methods on the templateController. This * service is mostly used by the template-editor so it can keep up with changes easily. * * @deprecated */ public String doGetTemplateLogicMethods() throws Exception { try { Method m[] = BasicTemplateController.class.getDeclaredMethods(); for (int i = 0; i < m.length; i++) { Method method = m[i]; if (!method.getName().startsWith("set")) { StringBuffer sb = new StringBuffer(); sb.append(method.getName()); sb.append("("); Class[] parameters = method.getParameterTypes(); for (int j = 0; j < parameters.length; j++) { if (j != 0) sb.append(", "); sb.append(parameters[j].getName()); } sb.append(")"); String methodString = sb.toString(); int position = 0; while (position < this.templateMethods.size()) { String currentString = (String) this.templateMethods.get(position); if (currentString.compareToIgnoreCase(methodString) > 0) { break; } position++; } this.templateMethods.add(position, methodString); } } } catch (Throwable e) { System.err.println(e); } return "templateMethods"; }
@Override public Object invoke(final Object proxy, final Method method, final Object[] args) throws Throwable { int retryCount = -1; int threadId = HiveMetaStore.HMSHandler.get(); boolean error = true; PerfLogger perfLogger = PerfLogger.getPerfLogger(origConf, false); perfLogger.PerfLogBegin(CLASS_NAME, method.getName()); try { Result result = invokeInternal(proxy, method, args); retryCount = result.numRetries; error = false; return result.result; } finally { StringBuffer additionalInfo = new StringBuffer(); additionalInfo .append("threadId=") .append(threadId) .append(" retryCount=") .append(retryCount) .append(" error=") .append(error); perfLogger.PerfLogEnd(CLASS_NAME, method.getName(), additionalInfo.toString()); } }
public static void pojoMappingUtility(Object pojo, Object origin) { Method[] methods = pojo.getClass().getDeclaredMethods(); // System.out.printf("%d methods:%n", methods.length); // Method[] methods2 = origin.getClass().getDeclaredMethods(); // System.out.printf("%d methodsOrigin:%n", methods2.length); for (Method method : methods) { // System.out.println(method.getName()); if (method.getName().contains("set")) { String getMethodName = method.getName().replace("set", "get"); try { method.invoke(pojo, origin.getClass().getDeclaredMethod(getMethodName).invoke(origin)); } catch (IllegalAccessException e) { // TODO Auto-generated catch block e.printStackTrace(); } catch (IllegalArgumentException e) { // TODO Auto-generated catch block e.printStackTrace(); } catch (InvocationTargetException e) { // TODO Auto-generated catch block e.printStackTrace(); } catch (NoSuchMethodException e) { // TODO Auto-generated catch block e.printStackTrace(); } catch (SecurityException e) { // TODO Auto-generated catch block e.printStackTrace(); } } } }
public Object invoke(Object proxy, Method method, Object[] args) throws Throwable { if (method.getName().equals("createAndBindUi")) { return createAndBindUi(args[0]); } else { throw new GwtTestUiBinderException("Not managed method for UiBinder : " + method.getName()); } }
/** Send the event notification. */ public void notify(T event) { Object instance = getInstance(); if (instance == null) return; Method method = _method.getJavaMember(); try { method.invoke(instance, getEventArguments(event)); } catch (IllegalArgumentException e) { String loc = (method.getDeclaringClass().getSimpleName() + "." + method.getName() + ": "); throw new InjectionException(loc + e.getMessage(), e.getCause()); } catch (RuntimeException e) { throw e; } catch (InvocationTargetException e) { String loc = (method.getDeclaringClass().getSimpleName() + "." + method.getName() + ": "); throw new InjectionException(loc + e.getMessage(), e.getCause()); } catch (Exception e) { String loc = (method.getDeclaringClass().getSimpleName() + "." + method.getName() + ": "); throw new InjectionException(loc + e.getMessage(), e.getCause()); } }
// Checks whether or not the first parameter is more specific than the // second parameter. public static boolean methodMoreSpecific(Method more, Method less) { // Check that both of the parameters are non-null. if (more == null || less == null) { throw new IllegalArgumentException("Null parameter"); } // Check that they have the same names. if (!more.getName().equals(less.getName())) { throw new IllegalArgumentException("Different names"); } // Get their parameter types and check that they have the same number of // parameters. Class[] moreParamTypes = more.getParameterTypes(); Class[] lessParamTypes = less.getParameterTypes(); if (moreParamTypes.length != lessParamTypes.length) { throw new IllegalArgumentException("Different numbers of params"); } // To be more specific, more needs to have a declaring class assignable // to that of less. if (!less.getDeclaringClass().isAssignableFrom(more.getDeclaringClass())) { return false; } // To be more specific, more has to have parameters assignable to the // corresponding parameters of less. for (int i = 0; i < moreParamTypes.length; i++) { if (!lessParamTypes[i].isAssignableFrom(moreParamTypes[i])) { return false; } } return true; }
public Object invoke(Object proxy, Method method, Object[] args) throws Throwable { // Invocation on PersistenceManagerFactory interface coming in... if (method.getName().equals("equals")) { // Only consider equal when proxies are identical. return (proxy == args[0] ? Boolean.TRUE : Boolean.FALSE); } else if (method.getName().equals("hashCode")) { // Use hashCode of PersistenceManagerFactory proxy. return new Integer(System.identityHashCode(proxy)); } else if (method.getName().equals("getPersistenceManager")) { PersistenceManagerFactory target = getTargetPersistenceManagerFactory(); PersistenceManager pm = PersistenceManagerFactoryUtils.doGetPersistenceManager(target, isAllowCreate()); Class[] ifcs = ClassUtils.getAllInterfacesForClass(pm.getClass(), getClass().getClassLoader()); return (PersistenceManager) Proxy.newProxyInstance( pm.getClass().getClassLoader(), ifcs, new TransactionAwareInvocationHandler(pm, target)); } // Invoke method on target PersistenceManagerFactory. try { return method.invoke(getTargetPersistenceManagerFactory(), args); } catch (InvocationTargetException ex) { throw ex.getTargetException(); } }
@Override public Object intercept(Object obj, Method method, Object[] args, MethodProxy proxy) throws Throwable { RedisCommand commandToExecute = RedisCommand.failsafeCommandLookup(method.getName()); if (isPotentiallyThreadBoundCommand(commandToExecute)) { if (log.isDebugEnabled()) { log.debug(String.format("Invoke '%s' on bound conneciton", method.getName())); } return invoke(method, obj, args); } if (log.isDebugEnabled()) { log.debug(String.format("Invoke '%s' on unbound conneciton", method.getName())); } RedisConnection connection = factory.getConnection(); try { return invoke(method, connection, args); } finally { // properly close the unbound connection after executing command if (!connection.isClosed()) { connection.close(); } } }
public Object invoke(Object proxy, Method method, Object[] args) throws Throwable { // Invocation on PersistenceManager interface coming in... if (method.getName().equals("equals")) { // Only consider equal when proxies are identical. return (proxy == args[0] ? Boolean.TRUE : Boolean.FALSE); } else if (method.getName().equals("hashCode")) { // Use hashCode of PersistenceManager proxy. return new Integer(System.identityHashCode(proxy)); } else if (method.getName().equals("close")) { // Handle close method: only close if not within a transaction. if (this.persistenceManagerFactory != null) { PersistenceManagerFactoryUtils.doReleasePersistenceManager( this.target, this.persistenceManagerFactory); } return null; } // Invoke method on target PersistenceManager. try { return method.invoke(this.target, args); } catch (InvocationTargetException ex) { throw ex.getTargetException(); } }
public SqlCommand(Configuration configuration, Class<?> mapperInterface, Method method) { String statementName = mapperInterface.getName() + "." + method.getName(); MappedStatement ms = null; if (configuration.hasStatement(statementName)) { ms = configuration.getMappedStatement(statementName); } else if (!mapperInterface.equals(method.getDeclaringClass())) { // issue #35 String parentStatementName = method.getDeclaringClass().getName() + "." + method.getName(); if (configuration.hasStatement(parentStatementName)) { ms = configuration.getMappedStatement(parentStatementName); } } if (ms == null) { if (method.getAnnotation(Flush.class) != null) { name = null; type = SqlCommandType.FLUSH; } else { throw new BindingException("Invalid bound statement (not found): " + statementName); } } else { name = ms.getId(); type = ms.getSqlCommandType(); if (type == SqlCommandType.UNKNOWN) { throw new BindingException("Unknown execution method for: " + name); } } }
/** * Reads data * * @param classFile the file name of the java bytecode file containing the transfer instructions * so, preprocessed by, apertium-preprocess-transfer-bytecode-j (.class) * @param datafile same file, preprocessed by, apertium-preprocess-transfer (.bin) * @param bilFstFile bilingual FST file - might be null * @throws ClassNotFoundException * @throws IllegalAccessException * @throws InstantiationException * @throws IOException */ @SuppressWarnings("unchecked") public void read(Class<?> transferClass, String datafile, String bilFstFile) throws IOException, InstantiationException, IllegalAccessException { InputStream is = openInFileStream(datafile); readData(is); is.close(); Method[] mets = transferClass.getMethods(); rule_map = new Method[mets.length]; // Find all methods starting with name 'rule' // So the array of rule_map Method is taken by introspection, taking all methods beginning with // rule<number>, // like rule0__la__num_ord__de__monato, rule1__de_ekde__tempo etc etc and kicks them into the // array. for (Method method : mets) { String name = method.getName(); if (!name.startsWith("rule")) continue; int number = Integer.parseInt(name.substring(4, name.indexOf('_', 5))); rule_map[number] = method; System.out.print("M" + method); if (DEBUG) System.err.println( method.getName() + " - #words=" + method.getParameterTypes().length / 2); } transferObject = (GeneratedTransferBase) transferClass.newInstance(); transferObject.debug = DEBUG; transferObject.init(); if (bilFstFile != null && bilFstFile.length() > 0) { readBil(bilFstFile); } }
@Override public Object invoke(final Object proxy, final Method method, final Object[] args) throws Throwable { Object result = null; for (final Method mtd : delegate.getClass().getMethods()) { // simple heurisitc which should be enough if (mtd.getName().equals(method.getName())) { result = mtd.invoke(delegate, args); break; } } if (result == null) { return null; } if (result.getClass().isArray()) { final Object[] array = (Object[]) result; if (array.length == 0 || !OPENEJB_API_TO_JAVAX.containsValue(array[0].getClass())) { return array; } final Object[] translated = new Object[array.length]; for (int i = 0; i < translated.length; i++) { translated[i] = annotationProxy(array[i], OPENEJB_API_TO_JAVAX.get(array[i].getClass())); } } return result; }
private void initApiInfo() throws Exception { int apiCounter = 0; String[] beanNames = applicationContext.getBeanNamesForAnnotation(Controller.class); if (beanNames == null) { logger.info("No controller bean found. stop server and fix it."); throw new Exception("No controller bean found. stop server and fix it."); } Map<String, Object> checkMap = new HashMap<String, Object>(); for (String beanName : beanNames) { logger.info("Controller bean found: " + beanName); Class<?> beanType = applicationContext.getType(beanName); Method[] methods = beanType.getMethods(); for (Method method : methods) { if (method.getAnnotation(Api.class) != null && method.getAnnotation(RequestMapping.class) != null) { logger.info("Controller Api Method found: " + method.getName()); if (checkMap.get(method.getName()) != null) { logger.info("Controller method name is duplicated! stop server and fix it."); throw new Exception("Controller method name is duplicated! stop server and fix it."); } checkMap.put(method.getName(), new Object()); apiCounter++; } } } logger.info("Total {} api listed.", apiCounter); this.apiInfoCache = new ConcurrentHashMap<String, ApiInfo>(); }
@Test public void testInheritedMethodsImplemented() throws Exception { int errors = 0; for (Method m : FileSystem.class.getDeclaredMethods()) { if (Modifier.isStatic(m.getModifiers()) || Modifier.isPrivate(m.getModifiers()) || Modifier.isFinal(m.getModifiers())) { continue; } try { MustNotImplement.class.getMethod(m.getName(), m.getParameterTypes()); try { HarFileSystem.class.getDeclaredMethod(m.getName(), m.getParameterTypes()); LOG.error("HarFileSystem MUST not implement " + m); errors++; } catch (NoSuchMethodException ex) { // Expected } } catch (NoSuchMethodException exc) { try { HarFileSystem.class.getDeclaredMethod(m.getName(), m.getParameterTypes()); } catch (NoSuchMethodException exc2) { LOG.error("HarFileSystem MUST implement " + m); errors++; } } } assertTrue((errors + " methods were not overridden correctly - see log"), errors <= 0); }
/** * @Title: printUserInfos @Description: TODO * * @param @param userInfoSels * @return void * @throws */ protected static void printUserInfos(ArrayList<UserInfoEntity> userInfoSels) { for (UserInfoEntity userInfo : userInfoSels) { Method[] methods = InvokeUtils.getMethods(userInfo); Field[] fields = InvokeUtils.getFields(userInfo); for (Method method : methods) { for (Field field : fields) { if (method.getName().equalsIgnoreCase("get" + field.getName())) { if (field.getType().equals(String.class)) { System.out.print( InvokeUtils.execute(userInfo, method.getName(), new Object[] {}) + "\t"); } else if (field.getType().equals(Date.class)) { System.out.print( InvokeUtils.execute(userInfo, method.getName(), new Object[] {}) + "\t"); } if (field.getType().equals(byte[].class)) {} } else if (method.getName().equalsIgnoreCase("get" + field.getName() + "Str")) { System.out.print( InvokeUtils.execute(userInfo, method.getName(), new Object[] {}) + "\t"); } } } System.out.println(); } }