org.apache.cassandra.utils.UUIDGen Java Examples

The following examples show how to use org.apache.cassandra.utils.UUIDGen. 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: 986499_AddColumnFamily_0_t.java    From coming with 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 File: ScrubTest.java    From stratio-cassandra with 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 #3
Source File: TraceState.java    From stratio-cassandra with 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 #4
Source File: ClientUtilsTest.java    From stratio-cassandra with 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 #5
Source File: AuditLogSerializationTest.java    From usergrid with 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 #6
Source File: 986499_AddColumnFamily_0_s.java    From coming with 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 File: 986499_AddColumnFamily_0_t.java    From coming with 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 #8
Source File: 986499_AddColumnFamily_0_s.java    From coming with 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 #9
Source File: 986499_AddColumnFamily_0_t.java    From coming with 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 #10
Source File: 986499_AddColumnFamily_0_s.java    From coming with 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 #11
Source File: TimeuuidFcts.java    From stratio-cassandra with 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 #12
Source File: BatchlogManagerTest.java    From stratio-cassandra with 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 #13
Source File: TimeUUIDTypeTest.java    From stratio-cassandra with 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 #14
Source File: MessageOut.java    From stratio-cassandra with 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 #15
Source File: UUIDTypeTest.java    From stratio-cassandra with 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 #16
Source File: Lists.java    From stratio-cassandra with 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 #17
Source File: UUIDTypeTest.java    From stratio-cassandra with 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 #18
Source File: SSTableExportTest.java    From stratio-cassandra with 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 #19
Source File: TimeuuidFcts.java    From stratio-cassandra with 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 #20
Source File: LexicalUUIDType.java    From stratio-cassandra with 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 #21
Source File: TimeUUIDType.java    From stratio-cassandra with 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 #22
Source File: PrepareMessage.java    From stratio-cassandra with 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 #23
Source File: TimeuuidFcts.java    From stratio-cassandra with 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 #24
Source File: AuditLogSerializationTest.java    From usergrid with 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() );
}
 
Example #25
Source File: TransferLogSerializationTest.java    From usergrid with Apache License 2.0 5 votes vote down vote up
@Test
public void recordTransferLog() throws Exception {

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

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

    String queueName = "tlst_queue_" + RandomStringUtils.randomAlphanumeric( 15 );
    String source = RandomStringUtils.randomAlphanumeric( 15 );
    String dest = RandomStringUtils.randomAlphanumeric( 15 );

    int numLogs = 100;

    for ( int i=0; i<numLogs; i++ ) {
        logSerialization.recordTransferLog( queueName, source, dest, UUIDGen.getTimeUUID());
    }

    int count = 0;
    int fetchCount = 0;
    PagingState pagingState = null;
    while ( true ) {

        Result<TransferLog> all = logSerialization.getAllTransferLogs( pagingState, 10 );

        // we only want entities for our queue
        List<TransferLog> logs = all.getEntities().stream()
            .filter( log -> log.getQueueName().equals( queueName ) ).collect( Collectors.toList() );

        count += logs.size();
        fetchCount++;
        if ( all.getPagingState() == null ) {
            break;
        }
        pagingState = all.getPagingState();
    }

    Assert.assertEquals( numLogs, count );
}
 
Example #26
Source File: TransferLogSerializationTest.java    From usergrid with Apache License 2.0 5 votes vote down vote up
@Test
public void removeTransferLog() throws Exception {

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

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

    String queueName = "tlst_queue_" + RandomStringUtils.randomAlphanumeric( 15 );
    String source = RandomStringUtils.randomAlphanumeric( 15 );
    String dest = RandomStringUtils.randomAlphanumeric( 15 );

    UUID messageId = UUIDGen.getTimeUUID();
    logSerialization.recordTransferLog( queueName, source, dest, messageId );

    List<TransferLog> allLogs = getTransferLogs( logSerialization );

    // we only want entities for our queue
    List<TransferLog> logs = allLogs.stream()
            .filter( log -> log.getQueueName().equals( queueName ) ).collect( Collectors.toList() );
    Assert.assertEquals( 1, logs.size());

    logSerialization.removeTransferLog( queueName, source, dest, messageId );

    List<TransferLog> all = getTransferLogs( logSerialization );
    logs = all.stream()
        .filter( log -> log.getQueueName().equals( queueName ) ).collect( Collectors.toList() );
    Assert.assertEquals( 0, logs.size());

    try {
        logSerialization.removeTransferLog( queueName, source, dest, messageId );
        Assert.fail("Removing non-existent log should throw exception");

    } catch ( QakkaException expected ) {
        // success!
    }
}
 
Example #27
Source File: Commit.java    From stratio-cassandra with 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 #28
Source File: PaxosState.java    From stratio-cassandra with 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 #29
Source File: HintedHandoffMetrics.java    From stratio-cassandra with 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 #30
Source File: AbstractCassandraStorage.java    From stratio-cassandra with Apache License 2.0 5 votes vote down vote up
/** 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());
}