commit
ee1ea99d90
@ -1,9 +1,14 @@
|
|||||||
|
|
||||||
The "REST with Spring" Classes
|
The "REST with Spring" Classes
|
||||||
==============================
|
==============================
|
||||||
|
|
||||||
After 5 months of work, here's the Master Class of REST With Spring: <br/>
|
After 5 months of work, here's the Master Class of REST With Spring: <br/>
|
||||||
**[>> THE REST WITH SPRING MASTER CLASS](http://www.baeldung.com/rest-with-spring-course?utm_source=github&utm_medium=social&utm_content=tutorials&utm_campaign=rws#master-class)**
|
**[>> THE REST WITH SPRING MASTER CLASS](http://www.baeldung.com/rest-with-spring-course?utm_source=github&utm_medium=social&utm_content=tutorials&utm_campaign=rws#master-class)**
|
||||||
|
|
||||||
|
And here's the Master Class of Learn Spring Security: <br/>
|
||||||
|
**[>> LEARN SPRING SECURITY MASTER CLASS](http://www.baeldung.com/learn-spring-security-course?utm_source=github&utm_medium=social&utm_content=tutorials&utm_campaign=lss#master-class)**
|
||||||
|
|
||||||
|
|
||||||
|
|
||||||
Spring Tutorials
|
Spring Tutorials
|
||||||
================
|
================
|
||||||
|
@ -9,7 +9,7 @@
|
|||||||
<url>http://maven.apache.org</url>
|
<url>http://maven.apache.org</url>
|
||||||
|
|
||||||
<properties>
|
<properties>
|
||||||
<maven-compiler-plugin.version>3.6.0</maven-compiler-plugin.version>
|
<maven-compiler-plugin.version>3.7.0</maven-compiler-plugin.version>
|
||||||
</properties>
|
</properties>
|
||||||
|
|
||||||
<dependencies>
|
<dependencies>
|
||||||
@ -26,8 +26,8 @@
|
|||||||
<artifactId>maven-compiler-plugin</artifactId>
|
<artifactId>maven-compiler-plugin</artifactId>
|
||||||
<version>3.7.0</version>
|
<version>3.7.0</version>
|
||||||
<configuration>
|
<configuration>
|
||||||
<source>1.6</source>
|
<source>1.8</source>
|
||||||
<target>1.6</target>
|
<target>1.8</target>
|
||||||
</configuration>
|
</configuration>
|
||||||
</plugin>
|
</plugin>
|
||||||
<plugin>
|
<plugin>
|
||||||
|
@ -15,7 +15,7 @@
|
|||||||
|
|
||||||
<properties>
|
<properties>
|
||||||
<auto-service.version>1.0-rc2</auto-service.version>
|
<auto-service.version>1.0-rc2</auto-service.version>
|
||||||
<maven-compiler-plugin.version>3.6.0</maven-compiler-plugin.version>
|
<maven-compiler-plugin.version>3.7.0</maven-compiler-plugin.version>
|
||||||
</properties>
|
</properties>
|
||||||
|
|
||||||
<dependencies>
|
<dependencies>
|
||||||
|
@ -65,7 +65,7 @@
|
|||||||
<plugin>
|
<plugin>
|
||||||
<groupId>org.apache.maven.plugins</groupId>
|
<groupId>org.apache.maven.plugins</groupId>
|
||||||
<artifactId>maven-compiler-plugin</artifactId>
|
<artifactId>maven-compiler-plugin</artifactId>
|
||||||
<version>3.6.2</version>
|
<version>3.7.0</version>
|
||||||
<configuration>
|
<configuration>
|
||||||
<source>1.8</source>
|
<source>1.8</source>
|
||||||
<target>1.8</target>
|
<target>1.8</target>
|
||||||
|
@ -12,7 +12,7 @@
|
|||||||
|
|
||||||
<properties>
|
<properties>
|
||||||
<project.build.sourceEncoding>UTF-8</project.build.sourceEncoding>
|
<project.build.sourceEncoding>UTF-8</project.build.sourceEncoding>
|
||||||
<maven-compiler-plugin.version>3.6.0</maven-compiler-plugin.version>
|
<maven-compiler-plugin.version>3.7.0</maven-compiler-plugin.version>
|
||||||
<maven-surefire-plugin.version>2.19.1</maven-surefire-plugin.version>
|
<maven-surefire-plugin.version>2.19.1</maven-surefire-plugin.version>
|
||||||
<camel.version>2.19.1</camel.version>
|
<camel.version>2.19.1</camel.version>
|
||||||
<spring-boot-starter.version>1.5.4.RELEASE</spring-boot-starter.version>
|
<spring-boot-starter.version>1.5.4.RELEASE</spring-boot-starter.version>
|
||||||
|
2
cas/cas-secured-app/README.md
Normal file
2
cas/cas-secured-app/README.md
Normal file
@ -0,0 +1,2 @@
|
|||||||
|
## Relevant articles:
|
||||||
|
- [CAS SSO With Spring Security](http://www.baeldung.com/spring-security-cas-sso)
|
@ -14,7 +14,7 @@
|
|||||||
<parent>
|
<parent>
|
||||||
<groupId>org.springframework.boot</groupId>
|
<groupId>org.springframework.boot</groupId>
|
||||||
<artifactId>spring-boot-starter-parent</artifactId>
|
<artifactId>spring-boot-starter-parent</artifactId>
|
||||||
<version>2.0.0.BUILD-SNAPSHOT</version>
|
<version>2.0.0.M7</version>
|
||||||
<relativePath/> <!-- lookup parent from repository -->
|
<relativePath/> <!-- lookup parent from repository -->
|
||||||
</parent>
|
</parent>
|
||||||
|
|
||||||
@ -87,14 +87,6 @@
|
|||||||
</build>
|
</build>
|
||||||
|
|
||||||
<repositories>
|
<repositories>
|
||||||
<repository>
|
|
||||||
<id>spring-snapshots</id>
|
|
||||||
<name>Spring Snapshots</name>
|
|
||||||
<url>https://repo.spring.io/snapshot</url>
|
|
||||||
<snapshots>
|
|
||||||
<enabled>true</enabled>
|
|
||||||
</snapshots>
|
|
||||||
</repository>
|
|
||||||
<repository>
|
<repository>
|
||||||
<id>spring-milestones</id>
|
<id>spring-milestones</id>
|
||||||
<name>Spring Milestones</name>
|
<name>Spring Milestones</name>
|
||||||
@ -106,14 +98,6 @@
|
|||||||
</repositories>
|
</repositories>
|
||||||
|
|
||||||
<pluginRepositories>
|
<pluginRepositories>
|
||||||
<pluginRepository>
|
|
||||||
<id>spring-snapshots</id>
|
|
||||||
<name>Spring Snapshots</name>
|
|
||||||
<url>https://repo.spring.io/snapshot</url>
|
|
||||||
<snapshots>
|
|
||||||
<enabled>true</enabled>
|
|
||||||
</snapshots>
|
|
||||||
</pluginRepository>
|
|
||||||
<pluginRepository>
|
<pluginRepository>
|
||||||
<id>spring-milestones</id>
|
<id>spring-milestones</id>
|
||||||
<name>Spring Milestones</name>
|
<name>Spring Milestones</name>
|
||||||
|
@ -1,6 +1,7 @@
|
|||||||
package com.baeldung.cassecuredapp.controllers;
|
package com.baeldung.cassecuredapp.controllers;
|
||||||
|
|
||||||
import org.apache.log4j.Logger;
|
import org.apache.logging.log4j.Logger;
|
||||||
|
import org.apache.logging.log4j.LogManager;
|
||||||
import org.springframework.security.core.Authentication;
|
import org.springframework.security.core.Authentication;
|
||||||
import org.springframework.security.core.context.SecurityContextHolder;
|
import org.springframework.security.core.context.SecurityContextHolder;
|
||||||
import org.springframework.security.web.authentication.logout.CookieClearingLogoutHandler;
|
import org.springframework.security.web.authentication.logout.CookieClearingLogoutHandler;
|
||||||
@ -15,7 +16,7 @@ import javax.servlet.http.HttpServletResponse;
|
|||||||
@Controller
|
@Controller
|
||||||
public class AuthController {
|
public class AuthController {
|
||||||
|
|
||||||
private Logger logger = Logger.getLogger(AuthController.class);
|
private Logger logger = LogManager.getLogger(AuthController.class);
|
||||||
|
|
||||||
@GetMapping("/logout")
|
@GetMapping("/logout")
|
||||||
public String logout(
|
public String logout(
|
||||||
|
@ -52,7 +52,11 @@
|
|||||||
<plugin>
|
<plugin>
|
||||||
<groupId>org.apache.maven.plugins</groupId>
|
<groupId>org.apache.maven.plugins</groupId>
|
||||||
<artifactId>maven-compiler-plugin</artifactId>
|
<artifactId>maven-compiler-plugin</artifactId>
|
||||||
<version>3.3</version>
|
<version>3.7.0</version>
|
||||||
|
<configuration>
|
||||||
|
<source>1.8</source>
|
||||||
|
<target>1.8</target>
|
||||||
|
</configuration>
|
||||||
</plugin>
|
</plugin>
|
||||||
</plugins>
|
</plugins>
|
||||||
<finalName>cas</finalName>
|
<finalName>cas</finalName>
|
||||||
|
@ -32,3 +32,5 @@
|
|||||||
- [“Stream has already been operated upon or closed” Exception in Java](http://www.baeldung.com/java-stream-operated-upon-or-closed-exception)
|
- [“Stream has already been operated upon or closed” Exception in Java](http://www.baeldung.com/java-stream-operated-upon-or-closed-exception)
|
||||||
- [Display All Time Zones With GMT And UTC in Java](http://www.baeldung.com/java-time-zones)
|
- [Display All Time Zones With GMT And UTC in Java](http://www.baeldung.com/java-time-zones)
|
||||||
- [Copy a File with Java](http://www.baeldung.com/java-copy-file)
|
- [Copy a File with Java](http://www.baeldung.com/java-copy-file)
|
||||||
|
- [Generating Prime Numbers in Java](http://www.baeldung.com/java-generate-prime-numbers)
|
||||||
|
- [Static and Default Methods in Interfaces in Java](http://www.baeldung.com/java-static-default-methods)
|
||||||
|
@ -83,6 +83,24 @@
|
|||||||
<scope>test</scope>
|
<scope>test</scope>
|
||||||
</dependency>
|
</dependency>
|
||||||
|
|
||||||
|
<dependency>
|
||||||
|
<groupId>org.openjdk.jmh</groupId>
|
||||||
|
<artifactId>jmh-core</artifactId>
|
||||||
|
<version>1.19</version>
|
||||||
|
</dependency>
|
||||||
|
|
||||||
|
<dependency>
|
||||||
|
<groupId>org.openjdk.jmh</groupId>
|
||||||
|
<artifactId>jmh-generator-annprocess</artifactId>
|
||||||
|
<version>1.19</version>
|
||||||
|
</dependency>
|
||||||
|
|
||||||
|
<dependency>
|
||||||
|
<groupId>org.openjdk.jmh</groupId>
|
||||||
|
<artifactId>jmh-generator-bytecode</artifactId>
|
||||||
|
<version>1.19</version>
|
||||||
|
</dependency>
|
||||||
|
|
||||||
</dependencies>
|
</dependencies>
|
||||||
|
|
||||||
<build>
|
<build>
|
||||||
|
@ -2,7 +2,6 @@ package com.baeldung.datetime;
|
|||||||
|
|
||||||
import java.time.Duration;
|
import java.time.Duration;
|
||||||
import java.time.LocalTime;
|
import java.time.LocalTime;
|
||||||
import java.time.Period;
|
|
||||||
|
|
||||||
public class UseDuration {
|
public class UseDuration {
|
||||||
|
|
||||||
|
@ -0,0 +1,18 @@
|
|||||||
|
package com.baeldung.defaultstaticinterfacemethods.application;
|
||||||
|
|
||||||
|
import com.baeldung.defaultstaticinterfacemethods.model.Car;
|
||||||
|
import com.baeldung.defaultstaticinterfacemethods.model.Vehicle;
|
||||||
|
|
||||||
|
public class Application {
|
||||||
|
|
||||||
|
public static void main(String[] args) {
|
||||||
|
|
||||||
|
Vehicle car = new Car("BMW");
|
||||||
|
System.out.println(car.getBrand());
|
||||||
|
System.out.println(car.speedUp());
|
||||||
|
System.out.println(car.slowDown());
|
||||||
|
System.out.println(car.turnAlarmOn());
|
||||||
|
System.out.println(car.turnAlarmOff());
|
||||||
|
System.out.println(Vehicle.getHorsePower(2500, 480));
|
||||||
|
}
|
||||||
|
}
|
@ -0,0 +1,12 @@
|
|||||||
|
package com.baeldung.defaultstaticinterfacemethods.model;
|
||||||
|
|
||||||
|
public interface Alarm {
|
||||||
|
|
||||||
|
default String turnAlarmOn() {
|
||||||
|
return "Turning the alarm on.";
|
||||||
|
}
|
||||||
|
|
||||||
|
default String turnAlarmOff() {
|
||||||
|
return "Turning the alarm off.";
|
||||||
|
}
|
||||||
|
}
|
@ -0,0 +1,25 @@
|
|||||||
|
package com.baeldung.defaultstaticinterfacemethods.model;
|
||||||
|
|
||||||
|
public class Car implements Vehicle {
|
||||||
|
|
||||||
|
private final String brand;
|
||||||
|
|
||||||
|
public Car(String brand) {
|
||||||
|
this.brand = brand;
|
||||||
|
}
|
||||||
|
|
||||||
|
@Override
|
||||||
|
public String getBrand() {
|
||||||
|
return brand;
|
||||||
|
}
|
||||||
|
|
||||||
|
@Override
|
||||||
|
public String speedUp() {
|
||||||
|
return "The car is speeding up.";
|
||||||
|
}
|
||||||
|
|
||||||
|
@Override
|
||||||
|
public String slowDown() {
|
||||||
|
return "The car is slowing down.";
|
||||||
|
}
|
||||||
|
}
|
@ -0,0 +1,25 @@
|
|||||||
|
package com.baeldung.defaultstaticinterfacemethods.model;
|
||||||
|
|
||||||
|
public class Motorbike implements Vehicle {
|
||||||
|
|
||||||
|
private final String brand;
|
||||||
|
|
||||||
|
public Motorbike(String brand) {
|
||||||
|
this.brand = brand;
|
||||||
|
}
|
||||||
|
|
||||||
|
@Override
|
||||||
|
public String getBrand() {
|
||||||
|
return brand;
|
||||||
|
}
|
||||||
|
|
||||||
|
@Override
|
||||||
|
public String speedUp() {
|
||||||
|
return "The motorbike is speeding up.";
|
||||||
|
}
|
||||||
|
|
||||||
|
@Override
|
||||||
|
public String slowDown() {
|
||||||
|
return "The motorbike is slowing down.";
|
||||||
|
}
|
||||||
|
}
|
@ -0,0 +1,35 @@
|
|||||||
|
package com.baeldung.defaultstaticinterfacemethods.model;
|
||||||
|
|
||||||
|
public class MultiAlarmCar implements Vehicle, Alarm {
|
||||||
|
|
||||||
|
private final String brand;
|
||||||
|
|
||||||
|
public MultiAlarmCar(String brand) {
|
||||||
|
this.brand = brand;
|
||||||
|
}
|
||||||
|
|
||||||
|
@Override
|
||||||
|
public String getBrand() {
|
||||||
|
return brand;
|
||||||
|
}
|
||||||
|
|
||||||
|
@Override
|
||||||
|
public String speedUp() {
|
||||||
|
return "The motorbike is speeding up.";
|
||||||
|
}
|
||||||
|
|
||||||
|
@Override
|
||||||
|
public String slowDown() {
|
||||||
|
return "The mootorbike is slowing down.";
|
||||||
|
}
|
||||||
|
|
||||||
|
@Override
|
||||||
|
public String turnAlarmOn() {
|
||||||
|
return Vehicle.super.turnAlarmOn() + " " + Alarm.super.turnAlarmOn();
|
||||||
|
}
|
||||||
|
|
||||||
|
@Override
|
||||||
|
public String turnAlarmOff() {
|
||||||
|
return Vehicle.super.turnAlarmOff() + " " + Alarm.super.turnAlarmOff();
|
||||||
|
}
|
||||||
|
}
|
@ -0,0 +1,22 @@
|
|||||||
|
package com.baeldung.defaultstaticinterfacemethods.model;
|
||||||
|
|
||||||
|
public interface Vehicle {
|
||||||
|
|
||||||
|
String getBrand();
|
||||||
|
|
||||||
|
String speedUp();
|
||||||
|
|
||||||
|
String slowDown();
|
||||||
|
|
||||||
|
default String turnAlarmOn() {
|
||||||
|
return "Turning the vehice alarm on.";
|
||||||
|
}
|
||||||
|
|
||||||
|
default String turnAlarmOff() {
|
||||||
|
return "Turning the vehicle alarm off.";
|
||||||
|
}
|
||||||
|
|
||||||
|
static int getHorsePower(int rpm, int torque) {
|
||||||
|
return (rpm * torque) / 5252;
|
||||||
|
}
|
||||||
|
}
|
@ -0,0 +1,80 @@
|
|||||||
|
package com.baeldung.iterators;
|
||||||
|
|
||||||
|
import java.util.ArrayList;
|
||||||
|
import java.util.Iterator;
|
||||||
|
import java.util.concurrent.ConcurrentHashMap;
|
||||||
|
|
||||||
|
/**
|
||||||
|
* Source code https://github.com/eugenp/tutorials
|
||||||
|
*
|
||||||
|
* @author Santosh Thakur
|
||||||
|
*/
|
||||||
|
|
||||||
|
public class Iterators {
|
||||||
|
|
||||||
|
public static int failFast1() {
|
||||||
|
ArrayList<Integer> numbers = new ArrayList<>();
|
||||||
|
|
||||||
|
numbers.add(10);
|
||||||
|
numbers.add(20);
|
||||||
|
numbers.add(30);
|
||||||
|
numbers.add(40);
|
||||||
|
|
||||||
|
Iterator<Integer> iterator = numbers.iterator();
|
||||||
|
while (iterator.hasNext()) {
|
||||||
|
Integer number = iterator.next();
|
||||||
|
numbers.add(50);
|
||||||
|
}
|
||||||
|
|
||||||
|
return numbers.size();
|
||||||
|
}
|
||||||
|
|
||||||
|
public static int failFast2() {
|
||||||
|
ArrayList<Integer> numbers = new ArrayList<>();
|
||||||
|
numbers.add(10);
|
||||||
|
numbers.add(20);
|
||||||
|
numbers.add(30);
|
||||||
|
numbers.add(40);
|
||||||
|
|
||||||
|
Iterator<Integer> iterator = numbers.iterator();
|
||||||
|
while (iterator.hasNext()) {
|
||||||
|
if (iterator.next() == 30) {
|
||||||
|
// will not throw Exception
|
||||||
|
iterator.remove();
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
System.out.println("using iterator's remove method = " + numbers);
|
||||||
|
|
||||||
|
iterator = numbers.iterator();
|
||||||
|
while (iterator.hasNext()) {
|
||||||
|
if (iterator.next() == 40) {
|
||||||
|
// will throw Exception on
|
||||||
|
// next call of next() method
|
||||||
|
numbers.remove(2);
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
return numbers.size();
|
||||||
|
}
|
||||||
|
|
||||||
|
public static int failSafe1() {
|
||||||
|
ConcurrentHashMap<String, Integer> map = new ConcurrentHashMap<>();
|
||||||
|
|
||||||
|
map.put("First", 10);
|
||||||
|
map.put("Second", 20);
|
||||||
|
map.put("Third", 30);
|
||||||
|
map.put("Fourth", 40);
|
||||||
|
|
||||||
|
Iterator<String> iterator = map.keySet()
|
||||||
|
.iterator();
|
||||||
|
|
||||||
|
while (iterator.hasNext()) {
|
||||||
|
String key = iterator.next();
|
||||||
|
map.put("Fifth", 50);
|
||||||
|
}
|
||||||
|
|
||||||
|
return map.size();
|
||||||
|
}
|
||||||
|
|
||||||
|
}
|
@ -0,0 +1,23 @@
|
|||||||
|
package com.baeldung.stream;
|
||||||
|
|
||||||
|
import java.util.Arrays;
|
||||||
|
import java.util.stream.IntStream;
|
||||||
|
|
||||||
|
class PrimitiveStreams {
|
||||||
|
|
||||||
|
int min(int[] integers) {
|
||||||
|
return Arrays.stream(integers).min().getAsInt();
|
||||||
|
}
|
||||||
|
|
||||||
|
int max(int... integers) {
|
||||||
|
return IntStream.of(integers).max().getAsInt();
|
||||||
|
}
|
||||||
|
|
||||||
|
int sum(int... integers) {
|
||||||
|
return IntStream.of(integers).sum();
|
||||||
|
}
|
||||||
|
|
||||||
|
double avg(int... integers) {
|
||||||
|
return IntStream.of(integers).average().getAsDouble();
|
||||||
|
}
|
||||||
|
}
|
@ -1,8 +1,6 @@
|
|||||||
package com.baeldung.streamApi;
|
package com.baeldung.streamApi;
|
||||||
|
|
||||||
import java.util.List;
|
import java.util.List;
|
||||||
import java.util.Optional;
|
|
||||||
import java.util.stream.IntStream;
|
|
||||||
import java.util.stream.Stream;
|
import java.util.stream.Stream;
|
||||||
|
|
||||||
/**
|
/**
|
||||||
|
@ -0,0 +1,61 @@
|
|||||||
|
package com.baeldung.counter;
|
||||||
|
|
||||||
|
import java.util.HashMap;
|
||||||
|
import java.util.Map;
|
||||||
|
import java.util.Random;
|
||||||
|
|
||||||
|
import org.openjdk.jmh.annotations.Benchmark;
|
||||||
|
import org.openjdk.jmh.annotations.BenchmarkMode;
|
||||||
|
import org.openjdk.jmh.annotations.Fork;
|
||||||
|
import org.openjdk.jmh.annotations.Mode;
|
||||||
|
|
||||||
|
import com.baeldung.counter.CounterUtil.MutableInteger;
|
||||||
|
|
||||||
|
@Fork(value = 1, warmups = 3)
|
||||||
|
@BenchmarkMode(Mode.All)
|
||||||
|
public class CounterStatistics {
|
||||||
|
|
||||||
|
private static final Map<String, Integer> counterMap = new HashMap<>();
|
||||||
|
private static final Map<String, MutableInteger> counterWithMutableIntMap = new HashMap<>();
|
||||||
|
private static final Map<String, int[]> counterWithIntArrayMap = new HashMap<>();
|
||||||
|
private static final Map<String, Long> counterWithLongWrapperMap = new HashMap<>();
|
||||||
|
private static final Map<String, Long> counterWithLongWrapperStreamMap = new HashMap<>();
|
||||||
|
|
||||||
|
static {
|
||||||
|
CounterUtil.COUNTRY_NAMES = new String[10000];
|
||||||
|
final String prefix = "NewString";
|
||||||
|
Random random = new Random();
|
||||||
|
for (int i=0; i<10000; i++) {
|
||||||
|
CounterUtil.COUNTRY_NAMES[i] = new String(prefix + random.nextInt(1000));
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
@Benchmark
|
||||||
|
public void wrapperAsCounter() {
|
||||||
|
CounterUtil.counterWithWrapperObject(counterMap);
|
||||||
|
}
|
||||||
|
|
||||||
|
@Benchmark
|
||||||
|
public void lambdaExpressionWithWrapper() {
|
||||||
|
CounterUtil.counterWithLambdaAndWrapper(counterWithLongWrapperMap);
|
||||||
|
}
|
||||||
|
|
||||||
|
@Benchmark
|
||||||
|
public void parallelStreamWithWrapper() {
|
||||||
|
CounterUtil.counterWithParallelStreamAndWrapper(counterWithLongWrapperStreamMap);
|
||||||
|
}
|
||||||
|
|
||||||
|
@Benchmark
|
||||||
|
public void mutableIntegerAsCounter() {
|
||||||
|
CounterUtil.counterWithMutableInteger(counterWithMutableIntMap);
|
||||||
|
}
|
||||||
|
|
||||||
|
@Benchmark
|
||||||
|
public void primitiveArrayAsCounter() {
|
||||||
|
CounterUtil.counterWithPrimitiveArray(counterWithIntArrayMap);
|
||||||
|
}
|
||||||
|
|
||||||
|
public static void main(String[] args) throws Exception {
|
||||||
|
org.openjdk.jmh.Main.main(args);
|
||||||
|
}
|
||||||
|
}
|
@ -0,0 +1,53 @@
|
|||||||
|
package com.baeldung.counter;
|
||||||
|
|
||||||
|
import java.util.HashMap;
|
||||||
|
import java.util.Map;
|
||||||
|
|
||||||
|
import static org.junit.Assert.*;
|
||||||
|
|
||||||
|
import org.junit.Test;
|
||||||
|
|
||||||
|
import com.baeldung.counter.CounterUtil.MutableInteger;
|
||||||
|
|
||||||
|
public class CounterTest {
|
||||||
|
|
||||||
|
@Test
|
||||||
|
public void whenMapWithWrapperAsCounter_runsSuccessfully() {
|
||||||
|
Map<String, Integer> counterMap = new HashMap<>();
|
||||||
|
CounterUtil.counterWithWrapperObject(counterMap);
|
||||||
|
|
||||||
|
assertEquals(3, counterMap.get("China")
|
||||||
|
.intValue());
|
||||||
|
assertEquals(2, counterMap.get("India")
|
||||||
|
.intValue());
|
||||||
|
}
|
||||||
|
|
||||||
|
@Test
|
||||||
|
public void whenMapWithLambdaAndWrapperCounter_runsSuccessfully() {
|
||||||
|
Map<String, Long> counterMap = new HashMap<>();
|
||||||
|
CounterUtil.counterWithLambdaAndWrapper(counterMap);
|
||||||
|
|
||||||
|
assertEquals(3l, counterMap.get("China")
|
||||||
|
.longValue());
|
||||||
|
assertEquals(2l, counterMap.get("India")
|
||||||
|
.longValue());
|
||||||
|
}
|
||||||
|
|
||||||
|
@Test
|
||||||
|
public void whenMapWithMutableIntegerCounter_runsSuccessfully() {
|
||||||
|
Map<String, MutableInteger> counterMap = new HashMap<>();
|
||||||
|
CounterUtil.counterWithMutableInteger(counterMap);
|
||||||
|
assertEquals(3, counterMap.get("China")
|
||||||
|
.getCount());
|
||||||
|
assertEquals(2, counterMap.get("India")
|
||||||
|
.getCount());
|
||||||
|
}
|
||||||
|
|
||||||
|
@Test
|
||||||
|
public void whenMapWithPrimitiveArray_runsSuccessfully() {
|
||||||
|
Map<String, int[]> counterMap = new HashMap<>();
|
||||||
|
CounterUtil.counterWithPrimitiveArray(counterMap);
|
||||||
|
assertEquals(3, counterMap.get("China")[0]);
|
||||||
|
assertEquals(2, counterMap.get("India")[0]);
|
||||||
|
}
|
||||||
|
}
|
@ -0,0 +1,57 @@
|
|||||||
|
package com.baeldung.counter;
|
||||||
|
|
||||||
|
import java.util.Map;
|
||||||
|
import java.util.stream.Collectors;
|
||||||
|
import java.util.stream.Stream;
|
||||||
|
|
||||||
|
public class CounterUtil {
|
||||||
|
|
||||||
|
public static String[] COUNTRY_NAMES = { "China", "Australia", "India", "USA", "USSR", "UK", "China", "France", "Poland", "Austria", "India", "USA", "Egypt", "China" };
|
||||||
|
|
||||||
|
public static void counterWithWrapperObject(Map<String, Integer> counterMap) {
|
||||||
|
for (String country : COUNTRY_NAMES) {
|
||||||
|
counterMap.compute(country, (k, v) -> v == null ? 1 : v + 1);
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
public static void counterWithLambdaAndWrapper(Map<String, Long> counterMap) {
|
||||||
|
Stream.of(COUNTRY_NAMES)
|
||||||
|
.collect(Collectors.groupingBy(k -> k, () -> counterMap, Collectors.counting()));
|
||||||
|
}
|
||||||
|
|
||||||
|
public static void counterWithParallelStreamAndWrapper(Map<String, Long> counterMap) {
|
||||||
|
Stream.of(COUNTRY_NAMES)
|
||||||
|
.parallel()
|
||||||
|
.collect(Collectors.groupingBy(k -> k, () -> counterMap, Collectors.counting()));
|
||||||
|
}
|
||||||
|
|
||||||
|
public static class MutableInteger {
|
||||||
|
int count;
|
||||||
|
|
||||||
|
public MutableInteger(int count) {
|
||||||
|
this.count = count;
|
||||||
|
}
|
||||||
|
|
||||||
|
public void increment() {
|
||||||
|
this.count++;
|
||||||
|
}
|
||||||
|
|
||||||
|
public int getCount() {
|
||||||
|
return this.count;
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
public static void counterWithMutableInteger(Map<String, MutableInteger> counterMap) {
|
||||||
|
for (String country : COUNTRY_NAMES) {
|
||||||
|
counterMap.compute(country, (k, v) -> v == null ? new MutableInteger(0) : v)
|
||||||
|
.increment();
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
public static void counterWithPrimitiveArray(Map<String, int[]> counterMap) {
|
||||||
|
for (String country : COUNTRY_NAMES) {
|
||||||
|
counterMap.compute(country, (k, v) -> v == null ? new int[] { 0 } : v)[0]++;
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
}
|
@ -4,7 +4,6 @@ import java.time.LocalDate;
|
|||||||
import java.time.LocalTime;
|
import java.time.LocalTime;
|
||||||
import java.time.Month;
|
import java.time.Month;
|
||||||
|
|
||||||
import org.junit.Assert;
|
|
||||||
import org.junit.Test;
|
import org.junit.Test;
|
||||||
|
|
||||||
import static org.junit.Assert.assertEquals;
|
import static org.junit.Assert.assertEquals;
|
||||||
|
@ -4,7 +4,6 @@ import java.time.DayOfWeek;
|
|||||||
import java.time.LocalDate;
|
import java.time.LocalDate;
|
||||||
import java.time.LocalDateTime;
|
import java.time.LocalDateTime;
|
||||||
|
|
||||||
import org.junit.Assert;
|
|
||||||
import org.junit.Test;
|
import org.junit.Test;
|
||||||
|
|
||||||
import static org.junit.Assert.assertEquals;
|
import static org.junit.Assert.assertEquals;
|
||||||
|
@ -0,0 +1,79 @@
|
|||||||
|
package com.baeldung.defaultistaticinterfacemethods.test;
|
||||||
|
|
||||||
|
import com.baeldung.defaultstaticinterfacemethods.model.Car;
|
||||||
|
import com.baeldung.defaultstaticinterfacemethods.model.Motorbike;
|
||||||
|
import com.baeldung.defaultstaticinterfacemethods.model.Vehicle;
|
||||||
|
import org.junit.BeforeClass;
|
||||||
|
import org.junit.Test;
|
||||||
|
import static org.assertj.core.api.Assertions.*;
|
||||||
|
|
||||||
|
public class StaticDefaulInterfaceMethodUnitTest {
|
||||||
|
|
||||||
|
private static Car car;
|
||||||
|
private static Motorbike motorbike;
|
||||||
|
|
||||||
|
@BeforeClass
|
||||||
|
public static void setUpCarInstance() {
|
||||||
|
car = new Car("BMW");
|
||||||
|
}
|
||||||
|
|
||||||
|
@BeforeClass
|
||||||
|
public static void setUpMotorbikeInstance() {
|
||||||
|
motorbike = new Motorbike("Yamaha");
|
||||||
|
}
|
||||||
|
|
||||||
|
@Test
|
||||||
|
public void givenCarInstace_whenBrandisBMW_thenOneAssertion() {
|
||||||
|
assertThat(car.getBrand()).isEqualTo("BMW");
|
||||||
|
}
|
||||||
|
|
||||||
|
@Test
|
||||||
|
public void givenCarInstance_whenCallingSpeedUp_thenOneAssertion() {
|
||||||
|
assertThat(car.speedUp()).isEqualTo("The car is speeding up.");
|
||||||
|
}
|
||||||
|
|
||||||
|
@Test
|
||||||
|
public void givenCarInstance_whenCallingSlowDown_thenOneAssertion() {
|
||||||
|
assertThat(car.slowDown()).isEqualTo("The car is slowing down.");
|
||||||
|
}
|
||||||
|
|
||||||
|
@Test
|
||||||
|
public void givenCarInstance_whenCallingTurnAlarmOn_thenOneAssertion() {
|
||||||
|
assertThat(car.turnAlarmOn()).isEqualTo("Turning the vehice alarm on.");
|
||||||
|
}
|
||||||
|
|
||||||
|
@Test
|
||||||
|
public void givenCarInstance_whenCallingTurnAlarmOff_thenOneAssertion() {
|
||||||
|
assertThat(car.turnAlarmOff()).isEqualTo("Turning the vehicle alarm off.");
|
||||||
|
}
|
||||||
|
|
||||||
|
@Test
|
||||||
|
public void givenVehicleInterface_whenCallinggetHorsePower_thenOneAssertion() {
|
||||||
|
assertThat(Vehicle.getHorsePower(2500, 480)).isEqualTo(228);
|
||||||
|
}
|
||||||
|
|
||||||
|
@Test
|
||||||
|
public void givenMooorbikeInstace_whenBrandisYamaha_thenOneAssertion() {
|
||||||
|
assertThat(motorbike.getBrand()).isEqualTo("Yamaha");
|
||||||
|
}
|
||||||
|
|
||||||
|
@Test
|
||||||
|
public void givenMotorbikeInstance_whenCallingSpeedUp_thenOneAssertion() {
|
||||||
|
assertThat(motorbike.speedUp()).isEqualTo("The motorbike is speeding up.");
|
||||||
|
}
|
||||||
|
|
||||||
|
@Test
|
||||||
|
public void givenMotorbikeInstance_whenCallingSlowDown_thenOneAssertion() {
|
||||||
|
assertThat(motorbike.slowDown()).isEqualTo("The motorbike is slowing down.");
|
||||||
|
}
|
||||||
|
|
||||||
|
@Test
|
||||||
|
public void givenMotorbikeInstance_whenCallingTurnAlarmOn_thenOneAssertion() {
|
||||||
|
assertThat(motorbike.turnAlarmOn()).isEqualTo("Turning the vehice alarm on.");
|
||||||
|
}
|
||||||
|
|
||||||
|
@Test
|
||||||
|
public void givenMotorbikeInstance_whenCallingTurnAlarmOff_thenOneAssertion() {
|
||||||
|
assertThat(motorbike.turnAlarmOff()).isEqualTo("Turning the vehicle alarm off.");
|
||||||
|
}
|
||||||
|
}
|
@ -0,0 +1,40 @@
|
|||||||
|
package com.baeldung.iterators;
|
||||||
|
|
||||||
|
import static com.baeldung.iterators.Iterators.failFast1;
|
||||||
|
import static com.baeldung.iterators.Iterators.failFast2;
|
||||||
|
import static com.baeldung.iterators.Iterators.failSafe1;
|
||||||
|
import static org.assertj.core.api.Assertions.assertThat;
|
||||||
|
import static org.assertj.core.api.Assertions.assertThatThrownBy;
|
||||||
|
|
||||||
|
import java.util.ConcurrentModificationException;
|
||||||
|
|
||||||
|
import org.junit.Test;
|
||||||
|
|
||||||
|
/**
|
||||||
|
* Source code https://github.com/eugenp/tutorials
|
||||||
|
*
|
||||||
|
* @author Santosh Thakur
|
||||||
|
*/
|
||||||
|
|
||||||
|
public class IteratorsTest {
|
||||||
|
|
||||||
|
@Test
|
||||||
|
public void whenFailFast_ThenThrowsException() {
|
||||||
|
assertThatThrownBy(() -> {
|
||||||
|
failFast1();
|
||||||
|
}).isInstanceOf(ConcurrentModificationException.class);
|
||||||
|
}
|
||||||
|
|
||||||
|
@Test
|
||||||
|
public void whenFailFast_ThenThrowsExceptionInSecondIteration() {
|
||||||
|
assertThatThrownBy(() -> {
|
||||||
|
failFast2();
|
||||||
|
}).isInstanceOf(ConcurrentModificationException.class);
|
||||||
|
}
|
||||||
|
|
||||||
|
@Test
|
||||||
|
public void whenFailSafe_ThenDoesNotThrowException() {
|
||||||
|
assertThat(failSafe1()).isGreaterThanOrEqualTo(0);
|
||||||
|
}
|
||||||
|
|
||||||
|
}
|
@ -6,7 +6,6 @@ import java.util.Comparator;
|
|||||||
import org.junit.Before;
|
import org.junit.Before;
|
||||||
import org.junit.Test;
|
import org.junit.Test;
|
||||||
|
|
||||||
import lombok.Data;
|
|
||||||
import static org.junit.Assert.assertTrue;
|
import static org.junit.Assert.assertTrue;
|
||||||
|
|
||||||
public class Java8ComparatorUnitTest {
|
public class Java8ComparatorUnitTest {
|
||||||
@ -134,8 +133,7 @@ public class Java8ComparatorUnitTest {
|
|||||||
|
|
||||||
@Test
|
@Test
|
||||||
public void whenThenComparing_thenSortedByAgeName() {
|
public void whenThenComparing_thenSortedByAgeName() {
|
||||||
Comparator<Employee> employee_Age_Name_Comparator = Comparator.comparing(Employee::getAge)
|
Comparator<Employee> employee_Age_Name_Comparator = Comparator.comparing(Employee::getAge).thenComparing(Employee::getName);
|
||||||
.thenComparing(Employee::getName);
|
|
||||||
|
|
||||||
Arrays.sort(someMoreEmployees, employee_Age_Name_Comparator);
|
Arrays.sort(someMoreEmployees, employee_Age_Name_Comparator);
|
||||||
// System.out.println(Arrays.toString(someMoreEmployees));
|
// System.out.println(Arrays.toString(someMoreEmployees));
|
||||||
@ -144,8 +142,7 @@ public class Java8ComparatorUnitTest {
|
|||||||
|
|
||||||
@Test
|
@Test
|
||||||
public void whenThenComparing_thenSortedByNameAge() {
|
public void whenThenComparing_thenSortedByNameAge() {
|
||||||
Comparator<Employee> employee_Name_Age_Comparator = Comparator.comparing(Employee::getName)
|
Comparator<Employee> employee_Name_Age_Comparator = Comparator.comparing(Employee::getName).thenComparingInt(Employee::getAge);
|
||||||
.thenComparingInt(Employee::getAge);
|
|
||||||
|
|
||||||
Arrays.sort(someMoreEmployees, employee_Name_Age_Comparator);
|
Arrays.sort(someMoreEmployees, employee_Name_Age_Comparator);
|
||||||
// System.out.println(Arrays.toString(someMoreEmployees));
|
// System.out.println(Arrays.toString(someMoreEmployees));
|
||||||
|
@ -0,0 +1,96 @@
|
|||||||
|
package com.baeldung.stream;
|
||||||
|
|
||||||
|
import org.junit.Test;
|
||||||
|
|
||||||
|
import java.util.Arrays;
|
||||||
|
import java.util.List;
|
||||||
|
import java.util.stream.Collectors;
|
||||||
|
import java.util.stream.IntStream;
|
||||||
|
|
||||||
|
import static org.junit.Assert.assertEquals;
|
||||||
|
import static org.junit.Assert.assertTrue;
|
||||||
|
|
||||||
|
public class PrimitiveStreamsUnitTest {
|
||||||
|
|
||||||
|
private PrimitiveStreams streams = new PrimitiveStreams();
|
||||||
|
|
||||||
|
@Test
|
||||||
|
public void givenAnArrayOfIntegersWhenMinIsCalledThenCorrectMinIsReturned() {
|
||||||
|
int[] integers = new int[] {20, 98, 12, 7, 35};
|
||||||
|
int min = streams.min(integers); // returns 7
|
||||||
|
|
||||||
|
assertEquals(7, min);
|
||||||
|
}
|
||||||
|
|
||||||
|
@Test
|
||||||
|
public void givenAnArrayOfIntegersWhenMaxIsCalledThenCorrectMaxIsReturned() {
|
||||||
|
int max = streams.max(20, 98, 12, 7, 35);
|
||||||
|
|
||||||
|
assertEquals(98, max);
|
||||||
|
}
|
||||||
|
|
||||||
|
@Test
|
||||||
|
public void givenAnArrayOfIntegersWhenSumIsCalledThenCorrectSumIsReturned() {
|
||||||
|
int sum = streams.sum(20, 98, 12, 7, 35);
|
||||||
|
|
||||||
|
assertEquals(172, sum);
|
||||||
|
}
|
||||||
|
|
||||||
|
@Test
|
||||||
|
public void givenAnArrayOfIntegersWhenAvgIsCalledThenCorrectAvgIsReturned() {
|
||||||
|
double avg = streams.avg(20, 98, 12, 7, 35);
|
||||||
|
|
||||||
|
assertTrue(34.4 == avg);
|
||||||
|
}
|
||||||
|
|
||||||
|
@Test
|
||||||
|
public void givenARangeOfIntegersWhenIntStreamSumIsCalledThenCorrectSumIsReturned() {
|
||||||
|
int sum = IntStream.range(1, 10).sum();
|
||||||
|
|
||||||
|
assertEquals(45, sum);
|
||||||
|
}
|
||||||
|
|
||||||
|
@Test
|
||||||
|
public void givenARangeClosedOfIntegersWhenIntStreamSumIsCalledThenCorrectSumIsReturned() {
|
||||||
|
int sum = IntStream.rangeClosed(1, 10).sum();
|
||||||
|
|
||||||
|
assertEquals(55, sum);
|
||||||
|
}
|
||||||
|
|
||||||
|
@Test
|
||||||
|
public void givenARangeWhenForEachIsCalledThenTheIndicesWillBePrinted() {
|
||||||
|
IntStream.rangeClosed(1, 5).parallel().forEach(System.out::println);
|
||||||
|
}
|
||||||
|
|
||||||
|
@Test
|
||||||
|
public void givenAnArrayWhenSumIsCalledThenTheCorrectSumIsReturned() {
|
||||||
|
|
||||||
|
int sum = Arrays.asList(33,45).stream().mapToInt(a -> a).sum();
|
||||||
|
|
||||||
|
assertEquals(78, sum);
|
||||||
|
}
|
||||||
|
|
||||||
|
@Test
|
||||||
|
public void givenAnIntStreamThenGetTheEvenIntegers() {
|
||||||
|
List<Integer> evenInts = IntStream.rangeClosed(1, 10)
|
||||||
|
.filter(i -> i % 2 == 0)
|
||||||
|
.boxed()
|
||||||
|
.collect(Collectors.toList());
|
||||||
|
|
||||||
|
List<Integer> expected = IntStream.of(2, 4, 6, 8, 10).boxed().collect(Collectors.toList());
|
||||||
|
|
||||||
|
assertEquals(expected, evenInts);
|
||||||
|
}
|
||||||
|
|
||||||
|
class Person {
|
||||||
|
private int age;
|
||||||
|
|
||||||
|
Person(int age) {
|
||||||
|
this.age = age;
|
||||||
|
}
|
||||||
|
|
||||||
|
int getAge() {
|
||||||
|
return age;
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
@ -1,7 +1,6 @@
|
|||||||
package com.baeldung.temporaladjusters;
|
package com.baeldung.temporaladjusters;
|
||||||
|
|
||||||
import com.baeldung.temporaladjuster.CustomTemporalAdjuster;
|
import com.baeldung.temporaladjuster.CustomTemporalAdjuster;
|
||||||
import org.junit.Assert;
|
|
||||||
import org.junit.Test;
|
import org.junit.Test;
|
||||||
|
|
||||||
import java.time.LocalDate;
|
import java.time.LocalDate;
|
||||||
|
@ -18,3 +18,5 @@
|
|||||||
- [How to Get All Dates Between Two Dates?](http://www.baeldung.com/java-between-dates)
|
- [How to Get All Dates Between Two Dates?](http://www.baeldung.com/java-between-dates)
|
||||||
- [Java 9 java.util.Objects Additions](http://www.baeldung.com/java-9-objects-new)
|
- [Java 9 java.util.Objects Additions](http://www.baeldung.com/java-9-objects-new)
|
||||||
- [Compact Strings in Java 9](http://www.baeldung.com/java-9-compact-string)
|
- [Compact Strings in Java 9](http://www.baeldung.com/java-9-compact-string)
|
||||||
|
- [Convert Date to LocalDate or LocalDateTime and Back](http://www.baeldung.com/java-date-to-localdate-and-localdatetime)
|
||||||
|
- [Java 9 Variable Handles Demistyfied](http://www.baeldung.com/java-variable-handles)
|
||||||
|
3
core-java-9/compile-httpclient.bat
Normal file
3
core-java-9/compile-httpclient.bat
Normal file
@ -0,0 +1,3 @@
|
|||||||
|
javac --module-path mods -d mods/com.baeldung.httpclient^
|
||||||
|
src/modules/com.baeldung.httpclient/module-info.java^
|
||||||
|
src/modules/com.baeldung.httpclient/com/baeldung/httpclient/HttpClientExample.java
|
@ -90,7 +90,7 @@
|
|||||||
<org.slf4j.version>1.7.21</org.slf4j.version>
|
<org.slf4j.version>1.7.21</org.slf4j.version>
|
||||||
<ch.qos.logback.version>1.2.1</ch.qos.logback.version>
|
<ch.qos.logback.version>1.2.1</ch.qos.logback.version>
|
||||||
<!-- maven plugins -->
|
<!-- maven plugins -->
|
||||||
<maven-compiler-plugin.version>3.6.0</maven-compiler-plugin.version>
|
<maven-compiler-plugin.version>3.7.0</maven-compiler-plugin.version>
|
||||||
<maven-surefire-plugin.version>2.19.1</maven-surefire-plugin.version>
|
<maven-surefire-plugin.version>2.19.1</maven-surefire-plugin.version>
|
||||||
|
|
||||||
<!-- testing -->
|
<!-- testing -->
|
||||||
|
1
core-java-9/run-httpclient.bat
Normal file
1
core-java-9/run-httpclient.bat
Normal file
@ -0,0 +1 @@
|
|||||||
|
java --module-path mods -m com.baeldung.httpclient/com.baeldung.httpclient.HttpClientExample
|
@ -0,0 +1,84 @@
|
|||||||
|
/*
|
||||||
|
* To change this license header, choose License Headers in Project Properties.
|
||||||
|
* To change this template file, choose Tools | Templates
|
||||||
|
* and open the template in the editor.
|
||||||
|
*/
|
||||||
|
package com.baeldung.httpclient;
|
||||||
|
|
||||||
|
import java.io.File;
|
||||||
|
import java.io.IOException;
|
||||||
|
import java.net.URI;
|
||||||
|
import java.net.URISyntaxException;
|
||||||
|
import java.nio.file.Paths;
|
||||||
|
import java.util.Arrays;
|
||||||
|
import java.util.List;
|
||||||
|
import java.util.concurrent.CompletableFuture;
|
||||||
|
import java.util.stream.Collectors;
|
||||||
|
import jdk.incubator.http.HttpClient;
|
||||||
|
import jdk.incubator.http.HttpRequest;
|
||||||
|
import jdk.incubator.http.HttpRequest.BodyProcessor;
|
||||||
|
import jdk.incubator.http.HttpResponse;
|
||||||
|
import jdk.incubator.http.HttpResponse.BodyHandler;
|
||||||
|
|
||||||
|
/**
|
||||||
|
*
|
||||||
|
* @author pkaria
|
||||||
|
*/
|
||||||
|
public class HttpClientExample {
|
||||||
|
|
||||||
|
public static void main(String[] args) throws Exception {
|
||||||
|
httpGetRequest();
|
||||||
|
httpPostRequest();
|
||||||
|
asynchronousRequest();
|
||||||
|
asynchronousMultipleRequests();
|
||||||
|
}
|
||||||
|
|
||||||
|
public static void httpGetRequest() throws URISyntaxException, IOException, InterruptedException {
|
||||||
|
HttpClient client = HttpClient.newHttpClient();
|
||||||
|
URI httpURI = new URI("http://jsonplaceholder.typicode.com/posts/1");
|
||||||
|
HttpRequest request = HttpRequest.newBuilder(httpURI).GET()
|
||||||
|
.headers("Accept-Enconding", "gzip, deflate").build();
|
||||||
|
HttpResponse<String> response = client.send(request, HttpResponse.BodyHandler.asString());
|
||||||
|
String responseBody = response.body();
|
||||||
|
int responseStatusCode = response.statusCode();
|
||||||
|
System.out.println(responseBody);
|
||||||
|
}
|
||||||
|
|
||||||
|
public static void httpPostRequest() throws URISyntaxException, IOException, InterruptedException {
|
||||||
|
HttpClient client = HttpClient
|
||||||
|
.newBuilder()
|
||||||
|
.build();
|
||||||
|
HttpRequest request = HttpRequest
|
||||||
|
.newBuilder(new URI("http://jsonplaceholder.typicode.com/posts"))
|
||||||
|
.POST(BodyProcessor.fromString("Sample Post Request"))
|
||||||
|
.build();
|
||||||
|
HttpResponse<String> response
|
||||||
|
= client.send(request, HttpResponse.BodyHandler.asString());
|
||||||
|
String responseBody = response.body();
|
||||||
|
System.out.println(responseBody);
|
||||||
|
}
|
||||||
|
|
||||||
|
public static void asynchronousRequest() throws URISyntaxException {
|
||||||
|
HttpClient client = HttpClient.newHttpClient();
|
||||||
|
URI httpURI = new URI("http://jsonplaceholder.typicode.com/posts/1");
|
||||||
|
HttpRequest request = HttpRequest.newBuilder(httpURI).GET().build();
|
||||||
|
CompletableFuture<HttpResponse<String>> futureResponse = client.sendAsync(request,
|
||||||
|
HttpResponse.BodyHandler.asString());
|
||||||
|
}
|
||||||
|
|
||||||
|
public static void asynchronousMultipleRequests() throws URISyntaxException {
|
||||||
|
List<URI> targets = Arrays.asList(new URI("http://jsonplaceholder.typicode.com/posts/1"), new URI("http://jsonplaceholder.typicode.com/posts/2"));
|
||||||
|
HttpClient client = HttpClient.newHttpClient();
|
||||||
|
List<CompletableFuture<File>> futures = targets
|
||||||
|
.stream()
|
||||||
|
.map(target -> client
|
||||||
|
.sendAsync(
|
||||||
|
HttpRequest.newBuilder(target)
|
||||||
|
.GET()
|
||||||
|
.build(),
|
||||||
|
BodyHandler.asFile(Paths.get("base", target.getPath())))
|
||||||
|
.thenApply(response -> response.body())
|
||||||
|
.thenApply(path -> path.toFile()))
|
||||||
|
.collect(Collectors.toList());
|
||||||
|
}
|
||||||
|
}
|
@ -0,0 +1,3 @@
|
|||||||
|
module com.baeldung.httpclient {
|
||||||
|
requires jdk.incubator.httpclient;
|
||||||
|
}
|
@ -0,0 +1,106 @@
|
|||||||
|
package com.baeldung.java9.varhandles;
|
||||||
|
|
||||||
|
import org.junit.Test;
|
||||||
|
|
||||||
|
import java.lang.invoke.MethodHandles;
|
||||||
|
import java.lang.invoke.VarHandle;
|
||||||
|
|
||||||
|
import static org.assertj.core.api.Assertions.assertThat;
|
||||||
|
|
||||||
|
public class VariableHandlesTest {
|
||||||
|
|
||||||
|
public int publicTestVariable = 1;
|
||||||
|
private int privateTestVariable = 1;
|
||||||
|
public int variableToSet = 1;
|
||||||
|
public int variableToCompareAndSet = 1;
|
||||||
|
public int variableToGetAndAdd = 0;
|
||||||
|
public byte variableToBitwiseOr = 0;
|
||||||
|
|
||||||
|
@Test
|
||||||
|
public void whenVariableHandleForPublicVariableIsCreated_ThenItIsInitializedProperly() throws NoSuchFieldException, IllegalAccessException {
|
||||||
|
VarHandle publicIntHandle = MethodHandles
|
||||||
|
.lookup()
|
||||||
|
.in(VariableHandlesTest.class)
|
||||||
|
.findVarHandle(VariableHandlesTest.class, "publicTestVariable", int.class);
|
||||||
|
|
||||||
|
assertThat(publicIntHandle.coordinateTypes().size() == 1);
|
||||||
|
assertThat(publicIntHandle.coordinateTypes().get(0) == VariableHandles.class);
|
||||||
|
|
||||||
|
}
|
||||||
|
|
||||||
|
@Test
|
||||||
|
public void whenVariableHandleForPrivateVariableIsCreated_ThenItIsInitializedProperly() throws NoSuchFieldException, IllegalAccessException {
|
||||||
|
VarHandle privateIntHandle = MethodHandles
|
||||||
|
.privateLookupIn(VariableHandlesTest.class, MethodHandles.lookup())
|
||||||
|
.findVarHandle(VariableHandlesTest.class, "privateTestVariable", int.class);
|
||||||
|
|
||||||
|
assertThat(privateIntHandle.coordinateTypes().size() == 1);
|
||||||
|
assertThat(privateIntHandle.coordinateTypes().get(0) == VariableHandlesTest.class);
|
||||||
|
|
||||||
|
}
|
||||||
|
|
||||||
|
@Test
|
||||||
|
public void whenVariableHandleForArrayVariableIsCreated_ThenItIsInitializedProperly() throws NoSuchFieldException, IllegalAccessException {
|
||||||
|
VarHandle arrayVarHandle = MethodHandles
|
||||||
|
.arrayElementVarHandle(int[].class);
|
||||||
|
|
||||||
|
assertThat(arrayVarHandle.coordinateTypes().size() == 2);
|
||||||
|
assertThat(arrayVarHandle.coordinateTypes().get(0) == int[].class);
|
||||||
|
}
|
||||||
|
|
||||||
|
@Test
|
||||||
|
public void givenVarHandle_whenGetIsInvoked_ThenValueOfVariableIsReturned() throws NoSuchFieldException, IllegalAccessException {
|
||||||
|
VarHandle publicIntHandle = MethodHandles
|
||||||
|
.lookup()
|
||||||
|
.in(VariableHandlesTest.class)
|
||||||
|
.findVarHandle(VariableHandlesTest.class, "publicTestVariable", int.class);
|
||||||
|
|
||||||
|
assertThat((int) publicIntHandle.get(this) == 1);
|
||||||
|
}
|
||||||
|
|
||||||
|
@Test
|
||||||
|
public void givenVarHandle_whenSetIsInvoked_ThenValueOfVariableIsChanged() throws NoSuchFieldException, IllegalAccessException {
|
||||||
|
VarHandle publicIntHandle = MethodHandles
|
||||||
|
.lookup()
|
||||||
|
.in(VariableHandlesTest.class)
|
||||||
|
.findVarHandle(VariableHandlesTest.class, "variableToSet", int.class);
|
||||||
|
publicIntHandle.set(this, 15);
|
||||||
|
|
||||||
|
assertThat((int) publicIntHandle.get(this) == 15);
|
||||||
|
}
|
||||||
|
|
||||||
|
@Test
|
||||||
|
public void givenVarHandle_whenCompareAndSetIsInvoked_ThenValueOfVariableIsChanged() throws NoSuchFieldException, IllegalAccessException {
|
||||||
|
VarHandle publicIntHandle = MethodHandles
|
||||||
|
.lookup()
|
||||||
|
.in(VariableHandlesTest.class)
|
||||||
|
.findVarHandle(VariableHandlesTest.class, "variableToCompareAndSet", int.class);
|
||||||
|
publicIntHandle.compareAndSet(this, 1, 100);
|
||||||
|
|
||||||
|
assertThat((int) publicIntHandle.get(this) == 100);
|
||||||
|
}
|
||||||
|
|
||||||
|
@Test
|
||||||
|
public void givenVarHandle_whenGetAndAddIsInvoked_ThenValueOfVariableIsChanged() throws NoSuchFieldException, IllegalAccessException {
|
||||||
|
VarHandle publicIntHandle = MethodHandles
|
||||||
|
.lookup()
|
||||||
|
.in(VariableHandlesTest.class)
|
||||||
|
.findVarHandle(VariableHandlesTest.class, "variableToGetAndAdd", int.class);
|
||||||
|
int before = (int) publicIntHandle.getAndAdd(this, 200);
|
||||||
|
|
||||||
|
assertThat(before == 0);
|
||||||
|
assertThat((int) publicIntHandle.get(this) == 200);
|
||||||
|
}
|
||||||
|
|
||||||
|
@Test
|
||||||
|
public void givenVarHandle_whenGetAndBitwiseOrIsInvoked_ThenValueOfVariableIsChanged() throws NoSuchFieldException, IllegalAccessException {
|
||||||
|
VarHandle publicIntHandle = MethodHandles
|
||||||
|
.lookup()
|
||||||
|
.in(VariableHandlesTest.class)
|
||||||
|
.findVarHandle(VariableHandlesTest.class, "variableToBitwiseOr", byte.class);
|
||||||
|
byte before = (byte) publicIntHandle.getAndBitwiseOr(this, (byte) 127);
|
||||||
|
|
||||||
|
assertThat(before == 0);
|
||||||
|
assertThat(variableToBitwiseOr == 127);
|
||||||
|
}
|
||||||
|
}
|
@ -31,3 +31,5 @@
|
|||||||
- [Overview of the java.util.concurrent](http://www.baeldung.com/java-util-concurrent)
|
- [Overview of the java.util.concurrent](http://www.baeldung.com/java-util-concurrent)
|
||||||
- [Semaphores in Java](http://www.baeldung.com/java-semaphore)
|
- [Semaphores in Java](http://www.baeldung.com/java-semaphore)
|
||||||
- [Daemon Threads in Java](http://www.baeldung.com/java-daemon-thread)
|
- [Daemon Threads in Java](http://www.baeldung.com/java-daemon-thread)
|
||||||
|
- [Implementing a Runnable vs Extending a Thread](http://www.baeldung.com/java-runnable-vs-extending-thread)
|
||||||
|
- [How to Kill a Java Thread](http://www.baeldung.com/java-thread-stop)
|
||||||
|
@ -0,0 +1,33 @@
|
|||||||
|
package com.baeldung.concurrent.waitandnotify;
|
||||||
|
|
||||||
|
public class Data {
|
||||||
|
private String packet;
|
||||||
|
|
||||||
|
// True if receiver should wait
|
||||||
|
// False if sender should wait
|
||||||
|
private boolean transfer = true;
|
||||||
|
|
||||||
|
public synchronized String receive() {
|
||||||
|
while (transfer) {
|
||||||
|
try {
|
||||||
|
wait();
|
||||||
|
} catch (InterruptedException e) {}
|
||||||
|
}
|
||||||
|
transfer = true;
|
||||||
|
|
||||||
|
notifyAll();
|
||||||
|
return packet;
|
||||||
|
}
|
||||||
|
|
||||||
|
public synchronized void send(String packet) {
|
||||||
|
while (!transfer) {
|
||||||
|
try {
|
||||||
|
wait();
|
||||||
|
} catch (InterruptedException e) {}
|
||||||
|
}
|
||||||
|
transfer = false;
|
||||||
|
|
||||||
|
this.packet = packet;
|
||||||
|
notifyAll();
|
||||||
|
}
|
||||||
|
}
|
@ -0,0 +1,12 @@
|
|||||||
|
package com.baeldung.concurrent.waitandnotify;
|
||||||
|
|
||||||
|
public class NetworkDriver {
|
||||||
|
public static void main(String[] args) {
|
||||||
|
Data data = new Data();
|
||||||
|
Thread sender = new Thread(new Sender(data));
|
||||||
|
Thread receiver = new Thread(new Receiver(data));
|
||||||
|
|
||||||
|
sender.start();
|
||||||
|
receiver.start();
|
||||||
|
}
|
||||||
|
}
|
@ -0,0 +1,25 @@
|
|||||||
|
package com.baeldung.concurrent.waitandnotify;
|
||||||
|
|
||||||
|
import java.util.concurrent.ThreadLocalRandom;
|
||||||
|
|
||||||
|
public class Receiver implements Runnable {
|
||||||
|
private Data load;
|
||||||
|
|
||||||
|
public Receiver(Data load) {
|
||||||
|
this.load = load;
|
||||||
|
}
|
||||||
|
|
||||||
|
public void run() {
|
||||||
|
for(String receivedMessage = load.receive();
|
||||||
|
!"End".equals(receivedMessage) ;
|
||||||
|
receivedMessage = load.receive()) {
|
||||||
|
|
||||||
|
System.out.println(receivedMessage);
|
||||||
|
|
||||||
|
//Thread.sleep() to mimic heavy server-side processing
|
||||||
|
try {
|
||||||
|
Thread.sleep(ThreadLocalRandom.current().nextInt(1000, 5000));
|
||||||
|
} catch (InterruptedException e) {}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
@ -0,0 +1,30 @@
|
|||||||
|
package com.baeldung.concurrent.waitandnotify;
|
||||||
|
|
||||||
|
import java.util.concurrent.ThreadLocalRandom;
|
||||||
|
|
||||||
|
public class Sender implements Runnable {
|
||||||
|
private Data data;
|
||||||
|
|
||||||
|
public Sender(Data data) {
|
||||||
|
this.data = data;
|
||||||
|
}
|
||||||
|
|
||||||
|
public void run() {
|
||||||
|
String packets[] = {
|
||||||
|
"First packet",
|
||||||
|
"Second packet",
|
||||||
|
"Third packet",
|
||||||
|
"Fourth packet",
|
||||||
|
"End"
|
||||||
|
};
|
||||||
|
|
||||||
|
for (String packet : packets) {
|
||||||
|
data.send(packet);
|
||||||
|
|
||||||
|
//Thread.sleep() to mimic heavy server-side processing
|
||||||
|
try {
|
||||||
|
Thread.sleep(ThreadLocalRandom.current().nextInt(1000, 5000));
|
||||||
|
} catch (InterruptedException e) {}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
@ -9,11 +9,10 @@ import java.util.List;
|
|||||||
import java.util.concurrent.*;
|
import java.util.concurrent.*;
|
||||||
|
|
||||||
import static junit.framework.TestCase.assertTrue;
|
import static junit.framework.TestCase.assertTrue;
|
||||||
import static org.junit.Assert.fail;
|
|
||||||
|
|
||||||
public class WaitingForThreadsToFinishTest {
|
public class WaitingForThreadsToFinishManualTest {
|
||||||
|
|
||||||
private static final Logger LOG = LoggerFactory.getLogger(WaitingForThreadsToFinishTest.class);
|
private static final Logger LOG = LoggerFactory.getLogger(WaitingForThreadsToFinishManualTest.class);
|
||||||
private final static ExecutorService WORKER_THREAD_POOL = Executors.newFixedThreadPool(10);
|
private final static ExecutorService WORKER_THREAD_POOL = Executors.newFixedThreadPool(10);
|
||||||
|
|
||||||
public void awaitTerminationAfterShutdown(ExecutorService threadPool) {
|
public void awaitTerminationAfterShutdown(ExecutorService threadPool) {
|
||||||
@ -40,9 +39,7 @@ public class WaitingForThreadsToFinishTest {
|
|||||||
CountDownLatch latch = new CountDownLatch(2);
|
CountDownLatch latch = new CountDownLatch(2);
|
||||||
|
|
||||||
for (int i = 0; i < 2; i++) {
|
for (int i = 0; i < 2; i++) {
|
||||||
WORKER_THREAD_POOL.submit(new Runnable() {
|
WORKER_THREAD_POOL.submit(() -> {
|
||||||
@Override
|
|
||||||
public void run() {
|
|
||||||
try {
|
try {
|
||||||
Thread.sleep(1000);
|
Thread.sleep(1000);
|
||||||
latch.countDown();
|
latch.countDown();
|
||||||
@ -50,7 +47,6 @@ public class WaitingForThreadsToFinishTest {
|
|||||||
e.printStackTrace();
|
e.printStackTrace();
|
||||||
Thread.currentThread().interrupt();
|
Thread.currentThread().interrupt();
|
||||||
}
|
}
|
||||||
}
|
|
||||||
});
|
});
|
||||||
}
|
}
|
||||||
|
|
||||||
@ -83,13 +79,9 @@ public class WaitingForThreadsToFinishTest {
|
|||||||
awaitTerminationAfterShutdown(WORKER_THREAD_POOL);
|
awaitTerminationAfterShutdown(WORKER_THREAD_POOL);
|
||||||
|
|
||||||
try {
|
try {
|
||||||
WORKER_THREAD_POOL.submit(new Callable<String>() {
|
WORKER_THREAD_POOL.submit((Callable<String>) () -> {
|
||||||
@Override
|
|
||||||
public String call() throws Exception {
|
|
||||||
fail("This thread should have been rejected !");
|
|
||||||
Thread.sleep(1000000);
|
Thread.sleep(1000000);
|
||||||
return null;
|
return null;
|
||||||
}
|
|
||||||
});
|
});
|
||||||
} catch (RejectedExecutionException ex) {
|
} catch (RejectedExecutionException ex) {
|
||||||
//
|
//
|
||||||
@ -150,66 +142,4 @@ public class WaitingForThreadsToFinishTest {
|
|||||||
awaitTerminationAfterShutdown(WORKER_THREAD_POOL);
|
awaitTerminationAfterShutdown(WORKER_THREAD_POOL);
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
@Test
|
|
||||||
public void givenMultipleThreads_whenUsingCompletableFutures_thenMainThreadShouldWaitForAllToFinish() {
|
|
||||||
|
|
||||||
CompletableFuture<String> future1 = CompletableFuture.supplyAsync(() -> {
|
|
||||||
|
|
||||||
try {
|
|
||||||
Thread.sleep(1000);
|
|
||||||
} catch (InterruptedException e) {
|
|
||||||
e.printStackTrace();
|
|
||||||
}
|
|
||||||
|
|
||||||
return "Hello";
|
|
||||||
});
|
|
||||||
|
|
||||||
CompletableFuture<String> future2 = CompletableFuture.supplyAsync(() -> {
|
|
||||||
|
|
||||||
try {
|
|
||||||
Thread.sleep(5000);
|
|
||||||
} catch (InterruptedException e) {
|
|
||||||
e.printStackTrace();
|
|
||||||
}
|
|
||||||
|
|
||||||
return "Beautiful";
|
|
||||||
});
|
|
||||||
|
|
||||||
CompletableFuture<String> future3 = CompletableFuture.supplyAsync(() -> {
|
|
||||||
|
|
||||||
try {
|
|
||||||
Thread.sleep(3000);
|
|
||||||
} catch (InterruptedException e) {
|
|
||||||
e.printStackTrace();
|
|
||||||
}
|
|
||||||
|
|
||||||
return "World";
|
|
||||||
});
|
|
||||||
|
|
||||||
long startProcessingTime = System.currentTimeMillis();
|
|
||||||
CompletableFuture<Void> combinedFuture = CompletableFuture.allOf(future1, future2, future3);
|
|
||||||
combinedFuture.join();
|
|
||||||
|
|
||||||
long totalProcessingTime = System.currentTimeMillis() - startProcessingTime;
|
|
||||||
assertTrue(totalProcessingTime >= 5000 && totalProcessingTime < 6000);
|
|
||||||
|
|
||||||
LOG.debug("Responses from all threads are available after " + totalProcessingTime + " milliseconds");
|
|
||||||
|
|
||||||
try {
|
|
||||||
String thread1Response = future1.get();
|
|
||||||
assertTrue(thread1Response.equals("Hello"));
|
|
||||||
|
|
||||||
String thread2Response = future2.get();
|
|
||||||
assertTrue(thread2Response.equals("Beautiful"));
|
|
||||||
|
|
||||||
String thread3Response = future3.get();
|
|
||||||
assertTrue(thread3Response.equals("World"));
|
|
||||||
|
|
||||||
} catch (InterruptedException | ExecutionException e) {
|
|
||||||
e.printStackTrace();
|
|
||||||
}
|
|
||||||
|
|
||||||
awaitTerminationAfterShutdown(WORKER_THREAD_POOL);
|
|
||||||
}
|
|
||||||
}
|
}
|
@ -0,0 +1,65 @@
|
|||||||
|
package com.baeldung.concurrent.waitandnotify;
|
||||||
|
|
||||||
|
import static org.junit.Assert.assertEquals;
|
||||||
|
|
||||||
|
import java.io.ByteArrayOutputStream;
|
||||||
|
import java.io.PrintStream;
|
||||||
|
import java.io.PrintWriter;
|
||||||
|
import java.io.StringWriter;
|
||||||
|
|
||||||
|
import org.junit.After;
|
||||||
|
import org.junit.Before;
|
||||||
|
import org.junit.Test;
|
||||||
|
|
||||||
|
public class NetworkIntegrationTest {
|
||||||
|
|
||||||
|
private final ByteArrayOutputStream outContent = new ByteArrayOutputStream();
|
||||||
|
private final ByteArrayOutputStream errContent = new ByteArrayOutputStream();
|
||||||
|
private String expected;
|
||||||
|
|
||||||
|
@Before
|
||||||
|
public void setUpStreams() {
|
||||||
|
System.setOut(new PrintStream(outContent));
|
||||||
|
System.setErr(new PrintStream(errContent));
|
||||||
|
}
|
||||||
|
|
||||||
|
@Before
|
||||||
|
public void setUpExpectedOutput() {
|
||||||
|
StringWriter expectedStringWriter = new StringWriter();
|
||||||
|
|
||||||
|
PrintWriter printWriter = new PrintWriter(expectedStringWriter);
|
||||||
|
printWriter.println("First packet");
|
||||||
|
printWriter.println("Second packet");
|
||||||
|
printWriter.println("Third packet");
|
||||||
|
printWriter.println("Fourth packet");
|
||||||
|
printWriter.close();
|
||||||
|
|
||||||
|
expected = expectedStringWriter.toString();
|
||||||
|
}
|
||||||
|
|
||||||
|
@After
|
||||||
|
public void cleanUpStreams() {
|
||||||
|
System.setOut(null);
|
||||||
|
System.setErr(null);
|
||||||
|
}
|
||||||
|
|
||||||
|
@Test
|
||||||
|
public void givenSenderAndReceiver_whenSendingPackets_thenNetworkSynchronized() {
|
||||||
|
Data data = new Data();
|
||||||
|
Thread sender = new Thread(new Sender(data));
|
||||||
|
Thread receiver = new Thread(new Receiver(data));
|
||||||
|
|
||||||
|
sender.start();
|
||||||
|
receiver.start();
|
||||||
|
|
||||||
|
//wait for sender and receiver to finish before we test against expected
|
||||||
|
try {
|
||||||
|
sender.join();
|
||||||
|
receiver.join();
|
||||||
|
} catch (InterruptedException e) {
|
||||||
|
e.printStackTrace();
|
||||||
|
}
|
||||||
|
|
||||||
|
assertEquals(expected, outContent.toString());
|
||||||
|
}
|
||||||
|
}
|
@ -483,7 +483,7 @@
|
|||||||
<avaitility.version>1.7.0</avaitility.version>
|
<avaitility.version>1.7.0</avaitility.version>
|
||||||
|
|
||||||
<!-- maven plugins -->
|
<!-- maven plugins -->
|
||||||
<maven-compiler-plugin.version>3.6.0</maven-compiler-plugin.version>
|
<maven-compiler-plugin.version>3.7.0</maven-compiler-plugin.version>
|
||||||
<maven-surefire-plugin.version>2.19.1</maven-surefire-plugin.version>
|
<maven-surefire-plugin.version>2.19.1</maven-surefire-plugin.version>
|
||||||
</properties>
|
</properties>
|
||||||
</project>
|
</project>
|
@ -120,4 +120,15 @@
|
|||||||
- [Guide to Java String Pool](http://www.baeldung.com/java-string-pool)
|
- [Guide to Java String Pool](http://www.baeldung.com/java-string-pool)
|
||||||
- [Copy a File with Java](http://www.baeldung.com/java-copy-file)
|
- [Copy a File with Java](http://www.baeldung.com/java-copy-file)
|
||||||
- [Introduction to Creational Design Patterns](http://www.baeldung.com/creational-design-patterns)
|
- [Introduction to Creational Design Patterns](http://www.baeldung.com/creational-design-patterns)
|
||||||
|
- [Quick Example - Comparator vs Comparable in Java](http://www.baeldung.com/java-comparator-comparable)
|
||||||
|
- [Quick Guide to Java Stack](http://www.baeldung.com/java-stack)
|
||||||
|
- [The Java continue and break Keywords](http://www.baeldung.com/java-continue-and-break)
|
||||||
|
- [Java – Append Data to a File](http://www.baeldung.com/java-append-to-file)
|
||||||
|
- [Introduction to the Java ArrayDeque](http://www.baeldung.com/java-array-deque)
|
||||||
|
- [Guide to java.util.Formatter](http://www.baeldung.com/java-string-formatter)
|
||||||
|
- [Batch Processing in JDBC](http://www.baeldung.com/jdbc-batch-processing)
|
||||||
|
- [Check if a Java Array Contains a Value](http://www.baeldung.com/java-array-contains-value)
|
||||||
|
- [How to Invert an Array in Java](http://www.baeldung.com/java-invert-array)
|
||||||
|
- [Guide to the Cipher Class](http://www.baeldung.com/java-cipher-class)
|
||||||
|
- [A Guide to Java Initialization](http://www.baeldung.com/java-initialization)
|
||||||
|
|
||||||
|
95
core-java/customers.xml
Normal file
95
core-java/customers.xml
Normal file
@ -0,0 +1,95 @@
|
|||||||
|
<?xml version="1.0"?>
|
||||||
|
<webRowSet xmlns="http://java.sun.com/xml/ns/jdbc" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
|
||||||
|
xsi:schemaLocation="http://java.sun.com/xml/ns/jdbc http://java.sun.com/xml/ns/jdbc/webrowset.xsd">
|
||||||
|
<properties>
|
||||||
|
<command>SELECT * FROM customers</command>
|
||||||
|
<concurrency>1008</concurrency>
|
||||||
|
<datasource><null/></datasource>
|
||||||
|
<escape-processing>true</escape-processing>
|
||||||
|
<fetch-direction>1000</fetch-direction>
|
||||||
|
<fetch-size>0</fetch-size>
|
||||||
|
<isolation-level>2</isolation-level>
|
||||||
|
<key-columns>
|
||||||
|
</key-columns>
|
||||||
|
<map>
|
||||||
|
</map>
|
||||||
|
<max-field-size>0</max-field-size>
|
||||||
|
<max-rows>0</max-rows>
|
||||||
|
<query-timeout>0</query-timeout>
|
||||||
|
<read-only>true</read-only>
|
||||||
|
<rowset-type>ResultSet.TYPE_SCROLL_INSENSITIVE</rowset-type>
|
||||||
|
<show-deleted>false</show-deleted>
|
||||||
|
<table-name>customers</table-name>
|
||||||
|
<url>jdbc:h2:mem:testdb</url>
|
||||||
|
<sync-provider>
|
||||||
|
<sync-provider-name>com.sun.rowset.providers.RIOptimisticProvider</sync-provider-name>
|
||||||
|
<sync-provider-vendor>Oracle Corporation</sync-provider-vendor>
|
||||||
|
<sync-provider-version>1.0</sync-provider-version>
|
||||||
|
<sync-provider-grade>2</sync-provider-grade>
|
||||||
|
<data-source-lock>1</data-source-lock>
|
||||||
|
</sync-provider>
|
||||||
|
</properties>
|
||||||
|
<metadata>
|
||||||
|
<column-count>2</column-count>
|
||||||
|
<column-definition>
|
||||||
|
<column-index>1</column-index>
|
||||||
|
<auto-increment>false</auto-increment>
|
||||||
|
<case-sensitive>true</case-sensitive>
|
||||||
|
<currency>false</currency>
|
||||||
|
<nullable>0</nullable>
|
||||||
|
<signed>true</signed>
|
||||||
|
<searchable>true</searchable>
|
||||||
|
<column-display-size>11</column-display-size>
|
||||||
|
<column-label>ID</column-label>
|
||||||
|
<column-name>ID</column-name>
|
||||||
|
<schema-name>PUBLIC</schema-name>
|
||||||
|
<column-precision>10</column-precision>
|
||||||
|
<column-scale>0</column-scale>
|
||||||
|
<table-name>CUSTOMERS</table-name>
|
||||||
|
<catalog-name>TESTDB</catalog-name>
|
||||||
|
<column-type>4</column-type>
|
||||||
|
<column-type-name>INTEGER</column-type-name>
|
||||||
|
</column-definition>
|
||||||
|
<column-definition>
|
||||||
|
<column-index>2</column-index>
|
||||||
|
<auto-increment>false</auto-increment>
|
||||||
|
<case-sensitive>true</case-sensitive>
|
||||||
|
<currency>false</currency>
|
||||||
|
<nullable>0</nullable>
|
||||||
|
<signed>true</signed>
|
||||||
|
<searchable>true</searchable>
|
||||||
|
<column-display-size>50</column-display-size>
|
||||||
|
<column-label>NAME</column-label>
|
||||||
|
<column-name>NAME</column-name>
|
||||||
|
<schema-name>PUBLIC</schema-name>
|
||||||
|
<column-precision>50</column-precision>
|
||||||
|
<column-scale>0</column-scale>
|
||||||
|
<table-name>CUSTOMERS</table-name>
|
||||||
|
<catalog-name>TESTDB</catalog-name>
|
||||||
|
<column-type>12</column-type>
|
||||||
|
<column-type-name>VARCHAR</column-type-name>
|
||||||
|
</column-definition>
|
||||||
|
</metadata>
|
||||||
|
<data>
|
||||||
|
<currentRow>
|
||||||
|
<columnValue>1</columnValue>
|
||||||
|
<columnValue>Customer1</columnValue>
|
||||||
|
</currentRow>
|
||||||
|
<currentRow>
|
||||||
|
<columnValue>2</columnValue>
|
||||||
|
<columnValue>Customer2</columnValue>
|
||||||
|
</currentRow>
|
||||||
|
<currentRow>
|
||||||
|
<columnValue>3</columnValue>
|
||||||
|
<columnValue>Customer3</columnValue>
|
||||||
|
</currentRow>
|
||||||
|
<currentRow>
|
||||||
|
<columnValue>4</columnValue>
|
||||||
|
<columnValue>Customer4</columnValue>
|
||||||
|
</currentRow>
|
||||||
|
<currentRow>
|
||||||
|
<columnValue>5</columnValue>
|
||||||
|
<columnValue>Customer5</columnValue>
|
||||||
|
</currentRow>
|
||||||
|
</data>
|
||||||
|
</webRowSet>
|
@ -181,6 +181,11 @@
|
|||||||
<version>2.1.0.1</version>
|
<version>2.1.0.1</version>
|
||||||
</dependency>
|
</dependency>
|
||||||
|
|
||||||
|
<dependency>
|
||||||
|
<groupId>com.sun.messaging.mq</groupId>
|
||||||
|
<artifactId>fscontext</artifactId>
|
||||||
|
<version>${fscontext.version}</version>
|
||||||
|
</dependency>
|
||||||
<dependency>
|
<dependency>
|
||||||
<groupId>com.codepoetics</groupId>
|
<groupId>com.codepoetics</groupId>
|
||||||
<artifactId>protonpack</artifactId>
|
<artifactId>protonpack</artifactId>
|
||||||
@ -211,6 +216,17 @@
|
|||||||
<artifactId>spring-web</artifactId>
|
<artifactId>spring-web</artifactId>
|
||||||
<version>4.3.4.RELEASE</version>
|
<version>4.3.4.RELEASE</version>
|
||||||
</dependency>
|
</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>
|
||||||
|
<version>2.4.0</version>
|
||||||
|
<scope>runtime</scope>
|
||||||
|
</dependency>
|
||||||
</dependencies>
|
</dependencies>
|
||||||
|
|
||||||
<build>
|
<build>
|
||||||
@ -244,7 +260,7 @@
|
|||||||
<exclude>**/*LongRunningUnitTest.java</exclude>
|
<exclude>**/*LongRunningUnitTest.java</exclude>
|
||||||
<exclude>**/*ManualTest.java</exclude>
|
<exclude>**/*ManualTest.java</exclude>
|
||||||
</excludes>
|
</excludes>
|
||||||
|
<testFailureIgnore>true</testFailureIgnore>
|
||||||
</configuration>
|
</configuration>
|
||||||
</plugin>
|
</plugin>
|
||||||
|
|
||||||
@ -448,7 +464,7 @@
|
|||||||
<logback.version>1.1.7</logback.version>
|
<logback.version>1.1.7</logback.version>
|
||||||
|
|
||||||
<!-- util -->
|
<!-- util -->
|
||||||
<guava.version>23.0</guava.version>
|
<guava.version>22.0</guava.version>
|
||||||
<commons-lang3.version>3.5</commons-lang3.version>
|
<commons-lang3.version>3.5</commons-lang3.version>
|
||||||
<bouncycastle.version>1.55</bouncycastle.version>
|
<bouncycastle.version>1.55</bouncycastle.version>
|
||||||
<commons-codec.version>1.10</commons-codec.version>
|
<commons-codec.version>1.10</commons-codec.version>
|
||||||
@ -473,7 +489,7 @@
|
|||||||
<avaitility.version>1.7.0</avaitility.version>
|
<avaitility.version>1.7.0</avaitility.version>
|
||||||
|
|
||||||
<!-- maven plugins -->
|
<!-- maven plugins -->
|
||||||
<maven-compiler-plugin.version>3.6.0</maven-compiler-plugin.version>
|
<maven-compiler-plugin.version>3.7.0</maven-compiler-plugin.version>
|
||||||
<maven-surefire-plugin.version>2.19.1</maven-surefire-plugin.version>
|
<maven-surefire-plugin.version>2.19.1</maven-surefire-plugin.version>
|
||||||
</properties>
|
</properties>
|
||||||
</project>
|
</project>
|
@ -0,0 +1,21 @@
|
|||||||
|
package com.baeldung.array;
|
||||||
|
|
||||||
|
import org.openjdk.jmh.runner.Runner;
|
||||||
|
import org.openjdk.jmh.runner.options.Options;
|
||||||
|
import org.openjdk.jmh.runner.options.OptionsBuilder;
|
||||||
|
|
||||||
|
public class ArrayBenchmarkRunner {
|
||||||
|
|
||||||
|
public static void main(String[] args) throws Exception {
|
||||||
|
|
||||||
|
Options options = new OptionsBuilder()
|
||||||
|
.include(SearchArrayTest.class.getSimpleName()).threads(1)
|
||||||
|
.forks(1).shouldFailOnError(true).shouldDoGC(true)
|
||||||
|
.jvmArgs("-server").build();
|
||||||
|
|
||||||
|
new Runner(options).run();
|
||||||
|
|
||||||
|
|
||||||
|
}
|
||||||
|
|
||||||
|
}
|
@ -0,0 +1,43 @@
|
|||||||
|
package com.baeldung.array;
|
||||||
|
|
||||||
|
import java.util.Arrays;
|
||||||
|
import java.util.Collections;
|
||||||
|
import java.util.List;
|
||||||
|
import java.util.stream.IntStream;
|
||||||
|
|
||||||
|
import org.apache.commons.lang3.ArrayUtils;
|
||||||
|
|
||||||
|
import com.google.common.collect.Lists;
|
||||||
|
|
||||||
|
public class ArrayInverter {
|
||||||
|
|
||||||
|
public void invertUsingFor(Object[] array) {
|
||||||
|
for (int i = 0; i < array.length / 2; i++) {
|
||||||
|
Object temp = array[i];
|
||||||
|
array[i] = array[array.length - 1 - i];
|
||||||
|
array[array.length - 1 - i] = temp;
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
public void invertUsingCollectionsReverse(Object[] array) {
|
||||||
|
List<Object> list = Arrays.asList(array);
|
||||||
|
Collections.reverse(list);
|
||||||
|
}
|
||||||
|
|
||||||
|
public Object[] invertUsingStreams(final Object[] array) {
|
||||||
|
return IntStream.rangeClosed(1, array.length)
|
||||||
|
.mapToObj(i -> array[array.length - i])
|
||||||
|
.toArray();
|
||||||
|
}
|
||||||
|
|
||||||
|
public void invertUsingCommonsLang(Object[] array) {
|
||||||
|
ArrayUtils.reverse(array);
|
||||||
|
}
|
||||||
|
|
||||||
|
public Object[] invertUsingGuava(Object[] array) {
|
||||||
|
List<Object> list = Arrays.asList(array);
|
||||||
|
List<Object> reverted = Lists.reverse(list);
|
||||||
|
return reverted.toArray();
|
||||||
|
}
|
||||||
|
|
||||||
|
}
|
@ -0,0 +1,96 @@
|
|||||||
|
package com.baeldung.array;
|
||||||
|
|
||||||
|
import org.openjdk.jmh.annotations.*;
|
||||||
|
|
||||||
|
import java.util.*;
|
||||||
|
import java.util.concurrent.TimeUnit;
|
||||||
|
|
||||||
|
@BenchmarkMode(Mode.AverageTime)
|
||||||
|
@Warmup(iterations = 5)
|
||||||
|
@OutputTimeUnit(TimeUnit.MICROSECONDS)
|
||||||
|
public class SearchArrayTest {
|
||||||
|
|
||||||
|
@State(Scope.Benchmark)
|
||||||
|
public static class SearchData {
|
||||||
|
static int count = 1000;
|
||||||
|
static String[] strings = seedArray(1000);
|
||||||
|
}
|
||||||
|
|
||||||
|
|
||||||
|
@Benchmark
|
||||||
|
public void searchArrayLoop() {
|
||||||
|
for (int i = 0; i < SearchData.count; i++) {
|
||||||
|
searchLoop(SearchData.strings, "T");
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
@Benchmark
|
||||||
|
public void searchArrayAllocNewList() {
|
||||||
|
for (int i = 0; i < SearchData.count; i++) {
|
||||||
|
searchList(SearchData.strings, "T");
|
||||||
|
}
|
||||||
|
|
||||||
|
}
|
||||||
|
|
||||||
|
@Benchmark
|
||||||
|
public void searchArrayAllocNewSet() {
|
||||||
|
for (int i = 0; i < SearchData.count; i++) {
|
||||||
|
searchSet(SearchData.strings, "T");
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
|
||||||
|
@Benchmark
|
||||||
|
public void searchArrayReuseList() {
|
||||||
|
List<String> asList = Arrays.asList(SearchData.strings);
|
||||||
|
for (int i = 0; i < SearchData.count; i++) {
|
||||||
|
asList.contains("T");
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
|
||||||
|
@Benchmark
|
||||||
|
public void searchArrayReuseSet() {
|
||||||
|
Set<String> asSet = new HashSet<>(Arrays.asList(SearchData.strings));
|
||||||
|
for (int i = 0; i < SearchData.count; i++) {
|
||||||
|
asSet.contains("T");
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
|
||||||
|
@Benchmark
|
||||||
|
public void searchArrayBinarySearch() {
|
||||||
|
Arrays.sort(SearchData.strings);
|
||||||
|
for (int i = 0; i < SearchData.count; i++) {
|
||||||
|
Arrays.binarySearch(SearchData.strings, "T");
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
private boolean searchList(String[] strings, String searchString) {
|
||||||
|
return Arrays.asList(strings).contains(searchString);
|
||||||
|
}
|
||||||
|
|
||||||
|
private boolean searchSet(String[] strings, String searchString) {
|
||||||
|
Set<String> set = new HashSet<>(Arrays.asList(strings));
|
||||||
|
return set.contains(searchString);
|
||||||
|
}
|
||||||
|
|
||||||
|
private boolean searchLoop(String[] strings, String searchString) {
|
||||||
|
for (String s : strings) {
|
||||||
|
if (s.equals(searchString))
|
||||||
|
return true;
|
||||||
|
}
|
||||||
|
return false;
|
||||||
|
}
|
||||||
|
|
||||||
|
private static String[] seedArray(int length) {
|
||||||
|
String[] strings = new String[length];
|
||||||
|
Random random = new Random();
|
||||||
|
for (int i = 0; i < length; i++)
|
||||||
|
{
|
||||||
|
strings[i] = String.valueOf(random.nextInt());
|
||||||
|
}
|
||||||
|
return strings;
|
||||||
|
}
|
||||||
|
|
||||||
|
}
|
35
core-java/src/main/java/com/baeldung/cipher/Encryptor.java
Normal file
35
core-java/src/main/java/com/baeldung/cipher/Encryptor.java
Normal file
@ -0,0 +1,35 @@
|
|||||||
|
package com.baeldung.cipher;
|
||||||
|
|
||||||
|
import javax.crypto.*;
|
||||||
|
import javax.crypto.spec.SecretKeySpec;
|
||||||
|
import java.security.InvalidKeyException;
|
||||||
|
import java.security.NoSuchAlgorithmException;
|
||||||
|
import java.security.cert.Certificate;
|
||||||
|
|
||||||
|
public class Encryptor {
|
||||||
|
|
||||||
|
public byte[] encryptMessage(byte[] message, byte[] keyBytes) throws InvalidKeyException, NoSuchPaddingException, NoSuchAlgorithmException, BadPaddingException, IllegalBlockSizeException {
|
||||||
|
Cipher cipher = Cipher.getInstance("AES/ECB/PKCS5Padding");
|
||||||
|
SecretKey secretKey = new SecretKeySpec(keyBytes, "AES");
|
||||||
|
cipher.init(Cipher.ENCRYPT_MODE, secretKey);
|
||||||
|
byte[] encryptedMessage = cipher.doFinal(message);
|
||||||
|
return encryptedMessage;
|
||||||
|
}
|
||||||
|
|
||||||
|
public byte[] encryptMessage(byte[] message, Certificate publicKeyCertificate) throws InvalidKeyException, NoSuchPaddingException, NoSuchAlgorithmException, BadPaddingException, IllegalBlockSizeException {
|
||||||
|
Cipher cipher = Cipher.getInstance("RSA/ECB/PKCS1Padding");
|
||||||
|
cipher.init(Cipher.ENCRYPT_MODE, publicKeyCertificate);
|
||||||
|
byte[] encryptedMessage = cipher.doFinal(message);
|
||||||
|
return encryptedMessage;
|
||||||
|
}
|
||||||
|
|
||||||
|
public byte[] decryptMessage(byte[] encryptedMessage, byte[] keyBytes) throws NoSuchPaddingException, NoSuchAlgorithmException, InvalidKeyException, BadPaddingException, IllegalBlockSizeException {
|
||||||
|
Cipher cipher = Cipher.getInstance("AES/ECB/PKCS5Padding");
|
||||||
|
SecretKey secretKey = new SecretKeySpec(keyBytes, "AES");
|
||||||
|
cipher.init(Cipher.DECRYPT_MODE, secretKey);
|
||||||
|
byte[] clearMessage = cipher.doFinal(encryptedMessage);
|
||||||
|
return clearMessage;
|
||||||
|
}
|
||||||
|
|
||||||
|
|
||||||
|
}
|
@ -0,0 +1,53 @@
|
|||||||
|
package com.baeldung.initializationguide;
|
||||||
|
|
||||||
|
import java.io.Serializable;
|
||||||
|
|
||||||
|
public class User implements Serializable, Cloneable {
|
||||||
|
private static final long serialVersionUID = 1L;
|
||||||
|
static String forum;
|
||||||
|
private String name;
|
||||||
|
private int id;
|
||||||
|
|
||||||
|
{
|
||||||
|
id = 0;
|
||||||
|
System.out.println("Instance Initializer");
|
||||||
|
}
|
||||||
|
|
||||||
|
static {
|
||||||
|
forum = "Java";
|
||||||
|
System.out.println("Static Initializer");
|
||||||
|
}
|
||||||
|
|
||||||
|
public User(String name, int id) {
|
||||||
|
super();
|
||||||
|
this.name = name;
|
||||||
|
this.id = id;
|
||||||
|
}
|
||||||
|
|
||||||
|
public User() {
|
||||||
|
System.out.println("Constructor");
|
||||||
|
}
|
||||||
|
|
||||||
|
public String getName() {
|
||||||
|
return name;
|
||||||
|
}
|
||||||
|
|
||||||
|
public void setName(String name) {
|
||||||
|
this.name = name;
|
||||||
|
}
|
||||||
|
|
||||||
|
public int getId() {
|
||||||
|
return id;
|
||||||
|
}
|
||||||
|
|
||||||
|
public void setId(int id) {
|
||||||
|
this.id = id;
|
||||||
|
}
|
||||||
|
|
||||||
|
@Override
|
||||||
|
protected Object clone() throws CloneNotSupportedException {
|
||||||
|
return this;
|
||||||
|
}
|
||||||
|
|
||||||
|
}
|
||||||
|
|
@ -0,0 +1,21 @@
|
|||||||
|
package com.baeldung.interfaces;
|
||||||
|
|
||||||
|
import java.util.ArrayList;
|
||||||
|
import java.util.List;
|
||||||
|
import java.util.stream.Collectors;
|
||||||
|
|
||||||
|
public class CommaSeparatedCustomers implements Customer.List {
|
||||||
|
|
||||||
|
private List<Customer> customers = new ArrayList<Customer>();
|
||||||
|
|
||||||
|
@Override
|
||||||
|
public void Add(Customer customer) {
|
||||||
|
customers.add(customer);
|
||||||
|
}
|
||||||
|
|
||||||
|
@Override
|
||||||
|
public String getCustomerNames() {
|
||||||
|
return customers.stream().map(customer -> customer.getName()).collect(Collectors.joining(","));
|
||||||
|
}
|
||||||
|
|
||||||
|
}
|
@ -0,0 +1,19 @@
|
|||||||
|
package com.baeldung.interfaces;
|
||||||
|
|
||||||
|
public class Customer {
|
||||||
|
public interface List {
|
||||||
|
void Add(Customer customer);
|
||||||
|
|
||||||
|
String getCustomerNames();
|
||||||
|
}
|
||||||
|
|
||||||
|
private String name;
|
||||||
|
|
||||||
|
public Customer(String name) {
|
||||||
|
this.name = name;
|
||||||
|
}
|
||||||
|
|
||||||
|
String getName() {
|
||||||
|
return name;
|
||||||
|
}
|
||||||
|
}
|
@ -0,0 +1,96 @@
|
|||||||
|
package com.baeldung.jdbc;
|
||||||
|
|
||||||
|
import java.sql.*;
|
||||||
|
import java.util.UUID;
|
||||||
|
|
||||||
|
public class BatchProcessing {
|
||||||
|
|
||||||
|
private final String[] EMPLOYEES = new String[]{"Zuck","Mike","Larry","Musk","Steve"};
|
||||||
|
private final String[] DESIGNATIONS = new String[]{"CFO","CSO","CTO","CEO","CMO"};
|
||||||
|
private final String[] ADDRESSES = new String[]{"China","York","Diego","Carolina","India"};
|
||||||
|
|
||||||
|
private Connection connection;
|
||||||
|
|
||||||
|
public void getConnection(){
|
||||||
|
try {
|
||||||
|
Class.forName("org.hsqldb.jdbcDriver");
|
||||||
|
connection = DriverManager.getConnection("jdbc:hsqldb:file:C:\\EMPLOYEEDB", "SA", "");
|
||||||
|
connection.setAutoCommit(false);
|
||||||
|
} catch (Exception e) {
|
||||||
|
e.printStackTrace(System.out);
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
public void createTables(){
|
||||||
|
try {
|
||||||
|
connection.createStatement().executeUpdate("create table EMPLOYEE (ID VARCHAR(36), NAME VARCHAR(45), DESIGNATION VARCHAR(15))");
|
||||||
|
connection.createStatement().executeUpdate("create table EMP_ADDRESS (ID VARCHAR(36), EMP_ID VARCHAR(36), ADDRESS VARCHAR(45))");
|
||||||
|
System.out.println("Tables Created!!!");
|
||||||
|
} catch (SQLException e) {
|
||||||
|
e.printStackTrace(System.out);
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
public void useStatement(){
|
||||||
|
try {
|
||||||
|
String insertEmployeeSQL = "INSERT INTO EMPLOYEE(ID, NAME, DESIGNATION) VALUES ('%s','%s','%s');";
|
||||||
|
String insertEmployeeAddrSQL = "INSERT INTO EMP_ADDRESS(ID, EMP_ID, ADDRESS) VALUES ('%s','%s','%s');";
|
||||||
|
Statement statement = connection.createStatement();
|
||||||
|
for(int i = 0; i < EMPLOYEES.length; i++){
|
||||||
|
String employeeId = UUID.randomUUID().toString();
|
||||||
|
statement.addBatch(String.format(insertEmployeeSQL, employeeId, EMPLOYEES[i],DESIGNATIONS[i]));
|
||||||
|
statement.addBatch(String.format(insertEmployeeAddrSQL, UUID.randomUUID().toString(),employeeId,ADDRESSES[i]));
|
||||||
|
}
|
||||||
|
statement.executeBatch();
|
||||||
|
connection.commit();
|
||||||
|
} catch (Exception e) {
|
||||||
|
try {
|
||||||
|
connection.rollback();
|
||||||
|
} catch (SQLException ex) {
|
||||||
|
System.out.println("Error during rollback");
|
||||||
|
System.out.println(ex.getMessage());
|
||||||
|
}
|
||||||
|
e.printStackTrace(System.out);
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
public void usePreparedStatement(){
|
||||||
|
try {
|
||||||
|
String insertEmployeeSQL = "INSERT INTO EMPLOYEE(ID, NAME, DESIGNATION) VALUES (?,?,?);";
|
||||||
|
String insertEmployeeAddrSQL = "INSERT INTO EMP_ADDRESS(ID, EMP_ID, ADDRESS) VALUES (?,?,?);";
|
||||||
|
PreparedStatement employeeStmt = connection.prepareStatement(insertEmployeeSQL);
|
||||||
|
PreparedStatement empAddressStmt = connection.prepareStatement(insertEmployeeAddrSQL);
|
||||||
|
for(int i = 0; i < EMPLOYEES.length; i++){
|
||||||
|
String employeeId = UUID.randomUUID().toString();
|
||||||
|
employeeStmt.setString(1,employeeId);
|
||||||
|
employeeStmt.setString(2,EMPLOYEES[i]);
|
||||||
|
employeeStmt.setString(3,DESIGNATIONS[i]);
|
||||||
|
employeeStmt.addBatch();
|
||||||
|
|
||||||
|
empAddressStmt.setString(1,UUID.randomUUID().toString());
|
||||||
|
empAddressStmt.setString(2,employeeId);
|
||||||
|
empAddressStmt.setString(3,ADDRESSES[i]);
|
||||||
|
empAddressStmt.addBatch();
|
||||||
|
}
|
||||||
|
employeeStmt.executeBatch();
|
||||||
|
empAddressStmt.executeBatch();
|
||||||
|
connection.commit();
|
||||||
|
} catch (Exception e) {
|
||||||
|
try {
|
||||||
|
connection.rollback();
|
||||||
|
} catch (SQLException ex) {
|
||||||
|
System.out.println("Error during rollback");
|
||||||
|
System.out.println(ex.getMessage());
|
||||||
|
}
|
||||||
|
e.printStackTrace(System.out);
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
public static void main(String[] args) {
|
||||||
|
BatchProcessing batchProcessing = new BatchProcessing();
|
||||||
|
batchProcessing.getConnection();
|
||||||
|
batchProcessing.createTables();
|
||||||
|
batchProcessing.useStatement();
|
||||||
|
batchProcessing.usePreparedStatement();
|
||||||
|
}
|
||||||
|
}
|
@ -0,0 +1,51 @@
|
|||||||
|
package com.baeldung.jdbcrowset;
|
||||||
|
|
||||||
|
import java.sql.Connection;
|
||||||
|
import java.sql.DriverManager;
|
||||||
|
import java.sql.SQLException;
|
||||||
|
import java.sql.Statement;
|
||||||
|
|
||||||
|
import javax.sql.rowset.JdbcRowSet;
|
||||||
|
import javax.sql.rowset.RowSetFactory;
|
||||||
|
import javax.sql.rowset.RowSetProvider;
|
||||||
|
|
||||||
|
import org.springframework.boot.autoconfigure.EnableAutoConfiguration;
|
||||||
|
import org.springframework.context.annotation.Configuration;
|
||||||
|
|
||||||
|
@Configuration
|
||||||
|
@EnableAutoConfiguration
|
||||||
|
public class DatabaseConfiguration {
|
||||||
|
|
||||||
|
|
||||||
|
public static Connection geth2Connection() throws Exception {
|
||||||
|
Class.forName("org.h2.Driver");
|
||||||
|
System.out.println("Driver Loaded.");
|
||||||
|
String url = "jdbc:h2:mem:testdb";
|
||||||
|
return DriverManager.getConnection(url, "sa", "");
|
||||||
|
}
|
||||||
|
|
||||||
|
public static void initDatabase(Statement stmt) throws SQLException{
|
||||||
|
int iter = 1;
|
||||||
|
while(iter<=5){
|
||||||
|
String customer = "Customer"+iter;
|
||||||
|
String sql ="INSERT INTO customers(id, name) VALUES ("+iter+ ",'"+customer+"');";
|
||||||
|
System.out.println("here is sql statmeent for execution: " + sql);
|
||||||
|
stmt.executeUpdate(sql);
|
||||||
|
iter++;
|
||||||
|
}
|
||||||
|
|
||||||
|
int iterb = 1;
|
||||||
|
while(iterb<=5){
|
||||||
|
String associate = "Associate"+iter;
|
||||||
|
String sql = "INSERT INTO associates(id, name) VALUES("+iterb+",'"+associate+"');";
|
||||||
|
System.out.println("here is sql statement for associate:"+ sql);
|
||||||
|
stmt.executeUpdate(sql);
|
||||||
|
iterb++;
|
||||||
|
}
|
||||||
|
|
||||||
|
|
||||||
|
}
|
||||||
|
|
||||||
|
|
||||||
|
|
||||||
|
}
|
@ -0,0 +1,24 @@
|
|||||||
|
package com.baeldung.jdbcrowset;
|
||||||
|
|
||||||
|
import javax.sql.RowSetEvent;
|
||||||
|
import javax.sql.RowSetListener;
|
||||||
|
|
||||||
|
public class ExampleListener implements RowSetListener {
|
||||||
|
|
||||||
|
|
||||||
|
public void cursorMoved(RowSetEvent event) {
|
||||||
|
System.out.println("ExampleListener alerted of cursorMoved event");
|
||||||
|
System.out.println(event.toString());
|
||||||
|
}
|
||||||
|
|
||||||
|
public void rowChanged(RowSetEvent event) {
|
||||||
|
System.out.println("ExampleListener alerted of rowChanged event");
|
||||||
|
System.out.println(event.toString());
|
||||||
|
}
|
||||||
|
|
||||||
|
public void rowSetChanged(RowSetEvent event) {
|
||||||
|
System.out.println("ExampleListener alerted of rowSetChanged event");
|
||||||
|
System.out.println(event.toString());
|
||||||
|
}
|
||||||
|
|
||||||
|
}
|
@ -0,0 +1,46 @@
|
|||||||
|
package com.baeldung.jdbcrowset;
|
||||||
|
|
||||||
|
import java.sql.SQLException;
|
||||||
|
import java.util.regex.Matcher;
|
||||||
|
import java.util.regex.Pattern;
|
||||||
|
|
||||||
|
import javax.sql.RowSet;
|
||||||
|
import javax.sql.rowset.Predicate;
|
||||||
|
|
||||||
|
public class FilterExample implements Predicate {
|
||||||
|
|
||||||
|
private Pattern pattern;
|
||||||
|
|
||||||
|
public FilterExample(String regexQuery) {
|
||||||
|
if (regexQuery != null && !regexQuery.isEmpty()) {
|
||||||
|
pattern = Pattern.compile(regexQuery);
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
public boolean evaluate(RowSet rs) {
|
||||||
|
try {
|
||||||
|
if (!rs.isAfterLast()) {
|
||||||
|
String name = rs.getString("name");
|
||||||
|
System.out.println(String.format(
|
||||||
|
"Searching for pattern '%s' in %s", pattern.toString(),
|
||||||
|
name));
|
||||||
|
Matcher matcher = pattern.matcher(name);
|
||||||
|
return matcher.matches();
|
||||||
|
} else
|
||||||
|
return false;
|
||||||
|
} catch (Exception e) {
|
||||||
|
e.printStackTrace();
|
||||||
|
return false;
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
public boolean evaluate(Object value, int column) throws SQLException {
|
||||||
|
throw new UnsupportedOperationException("This operation is unsupported.");
|
||||||
|
}
|
||||||
|
|
||||||
|
public boolean evaluate(Object value, String columnName)
|
||||||
|
throws SQLException {
|
||||||
|
throw new UnsupportedOperationException("This operation is unsupported.");
|
||||||
|
}
|
||||||
|
|
||||||
|
}
|
@ -0,0 +1,139 @@
|
|||||||
|
package com.baeldung.jdbcrowset;
|
||||||
|
|
||||||
|
import java.io.FileOutputStream;
|
||||||
|
import java.sql.Connection;
|
||||||
|
import java.sql.ResultSet;
|
||||||
|
import java.sql.ResultSetMetaData;
|
||||||
|
import java.sql.SQLException;
|
||||||
|
import java.sql.Statement;
|
||||||
|
|
||||||
|
import com.sun.rowset.*;
|
||||||
|
|
||||||
|
import javax.sql.rowset.CachedRowSet;
|
||||||
|
import javax.sql.rowset.FilteredRowSet;
|
||||||
|
import javax.sql.rowset.JdbcRowSet;
|
||||||
|
import javax.sql.rowset.JoinRowSet;
|
||||||
|
import javax.sql.rowset.RowSetFactory;
|
||||||
|
import javax.sql.rowset.RowSetProvider;
|
||||||
|
import javax.sql.rowset.WebRowSet;
|
||||||
|
|
||||||
|
import org.springframework.boot.SpringApplication;
|
||||||
|
import org.springframework.boot.autoconfigure.SpringBootApplication;
|
||||||
|
|
||||||
|
@SpringBootApplication
|
||||||
|
public class JdbcRowsetApplication {
|
||||||
|
|
||||||
|
public static void main(String[] args) throws Exception {
|
||||||
|
SpringApplication.run(JdbcRowsetApplication.class, args);
|
||||||
|
Statement stmt = null;
|
||||||
|
try {
|
||||||
|
Connection conn = DatabaseConfiguration.geth2Connection();
|
||||||
|
|
||||||
|
String drop = "DROP TABLE IF EXISTS customers, associates;";
|
||||||
|
String schema = "CREATE TABLE customers (id INT NOT NULL, name VARCHAR(50) NOT NULL, PRIMARY KEY (id)); ";
|
||||||
|
String schemapartb = "CREATE TABLE associates (id INT NOT NULL, name VARCHAR(50) NOT NULL, PRIMARY KEY (id));";
|
||||||
|
|
||||||
|
stmt = conn.createStatement();
|
||||||
|
stmt.executeUpdate(drop);
|
||||||
|
stmt.executeUpdate(schema);
|
||||||
|
stmt.executeUpdate(schemapartb);
|
||||||
|
// insert data
|
||||||
|
DatabaseConfiguration.initDatabase(stmt);
|
||||||
|
// JdbcRowSet Example
|
||||||
|
String sql = "SELECT * FROM customers";
|
||||||
|
JdbcRowSet jdbcRS;
|
||||||
|
jdbcRS = new JdbcRowSetImpl(conn);
|
||||||
|
jdbcRS.setType(ResultSet.TYPE_SCROLL_INSENSITIVE);
|
||||||
|
jdbcRS.setCommand(sql);
|
||||||
|
jdbcRS.execute();
|
||||||
|
jdbcRS.addRowSetListener(new ExampleListener());
|
||||||
|
|
||||||
|
while (jdbcRS.next()) {
|
||||||
|
// each call to next, generates a cursorMoved event
|
||||||
|
System.out.println("id=" + jdbcRS.getString(1));
|
||||||
|
System.out.println("name=" + jdbcRS.getString(2));
|
||||||
|
}
|
||||||
|
|
||||||
|
// CachedRowSet Example
|
||||||
|
String username = "sa";
|
||||||
|
String password = "";
|
||||||
|
String url = "jdbc:h2:mem:testdb";
|
||||||
|
CachedRowSet crs = new CachedRowSetImpl();
|
||||||
|
crs.setUsername(username);
|
||||||
|
crs.setPassword(password);
|
||||||
|
crs.setUrl(url);
|
||||||
|
crs.setCommand(sql);
|
||||||
|
crs.execute();
|
||||||
|
crs.addRowSetListener(new ExampleListener());
|
||||||
|
while (crs.next()) {
|
||||||
|
if (crs.getInt("id") == 1) {
|
||||||
|
System.out.println("CRS found customer1 and will remove the record.");
|
||||||
|
crs.deleteRow();
|
||||||
|
break;
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
// WebRowSet example
|
||||||
|
WebRowSet wrs = new WebRowSetImpl();
|
||||||
|
wrs.setUsername(username);
|
||||||
|
wrs.setPassword(password);
|
||||||
|
wrs.setUrl(url);
|
||||||
|
wrs.setCommand(sql);
|
||||||
|
wrs.execute();
|
||||||
|
FileOutputStream ostream = new FileOutputStream("customers.xml");
|
||||||
|
wrs.writeXml(ostream);
|
||||||
|
|
||||||
|
// JoinRowSet example
|
||||||
|
CachedRowSetImpl customers = new CachedRowSetImpl();
|
||||||
|
customers.setUsername(username);
|
||||||
|
customers.setPassword(password);
|
||||||
|
customers.setUrl(url);
|
||||||
|
customers.setCommand(sql);
|
||||||
|
customers.execute();
|
||||||
|
|
||||||
|
CachedRowSetImpl associates = new CachedRowSetImpl();
|
||||||
|
associates.setUsername(username);
|
||||||
|
associates.setPassword(password);
|
||||||
|
associates.setUrl(url);
|
||||||
|
String associatesSQL = "SELECT * FROM associates";
|
||||||
|
associates.setCommand(associatesSQL);
|
||||||
|
associates.execute();
|
||||||
|
|
||||||
|
JoinRowSet jrs = new JoinRowSetImpl();
|
||||||
|
final String ID = "id";
|
||||||
|
final String NAME = "name";
|
||||||
|
jrs.addRowSet(customers, ID);
|
||||||
|
jrs.addRowSet(associates, ID);
|
||||||
|
jrs.last();
|
||||||
|
System.out.println("Total rows: " + jrs.getRow());
|
||||||
|
jrs.beforeFirst();
|
||||||
|
while (jrs.next()) {
|
||||||
|
|
||||||
|
String string1 = jrs.getString(ID);
|
||||||
|
String string2 = jrs.getString(NAME);
|
||||||
|
System.out.println("ID: " + string1 + ", NAME: " + string2);
|
||||||
|
}
|
||||||
|
|
||||||
|
// FilteredRowSet example
|
||||||
|
RowSetFactory rsf = RowSetProvider.newFactory();
|
||||||
|
FilteredRowSet frs = rsf.createFilteredRowSet();
|
||||||
|
frs.setCommand("select * from customers");
|
||||||
|
frs.execute(conn);
|
||||||
|
frs.setFilter(new FilterExample("^[A-C].*"));
|
||||||
|
|
||||||
|
ResultSetMetaData rsmd = frs.getMetaData();
|
||||||
|
int columncount = rsmd.getColumnCount();
|
||||||
|
while (frs.next()) {
|
||||||
|
for (int i = 1; i <= columncount; i++) {
|
||||||
|
System.out.println(rsmd.getColumnLabel(i) + " = " + frs.getObject(i) + " ");
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
} catch (SQLException e) {
|
||||||
|
// TODO Auto-generated catch block
|
||||||
|
e.printStackTrace();
|
||||||
|
}
|
||||||
|
|
||||||
|
}
|
||||||
|
|
||||||
|
}
|
@ -1,11 +0,0 @@
|
|||||||
package com.baeldung.nestedclass;
|
|
||||||
|
|
||||||
public class Enclosing {
|
|
||||||
|
|
||||||
public static class Nested {
|
|
||||||
|
|
||||||
public void test() {
|
|
||||||
System.out.println("Calling test...");
|
|
||||||
}
|
|
||||||
}
|
|
||||||
}
|
|
@ -1,11 +0,0 @@
|
|||||||
package com.baeldung.nestedclass;
|
|
||||||
|
|
||||||
public class Outer {
|
|
||||||
|
|
||||||
public class Inner {
|
|
||||||
|
|
||||||
public void test() {
|
|
||||||
System.out.println("Calling test...");
|
|
||||||
}
|
|
||||||
}
|
|
||||||
}
|
|
@ -1,5 +0,0 @@
|
|||||||
package com.baeldung.nestedclass;
|
|
||||||
|
|
||||||
abstract class SimpleAbstractClass {
|
|
||||||
abstract void run();
|
|
||||||
}
|
|
@ -0,0 +1,38 @@
|
|||||||
|
package com.baeldung.polymorphism;
|
||||||
|
|
||||||
|
import java.awt.image.BufferedImage;
|
||||||
|
|
||||||
|
import org.slf4j.Logger;
|
||||||
|
import org.slf4j.LoggerFactory;
|
||||||
|
|
||||||
|
public class FileManager {
|
||||||
|
|
||||||
|
final static Logger logger = LoggerFactory.getLogger(FileManager.class);
|
||||||
|
|
||||||
|
public static void main(String[] args) {
|
||||||
|
GenericFile file1 = new TextFile("SampleTextFile", "This is a sample text content", "v1.0.0");
|
||||||
|
logger.info("File Info: \n" + file1.getFileInfo() + "\n");
|
||||||
|
ImageFile imageFile = new ImageFile("SampleImageFile", 200, 100, new BufferedImage(100, 200, BufferedImage.TYPE_INT_RGB).toString()
|
||||||
|
.getBytes(), "v1.0.0");
|
||||||
|
logger.info("File Info: \n" + imageFile.getFileInfo());
|
||||||
|
}
|
||||||
|
|
||||||
|
public static ImageFile createImageFile(String name, int height, int width, byte[] content, String version) {
|
||||||
|
ImageFile imageFile = new ImageFile(name, height, width, content, version);
|
||||||
|
logger.info("File 2 Info: \n" + imageFile.getFileInfo());
|
||||||
|
return imageFile;
|
||||||
|
}
|
||||||
|
|
||||||
|
public static GenericFile createTextFile(String name, String content, String version) {
|
||||||
|
GenericFile file1 = new TextFile(name, content, version);
|
||||||
|
logger.info("File 1 Info: \n" + file1.getFileInfo() + "\n");
|
||||||
|
return file1;
|
||||||
|
}
|
||||||
|
|
||||||
|
public static TextFile createTextFile2(String name, String content, String version) {
|
||||||
|
TextFile file1 = new TextFile(name, content, version);
|
||||||
|
logger.info("File 1 Info: \n" + file1.getFileInfo() + "\n");
|
||||||
|
return file1;
|
||||||
|
}
|
||||||
|
|
||||||
|
}
|
@ -0,0 +1,63 @@
|
|||||||
|
package com.baeldung.polymorphism;
|
||||||
|
|
||||||
|
import java.util.Date;
|
||||||
|
|
||||||
|
public class GenericFile {
|
||||||
|
private String name;
|
||||||
|
private String extension;
|
||||||
|
private Date dateCreated;
|
||||||
|
private String version;
|
||||||
|
private byte[] content;
|
||||||
|
|
||||||
|
public GenericFile() {
|
||||||
|
this.setDateCreated(new Date());
|
||||||
|
}
|
||||||
|
|
||||||
|
public String getName() {
|
||||||
|
return name;
|
||||||
|
}
|
||||||
|
|
||||||
|
public void setName(String name) {
|
||||||
|
this.name = name;
|
||||||
|
}
|
||||||
|
|
||||||
|
public String getExtension() {
|
||||||
|
return extension;
|
||||||
|
}
|
||||||
|
|
||||||
|
public void setExtension(String extension) {
|
||||||
|
this.extension = extension;
|
||||||
|
}
|
||||||
|
|
||||||
|
public Date getDateCreated() {
|
||||||
|
return dateCreated;
|
||||||
|
}
|
||||||
|
|
||||||
|
public void setDateCreated(Date dateCreated) {
|
||||||
|
this.dateCreated = dateCreated;
|
||||||
|
}
|
||||||
|
|
||||||
|
public String getVersion() {
|
||||||
|
return version;
|
||||||
|
}
|
||||||
|
|
||||||
|
public void setVersion(String version) {
|
||||||
|
this.version = version;
|
||||||
|
}
|
||||||
|
|
||||||
|
public byte[] getContent() {
|
||||||
|
return content;
|
||||||
|
}
|
||||||
|
|
||||||
|
public void setContent(byte[] content) {
|
||||||
|
this.content = content;
|
||||||
|
}
|
||||||
|
|
||||||
|
public String getFileInfo() {
|
||||||
|
return "Generic File Impl";
|
||||||
|
}
|
||||||
|
|
||||||
|
public Object read() {
|
||||||
|
return content;
|
||||||
|
}
|
||||||
|
}
|
@ -0,0 +1,41 @@
|
|||||||
|
package com.baeldung.polymorphism;
|
||||||
|
|
||||||
|
public class ImageFile extends GenericFile {
|
||||||
|
private int height;
|
||||||
|
private int width;
|
||||||
|
|
||||||
|
public ImageFile(String name, int height, int width, byte[] content, String version) {
|
||||||
|
this.setHeight(height);
|
||||||
|
this.setWidth(width);
|
||||||
|
this.setContent(content);
|
||||||
|
this.setName(name);
|
||||||
|
this.setVersion(version);
|
||||||
|
this.setExtension(".jpg");
|
||||||
|
}
|
||||||
|
|
||||||
|
public int getHeight() {
|
||||||
|
return height;
|
||||||
|
}
|
||||||
|
|
||||||
|
public void setHeight(int height) {
|
||||||
|
this.height = height;
|
||||||
|
}
|
||||||
|
|
||||||
|
public int getWidth() {
|
||||||
|
return width;
|
||||||
|
}
|
||||||
|
|
||||||
|
public void setWidth(int width) {
|
||||||
|
this.width = width;
|
||||||
|
}
|
||||||
|
|
||||||
|
public String getFileInfo() {
|
||||||
|
return "Image File Impl";
|
||||||
|
}
|
||||||
|
|
||||||
|
public String read() {
|
||||||
|
return this.getContent()
|
||||||
|
.toString();
|
||||||
|
}
|
||||||
|
|
||||||
|
}
|
@ -0,0 +1,44 @@
|
|||||||
|
package com.baeldung.polymorphism;
|
||||||
|
|
||||||
|
public class TextFile extends GenericFile {
|
||||||
|
private int wordCount;
|
||||||
|
|
||||||
|
public TextFile(String name, String content, String version) {
|
||||||
|
String[] words = content.split(" ");
|
||||||
|
this.setWordCount(words.length > 0 ? words.length : 1);
|
||||||
|
this.setContent(content.getBytes());
|
||||||
|
this.setName(name);
|
||||||
|
this.setVersion(version);
|
||||||
|
this.setExtension(".txt");
|
||||||
|
}
|
||||||
|
|
||||||
|
public int getWordCount() {
|
||||||
|
return wordCount;
|
||||||
|
}
|
||||||
|
|
||||||
|
public void setWordCount(int wordCount) {
|
||||||
|
this.wordCount = wordCount;
|
||||||
|
}
|
||||||
|
|
||||||
|
public String getFileInfo() {
|
||||||
|
return "Text File Impl";
|
||||||
|
}
|
||||||
|
|
||||||
|
public String read() {
|
||||||
|
return this.getContent()
|
||||||
|
.toString();
|
||||||
|
}
|
||||||
|
|
||||||
|
public String read(int limit) {
|
||||||
|
return this.getContent()
|
||||||
|
.toString()
|
||||||
|
.substring(0, limit);
|
||||||
|
}
|
||||||
|
|
||||||
|
public String read(int start, int stop) {
|
||||||
|
return this.getContent()
|
||||||
|
.toString()
|
||||||
|
.substring(start, stop);
|
||||||
|
}
|
||||||
|
|
||||||
|
}
|
48
core-java/src/main/java/com/baeldung/stream/FileCopy.java
Normal file
48
core-java/src/main/java/com/baeldung/stream/FileCopy.java
Normal file
@ -0,0 +1,48 @@
|
|||||||
|
package com.baeldung.stream;
|
||||||
|
|
||||||
|
import java.io.File;
|
||||||
|
import java.io.FileInputStream;
|
||||||
|
import java.io.FileOutputStream;
|
||||||
|
import java.io.IOException;
|
||||||
|
import java.io.InputStream;
|
||||||
|
import java.io.OutputStream;
|
||||||
|
import java.nio.channels.FileChannel;
|
||||||
|
import java.nio.file.Files;
|
||||||
|
|
||||||
|
import org.apache.commons.io.FileUtils;
|
||||||
|
|
||||||
|
public class FileCopy {
|
||||||
|
|
||||||
|
public static void copyFileUsingStream(File source, File dest) throws IOException {
|
||||||
|
InputStream is = null;
|
||||||
|
OutputStream os = null;
|
||||||
|
is = new FileInputStream(source);
|
||||||
|
os = new FileOutputStream(dest);
|
||||||
|
byte[] buffer = new byte[1024];
|
||||||
|
int length;
|
||||||
|
while ((length = is.read(buffer)) > 0) {
|
||||||
|
os.write(buffer, 0, length);
|
||||||
|
}
|
||||||
|
is.close();
|
||||||
|
os.close();
|
||||||
|
}
|
||||||
|
|
||||||
|
public static void copyFileUsingChannel(File source, File dest) throws IOException {
|
||||||
|
FileChannel sourceChannel = null;
|
||||||
|
FileChannel destChannel = null;
|
||||||
|
sourceChannel = new FileInputStream(source).getChannel();
|
||||||
|
destChannel = new FileOutputStream(dest).getChannel();
|
||||||
|
destChannel.transferFrom(sourceChannel, 0, sourceChannel.size());
|
||||||
|
sourceChannel.close();
|
||||||
|
destChannel.close();
|
||||||
|
}
|
||||||
|
|
||||||
|
public static void copyFileUsingApacheCommonsIO(File source, File dest) throws IOException {
|
||||||
|
FileUtils.copyFile(source, dest);
|
||||||
|
}
|
||||||
|
|
||||||
|
public static void copyFileUsingJavaFiles(File source, File dest) throws IOException {
|
||||||
|
Files.copy(source.toPath(), dest.toPath());
|
||||||
|
}
|
||||||
|
|
||||||
|
}
|
161
core-java/src/main/java/com/baeldung/tree/BinaryTree.java
Normal file
161
core-java/src/main/java/com/baeldung/tree/BinaryTree.java
Normal file
@ -0,0 +1,161 @@
|
|||||||
|
package com.baeldung.tree;
|
||||||
|
|
||||||
|
import java.util.LinkedList;
|
||||||
|
import java.util.Queue;
|
||||||
|
|
||||||
|
public class BinaryTree {
|
||||||
|
|
||||||
|
Node root;
|
||||||
|
|
||||||
|
public void add(int value) {
|
||||||
|
root = addRecursive(root, value);
|
||||||
|
}
|
||||||
|
|
||||||
|
private Node addRecursive(Node current, int value) {
|
||||||
|
|
||||||
|
if (current == null) {
|
||||||
|
return new Node(value);
|
||||||
|
}
|
||||||
|
|
||||||
|
if (value < current.value) {
|
||||||
|
current.left = addRecursive(current.left, value);
|
||||||
|
} else if (value > current.value) {
|
||||||
|
current.right = addRecursive(current.right, value);
|
||||||
|
}
|
||||||
|
|
||||||
|
return current;
|
||||||
|
}
|
||||||
|
|
||||||
|
public boolean isEmpty() {
|
||||||
|
return root == null;
|
||||||
|
}
|
||||||
|
|
||||||
|
public int getSize() {
|
||||||
|
return getSizeRecursive(root);
|
||||||
|
}
|
||||||
|
|
||||||
|
private int getSizeRecursive(Node current) {
|
||||||
|
return current == null ? 0 : getSizeRecursive(current.left) + 1 + getSizeRecursive(current.right);
|
||||||
|
}
|
||||||
|
|
||||||
|
public boolean containsNode(int value) {
|
||||||
|
return containsNodeRecursive(root, value);
|
||||||
|
}
|
||||||
|
|
||||||
|
private boolean containsNodeRecursive(Node current, int value) {
|
||||||
|
if (current == null) {
|
||||||
|
return false;
|
||||||
|
}
|
||||||
|
|
||||||
|
if (value == current.value) {
|
||||||
|
return true;
|
||||||
|
}
|
||||||
|
|
||||||
|
return value < current.value
|
||||||
|
? containsNodeRecursive(current.left, value)
|
||||||
|
: containsNodeRecursive(current.right, value);
|
||||||
|
}
|
||||||
|
|
||||||
|
public void delete(int value) {
|
||||||
|
deleteRecursive(root, value);
|
||||||
|
}
|
||||||
|
|
||||||
|
private Node deleteRecursive(Node current, int value) {
|
||||||
|
if (current == null) {
|
||||||
|
return null;
|
||||||
|
}
|
||||||
|
|
||||||
|
if (value == current.value) {
|
||||||
|
// Case 1: no children
|
||||||
|
if (current.left == null && current.right == null) {
|
||||||
|
return null;
|
||||||
|
}
|
||||||
|
|
||||||
|
// Case 2: only 1 child
|
||||||
|
if (current.right == null) {
|
||||||
|
return current.left;
|
||||||
|
}
|
||||||
|
|
||||||
|
if (current.left == null) {
|
||||||
|
return current.right;
|
||||||
|
}
|
||||||
|
|
||||||
|
// Case 3: 2 children
|
||||||
|
int smallestValue = findSmallestValue(current.right);
|
||||||
|
current.value = smallestValue;
|
||||||
|
current.right = deleteRecursive(current.right, smallestValue);
|
||||||
|
return current;
|
||||||
|
}
|
||||||
|
if (value < current.value) {
|
||||||
|
current.left = deleteRecursive(current.left, value);
|
||||||
|
return current;
|
||||||
|
}
|
||||||
|
|
||||||
|
current.right = deleteRecursive(current.right, value);
|
||||||
|
return current;
|
||||||
|
}
|
||||||
|
|
||||||
|
private int findSmallestValue(Node root) {
|
||||||
|
return root.left == null ? root.value : findSmallestValue(root.left);
|
||||||
|
}
|
||||||
|
|
||||||
|
public void traverseInOrder(Node node) {
|
||||||
|
if (node != null) {
|
||||||
|
traverseInOrder(node.left);
|
||||||
|
System.out.print(" " + node.value);
|
||||||
|
traverseInOrder(node.right);
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
public void traversePreOrder(Node node) {
|
||||||
|
if (node != null) {
|
||||||
|
System.out.print(" " + node.value);
|
||||||
|
traversePreOrder(node.left);
|
||||||
|
traversePreOrder(node.right);
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
public void traversePostOrder(Node node) {
|
||||||
|
if (node != null) {
|
||||||
|
traversePostOrder(node.left);
|
||||||
|
traversePostOrder(node.right);
|
||||||
|
System.out.print(" " + node.value);
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
public void traverseLevelOrder() {
|
||||||
|
if (root == null) {
|
||||||
|
return;
|
||||||
|
}
|
||||||
|
|
||||||
|
Queue<Node> nodes = new LinkedList<>();
|
||||||
|
nodes.add(root);
|
||||||
|
|
||||||
|
while (!nodes.isEmpty()) {
|
||||||
|
|
||||||
|
Node node = nodes.remove();
|
||||||
|
|
||||||
|
System.out.print(" " + node.value);
|
||||||
|
|
||||||
|
if (node.left != null) {
|
||||||
|
nodes.add(node.left);
|
||||||
|
}
|
||||||
|
|
||||||
|
if (node.left != null) {
|
||||||
|
nodes.add(node.right);
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
class Node {
|
||||||
|
int value;
|
||||||
|
Node left;
|
||||||
|
Node right;
|
||||||
|
|
||||||
|
Node(int value) {
|
||||||
|
this.value = value;
|
||||||
|
right = null;
|
||||||
|
left = null;
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
@ -0,0 +1,49 @@
|
|||||||
|
package com.baeldung.array;
|
||||||
|
|
||||||
|
import static org.assertj.core.api.Assertions.assertThat;
|
||||||
|
|
||||||
|
import org.junit.Test;
|
||||||
|
|
||||||
|
public class ArrayInverterUnitTest {
|
||||||
|
|
||||||
|
private String[] fruits = { "apples", "tomatoes", "bananas", "guavas", "pineapples", "oranges" };
|
||||||
|
|
||||||
|
@Test
|
||||||
|
public void invertArrayWithForLoop() {
|
||||||
|
ArrayInverter inverter = new ArrayInverter();
|
||||||
|
inverter.invertUsingFor(fruits);
|
||||||
|
|
||||||
|
assertThat(new String[] { "oranges", "pineapples", "guavas", "bananas", "tomatoes", "apples" }).isEqualTo(fruits);
|
||||||
|
}
|
||||||
|
|
||||||
|
@Test
|
||||||
|
public void invertArrayWithCollectionsReverse() {
|
||||||
|
ArrayInverter inverter = new ArrayInverter();
|
||||||
|
inverter.invertUsingCollectionsReverse(fruits);
|
||||||
|
|
||||||
|
assertThat(new String[] { "oranges", "pineapples", "guavas", "bananas", "tomatoes", "apples" }).isEqualTo(fruits);
|
||||||
|
}
|
||||||
|
|
||||||
|
@Test
|
||||||
|
public void invertArrayWithStreams() {
|
||||||
|
ArrayInverter inverter = new ArrayInverter();
|
||||||
|
|
||||||
|
assertThat(new String[] { "oranges", "pineapples", "guavas", "bananas", "tomatoes", "apples" }).isEqualTo(inverter.invertUsingStreams(fruits));
|
||||||
|
}
|
||||||
|
|
||||||
|
@Test
|
||||||
|
public void invertArrayWithCommonsLang() {
|
||||||
|
ArrayInverter inverter = new ArrayInverter();
|
||||||
|
inverter.invertUsingCommonsLang(fruits);
|
||||||
|
|
||||||
|
assertThat(new String[] { "oranges", "pineapples", "guavas", "bananas", "tomatoes", "apples" }).isEqualTo(fruits);
|
||||||
|
}
|
||||||
|
|
||||||
|
@Test
|
||||||
|
public void invertArrayWithGuava() {
|
||||||
|
ArrayInverter inverter = new ArrayInverter();
|
||||||
|
|
||||||
|
assertThat(new String[] { "oranges", "pineapples", "guavas", "bananas", "tomatoes", "apples" }).isEqualTo(inverter.invertUsingGuava(fruits));
|
||||||
|
}
|
||||||
|
|
||||||
|
}
|
@ -0,0 +1,70 @@
|
|||||||
|
package com.baeldung.cipher;
|
||||||
|
|
||||||
|
|
||||||
|
import org.junit.Before;
|
||||||
|
import org.junit.Test;
|
||||||
|
|
||||||
|
import java.io.ByteArrayInputStream;
|
||||||
|
import java.io.InputStream;
|
||||||
|
import java.security.cert.CertificateFactory;
|
||||||
|
import java.security.cert.X509Certificate;
|
||||||
|
|
||||||
|
import static org.assertj.core.api.Assertions.assertThat;
|
||||||
|
|
||||||
|
public class EncryptorUnitTest {
|
||||||
|
private String encKeyString;
|
||||||
|
private String message;
|
||||||
|
private String certificateString;
|
||||||
|
private Encryptor encryptor;
|
||||||
|
|
||||||
|
@Before
|
||||||
|
public void init(){
|
||||||
|
encKeyString = "1234567890123456";
|
||||||
|
message = "This is a secret message";
|
||||||
|
encryptor = new Encryptor();
|
||||||
|
certificateString = "-----BEGIN CERTIFICATE-----\n" +
|
||||||
|
"MIICVjCCAb8CAg37MA0GCSqGSIb3DQEBBQUAMIGbMQswCQYDVQQGEwJKUDEOMAwG\n" +
|
||||||
|
"A1UECBMFVG9reW8xEDAOBgNVBAcTB0NodW8ta3UxETAPBgNVBAoTCEZyYW5rNERE\n" +
|
||||||
|
"MRgwFgYDVQQLEw9XZWJDZXJ0IFN1cHBvcnQxGDAWBgNVBAMTD0ZyYW5rNEREIFdl\n" +
|
||||||
|
"YiBDQTEjMCEGCSqGSIb3DQEJARYUc3VwcG9ydEBmcmFuazRkZC5jb20wHhcNMTIw\n" +
|
||||||
|
"ODIyMDUyNzIzWhcNMTcwODIxMDUyNzIzWjBKMQswCQYDVQQGEwJKUDEOMAwGA1UE\n" +
|
||||||
|
"CAwFVG9reW8xETAPBgNVBAoMCEZyYW5rNEREMRgwFgYDVQQDDA93d3cuZXhhbXBs\n" +
|
||||||
|
"ZS5jb20wgZ8wDQYJKoZIhvcNAQEBBQADgY0AMIGJAoGBAMYBBrx5PlP0WNI/ZdzD\n" +
|
||||||
|
"+6Pktmurn+F2kQYbtc7XQh8/LTBvCo+P6iZoLEmUA9e7EXLRxgU1CVqeAi7QcAn9\n" +
|
||||||
|
"MwBlc8ksFJHB0rtf9pmf8Oza9E0Bynlq/4/Kb1x+d+AyhL7oK9tQwB24uHOueHi1\n" +
|
||||||
|
"C/iVv8CSWKiYe6hzN1txYe8rAgMBAAEwDQYJKoZIhvcNAQEFBQADgYEAASPdjigJ\n" +
|
||||||
|
"kXCqKWpnZ/Oc75EUcMi6HztaW8abUMlYXPIgkV2F7YanHOB7K4f7OOLjiz8DTPFf\n" +
|
||||||
|
"jC9UeuErhaA/zzWi8ewMTFZW/WshOrm3fNvcMrMLKtH534JKvcdMg6qIdjTFINIr\n" +
|
||||||
|
"evnAhf0cwULaebn+lMs8Pdl7y37+sfluVok=\n" +
|
||||||
|
"-----END CERTIFICATE-----";
|
||||||
|
}
|
||||||
|
|
||||||
|
@Test
|
||||||
|
public void givenEncryptionKey_whenMessageIsPassedToEncryptor_thenMessageIsEncrypted() throws Exception {
|
||||||
|
byte[] encryptedMessage = encryptor.encryptMessage(message.getBytes(),encKeyString.getBytes());
|
||||||
|
|
||||||
|
assertThat(encryptedMessage).isNotNull();
|
||||||
|
assertThat(encryptedMessage.length % 32).isEqualTo(0);
|
||||||
|
}
|
||||||
|
|
||||||
|
@Test
|
||||||
|
public void givenCertificateWithPublicKey_whenMessageIsPassedToEncryptor_thenMessageIsEncrypted() throws Exception {
|
||||||
|
CertificateFactory factory = CertificateFactory.getInstance("X.509");
|
||||||
|
InputStream is = new ByteArrayInputStream(certificateString.getBytes());
|
||||||
|
X509Certificate certificate = (X509Certificate) factory.generateCertificate(is);
|
||||||
|
|
||||||
|
byte[] encryptedMessage = encryptor.encryptMessage(message.getBytes(),certificate);
|
||||||
|
|
||||||
|
assertThat(encryptedMessage).isNotNull();
|
||||||
|
assertThat(encryptedMessage.length % 128).isEqualTo(0);
|
||||||
|
}
|
||||||
|
|
||||||
|
@Test
|
||||||
|
public void givenEncryptionKey_whenMessageIsEncrypted_thenDecryptMessage() throws Exception{
|
||||||
|
byte[] encryptedMessageBytes = encryptor.encryptMessage(message.getBytes(),encKeyString.getBytes());
|
||||||
|
|
||||||
|
byte[] clearMessageBytes = encryptor.decryptMessage(encryptedMessageBytes, encKeyString.getBytes());
|
||||||
|
|
||||||
|
assertThat(message).isEqualTo(new String(clearMessageBytes));
|
||||||
|
}
|
||||||
|
}
|
@ -0,0 +1,60 @@
|
|||||||
|
package com.baeldung.collection;
|
||||||
|
|
||||||
|
import java.util.ConcurrentModificationException;
|
||||||
|
import java.util.HashMap;
|
||||||
|
import java.util.Iterator;
|
||||||
|
import java.util.Map;
|
||||||
|
import java.util.TreeMap;
|
||||||
|
|
||||||
|
import org.hamcrest.Matchers;
|
||||||
|
import org.junit.Assert;
|
||||||
|
import org.junit.Test;
|
||||||
|
|
||||||
|
public class WhenComparingTreeMapVsHashMap {
|
||||||
|
|
||||||
|
@Test
|
||||||
|
public void whenInsertObjectsTreeMap_thenNaturalOrder() {
|
||||||
|
Map<Integer, String> treemap = new TreeMap<>();
|
||||||
|
treemap.put(3, "TreeMap");
|
||||||
|
treemap.put(2, "vs");
|
||||||
|
treemap.put(1, "HashMap");
|
||||||
|
Assert.assertThat(treemap.keySet(), Matchers.contains(1, 2, 3));
|
||||||
|
}
|
||||||
|
|
||||||
|
@Test(expected = NullPointerException.class)
|
||||||
|
public void whenInsertNullInTreeMap_thenException() {
|
||||||
|
Map<Integer, String> treemap = new TreeMap<>();
|
||||||
|
treemap.put(null, "NullPointerException");
|
||||||
|
}
|
||||||
|
|
||||||
|
@Test
|
||||||
|
public void whenInsertObjectsHashMap_thenRandomOrder() {
|
||||||
|
Map<Integer, String> hashmap = new HashMap<>();
|
||||||
|
hashmap.put(3, "TreeMap");
|
||||||
|
hashmap.put(2, "vs");
|
||||||
|
hashmap.put(1, "HashMap");
|
||||||
|
Assert.assertThat(hashmap.keySet(), Matchers.containsInAnyOrder(1, 2, 3));
|
||||||
|
}
|
||||||
|
|
||||||
|
@Test
|
||||||
|
public void whenInsertNullInHashMap_thenInsertsNull() {
|
||||||
|
Map<Integer, String> hashmap = new HashMap<>();
|
||||||
|
hashmap.put(null, null);
|
||||||
|
Assert.assertNull(hashmap.get(null));
|
||||||
|
}
|
||||||
|
|
||||||
|
@Test
|
||||||
|
public void givenHashMapAndTreeMap_whenputDuplicates_thenOnlyUnique() {
|
||||||
|
Map<Integer, String> treeMap = new HashMap<>();
|
||||||
|
treeMap.put(1, "Baeldung");
|
||||||
|
treeMap.put(1, "Baeldung");
|
||||||
|
|
||||||
|
Assert.assertTrue(treeMap.size() == 1);
|
||||||
|
|
||||||
|
Map<Integer, String> treeMap2 = new TreeMap<>();
|
||||||
|
treeMap2.put(1, "Baeldung");
|
||||||
|
treeMap2.put(1, "Baeldung");
|
||||||
|
|
||||||
|
Assert.assertTrue(treeMap2.size() == 1);
|
||||||
|
}
|
||||||
|
}
|
@ -0,0 +1,93 @@
|
|||||||
|
package com.baeldung.collection;
|
||||||
|
|
||||||
|
import java.util.ConcurrentModificationException;
|
||||||
|
import java.util.HashSet;
|
||||||
|
import java.util.Iterator;
|
||||||
|
import java.util.Set;
|
||||||
|
|
||||||
|
import org.junit.Assert;
|
||||||
|
import org.junit.Test;
|
||||||
|
|
||||||
|
public class WhenUsingHashSet {
|
||||||
|
|
||||||
|
@Test
|
||||||
|
public void whenAddingElement_shouldAddElement() {
|
||||||
|
Set<String> hashset = new HashSet<>();
|
||||||
|
Assert.assertTrue(hashset.add("String Added"));
|
||||||
|
}
|
||||||
|
|
||||||
|
@Test
|
||||||
|
public void whenCheckingForElement_shouldSearchForElement() {
|
||||||
|
Set<String> hashsetContains = new HashSet<>();
|
||||||
|
hashsetContains.add("String Added");
|
||||||
|
Assert.assertTrue(hashsetContains.contains("String Added"));
|
||||||
|
}
|
||||||
|
|
||||||
|
@Test
|
||||||
|
public void whenCheckingTheSizeOfHashSet_shouldReturnThesize() {
|
||||||
|
Set<String> hashSetSize = new HashSet<>();
|
||||||
|
hashSetSize.add("String Added");
|
||||||
|
Assert.assertEquals(1, hashSetSize.size());
|
||||||
|
}
|
||||||
|
|
||||||
|
@Test
|
||||||
|
public void whenCheckingForEmptyHashSet_shouldCheckForEmpty() {
|
||||||
|
Set<String> emptyHashSet = new HashSet<>();
|
||||||
|
Assert.assertTrue(emptyHashSet.isEmpty());
|
||||||
|
}
|
||||||
|
|
||||||
|
@Test
|
||||||
|
public void whenRemovingElement_shouldRemoveElement() {
|
||||||
|
Set<String> removeFromHashSet = new HashSet<>();
|
||||||
|
removeFromHashSet.add("String Added");
|
||||||
|
Assert.assertTrue(removeFromHashSet.remove("String Added"));
|
||||||
|
}
|
||||||
|
|
||||||
|
@Test
|
||||||
|
public void whenClearingHashSet_shouldClearHashSet() {
|
||||||
|
Set<String> clearHashSet = new HashSet<>();
|
||||||
|
clearHashSet.add("String Added");
|
||||||
|
clearHashSet.clear();
|
||||||
|
Assert.assertTrue(clearHashSet.isEmpty());
|
||||||
|
}
|
||||||
|
|
||||||
|
@Test
|
||||||
|
public void whenIteratingHashSet_shouldIterateHashSet() {
|
||||||
|
Set<String> hashset = new HashSet<>();
|
||||||
|
hashset.add("First");
|
||||||
|
hashset.add("Second");
|
||||||
|
hashset.add("Third");
|
||||||
|
Iterator<String> itr = hashset.iterator();
|
||||||
|
while (itr.hasNext()) {
|
||||||
|
System.out.println(itr.next());
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
@Test(expected = ConcurrentModificationException.class)
|
||||||
|
public void whenModifyingHashSetWhileIterating_shouldThrowException() {
|
||||||
|
Set<String> hashset = new HashSet<>();
|
||||||
|
hashset.add("First");
|
||||||
|
hashset.add("Second");
|
||||||
|
hashset.add("Third");
|
||||||
|
Iterator<String> itr = hashset.iterator();
|
||||||
|
while (itr.hasNext()) {
|
||||||
|
itr.next();
|
||||||
|
hashset.remove("Second");
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
@Test
|
||||||
|
public void whenRemovingElementUsingIterator_shouldRemoveElement() {
|
||||||
|
Set<String> hashset = new HashSet<>();
|
||||||
|
hashset.add("First");
|
||||||
|
hashset.add("Second");
|
||||||
|
hashset.add("Third");
|
||||||
|
Iterator<String> itr = hashset.iterator();
|
||||||
|
while (itr.hasNext()) {
|
||||||
|
String element = itr.next();
|
||||||
|
if (element.equals("Second"))
|
||||||
|
itr.remove();
|
||||||
|
}
|
||||||
|
Assert.assertEquals(2, hashset.size());
|
||||||
|
}
|
||||||
|
}
|
@ -0,0 +1,228 @@
|
|||||||
|
package com.baeldung.collection;
|
||||||
|
|
||||||
|
import java.util.Comparator;
|
||||||
|
import java.util.ConcurrentModificationException;
|
||||||
|
import java.util.Iterator;
|
||||||
|
import java.util.NavigableSet;
|
||||||
|
import java.util.Set;
|
||||||
|
import java.util.SortedSet;
|
||||||
|
import java.util.TreeSet;
|
||||||
|
|
||||||
|
import org.junit.Assert;
|
||||||
|
import org.junit.Test;
|
||||||
|
|
||||||
|
public class WhenUsingTreeSet {
|
||||||
|
|
||||||
|
private static class Element {
|
||||||
|
private Integer id;
|
||||||
|
|
||||||
|
public Integer getId() {
|
||||||
|
return id;
|
||||||
|
}
|
||||||
|
|
||||||
|
public void setId(Integer id) {
|
||||||
|
this.id = id;
|
||||||
|
}
|
||||||
|
|
||||||
|
@Override
|
||||||
|
public String toString() {
|
||||||
|
return id.toString();
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
private Comparator<Element> comparator = (ele1, ele2) -> {
|
||||||
|
return ele1.getId()
|
||||||
|
.compareTo(ele2.getId());
|
||||||
|
};
|
||||||
|
|
||||||
|
@Test
|
||||||
|
public void whenAddingElement_shouldAddElement() {
|
||||||
|
Set<String> treeSet = new TreeSet<>();
|
||||||
|
Assert.assertTrue(treeSet.add("String Added"));
|
||||||
|
}
|
||||||
|
|
||||||
|
@Test
|
||||||
|
public void whenCheckingForElement_shouldSearchForElement() {
|
||||||
|
Set<String> treeSetContains = new TreeSet<>();
|
||||||
|
treeSetContains.add("String Added");
|
||||||
|
Assert.assertTrue(treeSetContains.contains("String Added"));
|
||||||
|
}
|
||||||
|
|
||||||
|
@Test
|
||||||
|
public void whenRemovingElement_shouldRemoveElement() {
|
||||||
|
Set<String> removeFromTreeSet = new TreeSet<>();
|
||||||
|
removeFromTreeSet.add("String Added");
|
||||||
|
Assert.assertTrue(removeFromTreeSet.remove("String Added"));
|
||||||
|
}
|
||||||
|
|
||||||
|
@Test
|
||||||
|
public void whenClearingTreeSet_shouldClearTreeSet() {
|
||||||
|
Set<String> clearTreeSet = new TreeSet<>();
|
||||||
|
clearTreeSet.add("String Added");
|
||||||
|
clearTreeSet.clear();
|
||||||
|
Assert.assertTrue(clearTreeSet.isEmpty());
|
||||||
|
}
|
||||||
|
|
||||||
|
@Test
|
||||||
|
public void whenCheckingTheSizeOfTreeSet_shouldReturnThesize() {
|
||||||
|
Set<String> treeSetSize = new TreeSet<>();
|
||||||
|
treeSetSize.add("String Added");
|
||||||
|
Assert.assertEquals(1, treeSetSize.size());
|
||||||
|
}
|
||||||
|
|
||||||
|
@Test
|
||||||
|
public void whenCheckingForEmptyTreeSet_shouldCheckForEmpty() {
|
||||||
|
Set<String> emptyTreeSet = new TreeSet<>();
|
||||||
|
Assert.assertTrue(emptyTreeSet.isEmpty());
|
||||||
|
}
|
||||||
|
|
||||||
|
@Test
|
||||||
|
public void whenIteratingTreeSet_shouldIterateTreeSetInAscendingOrder() {
|
||||||
|
Set<String> treeSet = new TreeSet<>();
|
||||||
|
treeSet.add("First");
|
||||||
|
treeSet.add("Second");
|
||||||
|
treeSet.add("Third");
|
||||||
|
Iterator<String> itr = treeSet.iterator();
|
||||||
|
while (itr.hasNext()) {
|
||||||
|
System.out.println(itr.next());
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
@Test
|
||||||
|
public void whenIteratingTreeSet_shouldIterateTreeSetInDescendingOrder() {
|
||||||
|
TreeSet<String> treeSet = new TreeSet<>();
|
||||||
|
treeSet.add("First");
|
||||||
|
treeSet.add("Second");
|
||||||
|
treeSet.add("Third");
|
||||||
|
Iterator<String> itr = treeSet.descendingIterator();
|
||||||
|
while (itr.hasNext()) {
|
||||||
|
System.out.println(itr.next());
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
@Test(expected = ConcurrentModificationException.class)
|
||||||
|
public void whenModifyingTreeSetWhileIterating_shouldThrowException() {
|
||||||
|
Set<String> treeSet = new TreeSet<>();
|
||||||
|
treeSet.add("First");
|
||||||
|
treeSet.add("Second");
|
||||||
|
treeSet.add("Third");
|
||||||
|
Iterator<String> itr = treeSet.iterator();
|
||||||
|
while (itr.hasNext()) {
|
||||||
|
itr.next();
|
||||||
|
treeSet.remove("Second");
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
@Test
|
||||||
|
public void whenRemovingElementUsingIterator_shouldRemoveElement() {
|
||||||
|
Set<String> treeSet = new TreeSet<>();
|
||||||
|
treeSet.add("First");
|
||||||
|
treeSet.add("Second");
|
||||||
|
treeSet.add("Third");
|
||||||
|
Iterator<String> itr = treeSet.iterator();
|
||||||
|
while (itr.hasNext()) {
|
||||||
|
String element = itr.next();
|
||||||
|
if (element.equals("Second"))
|
||||||
|
itr.remove();
|
||||||
|
}
|
||||||
|
Assert.assertEquals(2, treeSet.size());
|
||||||
|
}
|
||||||
|
|
||||||
|
@Test(expected = NullPointerException.class)
|
||||||
|
public void whenAddingNullToNonEmptyTreeSet_shouldThrowException() {
|
||||||
|
Set<String> treeSet = new TreeSet<>();
|
||||||
|
treeSet.add("First");
|
||||||
|
treeSet.add(null);
|
||||||
|
}
|
||||||
|
|
||||||
|
@Test
|
||||||
|
public void whenCheckingFirstElement_shouldReturnFirstElement() {
|
||||||
|
TreeSet<String> treeSet = new TreeSet<>();
|
||||||
|
treeSet.add("First");
|
||||||
|
Assert.assertEquals("First", treeSet.first());
|
||||||
|
}
|
||||||
|
|
||||||
|
@Test
|
||||||
|
public void whenCheckingLastElement_shouldReturnLastElement() {
|
||||||
|
TreeSet<String> treeSet = new TreeSet<>();
|
||||||
|
treeSet.add("First");
|
||||||
|
treeSet.add("Last");
|
||||||
|
Assert.assertEquals("Last", treeSet.last());
|
||||||
|
}
|
||||||
|
|
||||||
|
@Test
|
||||||
|
public void whenUsingComparator_shouldSortAndInsertElements() {
|
||||||
|
Set<Element> treeSet = new TreeSet<>(comparator);
|
||||||
|
Element ele1 = new Element();
|
||||||
|
ele1.setId(100);
|
||||||
|
Element ele2 = new Element();
|
||||||
|
ele2.setId(200);
|
||||||
|
|
||||||
|
treeSet.add(ele1);
|
||||||
|
treeSet.add(ele2);
|
||||||
|
|
||||||
|
System.out.println(treeSet);
|
||||||
|
}
|
||||||
|
|
||||||
|
@Test
|
||||||
|
public void whenUsingHeadSet_shouldReturnElementsLessThanSpecifiedElement() {
|
||||||
|
Set<Element> treeSet = new TreeSet<>(comparator);
|
||||||
|
Element ele1 = new Element();
|
||||||
|
ele1.setId(100);
|
||||||
|
Element ele2 = new Element();
|
||||||
|
ele2.setId(200);
|
||||||
|
|
||||||
|
treeSet.add(ele1);
|
||||||
|
treeSet.add(ele2);
|
||||||
|
|
||||||
|
System.out.println(treeSet);
|
||||||
|
}
|
||||||
|
|
||||||
|
@Test
|
||||||
|
public void whenUsingSubSet_shouldReturnSubSetElements() {
|
||||||
|
SortedSet<Integer> treeSet = new TreeSet<>();
|
||||||
|
treeSet.add(1);
|
||||||
|
treeSet.add(2);
|
||||||
|
treeSet.add(3);
|
||||||
|
treeSet.add(4);
|
||||||
|
treeSet.add(5);
|
||||||
|
treeSet.add(6);
|
||||||
|
|
||||||
|
Set<Integer> expectedSet = new TreeSet<>();
|
||||||
|
expectedSet.add(2);
|
||||||
|
expectedSet.add(3);
|
||||||
|
expectedSet.add(4);
|
||||||
|
expectedSet.add(5);
|
||||||
|
|
||||||
|
Set<Integer> subSet = treeSet.subSet(2, 6);
|
||||||
|
Assert.assertEquals(expectedSet, subSet);
|
||||||
|
}
|
||||||
|
|
||||||
|
@Test
|
||||||
|
public void whenUsingHeadSet_shouldReturnHeadSetElements() {
|
||||||
|
SortedSet<Integer> treeSet = new TreeSet<>();
|
||||||
|
treeSet.add(1);
|
||||||
|
treeSet.add(2);
|
||||||
|
treeSet.add(3);
|
||||||
|
treeSet.add(4);
|
||||||
|
treeSet.add(5);
|
||||||
|
treeSet.add(6);
|
||||||
|
|
||||||
|
Set<Integer> subSet = treeSet.headSet(6);
|
||||||
|
Assert.assertEquals(subSet, treeSet.subSet(1, 6));
|
||||||
|
}
|
||||||
|
|
||||||
|
@Test
|
||||||
|
public void whenUsingTailSet_shouldReturnTailSetElements() {
|
||||||
|
NavigableSet<Integer> treeSet = new TreeSet<>();
|
||||||
|
treeSet.add(1);
|
||||||
|
treeSet.add(2);
|
||||||
|
treeSet.add(3);
|
||||||
|
treeSet.add(4);
|
||||||
|
treeSet.add(5);
|
||||||
|
treeSet.add(6);
|
||||||
|
|
||||||
|
Set<Integer> subSet = treeSet.tailSet(3);
|
||||||
|
Assert.assertEquals(subSet, treeSet.subSet(3, true, 6, true));
|
||||||
|
}
|
||||||
|
}
|
@ -0,0 +1,37 @@
|
|||||||
|
package com.baeldung.initializationguide;
|
||||||
|
import org.junit.Before;
|
||||||
|
import org.junit.Test;
|
||||||
|
|
||||||
|
import static org.assertj.core.api.Assertions.*;
|
||||||
|
|
||||||
|
import java.lang.reflect.InvocationTargetException;
|
||||||
|
|
||||||
|
public class UserTest {
|
||||||
|
|
||||||
|
@Test
|
||||||
|
public void givenUserInstance_whenIntializedWithNew_thenInstanceIsNotNull() {
|
||||||
|
User user = new User("Alice", 1);
|
||||||
|
assertThat(user).isNotNull();
|
||||||
|
}
|
||||||
|
|
||||||
|
@Test
|
||||||
|
public void givenUserInstance_whenInitializedWithReflection_thenInstanceIsNotNull() throws InstantiationException, IllegalAccessException, IllegalArgumentException, InvocationTargetException, NoSuchMethodException, SecurityException {
|
||||||
|
User user = User.class.getConstructor(String.class, int.class)
|
||||||
|
.newInstance("Alice", 2);
|
||||||
|
assertThat(user).isNotNull();
|
||||||
|
}
|
||||||
|
|
||||||
|
@Test
|
||||||
|
public void givenUserInstance_whenCopiedWithClone_thenExactMatchIsCreated() throws CloneNotSupportedException {
|
||||||
|
User user = new User("Alice", 3);
|
||||||
|
User clonedUser = (User) user.clone();
|
||||||
|
assertThat(clonedUser).isEqualTo(user);
|
||||||
|
}
|
||||||
|
|
||||||
|
@Test
|
||||||
|
public void givenUserInstance_whenValuesAreNotInitialized_thenUserNameAndIdReturnDefault() {
|
||||||
|
User user = new User();
|
||||||
|
assertThat(user.getName()).isNull();
|
||||||
|
assertThat(user.getId() == 0);
|
||||||
|
}
|
||||||
|
}
|
@ -0,0 +1,18 @@
|
|||||||
|
package com.baeldung.interfaces;
|
||||||
|
|
||||||
|
import static org.junit.Assert.assertEquals;
|
||||||
|
|
||||||
|
import org.junit.Test;
|
||||||
|
import org.junit.runner.RunWith;
|
||||||
|
import org.junit.runners.JUnit4;
|
||||||
|
|
||||||
|
@RunWith(JUnit4.class)
|
||||||
|
public class InnerInterfaceTests {
|
||||||
|
@Test
|
||||||
|
public void whenCustomerListJoined_thenReturnsJoinedNames() {
|
||||||
|
Customer.List customerList = new CommaSeparatedCustomers();
|
||||||
|
customerList.Add(new Customer("customer1"));
|
||||||
|
customerList.Add(new Customer("customer2"));
|
||||||
|
assertEquals("customer1,customer2", customerList.getCustomerNames());
|
||||||
|
}
|
||||||
|
}
|
@ -0,0 +1,71 @@
|
|||||||
|
package com.baeldung.jdbc;
|
||||||
|
|
||||||
|
|
||||||
|
import org.junit.Before;
|
||||||
|
import org.junit.Test;
|
||||||
|
import org.junit.runner.RunWith;
|
||||||
|
import org.mockito.InjectMocks;
|
||||||
|
import org.mockito.Mock;
|
||||||
|
import org.mockito.Mockito;
|
||||||
|
import org.mockito.MockitoAnnotations;
|
||||||
|
import org.mockito.junit.MockitoJUnitRunner;
|
||||||
|
|
||||||
|
import java.sql.Connection;
|
||||||
|
import java.sql.PreparedStatement;
|
||||||
|
import java.sql.Statement;
|
||||||
|
|
||||||
|
@RunWith(MockitoJUnitRunner.class)
|
||||||
|
public class BatchProcessingTest {
|
||||||
|
|
||||||
|
|
||||||
|
@InjectMocks
|
||||||
|
private BatchProcessing target = new BatchProcessing();
|
||||||
|
|
||||||
|
@Mock
|
||||||
|
private Connection connection;
|
||||||
|
|
||||||
|
@Mock
|
||||||
|
private Statement statement;
|
||||||
|
|
||||||
|
@Mock
|
||||||
|
private PreparedStatement employeeStatement;
|
||||||
|
|
||||||
|
@Mock
|
||||||
|
private PreparedStatement employeeAddressStatement;
|
||||||
|
|
||||||
|
@Before
|
||||||
|
public void before(){
|
||||||
|
MockitoAnnotations.initMocks(this);
|
||||||
|
}
|
||||||
|
|
||||||
|
|
||||||
|
@Test
|
||||||
|
public void when_useStatement_thenInsertData_success() throws Exception {
|
||||||
|
Mockito.when(connection.createStatement()).thenReturn(statement);
|
||||||
|
target.useStatement();
|
||||||
|
}
|
||||||
|
|
||||||
|
@Test
|
||||||
|
public void when_useStatement_ifThrowException_thenCatchException() throws Exception {
|
||||||
|
Mockito.when(connection.createStatement()).thenThrow(new RuntimeException());
|
||||||
|
target.useStatement();
|
||||||
|
}
|
||||||
|
|
||||||
|
@Test
|
||||||
|
public void when_usePreparedStatement_thenInsertData_success() throws Exception {
|
||||||
|
String insertEmployeeSQL = "INSERT INTO EMPLOYEE(ID, NAME, DESIGNATION) VALUES (?,?,?);";
|
||||||
|
String insertEmployeeAddrSQL = "INSERT INTO EMP_ADDRESS(ID, EMP_ID, ADDRESS) VALUES (?,?,?);";
|
||||||
|
Mockito.when(connection.prepareStatement(insertEmployeeSQL)).thenReturn(employeeStatement);
|
||||||
|
Mockito.when(connection.prepareStatement(insertEmployeeAddrSQL)).thenReturn(employeeAddressStatement);
|
||||||
|
target.usePreparedStatement();
|
||||||
|
}
|
||||||
|
|
||||||
|
@Test
|
||||||
|
public void when_usePreparedStatement_ifThrowException_thenCatchException() throws Exception {
|
||||||
|
String insertEmployeeSQL = "INSERT INTO EMPLOYEE(ID, NAME, DESIGNATION) VALUES (?,?,?);";
|
||||||
|
String insertEmployeeAddrSQL = "INSERT INTO EMP_ADDRESS(ID, EMP_ID, ADDRESS) VALUES (?,?,?);";
|
||||||
|
Mockito.when(connection.prepareStatement(insertEmployeeSQL)).thenReturn(employeeStatement);
|
||||||
|
Mockito.when(connection.prepareStatement(insertEmployeeAddrSQL)).thenThrow(new RuntimeException());
|
||||||
|
target.usePreparedStatement();
|
||||||
|
}
|
||||||
|
}
|
@ -0,0 +1,157 @@
|
|||||||
|
package com.baeldung.jdbcrowset;
|
||||||
|
|
||||||
|
import java.io.FileOutputStream;
|
||||||
|
import java.io.IOException;
|
||||||
|
import java.sql.Connection;
|
||||||
|
import java.sql.ResultSet;
|
||||||
|
import java.sql.ResultSetMetaData;
|
||||||
|
import java.sql.SQLException;
|
||||||
|
import java.sql.Statement;
|
||||||
|
|
||||||
|
import javax.sql.rowset.CachedRowSet;
|
||||||
|
import javax.sql.rowset.FilteredRowSet;
|
||||||
|
import javax.sql.rowset.JdbcRowSet;
|
||||||
|
import javax.sql.rowset.JoinRowSet;
|
||||||
|
import javax.sql.rowset.RowSetFactory;
|
||||||
|
import javax.sql.rowset.RowSetProvider;
|
||||||
|
import javax.sql.rowset.WebRowSet;
|
||||||
|
|
||||||
|
import org.junit.Before;
|
||||||
|
import org.junit.Test;
|
||||||
|
|
||||||
|
import com.sun.rowset.CachedRowSetImpl;
|
||||||
|
import com.sun.rowset.JdbcRowSetImpl;
|
||||||
|
import com.sun.rowset.JoinRowSetImpl;
|
||||||
|
import com.sun.rowset.WebRowSetImpl;
|
||||||
|
|
||||||
|
public class JdbcRowSetTest {
|
||||||
|
Statement stmt = null;
|
||||||
|
String username = "sa";
|
||||||
|
String password = "";
|
||||||
|
String url = "jdbc:h2:mem:testdb";
|
||||||
|
String sql = "SELECT * FROM customers";
|
||||||
|
|
||||||
|
@Before
|
||||||
|
public void setup() throws Exception {
|
||||||
|
Connection conn = DatabaseConfiguration.geth2Connection();
|
||||||
|
|
||||||
|
String drop = "DROP TABLE IF EXISTS customers, associates;";
|
||||||
|
String schema = "CREATE TABLE customers (id INT NOT NULL, name VARCHAR(50) NOT NULL, PRIMARY KEY (id)); ";
|
||||||
|
String schemapartb = "CREATE TABLE associates (id INT NOT NULL, name VARCHAR(50) NOT NULL, PRIMARY KEY (id));";
|
||||||
|
stmt = conn.createStatement();
|
||||||
|
stmt.executeUpdate(drop);
|
||||||
|
stmt.executeUpdate(schema);
|
||||||
|
stmt.executeUpdate(schemapartb);
|
||||||
|
DatabaseConfiguration.initDatabase(stmt);
|
||||||
|
|
||||||
|
}
|
||||||
|
|
||||||
|
// JdbcRowSet Example
|
||||||
|
@Test
|
||||||
|
public void createJdbcRowSet_SelectCustomers_ThenCorrect() throws Exception {
|
||||||
|
|
||||||
|
String sql = "SELECT * FROM customers";
|
||||||
|
JdbcRowSet jdbcRS;
|
||||||
|
Connection conn = DatabaseConfiguration.geth2Connection();
|
||||||
|
jdbcRS = new JdbcRowSetImpl(conn);
|
||||||
|
jdbcRS.setType(ResultSet.TYPE_SCROLL_INSENSITIVE);
|
||||||
|
jdbcRS.setCommand(sql);
|
||||||
|
jdbcRS.execute();
|
||||||
|
jdbcRS.addRowSetListener(new ExampleListener());
|
||||||
|
|
||||||
|
while (jdbcRS.next()) {
|
||||||
|
// each call to next, generates a cursorMoved event
|
||||||
|
System.out.println("id=" + jdbcRS.getString(1));
|
||||||
|
System.out.println("name=" + jdbcRS.getString(2));
|
||||||
|
}
|
||||||
|
|
||||||
|
}
|
||||||
|
|
||||||
|
// CachedRowSet Example
|
||||||
|
@Test
|
||||||
|
public void createCachedRowSet_DeleteRecord_ThenCorrect() throws Exception {
|
||||||
|
|
||||||
|
CachedRowSet crs = new CachedRowSetImpl();
|
||||||
|
crs.setUsername(username);
|
||||||
|
crs.setPassword(password);
|
||||||
|
crs.setUrl(url);
|
||||||
|
crs.setCommand(sql);
|
||||||
|
crs.execute();
|
||||||
|
crs.addRowSetListener(new ExampleListener());
|
||||||
|
while (crs.next()) {
|
||||||
|
if (crs.getInt("id") == 1) {
|
||||||
|
System.out.println("CRS found customer1 and will remove the record.");
|
||||||
|
crs.deleteRow();
|
||||||
|
break;
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
// WebRowSet example
|
||||||
|
@Test
|
||||||
|
public void createWebRowSet_SelectCustomers_WritetoXML_ThenCorrect() throws SQLException, IOException {
|
||||||
|
|
||||||
|
WebRowSet wrs = new WebRowSetImpl();
|
||||||
|
wrs.setUsername(username);
|
||||||
|
wrs.setPassword(password);
|
||||||
|
wrs.setUrl(url);
|
||||||
|
wrs.setCommand(sql);
|
||||||
|
wrs.execute();
|
||||||
|
FileOutputStream ostream = new FileOutputStream("customers.xml");
|
||||||
|
wrs.writeXml(ostream);
|
||||||
|
}
|
||||||
|
|
||||||
|
// JoinRowSet example
|
||||||
|
@Test
|
||||||
|
public void createCachedRowSets_DoJoinRowSet_ThenCorrect() throws Exception {
|
||||||
|
|
||||||
|
CachedRowSetImpl customers = new CachedRowSetImpl();
|
||||||
|
customers.setUsername(username);
|
||||||
|
customers.setPassword(password);
|
||||||
|
customers.setUrl(url);
|
||||||
|
customers.setCommand(sql);
|
||||||
|
customers.execute();
|
||||||
|
|
||||||
|
CachedRowSetImpl associates = new CachedRowSetImpl();
|
||||||
|
associates.setUsername(username);
|
||||||
|
associates.setPassword(password);
|
||||||
|
associates.setUrl(url);
|
||||||
|
String associatesSQL = "SELECT * FROM associates";
|
||||||
|
associates.setCommand(associatesSQL);
|
||||||
|
associates.execute();
|
||||||
|
|
||||||
|
JoinRowSet jrs = new JoinRowSetImpl();
|
||||||
|
final String ID = "id";
|
||||||
|
final String NAME = "name";
|
||||||
|
jrs.addRowSet(customers, ID);
|
||||||
|
jrs.addRowSet(associates, ID);
|
||||||
|
jrs.last();
|
||||||
|
System.out.println("Total rows: " + jrs.getRow());
|
||||||
|
jrs.beforeFirst();
|
||||||
|
while (jrs.next()) {
|
||||||
|
|
||||||
|
String string1 = jrs.getString(ID);
|
||||||
|
String string2 = jrs.getString(NAME);
|
||||||
|
System.out.println("ID: " + string1 + ", NAME: " + string2);
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
// FilteredRowSet example
|
||||||
|
@Test
|
||||||
|
public void createFilteredRowSet_filterByRegexExpression_thenCorrect() throws Exception {
|
||||||
|
RowSetFactory rsf = RowSetProvider.newFactory();
|
||||||
|
FilteredRowSet frs = rsf.createFilteredRowSet();
|
||||||
|
frs.setCommand("select * from customers");
|
||||||
|
Connection conn = DatabaseConfiguration.geth2Connection();
|
||||||
|
frs.execute(conn);
|
||||||
|
frs.setFilter(new FilterExample("^[A-C].*"));
|
||||||
|
|
||||||
|
ResultSetMetaData rsmd = frs.getMetaData();
|
||||||
|
int columncount = rsmd.getColumnCount();
|
||||||
|
while (frs.next()) {
|
||||||
|
for (int i = 1; i <= columncount; i++) {
|
||||||
|
System.out.println(rsmd.getColumnLabel(i) + " = " + frs.getObject(i) + " ");
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
@ -1,11 +1,38 @@
|
|||||||
package com.baeldung.loops;
|
package com.baeldung.loops;
|
||||||
|
|
||||||
|
import java.util.ArrayList;
|
||||||
|
import java.util.HashMap;
|
||||||
|
import java.util.HashSet;
|
||||||
|
import java.util.List;
|
||||||
|
import java.util.Map;
|
||||||
|
import java.util.Map.Entry;
|
||||||
|
import java.util.Set;
|
||||||
|
|
||||||
import org.junit.Assert;
|
import org.junit.Assert;
|
||||||
|
import org.junit.BeforeClass;
|
||||||
import org.junit.Test;
|
import org.junit.Test;
|
||||||
|
|
||||||
public class WhenUsingLoops {
|
public class WhenUsingLoops {
|
||||||
|
|
||||||
private LoopsInJava loops = new LoopsInJava();
|
private LoopsInJava loops = new LoopsInJava();
|
||||||
|
private static List<String> list = new ArrayList<>();
|
||||||
|
private static Set<String> set = new HashSet<>();
|
||||||
|
private static Map<String, Integer> map = new HashMap<>();
|
||||||
|
|
||||||
|
@BeforeClass
|
||||||
|
public static void setUp() {
|
||||||
|
list.add("One");
|
||||||
|
list.add("Two");
|
||||||
|
list.add("Three");
|
||||||
|
|
||||||
|
set.add("Four");
|
||||||
|
set.add("Five");
|
||||||
|
set.add("Six");
|
||||||
|
|
||||||
|
map.put("One", 1);
|
||||||
|
map.put("Two", 2);
|
||||||
|
map.put("Three", 3);
|
||||||
|
}
|
||||||
|
|
||||||
@Test
|
@Test
|
||||||
public void shouldRunForLoop() {
|
public void shouldRunForLoop() {
|
||||||
@ -34,4 +61,47 @@ public class WhenUsingLoops {
|
|||||||
int[] actual = loops.do_while_loop();
|
int[] actual = loops.do_while_loop();
|
||||||
Assert.assertArrayEquals(expected, actual);
|
Assert.assertArrayEquals(expected, actual);
|
||||||
}
|
}
|
||||||
|
|
||||||
|
@Test
|
||||||
|
public void whenUsingSimpleFor_shouldIterateList() {
|
||||||
|
for (int i = 0; i < list.size(); i++) {
|
||||||
|
System.out.println(list.get(i));
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
@Test
|
||||||
|
public void whenUsingEnhancedFor_shouldIterateList() {
|
||||||
|
for (String item : list) {
|
||||||
|
System.out.println(item);
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
@Test
|
||||||
|
public void whenUsingEnhancedFor_shouldIterateSet() {
|
||||||
|
for (String item : set) {
|
||||||
|
System.out.println(item);
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
@Test
|
||||||
|
public void whenUsingEnhancedFor_shouldIterateMap() {
|
||||||
|
for (Entry<String, Integer> entry : map.entrySet()) {
|
||||||
|
System.out.println("Key: " + entry.getKey() + " - " + "Value: " + entry.getValue());
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
@Test
|
||||||
|
public void whenUsingSimpleFor_shouldRunLabelledLoop() {
|
||||||
|
aa: for (int i = 1; i <= 3; i++) {
|
||||||
|
if (i == 1)
|
||||||
|
continue;
|
||||||
|
bb: for (int j = 1; j <= 3; j++) {
|
||||||
|
if (i == 2 && j == 2) {
|
||||||
|
break aa;
|
||||||
|
}
|
||||||
|
System.out.println(i + " " + j);
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
}
|
}
|
||||||
|
@ -2,10 +2,14 @@ package com.baeldung.nestedclass;
|
|||||||
|
|
||||||
import org.junit.Test;
|
import org.junit.Test;
|
||||||
|
|
||||||
public class AnonymousInnerTest {
|
abstract class SimpleAbstractClass {
|
||||||
|
abstract void run();
|
||||||
|
}
|
||||||
|
|
||||||
|
public class AnonymousInner {
|
||||||
|
|
||||||
@Test
|
@Test
|
||||||
public void whenRunAnonymousClass_thenCorrect() {
|
public void run() {
|
||||||
SimpleAbstractClass simpleAbstractClass = new SimpleAbstractClass() {
|
SimpleAbstractClass simpleAbstractClass = new SimpleAbstractClass() {
|
||||||
void run() {
|
void run() {
|
||||||
System.out.println("Running Anonymous Class...");
|
System.out.println("Running Anonymous Class...");
|
@ -0,0 +1,21 @@
|
|||||||
|
package com.baeldung.nestedclass;
|
||||||
|
|
||||||
|
import org.junit.Test;
|
||||||
|
|
||||||
|
public class Enclosing {
|
||||||
|
|
||||||
|
private static int x = 1;
|
||||||
|
|
||||||
|
public static class StaticNested {
|
||||||
|
|
||||||
|
private void run() {
|
||||||
|
System.out.println("x = " + x);
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
@Test
|
||||||
|
public void test() {
|
||||||
|
Enclosing.StaticNested nested = new Enclosing.StaticNested();
|
||||||
|
nested.run();
|
||||||
|
}
|
||||||
|
}
|
@ -1,13 +0,0 @@
|
|||||||
package com.baeldung.nestedclass;
|
|
||||||
|
|
||||||
import org.junit.Test;
|
|
||||||
|
|
||||||
public class InnerClassTest {
|
|
||||||
|
|
||||||
@Test
|
|
||||||
public void givenInnerClassWhenInstantiating_thenCorrect() {
|
|
||||||
Outer outer = new Outer();
|
|
||||||
Outer.Inner inner = outer.new Inner();
|
|
||||||
inner.test();
|
|
||||||
}
|
|
||||||
}
|
|
@ -1,12 +0,0 @@
|
|||||||
package com.baeldung.nestedclass;
|
|
||||||
|
|
||||||
import org.junit.Test;
|
|
||||||
|
|
||||||
public class LocalClassTest {
|
|
||||||
|
|
||||||
@Test
|
|
||||||
public void whenTestingLocalClass_thenCorrect() {
|
|
||||||
NewEnclosing newEnclosing = new NewEnclosing();
|
|
||||||
newEnclosing.run();
|
|
||||||
}
|
|
||||||
}
|
|
@ -1,12 +0,0 @@
|
|||||||
package com.baeldung.nestedclass;
|
|
||||||
|
|
||||||
import org.junit.Test;
|
|
||||||
|
|
||||||
public class NestedClassTest {
|
|
||||||
|
|
||||||
@Test
|
|
||||||
public void whenInstantiatingStaticNestedClass_thenCorrect() {
|
|
||||||
Enclosing.Nested nested = new Enclosing.Nested();
|
|
||||||
nested.test();
|
|
||||||
}
|
|
||||||
}
|
|
@ -1,10 +1,11 @@
|
|||||||
package com.baeldung.nestedclass;
|
package com.baeldung.nestedclass;
|
||||||
|
|
||||||
|
import org.junit.Test;
|
||||||
|
|
||||||
public class NewEnclosing {
|
public class NewEnclosing {
|
||||||
|
|
||||||
void run() {
|
private void run() {
|
||||||
class Local {
|
class Local {
|
||||||
|
|
||||||
void run() {
|
void run() {
|
||||||
System.out.println("Welcome to Baeldung!");
|
System.out.println("Welcome to Baeldung!");
|
||||||
}
|
}
|
||||||
@ -12,4 +13,10 @@ public class NewEnclosing {
|
|||||||
Local local = new Local();
|
Local local = new Local();
|
||||||
local.run();
|
local.run();
|
||||||
}
|
}
|
||||||
|
|
||||||
|
@Test
|
||||||
|
public void test() {
|
||||||
|
NewEnclosing newEnclosing = new NewEnclosing();
|
||||||
|
newEnclosing.run();
|
||||||
|
}
|
||||||
}
|
}
|
@ -0,0 +1,30 @@
|
|||||||
|
package com.baeldung.nestedclass;
|
||||||
|
|
||||||
|
import org.junit.Test;
|
||||||
|
|
||||||
|
public class NewOuter {
|
||||||
|
|
||||||
|
int a = 1;
|
||||||
|
static int b = 2;
|
||||||
|
|
||||||
|
public class InnerClass {
|
||||||
|
int a = 3;
|
||||||
|
static final int b = 4;
|
||||||
|
|
||||||
|
public void run() {
|
||||||
|
System.out.println("a = " + a);
|
||||||
|
System.out.println("b = " + b);
|
||||||
|
System.out.println("NewOuter.this.a = " + NewOuter.this.a);
|
||||||
|
System.out.println("NewOuter.b = " + NewOuter.b);
|
||||||
|
System.out.println("NewOuter.this.b = " + NewOuter.this.b);
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
@Test
|
||||||
|
public void test() {
|
||||||
|
NewOuter outer = new NewOuter();
|
||||||
|
NewOuter.InnerClass inner = outer.new InnerClass();
|
||||||
|
inner.run();
|
||||||
|
|
||||||
|
}
|
||||||
|
}
|
@ -1,32 +0,0 @@
|
|||||||
package com.baeldung.nestedclass;
|
|
||||||
|
|
||||||
import static org.junit.Assert.assertEquals;
|
|
||||||
import org.junit.Test;
|
|
||||||
|
|
||||||
public class NewOuterTest {
|
|
||||||
|
|
||||||
int a = 1;
|
|
||||||
static int b = 2;
|
|
||||||
|
|
||||||
public class InnerClass {
|
|
||||||
int a = 3;
|
|
||||||
static final int b = 4;
|
|
||||||
|
|
||||||
@Test
|
|
||||||
public void whenShadowing_thenCorrect() {
|
|
||||||
assertEquals(3, a);
|
|
||||||
assertEquals(4, b);
|
|
||||||
assertEquals(1, NewOuterTest.this.a);
|
|
||||||
assertEquals(2, NewOuterTest.b);
|
|
||||||
assertEquals(2, NewOuterTest.this.b);
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
@Test
|
|
||||||
public void shadowingTest() {
|
|
||||||
NewOuterTest outer = new NewOuterTest();
|
|
||||||
NewOuterTest.InnerClass inner = outer.new InnerClass();
|
|
||||||
inner.whenShadowing_thenCorrect();
|
|
||||||
|
|
||||||
}
|
|
||||||
}
|
|
20
core-java/src/test/java/com/baeldung/nestedclass/Outer.java
Normal file
20
core-java/src/test/java/com/baeldung/nestedclass/Outer.java
Normal file
@ -0,0 +1,20 @@
|
|||||||
|
package com.baeldung.nestedclass;
|
||||||
|
|
||||||
|
import org.junit.Test;
|
||||||
|
|
||||||
|
public class Outer {
|
||||||
|
|
||||||
|
public class Inner {
|
||||||
|
|
||||||
|
public void run() {
|
||||||
|
System.out.println("Calling test...");
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
@Test
|
||||||
|
public void test() {
|
||||||
|
Outer outer = new Outer();
|
||||||
|
Outer.Inner inner = outer.new Inner();
|
||||||
|
inner.run();
|
||||||
|
}
|
||||||
|
}
|
@ -0,0 +1,32 @@
|
|||||||
|
package com.baeldung.polymorphism;
|
||||||
|
|
||||||
|
import static org.junit.Assert.*;
|
||||||
|
|
||||||
|
import java.awt.image.BufferedImage;
|
||||||
|
import org.junit.Test;
|
||||||
|
|
||||||
|
public class PolymorphismUnitTest {
|
||||||
|
|
||||||
|
@Test
|
||||||
|
public void givenImageFile_whenFileCreated_shouldSucceed() {
|
||||||
|
ImageFile imageFile = FileManager.createImageFile("SampleImageFile", 200, 100, new BufferedImage(100, 200, BufferedImage.TYPE_INT_RGB).toString()
|
||||||
|
.getBytes(), "v1.0.0");
|
||||||
|
assertEquals(200, imageFile.getHeight());
|
||||||
|
}
|
||||||
|
|
||||||
|
// Downcasting then Upcasting
|
||||||
|
@Test
|
||||||
|
public void givenTextFile_whenTextFileCreatedAndAssignedToGenericFileAndCastBackToTextFileOnGetWordCount_shouldSucceed() {
|
||||||
|
GenericFile textFile = FileManager.createTextFile("SampleTextFile", "This is a sample text content", "v1.0.0");
|
||||||
|
TextFile textFile2 = (TextFile) textFile;
|
||||||
|
assertEquals(6, textFile2.getWordCount());
|
||||||
|
}
|
||||||
|
|
||||||
|
// Downcasting
|
||||||
|
@Test(expected = ClassCastException.class)
|
||||||
|
public void givenGenericFile_whenCastToTextFileAndInvokeGetWordCount_shouldFail() {
|
||||||
|
GenericFile genericFile = new GenericFile();
|
||||||
|
TextFile textFile = (TextFile) genericFile;
|
||||||
|
System.out.println(textFile.getWordCount());
|
||||||
|
}
|
||||||
|
}
|
@ -0,0 +1,47 @@
|
|||||||
|
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();
|
||||||
|
}
|
||||||
|
}
|
119
core-java/src/test/java/com/baeldung/tree/BinaryTreeTest.java
Normal file
119
core-java/src/test/java/com/baeldung/tree/BinaryTreeTest.java
Normal file
@ -0,0 +1,119 @@
|
|||||||
|
package com.baeldung.tree;
|
||||||
|
|
||||||
|
import static org.junit.Assert.assertEquals;
|
||||||
|
import static org.junit.Assert.assertFalse;
|
||||||
|
import static org.junit.Assert.assertTrue;
|
||||||
|
|
||||||
|
import org.junit.Test;
|
||||||
|
|
||||||
|
public class BinaryTreeTest {
|
||||||
|
|
||||||
|
@Test
|
||||||
|
public void givenABinaryTree_WhenAddingElements_ThenTreeNotEmpty() {
|
||||||
|
|
||||||
|
BinaryTree bt = createBinaryTree();
|
||||||
|
|
||||||
|
assertTrue(!bt.isEmpty());
|
||||||
|
}
|
||||||
|
|
||||||
|
@Test
|
||||||
|
public void givenABinaryTree_WhenAddingElements_ThenTreeContainsThoseElements() {
|
||||||
|
|
||||||
|
BinaryTree bt = createBinaryTree();
|
||||||
|
|
||||||
|
assertTrue(bt.containsNode(6));
|
||||||
|
assertTrue(bt.containsNode(4));
|
||||||
|
|
||||||
|
assertFalse(bt.containsNode(1));
|
||||||
|
}
|
||||||
|
|
||||||
|
@Test
|
||||||
|
public void givenABinaryTree_WhenAddingExistingElement_ThenElementIsNotAdded() {
|
||||||
|
|
||||||
|
BinaryTree bt = createBinaryTree();
|
||||||
|
|
||||||
|
int initialSize = bt.getSize();
|
||||||
|
|
||||||
|
assertTrue(bt.containsNode(3));
|
||||||
|
bt.add(3);
|
||||||
|
assertEquals(initialSize, bt.getSize());
|
||||||
|
}
|
||||||
|
|
||||||
|
@Test
|
||||||
|
public void givenABinaryTree_WhenLookingForNonExistingElement_ThenReturnsFalse() {
|
||||||
|
|
||||||
|
BinaryTree bt = createBinaryTree();
|
||||||
|
|
||||||
|
assertFalse(bt.containsNode(99));
|
||||||
|
}
|
||||||
|
|
||||||
|
@Test
|
||||||
|
public void givenABinaryTree_WhenDeletingElements_ThenTreeDoesNotContainThoseElements() {
|
||||||
|
|
||||||
|
BinaryTree bt = createBinaryTree();
|
||||||
|
|
||||||
|
assertTrue(bt.containsNode(9));
|
||||||
|
bt.delete(9);
|
||||||
|
assertFalse(bt.containsNode(9));
|
||||||
|
}
|
||||||
|
|
||||||
|
@Test
|
||||||
|
public void givenABinaryTree_WhenDeletingNonExistingElement_ThenTreeDoesNotDelete() {
|
||||||
|
|
||||||
|
BinaryTree bt = createBinaryTree();
|
||||||
|
|
||||||
|
int initialSize = bt.getSize();
|
||||||
|
|
||||||
|
assertFalse(bt.containsNode(99));
|
||||||
|
bt.delete(99);
|
||||||
|
assertFalse(bt.containsNode(99));
|
||||||
|
assertEquals(initialSize, bt.getSize());
|
||||||
|
}
|
||||||
|
|
||||||
|
@Test
|
||||||
|
public void givenABinaryTree_WhenTraversingInOrder_ThenPrintValues() {
|
||||||
|
|
||||||
|
BinaryTree bt = createBinaryTree();
|
||||||
|
|
||||||
|
bt.traverseInOrder(bt.root);
|
||||||
|
}
|
||||||
|
|
||||||
|
@Test
|
||||||
|
public void givenABinaryTree_WhenTraversingPreOrder_ThenPrintValues() {
|
||||||
|
|
||||||
|
BinaryTree bt = createBinaryTree();
|
||||||
|
|
||||||
|
bt.traversePreOrder(bt.root);
|
||||||
|
}
|
||||||
|
|
||||||
|
@Test
|
||||||
|
public void givenABinaryTree_WhenTraversingPostOrder_ThenPrintValues() {
|
||||||
|
|
||||||
|
BinaryTree bt = createBinaryTree();
|
||||||
|
|
||||||
|
bt.traversePostOrder(bt.root);
|
||||||
|
}
|
||||||
|
|
||||||
|
@Test
|
||||||
|
public void givenABinaryTree_WhenTraversingLevelOrder_ThenPrintValues() {
|
||||||
|
|
||||||
|
BinaryTree bt = createBinaryTree();
|
||||||
|
|
||||||
|
bt.traverseLevelOrder();
|
||||||
|
}
|
||||||
|
|
||||||
|
private BinaryTree createBinaryTree() {
|
||||||
|
BinaryTree bt = new BinaryTree();
|
||||||
|
|
||||||
|
bt.add(6);
|
||||||
|
bt.add(4);
|
||||||
|
bt.add(8);
|
||||||
|
bt.add(3);
|
||||||
|
bt.add(5);
|
||||||
|
bt.add(7);
|
||||||
|
bt.add(9);
|
||||||
|
|
||||||
|
return bt;
|
||||||
|
}
|
||||||
|
|
||||||
|
}
|
@ -0,0 +1,60 @@
|
|||||||
|
package com.baeldung.varargs;
|
||||||
|
|
||||||
|
import org.junit.Test;
|
||||||
|
|
||||||
|
import static org.hamcrest.CoreMatchers.is;
|
||||||
|
import static org.hamcrest.MatcherAssert.assertThat;
|
||||||
|
|
||||||
|
public class FormatterTest {
|
||||||
|
|
||||||
|
private final static String FORMAT = "%s %s %s";
|
||||||
|
|
||||||
|
@Test
|
||||||
|
public void givenNoArgument_thenEmptyAndTwoSpacesAreReturned() {
|
||||||
|
String actualResult = format();
|
||||||
|
|
||||||
|
assertThat(actualResult, is("empty "));
|
||||||
|
}
|
||||||
|
|
||||||
|
@Test
|
||||||
|
public void givenOneArgument_thenResultHasTwoTrailingSpace() {
|
||||||
|
String actualResult = format("baeldung");
|
||||||
|
|
||||||
|
assertThat(actualResult, is("baeldung "));
|
||||||
|
}
|
||||||
|
|
||||||
|
@Test
|
||||||
|
public void givenTwoArguments_thenOneTrailingSpaceExists() {
|
||||||
|
String actualResult = format("baeldung", "rocks");
|
||||||
|
|
||||||
|
assertThat(actualResult, is("baeldung rocks "));
|
||||||
|
}
|
||||||
|
|
||||||
|
@Test
|
||||||
|
public void givenMoreThanThreeArguments_thenTheFirstThreeAreUsed() {
|
||||||
|
String actualResult = formatWithVarArgs("baeldung", "rocks", "java", "and", "spring");
|
||||||
|
|
||||||
|
assertThat(actualResult, is("baeldung rocks java"));
|
||||||
|
}
|
||||||
|
|
||||||
|
public String format() {
|
||||||
|
return format("empty", "");
|
||||||
|
}
|
||||||
|
|
||||||
|
public String format(String value) {
|
||||||
|
return format(value, "");
|
||||||
|
}
|
||||||
|
|
||||||
|
public String format(String val1, String val2) {
|
||||||
|
return String.format(FORMAT, val1, val2, "");
|
||||||
|
}
|
||||||
|
|
||||||
|
public String formatWithVarArgs(String... values) {
|
||||||
|
if (values.length == 0) {
|
||||||
|
return "no arguments given";
|
||||||
|
}
|
||||||
|
|
||||||
|
return String.format(FORMAT, values);
|
||||||
|
}
|
||||||
|
|
||||||
|
}
|
2
core-java/src/test/resources/copyTest/dest/readme.txt
Normal file
2
core-java/src/test/resources/copyTest/dest/readme.txt
Normal file
@ -0,0 +1,2 @@
|
|||||||
|
files will be copied here and then deleted
|
||||||
|
remove `file.delete()` to see the files here
|
@ -0,0 +1 @@
|
|||||||
|
apache
|
@ -0,0 +1 @@
|
|||||||
|
channel
|
1
core-java/src/test/resources/copyTest/src/test_files.txt
Normal file
1
core-java/src/test/resources/copyTest/src/test_files.txt
Normal file
@ -0,0 +1 @@
|
|||||||
|
files
|
@ -0,0 +1 @@
|
|||||||
|
stream
|
@ -105,7 +105,11 @@
|
|||||||
<plugin>
|
<plugin>
|
||||||
<groupId>org.apache.maven.plugins</groupId>
|
<groupId>org.apache.maven.plugins</groupId>
|
||||||
<artifactId>maven-compiler-plugin</artifactId>
|
<artifactId>maven-compiler-plugin</artifactId>
|
||||||
<version>3.5.1</version>
|
<version>3.7.0</version>
|
||||||
|
<configuration>
|
||||||
|
<source>1.8</source>
|
||||||
|
<target>1.8</target>
|
||||||
|
</configuration>
|
||||||
<executions>
|
<executions>
|
||||||
<!-- Replacing default-compile as it is treated specially
|
<!-- Replacing default-compile as it is treated specially
|
||||||
by maven -->
|
by maven -->
|
||||||
|
@ -0,0 +1,51 @@
|
|||||||
|
package com.baeldung.kotlin
|
||||||
|
|
||||||
|
import org.junit.Assert
|
||||||
|
import org.junit.Test
|
||||||
|
|
||||||
|
class ExtensionMethods {
|
||||||
|
@Test
|
||||||
|
fun simpleExtensionMethod() {
|
||||||
|
fun String.escapeForXml() : String {
|
||||||
|
return this
|
||||||
|
.replace("&", "&")
|
||||||
|
.replace("<", "<")
|
||||||
|
.replace(">", ">")
|
||||||
|
}
|
||||||
|
|
||||||
|
Assert.assertEquals("Nothing", "Nothing".escapeForXml())
|
||||||
|
Assert.assertEquals("<Tag>", "<Tag>".escapeForXml())
|
||||||
|
Assert.assertEquals("a&b", "a&b".escapeForXml())
|
||||||
|
}
|
||||||
|
|
||||||
|
@Test
|
||||||
|
fun genericExtensionMethod() {
|
||||||
|
fun <T> T.concatAsString(b: T) : String {
|
||||||
|
return this.toString() + b.toString()
|
||||||
|
}
|
||||||
|
|
||||||
|
Assert.assertEquals("12", "1".concatAsString("2"))
|
||||||
|
Assert.assertEquals("12", 1.concatAsString(2))
|
||||||
|
// This doesn't compile
|
||||||
|
// Assert.assertEquals("12", 1.concatAsString(2.0))
|
||||||
|
}
|
||||||
|
|
||||||
|
@Test
|
||||||
|
fun infixExtensionMethod() {
|
||||||
|
infix fun Number.toPowerOf(exponent: Number): Double {
|
||||||
|
return Math.pow(this.toDouble(), exponent.toDouble())
|
||||||
|
}
|
||||||
|
|
||||||
|
Assert.assertEquals(9.0, 3 toPowerOf 2, 0.1)
|
||||||
|
Assert.assertEquals(3.0, 9 toPowerOf 0.5, 0.1)
|
||||||
|
}
|
||||||
|
|
||||||
|
@Test
|
||||||
|
fun operatorExtensionMethod() {
|
||||||
|
operator fun List<Int>.times(by: Int): List<Int> {
|
||||||
|
return this.map { it * by }
|
||||||
|
}
|
||||||
|
|
||||||
|
Assert.assertEquals(listOf(2, 4, 6), listOf(1, 2, 3) * 2)
|
||||||
|
}
|
||||||
|
}
|
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