@SuppressWarnings("unchecked") private void useLoggingInfoInsertValue( LoggingInfo loggingInfo, Object target, Annotation annotation, Method method) { if (annotation instanceof UseLoggingInfoConvertor) { UseLoggingInfoConvertor useLoggingInfo = (UseLoggingInfoConvertor) annotation; boolean f = false; for (PublisherType publisherType : useLoggingInfo.publisherTypes()) { if (publisherType.equals(loggingInfo.getPublisherType())) { f = true; break; } } if (f) { Class<? extends LoggingInfoConvertor<?>> convertorClass = useLoggingInfo.convertor(); LoggingInfoConvertor<Object> convertor = null; try { convertor = (LoggingInfoConvertor<Object>) convertorClass.newInstance(); } catch (Exception e) { if (log.isErrorEnabled()) { log.error("LoggingInfo convertor instantiation was failed!", e); } return; } if (convertor != null) { Object convertedValue = null; try { convertedValue = convertor.convert(loggingInfo); } catch (Exception e) { if (log.isErrorEnabled()) { log.error( "LoggingInfo convertation was failed! Null value used as convertation result!", e); } convertedValue = null; } try { method.invoke(target, convertedValue); } catch (Exception e) { if (log.isErrorEnabled()) { log.error( "Method invoke was failed! Please, check that method '" + method.toGenericString() + "' annotated correctly!", e); } } } } } }
private static String getMethodRequestMapping(Method method) { RequestMapping annot = AnnotationUtils.findAnnotation(method, RequestMapping.class); if (annot == null) { throw new IllegalArgumentException("No @RequestMapping on: " + method.toGenericString()); } if (ObjectUtils.isEmpty(annot.value()) || StringUtils.isEmpty(annot.value()[0])) { return "/"; } if (annot.value().length > 1 && logger.isWarnEnabled()) { logger.warn("Multiple paths on method " + method.toGenericString() + ", using first one"); } return annot.value()[0]; }
public static void main(String[] args) throws Exception { GenericeSubClass<Long> subClass = new GenericeSubClass<>(); subClass.method(); Method method = GenericeSuperClass.class.getMethod("method", new Class<?>[] {Object.class}); System.out.println(method.toGenericString()); System.out.println(method.toString()); }
/** * @param method * @return */ public static boolean isFluent(final Method method) { final Class<?> methodType = method.getDeclaringClass(); final Class<?> returnType = method.getReturnType(); if (returnType == null || returnType == void.class) { return false; } if (areAssignable(methodType, returnType)) { // Returning this would be allowed. // However, we should guard against methods that may actually want to return a field // that is the same type as itself. final Fluent fluent = method.getAnnotation(Fluent.class); if (fluent != null) { return fluent.value(); } if (method.getParameterTypes().length > 0) { // check if there is a single parameter type which is also compatible, // and throw an error telling the user that they must specify @Fluent(true) or // @Fluent(false) // Because the method signature is ambiguous if (areAssignable(methodType, method.getParameterTypes()[0])) { throw new NotConfiguredCorrectly( "Method " + method.toGenericString() + " in " + methodType + " has ambiguous return type; cannot tell if this method is Fluent. Please annotate " + "this method with @Fluent(true) if the method is supposed to `return this;` or " + "use @Fluent(false) if this method is supposed to return the first parameter."); } } return true; } return false; }
public int getPositionInVirtualTable( Pointer<Pointer<?>> pVirtualTable, Method method, NativeLibrary library) { // Pointer<?> typeInfo = pVirtualTable.get(1); int methodsOffset = 0; // library.isMSVC() ? 0 : -2;///2; String className = getCPPClassName(method.getDeclaringClass()); for (int iVirtual = 0; ; iVirtual++) { Pointer<?> pMethod = pVirtualTable.get(methodsOffset + iVirtual); String virtualMethodName = pMethod == null ? null : library.getSymbolName(pMethod.getPeer()); // System.out.println("#\n# At index " + methodsOffset + " + " + iVirtual + " of vptr for // class " + className + ", found symbol " + Long.toHexString(pMethod.getPeer()) + " = '" + // virtualMethodName + "'\n#"); if (virtualMethodName == null) { if (debug) info("\tVtable(" + className + ")[" + iVirtual + "] = null"); return -1; } try { MemberRef mr = library.parseSymbol(virtualMethodName); if (debug) info("\tVtable(" + className + ")[" + iVirtual + "] = " + virtualMethodName + " = " + mr); if (mr != null && mr.matchesSignature(method)) return iVirtual; else if (library.isMSVC() && !mr.matchesEnclosingType(method)) break; // no NULL terminator in MSVC++ vtables, so we have to guess when we've reached the // end } catch (Demangler.DemanglingException ex) { BridJ.warning( "Failed to demangle '" + virtualMethodName + "' during inspection of virtual table for '" + method.toGenericString() + "' : " + ex); } } return -1; }
// @Test public void methodName() throws NoSuchMethodException { Method[] toString = Map.class.getDeclaredMethods(); for (Method m : toString) { logger.info("methodObject:{}", m); logger.info("methodObject:{}", m.toGenericString()); } }
static { try { Map<String, Method> orderedMethods = new TreeMap<String, Method>(); for (Method m : MBeanServerConnection.class.getDeclaredMethods()) { orderedMethods.put(m.toGenericString(), m); } Method[] methods = orderedMethods.values().toArray(new Method[orderedMethods.size()]); Map<String, Method> asynchMethods = new TreeMap<String, Method>(); for (Method asynchMethod : AsynchJMXResponseListener.class.getDeclaredMethods()) { asynchMethods.put(asynchMethod.getName(), asynchMethod); } Map<Method, Byte> m2k = new HashMap<Method, Byte>(methods.length); Map<Byte, Method> k2m = new HashMap<Byte, Method>(methods.length); Map<Byte, Method> k2am = new HashMap<Byte, Method>(methods.length); for (int i = 0; i < methods.length; i++) { m2k.put(methods[i], (byte) i); k2m.put((byte) i, methods[i]); Method asynchMethod = asynchMethods.get(methods[i].getName() + "Response"); if (asynchMethod == null) throw new RuntimeException( "Failed to find asynch handler for [" + methods[i].toGenericString() + "]", new Throwable()); k2am.put((byte) i, asynchMethod); } methodToKey = Collections.unmodifiableMap(m2k); keyToMethod = Collections.unmodifiableMap(k2m); keyToAsynchMethod = Collections.unmodifiableMap(k2am); } catch (Exception ex) { throw new RuntimeException(ex); } }
/** * Resolve current method generic return type to a {@link GenericMetadataSupport}. * * @param method Method to resolve the return type. * @return {@link GenericMetadataSupport} representing this generic return type. */ public GenericMetadataSupport resolveGenericReturnType(Method method) { Type genericReturnType = method.getGenericReturnType(); // logger.log("Method '" + method.toGenericString() + "' has return type : " + // genericReturnType.getClass().getInterfaces()[0].getSimpleName() + " : " + genericReturnType); if (genericReturnType instanceof Class) { return new NotGenericReturnTypeSupport(genericReturnType); } if (genericReturnType instanceof ParameterizedType) { return new ParameterizedReturnType( this, method.getTypeParameters(), (ParameterizedType) method.getGenericReturnType()); } if (genericReturnType instanceof TypeVariable) { return new TypeVariableReturnType( this, method.getTypeParameters(), (TypeVariable) genericReturnType); } throw new MockitoException( "Ouch, it shouldn't happen, type '" + genericReturnType.getClass().getCanonicalName() + "' on method : '" + method.toGenericString() + "' is not supported : " + genericReturnType); }
@Override public Object answer(InvocationOnMock invocation) throws Throwable { Method calledMethod = invocation.getMethod(); String signature = calledMethod.toGenericString(); throw new RuntimeException(signature + " is not mocked!"); }
public Set<String> getISNodeMethodsNames(boolean fullQualified) throws FileNotFoundException, IOException { Set<String> set = new HashSet<String>(); for (Method method : org.jetbrains.mps.openapi.model.SNode.class.getMethods()) { set.add((fullQualified ? method.toGenericString() : method.getName())); } return set; }
@Override public String toString() { return format( "HandlerMethod %s.%s for payload type %s: %s", method.getDeclaringClass().getSimpleName(), method.getName(), getPayloadType().getSimpleName(), method.toGenericString()); }
private static <T> Object invoke(T actual, Method getter) { try { return getter.invoke(actual); } catch (Exception e) { AssertionError error = new AssertionError(String.format("Exception invoking %s", getter.toGenericString())); error.initCause(e); throw error; } }
public org.atemsource.atem.api.method.Method create(Method method) { ParameterTypeImpl parameterType = new ParameterTypeImpl(); parameterType.setCode(method.toGenericString()); for (int index = 0; index < method.getParameterTypes().length; index++) { Attribute<?, ?> parameter = create(parameterType, index, method); if (parameter != null) { parameterType.addAttribute(parameter); } } MethodImpl atemMethod = new MethodImpl(); atemMethod.setParameterType(parameterType); atemMethod.setReturnType(entityTypeRepository.getType(method.getReturnType())); atemMethod.setJavaMethod(method); atemMethod.setEntityType(entityTypeRepository.getEntityType(method.getDeclaringClass())); atemMethod.setCode(method.toGenericString()); parameterType.setMethod(atemMethod); return atemMethod; }
private Object getValue(Object event) throws InvalidEventException { try { return method.invoke(event); } catch (Exception e) { throw new InvalidEventException( firstNonNull(e.getCause(), e), "Unable to get value of event field %s: Exception occurred while invoking [%s]", name, method.toGenericString()); } }
/** * Finds and returns the valid target {@link JSONRequestHandler} annotated methods in the passed * class. * * @param clazz the class to inspect * @return a collection of valid json request methods */ public static Collection<Method> getTargetMethods(Class<?> clazz) { Map<String, Method> mappedMethods = new HashMap<String, Method>(); for (Method m : clazz.getMethods()) { JSONRequestHandler jsonHandler = m.getAnnotation(JSONRequestHandler.class); if (jsonHandler != null) { Class<?>[] paramTypes = m.getParameterTypes(); if (paramTypes.length < 1 || !JSONRequest.class.equals(paramTypes[0]) || containsPrimitives(paramTypes)) { LOG.warn("Invalid @JSONRequestHandler annotated method [{}]", m.toGenericString()); continue; } mappedMethods.put(m.getName() + "(" + StringHelper.getMethodDescriptor(m) + ")", m); // Class<?>[] paramTypes = m.getParameterTypes(); // if(paramTypes.length!=1 || !JSONRequest.class.equals(paramTypes[0])) { // LOG.warn("Invalid @JSONRequestHandler annotated method [{}]", m.toGenericString()); // continue; // } // mappedMethods.put(m.getName(), m); } } for (Method m : clazz.getDeclaredMethods()) { JSONRequestHandler jsonHandler = m.getAnnotation(JSONRequestHandler.class); if (jsonHandler != null) { Class<?>[] paramTypes = m.getParameterTypes(); if (paramTypes.length < 1 || !JSONRequest.class.equals(paramTypes[0])) { LOG.warn("Invalid @JSONRequestHandler annotated method [{}]", m.toGenericString()); continue; } mappedMethods.put(m.getName() + "(" + StringHelper.getMethodDescriptor(m) + ")", m); // Class<?>[] paramTypes = m.getParameterTypes(); // if(paramTypes.length!=1 || !JSONRequest.class.equals(paramTypes[0])) { // LOG.warn("Invalid @JSONRequestHandler annotated method [{}]", m.toGenericString()); // continue; // } // mappedMethods.put(m.getName(), m); } } return mappedMethods.values(); }
private void checkOverrideMethods(Class<?> clazz) throws Exception { boolean fail = false; for (Method m : clazz.getMethods()) { int mods = m.getModifiers(); if (Modifier.isStatic(mods) || Modifier.isFinal(mods) || m.isSynthetic()) { continue; } Class<?> declaringClass = m.getDeclaringClass(); if (declaringClass != clazz && declaringClass != Object.class) { System.err.println( "method is not overridden by " + clazz.getName() + ": " + m.toGenericString()); fail = true; } } assertFalse(clazz.getName() + " does not override some methods; see log above", fail); }
private String errorMessage(Method method, Object[] javaArgs) { StringBuilder m = new StringBuilder("Couldn't invoke ") .append(method.toGenericString()) .append(" with ") .append(Utils.join(javaArgs, ",")) .append(" ("); boolean comma = false; for (Object javaArg : javaArgs) { if (comma) m.append(","); m.append(javaArg.getClass()); comma = true; } m.append(")"); return m.toString(); }
/** Removed methods cache from original code. */ protected static Collection<Method> getMethods(Class<?> clazz) { Collection<Method> methods = ReflectUtil.getMethods(clazz); Iterator<Method> iterator = methods.iterator(); while (iterator.hasNext()) { Method method = iterator.next(); if (!method.isAnnotationPresent(SpringBean.class)) { iterator.remove(); } else { // If the method isn't public, try to make it accessible if (!method.isAccessible()) { try { method.setAccessible(true); } catch (SecurityException se) { throw new StripesRuntimeException( "Method " + clazz.getName() + "." + method.getName() + "is marked " + "with @SpringBean and is not public. An attempt to call " + "setAccessible(true) resulted in a SecurityException. Please " + "either make the method public or modify your JVM security " + "policy to allow Stripes to setAccessible(true).", se); } } // Ensure the method has only the one parameter if (method.getParameterTypes().length != 1) { throw new StripesRuntimeException( "A method marked with @SpringBean must have exactly one parameter: " + "the bean to be injected. Method [" + method.toGenericString() + "] has " + method.getParameterTypes().length + " parameters."); } } } return methods; }
@SuppressWarnings("unchecked") public PropertyMd(PropertyDescriptor prop, Class[] mandatoryAnnotations) throws InvalidEntityBeanPropertyException { this(prop); // check if all the annotations mentioned in mandatoryAnnotations list are present on the getter // method Method getterMethod = prop.getReadMethod(); for (Class annotation : mandatoryAnnotations) { if (getterMethod.getAnnotation(annotation) == null) { throw new InvalidEntityBeanPropertyException( "Attempting to create an " + this.getClass().getName() + " for a property which doesn't have " + annotation.getName() + " annotation: " + getterMethod.toGenericString()); } } }
@Override public void processSimEvent(SimEvent event) { Object[] requestedParameters = event.getParameters(); Method requestedMethod = this.lookupMethodForSimEvent(event); // this is consistent with the behavior pattern set by SimEntityBase if (null == requestedMethod) { return; } try { Level l = Level.FINEST; if (LOG.isLoggable(l)) { LOG.log( l, LogString.format( eventList, "Will invoke " + requestedMethod.toGenericString() + " on " + this.toString() + " which was found under the annotation sim event name \'" + event.getEventName() + "\'")); } requestedMethod.invoke(this, requestedParameters); } catch (IllegalAccessException ex) { throw new RuntimeException(ex); } catch (IllegalArgumentException ex) { throw new RuntimeException(ex); } catch (InvocationTargetException ex) { throw new RuntimeException(ex); } }
private static void validate(Method method, ParameterResolver[] parameterResolvers) { for (int i = 0; i < method.getParameterTypes().length; i++) { if (parameterResolvers[i] == null) { throw new UnsupportedHandlerException( format( "On method %s, parameter %s is invalid. It is not of any format supported by a provided" + "ParameterValueResolver.", method.toGenericString(), i + 1), method); } } /* special case: methods with equal signature on EventListener must be rejected, because it interferes with the Proxy mechanism */ if (method.getName().equals("handle") && Arrays.equals(method.getParameterTypes(), new Class[] {EventMessage.class})) { throw new UnsupportedHandlerException( String.format( "Event Handling class %s contains method %s that has a naming conflict with a " + "method on the EventHandler interface. Please rename the method.", method.getDeclaringClass().getSimpleName(), method.getName()), method); } }
@Override public int compare(final Method m1, final Method m2) { return m1.toGenericString().compareTo(m2.toGenericString()); }
public void test_parameterLessMethods() throws Exception { this.addNodeById("8150353254540236423"); this.addNodeById("8150353254540236549"); this.addNodeById("4195712261513743410"); SNode sNode = SNodeOperations.cast( this.getNodeById("8150353254540236424"), "jetbrains.mps.baseLanguage.structure.BlockStatement"); StatCountNodeReadAccessInEditorListener listener = new StatCountNodeReadAccessInEditorListener(sNode); NodeReadAccessCasterInEditor.setCellBuildNodeReadAccessListener(listener); Map<String, Integer> prevCheck = this.getReadAccessMap(); Map<String, Integer> currentCheckChanged = new HashMap<String, Integer>(); Map<String, Integer> currentCheckNew = new HashMap<String, Integer>(); Map<String, Exception> currentException = new HashMap<String, Exception>(); Set<String> contractMethods = this.getISNodeMethodsNames(false); List<Method> methods = new ArrayList<Method>(); methods.addAll(Arrays.asList(SNode.class.getMethods())); // 'delete' must be last checked method for (int i = 0; i < methods.size(); i++) { if (methods.get(i).getName().equals("delete") && i != (methods.size() - 1)) { Collections.swap(methods, i, (methods.size() - 1)); break; } } for (Method method : methods) { if ((method.getModifiers() & (Modifier.PUBLIC | Modifier.PROTECTED)) > 0 && method.getParameterAnnotations().length == 0 && contractMethods.contains(method.getName())) { try { method.invoke(sNode); } catch (Exception e) { currentException.put(method.getName(), e); } finally { Pair<Integer, List<String>> pair = listener.getResults(); listener.resetResults(); if (prevCheck.containsKey(method.toGenericString())) { if (!(this.isReadsCountUnChanged( prevCheck.get(method.toGenericString()).intValue(), pair.o1.intValue()))) { currentCheckChanged.put(method.toGenericString(), pair.o1); } } else { currentCheckNew.put(method.toGenericString(), pair.o1); } } } } StringBuilder error = new StringBuilder("Some changes occured in read access in SNode after last check:"); error.append(System.getProperty("line.separator")); error.append("Methods with changed number of read access:"); error.append(System.getProperty("line.separator")); for (String s : currentCheckChanged.keySet()) { error.append( "In method " + s + " current count " + currentCheckChanged.get(s) + ", prev count " + prevCheck.get(s)); error.append(System.getProperty("line.separator")); } error.append(System.getProperty("line.separator")); error.append("New methods with read access:"); error.append(System.getProperty("line.separator")); for (String s : currentCheckNew.keySet()) { error.append("In method " + s + " read count " + currentCheckNew.get(s)); error.append(System.getProperty("line.separator")); } error.append(System.getProperty("line.separator")); error.append("Methods ended with exception:"); error.append(System.getProperty("line.separator")); for (String s : currentException.keySet()) { error.append( "In method " + s + " was exception " + Arrays.toString(currentException.get(s).getStackTrace())); error.append(System.getProperty("line.separator")); } Assert.assertTrue( error.toString(), currentCheckChanged.isEmpty() && currentCheckNew.isEmpty() && currentException.isEmpty()); }
@Override protected void registerNativeMethod( Class<?> type, NativeLibrary typeLibrary, Method method, NativeLibrary methodLibrary, Builder builder, MethodCallInfoBuilder methodCallInfoBuilder) throws FileNotFoundException { int modifiers = method.getModifiers(); boolean isCPPClass = CPPObject.class.isAssignableFrom(method.getDeclaringClass()); // Annotation[][] anns = method.getParameterAnnotations(); if (!isCPPClass) { super.registerNativeMethod( type, typeLibrary, method, methodLibrary, builder, methodCallInfoBuilder); return; } MethodCallInfo mci = methodCallInfoBuilder.apply(method); Virtual va = method.getAnnotation(Virtual.class); if (va == null) { Symbol symbol = methodLibrary.getSymbol(method); mci.setForwardedPointer(symbol == null ? 0 : symbol.getAddress()); if (mci.getForwardedPointer() == 0) { assert error( "Method " + method.toGenericString() + " is not virtual but its address could not be resolved in the library."); return; } if (Modifier.isStatic(modifiers)) { builder.addFunction(mci); if (debug) info("Registering " + method + " as function or static C++ method " + symbol.getName()); } else { builder.addFunction(mci); if (debug) info("Registering " + method + " as C++ method " + symbol.getName()); } } else { if (Modifier.isStatic(modifiers)) { warning( "Method " + method.toGenericString() + " is native and maps to a function, but is not static."); } int theoreticalVirtualIndex = va.value(); int theoreticalAbsoluteVirtualIndex = theoreticalVirtualIndex < 0 ? -1 : getAbsoluteVirtualIndex(method, theoreticalVirtualIndex, type); int absoluteVirtualIndex; Pointer<Pointer<?>> pVirtualTable = isCPPClass && typeLibrary != null ? (Pointer) pointerToAddress(getVirtualTable(type, typeLibrary), Pointer.class) : null; if (pVirtualTable == null) { if (theoreticalAbsoluteVirtualIndex < 0) { error( "Method " + method.toGenericString() + " is virtual but the virtual table of class " + type.getName() + " was not found and the virtual method index is not provided in its @Virtual annotation."); return; } absoluteVirtualIndex = theoreticalAbsoluteVirtualIndex; } else { int guessedAbsoluteVirtualIndex = getPositionInVirtualTable(pVirtualTable, method, typeLibrary); if (guessedAbsoluteVirtualIndex < 0) { if (theoreticalAbsoluteVirtualIndex < 0) { error( "Method " + method.toGenericString() + " is virtual but its position could not be found in the virtual table."); return; } else { absoluteVirtualIndex = theoreticalAbsoluteVirtualIndex; } } else { if (theoreticalAbsoluteVirtualIndex >= 0 && guessedAbsoluteVirtualIndex != theoreticalAbsoluteVirtualIndex) { warning( "Method " + method.toGenericString() + " has @Virtual annotation indicating virtual index " + theoreticalAbsoluteVirtualIndex + ", but analysis of the actual virtual table rather indicates it has index " + guessedAbsoluteVirtualIndex + " (using the guess)"); } absoluteVirtualIndex = guessedAbsoluteVirtualIndex; } } mci.setVirtualIndex(absoluteVirtualIndex); if (debug) info( "Registering " + method.toGenericString() + " as virtual C++ method with absolute virtual table index = " + absoluteVirtualIndex); builder.addVirtualMethod(mci); } }
public void map(LoggingInfo loggingInfo, Object target) { LoggingCustomData loggingCustomData = loggingInfo.getLoggingCustomData(); Class<?> targetClass = target.getClass(); Class<?> klass = targetClass; Map<Annotation, Method> customAnnotationMethodMap = new HashMap<Annotation, Method>(); Map<Annotation, Method> annotationMethodMap = new HashMap<Annotation, Method>(); while (klass != Object.class) { for (final Method method : klass.getDeclaredMethods()) { for (final Annotation annotation : method.getAnnotations()) { if (loggingCustomData != null && CUSTOM_ANNOTATIONS.contains(annotation.annotationType())) { if (method.getParameterTypes().length != 1) { if (log.isWarnEnabled()) { log.warn( "Please, check that annotated method '" + method.toGenericString() + "' is setter method!"); } } customAnnotationMethodMap.put(annotation, method); } if (MAPPING_ANNOTATIONS.contains(annotation.annotationType())) { if (method.getParameterTypes().length != 1) { if (log.isWarnEnabled()) { log.warn( "Please, check that annotated method '" + method.toGenericString() + "' is setter method!"); } } annotationMethodMap.put(annotation, method); } } } klass = klass.getSuperclass(); } for (Entry<Annotation, Method> entry : annotationMethodMap.entrySet()) { Annotation annotation = entry.getKey(); Method method = entry.getValue(); if (SetterIncomingTime.class.equals(annotation.annotationType())) { insertValue(loggingInfo, target, annotation, method, loggingInfo.getIncomingMessageTime()); } if (SetterOutcomingTime.class.equals(annotation.annotationType())) { insertValue(loggingInfo, target, annotation, method, loggingInfo.getOutcomingMessageTime()); } if (SetterInputName.class.equals(annotation.annotationType())) { insertValue(loggingInfo, target, annotation, method, loggingInfo.getInputName()); } if (SetterServiceName.class.equals(annotation.annotationType())) { insertValue(loggingInfo, target, annotation, method, loggingInfo.getServiceName()); } if (SetterPublisher.class.equals(annotation.annotationType())) { insertValue( loggingInfo, target, annotation, method, loggingInfo.getPublisherType().toString()); } if (loggingInfo.getRequestMessage() != null) { if (SetterUrl.class.equals(annotation.annotationType()) && loggingInfo.getRequestMessage().getAddress() != null) { insertValue( loggingInfo, target, annotation, method, loggingInfo.getRequestMessage().getAddress().toString()); } if (SetterRequest.class.equals(annotation.annotationType()) && loggingInfo.getResponseMessage().getPayload() != null) { insertValue( loggingInfo, target, annotation, method, loggingInfo.getRequestMessage().getPayload().toString()); } } else { log.error("Request message is not present!"); } if (loggingInfo.getResponseMessage() != null) { if (SetterResponse.class.equals(annotation.annotationType()) && loggingInfo.getResponseMessage().getPayload() != null) { insertValue( loggingInfo, target, annotation, method, loggingInfo.getResponseMessage().getPayload().toString()); } } else { log.error("Response message is not present!"); } if (UseLoggingInfoConvertor.class.equals(annotation.annotationType())) { useLoggingInfoInsertValue(loggingInfo, target, annotation, method); } } for (Entry<Annotation, Method> entry : customAnnotationMethodMap.entrySet()) { Annotation annotation = entry.getKey(); Method method = entry.getValue(); if (SetterCustomStringValue1.class.equals(annotation.annotationType())) { insertValue(loggingInfo, target, annotation, method, loggingCustomData.getStringValue1()); } if (SetterCustomStringValue2.class.equals(annotation.annotationType())) { insertValue(loggingInfo, target, annotation, method, loggingCustomData.getStringValue2()); } if (SetterCustomStringValue3.class.equals(annotation.annotationType())) { insertValue(loggingInfo, target, annotation, method, loggingCustomData.getStringValue3()); } if (SetterCustomStringValue4.class.equals(annotation.annotationType())) { insertValue(loggingInfo, target, annotation, method, loggingCustomData.getStringValue4()); } if (SetterCustomStringValue5.class.equals(annotation.annotationType())) { insertValue(loggingInfo, target, annotation, method, loggingCustomData.getStringValue5()); } if (SetterCustomNumberValue1.class.equals(annotation.annotationType())) { insertValue(loggingInfo, target, annotation, method, loggingCustomData.getNumberValue1()); } if (SetterCustomNumberValue2.class.equals(annotation.annotationType())) { insertValue(loggingInfo, target, annotation, method, loggingCustomData.getNumberValue2()); } if (SetterCustomNumberValue3.class.equals(annotation.annotationType())) { insertValue(loggingInfo, target, annotation, method, loggingCustomData.getNumberValue3()); } if (SetterCustomNumberValue4.class.equals(annotation.annotationType())) { insertValue(loggingInfo, target, annotation, method, loggingCustomData.getNumberValue4()); } if (SetterCustomNumberValue5.class.equals(annotation.annotationType())) { insertValue(loggingInfo, target, annotation, method, loggingCustomData.getNumberValue5()); } if (SetterCustomDateValue1.class.equals(annotation.annotationType())) { insertValue(loggingInfo, target, annotation, method, loggingCustomData.getDateValue1()); } if (SetterCustomDateValue2.class.equals(annotation.annotationType())) { insertValue(loggingInfo, target, annotation, method, loggingCustomData.getDateValue2()); } if (SetterCustomDateValue3.class.equals(annotation.annotationType())) { insertValue(loggingInfo, target, annotation, method, loggingCustomData.getDateValue3()); } } }
/** * Creates a map of concrete json request handler invokers keyed by <b><code> * <service-name>/<op-name></code></b>. * * @param handlerInstance The request handler instance to generate invokers for * @return the map of generated invokers */ public static Map<String, Map<String, AbstractJSONRequestHandlerInvoker>> createInvokers( Object handlerInstance) { if (handlerInstance == null) throw new IllegalArgumentException("The passed handlerInstance was null"); Map<String, AbstractJSONRequestHandlerInvoker> subInvokerMap = new HashMap<String, AbstractJSONRequestHandlerInvoker>(); Map<String, Map<String, AbstractJSONRequestHandlerInvoker>> invokerMap = invokerCache.get(handlerInstance.getClass()); if (invokerMap != null) { LOG.info("Found Cached Invokers for [{}]", handlerInstance.getClass().getName()); return invokerMap; } invokerMap = new HashMap<String, Map<String, AbstractJSONRequestHandlerInvoker>>(1); LOG.info("Generating Invokers for [{}]", handlerInstance.getClass().getName()); JSONRequestService svc = handlerInstance.getClass().getAnnotation(JSONRequestService.class); final String invokerServiceKey = svc.name(); final String invokerServiceDescription = svc.description(); invokerMap.put(invokerServiceKey, subInvokerMap); ClassPool cp = new ClassPool(); cp.appendClassPath(new ClassClassPath(handlerInstance.getClass())); cp.appendClassPath(new ClassClassPath(AbstractJSONRequestHandlerInvoker.class)); cp.importPackage(handlerInstance.getClass().getPackage().getName()); Set<ClassLoader> classPathsAdded = new HashSet<ClassLoader>(); Set<String> packagesImported = new HashSet<String>(); try { final CtClass jsonRequestCtClass = cp.get(JSONRequest.class.getName()); final CtClass parent = cp.get(AbstractJSONRequestHandlerInvoker.class.getName()); CtClass targetClass = cp.get(handlerInstance.getClass().getName()); Collection<Method> methods = getTargetMethods(handlerInstance.getClass()); for (Method m : methods) { final JSONRequestHandler jsonHandler = m.getAnnotation(JSONRequestHandler.class); final String opName = jsonHandler.name(); final String opDescription = jsonHandler.description(); final RequestType opType = jsonHandler.type(); int targetMethodHashCode = m.toGenericString().hashCode(); final String className = String.format( "%s-%s%s-%s-%s", handlerInstance.getClass().getName(), invokerServiceKey, opName, "ServiceInvoker", targetMethodHashCode); final CtClass invokerClass = cp.makeClass(className, parent); CtField ctf = new CtField(targetClass, "typedTarget", invokerClass); ctf.setModifiers(ctf.getModifiers() | Modifier.FINAL); invokerClass.addField(ctf); for (CtConstructor parentCtor : parent.getConstructors()) { CtConstructor invokerCtor = CtNewConstructor.copy(parentCtor, invokerClass, null); invokerCtor.setBody( "{ super($$); typedTarget = (" + handlerInstance.getClass().getName() + ")$1; }"); invokerClass.addConstructor(invokerCtor); } CtMethod invokerMethod = CtNewMethod.copy( parent.getDeclaredMethod("doInvoke", new CtClass[] {jsonRequestCtClass}), invokerClass, null); StringBuilder b = new StringBuilder("{this.typedTarget.").append(m.getName()).append("($1"); final Class<?>[] ptypes = m.getParameterTypes(); final int remainingParamCount = ptypes.length - 1; // Set<Class<?>> classPathsAdded = new HashSet<Class<?>>(); // Set<String> packagesImported = new HashSet<String>(); if (remainingParamCount > 0) { for (int i = 0; i < remainingParamCount; i++) { final Class<?> type = ptypes[i + 1]; if (type.getName().contains("UniqueIdType")) { System.err.println("Comin Up...."); } if (type.isPrimitive()) { b.append(", (").append(type.getName()).append(") null"); } else { if (classPathsAdded.add(type.getClassLoader())) { cp.appendClassPath(new LoaderClassPath(type.getClassLoader())); } try { Package p = type.getPackage(); if (p == null) { if (type.isArray()) { if (!type.getComponentType().isPrimitive()) { p = type.getComponentType().getPackage(); } } } if (type.isEnum()) { final String f = type.getEnclosingClass().getName() + "." + type.getSimpleName(); b.append(", (").append(f).append(") null"); String pack = type.getEnclosingClass().getPackage().getName(); if (packagesImported.add(pack)) { cp.importPackage(pack); } continue; } if (p != null) { if (packagesImported.add(p.getName())) { cp.importPackage(p.getName()); } } } catch (Exception ex) { ex.printStackTrace(System.err); } b.append(", (").append(type.getSimpleName()).append(") null"); } } } b.append(");}"); System.out.println("[" + m.getName() + "]: [" + b.toString() + "]"); // invokerMethod.setBody("{this.typedTarget." + m.getName() + "($1);}"); invokerMethod.setBody(b.toString()); invokerMethod.setModifiers(invokerMethod.getModifiers() & ~Modifier.ABSTRACT); invokerClass.addMethod(invokerMethod); // invokerClass.writeFile(System.getProperty("java.io.tmpdir") + File.separator + // "jsoninvokers"); Class<?> clazz = invokerClass.toClass( handlerInstance.getClass().getClassLoader(), handlerInstance.getClass().getProtectionDomain()); Constructor<?> ctor = clazz.getDeclaredConstructor( Object.class, String.class, String.class, String.class, String.class, RequestType.class); AbstractJSONRequestHandlerInvoker invokerInstance = (AbstractJSONRequestHandlerInvoker) ctor.newInstance( handlerInstance, invokerServiceKey, invokerServiceDescription, opName, opDescription, opType); subInvokerMap.put(opName, invokerInstance); } invokerCache.put(handlerInstance.getClass(), invokerMap); return invokerMap; } catch (Exception ex) { LOG.error( "Failed to create RequestHandlerInvoker for [{}]", handlerInstance.getClass().getName(), ex); throw new RuntimeException( "Failed to create RequestHandlerInvoker [" + handlerInstance.getClass().getName() + "]", ex); } }
@Override public String toString() { return String.format("%s[%s]", this.getClass().getSimpleName(), method.toGenericString()); }
private static JSONArray methodsForLanguage(Context context, String language) { Class[] scriptingClasses = {JavaScriptEngine.class, SchemeEngine.class}; ArrayList<String> languages = new ArrayList<>(); languages.add(BootstrapSiteExporter.LANGUAGE_ALL.toLowerCase()); if (languages.contains(language) == false) languages.add(language.toLowerCase()); JSONArray declaredMethods = new JSONArray(); HashSet<String> included = new HashSet<>(); for (Class classObj : scriptingClasses) { Method[] methods = classObj.getMethods(); for (Method method : methods) { Annotation[] annotations = method.getDeclaredAnnotations(); for (Annotation annotation : annotations) { if (annotation instanceof ScriptingEngineMethod) { ScriptingEngineMethod scriptAnnotation = (ScriptingEngineMethod) annotation; String category = context.getString(scriptAnnotation.category()); String assetPath = scriptAnnotation.assetPath(); String scriptLanguage = scriptAnnotation.language(); String methodName = method.getName(); if (languages.contains(scriptLanguage.toLowerCase()) && included.contains(method.toGenericString()) == false) { StringBuilder args = new StringBuilder(); for (String argument : ((ScriptingEngineMethod) annotation).arguments()) { if (args.length() > 0) args.append(", "); args.append(argument); } JSONObject methodDef = new JSONObject(); try { methodDef.put( BootstrapSiteExporter.METHOD_NAME, methodName + "(" + args.toString() + ")"); methodDef.put(BootstrapSiteExporter.METHOD_FULL_NAME, method.toGenericString()); methodDef.put(BootstrapSiteExporter.METHOD_LANGUAGE, scriptLanguage); methodDef.put(BootstrapSiteExporter.METHOD_CATEGORY, category); if (assetPath.trim().length() > 0) methodDef.put(BootstrapSiteExporter.METHOD_ASSET_PATH, assetPath); } catch (JSONException e) { e.printStackTrace(); } declaredMethods.put(methodDef); included.add(method.toGenericString()); } } } } } return declaredMethods; }
/** java.lang.reflect.Method#toGenericString() */ public void test_toGenericString() throws Exception { Method method = GenericString.class.getDeclaredMethod("genericString", Object.class); assertEquals("Wrong generic String returned", GenericString.GENERIC, method.toGenericString()); }