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:com.netspective.commons.xdm.XmlDataModelSchema.java

public void storeElement(XdmParseContext pc, Object element, Object child, String elementName,
        boolean withinCustom) throws DataModelException {
    if (elementName == null)
        return;//from   w w w .ja va 2  s  .  co m

    NestedStorer ns = (NestedStorer) nestedStorers.get(elementName);
    try {
        if (ns == null && (!withinCustom && element instanceof CustomElementStorer))
            ((CustomElementStorer) element).storeCustomDataModelElement(pc, this, element, child, elementName);
        else if (ns != null)
            ns.store(element, child);
    } catch (InvocationTargetException ite) {
        pc.addError(
                "Could not store data for for element '" + elementName + "' at " + pc.getLocator().getSystemId()
                        + " line " + pc.getLocator().getLineNumber() + ": " + ite.getMessage());
        log.error(ite);
        if (pc.isThrowErrorException()) {
            Throwable t = ite.getTargetException();
            if (t instanceof DataModelException) {
                throw (DataModelException) t;
            }
            throw new DataModelException(pc, t);
        }
    } catch (Exception e) {
        pc.addError(
                "Could not store data for for element '" + elementName + "' at " + pc.getLocator().getSystemId()
                        + " line " + pc.getLocator().getLineNumber() + ": " + e.getMessage());
        log.error(e);
        if (pc.isThrowErrorException())
            throw new DataModelException(pc, e);
    }
}

From source file:com.netspective.commons.xdm.XmlDataModelSchema.java

protected Object createElement(XdmParseContext pc, String alternateClassName, Object element,
        String elementName) throws DataModelException, UnsupportedElementException {
    try {// w w  w.  j a v  a  2 s .  co m
        if (alternateClassName != null) {
            Class cls = null;
            try {
                cls = Class.forName(alternateClassName);
            } catch (ClassNotFoundException e) {
                pc.addError("Class '" + alternateClassName + "' for element '" + elementName + "' not found at "
                        + pc.getLocator().getSystemId() + " line " + pc.getLocator().getLineNumber() + ". "
                        + e.getMessage());
                log.error(e);
                if (pc.isThrowErrorException())
                    throw new DataModelException(pc, e);
                else {
                    NestedCreator nc = (NestedCreator) nestedCreators.get(elementName);
                    if (nc != null)
                        return nc.create(element);
                }
            }

            NestedAltClassCreator nac = (NestedAltClassCreator) nestedAltClassNameCreators.get(elementName);
            if (nac != null)
                return nac.create(element, cls);
            else {
                // check to make sure that either a storer or creator is available to ensure it's a valid tag
                if (nestedCreators.get(elementName) != null || nestedStorers.get(elementName) != null)
                    return cls.newInstance();

                UnsupportedElementException e = new UnsupportedElementException(this, pc, element, elementName);
                if (pc != null) {
                    pc.addError(e);
                    if (pc.isThrowErrorException())
                        throw e;
                    else
                        return null;
                } else
                    return null;
            }
        } else {
            NestedCreator nc = (NestedCreator) nestedCreators.get(elementName);
            if (nc != null)
                return nc.create(element);
        }
    } catch (InvocationTargetException ite) {
        pc.addError("Could not create class '" + alternateClassName + "' for element '" + elementName + "' at "
                + pc.getLocator().getSystemId() + " line " + pc.getLocator().getLineNumber() + ": "
                + ite.getMessage());
        log.error(ite);
        if (pc.isThrowErrorException()) {
            Throwable t = ite.getTargetException();
            if (t instanceof DataModelException) {
                throw (DataModelException) t;
            }
            throw new DataModelException(pc, t);
        }
    } catch (Exception e) {
        pc.addError("Could not create class '" + alternateClassName + "' for element '" + elementName + "' at "
                + pc.getLocator().getSystemId() + " line " + pc.getLocator().getLineNumber() + ": "
                + e.getMessage());
        log.error(e);
        if (pc.isThrowErrorException())
            throw new DataModelException(pc, e);
    }

    // if the element is being defined as a sub-element but has an attribute of the same name, it's a convenience attribute setter
    AttributeSetter as = (AttributeSetter) attributeSetters.get(elementName);
    if (as != null)
        return element;
    else {
        // see if we're trying to set a named flag as a sub-element
        for (Iterator i = flagsAttributeAccessors.entrySet().iterator(); i.hasNext();) {
            Map.Entry entry = (Map.Entry) i.next();
            AttributeAccessor accessor = (AttributeAccessor) entry.getValue();
            Object returnVal = null;
            try {
                returnVal = accessor.get(pc, element);
            } catch (Exception e) {
            }

            if (returnVal instanceof XdmBitmaskedFlagsAttribute)
                return element;
        }

        UnsupportedElementException e = new UnsupportedElementException(this, pc, element, elementName);
        if (pc != null) {
            pc.addError(e);
            if (pc.isThrowErrorException())
                throw e;
            else
                return null;
        } else
            return null;
    }
}

From source file:com.ucuenca.pentaho.plugin.step.EldaPDIStepDialog.java

private String lookupGetterMethod(String nameMethod) {
    String value = "";
    for (StepMeta stepMeta : this.transMeta.findPreviousSteps(this.stepMeta)) {

        StepMetaInterface stepMetaIn = stepMeta.getStepMetaInterface();

        try {/*from   w w  w.j  ava2  s .  c  o m*/
            for (Method method : stepMetaIn.getClass().getDeclaredMethods()) {
                if (method.getName().equals(nameMethod)) {
                    value = (String) method.invoke(stepMetaIn);
                    break;
                }
            }
        } catch (IllegalAccessException ne) {
            logBasic(ne.getMessage());
            value = "";
        } catch (IllegalArgumentException se) {
            logBasic(se.getMessage());
            value = "";
        } catch (InvocationTargetException ae) {
            logBasic(ae.getMessage());
            value = "";
        } finally {
            if (value != null)
                break;
        }
    }
    return value;
}

From source file:org.talend.core.model.update.RepositoryUpdateManager.java

public boolean doWork(boolean show, final boolean onlyImpactAnalysis) {
    /*//from  www.ja v a2 s.  co m
     * NOTE: Most of functions are similar with AbstractRepositoryUpdateManagerProvider.updateForRepository, so if
     * update this, maybe need check the updateForRepository too.
     */

    // check the dialog.
    boolean checked = true;
    boolean showed = false;
    if (show) {
        if (needForcePropagationForContext()) {
            checked = openRenameCheckedDialog(); // bug 4988
            showed = true;
        } else if (parameter != null && !needForcePropagation()) {
            // see feature 4786
            IDesignerCoreService designerCoreService = CoreRuntimePlugin.getInstance().getDesignerCoreService();
            boolean deactive = designerCoreService != null ? Boolean.parseBoolean(
                    designerCoreService.getPreferenceStore(ITalendCorePrefConstants.DEACTIVE_REPOSITORY_UPDATE))
                    : true;
            if (deactive) {
                return false;
            }

            checked = openPropagationDialog();
            showed = true;
        }
    } else {
        showed = true;
    }
    if (checked) {
        final List<UpdateResult> results = new ArrayList<UpdateResult>();
        boolean cancelable = !needForcePropagation();
        final IRunnableWithProgress runnable = new IRunnableWithProgress() {

            @SuppressWarnings("unchecked")
            @Override
            public void run(IProgressMonitor monitor) throws InvocationTargetException, InterruptedException {
                List<UpdateResult> returnResult = checkJobItemsForUpdate(monitor,
                        (Set<IUpdateItemType>) getTypes(), onlyImpactAnalysis);
                if (returnResult != null) {
                    results.addAll(returnResult);
                }
            }
        };

        try {
            if (CommonsPlugin.isHeadless() || Display.getCurrent() == null) {
                runnable.run(new NullProgressMonitor());
            } else {
                // final ProgressMonitorJobsDialog dialog = new ProgressMonitorJobsDialog(null);
                final ProgressMonitorDialog dialog = new ProgressMonitorDialog(null);
                dialog.run(true, cancelable, runnable);
            }

            // PlatformUI.getWorkbench().getProgressService().run(true, true, runnable);
        } catch (InvocationTargetException e) {
            ExceptionHandler.process(e);
        } catch (InterruptedException e) {
            if (e.getMessage().equals(UpdatesConstants.MONITOR_IS_CANCELED)) {
                return false;
            }
            ExceptionHandler.process(e);
        }
        List<UpdateResult> checkedResults = null;

        if (parameter == null) { // update all job
            checkedResults = filterSpecialCheckedResult(results);
        } else { // filter
            checkedResults = filterCheckedResult(results);
        }
        if (checkedResults != null && !checkedResults.isEmpty()) {
            boolean updateResult = false;
            if (showed || parameter == null || unShowDialog(checkedResults) || openPropagationDialog()) {
                IDesignerCoreService designerCoreService = CoreRuntimePlugin.getInstance()
                        .getDesignerCoreService();
                if (show) {
                    updateResult = designerCoreService.executeUpdatesManager(checkedResults,
                            onlyImpactAnalysis);
                } else {
                    updateResult = designerCoreService.executeUpdatesManagerBackgroud(checkedResults,
                            onlyImpactAnalysis);
                }
            }
            // Added TDQ-15353 propogate context changes on DQ side
            updateContextOnDQ(checked);
            return updateResult;
        }
        if (show) {
            openNoModificationDialog();
        }
    }

    // Added TDQ-15353 propogate context changes on DQ side
    updateContextOnDQ(checked);

    getColumnRenamedMap().clear();
    return false;
}

From source file:com.novartis.opensource.yada.YADARequest.java

/**
 * Uses java reflection to invoke the "setter" method associated to {@code alias}
 * @since 4.0.0// w  w w. j a v  a 2  s .  com
 * @param alias the parameter name
 * @param value the parameter value(s)
 * @throws YADARequestException when there is a method invocation problem with the setter for {@code alias} 
 */
public void invokeSetter(String alias, String[] value) throws YADARequestException {
    //input
    String field = getFieldAlias(alias);
    // list of methods
    Method[] methods = this.getClass().getMethods();
    // currently inquired method name
    String mName = "set" + field.substring(0, 1).toUpperCase() + field.substring(1);
    // iterate over methods
    for (int i = 0; i < methods.length; i++) {
        String methName = methods[i].getName();

        if (methName.equals(mName) && methods[i].getParameterTypes()[0].isArray()) {
            l.debug("methName:" + methName + ":" + mName);
            try {
                methods[i].invoke(this, new Object[] { value });
            } catch (InvocationTargetException e) {
                throw new YADARequestException(e.getMessage(), e);
            } catch (IllegalAccessException e) {
                throw new YADARequestException(e.getMessage(), e);
            }
        }
    }
}

From source file:com.novartis.opensource.yada.YADARequest.java

/**
 * Uses java reflection to invoke the "getter" method associated to the {@code alias} arg.
 * /* w w w  .j ava 2 s  .  co  m*/
 * @since 4.0.0
 * @param alias the parameter name
 * @return Object value of parameter corresponding to getter method 
 * @throws YADARequestException when method invocation fails
 */
public Object invokeGetter(String alias) throws YADARequestException {
    // input
    String field = getFieldAlias(alias);
    // return value
    Object o = null;
    // list of methods
    Method[] methods = this.getClass().getMethods();
    // currently inquired method name
    String mName = "set" + field.substring(0, 1).toUpperCase() + field.substring(1);
    // iterate over methods
    for (int i = 0; i < methods.length; i++) {
        String methName = methods[i].getName();
        if (methName.equals(mName)) {
            l.debug("methName:" + methName + ":" + mName);
            try {
                o = methods[i].invoke(this, new Object[] {});
            } catch (InvocationTargetException e) {
                throw new YADARequestException(e.getMessage(), e);
            } catch (IllegalAccessException e) {
                throw new YADARequestException(e.getMessage(), e);
            }
        }
    }
    return o;
}

From source file:com.novartis.opensource.yada.YADARequest.java

/**
 * Uses java reflection to invoke the "setter" method associated to {@code alias}
 * @param alias the parameter name//  w w  w  . j  av a 2 s. c o  m
 * @param value the parameter value
 * @throws YADARequestException when there is a method invocation problem with the setter for {@code alias}
 */
public void invokeSetter(String alias, String value) throws YADARequestException {
    //input
    String field = getFieldAlias(alias);
    // list of methods
    Method[] methods = this.getClass().getMethods();
    // currently inquired method name
    String mName = "set" + field.substring(0, 1).toUpperCase() + field.substring(1);
    // iterate over methods
    for (int i = 0; i < methods.length; i++) {
        String[] arglist = new String[1];
        String methName = methods[i].getName();

        if (methName.equals(mName)) {
            l.debug("methName:" + methName + ":" + mName);
            arglist[0] = value;
            try {
                if (methods[i].getParameterTypes()[0].isArray()) {
                    methods[i].invoke(this, (Object) arglist);
                }
                //l.debug("qname: " + getQname());
            } catch (InvocationTargetException e) {
                throw new YADARequestException(e.getMessage(), e);
            } catch (IllegalAccessException e) {
                throw new YADARequestException(e.getMessage(), e);
            }
        }
    }
}

From source file:org.apache.axis2.rpc.receivers.RPCMessageReceiver.java

/**
 * reflect and get the Java method - for each i'th param in the java method - get the first
 * child's i'th child -if the elem has an xsi:type attr then find the deserializer for it - if
 * not found, lookup deser for th i'th param (java type) - error if not found - deserialize &
 * save in an object array - end for/*w  ww.  jav  a 2 s.  c o m*/
 * <p/>
 * - invoke method and get the return value
 * <p/>
 * - look up serializer for return value based on the value and type
 * <p/>
 * - create response msg and add return value as grand child of <soap:body>
 *
 * @param inMessage incoming MessageContext
 * @param outMessage outgoing MessageContext
 * @throws AxisFault
 */

public void invokeBusinessLogic(MessageContext inMessage, MessageContext outMessage) throws AxisFault {
    Method method = null;
    try {
        // get the implementation class for the Web Service
        Object obj = getTheImplementationObject(inMessage);

        Class implClass = obj.getClass();

        AxisOperation op = inMessage.getOperationContext().getAxisOperation();
        method = (Method) (op.getParameterValue("myMethod"));
        // If the declaring class has changed, then the cached method is invalid, so we need to
        // reload it. This is to fix AXIS2-3947.
        if (method != null && method.getDeclaringClass() != implClass) {
            method = null;
        }
        AxisService service = inMessage.getAxisService();
        OMElement methodElement = inMessage.getEnvelope().getBody().getFirstElement();
        AxisMessage inAxisMessage = op.getMessage(WSDLConstants.MESSAGE_LABEL_IN_VALUE);
        String messageNameSpace = null;

        if (method == null) {
            String methodName = op.getName().getLocalPart();
            Method[] methods = implClass.getMethods();

            for (Method method1 : methods) {
                if (method1.isBridge()) {
                    continue;
                }
                if (method1.getName().equals(methodName)) {
                    method = method1;
                    op.addParameter("myMethod", method);
                    break;
                }
            }
            if (method == null) {
                throw new AxisFault("No such method '" + methodName + "' in class " + implClass.getName());
            }
        }
        Object resObject = null;
        if (inAxisMessage != null) {
            resObject = RPCUtil.invokeServiceClass(inAxisMessage, method, obj, messageNameSpace, methodElement,
                    inMessage);
        }

        SOAPFactory fac = getSOAPFactory(inMessage);

        // Handling the response
        AxisMessage outaxisMessage = op.getMessage(WSDLConstants.MESSAGE_LABEL_OUT_VALUE);
        if (outaxisMessage != null && outaxisMessage.getElementQName() != null) {
            messageNameSpace = outaxisMessage.getElementQName().getNamespaceURI();
        } else {
            messageNameSpace = service.getTargetNamespace();
        }

        OMNamespace ns = fac.createOMNamespace(messageNameSpace, service.getSchemaTargetNamespacePrefix());
        SOAPEnvelope envelope = fac.getDefaultEnvelope();
        OMElement bodyContent = null;

        if (WSDL2Constants.MEP_URI_ROBUST_IN_ONLY.equals(op.getMessageExchangePattern())) {
            OMElement bodyChild = fac.createOMElement(outMessage.getAxisMessage().getName(), ns);
            envelope.getBody().addChild(bodyChild);
            outMessage.setEnvelope(envelope);
            return;
        }
        Parameter generateBare = service.getParameter(Java2WSDLConstants.DOC_LIT_BARE_PARAMETER);
        if (generateBare != null && "true".equals(generateBare.getValue())) {
            RPCUtil.processResonseAsDocLitBare(resObject, service, envelope, fac, ns, bodyContent, outMessage);
        } else {
            RPCUtil.processResponseAsDocLitWrapped(resObject, service, method, envelope, fac, ns, bodyContent,
                    outMessage);
        }
        outMessage.setEnvelope(envelope);
    } catch (InvocationTargetException e) {
        String msg = null;
        Throwable cause = e.getCause();
        if (cause != null) {
            msg = cause.getMessage();
        }
        if (msg == null) {
            msg = "Exception occurred while trying to invoke service method "
                    + (method != null ? method.getName() : "null");
        }
        if (cause instanceof AxisFault) {
            log.debug(msg, cause);
            throw (AxisFault) cause;
        }

        Class[] exceptionTypes = method.getExceptionTypes();
        for (Class exceptionType : exceptionTypes) {
            if (exceptionType.getName().equals(cause.getClass().getName())) {
                // this is an bussiness logic exception so handle it properly
                String partQName = inMessage.getAxisService().getName() + getSimpleClassName(exceptionType);
                TypeTable typeTable = inMessage.getAxisService().getTypeTable();
                QName elementQName = typeTable.getQNamefortheType(partQName);
                SOAPFactory fac = getSOAPFactory(inMessage);
                OMElement exceptionElement = fac.createOMElement(elementQName);

                if (exceptionType.getName().equals(Exception.class.getName())) {
                    // this is an exception class. so create a element by hand and add the message
                    OMElement innterExceptionElement = fac.createOMElement(elementQName);
                    OMElement messageElement = fac.createOMElement("Message",
                            inMessage.getAxisService().getTargetNamespace(), null);
                    messageElement.setText(cause.getMessage());

                    innterExceptionElement.addChild(messageElement);
                    exceptionElement.addChild(innterExceptionElement);
                } else {
                    // if it is a normal bussiness exception we need to generate the schema assuming it is a pojo
                    QName innerElementQName = new QName(elementQName.getNamespaceURI(),
                            getSimpleClassName(exceptionType));
                    XMLStreamReader xr = BeanUtil.getPullParser(cause, innerElementQName, typeTable, true,
                            false);
                    StAXOMBuilder stAXOMBuilder = new StAXOMBuilder(OMAbstractFactory.getOMFactory(),
                            new StreamWrapper(xr));
                    OMElement documentElement = stAXOMBuilder.getDocumentElement();
                    exceptionElement.addChild(documentElement);
                }

                AxisFault axisFault = new AxisFault(cause.getMessage());
                axisFault.setDetail(exceptionElement);
                throw axisFault;
            }
        }

        log.error(msg, e);
        throw new AxisFault(msg, e);
    } catch (RuntimeException e) {
        log.error(e.getMessage(), e);
        throw AxisFault.makeFault(e);
    } catch (Exception e) {
        String msg = "Exception occurred while trying to invoke service method "
                + (method != null ? method.getName() : "null");
        log.error(msg, e);
        throw AxisFault.makeFault(e);
    }
}

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 {/* www  .  j  av a2s. com*/
        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;
}

From source file:processing.core.PApplet.java

/**
 * Create an offscreen PGraphics object for drawing. This can be used for
 * bitmap or vector images drawing or rendering.
 * <UL>/*from  w ww . j  a  v  a  2  s .  c om*/
 * <LI>Do not use "new PGraphicsXxxx()", use this method. This method
 * ensures that internal variables are set up properly that tie the new
 * graphics context back to its parent PApplet.
 * <LI>The basic way to create bitmap images is to use the <A
 * HREF="http://processing.org/reference/saveFrame_.html">saveFrame()</A>
 * function.
 * <LI>If you want to create a really large scene and write that, first make
 * sure that you've allocated a lot of memory in the Preferences.
 * <LI>If you want to create images that are larger than the screen, you
 * should create your own PGraphics object, draw to that, and use <A
 * HREF="http://processing.org/reference/save_.html">save()</A>. For now,
 * it's best to use <A HREF=
 * "http://dev.processing.org/reference/everything/javadoc/processing/core/PGraphics3D.html"
 * >P3D</A> in this scenario. P2D is currently disabled, and the JAVA2D
 * default will give mixed results. An example of using P3D:
 * 
 * <PRE>
 * 
 * PGraphics big;
 * 
 * void setup() {
 *    big = createGraphics(3000, 3000, P3D);
 * 
 *    big.beginDraw();
 *    big.background(128);
 *    big.line(20, 1800, 1800, 900);
 *    // etc..
 *    big.endDraw();
 * 
 *    // make sure the file is written to the sketch folder
 *    big.save(&quot;big.tif&quot;);
 * }
 * 
 * </PRE>
 * 
 * <LI>It's important to always wrap drawing to createGraphics() with
 * beginDraw() and endDraw() (beginFrame() and endFrame() prior to revision
 * 0115). The reason is that the renderer needs to know when drawing has
 * stopped, so that it can update itself internally. This also handles
 * calling the defaults() method, for people familiar with that.
 * <LI>It's not possible to use createGraphics() with the OPENGL renderer,
 * because it doesn't allow offscreen use.
 * <LI>With Processing 0115 and later, it's possible to write images in
 * formats other than the default .tga and .tiff. The exact formats and
 * background information can be found in the developer's reference for <A
 * HREF=
 * "http://dev.processing.org/reference/core/javadoc/processing/core/PImage.html#save(java.lang.String)"
 * >PImage.save()</A>.
 * </UL>
 */
public PGraphics createGraphics(int iwidth, int iheight, String irenderer) {
    PGraphics pg = null;
    if (irenderer.equals(JAVA2D)) {
        pg = new PGraphicsAndroid2D();
    } else if (irenderer.equals(P2D)) {
        pg = new PGraphics2D();
    } else if (irenderer.equals(P3D)) {
        pg = new PGraphics3D();
    } else {
        Class<?> rendererClass = null;
        Constructor<?> constructor = null;
        try {
            // The context class loader doesn't work:
            // rendererClass =
            // Thread.currentThread().getContextClassLoader().loadClass(irenderer);
            // even though it should, according to this discussion:
            // http://code.google.com/p/android/issues/detail?id=11101
            // While the method that is not supposed to work, using the
            // class loader, does:
            rendererClass = this.getClass().getClassLoader().loadClass(irenderer);
        } catch (ClassNotFoundException cnfe) {
            throw new RuntimeException("Missing renderer class");
        }

        if (rendererClass != null) {
            try {
                constructor = rendererClass.getConstructor(new Class[] {});
            } catch (NoSuchMethodException nsme) {
                throw new RuntimeException("Missing renderer constructor");
            }

            if (constructor != null) {
                try {
                    pg = (PGraphics) constructor.newInstance();
                } catch (InvocationTargetException e) {
                    e.printStackTrace();
                    throw new RuntimeException(e.getMessage());
                } catch (IllegalAccessException e) {
                    e.printStackTrace();
                    throw new RuntimeException(e.getMessage());
                } catch (InstantiationException e) {
                    e.printStackTrace();
                    throw new RuntimeException(e.getMessage());
                } catch (IllegalArgumentException e) {
                    e.printStackTrace();
                } catch (java.lang.InstantiationException e) {
                    e.printStackTrace();
                }
            }
        }
    }

    pg.setParent(this);
    pg.setPrimary(false);
    pg.setSize(iwidth, iheight);

    return pg;
}