-
Notifications
You must be signed in to change notification settings - Fork 912
/
JDBCSequentialFileFactoryTest.java
384 lines (326 loc) · 13.1 KB
/
JDBCSequentialFileFactoryTest.java
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
/*
* Licensed to the Apache Software Foundation (ASF) under one or more
* contributor license agreements. See the NOTICE file distributed with
* this work for additional information regarding copyright ownership.
* The ASF licenses this file to You under the Apache License, Version 2.0
* (the "License"); you may not use this file except in compliance with
* the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package org.apache.activemq.artemis.jdbc.store.file;
import java.nio.ByteBuffer;
import java.sql.DriverManager;
import java.sql.SQLException;
import java.util.Arrays;
import java.util.Collection;
import java.util.HashMap;
import java.util.HashSet;
import java.util.LinkedList;
import java.util.List;
import java.util.Map;
import java.util.Set;
import java.util.UUID;
import java.util.concurrent.CountDownLatch;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;
import java.util.concurrent.ScheduledExecutorService;
import java.util.concurrent.TimeUnit;
import org.apache.activemq.artemis.api.config.ActiveMQDefaultConfiguration;
import org.apache.activemq.artemis.api.core.ActiveMQBuffer;
import org.apache.activemq.artemis.api.core.ActiveMQBuffers;
import org.apache.activemq.artemis.core.io.IOCallback;
import org.apache.activemq.artemis.core.io.IOCriticalErrorListener;
import org.apache.activemq.artemis.core.io.SequentialFile;
import org.apache.activemq.artemis.jdbc.store.drivers.JDBCConnectionProvider;
import org.apache.activemq.artemis.jdbc.store.drivers.JDBCDataSourceUtils;
import org.apache.activemq.artemis.jdbc.store.drivers.JDBCUtils;
import org.apache.activemq.artemis.jdbc.store.sql.SQLProvider;
import org.apache.activemq.artemis.utils.ActiveMQThreadFactory;
import org.apache.activemq.artemis.utils.ThreadLeakCheckRule;
import org.apache.derby.jdbc.EmbeddedDriver;
import org.junit.After;
import org.junit.Assert;
import org.junit.Before;
import org.junit.Rule;
import org.junit.Test;
import org.junit.runner.RunWith;
import org.junit.runners.Parameterized;
import static org.junit.Assert.assertArrayEquals;
import static org.junit.Assert.assertEquals;
import static org.junit.Assert.assertTrue;
import static org.junit.Assert.fail;
@RunWith(Parameterized.class)
public class JDBCSequentialFileFactoryTest {
@Rule
public ThreadLeakCheckRule leakCheckRule = new ThreadLeakCheckRule();
private static String className = EmbeddedDriver.class.getCanonicalName();
private JDBCSequentialFileFactory factory;
private ExecutorService executor;
private ScheduledExecutorService scheduledExecutorService;
@Parameterized.Parameter
public boolean useAuthentication;
private String user = null;
private String password = null;
@Parameterized.Parameters(name = "authentication = {0}")
public static Collection<Object[]> data() {
return Arrays.asList(new Object[][]{{false}, {true}});
}
@Before
public void setup() throws Exception {
executor = Executors.newSingleThreadExecutor(ActiveMQThreadFactory.defaultThreadFactory(getClass().getName()));
scheduledExecutorService = Executors.newSingleThreadScheduledExecutor(ActiveMQThreadFactory.defaultThreadFactory(getClass().getName()));
Map<String, Object> dataSourceProperties = new HashMap<>();
if (useAuthentication) {
user = "testuser";
password = "testpassword";
System.setProperty("derby.connection.requireAuthentication", "true");
System.setProperty("derby.user." + user, password);
dataSourceProperties.put("username", user);
dataSourceProperties.put("password", password);
}
dataSourceProperties.put("url", "jdbc:derby:target/data;create=true");
dataSourceProperties.put("driverClassName", className);
String tableName = "FILES";
String jdbcDatasourceClass = ActiveMQDefaultConfiguration.getDefaultDataSourceClassName();
factory = new JDBCSequentialFileFactory(new JDBCConnectionProvider(JDBCDataSourceUtils.getDataSource(jdbcDatasourceClass, dataSourceProperties)), JDBCUtils.getSQLProvider(dataSourceProperties, tableName, SQLProvider.DatabaseStoreType.PAGE), executor, scheduledExecutorService, 100, new IOCriticalErrorListener() {
@Override
public void onIOException(Throwable code, String message, String file) {
}
});
factory.start();
}
@After
public void tearDown() throws Exception {
executor.shutdown();
scheduledExecutorService.shutdown();
factory.destroy();
}
@After
public void shutdownDerby() {
try {
if (useAuthentication) {
DriverManager.getConnection("jdbc:derby:;shutdown=true", user, password);
} else {
DriverManager.getConnection("jdbc:derby:;shutdown=true");
}
} catch (Exception ignored) {
}
if (useAuthentication) {
System.clearProperty("derby.connection.requireAuthentication");
System.clearProperty("derby.user." + user);
}
}
@Test
public void testJDBCFileFactoryStarted() throws Exception {
assertTrue(factory.isStarted());
}
@Test
public void testReadZeroBytesOnEmptyFile() throws Exception {
JDBCSequentialFile file = (JDBCSequentialFile) factory.createSequentialFile("test.txt");
file.open();
try {
final ByteBuffer readBuffer = ByteBuffer.allocate(0);
final int bytes = file.read(readBuffer);
assertEquals(0, bytes);
} finally {
file.close();
}
}
@Test
public void testReadZeroBytesOnNotEmptyFile() throws Exception {
final int fileLength = 8;
JDBCSequentialFile file = (JDBCSequentialFile) factory.createSequentialFile("test.txt");
file.open();
try {
file.writeDirect(ByteBuffer.allocate(fileLength), true);
assertEquals(fileLength, file.size());
final ByteBuffer readBuffer = ByteBuffer.allocate(0);
final int bytes = file.read(readBuffer);
assertEquals(0, bytes);
} finally {
file.close();
}
}
@Test
public void testReadOutOfBoundsOnEmptyFile() throws Exception {
JDBCSequentialFile file = (JDBCSequentialFile) factory.createSequentialFile("test.txt");
file.open();
try {
final ByteBuffer readBuffer = ByteBuffer.allocate(1);
file.position(1);
final int bytes = file.read(readBuffer);
assertTrue("bytes read should be < 0", bytes < 0);
} finally {
file.close();
}
}
@Test
public void testReadOutOfBoundsOnNotEmptyFile() throws Exception {
final int fileLength = 8;
JDBCSequentialFile file = (JDBCSequentialFile) factory.createSequentialFile("test.txt");
file.open();
try {
file.writeDirect(ByteBuffer.allocate(fileLength), true);
assertEquals(fileLength, file.size());
file.position(fileLength + 1);
final ByteBuffer readBuffer = ByteBuffer.allocate(fileLength);
final int bytes = file.read(readBuffer);
assertTrue("bytes read should be < 0", bytes < 0);
} finally {
file.close();
}
}
@Test
public void testCreateFiles() throws Exception {
int noFiles = 100;
List<SequentialFile> files = new LinkedList<>();
Set<String> fileNames = new HashSet<>();
for (int i = 0; i < noFiles; i++) {
String fileName = UUID.randomUUID().toString() + ".txt";
fileNames.add(fileName);
SequentialFile file = factory.createSequentialFile(fileName);
// We create files on Open
file.open();
files.add(file);
}
List<String> queryFileNames = factory.listFiles("txt");
assertTrue(queryFileNames.containsAll(fileNames));
for (SequentialFile file: files) {
file.close();
}
Assert.assertEquals(0, factory.getNumberOfOpenFiles());
}
@Test
public void testAsyncAppendToFile() throws Exception {
JDBCSequentialFile file = (JDBCSequentialFile) factory.createSequentialFile("test.txt");
file.open();
// Create buffer and fill with test data
int bufferSize = 1024;
ActiveMQBuffer src = ActiveMQBuffers.fixedBuffer(bufferSize);
for (int i = 0; i < bufferSize; i++) {
src.writeByte((byte) 1);
}
IOCallbackCountdown callback = new IOCallbackCountdown(1);
file.jdbcWrite(src, callback);
callback.assertEmpty(5);
checkData(file, src);
}
@Test
public void testWriteToFile() throws Exception {
JDBCSequentialFile file = (JDBCSequentialFile) factory.createSequentialFile("test.txt");
file.open();
ActiveMQBuffer src = ActiveMQBuffers.fixedBuffer(1);
src.writeByte((byte)7);
file.jdbcWrite(src, null);
checkData(file, src);
assertEquals(1, file.size());
file.close();
file = (JDBCSequentialFile) factory.createSequentialFile("test.txt");
file.open();
int bufferSize = 1024;
src = ActiveMQBuffers.fixedBuffer(bufferSize);
for (int i = 0; i < bufferSize; i++) {
src.writeByte((byte)i);
}
file.jdbcWrite(src, null, false);
checkData(file, src);
assertEquals(bufferSize, file.size());
}
@Test
public void testCopyFile() throws Exception {
JDBCSequentialFile file = (JDBCSequentialFile) factory.createSequentialFile("test.txt");
file.open();
// Create buffer and fill with test data
int bufferSize = 1024;
ActiveMQBuffer src = ActiveMQBuffers.fixedBuffer(bufferSize);
for (int i = 0; i < bufferSize; i++) {
src.writeByte((byte) 5);
}
IOCallbackCountdown callback = new IOCallbackCountdown(1);
file.jdbcWrite(src, callback);
JDBCSequentialFile copy = (JDBCSequentialFile) factory.createSequentialFile("copy.txt");
file.copyTo(copy);
checkData(file, src);
checkData(copy, src);
assertEquals(bufferSize, copy.size());
assertEquals(bufferSize, file.size());
}
@Test
public void testCloneFile() throws Exception {
JDBCSequentialFile file = (JDBCSequentialFile) factory.createSequentialFile("test.txt");
file.open();
// Create buffer and fill with test data
int bufferSize = 1024;
ActiveMQBuffer src = ActiveMQBuffers.fixedBuffer(bufferSize);
for (int i = 0; i < bufferSize; i++) {
src.writeByte((byte) 5);
}
IOCallbackCountdown callback = new IOCallbackCountdown(1);
file.jdbcWrite(src, callback);
assertEquals(bufferSize, file.size());
JDBCSequentialFile copy = (JDBCSequentialFile) file.cloneFile();
copy.open();
assertEquals(bufferSize, copy.size());
assertEquals(bufferSize, file.size());
}
/**
* Using a real file system users are not required to call file.open() in order to read the file size. The file
* descriptor has enough information. However, with JDBC we do require that some information is loaded in order to
* get the underlying BLOB. This tests ensures that file.size() returns the correct value, without the user calling
* file.open() with JDBCSequentialFile.
*
* @throws Exception
*/
@Test
public void testGetFileSizeWorksWhenNotOpen() throws Exception {
// Create test file with some data.
int testFileSize = 1024;
String fileName = "testFile.txt";
SequentialFile file = factory.createSequentialFile(fileName);
file.open();
// Write some data to the file
ActiveMQBuffer buffer = ActiveMQBuffers.wrappedBuffer(new byte[1024]);
file.write(buffer, true);
file.close();
try {
// Create a new pointer to the test file and ensure file.size() returns the correct value.
SequentialFile file2 = factory.createSequentialFile(fileName);
assertEquals(testFileSize, file2.size());
} catch (Throwable t) {
t.printStackTrace();
}
}
private void checkData(JDBCSequentialFile file, ActiveMQBuffer expectedData) throws SQLException {
expectedData.resetReaderIndex();
byte[] resultingBytes = new byte[expectedData.readableBytes()];
ByteBuffer byteBuffer = ByteBuffer.allocate(expectedData.readableBytes());
file.read(byteBuffer, null);
expectedData.getBytes(0, resultingBytes);
assertArrayEquals(resultingBytes, byteBuffer.array());
}
private class IOCallbackCountdown implements IOCallback {
private final CountDownLatch countDownLatch;
private IOCallbackCountdown(int size) {
this.countDownLatch = new CountDownLatch(size);
}
@Override
public void done() {
countDownLatch.countDown();
}
@Override
public void onError(int errorCode, String errorMessage) {
fail(errorMessage);
}
void assertEmpty(int timeout) throws InterruptedException {
countDownLatch.await(timeout, TimeUnit.SECONDS);
assertEquals(countDownLatch.getCount(), 0);
}
}
}