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
@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 Project: Elasticsearch   File: BlobShard.java    License: 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 Project: Elasticsearch   File: ArrayMapper.java    License: 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 4
Source Project: dk-fitting   File: ElasticsearchSchema.java    License: 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 5
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 6
Source Project: incubator-gobblin   File: SleepingTask.java    License: 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 7
Source Project: ipmi4j   File: Ipmi20SessionWrapper.java    License: 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 8
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 9
protected G createGenerator()
{
  try {
    return generatorClass.newInstance();
  } catch (Exception e) {
    throw Throwables.propagate(e);
  }
}
 
Example 10
Source Project: datacollector   File: MysqlBinLogSource.java    License: 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 11
Source Project: metacat   File: ConnectorUtils.java    License: 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 12
@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 13
Source Project: digdag   File: TDOperator.java    License: 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 Project: iceberg   File: DynFields.java    License: 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 15
Source Project: emodb   File: SimpleLifeCycleRegistry.java    License: 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 16
Source Project: kafkameter   File: LoadGenerator.java    License: 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 17
Source Project: digdag   File: ServerJmxIT.java    License: 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 18
Source Project: emodb   File: MessageSerializer.java    License: 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 19
Source Project: Kafdrop   File: CuratorKafkaMonitor.java    License: 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
@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);
    }
}