private UserType getSessionType(Session session, CassandraType type) { return session .getCluster() .getMetadata() .getKeyspace(session.getLoggedKeyspace()) .getUserType(type.getName()); }
public boolean validateUser(String username, String password) { AeSimpleSHA1 sha1handler = new AeSimpleSHA1(); String EncodedPassword = null; try { EncodedPassword = sha1handler.SHA1(password); } catch (UnsupportedEncodingException | NoSuchAlgorithmException et) { System.out.println("Can't check your password"); return false; } Session session = cluster.connect("ducquak"); PreparedStatement pS = session.prepare("SELECT * FROM users"); ResultSet rs = null; BoundStatement boundStatement = new BoundStatement(pS); rs = session.execute( // this is where the query is executed boundStatement // here you are binding the 'boundStatement' ); if (rs.isExhausted()) { System.out.println("Nothing returned"); return false; } else { for (Row row : rs) { String userName = row.getString("userName"); if (userName.equals(username)) { String StoredPass = row.getString("password"); if (StoredPass.compareTo(EncodedPassword) == 0) return true; } } } return false; }
@POST @Path("/login") @Consumes(MediaType.MULTIPART_FORM_DATA) public Response authenticate( @FormDataParam("username") String userId, @FormDataParam("password") String password) { Session session = databaseManager.getSession(); ResultSet user = session.execute("SELECT * FROM righteous.user where user_id = '" + userId + "'"); Row row = null; if (user.isExhausted()) { session.close(); return Response.status(200).entity("Invalid Username or Password").build(); } else { row = user.one(); } if (row.getString("user_id").equals(userId) && row.getString("user_password").equals(password)) { session.close(); return Response.status(200).entity("success").build(); } else { session.close(); return Response.status(200).entity("Invalid Username or Password").build(); } }
public java.util.LinkedList<Pic> getPicsForUser(String User) { java.util.LinkedList<Pic> Pics = new java.util.LinkedList<>(); Session session = cluster.connect("instagrAndrew"); PreparedStatement ps = session.prepare("select picid, hashtag, pic_added from userpiclist where user =?"); ResultSet rs = null; BoundStatement boundStatement = new BoundStatement(ps); rs = session.execute( // this is where the query is executed boundStatement.bind( // here you are binding the 'boundStatement' User)); if (rs.isExhausted()) { System.out.println("No Images returned"); return null; } else { for (Row row : rs) { Pic pic = new Pic(); java.util.UUID UUID = row.getUUID("picid"); Date d = row.getDate("pic_added"); java.sql.Timestamp tmp = new java.sql.Timestamp(d.getTime()); pic.setUUID(UUID); pic.setDate(tmp); String ht = row.getString("hashtag"); if (ht != null) { pic.setHashtag(ht); } Pics.add(pic); } } return Pics; }
@Override public void removeValuesUnusedLongerThan(long minimumAge, TimeUnit unit) throws BinaryStoreException { try { Date deadline = new Date(new Date().getTime() - unit.toMillis(minimumAge)); // When querying using 2nd indexes, Cassandra // (it's not CQL specific) requires that you use an '=' for at least one of // the indexed column in the where clause. This is a limitation of Cassandra. // So we have to do some tricks here ResultSet rs = session.execute( "SELECT cid from modeshape.binary where usage=0 and usage_time < " + deadline.getTime() + " allow filtering;"); Iterator<Row> rows = rs.iterator(); while (rows.hasNext()) { session.execute( "DELETE from modeshape.binary where cid = '" + rows.next().getString("cid") + "';"); } rs = session.execute( "SELECT cid from modeshape.binary where usage=1 and usage_time < " + deadline.getTime() + " allow filtering;"); rows = rs.iterator(); while (rows.hasNext()) { session.execute( "DELETE from modeshape.binary where cid = '" + rows.next().getString("cid") + "';"); } } catch (RuntimeException e) { throw new BinaryStoreException(e); } }
public Optional<Auction> getAuction(String auctionName) { BoundStatement auctionBoundStatement = getAuction.bind(auctionName); Row auction = session.execute(auctionBoundStatement).one(); LOGGER.debug("Getting auction information for auction {} rows {}", auctionName, auction); BoundStatement bidsBound = getAuctionBids.bind(auctionName); List<BidVo> bids = session .execute(bidsBound) .all() .stream() .map( row -> new BidVo( row.getString("bid_user"), row.getLong("bid_amount"), UUIDs.unixTimestamp(row.getUUID("bid_time")))) .collect(Collectors.toList()); return Optional.of( new Auction( auction.getString("name"), Instant.ofEpochMilli(auction.getLong("ends")), bids, auction.getString("owner"))); }
public void execute(Tuple tuple) { LOG.info("Story found"); String tweet = tuple.getString(0); outputCollector.ack(tuple); PreparedStatement preparedStatement = session.prepare("INSERT INTO tweets (seen, tweet) VALUES (?, ?)"); session.execute(preparedStatement.bind(new Timestamp(System.currentTimeMillis()), tweet)); }
@PostConstruct public void prepareStatements() { createAuction = session.prepare("insert INTO auctions (name, owner, ends) VALUES (?, ?, ?)"); getAuction = session.prepare("select * from auctions where name = ?"); getAuctionBids = session.prepare("select * from auction_bids where name = ?"); getAllAuctionSparse = session.prepare("select * from auctions"); storeBid = session.prepare( "INSERT INTO auction_bids (name, bid_time , bid_amount , bid_user) VALUES ( ?, ?, ?, ?);"); }
@Test public void testTridentTopology() throws Exception { Session session = cassandraCQLUnit.session; String[] stationIds = {"station-1", "station-2", "station-3"}; for (int i = 1; i < 4; i++) { ResultSet resultSet = session.execute( "INSERT INTO weather.station(id, name) VALUES(?, ?)", stationIds[i - 1], "Foo-Station-" + new Random().nextInt()); } ResultSet rows = cassandraCQLUnit.session.execute("SELECT * FROM weather.station"); for (Row row : rows) { System.out.println("####### row = " + row); } WeatherBatchSpout weatherBatchSpout = new WeatherBatchSpout( new Fields("weather_station_id", "temperature", "event_time"), 3, stationIds); TridentTopology topology = new TridentTopology(); Stream stream = topology.newStream("cassandra-trident-stream", weatherBatchSpout); CassandraStateFactory insertValuesStateFactory = getInsertTemperatureStateFactory(); CassandraStateFactory selectWeatherStationStateFactory = getSelectWeatherStationStateFactory(); TridentState selectState = topology.newStaticState(selectWeatherStationStateFactory); stream = stream.stateQuery( selectState, new Fields("weather_station_id"), new CassandraQuery(), new Fields("name")); stream = stream.each(new Fields("name"), new PrintFunction(), new Fields("name_x")); stream.partitionPersist( insertValuesStateFactory, new Fields("weather_station_id", "name", "event_time", "temperature"), new CassandraStateUpdater(), new Fields()); StormTopology stormTopology = topology.build(); LocalCluster cluster = new LocalCluster(); cluster.submitTopology("wordCounter", getConfig(), stormTopology); Thread.sleep(30 * 1000); rows = cassandraCQLUnit.session.execute("SELECT * FROM weather.temperature"); Assert.assertTrue(rows.iterator().hasNext()); // basic sanity check cluster.killTopology("wordCounter"); cluster.shutdown(); }
@POST @Path("/register") public Response register( @FormDataParam("id") String userId, @FormDataParam("username") String userName, @FormDataParam("password") String password, @FormDataParam("dob") String dob, @FormDataParam("gender") String gender, @FormDataParam("location") String location, @FormDataParam("proPic") InputStream proPicInputStream, @FormDataParam("proPic") FormDataContentDisposition proPicFileDetail) { Session session = databaseManager.getSession(); ResultSet users = session.execute("SELECT * FROM righteous.user"); Calendar calendar = new GregorianCalendar(); SimpleDateFormat simpleDateFormat = new SimpleDateFormat("yyyy-MM-dd"); Date date = null; try { date = simpleDateFormat.parse(dob); } catch (ParseException e1) { log.error("", e1); } calendar.setTime(date); for (Row row : users) { if (row.getString("user_id").equalsIgnoreCase(userId)) { return Response.status(200).entity("Username unavailable").build(); } } byte[] imageBytes = null; try { imageBytes = org.apache.commons.io.IOUtils.toByteArray(proPicInputStream); } catch (IOException e) { log.error("Unable to retrieve the image", e); } ByteBuffer imageByteBuffer = ByteBuffer.wrap(imageBytes); PreparedStatement preparedStatement = session.prepare( "INSERT INTO righteous.user (user_id, user_name, user_password, user_dob, user_gender, user_location, user_pic) " + "VALUES (?,?,?,?,?,?,?)"); BoundStatement boundStatement = new BoundStatement(preparedStatement); session.execute( boundStatement.bind( userId, userName, password, calendar.getTime(), gender, location, imageByteBuffer)); session.close(); return Response.status(200).entity("Registration successful").build(); }
private void refreshEndpointMap() { String keyspace = ConfigHelper.getOutputKeyspace(conf); try (Session session = CqlConfigHelper.getOutputCluster(ConfigHelper.getOutputInitialAddress(conf), conf) .connect(keyspace)) { rangeMap = new HashMap<>(); metadata = session.getCluster().getMetadata(); Set<TokenRange> ranges = metadata.getTokenRanges(); for (TokenRange range : ranges) { rangeMap.put(range, metadata.getReplicas(keyspace, range)); } } }
public static synchronized Session getSession(String host, int port) throws UnknownHostException { Session session = hostConnectionMap.getIfPresent(host); if (session == null || session.isClosed()) { Cluster.Builder builder = Cluster.builder().addContactPoint(host).withPort(port); Cluster cluster = builder.build(); session = cluster.connect(); hostConnectionMap.put(host, session); logger.debug("Created connection to {}.", host); logger.debug("Number of sessions opened are {}.", hostConnectionMap.size()); } return session; }
public List<ListenableFuture<ResultSet>> applyStatements(List<String> ss, boolean sync) throws Exception { List<ListenableFuture<ResultSet>> list = new ArrayList<>(); for (String s : ss) { System.out.println(s); if (sync) { session.execute(s); } else { list.add(session.executeAsync(s)); } } return list; }
@Test public void should_batch_counters() throws Exception { // Start batch CQLBatchingEntityManager batchEm = emf.createBatchingEntityManager(); batchEm.startBatch(); CompleteBean entity = CompleteBeanTestBuilder.builder().randomId().name("name").buid(); entity = batchEm.merge(entity); entity.setLabel("label"); Tweet welcomeTweet = TweetTestBuilder.tweet().randomId().content("welcomeTweet").buid(); entity.setWelcomeTweet(welcomeTweet); entity.getVersion().incr(10L); batchEm.merge(entity); Row result = session.execute("SELECT label from CompleteBean where id=" + entity.getId()).one(); assertThat(result).isNull(); result = session .execute( "SELECT counter_value from achilles_counter_table where fqcn='" + CompleteBean.class.getCanonicalName() + "' and primary_key='" + entity.getId() + "' and property_name='version'") .one(); assertThat(result.getLong("counter_value")).isEqualTo(10L); // Flush batchEm.endBatch(); result = session.execute("SELECT label from CompleteBean where id=" + entity.getId()).one(); assertThat(result.getString("label")).isEqualTo("label"); result = session .execute( "SELECT counter_value from achilles_counter_table where fqcn='" + CompleteBean.class.getCanonicalName() + "' and primary_key='" + entity.getId() + "' and property_name='version'") .one(); assertThat(result.getLong("counter_value")).isEqualTo(10L); assertThatBatchContextHasBeenReset(batchEm); }
public static void main(String[] args) { System.out.println("Connecting to db: " + System.getProperty("DB_HOST")); Cluster cluster = Cluster.builder().addContactPoints(System.getProperty("DB_HOST").split(",")).build(); Session session = cluster.connect(); session.execute( "CREATE KEYSPACE IF NOT EXISTS todolist WITH REPLICATION = { 'class' : 'SimpleStrategy', 'replication_factor' : 3 };"); session.execute( "CREATE TABLE IF NOT EXISTS todolist.todo (" + "id int PRIMARY KEY," + "text text);"); SpringApplication.run(Application.class, args); }
private void dropTables() { ResultSet resultSet = session.execute( "SELECT columnfamily_name FROM system.schema_columnfamilies " + "WHERE keyspace_name = 'rhq'"); for (Row row : resultSet) { String table = row.getString(0); if (table.equals("one_hour_metrics") || table.equals("six_hour_metrics") || table.equals("twenty_four_hour_metrics")) { log.info("Dropping table " + table); session.execute("DROP table rhq." + table); } } }
public void updateConnection( String displayName, String profileUrl, String imageUrl, String accessToken, String secret, String refreshToken, Long expireTime, String userId, String providerId, String providerUserId) { try { Statement updateConn = QueryBuilder.update(keyspace, table) .with(QueryBuilder.set("displayName", displayName)) .and(QueryBuilder.set("profileUrl", profileUrl)) .and(QueryBuilder.set("imageUrl", imageUrl)) .and(QueryBuilder.set("accessToken", accessToken)) .and(QueryBuilder.set("secret", secret)) .and(QueryBuilder.set("refreshToken", refreshToken)) .and(QueryBuilder.set("expireTime", expireTime)) .where(QueryBuilder.eq("userId", userId)) .and(QueryBuilder.eq("providerId", providerId)) .and(QueryBuilder.eq("providerUserId", providerUserId)); session.execute(updateConn); } catch (Exception e) { e.printStackTrace(); } }
public Set<String> findUserIdsConnectedTo(String providerId, Set<String> providerUserIds) { ResultSet rs = null; Set<String> localUserIds = null; Statement getUserIds = null; try { getUserIds = QueryBuilder.select() .column("userid") .from(keyspace, table) .where(QueryBuilder.eq("providerId", providerId)) .and(QueryBuilder.in("providerUserId", providerUserIds)); rs = session.execute(getUserIds); if (rs.all().size() > 0) { localUserIds = new HashSet<String>(); } for (Row row : rs.all()) { localUserIds.add(row.getString("userId")); } return localUserIds; } catch (Exception e) { e.printStackTrace(); } return null; }
private void initPreparedStatements() { find1HourData = session.prepare( "SELECT schedule_id, time, type, value, ttl(value), writetime(value) FROM rhq.one_hour_metrics " + "WHERE schedule_id = ?"); find6HourData = session.prepare( "SELECT schedule_id, time, type, value, ttl(value), writetime(value) FROM rhq.six_hour_metrics " + "WHERE schedule_id = ?"); find24HourData = session.prepare( "SELECT schedule_id, time, type, value, ttl(value), writetime(value) FROM rhq.twenty_four_hour_metrics " + "WHERE schedule_id = ?"); }
@SuppressWarnings("unchecked") @Override public void multiPut(List<List<Object>> keys, List<T> values) { LOG.debug("Putting the following keys: {} with values: {}", keys, values); try { List<Statement> statements = new ArrayList<Statement>(); // Retrieve the mapping statement for the key,val pair for (int i = 0; i < keys.size(); i++) { List<Object> key = keys.get(i); T val = values.get(i); Statement retrievedStatment = mapper.map(key, val); if (retrievedStatment instanceof BatchStatement) { // Allows for BatchStatements to be returned by the mapper. BatchStatement batchedStatment = (BatchStatement) retrievedStatment; statements.addAll(batchedStatment.getStatements()); } else { statements.add(retrievedStatment); } } // Execute all the statements as a batch. BatchStatement batch = new BatchStatement(batchType); batch.addAll(statements); session.execute(batch); _mwrites.incrBy(statements.size()); } catch (Exception e) { checkCassandraException(e); LOG.error("Exception {} caught.", e); } }
//////////////////////////////////// // Overridden Methods for IBackingMap //////////////////////////////////// @SuppressWarnings("unchecked") @Override public List<T> multiGet(List<List<Object>> keys) { try { List<T> values = new ArrayList<T>(); for (List<Object> rowKey : keys) { Statement statement = mapper.retrieve(rowKey); ResultSet results = session.execute(statement); // TODO: Better way to check for empty results besides accessing entire results list Iterator<Row> rowIter = results.iterator(); Row row; if (results != null && rowIter.hasNext() && (row = rowIter.next()) != null) { if (rowIter.hasNext()) { LOG.error("Found non-unique value for key [{}]", rowKey); } else { values.add((T) mapper.getValue(row)); } } else { values.add(null); } } _mreads.incrBy(values.size()); LOG.debug("Retrieving the following keys: {} with values: {}", keys, values); return values; } catch (Exception e) { checkCassandraException(e); throw new IllegalStateException("Impossible to reach this code"); } }
private void writeToRegister( String key, int index, String clId, long l, long latencyDep, long curr_deadline2, String string, Session session) { // TODO Auto-generated method stub String cqlStr = "INSERT INTO consistify.registry (KEY, CLID, DEADLINE, INDIC, LATENCYDEP,WAITINGTIME,STATUS, CREATETIME) VALUES ('" + key + "','" + clId + "','" + +curr_deadline2 + "','" + index + " ','" + latencyDep + " ','" + l + " ','" + string + " ','" + (long) System.currentTimeMillis() + "') if not exists"; Statement statement = new SimpleStatement(cqlStr); // System.out.println("****11consistify cqlStr:="+cqlStr); statement.setConsistencyLevel(ConsistencyLevel.ALL); session.execute(statement); // .executeAsync(arg0) }
// private ArrayList<RegistryEntry> readFromRegister(String key, Session session) { private String readFromRegister(String key, Session session) { // TODO Auto-generated method stub // Map<String, String> resultMap = new HashMap<String, String>(); String CLID = null, STATUS = null; String cqlStr = "SELECT * from consistify.registry WHERE key='" + key + "'"; Statement statement = new SimpleStatement(cqlStr); ResultSet results = session.execute(statement); CopyOnWriteArrayList<RegistryEntry> rList = new CopyOnWriteArrayList<RegistryEntry>(); RegistryEntry r = null; Scheduler scheduler = new Scheduler(); for (Row aRow : results) { // if (!resultMap.containsKey(aRow.getKey())) { if (aRow.getString("CREATETIME") != null && aRow.getString("key").equalsIgnoreCase(key)) { r = new RegistryEntry(); r.setKey(aRow.getString("key")); // System.out.println("**222*CLID:=="+aRow.getString("CLID")); r.setCLID(aRow.getString("CLID")); r.setDEADLINE(aRow.getString("DEADLINE")); r.setINDEX(aRow.getString("INDIC")); r.setLATENCYDEP(aRow.getString("LATENCYDEP")); r.setWAITINGTIME(aRow.getString("WAITINGTIME")); r.setSTATUS(aRow.getString("STATUS")); r.setCREATETIME(aRow.getString("CREATETIME")); rList.add(r); } // resultMap.put(aRow.getKey(), ++rowCnt); // System.out.println(aRow.getKey() + ":" + rowCnt); // } } // CLID = scheduler.schedule(rList).split(":")[0]; CLID = scheduler.schedule(rList); // System.out.println("****CLID:="+CLID); return CLID; }
public <K> void deleteByKeyAsync( Iterable<K> keys, Class<?> bean, Session session, ConsistencyLevel consistency) { for (K key : keys) { session.executeAsync(runDelete(key, bean, consistency)); } }
@Override public void output(Collection<Metric> metrics) { if (!eventRegistered.getAndSet(true)) { EventBusManager.createRegistrationPoint() .subscribe( WriteToStorageEvent.class, w -> { MetricStorage storage = w.storageToWriteTo().getSubStorageCalled("cassandra"); storage.store("metrics-to-cassandra", metricCount.longValue()); }); EvilManagerHack.subscribe(this.cluster); } if (metrics.size() == 0) { return; } Map<RetentionTable, BatchStatement> stms = LazyMap.<RetentionTable, BatchStatement>lazyMap( new HashMap<>(), () -> new BatchStatement()); for (Metric metric : metrics) { insertMetricIntoBatch(metric, stms); } KeyspaceMetadata metadata = cluster.getMetadata().getKeyspace(keyspace); for (RetentionTable table : stms.keySet()) { createTableIfNecessary(table, metadata); } for (BatchStatement batch : stms.values()) { session.execute(batch); } metricCount.addAndGet(metrics.size()); }
@Override public List<Application> getApplicationsFollowedBy(String userId) throws TException { checkUserId(userId); Statement query = createQueryForAppsFollowedBy(userId); ResultSet results; try { results = cassandra.execute(query); } catch (Exception ex) { LOG.error("Failed to query Cassandra for apps followed by User: [{}]", userId, ex); throw new OperationFailedException( "Could not find apps followed by user: "******"Found {} apps followed by {}", apps.size(), userId); return apps; }
@Override public List<User> getApplicationFollowers(String applicationId) throws TException { checkAppId(applicationId); Statement query = createQueryForFollowersOfApp(applicationId); ResultSet results; try { results = cassandra.execute(query); } catch (Exception ex) { LOG.error("Failed to query for App's followed: App: [{}]", applicationId, ex); throw new OperationFailedException("Could not query for App's Followers: " + ex.getMessage()); } List<User> followers = Lists.create(); for (Row row : results) { User follower = createUserFromRow(row); followers.add(follower); } LOG.debug("Found {} Users followed App [{}]", followers.size(), applicationId); return followers; }
public void changePassword(String username, String newPassword) { Session session = cluster.connect("ducquak"); Statement s00; s00 = QueryBuilder.select().all().from("ducquak", "users"); ResultSet rs = session.execute(s00); for (Row row : rs) { String olduserName = row.getString("userName"); if (olduserName.equals(username)) { Statement s01 = QueryBuilder.update("ducquak", "users") .with(set("password", username)) .where(eq("password", olduserName)); session.execute(s01); } } }
@Test public void should_execute_cas_successfully() throws Exception { // Given final AtomicBoolean casSuccess = new AtomicBoolean(false); CASResultListener listener = new CASResultListener() { @Override public void onCASSuccess() { casSuccess.compareAndSet(false, true); } @Override public void onCASError(CASResult casResult) {} }; when(rs.getQueryString()).thenReturn("INSERT INTO table IF NOT EXISTS"); wrapper = new RegularStatementWrapper( CompleteBean.class, rs, new Object[] {1}, ONE, Optional.fromNullable(listener), NO_SERIAL_CONSISTENCY); when(session.execute(rs)).thenReturn(resultSet); when(resultSet.one().getBool(CAS_RESULT_COLUMN)).thenReturn(true); // When wrapper.execute(session); // Then verify(session).execute(rs); assertThat(casSuccess.get()).isTrue(); }
public List<String> findUserIdsWithConnection(Connection<?> connection) { ResultSet rs = null; List<String> localUserIds = null; ConnectionKey key = connection.getKey(); Statement getUserIds = null; try { getUserIds = QueryBuilder.select() .column("userid") .from(keyspace, table) .allowFiltering() .where(QueryBuilder.eq("providerId", key.getProviderId())) .and(QueryBuilder.eq("providerUserId", key.getProviderUserId())); rs = session.execute(getUserIds); List<Row> rows = rs.all(); if (rows.size() > 0) { localUserIds = new LinkedList<String>(); } for (Row row : rows) { localUserIds.add(row.getString("userId")); } return localUserIds; } catch (Exception e) { e.printStackTrace(); } return null; }