Java com.google.common.util.concurrent.UncheckedExecutionException 代码实例

・13 分钟阅读

以下是展示如何使用com.google.common.util.concurrent.UncheckedExecutionException的最佳示例。 我们使用了代码质量辨别算法从开源项目中提取出了最佳的优秀示例。

实例 1


@Override
public void write(E entity) {
  Preconditions.checkState(state.equals(ReaderWriterState.OPEN),
      "Attempt to write to a writer in state:%s", state);
  reusedKey.reuseFor(entity);
  DatasetWriter<E> writer = cachedWriters.getIfPresent(reusedKey);
  if (writer == null) {
    // get a new key because it is stored in the cache
    StorageKey key = StorageKey.copy(reusedKey);
    try {
      writer = cachedWriters.getUnchecked(key);
    } catch (UncheckedExecutionException ex) {
      // catch & release: the correct exception is that the entity cannot be
      // written because it isn't in the View. But to avoid checking in every
      // write call, check when writers are created, catch the exception, and
      // throw the correct one here.
      throw new IllegalArgumentException(
          "View does not contain entity:" + entity, ex.getCause());
    }
  }
  writer.write(entity);
}
 

实例 2


static
public <K extends PMMLObject, V> V getValue(K key, LoadingCache<K, V> cache){
        try {
                return cache.get(key);
        } catch(ExecutionException ee){
                throw new InvalidFeatureException(key);
        } catch(UncheckedExecutionException uee){
                Throwable cause = uee.getCause();
                if(cause instanceof PMMLException){
                        throw (PMMLException)cause;
                }
                throw new InvalidFeatureException(key);
        }
}
 

实例 3


@Override
protected void startUp() throws Exception {
  Throwable failureCause = null;
  for (Service service : services) {
    try {
      service.startAndWait();
    } catch (UncheckedExecutionException e) {
      failureCause = e.getCause();
      break;
    }
  }
  if (failureCause != null) {
    // Stop all running services and then throw the failure exception
    try {
      stopAll();
    } catch (Throwable t) {
      // Ignore the stop error. Just log.
      LOG.warn("Failed when stopping all services on start failure", t);
    }
    Throwables.propagateIfPossible(failureCause, Exception.class);
    throw new RuntimeException(failureCause);
  }
}
 

实例 4


@Override
public T get(Locale language)
        throws ConfigurationException {
    if (language == null) {
        this.lock.readLock().lock();
        try {
            return this.nullLocale;
        } finally {
            this.lock.readLock().unlock();
        }
    } else {
        try {
            return this.cache.getUnchecked(language);
        } catch (UncheckedExecutionException ex) {
            if (ex.getCause() instanceof ConfigurationException) {
                throw (ConfigurationException) ex.getCause();
            } else {
                throw ex;
            }
        }
    }
}
 

实例 5


@Override
public Archetype getFlatArchetype(String archetypeId) {
    try {
        return flatArchetypeCache.getUnchecked(archetypeId);
    } catch (UncheckedExecutionException e) {
        if (e.getCause() instanceof RuntimeException) {
            throw (RuntimeException) e.getCause();
        }
        throw e;
    }
}
 

实例 6


private static <K,V> V getOrRethrow(final LoadingCache<K, V> cache, final K key) {
    try {
        return cache.getUnchecked(key);
    } catch (final UncheckedExecutionException e) {
        final Throwable cause = e.getCause();
        if(cause != null) {
            Throwables.propagateIfPossible(cause);
        }
        throw e;
    }
}
 

实例 7


@Override
protected void importData(final ProgressCallback<ImportStatus> progressionCallback, String... additionalsArgs) throws Exception {
    ResultSet res = null;
    boolean tableFound = true;
    boolean banHammerOnMysql = true;
    try (Connection conn = BAT.getConnection()) {
        // Check if the bungee suite tables are here
        final DatabaseMetaData dbm = conn.getMetaData();
        for(final String table : Arrays.asList("banhammer_bans", "banhammer_players")){
            final ResultSet tables = dbm.getTables(null, null, table, null);
            if (!tables.next()) {
                tableFound = false;
            }
        }
        // If mysql is on and the table weren't found, try to look for a banhammer.db file
        if(tableFound == false){
            banHammerOnMysql = false;
            if(new File(BAT.getInstance().getDataFolder(), "banhammer.db").exists()){
                progressionCallback.onMinorError("The SQLite Driver must be downloaded. The server may freeze during the download.");
                if(BAT.getInstance().loadSQLiteDriver()){
                    tableFound = true;
                }
            }else{
                throw new RuntimeException("No BanHammer tables was found in the MySQL database. "
                        + "If you used a .db file with BanHammer, please put your file into BAT folder and rename it 'banhammer.db'");
            }
        }
        progressionCallback.onMinorError("Starting importing data from " 
                + ((banHammerOnMysql) ? "mysql" : "sqlite") + " database banhammer.");
        if(tableFound){
            try(Connection connBH = (banHammerOnMysql) 
                    ? conn
                    : DriverManager.getConnection("jdbc:sqlite:" + BAT.getInstance().getDataFolder().getAbsolutePath() + File.separator
                            + "banhammer.db");){
                // Count the number of entries (use to show the progression)
                final ResultSet resCount = connBH.prepareStatement("SELECT  " + (banHammerOnMysql ? "count()" : "COUNT(*)") + " FROM banhammer_bans;"
                    ).executeQuery();
                if(resCount.next()){
                    status = new ImportStatus(resCount.getInt(banHammerOnMysql ? "count()" : "COUNT(*)"));
                }
                final PreparedStatement insertBans = conn.prepareStatement("INSERT INTO `" + SQLQueries.Ban.table
                    + "`(UUID, ban_ip, ban_staff, ban_server, ban_begin, ban_end, ban_reason, ban_state,"
                    + "ban_unbandate, ban_unbanstaff, ban_unbanreason) "
                    + "VALUES (?, null, ?, ?, ?, ?, ?, ?, ?, "
                    + "'Unspecified:BanHammer import', 'Unspecified:BanHammer import');");
                res = banHammerOnMysql 
                        ? connBH.createStatement().executeQuery("SELECT bans.*, (SELECT players.name FROM banhammer_players players " +
                            "WHERE bans.player_id = players.id) as player, (SELECT players.name FROM banhammer_players players " +
                            "WHERE bans.creator_id = players.id) as staff FROM banhammer_bans bans;")
                        : connBH.createStatement().executeQuery("SELECT *, strftime('%s',created_at), strftime('%s',expires_at), " +
                            "(SELECT players.name FROM banhammer_players players WHERE bans.player_id = players.id) as player, " +
                            "(SELECT players.name FROM banhammer_players players WHERE bans.creator_id = players.id) as staff " +
                            " FROM banhammer_bans bans;");
                int uncomittedEntries = 0;
                conn.setAutoCommit(false);
                while (res.next()) {
                    final String pName = res.getString("player");
                    final String server = IModule.GLOBAL_SERVER;
                    final String staff = res.getString("staff");
                    final String reason = res.getString("reason");
                    final Timestamp ban_begin = res.getTimestamp("created_at");
                    final Timestamp ban_end = res.getTimestamp("expires_at");
                    final int bhState = res.getInt("state");
                    // Sometimes for unknown reason a timestamp get a wrong value (year < 1970)
                    if(ban_end != null && ban_end.getTime() < 0){
                        continue;
                    }
                    // Get UUID
                    String UUID;
                    try{
                        UUID = uuidCache.get(pName);
                    }catch (final UncheckedExecutionException e) {
                        if(e.getCause() instanceof UUIDNotFoundException){
                            continue;
                        }else{
                            throw e;
                        }
                    }
                    // Insert the ban
                    insertBans.setString(1, UUID);
                    insertBans.setString(2, staff);
                    insertBans.setString(3, server);
                    insertBans.setTimestamp(4, ban_begin);
                    insertBans.setTimestamp(5, ban_end);
                    insertBans.setString(6, reason);
                    boolean state;
                    if(ban_end != null){
                        if(ban_end.getTime() > System.currentTimeMillis() && bhState == 0){
                            state = true;
                            insertBans.setTimestamp(8, null);
                        }else{
                            state = false;
                            insertBans.setTimestamp(8, ban_end);
                        }
                    }else{
                        state = (bhState == 0) ? true : false;
                        insertBans.setTimestamp(8, null);
                    }
                    insertBans.setBoolean(7, state);
                    insertBans.execute();
                    insertBans.clearParameters();
                    uncomittedEntries++;
                    if(UUID != null){
                        initPlayerRowInBatPlayer(conn, pName, UUID);
                    }
                    if(uncomittedEntries % 100 == 0){
                        conn.commit();
                        status.incrementConvertedEntries(uncomittedEntries);
                        uncomittedEntries = 0;
                        progressionCallback.onProgress(status);
                    }
                }
                conn.commit();
                status.incrementConvertedEntries(uncomittedEntries);
                progressionCallback.done(status, null);
            }finally{
                if(res != null){
                    DataSourceHandler.close(res);
                }
            }
    }
    }
}
 
讨论
淘淘あ西西 profile image