Example usage for java.lang.reflect InvocationTargetException getTargetException

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

Introduction

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

Prototype

public Throwable getTargetException() 

Source Link

Document

Get the thrown target exception.

Usage

From source file:org.apache.pluto.container.util.PlutoTestCase.java

protected void assertException(Object target, String methodName, Class[] parameterClasses, Object[] parameters,
        Class exceptionType) {/*from w  w w.j a v  a 2  s.co m*/
    try {
        Class targetClass = target.getClass();
        Method method = targetClass.getMethod(methodName, parameterClasses);
        method.invoke(target, parameters);
    } catch (InvocationTargetException ite) {
        Throwable t = ite.getTargetException();
        if (!t.getClass().equals(exceptionType)) {
            fail("Incorrect Exception thrown.  Expected: " + exceptionType.getName() + ", recieved "
                    + t.getClass().getName());
        }
    } catch (Throwable t) {
        fail("Invalid Test.  Reflection invocation and setup failed.");
    }
}

From source file:org.apache.sentry.binding.hbaseindexer.TestHBaseIndexerAuthzBinding.java

/**
 * Test that incorrect specification of the provider resource
 * throws an exception/*ww  w.  jav  a 2s  . com*/
 */
@Test
public void testResourceNotFound() throws Exception {
    HBaseIndexerAuthzConf indexerAuthzConf = new HBaseIndexerAuthzConf(
            Resources.getResource("sentry-site.xml"));
    setUsableAuthzConf(indexerAuthzConf);

    // bogus specification
    indexerAuthzConf.set(AuthzConfVars.AUTHZ_PROVIDER_RESOURCE.getVar(),
            new File(baseDir, "test-authz-bogus-provider.ini").getPath());
    try {
        new HBaseIndexerAuthzBinding(indexerAuthzConf);
        Assert.fail("Expected InvocationTargetException");
    } catch (InvocationTargetException e) {
        assertTrue(e.getTargetException() instanceof FileNotFoundException);
    }

    // missing specification
    indexerAuthzConf.unset(AuthzConfVars.AUTHZ_PROVIDER_RESOURCE.getVar());
    try {
        new HBaseIndexerAuthzBinding(indexerAuthzConf);
        Assert.fail("Expected InvocationTargetException");
    } catch (InvocationTargetException e) {
        assertTrue(e.getTargetException() instanceof IllegalArgumentException);
    }
}

From source file:org.apache.sentry.binding.solr.TestSolrAuthzBinding.java

/**
 * Test that incorrect specification of the provider resource
 * throws an exception/*from  w  w  w  . j av  a2  s.c  o  m*/
 */
@Test
public void testResourceNotFound() throws Exception {
    SolrAuthzConf solrAuthzConf = new SolrAuthzConf(Resources.getResource("sentry-site.xml"));
    setUsableAuthzConf(solrAuthzConf);

    // bogus specification
    solrAuthzConf.set(AuthzConfVars.AUTHZ_PROVIDER_RESOURCE.getVar(),
            new File(baseDir, "test-authz-bogus-provider.ini").getPath());
    try {
        new SolrAuthzBinding(solrAuthzConf);
        Assert.fail("Expected InvocationTargetException");
    } catch (InvocationTargetException e) {
        assertTrue(e.getTargetException() instanceof FileNotFoundException);
    }

    // missing specification
    solrAuthzConf.unset(AuthzConfVars.AUTHZ_PROVIDER_RESOURCE.getVar());
    try {
        new SolrAuthzBinding(solrAuthzConf);
        Assert.fail("Expected InvocationTargetException");
    } catch (InvocationTargetException e) {
        assertTrue(e.getTargetException() instanceof IllegalArgumentException);
    }
}

From source file:org.apache.sling.ide.eclipse.ui.internal.InstallEditorSection.java

private void initialize() {

    final ISlingLaunchpadConfiguration config = launchpadServer.getConfiguration();

    quickLocalInstallButton.setSelection(config.bundleInstallLocally());
    bundleLocalInstallButton.setSelection(!config.bundleInstallLocally());

    SelectionListener listener = new SelectionAdapter() {

        @Override//from  ww  w .  ja va2 s .  co m
        public void widgetSelected(SelectionEvent e) {
            execute(new SetBundleInstallLocallyCommand(server, quickLocalInstallButton.getSelection()));
        }
    };

    quickLocalInstallButton.addSelectionListener(listener);
    bundleLocalInstallButton.addSelectionListener(listener);

    Version serverVersion = launchpadServer
            .getBundleVersion(EmbeddedArtifactLocator.SUPPORT_BUNDLE_SYMBOLIC_NAME);
    final EmbeddedArtifact supportBundle = artifactLocator.loadToolingSupportBundle();

    final Version embeddedVersion = new Version(supportBundle.getVersion());

    updateActionArea(serverVersion, embeddedVersion);

    installOrUpdateSupportBundleLink.addHyperlinkListener(new HyperlinkAdapter() {

        @Override
        public void linkActivated(HyperlinkEvent e) {

            ProgressMonitorDialog dialog = new ProgressMonitorDialog(getShell());
            dialog.setCancelable(true);
            try {
                dialog.run(true, false, new IRunnableWithProgress() {

                    @Override
                    public void run(IProgressMonitor monitor)
                            throws InvocationTargetException, InterruptedException {
                        final Version remoteVersion;
                        monitor.beginTask("Installing support bundle", 3);
                        // double-check, just in case
                        monitor.setTaskName("Getting remote bundle version");

                        Version deployedVersion;
                        final String message;
                        try {
                            RepositoryInfo repositoryInfo = ServerUtil.getRepositoryInfo(server.getOriginal(),
                                    monitor);
                            OsgiClient client = osgiClientFactory.createOsgiClient(repositoryInfo);
                            remoteVersion = client
                                    .getBundleVersion(EmbeddedArtifactLocator.SUPPORT_BUNDLE_SYMBOLIC_NAME);
                            deployedVersion = remoteVersion;

                            monitor.worked(1);

                            if (remoteVersion != null && remoteVersion.compareTo(embeddedVersion) >= 0) {
                                // version already up-to-date, due to bundle version
                                // changing between startup check and now
                                message = "Bundle is already installed and up to date";
                            } else {
                                monitor.setTaskName("Installing bundle");
                                InputStream contents = null;
                                try {
                                    contents = supportBundle.openInputStream();
                                    client.installBundle(contents, supportBundle.getName());
                                } finally {
                                    IOUtils.closeQuietly(contents);
                                }
                                deployedVersion = embeddedVersion;
                                message = "Bundle version " + embeddedVersion + " installed";

                            }
                            monitor.worked(1);

                            monitor.setTaskName("Updating server configuration");
                            final Version finalDeployedVersion = deployedVersion;
                            Display.getDefault().syncExec(new Runnable() {
                                @Override
                                public void run() {
                                    execute(new SetBundleVersionCommand(server,
                                            EmbeddedArtifactLocator.SUPPORT_BUNDLE_SYMBOLIC_NAME,
                                            finalDeployedVersion.toString()));
                                    try {
                                        server.save(false, new NullProgressMonitor());
                                    } catch (CoreException e) {
                                        Activator.getDefault().getLog().log(e.getStatus());
                                    }
                                }
                            });
                            monitor.worked(1);

                        } catch (OsgiClientException e) {
                            throw new InvocationTargetException(e);
                        } catch (URISyntaxException e) {
                            throw new InvocationTargetException(e);
                        } catch (IOException e) {
                            throw new InvocationTargetException(e);
                        } finally {
                            monitor.done();
                        }

                        Display.getDefault().asyncExec(new Runnable() {
                            @Override
                            public void run() {
                                MessageDialog.openInformation(getShell(), "Support bundle install operation",
                                        message);
                            }
                        });
                    }
                });
            } catch (InvocationTargetException e1) {

                IStatus status = new Status(Status.ERROR, Activator.PLUGIN_ID,
                        "Error while installing support bundle: " + e1.getTargetException().getMessage(),
                        e1.getTargetException());

                ErrorDialog.openError(getShell(), "Error while installing support bundle", e1.getMessage(),
                        status);
            } catch (InterruptedException e1) {
                Thread.currentThread().interrupt();
                return;
            }
        }
    });
}

From source file:org.apache.struts.faces.renderer.BaseRenderer.java

/**
 * <p>Return an absolute URI for the current page suitable for use
 * in a portlet environment.  NOTE:  Implementation must not require
 * portlet API classes to be present, so use reflection as needed.</p>
 *
 * @param context <code>FacesContext</code> for the current request
 */// www .j a  v a  2 s . com
protected String portletUri(FacesContext context) {

    Object request = context.getExternalContext().getRequest();
    try {
        String scheme = (String) MethodUtils.invokeMethod(request, "getScheme", null);
        StringBuffer sb = new StringBuffer(scheme);
        sb.append("://");
        sb.append(MethodUtils.invokeMethod(request, "getServerName", null));
        Integer port = (Integer) MethodUtils.invokeMethod(request, "getServerPort", null);
        if ("http".equals(scheme) && (port.intValue() == 80)) {
            ;
        } else if ("https".equals(scheme) && (port.intValue() == 443)) {
            ;
        } else {
            sb.append(":" + port);
        }
        sb.append(MethodUtils.invokeMethod(request, "getContextPath", null));
        sb.append(context.getViewRoot().getViewId());
        return (sb.toString());
    } catch (InvocationTargetException e) {
        throw new FacesException(e.getTargetException());
    } catch (Exception e) {
        throw new FacesException(e);
    }

}

From source file:org.apache.struts.webapp.example.EditRegistrationAction.java

public ActionForward execute(ActionMapping mapping, ActionForm form, HttpServletRequest request,
        HttpServletResponse response) throws Exception {

    // Extract attributes we will need
    HttpSession session = request.getSession();
    String action = request.getParameter("action");
    if (action == null) {
        action = "Create";
    }/*  w  w w  .j  a  v a 2 s  . c  o m*/

    if (log.isDebugEnabled()) {
        log.debug("EditRegistrationAction:  Processing " + action + " action");
    }

    // Is there a currently logged on user?
    User user = null;
    if (!"Create".equals(action)) {
        user = (User) session.getAttribute(Constants.USER_KEY);
        if (user == null) {
            if (log.isDebugEnabled()) {
                log.debug(" User is not logged on in session " + session.getId());
            }
            return (mapping.findForward("logon"));
        }
    }

    RegistrationForm regform = (RegistrationForm) form;
    if (user != null) {
        if (log.isTraceEnabled()) {
            log.trace(" Populating form from " + user);
        }

        try {
            PropertyUtils.copyProperties(regform, user);
            regform.setAction(action);
            regform.setPassword(null);
            regform.setPassword2(null);

        } catch (InvocationTargetException e) {
            Throwable t = e.getTargetException();
            if (t == null)
                t = e;
            log.error("RegistrationForm.populate", t);
            throw new ServletException("RegistrationForm.populate", t);

        } catch (Throwable t) {
            log.error("RegistrationForm.populate", t);
            throw new ServletException("RegistrationForm.populate", t);
        }
    }

    // Set a transactional control token to prevent double posting
    if (log.isTraceEnabled()) {
        log.trace(" Setting transactional control token");
    }

    saveToken(request);

    // Forward control to the edit user registration page
    if (log.isTraceEnabled()) {
        log.trace(" Forwarding to 'success' page");
    }

    return (mapping.findForward("success"));

}

From source file:org.apache.struts.webapp.example.EditSubscriptionAction.java

public ActionForward execute(ActionMapping mapping, ActionForm form, HttpServletRequest request,
        HttpServletResponse response) throws Exception {

    // Extract attributes we will need
    HttpSession session = request.getSession();
    String action = request.getParameter("action");
    if (action == null) {
        action = "Create";
    }/*from  ww  w .  j ava  2  s .c o m*/

    String host = request.getParameter("host");
    if (log.isDebugEnabled()) {
        log.debug("EditSubscriptionAction:  Processing " + action + " action");
    }

    // Is there a currently logged on user?
    User user = (User) session.getAttribute(Constants.USER_KEY);
    if (user == null) {
        if (log.isTraceEnabled()) {
            log.trace(" User is not logged on in session " + session.getId());
        }
        return (mapping.findForward("logon"));
    }

    // Identify the relevant subscription
    Subscription subscription = user.findSubscription(request.getParameter("host"));

    if ((subscription == null) && !action.equals("Create")) {
        if (log.isTraceEnabled()) {
            log.trace(" No subscription for user " + user.getUsername() + " and host " + host);
        }

        return (mapping.findForward("failure"));
    }

    if (subscription != null) {
        session.setAttribute(Constants.SUBSCRIPTION_KEY, subscription);
    }

    SubscriptionForm subform = (SubscriptionForm) form;
    subform.setAction(action);
    if (!action.equals("Create")) {
        if (log.isTraceEnabled()) {
            log.trace(" Populating form from " + subscription);
        }

        try {
            PropertyUtils.copyProperties(subform, subscription);
            subform.setAction(action);

        } catch (InvocationTargetException e) {
            Throwable t = e.getTargetException();
            if (t == null)
                t = e;
            log.error("SubscriptionForm.populate", t);
            throw new ServletException("SubscriptionForm.populate", t);

        } catch (Throwable t) {
            log.error("SubscriptionForm.populate", t);
            throw new ServletException("SubscriptionForm.populate", t);
        }
    }

    // Forward control to the edit subscription page
    if (log.isTraceEnabled()) {
        log.trace(" Forwarding to 'success' page");
    }

    return (mapping.findForward("success"));

}

From source file:org.apache.struts.webapp.example.SaveRegistrationAction.java

public ActionForward execute(ActionMapping mapping, ActionForm form, HttpServletRequest request,
        HttpServletResponse response) throws Exception {

    // Extract attributes and parameters we will need
    HttpSession session = request.getSession();
    RegistrationForm regform = (RegistrationForm) form;
    String action = regform.getAction();
    if (action == null) {
        action = "Create";
    }//  w w  w.ja v  a2s.  co m

    UserDatabase database = (UserDatabase) servlet.getServletContext().getAttribute(Constants.DATABASE_KEY);

    if (log.isDebugEnabled()) {
        log.debug("SaveRegistrationAction:  Processing " + action + " action");
    }

    // Is there a currently logged on user (unless creating)?
    User user = (User) session.getAttribute(Constants.USER_KEY);
    if (!"Create".equals(action) && (user == null)) {
        if (log.isTraceEnabled()) {
            log.trace(" User is not logged on in session " + session.getId());
        }
        return (mapping.findForward("logon"));
    }

    // Was this transaction cancelled?
    if (isCancelled(request)) {
        if (log.isTraceEnabled()) {
            log.trace(" Transaction '" + action + "' was cancelled");
        }
        session.removeAttribute(Constants.SUBSCRIPTION_KEY);
        return (mapping.findForward("success"));
    }

    // Validate the transactional control token
    ActionMessages errors = new ActionMessages();
    if (log.isTraceEnabled()) {
        log.trace(" Checking transactional control token");
    }

    if (!isTokenValid(request)) {
        errors.add(ActionMessages.GLOBAL_MESSAGE, new ActionMessage("error.transaction.token"));
    }

    resetToken(request);

    // Validate the request parameters specified by the user
    if (log.isTraceEnabled()) {
        log.trace(" Performing extra validations");
    }

    String value = null;
    value = regform.getUsername();
    if (("Create".equals(action)) && (database.findUser(value) != null)) {
        errors.add("username", new ActionMessage("error.username.unique", regform.getUsername()));
    }

    if ("Create".equals(action)) {
        value = regform.getPassword();
        if ((value == null) || (value.length() < 1)) {
            errors.add("password", new ActionMessage("error.password.required"));
        }

        value = regform.getPassword2();

        if ((value == null) || (value.length() < 1)) {
            errors.add("password2", new ActionMessage("error.password2.required"));
        }
    }

    // Report any errors we have discovered back to the original form
    if (!errors.isEmpty()) {
        this.saveErrors(request, errors);
        this.saveToken(request);
        return (mapping.getInputForward());
    }

    // Update the user's persistent profile information
    try {
        if ("Create".equals(action)) {
            user = database.createUser(regform.getUsername());
        }

        String oldPassword = user.getPassword();
        PropertyUtils.copyProperties(user, regform);
        if ((regform.getPassword() == null) || (regform.getPassword().length() < 1)) {

            user.setPassword(oldPassword);
        }

    } catch (InvocationTargetException e) {
        Throwable t = e.getTargetException();
        if (t == null) {
            t = e;
        }

        log.error("Registration.populate", t);
        throw new ServletException("Registration.populate", t);

    } catch (Throwable t) {
        log.error("Registration.populate", t);
        throw new ServletException("Subscription.populate", t);
    }

    try {
        database.save();
    } catch (Exception e) {
        log.error("Database save", e);
    }

    // Log the user in if appropriate
    if ("Create".equals(action)) {
        session.setAttribute(Constants.USER_KEY, user);
        if (log.isTraceEnabled()) {
            log.trace(" User '" + user.getUsername() + "' logged on in session " + session.getId());
        }
    }

    // Remove the obsolete form bean
    if (mapping.getAttribute() != null) {
        if ("request".equals(mapping.getScope()))
            request.removeAttribute(mapping.getAttribute());
        else
            session.removeAttribute(mapping.getAttribute());
    }

    // Forward control to the specified success URI
    if (log.isTraceEnabled()) {
        log.trace(" Forwarding to success page");
    }

    return (mapping.findForward("success"));

}

From source file:org.apache.struts.webapp.example2.EditRegistrationAction.java

/**
 * Process the specified HTTP request, and create the corresponding HTTP
 * response (or forward to another web component that will create it).
 * Return an <code>ActionForward</code> instance describing where and how
 * control should be forwarded, or <code>null</code> if the response has
 * already been completed./*  ww  w.  j av  a2  s . co  m*/
 *
 * @param mapping The ActionMapping used to select this instance
 * @param form The optional ActionForm bean for this request (if any)
 * @param request The HTTP request we are processing
 * @param response The HTTP response we are creating
 *
 * @exception Exception if the application business logic throws
 *  an exception
 */
public ActionForward execute(ActionMapping mapping, ActionForm form, HttpServletRequest request,
        HttpServletResponse response) throws Exception {

    // Extract attributes we will need
    Locale locale = getLocale(request);
    MessageResources messages = getResources(request);
    HttpSession session = request.getSession();
    String action = request.getParameter("action");
    if (action == null)
        action = "Create";
    if (log.isDebugEnabled()) {
        log.debug("EditRegistrationAction:  Processing " + action + " action");
    }

    // Is there a currently logged on user?
    User user = null;
    if (!"Create".equals(action)) {
        user = (User) session.getAttribute(Constants.USER_KEY);
        if (user == null) {
            if (log.isDebugEnabled()) {
                log.debug(" User is not logged on in session " + session.getId());
            }
            return (mapping.findForward("logon"));
        }
    }

    // Populate the user registration form
    if (form == null) {
        if (log.isTraceEnabled()) {
            log.trace(" Creating new RegistrationForm bean under key " + mapping.getAttribute());
        }
        form = new RegistrationForm();
        if ("request".equals(mapping.getScope()))
            request.setAttribute(mapping.getAttribute(), form);
        else
            session.setAttribute(mapping.getAttribute(), form);
    }
    RegistrationForm regform = (RegistrationForm) form;
    if (user != null) {
        if (log.isTraceEnabled()) {
            log.trace(" Populating form from " + user);
        }
        try {
            PropertyUtils.copyProperties(regform, user);
            regform.setAction(action);
            regform.setPassword(null);
            regform.setPassword2(null);
        } catch (InvocationTargetException e) {
            Throwable t = e.getTargetException();
            if (t == null)
                t = e;
            log.error("RegistrationForm.populate", t);
            throw new ServletException("RegistrationForm.populate", t);
        } catch (Throwable t) {
            log.error("RegistrationForm.populate", t);
            throw new ServletException("RegistrationForm.populate", t);
        }
    }

    // Set a transactional control token to prevent double posting
    if (log.isTraceEnabled()) {
        log.trace(" Setting transactional control token");
    }
    saveToken(request);

    // Forward control to the edit user registration page
    if (log.isTraceEnabled()) {
        log.trace(" Forwarding to 'success' page");
    }
    if ("Create".equals(action)) {
        return (mapping.findForward("register"));
    } else {
        return (mapping.findForward("success"));
    }

}

From source file:org.apache.struts.webapp.example2.EditSubscriptionAction.java

/**
 * Process the specified HTTP request, and create the corresponding HTTP
 * response (or forward to another web component that will create it).
 * Return an <code>ActionForward</code> instance describing where and how
 * control should be forwarded, or <code>null</code> if the response has
 * already been completed./* w ww . j  a v a 2 s .  c  o m*/
 *
 * @param mapping The ActionMapping used to select this instance
 * @param form The optional ActionForm bean for this request (if any)
 * @param request The HTTP request we are processing
 * @param response The HTTP response we are creating
 *
 * @exception Exception if the application business logic throws
 *  an exception
 */
public ActionForward execute(ActionMapping mapping, ActionForm form, HttpServletRequest request,
        HttpServletResponse response) throws Exception {

    // Extract attributes we will need
    Locale locale = getLocale(request);
    MessageResources messages = getResources(request);
    HttpSession session = request.getSession();
    String action = request.getParameter("action");
    if (action == null) {
        action = "Create";
    }
    String host = request.getParameter("host");
    if (log.isDebugEnabled()) {
        log.debug("EditSubscriptionAction:  Processing " + action + " action");
    }

    // Is there a currently logged on user?
    User user = (User) session.getAttribute(Constants.USER_KEY);
    if (user == null) {
        if (log.isTraceEnabled()) {
            log.trace(" User is not logged on in session " + session.getId());
        }
        return (mapping.findForward("logon"));
    }

    // Identify the relevant subscription
    Subscription subscription = user.findSubscription(request.getParameter("host"));
    if ((subscription == null) && !action.equals("Create")) {
        if (log.isTraceEnabled()) {
            log.trace(" No subscription for user " + user.getUsername() + " and host " + host);
        }
        return (mapping.findForward("failure"));
    }
    if (subscription != null) {
        session.setAttribute(Constants.SUBSCRIPTION_KEY, subscription);
    }

    // Populate the subscription form
    if (form == null) {
        if (log.isTraceEnabled()) {
            log.trace(" Creating new SubscriptionForm bean under key " + mapping.getAttribute());
        }
        form = new SubscriptionForm();
        if ("request".equals(mapping.getScope())) {
            request.setAttribute(mapping.getAttribute(), form);
        } else {
            session.setAttribute(mapping.getAttribute(), form);
        }
    }
    SubscriptionForm subform = (SubscriptionForm) form;
    subform.setAction(action);
    if (!action.equals("Create")) {
        if (log.isTraceEnabled()) {
            log.trace(" Populating form from " + subscription);
        }
        try {
            PropertyUtils.copyProperties(subform, subscription);
            subform.setAction(action);
        } catch (InvocationTargetException e) {
            Throwable t = e.getTargetException();
            if (t == null)
                t = e;
            log.error("SubscriptionForm.populate", t);
            throw new ServletException("SubscriptionForm.populate", t);
        } catch (Throwable t) {
            log.error("SubscriptionForm.populate", t);
            throw new ServletException("SubscriptionForm.populate", t);
        }
    }

    // Forward control to the edit subscription page
    if (log.isTraceEnabled()) {
        log.trace(" Forwarding to 'success' page");
    }
    return (mapping.findForward("success"));

}