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; }
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; }
@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); } }
//////////////////////////////////// // 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"); } }
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; }
private void test() { ResultSet result = cassandraCQLUnit.session.execute( "select * from testCQLTable WHERE id='1690e8da-5bf8-49e8-9583-4dff8a570737'"); String val = result.iterator().next().getString("value"); assertEquals("Cql loaded string", val); }
/** Test simple statement inserts for all collection data types */ public void collectionInsertTest() throws Throwable { ResultSet rs; for (String execute_string : COLLECTION_INSERT_STATEMENTS) { rs = session.execute(execute_string); assertTrue(rs.isExhausted()); } assertEquals(SAMPLE_COLLECTIONS.size(), 255); assertEquals(COLLECTION_INSERT_STATEMENTS.size(), SAMPLE_COLLECTIONS.size()); }
/** Test simple statement inserts for all primitive data types */ public void primitiveInsertTest() throws Throwable { ResultSet rs; for (String execute_string : PRIMITIVE_INSERT_STATEMENTS) { rs = session.execute(execute_string); assertTrue(rs.isExhausted()); } assertEquals(SAMPLE_DATA.size(), 15); assertEquals(PRIMITIVE_INSERT_STATEMENTS.size(), SAMPLE_DATA.size()); }
/** * @param resultSet * @param type * @return * @deprecated as of 1.5, {@link * org.springframework.data.cassandra.mapping.CassandraMappingContext} handles type * conversion. */ @Deprecated public Object getSingleEntity(ResultSet resultSet, Class<?> type) { Object result = (resultSet.isExhausted() ? null : template.getConverter().read(type, resultSet.one())); warnIfMoreResults(resultSet); return result; }
/** * Test content for existence. * * @param key content identifier * @param alive true inside used content and false for checking within content marked as unused. * @return true if content found * @throws BinaryStoreException */ private boolean contentExists(BinaryKey key, boolean alive) throws BinaryStoreException { try { String query = "SELECT payload from modeshape.binary where cid='" + key.toString() + "'"; query = alive ? query + " and usage=1;" : query + " and usage = 0;"; ResultSet rs = session.execute(query); return rs.iterator().hasNext(); } catch (RuntimeException e) { throw new BinaryStoreException(e); } }
@Override public Company getCompany(final String firstName, final String lastName) { final String cql = "select * from company where first_name = ? and last_name = ?"; final PreparedStatement cachedPreparedStatement = getCachedPreparedStatement(cql); final BoundStatement statement = cachedPreparedStatement.bind(firstName, lastName); final ResultSet resultSet = cassandraOperations.getSession().execute(statement); final Row row = resultSet.one(); return toCompany(row); }
@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(); }
private void warnIfMoreResults(ResultSet resultSet) { if (log.isWarnEnabled() && !resultSet.isExhausted()) { int count = 0; while (resultSet.one() != null) { count++; } log.warn("ignoring extra {} row{}", count, count == 1 ? "" : "s"); } }
@Override public Iterable<BinaryKey> getAllBinaryKeys() throws BinaryStoreException { try { ResultSet rs = session.execute("SELECT cid from modeshape.binary WHERE usage=1;"); Iterator<Row> it = rs.iterator(); HashSet<BinaryKey> keys = new HashSet<BinaryKey>(); while (it.hasNext()) { keys.add(new BinaryKey(it.next().getString("cid"))); } return keys; } catch (RuntimeException e) { throw new BinaryStoreException(e); } }
@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 java.util.LinkedList<Pic> getMatchingPics(String searched) { java.util.LinkedList<Pic> picList = new java.util.LinkedList<Pic>(); Session session = cluster.connect("instagrAndrew"); PreparedStatement ps = session.prepare("select * from userpicList"); ResultSet rs = null; BoundStatement boundStatement = new BoundStatement(ps); rs = session.execute(boundStatement); if (rs.isExhausted()) { System.out.println("No Images returned"); return new java.util.LinkedList<Pic>(); } else { for (Row row : rs) { String fullString = row.getString("hashtag"); UUID uuid = row.getUUID("picId"); String us = row.getString("user"); Date d = row.getDate("pic_added"); java.sql.Timestamp tmp = new java.sql.Timestamp(d.getTime()); String[] tags; try { tags = fullString.split(","); } catch (Exception ex) { tags = null; } if (tags != null) { for (int i = 0; i < tags.length; i++) { if (tags[i].toLowerCase().equals(searched.toLowerCase())) { Pic toAdd = new Pic(); toAdd.setUUID(uuid); toAdd.setDate(tmp); toAdd.setUser(us); toAdd.setHashtag(fullString); picList.add(toAdd); break; } } } } } return picList; }
private void initScheme(Session session, String keyspace) throws IOException { if (keyspace == null) { keyspace = AlertProperties.getProperty(ALERTS_CASSANDRA_KEYSPACE, "hawkular_alerts"); } if (log.isDebugEnabled()) { log.debug("Checking Schema existence for keyspace: " + keyspace); } ResultSet resultSet = session.execute( "SELECT * FROM system.schema_keyspaces WHERE keyspace_name = '" + keyspace + "'"); if (!resultSet.isExhausted()) { log.debug("Schema already exist. Skipping schema creation."); initialized = true; return; } log.infof("Creating Schema for keyspace %s", keyspace); ImmutableMap<String, String> schemaVars = ImmutableMap.of("keyspace", keyspace); String updatedCQL = null; try (InputStream inputStream = CassCluster.class.getResourceAsStream("/hawkular-alerts-schema.cql"); InputStreamReader reader = new InputStreamReader(inputStream)) { String content = CharStreams.toString(reader); for (String cql : content.split("(?m)^-- #.*$")) { if (!cql.startsWith("--")) { updatedCQL = substituteVars(cql.trim(), schemaVars); if (log.isDebugEnabled()) { log.debug("Executing CQL:\n" + updatedCQL + "\n"); } session.execute(updatedCQL); } } } catch (Exception e) { log.errorf("Failed schema creation: %s\nEXECUTING CQL:\n%s", e, updatedCQL); } initialized = true; log.infof("Done creating Schema for keyspace: " + keyspace); }
@Test public void doAppendTest() throws IOException, InterruptedException { DeliveryCallback callback = new DeliveryCallback(); logAppender.doAppend(generateLogEventPack(20), callback); Thread.sleep(3000); CassandraLogEventDao logEventDao = (CassandraLogEventDao) ReflectionTestUtils.getField(logAppender, "logEventDao"); Session session = (Session) ReflectionTestUtils.getField(logEventDao, "session"); ResultSet resultSet = session.execute( QueryBuilder.select() .countAll() .from( KEY_SPACE_NAME, "logs_" + appToken + "_" + Math.abs(configuration.hashCode()))); Row row = resultSet.one(); Assert.assertEquals(20L, row.getLong(0)); Assert.assertEquals(1, callback.getSuccessCount()); }
@Override protected String getStoredMimeType(BinaryValue source) throws BinaryStoreException { try { checkContentExists(source); ResultSet rs = session.execute( "SELECT mime_type FROM modeshape.binary WHERE cid = '" + source.getKey() + "';"); Row row = rs.one(); if (row == null) { throw new BinaryStoreException( JcrI18n.unableToFindBinaryValue.text(source.getKey(), session)); } return row.getString("mime_type"); } catch (BinaryStoreException e) { throw e; } catch (RuntimeException e) { throw new BinaryStoreException(e); } }
@Test public void testCassandraBatchInsertAndSelectStatement() throws Exception { List<Book> books = getBookList(5); this.cassandraMessageHandler2.handleMessage(new GenericMessage<>(books)); Message<?> message = MessageBuilder.withPayload("Cassandra Guru").setHeader("limit", 2).build(); this.cassandraMessageHandler4.handleMessage(message); Message<?> receive = this.resultChannel.receive(10000); assertNotNull(receive); assertThat(receive.getPayload(), instanceOf(ResultSet.class)); ResultSet resultSet = (ResultSet) receive.getPayload(); assertNotNull(resultSet); List<Row> rows = resultSet.all(); assertEquals(2, rows.size()); this.cassandraMessageHandler1.handleMessage( new GenericMessage<>(QueryBuilder.truncate("book"))); }
@Override public InputStream getInputStream(BinaryKey key) throws BinaryStoreException { try { ResultSet rs = session.execute( "SELECT payload FROM modeshape.binary WHERE cid='" + key.toString() + "' and usage=1;"); Row row = rs.one(); if (row == null) { throw new BinaryStoreException(JcrI18n.unableToFindBinaryValue.text(key, session)); } ByteBuffer buffer = row.getBytes("payload"); return new BufferedInputStream(buffer); } catch (BinaryStoreException e) { throw e; } catch (RuntimeException e) { throw new BinaryStoreException(e); } }
public UUID getProfilePic(String User) { Session session = cluster.connect("instagrAndrew"); PreparedStatement ps = session.prepare("select profilepic from userprofiles where login =?"); 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) { java.util.UUID UUID = row.getUUID("profilepic"); return UUID; } return null; } }
@Override public boolean followingExists(String userId, String applicationId) throws TException { checkUserId(userId); checkAppId(applicationId); Statement query = createStatementToCheckIfFollowingExists(userId, applicationId); ResultSet results; try { results = cassandra.execute(query); } catch (Exception ex) { LOG.error( "Failed to query for following between User: [{}] App: [{}]", userId, applicationId, ex); throw new OperationFailedException("Could not query for following: " + ex.getMessage()); } Row row = results.one(); checkRowExists(row); long count = row.getLong(0); return count > 0; }
@SuppressWarnings("unchecked") public <T> List<T> recoverObjet(Class<T> bean, ResultSet resultSet) { List<T> listObjList = new LinkedList<T>(); for (Row row : resultSet.all()) { Map<String, Definition> mapDefinition = createMapDefinition(row.getColumnDefinitions()); Object newObjetc = createObject(bean, row, mapDefinition); listObjList.add((T) newObjetc); } return listObjList; }
public List<ListenableFuture<ResultSet>> moveTable(String name) throws ExecutionException { System.out.println("inserting data to destination:" + name); String query = "select * from " + name; BoundStatement bs = source.peer.bPrepare(source.session, query); ResultSet rs = source.session.execute(bs); ColumnDefinitions defs = rs.getColumnDefinitions(); int ncols = defs.size(); boolean update = false; for (int i = 0; i < ncols; ++i) { DataType dt = defs.getType(i); if (DataType.Name.COUNTER.equals(dt.getName())) { update = true; break; } } if (update) { return moveTableUpdate(name, rs, defs); } else { return moveTableInsert(name, rs, defs); } }
@Test public void should_throw_exception_on_cas_error() throws Exception { // Given final AtomicReference<CASResult> atomicCASResult = new AtomicReference<>(null); CASResultListener listener = new CASResultListener() { @Override public void onCASSuccess() {} @Override public void onCASError(CASResult casResult) { atomicCASResult.compareAndSet(null, casResult); } }; wrapper = new RegularStatementWrapper( CompleteBean.class, rs, new Object[] {1}, ONE, Optional.fromNullable(listener), NO_SERIAL_CONSISTENCY); wrapper.invoker = invoker; when(rs.getQueryString()).thenReturn("UPDATE table IF name='John' SET"); when(session.execute(rs)).thenReturn(resultSet); when(resultSet.one()).thenReturn(row); when(row.getBool(CAS_RESULT_COLUMN)).thenReturn(false); when(row.getColumnDefinitions()).thenReturn(columnDefinitions); when(columnDefinitions.iterator().hasNext()).thenReturn(true, true, false); Definition col1 = buildColumnDef("keyspace", "table", "[applied]", DataType.cboolean()); Definition col2 = buildColumnDef("keyspace", "table", "name", DataType.text()); when(columnDefinitions.iterator().next()).thenReturn(col1, col2); when(invoker.invokeOnRowForType(row, DataType.cboolean().asJavaClass(), "[applied]")) .thenReturn(false); when(invoker.invokeOnRowForType(row, DataType.text().asJavaClass(), "name")) .thenReturn("Helen"); // When wrapper.execute(session); // Then verify(session).execute(rs); final CASResult actual = atomicCASResult.get(); assertThat(actual).isNotNull(); assertThat(actual.operation()).isEqualTo(UPDATE); assertThat(actual.currentValues()) .contains(MapEntry.entry("[applied]", false), MapEntry.entry("name", "Helen")); }
private Row getRow(ResultSet resultSet) { Iterator<Row> iterator = resultSet.iterator(); if (!iterator.hasNext()) { return null; } Row firstRow = iterator.next(); if (singleResult && iterator.hasNext()) { throw new CassandraNotSingleResultException(resultSet); } return firstRow; }
@Test public void should_notify_listener_on_cas_error() throws Exception { // Given wrapper = new RegularStatementWrapper( CompleteBean.class, rs, new Object[] {1}, ONE, NO_LISTENER, NO_SERIAL_CONSISTENCY); wrapper.invoker = invoker; when(rs.getQueryString()).thenReturn("INSERT INTO table IF NOT EXISTS"); when(session.execute(rs)).thenReturn(resultSet); when(resultSet.one()).thenReturn(row); when(row.getBool(CAS_RESULT_COLUMN)).thenReturn(false); when(row.getColumnDefinitions()).thenReturn(columnDefinitions); when(columnDefinitions.iterator().hasNext()).thenReturn(true, true, false); Definition col1 = buildColumnDef("keyspace", "table", "[applied]", DataType.cboolean()); Definition col2 = buildColumnDef("keyspace", "table", "id", DataType.bigint()); when(columnDefinitions.iterator().next()).thenReturn(col1, col2); when(invoker.invokeOnRowForType(row, DataType.cboolean().asJavaClass(), "[applied]")) .thenReturn(false); when(invoker.invokeOnRowForType(row, DataType.bigint().asJavaClass(), "id")).thenReturn(10L); AchillesLightWeightTransactionException caughtEx = null; // When try { wrapper.execute(session); } catch (AchillesLightWeightTransactionException ace) { caughtEx = ace; } // Then verify(session).execute(rs); assertThat(caughtEx).isNotNull(); assertThat(caughtEx.operation()).isEqualTo(INSERT); assertThat(caughtEx.currentValues()) .contains(MapEntry.entry("[applied]", false), MapEntry.entry("id", 10L)); }