public void readFrom(DataInput in) throws Exception { type = Type.values()[in.readByte()]; lock_name = Util.readString(in); owner = (Owner) Util.readStreamable(Owner.class, in); timeout = in.readLong(); is_trylock = in.readBoolean(); }
/** * Invoked upon receiving a MERGE event from the MERGE layer. Starts the merge protocol. See * description of protocol in DESIGN. * * @param views A List of <em>different</em> views detected by the merge protocol */ public void merge(Map<Address, View> views) { if (isMergeInProgress()) { if (log.isTraceEnabled()) log.trace(gms.local_addr + ": merge is already running (merge_id=" + merge_id + ")"); return; } // we need the merge *coordinators* not merge participants because not everyone can lead a merge // ! Collection<Address> coords = Util.determineMergeCoords(views); Collection<Address> merge_participants = Util.determineMergeParticipants(views); Membership tmp = new Membership(coords); // establish a deterministic order, so that coords can elect leader tmp.sort(); Address merge_leader = tmp.elementAt(0); if (log.isDebugEnabled()) log.debug("determining merge leader from " + merge_participants); if (merge_leader.equals(gms.local_addr)) { if (log.isDebugEnabled()) log.debug( "I (" + gms.local_addr + ") will be the leader. Starting the merge task for " + merge_participants); merge_task.start(views); } else { if (log.isDebugEnabled()) log.debug( "I (" + gms.local_addr + ") am not the merge leader, " + "waiting for merge leader (" + merge_leader + ") to initiate merge"); } }
/** Kicks off the benchmark on all cluster nodes */ void startBenchmark() throws Throwable { RequestOptions options = new RequestOptions(ResponseMode.GET_ALL, 0); options.setFlags(Message.OOB, Message.DONT_BUNDLE, Message.NO_FC); RspList<Object> responses = disp.callRemoteMethods(null, new MethodCall(START), options); long total_reqs = 0; long total_time = 0; System.out.println("\n======================= Results: ==========================="); for (Map.Entry<Address, Rsp<Object>> entry : responses.entrySet()) { Address mbr = entry.getKey(); Rsp rsp = entry.getValue(); Results result = (Results) rsp.getValue(); total_reqs += result.num_gets + result.num_puts; total_time += result.time; System.out.println(mbr + ": " + result); } double total_reqs_sec = total_reqs / (total_time / 1000.0); double throughput = total_reqs_sec * msg_size; double ms_per_req = total_time / (double) total_reqs; Protocol prot = channel.getProtocolStack().findProtocol(unicast_protocols); System.out.println("\n"); System.out.println( Util.bold( "Average of " + f.format(total_reqs_sec) + " requests / sec (" + Util.printBytes(throughput) + " / sec), " + f.format(ms_per_req) + " ms /request (prot=" + prot.getName() + ")")); System.out.println("\n\n"); }
/** * Do a http operation * * @param urlConnection the HttpURLConnection to be used * @param inputData if not null,will be written to the urlconnection. * @param hasOutput if true, read content back from the urlconnection * @return Response * @throws IOException */ public static HttpResponse doOperation( HttpURLConnection urlConnection, byte[] inputData, boolean hasOutput) throws IOException { HttpResponse response = null; InputStream inputStream = null; OutputStream outputStream = null; byte[] payload = null; try { if (inputData != null) { urlConnection.setDoOutput(true); outputStream = urlConnection.getOutputStream(); outputStream.write(inputData); } /* * Get response code first. HttpURLConnection does not allow to * read inputstream if response code is not success code */ int responseCode = urlConnection.getResponseCode(); if (hasOutput && isSuccessCode(responseCode)) { payload = getBytes(urlConnection.getInputStream()); } response = new HttpResponse(urlConnection.getHeaderFields(), responseCode, payload); } finally { Util.close(inputStream); Util.close(outputStream); } return response; }
/** * @param views Guaranteed to be non-null and to have >= 2 members, or else this thread would * not be started */ public synchronized void start(Map<Address, View> views) { if (thread == null || thread.isAlive()) { this.coords.clear(); // now remove all members which don't have us in their view, so RPCs won't block (e.g. // FLUSH) // https://jira.jboss.org/browse/JGRP-1061 sanitizeViews(views); // Add all different coordinators of the views into the hashmap and sets their members: Collection<Address> coordinators = Util.determineMergeCoords(views); for (Address coord : coordinators) { View view = views.get(coord); if (view != null) this.coords.put(coord, new ArrayList<Address>(view.getMembers())); } // For the merge participants which are not coordinator, we simply add them, and the // associated // membership list consists only of themselves Collection<Address> merge_participants = Util.determineMergeParticipants(views); merge_participants.removeAll(coordinators); for (Address merge_participant : merge_participants) { Collection<Address> tmp = new ArrayList<Address>(); tmp.add(merge_participant); coords.putIfAbsent(merge_participant, tmp); } thread = gms.getThreadFactory().newThread(this, "MergeTask"); thread.setDaemon(true); thread.start(); } }
public void testRegularAndOOBUnicasts2() throws Exception { DISCARD discard = new DISCARD(); ProtocolStack stack = a.getProtocolStack(); stack.insertProtocol( discard, ProtocolStack.BELOW, (Class<? extends Protocol>[]) Util.getUnicastProtocols()); Address dest = b.getAddress(); Message m1 = new Message(dest, 1); Message m2 = new Message(dest, 2).setFlag(Message.Flag.OOB); Message m3 = new Message(dest, 3).setFlag(Message.Flag.OOB); Message m4 = new Message(dest, 4); MyReceiver receiver = new MyReceiver("B"); b.setReceiver(receiver); a.send(m1); discard.setDropDownUnicasts(2); a.send(m2); // dropped a.send(m3); // dropped a.send(m4); Collection<Integer> list = receiver.getMsgs(); int count = 10; while (list.size() < 4 && --count > 0) { Util.sleep(500); // time for potential retransmission sendStableMessages(a, b); } System.out.println("list = " + list); assert list.size() == 4 : "list is " + list; assert list.contains(1) && list.contains(2) && list.contains(3) && list.contains(4); }
public void testFlushWithCrashedParticipants() throws Exception { JChannel c1 = null; JChannel c2 = null; JChannel c3 = null; try { c1 = createChannel(true, 3, "C1"); changeProps(c1); c1.connect("testFlushWithCrashedFlushCoordinator"); c2 = createChannel(c1, "C2"); changeProps(c2); c2.connect("testFlushWithCrashedFlushCoordinator"); c3 = createChannel(c1, "C3"); changeProps(c3); c3.connect("testFlushWithCrashedFlushCoordinator"); // and then kill members other than flush coordinator Util.shutdown(c3); Util.shutdown(c1); // start flush Util.startFlush(c2); c2.stopFlush(); Util.waitUntilAllChannelsHaveSameSize(10000, 500, c2); // cluster should not hang and one remaining member should have a correct view assertTrue("correct view size", c2.getView().size() == 1); } finally { Util.close(c3, c2, c1); } }
public void testWithEveryoneHavingASingletonView() throws Exception { // Inject view {A} into A, B and C: injectView(Util.createView(a.getAddress(), 10, a.getAddress()), a); injectView(Util.createView(b.getAddress(), 10, b.getAddress()), b); injectView(Util.createView(c.getAddress(), 10, c.getAddress()), c); sendAndCheckMessages(5, a, b, c); }
private void send(Address dest) throws Exception { final CountDownLatch latch = new CountDownLatch(1); final BlockingReceiver receiver = new BlockingReceiver(latch); final int NUM = 10; b.setReceiver(receiver); a.send(dest, 1); // the only regular message for (int i = 2; i <= NUM; i++) a.send(new Message(dest, i).setFlag(Message.Flag.OOB)); sendStableMessages(a, b); List<Integer> list = receiver.getMsgs(); for (int i = 0; i < 20; i++) { if (list.size() == NUM - 1) break; sendStableMessages(a, b); Util.sleep(500); // give the asynchronous msgs some time to be received } System.out.println("list = " + list); assert list.size() == NUM - 1 : "list is " + list; assert list.contains(2) && list.contains(10); System.out.println("[" + Thread.currentThread().getName() + "]: releasing latch"); latch.countDown(); for (int i = 0; i < 20; i++) { if (list.size() == NUM) break; sendStableMessages(a, b); Util.sleep(1000); // give the asynchronous msgs some time to be received } System.out.println("list = " + list); assert list.size() == NUM : "list is " + list; for (int i = 1; i <= NUM; i++) assert list.contains(i); }
protected static void start(InetAddress dest, int port, String add_server, String remove_server) throws Throwable { try (Socket sock = new Socket(dest, port); DataInputStream in = new DataInputStream(sock.getInputStream()); DataOutputStream out = new DataOutputStream(sock.getOutputStream())) { CLIENT.RequestType type = add_server != null ? CLIENT.RequestType.add_server : CLIENT.RequestType.remove_server; out.writeByte((byte) type.ordinal()); byte[] buf = Util.stringToBytes(add_server != null ? add_server : remove_server); out.writeInt(buf.length); out.write(buf, 0, buf.length); type = CLIENT.RequestType.values()[in.readByte()]; if (type != CLIENT.RequestType.rsp) throw new IllegalStateException( String.format("expected type %s but got %s", CLIENT.RequestType.rsp, type)); int len = in.readInt(); if (len == 0) return; buf = new byte[len]; in.readFully(buf); Object response = Util.objectFromByteBuffer(buf); if (response instanceof Throwable) throw (Throwable) response; System.out.println("response = " + response); } catch (Exception ex) { ex.printStackTrace(); } }
/** Callback invoked by the protocol stack to deliver a message batch */ public void up(MessageBatch batch) { if (stats) { received_msgs += batch.size(); received_bytes += batch.length(); } // discard local messages (sent by myself to me) if (discard_own_messages && local_addr != null && batch.sender() != null && local_addr.equals(batch.sender())) return; for (Message msg : batch) { if (up_handler != null) { try { up_handler.up(new Event(Event.MSG, msg)); } catch (Throwable t) { log.error(Util.getMessage("UpHandlerFailure"), t); } } else if (receiver != null) { try { receiver.receive(msg); } catch (Throwable t) { log.error(Util.getMessage("ReceiverFailure"), t); } } } }
public static void testForEach() { class MyVisitor<T> implements Table.Visitor<T> { List<int[]> list = new ArrayList<int[]>(20); public boolean visit(long seqno, T element, int row, int column) { System.out.println("#" + seqno + ": " + element + ", row=" + row + ", column=" + column); list.add(new int[] {row, column}); return true; } } MyVisitor<Integer> visitor = new MyVisitor<Integer>(); Table<Integer> table = new Table<Integer>(3, 10, 0); for (int i = 1; i <= 20; i++) table.add(i, i); System.out.println("table = " + table); table.forEach(table.getLow() + 1, table.getHighestReceived() - 1, visitor); int count = 1; for (int[] pair : visitor.list) { int row = pair[0], column = pair[1]; if (count < Util.getNextHigherPowerOfTwo(10)) { assert row == 0; assert column == count; } else { assert row == 1; assert column == count - Util.getNextHigherPowerOfTwo(10); } count++; } }
/** * Message contains MethodCall. Execute it against *this* object and return result. Use * MethodCall.invoke() to do this. Return result. */ public Object handle(Message req) throws Exception { if (server_obj == null) { log.error(Util.getMessage("NoMethodHandlerIsRegisteredDiscardingRequest")); return null; } if (req == null || req.getLength() == 0) { log.error(Util.getMessage("MessageOrMessageBufferIsNull")); return null; } Object body = req_marshaller != null ? req_marshaller.objectFromBuffer(req.getRawBuffer(), req.getOffset(), req.getLength()) : req.getObject(); if (!(body instanceof MethodCall)) throw new IllegalArgumentException("message does not contain a MethodCall object"); MethodCall method_call = (MethodCall) body; if (log.isTraceEnabled()) log.trace("[sender=%s], method_call: %s", req.getSrc(), method_call); if (method_call.getMode() == MethodCall.ID) { if (method_lookup == null) throw new Exception( String.format( "MethodCall uses ID=%d, but method_lookup has not been set", method_call.getId())); Method m = method_lookup.findMethod(method_call.getId()); if (m == null) throw new Exception("no method found for " + method_call.getId()); method_call.setMethod(m); } return method_call.invoke(server_obj); }
public Protocol setValue(String name, Object value) { if (name == null || value == null) return this; Field field = Util.getField(getClass(), name); if (field == null) throw new IllegalArgumentException("field \"" + name + "\n not found"); Util.setField(field, this, value); return this; }
private static void _testMessage(Message msg) throws Exception { Buffer buf = Util.messageToByteBuffer(msg); Message msg2 = Util.byteBufferToMessage(buf.getBuf(), buf.getOffset(), buf.getLength()); Assert.assertEquals(msg.getSrc(), msg2.getSrc()); Assert.assertEquals(msg.getDest(), msg2.getDest()); Assert.assertEquals(msg.getLength(), msg2.getLength()); }
public static void testMessageToByteBuffer() throws Exception { _testMessage(new Message()); _testMessage(new Message(null, null, "hello world")); _testMessage(new Message(null, Util.createRandomAddress(), null)); _testMessage(new Message(null, Util.createRandomAddress(), null)); _testMessage(new Message(null, Util.createRandomAddress(), "bela")); }
public String toString() { StringBuilder ret = new StringBuilder(); InetAddress local = null, remote = null; String local_str, remote_str; Socket tmp_sock = sock; if (tmp_sock == null) ret.append("<null socket>"); else { // since the sock variable gets set to null we want to make // make sure we make it through here without a nullpointer exception local = tmp_sock.getLocalAddress(); remote = tmp_sock.getInetAddress(); local_str = local != null ? Util.shortName(local) : "<null>"; remote_str = remote != null ? Util.shortName(remote) : "<null>"; ret.append( '<' + local_str + ':' + tmp_sock.getLocalPort() + " --> " + remote_str + ':' + tmp_sock.getPort() + "> (" + ((System.currentTimeMillis() - last_access) / 1000) + " secs old)"); } tmp_sock = null; return ret.toString(); }
/** * Do a http operation * * @param urlConnection the HttpURLConnection to be used * @param inputData if not null,will be written to the urlconnection. * @param hasOutput if true, read content back from the urlconnection * @return Response */ private Response doOperation( HttpURLConnection urlConnection, byte[] inputData, boolean hasOutput) { Response response = null; InputStream inputStream = null; OutputStream outputStream = null; byte[] payload = null; try { if (inputData != null) { urlConnection.setDoOutput(true); outputStream = urlConnection.getOutputStream(); outputStream.write(inputData); } if (hasOutput) { inputStream = urlConnection.getInputStream(); payload = Util.readFileContents(urlConnection.getInputStream()); } response = new Response(urlConnection.getHeaderFields(), urlConnection.getResponseCode(), payload); } catch (IOException e) { log.error("Error calling service", e); } finally { Util.close(inputStream); Util.close(outputStream); } return response; }
public void writeTo(DataOutput out) throws Exception { out.writeByte(type.ordinal()); Util.writeString(lock_name, out); Util.writeStreamable(owner, out); out.writeLong(timeout); out.writeBoolean(is_trylock); }
/** Tests https://jira.jboss.org/jira/browse/JGRP-1079 */ public void testOOBMessageLoss() throws Exception { Util.close(b); // we only need 1 channel MyReceiver receiver = new MySleepingReceiver("C1", 1000); a.setReceiver(receiver); TP transport = a.getProtocolStack().getTransport(); transport.setOOBRejectionPolicy("discard"); final int NUM = 10; for (int i = 1; i <= NUM; i++) { Message msg = new Message(null, null, i); msg.setFlag(Message.OOB); a.send(msg); } STABLE stable = (STABLE) a.getProtocolStack().findProtocol(STABLE.class); if (stable != null) stable.runMessageGarbageCollection(); Collection<Integer> msgs = receiver.getMsgs(); for (int i = 0; i < 20; i++) { if (msgs.size() == NUM) break; Util.sleep(1000); sendStableMessages(a, b); } System.out.println("msgs = " + Util.print(msgs)); assert msgs.size() == NUM : "expected " + NUM + " messages but got " + msgs.size() + ", msgs=" + Util.print(msgs); for (int i = 1; i <= NUM; i++) { assert msgs.contains(i); } }
/** Tests https://jira.jboss.org/jira/browse/JGRP-1079 for unicast messages */ public void testOOBUnicastMessageLoss() throws Exception { MyReceiver receiver = new MySleepingReceiver("C2", 1000); b.setReceiver(receiver); a.getProtocolStack().getTransport().setOOBRejectionPolicy("discard"); final int NUM = 10; final Address dest = b.getAddress(); for (int i = 1; i <= NUM; i++) { Message msg = new Message(dest, null, i); msg.setFlag(Message.OOB); a.send(msg); } Collection<Integer> msgs = receiver.getMsgs(); for (int i = 0; i < 20; i++) { if (msgs.size() == NUM) break; Util.sleep(1000); // sendStableMessages(c1,c2); // not needed for unicasts ! } assert msgs.size() == NUM : "expected " + NUM + " messages but got " + msgs.size() + ", msgs=" + Util.print(msgs); for (int i = 1; i <= NUM; i++) { assert msgs.contains(i); } }
/** * Tests A|6, A|7, A|8 and B|7, B|8, B|9 -> we should have a subviews in MergeView consisting of * only 2 elements: A|5 and B|5 */ public void testMultipleViewsBySameMembers() throws Exception { View a1 = View.create( a.getAddress(), 6, a.getAddress(), b.getAddress(), c.getAddress(), d.getAddress()); // {A,B,C,D} View a2 = View.create(a.getAddress(), 7, a.getAddress(), b.getAddress(), c.getAddress()); // {A,B,C} View a3 = View.create(a.getAddress(), 8, a.getAddress(), b.getAddress()); // {A,B} View a4 = View.create(a.getAddress(), 9, a.getAddress()); // {A} View b1 = View.create(b.getAddress(), 7, b.getAddress(), c.getAddress(), d.getAddress()); View b2 = View.create(b.getAddress(), 8, b.getAddress(), c.getAddress()); View b3 = View.create(b.getAddress(), 9, b.getAddress()); Util.close(c, d); // not interested in those... // A and B cannot communicate: discard(true, a, b); // inject view A|6={A} into A and B|5={B} into B injectView(a4, a); injectView(b3, b); assert a.getView().equals(a4); assert b.getView().equals(b3); List<Event> merge_events = new ArrayList<>(); for (View view : Arrays.asList(a3, a4, a2, a1)) { MERGE3.MergeHeader hdr = MERGE3.MergeHeader.createInfo(view.getViewId(), null, null); Message msg = new Message(null, a.getAddress(), null).putHeader(merge_id, hdr); merge_events.add(new Event(Event.MSG, msg)); } for (View view : Arrays.asList(b2, b3, b1)) { MERGE3.MergeHeader hdr = MERGE3.MergeHeader.createInfo(view.getViewId(), null, null); Message msg = new Message(null, b.getAddress(), null).putHeader(merge_id, hdr); merge_events.add(new Event(Event.MSG, msg)); } // A and B can communicate again discard(false, a, b); injectMergeEvents(merge_events, a, b); checkInconsistencies(a, b); // merge will happen between A and B Util.waitUntilAllChannelsHaveSameSize(10000, 500, a, b); System.out.println("A's view: " + a.getView() + "\nB's view: " + b.getView()); assert a.getView().size() == 2; assert a.getView().containsMember(a.getAddress()); assert a.getView().containsMember(b.getAddress()); assert a.getView().equals(b.getView()); for (View merge_view : Arrays.asList(getViewFromGMS(a), getViewFromGMS(b))) { System.out.println(merge_view); assert merge_view instanceof MergeView; List<View> subviews = ((MergeView) merge_view).getSubgroups(); assert subviews.size() == 2; } }
public void testRegularAndOOBMulticasts() throws Exception { DISCARD discard = new DISCARD(); ProtocolStack stack = a.getProtocolStack(); stack.insertProtocol(discard, ProtocolStack.BELOW, NAKACK2.class); a.setDiscardOwnMessages(true); Address dest = null; // send to all Message m1 = new Message(dest, null, 1); Message m2 = new Message(dest, null, 2); m2.setFlag(Message.OOB); Message m3 = new Message(dest, null, 3); MyReceiver receiver = new MyReceiver("C2"); b.setReceiver(receiver); a.send(m1); discard.setDropDownMulticasts(1); a.send(m2); a.send(m3); Util.sleep(500); Collection<Integer> list = receiver.getMsgs(); for (int i = 0; i < 10; i++) { System.out.println("list = " + list); if (list.size() == 3) break; Util.sleep(1000); // give the asynchronous msgs some time to be received sendStableMessages(a, b); } assert list.size() == 3 : "list is " + list; assert list.contains(1) && list.contains(2) && list.contains(3); }
/** * Tests a simple split: {A,B} and {C,D} need to merge back into one subgroup. Checks how many * MergeViews are installed */ public void testSplitInTheMiddle2() throws Exception { View v1 = View.create(a.getAddress(), 10, a.getAddress(), b.getAddress()); View v2 = View.create(c.getAddress(), 10, c.getAddress(), d.getAddress()); injectView(v1, a, b); injectView(v2, c, d); enableInfoSender(false, a, b, c, d); Util.waitUntilAllChannelsHaveSameSize(10000, 500, a, b); Util.waitUntilAllChannelsHaveSameSize(10000, 500, c, d); enableInfoSender(false, a, b, c, d); for (JChannel ch : Arrays.asList(a, b, c, d)) System.out.println(ch.getName() + ": " + ch.getView()); System.out.println("\nEnabling INFO sending in merge protocols to merge subclusters"); enableInfoSender(true, a, b, c, d); Util.waitUntilAllChannelsHaveSameSize(30000, 1000, a, b, c, d); System.out.println("\nResulting views:"); for (JChannel ch : Arrays.asList(a, b, c, d)) { GMS gms = (GMS) ch.getProtocolStack().findProtocol(GMS.class); View mv = gms.view(); System.out.println(mv); } for (JChannel ch : Arrays.asList(a, b, c, d)) { GMS gms = (GMS) ch.getProtocolStack().findProtocol(GMS.class); View mv = gms.view(); assert mv instanceof MergeView; assert mv.size() == 4; assert ((MergeView) mv).getSubgroups().size() == 2; } for (JChannel ch : Arrays.asList(a, b, c, d)) { View view = ch.getView(); assert view.size() == 4 : "view should have 4 members: " + view; } }
/** Tests a merge between ViewIds of the same coord, e.g. A|6, A|7, A|8, A|9 */ public void testViewsBySameCoord() { View v1 = View.create( a.getAddress(), 6, a.getAddress(), b.getAddress(), c.getAddress(), d.getAddress()); // {A,B,C,D} View v2 = View.create(a.getAddress(), 7, a.getAddress(), b.getAddress(), c.getAddress()); // {A,B,C} View v3 = View.create(a.getAddress(), 8, a.getAddress(), b.getAddress()); // {A,B} View v4 = View.create(a.getAddress(), 9, a.getAddress()); // {A} Util.close(b, c, d); // not interested in those... MERGE3 merge = (MERGE3) a.getProtocolStack().findProtocol(MERGE3.class); for (View view : Arrays.asList(v1, v2, v4, v3)) { MERGE3.MergeHeader hdr = MERGE3.MergeHeader.createInfo(view.getViewId(), null, null); Message msg = new Message(null, a.getAddress(), null).putHeader(merge.getId(), hdr); merge.up(new Event(Event.MSG, msg)); } merge.checkInconsistencies(); // no merge will happen Util.waitUntilAllChannelsHaveSameSize(10000, 500, a); System.out.println("A's view: " + a.getView()); assert a.getView().size() == 1; assert a.getView().containsMember(a.getAddress()); }
public static void testDetermineMergeParticipantsAndMergeCoords() { Address a = Util.createRandomAddress(), b = Util.createRandomAddress(), c = Util.createRandomAddress(); org.jgroups.util.UUID.add(a, "A"); org.jgroups.util.UUID.add(b, "B"); org.jgroups.util.UUID.add(c, "C"); View v1 = View.create(b, 1, b, a, c); View v2 = View.create(b, 2, b, c); View v3 = View.create(b, 2, b, c); Map<Address, View> map = new HashMap<>(); map.put(a, v1); map.put(b, v2); map.put(c, v3); StringBuilder sb = new StringBuilder("map:\n"); for (Map.Entry<Address, View> entry : map.entrySet()) sb.append(entry.getKey() + ": " + entry.getValue() + "\n"); System.out.println(sb); Collection<Address> merge_participants = Util.determineMergeParticipants(map); System.out.println("merge_participants = " + merge_participants); assert merge_participants.size() == 2; assert merge_participants.contains(a) && merge_participants.contains(b); Collection<Address> merge_coords = Util.determineMergeCoords(map); System.out.println("merge_coords = " + merge_coords); assert merge_coords.size() == 1; assert merge_coords.contains(b); }
public static void testAllEqual() { Address[] mbrs = Util.createRandomAddresses(5); View[] views = { View.create(mbrs[0], 1, mbrs), View.create(mbrs[0], 1, mbrs), View.create(mbrs[0], 1, mbrs) }; boolean same = Util.allEqual(Arrays.asList(views)); System.out.println("views=" + Arrays.toString(views) + ", same = " + same); assert same; views = new View[] { View.create(mbrs[0], 1, mbrs), View.create(mbrs[0], 2, mbrs), View.create(mbrs[0], 1, mbrs) }; same = Util.allEqual(Arrays.asList(views)); System.out.println("views=" + Arrays.toString(views) + ", same = " + same); assert !same; views = new View[] { View.create(mbrs[1], 1, mbrs), View.create(mbrs[0], 1, mbrs), View.create(mbrs[0], 1, mbrs) }; same = Util.allEqual(Arrays.asList(views)); System.out.println("views=" + Arrays.toString(views) + ", same = " + same); assert !same; }
static void marshal(Object obj) throws Exception { byte[] buf = Util.objectToByteBuffer(obj); assert buf != null; assert buf.length > 0; Object obj2 = Util.objectFromByteBuffer(buf); System.out.println( "obj=" + obj + ", obj2=" + obj2 + " (type=" + obj.getClass().getName() + ", length=" + buf.length + " bytes)"); Assert.assertEquals(obj, obj2); if (obj instanceof Integer) { // test compressed ints and longs buf = new byte[10]; Bits.writeIntCompressed((int) obj, buf, 0); obj2 = Bits.readIntCompressed(buf, 0); assert obj.equals(obj2); } if (obj instanceof Long) { // test compressed ints and longs buf = new byte[10]; Bits.writeLongCompressed((long) obj, buf, 0); obj2 = Bits.readLongCompressed(buf, 0); assert obj.equals(obj2); } }
private static void marshalString(int size) throws Exception { byte[] tmp = new byte[size]; String str = new String(tmp, 0, tmp.length); byte[] retval = Util.objectToByteBuffer(str); System.out.println("length=" + retval.length + " bytes"); String obj = (String) Util.objectFromByteBuffer(retval); System.out.println("read " + obj.length() + " string"); }
public static void testStringMarshalling() throws Exception { byte[] tmp = {'B', 'e', 'l', 'a'}; String str = new String(tmp); byte[] buf = Util.objectToByteBuffer(str); String str2 = (String) Util.objectFromByteBuffer(buf); assert str.equals(str2); tmp[1] = 'a'; str2 = (String) Util.objectFromByteBuffer(buf); assert str.equals(str2); }