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

Following code examples demonstrate how to use org.apache.cassandra.utils.ByteBufferUtil from cassandra. These examples are extracted from various highly rated open source projects. You can directly use these code snippets or view their entire linked source code. These snippets are extracted to provide contextual information about how to use this class in the real world. These samples also let you understand some good practices on how to use org.apache.cassandra.utils.ByteBufferUtil and various code implementation of this class.
Example 1
Project : cassandra Source File : ContextAllocator.java View Source Code on GitHub

   public ByteBuffer clone(ByteBuffer buffer) {
      assert buffer != null;

      if(buffer.remaining() == 0) {
         return ByteBufferUtil.EMPTY_BYTE_BUFFER;
      } else {
         ByteBuffer cloned = this.allocate(buffer.remaining());
         cloned.mark();
         cloned.put(buffer.duplicate());
         cloned.reset();
         return cloned;
      }
   }
			
Example 2
Project : cassandra Source File : SlicePredicateExample.java View Source Code on GitHub

    public static void main(String[] args) throws Exception {
        Connector conn = new Connector();
        Cassandra.Client client = conn.connect();

        SlicePredicate predicate = new SlicePredicate();
        List<ByteBuffer> colNames = new ArrayList<ByteBuffer>();
        colNames.add(bytes("a"));
        colNames.add(bytes("b"));
        predicate.column_names = colNames;

        ColumnParent parent = new ColumnParent("Standard1");

        ByteBuffer key = bytes("k1");
        List<ColumnOrSuperColumn> results = client.get_slice(key, parent,
                predicate, ConsistencyLevel.ONE);

        for (ColumnOrSuperColumn cosc : results) {
            Column c = cosc.column;
            System.out.println(ByteBufferUtil.string(c.name) + " : "
                    + ByteBufferUtil.string(c.value));
        }

        conn.close();

        System.out.println("All done.");
    }
			
Example 3
Project : cassandra Source File : ConvertData.java View Source Code on GitHub

	public static ByteBuffer serialize(Object obj) {

		ByteBuffer bytebuffer = null;
		try {
			bytebuffer = ByteBufferUtil.getByteBuffer(obj);
		} catch (IOException e) {
			e.printStackTrace();
		}
		return bytebuffer;
	}
			
Example 4
Project : cassandra Source File : ConvertData.java View Source Code on GitHub

	public static Object deserialize(ByteBuffer bytebuffer) {

		Object obj = null;
		try {
			obj = (Object) ByteBufferUtil.getObject(bytebuffer);
		} catch (ClassNotFoundException e) {
			e.printStackTrace();
		} catch (IOException e) {
			e.printStackTrace();
		}
		return obj;
	}
			
Example 5
Project : cassandra Source File : TracingAppender.java View Source Code on GitHub

        {
            public void runMayThrow() throws Exception
            {
                ByteBuffer eventId = ByteBufferUtil.bytes(UUIDGen.makeType1UUIDFromHost(FBUtilities
                        .getBroadcastAddress()));
                CFMetaData cfMeta = CFMetaData.TraceEventsCf;
                ColumnFamily cf = ColumnFamily.create(cfMeta);
                addColumn(cf, buildName(cfMeta, eventId, bytes("source")), FBUtilities.getBroadcastAddress());
                addColumn(cf, buildName(cfMeta, eventId, bytes("thread")), threadName);
                addColumn(cf, buildName(cfMeta, eventId, bytes("happened_at")), event.getTimeStamp());
                addColumn(cf, buildName(cfMeta, eventId, bytes("source_elapsed")), elapsed);
                addColumn(cf, buildName(cfMeta, eventId, bytes("activity")), event.getMessage());
                RowMutation mutation = new RowMutation(Tracing.TRACE_KS, state.sessionIdBytes);
                mutation.add(cf);
                StorageProxy.mutate(Arrays.asList(mutation), ConsistencyLevel.ANY);
            }
        });
			
Example 6
Project : cassandra Source File : GetRangeSliceExample.java View Source Code on GitHub

    public static void main(String[] args) throws Exception {
        Connector conn = new Connector();
        Cassandra.Client client = conn.connect();

        System.out.println("Getting Range Slices.");

        SlicePredicate predicate = new SlicePredicate();
        List<ByteBuffer> colNames = new ArrayList<ByteBuffer>();
        colNames.add(bytes("a"));
        colNames.add(bytes("b"));
        predicate.column_names = colNames;

        ColumnParent parent = new ColumnParent("Standard1");

        KeyRange keyRange = new KeyRange();
        keyRange.start_key = bytes("k1");
        keyRange.end_key = bytes("k2");

        List<KeySlice> results = client.get_range_slices(parent, predicate,
                keyRange, ConsistencyLevel.ONE);

        for (KeySlice keySlice : results) {
            List<ColumnOrSuperColumn> cosc = keySlice.getColumns();

            System.out.println("Current row: " + new String(keySlice.getKey()));

            for (int i = 0; i < cosc.size(); i++) {
                Column c = cosc.get(i).getColumn();
                System.out.println(ByteBufferUtil.string(c.name) + " : "
                        + ByteBufferUtil.string(c.value));
            }
        }

        conn.close();

        System.out.println("All done.");
    }
			
Example 7
Project : cassandra Source File : SSTableCreator.java View Source Code on GitHub

    public File createSSTableFiles(String csvFile, String keyspace, String columnFamily, MutableInt lineCounter, MutableBoolean lastLineRead, BufferedReader reader) throws IOException {

        File directory = new File(keyspace+columnFamily);
        if (directory.exists()) {
            FileUtils.deleteDirectory(directory);
        }
        directory.mkdir();

        IPartitioner partitioner = new Murmur3Partitioner();

        List<AbstractType<?>> types = new ArrayList<AbstractType<?>>();
        types.add(AsciiType.instance);
        types.add(AsciiType.instance);
        CompositeType cmpType = CompositeType.getInstance(types);



        SSTableSimpleUnsortedWriter usersWriter = new SSTableSimpleUnsortedWriter(
                directory, partitioner, keyspace, columnFamily, cmpType, null, 64);


        String line;
        CsvEntry entry = new CsvEntry(csvFile);
        long timestamp = System.currentTimeMillis() * 1000;

        int currentCounter = 0;
        int ttl = daily_ttl;
        if(columnFamily.contains("hour"))
            ttl = hourly_ttl;


        while ((line = reader.readLine()) != null && currentCounter < LINES_IN_BATCH) {
            currentCounter++;
            if (entry.parse(line, lineCounter.intValue()+currentCounter)) {
                usersWriter.newRow(bytes(entry.partner_filter_gb1_gb2));
                usersWriter.addExpiringColumn(cmpType.builder().add(ByteBufferUtil.bytes(entry.dt_gb1_gb2)).add(ByteBufferUtil.bytes("dim_gb1")).build(), ByteBufferUtil.bytes(entry.dim_gb1), timestamp, ttl, (timestamp/1000) + ttl * 1000);
                usersWriter.addExpiringColumn(cmpType.builder().add(ByteBufferUtil.bytes(entry.dt_gb1_gb2)).add(ByteBufferUtil.bytes("dim_gb2")).build(), ByteBufferUtil.bytes(entry.dim_gb2), timestamp, ttl, (timestamp/1000) + ttl * 1000);
                usersWriter.addExpiringColumn(cmpType.builder().add(ByteBufferUtil.bytes(entry.dt_gb1_gb2)).add(ByteBufferUtil.bytes("f")).build(), ByteBufferUtil.bytes(entry.f), timestamp, ttl, (timestamp/1000) + ttl * 1000);
                for(int i=1; i < CsvEntry.max_allowed_measures;i++)
                {
                    usersWriter.addExpiringColumn(cmpType.builder().add(ByteBufferUtil.bytes(entry.dt_gb1_gb2)).add(ByteBufferUtil.bytes("m" + i)).build(), ByteBufferUtil.bytes(entry.getMeasures()[i]), timestamp, ttl, (timestamp/1000) + ttl * 1000);
                }
            }

        }
        lineCounter.add(currentCounter);
            lastLineRead.setValue(true);
        usersWriter.close();
        return directory;
    }
			
Example 8
Project : cassandra Source File : SSTableExportTest.java View Source Code on GitHub

    @Test
    public void testEnumeratekeys() throws IOException
    {
        File tempSS = tempSSTableFile("Keyspace1", "Standard1");
        ColumnFamily cfamily = ColumnFamily.create("Keyspace1", "Standard1");
        SSTableWriter writer = new SSTableWriter(tempSS.getPath(), 2);
        
        cfamily.addColumn(new QueryPath("Standard1", null, ByteBufferUtil.bytes("colA")), ByteBufferUtil.bytes("valA"), System.currentTimeMillis());
        writer.append(Util.dk("rowA"), cfamily);
        cfamily.clear();
        
        cfamily.addColumn(new QueryPath("Standard1", null, ByteBufferUtil.bytes("colB")), ByteBufferUtil.bytes("valB"), System.currentTimeMillis());
        writer.append(Util.dk("rowB"), cfamily);
        cfamily.clear();
     
        writer.closeAndOpenReader();
        
        File temp = File.createTempFile("Standard1", ".txt");
        SSTableExport.enumeratekeys(writer.getFilename(), new PrintStream(temp.getPath()));

        
        FileReader file = new FileReader(temp);
        char[] buf = new char[(int) temp.length()];
        file.read(buf);
        String output = new String(buf);

        String sep = System.getProperty("line.separator");
        assert output.equals(asHex("rowA") + sep + asHex("rowB") + sep) : output;
    }
			
Example 9
Project : cassandra Source File : SSTableExportTest.java View Source Code on GitHub

    @Test
    public void testExportSimpleCf() throws IOException
    {
        File tempSS = tempSSTableFile("Keyspace1", "Standard1");
        ColumnFamily cfamily = ColumnFamily.create("Keyspace1", "Standard1");
        SSTableWriter writer = new SSTableWriter(tempSS.getPath(), 2);
        
        cfamily.addColumn(new QueryPath("Standard1", null, ByteBufferUtil.bytes("colA")), ByteBufferUtil.bytes("valA"), System.currentTimeMillis());
        cfamily.addColumn(null, new ExpiringColumn(ByteBufferUtil.bytes("colExp"), ByteBufferUtil.bytes("valExp"), System.currentTimeMillis(), 42, nowInSec));
        writer.append(Util.dk("rowA"), cfamily);
        cfamily.clear();
        
        cfamily.addColumn(new QueryPath("Standard1", null, ByteBufferUtil.bytes("colB")), ByteBufferUtil.bytes("valB"), System.currentTimeMillis());
        writer.append(Util.dk("rowB"), cfamily);
        cfamily.clear();

        cfamily.addColumn(new QueryPath("Standard1", null, ByteBufferUtil.bytes("colX")), ByteBufferUtil.bytes("valX"), System.currentTimeMillis());
        writer.append(Util.dk("rowExclude"), cfamily);
        cfamily.clear();

        SSTableReader reader = writer.closeAndOpenReader();
        
        File tempJson = File.createTempFile("Standard1", ".json");
        SSTableExport.export(reader, new PrintStream(tempJson.getPath()), new String[]{asHex("rowExclude")});
        
        JSONObject json = (JSONObject)JSONValue.parse(new FileReader(tempJson));
        
        JSONArray rowA = (JSONArray)json.get(asHex("rowA"));
        JSONArray colA = (JSONArray)rowA.get(0);
        assert hexToBytes((String)colA.get(1)).equals(ByteBufferUtil.bytes("valA"));

        JSONArray colExp = (JSONArray)rowA.get(1);
        assert ((Long)colExp.get(4)) == 42;
        assert ((Long)colExp.get(5)) == nowInSec;
        
        JSONArray rowB = (JSONArray)json.get(asHex("rowB"));
        JSONArray colB = (JSONArray)rowB.get(0);
        assert !(Boolean)colB.get(3);

        JSONArray rowExclude = (JSONArray)json.get(asHex("rowExclude"));
        assert rowExclude == null;
    }
			
Example 10
Project : cassandra Source File : SSTableExportTest.java View Source Code on GitHub

    @Test
    public void testRoundTripStandardCf() throws IOException, ParseException
    {
        File tempSS = tempSSTableFile("Keyspace1", "Standard1");
        ColumnFamily cfamily = ColumnFamily.create("Keyspace1", "Standard1");
        SSTableWriter writer = new SSTableWriter(tempSS.getPath(), 2);
        
        cfamily.addColumn(new QueryPath("Standard1", null, ByteBufferUtil.bytes("name")), ByteBufferUtil.bytes("val"), System.currentTimeMillis());
        writer.append(Util.dk("rowA"), cfamily);
        cfamily.clear();

        cfamily.addColumn(new QueryPath("Standard1", null, ByteBufferUtil.bytes("name")), ByteBufferUtil.bytes("val"), System.currentTimeMillis());
        writer.append(Util.dk("rowExclude"), cfamily);
        cfamily.clear();

        SSTableReader reader = writer.closeAndOpenReader();
        
        File tempJson = File.createTempFile("Standard1", ".json");
        SSTableExport.export(reader, new PrintStream(tempJson.getPath()), new String[]{asHex("rowExclude")});
        
        File tempSS2 = tempSSTableFile("Keyspace1", "Standard1");
        SSTableImport.importJson(tempJson.getPath(), "Keyspace1", "Standard1", tempSS2.getPath());

        reader = SSTableReader.open(Descriptor.fromFilename(tempSS2.getPath()));
        QueryFilter qf = QueryFilter.getNamesFilter(Util.dk("rowA"), new QueryPath("Standard1", null, null), ByteBufferUtil.bytes("name"));
        ColumnFamily cf = qf.getSSTableColumnIterator(reader).getColumnFamily();
        assertTrue(cf != null);
        assertTrue(cf.getColumn(ByteBufferUtil.bytes("name")).value().equals(hexToBytes("76616c")));

        qf = QueryFilter.getNamesFilter(Util.dk("rowExclude"), new QueryPath("Standard1", null, null), ByteBufferUtil.bytes("name"));
        cf = qf.getSSTableColumnIterator(reader).getColumnFamily();
        assert cf == null;
    }
			
Example 11
Project : cassandra Source File : SSTableExportTest.java View Source Code on GitHub

    @Test
    public void testExportSuperCf() throws IOException
    {
        File tempSS = tempSSTableFile("Keyspace1", "Super4");
        ColumnFamily cfamily = ColumnFamily.create("Keyspace1", "Super4");
        SSTableWriter writer = new SSTableWriter(tempSS.getPath(), 2);
        
        cfamily.addColumn(new QueryPath("Super4", ByteBufferUtil.bytes("superA"), ByteBufferUtil.bytes("colA")), ByteBufferUtil.bytes("valA"), System.currentTimeMillis());
        writer.append(Util.dk("rowA"), cfamily);
        cfamily.clear();
        
        cfamily.addColumn(new QueryPath("Super4", ByteBufferUtil.bytes("superB"), ByteBufferUtil.bytes("colB")), ByteBufferUtil.bytes("valB"), System.currentTimeMillis());
        writer.append(Util.dk("rowB"), cfamily);
        cfamily.clear();

        cfamily.addColumn(new QueryPath("Super4", ByteBufferUtil.bytes("superX"), ByteBufferUtil.bytes("colX")), ByteBufferUtil.bytes("valX"), System.currentTimeMillis());
        writer.append(Util.dk("rowExclude"), cfamily);
        cfamily.clear();

        SSTableReader reader = writer.closeAndOpenReader();
        
        File tempJson = File.createTempFile("Super4", ".json");
        SSTableExport.export(reader, new PrintStream(tempJson.getPath()), new String[]{asHex("rowExclude")});
        
        JSONObject json = (JSONObject)JSONValue.parse(new FileReader(tempJson));
        
        JSONObject rowA = (JSONObject)json.get(asHex("rowA"));
        JSONObject superA = (JSONObject)rowA.get(cfamily.getComparator().getString(ByteBufferUtil.bytes("superA")));
        JSONArray subColumns = (JSONArray)superA.get("subColumns");
        JSONArray colA = (JSONArray)subColumns.get(0);
        JSONObject rowExclude = (JSONObject)json.get(asHex("rowExclude"));
        assert hexToBytes((String)colA.get(1)).equals(ByteBufferUtil.bytes("valA"));
        assert !(Boolean)colA.get(3);
        assert rowExclude == null;
    }
			
Example 12
Project : cassandra Source File : TestByteBuffer.java View Source Code on GitHub

	public static void main(String args[]) throws IOException, ClassNotFoundException{
		int i = 234;
		Integer j = 453333;
		ByteBuffer b1  = ByteBufferUtil.bytes(j);
		ByteBuffer b2  = ByteBufferUtil.getByteBuffer(j);
		System.out.println(b1.capacity());
		System.out.println(b2.capacity());
		Object obj1 = ByteBufferUtil.getObject(b1);
		Object obj2 = ByteBufferUtil.getObject(b2);
		System.out.println(obj1.toString());
		System.out.println(obj2.toString());
		
	}