Ejemplo n.º 1
0
  /**
   * Read a record from the database. Each field/value pair from the result will be stored in a
   * HashMap.
   *
   * @param table The name of the table
   * @param key The record key of the record to read.
   * @param fields The list of fields to read, or null for all of them
   * @param result A HashMap of field/value pairs for the result
   * @return Zero on success, a non-zero error code on error
   */
  public int read(
      String table, String key, Set<String> fields, HashMap<String, ByteIterator> result) {
    if (!_table.equals(table)) {
      try {
        client.set_keyspace(table);
        _table = table;
      } catch (Exception e) {
        e.printStackTrace();
        e.printStackTrace(System.out);
        return Error;
      }
    }

    for (int i = 0; i < OperationRetries; i++) {

      try {
        SlicePredicate predicate;
        if (fields == null) {
          predicate =
              new SlicePredicate()
                  .setSlice_range(new SliceRange(emptyByteBuffer, emptyByteBuffer, false, 1000000));

        } else {
          ArrayList<ByteBuffer> fieldlist = new ArrayList<ByteBuffer>(fields.size());
          for (String s : fields) {
            fieldlist.add(ByteBuffer.wrap(s.getBytes("UTF-8")));
          }

          predicate = new SlicePredicate().setColumn_names(fieldlist);
        }

        List<ColumnOrSuperColumn> results =
            client.get_slice(
                ByteBuffer.wrap(key.getBytes("UTF-8")), parent, predicate, ConsistencyLevel.ONE);

        if (_debug) {
          System.out.print("Reading key: " + key);
        }

        Column column;
        String name;
        ByteIterator value;
        for (ColumnOrSuperColumn oneresult : results) {

          column = oneresult.column;
          name =
              new String(
                  column.name.array(),
                  column.name.position() + column.name.arrayOffset(),
                  column.name.remaining());
          value =
              new ByteArrayByteIterator(
                  column.value.array(),
                  column.value.position() + column.value.arrayOffset(),
                  column.value.remaining());

          result.put(name, value);

          if (_debug) {
            System.out.print("(" + name + "=" + value + ")");
          }
        }

        if (_debug) {
          System.out.println();
        }

        return Ok;
      } catch (Exception e) {
        errorexception = e;
      }

      try {
        Thread.sleep(500);
      } catch (InterruptedException e) {
      }
    }
    errorexception.printStackTrace();
    errorexception.printStackTrace(System.out);
    return Error;
  }