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:eu.numberfour.n4js.npmexporter.ui.NpmExportWizard.java

@Override
public boolean performFinish() {

    String destination = exportPage.getDestinationValue();
    List<IProject> toExport = exportPage.getChosenProjects();
    boolean shouldPackAsTarball = exportPage.getShouldPackAsTarball();

    File folder = new File(destination);

    // remap all IProjects
    List<? extends IN4JSProject> toExportIN4JSProjects = mapToIN4JSProjects(toExport);

    if (runTools() && toolRunnerPage.isToolrunRequested()) {
        // bring to front.
        ((WizardDialog) getContainer()).showPage(toolRunnerPage);
    }//w  ww.ja  v a 2 s. c  o  m

    try {

        npmExporter.export(toExportIN4JSProjects, folder);

        if (shouldPackAsTarball) {
            npmExporter.tarAndZip(toExportIN4JSProjects, folder);
        }

        boolean runIt = runTools() && toolRunnerPage.queryRunTool();
        if (runIt) {
            final List<String> toolCommand = toolRunnerPage.getCommand();

            getContainer().run(true, true, new IRunnableWithProgress() {
                @Override
                public void run(IProgressMonitor monitor)
                        throws InvocationTargetException, InterruptedException {
                    try {

                        List<String> cmds = newArrayList();
                        // cmds.add("echo"); // prepend with echo for debug TODO remove
                        // cmds.addAll(toolCommand);
                        cmds.add("bash");
                        cmds.add("-login");
                        cmds.add("-c");
                        // cmds.addAll(toolCommand);
                        cmds.add(Joiner.on(" ").join(toolCommand));

                        System.out.println("Comman will be: " + Joiner.on(" :: ").join(cmds));

                        for (IN4JSProject p : toExportIN4JSProjects) {

                            String info = "Processing " + p.toString() + "\n";
                            System.out.println(info);
                            toolRunnerPage.appendText(info);

                            File dir = npmExporter.exportDestination(p, folder);

                            ProcessBuilder pb = new ProcessBuilder();
                            pb.directory(dir);
                            pb.command(cmds);
                            pb.redirectErrorStream(true);
                            Process proc = pb.start();

                            // handle each of proc's streams in a separate thread
                            ExecutorService handlerThreadPool = Executors.newFixedThreadPool(3);

                            // handlerThreadPool.submit(new Runnable() {
                            // @Override
                            // public void run() {
                            // // we want to write to the stdin of the process
                            // BufferedWriter stdin = new BufferedWriter(
                            // new OutputStreamWriter(proc.getOutputStream()));
                            //
                            // // read from our own stdin so we can write it to proc's stdin
                            // BufferedReader myStdin =
                            // new BufferedReader(new InputStreamReader(System.in));
                            // String line = null;
                            // try {
                            // do {
                            // line = myStdin.readLine();
                            // stdin.write(String.format("%s%n", line));
                            // stdin.flush();
                            // } while(! "exit".equalsIgnoreCase(line));
                            // } catch(IOException e) {
                            // e.printStackTrace();
                            // }
                            // }
                            // });

                            handlerThreadPool.submit(new Runnable() {
                                @Override
                                public void run() {
                                    // we want to read the stdout of the process
                                    BufferedReader stdout = new BufferedReader(
                                            new InputStreamReader(proc.getInputStream()));
                                    String line;
                                    try {
                                        while (null != (line = stdout.readLine())) {
                                            System.err.printf("[stderr] %s%n", line);
                                            toolRunnerPage.appendConsoleOut(line);
                                        }
                                    } catch (IOException e) {
                                        e.printStackTrace();
                                    }
                                }
                            });

                            handlerThreadPool.submit(new Runnable() {
                                @Override
                                public void run() {
                                    // we want to read the stderr of the process
                                    BufferedReader stderr = new BufferedReader(
                                            new InputStreamReader(proc.getErrorStream()));
                                    String line;
                                    try {
                                        while (null != (line = stderr.readLine())) {
                                            System.err.printf("[stderr] %s%n", line);
                                            toolRunnerPage.appendConsoleErr(line);
                                        }
                                    } catch (IOException e) {
                                        e.printStackTrace();
                                    }
                                }
                            });

                            // wait for the process to terminate
                            int exitCode = proc.waitFor();
                            System.out.printf("Process terminated with exit code %d%n", exitCode);
                            handlerThreadPool.shutdown();

                        }

                        // done with all projects.
                        // wait for close.

                        toolRunnerPage.queryCloseDialog();

                    } catch (Exception e) {
                        throw new InvocationTargetException(e);
                    }
                }
            });
        }

    } catch (IOException | ArchiveException | CompressorException e) {

        e.printStackTrace();

        Status s = new Status(ERROR, NpmExporterActivator.PLUGIN_ID, "Error occured during export.", e);
        N4JSActivator.getInstance().getLog().log(s);

        return false;
    } catch (InvocationTargetException e) {
        // TODO Auto-generated catch block
        e.printStackTrace();
    } catch (InterruptedException e) {
        // TODO Auto-generated catch block
        e.printStackTrace();
    }

    // successfully done, then store relevant history:
    exportPage.finish();
    if (runTools()) {
        toolRunnerPage.finish();
    }

    return true;
}

From source file:com.amazonaws.eclipse.elasticbeanstalk.webproject.CreateNewAwsJavaWebProjectRunnable.java

public void run(IProgressMonitor progressMonitor) throws InvocationTargetException, InterruptedException {
    SubMonitor monitor = SubMonitor.convert(progressMonitor, "Creating new AWS Java web project", 100);

    try {/*  w  w w.  ja  v a  2  s  .c o m*/
        IRuntime genericJeeServerRuntime = configureGenericJeeServerRuntime();

        // Create a WTP Dynamic Web project
        IDataModel newWebProjectDataModel = DataModelFactory
                .createDataModel(IWebFacetInstallDataModelProperties.class);
        newWebProjectDataModel.setProperty(IFacetProjectCreationDataModelProperties.FACET_PROJECT_NAME,
                dataModel.getProjectName());
        if (genericJeeServerRuntime != null) {
            newWebProjectDataModel.setProperty(IFacetProjectCreationDataModelProperties.FACET_RUNTIME,
                    RuntimeManager.getRuntime(genericJeeServerRuntime.getId()));
        }

        // Default to a 2.5 web app
        FacetDataModelMap facetDataModelMap = (FacetDataModelMap) newWebProjectDataModel
                .getProperty(IFacetProjectCreationDataModelProperties.FACET_DM_MAP);
        IDataModel facetDataModel = facetDataModelMap.getFacetDataModel(IJ2EEFacetConstants.DYNAMIC_WEB);
        facetDataModel.setProperty(IFacetDataModelProperties.FACET_VERSION, IJ2EEFacetConstants.DYNAMIC_WEB_25);

        newWebProjectDataModel.getDefaultOperation().execute(monitor.newChild(30), null);

        // Add the AWS SDK for Java
        IProject project = ResourcesPlugin.getWorkspace().getRoot().getProject(dataModel.getProjectName());
        IJavaProject javaProject = JavaCore.create(project);
        JavaSdkManager sdkManager = JavaSdkManager.getInstance();

        // When installing the SDK, make sure we're not in the middle of
        // bootstrapping the environment
        JavaSdkInstall sdkInstall = null;
        Job installationJob = null;
        synchronized (sdkManager) {
            sdkInstall = sdkManager.getDefaultSdkInstall();
            if (sdkInstall == null) {
                installationJob = sdkManager.getInstallationJob();
                if (installationJob == null) {
                    JavaSdkPlugin.getDefault().getLog().log(new Status(IStatus.ERROR, JavaSdkPlugin.PLUGIN_ID,
                            "Unable to check status of AWS SDK for Java download"));
                }
            }
        }

        if (sdkInstall == null && installationJob != null) {
            installationJob.join();
        }

        sdkInstall = sdkManager.getDefaultSdkInstall();
        if (sdkInstall != null) {
            sdkInstall.writeMetadataToProject(javaProject);
            AwsSdkClasspathUtils.addAwsSdkToProjectClasspath(javaProject, sdkInstall);
        }

        monitor.worked(20);

        // Mark it as a Java EE module dependency
        // TODO: If the user changes the SDK version (through the properties page) then we'll lose the
        //       Java EE module dependency classpath entry attribute.
        Map<IClasspathEntry, IPath> classpathEntriesToRuntimePath = new HashMap<IClasspathEntry, IPath>();
        IClasspathEntry entry = findSdkClasspathEntry(javaProject);
        final IPath runtimePath = ClasspathDependencyUtil.getRuntimePath(null, true,
                ClasspathDependencyUtil.isClassFolderEntry(entry));
        classpathEntriesToRuntimePath.put(entry, runtimePath);
        IDataModelOperation addDependencyAttributesOperation = UpdateClasspathAttributeUtil
                .createAddDependencyAttributesOperation(project.getName(), classpathEntriesToRuntimePath);
        addDependencyAttributesOperation.execute(monitor.newChild(30), null);

        // Add files to the the project
        addTemplateFiles(project);
        monitor.worked(10);

        // Configure the Tomcat session manager
        if (dataModel.getUseDynamoDBSessionManagement()) {
            addSessionManagerConfigurationFiles(project);
        }
        monitor.worked(10);

        // Open the readme.html in an editor browser window.
        File root = project.getLocation().toFile();
        final File indexHtml = new File(root, "WebContent/index.html");

        // Internal browser must be opened within UI thread
        Display.getDefault().syncExec(new Runnable() {
            public void run() {
                try {
                    IWebBrowser browser = BROWSER_SUPPORT.createBrowser(IWorkbenchBrowserSupport.AS_EDITOR,
                            null, null, null);
                    browser.openURL(indexHtml.toURI().toURL());
                } catch (Exception e) {
                    ElasticBeanstalkPlugin.getDefault()
                            .logException("Failed to open project index page in Eclipse editor.", e);
                }
            }
        });

    } catch (Exception e) {
        throw new InvocationTargetException(e);
    } finally {
        progressMonitor.done();
    }
}

From source file:org.toobsframework.data.beanutil.BeanMonkey.java

public static Collection populateCollection(IValidator v, String beanClazz, String indexPropertyName,
        Map properties, boolean validate, boolean noload)
        throws IllegalAccessException, InvocationTargetException, ValidationException, ClassNotFoundException,
        InstantiationException, PermissionException {

    // Do nothing unless all arguments have been specified
    if ((beanClazz == null) || (properties == null) || (indexPropertyName == null)) {
        log.warn("Proper parameters not present.");
        return null;
    }//from   w  w w.ja  va2  s  .  c o m

    ArrayList returnObjs = new ArrayList();

    Object[] indexProperty = (Object[]) properties.get(indexPropertyName);
    if (indexProperty == null) {
        log.warn("indexProperty [" + indexProperty + "] does not exist in the map.");
        return returnObjs;
    }

    Class beanClass = Class.forName(beanClazz);

    String beanClazzName = beanClass.getSimpleName(); //  beanClazz.substring(beanClazz.lastIndexOf(".") + 1);
    IObjectLoader odao = null;
    ICollectionLoader cdao = null;
    if (objectClass.isAssignableFrom(beanClass)) {
        odao = (IObjectLoader) beanFactory.getBean(
                Introspector.decapitalize(beanClazzName.substring(0, beanClazzName.length() - 4)) + "Dao");
        if (odao == null) {
            throw new InvocationTargetException(new Exception("Object DAO class "
                    + Introspector.decapitalize(beanClazzName) + "Dao could not be loaded"));
        }
    } else {
        cdao = (ICollectionLoader) beanFactory.getBean(
                Introspector.decapitalize(beanClazzName.substring(0, beanClazzName.length() - 4)) + "Dao");
        if (cdao == null) {
            throw new InvocationTargetException(new Exception("Collection DAO class "
                    + Introspector.decapitalize(beanClazzName) + "Dao could not be loaded"));
        }
    }

    boolean namespaceStrict = properties.containsKey("namespaceStrict");

    for (int index = 0; index < indexProperty.length; index++) {
        String guid = (String) indexProperty[index];

        boolean newBean = false;
        Object bean = null;
        if (!noload && guid != null && guid.length() > 0) {
            bean = (odao != null) ? odao.load(guid) : cdao.load(Integer.parseInt(guid));
        }
        if (bean == null) {
            bean = Class.forName(beanClazz).newInstance();
            newBean = true;
        }
        if (v != null) {
            v.prePopulate(bean, properties);
        }
        if (log.isDebugEnabled()) {
            log.debug("BeanMonkey.populate(" + bean + ", " + properties + ")");
        }

        Errors e = null;

        if (validate) {
            String beanClassName = null;
            beanClassName = bean.getClass().getName();
            beanClassName = beanClassName.substring(beanClassName.lastIndexOf(".") + 1);
            e = new BindException(bean, beanClassName);
        }

        String namespace = null;
        if (properties.containsKey("namespace") && !"".equals(properties.get("namespace"))) {
            namespace = (String) properties.get("namespace") + ".";
        }

        // Loop through the property name/value pairs to be set
        Iterator names = properties.keySet().iterator();
        while (names.hasNext()) {

            // Identify the property name and value(s) to be assigned
            String name = (String) names.next();
            if (name == null || (indexPropertyName.equals(name) && !noload)
                    || (namespaceStrict && !name.startsWith(namespace))) {
                continue;
            }

            Object value = null;
            if (properties.get(name) == null) {
                log.warn("Property [" + name + "] does not have a value in the map.");
                continue;
            }
            if (properties.get(name).getClass().isArray() && index < ((Object[]) properties.get(name)).length) {
                value = ((Object[]) properties.get(name))[index];
            } else if (properties.get(name).getClass().isArray()) {
                value = ((Object[]) properties.get(name))[0];
            } else {
                value = properties.get(name);
            }
            if (namespace != null) {
                name = name.replace(namespace, "");
            }

            PropertyDescriptor descriptor = null;
            Class type = null; // Java type of target property
            try {
                descriptor = PropertyUtils.getPropertyDescriptor(bean, name);
                if (descriptor == null) {
                    continue; // Skip this property setter
                }
            } catch (NoSuchMethodException nsm) {
                continue; // Skip this property setter
            } catch (IllegalArgumentException iae) {
                continue; // Skip null nested property
            }
            if (descriptor.getWriteMethod() == null) {
                if (log.isDebugEnabled()) {
                    log.debug("Skipping read-only property");
                }
                continue; // Read-only, skip this property setter
            }
            type = descriptor.getPropertyType();
            String className = type.getName();

            try {
                value = evaluatePropertyValue(name, className, namespace, value, properties, bean);
            } catch (NoSuchMethodException nsm) {
                continue;
            }

            try {
                BeanUtils.setProperty(bean, name, value);
            } catch (ConversionException ce) {
                log.error("populate - exception [bean:" + bean.getClass().getName() + " name:" + name
                        + " value:" + value + "] ");
                if (validate) {
                    e.rejectValue(name, name + ".conversionError", ce.getMessage());
                } else {
                    throw new ValidationException(bean, className, name, ce.getMessage());
                }
            } catch (Exception be) {
                log.error("populate - exception [bean:" + bean.getClass().getName() + " name:" + name
                        + " value:" + value + "] ");
                if (validate) {
                    e.rejectValue(name, name + ".error", be.getMessage());
                } else {
                    throw new ValidationException(bean, className, name, be.getMessage());
                }
            }
        }
        /*
        if (newBean && cdao != null) {
          BeanUtils.setProperty(bean, "id", -1);
        }
        */
        if (validate && e.getErrorCount() > 0) {
            throw new ValidationException(e);
        }

        returnObjs.add(bean);
    }

    return returnObjs;
}

From source file:com.mirth.connect.server.api.providers.MirthResourceInvocationHandlerProvider.java

@Override
public InvocationHandler create(Invocable method) {
    return new InvocationHandler() {
        @Override/*  w w w .j  av  a 2s. c  o m*/
        public Object invoke(Object proxy, Method method, Object[] args) throws Throwable {
            String originalThreadName = Thread.currentThread().getName();

            try {
                if (proxy instanceof MirthServlet) {
                    try {
                        MirthServlet mirthServlet = (MirthServlet) proxy;

                        Map<Method, MethodInfo> methodMap = infoMap.get(proxy.getClass());
                        if (methodMap == null) {
                            methodMap = new ConcurrentHashMap<Method, MethodInfo>();
                            infoMap.put(mirthServlet.getClass(), methodMap);
                        }

                        MethodInfo methodInfo = methodMap.get(method);
                        if (methodInfo == null) {
                            methodInfo = new MethodInfo();
                            methodMap.put(method, methodInfo);
                        }

                        Operation operation = methodInfo.getOperation();
                        if (operation == null) {
                            /*
                             * Get the operation from the MirthOperation annotation present on
                             * the interface method.
                             */
                            Class<?> clazz = proxy.getClass();

                            while (clazz != null && operation == null) {
                                for (Class<?> interfaceClass : clazz.getInterfaces()) {
                                    if (BaseServletInterface.class.isAssignableFrom(interfaceClass)) {
                                        operation = OperationUtil.getOperation(interfaceClass, method);
                                        if (operation != null) {
                                            methodInfo.setOperation(operation);
                                            break;
                                        }
                                    }
                                }

                                clazz = clazz.getSuperclass();
                            }
                        }
                        mirthServlet.setOperation(operation);

                        // Set thread name based on the servlet class and operation name
                        Thread.currentThread().setName(mirthServlet.getClass().getSimpleName() + " Thread ("
                                + operation.getDisplayName() + ") < " + originalThreadName);

                        /*
                         * If a DontCheckAuthorized annotation is present on the server
                         * implementation method, then no auditing is done now and the servlet
                         * is expected to call checkUserAuthorized. Two other optional
                         * annotations determine whether the channel/user ID should be used in
                         * the authorization check.
                         */
                        Boolean checkAuthorized = methodInfo.getCheckAuthorized();
                        if (checkAuthorized == null) {
                            checkAuthorized = true;

                            Method matchingMethod = mirthServlet.getClass().getMethod(method.getName(),
                                    method.getParameterTypes());
                            if (matchingMethod != null) {
                                checkAuthorized = matchingMethod
                                        .getAnnotation(DontCheckAuthorized.class) == null;
                                methodInfo.setCheckAuthorizedChannelId(
                                        matchingMethod.getAnnotation(CheckAuthorizedChannelId.class));
                                methodInfo.setCheckAuthorizedUserId(
                                        matchingMethod.getAnnotation(CheckAuthorizedUserId.class));
                            }

                            methodInfo.setCheckAuthorized(checkAuthorized);
                        }

                        if (checkAuthorized) {
                            /*
                             * We need to know what parameter index the channel/user ID resides
                             * at so we can correctly include it with the authorization request.
                             */
                            Integer channelIdIndex = methodInfo.getChannelIdIndex();
                            Integer userIdIndex = methodInfo.getUserIdIndex();

                            if (args.length > 0) {
                                List<String> paramNames = methodInfo.getParamNames();
                                if (paramNames == null) {
                                    paramNames = new ArrayList<String>();
                                    List<Integer> notFoundIndicies = new ArrayList<Integer>();

                                    /*
                                     * The Param annotation lets us know at runtime the name to
                                     * use when adding entries into the parameter map, which
                                     * will eventually be stored in the event logs.
                                     */
                                    int count = 0;
                                    for (Annotation[] paramAnnotations : method.getParameterAnnotations()) {
                                        boolean found = false;
                                        for (Annotation annotation : paramAnnotations) {
                                            if (annotation instanceof Param) {
                                                Param param = (Param) annotation;
                                                // Set the name to null if we're not including it in the parameter map
                                                paramNames.add(param.excludeFromAudit() ? null : param.value());
                                                found = true;
                                                break;
                                            }
                                        }
                                        if (!found) {
                                            notFoundIndicies.add(count);
                                            paramNames.add(null);
                                        }
                                        count++;
                                    }

                                    // For each parameter name that wasn't found, replace it with a default name to use in the parameter map
                                    if (CollectionUtils.isNotEmpty(notFoundIndicies)) {
                                        for (Integer index : notFoundIndicies) {
                                            paramNames.set(index, getDefaultParamName(paramNames));
                                        }
                                    }

                                    methodInfo.setParamNames(paramNames);
                                }

                                // Add all arguments to the parameter map, except those that had excludeFromAudit enabled.
                                for (int i = 0; i < args.length; i++) {
                                    String paramName = paramNames.get(i);
                                    if (paramName != null) {
                                        mirthServlet.addToParameterMap(paramNames.get(i), args[i]);
                                    }
                                }

                                if (channelIdIndex == null) {
                                    channelIdIndex = -1;
                                    if (methodInfo.getCheckAuthorizedChannelId() != null) {
                                        channelIdIndex = paramNames
                                                .indexOf(methodInfo.getCheckAuthorizedChannelId().paramName());
                                    }
                                    methodInfo.setChannelIdIndex(channelIdIndex);
                                }

                                if (userIdIndex == null) {
                                    userIdIndex = -1;
                                    if (methodInfo.getCheckAuthorizedUserId() != null) {
                                        userIdIndex = paramNames
                                                .indexOf(methodInfo.getCheckAuthorizedUserId().paramName());
                                    }
                                    methodInfo.setUserIdIndex(userIdIndex);
                                }
                            }

                            // Authorize the request
                            if (channelIdIndex != null && channelIdIndex >= 0) {
                                mirthServlet.checkUserAuthorized((String) args[channelIdIndex]);
                            } else if (userIdIndex != null && userIdIndex >= 0) {
                                mirthServlet.checkUserAuthorized((Integer) args[userIdIndex],
                                        methodInfo.getCheckAuthorizedUserId().auditCurrentUser());
                            } else {
                                mirthServlet.checkUserAuthorized();
                            }
                        }
                    } catch (Throwable t) {
                        Throwable converted = convertThrowable(t, new HashSet<Throwable>());
                        if (converted != null) {
                            t = converted;
                        }

                        if (!(t instanceof WebApplicationException)) {
                            t = new MirthApiException(t);
                        }
                        throw new InvocationTargetException(t);
                    }
                }

                try {
                    return method.invoke(proxy, args);
                } catch (InvocationTargetException e) {
                    Throwable converted = convertThrowable(e, new HashSet<Throwable>());
                    if (converted != null && converted instanceof InvocationTargetException) {
                        e = (InvocationTargetException) converted;
                    }
                    throw e;
                }
            } finally {
                Thread.currentThread().setName(originalThreadName);
            }
        }
    };
}

From source file:com.mirth.connect.server.api.providers.MirthResourceInvocationHandlerProvider.java

private Throwable convertThrowable(Throwable t, Set<Throwable> visited) {
    // If the target is null or we've already seen it, ignore
    if (t == null || visited.contains(t)) {
        return null;
    }/*from  w  ww.j  ava 2  s.c o m*/
    // Add the target to set of visited
    visited.add(t);

    // Recursively convert the causes
    Throwable cause = t.getCause();
    Throwable convertedCause = convertThrowable(cause, visited);

    if (t instanceof PersistenceException) {
        // Always convert this exception
        return new com.mirth.connect.client.core.api.PersistenceException(t.getMessage(),
                convertedCause != null ? convertedCause : cause);
    } else if (t instanceof WebApplicationException) {
        // This exception may contain an underlying exception stored in a JAX-RS response
        Response response = ((WebApplicationException) t).getResponse();
        Response convertedResponse = null;
        if (response != null && response.hasEntity()) {
            Object entity = response.getEntity();
            if (entity instanceof Throwable) {
                Object convertedEntity = convertThrowable((Throwable) entity, visited);
                if (convertedEntity != null) {
                    convertedResponse = Response.fromResponse(response).entity(convertedEntity).build();
                }
            }
        }

        if (convertedResponse != null) {
            return new MirthApiException(convertedResponse);
        } else if (convertedCause != null) {
            return new MirthApiException(convertedCause);
        }
    } else if (t instanceof InvocationTargetException) {
        // Ensure that this exception always has a cause of WebApplicationException
        if (convertedCause != null) {
            if (!(convertedCause instanceof WebApplicationException)) {
                convertedCause = new MirthApiException(convertedCause);
            }
            return new InvocationTargetException(convertedCause);
        } else if (cause != null && !(cause instanceof WebApplicationException)) {
            return new InvocationTargetException(new MirthApiException(cause));
        }
    } else if (convertedCause != null) {
        // Any other types, just construct a new instance with the converted cause
        try {
            try {
                return t.getClass().getConstructor(String.class, Throwable.class).newInstance(t.getMessage(),
                        convertedCause);
            } catch (Throwable t2) {
                // Ignore and return null
            }
            return t.getClass().getConstructor(Throwable.class).newInstance(convertedCause);
        } catch (Throwable t3) {
            // Ignore and return null
        }
    }

    return null;
}

From source file:com.amalto.workbench.compare.ResourceCompareInput.java

@Override
public Object prepareInput(IProgressMonitor pm) throws InvocationTargetException {

    try {//  w ww.  ja  va 2  s .com
        // fix for PR 1GFMLFB: ITPUI:WIN2000 - files that are out of sync with the file system appear as empty
        fLeftResource.refreshLocal(IResource.DEPTH_INFINITE, pm);
        fRightResource.refreshLocal(IResource.DEPTH_INFINITE, pm);
        if (fThreeWay && fAncestorResource != null) {
            fAncestorResource.refreshLocal(IResource.DEPTH_INFINITE, pm);
            // end fix
        }

        //pm.beginTask(Utilities.getString("ResourceCompare.taskName"), IProgressMonitor.UNKNOWN); //$NON-NLS-1$

        String leftLabel = fLeftResource.getName();
        String rightLabel = fRightResource.getName();

        String title;
        // if (fThreeWay) {
        //            String format= Utilities.getString("ResourceCompare.threeWay.title"); //$NON-NLS-1$
        // String ancestorLabel= fAncestorResource.getName();
        // title= MessageFormat.format(format, new String[] {ancestorLabel, leftLabel, rightLabel});
        // } else {
        //            String format= Utilities.getString("ResourceCompare.twoWay.title"); //$NON-NLS-1$
        // title= MessageFormat.format(format, new String[] {leftLabel, rightLabel});
        // }
        // setTitle(title);

        Differencer d = new Differencer() {

            @Override
            protected Object visit(Object parent, int description, Object ancestor, Object left, Object right) {
                return new MyDiffNode((IDiffContainer) parent, description, (ITypedElement) ancestor,
                        (ITypedElement) left, (ITypedElement) right);
            }
        };

        fRoot = d.findDifferences(fThreeWay, pm, null, fAncestor, fLeft, fRight);
        return fRoot;

    } catch (CoreException ex) {
        throw new InvocationTargetException(ex);
    } finally {
        pm.done();
    }
}

From source file:cn.dockerfoundry.ide.eclipse.server.ui.internal.CloudUiUtil.java

public static void runForked(final ICoreRunnable coreRunner, IRunnableContext progressService)
        throws OperationCanceledException, CoreException {
    try {//from  ww w .ja  v a  2s. com
        IRunnableWithProgress runner = new IRunnableWithProgress() {
            public void run(final IProgressMonitor monitor)
                    throws InvocationTargetException, InterruptedException {
                monitor.beginTask("", IProgressMonitor.UNKNOWN); //$NON-NLS-1$
                try {
                    coreRunner.run(monitor);
                } catch (CoreException e) {
                    throw new InvocationTargetException(e);
                } finally {
                    monitor.done();
                }
            }

        };
        progressService.run(true, true, runner);
    } catch (InvocationTargetException e) {
        if (e.getCause() instanceof CoreException) {
            throw (CoreException) e.getCause();
        } else {
            DockerFoundryServerUiPlugin.getDefault().getLog().log(new Status(IStatus.ERROR,
                    DockerFoundryServerUiPlugin.PLUGIN_ID, "Unexpected exception", e)); //$NON-NLS-1$
        }
    } catch (InterruptedException e) {
        throw new OperationCanceledException();
    }
}

From source file:com.jk.util.JKObjectUtil.java

/**
 * Call method.//w  w  w . ja v a  2 s.c om
 *
 * @param obj
 *            the obj
 * @param methodName
 *            the method name
 * @param includePrivateMehtods
 *            the include private mehtods
 * @param args
 *            the args
 * @throws InvocationTargetException
 *             the invocation target exception
 */
//////////////////////////////////////////////////////////////////////////////////////////////////////////////////
public static void callMethod(final Object obj, final String methodName, final boolean includePrivateMehtods,
        final Object... args) throws InvocationTargetException {
    final Class[] intArgsClass = initParamsClasses(args);
    try {
        Class<?> current = obj.getClass();
        Method method = null;
        while (current != Object.class) {
            try {
                method = current.getDeclaredMethod(methodName, intArgsClass);
                break;
            } catch (final NoSuchMethodException ex) {
                current = current.getSuperclass();
            }
        }
        if (method == null) {
            throw new NoSuchMethodException("Mehtod is not found in " + current);
        }
        method.setAccessible(true);
        method.invoke(obj, args);
    } catch (final InvocationTargetException e) {
        throw new InvocationTargetException(e.getCause());
    } catch (final Exception e) {
        throw new InvocationTargetException(e);
    }
}

From source file:eu.numberfour.n4js.npmexporter.ui.NpmExportWizard.java

/**
 * @param checked// w  w w .j a  va 2s. c o  m
 *            list of selected projects to export
 * @throws InterruptedException
 * @throws InvocationTargetException
 */
public void updateProjectsToExportSelection(Object[] checked)
        throws InvocationTargetException, InterruptedException {

    getContainer().run(true, true, new IRunnableWithProgress() {
        @Override
        public void run(IProgressMonitor monitor) throws InvocationTargetException, InterruptedException {
            try {
                List<IProject> checkedProjects = newArrayList();
                for (Object o : checked)
                    checkedProjects.add((IProject) o);
                List<? extends IN4JSProject> checkedIN4JSProjects = mapToIN4JSProjects(checkedProjects);

                // validate:
                final Diagnostician diag = new Diagnostician();
                List<IN4JSProject> _requiresMerge1 = newArrayList();
                for (IN4JSProject p : checkedIN4JSProjects) {
                    diag.setActiveProject(p);
                    npmExporter.validate(p, diag);
                    if (npmExporter.requiresJsonMerge(p)) {
                        _requiresMerge1.add(p);
                    }
                }
                setRequireJsonMerge(_requiresMerge1);

                Display.getDefault().asyncExec(new Runnable() {

                    @Override
                    public void run() {
                        if (diag.isIssueFree()) {
                            exportPage.setErrorMessage(null);
                            exportPage.setErrorText("");
                        } else {
                            exportPage.setPageComplete(false);

                            exportPage.setErrorMessage("Validation errors for projects: "
                                    + Joiner.on(", ").join(diag.projectsWithEntries().stream()
                                            .map(p -> p.getArtifactId()).iterator()));
                            String text = diag.asErrorText();

                            exportPage.setErrorText(text);
                        }

                    }
                });

            } catch (Exception e) {
                throw new InvocationTargetException(e);
            }
        }
    });
}

From source file:com.amalto.workbench.providers.XtentisServerObjectsRetriever.java

public synchronized void run(IProgressMonitor monitor) throws InvocationTargetException, InterruptedException {
    try {/* w  w w  .java 2 s  .  c o  m*/
        if (password == null || password.length() == 0) {
            throw new Exception(Messages.XtentisServerObjectsRetriever_0);
        }
        monitor.beginTask(Messages.bind(Messages.XtentisServerObjectsRetriever_1, IConstants.TALEND),
                Messages.XtentisServerObjectsRetriever_3.equals(username) ? 12 : 9);
        // server
        serverRoot = new TreeParent(serverName, null, TreeObject._SERVER_, endpointaddress,
                username + ":" + (password == null ? "" : password));//$NON-NLS-1$//$NON-NLS-2$

        // init load category
        monitor.subTask(Messages.XtentisServerObjectsRetriever_4);
        LocalTreeObjectRepository.getInstance().startUp(endpointaddress, username, password);
        LocalTreeObjectRepository.getInstance().switchOnListening();
        LocalTreeObjectRepository.getInstance().setLazySaveStrategy(true, serverRoot);
        monitor.worked(1);
        // Access to server and get port
        TMDMService service = Util.getMDMService(new URL(endpointaddress), username, password);
        service.ping(new WSPing(Messages.XtentisServerObjectsRetriever_5));// viewer user can't use studio

        monitor.worked(1);

        // fetch version info
        try {
            WSVersion version = service
                    .getComponentVersion(new WSGetComponentVersion(WSComponent.DATA_MANAGER, null));
            String versionStr = version.getMajor() + "." + version.getMinor() + "." + version.getRevision() //$NON-NLS-1$//$NON-NLS-2$
                    + "_" //$NON-NLS-1$
                    + version.getBuild();
            log.info("Server version = " + versionStr); //$NON-NLS-1$
        } catch (Exception e) {
            log.error(e.getMessage(), e);
        }

        if (monitor.isCanceled()) {
            throw new InterruptedException(Messages.XtentisServerObjectsRetriever_6);
        }

        monitor.subTask(Messages.XtentisServerObjectsRetriever_7);
        UserInfo user = new UserInfo();
        user.setUsername(username);
        user.setPassword(password);
        user.setServerUrl(endpointaddress);

        serverRoot.setUser(user);

        // String uriPre=serverRoot.getEndpointIpAddress();

        // Data Models
        TreeParent models = new TreeParent(EXtentisObjects.DataMODEL.getDisplayName(), serverRoot,
                TreeObject.DATA_MODEL, null, null);
        List<WSDataModelPK> xdmPKs = null;
        try {
            xdmPKs = service.getDataModelPKs(new WSRegexDataModelPKs("")).getWsDataModelPKs(); //$NON-NLS-1$
        } catch (Exception e) {

            log.error(e.getMessage(), e);
        }
        if (xdmPKs != null) {
            monitor.subTask(Messages.XtentisServerObjectsRetriever_8);
            for (WSDataModelPK pk : xdmPKs) {
                String name = pk.getPk();
                if (!name.startsWith("XMLSCHEMA")) {//$NON-NLS-1$
                    WSDataModel wsobj = null;
                    if (retriveWSObject) {
                        wsobj = service.getDataModel(new WSGetDataModel(pk));
                    }
                    TreeObject obj = new TreeObject(name, serverRoot, TreeObject.DATA_MODEL, pk, wsobj);
                    models.addChild(obj);
                }
            }
        }
        monitor.worked(1);
        if (monitor.isCanceled()) {
            throw new InterruptedException(Messages.XtentisServerObjectsRetriever_9);
        }

        // DataClusters
        TreeParent dataClusters = new TreeParent(EXtentisObjects.DataCluster.getDisplayName(), serverRoot,
                TreeObject.DATA_CLUSTER, null, null);
        List<WSDataClusterPK> xdcPKs = null;
        try {
            xdcPKs = service.getDataClusterPKs(new WSRegexDataClusterPKs("*")).getWsDataClusterPKs();//$NON-NLS-1$
        } catch (Exception e) {
            log.error(e.getMessage(), e);
        }
        if (xdcPKs != null) {
            monitor.subTask(Messages.XtentisServerObjectsRetriever_10);
            for (WSDataClusterPK pk : xdcPKs) {
                String name = pk.getPk();
                if (!("CACHE".equals(name))) { // FIXME: Hardcoded CACHE//$NON-NLS-1$
                    WSDataCluster wsObject = null;
                    try {
                        if (retriveWSObject) {
                            wsObject = service.getDataCluster(new WSGetDataCluster(pk));
                        }
                        TreeObject obj = new TreeObject(name, serverRoot, TreeObject.DATA_CLUSTER, pk,
                                wsObject);
                        dataClusters.addChild(obj);
                    } catch (Exception e) {
                        log.error(e.getMessage(), e);
                    }
                }
            }
        }
        monitor.worked(1);
        if (monitor.isCanceled()) {
            throw new InterruptedException(Messages.XtentisServerObjectsRetriever_11);
        }
        // event management
        TreeParent eventManagement = new TreeParent(EXtentisObjects.EventManagement.getDisplayName(),
                serverRoot, TreeObject.EVENT_MANAGEMENT, null, null);

        // subscript engine
        TreeObject engine = new TreeObject(EXtentisObjects.SubscriptionEngine.getDisplayName(), serverRoot,
                TreeObject.SUBSCRIPTION_ENGINE, null, null);
        eventManagement.addChild(engine);

        // transformer
        List<WSTransformerV2PK> transformerPKs = null;
        try {
            transformerPKs = service.getTransformerV2PKs(new WSGetTransformerV2PKs("")).getWsTransformerV2PK();//$NON-NLS-1$
        } catch (Exception e) {
            log.error(e.getMessage(), e);
        }
        TreeParent transformers = null;
        transformers = new TreeParent(EXtentisObjects.Transformer.getDisplayName(), serverRoot,
                TreeObject.TRANSFORMER, null, null);
        eventManagement.addChild(transformers);
        if (transformerPKs != null) {
            monitor.subTask(Messages.XtentisServerObjectsRetriever_12);
            for (WSTransformerV2PK pk : transformerPKs) {
                String id = pk.getPk();
                WSTransformerV2 wsobject = null;
                if (retriveWSObject) {
                    wsobject = service.getTransformerV2(new WSGetTransformerV2(pk));
                }
                TreeObject obj = new TreeObject(id, serverRoot, TreeObject.TRANSFORMER,
                        new WSTransformerV2PK(id), wsobject);
                transformers.addChild(obj);
            }
        }
        monitor.worked(1);

        // routing rule
        List<WSRoutingRulePK> routingRulePKs = null;
        try {
            routingRulePKs = service.getRoutingRulePKs(new WSGetRoutingRulePKs("")).getWsRoutingRulePKs();//$NON-NLS-1$
        } catch (Exception e) {
            log.error(e.getMessage(), e);
        }
        TreeParent rules = null;
        rules = new TreeParent(EXtentisObjects.RoutingRule.getDisplayName(), serverRoot,
                TreeObject.ROUTING_RULE, null, null);
        eventManagement.addChild(rules);
        if (routingRulePKs != null) {
            monitor.subTask(Messages.XtentisServerObjectsRetriever_13);
            for (WSRoutingRulePK pk : routingRulePKs) {
                String id = pk.getPk();
                WSRoutingRule wsobject = null;
                if (retriveWSObject) {
                    wsobject = service.getRoutingRule(new WSGetRoutingRule(pk));
                }
                TreeObject obj = new TreeObject(id, serverRoot, TreeObject.ROUTING_RULE,
                        new WSRoutingRulePK(id), wsobject);
                rules.addChild(obj);
            }
        }
        monitor.worked(1);

        // add event management to serverRoot
        serverRoot.addChild(eventManagement);

        // Views
        TreeParent views = new TreeParent(EXtentisObjects.View.getDisplayName(), serverRoot, TreeObject.VIEW,
                null, null);
        List<WSViewPK> viewPKs = null;
        try {
            viewPKs = service.getViewPKs((new WSGetViewPKs(""))).getWsViewPK();//$NON-NLS-1$
        } catch (Exception e) {
            log.error(e.getMessage(), e);

        }
        if (viewPKs != null) {
            monitor.subTask(Messages.XtentisServerObjectsRetriever_14);
            for (WSViewPK pk : viewPKs) {
                String name = pk.getPk();
                WSView wsobject = null;
                if (retriveWSObject) {
                    wsobject = service.getView(new WSGetView(pk));
                }
                TreeObject obj = new TreeObject(name, serverRoot, TreeObject.VIEW, new WSViewPK(name),
                        wsobject);
                views.addChild(obj);
            }
        }
        monitor.worked(1);
        if (monitor.isCanceled()) {
            throw new InterruptedException(Messages.XtentisServerObjectsRetriever_15);
        }

        // Stored Procedures
        TreeParent storedProcedures = new TreeParent(EXtentisObjects.StoredProcedure.getDisplayName(),
                serverRoot, TreeObject.STORED_PROCEDURE, null, null);
        List<WSStoredProcedurePK> spk = null;
        try {
            spk = service.getStoredProcedurePKs(new WSRegexStoredProcedure("")).getWsStoredProcedurePK();//$NON-NLS-1$
        } catch (Exception e) {

            log.error(e.getMessage(), e);
        }
        if (spk != null) {
            monitor.subTask(Messages.XtentisServerObjectsRetriever_16);
            for (WSStoredProcedurePK pk : spk) {
                String name = pk.getPk();
                WSStoredProcedure wsobject = null;
                if (retriveWSObject) {
                    wsobject = service.getStoredProcedure(new WSGetStoredProcedure(pk));
                }
                TreeObject obj = new TreeObject(name, serverRoot, TreeObject.STORED_PROCEDURE,
                        new WSStoredProcedurePK(name), wsobject);
                storedProcedures.addChild(obj);
            }
        }
        monitor.worked(1);
        if (monitor.isCanceled()) {
            throw new InterruptedException(Messages.XtentisServerObjectsRetriever_17);
        }

        // Service Configuration
        TreeObject serviceConfiguration = new TreeObject(EXtentisObjects.ServiceConfiguration.getDisplayName(),
                serverRoot, TreeObject.SERVICE_CONFIGURATION, null, null);
        // serviceConfiguration.setXObject(false);
        monitor.worked(1);
        if (monitor.isCanceled()) {
            throw new InterruptedException(Messages.XtentisServerObjectsRetriever_18);
        }

        // Menus
        List<WSMenuPK> menuPKs = null;
        boolean hasMenus = true;
        try {
            menuPKs = service.getMenuPKs(new WSGetMenuPKs("*")).getWsMenuPK();//$NON-NLS-1$
        } catch (Exception e) {
            log.error(e.getMessage(), e);
            // This server IS old
            hasMenus = false;
        }
        TreeParent menus = null;
        if (hasMenus) {
            menus = new TreeParent(EXtentisObjects.Menu.getDisplayName(), serverRoot, TreeObject.MENU, null,
                    null);
            if (menuPKs != null) {
                monitor.subTask(Messages.XtentisServerObjectsRetriever_19);
                for (WSMenuPK pk : menuPKs) {
                    String id = pk.getPk();
                    WSMenu wsobject = null;
                    try {
                        if (retriveWSObject) {
                            wsobject = service.getMenu(new WSGetMenu(pk));
                        }
                        TreeObject obj = new TreeObject(id, serverRoot, TreeObject.MENU, new WSMenuPK(id),
                                wsobject);
                        menus.addChild(obj);
                    } catch (Exception e) {
                        log.error(e.getMessage(), e);
                    }
                }
            }
            monitor.worked(1);

            if (monitor.isCanceled()) {
                throw new InterruptedException(Messages.XtentisServerObjectsRetriever_20);
            }
        }
        // move Job from EE to CE.

        monitor.worked(1);

        serverRoot.addChild(models);
        serverRoot.addChild(dataClusters);

        serverRoot.addChild(views);
        serverRoot.addChild(storedProcedures);

        serverRoot.addChild(serviceConfiguration);

        // serverRoot.addChild(workflow);
        // serverRoot.addChild(resources);

        if (hasMenus) {
            serverRoot.addChild(menus);
        }

        // available models
        List<IAvailableModel> availablemodels = AvailableModelUtil.getAvailableModels();
        for (IAvailableModel model : availablemodels) {
            model.addTreeObjects(service, monitor, serverRoot);
        }

        monitor.done();
    } catch (Exception e) {
        if (monitor.isCanceled()) {
            throw new InterruptedException(Messages.XtentisServerObjectsRetriever_21);
        }

        log.error(e.getMessage(), e);
        throw new InvocationTargetException(e);
    }
}