Example usage for java.lang.reflect InvocationTargetException getCause

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

Introduction

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

Prototype

public Throwable getCause() 

Source Link

Document

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

Usage

From source file:com.crossbusiness.resiliency.aspect.AbstractFallbackAspect.java

public Object rerouteToFallback(ProceedingJoinPoint pjp, Fallback fallbackConfig) throws Throwable {

    String[] fallbacks = fallbackConfig.value();
    Class<? extends Throwable>[] fallbackableExceptions = fallbackConfig.exceptions();

    List<Object> fallbackBeans = new ArrayList<Object>(fallbacks.length);
    for (String fallback : fallbacks) {
        try {/*  w  w w .  j a  v a2s . c  o m*/
            fallbackBeans.add(context.getBean(fallback));
        } catch (BeansException be) {
            log.error("configuration error: cannot find bean with name: '{}'", fallback, be);
            //configuration errors should be fixed immediately.    
            throw be;
        }
    }

    MethodSignature targetMethodSig = (MethodSignature) pjp.getSignature();
    Method targetMethod = targetMethodSig.getMethod();
    Class[] paramTypes = (Class[]) targetMethod.getParameterTypes();
    Object[] args = pjp.getArgs();

    log.debug("fallbacks: {} method: '{}'", fallbacks, targetMethod);

    try {
        return pjp.proceed();
    } catch (Throwable t) {

        // if the exception is not what we're looking for, rethrow it
        if (!isFallbackableException(t, fallbackableExceptions))
            throw t;

        log.debug("got exception while trying the targetBean method: '{}'. will try fallbackBean...",
                targetMethod);
        Iterator<Object> iter = fallbackBeans.iterator();
        while (iter.hasNext()) {
            Object fallbackBean = iter.next();
            Method fallbackMethod;
            try {
                fallbackMethod = fallbackBean.getClass().getMethod(targetMethod.getName(), paramTypes);
            } catch (NoSuchMethodException | SecurityException nsme) {
                log.error(
                        "configuration error: No matchig method found in fallbackBean: '{}' that matches to targetBean method: '{}'",
                        new Object[] { fallbackBean.getClass().getName(), targetMethod, nsme });
                //configuration errors should be fixed immediately.   
                throw nsme;
            }
            try {
                log.debug("trying fallbackBean method: '{}'...", fallbackMethod);
                return fallbackMethod.invoke(fallbackBean, args);
            } catch (IllegalArgumentException | IllegalAccessException iae) {
                log.error(
                        "configuration error: arguments missmatch: fallbackBean method: '{}' arguments  missmatch to targetBean method: '{}' arguments",
                        new Object[] { fallbackMethod, targetMethod, iae });
                //configuration errors should be fixed immediately.   
                throw iae;
            } catch (InvocationTargetException ite) {
                log.debug(
                        "got exception while trying the fallbackBean method: '{}'. will try next fallbackBean...",
                        fallbackMethod);
                //fallbackBean method thrown an exception. try next bean or throw exception if this is the last bean
                if (!iter.hasNext()) {
                    //TODO : do we still need to check isFallbackableException?
                    throw ite.getCause();
                }
            }
        }
        //code should never reach this line. 
        throw t;
    }
}

From source file:com.cloudera.sqoop.hive.HiveImport.java

@SuppressWarnings("unchecked")
/**//from   ww w  . ja  va  2  s .  c  o  m
 * Execute the script file via Hive.
 * If Hive's jars are on the classpath, run it in the same process.
 * Otherwise, execute the file with 'bin/hive'.
 *
 * @param filename The script file to run.
 * @param env the environment strings to pass to any subprocess.
 * @throws IOException if Hive did not exit successfully.
 */
private void executeScript(String filename, List<String> env) throws IOException {
    SubprocessSecurityManager subprocessSM = null;

    try {
        Class cliDriverClass = Class.forName(HIVE_MAIN_CLASS);

        // We loaded the CLI Driver in this JVM, so we will just
        // call it in-process. The CliDriver class has a method:
        // void main(String [] args) throws Exception.
        //
        // We'll call that here to invoke 'hive -f scriptfile'.
        // Because this method will call System.exit(), we use
        // a SecurityManager to prevent this.
        LOG.debug("Using in-process Hive instance.");

        subprocessSM = new SubprocessSecurityManager();
        subprocessSM.install();

        // Create the argv for the Hive Cli Driver.
        String[] argArray = new String[2];
        argArray[0] = "-f";
        argArray[1] = filename;

        // And invoke the static method on this array.
        Method mainMethod = cliDriverClass.getMethod("main", argArray.getClass());
        mainMethod.invoke(null, (Object) argArray);

    } catch (ClassNotFoundException cnfe) {
        // Hive is not on the classpath. Run externally.
        // This is not an error path.
        LOG.debug("Using external Hive process.");
        executeExternalHiveScript(filename, env);
    } catch (NoSuchMethodException nsme) {
        // Could not find a handle to the main() method.
        throw new IOException("Could not access CliDriver.main()", nsme);
    } catch (IllegalAccessException iae) {
        // Error getting a handle on the main() method.
        throw new IOException("Could not access CliDriver.main()", iae);
    } catch (InvocationTargetException ite) {
        // We ran CliDriver.main() and an exception was thrown from within Hive.
        // This may have been the ExitSecurityException triggered by the
        // SubprocessSecurityManager. If so, handle it. Otherwise, wrap in
        // an IOException and rethrow.

        Throwable cause = ite.getCause();
        if (cause instanceof ExitSecurityException) {
            ExitSecurityException ese = (ExitSecurityException) cause;
            int status = ese.getExitStatus();
            if (status != 0) {
                throw new IOException("Hive CliDriver exited with status=" + status);
            }
        } else {
            throw new IOException("Exception thrown in Hive", ite);
        }
    } finally {
        if (null != subprocessSM) {
            // Uninstall the SecurityManager used to trap System.exit().
            subprocessSM.uninstall();
        }
    }
}

From source file:reflex.node.KernelExecutor.java

public static ReflexValue executeFunction(int lineNumber, Object outerApi, String areaName, String fnName,
        List<ReflexValue> params) {
    String apiName;/*from  w  ww.j  a  v  a 2  s . c  o m*/
    if (!StringUtils.isEmpty(areaName) && areaName.length() > 1) {
        apiName = areaName.substring(0, 1).toUpperCase() + areaName.substring(1);
    } else {
        apiName = "<api name missing>";
    }
    int numPassedParams = params.size();
    try {
        // Find the method get[AreaName], which will return the area
        Method[] methods = outerApi.getClass().getMethods();
        String getApiMethodName = "get" + apiName;

        for (Method m : methods) {
            if (m.getName().equals(getApiMethodName)) {
                // Call that method to get the api requested
                Object api = m.invoke(outerApi);
                // Now find the method with the fnName
                Method[] innerMethods = api.getClass().getMethods();
                for (Method im : innerMethods) {
                    if (im.getName().equals(fnName)) {
                        // the api should just have one entry
                        Type[] types = im.getGenericParameterTypes();
                        int numExpectedParams = types.length;
                        if (numExpectedParams == numPassedParams) {
                            List<Object> callParams = new ArrayList<Object>(types.length);
                            // Now coerce the types...
                            for (int i = 0; i < types.length; i++) {
                                ReflexValue v = params.get(i);
                                Object x = convertValueToType(v, types[i]);
                                callParams.add(x);
                            }

                            // Now invoke
                            Object ret;
                            try {
                                ret = im.invoke(api, callParams.toArray());
                            } catch (InvocationTargetException e) {
                                // TODO Auto-generated catch block
                                throw new ReflexException(lineNumber, String.format(
                                        "Error in Reflex script at line %d. Call to %s.%s failed: %s",
                                        lineNumber, apiName, fnName, e.getTargetException().getMessage()), e);
                            }
                            ReflexValue retVal = new ReflexNullValue(lineNumber);
                            if (ret != null) {
                                retVal = new ReflexValue(convertObject(ret));
                            }
                            return retVal;
                        }
                    }
                }
                throw new ReflexException(lineNumber, String.format(
                        "API call not found: %s.%s (taking %s parameters)", apiName, fnName, numPassedParams));
            }
        }
        throw new ReflexException(lineNumber, "API '" + apiName + "' not found!");
    } catch (InvocationTargetException e) {
        Throwable cause = e.getCause();
        if (cause != null) {
            if (cause instanceof OutOfMemoryError) {
                log.error(ExceptionToString.format(e));
                throw (OutOfMemoryError) cause;
            } else if (cause instanceof RaptureException) {
                log.warn(ExceptionToString.format(e));
                String message = ((RaptureException) cause).getFormattedMessage();
                throw new ReflexException(lineNumber, message, e);
            } else {
                String details = null;
                if (cause.getMessage() != null) {
                    details = ": " + cause.getMessage();
                }
                RaptureException re = RaptureExceptionFactory
                        .create(String.format("Error executing api call: %s.%s (takes %s parameters)%s",
                                apiName, fnName, numPassedParams, details), e);

                String message = re.getFormattedMessage();
                throw new ReflexException(lineNumber, message, re);
            }
        }
        throw new ReflexException(lineNumber, e.getTargetException().getMessage(), e);
    } catch (ReflexException e) {
        throw e;
    } catch (Exception e) {
        log.error(ExceptionToString.format(e));
        throw new ReflexException(lineNumber, e.getMessage(), e);
    }
}

From source file:ca.uhn.fhir.rest.method.BaseMethodBinding.java

protected final Object invokeServerMethod(IRestfulServer<?> theServer, RequestDetails theRequest,
        Object[] theMethodParams) {
    // Handle server action interceptors
    RestOperationTypeEnum operationType = getRestOperationType(theRequest);
    if (operationType != null) {
        for (IServerInterceptor next : theServer.getInterceptors()) {
            ActionRequestDetails details = new ActionRequestDetails(theRequest);
            populateActionRequestDetailsForInterceptor(theRequest, details, theMethodParams);
            next.incomingRequestPreHandled(operationType, details);
        }/* www.j a v a 2  s .  c o m*/
    }

    // Actually invoke the method
    try {
        Method method = getMethod();
        return method.invoke(getProvider(), theMethodParams);
    } catch (InvocationTargetException e) {
        if (e.getCause() instanceof BaseServerResponseException) {
            throw (BaseServerResponseException) e.getCause();
        } else {
            throw new InternalErrorException("Failed to call access method", e);
        }
    } catch (Exception e) {
        throw new InternalErrorException("Failed to call access method", e);
    }
}

From source file:org.springframework.integration.handler.LambdaMessageProcessor.java

@Override
public Object processMessage(Message<?> message) {
    Object[] args = buildArgs(message);

    try {//from ww w. j av a  2  s . com
        return this.method.invoke(this.target, args);
    } catch (InvocationTargetException e) {
        if (e.getTargetException() instanceof ClassCastException) {
            logger.error(
                    "Could not invoke the method due to a class cast exception, if using a lambda in the DSL, "
                            + "consider using an overloaded EIP method that takes a Class<?> argument to explicitly "
                            + "specify the type. An example of when this often occurs is if the lambda is configured to "
                            + "receive a Message<?> argument.",
                    e.getCause());
        }
        throw new MessageHandlingException(message, e.getCause());
    } catch (Exception e) {
        throw new MessageHandlingException(message, e);
    }
}

From source file:com.crossbusiness.resiliency.aspect.spring.AnnotationFallbackAspect.java

public Object rerouteToFallback(ProceedingJoinPoint pjp, Fallback fallbackConfig) throws Throwable {

    String[] fallbacks = fallbackConfig.value();
    Class<? extends Throwable>[] fallbackableExceptions = fallbackConfig.exceptions();

    List<Object> fallbackBeans = new ArrayList<Object>(fallbacks.length);
    for (String fallback : fallbacks) {
        try {//ww w.  j  a v a  2 s .  c  om
            fallbackBeans.add(context.getBean(fallback));
        } catch (BeansException be) {
            log.error("configuration error: cannot find bean with name: '{}'", fallback, be);
            //configuration errors should be fixed immediately.
            throw be;
        }
    }

    MethodSignature targetMethodSig = (MethodSignature) pjp.getSignature();
    Method targetMethod = targetMethodSig.getMethod();
    Class[] paramTypes = (Class[]) targetMethod.getParameterTypes();
    Object[] args = pjp.getArgs();

    log.debug("fallbacks: {} method: '{}'", fallbacks, targetMethod);

    try {
        return pjp.proceed();
    } catch (Throwable t) {

        // if the exception is not what we're looking for, rethrow it
        if (!isFallbackableException(t, fallbackableExceptions))
            throw t;

        log.debug("got exception while trying the targetBean method: '{}'. will try fallbackBean...",
                targetMethod);
        Iterator<Object> iter = fallbackBeans.iterator();
        while (iter.hasNext()) {
            Object fallbackBean = iter.next();
            Method fallbackMethod;
            try {
                fallbackMethod = fallbackBean.getClass().getMethod(targetMethod.getName(), paramTypes);
            } catch (NoSuchMethodException | SecurityException nsme) {
                log.error(
                        "configuration error: No matchig method found in fallbackBean: '{}' that matches to targetBean method: '{}'",
                        new Object[] { fallbackBean.getClass().getName(), targetMethod, nsme });
                //configuration errors should be fixed immediately.
                throw nsme;
            }
            try {
                log.debug("trying fallbackBean method: '{}'...", fallbackMethod);
                return fallbackMethod.invoke(fallbackBean, args);
            } catch (IllegalArgumentException | IllegalAccessException iae) {
                log.error(
                        "configuration error: arguments missmatch: fallbackBean method: '{}' arguments  missmatch to targetBean method: '{}' arguments",
                        new Object[] { fallbackMethod, targetMethod, iae });
                //configuration errors should be fixed immediately.
                throw iae;
            } catch (InvocationTargetException ite) {
                log.debug(
                        "got exception while trying the fallbackBean method: '{}'. will try next fallbackBean...",
                        fallbackMethod);
                //fallbackBean method thrown an exception. try next bean or throw exception if this is the last bean
                if (!iter.hasNext()) {
                    //TODO : do we still need to check isFallbackableException?
                    throw ite.getCause();
                }
            }
        }
        //code should never reach this line.
        throw t;
    }
}

From source file:org.gwtwidgets.server.spring.GWTRPCServiceExporter.java

/**
 * Handles exceptions thrown by the target service, which are wrapped in
 * {@link InvocationTargetException}s due to invocation by reflection. This
 * method is invoked by {@link #processCall(String)}. This implementation
 * encodes exceptions as RPC errors and returns them. For details on
 * arguments please consult/*from  w  ww.  jav a2  s .c  o  m*/
 * {@link #invokeMethodOnService(Object, Method, Object[], RPCRequest)}.
 * 
 * @param e
 *            Exception thrown
 * @param service
 * @param targetMethod
 * @param parameters
 * @param rpcRequest
 * @return RPC payload
 * @throws Exception
 */
protected String handleInvocationTargetException(InvocationTargetException e, Object service,
        Method targetMethod, Object[] parameters, RPCRequest rpcRequest) throws Exception {
    Throwable cause = e.getCause();
    if (!(cause instanceof RuntimeException))
        logger.warn(cause);
    return encodeResponseForFailure(rpcRequest, cause, targetMethod, parameters);
}

From source file:edu.harvard.iq.dvn.ingest.dsb.SubsettableFileChecker.java

public String detectSubsettableFormat(File fh) {
    boolean DEBUG = false;
    String readableFormatType = null;
    try {//w w  w. j  ava 2s  .  c  o m
        int buffer_size = this.getBufferSize(fh);
        // set-up a FileChannel instance for a given file object
        FileChannel srcChannel = new FileInputStream(fh).getChannel();

        // create a read-only MappedByteBuffer
        MappedByteBuffer buff = srcChannel.map(FileChannel.MapMode.READ_ONLY, 0, buffer_size);

        //this.printHexDump(buff, "hex dump of the byte-buffer");

        //for (String fmt : defaultFormatSet){
        buff.rewind();
        dbgLog.fine("before the for loop");
        for (String fmt : this.getTestFormatSet()) {
            // get a test method
            Method mthd = testMethods.get(fmt);
            try {
                // invoke this method
                Object retobj = mthd.invoke(this, buff);
                String result = (String) retobj;

                if (result != null) {
                    dbgLog.fine("result for (" + fmt + ")=" + result);
                    if (DEBUG) {
                        out.println("result for (" + fmt + ")=" + result);
                    }
                    if (readableFileTypes.contains(result)) {
                        readableFormatType = result;
                    }
                    dbgLog.fine("readableFormatType=" + readableFormatType);
                    return readableFormatType;
                } else {
                    dbgLog.fine("null was returned for " + fmt + " test");
                    if (DEBUG) {
                        out.println("null was returned for " + fmt + " test");
                    }
                }
            } catch (InvocationTargetException e) {
                Throwable cause = e.getCause();
                err.format(cause.getMessage());
                e.printStackTrace();
            } catch (IllegalAccessException e) {
                e.printStackTrace();
            }
        }

        return readableFormatType;

    } catch (FileNotFoundException fe) {
        dbgLog.fine("exception detected: file was not foud");
        fe.printStackTrace();
    } catch (IOException ie) {
        dbgLog.fine("other io exception detected");
        ie.printStackTrace();
    }
    return readableFormatType;
}

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);/*from   ww  w  . j av  a  2 s  .c  om*/

    // 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.connectsdk.cordova.JSCommandDispatcher.java

public void dispatchCommand(String interfaceName, String methodName, JSCommand command, JSONObject args,
        boolean subscribe) {
    Method method = getMethod(interfaceName, methodName);

    if (method != null) {
        try {/*from   w ww. j  a  v  a 2s.c om*/
            Object returnValue = method.invoke(this, command, args);

            if (returnValue != null && returnValue instanceof ServiceSubscription) {
                command.serviceSubscription = (ServiceSubscription<?>) returnValue;
            }
        } catch (InvocationTargetException e) {
            Throwable cause = e.getCause();
            Exception wrappedException = new DispatcherException(
                    "Exception calling " + methodName + ": " + cause.toString());
            wrappedException.initCause(cause);

            wrappedException.printStackTrace();
            command.error(wrappedException);
        } catch (Exception e) {
            e.printStackTrace();
            command.error(e);
        }
    } else {
        Log.d("ConnectSDKCordova", "Method not implemented: " + interfaceName + "." + methodName);
        command.error("method not implemented");
    }
}