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

The following examples show how to use com.google.common.base.Throwables#propagate() . 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: YarnAppLauncherImpl.java    From attic-apex-core with Apache License 2.0 6 votes vote down vote up
@Override
public boolean isFinished()
{
  try {
    ApplicationReport appReport = yarnClient.getApplicationReport(appId);
    if (appReport != null) {
      if (appReport.getFinalApplicationStatus() == null
          || appReport.getFinalApplicationStatus() == FinalApplicationStatus.UNDEFINED) {
        return false;
      }
    }
    return true;
  } catch (YarnException | IOException e) {
    throw Throwables.propagate(e);
  }
}
 
Example 2
Source File: BlobShard.java    From Elasticsearch with Apache License 2.0 6 votes vote down vote up
public BlobStats blobStats() {
    final BlobStats stats = new BlobStats();

    stats.location(blobContainer().getBaseDirectory().getAbsolutePath());
    try {
        blobContainer().walkFiles(null, new BlobContainer.FileVisitor() {
            @Override
            public boolean visit(File file) {
                stats.totalUsage(stats.totalUsage() + file.length());
                stats.count(stats.count() + 1);
                return true;
            }
        });
    } catch (IOException e) {
        logger.error("error getting blob stats", e);
        Throwables.propagate(e);
    }
    return stats;
}
 
Example 3
Source File: SleepingTask.java    From incubator-gobblin with Apache License 2.0 6 votes vote down vote up
public SleepingTask(TaskContext taskContext) {
  super(taskContext);
  TaskState taskState = taskContext.getTaskState();
  sleepTime = taskState.getPropAsLong(SLEEP_TIME_IN_SECONDS, 10L);
  taskStateFile = new File(taskState.getProp(TASK_STATE_FILE_KEY));
  try {
    if (taskStateFile.exists()) {
      if (!taskStateFile.delete()) {
        log.error("Unable to delete {}", taskStateFile);
        throw new IOException("File Delete Exception");
      }
    } else {
      Files.createParentDirs(taskStateFile);
    }
  } catch (IOException e) {
    log.error("Unable to create directory: ", taskStateFile.getParent());
    Throwables.propagate(e);
  }
  taskStateFile.deleteOnExit();
}
 
Example 4
Source File: KinesisTableDescriptionSupplier.java    From presto-kinesis with Apache License 2.0 6 votes vote down vote up
private static List<Path> listFiles(Path dir)
{
    if ((dir != null) && Files.isDirectory(dir)) {
        try (DirectoryStream<Path> stream = Files.newDirectoryStream(dir)) {
            ImmutableList.Builder<Path> builder = ImmutableList.builder();
            for (Path file : stream) {
                builder.add(file);
            }

            return builder.build();
        }
        catch (IOException | DirectoryIteratorException x) {
            log.warn(x, "Warning.");
            throw Throwables.propagate(x);
        }
    }
    return ImmutableList.of();
}
 
Example 5
Source File: ElasticsearchSchema.java    From dk-fitting with Apache License 2.0 6 votes vote down vote up
@Override
protected Map<String, Table> getTableMap() {
    final ImmutableMap.Builder<String, Table> builder = ImmutableMap.builder();

    try {
        GetMappingsResponse response = client.admin().indices().getMappings(
                new GetMappingsRequest().indices(index)).get();
        ImmutableOpenMap<String, MappingMetaData> mapping = response.getMappings().get(index);
        for (ObjectObjectCursor<String, MappingMetaData> c: mapping) {
            builder.put(c.key, new ElasticsearchTable(client, index, c.key));
        }
    } catch (Exception e) {
        throw Throwables.propagate(e);
    }
    return builder.build();
}
 
Example 6
Source File: ArrayMapper.java    From Elasticsearch with Apache License 2.0 6 votes vote down vote up
public Mapper create(String name, ObjectMapper parentMapper, ParseContext context) {
    BuilderContext builderContext = new BuilderContext(context.indexSettings(), context.path());
    try {
        Mapper.Builder<?, ?> innerBuilder = detectInnerMapper(context, name, context.parser());
        if (innerBuilder == null) {
            return null;
        }
        Mapper mapper = innerBuilder.build(builderContext);
        mapper = DocumentParser.parseAndMergeUpdate(mapper, context);
        MappedFieldType mappedFieldType = newArrayFieldType(innerBuilder);
        String fullName = context.path().fullPathAsText(name);
        mappedFieldType.setNames(new MappedFieldType.Names(fullName));
        return new ArrayMapper(
                name,
                mappedFieldType,
                mappedFieldType.clone(),
                context.indexSettings(),
                MultiFields.empty(),
                null,
                mapper);
    } catch (IOException e) {
        throw Throwables.propagate(e);
    }
}
 
Example 7
Source File: CacheUtils.java    From ProjectAres with GNU Affero General Public License v3.0 5 votes vote down vote up
static <K, V> V getUnchecked(Cache<K, V> cache, K key, Supplier<V> supplier) {
    try {
        return cache.get(key, supplier::get);
    } catch(ExecutionException e) {
        throw Throwables.propagate(e);
    }
}
 
Example 8
Source File: MessageSerializer.java    From emodb with Apache License 2.0 5 votes vote down vote up
static ByteBuffer toByteBuffer(Object json) {
    try {
        return ByteBuffer.wrap(JSON.writeValueAsBytes(json));
    } catch (IOException e) {
        // Shouldn't get I/O errors writing to a byte buffer.
        throw Throwables.propagate(e);
    }
}
 
Example 9
Source File: ServerJmxIT.java    From digdag with Apache License 2.0 5 votes vote down vote up
private static JMXConnector connectJmx(TemporaryDigdagServer server)
    throws IOException
{
    Matcher matcher = JMX_PORT_PATTERN.matcher(server.outUtf8());
    assertThat(matcher.find(), is(true));
    int port = Integer.parseInt(matcher.group(1));

    try {
        JMXServiceURL url = new JMXServiceURL("service:jmx:rmi:///jndi/rmi://:" + port + "/jmxrmi");
        return JMXConnectorFactory.connect(url, null);
    }
    catch (MalformedURLException ex) {
        throw Throwables.propagate(ex);
    }
}
 
Example 10
Source File: LoadGenerator.java    From kafkameter with Apache License 2.0 5 votes vote down vote up
private SyntheticLoadGenerator createGenerator(String className, @Nullable String config) {
  try {
    return (SyntheticLoadGenerator) Class.forName(
        className, false, Thread.currentThread().getContextClassLoader()
    ).getConstructor(String.class).newInstance(config);
  } catch (Exception e) {
    log.fatalError("Exception initializing Load Generator class: " + className, e);
    throw Throwables.propagate(e);
  }
}
 
Example 11
Source File: SimpleLifeCycleRegistry.java    From emodb with Apache License 2.0 5 votes vote down vote up
@Override
public void close() throws IOException {
    try {
        stop();
    } catch (Exception e) {
        Throwables.propagateIfInstanceOf(e, IOException.class);
        throw Throwables.propagate(e);
    }
}
 
Example 12
Source File: DynFields.java    From iceberg with Apache License 2.0 5 votes vote down vote up
@SuppressWarnings("unchecked")
public T get(Object target) {
  try {
    return (T) field.get(target);
  } catch (IllegalAccessException e) {
    throw Throwables.propagate(e);
  }
}
 
Example 13
Source File: TDOperator.java    From digdag with Apache License 2.0 5 votes vote down vote up
public void ensureDatabaseDeleted(String name)
        throws TDClientException
{
    try {
        defaultRetryExecutor.run(() -> client.deleteDatabase(name));
    }
    catch (RetryGiveupException ex) {
        if (ex.getCause() instanceof TDClientHttpNotFoundException) {
            // ignore
            return;
        }
        throw Throwables.propagate(ex.getCause());
    }
}
 
Example 14
Source File: DockerImageCleanupFileCallable.java    From yet-another-docker-plugin with MIT License 5 votes vote down vote up
@Override
public Void invoke(File f, VirtualChannel channel) throws IOException, InterruptedException {
    PrintStream llog = taskListener.getLogger();
    llog.println("Creating connection to docker daemon...");
    try (DockerClient client = connector.getClient()) {
        return invoke(client);
    } catch (Exception ex) {
        Throwables.propagate(ex);
    }

    return null;
}
 
Example 15
Source File: ConnectorUtils.java    From metacat with Apache License 2.0 5 votes vote down vote up
private static <S extends ConnectorBaseService> Class<? extends S> getServiceClass(
    final String className,
    final Class<? extends S> baseClass
) {
    try {
        return Class.forName(className).asSubclass(baseClass);
    } catch (final ClassNotFoundException cnfe) {
        throw Throwables.propagate(cnfe);
    }
}
 
Example 16
Source File: MysqlBinLogSource.java    From datacollector with Apache License 2.0 5 votes vote down vote up
private boolean isGtidEnabled() {
  try {
    return VAR_GTID_MODE_ON.equals(Util.getGlobalVariable(dataSource, VAR_GTID_MODE));
  } catch (SQLException e) {
    throw Throwables.propagate(e);
  }
}
 
Example 17
Source File: AbstractWindowedOperatorBenchmarkApp.java    From attic-apex-malhar with Apache License 2.0 5 votes vote down vote up
protected G createGenerator()
{
  try {
    return generatorClass.newInstance();
  } catch (Exception e) {
    throw Throwables.propagate(e);
  }
}
 
Example 18
Source File: Ipmi20SessionWrapper.java    From ipmi4j with Apache License 2.0 5 votes vote down vote up
@Override
public int getWireLength(IpmiPacketContext context) {
    try {
        @CheckForNull
        IpmiSession session = context.getIpmiSession(getIpmiSessionId());

        IpmiConfidentialityAlgorithm confidentialityAlgorithm = getConfidentialityAlgorithm(session);
        IpmiIntegrityAlgorithm integrityAlgorithm = getIntegrityAlgorithm(session);

        IpmiPayload payload = getIpmiPayload();

        boolean oem = IpmiPayloadType.OEM_EXPLICIT.equals(payload.getPayloadType());
        int unencryptedLength = payload.getWireLength(context);
        int encryptedLength = confidentialityAlgorithm.getEncryptedLength(session, unencryptedLength);
        int integrityLength = (session == null)
                ? 0
                : IntegrityPad.PAD(encryptedLength).length
                + 1 // pad length
                + 1 // next header
                + integrityAlgorithm.getMacLength();
        return 1 // authenticationType
                + 1 // payloadType
                + (oem ? 4 : 0) // oemEnterpriseNumber
                + (oem ? 2 : 0) // oemPayloadId
                + 4 // ipmiSessionId
                + 4 // ipmiSessionSequenceNumber
                + 2 // payloadLength
                + encryptedLength
                + integrityLength;
    } catch (NoSuchAlgorithmException e) {
        throw Throwables.propagate(e);
    }
}
 
Example 19
Source File: CuratorKafkaMonitor.java    From Kafdrop with Apache License 2.0 4 votes vote down vote up
public TopicVO parseZkTopic(ChildData input)
{
   try
   {
      final TopicVO topic = new TopicVO(StringUtils.substringAfterLast(input.getPath(), "/"));

      final TopicRegistrationVO topicRegistration =
         objectMapper.reader(TopicRegistrationVO.class).readValue(input.getData());

      topic.setConfig(
         Optional.ofNullable(topicConfigPathCache.getCurrentData(ZkUtils.TopicConfigPath() + "/" + topic.getName()))
            .map(this::readTopicConfig)
            .orElse(Collections.emptyMap()));

      for (Map.Entry<Integer, List<Integer>> entry : topicRegistration.getReplicas().entrySet())
      {
         final int partitionId = entry.getKey();
         final List<Integer> partitionBrokerIds = entry.getValue();

         final TopicPartitionVO partition = new TopicPartitionVO(partitionId);

         final Optional<TopicPartitionStateVO> partitionState = partitionState(topic.getName(), partition.getId());

         partitionBrokerIds.stream()
            .map(brokerId -> {
               TopicPartitionVO.PartitionReplica replica = new TopicPartitionVO.PartitionReplica();
               replica.setId(brokerId);
               replica.setInService(partitionState.map(ps -> ps.getIsr().contains(brokerId)).orElse(false));
               replica.setLeader(partitionState.map(ps -> brokerId == ps.getLeader()).orElse(false));
               return replica;
            })
            .forEach(partition::addReplica);

         topic.addPartition(partition);
      }

      // todo: get partition sizes here as single bulk request?

      return topic;
   }
   catch (IOException e)
   {
      throw Throwables.propagate(e);
   }
}
 
Example 20
Source File: InfluxDbSenderProvider.java    From graylog-plugin-metrics-reporter with GNU General Public License v3.0 4 votes vote down vote up
@Override
public InfluxDbSender get() {
    try {
        final URI uri = configuration.getUri().parseServerAuthority();

        final String protocol = uri.getScheme().toLowerCase(Locale.ENGLISH);
        final String host = uri.getHost();
        final int port = uri.getPort();
        final String database = uri.getPath().replace("/", "");
        if (!Pattern.matches("[a-z][a-z0-9_]*", database)) {
            throw new IllegalArgumentException("Invalid database name \"" + database + "\"");
        }

        final int socketTimeout = Ints.saturatedCast(configuration.getSocketTimeout().toMilliseconds());
        final int connectTimeout = Ints.saturatedCast(configuration.getConnectTimeout().toMilliseconds());
        final int readTimeout = Ints.saturatedCast(configuration.getReadTimeout().toMilliseconds());

        final TimeUnit timePrecision = configuration.getTimePrecision();

        switch (protocol) {
            case "http":
            case "https":
                return new InfluxDbHttpSender(
                        protocol,
                        host,
                        port,
                        database,
                        uri.getUserInfo(),
                        timePrecision,
                        connectTimeout,
                        readTimeout,
                        "");
            case "tcp":
                return new InfluxDbTcpSender(
                        host,
                        port,
                        socketTimeout,
                        database,
                        "");
            case "udp":
                return new InfluxDbUdpSender(
                        host,
                        port,
                        socketTimeout,
                        database,
                        "");
            default:
                throw new IllegalArgumentException("Unsupported protocol \"" + protocol + "\"");
        }
    } catch (Exception e) {
        throw Throwables.propagate(e);
    }
}