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.google.dart.java2dart.SyntaxTranslator.java

/**
 * Recursively translates given {@link org.eclipse.jdt.core.dom.ASTNode} to Dart {@link ASTNode}.
 * //from w  w w. ja  v  a  2s  .  c  o  m
 * @return the corresponding Dart {@link ASTNode}, may be <code>null</code> if <code>null</code>
 *         argument was given; not <code>null</code> if argument is not <code>null</code> (if
 *         translation is not implemented, exception will be thrown).
 */
@SuppressWarnings("unchecked")
private <T extends ASTNode> T translate(final org.eclipse.jdt.core.dom.ASTNode node) {
    if (node == null) {
        return null;
    }
    ExecutionUtils.runRethrow(new RunnableEx() {
        @Override
        public void run() throws Exception {
            Method method = getMostSpecificMethod(node.getClass());
            try {
                method.invoke(SyntaxTranslator.this, node);
            } catch (InvocationTargetException e) {
                ExecutionUtils.propagate(e.getCause());
            }
        }
    });
    Assert.isNotNull(result, "No result for: " + node.getClass().getCanonicalName());
    T castedResult = (T) result;
    if (node instanceof org.eclipse.jdt.core.dom.Expression) {
        context.putNodeTypeBinding(result, ((org.eclipse.jdt.core.dom.Expression) node).resolveTypeBinding());
    }
    result = null;
    return castedResult;
}

From source file:org.codice.ddf.spatial.ogc.wfs.v2_0_0.catalog.source.TestWfsFilterDelegate.java

private void testSequentialPropertyIsNotOfTemporalType(String methName, Object... inputParams)
        throws Throwable {
    String mockMetacardAttribute = "myMetacardAttribute";
    String mockFeatureType = "myFeatureType";
    String mockFeatureProperty = "myFeatureProperty";
    List<String> mockProperties = new ArrayList<>(1);
    mockProperties.add(mockFeatureProperty);
    when(mockFeatureMetacardType.getProperties()).thenReturn(mockProperties);
    when(mockFeatureMetacardType.getName()).thenReturn(mockFeatureType);
    List<String> mockTemporalProperties = Collections.emptyList();
    when(mockFeatureMetacardType.getTemporalProperties()).thenReturn(mockTemporalProperties);
    FeatureAttributeDescriptor mockFeatureAttributeDescriptor = mock(FeatureAttributeDescriptor.class);
    when(mockFeatureAttributeDescriptor.isIndexed()).thenReturn(true);
    when(mockFeatureAttributeDescriptor.getPropertyName()).thenReturn(mockFeatureProperty);
    when(mockFeatureMetacardType.getAttributeDescriptor(mockFeatureProperty))
            .thenReturn(mockFeatureAttributeDescriptor);
    MetacardMapper mockMapper = mock(MetacardMapper.class);
    when(mockMapper.getFeatureProperty(mockMetacardAttribute)).thenReturn(mockFeatureProperty);
    WfsFilterDelegate delegate = new WfsFilterDelegate(mockFeatureMetacardType,
            MockWfsServer.getFilterCapabilities(), Wfs20Constants.EPSG_4326_URN, mockMapper,
            WfsConstants.LAT_LON_ORDER);

    try {//ww w.  j a v  a 2 s .  c  om
        // Inject the mockMetacardAttribute at the head of the array
        Object[] methParams = ObjectArrays.concat(mockMetacardAttribute, inputParams);
        // Generate the array of class types for the reflection call
        Class<?>[] classTypes = FluentIterable.from(Arrays.asList(methParams))
                .transform(new Function<Object, Class>() {
                    @Override
                    public Class<?> apply(Object o) {
                        // Autoboxing is a small problem with reflection when trying to be too clever
                        return (o instanceof Long) ? long.class : o.getClass();
                    }
                }).toArray(Class.class);

        Method method = WfsFilterDelegate.class.getMethod(methName, classTypes);
        method.invoke(delegate, methParams);
    } catch (InvocationTargetException e) {
        throw e.getCause();
    }
}

From source file:org.openecomp.sdnc.sli.aai.AAIDeclarations.java

private QueryStatus newModelProcessRelationshipList(Object instance, Map<String, String> params, String prefix,
        SvcLogicContext ctx) throws Exception {

    Class resourceClass = instance.getClass();

    Set<String> relationshipKeys = new TreeSet<String>();

    Set<String> set = params.keySet();

    for (String attribute : set) {
        String value = params.get(attribute);

        if (attribute.startsWith("relationship-list")) {
            relationshipKeys.add(attribute);
        }/*  w ww .  j av a  2  s.  c  o m*/
    }

    // 3. Process Relationships
    // add relationship list
    if (!relationshipKeys.isEmpty()) {
        RelationshipList relationshipList = null;
        Object obj = null;
        Method getRelationshipListMethod = resourceClass.getMethod("getRelationshipList");
        if (getRelationshipListMethod != null) {
            try {
                getRelationshipListMethod.setAccessible(true);
                obj = getRelationshipListMethod.invoke(instance);
            } catch (InvocationTargetException x) {
                Throwable cause = x.getCause();
            }
        }
        if (obj != null && obj instanceof RelationshipList) {
            relationshipList = (RelationshipList) obj;
        } else {
            relationshipList = new RelationshipList();
            Method setRelationshipListMethod = resourceClass.getMethod("setRelationshipList",
                    RelationshipList.class);
            if (setRelationshipListMethod != null) {
                try {
                    setRelationshipListMethod.setAccessible(true);
                    Object arglist[] = new Object[1];
                    arglist[0] = relationshipList;

                    obj = setRelationshipListMethod.invoke(instance, arglist);
                } catch (InvocationTargetException x) {
                    Throwable cause = x.getCause();
                }
            }
        }

        boolean createdNewRelationships = false;
        List<Relationship> relationships = relationshipList.getRelationship();
        if (relationships == null) {
            relationships = new ArrayList<Relationship>();
            createdNewRelationships = true;
        }

        int i = 0;
        int j = 0;
        while (true) {
            String searchKey = "relationship-list.relationship[" + i + "].related-to";
            if (!params.containsKey(searchKey))
                break;

            j = 0;
            String relatedTo = params.get(searchKey);
            String relatedLinkKey = "relationship-list.relationship[" + i + "].related-link";
            String relatedLink = null;
            if (params.containsKey(relatedLinkKey)) {
                relatedLink = params.get(relatedLinkKey);
            }

            Relationship relationship = new Relationship();
            relationships.add(relationship);
            relationship.setRelatedTo(relatedTo);
            if (relatedLink != null) {
                relationship.setRelatedLink(relatedLink);
            } else {
                List<RelationshipData> relData = relationship.getRelationshipData();

                while (true) {
                    String searchRelationshipKey = "relationship-list.relationship[" + i
                            + "].relationship-data[" + j + "].relationship-key";
                    String searchRelationshipValue = "relationship-list.relationship[" + i
                            + "].relationship-data[" + j + "].relationship-value";
                    if (!params.containsKey(searchRelationshipKey))
                        break;

                    RelationshipData relDatum = new RelationshipData();
                    relDatum.setRelationshipKey(params.get(searchRelationshipKey));
                    relDatum.setRelationshipValue(params.get(searchRelationshipValue));
                    relData.add(relDatum);
                    j++;
                }
            }

            i++;
        }
    }

    return QueryStatus.SUCCESS;
}

From source file:org.openecomp.sdnc.sli.aai.AAIDeclarations.java

private QueryStatus processDeleteRelationshipList(String resource, String key, SvcLogicContext ctx,
        HashMap<String, String> nameValues) {
    try {/*from  w  w w  . ja va 2  s.c  om*/
        AAIRequest request = AAIRequest.createRequest(resource, nameValues);
        if (request == null) {
            return QueryStatus.FAILURE;
        }

        request.processRequestPathValues(nameValues);
        URL url = request.getRequestUrl("GET", null);

        Class resourceClass = request.getModelClass();
        Object instance = getResource(url.toString(), resourceClass);
        if (instance == null)
            return QueryStatus.NOT_FOUND;

        // get resource version
        String resourceVersion = null;
        Method getResourceVersionMethod = resourceClass.getMethod("getResourceVersion");
        if (getResourceVersionMethod != null) {
            try {
                getResourceVersionMethod.setAccessible(true);
                Object object = getResourceVersionMethod.invoke(instance);
                if (object != null)
                    resourceVersion = object.toString();
            } catch (InvocationTargetException x) {
                Throwable cause = x.getCause();
            }
        }

        RelationshipList relationshipList = null;
        Object obj = null;
        Method getRelationshipListMethod = resourceClass.getMethod("getRelationshipList");
        if (getRelationshipListMethod != null) {
            try {
                getRelationshipListMethod.setAccessible(true);
                obj = getRelationshipListMethod.invoke(instance);
            } catch (InvocationTargetException x) {
                Throwable cause = x.getCause();
            }
        }
        if (obj != null && obj instanceof RelationshipList) {
            relationshipList = (RelationshipList) obj;
        } else {
            getLogger().debug("No relationships found to process.");
            return QueryStatus.NOT_FOUND;
        }

        if (relationshipList.getRelationship() == null || relationshipList.getRelationship().isEmpty()) {
            return QueryStatus.NOT_FOUND;
        }
        String relatedTo = nameValues.get("related_to");
        if (relatedTo == null) {
            return QueryStatus.FAILURE;
        }

        relatedTo = relatedTo.replaceAll("_", "-");

        String relatedLink = nameValues.get("relationship.related_link");
        if (relatedLink != null) {
            relatedLink = URLDecoder.decode(relatedLink, "UTF-8");
        }

        List<Relationship> relationships = relationshipList.getRelationship();
        List<Relationship> relationshipsToDelete = new LinkedList<Relationship>();

        for (Relationship relationship : relationships) {
            if (relatedTo.equals(relationship.getRelatedTo())) {
                if (relatedLink != null) {
                    if (relationship.getRelatedLink() != null) {
                        String localRelatedLink = relationship.getRelatedLink();
                        localRelatedLink = URLDecoder.decode(localRelatedLink, "UTF-8");
                        if (localRelatedLink.endsWith(relatedLink)) {
                            getLogger().debug(String.format("Found relationship of '%s' to keyword '%s'",
                                    relationship.getRelatedTo(), relatedTo));
                            relationshipsToDelete.add(relationship);
                        }
                    }
                } else {
                    getLogger().debug(String.format("Found relationship of '%s' to keyword '%s'",
                            relationship.getRelatedTo(), relatedTo));
                    relationshipsToDelete.add(relationship);
                }
            }
        }
        if (relationshipsToDelete == null || relationshipsToDelete.isEmpty()) {
            getLogger().info(String.format("Relationship has not been found for %s", key));
            return QueryStatus.NOT_FOUND;
        }

        String path = url.toString();
        path = path + "/relationship-list/relationship";
        URL deleteUrl = new URL(path);

        ObjectMapper mapper = AAIService.getObjectMapper();

        boolean cumulativeResponse = true;

        for (Relationship targetRelationship : relationshipsToDelete) {
            String json_text = mapper.writeValueAsString(targetRelationship);
            boolean response = deleteRelationshipList(deleteUrl, json_text);
            if (!response)
                cumulativeResponse = response;

        }

        if (!cumulativeResponse)
            return QueryStatus.FAILURE;

        return QueryStatus.SUCCESS;

    } catch (Exception exc) {
        getLogger().warn("processDelete", exc);
        return QueryStatus.FAILURE;
    }
}

From source file:org.graphwalker.ModelBasedTesting.java

private void executeMethod(Class<?> clsClass, Object objInstance, String strMethod, boolean isEdge)
        throws IllegalArgumentException, SecurityException, IllegalAccessException {
    if (strMethod.contains("/")) {
        strMethod = strMethod.substring(0, strMethod.indexOf('/'));
    }//from  ww w .ja  v a  2 s  . c o m

    if (strMethod.contains("[")) {
        strMethod = strMethod.substring(0, strMethod.indexOf('['));
    }

    if (strMethod.contains(" ")) {
        String s1 = strMethod.substring(0, strMethod.indexOf(' '));
        String s2 = strMethod.substring(strMethod.indexOf(' ') + 1);
        Class<?>[] paramTypes = { String.class };
        Object[] paramValues = { s2 };

        try {
            clsClass.getMethod(s1, paramTypes).invoke(objInstance, paramValues);
        } catch (InvocationTargetException e) {
            if (isEdge) {
                logger.error("InvocationTargetException for: " + getMachine().getLastEdge());
            } else {
                logger.error("InvocationTargetException for: " + getMachine().getCurrentVertex());
            }
            throw new RuntimeException("InvocationTargetException.", e);
        } catch (NoSuchMethodException e) {
            logger.error("In model: " + getGraph());
            if (isEdge) {
                logger.error("NoSuchMethodException for: " + getMachine().getLastEdge());
            } else {
                logger.error("NoSuchMethodException for: " + getMachine().getCurrentVertex());
            }
            throw new RuntimeException("NoSuchMethodException.", e);
        }
    } else {
        if (isEdge && strMethod.isEmpty()) {
            return;
        }
        try {
            Method m = clsClass.getMethod(strMethod, null);
            m.invoke(objInstance, null);
        } catch (InvocationTargetException e) {
            if (isEdge) {
                logger.error("InvocationTargetException for: " + getMachine().getLastEdge() + " : "
                        + e.getCause().getMessage());
            } else {
                logger.error("InvocationTargetException for: " + getMachine().getCurrentVertex() + " : "
                        + e.getCause().getMessage());
            }
            Util.logStackTraceToError(e);
            throw new RuntimeException("InvocationTargetException.", e.getCause());
        } catch (NoSuchMethodException e) {
            logger.error("In model: " + getGraph());
            if (isEdge) {
                logger.error("Method: " + getMachine().getLastEdge() + ", is missing in class: " + clsClass);
            } else {
                logger.error(
                        "Method: " + getMachine().getCurrentVertex() + ", is missing in class: " + clsClass);
            }
            throw new RuntimeException("NoSuchMethodException.", e);
        }
    }
}

From source file:jp.co.acroquest.jsonic.Formatter.java

public boolean format(final JSON json, final Context context, final Object src, final Object o,
        final OutputSource out) throws Exception {
    out.append('{');
    int count = 0;
    try {/*from   w ww.  ja v a2 s  .  c  o m*/
        Class<?> dynaBeanClass = ClassUtil.findClass("org.apache.commons.beanutils.DynaBean");

        Object dynaClass = dynaBeanClass.getMethod("getDynaClass").invoke(o);
        Object[] dynaProperties = (Object[]) dynaClass.getClass().getMethod("getDynaProperties")
                .invoke(dynaClass);

        if (dynaProperties != null && dynaProperties.length > 0) {
            Method getName = dynaProperties[0].getClass().getMethod("getName");
            Method get = dynaBeanClass.getMethod("get", String.class);

            for (Object dp : dynaProperties) {
                Object name = null;
                try {
                    name = getName.invoke(dp);
                } catch (InvocationTargetException e) {
                    throw e;
                } catch (Exception e) {
                }
                if (name == null)
                    continue;

                Object value = null;
                Exception cause = null;

                try {
                    value = get.invoke(o, name);
                } catch (Exception e) {
                    cause = e;
                }

                if (value == src || (cause == null && context.isSuppressNull() && value == null)) {
                    continue;
                }

                if (count != 0)
                    out.append(',');
                if (context.isPrettyPrint()) {
                    out.append('\n');
                    for (int j = 0; j < context.getDepth() + 1; j++)
                        out.append('\t');
                }
                StringFormatter.serialize(context, name.toString(), out);
                out.append(':');
                if (context.isPrettyPrint())
                    out.append(' ');
                context.enter(name);
                if (cause != null)
                    throw cause;
                value = json.preformatInternal(context, value);
                json.formatInternal(context, value, out);
                context.exit();
                count++;
            }
        }
    } catch (InvocationTargetException e) {
        if (e.getCause() instanceof Error) {
            throw (Error) e.getCause();
        } else if (e.getCause() instanceof RuntimeException) {
            throw (RuntimeException) e.getCause();
        } else {
            throw (Exception) e.getCause();
        }
    } catch (Exception e) {
        // no handle
    }
    if (context.isPrettyPrint() && count > 0) {
        out.append('\n');
        for (int j = 0; j < context.getDepth(); j++)
            out.append('\t');
    }
    out.append('}');
    return true;
}

From source file:org.eclipse.wb.internal.core.utils.ast.AstEditor.java

/**
 * Replaces given <code>originalNode</code> with <code>replacementNode</code>. This method uses
 * "duck type" implementation, i.e. uses names and types to identify location of nodes instead of
 * direct checks for {@link ASTNode} structures.
 *//*  w ww  .  j  a v a  2 s .  c o  m*/
@SuppressWarnings("unchecked")
public static void replaceNode(ASTNode originalNode, ASTNode replacementNode) throws Exception {
    ASTNode parent = originalNode.getParent();
    // special case: QualifiedName -> FieldAccess
    if (replaceNode_QualifiedName_to_FieldAccess(originalNode, replacementNode)) {
        return;
    }
    // use "duck type"
    Class<?> parentClass = parent.getClass();
    for (Method method : parentClass.getMethods()) {
        if (method.getParameterTypes().length == 0 && !m_invalidNodeMethods.contains(method)) {
            String methodName = method.getName();
            Class<?> returnType = method.getReturnType();
            try {
                // check for getXXX() and use setXXX()
                if (methodName.startsWith("get") && returnType.isAssignableFrom(originalNode.getClass())
                        && method.invoke(parent) == originalNode) {
                    String setMethodName = "set" + methodName.substring("get".length());
                    Method setMethod = parentClass.getMethod(setMethodName, new Class[] { returnType });
                    setMethod.invoke(parent, new Object[] { replacementNode });
                    break;
                }
                // check for "List xxx()" and use "List.set()"
                if (returnType == List.class) {
                    List<ASTNode> elements = (List<ASTNode>) method.invoke(parent);
                    int index = elements.indexOf(originalNode);
                    if (index != -1) {
                        elements.set(index, replacementNode);
                        break;
                    }
                }
            } catch (InvocationTargetException e) {
                Assert.isTrue(e.getCause() instanceof UnsupportedOperationException);
                // it is possible that we will try to call method that is not supported in JLS3 AST,
                // so we should catch exception and ignore such methods
                m_invalidNodeMethods.add(method);
            }
        }
    }
}

From source file:com.xpn.xwiki.XWiki.java

/**
 * @deprecated replaced by the <a href="http://code.xwiki.org/xwiki/bin/view/Plugins/MailSenderPlugin">Mail Sender
 *             Plugin</a>//  ww  w.  ja  va  2s. c o m
 */
@Deprecated
public void sendMessage(String sender, String[] recipients, String rawMessage, XWikiContext context)
        throws XWikiException {
    LOGGER.trace("Entering sendMessage()");

    // We'll be using the MailSender plugin, which has much more advanced capabilities (authentication, TLS).
    // Since the plugin is in another module, and it depends on the core, we have to use it through reflection in
    // order to avoid cyclic dependencies. This should be fixed once the mailsender becomes a clean component
    // instead of a plugin.
    Object mailSender;
    Class mailSenderClass;
    Method mailSenderSendRaw;

    try {
        mailSender = getPluginApi("mailsender", context);
        mailSenderClass = Class.forName("com.xpn.xwiki.plugin.mailsender.MailSenderPluginApi");

        // public int sendRawMessage(String from, String to, String rawMessage)
        mailSenderSendRaw = mailSenderClass.getMethod("sendRawMessage",
                new Class[] { String.class, String.class, String.class });
    } catch (Exception e) {
        LOGGER.error("Problem getting MailSender via Reflection. Using the old sendMessage mechanism.", e);
        sendMessageOld(sender, recipients, rawMessage, context);
        return;
    }

    if (LOGGER.isTraceEnabled()) {
        LOGGER.trace("Sending message = \"" + rawMessage + "\"");
    }

    String messageRecipients = StringUtils.join(recipients, ',');

    try {
        mailSenderSendRaw.invoke(mailSender, sender, messageRecipients, rawMessage);
    } catch (InvocationTargetException ite) {
        Throwable cause = ite.getCause();
        if (cause instanceof XWikiException) {
            throw (XWikiException) cause;
        } else {
            throw new RuntimeException(cause);
        }
    } catch (Exception e) {
        // Probably either IllegalAccessException or IllegalArgumentException
        // Shouldn't happen unless there were an incompatible code change
        throw new RuntimeException(e);
    }

    LOGGER.info("Exiting sendMessage(). It seems everything went ok.");
}

From source file:org.openTwoFactor.client.util.TwoFactorClientCommonUtils.java

/**
 * Safely invoke a reflection method/* w w  w  .  jav  a 2s  .c  om*/
 * 
 * @param method
 *            to invoke
 * @param invokeOn
 * @param paramsOrListOrArray must be an arg.  If null, will pass null.
 * if NO_PARAMS then will not pass in params.
 * @return the result
 */
public static Object invokeMethod(Method method, Object invokeOn, Object paramsOrListOrArray) {

    Object[] args = paramsOrListOrArray == NO_PARAMS ? null : (Object[]) toArray(paramsOrListOrArray);

    //we want to make sure things are accessible
    method.setAccessible(true);

    //only if the method exists, try to execute
    Object result = null;
    Exception e = null;
    try {
        result = method.invoke(invokeOn, args);
    } catch (IllegalAccessException iae) {
        e = iae;
    } catch (IllegalArgumentException iae) {
        e = iae;
    } catch (InvocationTargetException ite) {
        //this means the underlying call caused exception... its ok if runtime
        if (ite.getCause() instanceof RuntimeException) {
            throw (RuntimeException) ite.getCause();
        }
        //else throw as invocation target...
        e = ite;
    }
    if (e != null) {
        throw new RuntimeException("Cant execute reflection method: " + method.getName() + ", on: "
                + className(invokeOn) + ", with args: " + classNameCollection(args), e);
    }
    return result;
}

From source file:org.evosuite.testcase.statements.FunctionalMockStatement.java

@Override
public Throwable execute(Scope scope, PrintStream out) throws InvocationTargetException,
        IllegalArgumentException, IllegalAccessException, InstantiationException {

    Throwable exceptionThrown = null;

    try {/*from  w w w. ja v a  2 s .co m*/
        return super.exceptionHandler(new Executer() {

            @Override
            public void execute() throws InvocationTargetException, IllegalArgumentException,
                    IllegalAccessException, InstantiationException, CodeUnderTestException {

                // First create the listener
                listener = new EvoInvocationListener(retval.getType());

                //then create the mock
                Object ret;
                try {
                    logger.debug("Mockito: create mock for {}", targetClass);

                    ret = mock(targetClass, withSettings().invocationListeners(listener));
                    //ret = mockCreator.invoke(null,targetClass,withSettings().invocationListeners(listener));

                    //execute all "when" statements
                    int index = 0;

                    logger.debug("Mockito: going to mock {} different methods", mockedMethods.size());
                    for (MethodDescriptor md : mockedMethods) {

                        if (!md.shouldBeMocked()) {
                            //no need to mock a method that returns void
                            logger.debug("Mockito: method {} cannot be mocked", md.getMethodName());
                            continue;
                        }

                        Method method = md.getMethod(); //target method, eg foo.aMethod(...)

                        // this is needed if method is protected: it couldn't be called here, although fine in
                        // the generated JUnit tests
                        method.setAccessible(true);

                        //target inputs
                        Object[] targetInputs = new Object[md.getNumberOfInputParameters()];
                        for (int i = 0; i < targetInputs.length; i++) {
                            logger.debug("Mockito: executing matcher {}/{}", (1 + i), targetInputs.length);
                            targetInputs[i] = md.executeMatcher(i);
                        }

                        logger.debug("Mockito: going to invoke method {} with {} matchers", method.getName(),
                                targetInputs.length);

                        if (!method.getDeclaringClass().isAssignableFrom(ret.getClass())) {

                            String msg = "Mismatch between callee's class " + ret.getClass()
                                    + " and method's class " + method.getDeclaringClass();
                            msg += "\nTarget class classloader " + targetClass.getClassLoader()
                                    + " vs method's classloader " + method.getDeclaringClass().getClassLoader();
                            throw new EvosuiteError(msg);
                        }

                        //actual call foo.aMethod(...)
                        Object targetMethodResult;

                        try {
                            if (targetInputs.length == 0) {
                                targetMethodResult = method.invoke(ret);
                            } else {
                                targetMethodResult = method.invoke(ret, targetInputs);
                            }
                        } catch (InvocationTargetException e) {
                            logger.error(
                                    "Invocation of mocked {}.{}() threw an exception. "
                                            + "This means the method was not mocked",
                                    targetClass.getName(), method.getName());
                            throw e;
                        } catch (IllegalArgumentException e) {
                            logger.error("IAE on <" + method + "> when called with "
                                    + Arrays.toString(targetInputs));
                            throw e;
                        }

                        //when(...)
                        logger.debug("Mockito: call 'when'");
                        OngoingStubbing<Object> retForThen = Mockito.when(targetMethodResult);

                        //thenReturn(...)
                        Object[] thenReturnInputs = null;
                        try {
                            int size = Math.min(md.getCounter(), Properties.FUNCTIONAL_MOCKING_INPUT_LIMIT);

                            thenReturnInputs = new Object[size];

                            for (int i = 0; i < thenReturnInputs.length; i++) {

                                int k = i + index; //the position in flat parameter list
                                if (k >= parameters.size()) {
                                    throw new RuntimeException(
                                            "EvoSuite ERROR: index " + k + " out of " + parameters.size());
                                }

                                VariableReference parameterVar = parameters.get(i + index);
                                thenReturnInputs[i] = parameterVar.getObject(scope);

                                CodeUnderTestException codeUnderTestException = null;

                                if (thenReturnInputs[i] == null && method.getReturnType().isPrimitive()) {
                                    codeUnderTestException = new CodeUnderTestException(
                                            new NullPointerException());

                                } else if (thenReturnInputs[i] != null && !TypeUtils
                                        .isAssignable(thenReturnInputs[i].getClass(), method.getReturnType())) {
                                    codeUnderTestException = new CodeUnderTestException(
                                            new UncompilableCodeException(
                                                    "Cannot assign " + parameterVar.getVariableClass().getName()
                                                            + " to " + method.getReturnType()));
                                }

                                if (codeUnderTestException != null) {
                                    throw codeUnderTestException;
                                }

                                thenReturnInputs[i] = fixBoxing(thenReturnInputs[i], method.getReturnType());
                            }
                        } catch (Exception e) {
                            //be sure "then" is always called after a "when", otherwise Mockito might end up in
                            //a inconsistent state
                            retForThen
                                    .thenThrow(new RuntimeException("Failed to setup mock: " + e.getMessage()));
                            throw e;
                        }

                        //final call when(...).thenReturn(...)
                        logger.debug("Mockito: executing 'thenReturn'");
                        if (thenReturnInputs == null || thenReturnInputs.length == 0) {
                            retForThen.thenThrow(new RuntimeException("No valid return value"));
                        } else if (thenReturnInputs.length == 1) {
                            retForThen.thenReturn(thenReturnInputs[0]);
                        } else {
                            Object[] values = Arrays.copyOfRange(thenReturnInputs, 1, thenReturnInputs.length);
                            retForThen.thenReturn(thenReturnInputs[0], values);
                        }

                        index += thenReturnInputs == null ? 0 : thenReturnInputs.length;
                    }

                } catch (CodeUnderTestException e) {
                    throw e;
                } catch (java.lang.NoClassDefFoundError e) {
                    AtMostOnceLogger.error(logger, "Cannot use Mockito on " + targetClass
                            + " due to failed class initialization: " + e.getMessage());
                    return; //or should throw an exception?
                } catch (Throwable t) {
                    AtMostOnceLogger.error(logger,
                            "Failed to use Mockito on " + targetClass + ": " + t.getMessage());
                    throw new EvosuiteError(t);
                }

                //finally, activate the listener
                listener.activate();

                try {
                    retval.setObject(scope, ret);
                } catch (CodeUnderTestException e) {
                    throw e;
                } catch (Throwable e) {
                    throw new EvosuiteError(e);
                }
            }

            /**
             * a "char" can be used for a "int". But problem is that Mockito takes as input
             * Object, and so those get boxed. However, a Character cannot be used for a "int",
             * so we need to be sure to convert it here
             *
             * @param value
             * @param expectedType
             * @return
             */
            private Object fixBoxing(Object value, Class<?> expectedType) {

                if (!expectedType.isPrimitive()) {
                    return value;
                }

                Class<?> valuesClass = value.getClass();
                assert !valuesClass.isPrimitive();

                if (expectedType.equals(Integer.TYPE)) {
                    if (valuesClass.equals(Character.class)) {
                        value = (int) ((Character) value).charValue();
                    } else if (valuesClass.equals(Byte.class)) {
                        value = (int) ((Byte) value).intValue();
                    } else if (valuesClass.equals(Short.class)) {
                        value = (int) ((Short) value).intValue();
                    }
                }

                if (expectedType.equals(Double.TYPE)) {
                    if (valuesClass.equals(Integer.class)) {
                        value = (double) ((Integer) value).intValue();
                    } else if (valuesClass.equals(Byte.class)) {
                        value = (double) ((Byte) value).intValue();
                    } else if (valuesClass.equals(Character.class)) {
                        value = (double) ((Character) value).charValue();
                    } else if (valuesClass.equals(Short.class)) {
                        value = (double) ((Short) value).intValue();
                    } else if (valuesClass.equals(Long.class)) {
                        value = (double) ((Long) value).longValue();
                    } else if (valuesClass.equals(Float.class)) {
                        value = (double) ((Float) value).floatValue();
                    }
                }

                if (expectedType.equals(Float.TYPE)) {
                    if (valuesClass.equals(Integer.class)) {
                        value = (float) ((Integer) value).intValue();
                    } else if (valuesClass.equals(Byte.class)) {
                        value = (float) ((Byte) value).intValue();
                    } else if (valuesClass.equals(Character.class)) {
                        value = (float) ((Character) value).charValue();
                    } else if (valuesClass.equals(Short.class)) {
                        value = (float) ((Short) value).intValue();
                    } else if (valuesClass.equals(Long.class)) {
                        value = (float) ((Long) value).longValue();
                    }
                }

                if (expectedType.equals(Long.TYPE)) {
                    if (valuesClass.equals(Integer.class)) {
                        value = (long) ((Integer) value).intValue();
                    } else if (valuesClass.equals(Byte.class)) {
                        value = (long) ((Byte) value).intValue();
                    } else if (valuesClass.equals(Character.class)) {
                        value = (long) ((Character) value).charValue();
                    } else if (valuesClass.equals(Short.class)) {
                        value = (long) ((Short) value).intValue();
                    }
                }

                return value;
            }

            @Override
            public Set<Class<? extends Throwable>> throwableExceptions() {
                Set<Class<? extends Throwable>> t = new LinkedHashSet<>();
                t.add(InvocationTargetException.class);
                return t;
            }
        });

    } catch (InvocationTargetException e) {
        exceptionThrown = e.getCause();
    }
    return exceptionThrown;
}