java.lang.reflect.InvocationTargetException Java Examples

The following examples show how to use java.lang.reflect.InvocationTargetException. You can vote up the ones you like or vote down the ones you don't like, and go to the original project or source file by following the links above each example. You may check out the related API usage on the sidebar.
Example #1
Source File: DelegateInvocationHandlerImpl.java    From JDKSourceCode1.8 with MIT License 6 votes vote down vote up
public static InvocationHandler create( final Object delegate )
{
    SecurityManager s = System.getSecurityManager();
    if (s != null) {
        s.checkPermission(new DynamicAccessPermission("access"));
    }
    return new InvocationHandler() {
        public Object invoke( Object proxy, Method method, Object[] args )
            throws Throwable
        {
            // This throws an IllegalArgument exception if the delegate
            // is not assignable from method.getDeclaring class.
            try {
                return method.invoke( delegate, args ) ;
            } catch (InvocationTargetException ite) {
                // Propagate the underlying exception as the
                // result of the invocation
                throw ite.getCause() ;
            }
        }
    } ;
}
 
Example #2
Source File: AcquireLockBlockingUi.java    From elexis-3-core with Eclipse Public License 1.0 6 votes vote down vote up
public static void aquireAndRun(Identifiable identifiable, ILockHandler handler){
	Display display = Display.getDefault();
	display.syncExec(new Runnable() {
		
		@Override
		public void run(){
			ProgressMonitorDialog progress =
				new ProgressMonitorDialog(display.getActiveShell());
			try {
				progress.run(true, true, new AcquireLockRunnable(identifiable, handler));
			} catch (InvocationTargetException | InterruptedException e) {
				logger.warn("Exception during acquire lock.", e);
			}
		}
	});
}
 
Example #3
Source File: EdsdkErrorTest.java    From canon-sdk-java with MIT License 6 votes vote down vote up
@Test
void messageCanBeCustomized() throws IllegalAccessException, InvocationTargetException, InstantiationException, NoSuchMethodException {
    for (final EdsdkError value : EdsdkError.values()) {
        final Class<? extends EdsdkErrorException> aClass = value.getException().getClass();

        if (aClass.equals(EdsdkErrorException.class)) {
            continue;
        }

        final Constructor<? extends EdsdkErrorException> constructor;
        try {
            constructor = aClass.getConstructor(String.class);
        } catch (NoSuchMethodException e) {
            log.error("Missing constructor with string (message) for {}", value);
            throw e;
        }
        final EdsdkErrorException exception = constructor.newInstance("AnyMessage");
        Assertions.assertEquals("AnyMessage", exception.getMessage());
    }
}
 
Example #4
Source File: CachingFileSystem.java    From rubix with Apache License 2.0 6 votes vote down vote up
private synchronized void initializeClusterManager(Configuration conf, ClusterType clusterType)
    throws ClusterManagerInitilizationException
{
  if (clusterManager != null) {
    return;
  }

  String clusterManagerClassName = CacheConfig.getClusterManagerClass(conf, clusterType);
  log.info("Initializing cluster manager : " + clusterManagerClassName);

  try {
    Class clusterManagerClass = conf.getClassByName(clusterManagerClassName);
    Constructor constructor = clusterManagerClass.getConstructor();
    ClusterManager manager = (ClusterManager) constructor.newInstance();

    manager.initialize(conf);
    setClusterManager(manager);
  }
  catch (ClassNotFoundException | NoSuchMethodException | InstantiationException |
          IllegalAccessException | InvocationTargetException ex) {
    String errorMessage = String.format("Not able to initialize ClusterManager class : {0} ",
        clusterManagerClassName);
    log.error(errorMessage, ex);
    throw new ClusterManagerInitilizationException(errorMessage, ex);
  }
}
 
Example #5
Source File: Robot.java    From hottub with GNU General Public License v2.0 6 votes vote down vote up
/**
 * Waits until all events currently on the event queue have been processed.
 * @throws  IllegalThreadStateException if called on the AWT event dispatching thread
 */
public synchronized void waitForIdle() {
    checkNotDispatchThread();
    // post a dummy event to the queue so we know when
    // all the events before it have been processed
    try {
        SunToolkit.flushPendingEvents();
        EventQueue.invokeAndWait( new Runnable() {
                                        public void run() {
                                            // dummy implementation
                                        }
                                    } );
    } catch(InterruptedException ite) {
        System.err.println("Robot.waitForIdle, non-fatal exception caught:");
        ite.printStackTrace();
    } catch(InvocationTargetException ine) {
        System.err.println("Robot.waitForIdle, non-fatal exception caught:");
        ine.printStackTrace();
    }
}
 
Example #6
Source File: FXBrowserWindowSE.java    From CodenameOne with GNU General Public License v2.0 6 votes vote down vote up
public FXBrowserWindowSE(String startURL) {
    try {
        initUI(startURL);
    } catch (IllegalStateException ex) {
        try {
            EventQueue.invokeAndWait(new Runnable() {
                @Override
                public void run() {
                    new JFXPanel();
                }

            });
        } catch (InterruptedException iex) {
            Log.e(iex);
            throw ex;
        } catch (InvocationTargetException ite) {
            Log.e(ite);
            throw ex;
        }
        initUI(startURL);
    }
}
 
Example #7
Source File: OptionModesTester.java    From openjdk-jdk9 with GNU General Public License v2.0 6 votes vote down vote up
/**
 * Run all methods annotated with @Test, and throw an exception if any
 * errors are reported..
 * Typically called on a tester object in main()
 * @throws Exception if any errors occurred
 */
void runTests() throws Exception {
    for (Method m: getClass().getDeclaredMethods()) {
        Annotation a = m.getAnnotation(Test.class);
        if (a != null) {
            try {
                out.println("Running test " + m.getName());
                m.invoke(this);
            } catch (InvocationTargetException e) {
                Throwable cause = e.getCause();
                throw (cause instanceof Exception) ? ((Exception) cause) : e;
            }
            out.println();
        }
    }
    if (errors > 0)
        throw new Exception(errors + " errors occurred");
}
 
Example #8
Source File: DelegateInvocationHandlerImpl.java    From openjdk-jdk9 with GNU General Public License v2.0 6 votes vote down vote up
public static InvocationHandler create( final Object delegate )
{
    SecurityManager s = System.getSecurityManager();
    if (s != null) {
        s.checkPermission(new DynamicAccessPermission("access"));
    }
    return new InvocationHandler() {
        public Object invoke( Object proxy, Method method, Object[] args )
            throws Throwable
        {
            // This throws an IllegalArgument exception if the delegate
            // is not assignable from method.getDeclaring class.
            try {
                return method.invoke( delegate, args ) ;
            } catch (InvocationTargetException ite) {
                // Propagate the underlying exception as the
                // result of the invocation
                throw ite.getCause() ;
            }
        }
    } ;
}
 
Example #9
Source File: Class.java    From dragonwell8_jdk with GNU General Public License v2.0 6 votes vote down vote up
/**
 * Returns the elements of this enum class or null if this
 * Class object does not represent an enum type;
 * identical to getEnumConstants except that the result is
 * uncloned, cached, and shared by all callers.
 */
T[] getEnumConstantsShared() {
    if (enumConstants == null) {
        if (!isEnum()) return null;
        try {
            final Method values = getMethod("values");
            java.security.AccessController.doPrivileged(
                new java.security.PrivilegedAction<Void>() {
                    public Void run() {
                            values.setAccessible(true);
                            return null;
                        }
                    });
            @SuppressWarnings("unchecked")
            T[] temporaryConstants = (T[])values.invoke(null);
            enumConstants = temporaryConstants;
        }
        // These can happen when users concoct enum-like classes
        // that don't comply with the enum spec.
        catch (InvocationTargetException | NoSuchMethodException |
               IllegalAccessException ex) { return null; }
    }
    return enumConstants;
}
 
Example #10
Source File: OptionConverter.java    From logging-log4j2 with Apache License 2.0 6 votes vote down vote up
/**
 * Instantiate an object given a class name. Check that the
 * <code>className</code> is a subclass of
 * <code>superClass</code>. If that test fails or the object could
 * not be instantiated, then <code>defaultValue</code> is returned.
 *
 * @param className    The fully qualified class name of the object to instantiate.
 * @param superClass   The class to which the new object should belong.
 * @param defaultValue The object to return in case of non-fulfillment
 */
public static Object instantiateByClassName(String className, Class<?> superClass,
        Object defaultValue) {
    if (className != null) {
        try {
            Object obj = LoaderUtil.newInstanceOf(className);
            if (!superClass.isAssignableFrom(obj.getClass())) {
                LOGGER.error("A \"{}\" object is not assignable to a \"{}\" variable", className,
                        superClass.getName());
                return defaultValue;
            }
            return obj;
        } catch (ClassNotFoundException | NoSuchMethodException | IllegalAccessException
                | InstantiationException | InvocationTargetException e) {
            LOGGER.error("Could not instantiate class [" + className + "].", e);
        }
    }
    return defaultValue;
}
 
Example #11
Source File: DslDeferredFunctionCall.java    From brooklyn-server with Apache License 2.0 6 votes vote down vote up
protected Maybe<Object> invoke() {
    findMethod();
    
    if (method.isPresent()) {
        Method m = method.get();
    
        checkCallAllowed(m);
    
        try {
            // Value is most likely another BrooklynDslDeferredSupplier - let the caller handle it,
            return Maybe.of(Reflections.invokeMethodFromArgs(instance, m, instanceArgs));
        } catch (IllegalArgumentException | IllegalAccessException | InvocationTargetException e) {
            // If the method is there but not executable for whatever reason fail with a fatal error, don't return an absent.
            throw Exceptions.propagateAnnotated("Error invoking '"+toStringF(fnName, instanceArgs)+"' on '"+instance+"'", e);
        }
    } else {
        // could do deferred execution if an argument is a deferred supplier:
        // if we get a present from:
        // new Invoker(obj, fnName, replaceSuppliersWithNull(args)).findMethod()
        // then return a
        // new DslDeferredFunctionCall(...)
        
        return Maybe.absent(new IllegalArgumentException("No such function '"+fnName+"' taking args "+args+" (on "+obj+")"));
    }
}
 
Example #12
Source File: DescriptiveStatistics.java    From cacheonix-core with GNU Lesser General Public License v2.1 6 votes vote down vote up
/**
 * Returns an estimate for the pth percentile of the stored values. 
 * <p>
 * The implementation provided here follows the first estimation procedure presented
 * <a href="http://www.itl.nist.gov/div898/handbook/prc/section2/prc252.htm">here.</a>
 * </p><p>
 * <strong>Preconditions</strong>:<ul>
 * <li><code>0 &lt; p &lt; 100</code> (otherwise an 
 * <code>IllegalArgumentException</code> is thrown)</li>
 * <li>at least one value must be stored (returns <code>Double.NaN
 *     </code> otherwise)</li>
 * </ul></p>
 * 
 * @param p the requested percentile (scaled from 0 - 100)
 * @return An estimate for the pth percentile of the stored data 
 * @throws IllegalStateException if percentile implementation has been
 *  overridden and the supplied implementation does not support setQuantile
 * values
 */
public double getPercentile(double p) {
    if (percentileImpl instanceof Percentile) {
        ((Percentile) percentileImpl).setQuantile(p);
    } else {
        try {
            percentileImpl.getClass().getMethod("setQuantile", 
                    new Class[] {Double.TYPE}).invoke(percentileImpl,
                            new Object[] {new Double(p)});
        } catch (NoSuchMethodException e1) { // Setter guard should prevent
            throw new IllegalArgumentException(
               "Percentile implementation does not support setQuantile");
        } catch (IllegalAccessException e2) {
            throw new IllegalArgumentException(
                "IllegalAccessException setting quantile"); 
        } catch (InvocationTargetException e3) {
            throw new IllegalArgumentException(
                "Error setting quantile" + e3.toString()); 
        }
    }
    return apply(percentileImpl);
}
 
Example #13
Source File: StatementDecoratorInterceptor.java    From Tomcat8-Source-Read with MIT License 6 votes vote down vote up
@Override
public Object invoke(Object proxy, Method method, Object[] args) throws Throwable {
    if (method.getName().equals("getStatement")) {
        return this.st;
    } else {
        try {
            return method.invoke(this.delegate, args);
        } catch (Throwable t) {
            if (t instanceof InvocationTargetException
                    && t.getCause() != null) {
                throw t.getCause();
            } else {
                throw t;
            }
        }
    }
}
 
Example #14
Source File: NotificationUmaTracker.java    From 365browser with Apache License 2.0 6 votes vote down vote up
@TargetApi(26)
private boolean isChannelBlocked(@ChannelDefinitions.ChannelId String channelId) {
    // Use non-compat notification manager as compat does not have getNotificationChannel (yet).
    NotificationManager notificationManager =
            ContextUtils.getApplicationContext().getSystemService(NotificationManager.class);
    /*
    The code in the try-block uses reflection in order to compile as it calls APIs newer than
    our compileSdkVersion of Android. The equivalent code without reflection looks like this:

        NotificationChannel channel = notificationManager.getNotificationChannel(channelId);
        return (channel.getImportance() == NotificationManager.IMPORTANCE_NONE);
     */
    // TODO(crbug.com/707804) Remove the following reflection once compileSdk is bumped to O.
    try {
        Method getNotificationChannel = notificationManager.getClass().getMethod(
                "getNotificationChannel", String.class);
        Object channel = getNotificationChannel.invoke(notificationManager, channelId);
        Method getImportance = channel.getClass().getMethod("getImportance");
        int importance = (int) getImportance.invoke(channel);
        return (importance == NotificationManager.IMPORTANCE_NONE);
    } catch (NoSuchMethodException | InvocationTargetException | IllegalAccessException e) {
        Log.e(TAG, "Error checking channel importance:", e);
    }
    return false;
}
 
Example #15
Source File: ByObjectProp.java    From Cognizant-Intelligent-Test-Scripter with Apache License 2.0 6 votes vote down vote up
public By getBy(String propertyName, String value) {
    value = Objects.toString(value, "");
    for (ObjectPropClass objectPropClass : OBJ_PROP_CLASSES) {
        if (objectPropClass.propertyMethodMap.containsKey(propertyName)) {
            Method method = objectPropClass.propertyMethodMap.get(propertyName);
            try {
                return (By) method.invoke(objectPropClass.classObject, value);
            } catch (IllegalAccessException | IllegalArgumentException | InvocationTargetException ex) {
                Logger.getLogger(ByObjectProp.class.getName()).log(Level.SEVERE, null, ex);
            }
            break;
        }
    }
    Logger.getLogger(ByObjectProp.class.getName()).log(Level.SEVERE, "Find logic not implemented for - {0}", propertyName);
    return null;
}
 
Example #16
Source File: AbstractFactoryBean.java    From java-technology-stack with MIT License 6 votes vote down vote up
@Override
public Object invoke(Object proxy, Method method, Object[] args) throws Throwable {
	if (ReflectionUtils.isEqualsMethod(method)) {
		// Only consider equal when proxies are identical.
		return (proxy == args[0]);
	}
	else if (ReflectionUtils.isHashCodeMethod(method)) {
		// Use hashCode of reference proxy.
		return System.identityHashCode(proxy);
	}
	else if (!initialized && ReflectionUtils.isToStringMethod(method)) {
		return "Early singleton proxy for interfaces " +
				ObjectUtils.nullSafeToString(getEarlySingletonInterfaces());
	}
	try {
		return method.invoke(getSingletonInstance(), args);
	}
	catch (InvocationTargetException ex) {
		throw ex.getTargetException();
	}
}
 
Example #17
Source File: JRubyAdapter.java    From pokemon-go-xposed-mitm with GNU General Public License v3.0 6 votes vote down vote up
public static Object runRubyMethod(Object receiver, String methodName, Object... args) {
    try {
        Method m = ruby.getClass().getMethod("runRubyMethod", Class.class, Object.class, String.class, Object[].class);
        return m.invoke(ruby, Object.class, receiver, methodName, args);
    } catch (NoSuchMethodException nsme) {
        throw new RuntimeException(nsme);
    } catch (IllegalAccessException iae) {
        throw new RuntimeException(iae);
    } catch (java.lang.reflect.InvocationTargetException ite) {
        printStackTrace(ite);
        if (isDebugBuild) {
            throw new RuntimeException(ite);
        }
    }
    return null;
}
 
Example #18
Source File: ProxyTests.java    From ossindex-gradle-plugin with BSD 3-Clause "New" or "Revised" License 6 votes vote down vote up
/**
 * Ensure that OssIndexPlugin properly assembles the proxy argument and passes it to the DependencyAuditor.
 */
@Test
public void httpSystemProxyTest() throws InvocationTargetException, IllegalAccessException, NoSuchMethodException {
  Project project = mockProject();

  // Mock the proxy being provided as project properties
  mockSystemProxy(project, "http");

  OssIndexPlugin plugin = new OssIndexPlugin();
  AuditorFactory factory = mockAuditorFactory();
  plugin.setAuditorFactory(factory);

  // Simulate the process the gradle runs
  runGradleSimulation(project, plugin);

  verify(factory).getDependencyAuditor(null, Collections.EMPTY_SET, Collections.singletonList(getExpectedProxy("http")));
}
 
Example #19
Source File: DelegateInvocationHandlerImpl.java    From jdk1.8-source-analysis with Apache License 2.0 6 votes vote down vote up
public static InvocationHandler create( final Object delegate )
{
    SecurityManager s = System.getSecurityManager();
    if (s != null) {
        s.checkPermission(new DynamicAccessPermission("access"));
    }
    return new InvocationHandler() {
        public Object invoke( Object proxy, Method method, Object[] args )
            throws Throwable
        {
            // This throws an IllegalArgument exception if the delegate
            // is not assignable from method.getDeclaring class.
            try {
                return method.invoke( delegate, args ) ;
            } catch (InvocationTargetException ite) {
                // Propagate the underlying exception as the
                // result of the invocation
                throw ite.getCause() ;
            }
        }
    } ;
}
 
Example #20
Source File: HadoopRecoverableFsDataOutputStream.java    From Flink-CEPplus with Apache License 2.0 6 votes vote down vote up
private static boolean truncate(final FileSystem hadoopFs, final Path file, final long length) throws IOException {
	if (truncateHandle != null) {
		try {
			return (Boolean) truncateHandle.invoke(hadoopFs, file, length);
		}
		catch (InvocationTargetException e) {
			ExceptionUtils.rethrowIOException(e.getTargetException());
		}
		catch (Throwable t) {
			throw new IOException(
					"Truncation of file failed because of access/linking problems with Hadoop's truncate call. " +
							"This is most likely a dependency conflict or class loading problem.");
		}
	}
	else {
		throw new IllegalStateException("Truncation handle has not been initialized");
	}
	return false;
}
 
Example #21
Source File: Connection.java    From jdk8u-dev-jdk with GNU General Public License v2.0 6 votes vote down vote up
private Object createInetSocketAddress(String host, int port)
        throws NoSuchMethodException {

    try {
        Class<?> inetSocketAddressClass =
            Class.forName("java.net.InetSocketAddress");

        Constructor<?> inetSocketAddressCons =
            inetSocketAddressClass.getConstructor(new Class<?>[]{
            String.class, int.class});

        return inetSocketAddressCons.newInstance(new Object[]{
            host, new Integer(port)});

    } catch (ClassNotFoundException |
             InstantiationException |
             InvocationTargetException |
             IllegalAccessException e) {
        throw new NoSuchMethodException();

    }
}
 
Example #22
Source File: ConstructorMethod.java    From commons-jexl with Apache License 2.0 6 votes vote down vote up
@Override
public Object tryInvoke(String name, Object obj, Object... params) {
    try {
        Class<?> ctorClass = ctor.getDeclaringClass();
        boolean invoke = true;
        if (obj != null) {
            if (obj instanceof Class<?>) {
                invoke = ctorClass.equals(obj);
            } else {
                invoke = ctorClass.getName().equals(obj.toString());
            }
        }
        invoke &= name == null || ctorClass.getName().equals(name);
        if (invoke) {
            return ctor.newInstance(params);
        }
    } catch (InstantiationException | IllegalArgumentException | IllegalAccessException xinstance) {
        return Uberspect.TRY_FAILED;
    } catch (InvocationTargetException xinvoke) {
        throw JexlException.tryFailed(xinvoke); // throw
    }
    return Uberspect.TRY_FAILED;
}
 
Example #23
Source File: SaveAsActionTest.java    From PIPE with MIT License 5 votes vote down vote up
@Test
public void performsSaveAsWhenEvenIfPetriNetHasFile()
        throws InvocationTargetException, ParserConfigurationException, NoSuchMethodException,
        IllegalAccessException, TransformerException {
    File file1 = new File("test.xml");
    PetriNetName fileName = new PetriNetFileName(file1);
    when(mockPetriNet.getName()).thenReturn(fileName);
    File file2 = new File("test2.xml");
    when(mockFileChooser.getFiles()).thenReturn(new File[]{file2});
    saveAsAction.actionPerformed(null);
    verify(mockController).saveAsCurrentPetriNet(file2);
}
 
Example #24
Source File: CustomMongoHealthIndicator.java    From hesperides with GNU General Public License v3.0 5 votes vote down vote up
static ServerSessionPool getServerSessionPool(MongoClient mongoClient) {
    try {
        Method privateMethod = Mongo.class.getDeclaredMethod("getServerSessionPool", null);
        privateMethod.setAccessible(true);
        return (ServerSessionPool) privateMethod.invoke(mongoClient);
    } catch (NoSuchMethodException | IllegalAccessException | InvocationTargetException e) {
        throw new RuntimeException(e);
    }
}
 
Example #25
Source File: NativeBinaryExportOperation.java    From thym with Eclipse Public License 1.0 5 votes vote down vote up
@Override
protected void execute(IProgressMonitor monitor) throws CoreException,
		InvocationTargetException, InterruptedException {
	SubMonitor sm = SubMonitor.convert(monitor);
	sm.setWorkRemaining(delegates.size()*10);
	for (AbstractNativeBinaryBuildDelegate delegate : delegates) {
		if(monitor.isCanceled()){ 
			break; 
		}
		delegate.setRelease(true);
		delegate.buildNow(sm.newChild(10));
		try {
			File buildArtifact = delegate.getBuildArtifact();
			File destinationFile = new File(destinationDir, buildArtifact.getName());
			if(destinationFile.exists()){
				String callback = overwriteQuery.queryOverwrite(destinationFile.toString());
				if(IOverwriteQuery.NO.equals(callback)){
					continue;
				}
				if(IOverwriteQuery.CANCEL.equals(callback)){
					break;
				}
			}
			File artifact = delegate.getBuildArtifact();
			if(artifact.isDirectory()){
				FileUtils.copyDirectoryToDirectory(artifact, destinationDir);
			}else{
				FileUtils.copyFileToDirectory(artifact, destinationDir);
			}
			sm.done();
		} catch (IOException e) {
			HybridCore.log(IStatus.ERROR, "Error on NativeBinaryExportOperation", e);
		}
	}
	monitor.done(); 
}
 
Example #26
Source File: TMigrationImpl.java    From n4js with Eclipse Public License 1.0 5 votes vote down vote up
/**
 * <!-- begin-user-doc -->
 * <!-- end-user-doc -->
 * @generated
 */
@Override
public Object eInvoke(int operationID, EList<?> arguments) throws InvocationTargetException {
	switch (operationID) {
		case TypesPackage.TMIGRATION___GET_PRINCIPAL_ARGUMENT_TYPE:
			return getPrincipalArgumentType();
		case TypesPackage.TMIGRATION___GET_MIGRATION_AS_STRING:
			return getMigrationAsString();
	}
	return super.eInvoke(operationID, arguments);
}
 
Example #27
Source File: BidiBase.java    From jdk8u-jdk with GNU General Public License v2.0 5 votes vote down vote up
/**
 * Invokes NumericShaping shape(text,start,count) method.
 */
static void shape(Object shaper, char[] text, int start, int count) {
    if (shapeMethod == null)
        throw new AssertionError("Should not get here");
    try {
        shapeMethod.invoke(shaper, text, start, count);
    } catch (InvocationTargetException e) {
        Throwable cause = e.getCause();
        if (cause instanceof RuntimeException)
            throw (RuntimeException)cause;
        throw new AssertionError(e);
    } catch (IllegalAccessException iae) {
        throw new AssertionError(iae);
    }
}
 
Example #28
Source File: ReplaceWithRemoteAction.java    From APICloud-Studio with GNU General Public License v3.0 5 votes vote down vote up
public void execute(IAction action)  throws InvocationTargetException, InterruptedException {		
		IResource[] resources = null;

		try {
			resources = checkOverwriteOfDirtyResources(getSelectedResources());
		} catch (TeamException e) {
			throw new InvocationTargetException(e);
		}

		// Peform the replace in the background
		ReplaceOperation replaceOperation = new ReplaceOperation(getTargetPart(), resources, this.revision);
//		replaceOperation.setResourcesToUpdate(getSelectedResources());
		replaceOperation.run();
	}
 
Example #29
Source File: SeMetricName.java    From smallrye-metrics with Apache License 2.0 5 votes vote down vote up
private String getParameterName(AnnotatedParameter<?> parameter) {
    try {
        Method method = Method.class.getMethod("getParameters");
        Object[] parameters = (Object[]) method.invoke(parameter.getDeclaringCallable().getJavaMember());
        Object param = parameters[parameter.getPosition()];
        Class<?> Parameter = Class.forName("java.lang.reflect.Parameter");
        if ((Boolean) Parameter.getMethod("isNamePresent").invoke(param)) {
            return (String) Parameter.getMethod("getName").invoke(param);
        } else {
            throw SmallRyeMetricsMessages.msg.unableToRetrieveParameterName(parameter);
        }
    } catch (NoSuchMethodException | IllegalAccessException | InvocationTargetException | ClassNotFoundException cause) {
        throw SmallRyeMetricsMessages.msg.unableToRetrieveParameterName(parameter);
    }
}
 
Example #30
Source File: Handlers.java    From PYX-Reloaded with Apache License 2.0 5 votes vote down vote up
@NotNull
public static BaseHandler obtain(String op) throws BaseCahHandler.CahException {
    BaseHandler handler;
    Class<? extends BaseHandler> cls = Handlers.LIST.get(op);
    if (cls != null) {
        handler = handlers.get(cls);
        if (handler == null) {
            try {
                Constructor<?> constructor = cls.getConstructors()[0];
                Parameter[] parameters = constructor.getParameters();
                Object[] objects = new Object[parameters.length];

                for (int i = 0; i < parameters.length; i++)
                    objects[i] = Providers.get(parameters[i].getAnnotations()[0].annotationType()).get();

                handler = (BaseHandler) constructor.newInstance(objects);
                handlers.put(cls, handler);
            } catch (InstantiationException | IllegalAccessException | InvocationTargetException ex) {
                throw new BaseCahHandler.CahException(Consts.ErrorCode.BAD_OP, ex);
            }
        }
    } else {
        throw new BaseCahHandler.CahException(Consts.ErrorCode.BAD_OP);
    }

    return handler;
}