Example usage for java.lang Throwable getClass

List of usage examples for java.lang Throwable getClass

Introduction

In this page you can find the example usage for java.lang Throwable getClass.

Prototype

@HotSpotIntrinsicCandidate
public final native Class<?> getClass();

Source Link

Document

Returns the runtime class of this Object .

Usage

From source file:com.evolveum.midpoint.model.impl.lens.Clockwork.java

public static void throwException(Throwable e) throws ObjectAlreadyExistsException, ObjectNotFoundException {
    if (e instanceof ObjectAlreadyExistsException) {
        throw (ObjectAlreadyExistsException) e;
    } else if (e instanceof ObjectNotFoundException) {
        throw (ObjectNotFoundException) e;
    } else if (e instanceof SystemException) {
        throw (SystemException) e;
    } else {/*from www  . ja va 2  s  .  c  om*/
        throw new SystemException("Unexpected exception " + e.getClass() + " " + e.getMessage(), e);
    }
}

From source file:com.twinsoft.convertigo.beans.core.DatabaseObject.java

public static DatabaseObject read(Node node) throws EngineException {
    String objectClassName = "n/a";
    String childNodeName = "n/a";
    String propertyName = "n/a";
    String propertyValue = "n/a";
    DatabaseObject databaseObject = null;
    Element element = (Element) node;

    objectClassName = element.getAttribute("classname");

    // Migration to 4.x+ projects
    if (objectClassName.equals("com.twinsoft.convertigo.beans.core.ScreenClass")) {
        objectClassName = "com.twinsoft.convertigo.beans.screenclasses.JavelinScreenClass";
    }//  ww w . j a v  a2s.co  m

    String version = element.getAttribute("version");
    if ("".equals(version)) {
        version = node.getOwnerDocument().getDocumentElement().getAttribute("beans");
        if (!"".equals(version)) {
            element.setAttribute("version", version);
        }
    }
    // Verifying product version
    if (VersionUtils.compareProductVersion(Version.productVersion, version) < 0) {
        String message = "Unable to create an object of product version superior to the current beans product version ("
                + com.twinsoft.convertigo.beans.Version.version + ").\n" + "Object class: " + objectClassName
                + "\n" + "Object version: " + version;
        EngineException ee = new EngineException(message);
        throw ee;
    }

    try {
        Engine.logBeans.trace("Creating object of class \"" + objectClassName + "\"");
        databaseObject = (DatabaseObject) Class.forName(objectClassName).newInstance();
    } catch (Exception e) {
        String s = node.getNodeName();// XMLUtils.prettyPrintDOM(node);
        String message = "Unable to create a new instance of the object from the serialized XML data.\n"
                + "Object class: '" + objectClassName + "'\n" + "Object version: " + version + "\n"
                + "XML data:\n" + s;
        EngineException ee = new EngineException(message, e);
        throw ee;
    }

    try {
        // Performs custom configuration before object de-serialization
        databaseObject.preconfigure(element);
    } catch (Exception e) {
        String s = XMLUtils.prettyPrintDOM(node);
        String message = "Unable to configure the object from serialized XML data before its creation.\n"
                + "Object class: '" + objectClassName + "'\n" + "XML data:\n" + s;
        EngineException ee = new EngineException(message, e);
        throw ee;
    }

    try {
        long priority = new Long(element.getAttribute("priority")).longValue();
        databaseObject.priority = priority;

        Class<? extends DatabaseObject> databaseObjectClass = databaseObject.getClass();
        BeanInfo bi = CachedIntrospector.getBeanInfo(databaseObjectClass);
        PropertyDescriptor[] pds = bi.getPropertyDescriptors();

        NodeList childNodes = element.getChildNodes();
        int len = childNodes.getLength();

        PropertyDescriptor pd;
        Object propertyObjectValue;
        Class<?> propertyType;
        NamedNodeMap childAttributes;
        boolean maskValue = false;

        for (int i = 0; i < len; i++) {
            Node childNode = childNodes.item(i);
            if (childNode.getNodeType() != Node.ELEMENT_NODE) {
                continue;
            }

            Element childElement = (Element) childNode;

            childNodeName = childNode.getNodeName();

            Engine.logBeans.trace("Analyzing node '" + childNodeName + "'");

            if (childNodeName.equalsIgnoreCase("property")) {
                childAttributes = childNode.getAttributes();
                propertyName = childAttributes.getNamedItem("name").getNodeValue();
                Engine.logBeans.trace("  name = '" + propertyName + "'");
                pd = findPropertyDescriptor(pds, propertyName);
                if (pd == null) {
                    Engine.logBeans.warn(
                            "Unable to find the definition of property \"" + propertyName + "\"; skipping.");
                    continue;
                }
                propertyType = pd.getPropertyType();
                propertyObjectValue = XMLUtils
                        .readObjectFromXml((Element) XMLUtils.findChildNode(childNode, Node.ELEMENT_NODE));

                // Hides value in log trace if needed
                if ("false".equals(childElement.getAttribute("traceable"))) {
                    maskValue = true;
                }
                Engine.logBeans.trace("  value='"
                        + (maskValue ? Visibility.maskValue(propertyObjectValue) : propertyObjectValue) + "'");

                // Decrypts value if needed
                try {
                    if ("true".equals(childElement.getAttribute("ciphered"))) {
                        propertyObjectValue = decryptPropertyValue(propertyObjectValue);
                    }
                } catch (Exception e) {
                }

                propertyObjectValue = databaseObject.compileProperty(propertyType, propertyName,
                        propertyObjectValue);

                if (Enum.class.isAssignableFrom(propertyType)) {
                    propertyObjectValue = EnumUtils.valueOf(propertyType, propertyObjectValue);
                }

                propertyValue = propertyObjectValue.toString();

                Method setter = pd.getWriteMethod();
                Engine.logBeans.trace("  setter='" + setter.getName() + "'");
                Engine.logBeans.trace("  param type='" + propertyObjectValue.getClass().getName() + "'");
                Engine.logBeans.trace("  expected type='" + propertyType.getName() + "'");
                try {
                    setter.invoke(databaseObject, new Object[] { propertyObjectValue });
                } catch (InvocationTargetException e) {
                    Throwable targetException = e.getTargetException();
                    Engine.logBeans.warn("Unable to set the property '" + propertyName + "' for the object '"
                            + databaseObject.getName() + "' (" + objectClassName + "): ["
                            + targetException.getClass().getName() + "] " + targetException.getMessage());
                }

                if (Boolean.TRUE.equals(pd.getValue("nillable"))) {
                    Node nodeNull = childAttributes.getNamedItem("isNull");
                    String valNull = (nodeNull == null) ? "false" : nodeNull.getNodeValue();
                    Engine.logBeans.trace("  treats as null='" + valNull + "'");
                    try {
                        Method method = databaseObject.getClass().getMethod("setNullProperty",
                                new Class[] { String.class, Boolean.class });
                        method.invoke(databaseObject, new Object[] { propertyName, Boolean.valueOf(valNull) });
                    } catch (Exception ex) {
                        Engine.logBeans.warn("Unable to set the 'isNull' attribute for property '"
                                + propertyName + "' of '" + databaseObject.getName() + "' object");
                    }
                }
            }
        }
    } catch (Exception e) {
        String message = "Unable to set the object properties from the serialized XML data.\n"
                + "Object class: '" + objectClassName + "'\n" + "XML analyzed node: " + childNodeName + "\n"
                + "Property name: " + propertyName + "\n" + "Property value: " + propertyValue;
        EngineException ee = new EngineException(message, e);
        throw ee;
    }

    try {
        // Performs custom configuration
        databaseObject.configure(element);
    } catch (Exception e) {
        String s = XMLUtils.prettyPrintDOM(node);
        String message = "Unable to configure the object from serialized XML data after its creation.\n"
                + "Object class: '" + objectClassName + "'\n" + "XML data:\n" + s;
        EngineException ee = new EngineException(message, e);
        throw ee;
    }

    return databaseObject;
}

From source file:at.gridtec.lambda4j.consumer.bi.ThrowableBiConsumer.java

/**
 * Returns a composed {@link BiConsumer2} that first applies this consumer to its input, and then applies the {@code
 * recover} operation if a {@link Throwable} is thrown from this one. The {@code recover} operation is represented
 * by a curried operation which is called with throwable information and same arguments of this consumer.
 *
 * @param recover The operation to apply if this consumer throws a {@code Throwable}
 * @return A composed {@link BiConsumer2} that first applies this consumer to its input, and then applies the {@code
 * recover} operation if a {@code Throwable} is thrown from this one.
 * @throws NullPointerException If given argument or the returned enclosing consumer is {@code null}
 * @implSpec The implementation checks that the returned enclosing consumer from {@code recover} operation is not
 * {@code null}. If it is, then a {@link NullPointerException} with appropriate message is thrown.
 * @implNote If thrown {@code Throwable} is of type {@link Error}, it is thrown as-is and thus not passed to {@code
 * recover} operation./*from   w  w w  .  ja v  a  2 s  .  c o m*/
 */
@Nonnull
default BiConsumer2<T, U> recover(
        @Nonnull final Function<? super Throwable, ? extends BiConsumer<? super T, ? super U>> recover) {
    Objects.requireNonNull(recover);
    return (t, u) -> {
        try {
            this.acceptThrows(t, u);
        } catch (Error e) {
            throw e;
        } catch (Throwable throwable) {
            final BiConsumer<? super T, ? super U> consumer = recover.apply(throwable);
            Objects.requireNonNull(consumer,
                    () -> "recover returned null for " + throwable.getClass() + ": " + throwable.getMessage());
            consumer.accept(t, u);
        }
    };
}

From source file:hermes.renderers.RendererManager.java

public void setConfig(ClassLoader classLoader, HermesConfig config) throws HermesException {
    boolean gotDefaultRenderer = false;

    for (Iterator iter = config.getRenderer().iterator(); iter.hasNext();) {
        RendererConfig rConfig = (RendererConfig) iter.next();

        try {/*from  w w  w. ja  va 2s.  co m*/
            MessageRenderer renderer = createRenderer(classLoader, rConfig);

            if (renderer.getClass().getName().equals(DefaultMessageRenderer.class.getName())) {
                gotDefaultRenderer = true;
            }

            renderersByClass.put(rConfig.getClassName(), renderer);
            renderersByName.put(renderer.getDisplayName(), renderer);
        } catch (Throwable t) {
            log.error("cannot load renderer " + rConfig.getClassName() + ": " + t.getMessage(), t);

            if (HermesBrowser.getBrowser() != null) {
                JOptionPane.showMessageDialog(
                        HermesBrowser.getBrowser(), "Cannot load renderer " + rConfig.getClassName() + ":\n"
                                + t.getClass().getName() + "\n" + t.getMessage(),
                        "Error", JOptionPane.ERROR_MESSAGE);
            }
        }

    }

    renderers.clear();

    //
    // Handle upgrades to Hermes 1.6 where this may be missing.

    if (!gotDefaultRenderer) {
        RendererConfig rConfig = new RendererConfig();

        rConfig.setClassName(DefaultMessageRenderer.class.getName());

        config.getRenderer().add(rConfig);

        renderers.add(new DefaultMessageRenderer());
    }

    final StringTokenizer rendererClasses = new StringTokenizer(
            System.getProperty(SystemProperties.RENDERER_CLASSES, SystemProperties.DEFAULT_RENDERER_CLASSES),
            ",");

    while (rendererClasses.hasMoreTokens()) {
        final String rendererClassName = rendererClasses.nextToken();

        if (renderersByClass.containsKey(rendererClassName)) {
            renderers.add(renderersByClass.get(rendererClassName));
        } else {
            try {
                MessageRenderer renderer = (MessageRenderer) Class.forName(rendererClassName).newInstance();
                renderers.add(renderer);

                renderersByClass.put(rendererClassName, renderer);
                renderersByName.put(renderer.getDisplayName(), renderer);
            } catch (Throwable t) {
                log.error("cannot instantiate renderer: " + rendererClassName + ": " + t.getMessage(), t);
            }
        }
    }

    log.debug("renderer chain:");

    for (MessageRenderer r : renderers) {
        log.debug(r.getDisplayName() + ": " + r.getClass().getName());
    }

    for (Iterator hIter = HermesBrowser.getConfigDAO().getAllSessions(config).iterator(); hIter.hasNext();) {
        SessionConfig sConfig = (SessionConfig) hIter.next();

        for (Iterator iter2 = HermesBrowser.getConfigDAO().getAllDestinations(config, sConfig.getId())
                .iterator(); iter2.hasNext();) {
            DestinationConfig dConfig = (DestinationConfig) iter2.next();

            if (dConfig.getRenderer() != null) {
                // @@TODO Remove the old destination specific renderers.

                dConfig.setRenderer(null);
            }
        }
    }
}

From source file:com.haulmont.cuba.core.global.RemoteException.java

@SuppressWarnings("unchecked")
public RemoteException(Throwable throwable) {
    List<Throwable> list = ExceptionUtils.getThrowableList(throwable);
    for (int i = 0; i < list.size(); i++) {
        Throwable t = list.get(i);
        boolean suitable = true;
        List<Throwable> causesOfT = list.subList(i, list.size());
        for (Throwable aCauseOfT : causesOfT) {
            if (!isSuitable(aCauseOfT)) {
                suitable = false;// w w  w  .  j  a v a2s. c o  m
                break;
            }
        }
        if (suitable)
            causes.add(new Cause(t));
        else
            causes.add(new Cause(t.getClass().getName(), t.getMessage()));
    }
}

From source file:com.jxva.exception.ExceptionUtil.java

/**
 * <p>Sets the cause of a <code>Throwable</code> using introspection, allowing
 * source code compatibility between pre-1.4 and post-1.4 Java releases.</p>
 *
 * <p>The typical use of this method is inside a constructor as in
 * the following example:</p>/*from w  w  w.ja  v  a2  s.  c  o  m*/
 *
 * <pre>
 * import org.apache.commons.lang.exception.ExceptionUtils;
 *  
 * public class MyException extends Exception {
 *  
 *    public MyException(String msg) {
 *       super(msg);
 *    }
 *
 *    public MyException(String msg, Throwable cause) {
 *       super(msg);
 *       ExceptionUtils.setCause(this, cause);
 *    }
 * }
 * </pre>
 *
 * @param target  the target <code>Throwable</code>
 * @param cause  the <code>Throwable</code> to set in the target
 * @return a <code>true</code> if the target has been modified
 * @since 2.2
 */
public static boolean setCause(Throwable target, Throwable cause) {
    if (target == null) {
        throw new ArgumentException("target");
    }
    Object[] causeArgs = new Object[] { cause };
    boolean modifiedTarget = false;
    if (THROWABLE_INITCAUSE_METHOD != null) {
        try {
            THROWABLE_INITCAUSE_METHOD.invoke(target, causeArgs);
            modifiedTarget = true;
        } catch (IllegalAccessException ignored) {
            // Exception ignored.
        } catch (InvocationTargetException ignored) {
            // Exception ignored.
        }
    }
    try {
        Method setCauseMethod = target.getClass().getMethod("setCause", new Class[] { Throwable.class });
        setCauseMethod.invoke(target, causeArgs);
        modifiedTarget = true;
    } catch (NoSuchMethodException ignored) {
        // Exception ignored.
    } catch (IllegalAccessException ignored) {
        // Exception ignored.
    } catch (InvocationTargetException ignored) {
        // Exception ignored.
    }
    return modifiedTarget;
}

From source file:io.wcm.caravan.io.http.impl.ResilientHttpImpl.java

private Throwable mapToKnownException(String serviceName, Request request, Throwable ex) {
    if (ex instanceof RequestFailedRuntimeException || ex instanceof IllegalResponseRuntimeException) {
        return ex;
    }//ww w. j a v a2  s  .  co  m
    if (ex instanceof HystrixRuntimeException && ex.getCause() != null) {
        return mapToKnownException(serviceName, request, ex.getCause());
    }
    throw new RequestFailedRuntimeException(serviceName, request,
            StringUtils.defaultString(ex.getMessage(), ex.getClass().getSimpleName()), ex);
}

From source file:com.seajas.search.utilities.remoting.JsonHttpSupport.java

@Test
public void resultError() throws Exception {
    Throwable error = new RuntimeException("test");
    RemoteInvocationResult result = new RemoteInvocationResult(error);

    ByteArrayOutputStream buffer = new ByteArrayOutputStream();
    exporter.writeRemoteInvocationResult(null, result, buffer);
    ByteArrayInputStream stream = new ByteArrayInputStream(buffer.toByteArray());
    RemoteInvocationResult deserialized = executor.readRemoteInvocationResult(stream, null);
    assertNull(deserialized.getValue());
    assertNotNull(deserialized.getException());
    assertEquals(error.getClass(), deserialized.getException().getClass());
    assertEquals(error.getMessage(), deserialized.getException().getMessage());
}

From source file:com.strandls.alchemy.rest.client.exception.ExceptionPayloadDeserializer.java

@SuppressWarnings("unchecked")
@Override//w  w  w . j  a v  a2  s.co  m
public ExceptionPayload deserialize(final JsonParser jp, final DeserializationContext ctxt)
        throws IOException, JsonProcessingException {
    final ObjectMapper sourceObjectMapper = ((ObjectMapper) jp.getCodec());

    final ObjectNode tree = jp.readValueAsTree();

    String message = null;
    if (tree.has("exceptionMessage")) {
        message = tree.get("exceptionMessage").asText();
    }

    Throwable exception = null;
    try {
        final String className = tree.get("exceptionClassFQN").asText();
        final Class<? extends Throwable> clazz = (Class<? extends Throwable>) ReflectionUtils
                .forName(className);
        exception = sourceObjectMapper.treeToValue(tree.get("exception"), clazz);
    } catch (final Throwable t) {
        log.warn("Error deserializing exception class", t);
        exception = new InternalServerErrorException(message);
    }

    return new ExceptionPayload(exception.getClass().getName(), message, exception);
}