001
014
015 package com.liferay.portal.kernel.nio.intraband.welder.test;
016
017 import com.liferay.portal.kernel.io.unsync.UnsyncByteArrayInputStream;
018 import com.liferay.portal.kernel.io.unsync.UnsyncByteArrayOutputStream;
019 import com.liferay.portal.kernel.nio.intraband.welder.Welder;
020
021 import java.io.ObjectInputStream;
022 import java.io.ObjectOutputStream;
023
024 import java.nio.ByteBuffer;
025 import java.nio.channels.GatheringByteChannel;
026 import java.nio.channels.ScatteringByteChannel;
027
028 import java.util.Random;
029 import java.util.concurrent.Callable;
030 import java.util.concurrent.FutureTask;
031
032 import org.junit.Assert;
033
034
037 public class WelderTestUtil {
038
039 public static void assertConnectted(
040 final ScatteringByteChannel scatteringByteChannel,
041 final GatheringByteChannel gatheringByteChannel)
042 throws Exception {
043
044 Random random = new Random();
045
046 final byte[] data = new byte[1024 * 1024];
047
048 random.nextBytes(data);
049
050 FutureTask<Void> writeFutureTask = new FutureTask<Void>(
051 new Callable<Void>() {
052
053 @Override
054 public Void call() throws Exception {
055 ByteBuffer byteBuffer = ByteBuffer.wrap(data);
056
057 while (byteBuffer.hasRemaining()) {
058 gatheringByteChannel.write(byteBuffer);
059 }
060
061 return null;
062 }
063 });
064
065 Thread writeThread = new Thread(writeFutureTask);
066
067 writeThread.start();
068
069 FutureTask<byte[]> readFutureTask = new FutureTask<byte[]>(
070 new Callable<byte[]>() {
071
072 @Override
073 public byte[] call() throws Exception {
074 ByteBuffer byteBuffer = ByteBuffer.allocate(data.length);
075
076 while (byteBuffer.hasRemaining()) {
077 scatteringByteChannel.read(byteBuffer);
078 }
079
080 return byteBuffer.array();
081 }
082 });
083
084 Thread readThread = new Thread(readFutureTask);
085
086 readThread.start();
087
088 writeFutureTask.get();
089
090 Assert.assertArrayEquals(data, readFutureTask.get());
091 }
092
093 public static <T extends Welder> T transform(T welder) throws Exception {
094 UnsyncByteArrayOutputStream unsyncByteArrayOutputStream =
095 new UnsyncByteArrayOutputStream();
096
097 try (ObjectOutputStream objectOutputStream = new ObjectOutputStream(
098 unsyncByteArrayOutputStream)) {
099
100 objectOutputStream.writeObject(welder);
101 }
102
103 ByteBuffer byteBuffer =
104 unsyncByteArrayOutputStream.unsafeGetByteBuffer();
105
106 UnsyncByteArrayInputStream unsyncByteArrayInputStream =
107 new UnsyncByteArrayInputStream(
108 byteBuffer.array(), 0, byteBuffer.remaining());
109
110 ObjectInputStream objectInputStream = new ObjectInputStream(
111 unsyncByteArrayInputStream);
112
113 return (T)objectInputStream.readObject();
114 }
115
116 }