Java Code Examples for org.apache.cassandra.utils.UUIDGen

The following examples show how to use org.apache.cassandra.utils.UUIDGen. These examples are extracted from open source projects. 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 Project: coming   Source File: 986499_AddColumnFamily_0_s.java    License: MIT License 6 votes vote down vote up
public AddColumnFamily(CFMetaData cfm) throws ConfigurationException, IOException
{
    super(UUIDGen.makeType1UUIDFromHost(FBUtilities.getLocalAddress()), DatabaseDescriptor.getDefsVersion());
    this.cfm = cfm;
    KSMetaData ksm = DatabaseDescriptor.getTableDefinition(cfm.tableName);
    
    if (ksm == null)
        throw new ConfigurationException("Keyspace does not already exist.");
    else if (ksm.cfMetaData().containsKey(cfm.cfName))
        throw new ConfigurationException("CF is already defined in that keyspace.");
    else if (!Migration.isLegalName(cfm.cfName))
        throw new ConfigurationException("Invalid column family name: " + cfm.cfName);
    
    KSMetaData newKsm = makeNewKeyspaceDefinition(ksm);
    
    rm = Migration.makeDefinitionMutation(newKsm, null, newVersion);
}
 
Example 2
Source Project: coming   Source File: 986499_AddColumnFamily_0_t.java    License: MIT License 6 votes vote down vote up
public AddColumnFamily(CFMetaData cfm) throws ConfigurationException, IOException
{
    super(UUIDGen.makeType1UUIDFromHost(FBUtilities.getLocalAddress()), DatabaseDescriptor.getDefsVersion());
    this.cfm = cfm;
    KSMetaData ksm = DatabaseDescriptor.getTableDefinition(cfm.tableName);
    
    if (ksm == null)
        throw new ConfigurationException("Keyspace does not already exist.");
    else if (ksm.cfMetaData().containsKey(cfm.cfName))
        throw new ConfigurationException("CF is already defined in that keyspace.");
    else if (!Migration.isLegalName(cfm.cfName))
        throw new ConfigurationException("Invalid column family name: " + cfm.cfName);
    
    KSMetaData newKsm = makeNewKeyspaceDefinition(ksm);
    
    rm = Migration.makeDefinitionMutation(newKsm, null, newVersion);
}
 
Example 3
Source Project: coming   Source File: 986499_AddColumnFamily_0_s.java    License: MIT License 6 votes vote down vote up
public AddColumnFamily(CFMetaData cfm) throws ConfigurationException, IOException
{
    super(UUIDGen.makeType1UUIDFromHost(FBUtilities.getLocalAddress()), DatabaseDescriptor.getDefsVersion());
    this.cfm = cfm;
    KSMetaData ksm = DatabaseDescriptor.getTableDefinition(cfm.tableName);
    
    if (ksm == null)
        throw new ConfigurationException("Keyspace does not already exist.");
    else if (ksm.cfMetaData().containsKey(cfm.cfName))
        throw new ConfigurationException("CF is already defined in that keyspace.");
    else if (!Migration.isLegalName(cfm.cfName))
        throw new ConfigurationException("Invalid column family name: " + cfm.cfName);
    
    KSMetaData newKsm = makeNewKeyspaceDefinition(ksm);
    
    rm = Migration.makeDefinitionMutation(newKsm, null, newVersion);
}
 
Example 4
Source Project: coming   Source File: 986499_AddColumnFamily_0_t.java    License: MIT License 6 votes vote down vote up
public AddColumnFamily(CFMetaData cfm) throws ConfigurationException, IOException
{
    super(UUIDGen.makeType1UUIDFromHost(FBUtilities.getLocalAddress()), DatabaseDescriptor.getDefsVersion());
    this.cfm = cfm;
    KSMetaData ksm = DatabaseDescriptor.getTableDefinition(cfm.tableName);
    
    if (ksm == null)
        throw new ConfigurationException("Keyspace does not already exist.");
    else if (ksm.cfMetaData().containsKey(cfm.cfName))
        throw new ConfigurationException("CF is already defined in that keyspace.");
    else if (!Migration.isLegalName(cfm.cfName))
        throw new ConfigurationException("Invalid column family name: " + cfm.cfName);
    
    KSMetaData newKsm = makeNewKeyspaceDefinition(ksm);
    
    rm = Migration.makeDefinitionMutation(newKsm, null, newVersion);
}
 
Example 5
Source Project: coming   Source File: 986499_AddColumnFamily_0_s.java    License: MIT License 6 votes vote down vote up
public AddColumnFamily(CFMetaData cfm) throws ConfigurationException, IOException
{
    super(UUIDGen.makeType1UUIDFromHost(FBUtilities.getLocalAddress()), DatabaseDescriptor.getDefsVersion());
    this.cfm = cfm;
    KSMetaData ksm = DatabaseDescriptor.getTableDefinition(cfm.tableName);
    
    if (ksm == null)
        throw new ConfigurationException("Keyspace does not already exist.");
    else if (ksm.cfMetaData().containsKey(cfm.cfName))
        throw new ConfigurationException("CF is already defined in that keyspace.");
    else if (!Migration.isLegalName(cfm.cfName))
        throw new ConfigurationException("Invalid column family name: " + cfm.cfName);
    
    KSMetaData newKsm = makeNewKeyspaceDefinition(ksm);
    
    rm = Migration.makeDefinitionMutation(newKsm, null, newVersion);
}
 
Example 6
Source Project: coming   Source File: 986499_AddColumnFamily_0_t.java    License: MIT License 6 votes vote down vote up
public AddColumnFamily(CFMetaData cfm) throws ConfigurationException, IOException
{
    super(UUIDGen.makeType1UUIDFromHost(FBUtilities.getLocalAddress()), DatabaseDescriptor.getDefsVersion());
    this.cfm = cfm;
    KSMetaData ksm = DatabaseDescriptor.getTableDefinition(cfm.tableName);
    
    if (ksm == null)
        throw new ConfigurationException("Keyspace does not already exist.");
    else if (ksm.cfMetaData().containsKey(cfm.cfName))
        throw new ConfigurationException("CF is already defined in that keyspace.");
    else if (!Migration.isLegalName(cfm.cfName))
        throw new ConfigurationException("Invalid column family name: " + cfm.cfName);
    
    KSMetaData newKsm = makeNewKeyspaceDefinition(ksm);
    
    rm = Migration.makeDefinitionMutation(newKsm, null, newVersion);
}
 
Example 7
Source Project: stratio-cassandra   Source File: TraceState.java    License: Apache License 2.0 6 votes vote down vote up
public static void trace(final ByteBuffer sessionIdBytes, final String message, final int elapsed)
{
    final String threadName = Thread.currentThread().getName();

    StageManager.getStage(Stage.TRACING).execute(new WrappedRunnable()
    {
        public void runMayThrow()
        {
            Mutation mutation = new Mutation(Tracing.TRACE_KS, sessionIdBytes);
            ColumnFamily cells = mutation.addOrGet(CFMetaData.TraceEventsCf);

            CFRowAdder adder = new CFRowAdder(cells, cells.metadata().comparator.make(UUIDGen.getTimeUUID()), FBUtilities.timestampMicros());
            adder.add("activity", message);
            adder.add("source", FBUtilities.getBroadcastAddress());
            if (elapsed >= 0)
                adder.add("source_elapsed", elapsed);
            adder.add("thread", threadName);

            Tracing.mutateWithCatch(mutation);
        }
    });
}
 
Example 8
Source Project: stratio-cassandra   Source File: ScrubTest.java    License: Apache License 2.0 6 votes vote down vote up
/**
 * Tests CASSANDRA-6892 (key aliases being used improperly for validation)
 */
@Test
public void testColumnNameEqualToDefaultKeyAlias() throws ExecutionException, InterruptedException
{
    Keyspace keyspace = Keyspace.open("Keyspace1");
    ColumnFamilyStore cfs = keyspace.getColumnFamilyStore("UUIDKeys");

    ColumnFamily cf = ArrayBackedSortedColumns.factory.create("Keyspace1", "UUIDKeys");
    cf.addColumn(column(CFMetaData.DEFAULT_KEY_ALIAS, "not a uuid", 1L));
    Mutation mutation = new Mutation("Keyspace1", ByteBufferUtil.bytes(UUIDGen.getTimeUUID()), cf);
    mutation.applyUnsafe();
    cfs.forceBlockingFlush();
    CompactionManager.instance.performScrub(cfs, false);

    assertEquals(1, cfs.getSSTables().size());
}
 
Example 9
Source Project: stratio-cassandra   Source File: ClientUtilsTest.java    License: Apache License 2.0 6 votes vote down vote up
/** Exercises the classes in the clientutil jar to expose missing dependencies. */
@Test
public void test()
{
    AsciiSerializer.instance.deserialize(AsciiSerializer.instance.serialize("string"));
    BooleanSerializer.instance.deserialize(BooleanSerializer.instance.serialize(true));
    BytesSerializer.instance.deserialize(BytesSerializer.instance.serialize(ByteBuffer.wrap("string".getBytes())));

    Date date = new Date(System.currentTimeMillis());
    ByteBuffer dateBB = TimestampSerializer.instance.serialize(date);
    TimestampSerializer.instance.deserialize(dateBB);

    DecimalSerializer.instance.deserialize(DecimalSerializer.instance.serialize(new BigDecimal(1)));
    DoubleSerializer.instance.deserialize(DoubleSerializer.instance.serialize(new Double(1.0d)));
    FloatSerializer.instance.deserialize(FloatSerializer.instance.serialize(new Float(1.0f)));
    Int32Serializer.instance.deserialize(Int32Serializer.instance.serialize(1));
    IntegerSerializer.instance.deserialize(IntegerSerializer.instance.serialize(new BigInteger("1")));
    LongSerializer.instance.deserialize(LongSerializer.instance.serialize(1L));
    UTF8Serializer.instance.deserialize(UTF8Serializer.instance.serialize("string"));

    // UUIDGen
    UUID uuid = UUIDGen.getTimeUUID();
    UUIDSerializer.instance.deserialize(UUIDSerializer.instance.serialize(uuid));
}
 
Example 10
Source Project: usergrid   Source File: AuditLogSerializationTest.java    License: Apache License 2.0 6 votes vote down vote up
@Test
public void testRecordAuditLog() throws Exception {

    CassandraClient cassandraClient = getInjector().getInstance( CassandraClientImpl.class );

    AuditLogSerialization logSerialization = getInjector().getInstance( AuditLogSerialization.class );

    // record some audit logs for a message
    UUID messageId = UUIDGen.getTimeUUID();
    String queueName = "alst_queue_" + RandomStringUtils.randomAlphanumeric( 15 );
    String source = RandomStringUtils.randomAlphanumeric( 15 );
    String dest = RandomStringUtils.randomAlphanumeric( 15 );

    logSerialization.recordAuditLog( AuditLog.Action.GET, AuditLog.Status.SUCCESS,
        queueName, dest, messageId, UUIDGen.getTimeUUID() );

    // get audit logs for that message
    Result<AuditLog> result = logSerialization.getAuditLogs( messageId );
    Assert.assertEquals( 1, result.getEntities().size() );
}
 
Example 11
Source Project: stratio-cassandra   Source File: Lists.java    License: Apache License 2.0 5 votes vote down vote up
static void doAppend(Term t, ColumnFamily cf, Composite prefix, ColumnDefinition column, UpdateParameters params) throws InvalidRequestException
{
    Term.Terminal value = t.bind(params.options);
    Lists.Value listValue = (Lists.Value)value;
    if (column.type.isMultiCell())
    {
        // If we append null, do nothing. Note that for Setter, we've
        // already removed the previous value so we're good here too
        if (value == null)
            return;

        List<ByteBuffer> toAdd = listValue.elements;
        for (int i = 0; i < toAdd.size(); i++)
        {
            ByteBuffer uuid = ByteBuffer.wrap(UUIDGen.getTimeUUIDBytes());
            cf.addColumn(params.makeColumn(cf.getComparator().create(prefix, column, uuid), toAdd.get(i)));
        }
    }
    else
    {
        // for frozen lists, we're overwriting the whole cell value
        CellName name = cf.getComparator().create(prefix, column);
        if (value == null)
            cf.addAtom(params.makeTombstone(name));
        else
            cf.addColumn(params.makeColumn(name, listValue.getWithProtocolVersion(Server.CURRENT_VERSION)));
    }
}
 
Example 12
Source Project: stratio-cassandra   Source File: TimeuuidFcts.java    License: Apache License 2.0 5 votes vote down vote up
public ByteBuffer execute(List<ByteBuffer> parameters)
{
    ByteBuffer bb = parameters.get(0);
    if (bb == null)
        return null;

    return ByteBuffer.wrap(UUIDGen.decompose(UUIDGen.minTimeUUID(TimestampType.instance.compose(bb).getTime())));
}
 
Example 13
Source Project: stratio-cassandra   Source File: TimeuuidFcts.java    License: Apache License 2.0 5 votes vote down vote up
public ByteBuffer execute(List<ByteBuffer> parameters)
{
    ByteBuffer bb = parameters.get(0);
    if (bb == null)
        return null;

    return ByteBuffer.wrap(UUIDGen.decompose(UUIDGen.maxTimeUUID(TimestampType.instance.compose(bb).getTime())));
}
 
Example 14
Source Project: stratio-cassandra   Source File: TimeuuidFcts.java    License: Apache License 2.0 5 votes vote down vote up
public ByteBuffer execute(List<ByteBuffer> parameters)
{
    ByteBuffer bb = parameters.get(0);
    if (bb == null)
        return null;

    return TimestampType.instance.decompose(new Date(UUIDGen.unixTimestamp(UUIDGen.getUUID(bb))));
}
 
Example 15
Source Project: stratio-cassandra   Source File: TimeuuidFcts.java    License: Apache License 2.0 5 votes vote down vote up
public ByteBuffer execute(List<ByteBuffer> parameters)
{
    ByteBuffer bb = parameters.get(0);
    if (bb == null)
        return null;

    return ByteBufferUtil.bytes(UUIDGen.unixTimestamp(UUIDGen.getUUID(bb)));
}
 
Example 16
/** set the value to the position of the tuple */
protected void setTupleValue(Tuple pair, int position, Object value) throws ExecException
{
   if (value instanceof BigInteger)
       pair.set(position, ((BigInteger) value).intValue());
   else if (value instanceof ByteBuffer)
       pair.set(position, new DataByteArray(ByteBufferUtil.getArray((ByteBuffer) value)));
   else if (value instanceof UUID)
       pair.set(position, new DataByteArray(UUIDGen.decompose((java.util.UUID) value)));
   else if (value instanceof Date)
       pair.set(position, TimestampType.instance.decompose((Date) value).getLong());
   else
       pair.set(position, value);
}
 
Example 17
/** convert object to ByteBuffer */
protected ByteBuffer objToBB(Object o)
{
    if (o == null)
        return nullToBB();
    if (o instanceof java.lang.String)
        return ByteBuffer.wrap(new DataByteArray((String)o).get());
    if (o instanceof Integer)
        return Int32Type.instance.decompose((Integer)o);
    if (o instanceof Long)
        return LongType.instance.decompose((Long)o);
    if (o instanceof Float)
        return FloatType.instance.decompose((Float)o);
    if (o instanceof Double)
        return DoubleType.instance.decompose((Double)o);
    if (o instanceof UUID)
        return ByteBuffer.wrap(UUIDGen.decompose((UUID) o));
    if(o instanceof Tuple) {
        List<Object> objects = ((Tuple)o).getAll();
        //collections
        if (objects.size() > 0 && objects.get(0) instanceof String)
        {
            String collectionType = (String) objects.get(0);
            if ("set".equalsIgnoreCase(collectionType) ||
                    "list".equalsIgnoreCase(collectionType))
                return objToListOrSetBB(objects.subList(1, objects.size()));
            else if ("map".equalsIgnoreCase(collectionType))
                return objToMapBB(objects.subList(1, objects.size()));
               
        }
        return objToCompositeBB(objects);
    }

    return ByteBuffer.wrap(((DataByteArray) o).get());
}
 
Example 18
Source Project: stratio-cassandra   Source File: HintedHandoffMetrics.java    License: Apache License 2.0 5 votes vote down vote up
public void log()
{
    for (Entry<InetAddress, DifferencingCounter> entry : notStored.asMap().entrySet())
    {
        long difference = entry.getValue().difference();
        if (difference == 0)
            continue;
        logger.warn("{} has {} dropped hints, because node is down past configured hint window.", entry.getKey(), difference);
        SystemKeyspace.updateHintsDropped(entry.getKey(), UUIDGen.getTimeUUID(), (int) difference);
    }
}
 
Example 19
Source Project: stratio-cassandra   Source File: PaxosState.java    License: Apache License 2.0 5 votes vote down vote up
public static void commit(Commit proposal)
{
    long start = System.nanoTime();
    try
    {
        // There is no guarantee we will see commits in the right order, because messages
        // can get delayed, so a proposal can be older than our current most recent ballot/commit.
        // Committing it is however always safe due to column timestamps, so always do it. However,
        // if our current in-progress ballot is strictly greater than the proposal one, we shouldn't
        // erase the in-progress update.
        // The table may have been truncated since the proposal was initiated. In that case, we
        // don't want to perform the mutation and potentially resurrect truncated data
        if (UUIDGen.unixTimestamp(proposal.ballot) >= SystemKeyspace.getTruncatedAt(proposal.update.metadata().cfId))
        {
            Tracing.trace("Committing proposal {}", proposal);
            Mutation mutation = proposal.makeMutation();
            Keyspace.open(mutation.getKeyspaceName()).apply(mutation, true);
        }
        else
        {
            Tracing.trace("Not committing proposal {} as ballot timestamp predates last truncation time", proposal);
        }
        // We don't need to lock, we're just blindly updating
        SystemKeyspace.savePaxosCommit(proposal);
    }
    finally
    {
        Keyspace.open(proposal.update.metadata().ksName).getColumnFamilyStore(proposal.update.metadata().cfId).metric.casCommit.addNano(System.nanoTime() - start);
    }
}
 
Example 20
Source Project: stratio-cassandra   Source File: Commit.java    License: Apache License 2.0 5 votes vote down vote up
private static ColumnFamily updatesWithPaxosTime(ColumnFamily updates, UUID ballot)
{
    ColumnFamily cf = updates.cloneMeShallow();
    long t = UUIDGen.microsTimestamp(ballot);
    // For the tombstones, we use t-1 so that when insert a collection literall, the range tombstone that deletes the previous values of
    // the collection and we want that to have a lower timestamp and our new values. Since tombstones wins over normal insert, using t-1
    // should not be a problem in general (see #6069).
    cf.deletionInfo().updateAllTimestamp(t-1);
    for (Cell cell : updates)
        cf.addAtom(cell.withUpdatedTimestamp(t));
    return cf;
}
 
Example 21
Source Project: stratio-cassandra   Source File: PrepareMessage.java    License: Apache License 2.0 5 votes vote down vote up
public Message.Response execute(QueryState state)
{
    try
    {
        UUID tracingId = null;
        if (isTracingRequested())
        {
            tracingId = UUIDGen.getTimeUUID();
            state.prepareTracingSession(tracingId);
        }

        if (state.traceNextQuery())
        {
            state.createTracingSession();
            Tracing.instance.begin("Preparing CQL3 query", ImmutableMap.of("query", query));
        }

        Message.Response response = state.getClientState().getCQLQueryHandler().prepare(query, state);

        if (tracingId != null)
            response.setTracingId(tracingId);

        return response;
    }
    catch (Exception e)
    {
        JVMStabilityInspector.inspectThrowable(e);
        return ErrorMessage.fromException(e);
    }
    finally
    {
        Tracing.instance.stopSession();
    }
}
 
Example 22
Source Project: stratio-cassandra   Source File: TimeUUIDType.java    License: Apache License 2.0 5 votes vote down vote up
@Override
public ByteBuffer fromStringCQL2(String source) throws MarshalException
{
    // Return an empty ByteBuffer for an empty string.
    if (source.isEmpty())
        return ByteBufferUtil.EMPTY_BYTE_BUFFER;

    ByteBuffer idBytes = null;

    // ffffffff-ffff-ffff-ffff-ffffffffff
    if (regexPattern.matcher(source).matches())
    {
        UUID uuid = null;
        try
        {
            uuid = UUID.fromString(source);
            idBytes = decompose(uuid);
        }
        catch (IllegalArgumentException e)
        {
            throw new MarshalException(String.format("unable to make UUID from '%s'", source), e);
        }

        if (uuid.version() != 1)
            throw new MarshalException("TimeUUID supports only version 1 UUIDs");
    }
    else
    {
        idBytes = ByteBuffer.wrap(UUIDGen.getTimeUUIDBytes(TimestampSerializer.dateStringToTimestamp(source)));
    }

    return idBytes;
}
 
Example 23
Source Project: stratio-cassandra   Source File: LexicalUUIDType.java    License: Apache License 2.0 5 votes vote down vote up
public int compare(ByteBuffer o1, ByteBuffer o2)
{
    if (!o1.hasRemaining() || !o2.hasRemaining())
        return o1.hasRemaining() ? 1 : o2.hasRemaining() ? -1 : 0;

    return UUIDGen.getUUID(o1).compareTo(UUIDGen.getUUID(o2));
}
 
Example 24
Source Project: stratio-cassandra   Source File: MessageOut.java    License: Apache License 2.0 5 votes vote down vote up
public MessageOut(MessagingService.Verb verb, T payload, IVersionedSerializer<T> serializer)
{
    this(verb,
         payload,
         serializer,
         isTracing() ? ImmutableMap.of(TRACE_HEADER, UUIDGen.decompose(Tracing.instance.getSessionId()))
                     : Collections.<String, byte[]>emptyMap());
}
 
Example 25
Source Project: stratio-cassandra   Source File: BatchlogManagerTest.java    License: Apache License 2.0 5 votes vote down vote up
@Before
public void setUp() throws Exception
{
    TokenMetadata metadata = StorageService.instance.getTokenMetadata();
    InetAddress localhost = InetAddress.getByName("127.0.0.1");
    metadata.updateNormalToken(Util.token("A"), localhost);
    metadata.updateHostId(UUIDGen.getTimeUUID(), localhost);
}
 
Example 26
Source Project: stratio-cassandra   Source File: TimeUUIDTypeTest.java    License: Apache License 2.0 5 votes vote down vote up
@Test
public void testEquality()
{
    UUID a = UUIDGen.getTimeUUID();
    UUID b = new UUID(a.getMostSignificantBits(), a.getLeastSignificantBits());

    timeUUIDType.validate(ByteBuffer.wrap(UUIDGen.decompose(a)));
    timeUUIDType.validate(ByteBuffer.wrap(UUIDGen.decompose(b)));
    assertEquals(0, timeUUIDType.compare(ByteBuffer.wrap(UUIDGen.decompose(a)), ByteBuffer.wrap(UUIDGen.decompose(b))));
}
 
Example 27
Source Project: stratio-cassandra   Source File: UUIDTypeTest.java    License: Apache License 2.0 5 votes vote down vote up
@Test
public void testCompare()
{

    UUID t1 = UUIDGen.getTimeUUID();
    UUID t2 = UUIDGen.getTimeUUID();

    testCompare(null, t2, -1);
    testCompare(t1, null, 1);

    testCompare(t1, t2, -1);
    testCompare(t1, t1, 0);
    testCompare(t2, t2, 0);

    UUID nullId = new UUID(0, 0);

    testCompare(nullId, t1, -1);
    testCompare(t2, nullId, 1);
    testCompare(nullId, nullId, 0);

    for (int test = 1; test < 32; test++)
    {
        UUID r1 = UUID.randomUUID();
        UUID r2 = UUID.randomUUID();

        testCompare(r1, r2, compareUUID(r1, r2));
        testCompare(r1, r1, 0);
        testCompare(r2, r2, 0);

        testCompare(t1, r1, -1);
        testCompare(r2, t2, 1);
    }
}
 
Example 28
Source Project: stratio-cassandra   Source File: UUIDTypeTest.java    License: Apache License 2.0 5 votes vote down vote up
@Test
public void testTimeEquality()
{
    UUID a = UUIDGen.getTimeUUID();
    UUID b = new UUID(a.getMostSignificantBits(),
            a.getLeastSignificantBits());

    assertEquals(0, uuidType.compare(bytebuffer(a), bytebuffer(b)));
}
 
Example 29
Source Project: stratio-cassandra   Source File: SSTableExportTest.java    License: Apache License 2.0 5 votes vote down vote up
/**
 * Tests CASSANDRA-6892 (key aliases being used improperly for validation)
 */
@Test
public void testColumnNameEqualToDefaultKeyAlias() throws IOException, ParseException
{
    File tempSS = tempSSTableFile("Keyspace1", "UUIDKeys");
    ColumnFamily cfamily = ArrayBackedSortedColumns.factory.create("Keyspace1", "UUIDKeys");
    SSTableWriter writer = new SSTableWriter(tempSS.getPath(), 2, ActiveRepairService.UNREPAIRED_SSTABLE);

    // Add a row
    cfamily.addColumn(column(CFMetaData.DEFAULT_KEY_ALIAS, "not a uuid", 1L));
    writer.append(Util.dk(ByteBufferUtil.bytes(UUIDGen.getTimeUUID())), cfamily);

    SSTableReader reader = writer.closeAndOpenReader();
    // Export to JSON and verify
    File tempJson = File.createTempFile("CFWithColumnNameEqualToDefaultKeyAlias", ".json");
    SSTableExport.export(reader, new PrintStream(tempJson.getPath()), new String[0],
            CFMetaData.sparseCFMetaData("Keyspace1", "UUIDKeys", BytesType.instance));

    JSONArray json = (JSONArray)JSONValue.parseWithException(new FileReader(tempJson));
    assertEquals(1, json.size());

    JSONObject row = (JSONObject)json.get(0);
    JSONArray cols = (JSONArray) row.get("cells");
    assertEquals(1, cols.size());

    // check column name and value
    JSONArray col = (JSONArray) cols.get(0);
    assertEquals(CFMetaData.DEFAULT_KEY_ALIAS, ByteBufferUtil.string(hexToBytes((String) col.get(0))));
    assertEquals("not a uuid", ByteBufferUtil.string(hexToBytes((String) col.get(1))));
}
 
Example 30
Source Project: usergrid   Source File: AuditLogSerializationTest.java    License: Apache License 2.0 5 votes vote down vote up
@Test
public void testGetAuditLogs() throws Exception {

    CassandraClient cassandraClient = getInjector().getInstance( CassandraClientImpl.class );

    AuditLogSerialization logSerialization = getInjector().getInstance( AuditLogSerialization.class );

    // record some audit logs for a message
    UUID messageId = UUIDGen.getTimeUUID();
    String queueName = "alst_queue_" + RandomStringUtils.randomAlphanumeric( 15 );
    String source = RandomStringUtils.randomAlphanumeric( 15 );
    String dest = RandomStringUtils.randomAlphanumeric( 15 );

    int numLogs = 10;

    UUID queueMessageId1 = UUIDGen.getTimeUUID();
    for ( int i=0; i<numLogs; i++ ) {
        logSerialization.recordAuditLog( AuditLog.Action.GET, AuditLog.Status.SUCCESS,
                queueName, dest, messageId, queueMessageId1 );
        Thread.sleep(5);
    }

    UUID queueMessageId2 = UUIDGen.getTimeUUID();
    for ( int i=0; i<numLogs; i++ ) {
        logSerialization.recordAuditLog( AuditLog.Action.GET, AuditLog.Status.SUCCESS,
                queueName, dest, messageId, queueMessageId2 );
        Thread.sleep(5);
    }

    UUID queueMessageId3 = UUIDGen.getTimeUUID();
    for ( int i=0; i<numLogs; i++ ) {
        logSerialization.recordAuditLog( AuditLog.Action.GET, AuditLog.Status.SUCCESS,
                queueName, dest, messageId, queueMessageId3 );
        Thread.sleep(5);
    }

    // test that we have 3 X number of logs for the messageId
    Result<AuditLog> result = logSerialization.getAuditLogs( messageId );
    Assert.assertEquals( numLogs * 3, result.getEntities().size() );
}