PageRenderTime 63ms CodeModel.GetById 17ms app.highlight 41ms RepoModel.GetById 1ms app.codeStats 0ms

/hazelcast/src/main/java/com/hazelcast/impl/TestUtil.java

https://bitbucket.org/gabral6_gmailcom/hazelcast
Java | 708 lines | 565 code | 128 blank | 15 comment | 66 complexity | cdf53d3a87797fee377c517796bff532 MD5 | raw file
  1/*
  2 * Copyright (c) 2008-2013, Hazelcast, Inc. All Rights Reserved.
  3 *
  4 * Licensed under the Apache License, Version 2.0 (the "License");
  5 * you may not use this file except in compliance with the License.
  6 * You may obtain a copy of the License at
  7 *
  8 * http://www.apache.org/licenses/LICENSE-2.0
  9 *
 10 * Unless required by applicable law or agreed to in writing, software
 11 * distributed under the License is distributed on an "AS IS" BASIS,
 12 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 13 * See the License for the specific language governing permissions and
 14 * limitations under the License.
 15 */
 16
 17package com.hazelcast.impl;
 18
 19import com.hazelcast.config.Config;
 20import com.hazelcast.core.*;
 21import com.hazelcast.impl.partition.PartitionInfo;
 22import com.hazelcast.impl.partition.PartitionListener;
 23import com.hazelcast.impl.partition.PartitionReplicaChangeEvent;
 24import com.hazelcast.nio.Address;
 25import com.hazelcast.nio.Data;
 26import com.hazelcast.partition.MigrationEvent;
 27import com.hazelcast.partition.MigrationListener;
 28import com.hazelcast.partition.Partition;
 29import com.hazelcast.partition.PartitionService;
 30import org.junit.Ignore;
 31
 32import java.io.Serializable;
 33import java.sql.Timestamp;
 34import java.util.Date;
 35import java.util.concurrent.Callable;
 36import java.util.concurrent.CountDownLatch;
 37import java.util.concurrent.TimeUnit;
 38
 39import static com.hazelcast.nio.IOUtil.toData;
 40import static junit.framework.Assert.assertEquals;
 41import static junit.framework.Assert.assertTrue;
 42import static org.mockito.Mockito.mock;
 43
 44@Ignore
 45public class TestUtil {
 46
 47    public static boolean migrateKey(Object key, HazelcastInstance oldest, HazelcastInstance to, final int replicaIndex) throws Exception {
 48        final int partitionId = oldest.getPartitionService().getPartition(key).getPartitionId();
 49        final ConcurrentMapManager concurrentMapManagerOldest = getConcurrentMapManager(oldest);
 50        final ConcurrentMapManager concurrentMapManagerTo = getConcurrentMapManager(to);
 51        final PartitionInfo partitionInfoOldest = concurrentMapManagerOldest.getPartitionInfo(partitionId);
 52        final PartitionInfo partitionInfoTo = concurrentMapManagerTo.getPartitionInfo(partitionId);
 53        final MemberImpl currentOwnerMember = concurrentMapManagerOldest.getMember(partitionInfoOldest.getReplicaAddress(replicaIndex));
 54        final MemberImpl toMember = (MemberImpl) to.getCluster().getLocalMember();
 55        if (!currentOwnerMember.equals(toMember)) {
 56            final Address addressCurrentOwner = currentOwnerMember.getAddress();
 57            final Address addressNewOwner = toMember.getAddress();
 58            PartitionListenerLatch latchOldest = new PartitionListenerLatch(toMember.getAddress(), partitionId, replicaIndex);
 59            PartitionListenerLatch latchTo = new PartitionListenerLatch(toMember.getAddress(), partitionId, replicaIndex);
 60            concurrentMapManagerOldest.getPartitionManager().addPartitionListener(latchOldest);
 61            concurrentMapManagerTo.getPartitionManager().addPartitionListener(latchTo);
 62            concurrentMapManagerOldest.enqueueAndReturn(new Processable() {
 63                public void process() {
 64                    concurrentMapManagerOldest.partitionManager.forcePartitionOwnerMigration(partitionId, replicaIndex, addressCurrentOwner, addressNewOwner);
 65                }
 66            });
 67            assertTrue("Migration should get completed in 20 seconds!!", latchOldest.await(20, TimeUnit.SECONDS));
 68            assertTrue("Migration should get completed in 20 seconds!!", latchTo.await(20, TimeUnit.SECONDS));
 69        }
 70        assertEquals(toMember.getAddress(), partitionInfoOldest.getReplicaAddress(replicaIndex));
 71        assertEquals(toMember.getAddress(), partitionInfoTo.getReplicaAddress(replicaIndex));
 72        return true;
 73    }
 74
 75    public static class MigrationCompletionLatch implements MigrationListener {
 76        final int partitionId;
 77        final CountDownLatch latch;
 78
 79        public MigrationCompletionLatch(Object key, HazelcastInstance... h) {
 80            this.partitionId = h[0].getPartitionService().getPartition(key).getPartitionId();
 81            this.latch = new CountDownLatch(h.length);
 82            for (HazelcastInstance hazelcastInstance : h) {
 83                hazelcastInstance.getPartitionService().addMigrationListener(this);
 84            }
 85        }
 86
 87        public void migrationStarted(MigrationEvent migrationEvent) {
 88        }
 89
 90        public void migrationCompleted(MigrationEvent migrationEvent) {
 91            if (migrationEvent.getPartitionId() == partitionId) {
 92                latch.countDown();
 93            }
 94        }
 95
 96        public void migrationFailed(final MigrationEvent migrationEvent) {
 97        }
 98
 99        public boolean await(int time, TimeUnit timeUnit) throws InterruptedException {
100            return latch.await(time, timeUnit);
101        }
102    }
103
104    static class PartitionListenerLatch implements PartitionListener {
105        final CountDownLatch migrationLatch = new CountDownLatch(1);
106        final Address toAddress;
107        final int partitionId;
108        final int replicaIndex;
109
110        PartitionListenerLatch(Address toAddress, int partitionId, int replicaIndex) {
111            this.toAddress = toAddress;
112            this.partitionId = partitionId;
113            this.replicaIndex = replicaIndex;
114        }
115
116        public void replicaChanged(PartitionReplicaChangeEvent event) {
117            if (event.getReplicaIndex() == replicaIndex
118                    && event.getPartitionId() == partitionId
119                    && toAddress != null
120                    && toAddress.equals(event.getNewAddress())) {
121                migrationLatch.countDown();
122            }
123        }
124
125        public boolean await(int time, TimeUnit timeUnit) throws InterruptedException {
126            return migrationLatch.await(time, timeUnit);
127        }
128    }
129
130    public static Node getNode(HazelcastInstance h) {
131        FactoryImpl.HazelcastInstanceProxy hiProxy = (FactoryImpl.HazelcastInstanceProxy) h;
132        return hiProxy.getFactory().node;
133    }
134
135    public static ConcurrentMapManager getConcurrentMapManager(HazelcastInstance h) {
136        return getNode(h).concurrentMapManager;
137    }
138
139    public static CMap mockCMap(String name) {
140        FactoryImpl mockFactory = mock(FactoryImpl.class);
141        Node node = new Node(mockFactory, new Config());
142        node.serviceThread = Thread.currentThread();
143        return new CMap(node.concurrentMapManager, "c:" + name);
144    }
145
146    public static CMap getCMap(HazelcastInstance h, String name) {
147        ConcurrentMapManager concurrentMapManager = getConcurrentMapManager(h);
148        String fullName = Prefix.MAP + name;
149        return concurrentMapManager.getMap(fullName);
150    }
151
152    public static CMap getCMapForMultiMap(HazelcastInstance h, String name) {
153        ConcurrentMapManager concurrentMapManager = getConcurrentMapManager(h);
154        String fullName = Prefix.MULTIMAP + name;
155        return concurrentMapManager.getMap(fullName);
156    }
157
158    public static Partition getPartitionById(PartitionService partitionService, int partitionId) {
159        for (Partition partition : partitionService.getPartitions()) {
160            if (partition.getPartitionId() == partitionId) {
161                return partition;
162            }
163        }
164        return null;
165    }
166
167    public static Record newRecord(CMap cmap, long recordId, Data key, Data value) {
168        return new DefaultRecord(cmap, 1, key, value, 0, 0, recordId);
169    }
170
171    public static Record newRecord(long recordId, Data key, Data value) {
172        CMap cmap = mock(CMap.class);
173        return newRecord(cmap, recordId, key, value);
174    }
175
176    public static Record newRecord(CMap cmap, long recordId, Object key, Object value) {
177        return newRecord(cmap, recordId, toData(key), toData(value));
178    }
179
180    public static Record newRecord(long recordId, Object key, Object value) {
181        return newRecord(recordId, toData(key), toData(value));
182    }
183
184    public static Record newRecord(long recordId) {
185        return newRecord(recordId, null, null);
186    }
187
188    public static Request newPutRequest(Data key, Data value) {
189        return newPutRequest(key, value, -1);
190    }
191
192    public static Request newPutRequest(Data key, Data value, long ttl) {
193        return newRequest(ClusterOperation.CONCURRENT_MAP_PUT, key, value, ttl);
194    }
195
196    public static Request newPutIfAbsentRequest(Data key, Data value, long ttl) {
197        return newRequest(ClusterOperation.CONCURRENT_MAP_PUT_IF_ABSENT, key, value, ttl);
198    }
199
200    public static Request newRequest(ClusterOperation operation, Data key, Data value, long ttl) {
201        Request request = new Request();
202        request.setLocal(operation, null, key, value, -1, -1, ttl, null);
203        return request;
204    }
205
206    public static Request newRemoveRequest(Data key) {
207        return newRequest(ClusterOperation.CONCURRENT_MAP_REMOVE, key, null, -1);
208    }
209
210    public static Request newEvictRequest(Data key) {
211        return newRequest(ClusterOperation.CONCURRENT_MAP_EVICT, key, null, -1);
212    }
213
214    public static Request newGetRequest(Data key) {
215        return newRequest(ClusterOperation.CONCURRENT_MAP_GET, key, null, -1);
216    }
217
218    public static Request newContainsRequest(Data key, Data value) {
219        if (value == null) {
220            return newRequest(ClusterOperation.CONCURRENT_MAP_CONTAINS_KEY, key, value, -1);
221        } else {
222            return newRequest(ClusterOperation.CONCURRENT_MAP_CONTAINS_ENTRY, key, value, -1);
223        }
224    }
225
226    @Ignore
227    public static class ValueType implements Serializable {
228        String typeName;
229
230        public ValueType(String typeName) {
231            this.typeName = typeName;
232        }
233
234        public ValueType() {
235        }
236
237        public String getTypeName() {
238            return typeName;
239        }
240    }
241
242    @Ignore
243    public static abstract class AbstractValue implements Serializable {
244        public String name;
245
246        public AbstractValue(String name) {
247            this.name = name;
248        }
249
250        protected AbstractValue() {
251        }
252
253        @Override
254        public boolean equals(final Object o) {
255            if (this == o) return true;
256            if (o == null || getClass() != o.getClass()) return false;
257
258            final AbstractValue that = (AbstractValue) o;
259
260            if (name != null ? !name.equals(that.name) : that.name != null) return false;
261
262            return true;
263        }
264
265        @Override
266        public int hashCode() {
267            return name != null ? name.hashCode() : 0;
268        }
269    }
270
271    @Ignore
272    public static class Value extends AbstractValue implements Serializable {
273        ValueType type;
274        int index;
275
276        public Value(String name, ValueType type, int index) {
277            super(name);
278            this.type = type;
279            this.index = index;
280        }
281
282        public Value(String name, int index) {
283            super(name);
284            this.index = index;
285        }
286
287        public Value(String name) {
288            this(name, null, 0);
289        }
290
291        public Value() {
292            super("unknown");
293        }
294
295        public ValueType getType() {
296            return type;
297        }
298
299        public int getIndex() {
300            return index;
301        }
302
303        public void setIndex(final int index) {
304            this.index = index;
305        }
306
307        @Override
308        public boolean equals(final Object o) {
309            if (this == o) return true;
310            if (o == null || getClass() != o.getClass()) return false;
311            if (!super.equals(o)) return false;
312
313            final Value value = (Value) o;
314
315            if (index != value.index) return false;
316            if (type != null ? !type.equals(value.type) : value.type != null) return false;
317
318            return true;
319        }
320
321        @Override
322        public int hashCode() {
323            int result = super.hashCode();
324            result = 31 * result + (type != null ? type.hashCode() : 0);
325            result = 31 * result + index;
326            return result;
327        }
328
329        @Override
330        public String toString() {
331            final StringBuilder sb = new StringBuilder();
332            sb.append("Value");
333            sb.append("{name=").append(name);
334            sb.append(", index=").append(index);
335            sb.append(", type=").append(type);
336            sb.append('}');
337            return sb.toString();
338        }
339    }
340
341    @Ignore
342    public static class EmptyMapEntry implements MapEntry {
343        private long cost;
344        private long creationTime;
345        private long expirationTime;
346        private int hits;
347        private long lastAccessTime;
348        private long lastUpdateTime;
349        private long lastStoredTime;
350        private int version;
351        private boolean valid;
352        private Object key;
353        private Object value;
354        private long id;
355
356        public EmptyMapEntry(long id) {
357            this.id = id;
358        }
359
360        public long getCost() {
361            return cost;
362        }
363
364        public long getCreationTime() {
365            return creationTime;
366        }
367
368        public long getExpirationTime() {
369            return expirationTime;
370        }
371
372        public int getHits() {
373            return hits;
374        }
375
376        public long getLastAccessTime() {
377            return lastAccessTime;
378        }
379
380        public long getLastStoredTime() {
381            return lastStoredTime;
382        }
383
384        public long getLastUpdateTime() {
385            return lastUpdateTime;
386        }
387
388        public long getVersion() {
389            return version;
390        }
391
392        public boolean isValid() {
393            return valid;
394        }
395
396        public Object getKey() {
397            return key;
398        }
399
400        public Object getValue() {
401            return value;
402        }
403
404        public Object setValue(Object value) {
405            Object oldValue = this.value;
406            this.value = value;
407            return oldValue;
408        }
409
410        public void setCost(long cost) {
411            this.cost = cost;
412        }
413
414        public void setCreationTime(long creationTime) {
415            this.creationTime = creationTime;
416        }
417
418        public void setExpirationTime(long expirationTime) {
419            this.expirationTime = expirationTime;
420        }
421
422        public void setHits(int hits) {
423            this.hits = hits;
424        }
425
426        public void setKey(Object key) {
427            this.key = key;
428        }
429
430        public void setLastAccessTime(long lastAccessTime) {
431            this.lastAccessTime = lastAccessTime;
432        }
433
434        public void setLastUpdateTime(long lastUpdateTime) {
435            this.lastUpdateTime = lastUpdateTime;
436        }
437
438        public void setValid(boolean valid) {
439            this.valid = valid;
440        }
441
442        public void setVersion(int version) {
443            this.version = version;
444        }
445
446        public long getId() {
447            return id;
448        }
449
450        @Override
451        public boolean equals(Object o) {
452            if (this == o) return true;
453            if (o == null || getClass() != o.getClass()) return false;
454            EmptyMapEntry that = (EmptyMapEntry) o;
455            if (id != that.id) return false;
456            return true;
457        }
458
459        @Override
460        public int hashCode() {
461            return (int) (id ^ (id >>> 32));
462        }
463
464        @Override
465        public String toString() {
466            return "EmptyMapEntry{" +
467                    "id=" + id +
468                    ", expirationTime=" + expirationTime +
469                    ", hits=" + hits +
470                    ", lastAccessTime=" + lastAccessTime +
471                    ", lastUpdateTime=" + lastUpdateTime +
472                    ", key=" + key +
473                    ", value=" + value +
474                    ", valid=" + valid +
475                    ", creationTime=" + creationTime +
476                    ", cost=" + cost +
477                    ", version=" + version +
478                    '}';
479        }
480    }
481
482    @Ignore
483    public static class OrderUpdateRunnable implements Serializable, Runnable, PartitionAware<Integer>, HazelcastInstanceAware {
484        int customerId;
485        int orderId;
486        transient HazelcastInstance hazelcastInstance;
487
488        public OrderUpdateRunnable(int orderId, int customerId) {
489            this.customerId = customerId;
490            this.orderId = orderId;
491        }
492
493        public void run() {
494            if (!hazelcastInstance.getPartitionService().getPartition(customerId).getOwner().localMember()) {
495                throw new RuntimeException("Not local member");
496            }
497        }
498
499        public int getCustomerId() {
500            return customerId;
501        }
502
503        public int getOrderId() {
504            return orderId;
505        }
506
507        public Integer getPartitionKey() {
508            return customerId;
509        }
510
511        public void setHazelcastInstance(HazelcastInstance hazelcastInstance) {
512            this.hazelcastInstance = hazelcastInstance;
513        }
514
515        @Override
516        public String toString() {
517            return "OrderUpdateRunnable{" +
518                    "customerId=" + customerId +
519                    ", orderId=" + orderId +
520                    '}';
521        }
522    }
523
524    @Ignore
525    public static class OrderUpdateCallable implements Serializable, Callable<Boolean>, PartitionAware, HazelcastInstanceAware {
526        int customerId;
527        int orderId;
528        transient HazelcastInstance hazelcastInstance;
529
530        public OrderUpdateCallable(int orderId, int customerId) {
531            this.customerId = customerId;
532            this.orderId = orderId;
533        }
534
535        public Boolean call() throws Exception {
536            return hazelcastInstance.getPartitionService().getPartition(customerId).getOwner().localMember();
537        }
538
539        public int getCustomerId() {
540            return customerId;
541        }
542
543        public int getOrderId() {
544            return orderId;
545        }
546
547        public Object getPartitionKey() {
548            return customerId;
549        }
550
551        public void setHazelcastInstance(HazelcastInstance hazelcastInstance) {
552            this.hazelcastInstance = hazelcastInstance;
553        }
554
555        @Override
556        public String toString() {
557            return "OrderUpdateCallable{" +
558                    "customerId=" + customerId +
559                    ", orderId=" + orderId +
560                    '}';
561        }
562    }
563
564    @Ignore
565    public static class OrderKey implements Serializable, PartitionAware {
566        int customerId;
567        int orderId;
568
569        public OrderKey(int orderId, int customerId) {
570            this.customerId = customerId;
571            this.orderId = orderId;
572        }
573
574        public int getCustomerId() {
575            return customerId;
576        }
577
578        public int getOrderId() {
579            return orderId;
580        }
581
582        public Object getPartitionKey() {
583            return customerId;
584        }
585
586        @Override
587        public String toString() {
588            return "OrderKey{" +
589                    "customerId=" + customerId +
590                    ", orderId=" + orderId +
591                    '}';
592        }
593    }
594
595    public static enum State {
596        STATE1, STATE2
597    }
598
599    @Ignore
600    public static class Employee implements Serializable {
601        long id;
602        String name;
603        String city;
604        int age;
605        boolean active;
606        double salary;
607        Timestamp date;
608        Date createDate;
609        java.sql.Date sqlDate;
610        State state;
611
612        public Employee(long id, String name, int age, boolean live, double salary, State state) {
613            this.state = state;
614        }
615
616        public Employee(long id, String name, int age, boolean live, double salary) {
617            this(id, name, null, age, live, salary);
618        }
619
620        public Employee(String name, int age, boolean live, double salary) {
621            this(-1, name, age, live, salary);
622        }
623
624        public Employee(long id, String name, String city, int age, boolean live, double salary) {
625            this.id = id;
626            this.name = name;
627            this.city = city;
628            this.age = age;
629            this.active = live;
630            this.salary = salary;
631            this.createDate = new Date();
632            this.date = new Timestamp(createDate.getTime());
633            this.sqlDate = new java.sql.Date(createDate.getTime());
634        }
635
636        public Employee() {
637        }
638
639        public Timestamp getDate() {
640            return date;
641        }
642
643        public String getName() {
644            return name;
645        }
646
647        public String getCity() {
648            return city;
649        }
650
651        public int getAge() {
652            return age;
653        }
654
655        public double getSalary() {
656            return salary;
657        }
658
659        public boolean isActive() {
660            return active;
661        }
662
663        public State getState() {
664            return state;
665        }
666
667        public void setState(State state) {
668            this.state = state;
669        }
670
671        @Override
672        public boolean equals(Object o) {
673            if (this == o) return true;
674            if (o == null || getClass() != o.getClass()) return false;
675            Employee employee = (Employee) o;
676            if (active != employee.active) return false;
677            if (age != employee.age) return false;
678            if (Double.compare(employee.salary, salary) != 0) return false;
679            if (name != null ? !name.equals(employee.name) : employee.name != null) return false;
680            return true;
681        }
682
683        @Override
684        public int hashCode() {
685            int result;
686            long temp;
687            result = name != null ? name.hashCode() : 0;
688            result = 31 * result + age;
689            result = 31 * result + (active ? 1 : 0);
690            temp = salary != +0.0d ? Double.doubleToLongBits(salary) : 0L;
691            result = 31 * result + (int) (temp ^ (temp >>> 32));
692            return result;
693        }
694
695        @Override
696        public String toString() {
697            final StringBuffer sb = new StringBuffer();
698            sb.append("Employee");
699            sb.append("{name='").append(name).append('\'');
700            sb.append(", city=").append(city);
701            sb.append(", age=").append(age);
702            sb.append(", active=").append(active);
703            sb.append(", salary=").append(salary);
704            sb.append('}');
705            return sb.toString();
706        }
707    }
708}