Example #1
0
  /**
   * Add new Column<long,long> to a given row in a given cassandra column family
   *
   * @param columnFamily column family name
   * @param row row name
   * @param key long key value of the column
   * @param value long value of the column
   * @param keyspace Cassandra KeySpace
   * @throws CassandraDataAccessException
   */
  public static void addLongContentToRow(
      String columnFamily, String row, long key, long value, Keyspace keyspace)
      throws CassandraDataAccessException {

    if (keyspace == null) {
      throw new CassandraDataAccessException("Can't add Data , no keySpace provided ");
    }

    if (columnFamily == null || row == null) {
      throw new CassandraDataAccessException(
          "Can't add data with columnFamily = "
              + columnFamily
              + " and rowName="
              + row
              + " key = "
              + key);
    }

    try {
      Mutator<String> mutator = HFactory.createMutator(keyspace, stringSerializer);
      mutator.insert(
          row, columnFamily, HFactory.createColumn(key, value, longSerializer, longSerializer));
      mutator.execute();
    } catch (Exception e) {
      throw new CassandraDataAccessException("Error while adding long content to a row", e);
    }
  }
Example #2
0
  /**
   * Add a new Column <long,byte[]> to a given row in a given column family
   *
   * @param columnFamily column family name
   * @param row row name
   * @param key long key value
   * @param value value as a byte array
   * @param keyspace CassandraKeySpace
   * @throws CassandraDataAccessException
   */
  public static void addLongByteArrayColumnToRow(
      String columnFamily, String row, long key, byte[] value, Keyspace keyspace)
      throws CassandraDataAccessException {
    if (keyspace == null) {
      throw new CassandraDataAccessException("Can't add Data , no keySpace provided ");
    }

    if (columnFamily == null || row == null || value == null) {
      throw new CassandraDataAccessException(
          "Can't add data with columnFamily = "
              + columnFamily
              + " and row="
              + row
              + " key  = "
              + key
              + " value = "
              + value);
    }

    try {
      Mutator<String> messageContentMutator = HFactory.createMutator(keyspace, stringSerializer);
      messageContentMutator.addInsertion(
          row,
          columnFamily,
          HFactory.createColumn(key, value, longSerializer, bytesArraySerializer));
      messageContentMutator.execute();
    } catch (Exception e) {
      throw new CassandraDataAccessException(
          "Error while adding new Column <int,byte[]> to cassandra store", e);
    }
  }
Example #3
0
  /**
   * Add a Mapping to a Given Row in cassandra column family. Mappings are used as search indexes
   *
   * @param columnFamily columnFamilyName
   * @param row row name
   * @param cKey key name for the adding column
   * @param cValue value for the adding column
   * @param keyspace Cassandra KeySpace
   * @throws CassandraDataAccessException In case of database access error or data error
   */
  public static void addMappingToRaw(
      String columnFamily, String row, String cKey, String cValue, Keyspace keyspace)
      throws CassandraDataAccessException {

    if (keyspace == null) {
      throw new CassandraDataAccessException("Can't add Data , no KeySpace provided ");
    }

    if (columnFamily == null || row == null || cKey == null) {
      throw new CassandraDataAccessException(
          "Can't add data with columnFamily = "
              + columnFamily
              + " and rowName="
              + row
              + " key = "
              + cKey);
    }

    try {
      Mutator<String> mutator = HFactory.createMutator(keyspace, stringSerializer);
      mutator.addInsertion(
          row,
          columnFamily,
          HFactory.createColumn(cKey, cValue.trim(), stringSerializer, stringSerializer));
      mutator.execute();
    } catch (Exception e) {
      throw new CassandraDataAccessException("Error while adding a Mapping to row ", e);
    }
  }
Example #4
0
  /**
   * Add Message to a Given Queue in Cassandra
   *
   * @param columnFamily ColumnFamily name
   * @param queue queue name
   * @param messageId Message id
   * @param message message in bytes
   * @param keyspace Cassandra KeySpace
   * @throws CassandraDataAccessException In case of database access error
   */
  public static void addMessageToQueue(
      String columnFamily, String queue, long messageId, byte[] message, Keyspace keyspace)
      throws CassandraDataAccessException {

    if (keyspace == null) {
      throw new CassandraDataAccessException("Can't add Data , no mutator provided ");
    }

    if (columnFamily == null || queue == null || message == null) {
      throw new CassandraDataAccessException(
          "Can't add data with columnFamily = "
              + columnFamily
              + " and queue="
              + queue
              + " message id  = "
              + messageId
              + " message = "
              + message);
    }

    try {
      Mutator<String> mutator = HFactory.createMutator(keyspace, stringSerializer);
      mutator.addInsertion(
          queue.trim(),
          columnFamily,
          HFactory.createColumn(messageId, message, longSerializer, bytesArraySerializer));
      mutator.execute();

    } catch (Exception e) {
      throw new CassandraDataAccessException("Error while adding message to Queue", e);
    }
  }
Example #5
0
  public static void addIntegerByteArrayContentToRaw(
      String columnFamily,
      String row,
      int key,
      byte[] value,
      Mutator<String> mutator,
      boolean execute)
      throws CassandraDataAccessException {

    if (mutator == null) {
      throw new CassandraDataAccessException("Can't add Data , no Mutator provided ");
    }

    if (columnFamily == null || row == null || value == null) {
      throw new CassandraDataAccessException(
          "Can't add data with columnFamily = "
              + columnFamily
              + " and row="
              + row
              + " key  = "
              + key
              + " value = "
              + value);
    }

    mutator.addInsertion(
        row,
        columnFamily,
        HFactory.createColumn(key, value, integerSerializer, bytesArraySerializer));
    if (execute) {
      mutator.execute();
    }
  }
 private void insertSubscription(SubscriptionContext context) {
   Mutator<Object> mutator = getObjectMutator();
   mutator.addInsertion(
       context.getId(),
       SUBSCRIPTION_COLUMN_FAMILY_NAME,
       HFactory.createColumn("value", context, STRING_SERIALIZER, OBJECT_SERIALIZER));
   mutator.execute();
 }
 public void put(String columnFamily, String key, byte[] value) {
   Mutator<String> mutator = HFactory.createMutator(this._keyspace, StringSerializer.get());
   mutator.insert(
       key,
       columnFamily,
       HFactory.createColumn(
           DEFAULT_COLUMN_NAME, value, StringSerializer.get(), BytesArraySerializer.get()));
 }
 public void addEventSoftState(EventSoftState state) {
   Mutator<String> mutator = getStringMutator();
   mutator.addInsertion(
       state.getResourceURL(),
       EVENT_SOFT_STATE_COLUMN_FAMILY_NAME,
       HFactory.createColumn(state.getEntityTag(), state, STRING_SERIALIZER, OBJECT_SERIALIZER));
   mutator.execute();
 }
Example #9
0
  public static <A, B> HColumn<A, B> column(final A name, final B value) {

    return HFactory.createColumn(
        name, //
        value, //
        (Serializer<A>) SerializerTypeInferer.getSerializer(name), //
        (Serializer<B>) SerializerTypeInferer.getSerializer(value));
  }
 @Override
 public void save(
     PersistenceManagementEvent persistenceManagementEvent,
     String nodeID,
     PersistenceObject persistenceObject) {
   Mutator<String> mutator = HFactory.createMutator(keyspace, sser);
   mutator.insert(
       persistenceManagementEvent.getRevision(),
       COLUMN_FAMILY_NAME,
       HFactory.createColumn(nodeID, ByteSerializer.OToB(persistenceObject), sser, bser));
   mutator.insert(
       persistenceManagementEvent.getExecutionPlanIdentifier(),
       INDEX_COLUMN_FAMILY_NAME,
       HFactory.createColumn(
           persistenceManagementEvent.getRevision(),
           String.valueOf(System.currentTimeMillis()),
           sser,
           sser));
   mutator.execute();
 }
 void insertData(String dpname, Date d, Timestamp u, double value) {
   try {
     long timeInMicroSeconds = u.getTime();
     // UUID timeUUIDColumnName = TimeUUIDUtils.getTimeUUID(timeInMicroSeconds);
     System.out.println(d + "\t" + timeInMicroSeconds + "\t" + value);
     DateSerializer ds = new DateSerializer();
     Mutator<Date> mu = HFactory.createMutator(keyspace, ds);
     mu.insert(d, dpname, HFactory.createColumn(timeInMicroSeconds, value));
   } catch (Exception e) {
     e.printStackTrace();
   }
 }
 private void insertResource(Resource resource) {
   Mutator<String> mutator = getStringMutator();
   mutator.addInsertion(
       resource.getUri(),
       RESOURCE_COLUMN_FAMILY_NAME,
       HFactory.createColumn(
           ((SIPResource) resource).getEventName(),
           resource,
           STRING_SERIALIZER,
           OBJECT_SERIALIZER));
   mutator.execute();
 }
 public void addNotifyBody(
     String resourceUri, String eventName, String notifyBodyType, NotifyBody notifyBody) {
   if (SIPConstans.EVENT_NAME_PRESENCE.equals(eventName)) {
     Mutator<String> mutator = getStringMutator();
     mutator.addInsertion(
         resourceUri,
         PRESENCE_NB_COLUMN_FAMILY_NAME,
         HFactory.createColumn(notifyBodyType, notifyBody, STRING_SERIALIZER, OBJECT_SERIALIZER));
     mutator.execute();
   } else {
     throw new IllegalArgumentException("Can't save notify body for event[" + eventName + "]");
   }
 }
  @Override
  public void insertTatamibotConfiguration(TatamibotConfiguration tatamibotConfiguration) {
    UUID tatamibotConfigurationId = TimeUUIDUtils.getUniqueTimeUUIDinMillis();
    Mutator<String> mutator = HFactory.createMutator(keyspaceOperator, StringSerializer.get());
    mutator.insert(
        tatamibotConfiguration.getDomain(),
        ColumnFamilyKeys.DOMAIN_TATAMIBOT_CF,
        HFactory.createColumn(
            tatamibotConfigurationId, "", UUIDSerializer.get(), StringSerializer.get()));

    tatamibotConfiguration.setTatamibotConfigurationId(tatamibotConfigurationId.toString());
    em.persist(tatamibotConfiguration);
  }
  @Override
  @CacheEvict(value = "domain-tags-cache", key = "#domain")
  public void addTag(String domain, String tag) {
    HColumn<UUID, String> column =
        HFactory.createColumn(
            TimeUUIDUtils.getUniqueTimeUUIDinMillis(),
            tag,
            COLUMN_TTL,
            UUIDSerializer.get(),
            StringSerializer.get());

    Mutator<String> mutator = HFactory.createMutator(keyspaceOperator, StringSerializer.get());

    mutator.insert(domain, TRENDS_CF, column);
  }
Example #16
0
 @Override
 public Mutator addDataToBatchInsertion(
     Object data,
     String streamColumnFamily,
     String columnName,
     String rowKey,
     Mutator<String> mutator) {
   Long longVal = ((data) instanceof Double) ? ((Double) data).longValue() : (Long) data;
   if (longVal != null) {
     mutator.addInsertion(
         rowKey,
         streamColumnFamily,
         HFactory.createColumn(columnName, longVal, stringSerializer, longSerializer));
   }
   return mutator;
 }
 private void removeResourceSubRelation(SubscriptionContext context) {
   String notifyBodyType = ((SIPSubscriptionContext) context).getNotifyBodyType();
   HColumn<String, Object> resourceSubs =
       queryResourceSubs(context.getSubscribee(), notifyBodyType);
   List<SubscriptionID> idList = null;
   if (resourceSubs != null) {
     idList = (List<SubscriptionID>) resourceSubs.getValue();
     idList.remove((SubscriptionID) context.getId());
   } else {
     return;
   }
   Mutator<String> mutator = getStringMutator();
   mutator.addInsertion(
       context.getSubscribee(),
       RESOURCE_SUB_COLUMN_FAMILY_NAME,
       HFactory.createColumn(notifyBodyType, idList, STRING_SERIALIZER, OBJECT_SERIALIZER));
   mutator.execute();
 }
Example #18
0
    @Override
    public void run() {
      Calendar instance = Calendar.getInstance();
      instance.set(2012, 1, 1, 0, 0, 0);
      Date time = instance.getTime();
      Mutator<String> mutator = HFactory.createMutator(keyspace, new AsciiSerializer());

      for (int i = 0; i < 300; i++) {
        HColumn<Date, byte[]> column =
            HFactory.createColumn(
                time, new byte[] {}, DateSerializer.get(), BytesArraySerializer.get());
        String hitCampaignName = getHitCampaignName();
        if (hitCampaignName != null) mutator.addInsertion(customer, hitCampaignName, column);
        mutator.addInsertion(customer, "global", column);
        time = new Date(time.getTime() + 2000);
      }
      mutator.execute();
    }
  /**
   * Check if the tags exists and add them if they don't exist.
   *
   * @param keyspaceOperator
   * @param columnfamily
   * @param columnfamilyId
   * @param tags
   * @return
   */
  private int addTags(
      Keyspace keyspaceOperator, String columnfamily, String columnfamilyId, List<String> tags) {

    // Get current user tags
    List<String> currentTags =
        getTags(
            keyspaceOperator,
            columnfamily,
            columnfamilyId,
            TAG_COLUMN_MIN_NAME,
            TAG_COLUMN_MAX_NAME);

    // Get the number of tags of the user
    int nbColumns = currentTags.size();
    int nbAddedTags = 0;

    Mutator<String> mutator = HFactory.createMutator(keyspaceOperator, StringSerializer.get());

    for (String tag : tags) {
      String tagLowerCase = tag.toLowerCase();

      // Check if the tag already exists
      if (currentTags.contains(tagLowerCase)) {
        // This tag already exists => we don't add it!
        continue;
      }

      // Add the new tag
      nbColumns++;
      String columnName = COLUMN_TAG_PREFIX + nbColumns;

      mutator.insert(
          columnfamilyId,
          columnfamily,
          HFactory.createColumn(
              columnName, tagLowerCase, StringSerializer.get(), StringSerializer.get()));
      nbAddedTags++;
    }

    return nbAddedTags;
  }
Example #20
0
  public static void addMappingToRow(
      String columnFamily,
      String row,
      String cKey,
      String cValue,
      Mutator<String> mutator,
      boolean execute)
      throws CassandraDataAccessException {

    if (mutator == null) {
      throw new CassandraDataAccessException("Can't add Data , no mutator provided ");
    }

    mutator.addInsertion(
        row,
        columnFamily,
        HFactory.createColumn(cKey, cValue.trim(), stringSerializer, stringSerializer));

    if (execute) {
      mutator.execute();
    }
  }
  @Override
  public int batchUpdateVersioning(
      String cf, List<Node[]> li, String keyspace, String URN_author, String txID) {
    Hashtable<String, List<Node[]>> versioned_entities = new Hashtable<String, List<Node[]>>();
    Hashtable<String, String> previous_commit_id = new Hashtable<String, String>();
    boolean successful_fetch =
        fetchMostRecentVersions(
            keyspace, cf, li, txID, URN_author, versioned_entities, previous_commit_id);
    if (!successful_fetch) {
      // it means that for one entity there is already a lastCID > txID
      // we have to abort here the insertion
      return 2;
    }

    // now update the properties into the recent versions fetched
    for (Iterator<Node[]> it = li.iterator(); it.hasNext(); ) {
      Node[] current = it.next();
      String prop = current[1].toN3();
      String value_old = current[2].toN3();
      Node value_new = current[3];

      List<Node[]> entity_version = versioned_entities.get("<" + current[0].toString() + "-VER>");
      for (Iterator<Node[]> it_version = entity_version.iterator(); it_version.hasNext(); ) {
        Node[] ver_ent = it_version.next();
        String ver_prop = ver_ent[1].toN3();
        String ver_value = ver_ent[2].toN3();
        // check if this is the triple to be replaces
        if (prop.equals(ver_prop) && value_old.equals(ver_value)) ver_ent[2] = value_new;
      }
    }

    // SPO
    // insert 's-VER' and 's-URN' new versions
    Mutator<String> m = HFactory.createMutator(getExistingKeyspace(keyspace), _ss);
    for (Iterator<String> it = versioned_entities.keySet().iterator(); it.hasNext(); ) {
      String row_entity_key = it.next();
      // there is a list of properties to be added to the new version of this entity
      List<Node[]> entity_old_version = versioned_entities.get(row_entity_key);
      String old_version_num = previous_commit_id.get(row_entity_key);

      for (Iterator it_old_v = entity_old_version.iterator(); it_old_v.hasNext(); ) {
        Node[] nx = (Node[]) it_old_v.next();
        // reorder for the key
        Node[] reordered = Util.reorder(nx, _maps.get(cf));
        String rowKey = new Resource(reordered[0].toString()).toN3();
        if (!reordered[0].toString().contains("-VER"))
          rowKey = new Resource(reordered[0].toString() + "-VER").toN3();

        /* this is the approach without using Snowflake
        int next_ver = old_version_num+1;*/
        String next_ver;
        // if txID is different than null, it means this is called in a transactional context
        if (txID != null) next_ver = txID;
        else next_ver = String.valueOf(Integer.valueOf(old_version_num) + 1);

        // VER, URN
        Composite colKey = new Composite();
        colKey.addComponent(next_ver, StringSerializer.get());
        colKey.addComponent(URN_author, StringSerializer.get());
        String colKey_s = Nodes.toN3(new Node[] {reordered[1], reordered[2]});
        colKey.addComponent(colKey_s, StringSerializer.get());
        HColumn<Composite, String> hColumnObj_itemID =
            HFactory.createColumn(colKey, "", new CompositeSerializer(), StringSerializer.get());
        m.addInsertion(rowKey, cf, hColumnObj_itemID);

        // URN, VER
        rowKey = new Resource(reordered[0].toString() + "-URN").toN3();
        colKey = new Composite();
        colKey.addComponent(URN_author, StringSerializer.get());
        colKey.addComponent(String.valueOf(next_ver), StringSerializer.get());
        colKey_s = Nodes.toN3(new Node[] {reordered[1], reordered[2]});
        colKey.addComponent(colKey_s, StringSerializer.get());

        hColumnObj_itemID =
            HFactory.createColumn(colKey, "", new CompositeSerializer(), StringSerializer.get());
        m.addInsertion(rowKey, cf, hColumnObj_itemID);
      }
      m.execute();
    }
    // now try to write all CID,prevCID; if check my writes is enabled, it can abort in case
    // there are conflicts
    return commitOrAbort(keyspace, txID, URN_author, versioned_entities, previous_commit_id);
  }
  @Override
  protected int batchInsertVersioning(
      String cf, List<Node[]> li, String keyspace, String URN_author, String txID) {
    Hashtable<String, List<Node[]>> versioned_entities = new Hashtable<String, List<Node[]>>();
    Hashtable<String, String> previous_commit_id = new Hashtable<String, String>();
    boolean successful_fetch =
        fetchMostRecentVersions(
            keyspace, cf, li, txID, URN_author, versioned_entities, previous_commit_id);
    if (!successful_fetch) {
      // it means that for one entity there is already a lastCID > txID
      // we have to abort here the insertion
      return 2;
    }

    /*
    // SIMULATE SOME DELAY HERE !!
    try{
    Thread.sleep(System.currentTimeMillis()%10000);
    }catch(Exception ex) {}
    // END [THIS MUST BE ERASED IN PRODUCTION!!]*/

    // add the new triples to previous versions
    for (Iterator<Node[]> it_triples = li.iterator(); it_triples.hasNext(); ) {
      Node[] triple = it_triples.next();
      String rowKey = new Resource(triple[0].toString() + "-VER").toN3();

      List<Node[]> prev_version = versioned_entities.get(rowKey);
      prev_version.add(triple);
      versioned_entities.put(rowKey, prev_version);
    }

    // SPO
    // insert 's-VER' and 's-URN' new versions
    Mutator<String> m = HFactory.createMutator(getExistingKeyspace(keyspace), _ss);
    for (Iterator<String> it = versioned_entities.keySet().iterator(); it.hasNext(); ) {
      String row_entity_key = it.next();
      // there is a list of properties to be added to the new version of this entity
      List<Node[]> entity_old_version = versioned_entities.get(row_entity_key);
      String old_version_num = previous_commit_id.get(row_entity_key);

      for (Iterator it_old_v = entity_old_version.iterator(); it_old_v.hasNext(); ) {
        Node[] nx = (Node[]) it_old_v.next();
        // reorder for the key
        Node[] reordered = Util.reorder(nx, _maps.get(cf));
        String rowKey = new Resource(reordered[0].toString()).toN3();
        if (!reordered[0].toString().contains("-VER"))
          rowKey = new Resource(reordered[0].toString() + "-VER").toN3();

        /* this is the approach without using Snowflake
        int next_ver = old_version_num+1;*/
        String next_ver;
        // if txID is different than null, it means this is called in a transactional context
        if (txID != null) next_ver = txID;
        else next_ver = String.valueOf(Integer.valueOf(old_version_num) + 1);

        // VER, URN
        Composite colKey = new Composite();
        colKey.addComponent(next_ver, StringSerializer.get());
        colKey.addComponent(URN_author, StringSerializer.get());
        String colKey_s = Nodes.toN3(new Node[] {reordered[1], reordered[2]});
        colKey.addComponent(colKey_s, StringSerializer.get());
        HColumn<Composite, String> hColumnObj_itemID =
            HFactory.createColumn(colKey, "", new CompositeSerializer(), StringSerializer.get());
        m.addInsertion(rowKey, cf, hColumnObj_itemID);

        // URN, VER
        rowKey = new Resource(reordered[0].toString() + "-URN").toN3();
        colKey = new Composite();
        colKey.addComponent(URN_author, StringSerializer.get());
        colKey.addComponent(String.valueOf(next_ver), StringSerializer.get());
        colKey_s = Nodes.toN3(new Node[] {reordered[1], reordered[2]});
        colKey.addComponent(colKey_s, StringSerializer.get());

        hColumnObj_itemID =
            HFactory.createColumn(colKey, "", new CompositeSerializer(), StringSerializer.get());
        m.addInsertion(rowKey, cf, hColumnObj_itemID);
      }
      m.execute();
    }
    // now try to write all CID,prevCID; if check my writes is enabled, it can abort in case
    // there are conflicts
    return commitOrAbort(keyspace, txID, URN_author, versioned_entities, previous_commit_id);
  }
Example #23
0
 public void insertColumnBatch(K key, N name, V value, Mutator<K> mutator) {
   mutator.addInsertion(
       key,
       columnFamily,
       HFactory.createColumn(name, value, columnNameSerializer, valueSerializer));
 }
Example #24
0
 public void setValueBatch(K key, N name, V value, int ttl, Mutator<K> mutator) {
   mutator.addInsertion(
       key,
       columnFamily,
       HFactory.createColumn(name, value, columnNameSerializer, valueSerializer).setTtl(ttl));
 }