Example usage for java.lang.reflect InvocationTargetException getTargetException

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

Introduction

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

Prototype

public Throwable getTargetException() 

Source Link

Document

Get the thrown target exception.

Usage

From source file:net.sf.ehcache.config.BeanHandler.java

/**
 * Attaches a child element to its parent.
 *//*from  w  w  w .j  a va2  s . co m*/
private void addChild(final Object parent, final Object child, final String name) throws SAXException {
    try {
        // Look for an add<name> method on the parent
        final Method method = findSetMethod(parent.getClass(), "add", name);
        if (method != null) {
            method.invoke(parent, new Object[] { child });
        }
    } catch (final InvocationTargetException e) {
        final SAXException exc = new SAXException(getLocation() + ": Could not finish element <" + name + ">."
                + " Message was: " + e.getTargetException());
        throw exc;
    } catch (final Exception e) {
        throw new SAXException(getLocation() + ": Could not finish element <" + name + ">.");
    }
}

From source file:net.sf.ehcache.config.BeanHandler.java

/**
 * Sets an attribute./*  w  ww  . j  a  v  a  2s  .  co  m*/
 */
private void setAttribute(final ElementInfo element, final String attrName, final String attrValue)
        throws SAXException {
    try {
        // Look for a set<name> method
        final Class objClass = element.bean.getClass();
        final Method method = findSetMethod(objClass, "set", attrName);
        if (method != null) {
            final Object realValue = convert(method.getParameterTypes()[0], attrValue);
            method.invoke(element.bean, new Object[] { realValue });
            return;
        } else {
            //allow references to an XML schema but do not use it
            if (element.elementName.equals("ehcache")) {
                if (LOG.isDebugEnabled()) {
                    LOG.debug("Ignoring ehcache attribute " + attrName);
                }
                return;
            }
        }
    } catch (final InvocationTargetException e) {
        throw new SAXException(getLocation() + ": Could not set attribute \"" + attrName + "\"."
                + ". Message was: " + e.getTargetException());
    } catch (final Exception e) {
        throw new SAXException(getLocation() + ": Could not set attribute \"" + attrName + "\".");
    }

    throw new SAXException(getLocation() + ": Element <" + element.elementName + "> does not allow attribute \""
            + attrName + "\".");
}

From source file:com.sun.faces.el.impl.FunctionInvocation.java

/**
 * Evaluates by looking up the name in the VariableResolver
 *///from   w w  w.  j ava2  s .  co m
public Object evaluate(ExpressionInfo exprInfo) throws ElException {
    FunctionMapper functions = exprInfo.getFunctionMapper();
    // if the Map is null, then the function is invalid
    if (functions == null) {
        if (log.isErrorEnabled()) {
            String message = MessageUtil.getMessageWithArgs(Constants.UNKNOWN_FUNCTION, functionName);
            log.error(message);
            throw new ElException(message);
        }
    }

    // normalize function name
    String prefix = null;
    String localName = null;
    int index = functionName.indexOf(':');
    if (index == -1) {
        prefix = "";
        localName = functionName;
    } else {
        prefix = functionName.substring(0, index);
        localName = functionName.substring(index + 1);
    }

    // ensure that the function's name is mapped
    Method target = (Method) functions.resolve(prefix, localName);
    if (target == null) {
        if (log.isErrorEnabled()) {
            String message = MessageUtil.getMessageWithArgs(Constants.UNKNOWN_FUNCTION, functionName);
            log.error(message);
            throw new ElException(message);
        }
    }

    // ensure that the number of arguments matches the number of parameters
    Class[] params = target.getParameterTypes();
    if (params.length != argumentList.size()) {
        if (log.isErrorEnabled()) {
            String message = MessageUtil.getMessageWithArgs(Constants.INAPPROPRIATE_FUNCTION_ARG_COUNT,
                    functionName, new Integer(params.length), new Integer(argumentList.size()));
            log.error(message);
            throw new ElException(message);
        }
    }

    // now, walk through each parameter, evaluating and casting its argument
    Object[] arguments = new Object[argumentList.size()];
    for (int i = 0; i < params.length; i++) {
        // evaluate
        arguments[i] = ((Expression) argumentList.get(i)).evaluate(exprInfo);
        // coerce
        arguments[i] = Coercions.coerce(arguments[i], params[i]);
    }

    // finally, invoke the target method, which we know to be static
    try {
        return (target.invoke(null, arguments));
    } catch (InvocationTargetException ex) {
        if (log.isErrorEnabled()) {
            String message = MessageUtil.getMessageWithArgs(Constants.FUNCTION_INVOCATION_ERROR, functionName);
            Throwable t = ex.getTargetException();
            log.error(message, t);
            throw new ElException(message, t);
        }
        return null;
    } catch (Throwable t) {
        if (log.isErrorEnabled()) {
            String message = MessageUtil.getMessageWithArgs(Constants.FUNCTION_INVOCATION_ERROR, functionName);
            log.error(message, t);
            throw new ElException(message, t);
        }
        return null;
    }
}

From source file:com.runwaysdk.controller.ServletDispatcher.java

private void handleInvocationTargetException(InvocationTargetException e) throws IOException {
    Throwable target = e.getTargetException();

    ErrorUtility.prepareThrowable(target, this.req, this.resp, this.isAsynchronous, true);
}

From source file:com.taobao.common.tedis.group.ReliableAsynTedisGroup.java

public void init() {
    if (!inited) {
        try {//ww  w  .jav  a  2 s .  co m
            if (this.cm == null) {
                this.cm = new DiamondConfigManager(appName, version);
            }
            this.ospreyManager = new OspreyManager("tedis-" + appName + "-" + version);
            this.ospreyManager.registerProcessor(new OspreyProcessor<ReliableAsynMessage>() {

                @Override
                public Class<ReliableAsynMessage> interest() {
                    return ReliableAsynMessage.class;
                }

                @Override
                public Result process(ReliableAsynMessage message) {
                    Result result = new Result();
                    long time = System.currentTimeMillis();

                    Single single = cm.getRouter().getAtomic(message.getSingleKey());
                    if (single == null) {
                        result.setSuccess(false);
                        result.setErrorMessage("Current atomic is null");
                        return result;
                    }

                    try {
                        message.getMethod().invoke(single.getTedis(), message.getArgs());
                    } catch (Throwable t) {
                        logger.warn("write exception:" + single.getProperties(), t);
                        try {
                            statLog(message.getMethod().getName(), false, time);
                            // 
                            InvocationTargetException ite = (InvocationTargetException) t;
                            UndeclaredThrowableException ute = (UndeclaredThrowableException) ite
                                    .getTargetException();
                            if (ute.getUndeclaredThrowable() instanceof TimeoutException) {
                                result.setSuccess(false);
                                result.setErrorMessage("TimeoutException");
                                result.setRuntimeException(ute);
                                return result;
                            } else {
                                ExecutionException ee = (ExecutionException) ute.getUndeclaredThrowable();
                                InvocationTargetException ite_1 = (InvocationTargetException) ee.getCause();
                                TedisException te = (TedisException) ite_1.getTargetException();
                                if (te.getCause() instanceof TedisConnectionException) {
                                    result.setSuccess(false);
                                    result.setErrorMessage("JedisConnectionException");
                                    result.setRuntimeException(te);
                                    return result;
                                }
                            }
                        } catch (Throwable tt) {
                            logger.warn(":", tt);
                        }
                    }
                    return result;
                }
            });
            this.ospreyManager.init();
            tedis = (RedisCommands) Proxy.newProxyInstance(RedisCommands.class.getClassLoader(),
                    new Class[] { RedisCommands.class }, new TedisGroupInvocationHandler());
        } catch (Exception e) {
            throw new TedisException("init failed", e);
        }
        inited = true;
    }
}

From source file:com.jigsforjava.web.controller.MultiActionController.java

/**
 * Invokes the named method. Uses a custom exception handler if possible;
 * otherwise, throw an unchecked exception; wrap a checked exception or
 * Throwable./* www  .java 2  s  .co m*/
 * 
 * @param handlerMethod The handler method to invoke.
 * @param request The current HTTP request.
 * @param response The current HTTP response.
 * @return The {@link ModelAndView} instance returned by the handler method.
 */
protected ModelAndView invokeHandlerMethod(Method handlerMethod, HttpServletRequest request,
        HttpServletResponse response) throws Exception {
    try {
        ActionContext actionContext = new ActionContext(request, response, handlerMethod);
        preHandlerInvocation(actionContext);
        ViewContext returnValue = (ViewContext) handlerMethod.invoke(getDelegate(), actionContext);
        postHandlerInvocation(actionContext, returnValue);
        ModelAndView mav = null;

        if (returnValue == null) {
            mav = new ModelAndView();
        } else if (HttpServletRequestUtils.isGetMethod(request)) {
            mav = returnValue.asModelAndView();
        } else // POST method
        {
            mav = returnValue.asModelAndUrl();
        }

        return mav;
    } catch (InvocationTargetException ex) {
        // The handler method threw an exception.
        return handleException(request, response, ex.getTargetException());
    } catch (Exception ex) {
        // The binding process threw an exception.
        return handleException(request, response, ex);
    }
}

From source file:com.snaplogic.snaps.uniteller.BaseService.java

@Override
protected void process(Document document, String inputViewName) {
    try {/*from   w  ww. j a v a 2 s .  c  o  m*/
        AccountBean bean = account.connect();
        String UFSConfigFilePath = urlEncoder.validateAndEncodeURI(bean.getConfigFilePath(), PATTERN, null)
                .toString();
        String UFSSecurityFilePath = urlEncoder
                .validateAndEncodeURI(bean.getSecurityPermFilePath(), PATTERN, null).toString();
        /* instantiating USFCreationClient */
        Class<?> CustomUSFCreationClient = Class.forName(UFS_FOLIO_CREATION_CLIENT_PKG_URI);
        Constructor<?> constructor = CustomUSFCreationClient
                .getDeclaredConstructor(new Class[] { IUFSConfigMgr.class, IUFSSecurityMgr.class });
        Object USFCreationClientObj = constructor.newInstance(CustomUFSConfigMgr.getInstance(UFSConfigFilePath),
                CustomUFSSecurityMgr.getInstance(UFSSecurityFilePath));
        Method setAutoUpdatePsw = CustomUSFCreationClient.getDeclaredMethod("setAutoUpdatePsw", Boolean.TYPE);
        setAutoUpdatePsw.invoke(USFCreationClientObj, autoUpdatePsw);
        /* Preparing the request for USF */
        Object data;
        if (document != null && (data = document.get()) != null) {
            if (data instanceof Map) {
                Map<String, Object> map = (Map<String, Object>) data;
                Class<?> UFSRequest = Class.forName(getUFSReqClassType());
                Object UFSRequestObj = UFSRequest.newInstance();
                Object inputFieldValue = null;
                Calendar cal = Calendar.getInstance();
                for (Method method : UFSRequest.getDeclaredMethods()) {
                    if (isSetter(method)
                            && (inputFieldValue = map.get(method.getName().substring(3))) != null) {
                        try {
                            String paramType = method.getParameterTypes()[0].getName();
                            if (paramType.equalsIgnoreCase(String.class.getName())) {
                                method.invoke(UFSRequest.cast(UFSRequestObj), String.valueOf(inputFieldValue));
                            } else if (paramType.equalsIgnoreCase(Double.class.getSimpleName())) {
                                method.invoke(UFSRequest.cast(UFSRequestObj),
                                        Double.parseDouble(String.valueOf(inputFieldValue)));
                            } else if (paramType.equalsIgnoreCase(INT)) {
                                method.invoke(UFSRequest.cast(UFSRequestObj),
                                        Integer.parseInt(String.valueOf(inputFieldValue)));
                            } else if (paramType.equalsIgnoreCase(Calendar.class.getName())) {
                                try {
                                    cal.setTime(sdtf.parse(String.valueOf(inputFieldValue)));
                                } catch (ParseException pe1) {
                                    try {
                                        cal.setTime(sdf.parse(String.valueOf(inputFieldValue)));
                                    } catch (ParseException pe) {
                                        writeToErrorView(
                                                String.format(DATE_PARSER_ERROR, DATETIME_FORMAT, DATE_FORMAT),
                                                pe.getMessage(), ERROR_RESOLUTION, pe);
                                    }
                                }
                                method.invoke(UFSRequest.cast(UFSRequestObj), cal);
                            }
                        } catch (IllegalArgumentException iae) {
                            writeToErrorView(String.format(ILLEGAL_ARGS_EXE, method.getName()),
                                    iae.getMessage(), ERROR_RESOLUTION, iae);
                        } catch (InvocationTargetException ite) {
                            writeToErrorView(ite.getTargetException().getMessage(), ite.getMessage(),
                                    ERROR_RESOLUTION, ite);
                        }
                    }
                }
                /* Invoking the request over USFCreationClient */
                Object UFSResponseObj = null;
                Method creationClientMethod = CustomUSFCreationClient
                        .getMethod(getCamelCaseForMethod(resourceType), UFSRequest);
                try {
                    UFSResponseObj = creationClientMethod.invoke(USFCreationClientObj,
                            UFSRequest.cast(UFSRequestObj));
                } catch (IllegalArgumentException iae) {
                    writeToErrorView(String.format(ILLEGAL_ARGS_EXE, creationClientMethod.getName()),
                            iae.getMessage(), ERROR_RESOLUTION, iae);
                } catch (InvocationTargetException ite) {
                    writeToErrorView(ite.getTargetException().getMessage(), ite.getMessage(), ERROR_RESOLUTION,
                            ite);
                }
                if (null != UFSResponseObj) {
                    outputViews.write(documentUtility.newDocument(processResponseObj(UFSResponseObj)));
                    counter.inc();
                }
            } else {
                writeToErrorView(NO_DATA_ERRMSG, NO_DATA_WARNING, NO_DATA_REASON, NO_DATA_RESOLUTION);
            }
        }
    } catch (Exception ex) {
        writeToErrorView(ERRORMSG, ex.getMessage(), ERROR_RESOLUTION, ex);
    }
}

From source file:de.xwic.appkit.webbase.table.DefaultColumnLabelProvider.java

/**
 * Read the property value as text from the element.
 * @param element//from  www  . jav  a 2 s .c  om
 * @return
 */
public Object getData(RowData element) {

    try {
        Object value;

        if (element.isArray()) {
            if (isCollection) {
                value = fetchSet(myProperty, element);
            } else {
                value = element.getData(myProperty);
            }
        } else if (element.getEntity() != null) {
            IEntity entity = element.getEntity();
            if (baseClass == null || baseClass != entity.getClass()) {
                // We have not introspected the beans for the propertyPath yet
                buildReadPath(entity);
            }

            value = entity;
            for (int i = 0; i < readMethods.length && value != null; i++) {
                value = readMethods[i].invoke(value, noArgs);
            }
        } else {
            value = element.getObject();
        }
        if (isPicklistEntry && value != null && value instanceof Integer) {
            IPicklisteDAO dao = DAOSystem.getDAO(IPicklisteDAO.class);
            value = dao.getPickListEntryByID((Integer) value);
        }
        return value;
    } catch (InvocationTargetException ite) {
        log.error("Failed to render column", ite);
        if (ite.getTargetException() instanceof SecurityException) {
            return "[N/A]";
        }
        return "ERR: Failed to render column!";
    } catch (Exception e) {
        log.error("Failed to render column", e);
        return "ERR: Failed to render column!";
    }

}

From source file:org.appverse.web.framework.backend.rest.managers.impl.live.RestCachingManagerImpl.java

private Object manageRestCaching(final Builder builder, final WebTarget webTarget, final Method method,
        final GenericType<?> type, final IRestPersistenceService<?> restService, final String key)
        throws Exception {
    //Check if caching logic is enabled in repository 
    //(RestCaching annotations could be present in interface OR implementations)

    RestCaching rc = AnnotationUtils.findAnnotation(restService.getClass(), RestCaching.class);
    if (rc != null && key != null) {
        String cacheName = rc.cacheName();
        Cache cache = cacheManager.getCache(cacheName);

        if (logger.isDebugEnabled())
            logger.debug("Checking path::" + key);

        Element wrap = cache.get(key);

        //Requested data should be in cache
        if (wrap != null) {
            if (logger.isDebugEnabled())
                logger.debug("Entry in cache is not null...checking expiration date..");
            CacheEntry entry = (CacheEntry) wrap.getObjectValue();
            EntityTag etag = entry.getEtag();
            //Data is cached, so we can return it and avoid to call rest service
            if (!entry.hasExpired() && entry.getObject() != null) {
                if (logger.isDebugEnabled())
                    logger.debug("Entry has not expired, so returned from cache");

                return entry.getObject();
            }//from  w  w  w  .j ava 2 s.  c o  m
            //Data is cached, but expired, so remove it
            else if (entry.hasExpired()) {
                if (logger.isDebugEnabled())
                    logger.debug("Entry has expired, do not use it");
            }
            //If we have EntityTag header, send to server to check conditional existence
            if (etag != null && etag.getValue() != null) {
                builder.header("If-None-Match", "\"" + etag.getValue() + "\"");
            }

        }

        if (logger.isDebugEnabled())
            logger.debug("Actual call to service");
        //Invoke rest service

        Object data = null;
        boolean notModified = false;
        try {
            //Paging methods
            if (webTarget != null)
                data = method.invoke(restService, webTarget, builder);
            //Common retrieve and retrieveList methods
            else {

                if (type != null)
                    data = method.invoke(builder, type);
                else
                    data = method.invoke(builder);
            }
        } catch (InvocationTargetException ite) {
            //This could be a NOT_MODIFIED response, produced by server ETAG caching
            //We must check it, and rethrow exception if it's another error
            Throwable target = ite.getTargetException();
            if (target != null && target instanceof RedirectionException) {
                RedirectionException re = (RedirectionException) target;
                if (re.getResponse().getStatus() == Status.NOT_MODIFIED.getStatusCode()) {
                    if (logger.isDebugEnabled())
                        logger.debug("NOT_MODIFIED response");

                    notModified = true;
                }
            }
            if (!notModified)
                throw ite;
        }
        //Jersey RestRequestCachingFilter intercept response from server and analyze headers

        if (logger.isDebugEnabled())
            logger.debug("Checking if we should insert or retrieve data in/from cache");
        wrap = cache.get(key);
        if (wrap != null) {
            CacheEntry entry = (CacheEntry) wrap.getObjectValue();
            //This only happens if response includes cache control headers. 
            //Jersey RestRequestCachingFilter is in charge of preparing this entry.
            if (entry.getObject() == null) {
                if (logger.isDebugEnabled())
                    logger.debug("Insert data in cache");
                entry.setObject(data);
            }
            //In this case, server is not returning data, since object is cached and not has been modified
            else if ((notModified || entry.getStatus() == Status.NOT_MODIFIED.getStatusCode())
                    && entry.getObject() != null) {
                if (logger.isDebugEnabled())
                    logger.debug("Retrieve data from cache");

                return entry.getObject();
            }

        }
        return data;

    }

    //Caching is not enabled

    //Paging methods
    if (webTarget != null)
        return method.invoke(restService, webTarget, builder);
    //Common retrieve and retrieveList methods
    else {
        if (type != null)
            return method.invoke(builder, type);
        else
            return method.invoke(builder);
    }
}

From source file:Browser.java

/**
 * Attempts to locate the default web browser on the local system.  
 * Caches results so it only locates the browser once for each use of this 
 * class per JVM instance.//from   w  ww.j  av  a  2s.com
 *
 * @return The browser for the system.  Note that this may not be what you 
 * would consider to be a standard web browser; instead, it's the 
 * application that gets called to open the default web browser.  In some 
 * cases, this will be a non-String object that provides the means of 
 * calling the default browser.
 */
private static Object locateBrowser() {
    if (browser != null) {
        return browser;
    }
    switch (jvm) {
    case MRJ_2_0:
        try {
            Integer finderCreatorCode = (Integer) makeOSType.invoke(null, new Object[] { FINDER_CREATOR });
            Object aeTarget = aeTargetConstructor.newInstance(new Object[] { finderCreatorCode });
            Integer gurlType = (Integer) makeOSType.invoke(null, new Object[] { GURL_EVENT });
            Object appleEvent = appleEventConstructor.newInstance(
                    new Object[] { gurlType, gurlType, aeTarget, kAutoGenerateReturnID, kAnyTransactionID });

            // Don't set browser = appleEvent because then the next time we call
            // locateBrowser(), we'll get the same AppleEvent, to which we'll 
            // already have added the relevant parameter. Instead, regenerate 
            // the AppleEvent every time. There's probably a way to do this 
            // better; if any has any ideas, please let me know.

            return appleEvent;
        } catch (IllegalAccessException iae) {
            browser = null;
            errorMessage = iae.getMessage();
            return browser;
        } catch (InstantiationException ie) {
            browser = null;
            errorMessage = ie.getMessage();
            return browser;
        } catch (InvocationTargetException ite) {
            browser = null;
            errorMessage = ite.getMessage();
            return browser;
        }

    case MRJ_2_1:
        File systemFolder;
        try {
            systemFolder = (File) findFolder.invoke(null, new Object[] { kSystemFolderType });
        } catch (IllegalArgumentException iare) {
            browser = null;
            errorMessage = iare.getMessage();
            return browser;
        } catch (IllegalAccessException iae) {
            browser = null;
            errorMessage = iae.getMessage();
            return browser;
        } catch (InvocationTargetException ite) {
            browser = null;
            errorMessage = ite.getTargetException().getClass() + ": " + ite.getTargetException().getMessage();
            return browser;
        }

        // Avoid a FilenameFilter because that can't be stopped mid-list
        String[] systemFolderFiles = systemFolder.list();

        for (int i = 0; i < systemFolderFiles.length; i++) {
            try {
                File file = new File(systemFolder, systemFolderFiles[i]);
                if (!file.isFile()) {
                    continue;
                }
                // We're looking for a file with a creator code of 'MACS' and
                // a type of 'FNDR'.  Only requiring the type results in non-Finder
                // applications being picked up on certain Mac OS 9 systems,
                // especially German ones, and sending a GURL event to those
                // applications results in a logout under Multiple Users.
                Object fileType = getFileType.invoke(null, new Object[] { file });
                if (FINDER_TYPE.equals(fileType.toString())) {
                    Object fileCreator = getFileCreator.invoke(null, new Object[] { file });
                    if (FINDER_CREATOR.equals(fileCreator.toString())) {
                        // Actually the Finder, but that's OK
                        browser = file.toString();
                        return browser;
                    }
                }
            } catch (IllegalArgumentException iare) {
                browser = browser;
                errorMessage = iare.getMessage();
                return null;
            } catch (IllegalAccessException iae) {
                browser = null;
                errorMessage = iae.getMessage();
                return browser;
            } catch (InvocationTargetException ite) {
                browser = null;
                errorMessage = ite.getTargetException().getClass() + ": "
                        + ite.getTargetException().getMessage();
                return browser;
            }
        }
        browser = null;
        break;

    case MRJ_3_0:
    case MRJ_3_1:
        browser = ""; // Return something non-null
        break;

    case WINDOWS_NT:
        browser = "cmd.exe";
        break;

    case WINDOWS_9x:
        browser = "command.com";
        break;

    case OTHER:
    default:
        browser = "netscape";
        break;
    }

    return browser;
}