Example usage for java.lang.reflect InvocationTargetException InvocationTargetException

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

Introduction

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

Prototype

public InvocationTargetException(Throwable target) 

Source Link

Document

Constructs a InvocationTargetException with a target exception.

Usage

From source file:org.codice.ddf.commands.catalog.SubjectCommands.java

private Object runWithUserName() throws InvocationTargetException {
    try {//  w  ww .jav a  2 s  .co m
        String password = getLine("Password for " + user + ": ", false);
        Subject subject = security.getSubject(user, password);

        if (subject == null) {
            printErrorMessage("Invalid username/password");
            return null;
        }

        return subject.execute(this::executeWithSubject);
    } catch (ExecutionException e) {
        LOGGER.error("Failed to run command: {}", e.getCause().getMessage(), e.getCause());
        throw new InvocationTargetException(e.getCause());
    } catch (IOException e) {
        LOGGER.error("Failed to run command", e);
        printErrorMessage("Failed to read password");
    }

    return null;
}

From source file:org.codice.ddf.security.common.Security.java

/**
 * Runs the {@link Callable} in the current thread as the current security framework's
 * {@link Subject}. If the security framework's {@link Subject} is not currently set and
 * the Java Subject contains the admin role, elevates and runs the {@link Callable} as the
 * system {@link Subject}./*from  w ww.  j  a v a  2  s  .  c o m*/
 *
 * @param codeToRun code to run
 * @param <T>       type of the returned value
 * @return value returned by the {@link Callable}
 * @throws SecurityServiceException  if the current subject didn' have enough permissions to run
 *                                   the code
 * @throws InvocationTargetException wraps any exception thrown by {@link Callable#call()}.
 *                                   {@link Callable} exception can be retrieved using the
 *                                   {@link InvocationTargetException#getCause()}.
 */
public <T> T runWithSubjectOrElevate(@NotNull Callable<T> codeToRun)
        throws SecurityServiceException, InvocationTargetException {
    notNull(codeToRun, "Callable cannot be null");

    try {
        try {
            org.apache.shiro.subject.Subject subject = org.apache.shiro.SecurityUtils.getSubject();
            return subject.execute(codeToRun);
        } catch (IllegalStateException | UnavailableSecurityManagerException e) {
            LOGGER.debug("No shiro subject available for running command, trying with Java Subject");
        }

        if (!javaSubjectHasAdminRole()) {
            SecurityLogger.audit(INSUFFICIENT_PERMISSIONS_ERROR);
            throw new SecurityServiceException(INSUFFICIENT_PERMISSIONS_ERROR);
        }

        Subject subject = getSystemSubject();

        if (subject == null) {
            SecurityLogger.audit(INSUFFICIENT_PERMISSIONS_ERROR);
            throw new SecurityServiceException(INSUFFICIENT_PERMISSIONS_ERROR);
        }

        SecurityLogger.auditWarn("Elevating current user permissions to use System subject");
        return subject.execute(codeToRun);
    } catch (ExecutionException e) {
        throw new InvocationTargetException(e.getCause());
    }
}

From source file:org.ebayopensource.turmeric.eclipse.typelibrary.ui.wizards.pages.ImportTypesWizardPage.java

@Override
public void run(IProgressMonitor monitor) throws InvocationTargetException, InterruptedException {
    try {//w w w.jav  a2  s . c o m
        monitor.beginTask("Extracting schema types from file...", IProgressMonitor.UNKNOWN);
        if (path.endsWith(SOAProjectConstants.XSD)) {
            ImportTypesFromXSDParser schmaHandler = new ImportTypesFromXSDParser();
            schmaHandler.cutXSD(path);
            types = schmaHandler.getTypeModels();
            referedTypes = schmaHandler.getReferedTLTypes();
        } else if (path.endsWith(SOAProjectConstants.WSDL)) {
            ImportTypesFromWSDLParser wsdlHandler = new ImportTypesFromWSDLParser();
            wsdlHandler.cutWSDL(path.toString());
            types = wsdlHandler.getTypeModels();
            referedTypes = wsdlHandler.getReferedTLTypes();
        }
    } catch (Exception e) {
        throw new InvocationTargetException(e);
    } finally {
        monitor.done();
    }
}

From source file:org.ebayopensource.turmeric.frameworkjars.ui.CopyLibraryDialog.java

@Override
protected void okPressed() {
    if (metadata == null)
        return;/*from  ww  w .  j  a v a  2 s .c om*/
    final String destination = this.destinationText.getText();
    final IRunnableWithProgress runnable = new IRunnableWithProgress() {

        @Override
        public void run(IProgressMonitor monitor) throws InvocationTargetException, InterruptedException {
            monitor.beginTask("Copying jars for library ->" + metadata + "...", IProgressMonitor.UNKNOWN);
            try {
                monitor.internalWorked(20);
                IMavenEclipseApi api = MavenApiPlugin.getDefault().getMavenEclipseApi();

                File destDir = new File(destination);
                if (destDir.exists() == false)
                    destDir.mkdir();
                else {
                    try {
                        FileUtils.cleanDirectory(destDir);
                    } catch (IOException e) {
                        e.printStackTrace();
                    }
                }
                monitor.internalWorked(20);
                try {
                    for (Artifact artifact : api.resolveArtifactAsClasspath(metadata)) {
                        File artifactFile = artifact.getFile();
                        if (artifactFile.getName().endsWith(".pom")) {
                            System.out.println("bad");
                        }
                        monitor.setTaskName("Copying from " + artifactFile + " to " + destDir);
                        FileUtils.copyFileToDirectory(artifact.getFile(), destDir);
                        monitor.internalWorked(20);
                    }
                } catch (Exception e) {
                    e.printStackTrace();
                }
            } catch (Exception e) {
                throw new InvocationTargetException(e);
            } finally {
                monitor.done();
            }
        }
    };

    final IProgressService service = PlatformUI.getWorkbench().getProgressService();
    try {
        service.run(false, false, runnable);
    } catch (Exception e) {
        ErrorDialog.openError(getShell(), "Error Occurred", "error occurred while copying library->" + metadata,
                new Status(IStatus.ERROR, "org.ebayopensource.turmeric", e.getLocalizedMessage(), e));
        e.printStackTrace();
    }

    super.okPressed();
}

From source file:org.eclipse.buckminster.jnlp.p2.wizard.install.InstallWizard.java

void retrieveStackInfo() throws InterruptedException {
    if (m_distroP2Properties == null) {
        try {/*w w  w .  j a va 2s  . c  o m*/
            ((AdvancedWizardDialog) getContainer()).disableNavigation();

            getContainer().run(true, true, new IRunnableWithProgress() {

                public void run(IProgressMonitor monitor)
                        throws InvocationTargetException, InterruptedException {
                    try {
                        m_distroP2Properties = m_distroProvider.getDistroP2Properties(m_draft, m_cspecId,
                                monitor);
                        m_opml = null;

                        String opmlString = m_distroP2Properties.getProperty(PROP_OPML);

                        if (opmlString != null) {
                            IParser<OPML> opmlParser = CorePlugin.getDefault().getParserFactory()
                                    .getOPMLParser(true);
                            m_opml = opmlParser.parse("byte image", new ByteArrayInputStream(
                                    TransferUtils.decompress(opmlString.getBytes("UTF-8"))));
                        }
                    } catch (InterruptedException e) {
                        throw e;
                    } catch (Exception e) {
                        throw new InvocationTargetException(e);
                    }

                    m_installLocation = Path
                            .fromOSString(MaterializationUtils.getDefaultDestination(m_artifactName));
                }
            });
        } catch (InterruptedException e) {
            throw e;
        } catch (Exception e) {
            if (e instanceof JNLPException)
                throw (JNLPException) e;

            Throwable originalException = e;

            if (e instanceof InvocationTargetException && e.getCause() != null)
                originalException = e.getCause();

            throw new JNLPException("Cannot read distro specification", ERROR_CODE_REMOTE_IO_EXCEPTION,
                    originalException);
        } finally {
            getContainer().updateButtons();
        }
    }

    if (m_distroP2Properties.size() == 0)
        throw new JNLPException("Materialization properties were not retrieved",
                ERROR_CODE_MISSING_PROPERTY_EXCEPTION);
}

From source file:org.eclipse.buckminster.jnlp.wizard.install.InstallWizard.java

void retrieveDistro(final Long distroId) {
    m_distro = null;/*from   w  ww.j  a va  2s  .  co  m*/
    m_cachedBOM = null;
    m_cachedBOMURL = null;

    if (distroId == null)
        return;

    m_distro = m_retrievedDistroCache.get(distroId);

    try {
        getContainer().run(true, false, new IRunnableWithProgress() {

            public void run(IProgressMonitor monitor) throws InvocationTargetException, InterruptedException {
                monitor.beginTask(null, IProgressMonitor.UNKNOWN);
                monitor.subTask(Messages.retrieving_distro_specification);

                if (m_distro == null) {
                    try {
                        m_distro = m_distroProvider.getDistro(m_draft, m_cspecId, distroId);
                    } catch (Exception e) {
                        throw new InvocationTargetException(e);
                    }
                    m_retrievedDistroCache.put(distroId, m_distro);
                }

                m_builder.initFrom(m_distro.getMspec());

                // extra properties
                m_builder.getProperties().put("distro.name", m_artifactName); //$NON-NLS-1$

                IPath location = m_builder.getInstallLocation() == null
                        ? Path.fromOSString(MaterializationUtils.getDefaultDestination(m_artifactName))
                        : MaterializationUtils.expandPath(m_builder, m_builder.getInstallLocation());
                m_builder.setInstallLocation(location);

                m_cachedBOM = m_distro.getBom();
                saveBOMLocally();

                initMSpecTree();

                monitor.done();
            }
        });
    } catch (Exception e) {
        if (e instanceof JNLPException)
            throw (JNLPException) e;

        Throwable originalException = e;

        if (e instanceof InvocationTargetException && e.getCause() != null)
            originalException = e.getCause();

        throw new JNLPException(Messages.cannot_read_distro_specification, ERROR_CODE_REMOTE_IO_EXCEPTION,
                originalException);
    }
}

From source file:org.eclipse.buckminster.jnlp.wizard.install.InstallWizard.java

void retrieveDistroVariants() {
    m_distroVariants = null;/*w ww  .j a v  a2  s  .co m*/
    try {
        getContainer().run(true, false, new IRunnableWithProgress() {

            public void run(IProgressMonitor monitor) throws InvocationTargetException, InterruptedException {
                monitor.beginTask(null, IProgressMonitor.UNKNOWN);
                monitor.subTask(Messages.retrieving_stack_variations);

                try {
                    m_distroVariants = m_distroProvider.getDistroVariants(m_draft, m_cspecId);
                } catch (Exception e) {
                    throw new InvocationTargetException(e);
                }

                monitor.done();
            }
        });
    } catch (Exception e) {
        Throwable originalException = e;

        if (e instanceof InvocationTargetException && e.getCause() != null)
            originalException = e.getCause();

        throw new JNLPException(Messages.cannot_read_stack_variations, ERROR_CODE_REMOTE_IO_EXCEPTION,
                originalException);
    }
}

From source file:org.eclipse.jubula.rc.swing.driver.EventThreadQueuerAwtImpl.java

/** {@inheritDoc} */
public Object invokeAndWait(String name, IRunnable runnable) throws StepExecutionException {

    Validate.notNull(runnable, "runnable must not be null"); //$NON-NLS-1$

    RunnableWrapper wrapper = new RunnableWrapper(name, runnable);
    try {//from w  ww. j a  v a2s  .  com
        if (SwingUtilities.isEventDispatchThread()) {
            wrapper.run();
        } else {
            SwingUtilities.invokeAndWait(wrapper);
        }

        StepExecutionException exception = wrapper.getException();
        if (exception != null) {
            throw new InvocationTargetException(exception);
        }
    } catch (InterruptedException ie) {
        // this (the waiting) thread was interrupted -> error
        log.error(ie);
        throw new StepExecutionException(ie);
    } catch (InvocationTargetException ite) {
        // the run() method from IRunnable has thrown an exception
        // -> log on info
        // -> throw a StepExecutionException
        Throwable thrown = ite.getTargetException();
        if (thrown instanceof StepExecutionException) {
            if (log.isInfoEnabled()) {
                log.info(ite);
            }
            throw (StepExecutionException) thrown;
        }

        // any other (unchecked) Exception from IRunnable.run()
        log.error("exception thrown by '" + wrapper.getName() //$NON-NLS-1$
                + "':", thrown); //$NON-NLS-1$
        throw new StepExecutionException(thrown);
    }

    return wrapper.getResult();
}

From source file:org.eclipse.jubula.rc.swt.driver.EventThreadQueuerSwtImpl.java

/** {@inheritDoc} */
public Object invokeAndWait(String name, IRunnable runnable)
        throws IllegalArgumentException, StepExecutionException {

    Validate.notNull(runnable, "runnable must not be null"); //$NON-NLS-1$
    RunnableWrapper wrapper = new RunnableWrapper(name, runnable);
    try {//from w w  w  .  j a va2 s .  c om
        Display display = getDisplay();
        if (display.isDisposed()) {
            // this may happen e.g. during the shutdown process of the AUT
            // see http://bugzilla.bredex.de/907 for additional information
            log.warn("Display has already been disposed - skipping IRunnable invocation!"); //$NON-NLS-1$
            return null;
        }
        display.syncExec(wrapper);
        StepExecutionException exception = wrapper.getException();
        if (exception != null) {
            throw new InvocationTargetException(exception);
        }
    } catch (InvocationTargetException ite) {
        // the run() method from IRunnable has thrown an exception
        // -> log on info
        // -> throw a StepExecutionException
        Throwable thrown = ite.getTargetException();
        if (thrown instanceof StepExecutionException) {
            if (log.isInfoEnabled()) {
                log.info(ite);
            }
            throw (StepExecutionException) thrown;
        }
        // any other (unchecked) Exception from IRunnable.run()
        log.error("exception thrown by '" + wrapper.getName() //$NON-NLS-1$
                + "':", thrown); //$NON-NLS-1$
        throw new StepExecutionException(thrown);
    }
    return wrapper.getResult();
}

From source file:org.eclipse.mylyn.tasks.ui.wizards.AbstractRepositorySettingsPage.java

/**
 * Validate settings provided by the {@link #getValidator(TaskRepository) validator}, typically the server settings.
 *
 * @since 2.0//from w  ww.  j  av a2 s.  c o m
 */
protected void validateSettings() {
    TaskRepository newTaskRepository = createTaskRepository();
    final Validator validator = getValidator(newTaskRepository);
    if (validator == null) {
        return;
    }

    try {
        getWizard().getContainer().run(true, true, new IRunnableWithProgress() {
            public void run(IProgressMonitor monitor) throws InvocationTargetException, InterruptedException {
                monitor.beginTask(Messages.AbstractRepositorySettingsPage_Validating_server_settings,
                        IProgressMonitor.UNKNOWN);
                try {
                    validator.run(monitor);
                    if (validator.getStatus() == null) {
                        validator.setStatus(Status.OK_STATUS);
                    }
                } catch (CoreException e) {
                    validator.setStatus(e.getStatus());
                } catch (OperationCanceledException e) {
                    validator.setStatus(Status.CANCEL_STATUS);
                    throw new InterruptedException();
                } catch (Exception e) {
                    throw new InvocationTargetException(e);
                } finally {
                    monitor.done();
                }
            }
        });
    } catch (InvocationTargetException e) {
        StatusManager.getManager()
                .handle(new Status(IStatus.ERROR, TasksUiPlugin.ID_PLUGIN,
                        Messages.AbstractRepositorySettingsPage_Internal_error_validating_repository, e),
                        StatusManager.SHOW | StatusManager.LOG);
        return;
    } catch (InterruptedException e) {
        // canceled
        return;
    }

    getWizard().getContainer().updateButtons();
    applyValidatorResult(validator);
    if (isValid) {
        saveToValidatedProperties(newTaskRepository);
    }
}