Example usage for java.lang Exception initCause

List of usage examples for java.lang Exception initCause

Introduction

In this page you can find the example usage for java.lang Exception initCause.

Prototype

public synchronized Throwable initCause(Throwable cause) 

Source Link

Document

Initializes the cause of this throwable to the specified value.

Usage

From source file:com.hippo.ehviewer.client.parser.RateGalleryParser.java

public static Result parse(String body) throws Exception {
    try {/* w ww .  j  a v  a2s.c  om*/
        JSONObject jsonObject = new JSONObject(body);
        Result result = new Result();
        result.rating = (float) jsonObject.getDouble("rating_avg");
        result.ratingCount = jsonObject.getInt("rating_cnt");
        return result;
    } catch (JSONException e) {
        Exception exception = new ParseException("Can't parse rate gallery", body);
        exception.initCause(e);
        throw exception;
    }
}

From source file:org.mycore.common.MCRUtils.java

@SafeVarargs
public static Exception unwrapExCeption(Exception e, Class<? extends Exception>... classes) {
    if (classes.length == 0) {
        return e;
    }//from  ww  w  . jav  a 2  s.co m
    Class<? extends Exception> mainExceptionClass = classes[0];
    Throwable check = e;
    for (Class<? extends Exception> instChk : classes) {
        if (instChk.isInstance(check)) {
            return (Exception) check;
        }
        check = check.getCause();
        if (check == null) {
            break;
        }
    }
    @SuppressWarnings("unchecked")
    Constructor<? extends Exception>[] constructors = (Constructor<? extends Exception>[]) mainExceptionClass
            .getConstructors();
    for (Constructor<? extends Exception> c : constructors) {
        Class<?>[] parameterTypes = c.getParameterTypes();
        try {
            if (parameterTypes.length == 0) {
                Exception exception = c.newInstance((Object[]) null);
                exception.initCause(e);
                return exception;
            }
            if (parameterTypes.length == 1 && parameterTypes[0].isAssignableFrom(mainExceptionClass)) {
                return c.newInstance(e);
            }
        } catch (InstantiationException | IllegalAccessException | IllegalArgumentException
                | InvocationTargetException ex) {
            LOGGER.warn("Exception while initializing exception " + mainExceptionClass.getCanonicalName(), ex);
            return e;
        }
    }
    LOGGER.warn("Could not instanciate Exception " + mainExceptionClass.getCanonicalName());
    return e;
}

From source file:org.apache.hive.service.cli.TestHiveSQLException.java

/**
 * Tests the conversion from a regular exception to the TStatus object
 *//* w  w w. j a va  2s .c  om*/
@Test
public void testExceptionToTStatus() {
    Exception ex1 = createException();
    ex1.initCause(createSimpleCause());
    TStatus status = HiveSQLException.toTStatus(ex1);

    Assert.assertEquals(TStatusCode.ERROR_STATUS, status.getStatusCode());
    Assert.assertEquals(ex1.getMessage(), status.getErrorMessage());
    Assert.assertEquals(HiveSQLException.toString(ex1), status.getInfoMessages());
}

From source file:org.apache.hive.service.cli.TestHiveSQLException.java

/**
 * Tests the conversion between the exception text with the simple cause and the
 * Throwable object//from   www .  j  av  a2 s.c  o m
 */
@Test
public void testExceptionMarshalling() throws Exception {
    Exception ex1 = createException();
    ex1.initCause(createSimpleCause());
    Throwable ex = HiveSQLException.toCause(HiveSQLException.toString(ex1));

    Assert.assertSame(RuntimeException.class, ex.getClass());
    Assert.assertEquals("exception1", ex.getMessage());
    Assert.assertSame(UnsupportedOperationException.class, ex.getCause().getClass());
    Assert.assertEquals("exception2", ex.getCause().getMessage());
}

From source file:org.apache.hive.service.cli.TestHiveSQLException.java

/**
 * Tests the conversion between the exception text with nested cause and
 * the Throwable object//from www.  j a v a 2  s  . c  o m
 */
@Test
public void testNestedException() {
    Exception ex1 = createException();
    ex1.initCause(createNestedCause());
    Throwable ex = HiveSQLException.toCause(HiveSQLException.toString(ex1));

    Assert.assertSame(RuntimeException.class, ex.getClass());
    Assert.assertEquals("exception1", ex.getMessage());

    Assert.assertSame(UnsupportedOperationException.class, ex.getCause().getClass());
    Assert.assertEquals("exception2", ex.getCause().getMessage());

    Assert.assertSame(Exception.class, ex.getCause().getCause().getClass());
    Assert.assertEquals("exception3", ex.getCause().getCause().getMessage());
}

From source file:org.apache.hive.service.cli.TestHiveSQLException.java

/**
 * Tests the conversion of the exception with unknown source
 *///from   w  w w.ja  v a  2  s.c  o  m
@Test
public void testExceptionWithUnknownSource() {
    Exception ex1 = createException();
    ex1.initCause(createSimpleCause());
    List<String> details = HiveSQLException.toString(ex1);

    // Simulate the unknown source
    String[] tokens = details.get(1).split(":");
    tokens[2] = null;
    tokens[3] = "-1";
    details.set(1, StringUtils.join(tokens, ":"));

    Throwable ex = HiveSQLException.toCause(details);

    Assert.assertSame(RuntimeException.class, ex.getClass());
    Assert.assertEquals("exception1", ex.getMessage());
    Assert.assertSame(UnsupportedOperationException.class, ex.getCause().getClass());
    Assert.assertEquals("exception2", ex.getCause().getMessage());
}

From source file:org.apache.hive.service.cli.TestHiveSQLException.java

/**
 * Tests the conversion of the exception from anonymous class
 *///from w  w w  .  java  2 s .co m
@Test
public void testExceptionFromAnonymousClass() {
    Dummy d = new Dummy() {

        public void testExceptionConversion() {
            Exception ex1 = createException();
            ex1.initCause(createSimpleCause());
            Throwable ex = HiveSQLException.toCause(HiveSQLException.toString(ex1));

            Assert.assertSame(RuntimeException.class, ex.getClass());
            Assert.assertEquals("exception1", ex.getMessage());
            Assert.assertSame(UnsupportedOperationException.class, ex.getCause().getClass());
            Assert.assertEquals("exception2", ex.getCause().getMessage());
        }
    };

    d.testExceptionConversion();
}

From source file:org.apache.hive.service.cli.TestHiveSQLException.java

/**
 * Tests the conversion of the exception that the class type of one of the causes
 * doesn't exist. The stack trace text is generated on the server and passed to JDBC
 * client. It's possible that some cause types don't exist on the client and HiveSQLException
 * can't convert them and use RunTimeException instead.
 *///  w ww .ja v  a2  s  . c o  m
@Test
public void testExceptionWithMissingTypeOnClient() {
    Exception ex1 = new UnsupportedOperationException();
    ex1.initCause(createSimpleCause());
    List<String> details = HiveSQLException.toString(ex1);

    // Simulate an unknown type
    String[] tokens = details.get(0).split(":");
    tokens[0] = "*DummyException";
    details.set(0, StringUtils.join(tokens, ":"));

    Throwable ex = HiveSQLException.toCause(details);
    Assert.assertEquals(RuntimeException.class, ex.getClass());
}

From source file:org.seedstack.seed.core.internal.data.DataManagerImpl.java

@Override
public void importData(InputStream inputStream, String acceptGroup, String acceptName, boolean clear) {
    Set<DataImporter<Object>> usedDataImporters = new HashSet<>();

    try {/*  w ww  .  ja va  2  s. c o  m*/
        ParsingState state = ParsingState.START;
        String group = null;
        String name = null;
        JsonParser jsonParser = this.jsonFactory
                .createParser(new InputStreamReader(inputStream, Charset.forName(UTF_8)));
        JsonToken jsonToken = jsonParser.nextToken();

        while (jsonToken != null) {
            switch (state) {
            case START:
                if (jsonToken == JsonToken.START_ARRAY) {
                    state = ParsingState.DEFINITION_START;
                } else {
                    throwParsingError(jsonParser.getCurrentLocation(), "start array expected");
                }

                break;
            case DEFINITION_START:
                if (jsonToken == JsonToken.START_OBJECT) {
                    state = ParsingState.DEFINITION_GROUP;
                } else {
                    throwParsingError(jsonParser.getCurrentLocation(), "start object expected");
                }

                break;
            case DEFINITION_GROUP:
                if (jsonToken == JsonToken.FIELD_NAME && GROUP.equals(jsonParser.getCurrentName())) {
                    group = jsonParser.nextTextValue();
                    state = ParsingState.DEFINITION_NAME;
                } else {
                    throwParsingError(jsonParser.getCurrentLocation(), "group field expected");
                }

                break;
            case DEFINITION_NAME:
                if (jsonToken == JsonToken.FIELD_NAME && NAME.equals(jsonParser.getCurrentName())) {
                    name = jsonParser.nextTextValue();
                    state = ParsingState.DEFINITION_ITEMS;
                } else {
                    throwParsingError(jsonParser.getCurrentLocation(), "name field expected");
                }

                break;
            case DEFINITION_ITEMS:
                if (jsonToken == JsonToken.FIELD_NAME && ITEMS.equals(jsonParser.getCurrentName())) {
                    usedDataImporters.add(consumeItems(jsonParser, group, name, acceptGroup, acceptName));
                    state = ParsingState.DEFINITION_END;
                } else {
                    throwParsingError(jsonParser.getCurrentLocation(), "items field expected");
                }

                break;
            case DEFINITION_END:
                if (jsonToken == JsonToken.END_OBJECT) {
                    group = null;
                    name = null;
                    state = ParsingState.END;
                } else {
                    throwParsingError(jsonParser.getCurrentLocation(), "end object expected");
                }

                break;
            case END:
                if (jsonToken == JsonToken.START_OBJECT) {
                    state = ParsingState.DEFINITION_GROUP;
                } else if (jsonToken == JsonToken.END_ARRAY) {
                    state = ParsingState.START;
                } else {
                    throwParsingError(jsonParser.getCurrentLocation(), "start object or end array expected");
                }

                break;
            default:
                throwParsingError(jsonParser.getCurrentLocation(), "unexpected parser state");
            }

            jsonToken = jsonParser.nextToken();
        }
    } catch (Exception e1) {
        for (DataImporter<Object> usedDataImporter : usedDataImporters) {
            try {
                usedDataImporter.rollback();
            } catch (Exception e2) {
                e2.initCause(e1);
                throw SeedException.wrap(e2, DataErrorCode.FAILED_TO_ROLLBACK_IMPORT).put(IMPORTER_CLASS,
                        usedDataImporter.getClass().getName());
            }
        }

        throw SeedException.wrap(e1, DataErrorCode.IMPORT_FAILED);
    }

    for (DataImporter<Object> usedDataImporter : usedDataImporters) {
        try {
            usedDataImporter.commit(clear);
        } catch (Exception e) {
            throw SeedException.wrap(e, DataErrorCode.FAILED_TO_COMMIT_IMPORT).put(IMPORTER_CLASS,
                    usedDataImporter.getClass().getName());
        }
    }
}

From source file:org.apache.hadoop.hive.shims.Hadoop23Shims.java

/**
 * If there is an AccessException buried somewhere in the chain of failures, wrap the original
 * exception in an AccessException. Othewise just return the original exception.
 *///from  w ww.  j av a  2 s .  co m
private static Exception wrapAccessException(Exception err) {
    final int maxDepth = 20;
    Throwable curErr = err;
    for (int idx = 0; curErr != null && idx < maxDepth; ++idx) {
        // fs.permission.AccessControlException removed by HADOOP-11356, but Hive users on older
        // Hadoop versions may still see this exception .. have to reference by name.
        if (curErr instanceof org.apache.hadoop.security.AccessControlException || curErr.getClass().getName()
                .equals("org.apache.hadoop.fs.permission.AccessControlException")) {
            Exception newErr = new AccessControlException(curErr.getMessage());
            newErr.initCause(err);
            return newErr;
        }
        curErr = curErr.getCause();
    }
    return err;
}