/**
  * Test content for existence.
  *
  * @param key content identifier
  * @param alive true inside used content and false for checking within content marked as unused.
  * @return true if content found
  * @throws BinaryStoreException
  */
 private boolean contentExists(BinaryKey key, boolean alive) throws BinaryStoreException {
   try {
     String query = "SELECT payload from modeshape.binary where cid='" + key.toString() + "'";
     query = alive ? query + " and usage=1;" : query + " and usage = 0;";
     ResultSet rs = session.execute(query);
     return rs.iterator().hasNext();
   } catch (RuntimeException e) {
     throw new BinaryStoreException(e);
   }
 }
  @Override
  public BinaryValue storeValue(InputStream stream) throws BinaryStoreException {
    // store into temporary file system store and get SHA-1
    BinaryValue temp = cache.storeValue(stream);
    try {
      // prepare new binary key based on SHA-1
      BinaryKey key = new BinaryKey(temp.getKey().toString());

      // check for duplicate content
      if (this.contentExists(key, ALIVE)) {
        return new StoredBinaryValue(this, key, temp.getSize());
      }

      // check unused content
      if (this.contentExists(key, UNUSED)) {
        session.execute("UPDATE modeshape.binary SET usage=1 WHERE cid='" + key + "';");
        return new StoredBinaryValue(this, key, temp.getSize());
      }

      // store content
      PreparedStatement query =
          session.prepare(
              "INSERT INTO modeshape.binary (cid, usage_time, payload, usage) VALUES ( ?,?,?,1 );");
      BoundStatement statement = new BoundStatement(query);
      session.execute(statement.bind(key.toString(), new Date(), buffer(stream)));
      return new StoredBinaryValue(this, key, temp.getSize());
    } catch (BinaryStoreException e) {
      throw e;
    } catch (IOException e) {
      throw new BinaryStoreException(e);
    } catch (RuntimeException e) {
      throw new BinaryStoreException(e);
    } finally {
      // remove content from temp store
      cache.markAsUnused(temp.getKey());
    }
  }
  @Override
  public InputStream getInputStream(BinaryKey key) throws BinaryStoreException {
    try {
      ResultSet rs =
          session.execute(
              "SELECT payload FROM modeshape.binary WHERE cid='"
                  + key.toString()
                  + "' and usage=1;");
      Row row = rs.one();
      if (row == null) {
        throw new BinaryStoreException(JcrI18n.unableToFindBinaryValue.text(key, session));
      }

      ByteBuffer buffer = row.getBytes("payload");
      return new BufferedInputStream(buffer);
    } catch (BinaryStoreException e) {
      throw e;
    } catch (RuntimeException e) {
      throw new BinaryStoreException(e);
    }
  }