Java Code Examples for com.datastax.driver.core.Row#getSet()

The following examples show how to use com.datastax.driver.core.Row#getSet() . You can vote up the ones you like or vote down the ones you don't like, and go to the original project or source file by following the links above each example. You may check out the related API usage on the sidebar.
Example 1
Source File: CassandraSchedulerModelDao.java    From arcusplatform with Apache License 2.0 6 votes vote down vote up
@Override
@Nullable
public ModelEntity findByAddress(Address address) {
   if(SchedulerCapability.NAMESPACE.equals(address.getGroup())) {
      try(Context cx = SchedulerMetrics.findByIdTimer.time()) {
         return findById((UUID) address.getId());
      }
   }

   try(Context cx = SchedulerMetrics.findByAddressTimer.time()) {
      Row row = session().execute( listByAddress.bind(address.getRepresentation()) ).one();
      if(row == null) {
         return null;
      }

      Set<UUID> schedulerIds = row.getSet(SchedulerAddressIndex.Columns.SCHEDULER_IDS, UUID.class);
      UUID schedulerId = Iterables.getFirst(schedulerIds, null);
      if(schedulerId == null) {
         return null;
      }

      return findById(schedulerId);
   }
}
 
Example 2
Source File: SetTest.java    From jmeter-cassandra with Apache License 2.0 6 votes vote down vote up
@Test
public void testInsertPreparedthesetle() {
    CassandraSampler cs = new CassandraSampler();

    cs.setProperty("sessionName",TESTSESSION);
    cs.setProperty("consistencyLevel", AbstractCassandaTestElement.ONE);
    cs.setProperty("resultVariable","rv");
    cs.setProperty("queryType", AbstractCassandaTestElement.PREPARED);
    cs.setProperty("queryArguments", "\"" + EXPECTED + "\"");
    cs.setProperty("query", "INSERT INTO " + TABLE + " (key,theset) VALUES (2, ?)");

    TestBeanHelper.prepare(cs);

    SampleResult res = cs.sample(new Entry());
    assertTrue(res.isSuccessful(), res.getResponseMessage());

    // See if the value matches
    Row row = session.execute("select theset from " + KEYSPACE + "." + TABLE + " where key = 2").one();
    Set<String> theSet = row.getSet(0, String.class);
    assertTrue(theSet.contains("one"));
    assertTrue(theSet.contains("two"));
    assertTrue(theSet.contains("three"));
    assertEquals(3, theSet.size());
}
 
Example 3
Source File: SchemaUpgrade.java    From glowroot with Apache License 2.0 6 votes vote down vote up
private void addSyntheticMonitorAndAlertPermissions() throws Exception {
    PreparedStatement insertPS =
            session.prepare("insert into role (name, permissions) values (?, ?)");
    ResultSet results = session.read("select name, permissions from role");
    for (Row row : results) {
        String name = row.getString(0);
        Set<String> permissions = row.getSet(1, String.class);
        Set<String> permissionsToBeAdded = upgradePermissions2(permissions);
        if (permissionsToBeAdded.isEmpty()) {
            continue;
        }
        permissions.addAll(permissionsToBeAdded);
        BoundStatement boundStatement = insertPS.bind();
        boundStatement.setString(0, name);
        boundStatement.setSet(1, permissions, String.class);
        session.write(boundStatement);
    }
}
 
Example 4
Source File: SchemaUpgrade.java    From glowroot with Apache License 2.0 6 votes vote down vote up
private void updateRoles() throws Exception {
    PreparedStatement insertPS =
            session.prepare("insert into role (name, permissions) values (?, ?)");
    ResultSet results = session.read("select name, permissions from role");
    for (Row row : results) {
        String name = row.getString(0);
        Set<String> permissions = row.getSet(1, String.class);
        Set<String> upgradedPermissions = upgradePermissions(permissions);
        if (upgradedPermissions == null) {
            continue;
        }
        BoundStatement boundStatement = insertPS.bind();
        boundStatement.setString(0, name);
        boundStatement.setSet(1, upgradedPermissions, String.class);
        session.write(boundStatement);
    }
}
 
Example 5
Source File: VoiceDAO.java    From arcusplatform with Apache License 2.0 6 votes vote down vote up
public Set<String> readAssistants(UUID placeId) {
   try(Timer.Context ctxt = readAssistantsTimer.time()) {
      ResultSet rs = session.execute(new BoundStatement(readAssistants).bind(placeId));
      Row r = rs.one();
      if(r == null) {
         return ImmutableSet.of();
      }

      // read repair google home
      Set<String> authorizations = new HashSet<>(r.getSet(Columns.voiceAssistants.name(), String.class));
      if(!r.isNull(Columns.googlehome.name()) && r.getBool(Columns.googlehome.name()) && !authorizations.contains(StartPlaceRequest.ASSISTANT_GOOGLE)) {
         recordAssistant(placeId, StartPlaceRequest.ASSISTANT_GOOGLE);
         authorizations.add(StartPlaceRequest.ASSISTANT_GOOGLE);
      }
      return authorizations;
   }
}
 
Example 6
Source File: AbstractUpsertOutputOperatorCodecsTest.java    From attic-apex-malhar with Apache License 2.0 5 votes vote down vote up
@Test
public void testForCollectionRemoval() throws Exception
{
  User aUser = new User();
  String userId = "user" + System.currentTimeMillis();
  aUser.setUserid(userId);
  FullName fullName = new FullName("first12" + System.currentTimeMillis(), "last12" + System.currentTimeMillis());
  aUser.setUsername(fullName);
  Set<String> emails = new HashSet<>();
  emails.add(new String("1"));
  emails.add(new String("2"));
  aUser.setEmails(emails);

  UpsertExecutionContext<User> originalEntry = new UpsertExecutionContext<>();
  originalEntry.setPayload(aUser);

  UpsertExecutionContext<User> subsequentUpdateForEmails = new UpsertExecutionContext<>();
  subsequentUpdateForEmails.setCollectionMutationStyle(
      UpsertExecutionContext.CollectionMutationStyle.REMOVE_FROM_EXISTING_COLLECTION);
  subsequentUpdateForEmails.setNullHandlingMutationStyle(
      UpsertExecutionContext.NullHandlingMutationStyle.IGNORE_NULL_COLUMNS);
  User oldUser = new User();
  oldUser.setUserid(userId);
  Set<String> updatedEmails = new HashSet<>();
  updatedEmails.add(new String("1"));
  oldUser.setEmails(updatedEmails);
  subsequentUpdateForEmails.setPayload(oldUser);
  userUpsertOperator.beginWindow(3);
  userUpsertOperator.input.process(originalEntry);
  userUpsertOperator.input.process(subsequentUpdateForEmails);
  userUpsertOperator.endWindow();

  ResultSet results = userUpsertOperator.session.execute(
      "SELECT * FROM unittests.users WHERE userid = '" + userId + "'");
  List<Row> rows = results.all();
  Row userRow = rows.get(0);
  Set<String> existingEmailsEntry = userRow.getSet("emails", String.class);
  assertEquals(1, existingEmailsEntry.size());
  assertEquals("" + 2, "" + existingEmailsEntry.iterator().next());
}
 
Example 7
Source File: SchemaUpgrade.java    From glowroot with Apache License 2.0 5 votes vote down vote up
private void updateRolePermissionName() throws Exception {
    PreparedStatement insertPS =
            session.prepare("insert into role (name, permissions) values (?, ?)");
    ResultSet results = session.read("select name, permissions from role");
    for (Row row : results) {
        String name = row.getString(0);
        Set<String> permissions = row.getSet(1, String.class);
        boolean updated = false;
        Set<String> upgradedPermissions = new HashSet<>();
        for (String permission : permissions) {
            PermissionParser parser = new PermissionParser(permission);
            parser.parse();
            if (parser.getPermission().equals("agent:alert")) {
                upgradedPermissions.add("agent:"
                        + PermissionParser.quoteIfNeededAndJoin(parser.getAgentRollupIds())
                        + ":incident");
                updated = true;
            } else {
                upgradedPermissions.add(permission);
            }
        }
        if (updated) {
            BoundStatement boundStatement = insertPS.bind();
            boundStatement.setString(0, name);
            boundStatement.setSet(1, upgradedPermissions, String.class);
            session.write(boundStatement);
        }
    }
}
 
Example 8
Source File: CassandraStorage.java    From cassandra-reaper with Apache License 2.0 5 votes vote down vote up
private static DiagEventSubscription createDiagEventSubscription(Row row) {
  return new DiagEventSubscription(
      Optional.of(row.getUUID("id")),
      row.getString("cluster"),
      Optional.of(row.getString("description")),
      row.getSet("nodes", String.class),
      row.getSet("events", String.class),
      row.getBool("export_sse"),
      row.getString("export_file_logger"),
      row.getString("export_http_endpoint"));
}
 
Example 9
Source File: IrisRealm.java    From arcusplatform with Apache License 2.0 5 votes vote down vote up
protected Set<String> getPermissions(com.datastax.driver.core.Session cassandraSession, Collection<String> roleNames) throws SQLException {
   Set<String> permissions = new LinkedHashSet<String>();
   for (String roleName : roleNames) {
      BoundStatement boundStatement = new BoundStatement(preparedPermissionsQuery);
      Row row = cassandraSession.execute(boundStatement.bind(roleName)).one();
      Set<String> thesePermissions = row.getSet("permission_names", String.class);
      // Add the permission to the set of permissions
      permissions.addAll(thesePermissions);
   }

   return permissions;
}
 
Example 10
Source File: IrisRealm.java    From arcusplatform with Apache License 2.0 5 votes vote down vote up
protected Set<String> getRoleNamesForUser(com.datastax.driver.core.Session cassandraSession, String username) throws SQLException {
   ParsedEmail parsedEmail = ParsedEmail.parse(username);
   BoundStatement boundStatement = new BoundStatement(preparedUserRolesQuery);
   Row row = cassandraSession.execute(boundStatement.bind(parsedEmail.getDomain(), parsedEmail.getUser_0_3(), parsedEmail.getUser())).one();
   Set<String> roleNames = row.getSet("role_names", String.class);
   return roleNames;
}
 
Example 11
Source File: AccountDAOImpl.java    From arcusplatform with Apache License 2.0 5 votes vote down vote up
@Override
protected void populateEntity(Row row, Account entity) {
   entity.setBillable(row.getBool(AccountEntityColumns.BILLABLE));
   entity.setState(row.getString(AccountEntityColumns.STATE));
   entity.setTaxExempt(row.getBool(AccountEntityColumns.TAX_EXEMPT));
   entity.setBillingFirstName(row.getString(AccountEntityColumns.BILLING_FIRST_NAME));
   entity.setBillingLastName(row.getString(AccountEntityColumns.BILLING_LAST_NAME));
   entity.setBillingCCType(row.getString(AccountEntityColumns.BILLING_CC_TYPE));
   entity.setBillingCCLast4(row.getString(AccountEntityColumns.BILLING_CC_LAST4));
   entity.setBillingStreet1(row.getString(AccountEntityColumns.BILLING_STREET1));
   entity.setBillingStreet2(row.getString(AccountEntityColumns.BILLING_STREET2));
   entity.setBillingCity(row.getString(AccountEntityColumns.BILLING_CITY));
   entity.setBillingState(row.getString(AccountEntityColumns.BILLING_STATE));
   entity.setBillingZip(row.getString(AccountEntityColumns.BILLING_ZIP));
   entity.setBillingZipPlusFour(row.getString(AccountEntityColumns.BILLING_ZIP_PLUS4));
   
   Set<UUID> placeIDs = row.getSet(AccountEntityColumns.PLACE_IDS, UUID.class);
   entity.setPlaceIDs(placeIDs == null || placeIDs.isEmpty() ? null : placeIDs);

   // Convert Subscription ID's to Map<ServiceLevel, String> if not empty
   Map<ServiceLevel, String> subIDs = null;
   Map<String, String> rowMap = row.getMap(AccountEntityColumns.SUBSCRIPTION_ID_MAP, String.class, String.class);
   if (rowMap != null && !rowMap.isEmpty()) {
   	subIDs = new HashMap<ServiceLevel, String>();
   	for (Map.Entry<String, String> item : rowMap.entrySet()) {
   		subIDs.put(ServiceLevel.valueOf(item.getKey()), item.getValue());
   	}
   }
   entity.setSubscriptionIDs(subIDs);
   entity.setOwner(row.getUUID(AccountEntityColumns.OWNER));
   entity.setTrialEnd(row.getTimestamp(AccountEntityColumns.TRIAL_END));
}
 
Example 12
Source File: PlaceDAOImpl.java    From arcusplatform with Apache License 2.0 5 votes vote down vote up
@Override
protected void populateEntity(Row row, Place entity) {
   entity.setCreated(row.getTimestamp(BaseEntityColumns.CREATED));
   entity.setModified(row.getTimestamp(BaseEntityColumns.MODIFIED));
   entity.setAccount(row.getUUID(PlaceEntityColumns.ACCOUNT_ID));
   entity.setName(row.getString(PlaceEntityColumns.NAME));
   entity.setState(row.getString(PlaceEntityColumns.STATE));
   entity.setStreetAddress1(row.getString(PlaceEntityColumns.STREET_ADDRESS_1));
   entity.setStreetAddress2(row.getString(PlaceEntityColumns.STREET_ADDRESS_2));
   entity.setCity(row.getString(PlaceEntityColumns.CITY));
   entity.setStateProv(row.getString(PlaceEntityColumns.STATE_PROV));
   entity.setZipCode(row.getString(PlaceEntityColumns.ZIP_CODE));
   entity.setZipPlus4(row.getString(PlaceEntityColumns.ZIP_PLUS_4));
   entity.setTzId(row.getString(PlaceEntityColumns.TZ_ID));
   entity.setTzName(row.getString(PlaceEntityColumns.TZ_NAME));
   entity.setTzOffset(row.getDouble(PlaceEntityColumns.TZ_OFFSET));
   entity.setTzUsesDST(row.getBool(PlaceEntityColumns.TZ_USES_DST));
   entity.setCountry(row.getString(PlaceEntityColumns.COUNTRY));
   entity.setAddrValidated(row.getBool(PlaceEntityColumns.ADDR_VALIDATED));
   entity.setAddrType(row.getString(PlaceEntityColumns.ADDR_TYPE));
   entity.setAddrZipType(row.getString(PlaceEntityColumns.ADDR_ZIP_TYPE));
   entity.setAddrLatitude(row.getDouble(PlaceEntityColumns.ADDR_LATITUDE));
   entity.setAddrLongitude(row.getDouble(PlaceEntityColumns.ADDR_LONGITUDE));
   entity.setAddrGeoPrecision(row.getString(PlaceEntityColumns.ADDR_GEO_PRECISION));
   entity.setAddrRDI(row.getString(PlaceEntityColumns.ADDR_RDI));
   entity.setAddrCounty(row.getString(PlaceEntityColumns.ADDR_COUNTY));
   entity.setAddrCountyFIPS(row.getString(PlaceEntityColumns.ADDR_COUNTY_FIPS));
   entity.setLastServiceLevelChange(row.getTimestamp(PlaceEntityColumns.LAST_SERVICE_LEVEL_CHANGE));
   String serviceLevel = row.getString(PlaceEntityColumns.SERVICE_LEVEL);
   if(serviceLevel != null) {
      entity.setServiceLevel(ServiceLevel.valueOf(serviceLevel));
   }
   Set<String> addons = row.getSet(PlaceEntityColumns.SERVICE_ADDONS, String.class);
   entity.setServiceAddons(addons == null || addons.isEmpty() ? null : addons);
   String population = row.getString(PlaceEntityColumns.POPULATION);
   entity.setPopulation(StringUtils.isEmpty(population)?Population.NAME_GENERAL:population);
   entity.setPrimary(row.getBool(PlaceEntityColumns.PRIMARY));

   populateMissingLocationData(entity);
}
 
Example 13
Source File: AbstractCassandraProcessor.java    From localization_nifi with Apache License 2.0 4 votes vote down vote up
protected static Object getCassandraObject(Row row, int i, DataType dataType) {
    if (dataType.equals(DataType.blob())) {
        return row.getBytes(i);

    } else if (dataType.equals(DataType.varint()) || dataType.equals(DataType.decimal())) {
        // Avro can't handle BigDecimal and BigInteger as numbers - it will throw an
        // AvroRuntimeException such as: "Unknown datum type: java.math.BigDecimal: 38"
        return row.getObject(i).toString();

    } else if (dataType.equals(DataType.cboolean())) {
        return row.getBool(i);

    } else if (dataType.equals(DataType.cint())) {
        return row.getInt(i);

    } else if (dataType.equals(DataType.bigint())
            || dataType.equals(DataType.counter())) {
        return row.getLong(i);

    } else if (dataType.equals(DataType.ascii())
            || dataType.equals(DataType.text())
            || dataType.equals(DataType.varchar())) {
        return row.getString(i);

    } else if (dataType.equals(DataType.cfloat())) {
        return row.getFloat(i);

    } else if (dataType.equals(DataType.cdouble())) {
        return row.getDouble(i);

    } else if (dataType.equals(DataType.timestamp())) {
        return row.getTimestamp(i);

    } else if (dataType.equals(DataType.date())) {
        return row.getDate(i);

    } else if (dataType.equals(DataType.time())) {
        return row.getTime(i);

    } else if (dataType.isCollection()) {

        List<DataType> typeArguments = dataType.getTypeArguments();
        if (typeArguments == null || typeArguments.size() == 0) {
            throw new IllegalArgumentException("Column[" + i + "] " + dataType.getName()
                    + " is a collection but no type arguments were specified!");
        }
        // Get the first type argument, to be used for lists and sets (and the first in a map)
        DataType firstArg = typeArguments.get(0);
        TypeCodec firstCodec = codecRegistry.codecFor(firstArg);
        if (dataType.equals(DataType.set(firstArg))) {
            return row.getSet(i, firstCodec.getJavaType());
        } else if (dataType.equals(DataType.list(firstArg))) {
            return row.getList(i, firstCodec.getJavaType());
        } else {
            // Must be an n-arg collection like map
            DataType secondArg = typeArguments.get(1);
            TypeCodec secondCodec = codecRegistry.codecFor(secondArg);
            if (dataType.equals(DataType.map(firstArg, secondArg))) {
                return row.getMap(i, firstCodec.getJavaType(), secondCodec.getJavaType());
            }
        }

    } else {
        // The different types that we support are numbers (int, long, double, float),
        // as well as boolean values and Strings. Since Avro doesn't provide
        // timestamp types, we want to convert those to Strings. So we will cast anything other
        // than numbers or booleans to strings by using the toString() method.
        return row.getObject(i).toString();
    }
    return null;
}
 
Example 14
Source File: AbstractUpsertOutputOperatorCodecsTest.java    From attic-apex-malhar with Apache License 2.0 4 votes vote down vote up
@Test
public void testForCollectionRemovalAndIfExists() throws Exception
{
  User aUser = new User();
  String userId = "user" + System.currentTimeMillis();
  aUser.setUserid(userId);
  FullName fullName = new FullName("first12" + System.currentTimeMillis(), "last12" + System.currentTimeMillis());
  aUser.setUsername(fullName);
  Set<String> emails = new HashSet<>();
  emails.add(new String("1"));
  emails.add(new String("2"));
  aUser.setEmails(emails);

  UpsertExecutionContext<User> originalEntry = new UpsertExecutionContext<>();
  originalEntry.setPayload(aUser);

  UpsertExecutionContext<User> subsequentUpdateForEmails = new UpsertExecutionContext<>();
  subsequentUpdateForEmails.setCollectionMutationStyle(
      UpsertExecutionContext.CollectionMutationStyle.REMOVE_FROM_EXISTING_COLLECTION);
  subsequentUpdateForEmails.setNullHandlingMutationStyle(
      UpsertExecutionContext.NullHandlingMutationStyle.IGNORE_NULL_COLUMNS);
  subsequentUpdateForEmails.setUpdateOnlyIfPrimaryKeyExists(true);
  User oldUser = new User();
  oldUser.setUserid(userId + System.currentTimeMillis()); // overriding with a non-existent user id
  Set<String> updatedEmails = new HashSet<>();
  updatedEmails.add(new String("1"));
  oldUser.setEmails(updatedEmails);
  subsequentUpdateForEmails.setPayload(oldUser);
  userUpsertOperator.beginWindow(4);
  userUpsertOperator.input.process(originalEntry);
  userUpsertOperator.input.process(subsequentUpdateForEmails);
  userUpsertOperator.endWindow();

  ResultSet results = userUpsertOperator.session.execute(
      "SELECT * FROM unittests.users WHERE userid = '" + userId + "'");
  List<Row> rows = results.all();
  Row userRow = rows.get(0);
  Set<String> existingEmailsEntry = userRow.getSet("emails", String.class);
  assertEquals(2, existingEmailsEntry.size());
  assertEquals("" + 1, "" + existingEmailsEntry.iterator().next());
}
 
Example 15
Source File: SchemaUpgrade.java    From glowroot with Apache License 2.0 4 votes vote down vote up
private void rewriteRoleTablePart2() throws Exception {
    if (!tableExists("role_temp")) {
        // previously failed mid-upgrade prior to updating schema version
        return;
    }
    dropTableIfExists("role");
    session.createTableWithLCS("create table if not exists role (name varchar, permissions"
            + " set<varchar>, primary key (name))");
    PreparedStatement insertPS =
            session.prepare("insert into role (name, permissions) values (?, ?)");
    Map<String, V09AgentRollup> v09AgentRollups = getV09AgentRollupsFromAgentRollupTable();
    ResultSet results = session.read("select name, permissions from role_temp");
    for (Row row : results) {
        Set<String> v09Permissions = row.getSet(1, String.class);
        Set<String> permissions = Sets.newLinkedHashSet();
        for (String v09Permission : v09Permissions) {
            if (!v09Permission.startsWith("agent:")) {
                // non-agent permission, no need for conversion
                permissions.add(v09Permission);
                continue;
            }
            if (v09Permission.equals("agent:") || v09Permission.startsWith("agent::")
                    || v09Permission.equals("agent:*")
                    || v09Permission.startsWith("agent:*:")) {
                // special cases, no need for conversion
                permissions.add(v09Permission);
                continue;
            }
            PermissionParser parser = new PermissionParser(v09Permission);
            parser.parse();
            List<String> v09AgentRollupIds = parser.getAgentRollupIds();
            String perm = parser.getPermission();
            if (v09AgentRollupIds.isEmpty()) {
                // this shouldn't happen since v09Permission doesn't start with "agent::"
                // (see condition above)
                logger.warn("found agent permission without any agents: {}", v09Permission);
                continue;
            }
            List<String> agentRollupIds = new ArrayList<>();
            for (String v09AgentRollupId : v09AgentRollupIds) {
                V09AgentRollup v09AgentRollup = v09AgentRollups.get(v09AgentRollupId);
                if (v09AgentRollup == null) {
                    // v09AgentRollupId was manually deleted (via the UI) from the
                    // agent_rollup table in which case its parent is no longer known
                    // and best to ignore
                    continue;
                }
                agentRollupIds.add(v09AgentRollup.agentRollupId());
            }
            if (agentRollupIds.isEmpty()) {
                // all v09AgentRollupIds were manually deleted (see comment above)
                continue;
            }
            if (perm.isEmpty()) {
                permissions.add(
                        "agent:" + PermissionParser.quoteIfNeededAndJoin(v09AgentRollupIds));
            } else {
                permissions.add("agent:" + PermissionParser.quoteIfNeededAndJoin(agentRollupIds)
                        + ":" + perm.substring("agent:".length()));
            }
        }
        if (permissions.isEmpty()) {
            // all v09AgentRollupIds for all permissions were manually deleted (see comments
            // above)
            continue;
        }
        BoundStatement boundStatement = insertPS.bind();
        boundStatement.setString(0, row.getString(0));
        boundStatement.setSet(1, permissions);
        session.write(boundStatement);
    }
    dropTableIfExists("role_temp");
}
 
Example 16
Source File: SchemaUpgrade.java    From glowroot with Apache License 2.0 4 votes vote down vote up
private void updateRolePermissionName2() throws Exception {
    PreparedStatement insertPS =
            session.prepare("insert into role (name, permissions) values (?, ?)");
    ResultSet results = session.read("select name, permissions from role");
    for (Row row : results) {
        String name = row.getString(0);
        Set<String> permissions = row.getSet(1, String.class);
        boolean updated = false;
        Set<String> upgradedPermissions = new HashSet<>();
        for (String permission : permissions) {
            PermissionParser parser = new PermissionParser(permission);
            parser.parse();
            if (parser.getPermission().equals("agent:transaction:profile")) {
                upgradedPermissions.add("agent:"
                        + PermissionParser.quoteIfNeededAndJoin(parser.getAgentRollupIds())
                        + ":transaction:threadProfile");
                updated = true;
            } else if (parser.getPermission().equals("agent:config:edit:gauge")) {
                upgradedPermissions.add("agent:"
                        + PermissionParser.quoteIfNeededAndJoin(parser.getAgentRollupIds())
                        + ":config:edit:gauges");
                updated = true;
            } else if (parser.getPermission().equals("agent:config:edit:syntheticMonitor")) {
                upgradedPermissions.add("agent:"
                        + PermissionParser.quoteIfNeededAndJoin(parser.getAgentRollupIds())
                        + ":config:edit:syntheticMonitors");
                updated = true;
            } else if (parser.getPermission().equals("agent:config:edit:alert")) {
                upgradedPermissions.add("agent:"
                        + PermissionParser.quoteIfNeededAndJoin(parser.getAgentRollupIds())
                        + ":config:edit:alerts");
                updated = true;
            } else if (parser.getPermission().equals("agent:config:edit:plugin")) {
                upgradedPermissions.add("agent:"
                        + PermissionParser.quoteIfNeededAndJoin(parser.getAgentRollupIds())
                        + ":config:edit:plugins");
                updated = true;
            } else if (parser.getPermission().equals("agent:config:edit:ui")) {
                upgradedPermissions.add("agent:"
                        + PermissionParser.quoteIfNeededAndJoin(parser.getAgentRollupIds())
                        + ":config:edit:uiDefaults");
                updated = true;
            } else {
                upgradedPermissions.add(permission);
            }
        }
        if (updated) {
            BoundStatement boundStatement = insertPS.bind();
            boundStatement.setString(0, name);
            boundStatement.setSet(1, upgradedPermissions, String.class);
            session.write(boundStatement);
        }
    }
}
 
Example 17
Source File: AbstractCassandraProcessor.java    From nifi with Apache License 2.0 4 votes vote down vote up
protected static Object getCassandraObject(Row row, int i, DataType dataType) {
    if (dataType.equals(DataType.blob())) {
        return row.getBytes(i);

    } else if (dataType.equals(DataType.varint()) || dataType.equals(DataType.decimal())) {
        // Avro can't handle BigDecimal and BigInteger as numbers - it will throw an
        // AvroRuntimeException such as: "Unknown datum type: java.math.BigDecimal: 38"
        return row.getObject(i).toString();

    } else if (dataType.equals(DataType.cboolean())) {
        return row.getBool(i);

    } else if (dataType.equals(DataType.cint())) {
        return row.getInt(i);

    } else if (dataType.equals(DataType.bigint())
            || dataType.equals(DataType.counter())) {
        return row.getLong(i);

    } else if (dataType.equals(DataType.ascii())
            || dataType.equals(DataType.text())
            || dataType.equals(DataType.varchar())) {
        return row.getString(i);

    } else if (dataType.equals(DataType.cfloat())) {
        return row.getFloat(i);

    } else if (dataType.equals(DataType.cdouble())) {
        return row.getDouble(i);

    } else if (dataType.equals(DataType.timestamp())) {
        return row.getTimestamp(i);

    } else if (dataType.equals(DataType.date())) {
        return row.getDate(i);

    } else if (dataType.equals(DataType.time())) {
        return row.getTime(i);

    } else if (dataType.isCollection()) {

        List<DataType> typeArguments = dataType.getTypeArguments();
        if (typeArguments == null || typeArguments.size() == 0) {
            throw new IllegalArgumentException("Column[" + i + "] " + dataType.getName()
                    + " is a collection but no type arguments were specified!");
        }
        // Get the first type argument, to be used for lists and sets (and the first in a map)
        DataType firstArg = typeArguments.get(0);
        TypeCodec firstCodec = codecRegistry.codecFor(firstArg);
        if (dataType.equals(DataType.set(firstArg))) {
            return row.getSet(i, firstCodec.getJavaType());
        } else if (dataType.equals(DataType.list(firstArg))) {
            return row.getList(i, firstCodec.getJavaType());
        } else {
            // Must be an n-arg collection like map
            DataType secondArg = typeArguments.get(1);
            TypeCodec secondCodec = codecRegistry.codecFor(secondArg);
            if (dataType.equals(DataType.map(firstArg, secondArg))) {
                return row.getMap(i, firstCodec.getJavaType(), secondCodec.getJavaType());
            }
        }

    } else {
        // The different types that we support are numbers (int, long, double, float),
        // as well as boolean values and Strings. Since Avro doesn't provide
        // timestamp types, we want to convert those to Strings. So we will cast anything other
        // than numbers or booleans to strings by using the toString() method.
        return row.getObject(i).toString();
    }
    return null;
}