Example usage for java.lang.reflect InvocationTargetException getCause

List of usage examples for java.lang.reflect InvocationTargetException getCause

Introduction

In this page you can find the example usage for java.lang.reflect InvocationTargetException getCause.

Prototype

public Throwable getCause() 

Source Link

Document

Returns the cause of this exception (the thrown target exception, which may be null ).

Usage

From source file:com.jaspersoft.studio.server.wizard.find.FindResourcePage.java

private void createTreeView(CTabFolder tabFolder) {
    CTabItem bptab = new CTabItem(tabFolder, SWT.NONE);
    bptab.setText("Tree");

    RepositoryComposite rcom = new RepositoryComposite(tabFolder, SWT.NONE, finderUI.getServerProfile()) {

        @Override/*w  w w.  j  a v a  2  s.co  m*/
        protected void okPressed() {
            ((FindWizardDialog) getContainer()).finishPressed();
        }

        @Override
        protected void setOkButtonEnabled(boolean resCompatible) {
            FindResourcePage.this.setPageComplete(resCompatible);
        }

        @Override
        protected void createReadRepositoryJob() {
            try {
                getContainer().run(true, true, new IRunnableWithProgress() {

                    @Override
                    public void run(IProgressMonitor monitor)
                            throws InvocationTargetException, InterruptedException {
                        doReadRepository(monitor);
                    }
                });
            } catch (InvocationTargetException e) {
                UIUtils.showError(e.getCause());
            } catch (InterruptedException e) {
                UIUtils.showError(e.getCause());
            }
        }

        @Override
        public boolean isResourceCompatible(MResource r) {
            if (Misc.isNullOrEmpty(finderUI.getTypes()))
                return true;
            String type = WsTypes.INST().toRestType(r.getValue().getWsType());
            for (String t : finderUI.getTypes()) {
                if (t.equals(type))
                    return true;
            }
            return false;
        }

        /*
         * (non-Javadoc)
         * 
         * @see
         * com.jaspersoft.studio.server.properties.dialog.RepositoryComposite
         * #setResource(com.jaspersoft.studio.server.model.MResource)
         */
        @Override
        public void setResource(MResource res) {
            super.setResource(res);
            value = res.getValue();
        }
    };
    rcom.setLayoutData(new GridData(GridData.FILL_BOTH));

    bptab.setControl(rcom);
}

From source file:uk.ac.diamond.scisoft.ncd.rcp.handlers.DataReductionHandler.java

@Override
public Object execute(ExecutionEvent event) throws ExecutionException {

    final IWorkbenchWindow window = PlatformUI.getWorkbench().getActiveWorkbenchWindow();
    IWorkbenchPage page = window.getActivePage();
    IStructuredSelection sel = (IStructuredSelection) page.getSelection(ProjectExplorer.VIEW_ID);
    if (sel == null || sel.isEmpty()) {
        sel = (IStructuredSelection) page.getSelection(Activator.FILEVIEW_ID);
    }/*  w w  w.  j  a v a 2 s.co  m*/

    if (sel != null && !sel.isEmpty()) {

        try {
            // We get the data reduction service using OSGI
            service = (IDataReductionService) Activator.getService(IDataReductionService.class);
            // This is a workaround for DAWNSCI-858
            if (service == null) {
                ActorBundleInitializer initer = com.isencia.passerelle.starter.Activator.getInitializer();
                if (initer != null)
                    initer.start();
            }
            if (service == null) {
                throw new RuntimeException("Cannot find IDataReductionService using activator!");
            }

            // Get data from NcdProcessingSourceProvider's and store in IDataReductionContext
            context = service.createContext();
            createData(context, window);

            // Now we configure the context, which throws exceptions if 
            // the configuration is invalid.
            createMaskAndRegion(context);
            service.configure(context);
        } catch (Exception e) {
            String msg = "SCISOFT NCD: Error reading data reduction parameters";
            logger.error(msg, e);
            MultiStatus mStatus = new MultiStatus(Activator.PLUGIN_ID, IStatus.ERROR, msg, e);
            for (StackTraceElement ste : e.getStackTrace()) {
                mStatus.add(new Status(IStatus.ERROR, Activator.PLUGIN_ID, ste.toString()));
            }
            StatusManager.getManager().handle(mStatus, StatusManager.BLOCK | StatusManager.SHOW);
            return Boolean.FALSE;
        }

        if (context.isEnableSector() && !isCalibrationResultsBean(context)) {
            boolean proceed = MessageDialog.openConfirm(window.getShell(), "Missing NCD calibration data",
                    "IMPORTANT! NCD calibration data was not found for currently selected SAXS detector.\n"
                            + "Data reduction pipeline will look for calibration information in the input files.\n"
                            + "Proceed with data reduction anyway?");
            if (!proceed) {
                return Boolean.FALSE;
            }
        }

        selObjects = sel.toArray();

        boolean runModal = uk.ac.diamond.scisoft.ncd.core.rcp.Activator.getDefault().getPreferenceStore()
                .getBoolean(NcdPreferences.NCD_REDUCTION_MODAL);
        final NcdDataReductionJob ncdProcess = new NcdDataReductionJob();
        if (runModal) {
            try {
                ProgressMonitorDialog dlg = new ProgressMonitorDialog(window.getShell());
                dlg.run(true, true, ncdProcess);
            } catch (InvocationTargetException ex) {
                Throwable cause = ex.getCause();
                String msg = "NCD Data Reduction has failed";
                logger.error(msg, cause);
                Status status = new Status(IStatus.ERROR, Activator.PLUGIN_ID, msg, cause);
                StatusManager.getManager().handle(status, StatusManager.BLOCK | StatusManager.SHOW);
                return Boolean.FALSE;
            } catch (InterruptedException ex) {
                Throwable cause = ex.getCause();
                String msg = "NCD Data Reduction was interrupted";
                logger.error(msg, cause);
                Status status = new Status(IStatus.ERROR, Activator.PLUGIN_ID, msg, cause);
                StatusManager.getManager().handle(status, StatusManager.BLOCK | StatusManager.SHOW);
                return Boolean.FALSE;
            }
        } else {
            final Job ncdJob = new Job("Running NCD data reduction") {

                @Override
                protected IStatus run(IProgressMonitor monitor) {
                    monitor.beginTask("Running NCD data reduction",
                            context.getWorkAmount() * selObjects.length);
                    ncdProcess.run(monitor);
                    monitor.done();
                    return Status.OK_STATUS;
                }
            };

            ncdJob.setUser(true);
            ncdJob.schedule();
        }
    } else {
        String msg = "Please select NeXus files to process in Project Explorer view before running NCD Data Reduction.";
        Status status = new Status(IStatus.CANCEL, Activator.PLUGIN_ID, msg);
        StatusManager.getManager().handle(status, StatusManager.BLOCK | StatusManager.SHOW);
    }
    return Boolean.TRUE;
}

From source file:org.eclipse.wb.internal.core.utils.reflect.ReflectionUtils.java

/**
 * @return the {@link Object} result of invoking method with given signature.
 *///from   www  .ja va 2s.  c  o m
public static Object invokeMethod(Object object, String signature, Object... arguments) throws Exception {
    Assert.isNotNull(object);
    Assert.isNotNull(arguments);
    // prepare class/object
    Class<?> refClass = getRefClass(object);
    Object refObject = getRefObject(object);
    // prepare method
    Method method = getMethodBySignature(refClass, signature);
    Assert.isNotNull(method, "Can not find method " + signature + " in " + refClass);
    // do invoke
    try {
        return method.invoke(refObject, arguments);
    } catch (InvocationTargetException e) {
        throw propagate(e.getCause());
    }
}

From source file:android.bus.EventBus.java

void invokeSubscriber(Subscription subscription, Object event) {
    try {//from w  w  w  .  jav a2 s  .c  o m
        subscription.subscriberMethod.method.invoke(subscription.subscriber, event);
    } catch (InvocationTargetException e) {
        handleSubscriberException(subscription, event, e.getCause());
    } catch (IllegalAccessException e) {
        throw new IllegalStateException("Unexpected exception", e);
    }
}

From source file:hu.netmind.beankeeper.node.impl.NodeManagerImpl.java

/**
 * Make the reflection call locally, for the local services.
 *///from ww w. j  a va  2 s .  c om
public Object callLocal(String service, String method, Class[] parameterTypes, Object[] parameters) {
    ensureState(NodeState.CONNECTED);
    // Get the service, and with the help of relfection, call the named
    // method
    Service serviceObject = context.getService(service);
    try {
        Method methodObject = serviceObject.getClass().getMethod(method, parameterTypes);
        return methodObject.invoke(serviceObject, parameters);
    } catch (InvocationTargetException e) {
        if (e.getCause() instanceof StoreException)
            throw (StoreException) e.getCause();
        throw new StoreException("received exception while invoking '" + method + "', of service: " + service,
                e.getCause());
    } catch (StoreException e) {
        throw e;
    } catch (Exception e) {
        throw new StoreException("could not invoke method '" + method + "', of service: " + service, e);
    }
}

From source file:com.liferay.maven.plugins.AbstractLiferayMojo.java

protected void executeTool(String toolClassName, ClassLoader classLoader, String[] args) throws Exception {

    Thread currentThread = Thread.currentThread();

    ClassLoader contextClassLoader = currentThread.getContextClassLoader();

    currentThread.setContextClassLoader(classLoader);

    SecurityManager currentSecurityManager = System.getSecurityManager();

    // Required to prevent premature exit by DBBuilder. See LPS-7524.

    SecurityManager securityManager = new SecurityManager() {

        public void checkPermission(Permission permission) {
        }/*from  w w w .j  av  a 2 s .  c o  m*/

        public void checkExit(int status) {
            throw new SecurityException();
        }

    };

    System.setSecurityManager(securityManager);

    try {
        System.setProperty("external-properties",
                "com/liferay/portal/tools/dependencies" + "/portal-tools.properties");
        System.setProperty("org.apache.commons.logging.Log", "org.apache.commons.logging.impl.Log4JLogger");

        Class<?> clazz = classLoader.loadClass(toolClassName);

        Method method = clazz.getMethod("main", String[].class);

        method.invoke(null, (Object) args);
    } catch (InvocationTargetException ite) {
        if (ite.getCause() instanceof SecurityException) {
        } else {
            throw ite;
        }
    } finally {
        currentThread.setContextClassLoader(contextClassLoader);

        System.clearProperty("org.apache.commons.logging.Log");

        System.setSecurityManager(currentSecurityManager);
    }
}

From source file:org.springframework.integration.mqtt.MqttAdapterTests.java

@Test
public void testSubscribeFailure() throws Exception {
    DefaultMqttPahoClientFactory factory = new DefaultMqttPahoClientFactory();
    factory.setCleanSession(false);/* ww  w  .  j ava 2s  .  co  m*/
    factory.setConnectionTimeout(23);
    factory.setKeepAliveInterval(45);
    factory.setPassword("pass");
    MemoryPersistence persistence = new MemoryPersistence();
    factory.setPersistence(persistence);
    final SocketFactory socketFactory = mock(SocketFactory.class);
    factory.setSocketFactory(socketFactory);
    final Properties props = new Properties();
    factory.setSslProperties(props);
    factory.setUserName("user");
    Will will = new Will("foo", "bar".getBytes(), 2, true);
    factory.setWill(will);

    factory = spy(factory);
    MqttAsyncClient aClient = mock(MqttAsyncClient.class);
    final MqttClient client = mock(MqttClient.class);
    willAnswer(invocation -> client).given(factory).getClientInstance(anyString(), anyString());
    given(client.isConnected()).willReturn(true);
    new DirectFieldAccessor(client).setPropertyValue("aClient", aClient);
    willAnswer(new CallsRealMethods()).given(client).connect(any(MqttConnectOptions.class));
    willAnswer(new CallsRealMethods()).given(client).subscribe(any(String[].class), any(int[].class));
    willReturn(alwaysComplete).given(aClient).connect(any(MqttConnectOptions.class), any(), any());

    IMqttToken token = mock(IMqttToken.class);
    given(token.getGrantedQos()).willReturn(new int[] { 0x80 });
    willReturn(token).given(aClient).subscribe(any(String[].class), any(int[].class), any(), any());

    MqttPahoMessageDrivenChannelAdapter adapter = new MqttPahoMessageDrivenChannelAdapter("foo", "bar", factory,
            "baz", "fix");
    AtomicReference<Method> method = new AtomicReference<>();
    ReflectionUtils.doWithMethods(MqttPahoMessageDrivenChannelAdapter.class, m -> {
        m.setAccessible(true);
        method.set(m);
    }, m -> m.getName().equals("connectAndSubscribe"));
    assertNotNull(method.get());
    try {
        method.get().invoke(adapter);
        fail("Expected InvocationTargetException");
    } catch (InvocationTargetException e) {
        assertThat(e.getCause(), instanceOf(MqttException.class));
        assertThat(((MqttException) e.getCause()).getReasonCode(),
                equalTo((int) MqttException.REASON_CODE_SUBSCRIBE_FAILED));
    }
}

From source file:org.apache.hadoop.hive.metastore.utils.MetaStoreServerUtils.java

/**
 * create listener instances as per the configuration.
 *
 * @param clazz Class of the listener//  w w  w.jav  a 2 s .  c  om
 * @param conf configuration object
 * @param listenerImplList Implementation class name
 * @return instance of the listener
 * @throws MetaException if there is any failure instantiating the class
 */
public static <T> List<T> getMetaStoreListeners(Class<T> clazz, Configuration conf, String listenerImplList)
        throws MetaException {
    List<T> listeners = new ArrayList<T>();

    if (StringUtils.isBlank(listenerImplList)) {
        return listeners;
    }

    String[] listenerImpls = listenerImplList.split(",");
    for (String listenerImpl : listenerImpls) {
        try {
            T listener = (T) Class.forName(listenerImpl.trim(), true, JavaUtils.getClassLoader())
                    .getConstructor(Configuration.class).newInstance(conf);
            listeners.add(listener);
        } catch (InvocationTargetException ie) {
            LOG.error("Got InvocationTargetException", ie);
            throw new MetaException(
                    "Failed to instantiate listener named: " + listenerImpl + ", reason: " + ie.getCause());
        } catch (Exception e) {
            LOG.error("Got Exception", e);
            throw new MetaException("Failed to instantiate listener named: " + listenerImpl + ", reason: " + e);
        }
    }

    return listeners;
}

From source file:com.app.test.util.SearchQueryUtilTest.java

@Test
public void testValidateSearchQueryInvalidKeywords() throws Exception {
    Method method = _clazz.getDeclaredMethod("_validateSearchQuery", SearchQuery.class);

    method.setAccessible(true);//from  w w w .  jav a 2  s . co  m

    SearchQuery searchQuery = new SearchQuery();

    try {
        method.invoke(_classInstance, searchQuery);

        Assert.fail();
    } catch (InvocationTargetException ite) {
        Assert.assertTrue(ite.getCause() instanceof SearchQueryException);
    }
}

From source file:com.app.test.util.SearchQueryUtilTest.java

@Test
public void testValidateSearchQueryInvalidPriceRange() throws Exception {
    Method method = _clazz.getDeclaredMethod("_validateSearchQuery", SearchQuery.class);

    method.setAccessible(true);/*w ww  . ja v  a  2 s .  c  o m*/

    SearchQuery searchQuery = new SearchQuery();

    searchQuery.setKeywords("Test keywords");
    searchQuery.setMinPrice(5.00);
    searchQuery.setMaxPrice(0.00);

    try {
        method.invoke(_classInstance, searchQuery);

        Assert.fail();
    } catch (InvocationTargetException ite) {
        Assert.assertTrue(ite.getCause() instanceof SearchQueryException);
    }
}