当前位置: 首页>>代码示例>>Java>>正文


Java Deferred.fromError方法代码示例

本文整理汇总了Java中com.stumbleupon.async.Deferred.fromError方法的典型用法代码示例。如果您正苦于以下问题:Java Deferred.fromError方法的具体用法?Java Deferred.fromError怎么用?Java Deferred.fromError使用的例子?那么恭喜您, 这里精选的方法代码示例或许可以为您提供帮助。您也可以进一步了解该方法所在com.stumbleupon.async.Deferred的用法示例。


在下文中一共展示了Deferred.fromError方法的10个代码示例,这些例子默认根据受欢迎程度排序。您可以为喜欢或者感觉有用的代码点赞,您的评价将有助于系统推荐出更棒的Java代码示例。

示例1: openScanner

import com.stumbleupon.async.Deferred; //导入方法依赖的package包/类
/**
 * Package-private access point for {@link Scanner}s to open themselves.
 * @param scanner The scanner to open.
 * @return A deferred scanner ID (long) if BigTable 0.94 and before, or a
 * deferred {@link Scanner.Response} if BigTable 0.95 and up.
 */
Deferred<Object> openScanner(final Scanner scanner) {
  num_scanners_opened.increment();

  if (LOG.isDebugEnabled()) {
    LOG.debug("BigTable API: Scanning table with {}", scanner.toString());
  }
  Table table = null;
  try {
    table = hbase_connection.getTable(TableName.valueOf(scanner.table()));
    ResultScanner result = table.getScanner(scanner.getHbaseScan());
    scanner.setResultScanner(result);
    scanner.setHbaseTable(table);

    return Deferred.fromResult(new Object());
  } catch (IOException e) {
    if (table != null) {
      try {
        table.close();
      } catch (Exception e1) {}
    }

    return Deferred.fromError(e);
  }
}
 
开发者ID:OpenTSDB,项目名称:asyncbigtable,代码行数:31,代码来源:HBaseClient.java

示例2: atomicIncrement

import com.stumbleupon.async.Deferred; //导入方法依赖的package包/类
/**
 * Atomically and durably increments a value in BigTable.
 * <p>
 * This is equivalent to
 * {@link #atomicIncrement(AtomicIncrementRequest, boolean) atomicIncrement}
 * {@code (request, true)}
 * @param request The increment request.
 * @return The deferred {@code long} value that results from the increment.
 */
public Deferred<Long> atomicIncrement(final AtomicIncrementRequest request) {
  num_atomic_increments.increment();

  Table table = null;
  try {
    table = hbase_connection.getTable(TableName.valueOf(request.table()));
    long val = table.incrementColumnValue(request.key(),
            request.family(), request.qualifier(),
            request.getAmount(),
            request.isDurable() ? Durability.USE_DEFAULT : Durability.SKIP_WAL);

    LOG.info("BigTable API: AtomicIncrement for {} returned {}", request, val);
    return Deferred.fromResult(val);
  } catch (IOException e) {
    return Deferred.fromError(e);
  } finally {
    close(table);
  }
}
 
开发者ID:OpenTSDB,项目名称:asyncbigtable,代码行数:29,代码来源:HBaseClient.java

示例3: insertTagset

import com.stumbleupon.async.Deferred; //导入方法依赖的package包/类
/**
 * Attempts to insert the provided tagset and ID. Returns {@code true} if the
 * write was successful, or {@code false} if the write failed due to a tagset
 * with the same ID already existing in the table.
 *
 * @param tagset the tagset to insert
 * @param id     the ID to insert the tagset with
 * @return whether the write succeeded
 */
private Deferred<Boolean> insertTagset(final SerializedTagset tagset, final int id) throws KuduException {
  final class InsertTagsetCB implements Callback<Deferred<Boolean>, OperationResponse> {
    @Override
    public Deferred<Boolean> call(OperationResponse response) {
      if (response.hasRowError()) {
        if (response.getRowError().getErrorStatus().isAlreadyPresent()) {
          LOG.info("Attempted to insert duplicate tagset; id: {}, tagset: {}", id, tagset);
          // TODO: Consider adding a backoff with jitter before attempting
          //       the insert again (if the lookup fails).
          return Deferred.fromResult(false);
        }
        return Deferred.fromError(new RuntimeException(
            String.format("Unable to insert tagset; id: %s, tagset: %s, error: %s",
                          id, tagset, response.getRowError())));
      } else {
        return Deferred.fromResult(true);
      }
    }
    @Override
    public String toString() {
      return MoreObjects.toStringHelper(this).toString();
    }
  }

  LOG.debug("Inserting tagset; id: {}, tags: {}", id, tagset);
  final AsyncKuduSession session = client.newSession();
  try {
    // We don't have to handle PleaseThrottleException because we are only
    // inserting a single row.
    final Insert insert = tagsetsTable.newInsert();
    insert.getRow().addInt(Tables.TAGSETS_ID_INDEX, id);
    insert.getRow().addBinary(Tables.TAGSETS_TAGSET_INDEX, tagset.getBytes());
    return session.apply(insert).addCallbackDeferring(new InsertTagsetCB());
  } finally {
    session.close();
  }
}
 
开发者ID:danburkert,项目名称:kudu-ts,代码行数:47,代码来源:Tagsets.java

示例4: compareAndSet

import com.stumbleupon.async.Deferred; //导入方法依赖的package包/类
/**
 * Atomic Compare-And-Set (CAS) on a single cell.
 * <p>
 * Note that edits sent through this method <b>cannot be batched</b>, and
 * won't be subject to the {@link #setFlushInterval flush interval}.  This
 * entails that write throughput will be lower with this method as edits
 * have to be sent out to the wire one by one.
 * <p>
 * This request enables you to atomically update the value of an existing
 * cell in BigTable using a CAS operation.  It's like a {@link PutRequest}
 * except that you also pass an expected value.  If the last version of the
 * cell identified by your {@code PutRequest} matches the expected value,
 * BigTable will atomically update it to the new value.
 * <p>
 * If the expected value is the empty byte array, BigTable will atomically
 * create the cell provided that it doesn't exist already. This can be used
 * to ensure that your RPC doesn't overwrite an existing value.  Note
 * however that this trick cannot be used the other way around to delete
 * an expected value atomically.
 * @param edit The new value to write.
 * @param expected The expected value of the cell to compare against.
 * <strong>This byte array will NOT be copied.</strong>
 * @return A deferred boolean, if {@code true} the CAS succeeded, otherwise
 * the CAS failed because the value in BigTable didn't match the expected value
 * of the CAS request.
 */
public Deferred<Boolean> compareAndSet(final PutRequest edit,
                                       final byte[] expected) {
  long ts1 = System.currentTimeMillis();

  Table table = null;
  try {
    table = hbase_connection.getTable(TableName.valueOf(edit.table()));

    Put put = new Put(edit.key());
    long ts = edit.timestamp();
    for (int i = 0; i < edit.qualifiers().length; i++) {
      put.addColumn(edit.family, edit.qualifiers()[i], ts, edit.values()[i]);
    }

    boolean success = table.checkAndPut(edit.key(), edit.family(), edit.qualifier(),
            Bytes.memcmp(EMPTY_ARRAY, expected) == 0 ? null : expected,
            put);

    long ts2 = System.currentTimeMillis();

    if (LOG.isDebugEnabled()) {
      LOG.debug("BigTable API compareAndSet for cell: [{}], expected: [{}] "
          + "returned success: {} in {}ms", edit,Bytes.pretty(expected), 
          success, ts2 - ts1);
    }

    return Deferred.fromResult(success);
  } catch (IOException e) {
    return Deferred.fromError(e);
  } finally {
    close(table);
  }
}
 
开发者ID:OpenTSDB,项目名称:asyncbigtable,代码行数:60,代码来源:HBaseClient.java

示例5: atomicIncrement

import com.stumbleupon.async.Deferred; //导入方法依赖的package包/类
public Deferred<Long> atomicIncrement(final AtomicIncrementRequest request) {
  num_atomic_increments.incrementAndGet();
  if (Bytes.memcmp(tsdb_uid_table, request.table) != 0) {
    return Deferred.fromError(new UnsupportedOperationException(
        "Increments are not supported on other tables yet"));
  }
  
  final Keyspace keyspace = getContext(request.table);
  ColumnPrefixDistributedRowLock<byte[]> lock = 
      new ColumnPrefixDistributedRowLock<byte[]>(keyspace, 
          TSDB_UID_ID_CAS, request.key)
          .withBackoff(new BoundedExponentialBackoff(250, 10000, 10))
          .expireLockAfter(lock_timeout, TimeUnit.MILLISECONDS);
  try {
    num_row_locks.incrementAndGet();
    final ColumnMap<String> columns = lock.acquireLockAndReadRow();
            
    // Modify a value and add it to a batch mutation
    final String qualifier = new String(request.qualifier());
    long value = 1;
    if (columns.get(qualifier) != null) {
      value = columns.get(qualifier).getLongValue() + 1;
    }
    final MutationBatch mutation = keyspace.prepareMutationBatch();
    mutation.setConsistencyLevel(ConsistencyLevel.CL_EACH_QUORUM);
    mutation.withRow(TSDB_UID_ID_CAS, request.key)
      .putColumn(qualifier, value, null);
    lock.releaseWithMutation(mutation);
    return Deferred.fromResult(value);
  } catch (Exception e) {
    try {
      lock.release();
    } catch (Exception e1) {
      LOG.error("Error releasing lock post exception for request: " + request, e1);
    }
    
    return Deferred.fromError(e);
  }
}
 
开发者ID:OpenTSDB,项目名称:asynccassandra,代码行数:40,代码来源:HBaseClient.java

示例6: shutdown

import com.stumbleupon.async.Deferred; //导入方法依赖的package包/类
/**
 * Gracefully closes connections
 */
@Override
public Deferred<Object> shutdown() {
  try {
    if (http_client != null) {
      http_client.close();
    }
    return Deferred.fromResult(null);
  } catch (IOException e) {
    return Deferred.fromError(e);
  }
}
 
开发者ID:OpenTSDB,项目名称:opentsdb-elasticsearch,代码行数:15,代码来源:ElasticSearch.java

示例7: insertTagset

import com.stumbleupon.async.Deferred; //导入方法依赖的package包/类
/**
 * Insert a tagset into the {@code tags} table.
 * @param id the tagset ID.
 * @param tagset the tagset.
 * @return The tagset ID.
 */
public Deferred<Integer> insertTagset(final int id, final SortedMap<String, String> tagset)
    throws KuduException {
  if (tagset.isEmpty()) { return Deferred.fromResult(id); }
  LOG.debug("Inserting tags; tagsetID: {}, tags: {}", id, tagset);
  final AsyncKuduSession session = client.newSession();

  class InsertTagsetCB implements Callback<Deferred<Integer>, List<OperationResponse>> {
    @Override
    public Deferred<Integer> call(List<OperationResponse> responses) {
      try {
        for (OperationResponse response : responses) {
          if (response.hasRowError()) {
            return Deferred.fromError(new RuntimeException(
                String.format("Unable to insert tag: %s", response.getRowError())));
          }
        }
        return Deferred.fromResult(id);
      } finally {
        session.close();
      }
    }
    @Override
    public String toString() {
      return MoreObjects.toStringHelper(this)
                        .add("id", id)
                        .add("tags", tagset)
                        .toString();
    }
  }

  if (tagset.size() > 1000) {
    session.setMutationBufferSpace(tagset.size());
  }
  session.setMutationBufferLowWatermark(1.0f);

  // buffer all of the tags into the session, and ensure that we don't get
  // a PleaseThrottleException. In practice the number of tags should be
  // small.
  session.setMutationBufferSpace(tagset.size());
  session.setMutationBufferLowWatermark(1.0f);
  session.setFlushMode(SessionConfiguration.FlushMode.MANUAL_FLUSH);
  for (Map.Entry<String, String> tag : tagset.entrySet()) {
    Insert insert = table.newInsert();
    // TODO: check with JD that if the inserts below fail, the error will
    // also be returned in the flush call.
    insert.getRow().addString(Tables.TAGS_KEY_INDEX, tag.getKey());
    insert.getRow().addString(Tables.TAGS_VALUE_INDEX, tag.getValue());
    insert.getRow().addInt(Tables.TAGS_TAGSET_ID_INDEX, id);
    session.apply(insert);
  }
  return session.flush().addCallbackDeferring(new InsertTagsetCB());
}
 
开发者ID:danburkert,项目名称:kudu-ts,代码行数:59,代码来源:Tags.java

示例8: nextRows

import com.stumbleupon.async.Deferred; //导入方法依赖的package包/类
/**
 * Scans a number of rows.
 * <p>
 * The last row returned may be partial if it's very wide and
 * {@link #setMaxNumKeyValues} wasn't called with a negative value in
 * argument.
 * <p>
 * Once this method returns {@code null} once (which indicates that this
 * {@code Scanner} is done scanning), calling it again leads to an undefined
 * behavior.
 * @return A deferred list of rows.  Each row is a list of {@link KeyValue}
 * and each element in the list returned represents a different row.  Rows
 * are returned in sequential order.  {@code null} is returned if there are
 * no more rows to scan.  Otherwise its {@link ArrayList#size size} is
 * guaranteed to be less than or equal to the value last given to
 * {@link #setMaxNumRows}.
 * @see #setMaxNumRows
 * @see #setMaxNumKeyValues
 */
public Deferred<ArrayList<ArrayList<KeyValue>>> nextRows() {
  try {
    if (result_scanner == null) {
      client.openScanner(this);
    }

    Result[] results = result_scanner.next(max_num_rows);

    if (results == null || results.length == 0) {
      client.closeScanner(this);
      return Deferred.fromResult(null);
    }

    ArrayList<ArrayList<KeyValue>> resultList = new ArrayList<ArrayList<KeyValue>>();

    for (Result result : results) {
      ArrayList<KeyValue> keyValueList = new ArrayList<KeyValue>(result.size());

      if (!result.isEmpty()) {
        for (NavigableMap.Entry<byte[], NavigableMap<
            byte[], NavigableMap<Long, byte[]>>> familyEntry : 
              result.getMap().entrySet()) {
          byte[] family = familyEntry.getKey();
          for (NavigableMap.Entry<byte[], NavigableMap<Long, byte[]>> 
            qualifierEntry : familyEntry.getValue().entrySet()) {
              byte[] qualifier = qualifierEntry.getKey();
              long ts = qualifierEntry.getValue().firstKey();
              byte[] value = qualifierEntry.getValue().get(ts);

              KeyValue kv = new KeyValue(result.getRow(), family,
                      qualifier, ts, value);
              keyValueList.add(kv);
          }
        }
      }

      resultList.add(keyValueList);
    }

    return Deferred.fromResult(resultList);
  } catch (IOException e) {
    invalidate();
    return Deferred.fromError(e);
  }
}
 
开发者ID:OpenTSDB,项目名称:asyncbigtable,代码行数:65,代码来源:Scanner.java

示例9: append

import com.stumbleupon.async.Deferred; //导入方法依赖的package包/类
public Deferred<Object> append(final AppendRequest request) {
  return Deferred.fromError(
      new UnsupportedOperationException("Not implemented yet"));
}
 
开发者ID:OpenTSDB,项目名称:asynccassandra,代码行数:5,代码来源:HBaseClient.java

示例10: executeQuery

import com.stumbleupon.async.Deferred; //导入方法依赖的package包/类
@Override
public Deferred<SearchQuery> executeQuery(final SearchQuery query) {
  final Deferred<SearchQuery> result = new Deferred<SearchQuery>();

  final StringBuilder uri = new StringBuilder(host);
  uri.append("/").append(index).append("/");
  switch(query.getType()) {
    case TSMETA:
    case TSMETA_SUMMARY:
    case TSUIDS:
      uri.append(ts_meta_schema.docType());
      break;
    case UIDMETA:
      uri.append(uid_meta_schema.docType());
      break;
    case ANNOTATION:
      uri.append(annotation_schema.docType());
      break;
    default:
      return Deferred.fromError(new IllegalArgumentException(
          "Unhandled query type: " + query.getType()));
  }
  uri.append("/_search");

  // setup the query body
  HashMap<String, Object> body = new HashMap<String, Object>(3);
  body.put("size", query.getLimit());
  body.put("from", query.getStartIndex());

  HashMap<String, Object> qs = new HashMap<String, Object>(1);
  body.put("query", qs);
  HashMap<String, String> query_string = new HashMap<String, String>(1);
  query_string.put("query", query.getQuery());
  qs.put("query_string", query_string);

  final HttpPost post = new HttpPost(uri.toString());
  post.setEntity(new ByteArrayEntity(JSON.serializeToBytes(body)));

  http_client.execute(post, new SearchCB(query, result));
  queries_executed.increment();
  return result;
}
 
开发者ID:OpenTSDB,项目名称:opentsdb-elasticsearch,代码行数:43,代码来源:ElasticSearch.java


注:本文中的com.stumbleupon.async.Deferred.fromError方法示例由纯净天空整理自Github/MSDocs等开源代码及文档管理平台,相关代码片段筛选自各路编程大神贡献的开源项目,源码版权归原作者所有,传播和使用请参考对应项目的License;未经允许,请勿转载。