Example usage for java.lang.reflect InvocationTargetException printStackTrace

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

Introduction

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

Prototype

public void printStackTrace() 

Source Link

Document

Prints this throwable and its backtrace to the standard error stream.

Usage

From source file:com.wcs.base.util.StringUtils.java

public static String toString(Object obj) {
    if (obj == null)
        return null;
    Class objClass = obj.getClass();
    if (objClass.getName().startsWith("java.lang"))
        return obj.toString();

    Method[] methods = null;/*from   ww  w  . j a  v  a 2s .co m*/
    Field[] fields = objClass.getDeclaredFields();
    StringBuffer result = new StringBuffer();
    if (isSubClassOf(objClass, "Collection")) {
        result.append(processIterator(((Collection) obj).iterator(), objClass));
    } else if (isSubClassOf(objClass, "Map")) {
        result.append(processMap((Map) obj, objClass));
    } else if (isSubClassOf(objClass, "Iterator")) {
        result.append(processIterator((Iterator) obj, objClass));
    } else if (isSubClassOf(objClass, "Enumeration")) {
        result.append(processEnumeration((Enumeration) obj, objClass));
    } else {
        if (!(objClass.getName().startsWith("java")) && fields.length > 0) {
            result.append(obj.getClass().getName()).append(":[");
            for (int i = 0; i < fields.length; i++) {
                result.append(fields[i].getName()).append(":");
                if (fields[i].isAccessible()) {
                    try {
                        result.append(toString(fields[i].get(obj)));
                    } catch (IllegalAccessException iae) {
                        iae.printStackTrace();
                    }
                } else {
                    if (methods == null) {
                        methods = objClass.getMethods();
                    }
                    for (int j = 0; j < methods.length; j++) {
                        if (methods[j].getName().equalsIgnoreCase("get" + fields[i].getName())) {
                            try {
                                result.append(toString(methods[j].invoke(obj, (Object[]) null)));
                            } catch (IllegalAccessException iae) {
                                iae.printStackTrace();
                            } catch (InvocationTargetException ite) {
                                ite.printStackTrace();
                            }
                        }
                    }
                }
                result.append("; ");
            }
            result.append(']');
        } else {
            result.append(obj);
            return result.toString();
        }
    }
    return result.toString();
}

From source file:org.eclipse.virgo.ide.ui.wizards.NewBundleProjectWizard.java

private void writeBundleData(final IJavaProject project, final String platformModule,
        final Map<String, String> properties) {
    WorkspaceModifyOperation oper = new WorkspaceModifyOperation() {
        @Override/*  ww w. ja v a2s.  co  m*/
        protected void execute(IProgressMonitor monitor)
                throws CoreException, InvocationTargetException, InterruptedException {
            BundleManifestUtils.createNewBundleManifest(project, bundleData.getId(), bundleData.getVersion(),
                    bundleData.getProvider(), bundleData.getName(), platformModule, properties);
            project.getProject().refreshLocal(IResource.DEPTH_INFINITE, monitor);
        }
    };

    try {
        getContainer().run(true, true, oper);
    } catch (InvocationTargetException e) {
        e.printStackTrace();
    } catch (InterruptedException e) {
        e.printStackTrace();
    }
}

From source file:org.eclipse.virgo.ide.ui.wizards.NewParProjectWizard.java

private void writeBundleData(final IProject project) {
    WorkspaceModifyOperation oper = new WorkspaceModifyOperation() {
        @Override//from  w w  w  .j  av  a2s  .c om
        protected void execute(IProgressMonitor monitor)
                throws CoreException, InvocationTargetException, InterruptedException {
            BundleManifestUtils.createNewParManifest(project, bundleData.getId(), bundleData.getVersion(),
                    bundleData.getName(), bundleData.getProvider());
            project.refreshLocal(IResource.DEPTH_INFINITE, monitor);
        }
    };

    try {
        getContainer().run(true, true, oper);
    } catch (InvocationTargetException e) {
        // TODO Auto-generated catch block
        e.printStackTrace();
    } catch (InterruptedException e) {
        // TODO Auto-generated catch block
        e.printStackTrace();
    }
}

From source file:sawtooth.examples.jvmsc.JvmScHandler.java

/**
 * the method that runs the bytecode stored in the set.
 *//*from   w w  w. ja  v  a  2s .c  o  m*/

public void run(String byteAddr, String method, List<String> parameters, State state)
        throws InvalidTransactionException, InternalError {
    try {
        Map<String, ByteString> getResponse = new HashMap<String, ByteString>();

        // Check if bytecode has already been stored in the handler else get
        if (!cachedBytecode.containsKey(byteAddr)) {
            ArrayList<String> byteAddress = new ArrayList<String>();
            byteAddress.add(byteAddr);
            getResponse = state.get(byteAddress);
            cachedBytecode.put(byteAddr, getResponse.get(byteAddr));
        }

        // Get bytecode and method list
        JVMEntry bytecodeEntry = JVMEntry.parseFrom(cachedBytecode.get(byteAddr));
        List<String> methods = bytecodeEntry.getMethodsList(); //check type of
        ByteString bytecode = bytecodeEntry.getBytecode();

        // Check that given method is a valid option in the method list
        if (!methods.contains(method)) {
            throw new InvalidTransactionException("Tried to access invalid Method: " + method);
        }

        //Need to retrive parameters from context_id
        //Need to break apart the parameters thinking they will look like the following
        //["name,value","&name,value"]
        List<byte[]> args = new ArrayList<byte[]>();
        String[] temp;
        for (int i = 0; i < parameters.size(); i++) {
            temp = parameters.get(i).split(",");
            if (temp[0].substring(0, 1).equals("&")) {
                ArrayList<String> address = new ArrayList<String>();
                address.add(temp[1]);
                getResponse = state.get(address);
                byte[] output = getResponse.get(temp[1]).toByteArray();
                if (output.length > 0) {
                    HashMap updateMap = this.mapper.readValue(getResponse.get(temp[1]).toByteArray(),
                            HashMap.class);
                    output = dataToByteArray(updateMap);
                    args.add(output);
                } else {
                    args.add("Not found".getBytes());
                }
            } else {
                args.add(temp[1].getBytes());
            }

        }

        //Load bytecode
        JvmClassLoader loader = new JvmClassLoader();
        Class loaded = loader.loadClassFromBytes(null, bytecode.toByteArray());

        //run bytecode method with the parameters, returns Map<string addr, byte[] value>
        Object classObject = loaded.newInstance();
        Method toInvoke = loaded.getMethod(method, ArrayList.class);
        Map<String, byte[]> output = new HashMap<String, byte[]>();
        try {
            output = (Map<String, byte[]>) toInvoke.invoke(classObject, new Object[] { args });
        } catch (InvocationTargetException ioe) {
            ioe.printStackTrace();
            throw new InvalidTransactionException("Something went wrong when invoking the method.");
        }

        // need to change Map<String, byte[]> to Map<String, ByteString>
        Map<String, ByteString> convertedOutput = new HashMap<String, ByteString>();
        String[] keys = output.keySet().toArray(new String[0]);

        for (int i = 0; i < keys.length; i++) {
            Object toCbor = dataFromByteArray(output.get(keys[i]));
            convertedOutput.put(keys[i], ByteString.copyFrom(this.mapper.writeValueAsBytes(toCbor)));
        }

        //update context --set [{addr, value}, ....]
        Collection<Map.Entry<String, ByteString>> entries = convertedOutput.entrySet();
        Collection<String> setResponse = state.set(entries);

        // Check the response
        if (setResponse.size() != entries.size()) {
            throw new InvalidTransactionException("Not all Updates were set correctly");
        }
    } catch (InvalidProtocolBufferException ioe) {
        ioe.printStackTrace();
    } catch (InstantiationException ioe) {
        ioe.printStackTrace();
    } catch (IllegalAccessException ioe) {
        ioe.printStackTrace();
    } catch (NoSuchMethodException ioe) {
        ioe.printStackTrace();
    } catch (com.fasterxml.jackson.core.JsonProcessingException ioe) {
        ioe.printStackTrace();
    } catch (ClassNotFoundException ioe) {
        ioe.printStackTrace();
    } catch (IOException ioe) {
        ioe.printStackTrace();
    }

}

From source file:edu.ku.brc.af.ui.forms.DataSetterForObj.java

public void setFieldValue(Object dataObj, String fieldName, Object data) {
    //log.debug("fieldName["+fieldName+"] dataObj["+dataObj+"] data ["+data+"]");
    try {/*from   w w  w.java 2s.co  m*/
        PropertyDescriptor descr = PropertyUtils.getPropertyDescriptor(dataObj, fieldName.trim());
        if (descr != null) {
            // Check to see if the class of the data we have is different than the one we are trying to set into
            // This typically happens when we have a TextField with a number and it needs to be converted from a 
            // String representation of the number to the actually numeric type like from String to Integer or Short
            Object dataVal = data;
            Class<?> fieldClass = descr.getPropertyType();
            if (data != null) {

                if (dataVal.getClass() != fieldClass && !fieldClass.isAssignableFrom(dataVal.getClass())) {
                    dataVal = UIHelper.convertDataFromString(dataVal.toString(), fieldClass);
                }
            } /*else // Data is Null
              {
              if (fieldClass.isAssignableFrom(Collection.class) || fieldClass.isAssignableFrom(Set.class))
              {
                  return;
              }
              }*/
            if (dataVal instanceof String && ((String) dataVal).isEmpty()) {
                dataVal = null;
            }
            Method setter = PropertyUtils.getWriteMethod(descr);
            if (setter != null && dataObj != null) {
                args[0] = dataVal;
                //log.debug("fieldname["+fieldName+"] dataObj["+dataObj+"] data ["+dataVal+"] ("+(dataVal != null ? dataVal.getClass().getSimpleName() : "")+")");
                setter.invoke(dataObj, dataVal);
            } else {
                log.error("dataObj was null - Trouble setting value field named["
                        + (fieldName != null ? fieldName.trim() : "null") + "] in data object ["
                        + (dataObj != null ? dataObj.getClass().toString() : "null") + "]");
            }
        } else {
            log.error("We could not find a field named[" + fieldName.trim() + "] in data object ["
                    + dataObj.getClass().toString() + "]");
        }
    } catch (java.lang.reflect.InvocationTargetException ex) {
        log.error("Trouble setting value field named[" + (fieldName != null ? fieldName.trim() : "null")
                + "] in data object [" + (dataObj != null ? dataObj.getClass().toString() : "null") + "]");
        log.error(ex);
        ex.printStackTrace();
        edu.ku.brc.af.core.UsageTracker.incrHandledUsageCount();
        edu.ku.brc.exceptions.ExceptionTracker.getInstance().capture(DataSetterForObj.class, ex);

    } catch (Exception ex) {
        log.error("Trouble setting value field named[" + (fieldName != null ? fieldName.trim() : "null")
                + "] in data object [" + (dataObj != null ? dataObj.getClass().toString() : "null") + "]");
        log.error(ex);
        ex.printStackTrace();
        edu.ku.brc.af.core.UsageTracker.incrHandledUsageCount();
        edu.ku.brc.exceptions.ExceptionTracker.getInstance().capture(DataSetterForObj.class, ex);
    }
}

From source file:org.openhie.openempi.loader.configuration.ConfigurableFileLoader.java

private void processField(String fieldName, String stringValue, String formatString, Class personClass,
        Object personInstance) {// ww  w .  j av a 2  s  .  c om
    if (fieldName.length() == 0)
        return;

    if (personClass == Person.class && fieldName.equals("idSequence")) {
        idSeq = stringValue;
        return;
    }

    String setMethodName = ConvertUtil.getSetMethodName(fieldName);
    Class[] paramTypes = new Class[1];

    Field field = null;
    try {
        field = personClass.getDeclaredField(fieldName);
    } catch (SecurityException e1) {
        e1.printStackTrace();
    } catch (NoSuchFieldException e1) {
        e1.printStackTrace();
    }

    Object value = null;
    Date dateValue = null;
    Race raceValue = null;
    Gender genderValue = null;
    Class paramClass = field.getType();
    if (paramClass == String.class) {
        value = stringValue;
    } else if (paramClass == Date.class) {
        SimpleDateFormat format = new SimpleDateFormat(formatString);
        try {
            dateValue = format.parse(stringValue);
        } catch (ParseException e) {
            e.printStackTrace();
        }
        value = dateValue;
    } else if (paramClass == Race.class) {
        raceValue = findRaceByName(stringValue);
        value = raceValue;
    } else if (paramClass == Gender.class) {
        genderValue = findGenderByCode(stringValue);
        value = genderValue;
    }

    if (value == null)
        return;
    paramTypes[0] = paramClass;
    Method setMethod = null;
    try {
        setMethod = personClass.getDeclaredMethod(setMethodName, paramTypes);
        Object[] params = new Object[1];
        params[0] = value;
        try {
            setMethod.invoke(personInstance, params);
        } catch (IllegalArgumentException e1) {
            e1.printStackTrace();
        } catch (IllegalAccessException e2) {
            e2.printStackTrace();
        } catch (InvocationTargetException e3) {
            e3.printStackTrace();
        }
    } catch (NoSuchMethodException e) {
        e.printStackTrace();
    }
}

From source file:com.chiorichan.account.AccountsKeeper.java

public Account accountConstruct(AccountLookupAdapter adapter, String userId, Object... params)
        throws LoginException {
    List<Class<?>> paramsClass = Lists.newLinkedList();

    for (Object o : params)
        paramsClass.add(o.getClass());//from ww w .ja  v  a 2s  .c o  m

    try {
        Constructor<? extends Account> constructor = adapter.getAccountClass()
                .getConstructor(paramsClass.toArray(new Class<?>[0]));
        return constructor.newInstance(params);
    } catch (InvocationTargetException e) {
        throw (LoginException) e.getTargetException();
    } catch (NoSuchMethodException | InstantiationException | IllegalAccessException
            | IllegalArgumentException e) {
        e.printStackTrace();
        AccountManager.getLogger().severe("We had a problem constructing a new instance of '"
                + adapter.getAccountClass().getCanonicalName()
                + "' account class. We are not sure of the reason but this is most likely a SEVERE error. For the time being, we constructed a MemoryAccount but this is only temporary and logins will fail.");
        return new MemoryAccount(userId, AccountLookupAdapter.MEMORY_ADAPTER);
    }
}

From source file:org.apache.tomcat.util.mx.DynamicMBeanProxy.java

public Object getAttribute(String attribute)
        throws AttributeNotFoundException, MBeanException, ReflectionException {
    if (methods == null)
        init();/*from  w w w  . java  2  s  .c o  m*/
    Method m = (Method) getAttMap.get(attribute);
    if (m == null)
        throw new AttributeNotFoundException(attribute);

    try {
        if (log.isDebugEnabled())
            log.debug(real.getClass().getName() + " getAttribute " + attribute);
        return m.invoke(real, NO_ARGS_PARAM);
    } catch (IllegalAccessException ex) {
        ex.printStackTrace();
        throw new MBeanException(ex);
    } catch (InvocationTargetException ex1) {
        ex1.printStackTrace();
        throw new MBeanException(ex1);
    }
}

From source file:org.apache.tomcat.util.mx.DynamicMBeanProxy.java

public void setAttribute(Attribute attribute)
        throws AttributeNotFoundException, InvalidAttributeValueException, MBeanException, ReflectionException {
    if (methods == null)
        init();//  w  w  w  .  j  av a2s.c  o  m
    // XXX Send notification !!!
    Method m = (Method) setAttMap.get(attribute.getName());
    if (m == null)
        throw new AttributeNotFoundException(attribute.getName());

    try {
        log.info(real.getClass().getName() + "setAttribute " + attribute.getName());
        m.invoke(real, new Object[] { attribute.getValue() });
    } catch (IllegalAccessException ex) {
        ex.printStackTrace();
        throw new MBeanException(ex);
    } catch (InvocationTargetException ex1) {
        ex1.printStackTrace();
        throw new MBeanException(ex1);
    }
}

From source file:com.jaspersoft.studio.server.wizard.find.FindResourcePage.java

private void search() {
    if (SystemUtils.IS_OS_WINDOWS)
        new Thread(new Runnable() {
            public void run() {
                try {
                    WSClientHelper.findResources(new NullProgressMonitor(), finderUI);
                } catch (Exception e) {
                    e.printStackTrace();
                }//from w  w  w.  java2 s  . c o  m
            }
        }).start();
    else
        try {
            getContainer().run(true, true, new IRunnableWithProgress() {

                @Override
                public void run(IProgressMonitor monitor)
                        throws InvocationTargetException, InterruptedException {
                    monitor.beginTask(Messages.FindResourcePage_19, IProgressMonitor.UNKNOWN);
                    try {
                        WSClientHelper.findResources(monitor, finderUI);
                    } catch (Exception e) {
                        e.printStackTrace();
                    } finally {
                        monitor.done();
                    }
                }
            });
        } catch (InvocationTargetException e1) {
            e1.printStackTrace();
        } catch (InterruptedException e1) {
            e1.printStackTrace();
        }
}