Merge remote-tracking branch 'upstream/master'
This commit is contained in:
commit
2d11766b50
@ -16,3 +16,4 @@
|
||||
- [Introduction to Minimax Algorithm](http://www.baeldung.com/java-minimax-algorithm)
|
||||
- [How to Calculate Levenshtein Distance in Java?](http://www.baeldung.com/java-levenshtein-distance)
|
||||
- [How to Find the Kth Largest Element in Java](http://www.baeldung.com/java-kth-largest-element)
|
||||
- [Multi-Swarm Optimization Algorithm in Java](http://www.baeldung.com/java-multi-swarm-algorithm)
|
||||
|
@ -9,6 +9,7 @@
|
||||
<exec-maven-plugin.version>1.5.0</exec-maven-plugin.version>
|
||||
<lombok.version>1.16.12</lombok.version>
|
||||
<commons-math3.version>3.6.1</commons-math3.version>
|
||||
<tradukisto.version>1.0.1</tradukisto.version>
|
||||
</properties>
|
||||
|
||||
<parent>
|
||||
@ -39,6 +40,11 @@
|
||||
<artifactId>jgrapht-core</artifactId>
|
||||
<version>1.0.1</version>
|
||||
</dependency>
|
||||
<dependency>
|
||||
<groupId>pl.allegro.finance</groupId>
|
||||
<artifactId>tradukisto</artifactId>
|
||||
<version>${tradukisto.version}</version>
|
||||
</dependency>
|
||||
<dependency>
|
||||
<groupId>org.assertj</groupId>
|
||||
<artifactId>assertj-core</artifactId>
|
||||
@ -46,7 +52,6 @@
|
||||
<scope>test</scope>
|
||||
</dependency>
|
||||
</dependencies>
|
||||
|
||||
<build>
|
||||
<pluginManagement>
|
||||
<plugins>
|
||||
|
@ -0,0 +1,75 @@
|
||||
package com.baeldung.algorithms.numberwordconverter;
|
||||
|
||||
import java.math.BigDecimal;
|
||||
|
||||
import pl.allegro.finance.tradukisto.MoneyConverters;
|
||||
|
||||
public class NumberWordConverter {
|
||||
|
||||
public static final String INVALID_INPUT_GIVEN = "Invalid input given";
|
||||
|
||||
public static final String[] ones = { "", "one", "two", "three", "four", "five", "six", "seven", "eight", "nine", "ten", "eleven", "twelve", "thirteen", "fourteen", "fifteen", "sixteen", "seventeen", "eighteen", "nineteen" };
|
||||
|
||||
public static final String[] tens = {
|
||||
"", // 0
|
||||
"", // 1
|
||||
"twenty", // 2
|
||||
"thirty", // 3
|
||||
"forty", // 4
|
||||
"fifty", // 5
|
||||
"sixty", // 6
|
||||
"seventy", // 7
|
||||
"eighty", // 8
|
||||
"ninety" // 9
|
||||
};
|
||||
|
||||
public static String getMoneyIntoWords(String input) {
|
||||
MoneyConverters converter = MoneyConverters.ENGLISH_BANKING_MONEY_VALUE;
|
||||
return converter.asWords(new BigDecimal(input));
|
||||
}
|
||||
|
||||
public static String getMoneyIntoWords(final double money) {
|
||||
long dollar = (long) money;
|
||||
long cents = Math.round((money - dollar) * 100);
|
||||
if (money == 0D) {
|
||||
return "";
|
||||
}
|
||||
if (money < 0) {
|
||||
return INVALID_INPUT_GIVEN;
|
||||
}
|
||||
String dollarPart = "";
|
||||
if (dollar > 0) {
|
||||
dollarPart = convert(dollar) + " dollar" + (dollar == 1 ? "" : "s");
|
||||
}
|
||||
String centsPart = "";
|
||||
if (cents > 0) {
|
||||
if (dollarPart.length() > 0) {
|
||||
centsPart = " and ";
|
||||
}
|
||||
centsPart += convert(cents) + " cent" + (cents == 1 ? "" : "s");
|
||||
}
|
||||
return dollarPart + centsPart;
|
||||
}
|
||||
|
||||
private static String convert(final long n) {
|
||||
if (n < 0) {
|
||||
return INVALID_INPUT_GIVEN;
|
||||
}
|
||||
if (n < 20) {
|
||||
return ones[(int) n];
|
||||
}
|
||||
if (n < 100) {
|
||||
return tens[(int) n / 10] + ((n % 10 != 0) ? " " : "") + ones[(int) n % 10];
|
||||
}
|
||||
if (n < 1000) {
|
||||
return ones[(int) n / 100] + " hundred" + ((n % 100 != 0) ? " " : "") + convert(n % 100);
|
||||
}
|
||||
if (n < 1_000_000) {
|
||||
return convert(n / 1000) + " thousand" + ((n % 1000 != 0) ? " " : "") + convert(n % 1000);
|
||||
}
|
||||
if (n < 1_000_000_000) {
|
||||
return convert(n / 1_000_000) + " million" + ((n % 1_000_000 != 0) ? " " : "") + convert(n % 1_000_000);
|
||||
}
|
||||
return convert(n / 1_000_000_000) + " billion" + ((n % 1_000_000_000 != 0) ? " " : "") + convert(n % 1_000_000_000);
|
||||
}
|
||||
}
|
@ -0,0 +1,84 @@
|
||||
package com.baeldung.algorithms.moneywords;
|
||||
|
||||
import static org.junit.Assert.assertEquals;
|
||||
|
||||
import org.junit.Test;
|
||||
|
||||
import com.baeldung.algorithms.numberwordconverter.NumberWordConverter;
|
||||
|
||||
public class NumberWordConverterTest {
|
||||
|
||||
@Test
|
||||
public void whenMoneyNegative_thenReturnInvalidInput() {
|
||||
assertEquals(NumberWordConverter.INVALID_INPUT_GIVEN, NumberWordConverter.getMoneyIntoWords(-13));
|
||||
}
|
||||
|
||||
@Test
|
||||
public void whenZeroDollarsGiven_thenReturnEmptyString() {
|
||||
assertEquals("", NumberWordConverter.getMoneyIntoWords(0));
|
||||
}
|
||||
|
||||
@Test
|
||||
public void whenOnlyDollarsGiven_thenReturnWords() {
|
||||
assertEquals("one dollar", NumberWordConverter.getMoneyIntoWords(1));
|
||||
}
|
||||
|
||||
@Test
|
||||
public void whenOnlyCentsGiven_thenReturnWords() {
|
||||
assertEquals("sixty cents", NumberWordConverter.getMoneyIntoWords(0.6));
|
||||
}
|
||||
|
||||
@Test
|
||||
public void whenAlmostAMillioDollarsGiven_thenReturnWords() {
|
||||
String expectedResult = "nine hundred ninety nine thousand nine hundred ninety nine dollars";
|
||||
assertEquals(expectedResult, NumberWordConverter.getMoneyIntoWords(999_999));
|
||||
}
|
||||
|
||||
@Test
|
||||
public void whenThirtyMillionDollarsGiven_thenReturnWords() {
|
||||
String expectedResult = "thirty three million three hundred forty eight thousand nine hundred seventy eight dollars";
|
||||
assertEquals(expectedResult, NumberWordConverter.getMoneyIntoWords(33_348_978));
|
||||
}
|
||||
|
||||
@Test
|
||||
public void whenTwoBillionDollarsGiven_thenReturnWords() {
|
||||
String expectedResult = "two billion one hundred thirty three million two hundred forty seven thousand eight hundred ten dollars";
|
||||
assertEquals(expectedResult, NumberWordConverter.getMoneyIntoWords(2_133_247_810));
|
||||
}
|
||||
|
||||
@Test
|
||||
public void whenGivenDollarsAndCents_thenReturnWords() {
|
||||
String expectedResult = "nine hundred twenty four dollars and sixty cents";
|
||||
assertEquals(expectedResult, NumberWordConverter.getMoneyIntoWords(924.6));
|
||||
}
|
||||
|
||||
@Test
|
||||
public void whenOneDollarAndNoCents_thenReturnDollarSingular() {
|
||||
assertEquals("one dollar", NumberWordConverter.getMoneyIntoWords(1));
|
||||
}
|
||||
|
||||
@Test
|
||||
public void whenNoDollarsAndOneCent_thenReturnCentSingular() {
|
||||
assertEquals("one cent", NumberWordConverter.getMoneyIntoWords(0.01));
|
||||
}
|
||||
|
||||
@Test
|
||||
public void whenNoDollarsAndTwoCents_thenReturnCentsPlural() {
|
||||
assertEquals("two cents", NumberWordConverter.getMoneyIntoWords(0.02));
|
||||
}
|
||||
|
||||
@Test
|
||||
public void whenNoDollarsAndNinetyNineCents_thenReturnWords() {
|
||||
assertEquals("ninety nine cents", NumberWordConverter.getMoneyIntoWords(0.99));
|
||||
}
|
||||
|
||||
@Test
|
||||
public void whenNoDollarsAndNineFiveNineCents_thenCorrectRounding() {
|
||||
assertEquals("ninety six cents", NumberWordConverter.getMoneyIntoWords(0.959));
|
||||
}
|
||||
|
||||
@Test
|
||||
public void whenGivenDollarsAndCents_thenReturnWordsVersionTwo() {
|
||||
assertEquals("three hundred ten £ 00/100", NumberWordConverter.getMoneyIntoWords("310"));
|
||||
}
|
||||
}
|
76
apache-curator/pom.xml
Normal file
76
apache-curator/pom.xml
Normal file
@ -0,0 +1,76 @@
|
||||
<project xmlns="http://maven.apache.org/POM/4.0.0" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
|
||||
xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd">
|
||||
<modelVersion>4.0.0</modelVersion>
|
||||
<artifactId>apache-curator</artifactId>
|
||||
<version>0.0.1-SNAPSHOT</version>
|
||||
<packaging>jar</packaging>
|
||||
|
||||
<parent>
|
||||
<groupId>com.baeldung</groupId>
|
||||
<artifactId>parent-modules</artifactId>
|
||||
<version>1.0.0-SNAPSHOT</version>
|
||||
</parent>
|
||||
|
||||
<properties>
|
||||
<curator.version>4.0.1</curator.version>
|
||||
<zookeeper.version>3.4.11</zookeeper.version>
|
||||
<jackson-databind.version>2.9.4</jackson-databind.version>
|
||||
|
||||
<!-- testing -->
|
||||
<assertj.version>3.6.1</assertj.version>
|
||||
<avaitility.version>1.7.0</avaitility.version>
|
||||
|
||||
</properties>
|
||||
|
||||
<dependencies>
|
||||
|
||||
<!-- curator -->
|
||||
|
||||
<dependency>
|
||||
<groupId>org.apache.curator</groupId>
|
||||
<artifactId>curator-x-async</artifactId>
|
||||
<version>${curator.version}</version>
|
||||
<exclusions>
|
||||
<exclusion>
|
||||
<groupId>org.apache.zookeeper</groupId>
|
||||
<artifactId>zookeeper</artifactId>
|
||||
</exclusion>
|
||||
</exclusions>
|
||||
</dependency>
|
||||
|
||||
<dependency>
|
||||
<groupId>org.apache.curator</groupId>
|
||||
<artifactId>curator-recipes</artifactId>
|
||||
<version>${curator.version}</version>
|
||||
</dependency>
|
||||
|
||||
<dependency>
|
||||
<groupId>org.apache.zookeeper</groupId>
|
||||
<artifactId>zookeeper</artifactId>
|
||||
<version>${zookeeper.version}</version>
|
||||
</dependency>
|
||||
|
||||
<!-- utils -->
|
||||
<dependency>
|
||||
<groupId>com.fasterxml.jackson.core</groupId>
|
||||
<artifactId>jackson-databind</artifactId>
|
||||
<version>${jackson-databind.version}</version>
|
||||
</dependency>
|
||||
|
||||
<!-- test scoped -->
|
||||
|
||||
<dependency>
|
||||
<groupId>org.assertj</groupId>
|
||||
<artifactId>assertj-core</artifactId>
|
||||
<version>${assertj.version}</version>
|
||||
<scope>test</scope>
|
||||
</dependency>
|
||||
|
||||
<dependency>
|
||||
<groupId>com.jayway.awaitility</groupId>
|
||||
<artifactId>awaitility</artifactId>
|
||||
<version>${avaitility.version}</version>
|
||||
<scope>test</scope>
|
||||
</dependency>
|
||||
</dependencies>
|
||||
</project>
|
@ -0,0 +1,31 @@
|
||||
package com.baeldung.apache.curator.modeled;
|
||||
|
||||
public class HostConfig {
|
||||
private String hostname;
|
||||
private int port;
|
||||
|
||||
public HostConfig() {
|
||||
|
||||
}
|
||||
|
||||
public HostConfig(String hostname, int port) {
|
||||
this.hostname = hostname;
|
||||
this.port = port;
|
||||
}
|
||||
|
||||
public int getPort() {
|
||||
return port;
|
||||
}
|
||||
|
||||
public void setPort(int port) {
|
||||
this.port = port;
|
||||
}
|
||||
|
||||
public String getHostname() {
|
||||
return hostname;
|
||||
}
|
||||
|
||||
public void setHostname(String hostname) {
|
||||
this.hostname = hostname;
|
||||
}
|
||||
}
|
@ -0,0 +1,22 @@
|
||||
package com.baeldung.apache.curator;
|
||||
|
||||
import org.apache.curator.RetryPolicy;
|
||||
import org.apache.curator.framework.CuratorFramework;
|
||||
import org.apache.curator.framework.CuratorFrameworkFactory;
|
||||
import org.apache.curator.retry.RetryNTimes;
|
||||
import org.junit.Before;
|
||||
|
||||
public abstract class BaseTest {
|
||||
|
||||
@Before
|
||||
public void setup() {
|
||||
org.apache.log4j.BasicConfigurator.configure();
|
||||
}
|
||||
|
||||
protected CuratorFramework newClient() {
|
||||
int sleepMsBetweenRetries = 100;
|
||||
int maxRetries = 3;
|
||||
RetryPolicy retryPolicy = new RetryNTimes(maxRetries, sleepMsBetweenRetries);
|
||||
return CuratorFrameworkFactory.newClient("127.0.0.1:2181", retryPolicy);
|
||||
}
|
||||
}
|
@ -0,0 +1,89 @@
|
||||
package com.baeldung.apache.curator.configuration;
|
||||
|
||||
import static com.jayway.awaitility.Awaitility.await;
|
||||
import static org.assertj.core.api.Assertions.assertThat;
|
||||
|
||||
import java.util.ArrayList;
|
||||
import java.util.List;
|
||||
import java.util.UUID;
|
||||
import java.util.concurrent.atomic.AtomicBoolean;
|
||||
|
||||
import org.apache.curator.framework.CuratorFramework;
|
||||
import org.apache.curator.x.async.AsyncCuratorFramework;
|
||||
import org.junit.Test;
|
||||
|
||||
import com.baeldung.apache.curator.BaseTest;
|
||||
|
||||
public class ConfigurationManagementManualTest extends BaseTest {
|
||||
|
||||
private static final String KEY_FORMAT = "/%s";
|
||||
|
||||
@Test
|
||||
public void givenPath_whenCreateKey_thenValueIsStored() throws Exception {
|
||||
try (CuratorFramework client = newClient()) {
|
||||
client.start();
|
||||
AsyncCuratorFramework async = AsyncCuratorFramework.wrap(client);
|
||||
String key = getKey();
|
||||
String expected = "my_value";
|
||||
|
||||
// Create key nodes structure
|
||||
client.create()
|
||||
.forPath(key);
|
||||
|
||||
// Set data value for our key
|
||||
async.setData()
|
||||
.forPath(key, expected.getBytes());
|
||||
|
||||
// Get data value
|
||||
AtomicBoolean isEquals = new AtomicBoolean();
|
||||
async.getData()
|
||||
.forPath(key)
|
||||
.thenAccept(
|
||||
data -> isEquals.set(new String(data).equals(expected)));
|
||||
|
||||
await().until(() -> assertThat(isEquals.get()).isTrue());
|
||||
}
|
||||
}
|
||||
|
||||
@Test
|
||||
public void givenPath_whenWatchAKeyAndStoreAValue_thenWatcherIsTriggered()
|
||||
throws Exception {
|
||||
try (CuratorFramework client = newClient()) {
|
||||
client.start();
|
||||
AsyncCuratorFramework async = AsyncCuratorFramework.wrap(client);
|
||||
String key = getKey();
|
||||
String expected = "my_value";
|
||||
|
||||
// Create key structure
|
||||
async.create()
|
||||
.forPath(key);
|
||||
|
||||
List<String> changes = new ArrayList<>();
|
||||
|
||||
// Watch data value
|
||||
async.watched()
|
||||
.getData()
|
||||
.forPath(key)
|
||||
.event()
|
||||
.thenAccept(watchedEvent -> {
|
||||
try {
|
||||
changes.add(new String(client.getData()
|
||||
.forPath(watchedEvent.getPath())));
|
||||
} catch (Exception e) {
|
||||
// fail ...
|
||||
}
|
||||
});
|
||||
|
||||
// Set data value for our key
|
||||
async.setData()
|
||||
.forPath(key, expected.getBytes());
|
||||
|
||||
await().until(() -> assertThat(changes.size() > 0).isTrue());
|
||||
}
|
||||
}
|
||||
|
||||
private String getKey() {
|
||||
return String.format(KEY_FORMAT, UUID.randomUUID()
|
||||
.toString());
|
||||
}
|
||||
}
|
@ -0,0 +1,79 @@
|
||||
package com.baeldung.apache.curator.connection;
|
||||
|
||||
import static com.jayway.awaitility.Awaitility.await;
|
||||
import static org.assertj.core.api.Assertions.assertThat;
|
||||
|
||||
import java.util.concurrent.atomic.AtomicBoolean;
|
||||
|
||||
import org.apache.curator.RetryPolicy;
|
||||
import org.apache.curator.framework.CuratorFramework;
|
||||
import org.apache.curator.framework.CuratorFrameworkFactory;
|
||||
import org.apache.curator.retry.RetryNTimes;
|
||||
import org.apache.curator.x.async.AsyncCuratorFramework;
|
||||
import org.junit.Test;
|
||||
|
||||
public class ConnectionManagementManualTest {
|
||||
|
||||
@Test
|
||||
public void givenRunningZookeeper_whenOpenConnection_thenClientIsOpened()
|
||||
throws Exception {
|
||||
int sleepMsBetweenRetries = 100;
|
||||
int maxRetries = 3;
|
||||
RetryPolicy retryPolicy = new RetryNTimes(maxRetries,
|
||||
sleepMsBetweenRetries);
|
||||
|
||||
try (CuratorFramework client = CuratorFrameworkFactory
|
||||
.newClient("127.0.0.1:2181", retryPolicy)) {
|
||||
client.start();
|
||||
|
||||
assertThat(client.checkExists()
|
||||
.forPath("/")).isNotNull();
|
||||
}
|
||||
}
|
||||
|
||||
@Test
|
||||
public void givenRunningZookeeper_whenOpenConnectionUsingAsyncNotBlocking_thenClientIsOpened()
|
||||
throws InterruptedException {
|
||||
int sleepMsBetweenRetries = 100;
|
||||
int maxRetries = 3;
|
||||
RetryPolicy retryPolicy = new RetryNTimes(maxRetries,
|
||||
sleepMsBetweenRetries);
|
||||
|
||||
try (CuratorFramework client = CuratorFrameworkFactory
|
||||
.newClient("127.0.0.1:2181", retryPolicy)) {
|
||||
client.start();
|
||||
AsyncCuratorFramework async = AsyncCuratorFramework.wrap(client);
|
||||
|
||||
AtomicBoolean exists = new AtomicBoolean(false);
|
||||
|
||||
async.checkExists()
|
||||
.forPath("/")
|
||||
.thenAcceptAsync(s -> exists.set(s != null));
|
||||
|
||||
await().until(() -> assertThat(exists.get()).isTrue());
|
||||
}
|
||||
}
|
||||
|
||||
@Test
|
||||
public void givenRunningZookeeper_whenOpenConnectionUsingAsyncBlocking_thenClientIsOpened()
|
||||
throws InterruptedException {
|
||||
int sleepMsBetweenRetries = 100;
|
||||
int maxRetries = 3;
|
||||
RetryPolicy retryPolicy = new RetryNTimes(maxRetries,
|
||||
sleepMsBetweenRetries);
|
||||
|
||||
try (CuratorFramework client = CuratorFrameworkFactory
|
||||
.newClient("127.0.0.1:2181", retryPolicy)) {
|
||||
client.start();
|
||||
AsyncCuratorFramework async = AsyncCuratorFramework.wrap(client);
|
||||
|
||||
AtomicBoolean exists = new AtomicBoolean(false);
|
||||
|
||||
async.checkExists()
|
||||
.forPath("/")
|
||||
.thenAccept(s -> exists.set(s != null));
|
||||
|
||||
await().until(() -> assertThat(exists.get()).isTrue());
|
||||
}
|
||||
}
|
||||
}
|
@ -0,0 +1,49 @@
|
||||
package com.baeldung.apache.curator.modeled;
|
||||
|
||||
import static org.assertj.core.api.Assertions.assertThat;
|
||||
import static org.assertj.core.api.Assertions.fail;
|
||||
|
||||
import org.apache.curator.framework.CuratorFramework;
|
||||
import org.apache.curator.x.async.AsyncCuratorFramework;
|
||||
import org.apache.curator.x.async.modeled.JacksonModelSerializer;
|
||||
import org.apache.curator.x.async.modeled.ModelSpec;
|
||||
import org.apache.curator.x.async.modeled.ModeledFramework;
|
||||
import org.apache.curator.x.async.modeled.ZPath;
|
||||
import org.junit.Test;
|
||||
|
||||
import com.baeldung.apache.curator.BaseTest;
|
||||
|
||||
public class ModelTypedExamplesManualTest extends BaseTest {
|
||||
|
||||
@Test
|
||||
public void givenPath_whenStoreAModel_thenNodesAreCreated()
|
||||
throws InterruptedException {
|
||||
|
||||
ModelSpec<HostConfig> mySpec = ModelSpec
|
||||
.builder(ZPath.parseWithIds("/config/dev"),
|
||||
JacksonModelSerializer.build(HostConfig.class))
|
||||
.build();
|
||||
|
||||
try (CuratorFramework client = newClient()) {
|
||||
client.start();
|
||||
AsyncCuratorFramework async = AsyncCuratorFramework.wrap(client);
|
||||
ModeledFramework<HostConfig> modeledClient = ModeledFramework
|
||||
.wrap(async, mySpec);
|
||||
|
||||
modeledClient.set(new HostConfig("host-name", 8080));
|
||||
|
||||
modeledClient.read()
|
||||
.whenComplete((value, e) -> {
|
||||
if (e != null) {
|
||||
fail("Cannot read host config", e);
|
||||
} else {
|
||||
assertThat(value).isNotNull();
|
||||
assertThat(value.getHostname()).isEqualTo("host-name");
|
||||
assertThat(value.getPort()).isEqualTo(8080);
|
||||
}
|
||||
|
||||
});
|
||||
}
|
||||
|
||||
}
|
||||
}
|
@ -0,0 +1,74 @@
|
||||
package com.baeldung.apache.curator.recipes;
|
||||
|
||||
import static org.assertj.core.api.Assertions.assertThat;
|
||||
|
||||
import org.apache.curator.framework.CuratorFramework;
|
||||
import org.apache.curator.framework.recipes.leader.LeaderSelector;
|
||||
import org.apache.curator.framework.recipes.leader.LeaderSelectorListener;
|
||||
import org.apache.curator.framework.recipes.locks.InterProcessSemaphoreMutex;
|
||||
import org.apache.curator.framework.recipes.shared.SharedCount;
|
||||
import org.apache.curator.framework.state.ConnectionState;
|
||||
import org.junit.Test;
|
||||
|
||||
import com.baeldung.apache.curator.BaseTest;
|
||||
|
||||
public class RecipesManualTest extends BaseTest {
|
||||
|
||||
@Test
|
||||
public void givenRunningZookeeper_whenUsingLeaderElection_thenNoErrors() {
|
||||
try (CuratorFramework client = newClient()) {
|
||||
client.start();
|
||||
LeaderSelector leaderSelector = new LeaderSelector(client, "/mutex/select/leader/for/job/A", new LeaderSelectorListener() {
|
||||
|
||||
@Override
|
||||
public void stateChanged(CuratorFramework client, ConnectionState newState) {
|
||||
|
||||
}
|
||||
|
||||
@Override
|
||||
public void takeLeadership(CuratorFramework client) throws Exception {
|
||||
// I'm the leader of the job A !
|
||||
}
|
||||
|
||||
});
|
||||
|
||||
leaderSelector.start();
|
||||
|
||||
// Wait until the job A is done among all the members
|
||||
|
||||
leaderSelector.close();
|
||||
}
|
||||
}
|
||||
|
||||
@Test
|
||||
public void givenRunningZookeeper_whenUsingSharedLock_thenNoErrors() throws Exception {
|
||||
try (CuratorFramework client = newClient()) {
|
||||
client.start();
|
||||
InterProcessSemaphoreMutex sharedLock = new InterProcessSemaphoreMutex(client, "/mutex/process/A");
|
||||
|
||||
sharedLock.acquire();
|
||||
|
||||
// Do process A
|
||||
|
||||
sharedLock.release();
|
||||
}
|
||||
}
|
||||
|
||||
@Test
|
||||
public void givenRunningZookeeper_whenUsingSharedCounter_thenCounterIsIncrement() throws Exception {
|
||||
try (CuratorFramework client = newClient()) {
|
||||
client.start();
|
||||
|
||||
try (SharedCount counter = new SharedCount(client, "/counters/A", 0)) {
|
||||
counter.start();
|
||||
|
||||
counter.setCount(0);
|
||||
counter.setCount(counter.getCount() + 1);
|
||||
|
||||
assertThat(counter.getCount()).isEqualTo(1);
|
||||
}
|
||||
|
||||
}
|
||||
}
|
||||
|
||||
}
|
25
apache-tika/pom.xml
Normal file
25
apache-tika/pom.xml
Normal file
@ -0,0 +1,25 @@
|
||||
<project xmlns="http://maven.apache.org/POM/4.0.0" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
|
||||
xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd">
|
||||
<modelVersion>4.0.0</modelVersion>
|
||||
<groupId>com.baeldung</groupId>
|
||||
<artifactId>apache-tika</artifactId>
|
||||
<version>0.0.1-SNAPSHOT</version>
|
||||
|
||||
<parent>
|
||||
<groupId>com.baeldung</groupId>
|
||||
<artifactId>parent-modules</artifactId>
|
||||
<version>1.0.0-SNAPSHOT</version>
|
||||
</parent>
|
||||
|
||||
<properties>
|
||||
<tika.version>1.17</tika.version>
|
||||
</properties>
|
||||
|
||||
<dependencies>
|
||||
<dependency>
|
||||
<groupId>org.apache.tika</groupId>
|
||||
<artifactId>tika-parsers</artifactId>
|
||||
<version>${tika.version}</version>
|
||||
</dependency>
|
||||
</dependencies>
|
||||
</project>
|
@ -0,0 +1,67 @@
|
||||
package com.baeldung.tika;
|
||||
|
||||
import java.io.IOException;
|
||||
import java.io.InputStream;
|
||||
|
||||
import org.apache.tika.Tika;
|
||||
import org.apache.tika.detect.DefaultDetector;
|
||||
import org.apache.tika.detect.Detector;
|
||||
import org.apache.tika.exception.TikaException;
|
||||
import org.apache.tika.metadata.Metadata;
|
||||
import org.apache.tika.mime.MediaType;
|
||||
import org.apache.tika.parser.AutoDetectParser;
|
||||
import org.apache.tika.parser.ParseContext;
|
||||
import org.apache.tika.parser.Parser;
|
||||
import org.apache.tika.sax.BodyContentHandler;
|
||||
import org.xml.sax.ContentHandler;
|
||||
import org.xml.sax.SAXException;
|
||||
|
||||
public class TikaAnalysis {
|
||||
public static String detectDocTypeUsingDetector(InputStream stream) throws IOException {
|
||||
Detector detector = new DefaultDetector();
|
||||
Metadata metadata = new Metadata();
|
||||
|
||||
MediaType mediaType = detector.detect(stream, metadata);
|
||||
return mediaType.toString();
|
||||
}
|
||||
|
||||
public static String detectDocTypeUsingFacade(InputStream stream) throws IOException {
|
||||
Tika tika = new Tika();
|
||||
String mediaType = tika.detect(stream);
|
||||
return mediaType;
|
||||
}
|
||||
|
||||
public static String extractContentUsingParser(InputStream stream) throws IOException, TikaException, SAXException {
|
||||
Parser parser = new AutoDetectParser();
|
||||
ContentHandler handler = new BodyContentHandler();
|
||||
Metadata metadata = new Metadata();
|
||||
ParseContext context = new ParseContext();
|
||||
|
||||
parser.parse(stream, handler, metadata, context);
|
||||
return handler.toString();
|
||||
}
|
||||
|
||||
public static String extractContentUsingFacade(InputStream stream) throws IOException, TikaException {
|
||||
Tika tika = new Tika();
|
||||
String content = tika.parseToString(stream);
|
||||
return content;
|
||||
}
|
||||
|
||||
public static Metadata extractMetadatatUsingParser(InputStream stream) throws IOException, SAXException, TikaException {
|
||||
Parser parser = new AutoDetectParser();
|
||||
ContentHandler handler = new BodyContentHandler();
|
||||
Metadata metadata = new Metadata();
|
||||
ParseContext context = new ParseContext();
|
||||
|
||||
parser.parse(stream, handler, metadata, context);
|
||||
return metadata;
|
||||
}
|
||||
|
||||
public static Metadata extractMetadatatUsingFacade(InputStream stream) throws IOException, TikaException {
|
||||
Tika tika = new Tika();
|
||||
Metadata metadata = new Metadata();
|
||||
|
||||
tika.parse(stream, metadata);
|
||||
return metadata;
|
||||
}
|
||||
}
|
@ -0,0 +1,79 @@
|
||||
package com.baeldung.tika;
|
||||
|
||||
import static org.hamcrest.CoreMatchers.containsString;
|
||||
import static org.junit.Assert.assertEquals;
|
||||
import static org.junit.Assert.assertThat;
|
||||
|
||||
import java.io.IOException;
|
||||
import java.io.InputStream;
|
||||
|
||||
import org.apache.tika.exception.TikaException;
|
||||
import org.apache.tika.metadata.Metadata;
|
||||
import org.junit.Test;
|
||||
import org.xml.sax.SAXException;
|
||||
|
||||
public class TikaUnitTest {
|
||||
@Test
|
||||
public void whenUsingDetector_thenDocumentTypeIsReturned() throws IOException {
|
||||
InputStream stream = this.getClass().getClassLoader().getResourceAsStream("tika.txt");
|
||||
String mediaType = TikaAnalysis.detectDocTypeUsingDetector(stream);
|
||||
|
||||
assertEquals("application/pdf", mediaType);
|
||||
|
||||
stream.close();
|
||||
}
|
||||
|
||||
@Test
|
||||
public void whenUsingFacade_thenDocumentTypeIsReturned() throws IOException {
|
||||
InputStream stream = this.getClass().getClassLoader().getResourceAsStream("tika.txt");
|
||||
String mediaType = TikaAnalysis.detectDocTypeUsingFacade(stream);
|
||||
|
||||
assertEquals("application/pdf", mediaType);
|
||||
|
||||
stream.close();
|
||||
}
|
||||
|
||||
@Test
|
||||
public void whenUsingParser_thenContentIsReturned() throws IOException, TikaException, SAXException {
|
||||
InputStream stream = this.getClass().getClassLoader().getResourceAsStream("tika.docx");
|
||||
String content = TikaAnalysis.extractContentUsingParser(stream);
|
||||
|
||||
assertThat(content, containsString("Apache Tika - a content analysis toolkit"));
|
||||
assertThat(content, containsString("detects and extracts metadata and text"));
|
||||
|
||||
stream.close();
|
||||
}
|
||||
|
||||
@Test
|
||||
public void whenUsingFacade_thenContentIsReturned() throws IOException, TikaException {
|
||||
InputStream stream = this.getClass().getClassLoader().getResourceAsStream("tika.docx");
|
||||
String content = TikaAnalysis.extractContentUsingFacade(stream);
|
||||
|
||||
assertThat(content, containsString("Apache Tika - a content analysis toolkit"));
|
||||
assertThat(content, containsString("detects and extracts metadata and text"));
|
||||
|
||||
stream.close();
|
||||
}
|
||||
|
||||
@Test
|
||||
public void whenUsingParser_thenMetadataIsReturned() throws IOException, TikaException, SAXException {
|
||||
InputStream stream = this.getClass().getClassLoader().getResourceAsStream("tika.xlsx");
|
||||
Metadata metadata = TikaAnalysis.extractMetadatatUsingParser(stream);
|
||||
|
||||
assertEquals("org.apache.tika.parser.DefaultParser", metadata.get("X-Parsed-By"));
|
||||
assertEquals("Microsoft Office User", metadata.get("Author"));
|
||||
|
||||
stream.close();
|
||||
}
|
||||
|
||||
@Test
|
||||
public void whenUsingFacade_thenMetadataIsReturned() throws IOException, TikaException {
|
||||
InputStream stream = this.getClass().getClassLoader().getResourceAsStream("tika.xlsx");
|
||||
Metadata metadata = TikaAnalysis.extractMetadatatUsingFacade(stream);
|
||||
|
||||
assertEquals("org.apache.tika.parser.DefaultParser", metadata.get("X-Parsed-By"));
|
||||
assertEquals("Microsoft Office User", metadata.get("Author"));
|
||||
|
||||
stream.close();
|
||||
}
|
||||
}
|
BIN
apache-tika/src/test/resources/tika.docx
Normal file
BIN
apache-tika/src/test/resources/tika.docx
Normal file
Binary file not shown.
BIN
apache-tika/src/test/resources/tika.txt
Normal file
BIN
apache-tika/src/test/resources/tika.txt
Normal file
Binary file not shown.
BIN
apache-tika/src/test/resources/tika.xlsx
Normal file
BIN
apache-tika/src/test/resources/tika.xlsx
Normal file
Binary file not shown.
@ -6,6 +6,12 @@
|
||||
<version>0.0.1-SNAPSHOT</version>
|
||||
<packaging>jar</packaging>
|
||||
|
||||
<parent>
|
||||
<groupId>com.baeldung</groupId>
|
||||
<artifactId>parent-modules</artifactId>
|
||||
<version>1.0.0-SNAPSHOT</version>
|
||||
</parent>
|
||||
|
||||
<dependencies>
|
||||
<dependency>
|
||||
<groupId>org.apache.zookeeper</groupId>
|
||||
|
137
aws/src/main/java/com/baeldung/ec2/EC2Application.java
Normal file
137
aws/src/main/java/com/baeldung/ec2/EC2Application.java
Normal file
@ -0,0 +1,137 @@
|
||||
package com.baeldung.ec2;
|
||||
|
||||
import java.util.Arrays;
|
||||
|
||||
import com.amazonaws.auth.AWSCredentials;
|
||||
import com.amazonaws.auth.AWSStaticCredentialsProvider;
|
||||
import com.amazonaws.auth.BasicAWSCredentials;
|
||||
import com.amazonaws.regions.Regions;
|
||||
import com.amazonaws.services.ec2.AmazonEC2;
|
||||
import com.amazonaws.services.ec2.AmazonEC2ClientBuilder;
|
||||
import com.amazonaws.services.ec2.model.AuthorizeSecurityGroupIngressRequest;
|
||||
import com.amazonaws.services.ec2.model.CreateKeyPairRequest;
|
||||
import com.amazonaws.services.ec2.model.CreateKeyPairResult;
|
||||
import com.amazonaws.services.ec2.model.CreateSecurityGroupRequest;
|
||||
import com.amazonaws.services.ec2.model.DescribeInstancesRequest;
|
||||
import com.amazonaws.services.ec2.model.DescribeInstancesResult;
|
||||
import com.amazonaws.services.ec2.model.DescribeKeyPairsRequest;
|
||||
import com.amazonaws.services.ec2.model.DescribeKeyPairsResult;
|
||||
import com.amazonaws.services.ec2.model.IpPermission;
|
||||
import com.amazonaws.services.ec2.model.IpRange;
|
||||
import com.amazonaws.services.ec2.model.MonitorInstancesRequest;
|
||||
import com.amazonaws.services.ec2.model.RebootInstancesRequest;
|
||||
import com.amazonaws.services.ec2.model.RunInstancesRequest;
|
||||
import com.amazonaws.services.ec2.model.StartInstancesRequest;
|
||||
import com.amazonaws.services.ec2.model.StopInstancesRequest;
|
||||
import com.amazonaws.services.ec2.model.UnmonitorInstancesRequest;
|
||||
|
||||
public class EC2Application {
|
||||
|
||||
private static final AWSCredentials credentials;
|
||||
|
||||
static {
|
||||
// put your accesskey and secretkey here
|
||||
credentials = new BasicAWSCredentials(
|
||||
"<AWS accesskey>",
|
||||
"<AWS secretkey>"
|
||||
);
|
||||
}
|
||||
|
||||
public static void main(String[] args) {
|
||||
|
||||
// Set up the client
|
||||
AmazonEC2 ec2Client = AmazonEC2ClientBuilder.standard()
|
||||
.withCredentials(new AWSStaticCredentialsProvider(credentials))
|
||||
.withRegion(Regions.US_EAST_1)
|
||||
.build();
|
||||
|
||||
// Create a security group
|
||||
CreateSecurityGroupRequest createSecurityGroupRequest = new CreateSecurityGroupRequest().withGroupName("BaeldungSecurityGroup")
|
||||
.withDescription("Baeldung Security Group");
|
||||
ec2Client.createSecurityGroup(createSecurityGroupRequest);
|
||||
|
||||
// Allow HTTP and SSH traffic
|
||||
IpRange ipRange1 = new IpRange().withCidrIp("0.0.0.0/0");
|
||||
|
||||
IpPermission ipPermission1 = new IpPermission().withIpv4Ranges(Arrays.asList(new IpRange[] { ipRange1 }))
|
||||
.withIpProtocol("tcp")
|
||||
.withFromPort(80)
|
||||
.withToPort(80);
|
||||
|
||||
IpPermission ipPermission2 = new IpPermission().withIpv4Ranges(Arrays.asList(new IpRange[] { ipRange1 }))
|
||||
.withIpProtocol("tcp")
|
||||
.withFromPort(22)
|
||||
.withToPort(22);
|
||||
|
||||
AuthorizeSecurityGroupIngressRequest authorizeSecurityGroupIngressRequest = new AuthorizeSecurityGroupIngressRequest()
|
||||
.withGroupName("BaeldungSecurityGroup")
|
||||
.withIpPermissions(ipPermission1, ipPermission2);
|
||||
|
||||
ec2Client.authorizeSecurityGroupIngress(authorizeSecurityGroupIngressRequest);
|
||||
|
||||
// Create KeyPair
|
||||
CreateKeyPairRequest createKeyPairRequest = new CreateKeyPairRequest()
|
||||
.withKeyName("baeldung-key-pair");
|
||||
CreateKeyPairResult createKeyPairResult = ec2Client.createKeyPair(createKeyPairRequest);
|
||||
String privateKey = createKeyPairResult
|
||||
.getKeyPair()
|
||||
.getKeyMaterial(); // make sure you keep it, the private key, Amazon doesn't store the private key
|
||||
|
||||
// See what key-pairs you've got
|
||||
DescribeKeyPairsRequest describeKeyPairsRequest = new DescribeKeyPairsRequest();
|
||||
DescribeKeyPairsResult describeKeyPairsResult = ec2Client.describeKeyPairs(describeKeyPairsRequest);
|
||||
|
||||
// Launch an Amazon Instance
|
||||
RunInstancesRequest runInstancesRequest = new RunInstancesRequest().withImageId("ami-97785bed") // https://docs.aws.amazon.com/AWSEC2/latest/UserGuide/AMIs.html | https://docs.aws.amazon.com/AWSEC2/latest/UserGuide/usingsharedamis-finding.html
|
||||
.withInstanceType("t2.micro") // https://docs.aws.amazon.com/AWSEC2/latest/UserGuide/instance-types.html
|
||||
.withMinCount(1)
|
||||
.withMaxCount(1)
|
||||
.withKeyName("baeldung-key-pair") // optional - if not present, can't connect to instance
|
||||
.withSecurityGroups("BaeldungSecurityGroup");
|
||||
|
||||
String yourInstanceId = ec2Client.runInstances(runInstancesRequest).getReservation().getInstances().get(0).getInstanceId();
|
||||
|
||||
// Start an Instance
|
||||
StartInstancesRequest startInstancesRequest = new StartInstancesRequest()
|
||||
.withInstanceIds(yourInstanceId);
|
||||
|
||||
ec2Client.startInstances(startInstancesRequest);
|
||||
|
||||
// Monitor Instances
|
||||
MonitorInstancesRequest monitorInstancesRequest = new MonitorInstancesRequest()
|
||||
.withInstanceIds(yourInstanceId);
|
||||
|
||||
ec2Client.monitorInstances(monitorInstancesRequest);
|
||||
|
||||
UnmonitorInstancesRequest unmonitorInstancesRequest = new UnmonitorInstancesRequest()
|
||||
.withInstanceIds(yourInstanceId);
|
||||
|
||||
ec2Client.unmonitorInstances(unmonitorInstancesRequest);
|
||||
|
||||
// Reboot an Instance
|
||||
|
||||
RebootInstancesRequest rebootInstancesRequest = new RebootInstancesRequest()
|
||||
.withInstanceIds(yourInstanceId);
|
||||
|
||||
ec2Client.rebootInstances(rebootInstancesRequest);
|
||||
|
||||
// Stop an Instance
|
||||
StopInstancesRequest stopInstancesRequest = new StopInstancesRequest()
|
||||
.withInstanceIds(yourInstanceId);
|
||||
|
||||
ec2Client.stopInstances(stopInstancesRequest)
|
||||
.getStoppingInstances()
|
||||
.get(0)
|
||||
.getPreviousState()
|
||||
.getName();
|
||||
|
||||
// Describe an Instance
|
||||
DescribeInstancesRequest describeInstancesRequest = new DescribeInstancesRequest();
|
||||
DescribeInstancesResult response = ec2Client.describeInstances(describeInstancesRequest);
|
||||
System.out.println(response.getReservations()
|
||||
.get(0)
|
||||
.getInstances()
|
||||
.get(0)
|
||||
.getKernelId());
|
||||
}
|
||||
}
|
@ -8,6 +8,6 @@ repositories {
|
||||
}
|
||||
|
||||
dependencies {
|
||||
compile 'org.codehaus.groovy:groovy-all:2.5.0-alpha-1'
|
||||
compile 'org.codehaus.groovy:groovy-all:2.4.13'
|
||||
testCompile 'org.spockframework:spock-core:1.1-groovy-2.4'
|
||||
}
|
||||
|
@ -1,6 +1,5 @@
|
||||
<?xml version="1.0" encoding="UTF-8"?>
|
||||
<project xmlns="http://maven.apache.org/POM/4.0.0" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
|
||||
xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd">
|
||||
<project xmlns="http://maven.apache.org/POM/4.0.0" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd">
|
||||
<modelVersion>4.0.0</modelVersion>
|
||||
|
||||
<artifactId>core-groovy</artifactId>
|
||||
@ -24,17 +23,17 @@
|
||||
<dependency>
|
||||
<groupId>org.codehaus.groovy</groupId>
|
||||
<artifactId>groovy</artifactId>
|
||||
<version>2.5.0-alpha-1</version>
|
||||
<version>2.4.13</version>
|
||||
</dependency>
|
||||
<dependency>
|
||||
<groupId>org.codehaus.groovy</groupId>
|
||||
<artifactId>groovy-all</artifactId>
|
||||
<version>2.5.0-alpha-1</version>
|
||||
<version>2.4.13</version>
|
||||
</dependency>
|
||||
<dependency>
|
||||
<groupId>org.codehaus.groovy</groupId>
|
||||
<artifactId>groovy-sql</artifactId>
|
||||
<version>2.5.0-alpha-1</version>
|
||||
<version>2.4.13</version>
|
||||
</dependency>
|
||||
<dependency>
|
||||
<groupId>org.junit.jupiter</groupId>
|
||||
|
@ -1,6 +1,5 @@
|
||||
package com.baeldung.json
|
||||
|
||||
import groovy.json.JsonGenerator
|
||||
import groovy.json.JsonOutput
|
||||
import groovy.json.JsonParserType
|
||||
import groovy.json.JsonSlurper
|
||||
@ -21,14 +20,6 @@ class JsonParser {
|
||||
JsonOutput.toJson(account)
|
||||
}
|
||||
|
||||
String toJson(Account account, String dateFormat, String... fieldsToExclude) {
|
||||
JsonGenerator generator = new JsonGenerator.Options()
|
||||
.dateFormat(dateFormat)
|
||||
.excludeFieldsByName(fieldsToExclude)
|
||||
.build()
|
||||
generator.toJson(account)
|
||||
}
|
||||
|
||||
String prettyfy(String json) {
|
||||
JsonOutput.prettyPrint(json)
|
||||
}
|
||||
|
@ -52,20 +52,6 @@ class JsonParserTest extends Specification {
|
||||
json == '{"value":15.6,"createdAt":"2018-01-01T00:00:00+0000","id":"123"}'
|
||||
}
|
||||
|
||||
def 'Should parse to Json given an Account object, a date format and fields to exclude' () {
|
||||
given:
|
||||
Account account = new Account(
|
||||
id: '123',
|
||||
value: 15.6,
|
||||
createdAt: new SimpleDateFormat('MM/dd/yyyy').parse('01/01/2018')
|
||||
)
|
||||
when:
|
||||
def json = jsonParser.toJson(account, 'MM/dd/yyyy', 'value')
|
||||
then:
|
||||
json
|
||||
json == '{"createdAt":"01/01/2018","id":"123"}'
|
||||
}
|
||||
|
||||
def 'Should prettify given a json string' () {
|
||||
given:
|
||||
String json = '{"value":15.6,"createdAt":"01/01/2018","id":"123456"}'
|
||||
|
@ -41,3 +41,5 @@
|
||||
- [Primitive Type Streams in Java 8](http://www.baeldung.com/java-8-primitive-streams)
|
||||
- [Fail-Safe Iterator vs Fail-Fast Iterator](http://www.baeldung.com/java-fail-safe-vs-fail-fast-iterator)
|
||||
- [Shuffling Collections In Java](http://www.baeldung.com/java-shuffle-collection)
|
||||
- [Java 8 StringJoiner](http://www.baeldung.com/java-string-joiner)
|
||||
- [Introduction to Spliterator in Java](http://www.baeldung.com/java-spliterator)
|
||||
|
@ -0,0 +1,71 @@
|
||||
package com.baeldung.findanelement;
|
||||
|
||||
import java.util.List;
|
||||
import java.util.ListIterator;
|
||||
import org.apache.commons.collections4.IterableUtils;
|
||||
import com.google.common.base.Predicate;
|
||||
import com.google.common.collect.Iterables;
|
||||
|
||||
public class FindElementInAList<T> {
|
||||
|
||||
public T findUsingIndexOf(T element, List<T> list) {
|
||||
int index = list.indexOf(element);
|
||||
if (index >= 0) {
|
||||
return element;
|
||||
}
|
||||
return null;
|
||||
}
|
||||
|
||||
public boolean findUsingListIterator(T element, List<T> list) {
|
||||
ListIterator<T> listIterator = list.listIterator();
|
||||
while (listIterator.hasNext()) {
|
||||
T elementFromList = listIterator.next();
|
||||
if (elementFromList.equals(element)) {
|
||||
return true;
|
||||
}
|
||||
}
|
||||
return false;
|
||||
}
|
||||
|
||||
public boolean findUsingEnhancedForLoop(T element, List<T> list) {
|
||||
for (T elementFromList : list) {
|
||||
if (element.equals(elementFromList)) {
|
||||
return true;
|
||||
}
|
||||
}
|
||||
return false;
|
||||
}
|
||||
|
||||
public T findUsingStream(T element, List<T> list) {
|
||||
return list.stream()
|
||||
.filter(integer -> integer.equals(element))
|
||||
.findFirst()
|
||||
.orElse(null);
|
||||
}
|
||||
|
||||
public T findUsingParallelStream(T element, List<T> list) {
|
||||
return list.parallelStream()
|
||||
.filter(integer -> integer.equals(element))
|
||||
.findAny()
|
||||
.orElse(null);
|
||||
}
|
||||
|
||||
public T findUsingGuava(T element, List<T> list) {
|
||||
T foundElement = Iterables.tryFind(list, new Predicate<T>() {
|
||||
public boolean apply(T input) {
|
||||
return element.equals(input);
|
||||
}
|
||||
}).orNull();
|
||||
return foundElement;
|
||||
}
|
||||
|
||||
public T findUsingApacheCommon(T element, List<T> list) {
|
||||
T foundElement = IterableUtils.find(list, new org.apache.commons.collections4.Predicate<T>() {
|
||||
public boolean evaluate(T input) {
|
||||
return element.equals(input);
|
||||
}
|
||||
});
|
||||
return foundElement;
|
||||
}
|
||||
|
||||
}
|
@ -0,0 +1,116 @@
|
||||
package com.baeldung.findanelement;
|
||||
|
||||
import static org.junit.Assert.assertNull;
|
||||
import static org.junit.Assert.assertTrue;
|
||||
import java.util.ArrayList;
|
||||
import java.util.List;
|
||||
import org.junit.Test;
|
||||
|
||||
public class FindAnElementTest {
|
||||
|
||||
private static List<Integer> scores = new ArrayList<>();
|
||||
static {
|
||||
scores.add(0);
|
||||
scores.add(1);
|
||||
scores.add(2);
|
||||
}
|
||||
|
||||
private static FindElementInAList<Integer> findElementInAList = new FindElementInAList<>();
|
||||
|
||||
@Test
|
||||
public void givenElement_whenFoundUsingIndexOf_thenReturnElement() {
|
||||
Integer scoreToFind = 1;
|
||||
Integer score = findElementInAList.findUsingIndexOf(scoreToFind, scores);
|
||||
assertTrue(score.equals(scoreToFind));
|
||||
}
|
||||
|
||||
@Test
|
||||
public void givenElement_whenNotFoundUsingListIterator_thenReturnNull() {
|
||||
boolean found = findElementInAList.findUsingListIterator(5, scores);
|
||||
assertTrue(!found);
|
||||
}
|
||||
|
||||
@Test
|
||||
public void givenElement_whenFoundListIterator_thenReturnElement() {
|
||||
Integer scoreToFind = 1;
|
||||
boolean found = findElementInAList.findUsingListIterator(scoreToFind, scores);
|
||||
assertTrue(found);
|
||||
}
|
||||
|
||||
@Test
|
||||
public void givenElement_whenNotFoundUsingIndexOf_thenReturnNull() {
|
||||
Integer score = findElementInAList.findUsingIndexOf(5, scores);
|
||||
assertNull(score);
|
||||
}
|
||||
|
||||
@Test
|
||||
public void givenElement_whenFoundUsingEnhancedForLoop_thenReturnElement() {
|
||||
Integer scoreToFind = 1;
|
||||
boolean found = findElementInAList.findUsingEnhancedForLoop(scoreToFind, scores);
|
||||
assertTrue(found);
|
||||
}
|
||||
|
||||
@Test
|
||||
public void givenElement_whenNotFoundUsingEnhancedForLoop_thenReturnNull() {
|
||||
Integer scoreToFind = 5;
|
||||
boolean found = findElementInAList.findUsingEnhancedForLoop(scoreToFind, scores);
|
||||
assertTrue(!found);
|
||||
}
|
||||
|
||||
@Test
|
||||
public void givenElement_whenFoundUsingStream_thenReturnElement() {
|
||||
Integer scoreToFind = 1;
|
||||
Integer score = findElementInAList.findUsingStream(scoreToFind, scores);
|
||||
assertTrue(score.equals(scoreToFind));
|
||||
}
|
||||
|
||||
@Test
|
||||
public void givenElement_whenNotFoundUsingStream_thenReturnNull() {
|
||||
Integer scoreToFind = 5;
|
||||
Integer score = findElementInAList.findUsingStream(scoreToFind, scores);
|
||||
assertNull(score);
|
||||
}
|
||||
|
||||
@Test
|
||||
public void givenElement_whenFoundUsingParallelStream_thenReturnElement() {
|
||||
Integer scoreToFind = 1;
|
||||
Integer score = findElementInAList.findUsingParallelStream(scoreToFind, scores);
|
||||
assertTrue(score.equals(scoreToFind));
|
||||
}
|
||||
|
||||
@Test
|
||||
public void givenElement_whenNotFoundUsingParallelStream_thenReturnNull() {
|
||||
Integer scoreToFind = 5;
|
||||
Integer score = findElementInAList.findUsingParallelStream(scoreToFind, scores);
|
||||
assertNull(score);
|
||||
}
|
||||
|
||||
@Test
|
||||
public void givenElement_whenFoundUsingGuava_thenReturnElement() {
|
||||
Integer scoreToFind = 1;
|
||||
Integer score = findElementInAList.findUsingGuava(scoreToFind, scores);
|
||||
assertTrue(score.equals(scoreToFind));
|
||||
}
|
||||
|
||||
@Test
|
||||
public void givenElement_whenNotFoundUsingGuava_thenReturnNull() {
|
||||
Integer scoreToFind = 5;
|
||||
Integer score = findElementInAList.findUsingGuava(scoreToFind, scores);
|
||||
assertNull(score);
|
||||
}
|
||||
|
||||
@Test
|
||||
public void givenElement_whenFoundUsingApacheCommons_thenReturnElement() {
|
||||
Integer scoreToFind = 1;
|
||||
Integer score = findElementInAList.findUsingApacheCommon(scoreToFind, scores);
|
||||
assertTrue(score.equals(scoreToFind));
|
||||
}
|
||||
|
||||
@Test
|
||||
public void givenElement_whenNotFoundUsingApacheCommons_thenReturnNull() {
|
||||
Integer scoreToFind = 5;
|
||||
Integer score = findElementInAList.findUsingApacheCommon(scoreToFind, scores);
|
||||
assertNull(score);
|
||||
}
|
||||
|
||||
}
|
@ -0,0 +1,89 @@
|
||||
package com.baeldung.math;
|
||||
|
||||
import static org.junit.Assert.assertEquals;
|
||||
|
||||
import org.junit.Test;
|
||||
|
||||
public class MathNewMethodsUnitTest {
|
||||
|
||||
@Test
|
||||
public void whenAddExactToInteger_thenExpectCorrectArithmeticResult() {
|
||||
assertEquals(150, Math.addExact(100, 50)); // Returns 150
|
||||
}
|
||||
|
||||
@Test
|
||||
public void whenSubstractExactFromInteger_thenExpectCorrectArithmeticResult() {
|
||||
assertEquals(50, Math.subtractExact(100, 50)); // Returns 50
|
||||
}
|
||||
|
||||
@Test
|
||||
public void whenDecrementExactInteger_thenExpectCorrectArithmeticResult() {
|
||||
assertEquals(99, Math.decrementExact(100)); // Returns 99
|
||||
}
|
||||
|
||||
@Test
|
||||
public void whenIncrementExactToInteger_thenExpectCorrectArithmeticResult() {
|
||||
assertEquals(101, Math.incrementExact(100)); // Returns 101
|
||||
}
|
||||
|
||||
@Test
|
||||
public void whenMultiplyExactTwoIntegers_thenExpectCorrectArithmeticResult() {
|
||||
assertEquals(500, Math.multiplyExact(100, 5)); // Returns 500
|
||||
}
|
||||
|
||||
@Test
|
||||
public void whenNegateExactInteger_thenExpectCorrectArithmeticResult() {
|
||||
assertEquals(-100, Math.negateExact(100)); // Returns -100
|
||||
}
|
||||
|
||||
@Test(expected = ArithmeticException.class)
|
||||
public void whenAddToMaxInteger_thenThrowsArithmeticException() {
|
||||
Math.addExact(Integer.MAX_VALUE, 1); // Throws ArithmeticException
|
||||
}
|
||||
|
||||
@Test(expected = ArithmeticException.class)
|
||||
public void whenDecrementMinInteger_thenThrowsArithmeticException() {
|
||||
Math.decrementExact(Integer.MIN_VALUE); // Throws ArithmeticException
|
||||
}
|
||||
|
||||
@Test(expected = ArithmeticException.class)
|
||||
public void whenIncrementMaxLong_thenThrowsArithmeticException() {
|
||||
Math.incrementExact(Long.MAX_VALUE); // Throws ArithmeticException
|
||||
}
|
||||
|
||||
@Test(expected = ArithmeticException.class)
|
||||
public void whenMultiplyMaxLong_thenThrowsArithmeticException() {
|
||||
Math.multiplyExact(Long.MAX_VALUE, 2); // Throws ArithmeticException
|
||||
}
|
||||
|
||||
@Test(expected = ArithmeticException.class)
|
||||
public void whenNegateMinInteger_thenThrowsArithmeticException() {
|
||||
Math.negateExact(Integer.MIN_VALUE); // MinInt value: −2.147.483.648, but MaxInt Value: 2.147.483.647 => Throws ArithmeticException
|
||||
}
|
||||
|
||||
@Test(expected = ArithmeticException.class)
|
||||
public void whenSubstractFromMinInteger_thenThrowsArithmeticException() {
|
||||
Math.subtractExact(Integer.MIN_VALUE, 1);
|
||||
}
|
||||
|
||||
@Test
|
||||
public void whenFloorDivTwoIntegers_thenExpectCorrectArithmeticResult() {
|
||||
assertEquals(3, Math.floorDiv(7, 2)); // Exact quotient is 3.5 so floor(3.5) == 3
|
||||
assertEquals(-4, Math.floorDiv(-7, 2)); // Exact quotient is -3.5 so floor(-3.5) == -4
|
||||
}
|
||||
|
||||
@Test
|
||||
public void whenModDivTwoIntegers_thenExpectCorrectArithmeticResult() {
|
||||
assertEquals(2, Math.floorMod(5, 3)); // Returns 2: floorMod for positive numbers returns the same as % operator
|
||||
assertEquals(1, Math.floorMod(-5, 3)); // Returns 1 and not 2 because floorDiv(-5, 3) is -2 and not -1 and (-2*3) + (1) = -5
|
||||
}
|
||||
|
||||
@Test
|
||||
public void whenNextDownOfDouble_thenExpectCorrectNumber() {
|
||||
double number = 3.0;
|
||||
double expected = 2.999999999999;
|
||||
double delta = 0.00000001;
|
||||
assertEquals(expected, Math.nextDown(number), delta); // The delta defines the accepted error range
|
||||
}
|
||||
|
||||
}
|
23
core-java-io/.gitignore
vendored
23
core-java-io/.gitignore
vendored
@ -1,26 +1,5 @@
|
||||
*.class
|
||||
|
||||
0.*
|
||||
|
||||
#folders#
|
||||
/target
|
||||
/neoDb*
|
||||
/data
|
||||
/src/main/webapp/WEB-INF/classes
|
||||
*/META-INF/*
|
||||
.resourceCache
|
||||
|
||||
# Packaged files #
|
||||
*.jar
|
||||
*.war
|
||||
*.ear
|
||||
|
||||
# Files generated by integration tests
|
||||
*.txt
|
||||
backup-pom.xml
|
||||
/bin/
|
||||
# *.txt
|
||||
/temp
|
||||
|
||||
#IntelliJ specific
|
||||
.idea/
|
||||
*.iml
|
@ -1,5 +1,4 @@
|
||||
<project xmlns="http://maven.apache.org/POM/4.0.0" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
|
||||
xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd">
|
||||
<project xmlns="http://maven.apache.org/POM/4.0.0" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd">
|
||||
<modelVersion>4.0.0</modelVersion>
|
||||
<groupId>com.baeldung</groupId>
|
||||
<artifactId>core-java-io</artifactId>
|
||||
@ -211,16 +210,6 @@
|
||||
<artifactId>jmh-generator-annprocess</artifactId>
|
||||
<version>1.19</version>
|
||||
</dependency>
|
||||
<dependency>
|
||||
<groupId>org.springframework</groupId>
|
||||
<artifactId>spring-web</artifactId>
|
||||
<version>4.3.4.RELEASE</version>
|
||||
</dependency>
|
||||
<dependency>
|
||||
<groupId>org.springframework.boot</groupId>
|
||||
<artifactId>spring-boot-starter</artifactId>
|
||||
<version>1.5.8.RELEASE</version>
|
||||
</dependency>
|
||||
<dependency>
|
||||
<groupId>org.hsqldb</groupId>
|
||||
<artifactId>hsqldb</artifactId>
|
||||
@ -264,99 +253,6 @@
|
||||
</configuration>
|
||||
</plugin>
|
||||
|
||||
<plugin>
|
||||
<groupId>org.apache.maven.plugins</groupId>
|
||||
<artifactId>maven-dependency-plugin</artifactId>
|
||||
<executions>
|
||||
<execution>
|
||||
<id>copy-dependencies</id>
|
||||
<phase>prepare-package</phase>
|
||||
<goals>
|
||||
<goal>copy-dependencies</goal>
|
||||
</goals>
|
||||
<configuration>
|
||||
<outputDirectory>${project.build.directory}/libs</outputDirectory>
|
||||
</configuration>
|
||||
</execution>
|
||||
</executions>
|
||||
</plugin>
|
||||
|
||||
<plugin>
|
||||
<groupId>org.apache.maven.plugins</groupId>
|
||||
<artifactId>maven-jar-plugin</artifactId>
|
||||
<configuration>
|
||||
<archive>
|
||||
<manifest>
|
||||
<addClasspath>true</addClasspath>
|
||||
<classpathPrefix>libs/</classpathPrefix>
|
||||
<mainClass>org.baeldung.executable.ExecutableMavenJar</mainClass>
|
||||
</manifest>
|
||||
</archive>
|
||||
</configuration>
|
||||
</plugin>
|
||||
|
||||
<plugin>
|
||||
<groupId>org.apache.maven.plugins</groupId>
|
||||
<artifactId>maven-assembly-plugin</artifactId>
|
||||
<executions>
|
||||
<execution>
|
||||
<phase>package</phase>
|
||||
<goals>
|
||||
<goal>single</goal>
|
||||
</goals>
|
||||
<configuration>
|
||||
<archiveBaseDirectory>${project.basedir}</archiveBaseDirectory>
|
||||
<archive>
|
||||
<manifest>
|
||||
<mainClass>org.baeldung.executable.ExecutableMavenJar</mainClass>
|
||||
</manifest>
|
||||
</archive>
|
||||
<descriptorRefs>
|
||||
<descriptorRef>jar-with-dependencies</descriptorRef>
|
||||
</descriptorRefs>
|
||||
</configuration>
|
||||
</execution>
|
||||
</executions>
|
||||
</plugin>
|
||||
|
||||
<plugin>
|
||||
<groupId>org.apache.maven.plugins</groupId>
|
||||
<artifactId>maven-shade-plugin</artifactId>
|
||||
<executions>
|
||||
<execution>
|
||||
<goals>
|
||||
<goal>shade</goal>
|
||||
</goals>
|
||||
<configuration>
|
||||
<shadedArtifactAttached>true</shadedArtifactAttached>
|
||||
<transformers>
|
||||
<transformer
|
||||
implementation="org.apache.maven.plugins.shade.resource.ManifestResourceTransformer">
|
||||
<mainClass>org.baeldung.executable.ExecutableMavenJar</mainClass>
|
||||
</transformer>
|
||||
</transformers>
|
||||
</configuration>
|
||||
</execution>
|
||||
</executions>
|
||||
</plugin>
|
||||
|
||||
<plugin>
|
||||
<groupId>com.jolira</groupId>
|
||||
<artifactId>onejar-maven-plugin</artifactId>
|
||||
<executions>
|
||||
<execution>
|
||||
<configuration>
|
||||
<mainClass>org.baeldung.executable.ExecutableMavenJar</mainClass>
|
||||
<attachToBuild>true</attachToBuild>
|
||||
<filename>${project.build.finalName}-onejar.${project.packaging}</filename>
|
||||
</configuration>
|
||||
<goals>
|
||||
<goal>one-jar</goal>
|
||||
</goals>
|
||||
</execution>
|
||||
</executions>
|
||||
</plugin>
|
||||
|
||||
<plugin>
|
||||
<groupId>org.springframework.boot</groupId>
|
||||
<artifactId>spring-boot-maven-plugin</artifactId>
|
||||
@ -384,7 +280,7 @@
|
||||
<argument>-Xmx300m</argument>
|
||||
<argument>-XX:+UseParallelGC</argument>
|
||||
<argument>-classpath</argument>
|
||||
<classpath/>
|
||||
<classpath />
|
||||
<argument>com.baeldung.outofmemoryerror.OutOfMemoryGCLimitExceed</argument>
|
||||
</arguments>
|
||||
</configuration>
|
||||
@ -442,7 +338,7 @@
|
||||
<executions>
|
||||
<execution>
|
||||
<id>run-benchmarks</id>
|
||||
<!-- <phase>integration-test</phase>-->
|
||||
<!-- <phase>integration-test</phase> -->
|
||||
<phase>none</phase>
|
||||
<goals>
|
||||
<goal>exec</goal>
|
||||
@ -452,7 +348,7 @@
|
||||
<executable>java</executable>
|
||||
<arguments>
|
||||
<argument>-classpath</argument>
|
||||
<classpath/>
|
||||
<classpath />
|
||||
<argument>org.openjdk.jmh.Main</argument>
|
||||
<argument>.*</argument>
|
||||
</arguments>
|
||||
|
@ -1,2 +0,0 @@
|
||||
line 1
|
||||
a second line
|
@ -30,8 +30,7 @@ public class FileCopierTest {
|
||||
@Test
|
||||
public void givenIoAPI_whenCopied_thenCopyExistsWithSameContents() throws IOException {
|
||||
File copied = new File("src/test/resources/copiedWithIo.txt");
|
||||
try (InputStream in = new BufferedInputStream(new FileInputStream(original));
|
||||
OutputStream out = new BufferedOutputStream(new FileOutputStream(copied))) {
|
||||
try (InputStream in = new BufferedInputStream(new FileInputStream(original)); OutputStream out = new BufferedOutputStream(new FileOutputStream(copied))) {
|
||||
byte[] buffer = new byte[1024];
|
||||
int lengthRead;
|
||||
while ((lengthRead = in.read(buffer)) > 0) {
|
||||
|
@ -3,7 +3,6 @@ package com.baeldung.file;
|
||||
import org.apache.commons.io.FileUtils;
|
||||
import org.hamcrest.CoreMatchers;
|
||||
import org.hamcrest.Matchers;
|
||||
import org.junit.Assert;
|
||||
import org.junit.Test;
|
||||
|
||||
import java.io.BufferedReader;
|
||||
|
@ -42,19 +42,14 @@ public class FilesTest {
|
||||
CharSink chs = com.google.common.io.Files.asCharSink(file, Charsets.UTF_8, FileWriteMode.APPEND);
|
||||
chs.write("Spain\r\n");
|
||||
|
||||
assertThat(StreamUtils.getStringFromInputStream(
|
||||
new FileInputStream(fileName)))
|
||||
.isEqualTo("UK\r\n" + "US\r\n" + "Germany\r\n" + "Spain\r\n");
|
||||
assertThat(StreamUtils.getStringFromInputStream(new FileInputStream(fileName))).isEqualTo("UK\r\n" + "US\r\n" + "Germany\r\n" + "Spain\r\n");
|
||||
}
|
||||
|
||||
|
||||
@Test
|
||||
public void whenAppendToFileUsingFiles_thenCorrect() throws IOException {
|
||||
Files.write(Paths.get(fileName), "Spain\r\n".getBytes(), StandardOpenOption.APPEND);
|
||||
|
||||
assertThat(StreamUtils.getStringFromInputStream(
|
||||
new FileInputStream(fileName)))
|
||||
.isEqualTo("UK\r\n" + "US\r\n" + "Germany\r\n" + "Spain\r\n");
|
||||
assertThat(StreamUtils.getStringFromInputStream(new FileInputStream(fileName))).isEqualTo("UK\r\n" + "US\r\n" + "Germany\r\n" + "Spain\r\n");
|
||||
}
|
||||
|
||||
@Test
|
||||
@ -62,9 +57,7 @@ public class FilesTest {
|
||||
File file = new File(fileName);
|
||||
FileUtils.writeStringToFile(file, "Spain\r\n", StandardCharsets.UTF_8, true);
|
||||
|
||||
assertThat(StreamUtils.getStringFromInputStream(
|
||||
new FileInputStream(fileName)))
|
||||
.isEqualTo("UK\r\n" + "US\r\n" + "Germany\r\n" + "Spain\r\n");
|
||||
assertThat(StreamUtils.getStringFromInputStream(new FileInputStream(fileName))).isEqualTo("UK\r\n" + "US\r\n" + "Germany\r\n" + "Spain\r\n");
|
||||
}
|
||||
|
||||
@Test
|
||||
@ -73,9 +66,7 @@ public class FilesTest {
|
||||
fos.write("Spain\r\n".getBytes());
|
||||
fos.close();
|
||||
|
||||
assertThat(StreamUtils.getStringFromInputStream(
|
||||
new FileInputStream(fileName)))
|
||||
.isEqualTo("UK\r\n" + "US\r\n" + "Germany\r\n" + "Spain\r\n");
|
||||
assertThat(StreamUtils.getStringFromInputStream(new FileInputStream(fileName))).isEqualTo("UK\r\n" + "US\r\n" + "Germany\r\n" + "Spain\r\n");
|
||||
}
|
||||
|
||||
@Test
|
||||
@ -86,9 +77,6 @@ public class FilesTest {
|
||||
bw.newLine();
|
||||
bw.close();
|
||||
|
||||
assertThat(
|
||||
StreamUtils.getStringFromInputStream(
|
||||
new FileInputStream(fileName)))
|
||||
.isEqualTo("UK\r\n" + "US\r\n" + "Germany\r\n" + "Spain\n");
|
||||
assertThat(StreamUtils.getStringFromInputStream(new FileInputStream(fileName))).isEqualTo("UK\r\n" + "US\r\n" + "Germany\r\n" + "Spain\n");
|
||||
}
|
||||
}
|
@ -9,7 +9,6 @@ import java.net.URI;
|
||||
import java.nio.file.NoSuchFileException;
|
||||
import java.nio.file.Path;
|
||||
import java.nio.file.Paths;
|
||||
import java.util.Date;
|
||||
|
||||
import org.junit.Test;
|
||||
|
||||
|
@ -17,18 +17,19 @@ import java.util.concurrent.Future;
|
||||
import static org.junit.Assert.assertEquals;
|
||||
|
||||
public class AsyncFileIntegrationTest {
|
||||
|
||||
@Test
|
||||
public void givenPath_whenReadsContentWithFuture_thenCorrect() throws IOException, ExecutionException, InterruptedException {
|
||||
Path path = Paths.get(URI.create(this.getClass().getClassLoader().getResource("file.txt").toString()));
|
||||
AsynchronousFileChannel fileChannel = AsynchronousFileChannel.open(path, StandardOpenOption.READ);
|
||||
final Path path = Paths.get(URI.create(this.getClass().getClassLoader().getResource("file.txt").toString()));
|
||||
final AsynchronousFileChannel fileChannel = AsynchronousFileChannel.open(path, StandardOpenOption.READ);
|
||||
|
||||
ByteBuffer buffer = ByteBuffer.allocate(1024);
|
||||
final ByteBuffer buffer = ByteBuffer.allocate(1024);
|
||||
|
||||
Future<Integer> operation = fileChannel.read(buffer, 0);
|
||||
final Future<Integer> operation = fileChannel.read(buffer, 0);
|
||||
|
||||
operation.get();
|
||||
|
||||
String fileContent = new String(buffer.array()).trim();
|
||||
final String fileContent = new String(buffer.array()).trim();
|
||||
buffer.clear();
|
||||
|
||||
assertEquals(fileContent, "baeldung.com");
|
||||
@ -36,18 +37,16 @@ public class AsyncFileIntegrationTest {
|
||||
|
||||
@Test
|
||||
public void givenPath_whenReadsContentWithCompletionHandler_thenCorrect() throws IOException {
|
||||
Path path = Paths.get(URI.create(AsyncFileIntegrationTest.class.getResource("/file.txt").toString()));
|
||||
AsynchronousFileChannel fileChannel = AsynchronousFileChannel.open(path, StandardOpenOption.READ);
|
||||
final Path path = Paths.get(URI.create(this.getClass().getClassLoader().getResource("file.txt").toString()));
|
||||
final AsynchronousFileChannel fileChannel = AsynchronousFileChannel.open(path, StandardOpenOption.READ);
|
||||
|
||||
ByteBuffer buffer = ByteBuffer.allocate(1024);
|
||||
final ByteBuffer buffer = ByteBuffer.allocate(1024);
|
||||
|
||||
fileChannel.read(buffer, 0, buffer, new CompletionHandler<Integer, ByteBuffer>() {
|
||||
|
||||
@Override
|
||||
public void completed(Integer result, ByteBuffer attachment) {
|
||||
// result is number of bytes read
|
||||
// attachment is the buffer
|
||||
|
||||
}
|
||||
|
||||
@Override
|
||||
@ -59,42 +58,40 @@ public class AsyncFileIntegrationTest {
|
||||
|
||||
@Test
|
||||
public void givenPathAndContent_whenWritesToFileWithFuture_thenCorrect() throws IOException, ExecutionException, InterruptedException {
|
||||
String fileName = "temp";
|
||||
Path path = Paths.get(fileName);
|
||||
AsynchronousFileChannel fileChannel = AsynchronousFileChannel.open(path, StandardOpenOption.WRITE, StandardOpenOption.CREATE);
|
||||
final String fileName = "temp";
|
||||
final Path path = Paths.get(fileName);
|
||||
final AsynchronousFileChannel fileChannel = AsynchronousFileChannel.open(path, StandardOpenOption.WRITE, StandardOpenOption.CREATE);
|
||||
|
||||
ByteBuffer buffer = ByteBuffer.allocate(1024);
|
||||
long position = 0;
|
||||
final ByteBuffer buffer = ByteBuffer.allocate(1024);
|
||||
final long position = 0;
|
||||
|
||||
buffer.put("hello world".getBytes());
|
||||
buffer.flip();
|
||||
|
||||
Future<Integer> operation = fileChannel.write(buffer, position);
|
||||
final Future<Integer> operation = fileChannel.write(buffer, position);
|
||||
buffer.clear();
|
||||
|
||||
operation.get();
|
||||
|
||||
String content = readContent(path);
|
||||
final String content = readContent(path);
|
||||
assertEquals("hello world", content);
|
||||
}
|
||||
|
||||
@Test
|
||||
public void givenPathAndContent_whenWritesToFileWithHandler_thenCorrect() throws IOException {
|
||||
String fileName = UUID.randomUUID().toString();
|
||||
Path path = Paths.get(fileName);
|
||||
AsynchronousFileChannel fileChannel = AsynchronousFileChannel.open(path, StandardOpenOption.WRITE, StandardOpenOption.CREATE, StandardOpenOption.DELETE_ON_CLOSE);
|
||||
final String fileName = UUID.randomUUID().toString();
|
||||
final Path path = Paths.get(fileName);
|
||||
final AsynchronousFileChannel fileChannel = AsynchronousFileChannel.open(path, StandardOpenOption.WRITE, StandardOpenOption.CREATE, StandardOpenOption.DELETE_ON_CLOSE);
|
||||
|
||||
ByteBuffer buffer = ByteBuffer.allocate(1024);
|
||||
final ByteBuffer buffer = ByteBuffer.allocate(1024);
|
||||
buffer.put("hello world".getBytes());
|
||||
buffer.flip();
|
||||
|
||||
fileChannel.write(buffer, 0, buffer, new CompletionHandler<Integer, ByteBuffer>() {
|
||||
|
||||
@Override
|
||||
public void completed(Integer result, ByteBuffer attachment) {
|
||||
// result is number of bytes written
|
||||
// attachment is the buffer
|
||||
|
||||
}
|
||||
|
||||
@Override
|
||||
@ -104,23 +101,25 @@ public class AsyncFileIntegrationTest {
|
||||
});
|
||||
}
|
||||
|
||||
public static String readContent(Path file) throws ExecutionException, InterruptedException {
|
||||
//
|
||||
|
||||
private String readContent(Path file) throws ExecutionException, InterruptedException {
|
||||
AsynchronousFileChannel fileChannel = null;
|
||||
try {
|
||||
fileChannel = AsynchronousFileChannel.open(file, StandardOpenOption.READ);
|
||||
} catch (IOException e) {
|
||||
// TODO Auto-generated catch block
|
||||
e.printStackTrace();
|
||||
}
|
||||
|
||||
ByteBuffer buffer = ByteBuffer.allocate(1024);
|
||||
final ByteBuffer buffer = ByteBuffer.allocate(1024);
|
||||
|
||||
Future<Integer> operation = fileChannel.read(buffer, 0);
|
||||
final Future<Integer> operation = fileChannel.read(buffer, 0);
|
||||
|
||||
operation.get();
|
||||
|
||||
String fileContent = new String(buffer.array()).trim();
|
||||
final String fileContent = new String(buffer.array()).trim();
|
||||
buffer.clear();
|
||||
return fileContent;
|
||||
}
|
||||
|
||||
}
|
@ -20,7 +20,6 @@ public class BasicAttribsIntegrationTest {
|
||||
|
||||
private static final Logger LOG = LoggerFactory.getLogger(BasicAttribsIntegrationTest.class);
|
||||
|
||||
|
||||
private static final String HOME = System.getProperty("user.home");
|
||||
private static BasicFileAttributes basicAttribs;
|
||||
|
||||
|
@ -55,12 +55,7 @@ public class JavaFolderSizeUnitTest {
|
||||
@Test
|
||||
public void whenGetFolderSizeUsingJava8_thenCorrect() throws IOException {
|
||||
final Path folder = Paths.get(path);
|
||||
final long size = Files.walk(folder)
|
||||
.filter(p -> p.toFile()
|
||||
.isFile())
|
||||
.mapToLong(p -> p.toFile()
|
||||
.length())
|
||||
.sum();
|
||||
final long size = Files.walk(folder).filter(p -> p.toFile().isFile()).mapToLong(p -> p.toFile().length()).sum();
|
||||
|
||||
assertEquals(EXPECTED_SIZE, size);
|
||||
}
|
||||
@ -77,12 +72,8 @@ public class JavaFolderSizeUnitTest {
|
||||
public void whenGetFolderSizeUsingGuava_thenCorrect() {
|
||||
final File folder = new File(path);
|
||||
|
||||
final Iterable<File> files = com.google.common.io.Files.fileTreeTraverser()
|
||||
.breadthFirstTraversal(folder);
|
||||
final long size = StreamSupport.stream(files.spliterator(), false)
|
||||
.filter(File::isFile)
|
||||
.mapToLong(File::length)
|
||||
.sum();
|
||||
final Iterable<File> files = com.google.common.io.Files.fileTreeTraverser().breadthFirstTraversal(folder);
|
||||
final long size = StreamSupport.stream(files.spliterator(), false).filter(File::isFile).mapToLong(File::length).sum();
|
||||
|
||||
assertEquals(EXPECTED_SIZE, size);
|
||||
}
|
||||
|
@ -18,14 +18,13 @@ import static org.junit.Assert.assertNotNull;
|
||||
|
||||
public class MappedByteBufferUnitTest {
|
||||
|
||||
|
||||
@Test
|
||||
public void givenFileChannel_whenReadToTheMappedByteBuffer_thenShouldSuccess() throws Exception {
|
||||
//given
|
||||
// given
|
||||
CharBuffer charBuffer = null;
|
||||
Path pathToRead = getFileURIFromResources("fileToRead.txt");
|
||||
|
||||
//when
|
||||
// when
|
||||
try (FileChannel fileChannel = (FileChannel) Files.newByteChannel(pathToRead, EnumSet.of(StandardOpenOption.READ))) {
|
||||
MappedByteBuffer mappedByteBuffer = fileChannel.map(FileChannel.MapMode.READ_ONLY, 0, fileChannel.size());
|
||||
|
||||
@ -34,20 +33,19 @@ public class MappedByteBufferUnitTest {
|
||||
}
|
||||
}
|
||||
|
||||
//then
|
||||
// then
|
||||
assertNotNull(charBuffer);
|
||||
assertEquals(charBuffer.toString(), "This is a content of the file");
|
||||
}
|
||||
|
||||
@Test
|
||||
public void givenPath_whenWriteToItUsingMappedByteBuffer_thenShouldSuccessfullyWrite() throws Exception {
|
||||
//given
|
||||
CharBuffer charBuffer = CharBuffer.wrap("This will be written to the file");
|
||||
Path pathToWrite = getFileURIFromResources("fileToWriteTo.txt");
|
||||
// given
|
||||
final CharBuffer charBuffer = CharBuffer.wrap("This will be written to the file");
|
||||
final Path pathToWrite = getFileURIFromResources("fileToWriteTo.txt");
|
||||
|
||||
//when
|
||||
try (FileChannel fileChannel = (FileChannel) Files.newByteChannel(pathToWrite,
|
||||
EnumSet.of(StandardOpenOption.READ, StandardOpenOption.WRITE, StandardOpenOption.TRUNCATE_EXISTING))) {
|
||||
// when
|
||||
try (FileChannel fileChannel = (FileChannel) Files.newByteChannel(pathToWrite, EnumSet.of(StandardOpenOption.READ, StandardOpenOption.WRITE, StandardOpenOption.TRUNCATE_EXISTING))) {
|
||||
MappedByteBuffer mappedByteBuffer = fileChannel.map(FileChannel.MapMode.READ_WRITE, 0, charBuffer.length());
|
||||
|
||||
if (mappedByteBuffer != null) {
|
||||
@ -55,14 +53,16 @@ public class MappedByteBufferUnitTest {
|
||||
}
|
||||
}
|
||||
|
||||
//then
|
||||
List<String> fileContent = Files.readAllLines(pathToWrite);
|
||||
// then
|
||||
final List<String> fileContent = Files.readAllLines(pathToWrite);
|
||||
assertEquals(fileContent.get(0), "This will be written to the file");
|
||||
|
||||
}
|
||||
|
||||
private Path getFileURIFromResources(String fileName) throws Exception {
|
||||
ClassLoader classLoader = getClass().getClassLoader();
|
||||
//
|
||||
|
||||
private final Path getFileURIFromResources(String fileName) throws Exception {
|
||||
final ClassLoader classLoader = getClass().getClassLoader();
|
||||
return Paths.get(classLoader.getResource(fileName).toURI());
|
||||
}
|
||||
}
|
||||
|
@ -1,47 +0,0 @@
|
||||
package com.baeldung.stream;
|
||||
|
||||
import static org.junit.Assert.assertTrue;
|
||||
|
||||
import java.io.File;
|
||||
import java.io.IOException;
|
||||
|
||||
import org.junit.Test;
|
||||
|
||||
public class FileCopyTest {
|
||||
|
||||
@Test
|
||||
public void whenUsingStream_thenCopyFile() throws IOException {
|
||||
File src = new File("src" + File.separator + "test" + File.separator + "resources" + File.separator + "copyTest" + File.separator + "src" + File.separator + "test_stream.txt");
|
||||
File dest = new File("src" + File.separator + "test" + File.separator + "resources" + File.separator + "copyTest" + File.separator + "dest" + File.separator + "test_stream.txt");
|
||||
FileCopy.copyFileUsingStream(src, dest);
|
||||
assertTrue(dest.exists());
|
||||
dest.delete();
|
||||
}
|
||||
|
||||
@Test
|
||||
public void whenUsingFiles_thenCopyFile() throws IOException {
|
||||
File src = new File("src" + File.separator + "test" + File.separator + "resources" + File.separator + "copyTest" + File.separator + "src" + File.separator + "test_files.txt");
|
||||
File dest = new File("src" + File.separator + "test" + File.separator + "resources" + File.separator + "copyTest" + File.separator + "dest" + File.separator + "test_files.txt");
|
||||
FileCopy.copyFileUsingJavaFiles(src, dest);
|
||||
assertTrue(dest.exists());
|
||||
dest.delete();
|
||||
}
|
||||
|
||||
@Test
|
||||
public void whenUsingChannel_thenCopyFile() throws IOException {
|
||||
File src = new File("src" + File.separator + "test" + File.separator + "resources" + File.separator + "copyTest" + File.separator + "src" + File.separator + "test_channel.txt");
|
||||
File dest = new File("src" + File.separator + "test" + File.separator + "resources" + File.separator + "copyTest" + File.separator + "dest" + File.separator + "test_channel.txt");
|
||||
FileCopy.copyFileUsingChannel(src, dest);
|
||||
assertTrue(dest.exists());
|
||||
dest.delete();
|
||||
}
|
||||
|
||||
@Test
|
||||
public void whenUsingApache_thenCopyFile() throws IOException {
|
||||
File src = new File("src" + File.separator + "test" + File.separator + "resources" + File.separator + "copyTest" + File.separator + "src" + File.separator + "test_apache.txt");
|
||||
File dest = new File("src" + File.separator + "test" + File.separator + "resources" + File.separator + "copyTest" + File.separator + "dest" + File.separator + "test_apache.txt");
|
||||
FileCopy.copyFileUsingApacheCommonsIO(src, dest);
|
||||
assertTrue(dest.exists());
|
||||
dest.delete();
|
||||
}
|
||||
}
|
@ -0,0 +1,52 @@
|
||||
package com.baeldung.stream;
|
||||
|
||||
import static org.junit.Assert.assertTrue;
|
||||
|
||||
import java.io.File;
|
||||
import java.io.IOException;
|
||||
|
||||
import org.junit.Test;
|
||||
|
||||
public class FileCopyUnitTest {
|
||||
|
||||
@Test
|
||||
public void whenUsingStream_thenCopyFile() throws IOException {
|
||||
final File src = new File("src" + File.separator + "test" + File.separator + "resources" + File.separator + "copyTest" + File.separator + "src" + File.separator + "test_stream.txt");
|
||||
final File dest = new File("src" + File.separator + "test" + File.separator + "resources" + File.separator + "copyTest" + File.separator + "dest" + File.separator + "test_stream.txt");
|
||||
FileCopy.copyFileUsingStream(src, dest);
|
||||
|
||||
assertTrue(dest.exists());
|
||||
dest.delete();
|
||||
}
|
||||
|
||||
@Test
|
||||
public void whenUsingFiles_thenCopyFile() throws IOException {
|
||||
final File src = new File("src" + File.separator + "test" + File.separator + "resources" + File.separator + "copyTest" + File.separator + "src" + File.separator + "test_files.txt");
|
||||
final File dest = new File("src" + File.separator + "test" + File.separator + "resources" + File.separator + "copyTest" + File.separator + "dest" + File.separator + "test_files.txt");
|
||||
FileCopy.copyFileUsingJavaFiles(src, dest);
|
||||
|
||||
assertTrue(dest.exists());
|
||||
dest.delete();
|
||||
}
|
||||
|
||||
@Test
|
||||
public void whenUsingChannel_thenCopyFile() throws IOException {
|
||||
final File src = new File("src" + File.separator + "test" + File.separator + "resources" + File.separator + "copyTest" + File.separator + "src" + File.separator + "test_channel.txt");
|
||||
final File dest = new File("src" + File.separator + "test" + File.separator + "resources" + File.separator + "copyTest" + File.separator + "dest" + File.separator + "test_channel.txt");
|
||||
FileCopy.copyFileUsingChannel(src, dest);
|
||||
|
||||
assertTrue(dest.exists());
|
||||
dest.delete();
|
||||
}
|
||||
|
||||
@Test
|
||||
public void whenUsingApache_thenCopyFile() throws IOException {
|
||||
final File src = new File("src" + File.separator + "test" + File.separator + "resources" + File.separator + "copyTest" + File.separator + "src" + File.separator + "test_apache.txt");
|
||||
final File dest = new File("src" + File.separator + "test" + File.separator + "resources" + File.separator + "copyTest" + File.separator + "dest" + File.separator + "test_apache.txt");
|
||||
FileCopy.copyFileUsingApacheCommonsIO(src, dest);
|
||||
|
||||
assertTrue(dest.exists());
|
||||
dest.delete();
|
||||
}
|
||||
|
||||
}
|
@ -152,11 +152,11 @@ public class JavaInputStreamToXUnitTest {
|
||||
|
||||
@Test
|
||||
public final void whenConvertingToFile_thenCorrect() throws IOException {
|
||||
final InputStream initialStream = new FileInputStream(new File("src/main/resources/sample.txt"));
|
||||
final InputStream initialStream = new FileInputStream(new File("src/test/resources/sample.txt"));
|
||||
final byte[] buffer = new byte[initialStream.available()];
|
||||
initialStream.read(buffer);
|
||||
|
||||
final File targetFile = new File("src/main/resources/targetFile.tmp");
|
||||
final File targetFile = new File("src/test/resources/targetFile.tmp");
|
||||
final OutputStream outStream = new FileOutputStream(targetFile);
|
||||
outStream.write(buffer);
|
||||
|
||||
@ -166,8 +166,8 @@ public class JavaInputStreamToXUnitTest {
|
||||
|
||||
@Test
|
||||
public final void whenConvertingInProgressToFile_thenCorrect() throws IOException {
|
||||
final InputStream initialStream = new FileInputStream(new File("src/main/resources/sample.txt"));
|
||||
final File targetFile = new File("src/main/resources/targetFile.tmp");
|
||||
final InputStream initialStream = new FileInputStream(new File("src/test/resources/sample.txt"));
|
||||
final File targetFile = new File("src/test/resources/targetFile.tmp");
|
||||
final OutputStream outStream = new FileOutputStream(targetFile);
|
||||
|
||||
final byte[] buffer = new byte[8 * 1024];
|
||||
@ -182,8 +182,8 @@ public class JavaInputStreamToXUnitTest {
|
||||
|
||||
@Test
|
||||
public final void whenConvertingAnInProgressInputStreamToFile_thenCorrect2() throws IOException {
|
||||
final InputStream initialStream = new FileInputStream(new File("src/main/resources/sample.txt"));
|
||||
final File targetFile = new File("src/main/resources/targetFile.tmp");
|
||||
final InputStream initialStream = new FileInputStream(new File("src/test/resources/sample.txt"));
|
||||
final File targetFile = new File("src/test/resources/targetFile.tmp");
|
||||
|
||||
java.nio.file.Files.copy(initialStream, targetFile.toPath(), StandardCopyOption.REPLACE_EXISTING);
|
||||
|
||||
@ -192,11 +192,11 @@ public class JavaInputStreamToXUnitTest {
|
||||
|
||||
@Test
|
||||
public final void whenConvertingInputStreamToFile_thenCorrect3() throws IOException {
|
||||
final InputStream initialStream = new FileInputStream(new File("src/main/resources/sample.txt"));
|
||||
final InputStream initialStream = new FileInputStream(new File("src/test/resources/sample.txt"));
|
||||
final byte[] buffer = new byte[initialStream.available()];
|
||||
initialStream.read(buffer);
|
||||
|
||||
final File targetFile = new File("src/main/resources/targetFile.tmp");
|
||||
final File targetFile = new File("src/test/resources/targetFile.tmp");
|
||||
Files.write(buffer, targetFile);
|
||||
|
||||
IOUtils.closeQuietly(initialStream);
|
||||
@ -204,9 +204,9 @@ public class JavaInputStreamToXUnitTest {
|
||||
|
||||
@Test
|
||||
public final void whenConvertingInputStreamToFile_thenCorrect4() throws IOException {
|
||||
final InputStream initialStream = FileUtils.openInputStream(new File("src/main/resources/sample.txt"));
|
||||
final InputStream initialStream = FileUtils.openInputStream(new File("src/test/resources/sample.txt"));
|
||||
|
||||
final File targetFile = new File("src/main/resources/targetFile.tmp");
|
||||
final File targetFile = new File("src/test/resources/targetFile.tmp");
|
||||
|
||||
FileUtils.copyInputStreamToFile(initialStream, targetFile);
|
||||
}
|
||||
|
@ -18,7 +18,6 @@ import static org.junit.Assert.assertTrue;
|
||||
|
||||
public class JavaReadFromFileUnitTest {
|
||||
|
||||
|
||||
private static final Logger LOG = LoggerFactory.getLogger(JavaReadFromFileUnitTest.class);
|
||||
|
||||
@Test
|
||||
@ -107,11 +106,12 @@ public class JavaReadFromFileUnitTest {
|
||||
|
||||
@Test
|
||||
public void whenReadUTFEncodedFile_thenCorrect() throws IOException {
|
||||
final String expected_value = "青空";
|
||||
final String expected_value = "é<EFBFBD>’空";
|
||||
final BufferedReader reader = new BufferedReader(new InputStreamReader(new FileInputStream("src/test/resources/test_read7.in"), "UTF-8"));
|
||||
final String currentLine = reader.readLine();
|
||||
reader.close();
|
||||
LOG.debug(currentLine);
|
||||
|
||||
assertEquals(expected_value, currentLine);
|
||||
}
|
||||
|
||||
|
@ -68,7 +68,7 @@ public class JavaXToInputStreamUnitTest {
|
||||
|
||||
@Test
|
||||
public final void givenUsingPlainJava_whenConvertingFileToInputStream_thenCorrect() throws IOException {
|
||||
final File initialFile = new File("src/main/resources/sample.txt");
|
||||
final File initialFile = new File("src/test/resources/sample.txt");
|
||||
final InputStream targetStream = new FileInputStream(initialFile);
|
||||
|
||||
IOUtils.closeQuietly(targetStream);
|
||||
@ -76,7 +76,7 @@ public class JavaXToInputStreamUnitTest {
|
||||
|
||||
@Test
|
||||
public final void givenUsingGuava_whenConvertingFileToInputStream_thenCorrect() throws IOException {
|
||||
final File initialFile = new File("src/main/resources/sample.txt");
|
||||
final File initialFile = new File("src/test/resources/sample.txt");
|
||||
final InputStream targetStream = Files.asByteSource(initialFile).openStream();
|
||||
|
||||
IOUtils.closeQuietly(targetStream);
|
||||
@ -84,7 +84,7 @@ public class JavaXToInputStreamUnitTest {
|
||||
|
||||
@Test
|
||||
public final void givenUsingCommonsIO_whenConvertingFileToInputStream_thenCorrect() throws IOException {
|
||||
final File initialFile = new File("src/main/resources/sample.txt");
|
||||
final File initialFile = new File("src/test/resources/sample.txt");
|
||||
final InputStream targetStream = FileUtils.openInputStream(initialFile);
|
||||
|
||||
IOUtils.closeQuietly(targetStream);
|
||||
|
0
core-java-io/src/test/resources/copiedWithIo.txt
Normal file
0
core-java-io/src/test/resources/copiedWithIo.txt
Normal file
0
core-java-io/src/test/resources/copiedWithNio.txt
Normal file
0
core-java-io/src/test/resources/copiedWithNio.txt
Normal file
0
core-java-io/src/test/resources/fileToWriteTo.txt
Normal file
0
core-java-io/src/test/resources/fileToWriteTo.txt
Normal file
1
core-java-io/src/test/resources/initialFile.txt
Normal file
1
core-java-io/src/test/resources/initialFile.txt
Normal file
@ -0,0 +1 @@
|
||||
With Commons IO
|
0
core-java-io/src/test/resources/original.txt
Normal file
0
core-java-io/src/test/resources/original.txt
Normal file
1
core-java-io/src/test/resources/sample.txt
Normal file
1
core-java-io/src/test/resources/sample.txt
Normal file
@ -0,0 +1 @@
|
||||
Hello World
|
1
core-java-io/src/test/resources/targetFile.tmp
Normal file
1
core-java-io/src/test/resources/targetFile.tmp
Normal file
@ -0,0 +1 @@
|
||||
Hello World
|
1
core-java-io/src/test/resources/targetFile.txt
Normal file
1
core-java-io/src/test/resources/targetFile.txt
Normal file
@ -0,0 +1 @@
|
||||
Some textSome text
|
1
core-java-io/src/test/resources/test_write.txt
Normal file
1
core-java-io/src/test/resources/test_write.txt
Normal file
@ -0,0 +1 @@
|
||||
Some StringProduct name is iPhone and its price is 1000 $
|
BIN
core-java-io/src/test/resources/test_write_1.txt
Normal file
BIN
core-java-io/src/test/resources/test_write_1.txt
Normal file
Binary file not shown.
BIN
core-java-io/src/test/resources/test_write_2.txt
Normal file
BIN
core-java-io/src/test/resources/test_write_2.txt
Normal file
Binary file not shown.
1
core-java-io/src/test/resources/test_write_3.txt
Normal file
1
core-java-io/src/test/resources/test_write_3.txt
Normal file
@ -0,0 +1 @@
|
||||
Hello World
|
BIN
core-java-io/src/test/resources/test_write_4.txt
Normal file
BIN
core-java-io/src/test/resources/test_write_4.txt
Normal file
Binary file not shown.
1
core-java-io/src/test/resources/test_write_5.txt
Normal file
1
core-java-io/src/test/resources/test_write_5.txt
Normal file
@ -0,0 +1 @@
|
||||
Hello
|
@ -129,3 +129,11 @@
|
||||
- [A Guide to the finalize Method in Java](http://www.baeldung.com/java-finalize)
|
||||
- [Compiling Java *.class Files with javac](http://www.baeldung.com/javac)
|
||||
- [Method Overloading and Overriding in Java](http://www.baeldung.com/java-method-overload-override)
|
||||
- [A Guide to TreeSet in Java](http://www.baeldung.com/java-tree-set)
|
||||
- [Guide to ThreadLocalRandom in Java](http://www.baeldung.com/java-thread-local-random)
|
||||
- [Java TreeMap vs HashMap](http://www.baeldung.com/java-treemap-vs-hashmap)
|
||||
- [A Guide to Iterator in Java](http://www.baeldung.com/java-iterator)
|
||||
- [The Trie Data Structure in Java](http://www.baeldung.com/trie-java)
|
||||
- [Introduction to Javadoc](http://www.baeldung.com/javadoc)
|
||||
- [How to TDD a List Implementation](http://jira.baeldung.com/browse/BAEL-1537)
|
||||
|
||||
|
@ -0,0 +1,20 @@
|
||||
package com.baeldung.array;
|
||||
|
||||
public class Find2ndLargestInArray {
|
||||
|
||||
public static int find2ndLargestElement(int[] array) {
|
||||
int maxElement = array[0];
|
||||
int secondLargestElement = -1;
|
||||
|
||||
for (int index = 0; index < array.length; index++) {
|
||||
if (maxElement <= array[index]) {
|
||||
secondLargestElement = maxElement;
|
||||
maxElement = array[index];
|
||||
} else if (secondLargestElement < array[index]) {
|
||||
secondLargestElement = array[index];
|
||||
}
|
||||
}
|
||||
return secondLargestElement;
|
||||
}
|
||||
|
||||
}
|
@ -0,0 +1,22 @@
|
||||
package com.baeldung.array;
|
||||
|
||||
import java.util.Arrays;
|
||||
|
||||
public class FindElementInArray {
|
||||
|
||||
public static boolean findGivenElementInArrayWithoutUsingStream(int[] array, int element) {
|
||||
boolean actualResult = false;
|
||||
|
||||
for (int index = 0; index < array.length; index++) {
|
||||
if (element == array[index]) {
|
||||
actualResult = true;
|
||||
break;
|
||||
}
|
||||
}
|
||||
return actualResult;
|
||||
}
|
||||
|
||||
public static boolean findGivenElementInArrayUsingStream(int[] array, int element) {
|
||||
return Arrays.stream(array).filter(x -> element == x).findFirst().isPresent();
|
||||
}
|
||||
}
|
@ -0,0 +1,27 @@
|
||||
package com.baeldung.array;
|
||||
|
||||
import java.util.Arrays;
|
||||
|
||||
public class SumAndAverageInArray {
|
||||
|
||||
public static int findSumWithoutUsingStream(int[] array) {
|
||||
int sum = 0;
|
||||
for (int index = 0; index < array.length; index++) {
|
||||
sum += array[index];
|
||||
}
|
||||
return sum;
|
||||
}
|
||||
|
||||
public static int findSumUsingStream(int[] array) {
|
||||
return Arrays.stream(array).sum();
|
||||
}
|
||||
|
||||
public static double findAverageWithoutUsingStream(int[] array) {
|
||||
int sum = findSumWithoutUsingStream(array);
|
||||
return (double) sum / array.length;
|
||||
}
|
||||
|
||||
public static double findAverageUsingStream(int[] array) {
|
||||
return Arrays.stream(array).average().getAsDouble();
|
||||
}
|
||||
}
|
62
core-java/src/main/java/com/baeldung/asciiart/AsciiArt.java
Normal file
62
core-java/src/main/java/com/baeldung/asciiart/AsciiArt.java
Normal file
@ -0,0 +1,62 @@
|
||||
package com.baeldung.asciiart;
|
||||
|
||||
import java.awt.Font;
|
||||
import java.awt.Graphics;
|
||||
import java.awt.Graphics2D;
|
||||
import java.awt.RenderingHints;
|
||||
import java.awt.image.BufferedImage;
|
||||
|
||||
public class AsciiArt {
|
||||
|
||||
public AsciiArt() {
|
||||
}
|
||||
|
||||
public void drawString(String text, String artChar, Settings settings) {
|
||||
BufferedImage image = getImageIntegerMode(settings.width, settings.height);
|
||||
|
||||
Graphics2D graphics2D = getGraphics2D(image.getGraphics(), settings);
|
||||
graphics2D.drawString(text, 6, ((int) (settings.height * 0.67)));
|
||||
|
||||
for (int y = 0; y < settings.height; y++) {
|
||||
StringBuilder stringBuilder = new StringBuilder();
|
||||
|
||||
for (int x = 0; x < settings.width; x++) {
|
||||
stringBuilder.append(image.getRGB(x, y) == -16777216 ? " " : artChar);
|
||||
}
|
||||
|
||||
if (stringBuilder.toString()
|
||||
.trim()
|
||||
.isEmpty()) {
|
||||
continue;
|
||||
}
|
||||
|
||||
System.out.println(stringBuilder);
|
||||
}
|
||||
|
||||
}
|
||||
|
||||
private BufferedImage getImageIntegerMode(int width, int height) {
|
||||
return new BufferedImage(width, height, BufferedImage.TYPE_INT_RGB);
|
||||
}
|
||||
|
||||
private Graphics2D getGraphics2D(Graphics graphics, Settings settings) {
|
||||
graphics.setFont(settings.font);
|
||||
|
||||
Graphics2D graphics2D = (Graphics2D) graphics;
|
||||
graphics2D.setRenderingHint(RenderingHints.KEY_TEXT_ANTIALIASING, RenderingHints.VALUE_TEXT_ANTIALIAS_ON);
|
||||
|
||||
return graphics2D;
|
||||
}
|
||||
|
||||
public class Settings {
|
||||
public Font font;
|
||||
public int width;
|
||||
public int height;
|
||||
|
||||
public Settings(Font font, int width, int height) {
|
||||
this.font = font;
|
||||
this.width = width;
|
||||
this.height = height;
|
||||
}
|
||||
}
|
||||
}
|
@ -0,0 +1,24 @@
|
||||
package com.baeldung.casting;
|
||||
|
||||
import java.util.ArrayList;
|
||||
import java.util.List;
|
||||
|
||||
public class AnimalFeederGeneric<T> {
|
||||
private Class<T> type;
|
||||
|
||||
public AnimalFeederGeneric(Class<T> type) {
|
||||
this.type = type;
|
||||
}
|
||||
|
||||
public List<T> feed(List<Animal> animals) {
|
||||
List<T> list = new ArrayList<T>();
|
||||
animals.forEach(animal -> {
|
||||
if (type.isInstance(animal)) {
|
||||
T objAsType = type.cast(animal);
|
||||
list.add(objAsType);
|
||||
}
|
||||
});
|
||||
return list;
|
||||
}
|
||||
|
||||
}
|
@ -1,5 +0,0 @@
|
||||
package com.baeldung.designpatterns.chainofresponsibility;
|
||||
|
||||
public interface AuthenticationProvider {
|
||||
|
||||
}
|
@ -9,6 +9,58 @@ import java.util.ListIterator;
|
||||
public class CustomList<E> implements List<E> {
|
||||
private Object[] internal = {};
|
||||
|
||||
@Override
|
||||
public boolean isEmpty() {
|
||||
// the first cycle
|
||||
// return true;
|
||||
|
||||
// the second cycle
|
||||
// if (internal.length != 0) {
|
||||
// return false;
|
||||
// } else {
|
||||
// return true;
|
||||
// }
|
||||
|
||||
// refactoring
|
||||
return internal.length == 0;
|
||||
}
|
||||
|
||||
@Override
|
||||
public int size() {
|
||||
// the first cycle
|
||||
// if (isEmpty()) {
|
||||
// return 0;
|
||||
// } else {
|
||||
// return internal.length;
|
||||
// }
|
||||
|
||||
// refactoring
|
||||
return internal.length;
|
||||
}
|
||||
|
||||
@SuppressWarnings("unchecked")
|
||||
@Override
|
||||
public E get(int index) {
|
||||
// the first cycle
|
||||
// return (E) internal[0];
|
||||
|
||||
// improvement
|
||||
return (E) internal[index];
|
||||
}
|
||||
|
||||
@Override
|
||||
public boolean add(E element) {
|
||||
// the first cycle
|
||||
// internal = new Object[] { element };
|
||||
// return true;
|
||||
|
||||
// the second cycle
|
||||
Object[] temp = Arrays.copyOf(internal, internal.length + 1);
|
||||
temp[internal.length] = element;
|
||||
internal = temp;
|
||||
return true;
|
||||
}
|
||||
|
||||
@Override
|
||||
public void add(int index, E element) {
|
||||
throw new UnsupportedOperationException();
|
||||
@ -44,40 +96,8 @@ public class CustomList<E> implements List<E> {
|
||||
throw new UnsupportedOperationException();
|
||||
}
|
||||
|
||||
@Override
|
||||
public int size() {
|
||||
return internal.length;
|
||||
}
|
||||
|
||||
@Override
|
||||
public boolean isEmpty() {
|
||||
return internal.length == 0;
|
||||
}
|
||||
|
||||
@Override
|
||||
public boolean add(E element) {
|
||||
// the first cycle
|
||||
// internal = new Object[1];
|
||||
// internal[0] = element;
|
||||
// return true;
|
||||
|
||||
Object[] temp = new Object[internal.length + 1];
|
||||
System.arraycopy(internal, 0, temp, 0, internal.length);
|
||||
temp[internal.length] = element;
|
||||
internal = temp;
|
||||
return true;
|
||||
}
|
||||
|
||||
@SuppressWarnings("unchecked")
|
||||
@Override
|
||||
public E get(int index) {
|
||||
return (E) internal[index];
|
||||
}
|
||||
|
||||
@Override
|
||||
public boolean contains(Object object) {
|
||||
// return false
|
||||
|
||||
for (Object element : internal) {
|
||||
if (object.equals(element)) {
|
||||
return true;
|
||||
@ -88,14 +108,6 @@ public class CustomList<E> implements List<E> {
|
||||
|
||||
@Override
|
||||
public boolean containsAll(Collection<?> collection) {
|
||||
// the first cycle
|
||||
// for (Object element : collection) {
|
||||
// if (element.equals(internal[0])) {
|
||||
// return true;
|
||||
// }
|
||||
// }
|
||||
// return false;
|
||||
|
||||
for (Object element : collection)
|
||||
if (!contains(element)) {
|
||||
return false;
|
||||
@ -118,12 +130,6 @@ public class CustomList<E> implements List<E> {
|
||||
|
||||
@Override
|
||||
public int indexOf(Object object) {
|
||||
// the first cycle
|
||||
// if (object.equals(internal[0])) {
|
||||
// return 0;
|
||||
// }
|
||||
// return -1;
|
||||
|
||||
for (int i = 0; i < internal.length; i++) {
|
||||
if (object.equals(internal[i])) {
|
||||
return i;
|
||||
@ -134,12 +140,6 @@ public class CustomList<E> implements List<E> {
|
||||
|
||||
@Override
|
||||
public int lastIndexOf(Object object) {
|
||||
// the first cycle
|
||||
// if (object.equals(internal[0])) {
|
||||
// return 0;
|
||||
// }
|
||||
// return -1;
|
||||
|
||||
for (int i = internal.length - 1; i >= 0; i--) {
|
||||
if (object.equals(internal[i])) {
|
||||
return i;
|
||||
@ -151,9 +151,6 @@ public class CustomList<E> implements List<E> {
|
||||
@SuppressWarnings("unchecked")
|
||||
@Override
|
||||
public List<E> subList(int fromIndex, int toIndex) {
|
||||
// the first cycle
|
||||
// return (List<E>) Arrays.asList(internal);
|
||||
|
||||
Object[] temp = new Object[toIndex - fromIndex];
|
||||
System.arraycopy(internal, fromIndex, temp, 0, temp.length);
|
||||
return (List<E>) Arrays.asList(temp);
|
||||
@ -167,16 +164,6 @@ public class CustomList<E> implements List<E> {
|
||||
@SuppressWarnings("unchecked")
|
||||
@Override
|
||||
public <T> T[] toArray(T[] array) {
|
||||
// the first cycle
|
||||
// array[0] = (T) internal[0];
|
||||
// return array;
|
||||
|
||||
// the second cycle
|
||||
// if (array.length < internal.length) {
|
||||
// return (T[]) Arrays.copyOf(internal, internal.length, array.getClass());
|
||||
// }
|
||||
// return (T[]) Arrays.copyOf(internal, internal.length, array.getClass());
|
||||
|
||||
if (array.length < internal.length) {
|
||||
return (T[]) Arrays.copyOf(internal, internal.length, array.getClass());
|
||||
}
|
||||
@ -209,18 +196,12 @@ public class CustomList<E> implements List<E> {
|
||||
|
||||
@Override
|
||||
public boolean hasNext() {
|
||||
// the first cycle
|
||||
// return true;
|
||||
|
||||
return index != internal.length;
|
||||
}
|
||||
|
||||
@SuppressWarnings("unchecked")
|
||||
@Override
|
||||
public E next() {
|
||||
// the first cycle
|
||||
// return (E) CustomList.this.internal[0];
|
||||
|
||||
E element = (E) CustomList.this.internal[index];
|
||||
index++;
|
||||
return element;
|
||||
|
@ -23,9 +23,15 @@ public class SuperHero extends Person {
|
||||
* @return the amount of health hero has after attack
|
||||
* @see <a href="http://www.link_to_jira/HERO-402">HERO-402</a>
|
||||
* @since 1.0
|
||||
* @deprecated As of version 1.1, use . . . instead
|
||||
* @version 1.2
|
||||
* @throws IllegalArgumentException if incomingDamage is negative
|
||||
*/
|
||||
public int successfullyAttacked(int incomingDamage, String damageType) {
|
||||
public int successfullyAttacked(int incomingDamage, String damageType) throws Exception {
|
||||
// do things
|
||||
if (incomingDamage < 0) {
|
||||
throw new IllegalArgumentException ("Cannot cause negative damage");
|
||||
}
|
||||
return 0;
|
||||
}
|
||||
|
||||
|
@ -1,2 +0,0 @@
|
||||
line 1
|
||||
a second line
|
@ -0,0 +1,16 @@
|
||||
package com.baeldung.array;
|
||||
|
||||
import org.junit.Assert;
|
||||
import org.junit.Test;
|
||||
|
||||
public class Find2ndLargestInArrayTest {
|
||||
@Test
|
||||
public void givenAnIntArray_thenFind2ndLargestElement() {
|
||||
int[] array = { 1, 3, 24, 16, 87, 20 };
|
||||
int expected2ndLargest = 24;
|
||||
|
||||
int actualSecondLargestElement = Find2ndLargestInArray.find2ndLargestElement(array);
|
||||
|
||||
Assert.assertEquals(expected2ndLargest, actualSecondLargestElement);
|
||||
}
|
||||
}
|
@ -0,0 +1,35 @@
|
||||
package com.baeldung.array;
|
||||
|
||||
import org.junit.Assert;
|
||||
import org.junit.Test;
|
||||
|
||||
public class FindElementInArrayTest {
|
||||
@Test
|
||||
public void givenAnIntArray_whenNotUsingStream_thenFindAnElement() {
|
||||
int[] array = { 1, 3, 4, 8, 19, 20 };
|
||||
int element = 19;
|
||||
boolean expectedResult = true;
|
||||
boolean actualResult = FindElementInArray.findGivenElementInArrayWithoutUsingStream(array, element);
|
||||
Assert.assertEquals(expectedResult, actualResult);
|
||||
|
||||
element = 78;
|
||||
expectedResult = false;
|
||||
actualResult = FindElementInArray.findGivenElementInArrayWithoutUsingStream(array, element);
|
||||
Assert.assertEquals(expectedResult, actualResult);
|
||||
}
|
||||
|
||||
@Test
|
||||
public void givenAnIntArray_whenUsingStream_thenFindAnElement() {
|
||||
int[] array = { 15, 16, 12, 18 };
|
||||
int element = 16;
|
||||
boolean expectedResult = true;
|
||||
boolean actualResult = FindElementInArray.findGivenElementInArrayUsingStream(array, element);
|
||||
Assert.assertEquals(expectedResult, actualResult);
|
||||
|
||||
element = 20;
|
||||
expectedResult = false;
|
||||
actualResult = FindElementInArray.findGivenElementInArrayUsingStream(array, element);
|
||||
Assert.assertEquals(expectedResult, actualResult);
|
||||
}
|
||||
|
||||
}
|
@ -0,0 +1,41 @@
|
||||
package com.baeldung.array;
|
||||
|
||||
import org.junit.Assert;
|
||||
import org.junit.Test;
|
||||
|
||||
public class SumAndAverageInArrayTest {
|
||||
@Test
|
||||
public void givenAnIntArray_whenNotUsingStream_thenFindSum() {
|
||||
int[] array = { 1, 3, 4, 8, 19, 20 };
|
||||
int expectedSumOfArray = 55;
|
||||
int actualSumOfArray = SumAndAverageInArray.findSumWithoutUsingStream(array);
|
||||
Assert.assertEquals(expectedSumOfArray, actualSumOfArray);
|
||||
}
|
||||
|
||||
@Test
|
||||
public void givenAnIntArray_whenUsingStream_thenFindSum() {
|
||||
int[] array = { 1, 3, 4, 8, 19, 20 };
|
||||
int expectedSumOfArray = 55;
|
||||
int actualSumOfArray = SumAndAverageInArray.findSumUsingStream(array);
|
||||
|
||||
Assert.assertEquals(expectedSumOfArray, actualSumOfArray);
|
||||
}
|
||||
|
||||
@Test
|
||||
public void givenAnIntArray_whenNotUsingStream_thenFindAverage() {
|
||||
int[] array = { 1, 3, 4, 8, 19, 20 };
|
||||
double expectedAvgOfArray = 9.17;
|
||||
double actualAvgOfArray = SumAndAverageInArray.findAverageWithoutUsingStream(array);
|
||||
|
||||
Assert.assertEquals(expectedAvgOfArray, actualAvgOfArray, 0.0034);
|
||||
}
|
||||
|
||||
@Test
|
||||
public void givenAnIntArray_whenUsingStream_thenFindAverage() {
|
||||
int[] array = { 1, 3, 4, 8, 19, 20 };
|
||||
double expectedAvgOfArray = 9.17;
|
||||
double actualAvgOfArray = SumAndAverageInArray.findAverageUsingStream(array);
|
||||
|
||||
Assert.assertEquals(expectedAvgOfArray, actualAvgOfArray, 0.0034);
|
||||
}
|
||||
}
|
@ -0,0 +1,20 @@
|
||||
package com.baeldung.asciiart;
|
||||
|
||||
import java.awt.Font;
|
||||
|
||||
import org.junit.Test;
|
||||
|
||||
import com.baeldung.asciiart.AsciiArt.Settings;
|
||||
|
||||
public class AsciiArtTest {
|
||||
|
||||
@Test
|
||||
public void givenTextWithAsciiCharacterAndSettings_shouldPrintAsciiArt() {
|
||||
AsciiArt asciiArt = new AsciiArt();
|
||||
String text = "BAELDUNG";
|
||||
Settings settings = asciiArt.new Settings(new Font("SansSerif", Font.BOLD, 24), text.length() * 30, 30); // 30 pixel width per character
|
||||
|
||||
asciiArt.drawString(text, "*", settings);
|
||||
}
|
||||
|
||||
}
|
@ -11,6 +11,7 @@ public class CastingTest {
|
||||
public void whenPrimitiveConverted_thenValueChanged() {
|
||||
double myDouble = 1.1;
|
||||
int myInt = (int) myDouble;
|
||||
|
||||
assertNotEquals(myDouble, myInt);
|
||||
}
|
||||
|
||||
@ -55,4 +56,25 @@ public class CastingTest {
|
||||
animals.add(new Dog());
|
||||
new AnimalFeeder().uncheckedFeed(animals);
|
||||
}
|
||||
|
||||
@Test
|
||||
public void whenDowncastToCatWithCastMethod_thenMeowIsCalled() {
|
||||
Animal animal = new Cat();
|
||||
if (Cat.class.isInstance(animal)) {
|
||||
Cat cat = Cat.class.cast(animal);
|
||||
cat.meow();
|
||||
}
|
||||
}
|
||||
|
||||
@Test
|
||||
public void whenParameterCat_thenOnlyCatsFed() {
|
||||
List<Animal> animals = new ArrayList<>();
|
||||
animals.add(new Cat());
|
||||
animals.add(new Dog());
|
||||
AnimalFeederGeneric<Cat> catFeeder = new AnimalFeederGeneric<Cat>(Cat.class);
|
||||
List<Cat> fedAnimals = catFeeder.feed(animals);
|
||||
|
||||
assertTrue(fedAnimals.size() == 1);
|
||||
assertTrue(fedAnimals.get(0) instanceof Cat);
|
||||
}
|
||||
}
|
||||
|
@ -14,6 +14,58 @@ import java.util.List;
|
||||
import org.junit.Test;
|
||||
|
||||
public class CustomListUnitTest {
|
||||
@Test
|
||||
public void givenEmptyList_whenIsEmpty_thenTrueIsReturned() {
|
||||
List<Object> list = new CustomList<>();
|
||||
|
||||
assertTrue(list.isEmpty());
|
||||
}
|
||||
|
||||
@Test
|
||||
public void givenNonEmptyList_whenIsEmpty_thenFalseIsReturned() {
|
||||
List<Object> list = new CustomList<>();
|
||||
list.add(null);
|
||||
|
||||
assertFalse(list.isEmpty());
|
||||
}
|
||||
|
||||
@Test
|
||||
public void givenListWithAnElement_whenSize_thenOneIsReturned() {
|
||||
List<Object> list = new CustomList<>();
|
||||
list.add(null);
|
||||
|
||||
assertEquals(1, list.size());
|
||||
}
|
||||
|
||||
@Test
|
||||
public void givenListWithAnElement_whenGet_thenThatElementIsReturned() {
|
||||
List<Object> list = new CustomList<>();
|
||||
list.add("baeldung");
|
||||
Object element = list.get(0);
|
||||
|
||||
assertEquals("baeldung", element);
|
||||
}
|
||||
|
||||
@Test
|
||||
public void givenEmptyList_whenElementIsAdded_thenGetReturnsThatElement() {
|
||||
List<Object> list = new CustomList<>();
|
||||
boolean succeeded = list.add(null);
|
||||
|
||||
assertTrue(succeeded);
|
||||
}
|
||||
|
||||
@Test
|
||||
public void givenListWithAnElement_whenAnotherIsAdded_thenGetReturnsBoth() {
|
||||
List<Object> list = new CustomList<>();
|
||||
list.add("baeldung");
|
||||
list.add(".com");
|
||||
Object element1 = list.get(0);
|
||||
Object element2 = list.get(1);
|
||||
|
||||
assertEquals("baeldung", element1);
|
||||
assertEquals(".com", element2);
|
||||
}
|
||||
|
||||
@Test(expected = UnsupportedOperationException.class)
|
||||
public void whenAddToSpecifiedIndex_thenExceptionIsThrown() {
|
||||
new CustomList<>().add(0, null);
|
||||
@ -64,44 +116,6 @@ public class CustomListUnitTest {
|
||||
list.retainAll(collection);
|
||||
}
|
||||
|
||||
@Test
|
||||
public void givenEmptyList_whenSize_thenZeroIsReturned() {
|
||||
List<Object> list = new CustomList<>();
|
||||
|
||||
assertEquals(0, list.size());
|
||||
}
|
||||
|
||||
@Test
|
||||
public void givenEmptyList_whenIsEmpty_thenTrueIsReturned() {
|
||||
List<Object> list = new CustomList<>();
|
||||
|
||||
assertTrue(list.isEmpty());
|
||||
}
|
||||
|
||||
@Test
|
||||
public void givenEmptyList_whenElementIsAdded_thenGetReturnsThatElement() {
|
||||
List<Object> list = new CustomList<>();
|
||||
boolean succeeded = list.add("baeldung");
|
||||
Object element = list.get(0);
|
||||
|
||||
assertTrue(succeeded);
|
||||
assertEquals("baeldung", element);
|
||||
}
|
||||
|
||||
@Test
|
||||
public void givenListWithAnElement_whenAnotherIsAdded_thenGetReturnsBoth() {
|
||||
List<Object> list = new CustomList<>();
|
||||
boolean succeeded1 = list.add("baeldung");
|
||||
boolean succeeded2 = list.add(".com");
|
||||
Object element1 = list.get(0);
|
||||
Object element2 = list.get(1);
|
||||
|
||||
assertTrue(succeeded1);
|
||||
assertTrue(succeeded2);
|
||||
assertEquals("baeldung", element1);
|
||||
assertEquals(".com", element2);
|
||||
}
|
||||
|
||||
@Test
|
||||
public void givenEmptyList_whenContains_thenFalseIsReturned() {
|
||||
List<Object> list = new CustomList<>();
|
||||
@ -271,7 +285,7 @@ public class CustomListUnitTest {
|
||||
}
|
||||
|
||||
@Test
|
||||
public void whenIteratorNextIsCalledTwice_thenTheSecondReturnsFalse() {
|
||||
public void whenIteratorHasNextIsCalledTwice_thenTheSecondReturnsFalse() {
|
||||
List<Object> list = new CustomList<>();
|
||||
list.add("baeldung");
|
||||
Iterator<Object> iterator = list.iterator();
|
||||
|
@ -1 +0,0 @@
|
||||
Hello world !
|
@ -18,3 +18,6 @@
|
||||
- [JUnit 5 for Kotlin Developers](http://www.baeldung.com/junit-5-kotlin)
|
||||
- [Extension Methods in Kotlin](http://www.baeldung.com/kotlin-extension-methods)
|
||||
- [Infix Functions in Kotlin](http://www.baeldung.com/kotlin-infix-functions)
|
||||
- [Try-with-resources in Kotlin](http://www.baeldung.com/kotlin-try-with-resources)
|
||||
- [HTTP Requests with Kotlin and khttp](http://www.baeldung.com/kotlin-khttp)
|
||||
- [Kotlin Dependency Injection with Kodein](http://www.baeldung.com/kotlin-kodein-dependency-injection)
|
||||
|
@ -1,6 +1,5 @@
|
||||
<?xml version="1.0"?>
|
||||
<project xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd"
|
||||
xmlns="http://maven.apache.org/POM/4.0.0" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance">
|
||||
<project xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd" xmlns="http://maven.apache.org/POM/4.0.0" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance">
|
||||
<modelVersion>4.0.0</modelVersion>
|
||||
<groupId>com.baeldung.ethereumj</groupId>
|
||||
<artifactId>ethereumj</artifactId>
|
||||
@ -8,16 +7,11 @@
|
||||
<version>1.0.0</version>
|
||||
<name>ethereumj</name>
|
||||
|
||||
<properties>
|
||||
<project.build.sourceEncoding>UTF-8</project.build.sourceEncoding>
|
||||
<java.version>1.8</java.version>
|
||||
<tomcat.version>8.5.4</tomcat.version>
|
||||
</properties>
|
||||
|
||||
<parent>
|
||||
<groupId>org.springframework.boot</groupId>
|
||||
<artifactId>spring-boot-starter-parent</artifactId>
|
||||
<version>1.5.6.RELEASE</version>
|
||||
<artifactId>parent-boot-5</artifactId>
|
||||
<groupId>com.baeldung</groupId>
|
||||
<version>0.0.1-SNAPSHOT</version>
|
||||
<relativePath>../parent-boot-5</relativePath>
|
||||
</parent>
|
||||
|
||||
<repositories>
|
||||
@ -38,14 +32,12 @@
|
||||
<dependency>
|
||||
<groupId>org.springframework.boot</groupId>
|
||||
<artifactId>spring-boot-starter-tomcat</artifactId>
|
||||
<!--<scope>provided</scope>-->
|
||||
</dependency>
|
||||
|
||||
<!-- Unit Testing -->
|
||||
<dependency>
|
||||
<groupId>org.springframework.boot</groupId>
|
||||
<artifactId>spring-boot-starter-test</artifactId>
|
||||
<version>1.5.6.RELEASE</version>
|
||||
<scope>test</scope>
|
||||
</dependency>
|
||||
|
||||
@ -107,4 +99,11 @@
|
||||
</build>
|
||||
</profile>
|
||||
</profiles>
|
||||
|
||||
<properties>
|
||||
<project.build.sourceEncoding>UTF-8</project.build.sourceEncoding>
|
||||
<java.version>1.8</java.version>
|
||||
<tomcat.version>8.5.4</tomcat.version>
|
||||
</properties>
|
||||
|
||||
</project>
|
@ -3,7 +3,6 @@ package com.baeldung.geotools;
|
||||
import static org.junit.Assert.assertNotNull;
|
||||
|
||||
import org.geotools.feature.DefaultFeatureCollection;
|
||||
import org.geotools.feature.simple.SimpleFeatureBuilder;
|
||||
import org.junit.Test;
|
||||
import org.opengis.feature.simple.SimpleFeatureType;
|
||||
|
||||
@ -19,4 +18,5 @@ public class GeoToolsUnitTest {
|
||||
|
||||
assertNotNull(collection);
|
||||
}
|
||||
|
||||
}
|
||||
|
@ -33,3 +33,60 @@ task execSecondTest {
|
||||
}
|
||||
println 'This will be executed during the configuration phase as well.'
|
||||
}
|
||||
|
||||
task welcome {
|
||||
doLast {
|
||||
println 'Welcome on the Baeldung!'
|
||||
}
|
||||
}
|
||||
|
||||
task welcomeWithGroup {
|
||||
group 'Sample category'
|
||||
doLast {
|
||||
println 'Welcome on the Baeldung!'
|
||||
}
|
||||
}
|
||||
|
||||
task welcomeWithGroupAndDescription {
|
||||
group 'Sample category'
|
||||
description 'Tasks which shows welcome message'
|
||||
doLast {
|
||||
println 'Welcome on the Baeldung!'
|
||||
}
|
||||
}
|
||||
|
||||
class PrintToolVersionTask extends DefaultTask {
|
||||
String tool
|
||||
|
||||
@TaskAction
|
||||
void printToolVersion() {
|
||||
switch (tool) {
|
||||
case 'java':
|
||||
println System.getProperty("java.version")
|
||||
break
|
||||
case 'groovy':
|
||||
println GroovySystem.version
|
||||
break
|
||||
default:
|
||||
throw new IllegalArgumentException("Unknown tool")
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
task printJavaVersion(type : PrintToolVersionTask) {
|
||||
tool 'java'
|
||||
}
|
||||
|
||||
task printGroovyVersion(type : PrintToolVersionTask) {
|
||||
tool 'groovy'
|
||||
}
|
||||
|
||||
import com.baeldung.PrintToolVersionBuildSrcTask
|
||||
|
||||
task printJavaVersionBuildSrc(type : PrintToolVersionBuildSrcTask) {
|
||||
tool 'java'
|
||||
}
|
||||
|
||||
task printGroovyVersionBuildSrc(type : PrintToolVersionBuildSrcTask) {
|
||||
tool 'groovy'
|
||||
}
|
@ -0,0 +1,22 @@
|
||||
package com.baeldung
|
||||
|
||||
import org.gradle.api.DefaultTask
|
||||
import org.gradle.api.tasks.TaskAction
|
||||
|
||||
class PrintToolVersionBuildSrcTask extends DefaultTask {
|
||||
String tool
|
||||
|
||||
@TaskAction
|
||||
void printToolVersion() {
|
||||
switch (tool) {
|
||||
case 'java':
|
||||
println System.getProperty("java.version")
|
||||
break
|
||||
case 'groovy':
|
||||
println GroovySystem.version
|
||||
break
|
||||
default:
|
||||
throw new IllegalArgumentException("Unknown tool")
|
||||
}
|
||||
}
|
||||
}
|
@ -44,12 +44,6 @@
|
||||
<scope>test</scope>
|
||||
</dependency>
|
||||
|
||||
<dependency>
|
||||
<groupId>org.hamcrest</groupId>
|
||||
<artifactId>java-hamcrest</artifactId>
|
||||
<version>2.0.0.0</version>
|
||||
<scope>test</scope>
|
||||
</dependency>
|
||||
|
||||
</dependencies>
|
||||
|
||||
|
@ -31,7 +31,6 @@
|
||||
<dependency>
|
||||
<groupId>org.springframework.boot</groupId>
|
||||
<artifactId>spring-boot-starter-tomcat</artifactId>
|
||||
<scope>provided</scope>
|
||||
</dependency>
|
||||
|
||||
</dependencies>
|
||||
|
@ -0,0 +1,61 @@
|
||||
package com.baeldung.hibernate.lob;
|
||||
|
||||
import java.io.FileInputStream;
|
||||
import java.io.IOException;
|
||||
import java.net.URL;
|
||||
import java.util.Properties;
|
||||
|
||||
import org.apache.commons.lang3.StringUtils;
|
||||
import org.hibernate.SessionFactory;
|
||||
import org.hibernate.boot.Metadata;
|
||||
import org.hibernate.boot.MetadataSources;
|
||||
import org.hibernate.boot.registry.StandardServiceRegistryBuilder;
|
||||
import org.hibernate.service.ServiceRegistry;
|
||||
|
||||
import com.baeldung.hibernate.lob.model.User;
|
||||
|
||||
public class HibernateSessionUtil {
|
||||
|
||||
private static SessionFactory sessionFactory;
|
||||
private static String PROPERTY_FILE_NAME;
|
||||
|
||||
public static SessionFactory getSessionFactory() throws IOException {
|
||||
return getSessionFactory(null);
|
||||
}
|
||||
|
||||
public static SessionFactory getSessionFactory(String propertyFileName) throws IOException {
|
||||
PROPERTY_FILE_NAME = propertyFileName;
|
||||
if (sessionFactory == null) {
|
||||
ServiceRegistry serviceRegistry = configureServiceRegistry();
|
||||
sessionFactory = makeSessionFactory(serviceRegistry);
|
||||
}
|
||||
return sessionFactory;
|
||||
}
|
||||
|
||||
private static SessionFactory makeSessionFactory(ServiceRegistry serviceRegistry) {
|
||||
MetadataSources metadataSources = new MetadataSources(serviceRegistry);
|
||||
metadataSources.addAnnotatedClass(User.class);
|
||||
|
||||
Metadata metadata = metadataSources.buildMetadata();
|
||||
return metadata.getSessionFactoryBuilder()
|
||||
.build();
|
||||
|
||||
}
|
||||
|
||||
private static ServiceRegistry configureServiceRegistry() throws IOException {
|
||||
Properties properties = getProperties();
|
||||
return new StandardServiceRegistryBuilder().applySettings(properties)
|
||||
.build();
|
||||
}
|
||||
|
||||
private static Properties getProperties() throws IOException {
|
||||
Properties properties = new Properties();
|
||||
URL propertiesURL = Thread.currentThread()
|
||||
.getContextClassLoader()
|
||||
.getResource(StringUtils.defaultString(PROPERTY_FILE_NAME, "hibernate.properties"));
|
||||
try (FileInputStream inputStream = new FileInputStream(propertiesURL.getFile())) {
|
||||
properties.load(inputStream);
|
||||
}
|
||||
return properties;
|
||||
}
|
||||
}
|
@ -0,0 +1,46 @@
|
||||
package com.baeldung.hibernate.lob.model;
|
||||
|
||||
import javax.persistence.Column;
|
||||
import javax.persistence.Entity;
|
||||
import javax.persistence.Id;
|
||||
import javax.persistence.Lob;
|
||||
import javax.persistence.Table;
|
||||
|
||||
@Entity
|
||||
@Table(name="user")
|
||||
public class User {
|
||||
|
||||
@Id
|
||||
private String id;
|
||||
|
||||
@Column(name = "name", columnDefinition="VARCHAR(128)")
|
||||
private String name;
|
||||
|
||||
@Lob
|
||||
@Column(name = "photo", columnDefinition="BLOB")
|
||||
private byte[] photo;
|
||||
|
||||
public String getId() {
|
||||
return id;
|
||||
}
|
||||
|
||||
public void setId(String id) {
|
||||
this.id = id;
|
||||
}
|
||||
|
||||
public String getName() {
|
||||
return name;
|
||||
}
|
||||
|
||||
public void setName(String name) {
|
||||
this.name = name;
|
||||
}
|
||||
|
||||
public byte[] getPhoto() {
|
||||
return photo;
|
||||
}
|
||||
|
||||
public void setPhoto(byte[] photo) {
|
||||
this.photo = photo;
|
||||
}
|
||||
}
|
@ -0,0 +1,61 @@
|
||||
package com.baeldung.hibernate.lob;
|
||||
|
||||
import static org.junit.Assert.assertEquals;
|
||||
import static org.junit.Assert.assertNotNull;
|
||||
import static org.junit.Assert.assertTrue;
|
||||
import static org.junit.Assert.fail;
|
||||
|
||||
import java.io.IOException;
|
||||
import java.io.InputStream;
|
||||
import java.util.Arrays;
|
||||
|
||||
import org.apache.commons.io.IOUtils;
|
||||
import org.hibernate.HibernateException;
|
||||
import org.hibernate.Session;
|
||||
import org.junit.After;
|
||||
import org.junit.Before;
|
||||
import org.junit.Test;
|
||||
|
||||
import com.baeldung.hibernate.lob.model.User;
|
||||
|
||||
public class LobTest {
|
||||
|
||||
private Session session;
|
||||
|
||||
@Before
|
||||
public void init(){
|
||||
try {
|
||||
session = HibernateSessionUtil.getSessionFactory("hibernate.properties")
|
||||
.openSession();
|
||||
} catch (HibernateException | IOException e) {
|
||||
fail("Failed to initiate Hibernate Session [Exception:" + e.toString() + "]");
|
||||
}
|
||||
}
|
||||
|
||||
@After
|
||||
public void close(){
|
||||
if(session != null) session.close();
|
||||
}
|
||||
|
||||
@Test
|
||||
public void givenValidInsertLobObject_whenQueried_returnSameDataAsInserted(){
|
||||
User user = new User();
|
||||
try(InputStream inputStream = this.getClass().getClassLoader().getResourceAsStream("profile.png");) {
|
||||
// Get Image file from the resource
|
||||
if(inputStream == null) fail("Unable to get resources");
|
||||
user.setId("1");
|
||||
user.setName("User");
|
||||
user.setPhoto(IOUtils.toByteArray(inputStream));
|
||||
|
||||
session.persist(user);
|
||||
} catch (IOException e) {
|
||||
fail("Unable to read input stream");
|
||||
}
|
||||
|
||||
User result = session.find(User.class, "1");
|
||||
|
||||
assertNotNull("Query result is null", result);
|
||||
assertEquals("User's name is invalid", user.getName(), result.getName() );
|
||||
assertTrue("User's photo is corrupted", Arrays.equals(user.getPhoto(), result.getPhoto()) );
|
||||
}
|
||||
}
|
BIN
hibernate5/src/test/resources/profile.png
Normal file
BIN
hibernate5/src/test/resources/profile.png
Normal file
Binary file not shown.
After Width: | Height: | Size: 1.1 KiB |
@ -34,7 +34,6 @@
|
||||
<dependency>
|
||||
<groupId>org.springframework.boot</groupId>
|
||||
<artifactId>spring-boot-starter-tomcat</artifactId>
|
||||
<scope>provided</scope>
|
||||
</dependency>
|
||||
<dependency>
|
||||
<groupId>org.springframework.boot</groupId>
|
||||
|
@ -1 +0,0 @@
|
||||
## Relevant articles:
|
@ -1,2 +1,3 @@
|
||||
### Relevant Articles:
|
||||
- [RESTFul CRUD application with JavaLite] ()
|
||||
|
||||
- [A Guide to JavaLite – Building a RESTful CRUD application](http://www.baeldung.com/javalite-rest)
|
||||
|
3
java-rmi/README.md
Normal file
3
java-rmi/README.md
Normal file
@ -0,0 +1,3 @@
|
||||
### Relevant articles
|
||||
|
||||
- [Getting Started with Java RMI](http://www.baeldung.com/java-rmi)
|
14
java-spi/exchange-rate-api/pom.xml
Normal file
14
java-spi/exchange-rate-api/pom.xml
Normal file
@ -0,0 +1,14 @@
|
||||
<project xmlns="http://maven.apache.org/POM/4.0.0" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
|
||||
xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd">
|
||||
<modelVersion>4.0.0</modelVersion>
|
||||
|
||||
<artifactId>exchange-rate-api</artifactId>
|
||||
<packaging>jar</packaging>
|
||||
|
||||
<parent>
|
||||
<groupId>com.baeldung</groupId>
|
||||
<artifactId>java-spi</artifactId>
|
||||
<version>1.0.0-SNAPSHOT</version>
|
||||
</parent>
|
||||
|
||||
</project>
|
@ -0,0 +1,42 @@
|
||||
package com.baeldung.rate;
|
||||
|
||||
import com.baeldung.rate.exception.ProviderNotFoundException;
|
||||
import com.baeldung.rate.spi.ExchangeRateProvider;
|
||||
|
||||
import java.util.ArrayList;
|
||||
import java.util.Iterator;
|
||||
import java.util.List;
|
||||
import java.util.ServiceLoader;
|
||||
|
||||
public final class ExchangeRate {
|
||||
|
||||
private static final String DEFAULT_PROVIDER = "com.baeldung.rate.spi.YahooFinanceExchangeRateProvider";
|
||||
|
||||
//All providers
|
||||
public static List<ExchangeRateProvider> providers() {
|
||||
List<ExchangeRateProvider> services = new ArrayList<>();
|
||||
ServiceLoader<ExchangeRateProvider> loader = ServiceLoader.load(ExchangeRateProvider.class);
|
||||
loader.forEach(exchangeRateProvider -> {
|
||||
services.add(exchangeRateProvider);
|
||||
});
|
||||
return services;
|
||||
}
|
||||
|
||||
//Default provider
|
||||
public static ExchangeRateProvider provider() {
|
||||
return provider(DEFAULT_PROVIDER);
|
||||
}
|
||||
|
||||
//provider by name
|
||||
public static ExchangeRateProvider provider(String providerName) {
|
||||
ServiceLoader<ExchangeRateProvider> loader = ServiceLoader.load(ExchangeRateProvider.class);
|
||||
Iterator<ExchangeRateProvider> it = loader.iterator();
|
||||
while (it.hasNext()) {
|
||||
ExchangeRateProvider provider = it.next();
|
||||
if (providerName.equals(provider.getClass().getName())) {
|
||||
return provider;
|
||||
}
|
||||
}
|
||||
throw new ProviderNotFoundException("Exchange Rate provider " + providerName + " not found");
|
||||
}
|
||||
}
|
@ -0,0 +1,44 @@
|
||||
package com.baeldung.rate.api;
|
||||
|
||||
import java.math.BigDecimal;
|
||||
import java.time.LocalDate;
|
||||
|
||||
public class Quote {
|
||||
private String currency;
|
||||
private BigDecimal ask;
|
||||
private BigDecimal bid;
|
||||
private LocalDate date;
|
||||
//...
|
||||
|
||||
public String getCurrency() {
|
||||
return currency;
|
||||
}
|
||||
|
||||
public void setCurrency(String currency) {
|
||||
this.currency = currency;
|
||||
}
|
||||
|
||||
public BigDecimal getAsk() {
|
||||
return ask;
|
||||
}
|
||||
|
||||
public void setAsk(BigDecimal ask) {
|
||||
this.ask = ask;
|
||||
}
|
||||
|
||||
public BigDecimal getBid() {
|
||||
return bid;
|
||||
}
|
||||
|
||||
public void setBid(BigDecimal bid) {
|
||||
this.bid = bid;
|
||||
}
|
||||
|
||||
public LocalDate getDate() {
|
||||
return date;
|
||||
}
|
||||
|
||||
public void setDate(LocalDate date) {
|
||||
this.date = date;
|
||||
}
|
||||
}
|
Some files were not shown because too many files have changed in this diff Show More
Loading…
x
Reference in New Issue
Block a user