Merge branch 'master' into BAEL-1423-jctools

This commit is contained in:
Tom Hombergs
2018-04-16 22:06:44 +02:00
committed by GitHub
413 changed files with 311233 additions and 971 deletions
@@ -28,7 +28,7 @@ import static org.junit.Assert.assertEquals;
import static org.junit.Assert.assertNotNull;
import static org.junit.Assert.assertTrue;
public class AsyncHttpClientTestCase {
public class AsyncHttpClientLiveTest {
private static AsyncHttpClient HTTP_CLIENT;
@@ -2,11 +2,9 @@ package com.baeldung.atlassian.fugue;
import io.atlassian.fugue.*;
import org.junit.Assert;
import org.junit.Before;
import org.junit.Test;
import java.util.NoSuchElementException;
import java.util.Optional;
import java.util.*;
import java.util.function.Function;
import static org.junit.Assert.*;
@@ -14,10 +12,6 @@ import static io.atlassian.fugue.Unit.Unit;
public class FugueTest {
@Before
public void setup() {
}
@Test
public void whenSome_thenDefined() {
Option<String> some = Option.some("value");
@@ -47,7 +41,11 @@ public class FugueTest {
@Test
public void whenNullOption_thenSome() {
Option<Object> some = Option.some("value").map(x -> null);
Option<String> some = Option.some("value") .map(String::toUpperCase);
assertEquals("VALUE", some.get());
some = some.map(x -> null);
assertNull(some.get());
some.forEach(Assert::assertNull);
@@ -74,6 +72,33 @@ public class FugueTest {
}
@Test
public void whenOption_thenIterable() {
Option<String> some = Option.some("value");
Iterable<String> strings = Iterables.concat(some, Arrays.asList("a", "b", "c"));
List<String> stringList = new ArrayList<>();
Iterables.addAll(stringList, strings);
assertEquals(4, stringList.size());
}
@Test
public void whenOption_thenStream() {
assertEquals(0, Option.none().toStream().count());
assertEquals(1, Option.some("value").toStream().count());
}
@Test
public void whenLift_thenPartialFunction() {
Function<Integer, Integer> f = (Integer x) -> x > 0 ? x + 1 : null;
Function<Option<Integer>, Option<Integer>> lifted = Options.lift(f);
assertEquals(2, (long) lifted.apply(Option.some(1)).get());
assertTrue(lifted.apply(Option.none()).isEmpty());
assertEquals(null, lifted.apply(Option.some(0)).get());
}
@Test
public void whenLeft_thenEither() {
Either<Integer, String> right = Either.right("value");
Either<Integer, String> left = Either.left(-1);
@@ -92,6 +117,8 @@ public class FugueTest {
assertTrue(either.isRight());
assertEquals("value", either.right().get());
either.right().forEach(x -> assertEquals("value", x));
}
private static String decodeSQLErrorCode(Integer x) {
@@ -193,4 +220,12 @@ public class FugueTest {
return Unit();
}
@Test
public void whenPair_thenLeftAndRight() {
Pair<Integer, String> pair = Pair.pair(1, "a");
assertEquals(1, (int) pair.left());
assertEquals("a", pair.right());
}
}
@@ -16,7 +16,7 @@ import static org.awaitility.Awaitility.setDefaultTimeout;
import static org.awaitility.proxy.AwaitilityClassProxy.to;
import static org.hamcrest.Matchers.equalTo;
public class AsyncServiceLongRunningUnitTest {
public class AsyncServiceLongRunningManualTest {
private AsyncService asyncService;
@Before
@@ -4,7 +4,7 @@ import org.junit.Test;
import static org.junit.Assert.assertTrue;
public class Docx4jReadAndWriteTest {
public class Docx4jReadAndWriteIntegrationTest {
private static final String imagePath = "src/main/resources/image.jpg";
private static final String outputPath = "helloWorld.docx";
@@ -10,7 +10,7 @@ import java.util.stream.LongStream;
import static org.assertj.core.api.AssertionsForInterfaceTypes.assertThat;
public class HLLLongRunningUnitTest {
public class HLLLongRunningManualTest {
@Test
public void givenHLL_whenAddHugeAmountOfNumbers_thenShouldReturnEstimatedCardinality() {
@@ -14,7 +14,7 @@ import javax.cache.spi.CachingProvider;
import static org.junit.Assert.assertEquals;
public class EventListenerTest {
public class EventListenerIntegrationTest {
private static final String CACHE_NAME = "MyCache";
@@ -0,0 +1,351 @@
package com.baeldung.jets3t;
import org.apache.commons.codec.digest.DigestUtils;
import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;
import org.jets3t.service.S3Service;
import org.jets3t.service.ServiceException;
import org.jets3t.service.impl.rest.httpclient.RestS3Service;
import org.jets3t.service.model.S3Bucket;
import org.jets3t.service.model.S3Object;
import org.jets3t.service.model.StorageObject;
import org.jets3t.service.security.AWSCredentials;
import org.junit.BeforeClass;
import org.junit.Test;
import java.io.*;
import java.nio.file.Files;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.stream.Collectors;
import static java.nio.file.StandardCopyOption.REPLACE_EXISTING;
import static junit.framework.TestCase.assertEquals;
import static org.junit.Assert.assertNotNull;
import static org.junit.Assert.assertTrue;
public class JetS3tLiveTest {
private Log log = LogFactory.getLog(JetS3tLiveTest.class);
private static final String BucketName = "baeldung-barfoo";
private static final String TestString = "test string";
private static final String TestStringName = "string object";
private static final String TgtBucket = "baeldung-tgtbucket";
private static S3Service s3Service;
@BeforeClass
public static void connectS3() throws Exception {
// Replace with your keys
String awsAccessKey = "your access key";
String awsSecretKey = "your secret key";
// Create credentials
AWSCredentials awsCredentials = new AWSCredentials(awsAccessKey, awsSecretKey);
// Create service
s3Service = new RestS3Service(awsCredentials);
}
@Test
public void givenCreate_AndDeleteBucket_CountGoesUpThenDown() throws Exception {
// List buckets, get a count
S3Bucket[] myBuckets = s3Service.listAllBuckets();
int count = Arrays.stream(myBuckets).map(S3Bucket::getName).collect(Collectors.toList()).size();
// Create a bucket
S3Bucket bucket = createBucket();
assertNotNull(bucket);
// List again
myBuckets = s3Service.listAllBuckets();
int newCount = Arrays.stream(myBuckets).map(S3Bucket::getName).collect(Collectors.toList()).size();
// We should have one more
assertEquals((count + 1), newCount);
// Delete so next test doesn't fail
deleteBucket();
// Check the count again, just for laughs
myBuckets = s3Service.listAllBuckets();
newCount = Arrays.stream(myBuckets).map(S3Bucket::getName).collect(Collectors.toList()).size();
assertEquals(count, newCount);
}
private S3Bucket createBucket() throws Exception {
S3Bucket bucket = s3Service.createBucket(BucketName);
log.info(bucket);
return bucket;
}
private void deleteBucket() throws ServiceException {
s3Service.deleteBucket(BucketName);
}
@Test
public void givenString_Uploaded_StringInfoIsAvailable() throws Exception {
// Create a bucket
S3Bucket bucket = createBucket();
assertNotNull(bucket);
// Upload a string
uploadStringData();
// Get the details
StorageObject objectDetailsOnly = s3Service.getObjectDetails(BucketName, TestStringName);
log.info("Content type: " + objectDetailsOnly.getContentType() + " length: " + objectDetailsOnly.getContentLength());
// Delete it
deleteObject(TestStringName);
// For next test
deleteBucket();
}
private void uploadStringData() throws Exception {
S3Object stringObject = new S3Object(TestStringName, TestString);
s3Service.putObject(BucketName, stringObject);
log.info("Content type:" + stringObject.getContentType());
}
private void deleteObject(String objectName) throws ServiceException {
s3Service.deleteObject(BucketName, objectName);
}
@Test
public void givenStringUploaded_StringIsDownloaded() throws Exception {
// Get a bucket
S3Bucket bucket = createBucket();
assertNotNull(bucket);
uploadStringData();
// Download
S3Object stringObject = s3Service.getObject(BucketName, TestStringName);
// Process stream into a string
String downloadedString = new BufferedReader(new InputStreamReader(stringObject.getDataInputStream())).lines().collect(Collectors.joining("\n"));
// Verify
assertTrue(TestString.equals(downloadedString));
// Clean up for next test
deleteObject(TestStringName);
deleteBucket();
}
@Test
public void givenBinaryFileUploaded_FileIsDownloaded() throws Exception {
// get a bucket
S3Bucket bucket = createBucket();
assertNotNull(bucket);
// Put a binary file
S3Object fileObject = new S3Object(new File("src/test/resources/test.jpg"));
s3Service.putObject(BucketName, fileObject);
// Print info about type and name
log.info("Content type:" + fileObject.getContentType());
log.info("File object name is " + fileObject.getName());
// Download
S3Object newFileObject = s3Service.getObject(BucketName, "test.jpg");
// Save to a different name
File newFile = new File("src/test/resources/newtest.jpg");
Files.copy(newFileObject.getDataInputStream(), newFile.toPath(), REPLACE_EXISTING);
// Get hashes and compare
String origMD5 = getFileMD5("src/test/resources/test.jpg");
String newMD5 = getFileMD5("src/test/resources/newtest.jpg");
assertTrue(origMD5.equals(newMD5));
// Clean up
deleteObject("test.jpg");
deleteBucket();
}
// Get MD5 hash for a file
private String getFileMD5(String filename) throws IOException {
try (FileInputStream fis = new FileInputStream(new File(filename))) {
return DigestUtils.md5Hex(fis);
}
}
@Test
public void givenStreamDataUploaded_StreamDataIsDownloaded() throws Exception {
// get a bucket
S3Bucket bucket = createBucket();
assertNotNull(bucket);
ArrayList<Integer> numbers = new ArrayList<>();
numbers.add(2);
numbers.add(3);
numbers.add(5);
numbers.add(7);
// Serialize ArrayList
ByteArrayOutputStream bytes = new ByteArrayOutputStream();
ObjectOutputStream objectOutputStream = new ObjectOutputStream(bytes);
objectOutputStream.writeObject(numbers);
// Wrap bytes
ByteArrayInputStream byteArrayInputStream = new ByteArrayInputStream(bytes.toByteArray());
// Create and populate object
S3Object streamObject = new S3Object("stream");
streamObject.setDataInputStream(byteArrayInputStream);
streamObject.setContentLength(byteArrayInputStream.available());
streamObject.setContentType("binary/octet-stream");
// Put it
s3Service.putObject(BucketName, streamObject);
// Get it
S3Object newStreamObject = s3Service.getObject(BucketName, "stream");
// Convert back to ArrayList
ObjectInputStream objectInputStream = new ObjectInputStream(newStreamObject.getDataInputStream());
ArrayList<Integer> newNumbers = (ArrayList<Integer>)objectInputStream.readObject();
assertEquals(2, (int)newNumbers.get(0));
assertEquals(3, (int)newNumbers.get(1));
assertEquals(5, (int)newNumbers.get(2));
assertEquals(7, (int)newNumbers.get(3));
// Clean up
deleteObject("stream");
deleteBucket();
}
@Test
public void whenFileCopied_CopyIsSame() throws Exception {
// get a bucket
S3Bucket bucket = createBucket();
assertNotNull(bucket);
// Put a binary file
S3Object fileObject = new S3Object(new File("src/test/resources/test.jpg"));
s3Service.putObject(BucketName, fileObject);
// Copy it
S3Object targetObject = new S3Object("testcopy.jpg");
s3Service.copyObject(BucketName, "test.jpg", BucketName, targetObject, false);
// Download
S3Object newFileObject = s3Service.getObject(BucketName, "testcopy.jpg");
// Save to a different name
File newFile = new File("src/test/resources/testcopy.jpg");
Files.copy(newFileObject.getDataInputStream(), newFile.toPath(), REPLACE_EXISTING);
// Get hashes and compare
String origMD5 = getFileMD5("src/test/resources/test.jpg");
String newMD5 = getFileMD5("src/test/resources/testcopy.jpg");
assertTrue(origMD5.equals(newMD5));
// Clean up
deleteObject("test.jpg");
deleteObject("testcopy.jpg");
deleteBucket();
}
@Test
public void whenFileRenamed_NewNameIsSame() throws Exception {
// get a bucket
S3Bucket bucket = createBucket();
assertNotNull(bucket);
// Put a binary file
S3Object fileObject = new S3Object(new File("src/test/resources/test.jpg"));
s3Service.putObject(BucketName, fileObject);
// Copy it
s3Service.renameObject(BucketName, "test.jpg", new S3Object("spidey.jpg"));
// Download
S3Object newFileObject = s3Service.getObject(BucketName, "spidey.jpg");
// Save to a different name
File newFile = new File("src/test/resources/spidey.jpg");
Files.copy(newFileObject.getDataInputStream(), newFile.toPath(), REPLACE_EXISTING);
// Get hashes and compare
String origMD5 = getFileMD5("src/test/resources/test.jpg");
String newMD5 = getFileMD5("src/test/resources/spidey.jpg");
assertTrue(origMD5.equals(newMD5));
// Clean up
deleteObject("test.jpg");
deleteObject("spidey.jpg");
deleteBucket();
}
@Test
public void whenFileMoved_NewInstanceIsSame() throws Exception {
// get a bucket
S3Bucket bucket = createBucket();
assertNotNull(bucket);
// create another bucket
S3Bucket tgtBucket = s3Service.createBucket(TgtBucket);
// Put a binary file
S3Object fileObject = new S3Object(new File("src/test/resources/test.jpg"));
s3Service.putObject(BucketName, fileObject);
// Copy it
s3Service.moveObject(BucketName, "test.jpg", TgtBucket,
new S3Object("spidey.jpg"), false);
// Download
S3Object newFileObject = s3Service.getObject(TgtBucket, "spidey.jpg");
// Save to a different name
File newFile = new File("src/test/resources/spidey.jpg");
Files.copy(newFileObject.getDataInputStream(), newFile.toPath(), REPLACE_EXISTING);
// Get hashes and compare
String origMD5 = getFileMD5("src/test/resources/test.jpg");
String newMD5 = getFileMD5("src/test/resources/spidey.jpg");
assertTrue(origMD5.equals(newMD5));
// Clean up
deleteBucket();
s3Service.deleteObject(TgtBucket, "spidey.jpg");
s3Service.deleteBucket(TgtBucket);
}
}
@@ -0,0 +1,97 @@
package com.baeldung.netty;
import java.nio.charset.Charset;
import static org.assertj.core.api.Assertions.*;
import org.assertj.core.api.Assertions;
import org.junit.Test;
import io.netty.channel.embedded.EmbeddedChannel;
import io.netty.handler.codec.http.DefaultFullHttpRequest;
import io.netty.handler.codec.http.FullHttpRequest;
import io.netty.handler.codec.http.FullHttpResponse;
import io.netty.handler.codec.http.HttpMethod;
import io.netty.handler.codec.http.HttpResponseStatus;
import io.netty.handler.codec.http.HttpVersion;
public class EmbeddedChannelUnitTest {
@Test
public void givenTwoChannelHandlers_testPipeline() {
final FullHttpRequest httpRequest = new DefaultFullHttpRequest(HttpVersion.HTTP_1_1, HttpMethod.GET,
"/calculate?a=10&b=5");
httpRequest.headers().add("Operator", "Add");
EmbeddedChannel channel = new EmbeddedChannel(new HttpMessageHandler(), new CalculatorOperationHandler());
channel.pipeline().addFirst(new HttpMessageHandler()).addLast(new CalculatorOperationHandler());
// send HTTP request to server and check that the message is on the inbound pipeline
assertThat(channel.writeInbound(httpRequest)).isTrue();
long inboundChannelResponse = channel.readInbound();
assertThat(inboundChannelResponse).isEqualTo(15);
// we should have an outbound message in the form of a HTTP response
assertThat(channel.outboundMessages().size()).isEqualTo(1);
// Object response = channel.readOutbound();
FullHttpResponse httpResponse = channel.readOutbound();
String httpResponseContent = httpResponse.content().toString(Charset.defaultCharset());
assertThat(httpResponseContent).isEqualTo("15");
}
@Test
public void givenTwoChannelHandlers_testExceptionHandlingInHttpMessageHandler() {
EmbeddedChannel channel = new EmbeddedChannel(new HttpMessageHandler(), new CalculatorOperationHandler());
final FullHttpRequest wrongHttpRequest = new DefaultFullHttpRequest(HttpVersion.HTTP_1_1, HttpMethod.POST,
"/calculate?a=10&b=5");
wrongHttpRequest.headers().add("Operator", "Add");
Throwable thrownException = catchThrowable(() -> {
// send invalid HTTP request to server and expect and error
channel.pipeline().fireChannelRead(wrongHttpRequest);
channel.checkException();
Assertions.failBecauseExceptionWasNotThrown(UnsupportedOperationException.class);
});
assertThat(thrownException)
.isInstanceOf(UnsupportedOperationException.class)
.hasMessage("HTTP method not supported");
FullHttpResponse errorHttpResponse = channel.readOutbound();
String errorHttpResponseContent = errorHttpResponse.content().toString(Charset.defaultCharset());
assertThat(errorHttpResponseContent).isEqualToIgnoringCase("Operation not defined");
assertThat(errorHttpResponse.status()).isEqualTo(HttpResponseStatus.INTERNAL_SERVER_ERROR);
}
@Test
public void givenTwoChannelHandlers_testExceptionHandlingInCalculatorOperationHandler() {
EmbeddedChannel channel = new EmbeddedChannel(new HttpMessageHandler(), new CalculatorOperationHandler());
final FullHttpRequest wrongHttpRequest = new DefaultFullHttpRequest(HttpVersion.HTTP_1_1, HttpMethod.GET,
"/calculate?a=10&b=5");
wrongHttpRequest.headers().add("Operator", "Invalid_operation");
Throwable thrownException = catchThrowable(() -> {
// send invalid HTTP request to server and expect and error
channel.writeInbound(wrongHttpRequest);
Assertions.failBecauseExceptionWasNotThrown(IllegalArgumentException.class);
});
// the HttpMessageHandler does not handle the exception and throws it down the
// pipeline
assertThat(thrownException).isInstanceOf(IllegalArgumentException.class).hasMessage("Operation not defined");
// the outbound message is a HTTP response with the status code 500
FullHttpResponse errorHttpResponse = channel.readOutbound();
String errorHttpResponseContent = errorHttpResponse.content().toString(Charset.defaultCharset());
assertThat(errorHttpResponseContent).isEqualToIgnoringCase("Operation not defined");
assertThat(errorHttpResponse.status()).isEqualTo(HttpResponseStatus.INTERNAL_SERVER_ERROR);
}
}
@@ -0,0 +1,66 @@
package com.baeldung.opencsv;
import com.baeldung.opencsv.helpers.Helpers;
import org.junit.After;
import org.junit.Before;
import org.junit.Test;
public class OpenCsvTest {
private Object testReadCsv(Object result) {
assert (result != null);
assert (result instanceof String);
assert (!((String) result).isEmpty());
System.out.println(result);
return result;
}
private Object testWriteCsv(Object result) {
assert (result instanceof String);
assert (!((String) result).isEmpty());
return result;
}
@Before
public void setup() {
}
@Test
public void positionExampleTest() {
testReadCsv(Application.simpleSyncPositionBeanExample());
}
@Test
public void namedColumnExampleTest() {
testReadCsv(Application.namedSyncColumnBeanExample());
}
@Test
public void writeCsvUsingBeanBuilderTest() {
testWriteCsv(Application.writeSyncCsvFromBeanExample());
}
@Test
public void oneByOneExampleTest() {
testReadCsv(Application.oneByOneSyncExample());
}
@Test
public void readAllExampleTest() {
testReadCsv(Application.readAllSyncExample());
}
@Test
public void csvWriterOneByOneTest() {
testWriteCsv(Application.csvWriterSyncOneByOne());
}
@Test
public void csvWriterAllTest() {
testWriteCsv(Application.csvWriterSyncAll());
}
@After
public void close() {
}
}
@@ -11,7 +11,7 @@ import java.util.concurrent.atomic.AtomicBoolean;
import static org.assertj.core.api.Java6Assertions.assertThat;
import static org.junit.Assert.assertTrue;
public class AccountTest {
public class AccountUnitTest {
@Test
public void givenAccount_whenDecrement_thenShouldReturnProperValue() {