Example usage for java.lang.reflect InvocationTargetException getMessage

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

Introduction

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

Prototype

public String getMessage() 

Source Link

Document

Returns the detail message string of this throwable.

Usage

From source file:org.apache.axis.Message.java

/**
 * Do the work of construction./*from  www  .  ja v a  2  s .  c  om*/
 *
 * @param initialContents may be String, byte[], InputStream, SOAPEnvelope,
 *                        or AxisFault
 * @param bodyInStream is true if initialContents is an InputStream
 *                     containing just the SOAP body (no SOAP-ENV)
 * @param contentType this if the contentType has been already determined
 *                   (as in the case of servlets)
 * @param contentLocation the location of the content
 * @param mimeHeaders  mime headers for attachments
 */
private void setup(Object initialContents, boolean bodyInStream, String contentType, String contentLocation,
        javax.xml.soap.MimeHeaders mimeHeaders) {

    if (contentType == null && mimeHeaders != null) {
        String contentTypes[] = mimeHeaders.getHeader("Content-Type");
        contentType = (contentTypes != null) ? contentTypes[0] : null;
    }
    if (contentLocation == null && mimeHeaders != null) {
        String contentLocations[] = mimeHeaders.getHeader("Content-Location");
        contentLocation = (contentLocations != null) ? contentLocations[0] : null;
    }
    if (contentType != null) {
        int delimiterIndex = contentType.lastIndexOf("charset");
        if (delimiterIndex > 0) {
            String charsetPart = contentType.substring(delimiterIndex);
            int delimiterIndex2 = charsetPart.indexOf(';');
            if (delimiterIndex2 != -1) {
                charsetPart = charsetPart.substring(0, delimiterIndex2);
            }
            int charsetIndex = charsetPart.indexOf('=');
            String charset = charsetPart.substring(charsetIndex + 1).trim();
            if ((charset.startsWith("\"") || charset.startsWith("\'"))) {
                charset = charset.substring(1, charset.length());
            }
            if ((charset.endsWith("\"") || charset.endsWith("\'"))) {
                charset = charset.substring(0, charset.length() - 1);
            }
            try {
                setProperty(SOAPMessage.CHARACTER_SET_ENCODING, charset);
            } catch (SOAPException e) {
            }
        }
    }
    // Try to construct an AttachmentsImpl object for attachment
    // functionality.
    // If there is no org.apache.axis.attachments.AttachmentsImpl class,
    // it must mean activation.jar is not present and attachments are not
    // supported.
    if (isAttachmentSupportEnabled(getMessageContext())) {
        // Construct one, and cast to Attachments.
        // There must be exactly one constructor of AttachmentsImpl, which
        // must take an org.apache.axis.Message!
        Constructor attachImplConstr = attachImpl.getConstructors()[0];
        try {
            mAttachments = (Attachments) attachImplConstr
                    .newInstance(new Object[] { initialContents, contentType, contentLocation });

            //If it can't support it, it wont have a root part.
            mSOAPPart = (SOAPPart) mAttachments.getRootPart();
        } catch (InvocationTargetException ex) {
            log.fatal(Messages.getMessage("invocationTargetException00"), ex);
            throw new RuntimeException(ex.getMessage());
        } catch (InstantiationException ex) {
            log.fatal(Messages.getMessage("instantiationException00"), ex);
            throw new RuntimeException(ex.getMessage());
        } catch (IllegalAccessException ex) {
            log.fatal(Messages.getMessage("illegalAccessException00"), ex);
            throw new RuntimeException(ex.getMessage());
        }
    } else if (contentType != null && contentType.startsWith("multipart")) {
        throw new RuntimeException(Messages.getMessage("noAttachments"));
    }

    // text/xml
    if (null == mSOAPPart) {
        mSOAPPart = new SOAPPart(this, initialContents, bodyInStream);
    } else
        mSOAPPart.setMessage(this);

    // The stream was not determined by a more complex type so default to
    if (mAttachments != null)
        mAttachments.setRootPart(mSOAPPart);

    headers = (mimeHeaders == null) ? new MimeHeaders() : new MimeHeaders(mimeHeaders);
}

From source file:com.amazonaws.mobileconnectors.pinpoint.targeting.notification.NotificationClient.java

private Notification createNotification(final int iconResId, final String title, final String contentText,
        final String imageUrl, final String imageIconUrl, final String imageSmallIconUrl,
        final PendingIntent contentIntent) {
    log.info("Create Notification:" + title + ", Content:" + contentText);
    if (android.os.Build.VERSION.SDK_INT < ANDROID_JELLYBEAN) {
        return createLegacyNotification(iconResId, title, contentText, contentIntent);
    }/*from  w w  w.j ava 2 s.  c om*/

    if (!initClassesAndMethodsByReflection()) {
        // fall back to creating the legacy notification.
        return createLegacyNotification(iconResId, title, contentText, contentIntent);
    }

    final Object notificationBuilder;
    final Object bigTextStyle;
    final Object bigPictureStyle;

    try {
        notificationBuilder = notificationBuilderConstructor
                .newInstance(pinpointContext.getApplicationContext());
        bigTextStyle = notificationBigTextStyleClass.newInstance();
        bigPictureStyle = notificationBigPictureStyleClass.newInstance();
    } catch (final InvocationTargetException ex) {
        log.debug("Can't invoke notification builder constructor. : " + ex.getMessage(), ex);
        return createLegacyNotification(iconResId, title, contentText, contentIntent);
    } catch (final IllegalAccessException ex) {
        log.debug("Can't access notification builder or bigTextStyle or bigPictureStyle classes. : "
                + ex.getMessage(), ex);
        return createLegacyNotification(iconResId, title, contentText, contentIntent);
    } catch (final InstantiationException ex) {
        log.debug(
                "Exception while instantiating notification builder or bigTextStyle or bigPictureStyle classes. : "
                        + ex.getMessage(),
                ex);
        return createLegacyNotification(iconResId, title, contentText, contentIntent);
    }

    try {
        setContentTitleMethod.invoke(notificationBuilder, title);
        setContentTextMethod.invoke(notificationBuilder, contentText);
        setContentIntent.invoke(notificationBuilder, contentIntent);
        setPriorityMethod.invoke(notificationBuilder, 1);
        final Uri defaultSoundUri = RingtoneManager.getDefaultUri(RingtoneManager.TYPE_NOTIFICATION);
        setSoundMethod.invoke(notificationBuilder, defaultSoundUri);

        if (!buildNotificationIcons(iconResId, imageIconUrl, imageSmallIconUrl, notificationBuilder)) {
            return createLegacyNotification(iconResId, title, contentText, contentIntent);
        }

        if (imageUrl != null) {
            try {
                notificationImage = new DownloadImageTask().execute(imageUrl).get();
                if (notificationImage != null) {
                    bigPictureMethod.invoke(bigPictureStyle, notificationImage);
                    setSummaryMethod.invoke(bigPictureStyle, contentText);
                    setStyleMethod.invoke(notificationBuilder, bigPictureStyle);
                } else {
                    bigTextMethod.invoke(bigTextStyle, contentText);
                    setStyleMethod.invoke(notificationBuilder, bigTextStyle);
                }
            } catch (final InterruptedException e) {
                log.error("Interrupted when downloading image : " + e.getMessage(), e);
            } catch (final ExecutionException e) {
                log.error("Failed execute download image thread : " + e.getMessage(), e);
            }
        }

        return (Notification) buildMethod.invoke(notificationBuilder);
    } catch (final InvocationTargetException ex) {
        log.debug("Can't invoke notification builder methods. : " + ex.getMessage(), ex);
        return createLegacyNotification(iconResId, title, contentText, contentIntent);
    } catch (final IllegalAccessException ex) {
        log.debug("Can't access notification builder methods. : " + ex.getMessage(), ex);
        return createLegacyNotification(iconResId, title, contentText, contentIntent);
    }
}

From source file:er.directtoweb.pages.ERD2WListPage.java

/**
 * Attempts to instantiate the custom edit object delegate subclass, if one has been specified.
 *//*from  w w w .  j  av  a  2s  .  c  o m*/
private ERDEditObjectDelegate editObjectDelegateInstance() {
    ERDEditObjectDelegate delegate = null;
    String delegateClassName = (String) d2wContext().valueForKey("editObjectDelegateClass");
    if (delegateClassName != null) {
        try {
            Class delegateClass = Class.forName(delegateClassName);
            Constructor delegateClassConstructor = delegateClass.getConstructor(WOContext.class);
            delegate = (ERDEditObjectDelegate) delegateClassConstructor.newInstance(context());
        } catch (LinkageError le) {
            if (le instanceof ExceptionInInitializerError) {
                log.warn("Could not initialize edit object delegate class: " + delegateClassName);
            } else {
                log.warn(
                        "Could not load  delegate class: " + delegateClassName + " due to: " + le.getMessage());
            }
        } catch (ClassNotFoundException cnfe) {
            log.warn("Could not find class for edit object delegate: " + delegateClassName);
        } catch (NoSuchMethodException nsme) {
            log.warn("Could not find constructor for edit object delegate class: " + delegateClassName);
        } catch (SecurityException se) {
            log.warn(
                    "Insufficient privileges to access edit object delegate constructor: " + delegateClassName);
        } catch (IllegalAccessException iae) {
            log.warn("Insufficient access to create edit object delegate instance: " + iae.getMessage());
        } catch (IllegalArgumentException iae) {
            log.warn("Used an illegal argument when creating edit object delegate instance: "
                    + iae.getMessage());
        } catch (InstantiationException ie) {
            log.warn("Could not instantiate edit object delegate instance: " + ie.getMessage());
        } catch (InvocationTargetException ite) {
            log.warn("Exception while invoking edit object delegate constructor: " + ite.getMessage());
        }
    }

    return delegate;
}

From source file:com.amalto.workbench.editors.DataClusterComposite.java

private TreeParent getRealTreeParent() {
    TreeParent treeParent = null;//from  w ww .j a va2s.c om
    TreeObject xObject = getXObject();
    if (xObject != null) {
        TreeParent serverRoot = xObject.getServerRoot();
        UserInfo user = serverRoot.getUser();

        String serverName = serverRoot.getName();
        String password = user.getPassword();
        String url = user.getServerUrl();
        String username = user.getUsername();

        final XtentisServerObjectsRetriever retriever = new XtentisServerObjectsRetriever(serverName, url,
                username, password);

        retriever.setRetriveWSObject(true);

        try {
            retriever.run(new NullProgressMonitor());
            treeParent = retriever.getServerRoot();// get the real server root as the treeParent
        } catch (InvocationTargetException e) {
            log.error(e.getMessage(), e);
        } catch (InterruptedException e) {
            log.error(e.getMessage(), e);
        }
    }

    return treeParent;
}

From source file:org.cloudifysource.dsl.internal.BaseDslScript.java

private void validateObject(final Object obj) throws DSLValidationException {

    final Method[] methods = obj.getClass().getDeclaredMethods();
    for (final Method method : methods) {
        if (method.getAnnotation(DSLValidation.class) != null) {
            final boolean accessible = method.isAccessible();
            try {
                @SuppressWarnings("unchecked")
                final Map<Object, Object> currentVars = this.getBinding().getVariables();
                final DSLValidationContext validationContext = new DSLValidationContext();
                validationContext.setFilePath((String) currentVars.get(DSLUtils.DSL_FILE_PATH_PROPERTY_NAME));
                method.setAccessible(true);
                method.invoke(obj, validationContext);

            } catch (final InvocationTargetException e) {
                throw new DSLValidationException(e.getTargetException().getMessage(), e.getTargetException());
            } catch (final Exception e) {
                throw new DSLValidationException("Failed to execute DSL validation: " + e.getMessage(), e);

            } finally {
                method.setAccessible(accessible);
            }//  w w  w.j a  va 2 s  .  c om
        }
    }

}

From source file:ai.general.net.MethodHandler.java

/**
 * Handles the request by calling the method represented by this handler.
 * Request parameters are converted to match the method signature if possible. If no conversion
 * is possible, the method is not called.
 *
 * @param request The request to handle.
 *///w  w w .j  av  a2s.  c  o  m
public void handle(Request request) {
    log.entry(request.getUri().toString());
    try {
        Object[] raw_args = request.getArguments().toArray();
        if (raw_args.length != parameter_types_.length) {
            request.getResult()
                    .addError(new Result.Error("invalid number of method arguments", "got " + raw_args.length
                            + " arguments for method with " + parameter_types_.length + " arguments"));
            log.exit("invalid number of arguments");
            return;
        }
        Object[] args = new Object[raw_args.length];
        for (int i = 0; i < raw_args.length; i++) {
            args[i] = json_parser_.convertValue(raw_args[i], parameter_types_[i]);
        }
        Object result = method_.invoke(instance_, args);
        if (result != null) {
            request.getResult().addValue(result);
        }
    } catch (InvocationTargetException e) {
        log.catching(Level.TRACE, e);
        Throwable cause = e.getCause();
        if (cause != null) {
            if (cause instanceof RpcException) {
                request.getResult()
                        .addError(new Result.Error(cause.getMessage(), ((RpcException) cause).getDetails()));
            } else {
                request.getResult().addError(new Result.Error(cause.getClass().getName(), cause.getMessage()));
            }
        } else {
            request.getResult().addError(new Result.Error("unspecified exception thrown by RPC method", null));
        }
    } catch (ReflectiveOperationException e) {
        log.catching(Level.TRACE, e);
        request.getResult().addError(new Result.Error("cannot call method with specified arguments", null));
    } catch (Exception e) {
        log.catching(Level.TRACE, e);
        request.getResult().addError(new Result.Error(e.getClass().getName(), e.getMessage()));
    }
    log.exit();
}

From source file:org.talend.mdm.engines.client.ui.wizards.DeployOnMDMExportWizardPage.java

/**
 * The Finish button was pressed. Try to do the required work now and answer a boolean indicating success. If false
 * is returned then the wizard will not close.
 * //from  www  .j  a v  a2  s  . c  om
 * @returns boolean
 */
@Override
public boolean finish() {
    try {
        boolean needContextScript = needContextScript();
        String context = contextCombo.getText();
        DeployJobProcess deployJobProcess = new DeployJobProcess(needContextScript, context);
        getContainer().run(true, false, deployJobProcess);
    } catch (InvocationTargetException ex) {
        log.error(ex.getMessage(), ex);
    } catch (InterruptedException ex) {
        log.error(ex.getMessage(), ex);
    }

    return true;
}

From source file:org.talend.repository.imports.ImportItemWizardPage.java

public void updateItemsList(final String path, boolean isneedUpdate) {
    if (!isneedUpdate) {
        if (path.equals(lastPath)) {
            return;
        }//w w  w .j  av  a2 s . co m
    }
    lastPath = path;

    if (path == null || path.length() == 0) {
        selectedItems = new ArrayList<ItemRecord>();
        checkTreeViewer.refresh(true);
        // get the top item to check if tree is empty, if not then uncheck everything
        TreeItem topItem = checkTreeViewer.getTree().getTopItem();
        if (topItem != null) {
            checkTreeViewer.setSubtreeChecked(topItem.getData(), false);
        } // else not root element, tree is already empty
        checkValidItems();
        return;
    }

    final boolean dirSelected = this.itemFromDirectoryRadio.getSelection();
    try {
        getContainer().run(true, true, new IRunnableWithProgress() {

            @Override
            public void run(IProgressMonitor monitor) {

                // monitor.beginTask(DataTransferMessages.WizardProjectsImportPage_SearchingMessage, 100);
                monitor.beginTask(
                        Messages.getString("DataTransferMessages.WizardProjectsImportPage_SearchingMessage"), //$NON-NLS-1$
                        100);
                File directory = new File(path);
                monitor.worked(10);
                if (!dirSelected && ArchiveFileManipulations.isTarFile(path)) {
                    sourceTarFile = getSpecifiedTarSourceFile(path);
                    if (sourceTarFile == null) {
                        return;
                    }

                    TarLeveledStructureProvider provider = new TarLeveledStructureProvider(sourceTarFile);
                    manager = ResourcesManagerFactory.getInstance().createResourcesManager(provider);

                    if (!manager.collectPath2Object(provider.getRoot())) {
                        return;
                    }
                } else if (!dirSelected && ArchiveFileManipulations.isZipFile(path)) {
                    sourceFile = getSpecifiedZipSourceFile(path);
                    if (sourceFile == null) {
                        return;
                    }
                    ZipLeveledStructureProvider provider = new ZipLeveledStructureProvider(sourceFile);
                    manager = ResourcesManagerFactory.getInstance().createResourcesManager(provider);

                    if (!manager.collectPath2Object(provider.getRoot())) {
                        return;
                    }
                } else if (dirSelected && directory.isDirectory()) {
                    manager = ResourcesManagerFactory.getInstance().createResourcesManager();

                    if (!manager.collectPath2Object(directory)) {
                        return;
                    }
                } else {
                    monitor.worked(60);
                }
                monitor.done();
            }

        });
    } catch (InvocationTargetException e) {
        IDEWorkbenchPlugin.log(e.getMessage(), e);
    } catch (InterruptedException e) {
        // Nothing to do if the user interrupts.
    }

    populateItems();
}

From source file:hu.bme.mit.sette.common.tasks.TestSuiteRunner.java

private void analyzeOne(Snippet snippet, File[] binaryDirectories) throws Exception {
    String snippetClassName = snippet.getContainer().getJavaClass().getName();
    String snippetMethodName = snippet.getMethod().getName();
    String testClassName = snippet.getContainer().getJavaClass().getName() + "_" + snippet.getMethod().getName()
            + "_Tests";

    logger.debug("Snippet: {}#{}()", snippetClassName, snippetMethodName);
    logger.debug("Tests: {}", testClassName);

    // create JaCoCo runtime and instrumenter
    IRuntime runtime = new LoggerRuntime();
    Instrumenter instrumenter = new Instrumenter(runtime);

    // start runtime
    RuntimeData data = new RuntimeData();
    runtime.startup(data);/*ww w. ja  v  a  2s . com*/

    // create class loader

    JaCoCoClassLoader classLoader = new JaCoCoClassLoader(binaryDirectories, instrumenter,
            getSnippetProject().getClassLoader());

    // load test class
    // snippet class and other dependencies will be loaded and instrumented
    // on the fly
    Class<?> testClass = classLoader.loadClass(testClassName);

    TestCase testClassInstance = (TestCase) testClass.newInstance();

    // invoke test methods
    // TODO separate collect and invoke
    for (Method m : testClass.getDeclaredMethods()) {
        if (m.isSynthetic()) {
            // skip synthetic method
            continue;
        }

        if (m.getName().startsWith("test")) {
            logger.trace("Invoking: " + m.getName());
            try {
                m.invoke(testClassInstance);
            } catch (InvocationTargetException e) {
                Throwable cause = e.getCause();

                if (cause instanceof NullPointerException || cause instanceof ArrayIndexOutOfBoundsException
                        || cause instanceof AssertionFailedError) {
                    logger.warn(cause.getClass().getName() + ": " + m.getDeclaringClass().getName() + "."
                            + m.getName());
                } else {
                    logger.error("Exception: " + m.getDeclaringClass().getName() + "." + m.getName());
                }
                logger.debug(e.getMessage(), e);
            }
        } else {
            logger.warn("Not test method: {}", m.getName());
        }
    }

    // collect data
    ExecutionDataStore executionData = new ExecutionDataStore();
    SessionInfoStore sessionInfos = new SessionInfoStore();
    data.collect(executionData, sessionInfos, false);
    runtime.shutdown();

    // get classes to analyse
    // store string to avoid the mess up between the different class loaders
    Set<String> javaClasses = new HashSet<>();
    javaClasses.add(snippetClassName);

    for (Constructor<?> inclConstructor : snippet.getIncludedConstructors()) {
        javaClasses.add(inclConstructor.getDeclaringClass().getName());
    }

    for (Method inclMethod : snippet.getIncludedMethods()) {
        javaClasses.add(inclMethod.getDeclaringClass().getName());
    }

    // TODO inner classes are not handled well enough

    // TODO anonymous classes can also have anonymous classes -> recursion

    Set<String> toAdd = new HashSet<>();
    for (String javaClass : javaClasses) {
        int i = 1;
        while (true) {
            // guess anonymous classes, like ClassName$1, ClassName$2 etc.
            try {
                classLoader.loadClass(javaClass + "$" + i);
                toAdd.add(javaClass + "$" + i);
                i++;
            } catch (ClassNotFoundException e) {
                // bad guess, no more anonymous classes on this level
                break;
            }
        }
    }
    javaClasses.addAll(toAdd);

    // analyse classes
    CoverageBuilder coverageBuilder = new CoverageBuilder();
    Analyzer analyzer = new Analyzer(executionData, coverageBuilder);

    for (String javaClassName : javaClasses) {
        logger.trace("Analysing: {}", javaClassName);
        analyzer.analyzeClass(classLoader.readBytes(javaClassName), javaClassName);
    }

    // TODO remove debug
    // new File("D:/SETTE/!DUMP/" + getTool().getName()).mkdirs();
    // PrintStream out = new PrintStream("D:/SETTE/!DUMP/"
    // + getTool().getName() + "/" + testClassName + ".out");

    Map<String, Triple<TreeSet<Integer>, TreeSet<Integer>, TreeSet<Integer>>> coverageInfo = new HashMap<>();

    for (final IClassCoverage cc : coverageBuilder.getClasses()) {
        String file = cc.getPackageName() + '/' + cc.getSourceFileName();
        file = file.replace('\\', '/');

        if (!coverageInfo.containsKey(file)) {
            coverageInfo.put(file,
                    Triple.of(new TreeSet<Integer>(), new TreeSet<Integer>(), new TreeSet<Integer>()));
        }

        // out.printf("Coverage of class %s%n", cc.getName());
        //
        // printCounter(out, "instructions",
        // cc.getInstructionCounter());
        // printCounter(out, "branches", cc.getBranchCounter());
        // printCounter(out, "lines", cc.getLineCounter());
        // printCounter(out, "methods", cc.getMethodCounter());
        // printCounter(out, "complexity", cc.getComplexityCounter());

        for (int l = cc.getFirstLine(); l <= cc.getLastLine(); l++) {
            switch (cc.getLine(l).getStatus()) {
            case ICounter.FULLY_COVERED:
                coverageInfo.get(file).getLeft().add(l);
                break;

            case ICounter.PARTLY_COVERED:
                coverageInfo.get(file).getMiddle().add(l);
                break;

            case ICounter.NOT_COVERED:
                coverageInfo.get(file).getRight().add(l);
                break;
            }
        }
    }

    // create coverage XML
    SnippetCoverageXml coverageXml = new SnippetCoverageXml();
    coverageXml.setToolName(getTool().getName());
    coverageXml.setSnippetProjectElement(
            new SnippetProjectElement(getSnippetProjectSettings().getBaseDirectory().getCanonicalPath()));

    coverageXml.setSnippetElement(
            new SnippetElement(snippet.getContainer().getJavaClass().getName(), snippet.getMethod().getName()));

    coverageXml.setResultType(ResultType.S);

    for (Entry<String, Triple<TreeSet<Integer>, TreeSet<Integer>, TreeSet<Integer>>> entry : coverageInfo
            .entrySet()) {
        TreeSet<Integer> full = entry.getValue().getLeft();
        TreeSet<Integer> partial = entry.getValue().getMiddle();
        TreeSet<Integer> not = entry.getValue().getRight();

        FileCoverageElement fce = new FileCoverageElement();
        fce.setName(entry.getKey());
        fce.setFullyCoveredLines(StringUtils.join(full, ' '));
        fce.setPartiallyCoveredLines(StringUtils.join(partial, ' '));
        fce.setNotCoveredLines(StringUtils.join(not, ' '));

        coverageXml.getCoverage().add(fce);
    }

    coverageXml.validate();

    // TODO needs more documentation
    File coverageFile = RunnerProjectUtils.getSnippetCoverageFile(getRunnerProjectSettings(), snippet);

    Serializer serializer = new Persister(new AnnotationStrategy(),
            new Format("<?xml version=\"1.0\" encoding= \"UTF-8\" ?>"));

    serializer.write(coverageXml, coverageFile);

    // TODO move HTML generation to another file/phase
    File htmlFile = RunnerProjectUtils.getSnippetHtmlFile(getRunnerProjectSettings(), snippet);

    String htmlTitle = getTool().getName() + " - " + snippetClassName + '.' + snippetMethodName + "()";
    StringBuilder htmlData = new StringBuilder();
    htmlData.append("<!DOCTYPE html>\n");
    htmlData.append("<html lang=\"hu\">\n");
    htmlData.append("<head>\n");
    htmlData.append("       <meta charset=\"utf-8\" />\n");
    htmlData.append("       <title>" + htmlTitle + "</title>\n");
    htmlData.append("       <style type=\"text/css\">\n");
    htmlData.append("               .code { font-family: 'Consolas', monospace; }\n");
    htmlData.append("               .code .line { border-bottom: 1px dotted #aaa; white-space: pre; }\n");
    htmlData.append("               .code .green { background-color: #CCFFCC; }\n");
    htmlData.append("               .code .yellow { background-color: #FFFF99; }\n");
    htmlData.append("               .code .red { background-color: #FFCCCC; }\n");
    htmlData.append("               .code .line .number {\n");
    htmlData.append("                       display: inline-block;\n");
    htmlData.append("                       width:50px;\n");
    htmlData.append("                       text-align:right;\n");
    htmlData.append("                       margin-right:5px;\n");
    htmlData.append("               }\n");
    htmlData.append("       </style>\n");
    htmlData.append("</head>\n");
    htmlData.append("\n");
    htmlData.append("<body>\n");
    htmlData.append("       <h1>" + htmlTitle + "</h1>\n");

    for (FileCoverageElement fce : coverageXml.getCoverage()) {
        htmlData.append("       <h2>" + fce.getName() + "</h2>\n");
        htmlData.append("       \n");

        File src = new File(getSnippetProject().getSettings().getSnippetSourceDirectory(), fce.getName());
        List<String> srcLines = FileUtils.readLines(src);

        SortedSet<Integer> full = linesToSortedSet(fce.getFullyCoveredLines());
        SortedSet<Integer> partial = linesToSortedSet(fce.getPartiallyCoveredLines());
        SortedSet<Integer> not = linesToSortedSet(fce.getNotCoveredLines());

        htmlData.append("       <div class=\"code\">\n");
        int i = 1;
        for (String srcLine : srcLines) {
            String divClass = getLineDivClass(i, full, partial, not);
            htmlData.append("               <div class=\"" + divClass + "\"><div class=\"number\">" + i
                    + "</div> " + srcLine + "</div>\n");
            i++;
        }
        htmlData.append("       </div>\n\n");

    }

    // htmlData.append("               <div class=\"line\"><div class=\"number\">1</div> package samplesnippets;</div>\n");
    // htmlData.append("               <div class=\"line\"><div class=\"number\">2</div> </div>\n");
    // htmlData.append("               <div class=\"line\"><div class=\"number\">3</div> import hu.bme.mit.sette.annotations.SetteIncludeCoverage;</div>\n");
    // htmlData.append("               <div class=\"line\"><div class=\"number\">4</div> import hu.bme.mit.sette.annotations.SetteNotSnippet;</div>\n");
    // htmlData.append("               <div class=\"line\"><div class=\"number\">5</div> import hu.bme.mit.sette.annotations.SetteRequiredStatementCoverage;</div>\n");
    // htmlData.append("               <div class=\"line\"><div class=\"number\">6</div> import hu.bme.mit.sette.annotations.SetteSnippetContainer;</div>\n");
    // htmlData.append("               <div class=\"line\"><div class=\"number\">7</div> import samplesnippets.inputs.SampleContainer_Inputs;</div>\n");
    // htmlData.append("               <div class=\"line\"><div class=\"number\">8</div> </div>\n");
    // htmlData.append("               <div class=\"line\"><div class=\"number\">9</div> @SetteSnippetContainer(category = "X1",</div>\n");
    // htmlData.append("               <div class=\"line\"><div class=\"number\">10</div>         goal = "Sample
    // snippet container",</div>\n");
    // htmlData.append("               <div class=\"line\"><div class=\"number\">11</div>         inputFactoryContainer = SampleContainer_Inputs.class)</div>\n");
    // htmlData.append("               <div class=\"line\"><div class=\"number\">12</div> public final class SampleContainer {</div>\n");
    // htmlData.append("               <div class=\"line\"><div class=\"number\">13</div>     private SampleContainer() {</div>\n");
    // htmlData.append("               <div class=\"line red\"><div class=\"number\">14</div>         throw new UnsupportedOperationException("Static
    // class");</div>\n");
    // htmlData.append("               <div class=\"line\"><div class=\"number\">15</div>     }</div>\n");
    // htmlData.append("               <div class=\"line\"><div class=\"number\">16</div> </div>\n");
    // htmlData.append("               <div class=\"line\"><div class=\"number\">17</div>     @SetteRequiredStatementCoverage(value = 100)</div>\n");
    // htmlData.append("               <div class=\"line green\"><div class=\"number\">18</div>     public static boolean snippet(int x) {</div>\n");
    // htmlData.append("               <div class=\"line yellow\"><div class=\"number\">19</div>         if (20 * x + 2 == 42) {</div>\n");
    // htmlData.append("               <div class=\"line green\"><div class=\"number\">20</div>             return true;</div>\n");
    // htmlData.append("               <div class=\"line green\"><div class=\"number\">21</div>         } else {</div>\n");
    // htmlData.append("               <div class=\"line green\"><div class=\"number\">22</div>             return false;</div>\n");
    // htmlData.append("               <div class=\"line green\"><div class=\"number\">23</div>         }</div>\n");
    // htmlData.append("               <div class=\"line green\"><div class=\"number\">24</div>     }</div>\n");
    // htmlData.append("               <div class=\"line\"><div class=\"number\">25</div> }</div>\n");
    // htmlData.append("               <div class=\"line\"><div class=\"number\">26</div> </div>\n");

    htmlData.append("</body>\n");
    htmlData.append("</html>\n");

    FileUtils.write(htmlFile, htmlData);
}

From source file:com.amalto.workbench.editors.DataClusterBrowserMainPage.java

private TreeParent getRealTreeParent() {
    TreeParent treeParent = null;/* w w w. j av a2s.co  m*/
    TreeObject xObject = getXObject();
    if (xObject != null) {
        TreeParent serverRoot = xObject.getServerRoot();
        UserInfo user = serverRoot.getUser();
        String serverName = serverRoot.getName();
        String password = user.getPassword();
        String url = user.getServerUrl();
        String username = user.getUsername();
        final XtentisServerObjectsRetriever retriever = new XtentisServerObjectsRetriever(serverName, url,
                username, password);
        retriever.setRetriveWSObject(true);
        try {
            retriever.run(new NullProgressMonitor());
            treeParent = retriever.getServerRoot();// get the real server root as the treeParent
        } catch (InvocationTargetException e) {
            log.error(e.getMessage(), e);
        } catch (InterruptedException e) {
            log.error(e.getMessage(), e);
        }
    }
    return treeParent;
}