下面列出了org.hibernate.dialect.lock.LockingStrategyException#org.apache.ignite.binary.BinaryObject 实例代码,或者点击链接到github查看源代码,也可以在右侧发表评论。
/** */
private void assertBinaryObjectsEqual(BinaryObject exp, BinaryObject actual) throws Exception {
assertBinaryTypesEqual(exp.type(), actual.type());
for (String f : exp.type().fieldNames()) {
Object expVal = exp.field(f);
Class<?> cls = expVal.getClass();
if (cls.getMethod("equals", Object.class).getDeclaringClass() == cls)
assertEquals(expVal, actual.field(f));
}
if (exp.type().isEnum())
assertEquals(exp.enumOrdinal(), actual.enumOrdinal());
}
/**
* @throws Exception If failed.
*/
@Test
public void testGetAsync() throws Exception {
IgniteCache<Integer, TestObject> c = jcache(0);
for (int i = 0; i < ENTRY_CNT; i++)
c.put(i, new TestObject(i));
for (int i = 0; i < ENTRY_CNT; i++) {
TestObject obj = c.getAsync(i).get();
assertNotNull(obj);
assertEquals(i, obj.val);
}
IgniteCache<Integer, BinaryObject> kpc = keepBinaryCache();
for (int i = 0; i < ENTRY_CNT; i++) {
BinaryObject po = kpc.getAsync(i).get();
assertEquals(i, (int)po.field("val"));
}
}
/**
* @param o Object.
* @return String representation of value.
*/
private static String valueOf(Object o) {
if (o == null)
return "null";
if (o instanceof byte[])
return "size=" + ((byte[])o).length;
if (o instanceof Byte[])
return "size=" + ((Byte[])o).length;
if (o instanceof Object[])
return "size=" + ((Object[])o).length + ", values=[" + mkString((Object[])o, 120) + "]";
if (o instanceof BinaryObject)
return binaryToString((BinaryObject)o);
return o.toString();
}
/**
* @throws Exception If failed.
*/
@Test
public void testBinaryObject() throws Exception {
BinaryMarshaller marsh = binaryMarshaller(Arrays.asList(new BinaryTypeConfiguration(SimpleObject.class.getName())));
SimpleObject obj = simpleObject();
BinaryObject po = marshal(obj, marsh);
BinaryObject po0 = marshalUnmarshal(po, marsh);
assertTrue(po.hasField("b"));
assertTrue(po.hasField("s"));
assertTrue(po.hasField("i"));
assertTrue(po.hasField("l"));
assertTrue(po.hasField("f"));
assertTrue(po.hasField("d"));
assertTrue(po.hasField("c"));
assertTrue(po.hasField("bool"));
assertFalse(po.hasField("no_such_field"));
assertEquals(obj, po.deserialize());
assertEquals(obj, po0.deserialize());
}
/**
* @param cache Cache.
* @param i Key.
* @param oneEntry If {@code true} then single entry is tested.
*/
private void checkBinaryRemoved(IgniteCache<Integer, TestValue> cache, int i, boolean oneEntry) {
IgniteCache<Integer, BinaryObject> cacheB = cache.withKeepBinary();
if (oneEntry) {
CacheEntry<Integer, BinaryObject> e = cacheB.getEntry(i);
assertNull(e);
}
else {
Set<Integer> set = new HashSet<>();
for (int j = 0; j < 10; j++)
set.add(i + j);
Collection<CacheEntry<Integer, BinaryObject>> es = cacheB.getEntries(set);
assertTrue(es.isEmpty());
}
}
/** {@inheritDoc} */
@Override public boolean apply(GridCacheEntryEx e) {
CacheObject val = peekVisibleValue(e);
if (this.val == null && val == null)
return true;
if (this.val == null || val == null)
return false;
GridCacheContext cctx = e.context();
if (this.val instanceof BinaryObject && val instanceof BinaryObject)
return F.eq(val, this.val);
Object thisVal = CU.value(this.val, cctx, false);
Object cacheVal = CU.value(val, cctx, false);
return F.eq(thisVal, cacheVal);
}
/**
*
*/
@SuppressWarnings("unchecked")
@Test
public void testCopyFromInnerObjects() {
ArrayList<Object> list = new ArrayList<>();
list.add(new GridBinaryTestClasses.TestObjectAllTypes());
list.add(list.get(0));
GridBinaryTestClasses.TestObjectContainer c = new GridBinaryTestClasses.TestObjectContainer(list);
BinaryObjectBuilderImpl builder = builder(toBinary(c));
builder.<List>getField("foo").add("!!!");
BinaryObject res = builder.build();
GridBinaryTestClasses.TestObjectContainer deserialized = res.deserialize();
List deserializedList = (List)deserialized.foo;
assertSame(deserializedList.get(0), deserializedList.get(1));
assertEquals("!!!", deserializedList.get(2));
assertTrue(deserializedList.get(0) instanceof GridBinaryTestClasses.TestObjectAllTypes);
}
/** {@inheritDoc} */
@Override public Object unwrappedValue() {
try {
if (val == null)
return null;
if (keepBinary && val instanceof BinaryObject)
return val;
return val.value(cacheObjValCtx, false);
}
catch (Exception e) {
cacheObjValCtx.kernalContext().log(UnwrapMvccDataEntry.class)
.error("Unable to convert value [" + value() + "]", e);
return null;
}
}
/** {@inheritDoc} */
@Override public RecommendationDatasetData<Serializable, Serializable> build(LearningEnvironment env,
Iterator<UpstreamEntry<Object, BinaryObject>> upstreamData, long upstreamDataSize, EmptyContext ctx) {
List<ObjectSubjectRatingTriplet<Serializable, Serializable>> ratings = new ArrayList<>();
while (upstreamData.hasNext()) {
UpstreamEntry<Object, BinaryObject> e = upstreamData.next();
BinaryObject val = e.getValue();
Serializable objId = val.field(objFieldName);
Serializable subjId = val.field(subjFieldName);
Number rating = val.field(ratingFieldName);
ratings.add(new ObjectSubjectRatingTriplet<>(objId, subjId, rating.doubleValue()));
}
return new RecommendationDatasetData<>(ratings);
}
/** {@inheritDoc} */
@Override protected Collection<? extends ComputeJob> split(
int gridSize,
Collection<BinaryObject> arg
) {
Collection<ComputeClientJob> jobs = new ArrayList<>();
Collection<BinaryObject> employees = new ArrayList<>();
// Split provided collection into batches and
// create a job for each batch.
for (BinaryObject employee : arg) {
employees.add(employee);
if (employees.size() == 3) {
jobs.add(new ComputeClientJob(employees));
employees = new ArrayList<>(3);
}
}
if (!employees.isEmpty())
jobs.add(new ComputeClientJob(employees));
return jobs;
}
/** {@inheritDoc} */
@Override public Object unwrappedKey() {
try {
if (keepBinary && key instanceof BinaryObject)
return key;
Object unwrapped = key.value(cacheObjValCtx, false);
if (unwrapped instanceof BinaryObject) {
if (keepBinary)
return unwrapped;
unwrapped = ((BinaryObject)unwrapped).deserialize();
}
return unwrapped;
}
catch (Exception e) {
cacheObjValCtx.kernalContext().log(UnwrapMvccDataEntry.class)
.error("Unable to convert key [" + key + "]", e);
return null;
}
}
/** {@inheritDoc} */
@SuppressWarnings("unchecked")
@Override public void clear(int batchSize) throws IgniteException {
A.ensure(batchSize >= 0, "Batch size cannot be negative: " + batchSize);
try {
Object obj = cache.invoke(queueKey, new ClearProcessor(id)).get();
if (obj == null)
return;
IgniteBiTuple<Long, Long> t = obj instanceof BinaryObject ? ((BinaryObject)obj).deserialize()
: (IgniteBiTuple<Long, Long>)obj;
checkRemoved(t.get1());
removeKeys(cache, id, queueName, collocated, t.get1(), t.get2(), batchSize);
}
catch (IgniteCheckedException e) {
throw U.convertException(e);
}
}
/** */
protected void loadData(IgniteEx node, int start, int end) {
try (IgniteDataStreamer<Object, Object> streamer = node.dataStreamer(POI_CACHE_NAME)) {
Random rnd = ThreadLocalRandom.current();
for (int i = start; i < end; i++) {
BinaryObject bo = node.binary().builder(POI_CLASS_NAME)
.setField(NAME_FIELD_NAME, "POI_" + i, String.class)
.setField(LATITUDE_FIELD_NAME, rnd.nextDouble(), Double.class)
.setField(LONGITUDE_FIELD_NAME, rnd.nextDouble(), Double.class)
.build();
streamer.addData(i, bo);
}
}
}
/** */
protected void performQueryingIntegrityCheck(Ignite ig, int key) throws Exception {
IgniteCache<Object, Object> cache = ig.cache(POI_CACHE_NAME).withKeepBinary();
String sql = String.format("DELETE FROM %s WHERE %s = %d", POI_TABLE_NAME, ID_FIELD_NAME, key);
List<List<?>> res = cache.query(new SqlFieldsQuery(sql).setSchema(POI_SCHEMA_NAME)).getAll();
assertEquals(1, res.size());
assertNull(cache.get(key));
sql = String.format("INSERT INTO %s(%s) VALUES (%s)", POI_TABLE_NAME,
String.join(",", ID_FIELD_NAME, NAME_FIELD_NAME), String.join(",", String.valueOf(key), "'test'"));
res = cache.query(new SqlFieldsQuery(sql).setSchema(POI_SCHEMA_NAME)).getAll();
assertEquals(1, res.size());
assertNotNull(cache.get(key));
sql = String.format("UPDATE %s SET %s = '%s' WHERE ID = %d", POI_TABLE_NAME, NAME_FIELD_NAME, "POI_" + key, key);
res = cache.query(new SqlFieldsQuery(sql).setSchema(POI_SCHEMA_NAME)).getAll();
assertEquals(1, res.size());
assertEquals("POI_" + key, ((BinaryObject)cache.get(key)).field(NAME_FIELD_NAME));
assertIndexUsed(cache, "SELECT * FROM " + POI_TABLE_NAME + " WHERE ID = " + key, KEY_PK_IDX_NAME);
}
/**
* Queries employees that work for organization with provided name.
*
* @param cache Ignite cache.
*/
private static void sqlJoinQuery(IgniteCache<BinaryObject, BinaryObject> cache) {
SqlFieldsQuery qry = new SqlFieldsQuery(
"select e.* from Employee e, \"" + ORGANIZATION_CACHE_NAME + "\".Organization as org " +
"where e.organizationId = org.keyId and org.name = ?");
String organizationName = "GridGain";
QueryCursor<List<?>> employees = cache.query(qry.setArgs(organizationName));
System.out.println();
System.out.println(">>> Employees working for " + organizationName + ':');
for (List<?> row : employees.getAll())
System.out.println(">>> " + row);
}
/**
*
*/
@SuppressWarnings("unchecked")
@Test
public void testCrossFormatObjectsIdentity() {
IgniteCache c = binKeysCache();
c.put(new ComplexBinaryFieldsListHashedKey(), "zzz");
// Now let's build an identical key for get
BinaryObjectBuilder bldr = grid(0).binary().builder(ComplexBinaryFieldsListHashedKey.class.getName());
bldr.setField("firstField", 1);
bldr.setField("secondField", "value");
bldr.setField("thirdField", 0x1020304050607080L);
BinaryObject binKey = bldr.build();
assertEquals("zzz", c.get(binKey));
}
/**
* @throws Exception If failed.
*/
@Test
public void testCharField() throws Exception {
BinaryObjectBuilder builder = builder("Class");
builder.setField("charField", (char)1);
BinaryObject po = builder.build();
assertEquals(expectedHashCode("Class"), po.type().typeId());
assertEquals(BinaryArrayIdentityResolver.instance().hashCode(po), po.hashCode());
assertEquals((char)1, po.<Character>field("charField").charValue());
}
/**
* @param id person id.
* @return Name for person with given id currently stored in cache.
*/
protected String nameForIdInCache(int id) {
Object o = cache().withKeepBinary().get(id);
assertTrue(String.valueOf(o), o instanceof BinaryObject);
return ((BinaryObject)o).field("name");
}
@Override
public boolean evaluate(CacheEntryEvent<?, ? extends BinaryObject> evt) throws CacheEntryListenerException {
Affinity<Object> affinity = ignite.affinity(evt.getSource().getName());
if (evt.getEventType().equals(EventType.CREATED) || evt.getEventType().equals(EventType.UPDATED) && affinity.isPrimary(ignite.cluster().localNode(), evt.getKey())) {
// Process this event. Ignored on backups.
return filter == null || !filter.apply(evt);
}
return false;
}
/**
* Queries names and salaries for all employees.
*
* @param cache Ignite cache.
*/
private static void sqlFieldsQuery(IgniteCache<BinaryObject, BinaryObject> cache) {
SqlFieldsQuery qry = new SqlFieldsQuery("select name, salary from Employee");
QueryCursor<List<?>> employees = cache.query(qry);
System.out.println();
System.out.println(">>> Employee names and their salaries:");
for (List<?> row : employees.getAll())
System.out.println(">>> [Name=" + row.get(0) + ", salary=" + row.get(1) + ']');
}
/** {@inheritDoc} */
@Override public void onAfterPut(Cache.Entry<BinaryObject, BinaryObject> entry) {
System.out.println("After put [e=" + entry + ']');
onAfterPut++;
assertEquals(1, (int)entry.getKey().field("key"));
assertEquals(10, (int)entry.getValue().field("val"));
}
/** {@inheritDoc} */
@Override public boolean test(Map<Object, Object> ctx) throws Exception {
ThreadLocalRandom rnd = ThreadLocalRandom.current();
if (rnd.nextBoolean()) {
double salary = rnd.nextDouble() * args.range() * 1000;
double maxSalary = salary + 1000;
Collection<Cache.Entry<Integer, Object>> entries = executeQuery(salary, maxSalary);
for (Cache.Entry<Integer, Object> entry : entries) {
Object o = entry.getValue();
double s = o instanceof Person ? ((Person) o).getSalary() : ((BinaryObject) o).<Double>field("salary");
if (s < salary || s > maxSalary)
throw new Exception("Invalid person retrieved [min=" + salary + ", max=" + maxSalary +
", person=" + o + ']');
}
qryCnt.getAndIncrement();
}
else {
int i = rnd.nextInt(args.range());
cache.query(new SqlFieldsQuery("merge into Person(_key, id, firstName, lastName, salary) " +
"values (?, ?, ?, ?, ?)").setArgs(i, i, "firstName" + i, "lastName" + i, (double) i * 1000));
putCnt.getAndIncrement();
}
return true;
}
/**
* @throws Exception If failed.
*/
@Test
public void testByteArrayField() throws Exception {
BinaryObjectBuilder builder = builder("Class");
builder.setField("byteArrayField", new byte[] {1, 2, 3});
BinaryObject po = builder.build();
assertEquals(expectedHashCode("Class"), po.type().typeId());
assertEquals(BinaryArrayIdentityResolver.instance().hashCode(po), po.hashCode());
assertTrue(Arrays.equals(new byte[] {1, 2, 3}, po.<byte[]>field("byteArrayField")));
}
/**
* Ensure that object w/o schema can be re-built.
*/
@Test
public void testBuildFromObjectWithoutSchema() {
BinaryObjectBuilderImpl binBuilder = wrap(new GridBinaryTestClass2());
BinaryObject binObj = binBuilder.build();
BinaryObjectBuilderImpl binBuilder2 = wrap(binObj);
binBuilder2.build();
}
/** {@inheritDoc} */
@Override public BinaryObject buildEnum(String typeName, int ord) {
guard();
try {
return proc.buildEnum(typeName, ord);
}
finally {
unguard();
}
}
@Override
public Tuple getTuple(EntityKey key, OperationContext operationContext) {
IgniteCache<Object, BinaryObject> entityCache = provider.getEntityCache( key.getMetadata() );
Object id = provider.createKeyObject( key );
BinaryObject bo = entityCache.get( id );
if ( bo != null ) {
return new Tuple( new IgniteTupleSnapshot( id, bo, key.getMetadata() ), SnapshotType.UPDATE );
}
else {
return null;
}
}
@Override
public void insertOrUpdateTuple(EntityKey key, TuplePointer tuplePointer, TupleContext tupleContext) throws TupleAlreadyExistsException {
IgniteCache<Object, BinaryObject> entityCache = provider.getEntityCache( key.getMetadata() );
Tuple tuple = tuplePointer.getTuple();
Object keyObject = null;
BinaryObjectBuilder builder = null;
IgniteTupleSnapshot tupleSnapshot = (IgniteTupleSnapshot) tuple.getSnapshot();
keyObject = tupleSnapshot.getCacheKey();
if ( tuple.getSnapshotType() == SnapshotType.UPDATE ) {
builder = provider.createBinaryObjectBuilder( tupleSnapshot.getCacheValue() );
}
else {
builder = provider.createBinaryObjectBuilder( provider.getEntityTypeName( key.getMetadata().getTable() ) );
}
for ( String columnName : tuple.getColumnNames() ) {
Object value = tuple.get( columnName );
if ( value != null ) {
builder.setField( StringHelper.realColumnName( columnName ), value );
}
else {
builder.removeField( StringHelper.realColumnName( columnName ) );
}
}
BinaryObject valueObject = builder.build();
entityCache.put( keyObject, valueObject );
tuplePointer.setTuple( new Tuple( new IgniteTupleSnapshot( keyObject, valueObject, key.getMetadata() ), SnapshotType.UPDATE ) );
}
/**
* @throws Exception If failed.
*/
@Test
public void testBinaryCopyNonPrimitives() throws Exception {
BinaryMarshaller marsh = binaryMarshaller(Arrays.asList(
new BinaryTypeConfiguration(SimpleObject.class.getName())
));
SimpleObject obj = simpleObject();
BinaryObject po = marshal(obj, marsh);
Map<String, Object> map = new HashMap<>(3, 1.0f);
SimpleObject newObj = new SimpleObject();
newObj.i = 12345;
newObj.fArr = new float[] {5, 8, 0};
newObj.str = "newStr";
map.put("str", "str555");
map.put("inner", newObj);
map.put("bArr", new byte[] {6, 7, 9});
BinaryObject copy = copy(po, map);
assertEquals("str555", copy.<String>field("str"));
assertEquals(newObj, copy.<BinaryObject>field("inner").deserialize());
assertArrayEquals(new byte[] {6, 7, 9}, copy.<byte[]>field("bArr"));
SimpleObject obj0 = copy.deserialize();
assertEquals("str555", obj0.str);
assertEquals(newObj, obj0.inner);
assertArrayEquals(new byte[] {6, 7, 9}, obj0.bArr);
}
/** {@inheritDoc} */
@Nullable @Override public V onBeforePut(Cache.Entry<K, V> e, V newVal) {
if (validate) {
validateEntry(e);
if (newVal != null)
assertFalse("NewVal: " + newVal, newVal instanceof BinaryObject);
}
return newVal;
}
/**
* 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);
}
}