Example usage for org.apache.commons.lang3.exception ExceptionUtils getRootCause

List of usage examples for org.apache.commons.lang3.exception ExceptionUtils getRootCause

Introduction

In this page you can find the example usage for org.apache.commons.lang3.exception ExceptionUtils getRootCause.

Prototype

public static Throwable getRootCause(final Throwable throwable) 

Source Link

Document

Introspects the Throwable to obtain the root cause.

This method walks through the exception chain to the last element, "root" of the tree, using #getCause(Throwable) , and returns that exception.

From version 2.2, this method handles recursive cause structures that might otherwise cause infinite loops.

Usage

From source file:org.apache.kylin.rest.util.AdHocUtil.java

public static boolean doAdHocQuery(String project, String sql, List<List<String>> results,
        List<SelectedColumnMeta> columnMetas, SQLException sqlException) throws Exception {

    boolean isExpectedCause = (ExceptionUtils.getRootCause(sqlException).getClass()
            .equals(NoRealizationFoundException.class));
    KylinConfig kylinConfig = KylinConfig.getInstanceFromEnv();

    if (isExpectedCause && kylinConfig.isAdhocEnabled()) {
        IAdHocRunner runner = (IAdHocRunner) ClassUtil.newInstance(kylinConfig.getAdHocRunnerClassName());
        IAdHocConverter converter = (IAdHocConverter) ClassUtil
                .newInstance(kylinConfig.getAdHocConverterClassName());

        runner.init(kylinConfig);/*from   w w w. ja  v a 2s  . c  om*/

        logger.debug("Ad-hoc query runner {}", runner);

        String expandCC = restoreComputedColumnToExpr(sql, project);
        String adhocSql = converter.convert(expandCC);
        if (!adhocSql.equals(sql)) {
            logger.info("before delegating to adhoc, the query is converted to {} ", adhocSql);
        }

        runner.executeQuery(adhocSql, results, columnMetas);

        return true;
    } else {
        throw sqlException;
    }
}

From source file:org.apache.kylin.rest.util.PushDownUtil.java

public static boolean doPushDownQuery(String project, String sql, List<List<String>> results,
        List<SelectedColumnMeta> columnMetas, SQLException sqlException) throws Exception {

    boolean isExpectedCause = (ExceptionUtils.getRootCause(sqlException).getClass()
            .equals(NoRealizationFoundException.class));
    KylinConfig kylinConfig = KylinConfig.getInstanceFromEnv();

    if (isExpectedCause && kylinConfig.isPushDownEnabled()) {

        logger.info("Query failed to utilize pre-calculation, routing to other engines", sqlException);
        IPushDownRunner runner = (IPushDownRunner) ClassUtil
                .newInstance(kylinConfig.getPushDownRunnerClassName());
        IPushDownConverter converter = (IPushDownConverter) ClassUtil
                .newInstance(kylinConfig.getPushDownConverterClassName());

        runner.init(kylinConfig);//from   w w  w.  j  a  va 2 s.  c  o m

        logger.debug("Query pushdown runner {}", runner);

        String expandCC = restoreComputedColumnToExpr(sql, project);
        if (!StringUtils.equals(expandCC, sql)) {
            logger.info("computed column in sql is expanded to:  " + expandCC);
        }
        String adhocSql = converter.convert(expandCC);
        if (!adhocSql.equals(expandCC)) {
            logger.info("the query is converted to {} according to kylin.query.pushdown.converter-class-name",
                    adhocSql);
        }

        runner.executeQuery(adhocSql, results, columnMetas);

        return true;
    } else {
        throw sqlException;
    }
}

From source file:org.apache.nifi.processors.azure.storage.ListAzureBlobStorage.java

@Override
protected List<BlobInfo> performListing(final ProcessContext context, final Long minTimestamp)
        throws IOException {
    String containerName = context.getProperty(AzureStorageUtils.CONTAINER).evaluateAttributeExpressions()
            .getValue();/*w  w  w  .  j  av a 2 s  .com*/
    String prefix = context.getProperty(PROP_PREFIX).evaluateAttributeExpressions().getValue();
    if (prefix == null) {
        prefix = "";
    }
    final List<BlobInfo> listing = new ArrayList<>();
    try {
        CloudBlobClient blobClient = AzureStorageUtils.createCloudBlobClient(context, getLogger(), null);
        CloudBlobContainer container = blobClient.getContainerReference(containerName);

        final OperationContext operationContext = new OperationContext();
        AzureStorageUtils.setProxy(operationContext, context);

        for (ListBlobItem blob : container.listBlobs(prefix, true, EnumSet.of(BlobListingDetails.METADATA),
                null, operationContext)) {
            if (blob instanceof CloudBlob) {
                CloudBlob cloudBlob = (CloudBlob) blob;
                BlobProperties properties = cloudBlob.getProperties();
                StorageUri uri = cloudBlob.getSnapshotQualifiedStorageUri();

                Builder builder = new BlobInfo.Builder().primaryUri(uri.getPrimaryUri().toString())
                        .blobName(cloudBlob.getName()).containerName(containerName)
                        .contentType(properties.getContentType())
                        .contentLanguage(properties.getContentLanguage()).etag(properties.getEtag())
                        .lastModifiedTime(properties.getLastModified().getTime())
                        .length(properties.getLength());

                if (uri.getSecondaryUri() != null) {
                    builder.secondaryUri(uri.getSecondaryUri().toString());
                }

                if (blob instanceof CloudBlockBlob) {
                    builder.blobType(AzureStorageUtils.BLOCK);
                } else {
                    builder.blobType(AzureStorageUtils.PAGE);
                }
                listing.add(builder.build());
            }
        }
    } catch (Throwable t) {
        throw new IOException(ExceptionUtils.getRootCause(t));
    }
    return listing;
}

From source file:org.apache.phoenix.end2end.UserDefinedFunctionsIT.java

/**
 * Test creating functions using dir otherthan hbase.dynamic.jars.dir
 * @throws Exception/*from   w w  w .j a  v a  2  s .  c  o  m*/
 */
@Test
public void testCreateFunctionNonDynamicJarDir() throws Exception {
    Connection conn = driver.connect(url, EMPTY_PROPS);
    String tableName = "table" + name.getMethodName();

    conn.createStatement().execute("create table " + tableName
            + "(tenant_id varchar not null, k integer not null, "
            + "firstname varchar, lastname varchar constraint pk primary key(tenant_id,k)) MULTI_TENANT=true");
    String tenantId = "tenId" + name.getMethodName();
    Connection tenantConn = driver.connect(url + ";" + PhoenixRuntime.TENANT_ID_ATTRIB + "=" + tenantId,
            EMPTY_PROPS);
    Statement stmtTenant = tenantConn.createStatement();
    tenantConn.commit();

    compileTestClass(MY_REVERSE_CLASS_NAME, MY_REVERSE_PROGRAM, 8);
    Path destJarPathOnHDFS = copyJarsFromDynamicJarsDirToDummyHDFSDir("myjar8.jar");

    try {
        String sql = "create function myfunction(VARCHAR) returns VARCHAR as 'org.apache.phoenix.end2end."
                + MY_REVERSE_CLASS_NAME + "' using jar '" + destJarPathOnHDFS.toString() + "'";
        stmtTenant.execute(sql);
        ResultSet rs = stmtTenant.executeQuery("select myfunction(firstname) from " + tableName);
        fail("expecting java.lang.SecurityException");
    } catch (Exception e) {
        assertTrue(ExceptionUtils.getRootCause(e) instanceof SecurityException);
    } finally {
        stmtTenant.execute("drop function myfunction");
    }
}

From source file:org.apache.pulsar.sql.presto.PulsarMetadata.java

@Override
public List<String> listSchemaNames(ConnectorSession session) {
    List<String> prestoSchemas = new LinkedList<>();
    try {/*from ww  w  .ja  v  a 2 s.c o m*/
        List<String> tenants = pulsarAdmin.tenants().getTenants();
        for (String tenant : tenants) {
            prestoSchemas.addAll(pulsarAdmin.namespaces().getNamespaces(tenant));
        }
    } catch (PulsarAdminException e) {
        throw new RuntimeException(
                "Failed to get schemas from pulsar: " + ExceptionUtils.getRootCause(e).getLocalizedMessage(),
                e);
    }
    return prestoSchemas;
}

From source file:org.apache.pulsar.sql.presto.PulsarMetadata.java

@Override
public List<SchemaTableName> listTables(ConnectorSession session, String schemaNameOrNull) {
    ImmutableList.Builder<SchemaTableName> builder = ImmutableList.builder();

    if (schemaNameOrNull != null) {

        if (schemaNameOrNull.equals(INFORMATION_SCHEMA)) {
            // no-op for now but add pulsar connector specific system tables here
        } else {/*from   w ww. j  a va 2s .c  o  m*/
            List<String> pulsarTopicList = null;
            try {
                pulsarTopicList = this.pulsarAdmin.topics().getList(schemaNameOrNull);
            } catch (PulsarAdminException e) {
                if (e.getStatusCode() == 404) {
                    log.warn("Schema " + schemaNameOrNull + " does not exsit");
                    return builder.build();
                }
                throw new RuntimeException("Failed to get tables/topics in " + schemaNameOrNull + ": "
                        + ExceptionUtils.getRootCause(e).getLocalizedMessage(), e);
            }
            if (pulsarTopicList != null) {
                pulsarTopicList.forEach(topic -> builder
                        .add(new SchemaTableName(schemaNameOrNull, TopicName.get(topic).getLocalName())));
            }
        }
    }
    return builder.build();
}

From source file:org.apache.pulsar.sql.presto.PulsarMetadata.java

private ConnectorTableMetadata getTableMetadata(SchemaTableName schemaTableName, boolean withInternalColumns) {

    if (schemaTableName.getSchemaName().equals(INFORMATION_SCHEMA)) {
        return null;
    }/*from w  w  w .  j av a  2s .  c  om*/

    TopicName topicName = TopicName
            .get(String.format("%s/%s", schemaTableName.getSchemaName(), schemaTableName.getTableName()));

    List<String> topics;
    try {
        if (!PulsarConnectorUtils.isPartitionedTopic(topicName, this.pulsarAdmin)) {
            topics = this.pulsarAdmin.topics().getList(schemaTableName.getSchemaName());
        } else {
            topics = this.pulsarAdmin.topics().getPartitionedTopicList((schemaTableName.getSchemaName()));
        }
    } catch (PulsarAdminException e) {
        if (e.getStatusCode() == 404) {
            throw new PrestoException(NOT_FOUND,
                    "Schema " + schemaTableName.getSchemaName() + " does not exist");
        }
        throw new RuntimeException("Failed to get topics in schema " + schemaTableName.getSchemaName() + ": "
                + ExceptionUtils.getRootCause(e).getLocalizedMessage(), e);
    }

    if (!topics.contains(topicName.toString())) {
        log.error("Table %s not found",
                String.format("%s/%s", schemaTableName.getSchemaName(), schemaTableName.getTableName()));
        throw new TableNotFoundException(schemaTableName);
    }

    SchemaInfo schemaInfo;
    try {
        schemaInfo = this.pulsarAdmin.schemas().getSchemaInfo(
                String.format("%s/%s", schemaTableName.getSchemaName(), schemaTableName.getTableName()));
    } catch (PulsarAdminException e) {
        if (e.getStatusCode() == 404) {
            // to indicate that we can't read from topic because there is no schema
            return null;
        }
        throw new RuntimeException("Failed to get schema information for topic "
                + String.format("%s/%s", schemaTableName.getSchemaName(), schemaTableName.getTableName()) + ": "
                + ExceptionUtils.getRootCause(e).getLocalizedMessage(), e);
    }

    String schemaJson = new String(schemaInfo.getSchema());
    if (StringUtils.isBlank(schemaJson)) {
        throw new PrestoException(NOT_SUPPORTED,
                "Topic " + topicName.toString() + " does not have a valid schema");
    }
    Schema schema;
    try {
        schema = PulsarConnectorUtils.parseSchema(schemaJson);
    } catch (SchemaParseException ex) {
        throw new PrestoException(NOT_SUPPORTED,
                "Topic " + topicName.toString() + " does not have a valid schema");
    }

    ImmutableList.Builder<ColumnMetadata> builder = ImmutableList.builder();

    builder.addAll(getColumns(null, schema, new HashSet<>(), new Stack<>(), new Stack<>()));

    if (withInternalColumns) {
        PulsarInternalColumn.getInternalFields().stream().forEach(new Consumer<PulsarInternalColumn>() {
            @Override
            public void accept(PulsarInternalColumn pulsarInternalColumn) {
                builder.add(pulsarInternalColumn.getColumnMetadata(false));
            }
        });
    }

    return new ConnectorTableMetadata(schemaTableName, builder.build());
}

From source file:org.apache.pulsar.sql.presto.PulsarSplitManager.java

@Override
public ConnectorSplitSource getSplits(ConnectorTransactionHandle transactionHandle, ConnectorSession session,
        ConnectorTableLayoutHandle layout, SplitSchedulingStrategy splitSchedulingStrategy) {

    int numSplits = this.pulsarConnectorConfig.getTargetNumSplits();

    PulsarTableLayoutHandle layoutHandle = (PulsarTableLayoutHandle) layout;
    PulsarTableHandle tableHandle = layoutHandle.getTable();
    TupleDomain<ColumnHandle> tupleDomain = layoutHandle.getTupleDomain();

    TopicName topicName = TopicName.get("persistent", NamespaceName.get(tableHandle.getSchemaName()),
            tableHandle.getTableName());

    SchemaInfo schemaInfo;/*from ww w . j av  a2  s  .c om*/
    try {
        schemaInfo = this.pulsarAdmin.schemas()
                .getSchemaInfo(String.format("%s/%s", tableHandle.getSchemaName(), tableHandle.getTableName()));
    } catch (PulsarAdminException e) {
        throw new RuntimeException("Failed to get schema for topic "
                + String.format("%s/%s", tableHandle.getSchemaName(), tableHandle.getTableName()) + ": "
                + ExceptionUtils.getRootCause(e).getLocalizedMessage(), e);
    }

    Collection<PulsarSplit> splits;
    try {
        if (!PulsarConnectorUtils.isPartitionedTopic(topicName, this.pulsarAdmin)) {
            splits = getSplitsNonPartitionedTopic(numSplits, topicName, tableHandle, schemaInfo, tupleDomain);
            log.debug("Splits for non-partitioned topic %s: %s", topicName, splits);
        } else {
            splits = getSplitsPartitionedTopic(numSplits, topicName, tableHandle, schemaInfo, tupleDomain);
            log.debug("Splits for partitioned topic %s: %s", topicName, splits);
        }
    } catch (Exception e) {
        log.error(e, "Failed to get splits");
        throw new RuntimeException(e);
    }
    return new FixedSplitSource(splits);
}

From source file:org.apache.pulsar.sql.presto.PulsarSplitManager.java

@VisibleForTesting
Collection<PulsarSplit> getSplitsPartitionedTopic(int numSplits, TopicName topicName,
        PulsarTableHandle tableHandle, SchemaInfo schemaInfo, TupleDomain<ColumnHandle> tupleDomain)
        throws Exception {
    int numPartitions;
    try {//  w w w  . j  a va  2s. c o m
        numPartitions = (this.pulsarAdmin.topics()
                .getPartitionedTopicMetadata(topicName.toString())).partitions;
    } catch (PulsarAdminException e) {
        throw new RuntimeException("Failed to get metadata for partitioned topic " + topicName + ": "
                + ExceptionUtils.getRootCause(e).getLocalizedMessage(), e);
    }

    int actualNumSplits = Math.max(numPartitions, numSplits);

    int splitsPerPartition = actualNumSplits / numPartitions;

    int splitRemainder = actualNumSplits % numPartitions;

    ManagedLedgerFactory managedLedgerFactory = getManagedLedgerFactory();

    try {
        List<PulsarSplit> splits = new LinkedList<>();
        for (int i = 0; i < numPartitions; i++) {

            int splitsForThisPartition = (splitRemainder > i) ? splitsPerPartition + 1 : splitsPerPartition;
            splits.addAll(getSplitsForTopic(topicName.getPartition(i).getPersistenceNamingEncoding(),
                    managedLedgerFactory, splitsForThisPartition, tableHandle, schemaInfo,
                    topicName.getPartition(i).getLocalName(), tupleDomain));
        }
        return splits;
    } finally {
        if (managedLedgerFactory != null) {
            try {
                managedLedgerFactory.shutdown();
            } catch (Exception e) {
                log.error(e);
            }
        }
    }
}

From source file:org.apache.rave.persistence.jpa.impl.H2OpenJpaDialect.java

/**
 * Translates an H2 database error into a Rave application Exception
 * /*from   ww w  .j  av  a2  s.c  o m*/
 * @param re the RuntimeException to translate to a Rave application exception
 * @return a Rave application exception representing the database error
 */
@Override
public DataAccessException translateExceptionIfPossible(RuntimeException re) {
    DataAccessException e = null;
    // first make sure the root exception is actually an org.h2.jdbc.JdbcSQLException
    if (ExceptionUtils.getRootCause(re) instanceof JdbcSQLException) {
        JdbcSQLException rootException = (JdbcSQLException) ExceptionUtils.getRootCause(re);

        // now translate the H2 specific error codes into Rave's common application Exceptions
        // add more error codes to the switch statement that should be specifically trapped                         
        switch (rootException.getErrorCode()) {
        case ErrorCode.DUPLICATE_KEY_1: {
            e = new DuplicateItemException("DUPLICATE_ITEM", rootException);
            break;
        }

        default: {
            e = new TranslatedH2Exception(rootException.getErrorCode(), "ERROR", "Unknown Database Error");
            break;
        }
        }
    } else {
        // we got a RuntimeException that wasn't an org.h2.jdbc.JdbcSQLException
        e = new TranslatedH2Exception(TranslatedH2Exception.UNKNOWN_ERROR_CODE, "ERROR",
                "Unknown Runtime Exception");
    }

    return e;
}