类com.google.common.base.Throwables源码实例Demo

下面列出了怎么用com.google.common.base.Throwables的API类实例代码及写法,或者点击链接到github查看源代码。

源代码1 项目: htmlelements   文件: RetryStatement.java
@Override
public Statement apply(Statement statement) throws Throwable {
    return () -> {
        Clock clock = new SystemClock();
        long end = clock.laterBy(timeout.in(TimeUnit.MILLISECONDS));
        Throwable lastException;
        do {
            try {
                return statement.evaluate();
            } catch (Throwable e) {
                lastException = e;
                if (ignoring.stream().anyMatch(clazz -> clazz.isInstance(e))) {
                    try {
                        Thread.sleep(polling.in(TimeUnit.MILLISECONDS));
                    } catch (InterruptedException i) {
                        break;
                    }
                } else {
                    Throwables.propagate(e);
                }
            }
        } while ((clock.isNowBefore(end)));
        throw lastException;
    };
}
 
源代码2 项目: ldp4j   文件: ApplicationContextTest.java
@Test
public void testWriteSession$completed$saveChanges(@Mocked final WriteSession nativeSession) throws Exception {
	new Expectations() {{
		delegate.createSession();result=nativeSession;
	}};
	ApplicationContext sut = createContext();
	WriteSession session = sut.createSession();
	session.saveChanges();
	try {
		session.saveChanges();
		fail("Session should not save changes after being completed");
	} catch (Exception e) {
		assertThat(Throwables.getRootCause(e),instanceOf(IllegalStateException.class));
	} finally {
		session.close();
	}
	verifySessionUsage(nativeSession);
}
 
源代码3 项目: jenkins-rest   文件: JenkinsErrorHandler.java
private String parseMessage(final HttpCommand command, final HttpResponse response) {
    if (response.getPayload() != null) {
        try {
            return Strings2.toStringAndClose(response.getPayload().openStream());
        } catch (IOException e) {
            throw Throwables.propagate(e);
        }
    } else {
        final String errorMessage = response.getFirstHeaderOrNull("X-Error");
        return new StringBuffer(command.getCurrentRequest().getRequestLine())
                .append(" -> ")
                .append(response.getStatusLine())
                .append(" -> ")
                .append(errorMessage != null ? errorMessage : "")
                .toString();
    }
}
 
源代码4 项目: brooklyn-server   文件: HttpToolResponse.java
public byte[] getContent() {
    synchronized (mutex) {
        if (content == null) {
            InputStream in = null;
            try {
                in = response.getEntity().getContent();
                ByteArrayOutputStream out = new ByteArrayOutputStream();
                ByteStreams.copy(in, out);
                content = out.toByteArray();
            } catch (IOException e) {
                throw Throwables.propagate(e);
            } finally {
                Streams.closeQuietly(in);
            }
        }
    }
    return content;
}
 
源代码5 项目: OpenPeripheral   文件: PropertyBuilderTest.java
private static void verifySingleGetterExecution(IMethodExecutor executor, Field targetField) {
	final IPropertyCallback target = mock(SingleCallbackSource.class);
	final IConverter converter = mock(IConverter.class);
	final IMethodCall call = executor.startCall(target);
	call.setEnv(Constants.ARG_CONVERTER, converter);

	final Value markerValue = new Value();
	when(target.getField(any(Field.class))).thenReturn(markerValue);

	final ConvertedValue markerConvertedValue = new ConvertedValue();
	when(converter.fromJava(any())).thenReturn(markerConvertedValue);

	try {
		final Object[] result = call.call();
		Assert.assertArrayEquals(new Object[] { markerConvertedValue }, result);
	} catch (Exception e) {
		throw Throwables.propagate(e);
	}

	verify(target).getField(targetField);
	verify(converter).fromJava(markerValue);
}
 
源代码6 项目: digdag   文件: RemotePluginLoader.java
private ClassLoader buildPluginClassLoader(List<ArtifactResult> artifactResults)
{
    ImmutableList.Builder<URL> urls = ImmutableList.builder();
    for (ArtifactResult artifactResult : artifactResults) {
        URL url;
        try {
            url = artifactResult.getArtifact().getFile().toPath().toUri().toURL();
        }
        catch (MalformedURLException ex) {
            throw Throwables.propagate(ex);
        }
        urls.add(url);
    }
    return new PluginClassLoader(urls.build(), RemotePluginLoader.class.getClassLoader(),
            PARENT_FIRST_PACKAGES, PARENT_FIRST_RESOURCES);
}
 
源代码7 项目: watcher   文件: AbstractCachedWatcherMetrics.java
public final Object watch(Map<String, Object> params) {
	try {
		if (cacheTime == null) {
			cacheTime = getCacheTime();
		}
		if (isCacheNotEnable()) {
			return doMonitor(params);
		} else {
			String key = buildKey(params);
			Object result = MetricsCache.INSTANCE.get(key);
			if (result == null) {
				result = doMonitor(params);
				if (result == null) {
					result = Constants.NULL;
				}
				MetricsCache.INSTANCE.put(key, result, cacheTime.getCacheTime());
				return result;
			} else {
				return result;
			}
		}
	} catch (Throwable throwable) {
		throw Throwables.propagate(throwable);
	}
}
 
源代码8 项目: navigator-sdk   文件: SSLUtils.java
private static TrustManager createTrustManager(ClientConfig config) {
  Preconditions.checkNotNull(config.getSSLTrustStoreLocation(),
      "Could not create TrustManager, No SSL trust store provided");
  //trust store
  String trustStoreType = config.getSslTrustStoreType();
  if (StringUtils.isEmpty(trustStoreType)) {
    trustStoreType = DEFAULT_TRUST_STORE_TYPE;
  }
  String trustStoreLocation = config.getSSLTrustStoreLocation();
  Preconditions.checkArgument(StringUtils.isNotEmpty(trustStoreLocation),
    "Trust store location not provided");
  String trustStorePassword = config.getSSLTrustStorePassword();
  Preconditions.checkArgument(StringUtils.isNotEmpty(trustStorePassword),
      "Trust store password not provided");

  try {
    return loadTrustManager(trustStoreType,
        trustStoreLocation,
        trustStorePassword);
  } catch (IOException | GeneralSecurityException e) {
    throw Throwables.propagate(e);
  }
}
 
源代码9 项目: flo   文件: BigQueryTasksTest.java
@Test
public void lookupShouldBeRunnable() throws Exception {
  final Future<TableId> future = FloRunner.runTask(BigQueryTasks.lookup(
      "non-existent-project", "non-existent-dataset", "non-existent-table")).future();

  try {
    future.get();
    fail("Did not expect to find a non-existent table");
  } catch (ExecutionException e) {
    // Verify that we are getting some well known error here so we know with some
    // certainty that we didn't get a serialization error. Yes, this is quite awful.
    final Throwable rootCause = Throwables.getRootCause(e);
    if (rootCause instanceof NotReady) {
      // Seems we had working credentials and the lookup worked. We're done here.
    } else if (rootCause instanceof GoogleJsonResponseException) {
      // Seems we managed to make a request, so the lookup executed. We're done here.
    } else if (rootCause instanceof IllegalArgumentException &&
        rootCause.getMessage().startsWith("A project ID is required")) {
      // Seems we managed to get as far as trying to instantiate the BigQuery client (in the task process).
      // We're done here.
    } else {
      // Not sure what went wrong here, might be serialization error, so be conservative and fail here.
      throw e;
    }
  }
}
 
源代码10 项目: datacollector   文件: LambdaUtil.java
/**
 * Runs a Supplier within the context of a specified ClassLoader and in priviledged mode.
 *
 * @param classLoader the ClassLoader to run the Supplier.
 * @param e1 Exception class that should be propagated as-is
 * @param e2 Exception class that should be propagated as-is
 * @param supplier the Supplier to run within the context of a specified ClassLoader.
 */
public static <T, E1 extends Exception, E2 extends Exception> T privilegedWithClassLoader(
    ClassLoader classLoader,
    Class<E1> e1,
    Class<E2> e2,
    ExceptionSupplier<T> supplier
) throws E1, E2 {
  try {
    return AccessController.doPrivileged((PrivilegedExceptionAction<T>) () -> withClassLoaderInternal(classLoader, supplier));
  } catch (PrivilegedActionException e) {
    Throwables.propagateIfPossible(e.getCause(), e1, e2);
    Throwables.propagate(e);
  }

  return null;
}
 
源代码11 项目: phoenix-tephra   文件: TransactionManager.java
public synchronized void recoverState() {
  try {
    TransactionSnapshot lastSnapshot = persistor.getLatestSnapshot();
    // if we failed before a snapshot could complete, we might not have one to restore
    if (lastSnapshot != null) {
      restoreSnapshot(lastSnapshot);
    }
    // replay any WALs since the last snapshot
    Collection<TransactionLog> logs = persistor.getLogsSince(lastSnapshotTime);
    if (logs != null) {
      replayLogs(logs);
    }
  } catch (IOException e) {
    LOG.error("Unable to read back transaction state:", e);
    throw Throwables.propagate(e);
  }
}
 
源代码12 项目: bazel   文件: AbstractQueueVisitor.java
@Override
public final void awaitQuiescence(boolean interruptWorkers) throws InterruptedException {
  Throwables.propagateIfPossible(catastrophe);
  try {
    synchronized (zeroRemainingTasks) {
      while (remainingTasks.get() != 0 && !jobsMustBeStopped) {
        zeroRemainingTasks.wait();
      }
    }
  } catch (InterruptedException e) {
    // Mark the visitor, so that it's known to be interrupted, and
    // then break out of here, stop the worker threads and return ASAP,
    // sending the interruption to the parent thread.
    setInterrupted();
  }

  awaitTermination(interruptWorkers);
}
 
源代码13 项目: api-compiler   文件: SwaggerToolDriverBase.java
private Model setupModel() {
  // Prevent INFO messages from polluting the log.
  Logger.getLogger("").setLevel(Level.WARNING);

  try {
    serviceConfig = generateServiceConfig();
  } catch (IOException e) {
    getDiagCollector().addDiag(Diag.error(SimpleLocation.TOPLEVEL,
        "Unexpected exception:%n%s", Throwables.getStackTraceAsString(e)));
  }

  model = Model.create(serviceConfig);
  onErrorsExit();

  // Register standard processors.
  StandardSetup.registerStandardProcessors(model);

  // Register standard config aspects.
  StandardSetup.registerStandardConfigAspects(model);

  return model;
}
 
源代码14 项目: rubix   文件: BookKeeperServer.java
private void startThriftServer(Configuration conf, BookKeeper bookKeeper)
{
  processor = new BookKeeperService.Processor(bookKeeper);
  log.info("Starting BookKeeperServer on port " + getBookKeeperServerPort(conf));
  try {
    TServerTransport serverTransport = new TServerSocket(
            new TServerSocket.ServerSocketTransportArgs().bindAddr(new InetSocketAddress(getBookKeeperServerPort(conf))).backlog(Integer.MAX_VALUE));
    server = new TThreadPoolServer(new TThreadPoolServer
        .Args(serverTransport)
        .processor(processor)
        .maxWorkerThreads(getServerMaxThreads(conf)));

    server.serve();
  }
  catch (TTransportException e) {
    log.error(Throwables.getStackTraceAsString(e));
  }
}
 
源代码15 项目: brooklyn-server   文件: BrooklynPropertiesImpl.java
@Override
public BrooklynPropertiesImpl addFrom(InputStream i) {
    // Ugly way to load them in order, but Properties is a Hashtable so loses order otherwise.
    @SuppressWarnings({ "serial" })
    Properties p = new Properties() {
        @Override
        public synchronized Object put(Object key, Object value) {
            // Trim the string values to remove leading and trailing spaces
            String s = (String) value;
            if (Strings.isBlank(s)) {
                s = Strings.EMPTY;
            } else {
                s = CharMatcher.BREAKING_WHITESPACE.trimFrom(s);
            }
            return BrooklynPropertiesImpl.this.put(key, s);
        }
    };
    try {
        p.load(i);
    } catch (IOException e) {
        throw Throwables.propagate(e);
    }
    return this;
}
 
源代码16 项目: googleads-java-lib   文件: ConfigurationHelper.java
/**
 * Loads configuration from a specified path. If not absolute, will look in
 * the user home directory, the current classpath and the system classpath.
 * Absolute classpath references will not work.
 *
 * @param path the path to try first as a resource, then as a file
 * @throws ConfigurationLoadException if the configuration could not be
 *         loaded.
 * @returns properties loaded from the specified path or null.
 */
public Configuration fromFile(String path) throws ConfigurationLoadException {
  PropertiesConfiguration propertiesConfiguration =
      setupConfiguration(new PropertiesConfiguration());
  propertiesConfiguration.setFileName(path);
  try {
    propertiesConfiguration.load();
  } catch (ConfigurationException e) {
    if (Throwables.getRootCause(e) instanceof AccessControlException){
      AdsServiceLoggers.ADS_API_LIB_LOG.debug("Properties could not be loaded.", e);
    } else {
      throw new ConfigurationLoadException(
          "Encountered a problem reading the provided configuration file \"" + path + "\"!", e);
    }
  }
  return propertiesConfiguration;
}
 
源代码17 项目: emodb   文件: CredentialEncrypter.java
private SecretKey createKey(byte[] initializationBytes) {
    try {
        // Create the encryption key from a SecureRandom seeded with the secret SEED value and initialization bytes.
        // This way different initialization values will generate different keys.
        SecureRandom random = SecureRandom.getInstance(SEED_PRNG);
        random.setSeed(BaseEncoding.base64().decode(SEED));
        random.setSeed(initializationBytes);

        byte[] keyBytes = new byte[16];
        random.nextBytes(keyBytes);

        return new SecretKeySpec(keyBytes, ALGORITHM);
    } catch (NoSuchAlgorithmException e) {
        // This shouldn't happen since SHA1PRNG is supported by all JVMs.
        throw Throwables.propagate(e);
    }
}
 
源代码18 项目: rubix   文件: DummyModeCachingInputStream.java
private void dummyRead(final long initPos, final byte[] buffer, final int offset, final int length)
{
  final long initNextReadBlock = initPos / blockSize;
  readService.execute(new Runnable()
  {
    @Override
    public void run()
    {
      try {
        long endBlock = ((initPos + (length - 1)) / blockSize) + 1;
        final List<ReadRequestChain> readRequestChains = setupReadRequestChains(buffer, offset, endBlock, length,
                initPos, initNextReadBlock);
        updateCacheAndStats(readRequestChains);
      }
      catch (IOException e) {
        throw Throwables.propagate(e);
      }
    }
  });
}
 
源代码19 项目: newts   文件: BlockingThreadPoolExecutor.java
@Override
public void rejectedExecution(Runnable task, ThreadPoolExecutor executor) {

    BlockingQueue<Runnable> queue = executor.getQueue();

    while (true) {
        if (executor.isShutdown()) {
            throw new RejectedExecutionException("ThreadPoolExecutor has shut down");
        }

        try {
            if (queue.offer(task, 300, TimeUnit.MILLISECONDS)) {
                break;
            }
        }
        catch (InterruptedException e) {
            throw Throwables.propagate(e);
        }
    }

}
 
private void init(boolean enableEventRecording)
{
  setupWsClient();
  setupRecording(enableEventRecording);
  setupStringCodecs();

  try {
    Path file = new Path(this.vars.appPath);
    URI uri = file.toUri();
    Configuration config = new YarnConfiguration();
    fileContext = uri.getScheme() == null ? FileContext.getFileContext(config) : FileContext.getFileContext(uri, config);
    saveMetaInfo();
    String fileName = String.format(CONTAINERS_INFO_FILENAME_FORMAT, plan.getLogicalPlan().getValue(LogicalPlan.APPLICATION_ATTEMPT_ID));
    this.containerFile = new FSJsonLineFile(fileContext, new Path(this.vars.appPath, fileName), FsPermission.getDefault());
    this.containerFile.append(getAppMasterContainerInfo());
    fileName = String.format(OPERATORS_INFO_FILENAME_FORMAT, plan.getLogicalPlan().getValue(LogicalPlan.APPLICATION_ATTEMPT_ID));
    this.operatorFile = new FSJsonLineFile(fileContext, new Path(this.vars.appPath, fileName), FsPermission.getDefault());
  } catch (IOException ex) {
    throw Throwables.propagate(ex);
  }
}
 
源代码21 项目: n4js   文件: GitUtils.java
/**
 * Obtain information about all submodules of the Git repository at the given path. Returns an empty map in case the
 * repository does not include submodules. Throws exceptions in case of error.
 */
public static Map<String, SubmoduleStatus> getSubmodules(final Path localClonePath) {

	if (!isValidLocalClonePath(localClonePath)) {
		throw new IllegalArgumentException("invalid localClonePath: " + localClonePath);
	}

	try (final Git git = open(localClonePath.toFile())) {
		return git.submoduleStatus().call();
	} catch (Exception e) {
		LOGGER.error(e.getClass().getSimpleName()
				+ " while trying to obtain status of all submodules"
				+ " of repository '" + localClonePath
				+ "':" + e.getLocalizedMessage());
		Throwables.throwIfUnchecked(e);
		throw new RuntimeException(e);
	}
}
 
源代码22 项目: attic-apex-malhar   文件: SQLExecEnvironment.java
/**
 * This is the main method takes SQL statement as input and contructs a DAG using contructs registered with this
 * {@link SQLExecEnvironment}.
 *
 * @param sql SQL statement that should be converted to a DAG.
 */
public void executeSQL(DAG dag, String sql)
{
  FrameworkConfig config = buildFrameWorkConfig();
  Planner planner = Frameworks.getPlanner(config);
  try {
    logger.info("Parsing SQL statement: {}", sql);
    SqlNode parsedTree = planner.parse(sql);
    SqlNode validatedTree = planner.validate(parsedTree);
    RelNode relationalTree = planner.rel(validatedTree).rel;
    logger.info("RelNode relationalTree generate from SQL statement is:\n {}",
        Util.toLinux(RelOptUtil.toString(relationalTree)));
    RelNodeVisitor visitor = new RelNodeVisitor(dag, typeFactory);
    visitor.traverse(relationalTree);
  } catch (Exception e) {
    throw Throwables.propagate(e);
  } finally {
    planner.close();
  }
}
 
源代码23 项目: nexus-public   文件: TrustStoreImpl.java
@Override
public SSLContext getSSLContext() {
  SSLContext _sslcontext = this.sslcontext; // local variable allows concurrent removeTrustCertificate
  if (_sslcontext == null) {
    try {
      // the trusted key store may have asychronously changed when NXRM is clustered, reload the managed store used
      // for fallback so the context doesn't use stale key store
      this.managedTrustManager = getManagedTrustManager(keyStoreManager);
      _sslcontext = SSLContext.getInstance(SSLConnectionSocketFactory.TLS);
      _sslcontext.init(keyManagers, trustManagers, DEFAULT_RANDOM);
      this.sslcontext = _sslcontext;
    }
    catch (Exception e) {
      log.debug("Could not create SSL context", e);
      Throwables.throwIfUnchecked(e);
      throw new RuntimeException(e);
    }
  }
  return _sslcontext;
}
 
@Test
public void testUnboundedRangeIsRejected() {
    try {
        final Restriction ageRestrictionInt = doInJPA(new JPATransactionFunction<Restriction>() {
            @Override
            public Restriction apply(EntityManager entityManager) {
                Restriction restriction = new Restriction();
                restriction.setRangeInt(Ranges.<Integer>all());
                entityManager.persist(restriction);

                return restriction;
            }
        });
        fail("An unbounded range should throw an exception!");
    } catch (Exception e) {
        Throwable rootCause = Throwables.getRootCause(e);
        assertTrue(rootCause instanceof IllegalArgumentException);
        assertTrue(rootCause.getMessage().contains("doesn't have any upper or lower bound!"));
    }
}
 
源代码25 项目: dremio-oss   文件: S3FileSystem.java
private S3Client getSyncClient(String bucket) throws IOException {
  try {
    return syncClientCache.get(bucket);
  } catch (ExecutionException | SdkClientException e ) {
    final Throwable cause = e.getCause();
    final Throwable toChain;
    if (cause == null) {
      toChain = e;
    } else {
      Throwables.throwIfInstanceOf(cause, UserException.class);
      Throwables.throwIfInstanceOf(cause, IOException.class);

      toChain = cause;
    }

    throw new IOException(String.format("Unable to create a sync S3 client for bucket %s", bucket), toChain);
  }
}
 
源代码26 项目: curator   文件: TestMigrationManager.java
@Test
public void testChecksumDataError()
{
    CuratorOp op1 = client.transactionOp().create().forPath("/test");
    CuratorOp op2 = client.transactionOp().create().forPath("/test/bar", "first".getBytes());
    Migration migration = () -> Arrays.asList(op1, op2);
    MigrationSet migrationSet = MigrationSet.build("1", Collections.singletonList(migration));
    complete(manager.migrate(migrationSet));

    CuratorOp op2Changed = client.transactionOp().create().forPath("/test/bar", "second".getBytes());
    migration = () -> Arrays.asList(op1, op2Changed);
    migrationSet = MigrationSet.build("1", Collections.singletonList(migration));
    try
    {
        complete(manager.migrate(migrationSet));
        Assert.fail("Should throw");
    }
    catch ( Throwable e )
    {
        Assert.assertTrue(Throwables.getRootCause(e) instanceof MigrationException);
    }
}
 
源代码27 项目: nomulus   文件: HttpsRelayServiceHandler.java
/** Terminates connection upon outbound exception. */
@Override
public void write(ChannelHandlerContext ctx, Object msg, ChannelPromise promise)
    throws Exception {
  promise.addListener(
      (ChannelFuture channelFuture) -> {
        if (!channelFuture.isSuccess()) {
          Throwable cause = channelFuture.cause();
          if (NON_FATAL_OUTBOUND_EXCEPTIONS.contains(Throwables.getRootCause(cause).getClass())) {
            logger.atWarning().withCause(channelFuture.cause()).log(
                "Outbound exception caught for channel %s", channelFuture.channel());
          } else {
            logger.atSevere().withCause(channelFuture.cause()).log(
                "Outbound exception caught for channel %s", channelFuture.channel());
          }
          ChannelFuture unusedFuture = channelFuture.channel().close();
        }
      });
  super.write(ctx, msg, promise);
}
 
源代码28 项目: vraptor4   文件: ExecuteMethodExceptionHandler.java
private void throwIfNotValidationException(Throwable original, Throwable alternativeCause) {
	Throwable cause = original.getCause();

	if (original instanceof ValidationException || cause instanceof ValidationException) {
		// fine... already parsed
		log.trace("swallowing {}", cause);
	} else {
		Throwables.propagateIfPossible(alternativeCause);
		throw new ApplicationLogicException(alternativeCause);
	}
}
 
源代码29 项目: rocket-console   文件: JsonUtil.java
public static void writeValue(Writer writer, Object obj) {
    try {
        objectMapper.writeValue(writer, obj);
    } catch (IOException e) {
        Throwables.propagateIfPossible(e);
    }
}
 
源代码30 项目: keywhiz   文件: GCMEncryptor.java
private byte[] gcm(boolean encrypt, byte[] input, byte[] nonce) throws AEADBadTagException {
  try {
    Cipher cipher = Cipher.getInstance(ENCRYPTION_ALGORITHM);
    SecretKey secretKey = new SecretKeySpec(key, KEY_ALGORITHM);

    GCMParameterSpec gcmParameters = new GCMParameterSpec(TAG_BITS, nonce);
    cipher.init(encrypt ? ENCRYPT_MODE : DECRYPT_MODE, secretKey, gcmParameters);
    return cipher.doFinal(input);
  } catch (NoSuchAlgorithmException | NoSuchPaddingException | BadPaddingException | IllegalBlockSizeException | InvalidAlgorithmParameterException | InvalidKeyException e) {
    Throwables.propagateIfInstanceOf(e, AEADBadTagException.class);
    throw Throwables.propagate(e);
  }
}