Java Code Examples for org.apache.ignite.binary.BinaryObjectBuilder#setField()

The following examples show how to use org.apache.ignite.binary.BinaryObjectBuilder#setField() . 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: IgniteCacheAbstractInsertSqlQuerySelfTest.java    From ignite with Apache License 2.0 6 votes vote down vote up
/**
 *
 */
Object createPerson2(int id, String name, int valFld) {
    if (!isBinaryMarshaller()) {
        Person2 p = new Person2(id);
        p.name = name;
        p.IntVal = valFld;

        return p;
    }
    else {
        BinaryObjectBuilder o = grid(0).binary().builder("Person2");
        o.setField("id", id);
        o.setField("name", name);
        o.setField("IntVal", valFld);

        return o.build();
    }
}
 
Example 2
Source File: CacheJdbcPojoStore.java    From ignite with Apache License 2.0 6 votes vote down vote up
/**
 * Construct binary object from query result.
 *
 * @param typeName Type name.
 * @param fields Fields descriptors.
 * @param loadColIdxs Select query columns index.
 * @param rs ResultSet.
 * @return Constructed binary object.
 * @throws CacheLoaderException If failed to construct binary object.
 */
protected Object buildBinaryObject(String typeName, JdbcTypeField[] fields, Map<String, Integer> loadColIdxs, ResultSet rs) throws CacheLoaderException {
    try {
        BinaryObjectBuilder builder = ignite.binary().builder(typeName);

        for (JdbcTypeField field : fields) {
            Integer colIdx = columnIndex(loadColIdxs, field.getDatabaseFieldName());

            Object colVal = transformer.getColumnValue(rs, colIdx, field.getJavaFieldType());

            builder.setField(field.getJavaFieldName(), colVal, (Class<Object>)field.getJavaFieldType());
        }

        return builder.build();
    }
    catch (SQLException e) {
        throw new CacheException("Failed to read binary object: " + typeName, e);
    }
}
 
Example 3
Source File: BinaryObjectBuilderDefaultMappersSelfTest.java    From ignite with Apache License 2.0 5 votes vote down vote up
/**
 * @throws Exception If failed.
 */
@Test
public void testDoubleArrayField() throws Exception {
    BinaryObjectBuilder builder = builder("Class");

    builder.setField("doubleArrayField", new double[] {1, 2, 3});

    BinaryObject po = builder.build();

    assertEquals(expectedHashCode("Class"), po.type().typeId());
    assertEquals(BinaryArrayIdentityResolver.instance().hashCode(po), po.hashCode());

    assertTrue(Arrays.equals(new double[] {1, 2, 3}, po.<double[]>field("doubleArrayField")));
}
 
Example 4
Source File: BinaryObjectBuilderDefaultMappersSelfTest.java    From ignite with Apache License 2.0 5 votes vote down vote up
/**
 * @throws Exception If failed.
 */
@Test
public void testByteField() throws Exception {
    BinaryObjectBuilder builder = builder("Class");

    builder.setField("byteField", (byte)1);

    BinaryObject po = builder.build();

    assertEquals(expectedHashCode("Class"), po.type().typeId());
    assertEquals(BinaryArrayIdentityResolver.instance().hashCode(po), po.hashCode());

    assertEquals((byte) 1, po.<Byte>field("byteField").byteValue());
}
 
Example 5
Source File: IgniteRepositoryQuery.java    From ignite with Apache License 2.0 5 votes vote down vote up
/**
 * convert row ( with list of field values) into domain entity
 */
private <V> V rowToEntity(final IgniteBinaryImpl binary,
    final BinaryType binType,
    final List<?> row,
    final List<GridQueryFieldMetadata> meta) {
    // additional data returned by query not present on domain object type
    final TreeMap<String, Object> metadata = new TreeMap<>(String.CASE_INSENSITIVE_ORDER);
    final BinaryObjectBuilder bldr = binary.builder(binType.typeName());

    for (int i = 0; i < row.size(); i++) {
        final GridQueryFieldMetadata fMeta = meta.get(i);
        final String metaField = fMeta.fieldName();
        // add existing entity fields to binary object
        if (binType.field(fMeta.fieldName()) != null && !metaField.equalsIgnoreCase(QueryUtils.KEY_FIELD_NAME)
            && !metaField.equalsIgnoreCase(QueryUtils.VAL_FIELD_NAME)) {
            final Object fieldValue = row.get(i);
            if (fieldValue != null) {
                final Class<?> clazz = getClassForBinaryField(binary, binType, fMeta);
                // null values must not be set into binary objects
                bldr.setField(metaField, fixExpectedType(fieldValue, clazz));
            }
        }
        else {
            // don't want key or val column... but wants null values
            if (!metaField.equalsIgnoreCase(QueryUtils.KEY_FIELD_NAME) && !metaField.equalsIgnoreCase(
                QueryUtils.VAL_FIELD_NAME))
                metadata.put(metaField, row.get(i));
        }
    }
    return bldr.build().deserialize();
}
 
Example 6
Source File: IgniteCacheBinaryEntryProcessorSelfTest.java    From ignite with Apache License 2.0 5 votes vote down vote up
/** {@inheritDoc} */
@Override public Void process(MutableEntry<Integer, BinaryObject> entry, Object... arguments)
    throws EntryProcessorException {
    BinaryObjectBuilder bldr = entry.getValue().toBuilder();

    Integer val = bldr.<Integer>getField("val");

    bldr.setField("val", val + 1);
    bldr.setField("strVal", "updated-" + val);

    entry.setValue(bldr.build());

    return null;
}
 
Example 7
Source File: SqlIncompatibleDataTypeExceptionTest.java    From ignite with Apache License 2.0 5 votes vote down vote up
/**
 * Test use _val field at INSERT statement.
 */
@Test
public void testUseValField() {
    // Unwrapped simple value.
    execSql("CREATE TABLE test_0 (id integer primary key, val varchar) WITH \"WRAP_VALUE=0\"");
    execSql("INSERT INTO test_0 (id, _val) VALUES (?, ?)", 0, "0");
    execSql("MERGE INTO test_0 (id, _val) VALUES (?, ?)", 1, "1");
    execSql("UPDATE test_0 SET _val = ?", "upd");

    // Composite value.
    execSql("CREATE TABLE test (id integer primary key, val varchar)");

    final BinaryObjectBuilder bob = grid().binary().builder("val");
    bob.setField("val", "0");

    GridTestUtils.assertThrows(log, () -> {
        execSql("INSERT INTO test (id, _val) VALUES (?, ?)", 0, bob.build());

        return null;
    }, IgniteSQLException.class, "Update of composite value column is not supported");

    GridTestUtils.assertThrows(log, () -> {
        execSql("MERGE INTO test (id, _val) VALUES (?, ?)", 0, bob.build());

        return null;
    }, IgniteSQLException.class, "Update of composite value column is not supported");

    GridTestUtils.assertThrows(log, () -> {
        execSql("UPDATE test SET _val=?", bob.build());

        return null;
    }, IgniteSQLException.class, "Update of composite value column is not supported");
}
 
Example 8
Source File: IgniteRepositoryQuery.java    From ignite with Apache License 2.0 5 votes vote down vote up
/**
 * convert row ( with list of field values) into domain entity
 */
private <V> V rowToEntity(final IgniteBinaryImpl binary,
    final BinaryType binType,
    final List<?> row,
    final List<GridQueryFieldMetadata> meta) {
    // additional data returned by query not present on domain object type
    final TreeMap<String, Object> metadata = new TreeMap<>(String.CASE_INSENSITIVE_ORDER);
    final BinaryObjectBuilder bldr = binary.builder(binType.typeName());

    for (int i = 0; i < row.size(); i++) {
        final GridQueryFieldMetadata fMeta = meta.get(i);
        final String metaField = fMeta.fieldName();
        // add existing entity fields to binary object
        if (binType.field(fMeta.fieldName()) != null && !metaField.equalsIgnoreCase(QueryUtils.KEY_FIELD_NAME)
            && !metaField.equalsIgnoreCase(QueryUtils.VAL_FIELD_NAME)) {
            final Object fieldValue = row.get(i);
            if (fieldValue != null) {
                final Class<?> clazz = getClassForBinaryField(binary, binType, fMeta);
                // null values must not be set into binary objects
                bldr.setField(metaField, fixExpectedType(fieldValue, clazz));
            }
        }
        else {
            // don't want key or val column... but wants null values
            if (!metaField.equalsIgnoreCase(QueryUtils.KEY_FIELD_NAME) && !metaField.equalsIgnoreCase(
                QueryUtils.VAL_FIELD_NAME))
                metadata.put(metaField, row.get(i));
        }
    }
    return bldr.build().deserialize();
}
 
Example 9
Source File: BinaryObjectBuilderDefaultMappersSelfTest.java    From ignite with Apache License 2.0 5 votes vote down vote up
/**
 * @throws Exception If failed.
 */
@Test
public void testBooleanField() throws Exception {
    BinaryObjectBuilder builder = builder("Class");

    builder.setField("booleanField", true);

    BinaryObject po = builder.build();

    assertEquals(expectedHashCode("Class"), po.type().typeId());
    assertEquals(BinaryArrayIdentityResolver.instance().hashCode(po), po.hashCode());

    assertTrue(po.<Boolean>field("booleanField"));
}
 
Example 10
Source File: IgniteCacheAbstractSqlDmlQuerySelfTest.java    From ignite with Apache License 2.0 5 votes vote down vote up
/**
 * Create binary person.
 *
 * @param id ID.
 * @param name Name.
 * @param secondName Second name.
 * @return Person.
 */
private Object createBinPerson(int id, String name, String secondName) {
    BinaryObjectBuilder bldr = ignite(0).binary().builder("Person");

    bldr.setField("id", id);
    bldr.setField("firstName", name);
    bldr.setField("secondName", secondName);

    return bldr.build();
}
 
Example 11
Source File: BinaryObjectBuilderDefaultMappersSelfTest.java    From ignite with Apache License 2.0 5 votes vote down vote up
/**
 * @throws Exception If failed.
 */
@Test
public void testLongArrayField() throws Exception {
    BinaryObjectBuilder builder = builder("Class");

    builder.setField("longArrayField", new long[] {1, 2, 3});

    BinaryObject po = builder.build();

    assertEquals(expectedHashCode("Class"), po.type().typeId());
    assertEquals(BinaryArrayIdentityResolver.instance().hashCode(po), po.hashCode());

    assertTrue(Arrays.equals(new long[] {1, 2, 3}, po.<long[]>field("longArrayField")));
}
 
Example 12
Source File: GridDataStreamerImplSelfTest.java    From ignite with Apache License 2.0 5 votes vote down vote up
/**
 *  Tries to propagate cache with binary objects created using the builder.
 *
 * @throws Exception If failed.
 */
@Test
public void testAddBinaryCreatedWithBuilder() throws Exception {
    try {
        binaries = true;

        startGrids(2);

        awaitPartitionMapExchange();

        Ignite g0 = grid(0);

        IgniteDataStreamer<Integer, BinaryObject> dataLdr = g0.dataStreamer(DEFAULT_CACHE_NAME);

        for (int i = 0; i < 500; i++) {
            BinaryObjectBuilder obj = g0.binary().builder("NoExistedClass");

            obj.setField("id", i);
            obj.setField("name", "name = " + i);

            dataLdr.addData(i, obj.build());
        }

        dataLdr.close(false);

        assertEquals(500, g0.cache(DEFAULT_CACHE_NAME).size(CachePeekMode.ALL));
        assertEquals(500, grid(1).cache(DEFAULT_CACHE_NAME).size(CachePeekMode.ALL));
    }
    finally {
        G.stopAll(true);
    }
}
 
Example 13
Source File: BinaryObjectBuilderDefaultMappersSelfTest.java    From ignite with Apache License 2.0 5 votes vote down vote up
/**
 * @throws Exception If failed.
 */
@Test
public void testLongField() throws Exception {
    BinaryObjectBuilder builder = builder("Class");

    builder.setField("longField", 1L);

    BinaryObject po = builder.build();

    assertEquals(expectedHashCode("Class"), po.type().typeId());
    assertEquals(BinaryArrayIdentityResolver.instance().hashCode(po), po.hashCode());

    assertEquals(1L, po.<Long>field("longField").longValue());
}
 
Example 14
Source File: BinaryObjectBuilderDefaultMappersSelfTest.java    From ignite with Apache License 2.0 5 votes vote down vote up
/**
 * @throws Exception If failed.
 */
@Test
public void testFloatArrayField() throws Exception {
    BinaryObjectBuilder builder = builder("Class");

    builder.setField("floatArrayField", new float[] {1, 2, 3});

    BinaryObject po = builder.build();

    assertEquals(expectedHashCode("Class"), po.type().typeId());
    assertEquals(BinaryArrayIdentityResolver.instance().hashCode(po), po.hashCode());

    assertTrue(Arrays.equals(new float[] {1, 2, 3}, po.<float[]>field("floatArrayField")));
}
 
Example 15
Source File: BinaryMetadataRemoveTest.java    From ignite with Apache License 2.0 4 votes vote down vote up
/**
 * Tests remove type metadata at all nodes (coordinator, server, client).
 */
@Test
public void testRemoveTypeOnNodes() throws Exception {
    List<IgniteEx[]> testNodeSets = new ArrayList<>();

    // Add all servers permutations to tests sets.
    for (Ignite ign0 : G.allGrids()) {
        for (Ignite ign1 : G.allGrids()) {
            for (Ignite ign2 : G.allGrids()) {
                IgniteEx ignx0 = (IgniteEx)ign0;
                IgniteEx ignx1 = (IgniteEx)ign1;
                IgniteEx ignx2 = (IgniteEx)ign2;

                if (!ignx0.context().clientNode()
                    && !ignx1.context().clientNode()
                    && !ignx2.context().clientNode())
                    testNodeSets.add(new IgniteEx[] {ignx0, ignx1, ignx2});
            }
        }
    }

    testNodeSets.add(new IgniteEx[] {grid("srv0"), grid("cli0"), grid("cli0")});
    testNodeSets.add(new IgniteEx[] {grid("cli0"), grid("cli0"), grid("cli0")});
    testNodeSets.add(new IgniteEx[] {grid("cli0"), grid("cli1"), grid("cli2")});

    for (IgniteEx[] testNodeSet : testNodeSets) {
        IgniteEx ignCreateType = testNodeSet[0];
        IgniteEx ignRemoveType = testNodeSet[1];
        IgniteEx ignRecreateType = testNodeSet[2];

        log.info("+++ Check [createOn=" + ignCreateType.name() +
            ", removeOn=" + ignRemoveType.name() + ", recreateOn=" + ignRecreateType.name());

        BinaryObjectBuilder builder0 = ignCreateType.binary().builder("Type0");

        builder0.setField("f", 1);
        builder0.build();

        delayIfClient(ignCreateType, ignRemoveType, ignRecreateType);

        removeType(ignRemoveType, "Type0");

        delayIfClient(ignCreateType, ignRemoveType, ignRecreateType);

        BinaryObjectBuilder builder1 = ignRecreateType.binary().builder("Type0");
        builder1.setField("f", "string");
        builder1.build();

        delayIfClient(ignCreateType, ignRemoveType, ignRecreateType);

        // Remove type at the end of test case.
        removeType(grid("srv0"), "Type0");

        delayIfClient(ignCreateType, ignRemoveType, ignRecreateType);
    }
}
 
Example 16
Source File: AbstractJdbcPojoQuerySelfTest.java    From ignite with Apache License 2.0 4 votes vote down vote up
/** {@inheritDoc} */
@Override protected void beforeTestsStarted() throws Exception {
    Ignite ignite = startGrid(0);

    BinaryObjectBuilder builder = ignite.binary().builder(TEST_OBJECT);
    BinaryObjectBuilder builder2 = ignite.binary().builder(TEST_OBJECT_2);

    builder2.setField("id", 1);
    builder2.setField("boolVal", true);

    BinaryObject testObject = builder2.build();

    builder.setField("id", 1);
    builder.setField("testObject", testObject);

    BinaryObject binObj = builder.build();

    IgniteCache<String, BinaryObject> cache = grid(0).cache(DEFAULT_CACHE_NAME);

    cache.put("0", binObj);
}
 
Example 17
Source File: BinaryObjectBuilderDefaultMappersSelfTest.java    From ignite with Apache License 2.0 4 votes vote down vote up
/**
 * @throws Exception If failed.
 */
@Test
public void testOffheapBinary() throws Exception {
    BinaryObjectBuilder builder = builder("Class");

    builder.setField("i", 111);
    builder.setField("f", 111.111f);
    builder.setField("iArr", new int[] {1, 2, 3});
    builder.setField("obj", new Key(1));
    builder.setField("col", Arrays.asList(new Value(1), new Value(2)), Collection.class);

    BinaryObject po = builder.build();

    byte[] arr = ((CacheObjectBinaryProcessorImpl)(grid(0)).context().cacheObjects()).marshal(po);

    long ptr = GridUnsafe.allocateMemory(arr.length + 5);

    try {
        long ptr0 = ptr;

        GridUnsafe.putBoolean(null, ptr0++, false);

        int len = arr.length;

        if (BIG_ENDIAN)
            GridUnsafe.putIntLE(ptr0, len);
        else
            GridUnsafe.putInt(ptr0, len);

        GridUnsafe.copyHeapOffheap(arr, GridUnsafe.BYTE_ARR_OFF, ptr0 + 4, arr.length);

        BinaryObject offheapObj = (BinaryObject)
            ((CacheObjectBinaryProcessorImpl)(grid(0)).context().cacheObjects()).unmarshal(ptr, false);

        assertEquals(BinaryObjectOffheapImpl.class, offheapObj.getClass());

        assertEquals(expectedHashCode("Class"), offheapObj.type().typeId());
        assertEquals(BinaryArrayIdentityResolver.instance().hashCode(po), offheapObj.hashCode());

        assertEquals(111, offheapObj.<Integer>field("i").intValue());
        assertEquals(111.111f, offheapObj.<Float>field("f").floatValue(), 0);
        assertTrue(Arrays.equals(new int[] {1, 2, 3}, offheapObj.<int[]>field("iArr")));
        assertEquals(1, offheapObj.<BinaryObject>field("obj").<Key>deserialize().i);

        List<BinaryObject> list = offheapObj.field("col");

        assertEquals(2, list.size());

        assertEquals(1, list.get(0).<Value>deserialize().i);
        assertEquals(2, list.get(1).<Value>deserialize().i);

        assertEquals(po, offheapObj);
        assertEquals(offheapObj, po);
    }
    finally {
        GridUnsafe.freeMemory(ptr);
    }
}
 
Example 18
Source File: BinaryTypeRegistrationTest.java    From ignite with Apache License 2.0 3 votes vote down vote up
/**
 * Register binary type.
 *
 * @param ignite Ignate instance.
 * @param fieldName Field name of new object.
 */
private static void register(Ignite ignite, String fieldName) {
    IgniteBinary binary = ignite.binary();

    BinaryObjectBuilder builder = binary.builder("TestType");

    builder.setField(fieldName, 1);

    builder.build();
}
 
Example 19
Source File: BinaryMetadataRemoveWithPersistenceTest.java    From ignite with Apache License 2.0 3 votes vote down vote up
/**
 * Remove type metadata and restart cluster.
 */
@Test
public void testRemoveTypeAndClusterRestart() throws Exception {
    for (String nodeName : new String[]{"srv0", "srv2", "cli0"}) {
        log.info("+++ Check on " + nodeName);

        BinaryObjectBuilder builder0 = grid(nodeName).binary().builder("Type0");

        builder0.setField("f", 1);
        builder0.build();

        delayIfClient(grid(nodeName));

        removeType(grid(nodeName), "Type0");

        delayIfClient(grid(nodeName));

        stopAllGrids();

        startCluster();

        BinaryObjectBuilder builder1 = grid(nodeName).binary().builder("Type0");
        builder1.setField("f", "string");
        builder1.build();

        delayIfClient(grid(nodeName));

        removeType(grid(nodeName), "Type0");

        delayIfClient(grid(nodeName));
    }
}
 
Example 20
Source File: IgniteSqlCreateTableTemplateTest.java    From ignite with Apache License 2.0 2 votes vote down vote up
/**
 * Tests select statement works on a table with BinaryObject as a primary key.
 */
@Test
public void testSelectForTableWithDataInsertedWithKeyValueAPI() {
    Ignite ignite = grid();
    IgniteCache cache = ignite.getOrCreateCache("test");

    createTable(cache, "PERSON", "DEFAULT_TEMPLATE");

    createTable(cache, "ORGANIZATION", "DEFAULT_TEMPLATE");

    BinaryObjectBuilder keyBuilder = ignite.binary().builder("PERSON_KEY");

    keyBuilder.setField("ID", 1);
    keyBuilder.setField("AFF_PERSON", 2);

    BinaryObjectBuilder valueBuilder = ignite.binary().builder("PERSON_VALUE");
    valueBuilder.setField("NAME", "test");

    ignite.cache("PERSON_CACHE").withKeepBinary().put(keyBuilder.build(), valueBuilder.build());

    keyBuilder = ignite.binary().builder("ORGANIZATION_KEY");

    keyBuilder.setField("ID", 1);
    keyBuilder.setField("AFF_ORGANIZATION", 2);

    valueBuilder = ignite.binary().builder("ORGANIZATION_VALUE");

    valueBuilder.setField("NAME", "test");

    ignite.cache("ORGANIZATION_CACHE").withKeepBinary().put(keyBuilder.build(), valueBuilder.build());

    assertEquals(1, ignite.cache("PERSON_CACHE").query(
        new SqlFieldsQuery("Select NAME from PERSON where ID = 1")).getAll().size()
    );

    assertEquals(1, ignite.cache("PERSON_CACHE").query(
        new SqlFieldsQuery("Select NAME from PERSON where AFF_PERSON = 2")).getAll().size()
    );

    assertEquals(1, ignite.cache("ORGANIZATION_CACHE").query(
        new SqlFieldsQuery("Select NAME from ORGANIZATION where AFF_ORGANIZATION = 2")).getAll().size()
    );

}