org.apache.ignite.binary.BinaryObjectBuilder Java Examples

The following examples show how to use org.apache.ignite.binary.BinaryObjectBuilder. 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: BinaryObjectBuilderAdditionalSelfTest.java    From ignite with Apache License 2.0 6 votes vote down vote up
/**
 * @throws Exception If failed.
 */
@Test
public void testSameBinaryKey() throws Exception {
    IgniteCache<BinaryObject, BinaryObject> replicatedCache =
        jcache(0).withKeepBinary();

    IgniteCache<BinaryObject, BinaryObject> partitionedCache =
        jcache(0, "partitioned").withKeepBinary();

    BinaryObjectBuilder keyBuilder = ignite(0).binary().builder("keyType")
        .setField("F1", "V1");

    BinaryObjectBuilder valBuilder = ignite(0).binary().builder("valueType")
        .setField("F2", "V2")
        .setField("F3", "V3");

    BinaryObject key = keyBuilder.build();
    BinaryObject val = valBuilder.build();

    replicatedCache.put(key, val);
    partitionedCache.put(key, val);

    assertNotNull(replicatedCache.get(key));
    assertNotNull(partitionedCache.get(key));
}
 
Example #2
Source File: IgniteDemo.java    From banyan with MIT License 6 votes vote down vote up
@Test
public void testBroadCastBinary() {
    CacheConfiguration<Long, Foobar> cacheConf = createCacheConf();
    IgniteCache<Long, Foobar> foobarCache = ignite.getOrCreateCache(cacheConf);
    IgniteConfiguration igniteConfiguration = getIgniteConfiguration();

    IgniteCluster cluster = ignite.cluster();
    ignite.compute(cluster.forRemotes()).broadcast(() -> {

        IgniteCache<Long, BinaryObject> fooCache = Ignition.getOrStart(igniteConfiguration).getOrCreateCache("foo").withKeepBinary();

        for (Cache.Entry<Long, BinaryObject> entry : fooCache.localEntries(CachePeekMode.PRIMARY)) {
            BinaryObjectBuilder foobar = entry.getValue().toBuilder();

            Integer val = foobar.getField("val");
            foobar.setField("val", val + 1);

            fooCache.put(entry.getKey(), foobar.build());
        }
    });

    assertEquals(foobarCache.get(1L).getVal(), 7);
    assertEquals(foobarCache.get(2L).getVal(), 8);
    assertEquals(foobarCache.get(3L).getVal(), 9);
}
 
Example #3
Source File: BinaryObjectBuilderDefaultMappersSelfTest.java    From ignite with Apache License 2.0 6 votes vote down vote up
/**
 * @throws Exception If failed.
 */
@Test
public void testCollectionField() throws Exception {
    BinaryObjectBuilder builder = builder("Class");

    builder.setField("collectionField", Arrays.asList(new Value(1), new Value(2)));
    builder.setField("collectionField2", Arrays.asList(new Value(1), new Value(2)), Collection.class);

    BinaryObject po = builder.build();

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

    List<Value> list = po.field("collectionField");

    assertEquals(2, list.size());
    assertEquals(1, list.get(0).i);
    assertEquals(2, list.get(1).i);

    List<BinaryObject> list2 = po.field("collectionField2");

    assertEquals(2, list2.size());
    assertEquals(1, list2.get(0).<Value>deserialize().i);
    assertEquals(2, list2.get(1).<Value>deserialize().i);
}
 
Example #4
Source File: IgniteDatastoreProvider.java    From hibernate-ogm-ignite with GNU Lesser General Public License v2.1 6 votes vote down vote up
public Object createAssociationKeyObject( RowKey rowKey, AssociationKeyMetadata keyMetadata ) {
	Object result = null;
	if ( IgniteAssociationSnapshot.isThirdTableAssociation( keyMetadata ) ) {
		result = UUID.randomUUID().toString();
	}
	else {
		String associationKeyColumns[] = keyMetadata.getAssociatedEntityKeyMetadata().getAssociationKeyColumns();
		if ( associationKeyColumns.length == 1 ) {
			result = rowKey.getColumnValue( associationKeyColumns[0] );
		}
		else {
			BinaryObjectBuilder builder = createBinaryObjectBuilder( findKeyType( keyMetadata.getAssociatedEntityKeyMetadata().getEntityKeyMetadata() ) );
			for ( int i = 0; i < associationKeyColumns.length; i++ ) {
				builder.setField( StringHelper.stringAfterPoint( associationKeyColumns[i] ), rowKey.getColumnValue( associationKeyColumns[i] ) );
			}
			result = builder.build();
		}
	}
	return result;
}
 
Example #5
Source File: GridCacheBinaryObjectsAbstractSelfTest.java    From ignite with Apache License 2.0 6 votes vote down vote up
/**
 * @throws Exception If failed.
 */
@Test
public void testReplaceWhenEmptyValue() throws Exception {
    IgniteCache<Integer, BinaryObject> kpc = keepBinaryCache();

    BinaryObjectBuilder bldr = grid(0).binary().builder("TestObjCls");

    bldr.setField("val", -42);

    BinaryObject testObj = bldr.build();

    for (int i = 0; i < ENTRY_CNT; i++) {
        assertNull(kpc.get(i));

        assertFalse(kpc.replace(i, testObj, testObj));
    }
}
 
Example #6
Source File: SqlIncompatibleDataTypeExceptionTest.java    From ignite with Apache License 2.0 6 votes vote down vote up
/**
 *
 */
@Test
public void testUseKeyField_Allow() {
    GridTestUtils.setFieldValue(UpdatePlanBuilder.class, "ALLOW_KEY_VAL_UPDATES", true);

    execSql("CREATE TABLE test (id0 integer, id1 integer, val varchar, primary key (id0, id1))");

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

    // Invalid usage, but allowed for backward compatibility
    // when ALLOW_KEY_VAL_COLUMNS set to true
    execSql("INSERT INTO test (_key, val) VALUES (?, ?)", bob.build(), 0);

    bob.setField("id0", 1);
    bob.setField("id1", 1);
    execSql("MERGE INTO test (_key, val) VALUES (?, ?)", bob.build(), 1);
}
 
Example #7
Source File: SqlIncompatibleDataTypeExceptionTest.java    From ignite with Apache License 2.0 6 votes vote down vote up
/**
 *
 */
@Test
public void testUseValField_Allow() {
    GridTestUtils.setFieldValue(UpdatePlanBuilder.class, "ALLOW_KEY_VAL_UPDATES", true);

    execSql("CREATE TABLE test (id integer primary key, val varchar)");

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

    // Invalid usage, but allowed for backward compatibility
    // when ALLOW_KEY_VAL_COLUMNS set to true
    execSql("INSERT INTO test (id, _val) VALUES (?, ?)", 0, bob.build());
    execSql("MERGE INTO test (id, _val) VALUES (?, ?)", 0, bob.build());
    execSql("UPDATE test SET _val=?", bob.build());
}
 
Example #8
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 #9
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 #10
Source File: BinaryObjectBuilderImpl.java    From ignite with Apache License 2.0 6 votes vote down vote up
/** {@inheritDoc} */
@Override public BinaryObjectBuilder setField(String name, Object val0) {
    Object val = assignedValues().get(name);

    if (val instanceof BinaryValueWithType)
        ((BinaryValueWithType)val).value(val0);
    else {
        Class valCls = (val == null) ? Object.class : val.getClass();

        val = val0 == null ? new BinaryValueWithType(BinaryUtils.typeByClass(valCls), null) : val0;
    }

    assignedValues().put(name, val);

    return this;
}
 
Example #11
Source File: BinaryObjectBuilderAdditionalSelfTest.java    From ignite with Apache License 2.0 6 votes vote down vote up
/**
 * @throws Exception If fails
 */
@Test
public void testBuilderReusage() throws Exception {
    // Check: rewrite null field value.
    BinaryObjectBuilder builder = newWrapper("SimpleCls1");

    builder.setField("f1", null, Object.class);
    assertNull(builder.build().field("f1"));

    builder.setField("f1", "val1");
    assertEquals("val1", builder.build().field("f1"));

    // Check: rewrite non-null field value to null and back.
    builder = newWrapper("SimpleCls2");

    builder.setField("f1", "val1", String.class);
    assertEquals("val1", builder.build().field("f1"));

    builder.setField("f1", null);
    assertNull(builder.build().field("f1"));

    builder.setField("f1", "val2");
    assertEquals("val2", builder.build().field("f1"));
}
 
Example #12
Source File: GridCacheContext.java    From ignite with Apache License 2.0 6 votes vote down vote up
/**
 * Prepare affinity field for builder (if possible).
 *
 * @param builder Builder.
 */
public void prepareAffinityField(BinaryObjectBuilder builder) {
    assert binaryMarshaller();
    assert builder instanceof BinaryObjectBuilderImpl;

    BinaryObjectBuilderImpl builder0 = (BinaryObjectBuilderImpl)builder;

    if (!cacheObjCtx.customAffinityMapper()) {
        CacheDefaultBinaryAffinityKeyMapper mapper =
            (CacheDefaultBinaryAffinityKeyMapper)cacheObjCtx.defaultAffMapper();

        BinaryField field = mapper.affinityKeyField(builder0.typeId());

        if (field != null) {
            String fieldName = field.name();

            builder0.affinityFieldName(fieldName);
        }
    }
}
 
Example #13
Source File: CacheJdbcPojoStoreTest.java    From ignite with Apache License 2.0 6 votes vote down vote up
/**
 * @param obj Object.
 */
private Object wrap(Object obj) throws IllegalAccessException {
    if (binaryEnable) {
        Class<?> cls = obj.getClass();

        BinaryObjectBuilder builder = ig.binary().builder(cls.getName());

        for (Field f : cls.getDeclaredFields()) {
            if (f.getName().contains("serialVersionUID"))
                continue;

            f.setAccessible(true);

            builder.setField(f.getName(), f.get(obj));
        }

        return builder.build();
    }

    return obj;
}
 
Example #14
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 #15
Source File: BinaryObjectBuilderDefaultMappersSelfTest.java    From ignite with Apache License 2.0 5 votes vote down vote up
/**
 * @throws Exception If failed.
 */
@Test
public void testObjectField() throws Exception {
    BinaryObjectBuilder builder = builder("Class");

    builder.setField("objectField", new Value(1));

    BinaryObject po = builder.build();

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

    assertEquals(1, po.<BinaryObject>field("objectField").<Value>deserialize().i);
}
 
Example #16
Source File: AbstractBinaryMetadataRegistrationTest.java    From ignite with Apache License 2.0 5 votes vote down vote up
/**
 * Tests type registration upon writing binary objects to a cache.
 */
@Test
public void testMetadataRegisteredOnceForBinaryObject() {
    BinaryObjectBuilder builder = grid().binary().builder("TestBinaryType");

    builder.setField("testField", 1);

    checkMetadataRegisteredOnce(builder.build());
}
 
Example #17
Source File: BinaryMetadataUpdatesFlowTest.java    From ignite with Apache License 2.0 5 votes vote down vote up
/**
 * @param builder Builder.
 * @param desc Descriptor with parameters of BinaryObject to build.
 * @return BinaryObject built by provided description
 */
private static BinaryObject newBinaryObject(BinaryObjectBuilder builder, BinaryUpdateDescription desc) {
    builder.setField(SEQ_NUM_FLD, desc.itemId + 1);
    builder.setField(desc.fieldName, desc.val);

    return builder.build();
}
 
Example #18
Source File: BinaryMarshallerSelfTest.java    From ignite with Apache License 2.0 5 votes vote down vote up
/**
 * @param po Binary object.
 * @param fields Fields.
 * @return Copy.
 */
private BinaryObject copy(BinaryObject po, Map<String, Object> fields) {
    BinaryObjectBuilder builder = BinaryObjectBuilderImpl.wrap(po);

    if (fields != null) {
        for (Map.Entry<String, Object> e : fields.entrySet())
            builder.setField(e.getKey(), e.getValue());
    }

    return builder.build();
}
 
Example #19
Source File: BinaryObjectBuilderDefaultMappersSelfTest.java    From ignite with Apache License 2.0 5 votes vote down vote up
/**
 * @throws Exception If failed.
 */
@Test
public void testSeveralFields() 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();

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

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

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

    assertEquals(2, list.size());

    assertEquals(1, list.get(0).<Value>deserialize().i);
    assertEquals(2, list.get(1).<Value>deserialize().i);
}
 
Example #20
Source File: BinaryMetadataUpdatesFlowTest.java    From ignite with Apache License 2.0 5 votes vote down vote up
/** {@inheritDoc} */
@Override public Object call() throws Exception {
    startLatch.await();

    IgniteCache<Object, Object> cache = ignite.cache(DEFAULT_CACHE_NAME).withKeepBinary();

    workersCntr.incrementAndGet();

    try {
        while (!updatesQueue.isEmpty()) {
            BinaryUpdateDescription desc = updatesQueue.poll();

            if (desc == null)
                break;

            BinaryObjectBuilder builder = ignite.binary().builder(BINARY_TYPE_NAME);

            BinaryObject bo = newBinaryObject(builder, desc);

            cache.put(desc.itemId, bo);

            if (restartIdx.get() == idx)
                break;
        }
    }
    finally {
        workersCntr.decrementAndGet();

        if (restartIdx.get() == idx)
            restartIdx.set(-1);
    }

    return null;
}
 
Example #21
Source File: ClientBinary.java    From ignite with Apache License 2.0 5 votes vote down vote up
/** {@inheritDoc} */
@Override public BinaryObjectBuilder builder(BinaryObject binaryObj) {
    if (binaryObj == null)
        throw new NullPointerException("binaryObj");

    return BinaryObjectBuilderImpl.wrap(binaryObj);
}
 
Example #22
Source File: BinaryObjectBuilderImpl.java    From ignite with Apache License 2.0 5 votes vote down vote up
/** {@inheritDoc} */
@Override public <T> BinaryObjectBuilder setField(String name, @Nullable T val, Class<? super T> type) {
    byte typeId;

    if (Collection.class.equals(type))
        typeId = GridBinaryMarshaller.COL;
    else if (Map.class.equals(type))
        typeId = GridBinaryMarshaller.MAP;
    else
        typeId = BinaryUtils.typeByClass(type);

    assignedValues().put(name, new BinaryValueWithType(typeId, val));

    return this;
}
 
Example #23
Source File: BinaryObjectTypeCompatibilityTest.java    From ignite with Apache License 2.0 5 votes vote down vote up
/**
 * @throws Exception If failed.
 */
@Test
public void testCompatibilityWithObject() throws Exception {
    Ignite ignite = startGrid();

    BinaryObjectBuilder bldr = ignite.binary().builder("ObjectWrapper");
    bldr.setField("objField", new Object());
    bldr.build();

    validateMap(bldr, "objField", new HashMap<>());
    validateMap(bldr, "objField", new LinkedHashMap<>());
    validateMap(bldr, "objField", new TreeMap<>());

    validateCollection(bldr, "objField", new ArrayList<>());
    validateCollection(bldr, "objField", new LinkedList<>());
    validateCollection(bldr, "objField", new HashSet<>());
    validateCollection(bldr, "objField", new LinkedHashSet<>());
    validateCollection(bldr, "objField", new TreeSet<>());

    validate(bldr, "objField", (byte)RANDOM.nextInt());
    validate(bldr, "objField", (short)RANDOM.nextInt());
    validate(bldr, "objField", (char)RANDOM.nextInt());
    validate(bldr, "objField", RANDOM.nextInt());
    validate(bldr, "objField", RANDOM.nextLong());
    validate(bldr, "objField", RANDOM.nextFloat());
    validate(bldr, "objField", RANDOM.nextDouble());

    validate(bldr, "objField", Enum.DEFAULT);
    validate(bldr, "objField", new BigDecimal(RANDOM.nextInt()));
    validate(bldr, "objField", "Test string");
    validate(bldr, "objField", new Date());
    validate(bldr, "objField", new Timestamp(System.currentTimeMillis()));
    validate(bldr, "objField", new Time(System.currentTimeMillis()));
    validate(bldr, "objField", UUID.randomUUID());
}
 
Example #24
Source File: BinaryObjectBuilderDefaultMappersSelfTest.java    From ignite with Apache License 2.0 5 votes vote down vote up
/**
 * @throws Exception If failed.
 */
@Test
public void testDecimalArrayField() throws Exception {
    BinaryObjectBuilder builder = builder("Class");

    builder.setField("decimalArrayField", new BigDecimal[] {BigDecimal.ONE, BigDecimal.TEN});

    BinaryObject po = builder.build();

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

    assertTrue(Arrays.equals(new BigDecimal[] {BigDecimal.ONE, BigDecimal.TEN}, po.<String[]>field("decimalArrayField")));
}
 
Example #25
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 #26
Source File: IgniteBinaryImpl.java    From ignite with Apache License 2.0 5 votes vote down vote up
/** {@inheritDoc} */
@Override public BinaryObjectBuilder builder(BinaryObject binaryObj) {
    guard();

    try {
        return proc.builder(binaryObj);
    }
    finally {
        unguard();
    }
}
 
Example #27
Source File: BinaryObjectBuilderDefaultMappersSelfTest.java    From ignite with Apache License 2.0 5 votes vote down vote up
/**
 * @throws Exception If failed.
 */
@Test
public void testDoubleField() throws Exception {
    BinaryObjectBuilder builder = builder("Class");

    builder.setField("doubleField", 1.0d);

    BinaryObject po = builder.build();

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

    assertEquals(1.0d, po.<Double>field("doubleField").doubleValue(), 0);
}
 
Example #28
Source File: BinaryObjectTypeCompatibilityTest.java    From ignite with Apache License 2.0 5 votes vote down vote up
/**
 * @param bldr {@link BinaryObjectBuilder}, that will be used for testing.
 * @param fldName Name of the field being tested.
 * @param src {@link Map} object, that should be tested.
 */
private void validateMap(BinaryObjectBuilder bldr, String fldName, Map<Integer, String> src) {
    for (int i = 0; i < 1000; i++) {
        int key = RANDOM.nextInt();
        src.put(key, Integer.toString(key));
    }

    bldr.setField(fldName, src);

    BinaryObject binObj = bldr.build();

    Map<Integer, String> res = deserialize(binObj.field(fldName));

    assertEquals(src, res);
}
 
Example #29
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 #30
Source File: IgnitePdsCacheObjectBinaryProcessorOnDiscoveryTest.java    From ignite with Apache License 2.0 5 votes vote down vote up
/**
 * @param ig Ig.
 * @param typeName Type name.
 * @param fields Fields.
 */
@SafeVarargs
private final BinaryObject addBinaryType(Ignite ig, String typeName, IgniteBiTuple<String, Class<?>>... fields) {
    BinaryObjectBuilder builder = ig.binary().builder(typeName);

    if (fields != null) {
        for (IgniteBiTuple<String,Class<?>> field: fields)
            builder.setField(field.get1(), field.get2());
    }

    return builder.build();
}