Example usage for java.lang IllegalStateException getCause

List of usage examples for java.lang IllegalStateException getCause

Introduction

In this page you can find the example usage for java.lang IllegalStateException getCause.

Prototype

public synchronized Throwable getCause() 

Source Link

Document

Returns the cause of this throwable or null if the cause is nonexistent or unknown.

Usage

From source file:org.sonar.scanner.scan.filesystem.MetadataGeneratorTest.java

@Test
public void non_existing_file_should_throw_exception() {
    try {/*  ww  w.ja v  a 2  s.c  o m*/
        createInputFileWithMetadata(Paths.get(""), "non_existing");
        Assert.fail();
    } catch (IllegalStateException e) {
        assertThat(e.getMessage())
                .endsWith("Unable to read file " + Paths.get("").resolve("non_existing").toAbsolutePath());
        assertThat(e.getCause()).isInstanceOf(IllegalStateException.class);
    }
}

From source file:co.runrightfast.vertx.core.eventbus.ProtobufMessageProducer.java

private void registerMessageCodec(final ProtobufMessageCodec<A> codec) {
    try {//from  w  ww  .j a  v  a  2 s  .  c o  m
        eventBus.registerDefaultCodec(codec.getDefaultInstance().getClass(), (MessageCodec) codec);
    } catch (final IllegalStateException e) {
        log.logp(FINE, "ProtobufMessageProducer", "registerMessageCodec",
                "failed to register codec for request message", e.getCause());
    }
}

From source file:org.sonar.scanner.scan.filesystem.InputFileBuilderTest.java

@Test
public void should_detect_charset_from_BOM() {
    File basedir = new File("src/test/resources/org/sonar/scanner/scan/filesystem/");
    when(fs.baseDir()).thenReturn(basedir);
    when(fs.encoding()).thenReturn(StandardCharsets.US_ASCII);
    when(langDetection.language(any(InputFile.class))).thenReturn("java");
    InputFileBuilder builder = new InputFileBuilder("moduleKey", new PathResolver(), langDetection,
            statusDetection, fs, new MapSettings(), new FileMetadata());

    assertThat(createAndComplete(builder, new File(basedir, "without_BOM.txt")).charset())
            .isEqualTo(StandardCharsets.US_ASCII);
    assertThat(createAndComplete(builder, new File(basedir, "UTF-8.txt")).charset())
            .isEqualTo(StandardCharsets.UTF_8);
    assertThat(createAndComplete(builder, new File(basedir, "UTF-16BE.txt")).charset())
            .isEqualTo(StandardCharsets.UTF_16BE);
    assertThat(createAndComplete(builder, new File(basedir, "UTF-16LE.txt")).charset())
            .isEqualTo(StandardCharsets.UTF_16LE);
    assertThat(createAndComplete(builder, new File(basedir, "UTF-32BE.txt")).charset())
            .isEqualTo(InputFileBuilder.UTF_32BE);
    assertThat(createAndComplete(builder, new File(basedir, "UTF-32LE.txt")).charset())
            .isEqualTo(InputFileBuilder.UTF_32LE);

    try {/*from  www.  j  ava 2 s . c  o m*/
        createAndComplete(builder, new File(basedir, "non_existing"));
        Assert.fail();
    } catch (IllegalStateException e) {
        assertThat(e.getMessage())
                .isEqualTo("Unable to read file " + new File(basedir, "non_existing").getAbsolutePath());
        assertThat(e.getCause()).isInstanceOf(FileNotFoundException.class);
    }
}

From source file:com.puppycrawl.tools.checkstyle.TreeWalkerTest.java

@Test
public void testDestroyNonExistingCache() throws Exception {
    final TreeWalker treeWalker = new TreeWalker();
    treeWalker.configure(new DefaultConfiguration("default config"));
    if (System.getProperty("os.name").toLowerCase(Locale.ENGLISH).startsWith("windows")) {
        // https://support.microsoft.com/en-us/kb/177506 but this only for NTFS
        // WindowsServer 2012 use Resilient File System (ReFS), so any name is ok
        File file = new File("C\\:invalid");
        treeWalker.setCacheFile(file.getAbsolutePath());
    } else {//from w  ww.j  av  a 2 s  .  c o  m
        treeWalker.setCacheFile(File.separator + ":invalid");
    }
    try {
        treeWalker.destroy();
        fail("Exception did not happen");
    } catch (IllegalStateException ex) {
        assertTrue(ex.getCause() instanceof IOException);
    }
}

From source file:org.apache.tinkerpop.gremlin.giraph.process.computer.GiraphGraphComputer.java

@Override
public int run(final String[] args) {
    final Storage storage = FileSystemStorage.open(this.giraphConfiguration);
    storage.rm(this.giraphConfiguration.get(Constants.GREMLIN_HADOOP_OUTPUT_LOCATION));
    this.giraphConfiguration.setBoolean(Constants.GREMLIN_HADOOP_GRAPH_OUTPUT_FORMAT_HAS_EDGES,
            this.persist.equals(Persist.EDGES));
    try {//w w  w  . j ava 2 s.  c om
        // store vertex and edge filters (will propagate down to native InputFormat or else GiraphVertexInputFormat will process)
        final BaseConfiguration apacheConfiguration = new BaseConfiguration();
        apacheConfiguration.setDelimiterParsingDisabled(true);
        GraphFilterAware.storeGraphFilter(apacheConfiguration, this.giraphConfiguration, this.graphFilter);

        // it is possible to run graph computer without a vertex program (and thus, only map reduce jobs if they exist)
        if (null != this.vertexProgram) {
            // a way to verify in Giraph whether the traversal will go over the wire or not
            try {
                VertexProgram.createVertexProgram(this.hadoopGraph,
                        ConfUtil.makeApacheConfiguration(this.giraphConfiguration));
            } catch (final IllegalStateException e) {
                if (e.getCause() instanceof NumberFormatException)
                    throw new NotSerializableException(
                            "The provided traversal is not serializable and thus, can not be distributed across the cluster");
            }
            // remove historic combiners in configuration propagation (this occurs when job chaining)
            if (!this.vertexProgram.getMessageCombiner().isPresent())
                this.giraphConfiguration.unset(GiraphConstants.MESSAGE_COMBINER_CLASS.getKey());
            // split required workers across system (open map slots + max threads per machine = total amount of TinkerPop workers)
            if (!this.useWorkerThreadsInConfiguration) {
                final Cluster cluster = new Cluster(GiraphGraphComputer.this.giraphConfiguration);
                int totalMappers = cluster.getClusterStatus().getMapSlotCapacity() - 1; // 1 is needed for master
                cluster.close();
                if (this.workers <= totalMappers) {
                    this.giraphConfiguration.setWorkerConfiguration(this.workers, this.workers, 100.0F);
                    this.giraphConfiguration.setNumComputeThreads(1);
                } else {
                    if (totalMappers == 0)
                        totalMappers = 1; // happens in local mode
                    int threadsPerMapper = Long
                            .valueOf(Math.round((double) this.workers / (double) totalMappers)).intValue(); // TODO: need to find least common denominator
                    this.giraphConfiguration.setWorkerConfiguration(totalMappers, totalMappers, 100.0F);
                    this.giraphConfiguration.setNumComputeThreads(threadsPerMapper);
                }
            }
            // prepare the giraph vertex-centric computing job
            final GiraphJob job = new GiraphJob(this.giraphConfiguration,
                    Constants.GREMLIN_HADOOP_GIRAPH_JOB_PREFIX + this.vertexProgram);
            job.getInternalJob().setJarByClass(GiraphGraphComputer.class);
            this.logger.info(Constants.GREMLIN_HADOOP_GIRAPH_JOB_PREFIX + this.vertexProgram);
            // handle input paths (if any)
            String inputLocation = this.giraphConfiguration.get(Constants.GREMLIN_HADOOP_INPUT_LOCATION, null);
            if (null != inputLocation && FileInputFormat.class.isAssignableFrom(this.giraphConfiguration
                    .getClass(Constants.GREMLIN_HADOOP_GRAPH_INPUT_FORMAT, InputFormat.class))) {
                inputLocation = Constants.getSearchGraphLocation(inputLocation, storage)
                        .orElse(this.giraphConfiguration.get(Constants.GREMLIN_HADOOP_INPUT_LOCATION));
                FileInputFormat.setInputPaths(job.getInternalJob(), new Path(inputLocation));
            }
            // handle output paths (if any)
            String outputLocation = this.giraphConfiguration.get(Constants.GREMLIN_HADOOP_OUTPUT_LOCATION,
                    null);
            if (null != outputLocation && FileOutputFormat.class.isAssignableFrom(this.giraphConfiguration
                    .getClass(Constants.GREMLIN_HADOOP_GRAPH_OUTPUT_FORMAT, OutputFormat.class))) {
                outputLocation = Constants.getGraphLocation(
                        this.giraphConfiguration.get(Constants.GREMLIN_HADOOP_OUTPUT_LOCATION));
                FileOutputFormat.setOutputPath(job.getInternalJob(), new Path(outputLocation));
            }
            // execute the job and wait until it completes (if it fails, throw an exception)
            if (!job.run(true))
                throw new IllegalStateException(
                        "The GiraphGraphComputer job failed -- aborting all subsequent MapReduce jobs: "
                                + job.getInternalJob().getStatus().getFailureInfo());
            // add vertex program memory values to the return memory
            for (final MemoryComputeKey memoryComputeKey : this.vertexProgram.getMemoryComputeKeys()) {
                if (!memoryComputeKey.isTransient() && storage.exists(Constants.getMemoryLocation(
                        this.giraphConfiguration.get(Constants.GREMLIN_HADOOP_OUTPUT_LOCATION),
                        memoryComputeKey.getKey()))) {
                    final ObjectWritableIterator iterator = new ObjectWritableIterator(this.giraphConfiguration,
                            new Path(Constants.getMemoryLocation(
                                    this.giraphConfiguration.get(Constants.GREMLIN_HADOOP_OUTPUT_LOCATION),
                                    memoryComputeKey.getKey())));
                    if (iterator.hasNext()) {
                        this.memory.set(memoryComputeKey.getKey(), iterator.next().getValue());
                    }
                    // vertex program memory items are not stored on disk
                    storage.rm(Constants.getMemoryLocation(
                            this.giraphConfiguration.get(Constants.GREMLIN_HADOOP_OUTPUT_LOCATION),
                            memoryComputeKey.getKey()));
                }
            }
            final Path path = new Path(Constants.getMemoryLocation(
                    this.giraphConfiguration.get(Constants.GREMLIN_HADOOP_OUTPUT_LOCATION),
                    Constants.HIDDEN_ITERATION));
            this.memory.setIteration(
                    (Integer) new ObjectWritableIterator(this.giraphConfiguration, path).next().getValue());
            storage.rm(Constants.getMemoryLocation(
                    this.giraphConfiguration.get(Constants.GREMLIN_HADOOP_OUTPUT_LOCATION),
                    Constants.HIDDEN_ITERATION));
        }
        // do map reduce jobs
        this.giraphConfiguration.setBoolean(Constants.GREMLIN_HADOOP_GRAPH_INPUT_FORMAT_HAS_EDGES,
                this.giraphConfiguration.getBoolean(Constants.GREMLIN_HADOOP_GRAPH_OUTPUT_FORMAT_HAS_EDGES,
                        true));
        for (final MapReduce mapReduce : this.mapReducers) {
            this.memory.addMapReduceMemoryKey(mapReduce);
            MapReduceHelper.executeMapReduceJob(mapReduce, this.memory, this.giraphConfiguration);
        }

        // if no persistence, delete the graph and memory output
        if (this.persist.equals(Persist.NOTHING))
            storage.rm(this.giraphConfiguration.get(Constants.GREMLIN_HADOOP_OUTPUT_LOCATION));
    } catch (final Exception e) {
        throw new IllegalStateException(e.getMessage(), e);
    }
    return 0;
}

From source file:cherry.foundation.async.AsyncFileProcessHandlerImplTest.java

@Test
public void testLaunchFileProcess_IOException() throws Exception {

    AsyncFileProcessHandlerImpl impl = createImpl();

    LocalDateTime now = LocalDateTime.now();
    when(bizDateTime.now()).thenReturn(now);
    when(asyncProcessStore.createFileProcess("a", now, "b", "c", "d", "e", 100L, "f")).thenReturn(10L);

    IOException ioException = new IOException();
    MultipartFile file = mock(MultipartFile.class);
    when(file.getName()).thenReturn("c");
    when(file.getOriginalFilename()).thenReturn("d");
    when(file.getContentType()).thenReturn("e");
    when(file.getSize()).thenReturn(100L);
    when(file.getInputStream()).thenThrow(ioException);

    try {//from  w w  w .  j a va2 s.co  m
        impl.launchFileProcess("a", "b", file, "f");
        fail("Exception must be thrown");
    } catch (IllegalStateException ex) {
        assertEquals(ioException, ex.getCause());
    }
}

From source file:org.sonatype.nexus.proxy.storage.remote.httpclient.HttpClientRemoteStorageTest.java

/**
 * When pool is depleted, and underlying HttpClient4x cannot fulfil request due to
 * {@link ConnectionPoolTimeoutException}, the {@link HttpClientRemoteStorage} should throw a new exception,
 * instance of {@link RemoteStorageTransportOverloadedException} to mark to core that transport is overloaded.
 *///from ww w.  j a  va  2s.co  m
@Test
public void emitProperExceptionOnPoolDepletion() throws Exception {
    setParameters();
    HttpClientFactoryImpl httpClientFactory = null;
    try {
        // the foreplay: setting up
        final RemoteStorageContext globalRemoteStorageContext = new DefaultRemoteStorageContext(null);
        final DefaultRemoteConnectionSettings rcs = new DefaultRemoteConnectionSettings();
        rcs.setConnectionTimeout(86400000);
        globalRemoteStorageContext.setRemoteConnectionSettings(new DefaultRemoteConnectionSettings());
        globalRemoteStorageContext.setRemoteProxySettings(mock(RemoteProxySettings.class));

        // real provider and initializing it with NexusStarted event
        httpClientFactory = new HttpClientFactoryImpl(Providers.of(mock(SystemStatus.class)),
                Providers.of(globalRemoteStorageContext), mock(EventBus.class),
                mock(PoolingClientConnectionManagerMBeanInstaller.class), null);

        // the RRS instance we test
        final HttpClientRemoteStorage underTest = new HttpClientRemoteStorage(
                Providers.of(mock(SystemStatus.class)), mock(MimeSupport.class), mock(QueryStringBuilder.class),
                new HttpClientManagerImpl(httpClientFactory));

        // a mock proxy repository with some mocks to make RRS work
        final RemoteStorageContext proxyContext = new DefaultRemoteStorageContext(globalRemoteStorageContext);
        final ProxyRepository repository = mock(ProxyRepository.class);
        when(repository.getId()).thenReturn("foo");
        when(repository.getName()).thenReturn("foo");
        when(repository.getRemoteUrl()).thenReturn("http://www.somehost.com/");
        when(repository.getRemoteStorageContext()).thenReturn(proxyContext);

        // a mock remote server that will simply "hang" to occupy the request socket
        final Server server = Server.withPort(0).serve("/").withBehaviours(Behaviours.pause(Time.days(1)))
                .start();
        // the URL we will try to connect to
        final String url = "http://foo.com:" + server.getPort() + "/foo/bar.jar";
        // the requesting logic packed as Runnable
        final Runnable request = new RequesterRunnable(underTest, repository, url);
        try {
            // we fire 1st request as a Thread, this thread will be blocked as Server will simply "pause"
            // this also means, that connection stays leased from pool, and since pool size is 1, we
            // intentionally depleted the connection pool (reached max connection count)
            final Thread blockedThread = new Thread(request);
            blockedThread.start();

            // give some time to thread above
            Thread.sleep(200);

            try {
                // in current thread we try to establish 2nd connection
                // this here will need to fail, as connection pool is depleted
                // ConnectionPoolTimeoutException should be thrown by HC4
                // that RRS "repackages" into RemoteStorageTransportOverloadedException
                request.run();

                // fail if no exception
                Assert.fail("RemoteStorageTransportOverloadedException expected!");
            } catch (IllegalStateException e) {
                Assert.assertNotNull("We except the cause be RemoteStorageTransportOverloadedException!",
                        e.getCause());
                Assert.assertEquals(RemoteStorageTransportOverloadedException.class, e.getCause().getClass());
            }
        } finally {
            server.stop();
        }
    } finally {
        if (httpClientFactory != null) {
            httpClientFactory.shutdown();
        }
        unsetParameters();
    }
}

From source file:com.puppycrawl.tools.checkstyle.CheckerTest.java

@Test
public void testDestroyNonExistingCache() throws Exception {
    // We use assumption to satisfy coverage rate on OS Windows, since persist() method of
    // class PropertyCacheFile does not throw IOException on OS Linux when path to a cache
    // directory is invalid on OS Windows.
    Assume.assumeTrue(System.getProperty("os.name").toLowerCase(Locale.ENGLISH).startsWith("windows"));

    final Checker checker = new Checker();
    final PackageObjectFactory factory = new PackageObjectFactory(new HashSet<String>(),
            Thread.currentThread().getContextClassLoader());
    checker.setModuleFactory(factory);/*from   w w w .j  a v a  2  s .co  m*/
    checker.configure(new DefaultConfiguration("default config"));
    final String tempFilePath = temporaryFolder.newFile().getPath() + ".\\\'";
    checker.setCacheFile(tempFilePath);
    try {
        checker.destroy();
        fail("Exception did not happen");
    } catch (IllegalStateException ex) {
        assertTrue(ex.getCause() instanceof IOException);
    }
}

From source file:com.puppycrawl.tools.checkstyle.CheckerTest.java

@Test
public void testDestroyCacheFileWithInvalidPath() throws Exception {
    final Checker checker = new Checker();
    final PackageObjectFactory factory = new PackageObjectFactory(new HashSet<String>(),
            Thread.currentThread().getContextClassLoader());
    checker.setModuleFactory(factory);//from  w w w  .ja  v a  2  s  .  c o  m
    checker.configure(new DefaultConfiguration("default config"));
    if (System.getProperty("os.name").toLowerCase(Locale.ENGLISH).startsWith("windows")) {
        // https://support.microsoft.com/en-us/kb/177506 but this only for NTFS
        // WindowsServer 2012 use Resilient File System (ReFS), so any name is ok
        final File file = new File("C\\:invalid");
        checker.setCacheFile(file.getAbsolutePath());
    } else {
        checker.setCacheFile(File.separator + ":invalid");
    }
    try {
        checker.destroy();
        fail("Exception did not happen");
    } catch (IllegalStateException ex) {
        assertThat(ex.getCause(), anyOf(instanceOf(IOException.class), instanceOf(InvalidPathException.class)));
    }
}

From source file:ch.cyberduck.core.pool.DefaultSessionPool.java

@Override
public Session<?> borrow(final BackgroundActionState callback) throws BackgroundException {
    final Integer numActive = pool.getNumActive();
    if (numActive > POOL_WARNING_THRESHOLD) {
        log.warn(String.format("Possibly large number of open connections (%d) in pool %s", numActive, this));
    }//from   w w w.j ava2s . co  m
    try {
        /*
         * The number of times this action has been run
         */
        int repeat = 0;
        while (!callback.isCanceled()) {
            try {
                if (log.isInfoEnabled()) {
                    log.info(String.format("Borrow session from pool %s", this));
                }
                final Session<?> session = pool.borrowObject();
                if (log.isInfoEnabled()) {
                    log.info(String.format("Borrowed session %s from pool %s", session, this));
                }
                if (DISCONNECTED == features) {
                    features = new StatelessSessionPool(connect, session, cache, transcript, registry);
                }
                return session.withListener(transcript);
            } catch (IllegalStateException e) {
                throw new ConnectionCanceledException(e);
            } catch (NoSuchElementException e) {
                if (pool.isClosed()) {
                    throw new ConnectionCanceledException(e);
                }
                final Throwable cause = e.getCause();
                if (null == cause) {
                    log.warn(String.format("Timeout borrowing session from pool %s. Wait for another %dms",
                            this, BORROW_MAX_WAIT_INTERVAL));
                    // Timeout
                    continue;
                }
                if (cause instanceof BackgroundException) {
                    final BackgroundException failure = (BackgroundException) cause;
                    log.warn(String.format("Failure %s obtaining connection for %s", failure, this));
                    if (diagnostics.determine(failure) == FailureDiagnostics.Type.network) {
                        final int max = Math.max(1, pool.getMaxIdle() - 1);
                        log.warn(String.format("Lower maximum idle pool size to %d connections.", max));
                        pool.setMaxIdle(max);
                        // Clear pool from idle connections
                        pool.clear();
                    }
                    throw failure;
                }
                log.error(String.format("Borrowing session from pool %s failed with %s", this, e));
                throw new DefaultExceptionMappingService().map(cause);
            }
        }
        throw new ConnectionCanceledException();
    } catch (BackgroundException e) {
        throw e;
    } catch (Exception e) {
        if (e.getCause() instanceof BackgroundException) {
            throw ((BackgroundException) e.getCause());
        }
        throw new BackgroundException(e.getMessage(), e);
    }
}