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

The following examples show how to use com.datastax.driver.core.Row#getBytes() . 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: SceneDaoImpl.java    From arcusplatform with Apache License 2.0 6 votes vote down vote up
protected SceneDefinition buildEntity(Row row) {
   SceneDefinition sd = new SceneDefinition();
   sd.setPlaceId(row.getUUID(Column.PLACE_ID.columnName()));
   sd.setSequenceId(row.getInt(Column.ID.columnName()));
   sd.setCreated(row.getTimestamp(Column.CREATED.columnName()));
   sd.setModified(row.getTimestamp(Column.MODIFIED.columnName()));
   sd.setName(row.getString(Column.NAME.columnName()));
   sd.setDescription(row.getString(Column.DESCRIPTION.columnName()));
   sd.setTags(row.getSet(Column.TAGS.columnName(), String.class));
   sd.setLastFireState(row.getString(SceneColumn.LAST_FIRE_STATE.columnName()));
   sd.setLastFireTime(row.getTimestamp(SceneColumn.LAST_FIRE_TIME.columnName()));
   sd.setSatisfiable(row.getBool(SceneColumn.SATISFIABLE.columnName()));
   sd.setNotification(row.getBool(SceneColumn.NOTIFICATION.columnName()));
   sd.setTemplate(row.getString(SceneColumn.TEMPLATE.columnName()));
   sd.setEnabled(row.getBool(SceneColumn.ENABLED.columnName()));
   ByteBuffer action = row.getBytes(SceneColumn.ACTION.columnName());
   if(action != null) {
      byte [] array = new byte[action.remaining()];
      action.get(array);
      sd.setAction(array);
   }
   return sd;
}
 
Example 2
Source File: ActionDaoImpl.java    From arcusplatform with Apache License 2.0 6 votes vote down vote up
protected ActionDefinition buildEntity(Row row) {
   ActionDefinition ad = new ActionDefinition();
   ad.setPlaceId(row.getUUID(Column.PLACE_ID.columnName()));
   ad.setSequenceId(row.getInt(Column.ID.columnName()));
   ad.setCreated(row.getTimestamp(Column.CREATED.columnName()));
   ad.setModified(row.getTimestamp(Column.MODIFIED.columnName()));
   ad.setLastExecuted(row.getTimestamp(ActionColumn.LAST_EXECUTED.columnName()));
   ad.setName(row.getString(Column.NAME.columnName()));
   ad.setDescription(row.getString(Column.DESCRIPTION.columnName()));
   ad.setTags(row.getSet(Column.TAGS.columnName(), String.class));

   ByteBuffer action = row.getBytes(ActionColumn.ACTION.columnName());
   if(action != null) {
      byte [] array = new byte[action.remaining()];
      action.get(array);
      ad.setAction(array);
   }
   return ad;
}
 
Example 3
Source File: CassandraActorSystemEventListenerRepository.java    From elasticactors with Apache License 2.0 6 votes vote down vote up
@Override
public List<ActorSystemEventListener> getAll(ShardKey shardKey, ActorSystemEvent event) {
    ResultSet resultSet = executeWithRetry(cassandraSession, selectStatement.bind(clusterName, shardKey.toString(), event.name()).setFetchSize(Integer.MAX_VALUE), logger);
    List<ActorSystemEventListener> resultList = new LinkedList<>();
    for (Row resultRow : resultSet) {
        for (int i = 0; i < resultRow.getColumnDefinitions().size(); i++) {
            ByteBuffer resultBuffer = resultRow.getBytes(i);
            byte[] resultBytes = new byte[resultBuffer.remaining()];
            resultBuffer.get(resultBytes);
            try {
                resultList.add(ActorSystemEventListenerDeserializer.get().deserialize(resultBytes));
            } catch(IOException e)  {
                logger.error("IOException while deserializing ActorSystemEventListener",e);
            }
        }
    }
    return resultList;
}
 
Example 4
Source File: CassandraSessionDAO.java    From arcusplatform with Apache License 2.0 6 votes vote down vote up
@Override
protected Session doReadSession(Serializable sessionId) {

   UUID id = toUuid(sessionId);

   PreparedStatement ps = prepareReadStatement();
   BoundStatement bs = new BoundStatement(ps);
   bs.bind(id);

   ResultSet results = cassandraSession.execute(bs);

   for(Row row : results) {
      UUID rowId = row.getUUID("id");
      if (id.equals(rowId)) {
         ByteBuffer buffer = row.getBytes("serialized_value");
         if (buffer != null) { //could be null if a tombstone due to TTL removal
            byte[] bytes = new byte[buffer.remaining()];
            buffer.get(bytes);
            return serializer.deserialize(bytes);
         }
      }
   }

   return null;
}
 
Example 5
Source File: CQLService.java    From Doradus with Apache License 2.0 6 votes vote down vote up
@Override
public List<DColumn> getColumns(String storeName, String rowKey, Collection<String> columnNames) {
    String tableName = storeToCQLName(storeName);
    boolean isValueBinary = columnValueIsBinary(storeName);
    ResultSet rs = executeQuery(Query.SELECT_1_ROW_COLUMN_SET,
                                tableName,
                                rowKey,
                                new ArrayList<String>(columnNames));    // must be a List
    List<Row> list = rs.all();
    List<DColumn> result = new ArrayList<>(list.size());
    for(Row r: list) {
        DColumn cqlCol = null;
        if (isValueBinary) {
            cqlCol = new DColumn(r.getString("column1"), r.getBytes("value"));
        } else {
            cqlCol = new DColumn(r.getString("column1"), r.getString("value"));
        }
        
        result.add(cqlCol);
    }
    return result;
}
 
Example 6
Source File: ResultImpl.java    From scalardb with Apache License 2.0 6 votes vote down vote up
private static Value convert(Row row, String name, DataType.Name type)
    throws UnsupportedTypeException {
  switch (type) {
    case BOOLEAN:
      return new BooleanValue(name, row.getBool(name));
    case INT:
      return new IntValue(name, row.getInt(name));
    case BIGINT:
      return new BigIntValue(name, row.getLong(name));
    case FLOAT:
      return new FloatValue(name, row.getFloat(name));
    case DOUBLE:
      return new DoubleValue(name, row.getDouble(name));
    case TEXT: // for backwards compatibility
    case VARCHAR:
      return new TextValue(name, row.getString(name));
    case BLOB:
      ByteBuffer buffer = row.getBytes(name);
      return new BlobValue(name, buffer == null ? null : buffer.array());
    default:
      throw new UnsupportedTypeException(type.toString());
  }
}
 
Example 7
Source File: CqlOperation.java    From stratio-cassandra with Apache License 2.0 6 votes vote down vote up
@Override
public Function<ResultSet, ByteBuffer[][]> javaDriverHandler()
{
    return new Function<ResultSet, ByteBuffer[][]>()
    {

        @Override
        public ByteBuffer[][] apply(ResultSet result)
        {
            if (result == null)
                return new ByteBuffer[0][];
            List<Row> rows = result.all();

            ByteBuffer[][] r = new ByteBuffer[rows.size()][];
            for (int i = 0 ; i < r.length ; i++)
            {
                Row row = rows.get(i);
                r[i] = new ByteBuffer[row.getColumnDefinitions().size()];
                for (int j = 0 ; j < row.getColumnDefinitions().size() ; j++)
                    r[i][j] = row.getBytes(j);
            }
            return r;
        }
    };
}
 
Example 8
Source File: QueueMessageSerializationImpl.java    From usergrid with Apache License 2.0 6 votes vote down vote up
@Override
public DatabaseQueueMessageBody loadMessageData(final UUID messageId ){

    logger.trace("loadMessageData {}", messageId);

    Clause messageIdClause = QueryBuilder.eq( COLUMN_MESSAGE_ID, messageId );

    Statement select = QueryBuilder.select().from( TABLE_MESSAGE_DATA).where(messageIdClause);

    Row row = cassandraClient.getApplicationSession().execute(select).one();
    if ( row == null ) {
        return null;
    }

    return new DatabaseQueueMessageBody(
            row.getBytes( COLUMN_MESSAGE_DATA),
            row.getString( COLUMN_CONTENT_TYPE));
}
 
Example 9
Source File: SyntheticResultDaoImpl.java    From glowroot with Apache License 2.0 6 votes vote down vote up
@Override
public List<SyntheticResultRollup0> readLastFromRollup0(String agentRollupId,
        String syntheticMonitorId, int x) throws Exception {
    BoundStatement boundStatement = readLastFromRollup0.bind();
    int i = 0;
    boundStatement.setString(i++, agentRollupId);
    boundStatement.setString(i++, syntheticMonitorId);
    boundStatement.setInt(i++, x);
    ResultSet results = session.read(boundStatement);
    List<SyntheticResultRollup0> syntheticResults = new ArrayList<>();
    for (Row row : results) {
        i = 0;
        long captureTime = checkNotNull(row.getTimestamp(i++)).getTime();
        double totalDurationNanos = row.getDouble(i++);
        ByteBuffer errorIntervalsBytes = row.getBytes(i++);
        syntheticResults.add(ImmutableSyntheticResultRollup0.builder()
                .captureTime(captureTime)
                .totalDurationNanos(totalDurationNanos)
                .error(errorIntervalsBytes != null)
                .build());
    }
    return syntheticResults;
}
 
Example 10
Source File: DeviceDAOImpl.java    From arcusplatform with Apache License 2.0 5 votes vote down vote up
@Override
public DeviceDriverStateHolder loadDriverState(Device device) {
   Preconditions.checkNotNull(device, "device cannot be null");
   Preconditions.checkNotNull(device.getId(), "device must have an id");

   BoundStatement bound = new BoundStatement(loadState);
   Row r;
   try(Context ctxt = loadDriverStateTimer.time()) {
      r = session.execute(bound.bind(device.getId())).one();
   }

   if(r == null) {
      return null;
   }

   Map<String,String> encoded = r.getMap(NonEntityColumns.ATTRIBUTES, String.class, String.class);
   AttributeMap attributes = AttributeMap.newMap();
   for(Map.Entry<String, String> entry: encoded.entrySet()) {
      AttributeKey<?> key = key(entry.getKey());
      if(key == null) {
         continue;
      }
      Object value = deserialize(key, entry.getValue());
      // this shouldn't be necessary...
      attributes.add(key.coerceToValue(value));
   }


   Map<String,Object> variables = new HashMap<>();
   ByteBuffer buf = r.getBytes(NonEntityColumns.VARIABLES);
   if (buf != null) {
      variables = SerializationUtils.deserialize(Bytes.getArray(buf));
   }

   return new DeviceDriverStateHolder(attributes, variables);
}
 
Example 11
Source File: CQLService.java    From Doradus with Apache License 2.0 5 votes vote down vote up
@Override
public List<DColumn> getColumns(String storeName, String rowKey, String startColumn, String endColumn, int count) {
    String tableName = storeToCQLName(storeName);
    ResultSet rs = null;
    if (startColumn == null) {
        if (endColumn == null) {
            rs = executeQuery(Query.SELECT_1_ROW_ALL_COLUMNS, tableName, rowKey, new Integer(count));
        } else {
            rs = executeQuery(Query.SELECT_1_ROW_LOWER_COLUMNS, tableName, rowKey, endColumn, new Integer(count));
        }
    } else if (endColumn == null) {
        rs = executeQuery(Query.SELECT_1_ROW_UPPER_COLUMNS, tableName, rowKey, startColumn, new Integer(count));
    } else {
        rs = executeQuery(Query.SELECT_1_ROW_COLUMN_RANGE, tableName, rowKey, startColumn, endColumn, new Integer(count));
    }
    List<Row> list = rs.all();
    List<DColumn> result = new ArrayList<>(list.size());
    boolean isValueBinary = columnValueIsBinary(storeName);
    for(Row r: list) {
        DColumn cqlCol = null;
        if (isValueBinary) {
            cqlCol = new DColumn(r.getString("column1"), r.getBytes("value"));
        } else {
            cqlCol = new DColumn(r.getString("column1"), r.getString("value"));
        }
        
        result.add(cqlCol);
    }
    return result;
}
 
Example 12
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;
}
 
Example 13
Source File: TraceDaoImpl.java    From glowroot with Apache License 2.0 4 votes vote down vote up
private static List<TracePoint> processPoints(ResultSet results, TracePointFilter filter,
        boolean partial, boolean errorPoints) throws IOException {
    List<TracePoint> tracePoints = new ArrayList<>();
    for (Row row : results) {
        int i = 0;
        String agentId = checkNotNull(row.getString(i++));
        String traceId = checkNotNull(row.getString(i++));
        long captureTime = checkNotNull(row.getTimestamp(i++)).getTime();
        if (partial) {
            // real_capture_time is only present for data written starting with 0.13.1
            Date realCaptureTime = row.getTimestamp(i++);
            if (realCaptureTime != null) {
                captureTime = realCaptureTime.getTime();
            }
        }
        long durationNanos = row.getLong(i++);
        boolean error = errorPoints || row.getBool(i++);
        // error points are defined by having an error message, so safe to checkNotNull
        String errorMessage = errorPoints ? checkNotNull(row.getString(i++)) : "";
        // headline is null for data inserted prior to 0.9.7
        String headline = Strings.nullToEmpty(row.getString(i++));
        String user = Strings.nullToEmpty(row.getString(i++));
        ByteBuffer attributeBytes = row.getBytes(i++);
        List<Trace.Attribute> attrs =
                Messages.parseDelimitedFrom(attributeBytes, Trace.Attribute.parser());
        Map<String, List<String>> attributes = attrs.stream().collect(
                Collectors.toMap(Trace.Attribute::getName, Trace.Attribute::getValueList));
        if (filter.matchesDuration(durationNanos)
                && filter.matchesHeadline(headline)
                && filter.matchesError(errorMessage)
                && filter.matchesUser(user)
                && filter.matchesAttributes(attributes)) {
            tracePoints.add(ImmutableTracePoint.builder()
                    .agentId(agentId)
                    .traceId(traceId)
                    .captureTime(captureTime)
                    .durationNanos(durationNanos)
                    .partial(partial)
                    .error(error)
                    .checkLiveTraces(false)
                    .build());
        }
    }
    return tracePoints;
}
 
Example 14
Source File: TraceDaoImpl.java    From glowroot with Apache License 2.0 4 votes vote down vote up
private List<Trace.Entry> readEntriesUsingPS(String agentId, String traceId,
        PreparedStatement readPS) throws Exception {
    BoundStatement boundStatement = readPS.bind();
    boundStatement.setString(0, agentId);
    boundStatement.setString(1, traceId);
    ResultSet results = session.read(boundStatement);
    List<Trace.Entry> entries = new ArrayList<>();
    while (!results.isExhausted()) {
        Row row = results.one();
        int i = 0;
        Trace.Entry.Builder entry = Trace.Entry.newBuilder()
                .setDepth(row.getInt(i++))
                .setStartOffsetNanos(row.getLong(i++))
                .setDurationNanos(row.getLong(i++))
                .setActive(row.getBool(i++));
        if (row.isNull(i + 1)) { // shared_query_text_index
            // message is null for trace entries added using addErrorEntry()
            entry.setMessage(Strings.nullToEmpty(row.getString(i++)));
            i++; // shared_query_text_index
            i++; // query_message_prefix
            i++; // query_message_suffix
        } else {
            i++; // message
            Trace.QueryEntryMessage queryEntryMessage = Trace.QueryEntryMessage.newBuilder()
                    .setSharedQueryTextIndex(row.getInt(i++))
                    .setPrefix(Strings.nullToEmpty(row.getString(i++)))
                    .setSuffix(Strings.nullToEmpty(row.getString(i++)))
                    .build();
            entry.setQueryEntryMessage(queryEntryMessage);
        }
        ByteBuffer detailBytes = row.getBytes(i++);
        if (detailBytes != null) {
            entry.addAllDetailEntry(
                    Messages.parseDelimitedFrom(detailBytes, Trace.DetailEntry.parser()));
        }
        ByteBuffer locationBytes = row.getBytes(i++);
        if (locationBytes != null) {
            entry.addAllLocationStackTraceElement(Messages.parseDelimitedFrom(locationBytes,
                    Proto.StackTraceElement.parser()));
        }
        ByteBuffer errorBytes = row.getBytes(i++);
        if (errorBytes != null) {
            entry.setError(Trace.Error.parseFrom(errorBytes));
        }
        entries.add(entry.build());
    }
    return entries;
}
 
Example 15
Source File: CassandraBlobStoreCache.java    From james-project with Apache License 2.0 4 votes vote down vote up
private byte[] toByteArray(Row row) {
    ByteBuffer byteBuffer = row.getBytes(DATA);
    byte[] data = new byte[byteBuffer.remaining()];
    byteBuffer.get(data);
    return data;
}
 
Example 16
Source File: CassandraDefaultBucketDAO.java    From james-project with Apache License 2.0 4 votes vote down vote up
private ByteBuffer rowToData(Row row) {
    return row.getBytes(DefaultBucketBlobParts.DATA);
}
 
Example 17
Source File: CassandraBucketDAO.java    From james-project with Apache License 2.0 4 votes vote down vote up
private ByteBuffer rowToData(Row row) {
    return row.getBytes(BucketBlobParts.DATA);
}
 
Example 18
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 19
Source File: GuicedCassandraSessionDAO.java    From arcusplatform with Apache License 2.0 4 votes vote down vote up
private Session hydrateSession(UUID id, Row row) {
	UUID rowId = row.getUUID(Columns.ID);
	if (id.equals(rowId)) {
		Date start = row.getTimestamp(Columns.START);
		// If this is null, then the row is a tombstone.
		if (start != null) {
			ByteBuffer buffer = row.getBytes(Columns.SERIALIZED);
			// If the buffer has anything, then it is an old style serialized session.
			if (buffer != null && buffer.remaining() > 0) {
				byte[] bytes = new byte[buffer.remaining()];
            buffer.get(bytes);
            return serializer.deserialize(bytes);
			}
			else {
				// New style session. Read the fields and create a session.
             Date stop = row.getTimestamp(Columns.STOP);
             Date lastAccess = row.getTimestamp(Columns.LAST_ACCESS);
				long timeout = row.getLong(Columns.TIMEOUT);
				boolean expired = row.getBool(Columns.EXPIRED);
				String host = row.getString(Columns.HOST);
				
				// Read the attributes
				Map<String, String> serialized_attrs = row.getMap(Columns.ATTRIBUTES, String.class, String.class);
				Map<Object, Object> attributes = new HashMap<>();
				for (Map.Entry<String, String> entry : serialized_attrs.entrySet()) {
					String json = entry.getValue();
					if (json != null && !json.isEmpty()) {
						attributes.put(entry.getKey(), deserializeAttribute(entry.getKey(), json));
					}
				}
				
				// Create and populate the session.
				SimpleSession session = new SimpleSession();
				session.setId(rowId);
				session.setStartTimestamp(start);
				session.setStopTimestamp(stop);
				session.setLastAccessTime(lastAccess);
				session.setTimeout(timeout);
				session.setExpired(expired);
				session.setHost(host);
				session.setAttributes(attributes);
				
				return session;
			}
		}
	}
	return null;
}
 
Example 20
Source File: DeviceDAOImpl.java    From arcusplatform with Apache License 2.0 4 votes vote down vote up
@Override
protected void populateEntity(Row row, Device entity) {
   entity.setAccount(row.getUUID(DeviceEntityColumns.ACCOUNT_ID));
   entity.setAddress(row.getString(DeviceEntityColumns.DRIVER_ADDRESS));
   entity.setProtocolAddress(row.getString(DeviceEntityColumns.PROTOCOL_ADDRESS));

   String hubId = row.getString(DeviceEntityColumns.HUB_ID2);
   if(hubId == null) {
      ColumnRepairMetrics.incHubIdCounter();
      hubId = row.getString(DeviceEntityColumns.HUB_ID);
   }

   entity.setHubId(hubId);
   entity.setProtocol(row.getString(DeviceEntityColumns.PROTOCOL_NAME));
   entity.setProtocolid(row.getString(DeviceEntityColumns.PROTOCOL_ID));

   String version = row.getString(DeviceEntityColumns.DRIVER_VERSION2);
   if(version == null) {
      ColumnRepairMetrics.incDriverVersionCounter();
      version = row.getString(DeviceEntityColumns.DRIVER_VERSION);
   }

   DriverId driverId = new DriverId(row.getString(DeviceEntityColumns.DRIVER_NAME), version == null ? Version.UNVERSIONED : Version.fromRepresentation(version));
   entity.setDriverId(driverId);
   entity.setState(row.getString(DeviceEntityColumns.STATE));
   entity.setPlace(row.getUUID(DeviceEntityColumns.PLACE_ID));
   entity.setCaps(row.getSet(DeviceEntityColumns.CAPS, String.class));
   entity.setDevtypehint(row.getString(DeviceEntityColumns.DEVTYPEHINT));
   entity.setName(row.getString(DeviceEntityColumns.NAME));

   entity.setVendor(row.getString(DeviceEntityColumns.VENDOR));
   entity.setModel(row.getString(DeviceEntityColumns.MODEL));
   entity.setProductId(row.getString(DeviceEntityColumns.PRODUCTID));
   entity.setSubprotocol(row.getString(DeviceEntityColumns.SUBPROTOCOL));
   ByteBuffer buf = row.getBytes(DeviceEntityColumns.PROTOCOL_ATTRS);
   if (buf != null) {
      entity.setProtocolAttributes(bytesToProtocolAttributes(Bytes.getArray(buf)));
   }
   entity.setDegradedCode(row.getString(DeviceEntityColumns.DEGRADED));
   entity.setHubLocal(row.getBool(DeviceEntityColumns.HUBLOCAL));
}