Java Code Examples for com.google.common.base.Throwables

The following examples show how to use com.google.common.base.Throwables. These examples are extracted from open source projects. You can vote up the ones you like or vote down the ones you don't like, and go to the original project or source file by following the links above each example. You may want to check out the right sidebar which shows the related API usage.
Example 1
Source Project: htmlelements   Source File: RetryStatement.java    License: Apache License 2.0 6 votes vote down vote up
@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;
    };
}
 
Example 2
Source Project: ldp4j   Source File: ApplicationContextTest.java    License: Apache License 2.0 6 votes vote down vote up
@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);
}
 
Example 3
Source Project: jenkins-rest   Source File: JenkinsErrorHandler.java    License: Apache License 2.0 6 votes vote down vote up
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();
    }
}
 
Example 4
Source Project: brooklyn-server   Source File: HttpToolResponse.java    License: Apache License 2.0 6 votes vote down vote up
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;
}
 
Example 5
Source Project: OpenPeripheral   Source File: PropertyBuilderTest.java    License: MIT License 6 votes vote down vote up
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);
}
 
Example 6
Source Project: digdag   Source File: RemotePluginLoader.java    License: Apache License 2.0 6 votes vote down vote up
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);
}
 
Example 7
Source Project: watcher   Source File: AbstractCachedWatcherMetrics.java    License: Apache License 2.0 6 votes vote down vote up
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);
	}
}
 
Example 8
Source Project: navigator-sdk   Source File: SSLUtils.java    License: Apache License 2.0 6 votes vote down vote up
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);
  }
}
 
Example 9
Source Project: flo   Source File: BigQueryTasksTest.java    License: Apache License 2.0 6 votes vote down vote up
@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;
    }
  }
}
 
Example 10
Source Project: datacollector   Source File: LambdaUtil.java    License: Apache License 2.0 6 votes vote down vote up
/**
 * 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;
}
 
Example 11
Source Project: phoenix-tephra   Source File: TransactionManager.java    License: Apache License 2.0 6 votes vote down vote up
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);
  }
}
 
Example 12
Source Project: bazel   Source File: AbstractQueueVisitor.java    License: Apache License 2.0 6 votes vote down vote up
@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);
}
 
Example 13
Source Project: api-compiler   Source File: SwaggerToolDriverBase.java    License: Apache License 2.0 6 votes vote down vote up
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;
}
 
Example 14
Source Project: rubix   Source File: BookKeeperServer.java    License: Apache License 2.0 6 votes vote down vote up
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));
  }
}
 
Example 15
Source Project: brooklyn-server   Source File: BrooklynPropertiesImpl.java    License: Apache License 2.0 6 votes vote down vote up
@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;
}
 
Example 16
Source Project: googleads-java-lib   Source File: ConfigurationHelper.java    License: Apache License 2.0 6 votes vote down vote up
/**
 * 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;
}
 
Example 17
Source Project: emodb   Source File: CredentialEncrypter.java    License: Apache License 2.0 6 votes vote down vote up
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);
    }
}
 
Example 18
Source Project: rubix   Source File: DummyModeCachingInputStream.java    License: Apache License 2.0 6 votes vote down vote up
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);
      }
    }
  });
}
 
Example 19
Source Project: newts   Source File: BlockingThreadPoolExecutor.java    License: Apache License 2.0 6 votes vote down vote up
@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);
        }
    }

}
 
Example 20
Source Project: attic-apex-core   Source File: StreamingContainerManager.java    License: Apache License 2.0 6 votes vote down vote up
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);
  }
}
 
Example 21
Source Project: n4js   Source File: GitUtils.java    License: Eclipse Public License 1.0 6 votes vote down vote up
/**
 * 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);
	}
}
 
Example 22
Source Project: attic-apex-malhar   Source File: SQLExecEnvironment.java    License: Apache License 2.0 6 votes vote down vote up
/**
 * 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();
  }
}
 
Example 23
Source Project: nexus-public   Source File: TrustStoreImpl.java    License: Eclipse Public License 1.0 6 votes vote down vote up
@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;
}
 
Example 24
@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!"));
    }
}
 
Example 25
Source Project: dremio-oss   Source File: S3FileSystem.java    License: Apache License 2.0 6 votes vote down vote up
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);
  }
}
 
Example 26
Source Project: curator   Source File: TestMigrationManager.java    License: Apache License 2.0 6 votes vote down vote up
@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);
    }
}
 
Example 27
Source Project: nomulus   Source File: HttpsRelayServiceHandler.java    License: Apache License 2.0 6 votes vote down vote up
/** 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);
}
 
Example 28
Source Project: vraptor4   Source File: ExecuteMethodExceptionHandler.java    License: Apache License 2.0 5 votes vote down vote up
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);
	}
}
 
Example 29
Source Project: rocket-console   Source File: JsonUtil.java    License: Apache License 2.0 5 votes vote down vote up
public static void writeValue(Writer writer, Object obj) {
    try {
        objectMapper.writeValue(writer, obj);
    } catch (IOException e) {
        Throwables.propagateIfPossible(e);
    }
}
 
Example 30
Source Project: keywhiz   Source File: GCMEncryptor.java    License: Apache License 2.0 5 votes vote down vote up
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);
  }
}
 
Example 31
Source Project: moserp   Source File: ContentUrlRewritingFilter.java    License: Apache License 2.0 5 votes vote down vote up
@Override
public Object run() {
    try {
        rewriteContent(RequestContext.getCurrentContext());
    } catch (final Exception e) {
        Throwables.propagate(e);
    }
    return null;
}
 
Example 32
@Override
public void exportProfile(RulesProfile ruleProfile, Writer writer) {
    try {
        new CFLintConfigExporter(ruleProfile.getActiveRulesByRepository(ColdFusionPlugin.REPOSITORY_KEY)).save(writer);
    } catch (IOException | XMLStreamException e) {
        Throwables.propagate(e);
    }
}
 
Example 33
Source Project: digdag   Source File: S3Storage.java    License: Apache License 2.0 5 votes vote down vote up
@Override
public void list(String keyPrefix, FileListing callback)
{
    checkArgument(keyPrefix != null, "keyPrefix is null");

    String errorMessage = "listing files on bucket " + bucket + " prefix " + keyPrefix;

    ListObjectsRequest req = new ListObjectsRequest();
    req.setBucketName(bucket);
    req.setPrefix(keyPrefix);

    ObjectListing listing;
    do {
        try {
            listing = getWithRetry(errorMessage, () -> client.listObjects(req));
        }
        catch (StorageFileNotFoundException ex) {
            throw Throwables.propagate(ex.getCause());
        }
        callback.accept(Lists.transform(
                    listing.getObjectSummaries(),
                    (summary) -> StorageObjectSummary.builder()
                        .key(summary.getKey())
                        .contentLength(summary.getSize())
                        .lastModified(summary.getLastModified().toInstant())
                        .build()
                    ));
        req.setMarker(listing.getNextMarker());
    }
    while (listing.isTruncated());
}
 
Example 34
Source Project: dremio-oss   Source File: LuceneSearchIndex.java    License: Apache License 2.0 5 votes vote down vote up
private void checkIfChanged() {
  try{
    if (!searcherManager.isSearcherCurrent()) {
      searcherManager.maybeRefreshBlocking();
    }
  }catch(IOException ex){
    throw Throwables.propagate(ex);
  }
}
 
Example 35
Source Project: dremio-oss   Source File: CachingOptionManager.java    License: Apache License 2.0 5 votes vote down vote up
@Override
public OptionValue getOption(String name) {
  try {
    return options.get(name);
  } catch (ExecutionException e) {
    throw Throwables.propagate(e.getCause());
  }
}
 
Example 36
Source Project: teku   Source File: SyncManager.java    License: Apache License 2.0 5 votes vote down vote up
private SafeFuture<Void> syncToPeer(final Eth2Peer syncPeer) {
  LOG.trace("Sync to peer {}", syncPeer.getId());
  return peerSync
      .sync(syncPeer)
      .thenCompose(
          result -> {
            if (result != PeerSyncResult.SUCCESSFUL_SYNC) {
              LOG.trace("Sync to peer {} failed with {}.", syncPeer.getId(), result.name());
              return asyncRunner.runAfterDelay(
                  this::executeSync, SHORT_DELAY.toMillis(), TimeUnit.MILLISECONDS);
            } else {
              LOG.trace("Successfully synced to peer {}.", syncPeer.getId());
              return completedFuture(null);
            }
          })
      .exceptionally(
          error -> {
            if (Throwables.getRootCause(error) instanceof PeerDisconnectedException) {
              LOG.debug("Peer {} disconnected during sync", syncPeer, error);

            } else {
              LOG.error("Error during sync to peer {}", syncPeer, error);
            }
            peersWithSyncErrors.add(syncPeer.getId());
            // Wait a little bit, clear error and retry
            asyncRunner
                .getDelayedFuture(LONG_DELAY.toMillis(), TimeUnit.MILLISECONDS)
                .thenAccept(
                    (res) -> {
                      peersWithSyncErrors.remove(syncPeer.getId());
                      startOrScheduleSync();
                    })
                .reportExceptions();
            return null;
          });
}
 
Example 37
Source Project: api-compiler   Source File: GenericToolDriverBase.java    License: Apache License 2.0 5 votes vote down vote up
/**
 * Runs the tool. Returns a non-zero exit code on errors.
 */
public int run() {
  // Run tool specific code.
  if (!getDiagCollector().hasErrors()) {
    try {
      process();
    } catch (Exception e) {
      getDiagCollector().addDiag(Diag.error(SimpleLocation.TOPLEVEL,
          "Unexpected exception:%n%s", Throwables.getStackTraceAsString(e)));
    }
  }
  reportDiag();
  return getDiagCollector().hasErrors() ? 1 : 0;
}
 
Example 38
public void deployTarballResource(String url, String targetName) {
    try {
        doDeployTarballResource(url, targetName);
    } catch (RuntimeException e) {
        LOG.error("Error deploying '" + url + "' on " + toString() + "; rethrowing...", e);
        throw Throwables.propagate(e);
    }
}
 
Example 39
Source Project: imhotep   Source File: AbstractFlamdexReader.java    License: Apache License 2.0 5 votes vote down vote up
public StringValueLookup getStringLookup(final String field) throws FlamdexOutOfMemoryException {
    try {
        return FieldCacher.newStringValueLookup(field, this, directory);
    } catch (IOException e) {
        throw Throwables.propagate(e);
    }
}
 
Example 40
Source Project: activitystreams   Source File: GsonWrapper.java    License: Apache License 2.0 5 votes vote down vote up
/**
 * Method readAs.
 * @param in InputStream
 * @param type Class<? extends A>

 * @return A */
public <A extends ASObject>A readAs(InputStream in, Class<? extends A> type) {
  try {
    return readAs(new InputStreamReader(in, charset), type);
  } catch (Throwable t) {
    throw Throwables.propagate(t);
  }
}