This commit is contained in:
eugenp 2014-10-14 11:24:14 +03:00
commit fe24adc61c
12 changed files with 592 additions and 3 deletions

View File

@ -163,7 +163,7 @@
<hibernate-validator.version>5.1.2.Final</hibernate-validator.version>
<!-- util -->
<guava.version>17.0</guava.version>
<guava.version>17.0</guava.version> <!-- upgrade to 18.0 -->
<commons-lang3.version>3.3.2</commons-lang3.version>
<!-- testing -->

View File

@ -1,5 +1,6 @@
package org.baeldung.java;
import java.nio.charset.Charset;
import java.util.Random;
import org.apache.commons.lang3.RandomStringUtils;
@ -151,7 +152,7 @@ public class CoreJavaRandomUnitTest {
public void givenUsingPlainJava_whenGeneratingRandomStringUnbounded_thenCorrect() {
final byte[] array = new byte[7]; // length is bounded by 7
new Random().nextBytes(array);
final String generatedString = new String(array);
final String generatedString = new String(array, Charset.forName("UTF-8"));
System.out.println(generatedString);
}
@ -166,7 +167,7 @@ public class CoreJavaRandomUnitTest {
final int randomLimitedInt = leftLimit + (int) (new Random().nextFloat() * (rightLimit - leftLimit));
buffer.append((char) randomLimitedInt);
}
final String generatedString = new String(buffer);
final String generatedString = buffer.toString();
System.out.println(generatedString);
}

View File

@ -0,0 +1,181 @@
package org.baeldung.java.io;
import static org.junit.Assert.assertEquals;
import static org.junit.Assert.assertTrue;
import java.io.BufferedReader;
import java.io.DataInputStream;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.io.RandomAccessFile;
import java.io.SequenceInputStream;
import java.io.StreamTokenizer;
import java.nio.ByteBuffer;
import java.nio.channels.FileChannel;
import java.nio.file.Files;
import java.nio.file.Path;
import java.nio.file.Paths;
import java.util.Scanner;
import org.junit.Test;
/*
MappedByteBuffer
*/
public class JavaReadFromFileTest {
@Test
public void whenReadWithBufferedReader_thenCorrect() throws IOException {
final String expected_value = "Hello world";
final BufferedReader reader = new BufferedReader(new FileReader("src/test/resources/test_read.in"));
final String currentLine = reader.readLine();
reader.close();
assertEquals(expected_value, currentLine);
}
@Test
public void whenReadWithScanner_thenCorrect() throws IOException {
final Scanner scanner = new Scanner(new File("src/test/resources/test_read1.in"));
scanner.useDelimiter(" ");
assertTrue(scanner.hasNext());
assertEquals("Hello", scanner.next());
assertEquals("world", scanner.next());
assertEquals(1, scanner.nextInt());
scanner.close();
}
@Test
public void whenReadWithScannerTwoDelimiters_thenCorrect() throws IOException {
final Scanner scanner = new Scanner(new File("src/test/resources/test_read2.in"));
scanner.useDelimiter(",| ");
assertTrue(scanner.hasNextInt());
assertEquals(2, scanner.nextInt());
assertEquals(3, scanner.nextInt());
assertEquals(4, scanner.nextInt());
scanner.close();
}
@Test
public void whenReadWithStreamTokenizer_thenCorrectTokens() throws IOException {
final FileReader reader = new FileReader("src/test/resources/test_read3.in");
final StreamTokenizer tokenizer = new StreamTokenizer(reader);
tokenizer.nextToken();
assertEquals(StreamTokenizer.TT_WORD, tokenizer.ttype);
assertEquals("Hello", tokenizer.sval);
tokenizer.nextToken();
assertEquals(StreamTokenizer.TT_NUMBER, tokenizer.ttype);
assertEquals(1, tokenizer.nval, 0.0000001);
tokenizer.nextToken();
assertEquals(StreamTokenizer.TT_EOF, tokenizer.ttype);
reader.close();
}
@Test
public void whenReadWithDataInputStream_thenCorrect() throws IOException {
final String expected_value = "Hello";
String result;
final DataInputStream reader = new DataInputStream(new FileInputStream("src/test/resources/test_read4.in"));
result = reader.readUTF();
reader.close();
assertEquals(expected_value, result);
}
public void whenReadTwoFilesWithSequenceInputStream_thenCorrect() throws IOException {
final int expected_value1 = 2000;
final int expected_value2 = 5000;
final FileInputStream stream1 = new FileInputStream("src/test/resources/test_read5.in");
final FileInputStream stream2 = new FileInputStream("src/test/resources/test_read6.in");
final SequenceInputStream sequence = new SequenceInputStream(stream1, stream2);
final DataInputStream reader = new DataInputStream(sequence);
assertEquals(expected_value1, reader.readInt());
assertEquals(expected_value2, reader.readInt());
reader.close();
stream2.close();
}
@Test
public void whenReadUTFEncodedFile_thenCorrect() throws IOException {
final String expected_value = "青空";
final BufferedReader reader = new BufferedReader(new InputStreamReader(new FileInputStream("src/test/resources/test_read7.in"), "UTF-8"));
final String currentLine = reader.readLine();
reader.close();
assertEquals(expected_value, currentLine);
}
@Test
public void whenReadFileContentsIntoString_thenCorrect() throws IOException {
final String expected_value = "Hello world \n Test line \n";
final BufferedReader reader = new BufferedReader(new FileReader("src/test/resources/test_read8.in"));
final StringBuilder builder = new StringBuilder();
String currentLine = reader.readLine();
while (currentLine != null) {
builder.append(currentLine);
builder.append("\n");
currentLine = reader.readLine();
}
reader.close();
assertEquals(expected_value, builder.toString());
}
@Test
public void whenReadWithFileChannel_thenCorrect() throws IOException {
final String expected_value = "Hello world";
final RandomAccessFile reader = new RandomAccessFile("src/test/resources/test_read.in", "r");
final FileChannel channel = reader.getChannel();
int bufferSize = 1024;
if (bufferSize > channel.size())
bufferSize = (int) channel.size();
final ByteBuffer buff = ByteBuffer.allocate(bufferSize);
channel.read(buff);
buff.flip();
assertEquals(expected_value, new String(buff.array()));
channel.close();
reader.close();
}
@Test
public void whenReadSmallFileJava7_thenCorrect() throws IOException {
final String expected_value = "Hello world";
final Path path = Paths.get("src/test/resources/test_read.in");
final String read = Files.readAllLines(path).get(0);
assertEquals(expected_value, read);
}
@Test
public void whenReadLargeFileJava7_thenCorrect() throws IOException {
final String expected_value = "Hello world";
final Path path = Paths.get("src/test/resources/test_read.in");
final BufferedReader reader = Files.newBufferedReader(path);
final String line = reader.readLine();
assertEquals(expected_value, line);
}
}

View File

@ -0,0 +1 @@
Hello world

View File

@ -0,0 +1 @@
Hello world 1

View File

@ -0,0 +1 @@
2,3 4

View File

@ -0,0 +1 @@
Hello 1

Binary file not shown.

View File

@ -0,0 +1 @@
青空

View File

@ -0,0 +1,2 @@
Hello world
Test line

View File

@ -0,0 +1,214 @@
package org.baeldung.guava;
import static org.junit.Assert.assertEquals;
import static org.junit.Assert.assertFalse;
import static org.junit.Assert.assertNull;
import java.util.HashMap;
import java.util.Map;
import java.util.concurrent.TimeUnit;
import org.junit.Test;
import com.google.common.base.Optional;
import com.google.common.cache.CacheBuilder;
import com.google.common.cache.CacheLoader;
import com.google.common.cache.LoadingCache;
import com.google.common.cache.RemovalCause;
import com.google.common.cache.RemovalListener;
import com.google.common.cache.RemovalNotification;
import com.google.common.cache.Weigher;
public class GuavaCacheTest {
@Test
public void whenCacheMiss_thenAutoLoad() {
final CacheLoader<String, String> loader = new CacheLoader<String, String>() {
@Override
public final String load(final String key) {
return key.toUpperCase();
}
};
final LoadingCache<String, String> cache = CacheBuilder.newBuilder().build(loader);
assertEquals(0, cache.size());
assertEquals("HELLO", cache.getUnchecked("hello"));
assertEquals(1, cache.size());
}
@Test
public void whenCacheReachMaxSize_thenEviction() {
final CacheLoader<String, String> loader = new CacheLoader<String, String>() {
@Override
public final String load(final String key) {
return key.toUpperCase();
}
};
final LoadingCache<String, String> cache = CacheBuilder.newBuilder().maximumSize(3).build(loader);
cache.getUnchecked("first");
cache.getUnchecked("second");
cache.getUnchecked("third");
cache.getUnchecked("forth");
assertEquals(3, cache.size());
assertNull(cache.getIfPresent("first"));
assertEquals("FORTH", cache.getIfPresent("forth"));
}
@Test
public void whenCacheReachMaxWeight_thenEviction() {
final CacheLoader<String, String> loader = new CacheLoader<String, String>() {
@Override
public final String load(final String key) {
return key.toUpperCase();
}
};
final Weigher<String, String> weighByLength = new Weigher<String, String>() {
@Override
public int weigh(final String key, final String value) {
return value.length();
}
};
final LoadingCache<String, String> cache = CacheBuilder.newBuilder().maximumWeight(16).weigher(weighByLength).build(loader);
cache.getUnchecked("first");
cache.getUnchecked("second");
cache.getUnchecked("third");
cache.getUnchecked("last");
assertEquals(3, cache.size());
assertNull(cache.getIfPresent("first"));
assertEquals("LAST", cache.getIfPresent("last"));
}
@Test
public void whenEntryIdle_thenEviction() throws InterruptedException {
final CacheLoader<String, String> loader = new CacheLoader<String, String>() {
@Override
public final String load(final String key) {
return key.toUpperCase();
}
};
final LoadingCache<String, String> cache = CacheBuilder.newBuilder().expireAfterAccess(2, TimeUnit.MILLISECONDS).build(loader);
cache.getUnchecked("hello");
assertEquals(1, cache.size());
cache.getUnchecked("hello");
Thread.sleep(300);
cache.getUnchecked("test");
assertEquals(1, cache.size());
assertNull(cache.getIfPresent("hello"));
}
@Test
public void whenEntryLiveTimeExpire_thenEviction() throws InterruptedException {
final CacheLoader<String, String> loader = new CacheLoader<String, String>() {
@Override
public final String load(final String key) {
return key.toUpperCase();
}
};
final LoadingCache<String, String> cache = CacheBuilder.newBuilder().expireAfterWrite(2, TimeUnit.MILLISECONDS).build(loader);
cache.getUnchecked("hello");
assertEquals(1, cache.size());
Thread.sleep(300);
cache.getUnchecked("test");
assertEquals(1, cache.size());
assertNull(cache.getIfPresent("hello"));
}
@Test
public void whenWeekKeyHasNoRef_thenRemoveFromCache() {
final CacheLoader<String, String> loader = new CacheLoader<String, String>() {
@Override
public final String load(final String key) {
return key.toUpperCase();
}
};
final LoadingCache<String, String> cache = CacheBuilder.newBuilder().weakKeys().build(loader);
}
@Test
public void whenSoftValue_thenRemoveFromCache() {
final CacheLoader<String, String> loader = new CacheLoader<String, String>() {
@Override
public final String load(final String key) {
return key.toUpperCase();
}
};
final LoadingCache<String, String> cache = CacheBuilder.newBuilder().softValues().build(loader);
}
@Test
public void whenNullValue_thenOptional() {
final CacheLoader<String, Optional<String>> loader = new CacheLoader<String, Optional<String>>() {
@Override
public final Optional<String> load(final String key) {
return Optional.fromNullable(getSuffix(key));
}
};
final LoadingCache<String, Optional<String>> cache = CacheBuilder.newBuilder().build(loader);
assertEquals("txt", cache.getUnchecked("text.txt").get());
assertFalse(cache.getUnchecked("hello").isPresent());
}
@Test
public void whenLiveTimeEnd_thenRefresh() {
final CacheLoader<String, String> loader = new CacheLoader<String, String>() {
@Override
public final String load(final String key) {
return key.toUpperCase();
}
};
final LoadingCache<String, String> cache = CacheBuilder.newBuilder().refreshAfterWrite(1, TimeUnit.MINUTES).build(loader);
}
@Test
public void whenPreloadCache_thenUsePutAll() {
final CacheLoader<String, String> loader = new CacheLoader<String, String>() {
@Override
public final String load(final String key) {
return key.toUpperCase();
}
};
final LoadingCache<String, String> cache = CacheBuilder.newBuilder().build(loader);
final Map<String, String> map = new HashMap<String, String>();
map.put("first", "FIRST");
map.put("second", "SECOND");
cache.putAll(map);
assertEquals(2, cache.size());
}
@Test
public void whenEntryRemovedFromCache_thenNotify() {
final CacheLoader<String, String> loader = new CacheLoader<String, String>() {
@Override
public final String load(final String key) {
return key.toUpperCase();
}
};
final RemovalListener<String, String> listener = new RemovalListener<String, String>() {
@Override
public void onRemoval(final RemovalNotification<String, String> n) {
if (n.wasEvicted()) {
final String cause = n.getCause().name();
assertEquals(RemovalCause.SIZE.toString(), cause);
}
}
};
final LoadingCache<String, String> cache = CacheBuilder.newBuilder().maximumSize(3).removalListener(listener).build(loader);
cache.getUnchecked("first");
cache.getUnchecked("second");
cache.getUnchecked("third");
cache.getUnchecked("last");
assertEquals(3, cache.size());
}
// UTIL
private String getSuffix(final String str) {
final int lastIndex = str.lastIndexOf('.');
if (lastIndex == -1)
return null;
return str.substring(lastIndex + 1);
}
}

View File

@ -0,0 +1,186 @@
package org.baeldung.guava;
import static org.hamcrest.Matchers.contains;
import static org.hamcrest.Matchers.containsInAnyOrder;
import static org.junit.Assert.assertEquals;
import static org.junit.Assert.assertFalse;
import static org.junit.Assert.assertThat;
import static org.junit.Assert.assertTrue;
import java.util.Collection;
import java.util.List;
import org.junit.Test;
import com.google.common.base.Function;
import com.google.common.base.Functions;
import com.google.common.base.Predicate;
import com.google.common.base.Predicates;
import com.google.common.collect.Collections2;
import com.google.common.collect.FluentIterable;
import com.google.common.collect.Iterables;
import com.google.common.collect.Lists;
public class GuavaFilterTransformCollectionsTest {
@Test
public void whenFilterWithCollections2_thenFiltered() {
final List<String> names = Lists.newArrayList("John", "Jane", "Adam", "Tom");
final Collection<String> result = Collections2.filter(names, Predicates.containsPattern("a"));
assertEquals(2, result.size());
assertThat(result, containsInAnyOrder("Jane", "Adam"));
result.add("anna");
assertEquals(5, names.size());
result.remove("Adam");
assertEquals(4, names.size());
}
@Test
public void whenFilterWithIterables_thenFiltered() {
final List<String> names = Lists.newArrayList("John", "Jane", "Adam", "Tom");
final Iterable<String> result = Iterables.filter(names, Predicates.containsPattern("a"));
assertThat(result, containsInAnyOrder("Jane", "Adam"));
}
@Test
public void whenFilterCollectionWithCustomPredicate_thenFiltered() {
final Predicate<String> predicate = new Predicate<String>() {
@Override
public final boolean apply(final String input) {
return input.startsWith("A") || input.startsWith("J");
}
};
final List<String> names = Lists.newArrayList("John", "Jane", "Adam", "Tom");
final Collection<String> result = Collections2.filter(names, predicate);
assertEquals(3, result.size());
assertThat(result, containsInAnyOrder("John", "Jane", "Adam"));
}
@Test
public void whenFilterUsingMultiplePredicates_thenFiltered() {
final List<String> names = Lists.newArrayList("John", "Jane", "Adam", "Tom");
final Collection<String> result = Collections2.filter(names, Predicates.or(Predicates.containsPattern("J"), Predicates.not(Predicates.containsPattern("a"))));
assertEquals(3, result.size());
assertThat(result, containsInAnyOrder("John", "Jane", "Tom"));
}
@Test
public void whenRemoveNullFromCollection_thenRemoved() {
final List<String> names = Lists.newArrayList("John", null, "Jane", null, "Adam", "Tom");
final Collection<String> result = Collections2.filter(names, Predicates.notNull());
assertEquals(4, result.size());
assertThat(result, containsInAnyOrder("John", "Jane", "Adam", "Tom"));
}
@Test
public void whenCheckAllElementsForCondition_thenChecked() {
final List<String> names = Lists.newArrayList("John", "Jane", "Adam", "Tom");
boolean result = Iterables.all(names, Predicates.containsPattern("n|m"));
assertTrue(result);
result = Iterables.all(names, Predicates.containsPattern("a"));
assertFalse(result);
}
@Test
public void whenTransformWithIterables_thenTransformed() {
final Function<String, Integer> function = new Function<String, Integer>() {
@Override
public final Integer apply(final String input) {
return input.length();
}
};
final List<String> names = Lists.newArrayList("John", "Jane", "Adam", "Tom");
final Iterable<Integer> result = Iterables.transform(names, function);
assertThat(result, contains(4, 4, 4, 3));
}
@Test
public void whenTransformWithCollections2_thenTransformed() {
final Function<String, Integer> function = new Function<String, Integer>() {
@Override
public final Integer apply(final String input) {
return input.length();
}
};
final List<String> names = Lists.newArrayList("John", "Jane", "Adam", "Tom");
final Collection<Integer> result = Collections2.transform(names, function);
assertEquals(4, result.size());
assertThat(result, contains(4, 4, 4, 3));
result.remove(3);
assertEquals(3, names.size());
}
@Test
public void whenTransformUsingComposedFunction_thenTransformed() {
final Function<String, Integer> f1 = new Function<String, Integer>() {
@Override
public final Integer apply(final String input) {
return input.length();
}
};
final Function<Integer, Boolean> f2 = new Function<Integer, Boolean>() {
@Override
public final Boolean apply(final Integer input) {
return input % 2 == 0;
}
};
final List<String> names = Lists.newArrayList("John", "Jane", "Adam", "Tom");
final Collection<Boolean> result = Collections2.transform(names, Functions.compose(f2, f1));
assertEquals(4, result.size());
assertThat(result, contains(true, true, true, false));
}
@Test
public void whenCreateFunctionFromPredicate_thenCreated() {
final List<String> names = Lists.newArrayList("John", "Jane", "Adam", "Tom");
final Collection<Boolean> result = Collections2.transform(names, Functions.forPredicate(Predicates.containsPattern("m")));
assertEquals(4, result.size());
assertThat(result, contains(false, false, true, true));
}
@Test
public void whenFilterAndTransformCollection_thenCorrect() {
final Predicate<String> predicate = new Predicate<String>() {
@Override
public final boolean apply(final String input) {
return input.startsWith("A") || input.startsWith("T");
}
};
final Function<String, Integer> func = new Function<String, Integer>() {
@Override
public final Integer apply(final String input) {
return input.length();
}
};
final List<String> names = Lists.newArrayList("John", "Jane", "Adam", "Tom");
final Collection<Integer> result = FluentIterable.from(names).filter(predicate).transform(func).toList();
assertEquals(2, result.size());
assertThat(result, containsInAnyOrder(4, 3));
}
}