001/*
002 *  Licensed to the Apache Software Foundation (ASF) under one
003 *  or more contributor license agreements.  See the NOTICE file
004 *  distributed with this work for additional information
005 *  regarding copyright ownership.  The ASF licenses this file
006 *  to you under the Apache License, Version 2.0 (the
007 *  "License"); you may not use this file except in compliance
008 *  with the License.  You may obtain a copy of the License at
009 *
010 *        http://www.apache.org/licenses/LICENSE-2.0
011 *
012 *  Unless required by applicable law or agreed to in writing,
013 *  software distributed under the License is distributed on an
014 *  "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
015 *  KIND, either express or implied.  See the License for the
016 *  specific language governing permissions and limitations
017 *  under the License.
018 */
019
020package org.apache.isis.core.commons.lang;
021
022import java.io.ByteArrayOutputStream;
023import java.io.IOException;
024import java.io.PrintStream;
025import java.lang.reflect.InvocationTargetException;
026
027import org.apache.isis.applib.RecoverableException;
028import org.apache.isis.core.commons.exceptions.IsisApplicationException;
029import org.apache.isis.core.metamodel.exceptions.MetaModelException;
030
031public final class ThrowableExtensions {
032
033    public static String stackTraceFor(final Throwable extendee) {
034        ByteArrayOutputStream baos = null;
035        try {
036            baos = new ByteArrayOutputStream();
037            extendee.printStackTrace(new PrintStream(baos));
038            return baos.toString();
039        } finally {
040            if (baos != null) {
041                try {
042                    baos.close();
043                } catch (final IOException ignore) {
044                }
045            }
046        }
047    }
048
049    public static void throwWithinIsisException(final InvocationTargetException e, final String error) {
050        final Throwable targetException = e.getTargetException();
051        if (targetException instanceof RecoverableException) {
052            // an application exception from the domain code is re-thrown as an
053            // IsisException with same semantics
054            // TODO: should probably be using ApplicationException here
055            throw new IsisApplicationException(targetException);
056        }
057        if (targetException instanceof RuntimeException) {
058            throw (RuntimeException) targetException;
059        } else {
060            throw new MetaModelException(targetException);
061        }
062    }
063}