Java Code Examples for com.google.common.base.Throwables#propagateIfInstanceOf()

The following examples show how to use com.google.common.base.Throwables#propagateIfInstanceOf() . 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 check out the related API usage on the sidebar.
Example 1
Source File: GcsServiceImpl.java    From appengine-gcs-client with Apache License 2.0 6 votes vote down vote up
@Override
public void update(final GcsFilename source, final GcsFileOptions fileOptions)
    throws IOException {
  try {
    RetryHelper.runWithRetries(new Callable<Void>() {
      @Override
      public Void call() throws IOException {
        long timeout = options.getRetryParams().getRequestTimeoutMillisForCurrentAttempt();
        raw.copyObject(source, source, fileOptions, timeout);
        return null;
      }
    }, options.getRetryParams(), exceptionHandler);
  } catch (RetryInterruptedException ex) {
    throw new ClosedByInterruptException();
  } catch (NonRetriableException e) {
    Throwables.propagateIfInstanceOf(e.getCause(), IOException.class);
    throw e;
  }
}
 
Example 2
Source File: ByteStreamUploader.java    From bazel with Apache License 2.0 6 votes vote down vote up
/**
 * Uploads a list of BLOBs concurrently to the remote {@code ByteStream} service. The call blocks
 * until the upload of all BLOBs is complete, or throws an {@link Exception} after the first
 * upload failed. Any other uploads will continue uploading in the background, until they complete
 * or the {@link #shutdown()} method is called. Errors encountered by these uploads are swallowed.
 *
 * <p>Uploads are retried according to the specified {@link RemoteRetrier}. Retrying is
 * transparent to the user of this API.
 *
 * <p>Trying to upload the same BLOB multiple times concurrently, results in only one upload being
 * performed. This is transparent to the user of this API.
 *
 * @param chunkers the data to upload.
 * @param forceUpload if {@code false} the blob is not uploaded if it has previously been
 *     uploaded, if {@code true} the blob is uploaded.
 * @throws IOException when reading of the {@link Chunker}s input source or uploading fails
 */
public void uploadBlobs(Map<HashCode, Chunker> chunkers, boolean forceUpload)
    throws IOException, InterruptedException {
  List<ListenableFuture<Void>> uploads = new ArrayList<>();

  for (Map.Entry<HashCode, Chunker> chunkerEntry : chunkers.entrySet()) {
    uploads.add(uploadBlobAsync(chunkerEntry.getKey(), chunkerEntry.getValue(), forceUpload));
  }

  try {
    for (ListenableFuture<Void> upload : uploads) {
      upload.get();
    }
  } catch (ExecutionException e) {
    Throwable cause = e.getCause();
    Throwables.propagateIfInstanceOf(cause, IOException.class);
    Throwables.propagateIfInstanceOf(cause, InterruptedException.class);
    Throwables.propagate(cause);
  }
}
 
Example 3
Source File: GcsOutputChannelImpl.java    From appengine-gcs-client with Apache License 2.0 6 votes vote down vote up
/**
 * Waits for the current outstanding request retrying it with exponential backoff if it fails.
 *
 * @throws ClosedByInterruptException if request was interrupted
 * @throws IOException In the event of FileNotFoundException, MalformedURLException
 * @throws RetriesExhaustedException if exceeding the number of retries
 */
private void waitForOutstandingRequest() throws IOException {
  if (outstandingRequest == null) {
    return;
  }
  try {
    RetryHelper.runWithRetries(new Callable<Void>() {
      @Override
      public Void call() throws IOException, InterruptedException {
        if (RetryHelper.getContext().getAttemptNumber() > 1) {
          outstandingRequest.retry();
        }
        token = outstandingRequest.waitForNextToken();
        outstandingRequest = null;
        return null;
      }
    }, retryParams, GcsServiceImpl.exceptionHandler);
  } catch (RetryInterruptedException ex) {
    token = null;
    throw new ClosedByInterruptException();
  } catch (NonRetriableException e) {
    Throwables.propagateIfInstanceOf(e.getCause(), IOException.class);
    throw e;
  }
}
 
Example 4
Source File: MapMaker.java    From codebuff with BSD 2-Clause "Simplified" License 6 votes vote down vote up
@SuppressWarnings("unchecked") // unsafe, which is one advantage of Cache over Map
@Override
public V get(Object key) {
  V value;
  try {
    value = getOrCompute((K) key);
  } catch (ExecutionException e) {
    Throwable cause = e.getCause();
    Throwables.propagateIfInstanceOf(cause, ComputationException.class);
    throw new ComputationException(cause);
  }
  if (value == null) {
    throw new NullPointerException(computingFunction + " returned null for key " + key + ".");
  }
  return value;
}
 
Example 5
Source File: BlockCompressedRecordFile.java    From lsmtree with Apache License 2.0 6 votes vote down vote up
public BlockCompressedRecordFile(final Supplier<? extends Either<IOException, ? extends RandomAccessDataInput>> inputSupplier, final Closeable closeable, String file, Serializer<E> serializer, CompressionCodec codec, BlockingQueue<Decompressor> decompressorPool, int blockSize, int recordIndexBits, int padBits, int maxChunkSize) throws IOException {
    this.inputSupplier = inputSupplier;
    this.file = file;
    this.serializer = serializer;
    this.codec = codec;
    this.blockSize = blockSize;
    this.padBits = padBits;
    this.maxChunkSize = maxChunkSize;
    pad = 1<<padBits;
    padMask = ~(long)(pad-1);
    shift = Math.max(recordIndexBits - padBits, 0);
    mask = (1L<<recordIndexBits)-1;
    closeableRef = SharedReference.create(closeable);
    try {
        blockCache = new BlockCache(decompressorPool);
    } catch (Throwable t) {
        Closeables2.closeQuietly(closeableRef, log);
        Throwables.propagateIfInstanceOf(t, IOException.class);
        throw Throwables.propagate(t);
    }
}
 
Example 6
Source File: AmqpTestConfiguration.java    From hawkbit with Eclipse Public License 1.0 6 votes vote down vote up
@Bean
ConnectionFactory rabbitConnectionFactory(final RabbitMqSetupService rabbitmqSetupService) {
    final CachingConnectionFactory factory = new CachingConnectionFactory();
    factory.setHost(rabbitmqSetupService.getHostname());
    factory.setPort(5672);
    factory.setUsername(rabbitmqSetupService.getUsername());
    factory.setPassword(rabbitmqSetupService.getPassword());
    try {
        factory.setVirtualHost(rabbitmqSetupService.createVirtualHost());
        // All exception are catched. The BrokerRunning decide if the
        // test should break or not
    } catch (@SuppressWarnings("squid:S2221") final Exception e) {
        Throwables.propagateIfInstanceOf(e, AlivenessException.class);
        LOG.error("Cannot create virtual host.", e);
    }
    return factory;
}
 
Example 7
Source File: ShardWorkerContext.java    From bazel-buildfarm with Apache License 2.0 6 votes vote down vote up
private void insertFile(Digest digest, Path file) throws IOException, InterruptedException {
  Write write =
      execFileSystem
          .getStorage()
          .getWrite(digest, UUID.randomUUID(), RequestMetadata.getDefaultInstance());
  try (OutputStream out = write.getOutput(deadlineAfter, deadlineAfterUnits, () -> {});
      InputStream in = Files.newInputStream(file)) {
    ByteStreams.copy(in, out);
  } catch (IOException e) {
    // complete writes should be ignored
    if (!write.isComplete()) {
      write.reset(); // we will not attempt retry with current behavior, abandon progress
      if (e.getCause() != null) {
        Throwables.propagateIfInstanceOf(e.getCause(), InterruptedException.class);
      }
      throw e;
    }
  }
}
 
Example 8
Source File: ServerLifeCycleManager.java    From digdag with Apache License 2.0 5 votes vote down vote up
private static void invokeMethods(Object obj, List<Method> methods)
    throws Exception
{
    for (Method method : methods) {
        try {
            method.invoke(obj);
        }
        catch (InvocationTargetException ex) {
            Throwable cause = ex.getCause();
            Throwables.propagateIfPossible(cause);
            Throwables.propagateIfInstanceOf(cause, Exception.class);
            throw Throwables.propagate(cause);
        }
    }
}
 
Example 9
Source File: DatabaseTestingUtils.java    From digdag with Apache License 2.0 5 votes vote down vote up
public static <X extends Throwable> void propagateOnly(Class<X> declaredType, Propagator r)
    throws X
{
    try {
        r.run();
    }
    catch (Exception ex) {
        Throwables.propagateIfInstanceOf((Throwable) ex, declaredType);
        throw Throwables.propagate(ex);
    }
}
 
Example 10
Source File: GCMEncryptor.java    From keywhiz with 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 11
Source File: ShardWorkerInstanceTest.java    From bazel-buildfarm with Apache License 2.0 5 votes vote down vote up
@Test(expected = UnsupportedOperationException.class)
public void getActionResultIsUnsupported() throws InterruptedException {
  try {
    instance.getActionResult(null, null).get();
  } catch (ExecutionException e) {
    Throwable cause = e.getCause();
    Throwables.propagateIfInstanceOf(cause, RuntimeException.class);
    throw new RuntimeException(cause);
  }
}
 
Example 12
Source File: InputFormatImportCommand.java    From kite with Apache License 2.0 5 votes vote down vote up
/**
 * Runs a task with the given {@link ClassLoader} as the context loader.
 *
 * @param task a {@link TransformTask}
 * @param loader a {@link ClassLoader}
 * @return the result of {@link TransformTask#run}
 * @throws IOException if the task throws an IOException
 * @throws InterruptedException if the task execution is interrupted
 */
private static PipelineResult runTaskWithClassLoader(
    final TransformTask task, final ClassLoader loader)
    throws IOException, InterruptedException {
  RunnableFuture<PipelineResult> future = new FutureTask<PipelineResult>(
      new Callable<PipelineResult>() {
        @Override
        public PipelineResult call() throws Exception {
          return task.run();
        }
      });

  Executors.newSingleThreadExecutor(
      new ThreadFactory() {
        @Override
        public Thread newThread(Runnable r) {
          Thread taskThread = new Thread(r, "transform-task");
          taskThread.setContextClassLoader(loader);
          return taskThread;
        }
      }).execute(future);

  try {
    return future.get();
  } catch (ExecutionException e) {
    Throwables.propagateIfInstanceOf(e.getCause(), IOException.class);
    throw Throwables.propagate(e.getCause());
  }
}
 
Example 13
Source File: PrestoMap.java    From transport with BSD 2-Clause "Simplified" License 5 votes vote down vote up
private int seekKey(Object key) {
  for (int i = 0; i < _block.getPositionCount(); i += 2) {
    try {
      if ((boolean) _keyEqualsMethod.invoke(readNativeValue(_keyType, _block, i), key)) {
        return i + 1;
      }
    } catch (Throwable t) {
      Throwables.propagateIfInstanceOf(t, Error.class);
      Throwables.propagateIfInstanceOf(t, PrestoException.class);
      throw new PrestoException(GENERIC_INTERNAL_ERROR, t);
    }
  }
  return -1;
}
 
Example 14
Source File: RestDataspaceImpl.java    From scheduling with GNU Affero General Public License v3.0 5 votes vote down vote up
public void writeFile(InputStream inputStream, FileObject outputFile, String encoding)
        throws FileSystemException, IOException {
    try {
        if (outputFile.exists()) {
            outputFile.delete(SELECT_SELF);
        }
        if (Strings.isNullOrEmpty(encoding)) {
            outputFile.createFile();
            logger.debug("Writing single file " + outputFile);
            FileSystem.copy(inputStream, outputFile);
        } else if ("gzip".equals(encoding)) {
            logger.debug("Expanding gzip archive into " + outputFile);
            VFSZipper.GZIP.unzip(inputStream, outputFile);
        } else if ("zip".equals(encoding)) {
            logger.debug("Expanding zip archive into " + outputFile);
            VFSZipper.ZIP.unzip(inputStream, outputFile);
        } else {
            logger.debug("Writing single file " + outputFile);
            outputFile.createFile();
            FileSystem.copy(inputStream, outputFile);
        }
    } catch (Throwable error) {
        if (outputFile != null) {
            try {
                if (outputFile.exists()) {
                    outputFile.delete(SELECT_SELF);
                }
            } catch (FileSystemException e1) {
                logger.error("Error occurred while deleting partially created file.", e1);
            }
        }
        Throwables.propagateIfInstanceOf(error, FileSystemException.class);
        Throwables.propagateIfInstanceOf(error, IOException.class);
        Throwables.propagate(error);
    }
}
 
Example 15
Source File: DremioDatabaseMetaDataImpl.java    From dremio-oss with Apache License 2.0 5 votes vote down vote up
@Override
public ResultSet getCatalogs() throws SQLException {
  throwIfClosed();
  try {
    return super.getCatalogs();
  } catch(SQLExecutionError e) {
    Throwables.propagateIfInstanceOf(e.getCause(), SQLException.class);
    throw e;
  }
}
 
Example 16
Source File: CoreStoreProviderImpl.java    From dremio-oss with Apache License 2.0 5 votes vote down vote up
/**
 * Build a common base CoreKVStore then delegates the final build steps to the StoreAssembler.
 * Also, adds the final store to the CoreStore provider's registry.
 * @param assembler Converts the base CoreKvStore into its final form.
 * @param <STORE> Final CoreKVStore type. Could be indexed or not indexed.
 * @return STORE returned by assembler.
 */
private <STORE extends CoreKVStore<K, V>> STORE build(StoreAssembler<K, V, STORE> assembler) {
  try{

    final KVStoreInfo kvStoreInfo = helper.getKVStoreInfo();

    // Stores are created sequentially.
    // If the store is not present at the start of load, there is no duplication.
    if (idToStore.containsKey(kvStoreInfo.getTablename())) {
      throw new DatastoreFatalException("Duplicate datastore " + kvStoreInfo.toString());
    }

    final Serializer<K, byte[]> keySerializer = (Serializer<K, byte[]>) helper.getKeyFormat().apply(ByteSerializerFactory.INSTANCE);
    final Serializer<V, byte[]> valueSerializer = (Serializer<V, byte[]>) helper.getValueFormat().apply(ByteSerializerFactory.INSTANCE);

    // write table's configuration to a file first
    if (!inMemory) {
      createMetaDataFile(kvStoreInfo);
    }

    final ByteStore rawStore = byteManager.getStore(kvStoreInfo.getTablename());

    CoreKVStore<K, V> coreKVStore =
      new CoreKVStoreImpl<>(
        rawStore,
        keySerializer,
        valueSerializer);

    final STORE store = assembler.run(coreKVStore);
    final StoreWithId<K, V> storeWithId = new StoreWithId<>(helper, store);

    idToStore.put(storeWithId.id, storeWithId);
    return store;
  } catch (Exception ex) {
    Throwables.propagateIfInstanceOf(ex.getCause(), DatastoreException.class);
    throw new DatastoreException(ex);
  }
}
 
Example 17
Source File: WorkflowExecutor.java    From digdag with Apache License 2.0 5 votes vote down vote up
public <T> T submitTransaction(int siteId, WorkflowSubmitterAction<T> func)
    throws ResourceNotFoundException, AttemptLimitExceededException, SessionAttemptConflictException
{
    try {
        return sm.getSessionStore(siteId).sessionTransaction((transaction) -> {
            return func.call(new WorkflowSubmitter(siteId, transaction, rm.getProjectStore(siteId), sm.getSessionStore(siteId), tm));
        });
    }
    catch (Exception ex) {
        Throwables.propagateIfInstanceOf(ex, ResourceNotFoundException.class);
        Throwables.propagateIfInstanceOf(ex, AttemptLimitExceededException.class);
        Throwables.propagateIfInstanceOf(ex, SessionAttemptConflictException.class);
        throw Throwables.propagate(ex);
    }
}
 
Example 18
Source File: Throwables2.java    From util with Apache License 2.0 4 votes vote down vote up
public static <X extends Throwable> RuntimeException propagate(Throwable t, Class<X> xClass) throws X {
    Throwables.propagateIfInstanceOf(t, xClass);
    throw Throwables.propagate(t);
}
 
Example 19
Source File: DatasetSink.java    From kite with Apache License 2.0 4 votes vote down vote up
@Override
public Status process() throws EventDeliveryException {
  if (writer == null) {
    try {
      this.writer = newWriter(login, target);
    } catch (DatasetException e) {
      // DatasetException includes DatasetNotFoundException
      throw new EventDeliveryException(
          "Cannot write to " + getName(), e);
    }
  }

  // handle file rolling
  if ((System.currentTimeMillis() - lastRolledMs) / 1000 > rollIntervalS) {
    // close the current writer and get a new one
    writer.close();
    this.writer = newWriter(login, target);
    this.lastRolledMs = System.currentTimeMillis();
    LOG.info("Rolled writer for " + getName());
  }

  Channel channel = getChannel();
  Transaction transaction = null;
  try {
    long processedEvents = 0;

    transaction = channel.getTransaction();
    transaction.begin();
    for (; processedEvents < batchSize; processedEvents += 1) {
      Event event = channel.take();
      if (event == null) {
        // no events available in the channel
        break;
      }

      this.datum = deserialize(event, reuseDatum ? datum : null);

      // writeEncoded would be an optimization in some cases, but HBase
      // will not support it and partitioned Datasets need to get partition
      // info from the entity Object. We may be able to avoid the
      // serialization round-trip otherwise.
      writer.write(datum);
    }

    // TODO: Add option to sync, depends on CDK-203
    if (writer instanceof Flushable) {
      ((Flushable) writer).flush();
    }

    // commit after data has been written and flushed
    transaction.commit();

    if (processedEvents == 0) {
      counter.incrementBatchEmptyCount();
      return Status.BACKOFF;
    } else if (processedEvents < batchSize) {
      counter.incrementBatchUnderflowCount();
    } else {
      counter.incrementBatchCompleteCount();
    }

    counter.addToEventDrainSuccessCount(processedEvents);

    return Status.READY;

  } catch (Throwable th) {
    // catch-all for any unhandled Throwable so that the transaction is
    // correctly rolled back.
    if (transaction != null) {
      try {
        transaction.rollback();
      } catch (Exception ex) {
        LOG.error("Transaction rollback failed", ex);
        throw Throwables.propagate(ex);
      }
    }

    // close the writer and remove the its reference
    writer.close();
    this.writer = null;
    this.lastRolledMs = System.currentTimeMillis();

    // handle the exception
    Throwables.propagateIfInstanceOf(th, Error.class);
    Throwables.propagateIfInstanceOf(th, EventDeliveryException.class);
    throw new EventDeliveryException(th);

  } finally {
    if (transaction != null) {
      transaction.close();
    }
  }
}
 
Example 20
Source File: Throwables2.java    From util with Apache License 2.0 4 votes vote down vote up
public static <X1 extends Throwable, X2 extends Throwable, X3 extends Throwable> RuntimeException propagate(Throwable t, Class<X1> x1Class, Class<X2> x2Class, Class<X3> x3Class) throws X1, X2, X3 {
    Throwables.propagateIfInstanceOf(t, x1Class);
    Throwables.propagateIfInstanceOf(t, x2Class);
    Throwables.propagateIfInstanceOf(t, x3Class);
    throw Throwables.propagate(t);
}