Esempio n. 1
0
  @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();
    }
  }
  @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();
  }
  /**
   * @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;
  }
  @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);
  }
  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");
    }
  }
  @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"));
  }
 @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);
   }
 }
  @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);
    }
  }
  @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;
  }
  @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));
  }