List of usage examples for java.lang.reflect Method toString
public String toString()
From source file:org.flite.cach3.aop.UpdateAssignCacheAdvice.java
private void doUpdate(final JoinPoint jp, final Object retVal) throws Throwable { // If we've disabled the caching programmatically (or via properties file) just flow through. if (isCacheDisabled()) { LOG.debug("Caching is disabled."); return;/*from w ww . j a va2 s. com*/ } final MemcachedClientIF cache = getMemcachedClient(); final Method methodToCache = getMethodToCache(jp); List<UpdateAssignCache> lAnnotations; if (methodToCache.getAnnotation(UpdateAssignCache.class) != null) { lAnnotations = Arrays.asList(methodToCache.getAnnotation(UpdateAssignCache.class)); } else { lAnnotations = Arrays.asList(methodToCache.getAnnotation(UpdateAssignCaches.class).value()); } for (int i = 0; i < lAnnotations.size(); i++) { try { // This is injected caching. If anything goes wrong in the caching, LOG the crap outta it, // but do not let it surface up past the AOP injection itself. final AnnotationInfo info = getAnnotationInfo(lAnnotations.get(i), methodToCache.getName(), getJitterDefault()); final String cacheKey = buildCacheKey(info.getAsString(AType.ASSIGN_KEY), info.getAsString(AType.NAMESPACE), info.getAsString(AType.KEY_PREFIX)); final int dataIndex = info.getAsInteger(AType.DATA_INDEX, -2).intValue(); final Object dataObject = dataIndex == -1 ? retVal : getIndexObject(dataIndex, jp.getArgs(), methodToCache.toString()); final Object submission = (dataObject == null) ? new PertinentNegativeNull() : dataObject; cache.set(cacheKey, info.getAsInteger(AType.JITTER), submission); // Notify the observers that a cache interaction happened. final List<UpdateAssignCacheListener> listeners = getPertinentListeners( UpdateAssignCacheListener.class, info.getAsString(AType.NAMESPACE)); if (listeners != null && !listeners.isEmpty()) { for (final UpdateAssignCacheListener listener : listeners) { try { listener.triggeredUpdateAssignCache(info.getAsString(AType.NAMESPACE), info.getAsString(AType.ASSIGN_KEY), dataObject, retVal, jp.getArgs()); } catch (Exception ex) { LOG.warn("Problem when triggering a listener.", ex); } } } } catch (Exception ex) { if (LOG.isDebugEnabled()) { LOG.warn("Caching on " + jp.toShortString() + " aborted due to an error.", ex); } else { LOG.warn("Caching on " + jp.toShortString() + " aborted due to an error: " + ex.getMessage()); } } } }
From source file:com.facebook.GraphObjectWrapper.java
private static <T extends GraphObject> void verifyCanProxyClass(Class<T> graphObjectClass) { if (hasClassBeenVerified(graphObjectClass)) { return;//from w ww . jav a 2 s. c o m } if (!graphObjectClass.isInterface()) { throw new FacebookGraphObjectException( "GraphObjectWrapper can only wrap interfaces, not class: " + graphObjectClass.getName()); } Method[] methods = graphObjectClass.getMethods(); for (Method method : methods) { String methodName = method.getName(); int parameterCount = method.getParameterTypes().length; Class<?> returnType = method.getReturnType(); boolean hasPropertyNameOverride = method.isAnnotationPresent(PropertyName.class); if (method.getDeclaringClass().isAssignableFrom(GraphObject.class)) { // Don't worry about any methods from GraphObject or one of its base classes. continue; } else if (parameterCount == 1 && returnType == Void.TYPE) { if (hasPropertyNameOverride) { // If a property override is present, it MUST be valid. We don't fallback // to using the method name if (!Utility.isNullOrEmpty(method.getAnnotation(PropertyName.class).value())) { continue; } } else if (methodName.startsWith("set") && methodName.length() > 3) { // Looks like a valid setter continue; } } else if (parameterCount == 0 && returnType != Void.TYPE) { if (hasPropertyNameOverride) { // If a property override is present, it MUST be valid. We don't fallback // to using the method name if (!Utility.isNullOrEmpty(method.getAnnotation(PropertyName.class).value())) { continue; } } else if (methodName.startsWith("get") && methodName.length() > 3) { // Looks like a valid getter continue; } } throw new FacebookGraphObjectException("GraphObjectWrapper can't proxy method: " + method.toString()); } recordClassHasBeenVerified(graphObjectClass); }
From source file:org.ut.biolab.medsavant.MedSavantServlet.java
public String json_invoke(String adapter, String method, String jsonStr) throws IllegalArgumentException { adapter = adapter + "Adapter"; Field selectedAdapter = null; for (Field f : MedSavantServlet.class.getDeclaredFields()) { if (f.getType().getSimpleName().equalsIgnoreCase(adapter)) { selectedAdapter = f;/*from ww w . j a v a 2 s .c o m*/ } } if (selectedAdapter == null) { throw new IllegalArgumentException("The adapter " + adapter + " does not exist"); } JsonParser parser = new JsonParser(); JsonArray gArray = parser.parse(jsonStr).getAsJsonArray(); JsonElement jse = parser.parse(jsonStr); JsonArray jsonArray; if (jse.isJsonArray()) { jsonArray = jse.getAsJsonArray(); } else { throw new IllegalArgumentException("The json method arguments are not an array"); } Method selectedMethod = null; for (Method m : selectedAdapter.getType().getMethods()) { if (m.getName().equalsIgnoreCase(method) && m.getGenericParameterTypes().length == (jsonArray.size() + 1)) { selectedMethod = m; } } if (selectedMethod == null) { throw new IllegalArgumentException("The method " + method + " in adapter " + adapter + " with " + jsonArray.size() + " arguments does not exist"); } int i = 0; Object[] methodArgs = new Object[selectedMethod.getParameterTypes().length]; try { for (Type t : selectedMethod.getGenericParameterTypes()) { LOG.debug("Field " + i + " is " + t.toString() + " for method " + selectedMethod.toString()); methodArgs[i] = (i > 0) ? gson.fromJson(gArray.get(i - 1), t) : session.getSessionId(); ++i; } } catch (JsonParseException je) { LOG.error(je); } Object selectedAdapterInstance = null; try { selectedAdapterInstance = selectedAdapter.get(this); if (selectedAdapterInstance == null) { throw new NullPointerException( "Requested adapter " + selectedAdapter.getName() + " was not initialized."); } MethodInvocation methodInvocation = new MethodInvocation(session, gson, selectedAdapterInstance, selectedMethod, methodArgs); return methodInvocation.invoke(); } catch (IllegalAccessException iae) { throw new IllegalArgumentException("Couldn't execute method with given arguments: " + iae.getMessage()); } catch (LockException lex) { //this shouldn't happen, as locking exceptions can only be thrown by queued method invocations, which //are intercepted in the BlockingQueueManager. String msg = "Unexpected locking exception thrown in unqueued method invocation."; LOG.error(msg); throw new IllegalArgumentException(msg + ": " + lex.getMessage()); } }
From source file:org.eclipse.wb.internal.rcp.model.rcp.EditorPartInfo.java
private void setEditorSite() throws Exception { ClassLoader editorLoader = JavaInfoUtils.getClassLoader(this); Class<?> editorSiteClass = editorLoader.loadClass("org.eclipse.ui.IEditorSite"); Class<?> editorInputClass = editorLoader.loadClass("org.eclipse.ui.IEditorInput"); // create IEditorSite Object editorSite = Proxy.newProxyInstance(editorLoader, new Class<?>[] { editorSiteClass }, new InvocationHandler() { public Object invoke(Object proxy, Method method, Object[] args) throws Throwable { String signature = ReflectionUtils.getMethodSignature(method); if (signature.equals("toString()")) { return "IEditorSite_stub"; }// w ww . j a v a 2s .co m if (signature.equals("hashCode()")) { return 0; } if (signature.equals("getId()")) { return getID(); } if (signature.equals("getWorkbenchWindow()")) { return DesignerPlugin.getActiveWorkbenchWindow(); } // IServiceLocator if (signature.equals("hasService(java.lang.Class)")) { IServiceLocator serviceLocator = DesignerPlugin.getActiveWorkbenchWindow(); return serviceLocator.hasService((Class<?>) args[0]); } if (signature.equals("getService(java.lang.Class)")) { IServiceLocator serviceLocator = DesignerPlugin.getActiveWorkbenchWindow(); return serviceLocator.getService((Class<?>) args[0]); } // not implemented throw new NotImplementedException(method.toString()); } }); // create org.eclipse.ui.IEditorInput Object editorInput = Proxy.newProxyInstance(editorLoader, new Class<?>[] { editorInputClass }, new InvocationHandler() { public Object invoke(Object proxy, Method method, Object[] args) throws Throwable { Class<?> returnType = method.getReturnType(); return ReflectionUtils.getDefaultValue(returnType); } }); // call init(IEditorSite,IEditorInput) ReflectionUtils.invokeMethod(getObject(), "init(org.eclipse.ui.IEditorSite,org.eclipse.ui.IEditorInput)", editorSite, editorInput); }
From source file:org.neovera.jdiablo.environment.SpringEnvironment.java
private void setValue(PropertyDescriptor pd, Object target, String value) { Method writeMethod = pd.getWriteMethod(); if (writeMethod == null) { throw new RuntimeException("No write method found for property " + pd.getName()); }//from w w w . j a va 2 s . co m try { if (writeMethod.getParameterTypes()[0].equals(Boolean.class) || "boolean".equals(writeMethod.getParameterTypes()[0].getName())) { writeMethod.invoke(target, value == null ? false : "true".equals(value)); } else if (writeMethod.getParameterTypes()[0].equals(Integer.class) || "int".equals(writeMethod.getParameterTypes()[0].getName())) { writeMethod.invoke(target, value == null ? 0 : Integer.parseInt(value)); } else if (writeMethod.getParameterTypes()[0].equals(Long.class) || "long".equals(writeMethod.getParameterTypes()[0].getName())) { writeMethod.invoke(target, value == null ? 0 : Long.parseLong(value)); } else if (writeMethod.getParameterTypes()[0].equals(BigDecimal.class)) { writeMethod.invoke(target, value == null ? null : new BigDecimal(value)); } else if (writeMethod.getParameterTypes()[0].equals(String.class)) { writeMethod.invoke(target, value); } else if (writeMethod.getParameterTypes()[0].isArray() && writeMethod.getParameterTypes()[0].getName().contains(String.class.getName())) { writeMethod.invoke(target, (Object[]) value.split(",")); } else { throw new RuntimeException("Could not resolve parameter type for " + writeMethod.toString()); } } catch (InvocationTargetException e) { throw new RuntimeException(e); } catch (IllegalAccessException e) { throw new RuntimeException(e); } }
From source file:corner.cache.services.impl.CacheableDefinitionParserImpl.java
/** * @see corner.cache.services.CacheableDefinitionParser#parseAsKey(org.apache.tapestry5.ioc.Invocation, java.lang.reflect.Method, corner.cache.services.CacheManager) *///from w w w . j av a2 s . c om @Override public String parseAsKey(Invocation invocation, Method method) { Cacheable cacheable = method.getAnnotation(Cacheable.class); if (cacheable == null) { return null; } Definition define = null; //if (define == null) { // ? Builder defineBuilder = CacheableDefine.Definition.newBuilder(); Annotation[][] parametersAnnotations = method.getParameterAnnotations(); for (int i = 0; i < parametersAnnotations.length; i++) { Annotation[] pa = parametersAnnotations[i]; for (Annotation a : pa) { if (a instanceof CacheKeyParameter) { defineBuilder.addParameterIndex(i); } } } define = defineBuilder.build(); // ? List<String> keyParameter = new ArrayList<String>(); Object pObj; Class pType; for (int i = 0; i < define.getParameterIndexCount(); i++) { int pIndex = define.getParameterIndex(i); pObj = invocation.getParameter(pIndex); pType = null; if (pObj != null) { pType = entityService.getEntityClass(pObj); } if (pType == null) { pType = method.getParameterTypes()[pIndex]; } ValueEncoder encoder = valueEncoderSource.getValueEncoder(pType); keyParameter.add(encoder.toClient(pObj)); } //key String key = null; String keyFormat = cacheable.keyFormat(); logger.debug("key parameter:{}", keyParameter); if (!StringUtils.hasText(keyFormat)) { key = DigestUtils.shaHex(method.toString() + keyParameter.toString()); } else { key = String.format(keyFormat, keyParameter.toArray(new Object[0])); } CacheStrategy strategy = this.source.findStrategy(cacheable.strategy()); CacheNsParameter[] nses = cacheable.namespaces(); if (strategy == null) { throw new RuntimeException("fail to find cache strategy instance!"); } return strategy.appendNamespace(cacheManager, cacheable.clazz(), nses, key, keyParameter.toArray()); }
From source file:org.solmix.datax.support.InvokerObject.java
public Object invoke() throws InvokerException { Method method = getServiceMethod(); Object instance = getServiceInstance(); List<Object> methodArgs = new ArrayList<Object>(); Class<?>[] parameterTypes = method.getParameterTypes(); Annotation[][] parameterAnnotations = method.getParameterAnnotations(); GenericParameterNode[] genericParamTypes = getGenericParameterTypes(method); Map<Integer, MethodArgInfo> argsInfo = invokerInfo.getMethodArgs(); for (int i = 0; i < parameterTypes.length; i++) { Class<?> paramType = parameterTypes[i]; MethodArgInfo argInfo = (argsInfo == null ? null : argsInfo.get(i)); GenericParameterNode genericParamInfo = genericParamTypes[i]; Annotation[] parameterannotation = parameterAnnotations[i]; if (genericParamInfo != null && genericParamInfo.getClassByIndex(0) == paramType) genericParamInfo = genericParamInfo.getChildNode(); try {//from w w w .j a va 2 s . c o m methodArgs.add(lookupValue(paramType, argInfo, parameterannotation, genericParamInfo)); } catch (Exception e) { String errorString = new StringBuilder().append("Unable to assign a argument to slot #") .append(i + 1).append(" taking type: ").append(paramType.getName()).append(" of method:") .append(method.toString()).append(" Can't lookup arguments match this type").toString(); throw new InvokerException(errorString, e); } } Object args[] = DataUtils.listToArray(methodArgs); if (LOG.isTraceEnabled()) { LOG.trace((new StringBuilder()).append("method takes: ").append(parameterTypes.length) .append(" args. I've assembled: ").append(methodArgs.size()).append(" args") .append(" invoking method:").append(getFormattedMethodSignature(method)) .append(" with arg types: ").append(getFormattedParamTypes(args)).toString()); } try { return method.invoke(instance, args); } catch (InvocationTargetException e) { throw new InvokerException(e.getMessage(), e.getCause()); } catch (Exception e) { throw new InvokerException("Invoke Exception", e); } }
From source file:com.weibo.api.motan.protocol.yar.YarProtocolUtil.java
private static Object[] adaptParams(Method method, Object[] arguments, Class<?>[] argumentClazz) { // FIXME the real parameter type may not same with formal parameter, for instance, formal // parameter type is int, the real parameter maybe use String in php // any elegant way? for (int i = 0; i < argumentClazz.length; i++) { try {/* w ww . ja v a 2s. com*/ if ("int".equals(argumentClazz[i].getName()) || "java.lang.Integer".equals(argumentClazz[i].getName())) { if (arguments[i] == null) { arguments[i] = 0;// default } else if (arguments[i] instanceof String) { arguments[i] = Integer.parseInt((String) arguments[i]); } else if (arguments[i] instanceof Number) { arguments[i] = ((Number) arguments[i]).intValue(); } else { throw new RuntimeException(); } } else if ("long".equals(argumentClazz[i].getName()) || "java.lang.Long".equals(argumentClazz[i].getName())) { if (arguments[i] == null) { arguments[i] = 0;// default } else if (arguments[i] instanceof String) { arguments[i] = Long.parseLong((String) arguments[i]); } else if (arguments[i] instanceof Number) { arguments[i] = ((Number) arguments[i]).longValue(); } else { throw new RuntimeException(); } } else if ("float".equals(argumentClazz[i].getName()) || "java.lang.Float".equals(argumentClazz[i].getName())) { if (arguments[i] == null) { arguments[i] = 0.0f;// default } else if (arguments[i] instanceof String) { arguments[i] = Float.parseFloat((String) arguments[i]); } else if (arguments[i] instanceof Number) { arguments[i] = ((Number) arguments[i]).floatValue(); } else { throw new RuntimeException(); } } else if ("double".equals(argumentClazz[i].getName()) || "java.lang.Double".equals(argumentClazz[i].getName())) { if (arguments[i] == null) { arguments[i] = 0.0f;// default } else if (arguments[i] instanceof String) { arguments[i] = Double.parseDouble((String) arguments[i]); } else if (arguments[i] instanceof Number) { arguments[i] = ((Number) arguments[i]).doubleValue(); } else { throw new RuntimeException(); } } else if ("boolean".equals(argumentClazz[i].getName()) || "java.lang.Boolean".equals(argumentClazz[i].getName())) { if (arguments[i] instanceof Boolean) { continue; } if (arguments[i] instanceof String) { arguments[i] = Boolean.valueOf(((String) arguments[i])); } else { throw new RuntimeException(); } } } catch (Exception e) { throw new MotanServiceException("adapt param fail! method:" + method.toString() + ", require param:" + argumentClazz[i].getName() + ", actual param:" + (arguments[i] == null ? null : arguments[i].getClass().getName() + "-" + arguments[i])); } } return arguments; }
From source file:ca.uhn.fhir.jaxrs.server.AbstractJaxRsConformanceProvider.java
/** * This method will add a provider to the conformance. This method is almost an exact copy of {@link ca.uhn.fhir.rest.server.RestfulServer#findResourceMethods } * /*w ww . jav a 2 s.c o m*/ * @param theProvider * an instance of the provider interface * @param theProviderInterface * the class describing the providers interface * @return the numbers of basemethodbindings added * @see ca.uhn.fhir.rest.server.RestfulServer#findResourceMethods */ public int addProvider(IResourceProvider theProvider, Class<? extends IResourceProvider> theProviderInterface) throws ConfigurationException { int count = 0; for (Method m : ReflectionUtil.getDeclaredMethods(theProviderInterface)) { BaseMethodBinding<?> foundMethodBinding = BaseMethodBinding.bindMethod(m, getFhirContext(), theProvider); if (foundMethodBinding == null) { continue; } count++; // if (foundMethodBinding instanceof ConformanceMethodBinding) { // myServerConformanceMethod = foundMethodBinding; // continue; // } if (!Modifier.isPublic(m.getModifiers())) { throw new ConfigurationException( "Method '" + m.getName() + "' is not public, FHIR RESTful methods must be public"); } else { if (Modifier.isStatic(m.getModifiers())) { throw new ConfigurationException( "Method '" + m.getName() + "' is static, FHIR RESTful methods must not be static"); } else { ourLog.debug("Scanning public method: {}#{}", theProvider.getClass(), m.getName()); String resourceName = foundMethodBinding.getResourceName(); ResourceBinding resourceBinding; if (resourceName == null) { resourceBinding = myServerBinding; } else { RuntimeResourceDefinition definition = getFhirContext().getResourceDefinition(resourceName); if (myResourceNameToBinding.containsKey(definition.getName())) { resourceBinding = myResourceNameToBinding.get(definition.getName()); } else { resourceBinding = new ResourceBinding(); resourceBinding.setResourceName(resourceName); myResourceNameToBinding.put(resourceName, resourceBinding); } } List<Class<?>> allowableParams = foundMethodBinding.getAllowableParamAnnotations(); if (allowableParams != null) { for (Annotation[] nextParamAnnotations : m.getParameterAnnotations()) { for (Annotation annotation : nextParamAnnotations) { Package pack = annotation.annotationType().getPackage(); if (pack.equals(IdParam.class.getPackage())) { if (!allowableParams.contains(annotation.annotationType())) { throw new ConfigurationException("Method[" + m.toString() + "] is not allowed to have a parameter annotated with " + annotation); } } } } } resourceBinding.addMethod(foundMethodBinding); ourLog.debug(" * Method: {}#{} is a handler", theProvider.getClass(), m.getName()); } } } return count; }
From source file:org.pentaho.hadoop.shim.mapr31.authentication.PropertyAuthenticationProviderParser.java
private void processPrefix(String prefix) { AuthenticationProvider provider = authenticationProviderInstantiator .instantiate(properties.getProperty(prefix + ".class")); if (provider != null) { for (Method method : provider.getClass().getMethods()) { if (method.getName().startsWith("set") && method.getName().length() >= 4 && method.getParameterTypes().length == 1) { String propName = prefix + "." + method.getName().substring(3, 4).toLowerCase(); if (method.getName().length() > 4) { propName += method.getName().substring(4); }//from w w w.j av a2 s .c o m if (properties.containsKey(propName)) { String strValue = Encr.decryptPasswordOptionallyEncrypted(properties.getProperty(propName)); Object actualValue = null; Class<?> argType = method.getParameterTypes()[0]; if (argType.isPrimitive()) { argType = ClassUtils.primitiveToWrapper(argType); } if (argType == String.class) { actualValue = strValue; } else { Method valueOf = null; try { valueOf = argType.getMethod("valueOf", String.class); } catch (NoSuchMethodException e1) { logger.warn("Unable to find valueOf method on " + argType.getClass().getCanonicalName()); } if (valueOf != null && Modifier.isStatic(valueOf.getModifiers())) { try { actualValue = valueOf.invoke(null, strValue); } catch (Exception e) { logger.warn("Unable to convert string property " + propName + "(" + strValue + ") to " + argType.getClass().getCanonicalName() + " to invoke setter " + method.getName(), e); } } else { logger.warn("Could not find method to convert " + propName + "(" + strValue + ") to " + argType.getClass().getCanonicalName() + " (currently only primitives and their wrappers are supported)"); } } if (actualValue != null) { try { method.invoke(provider, strValue); } catch (Exception e) { Throwable cause = e; if (e instanceof InvocationTargetException) { cause = e.getCause(); } logger.warn("Error invoking setter " + method.toString() + " with property " + propName + "(" + strValue + ")", cause); } } } } } manager.registerAuthenticationProvider(provider); } }