diff --git a/CHANGELOG.md b/CHANGELOG.md
index cfb5b9a..4b50a77 100644
--- a/CHANGELOG.md
+++ b/CHANGELOG.md
@@ -4,6 +4,9 @@
All notable changes to this project will be documented in this file.
This project adheres to [Semantic Versioning](https://semver.org/spec/v2.0.0.html).
+## [v2.0.0] - 2023-10-24
+ - Feature #25901, add Cassandra 4.1.3 java client
+
## [v1.18.0] - 2022-09-20
- Feature #23891, The (wrongly named) Feed class has been changed to Post, all the methods have been changed accordingly and the old one set as deprecated
diff --git a/META-INF/MANIFEST.MF b/META-INF/MANIFEST.MF
index 5e94951..ed49fc3 100644
--- a/META-INF/MANIFEST.MF
+++ b/META-INF/MANIFEST.MF
@@ -1,3 +1,3 @@
Manifest-Version: 1.0
-Class-Path:
+Main-Class: org.gcube.portal.databook.server.Tester
diff --git a/pom.xml b/pom.xml
index d7074d7..4347bf6 100644
--- a/pom.xml
+++ b/pom.xml
@@ -11,7 +11,7 @@
org.gcube.portal
social-networking-library
- 1.18.0
+ 2.0.0-SNAPSHOT
gCube Social Networking Library
The gCube Social Networking Library is the 'bridge' between your gCube Applications and the social networking facilities.
@@ -28,57 +28,39 @@
2.8.1
UTF-8
UTF-8
+ 4.13.0
+ 1.2.3
-
-
-
- org.gcube.distribution
- maven-portal-bom
- 3.6.4
- pom
- import
-
-
-
+
+ com.datastax.oss
+ java-driver-query-builder
+ ${cassandra.driver.oss.version}
+
+
+ com.datastax.oss
+ java-driver-mapper-runtime
+ ${cassandra.driver.oss.version}
+
com.google
gwt-jsonmaker
-
-
- com.netflix.astyanax
- astyanax-core
- provided
-
-
- org.slf4j
- log4j-over-slf4j
-
-
-
-
- com.netflix.astyanax
- astyanax-thrift
- provided
-
-
- com.netflix.astyanax
- astyanax-cassandra
- provided
+ 1.2.1
org.gcube.resources.discovery
ic-client
+ [1.0.5-SNAPSHOT,2.0.0-SNAPSHOT)
org.gcube.common.portal
portal-manager
- provided
+ [2.4.2-SNAPSHOT,3.0.0-SNAPSHOT)
com.sun.mail
javax.mail
- provided
+ 1.5.2
junit
@@ -89,15 +71,21 @@
com.google.gwt
gwt-user
${gwtVersion}
- provided
org.slf4j
slf4j-log4j12
+ 1.6.4
org.slf4j
slf4j-api
+ 1.6.4
+
+
+ commons-lang
+ commons-lang
+ 2.6
@@ -135,6 +123,31 @@
true
+
+ org.apache.maven.plugins
+ maven-assembly-plugin
+ 3.4.2
+
+
+
+ true
+ org.gcube.portal.databook.server.Tester
+
+
+
+ jar-with-dependencies
+
+
+
+
+ assemble-all
+ package
+
+ single
+
+
+
+
diff --git a/src/main/java/org/gcube/portal/databook/server/CassandraClusterConnection.java b/src/main/java/org/gcube/portal/databook/server/CassandraClusterConnection.java
index 7627070..25927bd 100644
--- a/src/main/java/org/gcube/portal/databook/server/CassandraClusterConnection.java
+++ b/src/main/java/org/gcube/portal/databook/server/CassandraClusterConnection.java
@@ -1,33 +1,25 @@
package org.gcube.portal.databook.server;
-import java.util.HashMap;
-import java.util.Map;
-import java.util.UUID;
+import java.net.InetSocketAddress;
+import java.time.Duration;
+import java.util.List;
+
+import com.datastax.oss.driver.api.core.CqlSession;
+import com.datastax.oss.driver.api.core.CqlSessionBuilder;
+import com.datastax.oss.driver.api.core.config.DefaultDriverOption;
+import com.datastax.oss.driver.api.core.config.DriverConfigLoader;
+import com.datastax.oss.driver.api.core.cql.ResultSet;
+import com.datastax.oss.driver.api.core.metadata.Metadata;
+import com.datastax.oss.driver.api.core.metadata.schema.KeyspaceMetadata;
+import com.datastax.oss.driver.api.core.type.DataTypes;
+import com.datastax.oss.driver.api.querybuilder.SchemaBuilder;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
-import com.netflix.astyanax.AstyanaxContext;
-import com.netflix.astyanax.Cluster;
-import com.netflix.astyanax.Keyspace;
-import com.netflix.astyanax.connectionpool.NodeDiscoveryType;
-import com.netflix.astyanax.connectionpool.OperationResult;
-import com.netflix.astyanax.connectionpool.exceptions.ConnectionException;
-import com.netflix.astyanax.connectionpool.impl.ConnectionPoolConfigurationImpl;
-import com.netflix.astyanax.connectionpool.impl.ConnectionPoolType;
-import com.netflix.astyanax.connectionpool.impl.CountingConnectionPoolMonitor;
-import com.netflix.astyanax.ddl.ColumnDefinition;
-import com.netflix.astyanax.ddl.ColumnFamilyDefinition;
-import com.netflix.astyanax.ddl.KeyspaceDefinition;
-import com.netflix.astyanax.ddl.SchemaChangeResult;
-import com.netflix.astyanax.impl.AstyanaxConfigurationImpl;
-import com.netflix.astyanax.thrift.ThriftFamilyFactory;
-import com.netflix.astyanax.thrift.ddl.ThriftColumnDefinitionImpl;
-import com.netflix.astyanax.thrift.ddl.ThriftColumnFamilyDefinitionImpl;
-
/**
* @author Massimiliano Assante ISTI-CNR
- * @author Costantino Perciante ISTI-CNR
+ * @author Ahmed Salah Tawfik Ibrahim ISTI-CNR
*
*/
public class CassandraClusterConnection {
@@ -39,304 +31,473 @@ public class CassandraClusterConnection {
/**
* keyspace location
*/
- private static String clusterName;
- private static String host;
- private static String keyspaceName;
+ private static List hosts;
+ private static String datacenterName;
+ private static String keyspaceName;
+ private CqlSession myKeyspaceSession;
- private Keyspace myKeyspace;
/**
- *
+ *
* @param dropSchema set true if you want do drop the current and set up new one
* the connection to cassandra cluster
*/
protected CassandraClusterConnection(boolean dropSchema) {
- if (clusterName == null || host == null || keyspaceName == null) {
+ if (hosts == null || datacenterName == null || keyspaceName == null) {
RunningCluster cluster = RunningCluster.getInstance(null);
- clusterName = cluster.getClusterName();
- host = cluster.getHost();
- keyspaceName = cluster.getKeyspaceName();
- }
- AstyanaxContext clusterContext = new AstyanaxContext.Builder()
- .forCluster(clusterName)
- .withAstyanaxConfiguration(new AstyanaxConfigurationImpl())
- .withConnectionPoolConfiguration(
- new ConnectionPoolConfigurationImpl(
- clusterName).setMaxConnsPerHost(100)
- .setSeeds(host))
- .withConnectionPoolMonitor(
- new CountingConnectionPoolMonitor())
- .buildCluster(ThriftFamilyFactory.getInstance());
+ //host = cluster.getHost();
+ hosts = cluster.getHosts();
+ datacenterName = cluster.getDatacenterName();
+ keyspaceName = cluster.getKeyspaceName();
+ }
_log.info(keyspaceName + " KeySpace SetUp ...");
- SetUpKeySpaces(clusterContext, dropSchema);
+ SetUpKeySpaces(dropSchema);
+ myKeyspaceSession = connect(keyspaceName);
_log.info("CONNECTED! using KeySpace: " + keyspaceName);
-
- // then close connection pool for cluster
- _log.info("Closing cluster connection pool no longer needed (keyspace one will be used)");
- clusterContext.shutdown();
- _log.info("Closed cluster connection pool no longer needed (keyspace one will be used)");
}
/**
- * Close the connection pool
- */
- public void closeConnection(){
-
- if(myKeyspace != null){
- try{
- _log.info("Closing pool connection");
- myKeyspace.getConnectionPool().shutdown();
- _log.info("Pool closed!");
- }catch(Exception e){
- _log.error("Unable to close connection pool", e);
- }
- }
- }
-
- /**
- *
- * @param dropSchema set true if you want do drop the current and set up new one
+ *
+ * @param dropSchema set true if you want to drop the current and set up new one
* the connection to cassandra cluster
*/
protected CassandraClusterConnection(boolean dropSchema, String infrastructureName) {
- if (clusterName == null || host == null || keyspaceName == null) {
+ if (hosts == null || datacenterName == null || keyspaceName == null) {
RunningCluster cluster = RunningCluster.getInstance(infrastructureName);
- clusterName = cluster.getClusterName();
- host = cluster.getHost();
+ //host = cluster.getHost();
+ hosts = cluster.getHosts();
+ datacenterName = cluster.getDatacenterName();
keyspaceName = cluster.getKeyspaceName();
- }
-
- AstyanaxContext clusterContext = new AstyanaxContext.Builder()
- .forCluster(clusterName)
- .withAstyanaxConfiguration(new AstyanaxConfigurationImpl())
- .withConnectionPoolConfiguration(
- new ConnectionPoolConfigurationImpl(
- clusterName).setMaxConnsPerHost(100)
- .setSeeds(host))
- .withConnectionPoolMonitor(
- new CountingConnectionPoolMonitor())
- .buildCluster(ThriftFamilyFactory.getInstance());
-
+ }
_log.info(keyspaceName + " KeySpace SetUp ...");
- SetUpKeySpaces(clusterContext, dropSchema);
+ SetUpKeySpaces(dropSchema);
+ myKeyspaceSession = connect(keyspaceName);
_log.info("CONNECTED! using KeySpace: " + keyspaceName);
-
- // then close connection pool for cluster
- _log.info("Closing cluster connection pool no longer needed (keyspace one will be used)");
- clusterContext.shutdown();
- _log.info("Closed cluster connection pool no longer needed (keyspace one will be used)");
+ }
+
+ public CqlSession getKeyspaceSession(){
+ if (myKeyspaceSession.isClosed()){
+ myKeyspaceSession = connect(keyspaceName);
+ }
+ return myKeyspaceSession;
}
/**
- * Get the reference to the current keyspace
- * @return keyspace reference
+ * @param dropSchema set true if you want to drop the current and set up new one
+ * the connection to cassandra cluster
*/
- public Keyspace getKeyspace() {
-
- // The Keyspace instance can be shared among different requests
- if(myKeyspace == null){
- synchronized(this){
- if(myKeyspace == null){ // double checked lock
- AstyanaxContext context = new AstyanaxContext.Builder()
- .forCluster(clusterName)
- .forKeyspace(keyspaceName)
- .withAstyanaxConfiguration(
- new AstyanaxConfigurationImpl()
- .setDiscoveryType(NodeDiscoveryType.NONE) // use only the host given as seeds (do not discover)
- .setConnectionPoolType(ConnectionPoolType.ROUND_ROBIN) // how to handle connections of the the connection pool
- )
- .withConnectionPoolConfiguration(
- new ConnectionPoolConfigurationImpl("MyConnectionPool")
- .setMaxConnsPerHost(3) // for each seed(host)
- .setSocketTimeout(2000) //-> default: 11 seconds
- //.setConnectTimeout(1000) -> default: 2 seconds
- .setSeeds(host)
- )
- .withConnectionPoolMonitor(new CountingConnectionPoolMonitor())
- .buildKeyspace(ThriftFamilyFactory.getInstance());
-
-
- context.start();
-
- // save keyspace reference
- myKeyspace = context.getEntity();
-
- }
+ public void SetUpKeySpaces(boolean dropSchema) {
+ boolean createNew = false;
+ boolean found = false;
+ CqlSession session = connect();
+ Metadata metaData = session.getMetadata();
+ for (KeyspaceMetadata meta : metaData.getKeyspaces().values()) {
+ if (meta.getName().toString().equals(keyspaceName)){
+ found = true;
+ break;
}
}
-
- return myKeyspace;
- }
-
- /**
- *
- * @param clusterContext
- * @param dropSchema
- * @throws ConnectionException
- */
- public void SetUpKeySpaces(AstyanaxContext clusterContext, boolean dropSchema) {
- boolean createNew = false;
- clusterContext.start();
try {
- Cluster cluster = clusterContext.getEntity();
- KeyspaceDefinition keyspaceDef = cluster.describeKeyspace(keyspaceName);
-
- if (dropSchema && keyspaceDef != null) {
+ if (dropSchema && found) {
_log.info("Dropping Keyspace: " + keyspaceName + " ...");
try {
- OperationResult returned = cluster.dropKeyspace(keyspaceName);
+ ResultSet returned = dropKeyspace();
Thread.sleep(2000);
- _log.info("Dropped " + returned.getResult().toString());
- } catch (ConnectionException e) {
+ if (returned.wasApplied())
+ _log.info("Dropped " + keyspaceName);
+ else
+ _log.info("Couldn't drop " + keyspaceName);
+ } catch (Exception e) {
_log.error("Dropping Keyspace operation Failed ... " + keyspaceName + " does NOT exists");
return;
- } catch (InterruptedException e) {
- e.printStackTrace();
- }
+ }
createNew = true;
+ }
- }
-
- keyspaceDef = cluster.makeKeyspaceDefinition();
- keyspaceDef = cluster.describeKeyspace(keyspaceName);
-
- if (keyspaceDef == null || keyspaceDef.getName() == null || createNew) {
+ if (!found || createNew) {
_log.info("Keyspace does not exist, triggering schema creation ... ");
- createSchema(cluster);
- _log.info("Cluster " + clusterName + " on " + host + " Initialized OK!");
+ int replicationFactor = 2;
+ createKeyspace(keyspaceName, replicationFactor);
+ closeSession(session);
+ createTables();
_log.info("Using Keyspace " + keyspaceName);
}
- } catch (ConnectionException e) {
+ } catch (Exception e) {
e.printStackTrace();
}
}
-
/*
- *
+ *
********************** CASSANDRA KEYSPACE CREATION ***********************
*
*/
- /**
- * create the databook schema
- * @return
- * @throws ConnectionException
- */
- private void createSchema(Cluster cluster) throws ConnectionException {
-
- Map stratOptions = new HashMap();
- stratOptions.put("replication_factor", "1");
-
- KeyspaceDefinition ksDef = cluster.makeKeyspaceDefinition();
-
- //get static column families with secondary indexes
- /**
- * define Notifications CF with Type as secondary index
- */
- ColumnFamilyDefinition cfDefNotifications = getStaticCFDef(DBCassandraAstyanaxImpl.NOTIFICATIONS, "Type");
- /**
- * define Feeds CF with Privacy as secondary index
- */
- ColumnFamilyDefinition cfDefFeeds = getStaticCFDef(DBCassandraAstyanaxImpl.FEEDS, "Privacy");
- /**
- * define Comments CF with FeedId as secondary index
- */
- ColumnFamilyDefinition cfDefComments = getStaticCFDef(DBCassandraAstyanaxImpl.COMMENTS, "Feedid");
- /**
- * define Likes CF with FeedId as secondary index
- */
- ColumnFamilyDefinition cfDefLikes = getStaticCFDef(DBCassandraAstyanaxImpl.LIKES, "Feedid");
- /**
- * define Invites CF with SenderUserId as secondary index
- */
- ColumnFamilyDefinition cfDefInvites = getStaticCFDef(DBCassandraAstyanaxImpl.INVITES, "SenderUserId");
- /**
- * define Attachments CF with FeedId as secondary index
- */
- ColumnFamilyDefinition cfDefAttachments = getStaticCFDef(DBCassandraAstyanaxImpl.ATTACHMENTS, "feedId");
-
-
- //get dynamic column families, act as auxiliary indexes
- ColumnFamilyDefinition cfDefConn = getDynamicCFDef(DBCassandraAstyanaxImpl.CONNECTIONS);
- ColumnFamilyDefinition cfDefPendingConn = getDynamicCFDef(DBCassandraAstyanaxImpl.PENDING_CONNECTIONS_CF_NAME);
- ColumnFamilyDefinition cfDefVRETimeline = getDynamicCFDef(DBCassandraAstyanaxImpl.VRE_TIMELINE_FEEDS);
- ColumnFamilyDefinition cfDefAPPTimeline = getDynamicCFDef(DBCassandraAstyanaxImpl.APP_TIMELINE_FEEDS);
- ColumnFamilyDefinition cfDefUserTimeline = getDynamicCFDef(DBCassandraAstyanaxImpl.USER_TIMELINE_FEEDS);
- ColumnFamilyDefinition cfDefUserLikedFeeds = getDynamicCFDef(DBCassandraAstyanaxImpl.USER_LIKED_FEEDS);
- ColumnFamilyDefinition cfDefUserNotifications = getDynamicCFDef(DBCassandraAstyanaxImpl.USER_NOTIFICATIONS);
- ColumnFamilyDefinition cfDefUserNotificationsUnread = getDynamicCFDef(DBCassandraAstyanaxImpl.USER_NOTIFICATIONS_UNREAD);
- ColumnFamilyDefinition cfDefUserNotificationsPreferences = getDynamicCFDef(DBCassandraAstyanaxImpl.USER_NOTIFICATIONS_PREFERENCES);
- ColumnFamilyDefinition cfDefEmailInvitesTimeline = getDynamicCFDef(DBCassandraAstyanaxImpl.EMAIL_INVITES);
- ColumnFamilyDefinition cfDefVREInvitesTimeline = getDynamicCFDef(DBCassandraAstyanaxImpl.VRE_INVITES);
- ColumnFamilyDefinition cfDefHashtagsCounter = getDynamicCFDef(DBCassandraAstyanaxImpl.HASHTAGS_COUNTER);
- ColumnFamilyDefinition cfDefHashtagTimeline = getDynamicCFDef(DBCassandraAstyanaxImpl.HASHTAGGED_FEEDS);
- ColumnFamilyDefinition cfDefHashtagCommentsTimeline = getDynamicCFDef(DBCassandraAstyanaxImpl.HASHTAGGED_COMMENTS);
-
-
- ksDef.setName(keyspaceName)
- .setStrategyOptions(stratOptions)
- .setStrategyClass("SimpleStrategy")
- .addColumnFamily(cfDefNotifications)
- .addColumnFamily(cfDefFeeds)
- .addColumnFamily(cfDefComments)
- .addColumnFamily(cfDefLikes)
- .addColumnFamily(cfDefInvites)
- .addColumnFamily(cfDefAttachments)
- .addColumnFamily(cfDefConn)
- .addColumnFamily(cfDefPendingConn)
- .addColumnFamily(cfDefVRETimeline)
- .addColumnFamily(cfDefAPPTimeline)
- .addColumnFamily(cfDefUserTimeline)
- .addColumnFamily(cfDefUserNotifications)
- .addColumnFamily(cfDefUserNotificationsUnread)
- .addColumnFamily(cfDefUserNotificationsPreferences)
- .addColumnFamily(cfDefUserLikedFeeds)
- .addColumnFamily(cfDefEmailInvitesTimeline)
- .addColumnFamily(cfDefVREInvitesTimeline)
- .addColumnFamily(cfDefHashtagsCounter)
- .addColumnFamily(cfDefHashtagTimeline)
- .addColumnFamily(cfDefHashtagCommentsTimeline);
-
- cluster.addKeyspace(ksDef);
+ private static CqlSession connect() {
+ CqlSession cqlSession = configBuilder(CqlSession.builder())
+ .addContactPoints(hosts)
+ .withLocalDatacenter(datacenterName)
+ .build();
+ _log.info("[OK] Connected to Cassandra Cluster");
+ return cqlSession;
+ }
+ private static CqlSession connect(String KEYSPACE_NAME) {
+ CqlSession cqlSession = configBuilder(CqlSession.builder())
+ .addContactPoints(hosts)
+ .withKeyspace(KEYSPACE_NAME)
+ .withLocalDatacenter("1")
+ .build();
+ _log.info("[OK] Connected to Keyspace {} ", KEYSPACE_NAME);
+ return cqlSession;
}
- /**
- * create a dynamic column family to be added in a keyspace
- *
- * @param cfName the CF name
- * @return the instance to be added to the keyspace
- */
- private ColumnFamilyDefinition getDynamicCFDef(String cfName) {
- ColumnFamilyDefinition columnFamilyDefinition = new ThriftColumnFamilyDefinitionImpl();
- columnFamilyDefinition.setName(cfName);
- columnFamilyDefinition.setKeyValidationClass("UTF8Type");
- columnFamilyDefinition.setComparatorType("UTF8Type");
- return columnFamilyDefinition;
+ public static void closeSession(CqlSession session) {
+ if (session != null) session.close();
+ _log.info("[OK]Session is now closed");
}
- /**
- * create a static column family to be added in a keyspace with possibility to add a secondary index for a given column
- *
- * @param cfName the CF name
- * @param secondaryIndexedField the column name of the column to index
- * @return the instance to be added to the keyspace
- */
- private ColumnFamilyDefinition getStaticCFDef(String cfName, String secondaryIndexedField) {
- ColumnFamilyDefinition columnFamilyDefinition = new ThriftColumnFamilyDefinitionImpl();
- columnFamilyDefinition.setName(cfName);
-
- columnFamilyDefinition.setKeyValidationClass("UTF8Type");
- columnFamilyDefinition.setComparatorType("UTF8Type");
-
-
- //Add secondary index for userid
- ColumnDefinition typeCDef = new ThriftColumnDefinitionImpl();
- typeCDef.setName(secondaryIndexedField)
- .setValidationClass("UTF8Type");
- typeCDef.setIndex(secondaryIndexedField+"_"+UUID.randomUUID().toString().substring(0,5), "KEYS");
-
- columnFamilyDefinition.addColumnDefinition(typeCDef);
- return columnFamilyDefinition;
+ public void closeConnection(){
+ if(!myKeyspaceSession.isClosed()){
+ try{
+ _log.info("Closing connection");
+ closeSession(myKeyspaceSession);
+ _log.info("Connection closed!");
+ }catch(Exception e){
+ _log.error("Unable to close connection", e);
+ }
+ }
}
+
+ private static CqlSessionBuilder configBuilder(CqlSessionBuilder cqlSessionBuilder){
+ return cqlSessionBuilder
+ .withConfigLoader(DriverConfigLoader.programmaticBuilder()
+ // Resolves the timeout query 'SELECT * FROM system_schema.tables' timed out after PT2S
+ .withDuration(DefaultDriverOption.METADATA_SCHEMA_REQUEST_TIMEOUT, Duration.ofMillis(240000))
+ .withDuration(DefaultDriverOption.CONNECTION_INIT_QUERY_TIMEOUT, Duration.ofMillis(240000))
+ .withDuration(DefaultDriverOption.REQUEST_TIMEOUT, Duration.ofMillis(240000))
+ .build());
+ }
+ private static void createKeyspace(String keyspaceName, int replicationFactor) {
+ try (CqlSession cqlSession = configBuilder(CqlSession.builder())
+ .addContactPoints(hosts)
+ .withLocalDatacenter("1")
+ .build()) {
+ cqlSession.execute(SchemaBuilder.createKeyspace(keyspaceName)
+ .ifNotExists()
+ .withSimpleStrategy(replicationFactor)
+ .withDurableWrites(true)
+ .build());
+ _log.info("+ Keyspace '{}' created.", keyspaceName);
+ closeSession(cqlSession);
+ }
+ }
+
+ private static ResultSet dropKeyspace(){
+ ResultSet toreturn;
+ try (CqlSession cqlSession = configBuilder(CqlSession.builder())
+ .addContactPoints(hosts)
+ .withLocalDatacenter("1")
+ .build()) {
+ toreturn = cqlSession.execute(SchemaBuilder.dropKeyspace(keyspaceName).ifExists().build());
+ _log.info("Keyspace {} dropped.", keyspaceName);
+ closeSession(cqlSession);
+ }
+ return toreturn;
+ }
+ private void createTables(){
+ try (CqlSession cqlSession = configBuilder(CqlSession.builder())
+ .addContactPoints(hosts)
+ .withLocalDatacenter("1")
+ .withKeyspace(keyspaceName)
+ .build()) {
+
+ createTableUSERNotificationsPreferences(cqlSession);
+ createTableUSERNotifications(cqlSession);
+ createTableVRETimeline(cqlSession);
+ createTableAppTimeline(cqlSession);
+ createTableUSERTimeline(cqlSession);
+ createTableHashtaggedPosts(cqlSession);
+ createTableHashtaggedComments(cqlSession);
+ createTableHashtagsCounter(cqlSession);
+ createTableUSERNotificationsUnread(cqlSession);
+ createTableUSERLikes(cqlSession);
+ createTableVREInvites(cqlSession);
+ createTableEMAILInvites(cqlSession);
+ createTableAttachments(cqlSession);
+ createTableInvites(cqlSession);
+ createTableLikes(cqlSession);
+ createTableComments(cqlSession);
+ createTableNotifications(cqlSession);
+ createTablePosts(cqlSession);
+
+ closeSession(cqlSession);
+ }
+ }
+ private void createTableUSERNotificationsPreferences(CqlSession cqlSession) {
+ cqlSession.execute(SchemaBuilder.createTable("UserNotificationsPreferences")
+ .ifNotExists()
+ .withPartitionKey("userid", DataTypes.TEXT)
+ .withPartitionKey("type", DataTypes.TEXT)
+ .withColumn("preference", DataTypes.TEXT)
+ .withCompactStorage()
+ .build());
+
+ _log.info("+ Table '{}' has been created (if needed).", "USERNotificationsPreferences");
+ }
+ private void createTableUSERNotifications(CqlSession cqlSession) {
+ cqlSession.execute(SchemaBuilder.createTable("UserNotifications")
+ .ifNotExists()
+ .withPartitionKey("userid", DataTypes.TEXT)
+ .withPartitionKey("timestamp", DataTypes.TIMESTAMP)
+ .withColumn("notid", DataTypes.UUID)
+ .withCompactStorage()
+ .build());
+
+ _log.info("+ Table '{}' has been created (if needed).", "USERNotifications");
+ }
+ private void createTableVRETimeline(CqlSession cqlSession) {
+ cqlSession.execute(SchemaBuilder.createTable("VRETimeline")
+ .ifNotExists()
+ .withPartitionKey("vreid", DataTypes.TEXT)
+ .withPartitionKey("timestamp", DataTypes.TIMESTAMP)
+ .withColumn("postid", DataTypes.UUID)
+ .withCompactStorage()
+ .build());
+
+ _log.info("+ Table '{}' has been created (if needed).", "VRETimeline");
+ }
+ private void createTableAppTimeline(CqlSession cqlSession) {
+ cqlSession.execute(SchemaBuilder.createTable("AppTimeline")
+ .ifNotExists()
+ .withPartitionKey("appid", DataTypes.TEXT)
+ .withPartitionKey("timestamp", DataTypes.TIMESTAMP)
+ .withColumn("postid", DataTypes.UUID)
+ .withCompactStorage()
+ .build());
+
+ _log.info("+ Table '{}' has been created (if needed).", "AppTimeline");
+ }
+ private void createTableUSERTimeline(CqlSession cqlSession) {
+ cqlSession.execute(SchemaBuilder.createTable("UserTimeline")
+ .ifNotExists()
+ .withPartitionKey("userid", DataTypes.TEXT)
+ .withPartitionKey("timestamp", DataTypes.TIMESTAMP)
+ .withColumn("postid", DataTypes.UUID)
+ .withCompactStorage()
+ .build());
+ _log.info("+ Table '{}' has been created (if needed).", "USERTimeline");
+ }
+ private void createTableHashtaggedPosts(CqlSession cqlSession) {
+ cqlSession.execute(SchemaBuilder.createTable("HashtaggedPosts")
+ .ifNotExists()
+ .withPartitionKey("hashtag", DataTypes.TEXT)
+ .withPartitionKey("postid", DataTypes.UUID)
+ .withColumn("vreid", DataTypes.TEXT)
+ .withCompactStorage()
+ .build());
+
+ _log.info("+ Table '{}' has been created (if needed).", "HashtaggedPosts");
+ }
+ private void createTableHashtaggedComments(CqlSession cqlSession) {
+ cqlSession.execute(SchemaBuilder.createTable("HashtaggedComments")
+ .ifNotExists()
+ .withPartitionKey("hashtag", DataTypes.TEXT)
+ .withPartitionKey("commentid", DataTypes.UUID)
+ .withColumn("vreid", DataTypes.TEXT)
+ .withCompactStorage()
+ .build());
+
+ _log.info("+ Table '{}' has been created (if needed).", "HashtaggedComments");
+ }
+ private void createTableHashtagsCounter(CqlSession cqlSession) {
+ cqlSession.execute(SchemaBuilder.createTable("HashtagsCounter")
+ .ifNotExists()
+ .withPartitionKey("vreid", DataTypes.TEXT)
+ .withPartitionKey("hashtag", DataTypes.TEXT)
+ .withColumn("count", DataTypes.BIGINT)
+ .withCompactStorage()
+ .build());
+
+ _log.info("+ Table '{}' has been created (if needed).", "HashtagsCounter");
+ }
+ private void createTableUSERNotificationsUnread(CqlSession cqlSession) {
+ cqlSession.execute(SchemaBuilder.createTable("UserUnreadNotifications")
+ .ifNotExists()
+ .withPartitionKey("userid", DataTypes.TEXT)
+ .withPartitionKey("timestamp", DataTypes.TIMESTAMP)
+ .withColumn("notid", DataTypes.UUID)
+ .withCompactStorage()
+ .build());
+ _log.info("+ Table '{}' has been created (if needed).", "USERNotificationsUnread");
+ }
+ private void createTableUSERLikes(CqlSession cqlSession) {
+ cqlSession.execute(SchemaBuilder.createTable("UserLikes")
+ .ifNotExists()
+ .withPartitionKey("userid", DataTypes.TEXT)
+ .withPartitionKey("likeid", DataTypes.UUID)
+ .withColumn("postid", DataTypes.UUID)
+ .withCompactStorage()
+ .build());
+
+ _log.info("+ Table '{}' has been created (if needed).", "USERLikes");
+ }
+ private void createTableVREInvites(CqlSession cqlSession) {
+ cqlSession.execute(SchemaBuilder.createTable("VREInvites")
+ .ifNotExists()
+ .withPartitionKey("vreid", DataTypes.TEXT)
+ .withPartitionKey("inviteid", DataTypes.UUID)
+ .withColumn("status", DataTypes.TEXT)
+ .withCompactStorage()
+ .build());
+
+ _log.info("+ Table '{}' has been created (if needed).", "VREInvites");
+ }
+ private void createTableEMAILInvites(CqlSession cqlSession) {
+ cqlSession.execute(SchemaBuilder.createTable("EmailInvites")
+ .ifNotExists()
+ .withPartitionKey("email", DataTypes.TEXT)
+ .withPartitionKey("vreid", DataTypes.TEXT)
+ .withColumn("inviteid", DataTypes.UUID)
+ .withCompactStorage()
+ .build());
+ _log.info("+ Table '{}' has been created (if needed).", "EMAILInvites");
+ }
+ private void createTableAttachments(CqlSession cqlSession) {
+ cqlSession.execute(SchemaBuilder.createTable("Attachments")
+ .ifNotExists()
+ .withPartitionKey("attachid", DataTypes.UUID)
+ .withColumn("postid", DataTypes.UUID)
+ .withColumn("uri", DataTypes.TEXT)
+ .withColumn("name", DataTypes.TEXT)
+ .withColumn("description", DataTypes.TEXT)
+ .withColumn("urithumbnail", DataTypes.TEXT)
+ .withColumn("mimetype", DataTypes.TEXT)
+ .withCompactStorage()
+ .build());
+ cqlSession.execute(SchemaBuilder.createIndex("post_attach")
+ .ifNotExists()
+ .onTable("Attachments")
+ .andColumn("postid")
+ .build());
+
+ _log.info("+ Table '{}' has been created (if needed).", "Attachments");
+ }
+ private void createTableInvites(CqlSession cqlSession) {
+ cqlSession.execute(SchemaBuilder.createTable("Invites")
+ .ifNotExists()
+ .withPartitionKey("inviteid", DataTypes.UUID)
+ .withColumn("senderuserid", DataTypes.TEXT)
+ .withColumn("vreid", DataTypes.TEXT)
+ .withColumn("email", DataTypes.TEXT)
+ .withColumn("controlcode", DataTypes.TEXT)
+ .withColumn("status", DataTypes.TEXT)
+ .withColumn("timestamp", DataTypes.TIMESTAMP)
+ .withColumn("senderfullname", DataTypes.TEXT)
+ .withCompactStorage()
+ .build());
+ cqlSession.execute(SchemaBuilder.createIndex("sender")
+ .ifNotExists()
+ .onTable("Invites")
+ .andColumn("senderuserid")
+ .build());
+
+ _log.info("+ Table '{}' has been created (if needed).", "Invites");
+ }
+ private void createTableLikes(CqlSession cqlSession) {
+ cqlSession.execute(SchemaBuilder.createTable("Likes")
+ .ifNotExists()
+ .withPartitionKey("likeid", DataTypes.UUID)
+ .withColumn("userid", DataTypes.TEXT)
+ .withColumn("fullname", DataTypes.TEXT)
+ .withColumn("thumbnailurl", DataTypes.TEXT)
+ .withColumn("postid", DataTypes.UUID)
+ .withColumn("timestamp", DataTypes.TIMESTAMP)
+ .withCompactStorage()
+ .build());
+ cqlSession.execute(SchemaBuilder.createIndex("post_likes")
+ .ifNotExists()
+ .onTable("Likes")
+ .andColumn("postid")
+ .build());
+
+ _log.info("+ Table '{}' has been created (if needed).", "Likes");
+ }
+ private void createTableComments(CqlSession cqlSession) {
+ cqlSession.execute(SchemaBuilder.createTable("Comments")
+ .ifNotExists()
+ .withPartitionKey("commentid", DataTypes.UUID)
+ .withColumn("userid", DataTypes.TEXT)
+ .withColumn("fullname", DataTypes.TEXT)
+ .withColumn("thumbnailurl", DataTypes.TEXT)
+ .withColumn("comment", DataTypes.TEXT)
+ .withColumn("postid", DataTypes.UUID)
+ .withColumn("timestamp", DataTypes.TIMESTAMP)
+ .withColumn("isedit", DataTypes.BOOLEAN)
+ .withColumn("lastedittime", DataTypes.TIMESTAMP)
+ .withCompactStorage()
+ .build());
+ cqlSession.execute(SchemaBuilder.createIndex("post_comments")
+ .ifNotExists()
+ .onTable("Comments")
+ .andColumn("postid")
+ .build());
+
+ _log.info("+ Table '{}' has been created (if needed).", "Comments");
+ }
+ private void createTableNotifications(CqlSession cqlSession) {
+ cqlSession.execute(SchemaBuilder.createTable("Notifications")
+ .ifNotExists()
+ .withPartitionKey("notid", DataTypes.UUID)
+ .withColumn("type", DataTypes.TEXT)
+ .withColumn("userid", DataTypes.TEXT)
+ .withColumn("subjectid", DataTypes.TEXT)
+ .withColumn("timestamp", DataTypes.TIMESTAMP)
+ .withColumn("description", DataTypes.TEXT)
+ .withColumn("uri", DataTypes.TEXT)
+ .withColumn("senderid", DataTypes.TEXT)
+ .withColumn("senderfullname", DataTypes.TEXT)
+ .withColumn("senderthumbnailurl", DataTypes.TEXT)
+ .withColumn("isread", DataTypes.BOOLEAN)
+ .withCompactStorage()
+ .build());
+ cqlSession.execute(SchemaBuilder.createIndex("not_type")
+ .ifNotExists()
+ .onTable("Notifications")
+ .andColumn("type")
+ .build());
+ _log.info("+ Table '{}' has been created (if needed).", "Notifications");
+ }
+ private void createTablePosts(CqlSession cqlSession) {
+ cqlSession.execute(SchemaBuilder.createTable("Posts")
+ .ifNotExists()
+ .withPartitionKey("postid", DataTypes.UUID)
+ .withColumn("linkhost", DataTypes.TEXT)
+ .withColumn("description", DataTypes.TEXT)
+ .withColumn("email", DataTypes.TEXT)
+ .withColumn("likesno", DataTypes.BIGINT)
+ .withColumn("thumbnailurl", DataTypes.TEXT)
+ .withColumn("linkdescription", DataTypes.TEXT)
+ .withColumn("timestamp", DataTypes.TIMESTAMP)
+ .withColumn("uri", DataTypes.TEXT)
+ .withColumn("isapplicationpost", DataTypes.BOOLEAN)
+ .withColumn("entityid", DataTypes.TEXT)
+ .withColumn("privacy", DataTypes.TEXT)
+ .withColumn("type", DataTypes.TEXT)
+ .withColumn("urithumbnail", DataTypes.TEXT)
+ .withColumn("vreid", DataTypes.TEXT)
+ .withColumn("multifileupload", DataTypes.BOOLEAN)
+ .withColumn("fullname", DataTypes.TEXT)
+ .withColumn("commentsno", DataTypes.BIGINT)
+ .withColumn("linktitle", DataTypes.TEXT)
+ .withCompactStorage()
+ .build());
+ cqlSession.execute(SchemaBuilder.createIndex("posts_privacy")
+ .ifNotExists()
+ .onTable("Posts")
+ .andColumn("privacy")
+ .build());
+
+ _log.info("+ Table '{}' has been created (if needed).", "Posts");
+ }
+
}
diff --git a/src/main/java/org/gcube/portal/databook/server/DBCassandraAstyanaxImpl.java b/src/main/java/org/gcube/portal/databook/server/DBCassandraAstyanaxImpl.java
deleted file mode 100644
index c426315..0000000
--- a/src/main/java/org/gcube/portal/databook/server/DBCassandraAstyanaxImpl.java
+++ /dev/null
@@ -1,3433 +0,0 @@
-package org.gcube.portal.databook.server;
-
-import java.util.ArrayList;
-import java.util.Arrays;
-import java.util.Calendar;
-import java.util.Collections;
-import java.util.Date;
-import java.util.HashMap;
-import java.util.HashSet;
-import java.util.List;
-import java.util.Map;
-import java.util.Set;
-import java.util.concurrent.atomic.AtomicInteger;
-
-import javax.mail.internet.AddressException;
-import javax.mail.internet.InternetAddress;
-
-import org.apache.commons.lang.NullArgumentException;
-import org.gcube.portal.databook.shared.Attachment;
-import org.gcube.portal.databook.shared.Comment;
-import org.gcube.portal.databook.shared.Feed;
-import org.gcube.portal.databook.shared.FeedType;
-import org.gcube.portal.databook.shared.Invite;
-import org.gcube.portal.databook.shared.InviteOperationResult;
-import org.gcube.portal.databook.shared.InviteStatus;
-import org.gcube.portal.databook.shared.Like;
-import org.gcube.portal.databook.shared.Notification;
-import org.gcube.portal.databook.shared.NotificationChannelType;
-import org.gcube.portal.databook.shared.NotificationType;
-import org.gcube.portal.databook.shared.Post;
-import org.gcube.portal.databook.shared.PostType;
-import org.gcube.portal.databook.shared.PrivacyLevel;
-import org.gcube.portal.databook.shared.RangeFeeds;
-import org.gcube.portal.databook.shared.RangePosts;
-import org.gcube.portal.databook.shared.ex.ColumnNameNotFoundException;
-import org.gcube.portal.databook.shared.ex.CommentIDNotFoundException;
-import org.gcube.portal.databook.shared.ex.FeedIDNotFoundException;
-import org.gcube.portal.databook.shared.ex.FeedTypeNotFoundException;
-import org.gcube.portal.databook.shared.ex.InviteIDNotFoundException;
-import org.gcube.portal.databook.shared.ex.InviteStatusNotFoundException;
-import org.gcube.portal.databook.shared.ex.LikeIDNotFoundException;
-import org.gcube.portal.databook.shared.ex.NotificationChannelTypeNotFoundException;
-import org.gcube.portal.databook.shared.ex.NotificationIDNotFoundException;
-import org.gcube.portal.databook.shared.ex.NotificationTypeNotFoundException;
-import org.gcube.portal.databook.shared.ex.PrivacyLevelTypeNotFoundException;
-import org.slf4j.Logger;
-import org.slf4j.LoggerFactory;
-
-import com.netflix.astyanax.MutationBatch;
-import com.netflix.astyanax.RowCallback;
-import com.netflix.astyanax.connectionpool.OperationResult;
-import com.netflix.astyanax.connectionpool.exceptions.ConnectionException;
-import com.netflix.astyanax.model.Column;
-import com.netflix.astyanax.model.ColumnFamily;
-import com.netflix.astyanax.model.ColumnList;
-import com.netflix.astyanax.model.Row;
-import com.netflix.astyanax.model.Rows;
-import com.netflix.astyanax.query.PreparedIndexExpression;
-import com.netflix.astyanax.serializers.StringSerializer;
-import com.netflix.astyanax.util.RangeBuilder;
-/**
- * @author Massimiliano Assante ISTI-CNR
- * @author Costantino Perciante ISTI-CNR
- * This class is used for querying and adding data to Cassandra via Astyanax High Level API
- */
-public final class DBCassandraAstyanaxImpl implements DatabookStore {
-
- /**
- * logger
- */
- private static final Logger _log = LoggerFactory.getLogger(DBCassandraAstyanaxImpl.class);
- /**
- * Column Family names
- */
- public static final String CONNECTIONS = "Connections";
- public static final String PENDING_CONNECTIONS_CF_NAME = "PendingConnections";
- public static final String NOTIFICATIONS = "Notifications";
- public static final String FEEDS = "Feeds";
- public static final String COMMENTS = "Comments";
- public static final String LIKES = "Likes";
- public static final String INVITES = "Invites";
- public static final String VRE_TIMELINE_FEEDS = "VRETimeline";
- public static final String USER_TIMELINE_FEEDS = "USERTimeline";
- public static final String APP_TIMELINE_FEEDS = "AppTimeline";
- public static final String USER_LIKED_FEEDS = "USERLikes";
- public static final String USER_NOTIFICATIONS = "USERNotifications"; // regular user notifications timeline (both read and unread, messages are included)
- public static final String USER_NOTIFICATIONS_UNREAD = "USERNotificationsUnread"; // only unread user notifications/ notifications messages
- public static final String USER_NOTIFICATIONS_PREFERENCES = "USERNotificationsPreferences"; // preferences for notifications
- public static final String HASHTAGS_COUNTER = "HashtagsCounter"; // count the hashtags per group and type
- public static final String HASHTAGGED_FEEDS = "HashtaggedFeeds"; // contains hashtags per type associated with vre and feed
- public static final String HASHTAGGED_COMMENTS = "HashtaggedComments"; // contains hashtags per type associated with vre and comment
- public static final String VRE_INVITES = "VREInvites"; //contains the emails that were invited per VRE
- public static final String EMAIL_INVITES = "EMAILInvites"; //contains the list of invitation per email
- public static final String ATTACHMENTS = "Attachments"; //contains the list of all the attachments in a feed
- public static final String FEED_ATTACHMENTS = "FeedAttachments"; //contains the list of all the attachments for a given feed (dynamic CF)
-
-
- private static ColumnFamily cf_Connections = new ColumnFamily(
- CONNECTIONS, // Column Family Name
- StringSerializer.get(), // Key Serializer
- StringSerializer.get()); // Column Serializer
- private static ColumnFamily cf_PendingConnections = new ColumnFamily(
- PENDING_CONNECTIONS_CF_NAME, // Column Family Name
- StringSerializer.get(), // Key Serializer
- StringSerializer.get()); // Column Serializer
- private static ColumnFamily cf_Feeds = new ColumnFamily(
- FEEDS, // Column Family Name
- StringSerializer.get(), // Key Serializer
- StringSerializer.get()); // Column Serializer
- private static ColumnFamily cf_UserTline = new ColumnFamily(
- USER_TIMELINE_FEEDS, // Column Family Name
- StringSerializer.get(), // Key Serializer
- StringSerializer.get()); // Column Serializer
-
- private static ColumnFamily cf_VRETline = new ColumnFamily(
- VRE_TIMELINE_FEEDS, // Column Family Name
- StringSerializer.get(), // Key Serializer
- StringSerializer.get()); // Column Serializer
-
- private static ColumnFamily cf_AppTline = new ColumnFamily(
- APP_TIMELINE_FEEDS, // Column Family Name
- StringSerializer.get(), // Key Serializer
- StringSerializer.get()); // Column Serializer
-
- private static ColumnFamily cf_Comments = new ColumnFamily(
- COMMENTS, // Column Family Name
- StringSerializer.get(), // Key Serializer
- StringSerializer.get()); // Column Serializer
- private static ColumnFamily cf_Likes = new ColumnFamily(
- LIKES, // Column Family Name
- StringSerializer.get(), // Key Serializer
- StringSerializer.get()); // Column Serializer
- private static ColumnFamily cf_Invites = new ColumnFamily(
- INVITES, // Column Family Name
- StringSerializer.get(), // Key Serializer
- StringSerializer.get()); // Column Serializer
- private static ColumnFamily cf_UserLikedFeeds = new ColumnFamily(
- USER_LIKED_FEEDS, // Column Family Name
- StringSerializer.get(), // Key Serializer
- StringSerializer.get()); // Column Serializer
- private static ColumnFamily cf_Notifications = new ColumnFamily(
- NOTIFICATIONS, // Column Family Name
- StringSerializer.get(), // Key Serializer
- StringSerializer.get()); // Column Serializer
- private static ColumnFamily cf_UserNotifications = new ColumnFamily(
- USER_NOTIFICATIONS, // Column Family Name
- StringSerializer.get(), // Key Serializer
- StringSerializer.get()); // Column Serializer
- private static ColumnFamily cf_UserNotificationsUnread = new ColumnFamily(
- USER_NOTIFICATIONS_UNREAD, // Column Family Name
- StringSerializer.get(), // Key Serializer
- StringSerializer.get()); // Column Serializer
- protected static ColumnFamily cf_UserNotificationsPreferences = new ColumnFamily(
- USER_NOTIFICATIONS_PREFERENCES, // Column Family Name
- StringSerializer.get(), // Key Serializer
- StringSerializer.get()); // Column Serializer
- private static ColumnFamily cf_HashtagsCounter = new ColumnFamily(
- HASHTAGS_COUNTER, // Column Family Name
- StringSerializer.get(), // Key Serializer
- StringSerializer.get()); // Column Serializer
- protected static ColumnFamily cf_HashtagTimelineFeed = new ColumnFamily(
- HASHTAGGED_FEEDS, // Column Family Name
- StringSerializer.get(), // Key Serializer
- StringSerializer.get()); // Column Serializer
- protected static ColumnFamily cf_HashtagTimelineComment = new ColumnFamily(
- HASHTAGGED_COMMENTS, // Column Family Name
- StringSerializer.get(), // Key Serializer
- StringSerializer.get()); // Column Serializer
- private static ColumnFamily cf_VREInvites = new ColumnFamily(
- VRE_INVITES, // Column Family Name
- StringSerializer.get(), // Key Serializer
- StringSerializer.get()); // Column Serializer
- protected static ColumnFamily cf_EmailInvites = new ColumnFamily(
- EMAIL_INVITES, // Column Family Name
- StringSerializer.get(), // Key Serializer
- StringSerializer.get()); // Column Serializer
-
- protected static ColumnFamily cf_Attachments = new ColumnFamily(
- ATTACHMENTS, // Column Family Name
- StringSerializer.get(), // Key Serializer
- StringSerializer.get()); // Column Serializer
-
- /**
- * connection instance
- */
- private CassandraClusterConnection conn;
-
- protected CassandraClusterConnection getConnection() {
- return conn;
- }
- /**
- * use this constructor carefully from test classes
- * @param dropSchema set true if you want do drop the current and set up new one
- */
- protected DBCassandraAstyanaxImpl(boolean dropSchema) {
- conn = new CassandraClusterConnection(dropSchema);
- }
- /**
- * public constructor, no dropping schema is allowed
- */
- public DBCassandraAstyanaxImpl() {
- conn = new CassandraClusterConnection(false);
- }
-
- /**
- * public constructor, no dropping schema is allowed, infrastructureName is given.
- */
- public DBCassandraAstyanaxImpl(String infrastructureName) {
- conn = new CassandraClusterConnection(false, infrastructureName);
- }
-
- /**
- * execute the mutation batch
- * @param m
- * @return true if everything went fine
- */
- private boolean execute(MutationBatch m) {
- try {
- m.execute();
- } catch (ConnectionException e) {
- e.printStackTrace();
- return false;
- }
- return true;
- }
- /*
- *
- ********************** FRIENDSHIPS (CONNECTIONS) ***********************
- *
- */
- /**
- * {@inheritDoc}
- */
- @Override
- public boolean requestFriendship(String from, String to) {
-
- MutationBatch m = conn.getKeyspace().prepareMutationBatch();
- m.withRow(cf_PendingConnections, to).putColumn(from, "", null);
- try {
- m.execute();
- } catch (ConnectionException e) {
- e.printStackTrace();
- return false;
- }
- _log.info(from + " has requested a connection to " + to);
- return true;
- }
- /**
- * {@inheritDoc}
- */
- @Override
- public boolean approveFriendship(String from, String to) {
-
- MutationBatch m = conn.getKeyspace().prepareMutationBatch();
- m.withRow(cf_Connections, to).putColumn(from, "", null);
- m.withRow(cf_Connections, from).putColumn(to, "", null);
- // Deleting a standard column
- m.withRow(cf_PendingConnections, from).deleteColumn(to);
- boolean result = execute(m);
- if (result)
- _log.info(from + " and " + to + " are now connected");
- return result;
- }
- /**
- * {@inheritDoc}
- */
- @Override
- public boolean denyFriendship(String from, String to) {
- // Deleting data
- MutationBatch m = conn.getKeyspace().prepareMutationBatch();
- m.withRow(cf_PendingConnections, from).deleteColumn(to);
- boolean result = execute(m);
- if (result)
- _log.info(from + " has denied connection to " + to);
- return result;
- }
- /**
- * {@inheritDoc}
- */
- @Override
- public List getFriends(String userid) {
- OperationResult> result = null;
- try {
- result = conn.getKeyspace().prepareQuery(cf_Connections)
- .getKeySlice(userid)
- .execute();
- } catch (ConnectionException e) {
- e.printStackTrace();
- return null;
- }
-
- ArrayList toReturn = new ArrayList();
-
- // Iterate rows and their columns
- for (Row row : result.getResult()) {
- for (Column column : row.getColumns()) {
- toReturn.add(column.getName());
- }
- }
- return toReturn;
- }
- /**
- * {@inheritDoc}
- */
- @Override
- public List getPendingFriendRequests(String userid) {
- OperationResult> result = null;
- try {
- result = conn.getKeyspace().prepareQuery(cf_PendingConnections)
- .getKeySlice(userid)
- .execute();
- } catch (ConnectionException e) {
- e.printStackTrace();
- return null;
- }
-
- ArrayList toReturn = new ArrayList();
-
- // Iterate rows and their columns
- for (Row row : result.getResult()) {
- for (Column column : row.getColumns()) {
- toReturn.add(column.getName());
- }
- }
- return toReturn;
- }
- /*
- *
- ********************** FEEDS ***********************
- *
- */
- /**
- * common part to save a feed
- * @deprecated
- * @param feed
- * @return the partial mutation batch instance
- */
- private MutationBatch initSaveFeed(Feed feed) {
- // Inserting data
- MutationBatch m = conn.getKeyspace().prepareMutationBatch();
- //an entry in the feed CF
- m.withRow(cf_Feeds, feed.getKey().toString())
- .putColumn("Entityid", feed.getEntityId(), null)
- .putColumn("Time", feed.getTime().getTime()+"", null)
- .putColumn("Vreid", feed.getVreid(), null)
- .putColumn("Uri", feed.getUri(), null)
- .putColumn("UriThumbnail", feed.getUriThumbnail(), null)
- .putColumn("Description", feed.getDescription(), null)
- .putColumn("Privacy", feed.getPrivacy().toString(), null)
- .putColumn("FullName", feed.getFullName(), null)
- .putColumn("Type", feed.getType().toString(), null)
- .putColumn("Email", feed.getEmail(), null)
- .putColumn("ThumbnailURL", feed.getThumbnailURL(), null)
- .putColumn("CommentsNo", feed.getCommentsNo(), null)
- .putColumn("LikesNo", feed.getLikesNo(), null)
- .putColumn("LinkTitle", feed.getLinkTitle(), null)
- .putColumn("LinkDescription", feed.getLinkDescription(), null)
- .putColumn("LinkHost", feed.getLinkHost(), null)
- .putColumn("IsApplicationFeed", feed.isApplicationFeed(), null)
- .putColumn("multiFileUpload", feed.isMultiFileUpload(), null);
- return m;
- }
- /**
- * common part to save a feed
- * @param post
- * @return the partial mutation batch instance
- */
- private MutationBatch initSavePost(Post post) {
- // Inserting data
- MutationBatch m = conn.getKeyspace().prepareMutationBatch();
- //an entry in the feed CF
- m.withRow(cf_Feeds, post.getKey().toString())
- .putColumn("Entityid", post.getEntityId(), null)
- .putColumn("Time", post.getTime().getTime()+"", null)
- .putColumn("Vreid", post.getVreid(), null)
- .putColumn("Uri", post.getUri(), null)
- .putColumn("UriThumbnail", post.getUriThumbnail(), null)
- .putColumn("Description", post.getDescription(), null)
- .putColumn("Privacy", post.getPrivacy().toString(), null)
- .putColumn("FullName", post.getFullName(), null)
- .putColumn("Type", post.getType().toString(), null)
- .putColumn("Email", post.getEmail(), null)
- .putColumn("ThumbnailURL", post.getThumbnailURL(), null)
- .putColumn("CommentsNo", post.getCommentsNo(), null)
- .putColumn("LikesNo", post.getLikesNo(), null)
- .putColumn("LinkTitle", post.getLinkTitle(), null)
- .putColumn("LinkDescription", post.getLinkDescription(), null)
- .putColumn("LinkHost", post.getLinkHost(), null)
- .putColumn("IsApplicationFeed", post.isApplicationFeed(), null)
- .putColumn("multiFileUpload", post.isMultiFileUpload(), null);
- return m;
- }
- /**
- * {@inheritDoc}
- */
- @Deprecated
- @Override
- public boolean saveUserFeed(Feed feed) {
- MutationBatch m = initSaveFeed(feed);
-
- //an entry in the user Timeline
- m.withRow(cf_UserTline, feed.getEntityId())
- .putColumn(feed.getTime().getTime()+"", feed.getKey().toString(), null);
-
- //an entry in the VRES Timeline iff vreid field is not empty
- if (feed.getVreid() != null && feed.getVreid().compareTo("") != 0) {
- //an entry in the VRES Timeline
- m.withRow(cf_VRETline, feed.getVreid())
- .putColumn(feed.getTime().getTime()+"", feed.getKey().toString(), null);
- }
- return execute(m);
- }
- /**
- * {@inheritDoc}
- */
- @Override
- public boolean saveUserPost(Post post) {
- MutationBatch m = initSavePost(post);
-
- //an entry in the user Timeline
- m.withRow(cf_UserTline, post.getEntityId())
- .putColumn(post.getTime().getTime()+"", post.getKey().toString(), null);
-
- //an entry in the VRES Timeline iff vreid field is not empty
- if (post.getVreid() != null && post.getVreid().compareTo("") != 0) {
- //an entry in the VRES Timeline
- m.withRow(cf_VRETline, post.getVreid())
- .putColumn(post.getTime().getTime()+"", post.getKey().toString(), null);
- }
- return execute(m);
- }
- /**
- * {@inheritDoc}
- */
- @Deprecated
- @Override
- public boolean saveUserFeed(Feed feed, List attachments) {
- if (attachments != null && !attachments.isEmpty())
- feed.setMultiFileUpload(true);
- boolean saveFeedResult = saveUserFeed(feed);
- if (saveFeedResult) {
- String feedKey = feed.getKey();
- for (Attachment attachment : attachments) {
- boolean attachSaveResult = saveAttachmentEntry(feedKey, attachment);
- if (!attachSaveResult)
- _log.warn("Some of the attachments failed to me saved: " + attachment.getName());
- }
- return true;
- }
- else return false;
- }
- /**
- * {@inheritDoc}
- */
- @Override
- public boolean saveUserPost(Post post, List attachments) {
- if (attachments != null && !attachments.isEmpty())
- post.setMultiFileUpload(true);
- boolean saveFeedResult = saveUserPost(post);
- if (saveFeedResult) {
- String postkey = post.getKey();
- for (Attachment attachment : attachments) {
- boolean attachSaveResult = saveAttachmentEntry(postkey, attachment);
- if (!attachSaveResult)
- _log.warn("Some of the attachments failed to be saved: " + attachment.getName());
- }
- return true;
- }
- else return false;
- }
-
- /**
- * {@inheritDoc}
- */
- @Override
- @Deprecated
- public boolean saveAppFeed(Feed feed) {
- MutationBatch m = initSaveFeed(feed);
-
- //an entry in the Applications Timeline
- m.withRow(cf_AppTline, feed.getEntityId())
- .putColumn(feed.getTime().getTime()+"", feed.getKey().toString(), null);
-
- //an entry in the VRES Timeline iff vreid field is not empty
- if (feed.getVreid() != null && feed.getVreid().compareTo("") != 0) {
- //an entry in the VRES Timeline
- m.withRow(cf_VRETline, feed.getVreid())
- .putColumn(feed.getTime().getTime()+"", feed.getKey().toString(), null);
- }
- boolean result = execute(m);
- if (result)
- _log.trace("saveAppFeed OK!");
- return result;
- }
- /**
- * {@inheritDoc}
- */
- @Override
- public boolean saveAppPost(Post post) {
- MutationBatch m = initSavePost(post);
-
- //an entry in the Applications Timeline
- m.withRow(cf_AppTline, post.getEntityId())
- .putColumn(post.getTime().getTime()+"", post.getKey().toString(), null);
-
- //an entry in the VRES Timeline iff vreid field is not empty
- if (post.getVreid() != null && post.getVreid().compareTo("") != 0) {
- //an entry in the VRES Timeline
- m.withRow(cf_VRETline, post.getVreid())
- .putColumn(post.getTime().getTime()+"", post.getKey().toString(), null);
- }
- boolean result = execute(m);
- if (result)
- _log.trace("saveAppFeed OK!");
- return result;
- }
- /**
- * {@inheritDoc}
- */
- @Deprecated
- @Override
- public boolean saveAppFeed(Feed feed, List attachments) {
- if (attachments != null && !attachments.isEmpty())
- feed.setMultiFileUpload(true);
- boolean saveFeedResult = saveAppFeed(feed);
- if (saveFeedResult) {
- String feedKey = feed.getKey();
- for (Attachment attachment : attachments) {
- boolean attachSaveResult = saveAttachmentEntry(feedKey, attachment);
- if (!attachSaveResult)
- _log.warn("Some of the attachments failed to me saved: " + attachment.getName());
- }
- return true;
- }
- else return false;
- }
- /**
- * {@inheritDoc}
- */
- @Override
- public boolean saveAppPost(Post post, List attachments) {
- if (attachments != null && !attachments.isEmpty())
- post.setMultiFileUpload(true);
- boolean saveFeedResult = saveAppPost(post);
- if (saveFeedResult) {
- String feedKey = post.getKey();
- for (Attachment attachment : attachments) {
- boolean attachSaveResult = saveAttachmentEntry(feedKey, attachment);
- if (!attachSaveResult)
- _log.warn("Some of the attachments failed to be saved: " + attachment.getName());
- }
- return true;
- }
- else return false;
- }
- /**
- * {@inheritDoc}
- */
- @Deprecated
- @Override
- public boolean saveFeedToVRETimeline(String feedKey, String vreid) throws FeedIDNotFoundException {
- String feedId = feedKey;
- Feed toCheck = null;
- try {
- toCheck = readFeed(feedId);
- if (toCheck == null)
- throw new FeedIDNotFoundException("Could not find Feed with id " + feedId, feedId);
- } catch (Exception e) {
- e.printStackTrace();
- return false;
- }
- MutationBatch m = conn.getKeyspace().prepareMutationBatch();
-
- //an entry in the user Timeline
- m.withRow(cf_VRETline, vreid)
- .putColumn(toCheck.getTime().getTime()+"", feedKey, null);
- return execute(m);
- }
- /**
- * {@inheritDoc}
- */
- @Override
- public boolean savePostToVRETimeline(String postKey, String vreid) throws FeedIDNotFoundException {
- String postId = postKey;
- Post toCheck = null;
- try {
- toCheck = readPost(postId);
- if (toCheck == null)
- throw new FeedIDNotFoundException("Could not find Post with id " + postId, postId);
- } catch (Exception e) {
- e.printStackTrace();
- return false;
- }
- MutationBatch m = conn.getKeyspace().prepareMutationBatch();
-
- //an entry in the user Timeline
- m.withRow(cf_VRETline, vreid)
- .putColumn(toCheck.getTime().getTime()+"", postKey, null);
- return execute(m);
- }
- /**
- * {@inheritDoc}
- */
- @Deprecated
- @Override
- public Feed readFeed(String feedid)
- throws PrivacyLevelTypeNotFoundException,
- FeedTypeNotFoundException, FeedIDNotFoundException, ColumnNameNotFoundException {
- Feed toReturn = new Feed();
- OperationResult> result;
- try {
- result = conn.getKeyspace().prepareQuery(cf_Feeds)
- .getKey(feedid)
- .execute();
-
- ColumnList columns = result.getResult();
- if (columns.size() == 0) {
- throw new FeedIDNotFoundException("The requested feedid: " + feedid + " is not existing", feedid);
- }
-
- toReturn.setKey(feedid);
- toReturn.setDescription(columns.getColumnByName("Description").getStringValue());
- toReturn.setEmail(columns.getColumnByName("Email").getStringValue());
- toReturn.setFullName(columns.getColumnByName("FullName").getStringValue());
- toReturn.setPrivacy(getPrivacyLevel(columns.getColumnByName("Privacy").getStringValue()));
- toReturn.setThumbnailURL(columns.getColumnByName("ThumbnailURL").getStringValue());
- toReturn.setTime(getDateFromTimeInMillis(columns.getColumnByName("Time").getStringValue()));
-
- FeedType ft = getFeedType(columns.getColumnByName("Type").getStringValue());
-
- toReturn.setType(ft);
- toReturn.setUri(columns.getColumnByName("Uri").getStringValue());
- toReturn.setUriThumbnail(columns.getColumnByName("UriThumbnail").getStringValue());
- toReturn.setVreid(columns.getColumnByName("Vreid").getStringValue());
- toReturn.setEntityId(columns.getColumnByName("Entityid").getStringValue());
- toReturn.setCommentsNo(columns.getColumnByName("CommentsNo").getStringValue());
- toReturn.setLikesNo(columns.getColumnByName("LikesNo").getStringValue());
-
- toReturn.setLinkTitle(columns.getColumnByName("LinkTitle").getStringValue());
- toReturn.setLinkDescription(columns.getColumnByName("LinkDescription").getStringValue());
- toReturn.setLinkHost(columns.getColumnByName("LinkHost").getStringValue());
- toReturn.setApplicationFeed(columns.getColumnByName("IsApplicationFeed").getBooleanValue());
- boolean isMultiFileUpload = false;
- try {
- isMultiFileUpload = columns.getColumnByName("multiFileUpload").getBooleanValue();
- }
- catch (NullPointerException e) { }
- toReturn.setMultiFileUpload(isMultiFileUpload);
-
- } catch (ConnectionException e) {
- e.printStackTrace();
- return null;
- }
- return toReturn;
- }
- /**
- * {@inheritDoc}
- */
- @Override
- public Post readPost(String postid)
- throws PrivacyLevelTypeNotFoundException,
- FeedTypeNotFoundException, FeedIDNotFoundException, ColumnNameNotFoundException {
- Post toReturn = new Post();
- OperationResult> result;
- try {
- result = conn.getKeyspace().prepareQuery(cf_Feeds)
- .getKey(postid)
- .execute();
-
- ColumnList columns = result.getResult();
- if (columns.size() == 0) {
- throw new FeedIDNotFoundException("The requested feedid: " + postid + " is not existing", postid);
- }
-
- toReturn.setKey(postid);
- toReturn.setDescription(columns.getColumnByName("Description").getStringValue());
- toReturn.setEmail(columns.getColumnByName("Email").getStringValue());
- toReturn.setFullName(columns.getColumnByName("FullName").getStringValue());
- toReturn.setPrivacy(getPrivacyLevel(columns.getColumnByName("Privacy").getStringValue()));
- toReturn.setThumbnailURL(columns.getColumnByName("ThumbnailURL").getStringValue());
- toReturn.setTime(getDateFromTimeInMillis(columns.getColumnByName("Time").getStringValue()));
-
- PostType ptype = getPostType(columns.getColumnByName("Type").getStringValue());
-
- toReturn.setType(ptype);
- toReturn.setUri(columns.getColumnByName("Uri").getStringValue());
- toReturn.setUriThumbnail(columns.getColumnByName("UriThumbnail").getStringValue());
- toReturn.setVreid(columns.getColumnByName("Vreid").getStringValue());
- toReturn.setEntityId(columns.getColumnByName("Entityid").getStringValue());
- toReturn.setCommentsNo(columns.getColumnByName("CommentsNo").getStringValue());
- toReturn.setLikesNo(columns.getColumnByName("LikesNo").getStringValue());
-
- toReturn.setLinkTitle(columns.getColumnByName("LinkTitle").getStringValue());
- toReturn.setLinkDescription(columns.getColumnByName("LinkDescription").getStringValue());
- toReturn.setLinkHost(columns.getColumnByName("LinkHost").getStringValue());
- toReturn.setApplicationFeed(columns.getColumnByName("IsApplicationFeed").getBooleanValue());
- boolean isMultiFileUpload = false;
- try {
- isMultiFileUpload = columns.getColumnByName("multiFileUpload").getBooleanValue();
- }
- catch (NullPointerException e) { }
- toReturn.setMultiFileUpload(isMultiFileUpload);
-
- } catch (ConnectionException e) {
- e.printStackTrace();
- return null;
- }
- return toReturn;
- }
- /**
- * {@inheritDoc}
- */
- @Override
- @Deprecated
- public List getRecentFeedsByUserAndDate(String userid, long timeInMillis) throws IllegalArgumentException {
- Date now = new Date();
- if (timeInMillis > now.getTime())
- throw new IllegalArgumentException("the timeInMillis must be before today");
-
- OperationResult> result = null;
- try {
- result = conn.getKeyspace().prepareQuery(cf_UserTline)
- .getKeySlice(userid)
- .execute();
- } catch (ConnectionException e) {
- e.printStackTrace();
- }
- List toReturn = new ArrayList();
- // Iterate rows and their columns
- for (Row row : result.getResult()) {
- for (Column column : row.getColumns()) {
- long feedTime = Long.parseLong(column.getName());
- if (feedTime > timeInMillis) {
- try {
- Feed toCheck = readFeed(column.getStringValue());
- if (toCheck.getType() != FeedType.DISABLED)
- toReturn.add(toCheck);
- } catch (PrivacyLevelTypeNotFoundException
- | FeedTypeNotFoundException
- | FeedIDNotFoundException
- | ColumnNameNotFoundException e) {
- e.printStackTrace();
- }
- }
- }
- }
- return toReturn;
- }
- /**
- * {@inheritDoc}
- */
- @Override
- public List getRecentPostsByUserAndDate(String userid, long timeInMillis) throws IllegalArgumentException {
- Date now = new Date();
- if (timeInMillis > now.getTime())
- throw new IllegalArgumentException("the timeInMillis must be before today");
-
- OperationResult> result = null;
- try {
- result = conn.getKeyspace().prepareQuery(cf_UserTline)
- .getKeySlice(userid)
- .execute();
- } catch (ConnectionException e) {
- e.printStackTrace();
- }
- List toReturn = new ArrayList<>();
- // Iterate rows and their columns
- for (Row row : result.getResult()) {
- for (Column column : row.getColumns()) {
- long feedTime = Long.parseLong(column.getName());
- if (feedTime > timeInMillis) {
- try {
- Post toCheck = readPost(column.getStringValue());
- if (toCheck.getType() != PostType.DISABLED)
- toReturn.add(toCheck);
- } catch (PrivacyLevelTypeNotFoundException
- | FeedTypeNotFoundException
- | FeedIDNotFoundException
- | ColumnNameNotFoundException e) {
- e.printStackTrace();
- }
- }
- }
- }
- return toReturn;
- }
- /**
- * {@inheritDoc}
- */
- @Deprecated
- @Override
- public boolean deleteFeed(String feedId) throws FeedIDNotFoundException, PrivacyLevelTypeNotFoundException, FeedTypeNotFoundException, ColumnNameNotFoundException {
- Feed toDelete = readFeed(feedId);
- MutationBatch m = conn.getKeyspace().prepareMutationBatch();
- //edit the entry in the feed CF
- m.withRow(cf_Feeds, toDelete.getKey().toString()).putColumn("Type", ""+FeedType.DISABLED, null);
- try {
- m.execute();
- } catch (ConnectionException e) {
- _log.error("Delete Feed ERROR for feedid " + feedId);
- return false;
- }
- _log.info("Delete Feed OK");
- return true;
- }
- /**
- * {@inheritDoc}
- */
- @Override
- public boolean deletePost(String postid) throws FeedIDNotFoundException, PrivacyLevelTypeNotFoundException, FeedTypeNotFoundException, ColumnNameNotFoundException {
- Post toDelete = readPost(postid);
- MutationBatch m = conn.getKeyspace().prepareMutationBatch();
- //edit the entry in the feed CF
- m.withRow(cf_Feeds, toDelete.getKey().toString()).putColumn("Type", ""+PostType.DISABLED, null);
- try {
- m.execute();
- } catch (ConnectionException e) {
- _log.error("Delete Post ERROR for postid " + postid);
- return false;
- }
- _log.info("Delete Post OK");
- return true;
- }
- /**
- * {@inheritDoc}
- */
- @Deprecated
- @Override
- public List getAllFeedsByUser(String userid) throws PrivacyLevelTypeNotFoundException, FeedTypeNotFoundException, ColumnNameNotFoundException, FeedIDNotFoundException {
- return getFeedsByIds(getUserFeedIds(userid));
- }
- /**
- * {@inheritDoc}
- */
- @Override
- public List getAllPostsByUser(String userid) throws PrivacyLevelTypeNotFoundException, FeedTypeNotFoundException, ColumnNameNotFoundException, FeedIDNotFoundException {
- return getPostsByIds(getUserPostIds(userid));
- }
- /**
- * {@inheritDoc}
- */
- @Override
- public List getAllFeedsByApp(String appid) throws PrivacyLevelTypeNotFoundException, FeedTypeNotFoundException, ColumnNameNotFoundException, FeedIDNotFoundException {
- return getFeedsByIds(getAppFeedIds(appid));
- }
- /**
- * {@inheritDoc}
- */
- @Override
- public List getAllPostsByApp(String appid) throws PrivacyLevelTypeNotFoundException, FeedTypeNotFoundException, ColumnNameNotFoundException, FeedIDNotFoundException {
- return getPostsByIds(getAppPostIds(appid));
- }
- /**
- * {@inheritDoc}
- * @throws Exception
- */
- @Deprecated
- @Override
- public List getRecentCommentedFeedsByUserAndDate(String userid,
- long timeInMillis) throws Exception {
-
- List toReturn = new ArrayList();
-
- Date now = new Date();
- if (timeInMillis > now.getTime())
- throw new IllegalArgumentException("the timeInMillis must be before today");
-
- if(userid == null || userid.isEmpty())
- throw new IllegalArgumentException("the userId parameter cannot be null/empty");
-
- // get the last comments by the user (it is not needed to get them sorted)
- List lastComments = getRecentCommentsByUserAndDateBody(userid, timeInMillis, false);
-
- // evaluate unique feeds' ids
- HashSet feedsIds = new HashSet();
-
- for (Comment comment : lastComments) {
- String feedId = comment.getFeedid();
- try{
- if(!feedsIds.contains(feedId)){
- feedsIds.add(feedId);
- toReturn.add(readFeed(feedId));
- }
- }catch(Exception e){
- _log.error("Unable to retrieve feed with id " + feedId, e);
- }
- }
-
- Collections.sort(toReturn, Collections.reverseOrder());
- return toReturn;
- }
- /**
- * {@inheritDoc}
- * @throws Exception
- */
- @Override
- public List getRecentCommentedPostsByUserAndDate(String userid,
- long timeInMillis) throws Exception {
-
- List toReturn = new ArrayList();
-
- Date now = new Date();
- if (timeInMillis > now.getTime())
- throw new IllegalArgumentException("the timeInMillis must be before today");
-
- if(userid == null || userid.isEmpty())
- throw new IllegalArgumentException("the userId parameter cannot be null/empty");
-
- // get the last comments by the user (it is not needed to get them sorted)
- List lastComments = getRecentCommentsByUserAndDateBody(userid, timeInMillis, false);
-
- // evaluate unique feeds' ids
- HashSet postIds = new HashSet();
-
- for (Comment comment : lastComments) {
- String postId = comment.getFeedid();
- try{
- if(!postIds.contains(postId)){
- postIds.add(postId);
- toReturn.add(readPost(postId));
- }
- }catch(Exception e){
- _log.error("Unable to retrieve feed with id " + postId, e);
- }
- }
-
- Collections.sort(toReturn, Collections.reverseOrder());
- return toReturn;
- }
- /**
- * @deprecated
- * helper method that retrieve all the feeds belongin to a list of Ids
- * @param feedIds
- * @return
- * @throws ColumnNameNotFoundException
- * @throws FeedIDNotFoundException
- * @throws FeedTypeNotFoundException
- * @throws PrivacyLevelTypeNotFoundException
- */
- private List getFeedsByIds(List feedIds) throws PrivacyLevelTypeNotFoundException, FeedTypeNotFoundException, FeedIDNotFoundException, ColumnNameNotFoundException {
- ArrayList toReturn = new ArrayList();
- for (String feedid : feedIds) {
- Feed toAdd = readFeed(feedid);
- if (toAdd.getType() == FeedType.TWEET || toAdd.getType() == FeedType.SHARE || toAdd.getType() == FeedType.PUBLISH)
- toReturn.add(toAdd);
- }
- return toReturn;
- }
- /**
- * helper method that retrieve all the feeds belongin to a list of Ids
- * @param postIds
- * @return
- * @throws ColumnNameNotFoundException
- * @throws FeedIDNotFoundException
- * @throws FeedTypeNotFoundException
- * @throws PrivacyLevelTypeNotFoundException
- */
- private List getPostsByIds(List postIds) throws PrivacyLevelTypeNotFoundException, FeedTypeNotFoundException, FeedIDNotFoundException, ColumnNameNotFoundException {
- ArrayList toReturn = new ArrayList();
- for (String feedid : postIds) {
- Post toAdd = readPost(feedid);
- if (toAdd.getType() == PostType.TWEET || toAdd.getType() == PostType.SHARE || toAdd.getType() == PostType.PUBLISH)
- toReturn.add(toAdd);
- }
- return toReturn;
- }
- /**
- * helper method that retrieve all the feed Ids belonging to a user
- * @param userid user identifier
- * @return simply return a list of user feed UUID in chronological order from the oldest to the more recent
- */
- @Deprecated
- private ArrayList getUserFeedIds(String userid) {
- OperationResult> result = null;
- try {
- result = conn.getKeyspace().prepareQuery(cf_UserTline)
- .getKeySlice(userid)
- .execute();
- } catch (ConnectionException e) {
- e.printStackTrace();
- }
-
- ArrayList toReturn = new ArrayList();
-
- // Iterate rows and their columns
- for (Row row : result.getResult()) {
- for (Column column : row.getColumns()) {
- toReturn.add(column.getStringValue());
- }
- }
- return toReturn;
- }
- /**
- * helper method that retrieve all the post Ids belonging to a user
- * @param userid user identifier
- * @return simply return a list of user post UUID in chronological order from the oldest to the more recent
- */
- private ArrayList getUserPostIds(String userid) {
- OperationResult> result = null;
- try {
- result = conn.getKeyspace().prepareQuery(cf_UserTline)
- .getKeySlice(userid)
- .execute();
- } catch (ConnectionException e) {
- e.printStackTrace();
- }
-
- ArrayList toReturn = new ArrayList();
-
- // Iterate rows and their columns
- for (Row row : result.getResult()) {
- for (Column column : row.getColumns()) {
- toReturn.add(column.getStringValue());
- }
- }
- return toReturn;
- }
-
- /**
- * helper method that return whether the user
- * @param userid user identifier
- * @param feedid the feed identifier
- * @return true if the feed id liked already
- */
- private boolean isFeedLiked(String userid, String feedid) {
- OperationResult> result = null;
- try {
- result = conn.getKeyspace().prepareQuery(cf_UserLikedFeeds)
- .getKeySlice(userid)
- .execute();
- } catch (ConnectionException e) {
- e.printStackTrace();
- }
-
- // Iterate rows and their columns looking for the feeid id
- for (Row row : result.getResult()) {
- for (Column column : row.getColumns()) {
- if (column.getStringValue().compareTo(feedid)==0)
- return true;
- }
- }
- return false;
- }
-
-
- /**
- * helper method that retrieve all the feed Ids belonging to an application
- * @param appid application identifier
- * @return simply return a list of app feed UUID in chronological order from the oldest to the more recent
- */
- @Deprecated
- private ArrayList getAppFeedIds(String appid) {
- OperationResult> result = null;
- try {
- result = conn.getKeyspace().prepareQuery(cf_AppTline)
- .getKeySlice(appid)
- .execute();
- } catch (ConnectionException e) {
- e.printStackTrace();
- }
-
- ArrayList toReturn = new ArrayList();
-
- // Iterate rows and their columns
- for (Row row : result.getResult()) {
- for (Column column : row.getColumns()) {
- toReturn.add(column.getStringValue());
- }
- }
- return toReturn;
- }
- /**
- * helper method that retrieve all the post Ids belonging to an application
- * @param appid application identifier
- * @return simply return a list of app post UUID in chronological order from the oldest to the more recent
- */
- private ArrayList getAppPostIds(String appid) {
- OperationResult> result = null;
- try {
- result = conn.getKeyspace().prepareQuery(cf_AppTline)
- .getKeySlice(appid)
- .execute();
- } catch (ConnectionException e) {
- e.printStackTrace();
- }
-
- ArrayList toReturn = new ArrayList();
-
- // Iterate rows and their columns
- for (Row row : result.getResult()) {
- for (Column column : row.getColumns()) {
- toReturn.add(column.getStringValue());
- }
- }
- return toReturn;
- }
-
- /**
- * {@inheritDoc}
- */
- @Deprecated
- @Override
- public List getAllPortalPrivacyLevelFeeds() throws FeedTypeNotFoundException, ColumnNameNotFoundException, PrivacyLevelTypeNotFoundException {
- ArrayList toReturn = new ArrayList();
- OperationResult> result;
- try {
- result = conn.getKeyspace().prepareQuery(cf_Feeds)
- .searchWithIndex()
- .setLimit(20) // Number of rows returned
- .addExpression()
- .whereColumn("Privacy").equals().value(PrivacyLevel.PORTAL.toString())
- .execute();
- // Iterate rows and their columns
- for (Row row : result.getResult()) {
- Feed toAdd = new Feed();
- toAdd.setKey(row.getKey());
- for (Column col : row.getColumns()) {
- if (col.getName().compareTo("Description") == 0)
- toAdd.setDescription(col.getStringValue());
- else if (col.getName().compareTo("FullName") == 0)
- toAdd.setFullName(col.getStringValue());
- else if (col.getName().compareTo("Email") == 0)
- toAdd.setEmail(col.getStringValue());
- else if (col.getName().compareTo("Privacy") == 0)
- toAdd.setPrivacy(getPrivacyLevel(col.getStringValue()));
- else if (col.getName().compareTo("ThumbnailURL") == 0)
- toAdd.setThumbnailURL(col.getStringValue());
- else if (col.getName().compareTo("Time") == 0)
- toAdd.setTime(getDateFromTimeInMillis(col.getStringValue()));
- else if (col.getName().compareTo("Type") == 0) {
- FeedType ft = getFeedType(col.getStringValue());
- toAdd.setType(ft);
- }
- else if (col.getName().compareTo("Uri") == 0)
- toAdd.setUri(col.getStringValue());
- else if (col.getName().compareTo("UriThumbnail") == 0)
- toAdd.setUriThumbnail(col.getStringValue());
- else if (col.getName().compareTo("Vreid") == 0)
- toAdd.setVreid(col.getStringValue());
- else if (col.getName().compareTo("Entityid") == 0)
- toAdd.setEntityId(col.getStringValue());
- else if (col.getName().compareTo("CommentsNo") == 0)
- toAdd.setCommentsNo(col.getStringValue());
- else if (col.getName().compareTo("LikesNo") == 0)
- toAdd.setLikesNo(col.getStringValue());
- else if (col.getName().compareTo("LinkDescription") == 0)
- toAdd.setLinkDescription(col.getStringValue());
- else if (col.getName().compareTo("LinkHost") == 0)
- toAdd.setLinkHost(col.getStringValue());
- else if (col.getName().compareTo("LinkTitle") == 0)
- toAdd.setLinkTitle(col.getStringValue());
- else if (col.getName().compareTo("IsApplicationFeed") == 0)
- toAdd.setApplicationFeed(col.getBooleanValue());
- else {
- _log.warn("getAllPortalPrivacyLevelFeeds(): Could not assign variable to this Feed for column name: " + col.getName());
- }
- }
- if (toAdd.getType() == FeedType.TWEET || toAdd.getType() == FeedType.SHARE || toAdd.getType() == FeedType.PUBLISH)
- toReturn.add(toAdd);
- }
- } catch (ConnectionException e) {
- e.printStackTrace();
- return toReturn;
- }
- return toReturn;
- }
- @Override
- public List getAllPortalPrivacyLevelPosts() throws FeedTypeNotFoundException, ColumnNameNotFoundException, PrivacyLevelTypeNotFoundException {
- ArrayList toReturn = new ArrayList();
- OperationResult> result;
- try {
- result = conn.getKeyspace().prepareQuery(cf_Feeds)
- .searchWithIndex()
- .setLimit(20) // Number of rows returned
- .addExpression()
- .whereColumn("Privacy").equals().value(PrivacyLevel.PORTAL.toString())
- .execute();
- // Iterate rows and their columns
- for (Row row : result.getResult()) {
- Post toAdd = new Post();
- toAdd.setKey(row.getKey());
- for (Column col : row.getColumns()) {
- if (col.getName().compareTo("Description") == 0)
- toAdd.setDescription(col.getStringValue());
- else if (col.getName().compareTo("FullName") == 0)
- toAdd.setFullName(col.getStringValue());
- else if (col.getName().compareTo("Email") == 0)
- toAdd.setEmail(col.getStringValue());
- else if (col.getName().compareTo("Privacy") == 0)
- toAdd.setPrivacy(getPrivacyLevel(col.getStringValue()));
- else if (col.getName().compareTo("ThumbnailURL") == 0)
- toAdd.setThumbnailURL(col.getStringValue());
- else if (col.getName().compareTo("Time") == 0)
- toAdd.setTime(getDateFromTimeInMillis(col.getStringValue()));
- else if (col.getName().compareTo("Type") == 0) {
- PostType ft = getPostType(col.getStringValue());
- toAdd.setType(ft);
- }
- else if (col.getName().compareTo("Uri") == 0)
- toAdd.setUri(col.getStringValue());
- else if (col.getName().compareTo("UriThumbnail") == 0)
- toAdd.setUriThumbnail(col.getStringValue());
- else if (col.getName().compareTo("Vreid") == 0)
- toAdd.setVreid(col.getStringValue());
- else if (col.getName().compareTo("Entityid") == 0)
- toAdd.setEntityId(col.getStringValue());
- else if (col.getName().compareTo("CommentsNo") == 0)
- toAdd.setCommentsNo(col.getStringValue());
- else if (col.getName().compareTo("LikesNo") == 0)
- toAdd.setLikesNo(col.getStringValue());
- else if (col.getName().compareTo("LinkDescription") == 0)
- toAdd.setLinkDescription(col.getStringValue());
- else if (col.getName().compareTo("LinkHost") == 0)
- toAdd.setLinkHost(col.getStringValue());
- else if (col.getName().compareTo("LinkTitle") == 0)
- toAdd.setLinkTitle(col.getStringValue());
- else if (col.getName().compareTo("IsApplicationFeed") == 0)
- toAdd.setApplicationFeed(col.getBooleanValue());
- else {
- _log.warn("getAllPortalPrivacyLevelFeeds(): Could not assign variable to this Feed for column name: " + col.getName());
- }
- }
- if (toAdd.getType() == PostType.TWEET || toAdd.getType() == PostType.SHARE || toAdd.getType() == PostType.PUBLISH)
- toReturn.add(toAdd);
- }
- } catch (ConnectionException e) {
- e.printStackTrace();
- return toReturn;
- }
- return toReturn;
- }
- /**
- * {@inheritDoc}
- */
- @Override
- @Deprecated
- public List getRecentFeedsByUser(String userid, int quantity) throws PrivacyLevelTypeNotFoundException, FeedTypeNotFoundException, ColumnNameNotFoundException, FeedIDNotFoundException {
- ArrayList toReturn = new ArrayList();
- ArrayList feedIDs = getUserFeedIds(userid);
- //check if quantity is greater than user feeds
- quantity = (quantity > feedIDs.size()) ? feedIDs.size() : quantity;
-
- //need them in reverse order
- for (int i = feedIDs.size()-1; i >= (feedIDs.size()-quantity); i--) {
- Feed toAdd = readFeed(feedIDs.get(i));
- if (toAdd.getType() == FeedType.TWEET || toAdd.getType() == FeedType.SHARE || toAdd.getType() == FeedType.PUBLISH) {
- toReturn.add(toAdd);
- _log.trace("Read recent feed: " + feedIDs.get(i));
- } else {
- _log.trace("Read and skipped feed: " + feedIDs.get(i) + " (Removed Feed)");
- quantity += 1; //increase the quantity in case of removed feed
- //check if quantity is greater than user feeds
- quantity = (quantity > feedIDs.size()) ? feedIDs.size() : quantity;
- }
- }
- return toReturn;
- }
- @Override
- public List getRecentPostsByUser(String userid, int quantity) throws PrivacyLevelTypeNotFoundException, FeedTypeNotFoundException, ColumnNameNotFoundException, FeedIDNotFoundException {
- ArrayList toReturn = new ArrayList();
- ArrayList postIDs = getUserPostIds(userid);
- //check if quantity is greater than user feeds
- quantity = (quantity > postIDs.size()) ? postIDs.size() : quantity;
-
- //need them in reverse order
- for (int i = postIDs.size()-1; i >= (postIDs.size()-quantity); i--) {
- Post toAdd = readPost(postIDs.get(i));
- if (toAdd.getType() == PostType.TWEET || toAdd.getType() == PostType.SHARE || toAdd.getType() == PostType.PUBLISH) {
- toReturn.add(toAdd);
- _log.trace("Read recent post: " + postIDs.get(i));
- } else {
- _log.trace("Read and skipped post: " + postIDs.get(i) + " (Removed Post)");
- quantity += 1; //increase the quantity in case of removed post
- //check if quantity is greater than user feeds
- quantity = (quantity > postIDs.size()) ? postIDs.size() : quantity;
- }
- }
- return toReturn;
- }
- /**
- * {@inheritDoc}
- */
- @Override
- @Deprecated
- public List getAllFeedsByVRE(String vreid) throws PrivacyLevelTypeNotFoundException, FeedTypeNotFoundException, ColumnNameNotFoundException, FeedIDNotFoundException {
- return getFeedsByIds(getVREFeedIds(vreid));
- }
- /**
- * {@inheritDoc}
- */
- @Override
- public List getAllPostsByVRE(String vreid) throws PrivacyLevelTypeNotFoundException, FeedTypeNotFoundException, ColumnNameNotFoundException, FeedIDNotFoundException {
- return getPostsByIds(getVREPostIds(vreid));
- }
- /**
- * {@inheritDoc}
- */
- @Deprecated
- @Override
- public List getRecentFeedsByVRE(String vreid, int quantity) throws PrivacyLevelTypeNotFoundException, FeedTypeNotFoundException, ColumnNameNotFoundException, FeedIDNotFoundException {
- ArrayList toReturn = new ArrayList();
- ArrayList feedIDs = getVREFeedIds(vreid);
- //check if quantity is greater than user feeds
- quantity = (quantity > feedIDs.size()) ? feedIDs.size() : quantity;
-
- //need them in reverse order
- for (int i = feedIDs.size()-1; i >= (feedIDs.size()-quantity); i--) {
- Feed toAdd = readFeed(feedIDs.get(i));
- if (toAdd.getType() == FeedType.TWEET || toAdd.getType() == FeedType.SHARE || toAdd.getType() == FeedType.PUBLISH) {
- toReturn.add(toAdd);
- _log.trace("Read recent feed: " + feedIDs.get(i));
- } else {
- _log.trace("Read and skipped feed: " + feedIDs.get(i) + " (Removed Feed) .");
- quantity += 1; //increase the quantity in case of removed feed
- //check if quantity is greater than user feeds
- quantity = (quantity > feedIDs.size()) ? feedIDs.size() : quantity;
- }
- }
- return toReturn;
- }
- @Override
- public List getRecentPostsByVRE(String vreid, int quantity) throws PrivacyLevelTypeNotFoundException, FeedTypeNotFoundException, ColumnNameNotFoundException, FeedIDNotFoundException {
- ArrayList toReturn = new ArrayList();
- ArrayList postIDs = getVREPostIds(vreid);
- //check if quantity is greater than user posts
- quantity = (quantity > postIDs.size()) ? postIDs.size() : quantity;
-
- //need them in reverse order
- for (int i = postIDs.size()-1; i >= (postIDs.size()-quantity); i--) {
- Post toAdd = readPost(postIDs.get(i));
- if (toAdd.getType() == PostType.TWEET || toAdd.getType() == PostType.SHARE || toAdd.getType() == PostType.PUBLISH) {
- toReturn.add(toAdd);
- _log.trace("Read recent Post: " + postIDs.get(i));
- } else {
- _log.trace("Read and skipped Post: " + postIDs.get(i) + " (Removed Post) .");
- quantity += 1; //increase the quantity in case of removed Post
- //check if quantity is greater than user Posts
- quantity = (quantity > postIDs.size()) ? postIDs.size() : quantity;
- }
- }
- return toReturn;
- }
- /**
- * {@inheritDoc}
- */
- @Override
- public RangeFeeds getRecentFeedsByVREAndRange(String vreid, int from, int quantity) throws IllegalArgumentException, PrivacyLevelTypeNotFoundException, FeedTypeNotFoundException, ColumnNameNotFoundException, FeedIDNotFoundException {
- if (from < 1) {
- throw new IllegalArgumentException("From must be greather than 0");
- }
- ArrayList feedsToReturn = new ArrayList();
- ArrayList feedIDs = getVREFeedIds(vreid);
-
- //if from is greater than feeds size return empty
- if (from >= feedIDs.size()) {
- _log.warn("The starting point of the range is greather than the total number of feeds for this timeline: " + from + " >= " + feedIDs.size());
- return new RangeFeeds();
- }
-
- int rangeStart = feedIDs.size()-from;
- int rangeEnd = rangeStart-quantity;
-
- //check that you reached the end
- if (rangeEnd<1)
- rangeEnd = 0;
-
- _log.debug("BEFORE starting Point=" + rangeStart + " rangeEnd= " + rangeEnd);
- //need them in reverse order
- int howMany = from;
- for (int i = rangeStart; i > rangeEnd; i--) {
- Feed toAdd = readFeed(feedIDs.get(i));
- if (toAdd.getType() == FeedType.TWEET || toAdd.getType() == FeedType.SHARE || toAdd.getType() == FeedType.PUBLISH) {
- feedsToReturn.add(toAdd);
- _log.trace("Read recent feed, i=" + i + " id= " + feedIDs.get(i));
- } else {
- _log.trace("Read and skipped feed, i=" + i + " id=: " + feedIDs.get(i) + " (Removed Feed) .");
- rangeEnd -= 1; //increase the upTo in case of removed feed
- //check if quantity is greater than user feeds
- rangeEnd = (rangeEnd > 0) ? rangeEnd : 0;
- }
- howMany++;
- }
- _log.debug("AFTER: starting Point==" + rangeStart + " rangeEnd= " + rangeEnd);
- return new RangeFeeds(howMany+1, feedsToReturn);
- }
- /**
- * {@inheritDoc}
- */
- @Override
- public RangePosts getRecentPostsByVREAndRange(String vreid, int from, int quantity) throws IllegalArgumentException, PrivacyLevelTypeNotFoundException, FeedTypeNotFoundException, ColumnNameNotFoundException, FeedIDNotFoundException {
- if (from < 1) {
- throw new IllegalArgumentException("From must be greather than 0");
- }
- ArrayList feedsToReturn = new ArrayList();
- ArrayList feedIDs = getVREPostIds(vreid);
-
- //if from is greater than feeds size return empty
- if (from >= feedIDs.size()) {
- _log.warn("The starting point of the range is greather than the total number of feeds for this timeline: " + from + " >= " + feedIDs.size());
- return new RangePosts();
- }
-
- int rangeStart = feedIDs.size()-from;
- int rangeEnd = rangeStart-quantity;
-
- //check that you reached the end
- if (rangeEnd<1)
- rangeEnd = 0;
-
- _log.debug("BEFORE starting Point=" + rangeStart + " rangeEnd= " + rangeEnd);
- //need them in reverse order
- int howMany = from;
- for (int i = rangeStart; i > rangeEnd; i--) {
- Post toAdd = readPost(feedIDs.get(i));
- if (toAdd.getType() == PostType.TWEET || toAdd.getType() == PostType.SHARE || toAdd.getType() == PostType.PUBLISH) {
- feedsToReturn.add(toAdd);
- _log.trace("Read recent post, i=" + i + " id= " + feedIDs.get(i));
- } else {
- _log.trace("Read and skipped post, i=" + i + " id=: " + feedIDs.get(i) + " (Removed post) .");
- rangeEnd -= 1; //increase the upTo in case of removed feed
- //check if quantity is greater than user feeds
- rangeEnd = (rangeEnd > 0) ? rangeEnd : 0;
- }
- howMany++;
- }
- _log.debug("AFTER: starting Point==" + rangeStart + " rangeEnd= " + rangeEnd);
- return new RangePosts(howMany+1, feedsToReturn);
- }
- /**
- * @deprecated
- * get a list of user vre feed UUIDs in chronological order from the oldest to the more recent
- * @param vreid vreid identifier (scope)
- * @return simply return a list of user vre feed UUIDs in chronological order from the oldest to the more recent
- */
- private ArrayList getVREFeedIds(String vreid) {
- OperationResult> result = null;
- try {
- result = conn.getKeyspace().prepareQuery(cf_VRETline)
- .getKeySlice(vreid)
- .execute();
- } catch (ConnectionException e) {
- e.printStackTrace();
- }
-
- ArrayList toReturn = new ArrayList();
-
- // Iterate rows and their columns
- for (Row row : result.getResult()) {
- for (Column column : row.getColumns()) {
- toReturn.add(column.getStringValue());
- }
- }
- return toReturn;
- }
- /**
- * get a list of user vre post UUIDs in chronological order from the oldest to the more recent
- * @param vreid vreid identifier (scope)
- * @return simply return a list of user vre post UUIDs in chronological order from the oldest to the more recent
- */
- private ArrayList getVREPostIds(String vreid) {
- OperationResult> result = null;
- try {
- result = conn.getKeyspace().prepareQuery(cf_VRETline)
- .getKeySlice(vreid)
- .execute();
- } catch (ConnectionException e) {
- e.printStackTrace();
- }
-
- ArrayList toReturn = new ArrayList();
-
- // Iterate rows and their columns
- for (Row row : result.getResult()) {
- for (Column column : row.getColumns()) {
- toReturn.add(column.getStringValue());
- }
- }
- return toReturn;
- }
- /*
- *
- ********************** NOTIFICATIONS ***********************
- *
- */
- /**
- * {@inheritDoc}
- */
- @Override
- public boolean saveNotification(Notification n) {
- // Inserting data
- MutationBatch m = conn.getKeyspace().prepareMutationBatch();
- //an entry in the feed CF
- m.withRow(cf_Notifications, n.getKey().toString())
- .putColumn("Type", n.getType().toString(), null)
- .putColumn("Userid", n.getUserid(), null)
- .putColumn("Subjectid", n.getSubjectid(), null)
- .putColumn("Time", n.getTime().getTime()+"", null)
- .putColumn("Uri", n.getUri(), null)
- .putColumn("Description", n.getDescription(), null)
- .putColumn("Read", n.isRead(), null)
- .putColumn("Senderid", n.getSenderid(), null)
- .putColumn("SenderFullName", n.getSenderFullName(), null)
- .putColumn("SenderThumbnail", n.getSenderThumbnail(), null);
-
- //an entry in the user Notifications Timeline
- m.withRow(cf_UserNotifications, n.getUserid()).putColumn(n.getTime().getTime()+"", n.getKey().toString(), null);
-
- // save key in the unread notifications column family too
- m.withRow(cf_UserNotificationsUnread, n.getUserid()).putColumn(n.getTime().getTime()+"", n.getKey().toString(), null);
-
- return execute(m);
- }
-
- /**
- * {@inheritDoc}
- */
- @Override
- public Notification readNotification(String notificationid) throws NotificationIDNotFoundException, NotificationTypeNotFoundException, ColumnNameNotFoundException {
- Notification toReturn = new Notification();
- OperationResult> result;
- try {
- result = conn.getKeyspace().prepareQuery(cf_Notifications)
- .getKey(notificationid)
- .execute();
-
- ColumnList columns = result.getResult();
- if (columns.size() == 0) {
- throw new NotificationIDNotFoundException("The requested notificationid: " + notificationid + " is not existing");
- }
-
- toReturn.setKey(notificationid);
- NotificationType nt = getNotificationType(columns.getColumnByName("Type").getStringValue());
- toReturn.setType(nt);
- toReturn.setUserid(columns.getColumnByName("Userid").getStringValue());
- toReturn.setSubjectid(columns.getColumnByName("Subjectid").getStringValue());
- toReturn.setTime(getDateFromTimeInMillis(columns.getColumnByName("Time").getStringValue()));
- toReturn.setUri(columns.getColumnByName("Uri").getStringValue());
- toReturn.setDescription(columns.getColumnByName("Description").getStringValue());
- toReturn.setRead(columns.getColumnByName("Read").getBooleanValue());
- toReturn.setSenderid(columns.getColumnByName("Senderid").getStringValue());
- toReturn.setSenderFullName(columns.getColumnByName("SenderFullName").getStringValue());
- toReturn.setSenderThumbnail(columns.getColumnByName("SenderThumbnail").getStringValue());
-
- } catch (ConnectionException e) {
- e.printStackTrace();
- return null;
- }
- return toReturn;
- }
- /**
- * {@inheritDoc}
- */
- @Override
- public boolean setNotificationRead(String notificationidToSet) throws NotificationIDNotFoundException, NotificationTypeNotFoundException, ColumnNameNotFoundException {
- Notification toSet = readNotification(notificationidToSet);
- if (toSet == null)
- throw new NotificationIDNotFoundException("The specified notification to set Read with id: " + notificationidToSet + " does not exist");
-
- MutationBatch m = conn.getKeyspace().prepareMutationBatch();
-
- //set as read
- m.withRow(cf_Notifications, notificationidToSet).putColumn("Read", true, null);
-
- // delete the notification's key from the unread notifications column family
- m.withRow(cf_UserNotificationsUnread, toSet.getUserid()).deleteColumn(toSet.getTime().getTime()+"");
-
- // execute the operations
- try {
- m.execute();
- } catch (ConnectionException e) {
- _log.error("ERROR while setting Notification " + notificationidToSet + " to read.");
- return false;
- }
- _log.trace("Notification Set read OK to");
- return true;
- }
- /**
- *
- * @param userid user identifier
- * @return simply return a list of user notifications UUID in chronological order from the oldest to the more recent
- */
- private ArrayList getUserNotificationsIds(String userid) {
- OperationResult> result = null;
- try {
- result = conn.getKeyspace().prepareQuery(cf_UserNotifications)
- .getKeySlice(userid)
- .execute();
- } catch (ConnectionException e) {
- e.printStackTrace();
- }
-
- ArrayList toReturn = new ArrayList();
-
- // Iterate rows and their columns
- for (Row row : result.getResult()) {
- for (Column column : row.getColumns()) {
- toReturn.add(column.getStringValue());
- }
- }
- return toReturn;
- }
- /**
- * Return a list of not read notifications by user userid (messages as well as other notifications)
- * @param userid user identifier
- * @return simply return a list of not read user notifications UUID in chronological order from the oldest to the more recent
- */
- private ArrayList getUnreadUserNotificationsIds(String userid) {
- OperationResult> result = null;
- try {
- result = conn.getKeyspace().prepareQuery(cf_UserNotificationsUnread)
- .getKeySlice(userid)
- .execute();
- } catch (ConnectionException e) {
- e.printStackTrace();
- }
-
- ArrayList toReturn = new ArrayList();
-
- // Iterate rows and their columns
- for (Row row : result.getResult()) {
- for (Column column : row.getColumns()) {
- toReturn.add(column.getStringValue());
- }
- }
- return toReturn;
- }
- /**
- * {@inheritDoc}
- */
- @Override
- public List getAllNotificationByUser(String userid, int limit) throws NotificationTypeNotFoundException, ColumnNameNotFoundException {
- ArrayList toReturn = new ArrayList();
- ArrayList notificationsIDs = getUserNotificationsIds(userid);
- //check if quantity is greater than user feeds
- limit = (limit > notificationsIDs.size()) ? notificationsIDs.size() : limit;
-
- //need them in reverse order
- for (int i = notificationsIDs.size()-1; i >= (notificationsIDs.size()-limit); i--) {
- Notification toAdd = null;
- try {
- toAdd = readNotification(notificationsIDs.get(i));
- toReturn.add(toAdd);
- } catch (NotificationIDNotFoundException e) {
- _log.error("Notification not found id=" + notificationsIDs.get(i));
- }
- }
- return toReturn;
- }
- /**
- * {@inheritDoc}
- */
- @Override
- public List getUnreadNotificationsByUser(String userid) throws NotificationTypeNotFoundException, ColumnNameNotFoundException, NotificationIDNotFoundException {
- ArrayList toReturn = new ArrayList();
- ArrayList notificationsIDs = getUnreadUserNotificationsIds(userid);
-
- //need them in reverse order
- for (int i = notificationsIDs.size()-1; i >= 0; i--) {
- try{
- toReturn.add(readNotification(notificationsIDs.get(i)));
- }catch(Exception e){
- _log.error("Unable to read notification with key " + notificationsIDs.get(i));
- }
- }
-
- return toReturn;
- }
- /**
- * {@inheritDoc}
- */
- @Override
- public List getRangeNotificationsByUser(String userid,int from, int quantity) throws NotificationTypeNotFoundException, ColumnNameNotFoundException, NotificationIDNotFoundException {
- if (from < 1) {
- throw new IllegalArgumentException("From must be greather than 0");
- }
- ArrayList toReturn = new ArrayList();
- ArrayList notificationsIDs = getUserNotificationsIds(userid);
-
- //if from is greater than feeds size return empty
- if (from >= notificationsIDs.size()) {
- _log.warn("The starting point of the range is greather than the total number of feeds for this timeline: " + from + " >= " + notificationsIDs.size());
- return new ArrayList();
- }
-
- int rangeStart = notificationsIDs.size()-from;
- int rangeEnd = rangeStart-quantity;
-
- //check that you reached the end
- if (rangeEnd<1)
- rangeEnd = 0;
-
- _log.debug("BEFORE starting Point=" + rangeStart + " rangeEnd= " + rangeEnd);
- //need them in reverse order
- for (int i = rangeStart; i > rangeEnd; i--) {
- Notification toAdd = readNotification(notificationsIDs.get(i));
- toReturn.add(toAdd);
- }
- return toReturn;
- }
- /**
- * {@inheritDoc}
- */
- @Override
- public boolean setAllNotificationReadByUser(String userid) throws NotificationTypeNotFoundException, ColumnNameNotFoundException {
-
- // get the list of unread notifications
- ArrayList notificationsIDs = getUnreadUserNotificationsIds(userid);
-
- for (int i = notificationsIDs.size()-1; i >= 0; i--) {
- try{
-
- // set to read (and automatically remove from the unread column family)
- setNotificationRead(notificationsIDs.get(i));
-
- } catch (NotificationIDNotFoundException e) {
- _log.error("Could not set read notification with id =" + notificationsIDs.get(i));
- }
- }
- return true;
- }
-
- /**
- * {@inheritDoc}
- */
- @Override
- public boolean checkUnreadNotifications(String userid) throws NotificationTypeNotFoundException, ColumnNameNotFoundException {
-
- ArrayList unreadNotifications = getUnreadUserNotificationsIds(userid);
-
- for (int i = unreadNotifications.size() - 1; i >= 0; i--) {
- Notification toAdd;
- try {
- toAdd = readNotification(unreadNotifications.get(i));
- if (toAdd.getType() != NotificationType.MESSAGE)
- return true;
- } catch (NotificationIDNotFoundException e) {
- _log.error("Notification not found with id = " + unreadNotifications.get(i));
- }
- }
-
- return false;
- }
- /**
- * {@inheritDoc}
- */
- @Override
- public boolean checkUnreadMessagesNotifications(String userid) throws NotificationIDNotFoundException, NotificationTypeNotFoundException, ColumnNameNotFoundException {
-
- ArrayList unreadNotifications = getUnreadUserNotificationsIds(userid);
-
- for (int i = unreadNotifications.size() - 1; i >= 0; i--) {
- Notification toAdd;
- try {
- toAdd = readNotification(unreadNotifications.get(i));
- if (toAdd.getType() == NotificationType.MESSAGE)
- return true;
- } catch (NotificationIDNotFoundException e) {
- _log.error("Notification not found with id = " + unreadNotifications.get(i));
- }
- }
-
- return false;
- }
- /*
- *
- ********************** NOTIFICATION SETTINGS ***********************
- *
- */
- /**
- * {@inheritDoc}
- */
- @Override
- public List getUserNotificationChannels(String userid, NotificationType notificationType) throws NotificationChannelTypeNotFoundException, NotificationTypeNotFoundException {
- _log.trace("Asking for Single Notification preference of " + userid + " Type: " + notificationType);
- List toReturn = new ArrayList();
- NotificationChannelType[] toProcess = getUserNotificationPreferences(userid).get(notificationType);
- if (toProcess == null) {
- _log.warn("Single Notification preference of " + userid + " Type: " + notificationType + " not existing ... creating default");
- return createNewNotificationType(userid, notificationType);
- }
- else if (toProcess.length == 0)
- return toReturn;
- else
- for (int i = 0; i < toProcess.length; i++) {
- toReturn.add(toProcess[i]);
- }
- return toReturn;
- }
- /**
- * called when you add new notification types where the setting does not exist yet
- * please note: by default we set all notifications
- */
- private List createNewNotificationType(String userid, NotificationType notificationType) {
- List toReturn = new ArrayList();
- MutationBatch m = conn.getKeyspace().prepareMutationBatch();
- String valueToInsert = "";
- NotificationChannelType[] wpTypes = NotificationChannelType.values();
-
- for (int i = 0; i < wpTypes.length; i++) {
- valueToInsert += wpTypes[i];
- if (i < wpTypes.length-1)
- valueToInsert += ",";
- toReturn.add(wpTypes[i]); //add the new added notification type
- }
- m.withRow(cf_UserNotificationsPreferences, userid).putColumn(notificationType.toString(), valueToInsert, null);
- boolean overAllresult = execute(m);
- if (overAllresult) {
- _log.trace("Set New Notification Setting for " + userid + " OK");
- return toReturn;
- }
- return new ArrayList(); //no notification if sth fails
- }
- /**
- * {@inheritDoc}
- */
- @Override
- public boolean setUserNotificationPreferences(String userid, Map enabledChannels) {
- MutationBatch m = conn.getKeyspace().prepareMutationBatch();
-
- for (NotificationType nType : enabledChannels.keySet()) {
- String valueToInsert = "";
- int channelsNo = (enabledChannels.get(nType) != null) ? enabledChannels.get(nType).length : 0;
- for (int i = 0; i < channelsNo; i++) {
- valueToInsert += enabledChannels.get(nType)[i];
- if (i < channelsNo-1)
- valueToInsert += ",";
- }
- if (channelsNo == 0) { //in case no channels were selected
- valueToInsert = "";
- _log.trace("No Channels selected for " + nType + " by " + userid);
- }
- m.withRow(cf_UserNotificationsPreferences, userid).putColumn(nType.toString(), valueToInsert, null);
- }
-
- boolean overAllresult = execute(m);
- if (overAllresult)
- _log.trace("Set Notification Map for " + userid + " OK");
- else
- _log.trace("Set Notification Map for " + userid + " FAILED");
- return overAllresult;
- }
- /**
- * {@inheritDoc}
- *
- * by default Workspace and Calendar Notifications are set to Portal
- */
- @Override
- public Map getUserNotificationPreferences(String userid) throws NotificationTypeNotFoundException, NotificationChannelTypeNotFoundException {
- _log.trace("Asking for Notification preferences of " + userid);
- Map toReturn = new HashMap();
- OperationResult> result = null;
- try {
- result = conn.getKeyspace().prepareQuery(cf_UserNotificationsPreferences)
- .getKeySlice(userid)
- .execute();
- } catch (ConnectionException e) {
- e.printStackTrace();
- }
- //if there are no settings for this user create an entry and put all of them at true
- if (result.getResult().getRowByIndex(0).getColumns().size() == 0) {
- _log.info("Userid " + userid + " settings not found, initiating its preferences...");
- HashMap toCreate = new HashMap();
-
- for (int i = 0; i < NotificationType.values().length; i++) {
- //TODO: Potential bug in NotificationType for workspace are refactored
- //create a map with all notification enabled except for workspace notifications (They start with WP_) it was the only quick way
- if (NotificationType.values()[i].toString().startsWith("WP_")) {
- NotificationChannelType[] wpTypes = { NotificationChannelType.PORTAL };
- toCreate.put(NotificationType.values()[i], wpTypes);
- }
- else
- toCreate.put(NotificationType.values()[i], NotificationChannelType.values());
- }
- setUserNotificationPreferences(userid, toCreate); //commit the map
-
- return toCreate;
- }
- else {
- _log.trace("Notification preferences Found for " + userid);
- for (Row row : result.getResult())
- for (Column column : row.getColumns()) {
- String[] channels = column.getStringValue().split(",");
- if (channels != null && channels.length == 1 && channels[0].toString().equals("") ) { //it is empty, preference is set to no notification at all
- toReturn.put(getNotificationType(column.getName()), new NotificationChannelType[0]);
- } else {
- NotificationChannelType[] toAdd = new NotificationChannelType[channels.length];
- for (int i = 0; i < channels.length; i++) {
- if (channels[i].compareTo("") != 0) {
- toAdd[i] = (getChannelType(channels[i]));
- }
- }
- toReturn.put(getNotificationType(column.getName()), toAdd);
- }
- }
- }
- return toReturn;
- }
- /*
- *
- ********************** COMMENTS ***********************
- *
- */
- /**
- * {@inheritDoc}
- */
- @Override
- public boolean addComment(Comment comment) throws FeedIDNotFoundException {
- Feed toComment = null;
- if (comment == null)
- throw new NullArgumentException("Comment must be not null");
- if (comment.getFeedid() == null)
- throw new NullArgumentException("Comment feed id must be not null");
-
- String feedId = comment.getFeedid();
- try {
- toComment = readFeed(feedId);
- if (toComment == null)
- throw new FeedIDNotFoundException("Could not find Feed with id " + feedId + " to associate this comment", feedId);
- } catch (Exception e) {
- e.printStackTrace();
- return false;
- }
- // Inserting data
- MutationBatch m = conn.getKeyspace().prepareMutationBatch();
- //an entry in the Comment CF
- m.withRow(cf_Comments, comment.getKey().toString())
- .putColumn("Text", comment.getText(), null)
- .putColumn("Timestamp", comment.getTime().getTime()+"", null)
- .putColumn("Userid", comment.getUserid(), null)
- .putColumn("Feedid",comment.getFeedid(), null)
- .putColumn("FullName",comment.getFullName(), null)
- .putColumn("ThumbnailURL", comment.getThumbnailURL(), null)
- .putColumn("IsEdited", comment.isEdit(), null);
-
- try {
- m.execute();
- } catch (ConnectionException e) {
- e.printStackTrace();
- return false;
- }
- //update the comment count
- boolean updateCommentNoResult = updateFeedCommentsCount(toComment, true);
- return updateCommentNoResult;
- }
- /**
- * {@inheritDoc}
- */
- public Comment readCommentById(String commentId) throws CommentIDNotFoundException {
- Comment toReturn = new Comment();
- OperationResult> result;
- try {
- result = conn.getKeyspace().prepareQuery(cf_Comments)
- .getKey(commentId)
- .execute();
-
- ColumnList columns = result.getResult();
- if (columns.size() == 0) {
- throw new CommentIDNotFoundException("The requested commentId: " + commentId + " is not existing");
- }
-
- toReturn.setKey(commentId);
- toReturn.setText(columns.getColumnByName("Text").getStringValue());
- toReturn.setFullName(columns.getColumnByName("FullName").getStringValue());
- if(columns.getColumnByName("IsEdited") != null)
- toReturn.setEdit(columns.getColumnByName("IsEdited").getBooleanValue());
- toReturn.setFeedid(columns.getColumnByName("Feedid").getStringValue());
- toReturn.setUserid(columns.getColumnByName("Userid").getStringValue());
- toReturn.setTime(getDateFromTimeInMillis(columns.getColumnByName("Timestamp").getStringValue()));
- toReturn.setThumbnailURL(columns.getColumnByName("ThumbnailURL").getStringValue());
- if (columns.getColumnByName("LastEditTime") != null)
- toReturn.setLastEditTime(getDateFromTimeInMillis(columns.getColumnByName("LastEditTime").getStringValue()));
-
- } catch (ConnectionException e) {
- _log.debug(e.toString());
- return null;
- }
- return toReturn;
- }
- /**
- * {@inheritDoc}
- */
- @Override
- @Deprecated
- public List getAllCommentByFeed(String feedid) {
- return getAllCommentByPost(feedid);
- }
- /**
- * {@inheritDoc}
- */
- @Override
- public List getAllCommentByPost(String postid) {
- List toReturn = new ArrayList();
-
- PreparedIndexExpression clause = cf_Comments.newIndexClause().whereColumn("Feedid").equals().value(postid);
- OperationResult> result;
- try {
- result = conn.getKeyspace().prepareQuery(cf_Comments)
- .searchWithIndex()
- .setStartKey("")
- .addPreparedExpressions(Arrays.asList(clause))
- .execute();
-
- // Iterate rows and their columns
- for (Row row : result.getResult()) {
- Comment toAdd = new Comment();
- toAdd.setKey(row.getKey());
- for (Column col : row.getColumns()) {
- if (col.getName().compareTo("Text") == 0)
- toAdd.setText(col.getStringValue());
- else if (col.getName().compareTo("FullName") == 0)
- toAdd.setFullName(col.getStringValue());
- else if (col.getName().compareTo("Timestamp") == 0)
- toAdd.setTime(getDateFromTimeInMillis(col.getStringValue()));
- else if (col.getName().compareTo("Userid") == 0)
- toAdd.setUserid(col.getStringValue());
- else if (col.getName().compareTo("ThumbnailURL") == 0)
- toAdd.setThumbnailURL(col.getStringValue());
- else if (col.getName().compareTo("Feedid") == 0)
- toAdd.setFeedid(col.getStringValue());
- else if(col.getName().compareTo("IsEdited") == 0)
- toAdd.setEdit(col.getBooleanValue());
- else if(col.getName().compareTo("LastEditTime") == 0)
- toAdd.setLastEditTime(getDateFromTimeInMillis(col.getStringValue()));
- else {
- _log.error("getAllCommentByPost(): Could not assign variable to this Comment for column name: " + col.getName());
- }
- }
- toReturn.add(toAdd);
- }
- } catch (Exception e) {
- e.printStackTrace();
- return null;
- }
- return toReturn;
- }
-
- /**
- * {@inheritDoc}
- * @throws Exception
- */
- @Override
- public List getRecentCommentsByUserAndDate(final String userid,
- final long timeInMillis) throws Exception {
-
- final List commentsByUser;
-
- Date now = new Date();
- if (timeInMillis > now.getTime())
- throw new IllegalArgumentException("the timeInMillis must be before today");
-
- if(userid == null || userid.isEmpty())
- throw new IllegalArgumentException("the userId parameter cannot be null/empty");
-
-
- commentsByUser = getRecentCommentsByUserAndDateBody(userid, timeInMillis, true);
-
- return commentsByUser;
- }
-
- /**
- * Private method that allows also to specify if the returned list must be sorted or not
- * @param userid the user id
- * @param timeInMillis the initial time to consider
- * @param sort a boolean value to specify if the returned list must be sorted (from the most recent to the oldest comment)
- * @return a list of comments recently made by the user
- * @throws ConnectionException
- */
- private List getRecentCommentsByUserAndDateBody(final String userid,
- final long timeInMillis, boolean sort) throws ConnectionException{
-
- final List commentsByUser = new ArrayList();
- final AtomicInteger maxRetryExecutions = new AtomicInteger(10);
-
- /**
- * See https://github.com/Netflix/astyanax/wiki/Reading-Data for more information (Query all with callback)
- */
- conn.getKeyspace().prepareQuery(cf_Comments)
- .getAllRows()
- .setRowLimit(100) // Read in blocks of 100
- .withColumnRange(new RangeBuilder().setLimit(10).build())
- .executeWithCallback(new RowCallback() {
- @Override
- public void success(Rows rows) {
-
- // use a temporary list for each thread
- List partialCommentsList = new ArrayList();
-
- nextRow: for (Row row : rows) {
- for(Column column: row.getColumns()){
- if(column.getName().equals("Userid")){
- if(column.getStringValue().equals(userid)){
- try{
- Comment c = readCommentById(row.getKey());
- Feed f = readFeed(c.getFeedid());
- if(c.getTime().getTime() >= timeInMillis &&
- (f.getType() == FeedType.TWEET || f.getType() == FeedType.SHARE || f.getType() == FeedType.PUBLISH))
- partialCommentsList.add(c);
- }catch(Exception e){
- _log.error("Unable to read comment with id" + row.getKey(), e);
- }
- }
- continue nextRow;
- }
- }
- }
-
- // if there is something to save...
- if(partialCommentsList.size() > 0){
- synchronized (commentsByUser){
- commentsByUser.addAll(partialCommentsList);
- }
- }
- }
-
- @Override
- public boolean failure(ConnectionException e) {
- // decrement value
- int currentValue = maxRetryExecutions.decrementAndGet();
- if(currentValue <= 0){
- _log.error("Too many errors while fetching user's comments, exiting");
- return false;
- }else{
- _log.error("Error while fetching user's recent comments ... repeating operation");
- return true;
- }
- }
- });
-
- if(sort)
- Collections.sort(commentsByUser, Collections.reverseOrder());
-
- return commentsByUser;
-
- }
-
- /**
- * {@inheritDoc}
- */
- @Override
- public boolean editComment(Comment comment2Edit) throws PrivacyLevelTypeNotFoundException, FeedTypeNotFoundException, ColumnNameNotFoundException, CommentIDNotFoundException, FeedIDNotFoundException {
- MutationBatch m = conn.getKeyspace().prepareMutationBatch();
- //an entry in the feed CF
- m.withRow(cf_Comments, comment2Edit.getKey().toString()).putColumn("Text", comment2Edit.getText(), null);
- m.withRow(cf_Comments, comment2Edit.getKey().toString()).putColumn("IsEdited", comment2Edit.isEdit(), null);
- m.withRow(cf_Comments, comment2Edit.getKey().toString()).putColumn("LastEditTime", comment2Edit.getLastEditTime().getTime() + "", null);
- try {
- m.execute();
- } catch (ConnectionException e) {
- _log.error("Comments update NOT OK ");
- return false;
- }
- _log.info("Comments update OK to: " + comment2Edit.getText());
- return true;
- }
-
- /**
- * {@inheritDoc}
- */
- @Override
- public boolean deleteComment(String commentid, String feedid) throws PrivacyLevelTypeNotFoundException, FeedTypeNotFoundException, ColumnNameNotFoundException, CommentIDNotFoundException, FeedIDNotFoundException {
- Feed toUpdate = readFeed(feedid);
- boolean updateCommentNoResult = false;
-
- updateCommentNoResult = updateFeedCommentsCount(toUpdate, false);
- if (updateCommentNoResult) {
- MutationBatch m = conn.getKeyspace().prepareMutationBatch();
- m.withRow(cf_Comments, commentid)
- .delete();
-
- try {
- m.execute();
- } catch (ConnectionException e) {
- _log.error("Comment Delete FAILED for " + commentid + " from Feed " + feedid);
- e.printStackTrace();
- }
- _log.trace("Comment Deleted " + commentid + " from Feed " + feedid);
- }
-
-
- return updateCommentNoResult;
- }
- /**
- * {@inheritDoc}
- */
- @Override
- public boolean like(Like like) throws FeedIDNotFoundException {
- Feed toLike = null;
- if (like == null)
- throw new NullArgumentException("Like must be not null");
- if (like.getFeedid() == null)
- throw new NullArgumentException("Like feed id must be not null");
-
- String feedId = like.getFeedid();
- try {
- toLike = readFeed(feedId);
- if (toLike == null)
- throw new FeedIDNotFoundException("Could not find Feed with id " + feedId + " to associate this like", feedId);
- } catch (Exception e) {
- e.printStackTrace();
- return false;
- }
- if (isFeedLiked(like.getUserid(), feedId)) {
- _log.info("User " + like.getUserid() + " already liked Feed " + feedId);
- return true;
- }
- else {
- // Inserting data
- MutationBatch m = conn.getKeyspace().prepareMutationBatch();
- //an entry in the feed CF
- m.withRow(cf_Likes, like.getKey().toString())
- .putColumn("Timestamp", like.getTime().getTime()+"", null)
- .putColumn("Userid", like.getUserid(), null)
- .putColumn("Feedid",like.getFeedid(), null)
- .putColumn("FullName",like.getFullName(), null)
- .putColumn("ThumbnailURL", like.getThumbnailURL(), null);
- //and an entry in the UserLikesCF
- m.withRow(cf_UserLikedFeeds, like.getUserid()).putColumn(like.getKey(), like.getFeedid(), null);
-
- try {
- m.execute();
- } catch (ConnectionException e) {
- e.printStackTrace();
- return false;
- }
- return updateFeedLikesCount(toLike, true);
- }
- }
- /**
- * {@inheritDoc}
- */
- @Override
- public boolean unlike(String userid, String likeid, String feedid) throws PrivacyLevelTypeNotFoundException, FeedTypeNotFoundException, ColumnNameNotFoundException, LikeIDNotFoundException, FeedIDNotFoundException {
- Feed toUpdate = readFeed(feedid);
- boolean updateLikeNoResult = false;
-
- updateLikeNoResult = updateFeedLikesCount(toUpdate, false); //this remove 1 from the Feed CF LikeNO
- if (updateLikeNoResult) {
- MutationBatch m = conn.getKeyspace().prepareMutationBatch();
- //delete the row from LikesCF
- m.withRow(cf_Likes, likeid).delete();
- //delete the column from UserLikes
- m.withRow(cf_UserLikedFeeds, userid).deleteColumn(likeid);
-
-
-
- try {
- m.execute();
- } catch (ConnectionException e) {
- _log.error("Like Delete FAILED for " + likeid + " from Feed " + feedid);
- e.printStackTrace();
- }
- _log.trace("Unlike ok for " + likeid + " from Feed " + feedid);
- }
- return updateLikeNoResult;
- }
- /**
- * {@inheritDoc}
- */
- @Override
- @Deprecated
- public List getAllLikedFeedIdsByUser(String userid) {
- return getAllLikedPostIdsByUser(userid);
- }
- /**
- * {@inheritDoc}
- */
- @Override
- public List getAllLikedPostIdsByUser(String userid) {
- OperationResult> result = null;
- try {
- result = conn.getKeyspace().prepareQuery(cf_UserLikedFeeds)
- .getKeySlice(userid)
- .execute();
- } catch (ConnectionException e) {
- e.printStackTrace();
- }
-
- ArrayList toReturn = new ArrayList();
-
- // Iterate rows and their columns
- for (Row row : result.getResult()) {
- for (Column column : row.getColumns()) {
- toReturn.add(column.getStringValue());
- }
- }
- return toReturn;
- }
- /**
- * {@inheritDoc}
- */
- @Override
- public List getAllLikedFeedsByUser(String userid, int limit) throws PrivacyLevelTypeNotFoundException, FeedTypeNotFoundException, ColumnNameNotFoundException, FeedIDNotFoundException {
- ArrayList