This commit is contained in:
Radu Tamas 2018-03-14 16:09:47 +02:00
commit fe7ed30d4d
2724 changed files with 270845 additions and 6427 deletions

1
.gitignore vendored
View File

@ -43,3 +43,4 @@ spring-call-getters-using-reflection/.mvn/wrapper/maven-wrapper.properties
spring-check-if-a-property-is-null/.mvn/wrapper/maven-wrapper.properties spring-check-if-a-property-is-null/.mvn/wrapper/maven-wrapper.properties
*.springBeans *.springBeans
20171220-JMeter.csv

View File

@ -3,7 +3,8 @@ language: java
before_install: before_install:
- echo "MAVEN_OPTS='-Xmx2048M -Xss128M -XX:+CMSClassUnloadingEnabled -XX:+UseG1GC -XX:-UseGCOverheadLimit'" > ~/.mavenrc - echo "MAVEN_OPTS='-Xmx2048M -Xss128M -XX:+CMSClassUnloadingEnabled -XX:+UseG1GC -XX:-UseGCOverheadLimit'" > ~/.mavenrc
install: travis_wait 60 mvn -q test -fae install: skip
script: travis_wait 60 mvn -q test -fae
sudo: required sudo: required

21
LICENSE Normal file
View File

@ -0,0 +1,21 @@
MIT License
Copyright (c) 2017 Eugen Paraschiv
Permission is hereby granted, free of charge, to any person obtaining a copy
of this software and associated documentation files (the "Software"), to deal
in the Software without restriction, including without limitation the rights
to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
copies of the Software, and to permit persons to whom the Software is
furnished to do so, subject to the following conditions:
The above copyright notice and this permission notice shall be included in all
copies or substantial portions of the Software.
THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
SOFTWARE.

View File

@ -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
================ ================

129
activejdbc/pom.xml Normal file
View File

@ -0,0 +1,129 @@
<project xmlns="http://maven.apache.org/POM/4.0.0" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd">
<modelVersion>4.0.0</modelVersion>
<groupId>com.baeldung</groupId>
<artifactId>activejdbc</artifactId>
<version>1.0-SNAPSHOT</version>
<packaging>jar</packaging>
<name>activejdbc</name>
<url>http://maven.apache.org</url>
<properties>
<project.build.sourceEncoding>UTF-8</project.build.sourceEncoding>
<activejdbc.version>1.4.13</activejdbc.version>
<environments>development.test,development</environments>
</properties>
<build>
<plugins>
<plugin>
<groupId>org.apache.maven.plugins</groupId>
<artifactId>maven-compiler-plugin</artifactId>
<version>3.6.0</version>
<configuration>
<source>1.8</source>
<target>1.8</target>
<encoding>UTF-8</encoding>
</configuration>
</plugin>
<plugin>
<groupId>org.javalite</groupId>
<artifactId>activejdbc-instrumentation</artifactId>
<version>${activejdbc.version}</version>
<executions>
<execution>
<phase>process-classes</phase>
<goals>
<goal>instrument</goal>
</goals>
</execution>
</executions>
</plugin>
<plugin>
<groupId>org.javalite</groupId>
<artifactId>db-migrator-maven-plugin</artifactId>
<version>${activejdbc.version}</version>
<configuration>
<configFile>${project.basedir}/src/main/resources/database.properties</configFile>
<environments>${environments}</environments>
</configuration>
<dependencies>
<dependency>
<groupId>mysql</groupId>
<artifactId>mysql-connector-java</artifactId>
<version>5.1.34</version>
</dependency>
</dependencies>
</plugin>
<plugin>
<groupId>org.apache.maven.plugins</groupId>
<artifactId>maven-surefire-plugin</artifactId>
<version>2.18.1</version>
<configuration>
<reportFormat>brief</reportFormat>
<trimStackTrace>true</trimStackTrace>
<useFile>false</useFile>
<includes>
<include>**/*Spec*.java</include>
<include>**/*Test*.java</include>
</includes>
<excludes>
<exclude>**/helpers/*</exclude>
<exclude>**/*$*</exclude>
</excludes>
</configuration>
</plugin>
</plugins>
</build>
<dependencies>
<dependency>
<groupId>junit</groupId>
<artifactId>junit</artifactId>
<version>4.12</version>
<scope>test</scope>
</dependency>
<dependency>
<groupId>org.javalite</groupId>
<artifactId>activejdbc</artifactId>
<version>${activejdbc.version}</version>
<exclusions>
<exclusion>
<groupId>opensymphony</groupId>
<artifactId>oscache</artifactId>
</exclusion>
</exclusions>
</dependency>
<dependency>
<groupId>mysql</groupId>
<artifactId>mysql-connector-java</artifactId>
<version>5.1.34</version>
</dependency>
<dependency>
<groupId>org.slf4j</groupId>
<artifactId>slf4j-simple</artifactId>
<version>1.7.9</version>
</dependency>
</dependencies>
<repositories>
<repository>
<id>snapshots1</id>
<name>JavaLite Snapshots1</name>
<url>http://repo.javalite.io/</url>
<snapshots>
<enabled>true</enabled>
<updatePolicy>always</updatePolicy>
<checksumPolicy>warn</checksumPolicy>
</snapshots>
</repository>
</repositories>
<pluginRepositories>
<pluginRepository>
<id>snapshots2</id>
<name>JavaLite Snapshots2</name>
<url>http://repo.javalite.io/</url>
<snapshots>
<enabled>true</enabled>
<updatePolicy>always</updatePolicy>
<checksumPolicy>warn</checksumPolicy>
</snapshots>
</pluginRepository>
</pluginRepositories>
</project>

View File

@ -0,0 +1,61 @@
package com.baeldung;
import com.baeldung.model.Employee;
import com.baeldung.model.Role;
import org.javalite.activejdbc.Base;
import org.javalite.activejdbc.LazyList;
import org.javalite.activejdbc.Model;
public class ActiveJDBCApp
{
public static void main( String[] args )
{
try {
Base.open();
ActiveJDBCApp app = new ActiveJDBCApp();
app.create();
app.update();
app.delete();
app.deleteCascade();
} catch (Exception e) {
e.printStackTrace();
} finally {
Base.close();
}
}
protected void create() {
Employee employee = new Employee("Hugo","C","M","BN");
employee.saveIt();
employee.add(new Role("Java Developer","BN"));
LazyList<Model> all = Employee.findAll();
System.out.println(all.size());
}
protected void update() {
Employee employee = Employee.findFirst("first_name = ?","Hugo");
employee.set("last_namea","Choi").saveIt();
employee = Employee.findFirst("last_name = ?","Choi");
System.out.println(employee.getString("first_name") + " " + employee.getString("last_name"));
}
protected void delete() {
Employee employee = Employee.findFirst("first_name = ?","Hugo");
employee.delete();
employee = Employee.findFirst("last_name = ?","Choi");
if(null == employee){
System.out.println("No such Employee found!");
}
}
protected void deleteCascade() {
create();
Employee employee = Employee.findFirst("first_name = ?","Hugo");
employee.deleteCascade();
employee = Employee.findFirst("last_name = ?","C");
if(null == employee){
System.out.println("No such Employee found!");
}
}
}

View File

@ -0,0 +1,19 @@
package com.baeldung.model;
import org.javalite.activejdbc.Model;
public class Employee extends Model {
public Employee(){
}
public Employee(String firstName, String lastName, String gender, String createdBy) {
set("first_name1",firstName);
set("last_name",lastName);
set("gender",gender);
set("created_by",createdBy);
}
}

View File

@ -0,0 +1,18 @@
package com.baeldung.model;
import org.javalite.activejdbc.Model;
import org.javalite.activejdbc.annotations.Table;
@Table("EMP_ROLES")
public class Role extends Model {
public Role(){
}
public Role(String role,String createdBy){
set("role_name",role);
set("created_by",createdBy);
}
}

View File

@ -0,0 +1,25 @@
# noinspection SqlNoDataSourceInspectionForFile
create table organisation.employees
(
id int not null auto_increment
primary key,
first_name varchar(100) not null,
last_name varchar(100) not null,
gender varchar(1) not null,
created_at datetime not null,
updated_at datetime null,
created_by varchar(100) not null,
updated_by varchar(100) null
)ENGINE = InnoDB DEFAULT CHARSET = utf8;
create table organisation.emp_roles
(
id int not null auto_increment primary key,
employee_id int not null,
role_name varchar(100) not null,
created_at datetime not null,
updated_at datetime null,
created_by varchar(100) not null,
updated_by varchar(100) null
)ENGINE = InnoDB DEFAULT CHARSET = utf8;

View File

@ -0,0 +1,10 @@
development.driver=com.mysql.jdbc.Driver
development.username=root
development.password=123456
development.url=jdbc:mysql://localhost/organisation
development.test.driver=com.mysql.jdbc.Driver
development.test.username=root
development.test.password=123456
development.test.url=jdbc:mysql://localhost/organisation_test

View File

@ -0,0 +1,51 @@
package com.baeldung;
import com.baeldung.model.Employee;
import com.baeldung.model.Role;
import org.javalite.activejdbc.test.DBSpec;
import org.junit.Test;
import java.util.List;
public class ActiveJDBCAppTest extends DBSpec
{
@Test
public void ifEmployeeCreated_thenIsValid() {
Employee employee = new Employee("B", "N", "M", "BN");
the(employee).shouldBe("valid");
}
@Test
public void ifEmployeeCreatedWithRoles_thenShouldPersist() {
Employee employee = new Employee("B", "N", "M", "BN");
employee.saveIt();
employee.add(new Role("Java Developer","BN"));
employee.add(new Role("Lead Java Developer","BN"));
a(Role.count()).shouldBeEqual(2);
List<Role> roles = employee.getAll(Role.class).orderBy("created_at");
the(roles.get(0).getRoleName()).shouldBeEqual("Java Developer");
the(roles.get(1).getRoleName()).shouldBeEqual("Lead Java Developer");
}
@Test
public void ifEmployeeCreatedWithRoles_whenNameUpdated_thenShouldShowNewName() {
Employee employee = new Employee("Binesh", "N", "M", "BN");
employee.saveIt();
employee.add(new Role("Java Developer","BN"));
employee.add(new Role("Lead Java Developer","BN"));
employee = Employee.findFirst("first_name = ?", "Binesh");
employee.set("last_name","Narayanan").saveIt();
Employee updated = Employee.findFirst("first_name = ?", "Binesh");
the(updated.getLastName()).shouldBeEqual("Narayanan");
}
@Test
public void ifEmployeeCreatedWithRoles_whenDeleted_thenShouldNotBeFound() {
Employee employee = new Employee("Binesh", "N", "M", "BN");
employee.saveIt();
employee.add(new Role("Java Developer","BN"));
employee.delete();
employee = Employee.findFirst("first_name = ?", "Binesh");
the(employee).shouldBeNull();
}
}

View File

@ -14,3 +14,6 @@
- [Bubble Sort in Java](http://www.baeldung.com/java-bubble-sort) - [Bubble Sort in Java](http://www.baeldung.com/java-bubble-sort)
- [Introduction to JGraphT](http://www.baeldung.com/jgrapht) - [Introduction to JGraphT](http://www.baeldung.com/jgrapht)
- [Introduction to Minimax Algorithm](http://www.baeldung.com/java-minimax-algorithm) - [Introduction to Minimax Algorithm](http://www.baeldung.com/java-minimax-algorithm)
- [How to Calculate Levenshtein Distance in Java?](http://www.baeldung.com/java-levenshtein-distance)
- [How to Find the Kth Largest Element in Java](http://www.baeldung.com/java-kth-largest-element)
- [Multi-Swarm Optimization Algorithm in Java](http://www.baeldung.com/java-multi-swarm-algorithm)

View File

@ -9,6 +9,7 @@
<exec-maven-plugin.version>1.5.0</exec-maven-plugin.version> <exec-maven-plugin.version>1.5.0</exec-maven-plugin.version>
<lombok.version>1.16.12</lombok.version> <lombok.version>1.16.12</lombok.version>
<commons-math3.version>3.6.1</commons-math3.version> <commons-math3.version>3.6.1</commons-math3.version>
<tradukisto.version>1.0.1</tradukisto.version>
</properties> </properties>
<parent> <parent>
@ -39,8 +40,18 @@
<artifactId>jgrapht-core</artifactId> <artifactId>jgrapht-core</artifactId>
<version>1.0.1</version> <version>1.0.1</version>
</dependency> </dependency>
<dependency>
<groupId>pl.allegro.finance</groupId>
<artifactId>tradukisto</artifactId>
<version>${tradukisto.version}</version>
</dependency>
<dependency>
<groupId>org.assertj</groupId>
<artifactId>assertj-core</artifactId>
<version>3.9.0</version>
<scope>test</scope>
</dependency>
</dependencies> </dependencies>
<build> <build>
<pluginManagement> <pluginManagement>
<plugins> <plugins>

View File

@ -0,0 +1,111 @@
package com.baeldung.algorithms.kthlargest;
import java.util.Arrays;
import java.util.Collections;
import java.util.stream.IntStream;
public class FindKthLargest {
public int findKthLargestBySorting(Integer[] arr, int k) {
Arrays.sort(arr);
int targetIndex = arr.length - k;
return arr[targetIndex];
}
public int findKthLargestBySortingDesc(Integer[] arr, int k) {
Arrays.sort(arr, Collections.reverseOrder());
return arr[k - 1];
}
public int findKthElementByQuickSelect(Integer[] arr, int left, int right, int k) {
if (k >= 0 && k <= right - left + 1) {
int pos = partition(arr, left, right);
if (pos - left == k) {
return arr[pos];
}
if (pos - left > k) {
return findKthElementByQuickSelect(arr, left, pos - 1, k);
}
return findKthElementByQuickSelect(arr, pos + 1, right, k - pos + left - 1);
}
return 0;
}
public int findKthElementByQuickSelectWithIterativePartition(Integer[] arr, int left, int right, int k) {
if (k >= 0 && k <= right - left + 1) {
int pos = partitionIterative(arr, left, right);
if (pos - left == k) {
return arr[pos];
}
if (pos - left > k) {
return findKthElementByQuickSelectWithIterativePartition(arr, left, pos - 1, k);
}
return findKthElementByQuickSelectWithIterativePartition(arr, pos + 1, right, k - pos + left - 1);
}
return 0;
}
private int partition(Integer[] arr, int left, int right) {
int pivot = arr[right];
Integer[] leftArr;
Integer[] rightArr;
leftArr = IntStream.range(left, right)
.filter(i -> arr[i] < pivot)
.map(i -> arr[i])
.boxed()
.toArray(Integer[]::new);
rightArr = IntStream.range(left, right)
.filter(i -> arr[i] > pivot)
.map(i -> arr[i])
.boxed()
.toArray(Integer[]::new);
int leftArraySize = leftArr.length;
System.arraycopy(leftArr, 0, arr, left, leftArraySize);
arr[leftArraySize + left] = pivot;
System.arraycopy(rightArr, 0, arr, left + leftArraySize + 1, rightArr.length);
return left + leftArraySize;
}
private int partitionIterative(Integer[] arr, int left, int right) {
int pivot = arr[right], i = left;
for (int j = left; j <= right - 1; j++) {
if (arr[j] <= pivot) {
swap(arr, i, j);
i++;
}
}
swap(arr, i, right);
return i;
}
public int findKthElementByRandomizedQuickSelect(Integer[] arr, int left, int right, int k) {
if (k >= 0 && k <= right - left + 1) {
int pos = randomPartition(arr, left, right);
if (pos - left == k) {
return arr[pos];
}
if (pos - left > k) {
return findKthElementByRandomizedQuickSelect(arr, left, pos - 1, k);
}
return findKthElementByRandomizedQuickSelect(arr, pos + 1, right, k - pos + left - 1);
}
return 0;
}
private int randomPartition(Integer arr[], int left, int right) {
int n = right - left + 1;
int pivot = (int) (Math.random()) % n;
swap(arr, left + pivot, right);
return partition(arr, left, right);
}
private void swap(Integer[] arr, int n1, int n2) {
int temp = arr[n2];
arr[n2] = arr[n1];
arr[n1] = temp;
}
}

View File

@ -0,0 +1,52 @@
package com.baeldung.algorithms.maze.solver;
import java.util.ArrayList;
import java.util.Collections;
import java.util.LinkedList;
import java.util.List;
public class BFSMazeSolver {
private static final int[][] DIRECTIONS = { { 0, 1 }, { 1, 0 }, { 0, -1 }, { -1, 0 } };
public List<Coordinate> solve(Maze maze) {
LinkedList<Coordinate> nextToVisit = new LinkedList<>();
Coordinate start = maze.getEntry();
nextToVisit.add(start);
while (!nextToVisit.isEmpty()) {
Coordinate cur = nextToVisit.remove();
if (!maze.isValidLocation(cur.getX(), cur.getY()) || maze.isExplored(cur.getX(), cur.getY())) {
continue;
}
if (maze.isWall(cur.getX(), cur.getY())) {
maze.setVisited(cur.getX(), cur.getY(), true);
continue;
}
if (maze.isExit(cur.getX(), cur.getY())) {
return backtrackPath(cur);
}
for (int[] direction : DIRECTIONS) {
Coordinate coordinate = new Coordinate(cur.getX() + direction[0], cur.getY() + direction[1], cur);
nextToVisit.add(coordinate);
maze.setVisited(cur.getX(), cur.getY(), true);
}
}
return Collections.emptyList();
}
private List<Coordinate> backtrackPath(Coordinate cur) {
List<Coordinate> path = new ArrayList<>();
Coordinate iter = cur;
while (iter != null) {
path.add(iter);
iter = iter.parent;
}
return path;
}
}

View File

@ -0,0 +1,31 @@
package com.baeldung.algorithms.maze.solver;
public class Coordinate {
int x;
int y;
Coordinate parent;
public Coordinate(int x, int y) {
this.x = x;
this.y = y;
this.parent = null;
}
public Coordinate(int x, int y, Coordinate parent) {
this.x = x;
this.y = y;
this.parent = parent;
}
int getX() {
return x;
}
int getY() {
return y;
}
Coordinate getParent() {
return parent;
}
}

View File

@ -0,0 +1,48 @@
package com.baeldung.algorithms.maze.solver;
import java.util.ArrayList;
import java.util.Collections;
import java.util.List;
public class DFSMazeSolver {
private static final int[][] DIRECTIONS = { { 0, 1 }, { 1, 0 }, { 0, -1 }, { -1, 0 } };
public List<Coordinate> solve(Maze maze) {
List<Coordinate> path = new ArrayList<>();
if (explore(maze, maze.getEntry()
.getX(),
maze.getEntry()
.getY(),
path)) {
return path;
}
return Collections.emptyList();
}
private boolean explore(Maze maze, int row, int col, List<Coordinate> path) {
if (!maze.isValidLocation(row, col) || maze.isWall(row, col) || maze.isExplored(row, col)) {
return false;
}
path.add(new Coordinate(row, col));
maze.setVisited(row, col, true);
if (maze.isExit(row, col)) {
return true;
}
for (int[] direction : DIRECTIONS) {
Coordinate coordinate = getNextCoordinate(row, col, direction[0], direction[1]);
if (explore(maze, coordinate.getX(), coordinate.getY(), path)) {
return true;
}
}
path.remove(path.size() - 1);
return false;
}
private Coordinate getNextCoordinate(int row, int col, int i, int j) {
return new Coordinate(row + i, col + j);
}
}

View File

@ -0,0 +1,141 @@
package com.baeldung.algorithms.maze.solver;
import java.io.File;
import java.io.FileNotFoundException;
import java.util.Arrays;
import java.util.List;
import java.util.Scanner;
public class Maze {
private static final int ROAD = 0;
private static final int WALL = 1;
private static final int START = 2;
private static final int EXIT = 3;
private static final int PATH = 4;
private int[][] maze;
private boolean[][] visited;
private Coordinate start;
private Coordinate end;
public Maze(File maze) throws FileNotFoundException {
String fileText = "";
try (Scanner input = new Scanner(maze)) {
while (input.hasNextLine()) {
fileText += input.nextLine() + "\n";
}
}
initializeMaze(fileText);
}
private void initializeMaze(String text) {
if (text == null || (text = text.trim()).length() == 0) {
throw new IllegalArgumentException("empty lines data");
}
String[] lines = text.split("[\r]?\n");
maze = new int[lines.length][lines[0].length()];
visited = new boolean[lines.length][lines[0].length()];
for (int row = 0; row < getHeight(); row++) {
if (lines[row].length() != getWidth()) {
throw new IllegalArgumentException("line " + (row + 1) + " wrong length (was " + lines[row].length() + " but should be " + getWidth() + ")");
}
for (int col = 0; col < getWidth(); col++) {
if (lines[row].charAt(col) == '#')
maze[row][col] = WALL;
else if (lines[row].charAt(col) == 'S') {
maze[row][col] = START;
start = new Coordinate(row, col);
} else if (lines[row].charAt(col) == 'E') {
maze[row][col] = EXIT;
end = new Coordinate(row, col);
} else
maze[row][col] = ROAD;
}
}
}
public int getHeight() {
return maze.length;
}
public int getWidth() {
return maze[0].length;
}
public Coordinate getEntry() {
return start;
}
public Coordinate getExit() {
return end;
}
public boolean isExit(int x, int y) {
return x == end.getX() && y == end.getY();
}
public boolean isStart(int x, int y) {
return x == start.getX() && y == start.getY();
}
public boolean isExplored(int row, int col) {
return visited[row][col];
}
public boolean isWall(int row, int col) {
return maze[row][col] == WALL;
}
public void setVisited(int row, int col, boolean value) {
visited[row][col] = value;
}
public boolean isValidLocation(int row, int col) {
if (row < 0 || row >= getHeight() || col < 0 || col >= getWidth()) {
return false;
}
return true;
}
public void printPath(List<Coordinate> path) {
int[][] tempMaze = Arrays.stream(maze)
.map(int[]::clone)
.toArray(int[][]::new);
for (Coordinate coordinate : path) {
if (isStart(coordinate.getX(), coordinate.getY()) || isExit(coordinate.getX(), coordinate.getY())) {
continue;
}
tempMaze[coordinate.getX()][coordinate.getY()] = PATH;
}
System.out.println(toString(tempMaze));
}
public String toString(int[][] maze) {
StringBuilder result = new StringBuilder(getWidth() * (getHeight() + 1));
for (int row = 0; row < getHeight(); row++) {
for (int col = 0; col < getWidth(); col++) {
if (maze[row][col] == ROAD) {
result.append(' ');
} else if (maze[row][col] == WALL) {
result.append('#');
} else if (maze[row][col] == START) {
result.append('S');
} else if (maze[row][col] == EXIT) {
result.append('E');
} else {
result.append('.');
}
}
result.append('\n');
}
return result.toString();
}
public void reset() {
for (int i = 0; i < visited.length; i++)
Arrays.fill(visited[i], false);
}
}

View File

@ -0,0 +1,34 @@
package com.baeldung.algorithms.maze.solver;
import java.io.File;
import java.util.List;
public class MazeDriver {
public static void main(String[] args) throws Exception {
File maze1 = new File("src/main/resources/maze/maze1.txt");
File maze2 = new File("src/main/resources/maze/maze2.txt");
execute(maze1);
execute(maze2);
}
private static void execute(File file) throws Exception {
Maze maze = new Maze(file);
dfs(maze);
bfs(maze);
}
private static void bfs(Maze maze) {
BFSMazeSolver bfs = new BFSMazeSolver();
List<Coordinate> path = bfs.solve(maze);
maze.printPath(path);
maze.reset();
}
private static void dfs(Maze maze) {
DFSMazeSolver dfs = new DFSMazeSolver();
List<Coordinate> path = dfs.solve(maze);
maze.printPath(path);
maze.reset();
}
}

View File

@ -0,0 +1,47 @@
package com.baeldung.algorithms.multiswarm;
/**
* Constants used by the Multi-swarm optimization algorithms.
*
* @author Donato Rimenti
*
*/
public class Constants {
/**
* The inertia factor encourages a particle to continue moving in its
* current direction.
*/
public static final double INERTIA_FACTOR = 0.729;
/**
* The cognitive weight encourages a particle to move toward its historical
* best-known position.
*/
public static final double COGNITIVE_WEIGHT = 1.49445;
/**
* The social weight encourages a particle to move toward the best-known
* position found by any of the particles swarm-mates.
*/
public static final double SOCIAL_WEIGHT = 1.49445;
/**
* The global weight encourages a particle to move toward the best-known
* position found by any particle in any swarm.
*/
public static final double GLOBAL_WEIGHT = 0.3645;
/**
* Upper bound for the random generation. We use it to reduce the
* computation time since we can rawly estimate it.
*/
public static final int PARTICLE_UPPER_BOUND = 10000000;
/**
* Private constructor for utility class.
*/
private Constants() {
}
}

View File

@ -0,0 +1,21 @@
package com.baeldung.algorithms.multiswarm;
/**
* Interface for a fitness function, used to decouple the main algorithm logic
* from the specific problem solution.
*
* @author Donato Rimenti
*
*/
public interface FitnessFunction {
/**
* Returns the fitness of a particle given its position.
*
* @param particlePosition
* the position of the particle
* @return the fitness of the particle
*/
public double getFitness(long[] particlePosition);
}

View File

@ -0,0 +1,227 @@
package com.baeldung.algorithms.multiswarm;
import java.util.Arrays;
import java.util.Random;
/**
* Represents a collection of {@link Swarm}.
*
* @author Donato Rimenti
*
*/
public class Multiswarm {
/**
* The swarms managed by this multiswarm.
*/
private Swarm[] swarms;
/**
* The best position found within all the {@link #swarms}.
*/
private long[] bestPosition;
/**
* The best fitness score found within all the {@link #swarms}.
*/
private double bestFitness = Double.NEGATIVE_INFINITY;
/**
* A random generator.
*/
private Random random = new Random();
/**
* The fitness function used to determine how good is a particle.
*/
private FitnessFunction fitnessFunction;
/**
* Instantiates a new Multiswarm.
*
* @param numSwarms
* the number of {@link #swarms}
* @param particlesPerSwarm
* the number of particle for each {@link #swarms}
* @param fitnessFunction
* the {@link #fitnessFunction}
*/
public Multiswarm(int numSwarms, int particlesPerSwarm, FitnessFunction fitnessFunction) {
this.fitnessFunction = fitnessFunction;
this.swarms = new Swarm[numSwarms];
for (int i = 0; i < numSwarms; i++) {
swarms[i] = new Swarm(particlesPerSwarm);
}
}
/**
* Main loop of the algorithm. Iterates all particles of all
* {@link #swarms}. For each particle, computes the new fitness and checks
* if a new best position has been found among itself, the swarm and all the
* swarms and finally updates the particle position and speed.
*/
public void mainLoop() {
for (Swarm swarm : swarms) {
for (Particle particle : swarm.getParticles()) {
long[] particleOldPosition = particle.getPosition().clone();
// Calculate the particle fitness.
particle.setFitness(fitnessFunction.getFitness(particleOldPosition));
// Check if a new best position has been found for the particle
// itself, within the swarm and the multiswarm.
if (particle.getFitness() > particle.getBestFitness()) {
particle.setBestFitness(particle.getFitness());
particle.setBestPosition(particleOldPosition);
if (particle.getFitness() > swarm.getBestFitness()) {
swarm.setBestFitness(particle.getFitness());
swarm.setBestPosition(particleOldPosition);
if (swarm.getBestFitness() > bestFitness) {
bestFitness = swarm.getBestFitness();
bestPosition = swarm.getBestPosition().clone();
}
}
}
// Updates the particle position by adding the speed to the
// actual position.
long[] position = particle.getPosition();
long[] speed = particle.getSpeed();
position[0] += speed[0];
position[1] += speed[1];
// Updates the particle speed.
speed[0] = getNewParticleSpeedForIndex(particle, swarm, 0);
speed[1] = getNewParticleSpeedForIndex(particle, swarm, 1);
}
}
}
/**
* Computes a new speed for a given particle of a given swarm on a given
* axis. The new speed is computed using the formula:
*
* <pre>
* ({@link Constants#INERTIA_FACTOR} * {@link Particle#getSpeed()}) +
* (({@link Constants#COGNITIVE_WEIGHT} * random(0,1)) * ({@link Particle#getBestPosition()} - {@link Particle#getPosition()})) +
* (({@link Constants#SOCIAL_WEIGHT} * random(0,1)) * ({@link Swarm#getBestPosition()} - {@link Particle#getPosition()})) +
* (({@link Constants#GLOBAL_WEIGHT} * random(0,1)) * ({@link #bestPosition} - {@link Particle#getPosition()}))
* </pre>
*
* @param particle
* the particle whose new speed needs to be computed
* @param swarm
* the swarm which contains the particle
* @param index
* the index of the particle axis whose speeds needs to be
* computed
* @return the new speed of the particle passed on the given axis
*/
private int getNewParticleSpeedForIndex(Particle particle, Swarm swarm, int index) {
return (int) ((Constants.INERTIA_FACTOR * particle.getSpeed()[index])
+ (randomizePercentage(Constants.COGNITIVE_WEIGHT)
* (particle.getBestPosition()[index] - particle.getPosition()[index]))
+ (randomizePercentage(Constants.SOCIAL_WEIGHT)
* (swarm.getBestPosition()[index] - particle.getPosition()[index]))
+ (randomizePercentage(Constants.GLOBAL_WEIGHT)
* (bestPosition[index] - particle.getPosition()[index])));
}
/**
* Returns a random number between 0 and the value passed as argument.
*
* @param value
* the value to randomize
* @return a random value between 0 and the one passed as argument
*/
private double randomizePercentage(double value) {
return random.nextDouble() * value;
}
/**
* Gets the {@link #bestPosition}.
*
* @return the {@link #bestPosition}
*/
public long[] getBestPosition() {
return bestPosition;
}
/**
* Gets the {@link #bestFitness}.
*
* @return the {@link #bestFitness}
*/
public double getBestFitness() {
return bestFitness;
}
/*
* (non-Javadoc)
*
* @see java.lang.Object#hashCode()
*/
@Override
public int hashCode() {
final int prime = 31;
int result = 1;
long temp;
temp = Double.doubleToLongBits(bestFitness);
result = prime * result + (int) (temp ^ (temp >>> 32));
result = prime * result + Arrays.hashCode(bestPosition);
result = prime * result + ((fitnessFunction == null) ? 0 : fitnessFunction.hashCode());
result = prime * result + ((random == null) ? 0 : random.hashCode());
result = prime * result + Arrays.hashCode(swarms);
return result;
}
/*
* (non-Javadoc)
*
* @see java.lang.Object#equals(java.lang.Object)
*/
@Override
public boolean equals(Object obj) {
if (this == obj)
return true;
if (obj == null)
return false;
if (getClass() != obj.getClass())
return false;
Multiswarm other = (Multiswarm) obj;
if (Double.doubleToLongBits(bestFitness) != Double.doubleToLongBits(other.bestFitness))
return false;
if (!Arrays.equals(bestPosition, other.bestPosition))
return false;
if (fitnessFunction == null) {
if (other.fitnessFunction != null)
return false;
} else if (!fitnessFunction.equals(other.fitnessFunction))
return false;
if (random == null) {
if (other.random != null)
return false;
} else if (!random.equals(other.random))
return false;
if (!Arrays.equals(swarms, other.swarms))
return false;
return true;
}
/*
* (non-Javadoc)
*
* @see java.lang.Object#toString()
*/
@Override
public String toString() {
return "Multiswarm [swarms=" + Arrays.toString(swarms) + ", bestPosition=" + Arrays.toString(bestPosition)
+ ", bestFitness=" + bestFitness + ", random=" + random + ", fitnessFunction=" + fitnessFunction + "]";
}
}

View File

@ -0,0 +1,204 @@
package com.baeldung.algorithms.multiswarm;
import java.util.Arrays;
/**
* Represents a particle, the basic component of a {@link Swarm}.
*
* @author Donato Rimenti
*
*/
public class Particle {
/**
* The current position of this particle.
*/
private long[] position;
/**
* The speed of this particle.
*/
private long[] speed;
/**
* The fitness of this particle for the current position.
*/
private double fitness;
/**
* The best position found by this particle.
*/
private long[] bestPosition;
/**
* The best fitness found by this particle.
*/
private double bestFitness = Double.NEGATIVE_INFINITY;
/**
* Instantiates a new Particle.
*
* @param initialPosition
* the initial {@link #position}
* @param initialSpeed
* the initial {@link #speed}
*/
public Particle(long[] initialPosition, long[] initialSpeed) {
this.position = initialPosition;
this.speed = initialSpeed;
}
/**
* Gets the {@link #position}.
*
* @return the {@link #position}
*/
public long[] getPosition() {
return position;
}
/**
* Gets the {@link #speed}.
*
* @return the {@link #speed}
*/
public long[] getSpeed() {
return speed;
}
/**
* Gets the {@link #fitness}.
*
* @return the {@link #fitness}
*/
public double getFitness() {
return fitness;
}
/**
* Gets the {@link #bestPosition}.
*
* @return the {@link #bestPosition}
*/
public long[] getBestPosition() {
return bestPosition;
}
/**
* Gets the {@link #bestFitness}.
*
* @return the {@link #bestFitness}
*/
public double getBestFitness() {
return bestFitness;
}
/**
* Sets the {@link #position}.
*
* @param position
* the new {@link #position}
*/
public void setPosition(long[] position) {
this.position = position;
}
/**
* Sets the {@link #speed}.
*
* @param speed
* the new {@link #speed}
*/
public void setSpeed(long[] speed) {
this.speed = speed;
}
/**
* Sets the {@link #fitness}.
*
* @param fitness
* the new {@link #fitness}
*/
public void setFitness(double fitness) {
this.fitness = fitness;
}
/**
* Sets the {@link #bestPosition}.
*
* @param bestPosition
* the new {@link #bestPosition}
*/
public void setBestPosition(long[] bestPosition) {
this.bestPosition = bestPosition;
}
/**
* Sets the {@link #bestFitness}.
*
* @param bestFitness
* the new {@link #bestFitness}
*/
public void setBestFitness(double bestFitness) {
this.bestFitness = bestFitness;
}
/*
* (non-Javadoc)
*
* @see java.lang.Object#hashCode()
*/
@Override
public int hashCode() {
final int prime = 31;
int result = 1;
long temp;
temp = Double.doubleToLongBits(bestFitness);
result = prime * result + (int) (temp ^ (temp >>> 32));
result = prime * result + Arrays.hashCode(bestPosition);
temp = Double.doubleToLongBits(fitness);
result = prime * result + (int) (temp ^ (temp >>> 32));
result = prime * result + Arrays.hashCode(position);
result = prime * result + Arrays.hashCode(speed);
return result;
}
/*
* (non-Javadoc)
*
* @see java.lang.Object#equals(java.lang.Object)
*/
@Override
public boolean equals(Object obj) {
if (this == obj)
return true;
if (obj == null)
return false;
if (getClass() != obj.getClass())
return false;
Particle other = (Particle) obj;
if (Double.doubleToLongBits(bestFitness) != Double.doubleToLongBits(other.bestFitness))
return false;
if (!Arrays.equals(bestPosition, other.bestPosition))
return false;
if (Double.doubleToLongBits(fitness) != Double.doubleToLongBits(other.fitness))
return false;
if (!Arrays.equals(position, other.position))
return false;
if (!Arrays.equals(speed, other.speed))
return false;
return true;
}
/*
* (non-Javadoc)
*
* @see java.lang.Object#toString()
*/
@Override
public String toString() {
return "Particle [position=" + Arrays.toString(position) + ", speed=" + Arrays.toString(speed) + ", fitness="
+ fitness + ", bestPosition=" + Arrays.toString(bestPosition) + ", bestFitness=" + bestFitness + "]";
}
}

View File

@ -0,0 +1,155 @@
package com.baeldung.algorithms.multiswarm;
import java.util.Arrays;
import java.util.Random;
/**
* Represents a collection of {@link Particle}.
*
* @author Donato Rimenti
*
*/
public class Swarm {
/**
* The particles of this swarm.
*/
private Particle[] particles;
/**
* The best position found within the particles of this swarm.
*/
private long[] bestPosition;
/**
* The best fitness score found within the particles of this swarm.
*/
private double bestFitness = Double.NEGATIVE_INFINITY;
/**
* A random generator.
*/
private Random random = new Random();
/**
* Instantiates a new Swarm.
*
* @param numParticles
* the number of particles of the swarm
*/
public Swarm(int numParticles) {
particles = new Particle[numParticles];
for (int i = 0; i < numParticles; i++) {
long[] initialParticlePosition = { random.nextInt(Constants.PARTICLE_UPPER_BOUND),
random.nextInt(Constants.PARTICLE_UPPER_BOUND) };
long[] initialParticleSpeed = { random.nextInt(Constants.PARTICLE_UPPER_BOUND),
random.nextInt(Constants.PARTICLE_UPPER_BOUND) };
particles[i] = new Particle(initialParticlePosition, initialParticleSpeed);
}
}
/**
* Gets the {@link #particles}.
*
* @return the {@link #particles}
*/
public Particle[] getParticles() {
return particles;
}
/**
* Gets the {@link #bestPosition}.
*
* @return the {@link #bestPosition}
*/
public long[] getBestPosition() {
return bestPosition;
}
/**
* Gets the {@link #bestFitness}.
*
* @return the {@link #bestFitness}
*/
public double getBestFitness() {
return bestFitness;
}
/**
* Sets the {@link #bestPosition}.
*
* @param bestPosition
* the new {@link #bestPosition}
*/
public void setBestPosition(long[] bestPosition) {
this.bestPosition = bestPosition;
}
/**
* Sets the {@link #bestFitness}.
*
* @param bestFitness
* the new {@link #bestFitness}
*/
public void setBestFitness(double bestFitness) {
this.bestFitness = bestFitness;
}
/*
* (non-Javadoc)
*
* @see java.lang.Object#hashCode()
*/
@Override
public int hashCode() {
final int prime = 31;
int result = 1;
long temp;
temp = Double.doubleToLongBits(bestFitness);
result = prime * result + (int) (temp ^ (temp >>> 32));
result = prime * result + Arrays.hashCode(bestPosition);
result = prime * result + Arrays.hashCode(particles);
result = prime * result + ((random == null) ? 0 : random.hashCode());
return result;
}
/*
* (non-Javadoc)
*
* @see java.lang.Object#equals(java.lang.Object)
*/
@Override
public boolean equals(Object obj) {
if (this == obj)
return true;
if (obj == null)
return false;
if (getClass() != obj.getClass())
return false;
Swarm other = (Swarm) obj;
if (Double.doubleToLongBits(bestFitness) != Double.doubleToLongBits(other.bestFitness))
return false;
if (!Arrays.equals(bestPosition, other.bestPosition))
return false;
if (!Arrays.equals(particles, other.particles))
return false;
if (random == null) {
if (other.random != null)
return false;
} else if (!random.equals(other.random))
return false;
return true;
}
/*
* (non-Javadoc)
*
* @see java.lang.Object#toString()
*/
@Override
public String toString() {
return "Swarm [particles=" + Arrays.toString(particles) + ", bestPosition=" + Arrays.toString(bestPosition)
+ ", bestFitness=" + bestFitness + ", random=" + random + "]";
}
}

View File

@ -0,0 +1,75 @@
package com.baeldung.algorithms.numberwordconverter;
import java.math.BigDecimal;
import pl.allegro.finance.tradukisto.MoneyConverters;
public class NumberWordConverter {
public static final String INVALID_INPUT_GIVEN = "Invalid input given";
public static final String[] ones = { "", "one", "two", "three", "four", "five", "six", "seven", "eight", "nine", "ten", "eleven", "twelve", "thirteen", "fourteen", "fifteen", "sixteen", "seventeen", "eighteen", "nineteen" };
public static final String[] tens = {
"", // 0
"", // 1
"twenty", // 2
"thirty", // 3
"forty", // 4
"fifty", // 5
"sixty", // 6
"seventy", // 7
"eighty", // 8
"ninety" // 9
};
public static String getMoneyIntoWords(String input) {
MoneyConverters converter = MoneyConverters.ENGLISH_BANKING_MONEY_VALUE;
return converter.asWords(new BigDecimal(input));
}
public static String getMoneyIntoWords(final double money) {
long dollar = (long) money;
long cents = Math.round((money - dollar) * 100);
if (money == 0D) {
return "";
}
if (money < 0) {
return INVALID_INPUT_GIVEN;
}
String dollarPart = "";
if (dollar > 0) {
dollarPart = convert(dollar) + " dollar" + (dollar == 1 ? "" : "s");
}
String centsPart = "";
if (cents > 0) {
if (dollarPart.length() > 0) {
centsPart = " and ";
}
centsPart += convert(cents) + " cent" + (cents == 1 ? "" : "s");
}
return dollarPart + centsPart;
}
private static String convert(final long n) {
if (n < 0) {
return INVALID_INPUT_GIVEN;
}
if (n < 20) {
return ones[(int) n];
}
if (n < 100) {
return tens[(int) n / 10] + ((n % 10 != 0) ? " " : "") + ones[(int) n % 10];
}
if (n < 1000) {
return ones[(int) n / 100] + " hundred" + ((n % 100 != 0) ? " " : "") + convert(n % 100);
}
if (n < 1_000_000) {
return convert(n / 1000) + " thousand" + ((n % 1000 != 0) ? " " : "") + convert(n % 1000);
}
if (n < 1_000_000_000) {
return convert(n / 1_000_000) + " million" + ((n % 1_000_000 != 0) ? " " : "") + convert(n % 1_000_000);
}
return convert(n / 1_000_000_000) + " billion" + ((n % 1_000_000_000 != 0) ? " " : "") + convert(n % 1_000_000_000);
}
}

View File

@ -0,0 +1,59 @@
package com.baeldung.algorithms.prime;
import java.util.Arrays;
import java.util.LinkedList;
import java.util.List;
import java.util.stream.Collectors;
import java.util.stream.IntStream;
public class PrimeGenerator {
public static List<Integer> sieveOfEratosthenes(int n) {
final boolean prime[] = new boolean[n + 1];
Arrays.fill(prime, true);
for (int p = 2; p * p <= n; p++) {
if (prime[p]) {
for (int i = p * 2; i <= n; i += p)
prime[i] = false;
}
}
final List<Integer> primes = new LinkedList<>();
for (int i = 2; i <= n; i++) {
if (prime[i])
primes.add(i);
}
return primes;
}
public static List<Integer> primeNumbersBruteForce(int max) {
final List<Integer> primeNumbers = new LinkedList<Integer>();
for (int i = 2; i <= max; i++) {
if (isPrimeBruteForce(i)) {
primeNumbers.add(i);
}
}
return primeNumbers;
}
private static boolean isPrimeBruteForce(int x) {
for (int i = 2; i < x; i++) {
if (x % i == 0) {
return false;
}
}
return true;
}
public static List<Integer> primeNumbersTill(int max) {
return IntStream.rangeClosed(2, max)
.filter(x -> isPrime(x))
.boxed()
.collect(Collectors.toList());
}
private static boolean isPrime(int x) {
return IntStream.rangeClosed(2, (int) (Math.sqrt(x)))
.allMatch(n -> x % n != 0);
}
}

View File

@ -0,0 +1,104 @@
package com.baeldung.algorithms.sudoku;
import java.util.stream.IntStream;
public class BacktrackingAlgorithm {
private static final int BOARD_SIZE = 9;
private static final int SUBSECTION_SIZE = 3;
private static final int BOARD_START_INDEX = 0;
private static final int NO_VALUE = 0;
private static final int MIN_VALUE = 1;
private static final int MAX_VALUE = 9;
private static int[][] board = {
{8, 0, 0, 0, 0, 0, 0, 0, 0},
{0, 0, 3, 6, 0, 0, 0, 0, 0},
{0, 7, 0, 0, 9, 0, 2, 0, 0},
{0, 5, 0, 0, 0, 7, 0, 0, 0},
{0, 0, 0, 0, 4, 5, 7, 0, 0},
{0, 0, 0, 1, 0, 0, 0, 3, 0},
{0, 0, 1, 0, 0, 0, 0, 6, 8},
{0, 0, 8, 5, 0, 0, 0, 1, 0},
{0, 9, 0, 0, 0, 0, 4, 0, 0}
};
public static void main(String[] args) {
BacktrackingAlgorithm solver = new BacktrackingAlgorithm();
solver.solve(board);
solver.printBoard();
}
private void printBoard() {
for (int row = BOARD_START_INDEX; row < BOARD_SIZE; row++) {
for (int column = BOARD_START_INDEX; column < BOARD_SIZE; column++) {
System.out.print(board[row][column] + " ");
}
System.out.println();
}
}
private boolean solve(int[][] board) {
for (int row = BOARD_START_INDEX; row < BOARD_SIZE; row++) {
for (int column = BOARD_START_INDEX; column < BOARD_SIZE; column++) {
if (board[row][column] == NO_VALUE) {
for (int k = MIN_VALUE; k <= MAX_VALUE; k++) {
board[row][column] = k;
if (isValid(board, row, column) && solve(board)) {
return true;
}
board[row][column] = NO_VALUE;
}
return false;
}
}
}
return true;
}
private boolean isValid(int[][] board, int row, int column) {
return rowConstraint(board, row) &&
columnConstraint(board, column) &&
subsectionConstraint(board, row, column);
}
private boolean subsectionConstraint(int[][] board, int row, int column) {
boolean[] constraint = new boolean[BOARD_SIZE];
int subsectionRowStart = (row / SUBSECTION_SIZE) * SUBSECTION_SIZE;
int subsectionRowEnd = subsectionRowStart + SUBSECTION_SIZE;
int subsectionColumnStart = (column / SUBSECTION_SIZE) * SUBSECTION_SIZE;
int subsectionColumnEnd = subsectionColumnStart + SUBSECTION_SIZE;
for (int r = subsectionRowStart; r < subsectionRowEnd; r++) {
for (int c = subsectionColumnStart; c < subsectionColumnEnd; c++) {
if (!checkConstraint(board, r, constraint, c)) return false;
}
}
return true;
}
private boolean columnConstraint(int[][] board, int column) {
boolean[] constraint = new boolean[BOARD_SIZE];
return IntStream.range(BOARD_START_INDEX, BOARD_SIZE)
.allMatch(row -> checkConstraint(board, row, constraint, column));
}
private boolean rowConstraint(int[][] board, int row) {
boolean[] constraint = new boolean[BOARD_SIZE];
return IntStream.range(BOARD_START_INDEX, BOARD_SIZE)
.allMatch(column -> checkConstraint(board, row, constraint, column));
}
private boolean checkConstraint(int[][] board, int row, boolean[] constraint, int column) {
if (board[row][column] != NO_VALUE) {
if (!constraint[board[row][column] - 1]) {
constraint[board[row][column] - 1] = true;
} else {
return false;
}
}
return true;
}
}

View File

@ -0,0 +1,33 @@
package com.baeldung.algorithms.sudoku;
class ColumnNode extends DancingNode {
int size;
String name;
ColumnNode(String n) {
super();
size = 0;
name = n;
C = this;
}
void cover() {
unlinkLR();
for (DancingNode i = this.D; i != this; i = i.D) {
for (DancingNode j = i.R; j != i; j = j.R) {
j.unlinkUD();
j.C.size--;
}
}
}
void uncover() {
for (DancingNode i = this.U; i != this; i = i.U) {
for (DancingNode j = i.L; j != i; j = j.L) {
j.C.size++;
j.relinkUD();
}
}
relinkLR();
}
}

View File

@ -0,0 +1,133 @@
package com.baeldung.algorithms.sudoku;
import java.util.ArrayList;
import java.util.LinkedList;
import java.util.List;
public class DancingLinks {
private ColumnNode header;
private List<DancingNode> answer;
private void search(int k) {
if (header.R == header) {
handleSolution(answer);
} else {
ColumnNode c = selectColumnNodeHeuristic();
c.cover();
for (DancingNode r = c.D; r != c; r = r.D) {
answer.add(r);
for (DancingNode j = r.R; j != r; j = j.R) {
j.C.cover();
}
search(k + 1);
r = answer.remove(answer.size() - 1);
c = r.C;
for (DancingNode j = r.L; j != r; j = j.L) {
j.C.uncover();
}
}
c.uncover();
}
}
private ColumnNode selectColumnNodeHeuristic() {
int min = Integer.MAX_VALUE;
ColumnNode ret = null;
for (ColumnNode c = (ColumnNode) header.R; c != header; c = (ColumnNode) c.R) {
if (c.size < min) {
min = c.size;
ret = c;
}
}
return ret;
}
private ColumnNode makeDLXBoard(boolean[][] grid) {
final int COLS = grid[0].length;
ColumnNode headerNode = new ColumnNode("header");
List<ColumnNode> columnNodes = new ArrayList<>();
for (int i = 0; i < COLS; i++) {
ColumnNode n = new ColumnNode(Integer.toString(i));
columnNodes.add(n);
headerNode = (ColumnNode) headerNode.hookRight(n);
}
headerNode = headerNode.R.C;
for (boolean[] aGrid : grid) {
DancingNode prev = null;
for (int j = 0; j < COLS; j++) {
if (aGrid[j]) {
ColumnNode col = columnNodes.get(j);
DancingNode newNode = new DancingNode(col);
if (prev == null)
prev = newNode;
col.U.hookDown(newNode);
prev = prev.hookRight(newNode);
col.size++;
}
}
}
headerNode.size = COLS;
return headerNode;
}
DancingLinks(boolean[][] cover) {
header = makeDLXBoard(cover);
}
public void runSolver() {
answer = new LinkedList<>();
search(0);
}
private void handleSolution(List<DancingNode> answer) {
int[][] result = parseBoard(answer);
printSolution(result);
}
private int size = 9;
private int[][] parseBoard(List<DancingNode> answer) {
int[][] result = new int[size][size];
for (DancingNode n : answer) {
DancingNode rcNode = n;
int min = Integer.parseInt(rcNode.C.name);
for (DancingNode tmp = n.R; tmp != n; tmp = tmp.R) {
int val = Integer.parseInt(tmp.C.name);
if (val < min) {
min = val;
rcNode = tmp;
}
}
int ans1 = Integer.parseInt(rcNode.C.name);
int ans2 = Integer.parseInt(rcNode.R.C.name);
int r = ans1 / size;
int c = ans1 % size;
int num = (ans2 % size) + 1;
result[r][c] = num;
}
return result;
}
private static void printSolution(int[][] result) {
int size = result.length;
for (int[] aResult : result) {
StringBuilder ret = new StringBuilder();
for (int j = 0; j < size; j++) {
ret.append(aResult[j]).append(" ");
}
System.out.println(ret);
}
System.out.println();
}
}

View File

@ -0,0 +1,121 @@
package com.baeldung.algorithms.sudoku;
import java.util.Arrays;
public class DancingLinksAlgorithm {
private static final int BOARD_SIZE = 9;
private static final int SUBSECTION_SIZE = 3;
private static final int NO_VALUE = 0;
private static final int CONSTRAINTS = 4;
private static final int MIN_VALUE = 1;
private static final int MAX_VALUE = 9;
private static final int COVER_START_INDEX = 1;
private static int[][] board = {
{8, 0, 0, 0, 0, 0, 0, 0, 0},
{0, 0, 3, 6, 0, 0, 0, 0, 0},
{0, 7, 0, 0, 9, 0, 2, 0, 0},
{0, 5, 0, 0, 0, 7, 0, 0, 0},
{0, 0, 0, 0, 4, 5, 7, 0, 0},
{0, 0, 0, 1, 0, 0, 0, 3, 0},
{0, 0, 1, 0, 0, 0, 0, 6, 8},
{0, 0, 8, 5, 0, 0, 0, 1, 0},
{0, 9, 0, 0, 0, 0, 4, 0, 0}
};
public static void main(String[] args) {
DancingLinksAlgorithm solver = new DancingLinksAlgorithm();
solver.solve(board);
}
private void solve(int[][] board) {
boolean[][] cover = initializeExactCoverBoard(board);
DancingLinks dlx = new DancingLinks(cover);
dlx.runSolver();
}
private int getIndex(int row, int column, int num) {
return (row - 1) * BOARD_SIZE * BOARD_SIZE + (column - 1) * BOARD_SIZE + (num - 1);
}
private boolean[][] createExactCoverBoard() {
boolean[][] coverBoard = new boolean[BOARD_SIZE * BOARD_SIZE * MAX_VALUE][BOARD_SIZE * BOARD_SIZE * CONSTRAINTS];
int hBase = 0;
hBase = checkCellConstraint(coverBoard, hBase);
hBase = checkRowConstraint(coverBoard, hBase);
hBase = checkColumnConstraint(coverBoard, hBase);
checkSubsectionConstraint(coverBoard, hBase);
return coverBoard;
}
private int checkSubsectionConstraint(boolean[][] coverBoard, int hBase) {
for (int row = COVER_START_INDEX; row <= BOARD_SIZE; row += SUBSECTION_SIZE) {
for (int column = COVER_START_INDEX; column <= BOARD_SIZE; column += SUBSECTION_SIZE) {
for (int n = COVER_START_INDEX; n <= BOARD_SIZE; n++, hBase++) {
for (int rowDelta = 0; rowDelta < SUBSECTION_SIZE; rowDelta++) {
for (int columnDelta = 0; columnDelta < SUBSECTION_SIZE; columnDelta++) {
int index = getIndex(row + rowDelta, column + columnDelta, n);
coverBoard[index][hBase] = true;
}
}
}
}
}
return hBase;
}
private int checkColumnConstraint(boolean[][] coverBoard, int hBase) {
for (int column = COVER_START_INDEX; column <= BOARD_SIZE; column++) {
for (int n = COVER_START_INDEX; n <= BOARD_SIZE; n++, hBase++) {
for (int row = COVER_START_INDEX; row <= BOARD_SIZE; row++) {
int index = getIndex(row, column, n);
coverBoard[index][hBase] = true;
}
}
}
return hBase;
}
private int checkRowConstraint(boolean[][] coverBoard, int hBase) {
for (int row = COVER_START_INDEX; row <= BOARD_SIZE; row++) {
for (int n = COVER_START_INDEX; n <= BOARD_SIZE; n++, hBase++) {
for (int column = COVER_START_INDEX; column <= BOARD_SIZE; column++) {
int index = getIndex(row, column, n);
coverBoard[index][hBase] = true;
}
}
}
return hBase;
}
private int checkCellConstraint(boolean[][] coverBoard, int hBase) {
for (int row = COVER_START_INDEX; row <= BOARD_SIZE; row++) {
for (int column = COVER_START_INDEX; column <= BOARD_SIZE; column++, hBase++) {
for (int n = COVER_START_INDEX; n <= BOARD_SIZE; n++) {
int index = getIndex(row, column, n);
coverBoard[index][hBase] = true;
}
}
}
return hBase;
}
private boolean[][] initializeExactCoverBoard(int[][] board) {
boolean[][] coverBoard = createExactCoverBoard();
for (int row = COVER_START_INDEX; row <= BOARD_SIZE; row++) {
for (int column = COVER_START_INDEX; column <= BOARD_SIZE; column++) {
int n = board[row - 1][column - 1];
if (n != NO_VALUE) {
for (int num = MIN_VALUE; num <= MAX_VALUE; num++) {
if (num != n) {
Arrays.fill(coverBoard[getIndex(row, column, num)], false);
}
}
}
}
}
return coverBoard;
}
}

View File

@ -0,0 +1,50 @@
package com.baeldung.algorithms.sudoku;
class DancingNode {
DancingNode L, R, U, D;
ColumnNode C;
DancingNode hookDown(DancingNode node) {
assert (this.C == node.C);
node.D = this.D;
node.D.U = node;
node.U = this;
this.D = node;
return node;
}
DancingNode hookRight(DancingNode node) {
node.R = this.R;
node.R.L = node;
node.L = this;
this.R = node;
return node;
}
void unlinkLR() {
this.L.R = this.R;
this.R.L = this.L;
}
void relinkLR() {
this.L.R = this.R.L = this;
}
void unlinkUD() {
this.U.D = this.D;
this.D.U = this.U;
}
void relinkUD() {
this.U.D = this.D.U = this;
}
DancingNode() {
L = R = U = D = this;
}
DancingNode(ColumnNode c) {
this();
C = c;
}
}

View File

@ -0,0 +1,12 @@
S ########
# #
# ### ## #
# # # #
# # # # #
# ## #####
# # #
# # # # #
##### ####
# # E
# # # #
##########

View File

@ -0,0 +1,22 @@
S ##########################
# # # #
# # #### ############### #
# # # # # #
# # #### # # ###############
# # # # # # #
# # # #### ### ########### #
# # # # # #
# ################## #
######### # # # # #
# # #### # ####### # #
# # ### ### # # # # #
# # ## # ##### # #
##### ####### # # # # #
# # ## ## #### # #
# ##### ####### # #
# # ############
####### ######### # #
# # ######## #
# ####### ###### ## # E
# # # ## #
############################

View File

@ -0,0 +1,57 @@
package com.baeldung.algorithms.kthlargest;
import static org.assertj.core.api.Assertions.*;
import org.junit.Before;
import org.junit.Test;
public class FindKthLargestUnitTest {
private FindKthLargest findKthLargest;
private Integer[] arr = { 3, 7, 1, 2, 8, 10, 4, 5, 6, 9 };
@Before
public void setup() {
findKthLargest = new FindKthLargest();
}
@Test
public void givenIntArray_whenFindKthLargestBySorting_thenGetResult() {
int k = 3;
assertThat(findKthLargest.findKthLargestBySorting(arr, k)).isEqualTo(8);
}
@Test
public void givenIntArray_whenFindKthLargestBySortingDesc_thenGetResult() {
int k = 3;
assertThat(findKthLargest.findKthLargestBySortingDesc(arr, k)).isEqualTo(8);
}
@Test
public void givenIntArray_whenFindKthLargestByQuickSelect_thenGetResult() {
int k = 3;
int kthLargest = arr.length - k;
assertThat(findKthLargest.findKthElementByQuickSelect(arr, 0, arr.length - 1, kthLargest)).isEqualTo(8);
}
@Test
public void givenIntArray_whenFindKthElementByQuickSelectIterative_thenGetResult() {
int k = 3;
int kthLargest = arr.length - k;
assertThat(findKthLargest.findKthElementByQuickSelectWithIterativePartition(arr, 0, arr.length - 1, kthLargest)).isEqualTo(8);
}
@Test
public void givenIntArray_whenFindKthSmallestByQuickSelect_thenGetResult() {
int k = 3;
assertThat(findKthLargest.findKthElementByQuickSelect(arr, 0, arr.length - 1, k - 1)).isEqualTo(3);
}
@Test
public void givenIntArray_whenFindKthLargestByRandomizedQuickSelect_thenGetResult() {
int k = 3;
int kthLargest = arr.length - k;
assertThat(findKthLargest.findKthElementByRandomizedQuickSelect(arr, 0, arr.length - 1, kthLargest)).isEqualTo(8);
}
}

View File

@ -0,0 +1,84 @@
package com.baeldung.algorithms.moneywords;
import static org.junit.Assert.assertEquals;
import org.junit.Test;
import com.baeldung.algorithms.numberwordconverter.NumberWordConverter;
public class NumberWordConverterTest {
@Test
public void whenMoneyNegative_thenReturnInvalidInput() {
assertEquals(NumberWordConverter.INVALID_INPUT_GIVEN, NumberWordConverter.getMoneyIntoWords(-13));
}
@Test
public void whenZeroDollarsGiven_thenReturnEmptyString() {
assertEquals("", NumberWordConverter.getMoneyIntoWords(0));
}
@Test
public void whenOnlyDollarsGiven_thenReturnWords() {
assertEquals("one dollar", NumberWordConverter.getMoneyIntoWords(1));
}
@Test
public void whenOnlyCentsGiven_thenReturnWords() {
assertEquals("sixty cents", NumberWordConverter.getMoneyIntoWords(0.6));
}
@Test
public void whenAlmostAMillioDollarsGiven_thenReturnWords() {
String expectedResult = "nine hundred ninety nine thousand nine hundred ninety nine dollars";
assertEquals(expectedResult, NumberWordConverter.getMoneyIntoWords(999_999));
}
@Test
public void whenThirtyMillionDollarsGiven_thenReturnWords() {
String expectedResult = "thirty three million three hundred forty eight thousand nine hundred seventy eight dollars";
assertEquals(expectedResult, NumberWordConverter.getMoneyIntoWords(33_348_978));
}
@Test
public void whenTwoBillionDollarsGiven_thenReturnWords() {
String expectedResult = "two billion one hundred thirty three million two hundred forty seven thousand eight hundred ten dollars";
assertEquals(expectedResult, NumberWordConverter.getMoneyIntoWords(2_133_247_810));
}
@Test
public void whenGivenDollarsAndCents_thenReturnWords() {
String expectedResult = "nine hundred twenty four dollars and sixty cents";
assertEquals(expectedResult, NumberWordConverter.getMoneyIntoWords(924.6));
}
@Test
public void whenOneDollarAndNoCents_thenReturnDollarSingular() {
assertEquals("one dollar", NumberWordConverter.getMoneyIntoWords(1));
}
@Test
public void whenNoDollarsAndOneCent_thenReturnCentSingular() {
assertEquals("one cent", NumberWordConverter.getMoneyIntoWords(0.01));
}
@Test
public void whenNoDollarsAndTwoCents_thenReturnCentsPlural() {
assertEquals("two cents", NumberWordConverter.getMoneyIntoWords(0.02));
}
@Test
public void whenNoDollarsAndNinetyNineCents_thenReturnWords() {
assertEquals("ninety nine cents", NumberWordConverter.getMoneyIntoWords(0.99));
}
@Test
public void whenNoDollarsAndNineFiveNineCents_thenCorrectRounding() {
assertEquals("ninety six cents", NumberWordConverter.getMoneyIntoWords(0.959));
}
@Test
public void whenGivenDollarsAndCents_thenReturnWordsVersionTwo() {
assertEquals("three hundred ten £ 00/100", NumberWordConverter.getMoneyIntoWords("310"));
}
}

View File

@ -0,0 +1,52 @@
package com.baeldung.algorithms.multiswarm;
/**
* Specific fitness function implementation to solve the League of Legends
* problem. This is the problem statement: <br>
* <br>
* In League of Legends, a player's Effective Health when defending against
* physical damage is given by E=H(100+A)/100, where H is health and A is armor.
* Health costs 2.5 gold per unit, and Armor costs 18 gold per unit. You have
* 3600 gold, and you need to optimize the effectiveness E of your health and
* armor to survive as long as possible against the enemy team's attacks. How
* much of each should you buy? <br>
* <br>
*
* @author Donato Rimenti
*
*/
public class LolFitnessFunction implements FitnessFunction {
/*
* (non-Javadoc)
*
* @see
* com.baeldung.algorithms.multiswarm.FitnessFunction#getFitness(long[])
*/
@Override
public double getFitness(long[] particlePosition) {
long health = particlePosition[0];
long armor = particlePosition[1];
// No negatives values accepted.
if (health < 0 && armor < 0) {
return -(health * armor);
} else if (health < 0) {
return health;
} else if (armor < 0) {
return armor;
}
// Checks if the solution is actually feasible provided our gold.
double cost = (health * 2.5) + (armor * 18);
if (cost > 3600) {
return 3600 - cost;
} else {
// Check how good is the solution.
long fitness = (health * (100 + armor)) / 100;
return fitness;
}
}
}

View File

@ -0,0 +1,54 @@
package com.baeldung.algorithms.multiswarm;
import org.junit.Assert;
import org.junit.Rule;
import org.junit.Test;
import com.baeldung.algorithms.support.MayFailRule;
/**
* Test for {@link Multiswarm}.
*
* @author Donato Rimenti
*
*/
public class MultiswarmUnitTest {
/**
* Rule for handling expected failures. We use this since this test may
* actually fail due to bad luck in the random generation.
*/
@Rule
public MayFailRule mayFailRule = new MayFailRule();
/**
* Tests the multiswarm algorithm with a generic problem. The problem is the
* following: <br>
* <br>
* In League of Legends, a player's Effective Health when defending against
* physical damage is given by E=H(100+A)/100, where H is health and A is
* armor. Health costs 2.5 gold per unit, and Armor costs 18 gold per unit.
* You have 3600 gold, and you need to optimize the effectiveness E of your
* health and armor to survive as long as possible against the enemy team's
* attacks. How much of each should you buy? <br>
* <br>
* The solution is H = 1080, A = 50 for a total fitness of 1620. Tested with
* 50 swarms each with 1000 particles.
*/
@Test
public void givenMultiswarm_whenThousandIteration_thenSolutionFound() {
Multiswarm multiswarm = new Multiswarm(50, 1000, new LolFitnessFunction());
// Iterates 1000 times through the main loop and prints the result.
for (int i = 0; i < 1000; i++) {
multiswarm.mainLoop();
}
System.out.println("Best fitness found: " + multiswarm.getBestFitness() + "[" + multiswarm.getBestPosition()[0]
+ "," + multiswarm.getBestPosition()[1] + "]");
Assert.assertEquals(1080, multiswarm.getBestPosition()[0]);
Assert.assertEquals(50, multiswarm.getBestPosition()[1]);
Assert.assertEquals(1620, (int) multiswarm.getBestFitness());
}
}

View File

@ -0,0 +1,28 @@
package com.baeldung.algorithms.prime;
import static com.baeldung.algorithms.prime.PrimeGenerator.*;
import java.util.Arrays;
import java.util.List;
import org.junit.Test;
import static org.junit.Assert.*;
public class PrimeGeneratorTest {
@Test
public void whenBruteForced_returnsSuccessfully() {
final List<Integer> primeNumbers = primeNumbersBruteForce(20);
assertEquals(Arrays.asList(new Integer[] { 2, 3, 5, 7, 11, 13, 17, 19 }), primeNumbers);
}
@Test
public void whenOptimized_returnsSuccessfully() {
final List<Integer> primeNumbers = primeNumbersTill(20);
assertEquals(Arrays.asList(new Integer[] { 2, 3, 5, 7, 11, 13, 17, 19 }), primeNumbers);
}
@Test
public void whenSieveOfEratosthenes_returnsSuccessfully() {
final List<Integer> primeNumbers = sieveOfEratosthenes(20);
assertEquals(Arrays.asList(new Integer[] { 2, 3, 5, 7, 11, 13, 17, 19 }), primeNumbers);
}
}

View File

@ -0,0 +1,38 @@
package com.baeldung.algorithms.support;
import org.junit.Rule;
import org.junit.rules.TestRule;
import org.junit.runner.Description;
import org.junit.runners.model.Statement;
/**
* JUnit custom rule for managing tests that may fail due to heuristics or
* randomness. In order to use this, just instantiate this object as a public
* field inside the test class and annotate it with {@link Rule}.
*
* @author Donato Rimenti
*
*/
public class MayFailRule implements TestRule {
/*
* (non-Javadoc)
*
* @see org.junit.rules.TestRule#apply(org.junit.runners.model.Statement,
* org.junit.runner.Description)
*/
@Override
public Statement apply(Statement base, Description description) {
return new Statement() {
@Override
public void evaluate() throws Throwable {
try {
base.evaluate();
} catch (Throwable e) {
// Ignore the exception since we expect this.
}
}
};
}
}

View File

@ -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>

View File

@ -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>

76
apache-curator/pom.xml Normal file
View File

@ -0,0 +1,76 @@
<project xmlns="http://maven.apache.org/POM/4.0.0" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd">
<modelVersion>4.0.0</modelVersion>
<artifactId>apache-curator</artifactId>
<version>0.0.1-SNAPSHOT</version>
<packaging>jar</packaging>
<parent>
<groupId>com.baeldung</groupId>
<artifactId>parent-modules</artifactId>
<version>1.0.0-SNAPSHOT</version>
</parent>
<properties>
<curator.version>4.0.1</curator.version>
<zookeeper.version>3.4.11</zookeeper.version>
<jackson-databind.version>2.9.4</jackson-databind.version>
<!-- testing -->
<assertj.version>3.6.1</assertj.version>
<avaitility.version>1.7.0</avaitility.version>
</properties>
<dependencies>
<!-- curator -->
<dependency>
<groupId>org.apache.curator</groupId>
<artifactId>curator-x-async</artifactId>
<version>${curator.version}</version>
<exclusions>
<exclusion>
<groupId>org.apache.zookeeper</groupId>
<artifactId>zookeeper</artifactId>
</exclusion>
</exclusions>
</dependency>
<dependency>
<groupId>org.apache.curator</groupId>
<artifactId>curator-recipes</artifactId>
<version>${curator.version}</version>
</dependency>
<dependency>
<groupId>org.apache.zookeeper</groupId>
<artifactId>zookeeper</artifactId>
<version>${zookeeper.version}</version>
</dependency>
<!-- utils -->
<dependency>
<groupId>com.fasterxml.jackson.core</groupId>
<artifactId>jackson-databind</artifactId>
<version>${jackson-databind.version}</version>
</dependency>
<!-- test scoped -->
<dependency>
<groupId>org.assertj</groupId>
<artifactId>assertj-core</artifactId>
<version>${assertj.version}</version>
<scope>test</scope>
</dependency>
<dependency>
<groupId>com.jayway.awaitility</groupId>
<artifactId>awaitility</artifactId>
<version>${avaitility.version}</version>
<scope>test</scope>
</dependency>
</dependencies>
</project>

View File

@ -0,0 +1,31 @@
package com.baeldung.apache.curator.modeled;
public class HostConfig {
private String hostname;
private int port;
public HostConfig() {
}
public HostConfig(String hostname, int port) {
this.hostname = hostname;
this.port = port;
}
public int getPort() {
return port;
}
public void setPort(int port) {
this.port = port;
}
public String getHostname() {
return hostname;
}
public void setHostname(String hostname) {
this.hostname = hostname;
}
}

View File

@ -0,0 +1,22 @@
package com.baeldung.apache.curator;
import org.apache.curator.RetryPolicy;
import org.apache.curator.framework.CuratorFramework;
import org.apache.curator.framework.CuratorFrameworkFactory;
import org.apache.curator.retry.RetryNTimes;
import org.junit.Before;
public abstract class BaseTest {
@Before
public void setup() {
org.apache.log4j.BasicConfigurator.configure();
}
protected CuratorFramework newClient() {
int sleepMsBetweenRetries = 100;
int maxRetries = 3;
RetryPolicy retryPolicy = new RetryNTimes(maxRetries, sleepMsBetweenRetries);
return CuratorFrameworkFactory.newClient("127.0.0.1:2181", retryPolicy);
}
}

View File

@ -0,0 +1,89 @@
package com.baeldung.apache.curator.configuration;
import static com.jayway.awaitility.Awaitility.await;
import static org.assertj.core.api.Assertions.assertThat;
import java.util.ArrayList;
import java.util.List;
import java.util.UUID;
import java.util.concurrent.atomic.AtomicBoolean;
import org.apache.curator.framework.CuratorFramework;
import org.apache.curator.x.async.AsyncCuratorFramework;
import org.junit.Test;
import com.baeldung.apache.curator.BaseTest;
public class ConfigurationManagementManualTest extends BaseTest {
private static final String KEY_FORMAT = "/%s";
@Test
public void givenPath_whenCreateKey_thenValueIsStored() throws Exception {
try (CuratorFramework client = newClient()) {
client.start();
AsyncCuratorFramework async = AsyncCuratorFramework.wrap(client);
String key = getKey();
String expected = "my_value";
// Create key nodes structure
client.create()
.forPath(key);
// Set data value for our key
async.setData()
.forPath(key, expected.getBytes());
// Get data value
AtomicBoolean isEquals = new AtomicBoolean();
async.getData()
.forPath(key)
.thenAccept(
data -> isEquals.set(new String(data).equals(expected)));
await().until(() -> assertThat(isEquals.get()).isTrue());
}
}
@Test
public void givenPath_whenWatchAKeyAndStoreAValue_thenWatcherIsTriggered()
throws Exception {
try (CuratorFramework client = newClient()) {
client.start();
AsyncCuratorFramework async = AsyncCuratorFramework.wrap(client);
String key = getKey();
String expected = "my_value";
// Create key structure
async.create()
.forPath(key);
List<String> changes = new ArrayList<>();
// Watch data value
async.watched()
.getData()
.forPath(key)
.event()
.thenAccept(watchedEvent -> {
try {
changes.add(new String(client.getData()
.forPath(watchedEvent.getPath())));
} catch (Exception e) {
// fail ...
}
});
// Set data value for our key
async.setData()
.forPath(key, expected.getBytes());
await().until(() -> assertThat(changes.size() > 0).isTrue());
}
}
private String getKey() {
return String.format(KEY_FORMAT, UUID.randomUUID()
.toString());
}
}

View File

@ -0,0 +1,79 @@
package com.baeldung.apache.curator.connection;
import static com.jayway.awaitility.Awaitility.await;
import static org.assertj.core.api.Assertions.assertThat;
import java.util.concurrent.atomic.AtomicBoolean;
import org.apache.curator.RetryPolicy;
import org.apache.curator.framework.CuratorFramework;
import org.apache.curator.framework.CuratorFrameworkFactory;
import org.apache.curator.retry.RetryNTimes;
import org.apache.curator.x.async.AsyncCuratorFramework;
import org.junit.Test;
public class ConnectionManagementManualTest {
@Test
public void givenRunningZookeeper_whenOpenConnection_thenClientIsOpened()
throws Exception {
int sleepMsBetweenRetries = 100;
int maxRetries = 3;
RetryPolicy retryPolicy = new RetryNTimes(maxRetries,
sleepMsBetweenRetries);
try (CuratorFramework client = CuratorFrameworkFactory
.newClient("127.0.0.1:2181", retryPolicy)) {
client.start();
assertThat(client.checkExists()
.forPath("/")).isNotNull();
}
}
@Test
public void givenRunningZookeeper_whenOpenConnectionUsingAsyncNotBlocking_thenClientIsOpened()
throws InterruptedException {
int sleepMsBetweenRetries = 100;
int maxRetries = 3;
RetryPolicy retryPolicy = new RetryNTimes(maxRetries,
sleepMsBetweenRetries);
try (CuratorFramework client = CuratorFrameworkFactory
.newClient("127.0.0.1:2181", retryPolicy)) {
client.start();
AsyncCuratorFramework async = AsyncCuratorFramework.wrap(client);
AtomicBoolean exists = new AtomicBoolean(false);
async.checkExists()
.forPath("/")
.thenAcceptAsync(s -> exists.set(s != null));
await().until(() -> assertThat(exists.get()).isTrue());
}
}
@Test
public void givenRunningZookeeper_whenOpenConnectionUsingAsyncBlocking_thenClientIsOpened()
throws InterruptedException {
int sleepMsBetweenRetries = 100;
int maxRetries = 3;
RetryPolicy retryPolicy = new RetryNTimes(maxRetries,
sleepMsBetweenRetries);
try (CuratorFramework client = CuratorFrameworkFactory
.newClient("127.0.0.1:2181", retryPolicy)) {
client.start();
AsyncCuratorFramework async = AsyncCuratorFramework.wrap(client);
AtomicBoolean exists = new AtomicBoolean(false);
async.checkExists()
.forPath("/")
.thenAccept(s -> exists.set(s != null));
await().until(() -> assertThat(exists.get()).isTrue());
}
}
}

View File

@ -0,0 +1,49 @@
package com.baeldung.apache.curator.modeled;
import static org.assertj.core.api.Assertions.assertThat;
import static org.assertj.core.api.Assertions.fail;
import org.apache.curator.framework.CuratorFramework;
import org.apache.curator.x.async.AsyncCuratorFramework;
import org.apache.curator.x.async.modeled.JacksonModelSerializer;
import org.apache.curator.x.async.modeled.ModelSpec;
import org.apache.curator.x.async.modeled.ModeledFramework;
import org.apache.curator.x.async.modeled.ZPath;
import org.junit.Test;
import com.baeldung.apache.curator.BaseTest;
public class ModelTypedExamplesManualTest extends BaseTest {
@Test
public void givenPath_whenStoreAModel_thenNodesAreCreated()
throws InterruptedException {
ModelSpec<HostConfig> mySpec = ModelSpec
.builder(ZPath.parseWithIds("/config/dev"),
JacksonModelSerializer.build(HostConfig.class))
.build();
try (CuratorFramework client = newClient()) {
client.start();
AsyncCuratorFramework async = AsyncCuratorFramework.wrap(client);
ModeledFramework<HostConfig> modeledClient = ModeledFramework
.wrap(async, mySpec);
modeledClient.set(new HostConfig("host-name", 8080));
modeledClient.read()
.whenComplete((value, e) -> {
if (e != null) {
fail("Cannot read host config", e);
} else {
assertThat(value).isNotNull();
assertThat(value.getHostname()).isEqualTo("host-name");
assertThat(value.getPort()).isEqualTo(8080);
}
});
}
}
}

View File

@ -0,0 +1,74 @@
package com.baeldung.apache.curator.recipes;
import static org.assertj.core.api.Assertions.assertThat;
import org.apache.curator.framework.CuratorFramework;
import org.apache.curator.framework.recipes.leader.LeaderSelector;
import org.apache.curator.framework.recipes.leader.LeaderSelectorListener;
import org.apache.curator.framework.recipes.locks.InterProcessSemaphoreMutex;
import org.apache.curator.framework.recipes.shared.SharedCount;
import org.apache.curator.framework.state.ConnectionState;
import org.junit.Test;
import com.baeldung.apache.curator.BaseTest;
public class RecipesManualTest extends BaseTest {
@Test
public void givenRunningZookeeper_whenUsingLeaderElection_thenNoErrors() {
try (CuratorFramework client = newClient()) {
client.start();
LeaderSelector leaderSelector = new LeaderSelector(client, "/mutex/select/leader/for/job/A", new LeaderSelectorListener() {
@Override
public void stateChanged(CuratorFramework client, ConnectionState newState) {
}
@Override
public void takeLeadership(CuratorFramework client) throws Exception {
// I'm the leader of the job A !
}
});
leaderSelector.start();
// Wait until the job A is done among all the members
leaderSelector.close();
}
}
@Test
public void givenRunningZookeeper_whenUsingSharedLock_thenNoErrors() throws Exception {
try (CuratorFramework client = newClient()) {
client.start();
InterProcessSemaphoreMutex sharedLock = new InterProcessSemaphoreMutex(client, "/mutex/process/A");
sharedLock.acquire();
// Do process A
sharedLock.release();
}
}
@Test
public void givenRunningZookeeper_whenUsingSharedCounter_thenCounterIsIncrement() throws Exception {
try (CuratorFramework client = newClient()) {
client.start();
try (SharedCount counter = new SharedCount(client, "/counters/A", 0)) {
counter.start();
counter.setCount(0);
counter.setCount(counter.getCount() + 1);
assertThat(counter.getCount()).isEqualTo(1);
}
}
}
}

View File

@ -1,3 +1,4 @@
### Relevant Articles: ### Relevant Articles:
- [Microsoft Word Processing in Java with Apache POI](http://www.baeldung.com/java-microsoft-word-with-apache-poi) - [Microsoft Word Processing in Java with Apache POI](http://www.baeldung.com/java-microsoft-word-with-apache-poi)
- [Working with Microsoft Excel in Java](http://www.baeldung.com/java-microsoft-excel) - [Working with Microsoft Excel in Java](http://www.baeldung.com/java-microsoft-excel)
- [Creating a MS PowerPoint Presentation in Java](https://github.com/eugenp/tutorials/tree/master/apache-poi)

View File

@ -0,0 +1,224 @@
package com.baeldung.poi.powerpoint;
import org.apache.poi.sl.usermodel.AutoNumberingScheme;
import org.apache.poi.sl.usermodel.PictureData;
import org.apache.poi.sl.usermodel.TableCell;
import org.apache.poi.sl.usermodel.TextParagraph;
import org.apache.poi.util.IOUtils;
import org.apache.poi.xslf.usermodel.*;
import java.awt.*;
import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.io.IOException;
import java.util.ArrayList;
import java.util.List;
/**
* Helper class for the PowerPoint presentation creation
*/
public class PowerPointHelper {
/**
* Read an existing presentation
*
* @param fileLocation
* File location of the presentation
* @return instance of {@link XMLSlideShow}
* @throws IOException
*/
public XMLSlideShow readingExistingSlideShow(String fileLocation) throws IOException {
return new XMLSlideShow(new FileInputStream(fileLocation));
}
/**
* Create a sample presentation
*
* @param fileLocation
* File location of the presentation
* @throws IOException
*/
public void createPresentation(String fileLocation) throws IOException {
// Create presentation
XMLSlideShow ppt = new XMLSlideShow();
XSLFSlideMaster defaultMaster = ppt.getSlideMasters().get(0);
// Retriving the slide layout
XSLFSlideLayout layout = defaultMaster.getLayout(SlideLayout.TITLE_ONLY);
// Creating the 1st slide
XSLFSlide slide1 = ppt.createSlide(layout);
XSLFTextShape title = slide1.getPlaceholder(0);
// Clearing text to remove the predefined one in the template
title.clearText();
XSLFTextParagraph p = title.addNewTextParagraph();
XSLFTextRun r1 = p.addNewTextRun();
r1.setText("Baeldung");
r1.setFontColor(new Color(78, 147, 89));
r1.setFontSize(48.);
// Add Image
ClassLoader classLoader = getClass().getClassLoader();
byte[] pictureData = IOUtils.toByteArray(new FileInputStream(classLoader.getResource("logo-leaf.png").getFile()));
XSLFPictureData pd = ppt.addPicture(pictureData, PictureData.PictureType.PNG);
XSLFPictureShape picture = slide1.createPicture(pd);
picture.setAnchor(new Rectangle(320, 230, 100, 92));
// Creating 2nd slide
layout = defaultMaster.getLayout(SlideLayout.TITLE_AND_CONTENT);
XSLFSlide slide2 = ppt.createSlide(layout);
// setting the tile
title = slide2.getPlaceholder(0);
title.clearText();
XSLFTextRun r = title.addNewTextParagraph().addNewTextRun();
r.setText("Baeldung");
// Adding the link
XSLFHyperlink link = r.createHyperlink();
link.setAddress("http://www.baeldung.com");
// setting the content
XSLFTextShape content = slide2.getPlaceholder(1);
content.clearText(); // unset any existing text
content.addNewTextParagraph().addNewTextRun().setText("First paragraph");
content.addNewTextParagraph().addNewTextRun().setText("Second paragraph");
content.addNewTextParagraph().addNewTextRun().setText("Third paragraph");
// Creating 3rd slide - List
layout = defaultMaster.getLayout(SlideLayout.TITLE_AND_CONTENT);
XSLFSlide slide3 = ppt.createSlide(layout);
title = slide3.getPlaceholder(0);
title.clearText();
r = title.addNewTextParagraph().addNewTextRun();
r.setText("Lists");
content = slide3.getPlaceholder(1);
content.clearText();
XSLFTextParagraph p1 = content.addNewTextParagraph();
p1.setIndentLevel(0);
p1.setBullet(true);
r1 = p1.addNewTextRun();
r1.setText("Bullet");
// the next three paragraphs form an auto-numbered list
XSLFTextParagraph p2 = content.addNewTextParagraph();
p2.setBulletAutoNumber(AutoNumberingScheme.alphaLcParenRight, 1);
p2.setIndentLevel(1);
XSLFTextRun r2 = p2.addNewTextRun();
r2.setText("Numbered List Item - 1");
// Creating 4th slide
XSLFSlide slide4 = ppt.createSlide();
createTable(slide4);
// Save presentation
FileOutputStream out = new FileOutputStream(fileLocation);
ppt.write(out);
out.close();
// Closing presentation
ppt.close();
}
/**
* Delete a slide from the presentation
*
* @param ppt
* The presentation
* @param slideNumber
* The number of the slide to be deleted (0-based)
*/
public void deleteSlide(XMLSlideShow ppt, int slideNumber) {
ppt.removeSlide(slideNumber);
}
/**
* Re-order the slides inside a presentation
*
* @param ppt
* The presentation
* @param slideNumber
* The number of the slide to move
* @param newSlideNumber
* The new position of the slide (0-base)
*/
public void reorderSlide(XMLSlideShow ppt, int slideNumber, int newSlideNumber) {
List<XSLFSlide> slides = ppt.getSlides();
XSLFSlide secondSlide = slides.get(slideNumber);
ppt.setSlideOrder(secondSlide, newSlideNumber);
}
/**
* Retrieve the placeholder inside a slide
*
* @param slide
* The slide
* @return List of placeholder inside a slide
*/
public List<XSLFShape> retrieveTemplatePlaceholders(XSLFSlide slide) {
List<XSLFShape> placeholders = new ArrayList<>();
for (XSLFShape shape : slide.getShapes()) {
if (shape instanceof XSLFAutoShape) {
placeholders.add(shape);
}
}
return placeholders;
}
/**
* Create a table
*
* @param slide
* Slide
*/
private void createTable(XSLFSlide slide) {
XSLFTable tbl = slide.createTable();
tbl.setAnchor(new Rectangle(50, 50, 450, 300));
int numColumns = 3;
int numRows = 5;
// header
XSLFTableRow headerRow = tbl.addRow();
headerRow.setHeight(50);
for (int i = 0; i < numColumns; i++) {
XSLFTableCell th = headerRow.addCell();
XSLFTextParagraph p = th.addNewTextParagraph();
p.setTextAlign(TextParagraph.TextAlign.CENTER);
XSLFTextRun r = p.addNewTextRun();
r.setText("Header " + (i + 1));
r.setBold(true);
r.setFontColor(Color.white);
th.setFillColor(new Color(79, 129, 189));
th.setBorderWidth(TableCell.BorderEdge.bottom, 2.0);
th.setBorderColor(TableCell.BorderEdge.bottom, Color.white);
// all columns are equally sized
tbl.setColumnWidth(i, 150);
}
// data
for (int rownum = 0; rownum < numRows; rownum++) {
XSLFTableRow tr = tbl.addRow();
tr.setHeight(50);
for (int i = 0; i < numColumns; i++) {
XSLFTableCell cell = tr.addCell();
XSLFTextParagraph p = cell.addNewTextParagraph();
XSLFTextRun r = p.addNewTextRun();
r.setText("Cell " + (i * rownum + 1));
if (rownum % 2 == 0) {
cell.setFillColor(new Color(208, 216, 232));
} else {
cell.setFillColor(new Color(233, 247, 244));
}
}
}
}
}

View File

@ -0,0 +1,77 @@
package com.baeldung.poi.powerpoint;
import org.apache.poi.xslf.usermodel.XMLSlideShow;
import org.apache.poi.xslf.usermodel.XSLFShape;
import org.apache.poi.xslf.usermodel.XSLFSlide;
import org.junit.After;
import org.junit.Assert;
import org.junit.Before;
import org.junit.Test;
import java.io.File;
import java.util.List;
public class PowerPointIntegrationTest {
private PowerPointHelper pph;
private String fileLocation;
private static final String FILE_NAME = "presentation.pptx";
@Before
public void setUp() throws Exception {
File currDir = new File(".");
String path = currDir.getAbsolutePath();
fileLocation = path.substring(0, path.length() - 1) + FILE_NAME;
pph = new PowerPointHelper();
pph.createPresentation(fileLocation);
}
@Test
public void whenReadingAPresentation_thenOK() throws Exception {
XMLSlideShow xmlSlideShow = pph.readingExistingSlideShow(fileLocation);
Assert.assertNotNull(xmlSlideShow);
Assert.assertEquals(4, xmlSlideShow.getSlides().size());
}
@Test
public void whenRetrievingThePlaceholdersForEachSlide_thenOK() throws Exception {
XMLSlideShow xmlSlideShow = pph.readingExistingSlideShow(fileLocation);
List<XSLFShape> onlyTitleSlidePlaceholders = pph.retrieveTemplatePlaceholders(xmlSlideShow.getSlides().get(0));
List<XSLFShape> titleAndBodySlidePlaceholders = pph.retrieveTemplatePlaceholders(xmlSlideShow.getSlides().get(1));
List<XSLFShape> emptySlidePlaceholdes = pph.retrieveTemplatePlaceholders(xmlSlideShow.getSlides().get(3));
Assert.assertEquals(1, onlyTitleSlidePlaceholders.size());
Assert.assertEquals(2, titleAndBodySlidePlaceholders.size());
Assert.assertEquals(0, emptySlidePlaceholdes.size());
}
@Test
public void whenSortingSlides_thenOK() throws Exception {
XMLSlideShow xmlSlideShow = pph.readingExistingSlideShow(fileLocation);
XSLFSlide slide4 = xmlSlideShow.getSlides().get(3);
pph.reorderSlide(xmlSlideShow, 3, 1);
Assert.assertEquals(slide4, xmlSlideShow.getSlides().get(1));
}
@Test
public void givenPresentation_whenDeletingASlide_thenOK() throws Exception {
XMLSlideShow xmlSlideShow = pph.readingExistingSlideShow(fileLocation);
pph.deleteSlide(xmlSlideShow, 3);
Assert.assertEquals(3, xmlSlideShow.getSlides().size());
}
@After
public void tearDown() throws Exception {
File testFile = new File(fileLocation);
if (testFile.exists()) {
testFile.delete();
}
pph = null;
}
}

View File

@ -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>

3
apache-spark/README.md Normal file
View File

@ -0,0 +1,3 @@
### Relevant articles
- [Introduction to Apache Spark](http://www.baeldung.com/apache-spark)

25
apache-tika/pom.xml Normal file
View File

@ -0,0 +1,25 @@
<project xmlns="http://maven.apache.org/POM/4.0.0" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd">
<modelVersion>4.0.0</modelVersion>
<groupId>com.baeldung</groupId>
<artifactId>apache-tika</artifactId>
<version>0.0.1-SNAPSHOT</version>
<parent>
<groupId>com.baeldung</groupId>
<artifactId>parent-modules</artifactId>
<version>1.0.0-SNAPSHOT</version>
</parent>
<properties>
<tika.version>1.17</tika.version>
</properties>
<dependencies>
<dependency>
<groupId>org.apache.tika</groupId>
<artifactId>tika-parsers</artifactId>
<version>${tika.version}</version>
</dependency>
</dependencies>
</project>

View File

@ -0,0 +1,67 @@
package com.baeldung.tika;
import java.io.IOException;
import java.io.InputStream;
import org.apache.tika.Tika;
import org.apache.tika.detect.DefaultDetector;
import org.apache.tika.detect.Detector;
import org.apache.tika.exception.TikaException;
import org.apache.tika.metadata.Metadata;
import org.apache.tika.mime.MediaType;
import org.apache.tika.parser.AutoDetectParser;
import org.apache.tika.parser.ParseContext;
import org.apache.tika.parser.Parser;
import org.apache.tika.sax.BodyContentHandler;
import org.xml.sax.ContentHandler;
import org.xml.sax.SAXException;
public class TikaAnalysis {
public static String detectDocTypeUsingDetector(InputStream stream) throws IOException {
Detector detector = new DefaultDetector();
Metadata metadata = new Metadata();
MediaType mediaType = detector.detect(stream, metadata);
return mediaType.toString();
}
public static String detectDocTypeUsingFacade(InputStream stream) throws IOException {
Tika tika = new Tika();
String mediaType = tika.detect(stream);
return mediaType;
}
public static String extractContentUsingParser(InputStream stream) throws IOException, TikaException, SAXException {
Parser parser = new AutoDetectParser();
ContentHandler handler = new BodyContentHandler();
Metadata metadata = new Metadata();
ParseContext context = new ParseContext();
parser.parse(stream, handler, metadata, context);
return handler.toString();
}
public static String extractContentUsingFacade(InputStream stream) throws IOException, TikaException {
Tika tika = new Tika();
String content = tika.parseToString(stream);
return content;
}
public static Metadata extractMetadatatUsingParser(InputStream stream) throws IOException, SAXException, TikaException {
Parser parser = new AutoDetectParser();
ContentHandler handler = new BodyContentHandler();
Metadata metadata = new Metadata();
ParseContext context = new ParseContext();
parser.parse(stream, handler, metadata, context);
return metadata;
}
public static Metadata extractMetadatatUsingFacade(InputStream stream) throws IOException, TikaException {
Tika tika = new Tika();
Metadata metadata = new Metadata();
tika.parse(stream, metadata);
return metadata;
}
}

View File

@ -0,0 +1,79 @@
package com.baeldung.tika;
import static org.hamcrest.CoreMatchers.containsString;
import static org.junit.Assert.assertEquals;
import static org.junit.Assert.assertThat;
import java.io.IOException;
import java.io.InputStream;
import org.apache.tika.exception.TikaException;
import org.apache.tika.metadata.Metadata;
import org.junit.Test;
import org.xml.sax.SAXException;
public class TikaUnitTest {
@Test
public void whenUsingDetector_thenDocumentTypeIsReturned() throws IOException {
InputStream stream = this.getClass().getClassLoader().getResourceAsStream("tika.txt");
String mediaType = TikaAnalysis.detectDocTypeUsingDetector(stream);
assertEquals("application/pdf", mediaType);
stream.close();
}
@Test
public void whenUsingFacade_thenDocumentTypeIsReturned() throws IOException {
InputStream stream = this.getClass().getClassLoader().getResourceAsStream("tika.txt");
String mediaType = TikaAnalysis.detectDocTypeUsingFacade(stream);
assertEquals("application/pdf", mediaType);
stream.close();
}
@Test
public void whenUsingParser_thenContentIsReturned() throws IOException, TikaException, SAXException {
InputStream stream = this.getClass().getClassLoader().getResourceAsStream("tika.docx");
String content = TikaAnalysis.extractContentUsingParser(stream);
assertThat(content, containsString("Apache Tika - a content analysis toolkit"));
assertThat(content, containsString("detects and extracts metadata and text"));
stream.close();
}
@Test
public void whenUsingFacade_thenContentIsReturned() throws IOException, TikaException {
InputStream stream = this.getClass().getClassLoader().getResourceAsStream("tika.docx");
String content = TikaAnalysis.extractContentUsingFacade(stream);
assertThat(content, containsString("Apache Tika - a content analysis toolkit"));
assertThat(content, containsString("detects and extracts metadata and text"));
stream.close();
}
@Test
public void whenUsingParser_thenMetadataIsReturned() throws IOException, TikaException, SAXException {
InputStream stream = this.getClass().getClassLoader().getResourceAsStream("tika.xlsx");
Metadata metadata = TikaAnalysis.extractMetadatatUsingParser(stream);
assertEquals("org.apache.tika.parser.DefaultParser", metadata.get("X-Parsed-By"));
assertEquals("Microsoft Office User", metadata.get("Author"));
stream.close();
}
@Test
public void whenUsingFacade_thenMetadataIsReturned() throws IOException, TikaException {
InputStream stream = this.getClass().getClassLoader().getResourceAsStream("tika.xlsx");
Metadata metadata = TikaAnalysis.extractMetadatatUsingFacade(stream);
assertEquals("org.apache.tika.parser.DefaultParser", metadata.get("X-Parsed-By"));
assertEquals("Microsoft Office User", metadata.get("Author"));
stream.close();
}
}

Binary file not shown.

Binary file not shown.

Binary file not shown.

36
apache-zookeeper/pom.xml Normal file
View File

@ -0,0 +1,36 @@
<project xmlns="http://maven.apache.org/POM/4.0.0" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd">
<modelVersion>4.0.0</modelVersion>
<groupId>com.baeldung</groupId>
<artifactId>apache-zookeeper</artifactId>
<version>0.0.1-SNAPSHOT</version>
<packaging>jar</packaging>
<parent>
<groupId>com.baeldung</groupId>
<artifactId>parent-modules</artifactId>
<version>1.0.0-SNAPSHOT</version>
</parent>
<dependencies>
<dependency>
<groupId>org.apache.zookeeper</groupId>
<artifactId>zookeeper</artifactId>
<version>3.3.2</version>
<exclusions>
<exclusion>
<groupId>com.sun.jmx</groupId>
<artifactId>jmxri</artifactId>
</exclusion>
<exclusion>
<groupId>com.sun.jdmk</groupId>
<artifactId>jmxtools</artifactId>
</exclusion>
<exclusion>
<groupId>javax.jms</groupId>
<artifactId>jms</artifactId>
</exclusion>
</exclusions>
</dependency>
</dependencies>
</project>

View File

@ -0,0 +1,33 @@
package com.baeldung.zookeeper.connection;
import java.io.IOException;
import java.util.concurrent.CountDownLatch;
import org.apache.zookeeper.WatchedEvent;
import org.apache.zookeeper.Watcher;
import org.apache.zookeeper.Watcher.Event.KeeperState;
import org.apache.zookeeper.ZooKeeper;
public class ZKConnection {
private ZooKeeper zoo;
final CountDownLatch connectionLatch = new CountDownLatch(1);
public ZKConnection() {
}
public ZooKeeper connect(String host) throws IOException, InterruptedException {
zoo = new ZooKeeper(host, 2000, new Watcher() {
public void process(WatchedEvent we) {
if (we.getState() == KeeperState.SyncConnected) {
connectionLatch.countDown();
}
}
});
connectionLatch.await();
return zoo;
}
public void close() throws InterruptedException {
zoo.close();
}
}

View File

@ -0,0 +1,35 @@
package com.baeldung.zookeeper.manager;
import org.apache.zookeeper.KeeperException;
public interface ZKManager {
/**
* Create a Znode and save some data
*
* @param path
* @param data
* @throws KeeperException
* @throws InterruptedException
*/
public void create(String path, byte[] data) throws KeeperException, InterruptedException;
/**
* Get ZNode Data
*
* @param path
* @param boolean watchFlag
* @throws KeeperException
* @throws InterruptedException
*/
public Object getZNodeData(String path, boolean watchFlag);
/**
* Update the ZNode Data
*
* @param path
* @param data
* @throws KeeperException
* @throws InterruptedException
*/
public void update(String path, byte[] data) throws KeeperException, InterruptedException, KeeperException;
}

View File

@ -0,0 +1,58 @@
package com.baeldung.zookeeper.manager;
import org.apache.zookeeper.CreateMode;
import org.apache.zookeeper.KeeperException;
import org.apache.zookeeper.ZooDefs;
import org.apache.zookeeper.ZooKeeper;
import com.baeldung.zookeeper.connection.ZKConnection;
public class ZKManagerImpl implements ZKManager {
private static ZooKeeper zkeeper;
private static ZKConnection zkConnection;
public ZKManagerImpl() {
initialize();
}
/** * Initialize connection */
private void initialize() {
try {
zkConnection = new ZKConnection();
zkeeper = zkConnection.connect("localhost");
} catch (Exception e) {
System.out.println(e.getMessage());
}
}
public void closeConnection() {
try {
zkConnection.close();
} catch (InterruptedException e) {
System.out.println(e.getMessage());
}
}
public void create(String path, byte[] data) throws KeeperException, InterruptedException {
zkeeper.create(path, data, ZooDefs.Ids.OPEN_ACL_UNSAFE, CreateMode.PERSISTENT);
}
public Object getZNodeData(String path, boolean watchFlag) {
try {
byte[] b = null;
b = zkeeper.getData(path, null, null);
String data = new String(b, "UTF-8");
System.out.println(data);
return data;
} catch (Exception e) {
System.out.println(e.getMessage());
}
return null;
}
public void update(String path, byte[] data) throws KeeperException, InterruptedException {
int version = zkeeper.exists(path, true)
.getVersion();
zkeeper.setData(path, data, version);
}
}

View File

@ -0,0 +1,137 @@
package com.baeldung.ec2;
import java.util.Arrays;
import com.amazonaws.auth.AWSCredentials;
import com.amazonaws.auth.AWSStaticCredentialsProvider;
import com.amazonaws.auth.BasicAWSCredentials;
import com.amazonaws.regions.Regions;
import com.amazonaws.services.ec2.AmazonEC2;
import com.amazonaws.services.ec2.AmazonEC2ClientBuilder;
import com.amazonaws.services.ec2.model.AuthorizeSecurityGroupIngressRequest;
import com.amazonaws.services.ec2.model.CreateKeyPairRequest;
import com.amazonaws.services.ec2.model.CreateKeyPairResult;
import com.amazonaws.services.ec2.model.CreateSecurityGroupRequest;
import com.amazonaws.services.ec2.model.DescribeInstancesRequest;
import com.amazonaws.services.ec2.model.DescribeInstancesResult;
import com.amazonaws.services.ec2.model.DescribeKeyPairsRequest;
import com.amazonaws.services.ec2.model.DescribeKeyPairsResult;
import com.amazonaws.services.ec2.model.IpPermission;
import com.amazonaws.services.ec2.model.IpRange;
import com.amazonaws.services.ec2.model.MonitorInstancesRequest;
import com.amazonaws.services.ec2.model.RebootInstancesRequest;
import com.amazonaws.services.ec2.model.RunInstancesRequest;
import com.amazonaws.services.ec2.model.StartInstancesRequest;
import com.amazonaws.services.ec2.model.StopInstancesRequest;
import com.amazonaws.services.ec2.model.UnmonitorInstancesRequest;
public class EC2Application {
private static final AWSCredentials credentials;
static {
// put your accesskey and secretkey here
credentials = new BasicAWSCredentials(
"<AWS accesskey>",
"<AWS secretkey>"
);
}
public static void main(String[] args) {
// Set up the client
AmazonEC2 ec2Client = AmazonEC2ClientBuilder.standard()
.withCredentials(new AWSStaticCredentialsProvider(credentials))
.withRegion(Regions.US_EAST_1)
.build();
// Create a security group
CreateSecurityGroupRequest createSecurityGroupRequest = new CreateSecurityGroupRequest().withGroupName("BaeldungSecurityGroup")
.withDescription("Baeldung Security Group");
ec2Client.createSecurityGroup(createSecurityGroupRequest);
// Allow HTTP and SSH traffic
IpRange ipRange1 = new IpRange().withCidrIp("0.0.0.0/0");
IpPermission ipPermission1 = new IpPermission().withIpv4Ranges(Arrays.asList(new IpRange[] { ipRange1 }))
.withIpProtocol("tcp")
.withFromPort(80)
.withToPort(80);
IpPermission ipPermission2 = new IpPermission().withIpv4Ranges(Arrays.asList(new IpRange[] { ipRange1 }))
.withIpProtocol("tcp")
.withFromPort(22)
.withToPort(22);
AuthorizeSecurityGroupIngressRequest authorizeSecurityGroupIngressRequest = new AuthorizeSecurityGroupIngressRequest()
.withGroupName("BaeldungSecurityGroup")
.withIpPermissions(ipPermission1, ipPermission2);
ec2Client.authorizeSecurityGroupIngress(authorizeSecurityGroupIngressRequest);
// Create KeyPair
CreateKeyPairRequest createKeyPairRequest = new CreateKeyPairRequest()
.withKeyName("baeldung-key-pair");
CreateKeyPairResult createKeyPairResult = ec2Client.createKeyPair(createKeyPairRequest);
String privateKey = createKeyPairResult
.getKeyPair()
.getKeyMaterial(); // make sure you keep it, the private key, Amazon doesn't store the private key
// See what key-pairs you've got
DescribeKeyPairsRequest describeKeyPairsRequest = new DescribeKeyPairsRequest();
DescribeKeyPairsResult describeKeyPairsResult = ec2Client.describeKeyPairs(describeKeyPairsRequest);
// Launch an Amazon Instance
RunInstancesRequest runInstancesRequest = new RunInstancesRequest().withImageId("ami-97785bed") // https://docs.aws.amazon.com/AWSEC2/latest/UserGuide/AMIs.html | https://docs.aws.amazon.com/AWSEC2/latest/UserGuide/usingsharedamis-finding.html
.withInstanceType("t2.micro") // https://docs.aws.amazon.com/AWSEC2/latest/UserGuide/instance-types.html
.withMinCount(1)
.withMaxCount(1)
.withKeyName("baeldung-key-pair") // optional - if not present, can't connect to instance
.withSecurityGroups("BaeldungSecurityGroup");
String yourInstanceId = ec2Client.runInstances(runInstancesRequest).getReservation().getInstances().get(0).getInstanceId();
// Start an Instance
StartInstancesRequest startInstancesRequest = new StartInstancesRequest()
.withInstanceIds(yourInstanceId);
ec2Client.startInstances(startInstancesRequest);
// Monitor Instances
MonitorInstancesRequest monitorInstancesRequest = new MonitorInstancesRequest()
.withInstanceIds(yourInstanceId);
ec2Client.monitorInstances(monitorInstancesRequest);
UnmonitorInstancesRequest unmonitorInstancesRequest = new UnmonitorInstancesRequest()
.withInstanceIds(yourInstanceId);
ec2Client.unmonitorInstances(unmonitorInstancesRequest);
// Reboot an Instance
RebootInstancesRequest rebootInstancesRequest = new RebootInstancesRequest()
.withInstanceIds(yourInstanceId);
ec2Client.rebootInstances(rebootInstancesRequest);
// Stop an Instance
StopInstancesRequest stopInstancesRequest = new StopInstancesRequest()
.withInstanceIds(yourInstanceId);
ec2Client.stopInstances(stopInstancesRequest)
.getStoppingInstances()
.get(0)
.getPreviousState()
.getName();
// Describe an Instance
DescribeInstancesRequest describeInstancesRequest = new DescribeInstancesRequest();
DescribeInstancesResult response = ec2Client.describeInstances(describeInstancesRequest);
System.out.println(response.getReservations()
.get(0)
.getInstances()
.get(0)
.getKernelId());
}
}

View File

@ -28,8 +28,14 @@
<dependency> <dependency>
<groupId>junit</groupId> <groupId>junit</groupId>
<artifactId>junit</artifactId> <artifactId>junit</artifactId>
<version>3.8.1</version> <version>4.12</version>
<scope>test</scope> <scope>test</scope>
<exclusions>
<exclusion>
<artifactId>hamcrest-core</artifactId>
<groupId>org.hamcrest</groupId>
</exclusion>
</exclusions>
</dependency> </dependency>
</dependencies> </dependencies>
<dependencyManagement> <dependencyManagement>

View File

@ -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>

View File

@ -0,0 +1,2 @@
## Relevant articles:
- [CAS SSO With Spring Security](http://www.baeldung.com/spring-security-cas-sso)

View File

@ -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>
@ -65,18 +65,28 @@
<groupId>org.springframework.boot</groupId> <groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-maven-plugin</artifactId> <artifactId>spring-boot-maven-plugin</artifactId>
</plugin> </plugin>
<plugin>
<groupId>org.apache.maven.plugins</groupId>
<artifactId>maven-surefire-plugin</artifactId>
<version>${maven-surefire-plugin.version}</version>
<configuration>
<forkCount>3</forkCount>
<reuseForks>true</reuseForks>
<excludes>
<exclude>**/*IntegrationTest.java</exclude>
<exclude>**/*LongRunningUnitTest.java</exclude>
<exclude>**/*ManualTest.java</exclude>
<exclude>**/JdbcTest.java</exclude>
<exclude>**/*LiveTest.java</exclude>
</excludes>
</configuration>
</plugin>
</plugins> </plugins>
</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>
@ -88,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>
@ -107,4 +109,5 @@
</pluginRepositories> </pluginRepositories>
</project> </project>

View File

@ -40,14 +40,14 @@ public class CasSecuredAppApplication {
@Primary @Primary
public AuthenticationEntryPoint authenticationEntryPoint(ServiceProperties sP) { public AuthenticationEntryPoint authenticationEntryPoint(ServiceProperties sP) {
CasAuthenticationEntryPoint entryPoint = new CasAuthenticationEntryPoint(); CasAuthenticationEntryPoint entryPoint = new CasAuthenticationEntryPoint();
entryPoint.setLoginUrl("https://localhost:8443/cas/login"); entryPoint.setLoginUrl("https://localhost:6443/cas/login");
entryPoint.setServiceProperties(sP); entryPoint.setServiceProperties(sP);
return entryPoint; return entryPoint;
} }
@Bean @Bean
public TicketValidator ticketValidator() { public TicketValidator ticketValidator() {
return new Cas30ServiceTicketValidator("https://localhost:8443/cas"); return new Cas30ServiceTicketValidator("https://localhost:6443/cas");
} }
@Bean @Bean
@ -71,7 +71,7 @@ public class CasSecuredAppApplication {
@Bean @Bean
public LogoutFilter logoutFilter() { public LogoutFilter logoutFilter() {
LogoutFilter logoutFilter = new LogoutFilter( LogoutFilter logoutFilter = new LogoutFilter(
"https://localhost:8443/cas/logout", securityContextLogoutHandler()); "https://localhost:6443/cas/logout", securityContextLogoutHandler());
logoutFilter.setFilterProcessesUrl("/logout/cas"); logoutFilter.setFilterProcessesUrl("/logout/cas");
return logoutFilter; return logoutFilter;
} }
@ -79,7 +79,7 @@ public class CasSecuredAppApplication {
@Bean @Bean
public SingleSignOutFilter singleSignOutFilter() { public SingleSignOutFilter singleSignOutFilter() {
SingleSignOutFilter singleSignOutFilter = new SingleSignOutFilter(); SingleSignOutFilter singleSignOutFilter = new SingleSignOutFilter();
singleSignOutFilter.setCasServerUrlPrefix("https://localhost:8443/cas"); singleSignOutFilter.setCasServerUrlPrefix("https://localhost:6443/cas");
singleSignOutFilter.setIgnoreInitConfiguration(true); singleSignOutFilter.setIgnoreInitConfiguration(true);
return singleSignOutFilter; return singleSignOutFilter;
} }

View File

@ -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(

View File

@ -7,7 +7,7 @@ import org.springframework.test.context.junit4.SpringRunner;
@RunWith(SpringRunner.class) @RunWith(SpringRunner.class)
@SpringBootTest @SpringBootTest
public class CasSecuredAppApplicationTests { public class CasSecuredAppApplicationIntegrationTest {
@Test @Test
public void contextLoads() { public void contextLoads() {

Binary file not shown.

View File

@ -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>

View File

@ -2,9 +2,9 @@
# CAS Server Context Configuration # CAS Server Context Configuration
# #
server.context-path=/cas server.context-path=/cas
server.port=8443 server.port=6443
server.ssl.key-store=file:/etc/cas/thekeystore server.ssl.key-store=classpath:/etc/cas/thekeystore
server.ssl.key-store-password=changeit server.ssl.key-store-password=changeit
server.ssl.key-password=changeit server.ssl.key-password=changeit
# server.ssl.ciphers= # server.ssl.ciphers=
@ -40,6 +40,12 @@ spring.http.encoding.charset=UTF-8
spring.http.encoding.enabled=true spring.http.encoding.enabled=true
spring.http.encoding.force=true spring.http.encoding.force=true
##
#CAS CONFIG LOCATION
#
cas.standalone.config=classpath:/etc/cas/config
## ##
# CAS Cloud Bus Configuration # CAS Cloud Bus Configuration
# #
@ -82,6 +88,7 @@ spring.thymeleaf.mode=HTML
# CAS Log4j Configuration # CAS Log4j Configuration
# #
# logging.config=file:/etc/cas/log4j2.xml # logging.config=file:/etc/cas/log4j2.xml
server.context-parameters.isLog4jAutoInitializationDisabled=true server.context-parameters.isLog4jAutoInitializationDisabled=true
## ##
@ -102,11 +109,12 @@ cas.authn.jdbc.query[0].sql=SELECT * FROM users WHERE email = ?
cas.authn.jdbc.query[0].url=jdbc:mysql://127.0.0.1:3306/test?useUnicode=true&useJDBCCompliantTimezoneShift=true&useLegacyDatetimeCode=false&serverTimezone=UTC cas.authn.jdbc.query[0].url=jdbc:mysql://127.0.0.1:3306/test?useUnicode=true&useJDBCCompliantTimezoneShift=true&useLegacyDatetimeCode=false&serverTimezone=UTC
cas.authn.jdbc.query[0].dialect=org.hibernate.dialect.MySQLDialect cas.authn.jdbc.query[0].dialect=org.hibernate.dialect.MySQLDialect
cas.authn.jdbc.query[0].user=root cas.authn.jdbc.query[0].user=root
cas.authn.jdbc.query[0].password= cas.authn.jdbc.query[0].password=root
cas.authn.jdbc.query[0].ddlAuto=none cas.authn.jdbc.query[0].ddlAuto=none
cas.authn.jdbc.query[0].driverClass=com.mysql.jdbc.Driver #cas.authn.jdbc.query[0].driverClass=com.mysql.jdbc.Driver
cas.authn.jdbc.query[0].driverClass=com.mysql.cj.jdbc.Driver
cas.authn.jdbc.query[0].fieldPassword=password cas.authn.jdbc.query[0].fieldPassword=password
cas.authn.jdbc.query[0].passwordEncoder.type=BCRYPT cas.authn.jdbc.query[0].passwordEncoder.type=NONE
## ##

View File

@ -1,16 +1,15 @@
cas.server.name: https://localhost:8443 cas.server.name: https://localhost:6443
cas.server.prefix: https://localhost:8443/cas cas.server.prefix: https://localhost:643/cas
cas.adminPagesSecurity.ip=127\.0\.0\.1 cas.adminPagesSecurity.ip=127\.0\.0\.1
logging.config: file:/etc/cas/config/log4j2.xml
cas.serviceRegistry.initFromJson=true cas.serviceRegistry.initFromJson=true
cas.serviceRegistry.config.location=classpath:/services cas.serviceRegistry.config.location=classpath:/services
cas.authn.accept.users= cas.authn.accept.users=
cas.authn.accept.name= cas.authn.accept.name=
#CAS Database Authentication Property #CAS Database Authentication Property
# cas.authn.jdbc.query[0].healthQuery= # cas.authn.jdbc.query[0].healthQuery=

View File

@ -0,0 +1,16 @@
-- Dumping database structure for test
CREATE DATABASE IF NOT EXISTS `test` /*!40100 DEFAULT CHARACTER SET latin1 */;
USE `test`;
-- Dumping structure for table test.users
CREATE TABLE IF NOT EXISTS `users` (
`id` int(11) NOT NULL AUTO_INCREMENT,
`email` varchar(50) DEFAULT NULL,
`password` text DEFAULT NULL,
PRIMARY KEY (`id`)
) ENGINE=InnoDB AUTO_INCREMENT=3 DEFAULT CHARSET=latin1;
/*!40000 ALTER TABLE `users` DISABLE KEYS */;
INSERT INTO `users` (`id`, `email`, `password`) VALUES
(1, 'test@test.com', 'Mellon');
/*!40000 ALTER TABLE `users` ENABLE KEYS */;

View File

@ -0,0 +1,2 @@
info:
description: CAS Configuration

View File

@ -0,0 +1,7 @@
cas.server.name: https://cas.example.org:8443
cas.server.prefix: https://cas.example.org:8443/cas
cas.adminPagesSecurity.ip=127\.0\.0\.1
logging.config: file:/etc/cas/config/log4j2.xml
# cas.serviceRegistry.config.location: classpath:/services

View File

@ -0,0 +1,117 @@
<?xml version="1.0" encoding="UTF-8" ?>
<!-- Specify the refresh internal in seconds. -->
<Configuration monitorInterval="5" packages="org.apereo.cas.logging">
<Properties>
<!--
Default log directory is the current directory but that can be overridden with -Dcas.log.dir=<logdir>
Or you can change this property to a new default
-->
<Property name="cas.log.dir" >.</Property>
<!-- To see more CAS specific logging, adjust this property to info or debug or run server with -Dcas.log.leve=debug -->
<Property name="cas.log.level" >warn</Property>
</Properties>
<Appenders>
<Console name="console" target="SYSTEM_OUT">
<PatternLayout pattern="%d %p [%c] - &lt;%m&gt;%n"/>
</Console>
<RollingFile name="file" fileName="${sys:cas.log.dir}/cas.log" append="true"
filePattern="${sys:cas.log.dir}/cas-%d{yyyy-MM-dd-HH}-%i.log">
<PatternLayout pattern="%d %p [%c] - &lt;%m&gt;%n"/>
<Policies>
<OnStartupTriggeringPolicy />
<SizeBasedTriggeringPolicy size="10 MB"/>
<TimeBasedTriggeringPolicy />
</Policies>
</RollingFile>
<RollingFile name="auditlogfile" fileName="${sys:cas.log.dir}/cas_audit.log" append="true"
filePattern="${sys:cas.log.dir}/cas_audit-%d{yyyy-MM-dd-HH}-%i.log">
<PatternLayout pattern="%d %p [%c] - %m%n"/>
<Policies>
<OnStartupTriggeringPolicy />
<SizeBasedTriggeringPolicy size="10 MB"/>
<TimeBasedTriggeringPolicy />
</Policies>
</RollingFile>
<RollingFile name="perfFileAppender" fileName="${sys:cas.log.dir}/perfStats.log" append="true"
filePattern="${sys:cas.log.dir}/perfStats-%d{yyyy-MM-dd-HH}-%i.log">
<PatternLayout pattern="%m%n"/>
<Policies>
<OnStartupTriggeringPolicy />
<SizeBasedTriggeringPolicy size="10 MB"/>
<TimeBasedTriggeringPolicy />
</Policies>
</RollingFile>
<CasAppender name="casAudit">
<AppenderRef ref="auditlogfile" />
</CasAppender>
<CasAppender name="casFile">
<AppenderRef ref="file" />
</CasAppender>
<CasAppender name="casConsole">
<AppenderRef ref="console" />
</CasAppender>
<CasAppender name="casPerf">
<AppenderRef ref="perfFileAppender" />
</CasAppender>
</Appenders>
<Loggers>
<!-- If adding a Logger with level set higher than warn, make category as selective as possible -->
<!-- Loggers inherit appenders from Root Logger unless additivity is false -->
<AsyncLogger name="org.apereo" level="${sys:cas.log.level}" includeLocation="true"/>
<AsyncLogger name="org.apereo.services.persondir" level="${sys:cas.log.level}" includeLocation="true"/>
<AsyncLogger name="org.apereo.cas.web.flow" level="info" includeLocation="true"/>
<AsyncLogger name="org.apache" level="warn" />
<AsyncLogger name="org.apache.http" level="error" />
<AsyncLogger name="org.springframework" level="warn" />
<AsyncLogger name="org.springframework.cloud.server" level="warn" />
<AsyncLogger name="org.springframework.cloud.client" level="warn" />
<AsyncLogger name="org.springframework.cloud.bus" level="warn" />
<AsyncLogger name="org.springframework.aop" level="warn" />
<AsyncLogger name="org.springframework.boot" level="warn" />
<AsyncLogger name="org.springframework.boot.actuate.autoconfigure" level="warn" />
<AsyncLogger name="org.springframework.webflow" level="warn" />
<AsyncLogger name="org.springframework.session" level="warn" />
<AsyncLogger name="org.springframework.amqp" level="error" />
<AsyncLogger name="org.springframework.integration" level="warn" />
<AsyncLogger name="org.springframework.messaging" level="warn" />
<AsyncLogger name="org.springframework.web" level="warn" />
<AsyncLogger name="org.springframework.orm.jpa" level="warn" />
<AsyncLogger name="org.springframework.scheduling" level="warn" />
<AsyncLogger name="org.springframework.context.annotation" level="error" />
<AsyncLogger name="org.springframework.boot.devtools" level="error" />
<AsyncLogger name="org.springframework.web.socket" level="warn" />
<AsyncLogger name="org.thymeleaf" level="warn" />
<AsyncLogger name="org.pac4j" level="warn" />
<AsyncLogger name="org.opensaml" level="warn"/>
<AsyncLogger name="net.sf.ehcache" level="warn" />
<AsyncLogger name="com.couchbase" level="warn" includeLocation="true"/>
<AsyncLogger name="com.ryantenney.metrics" level="warn" />
<AsyncLogger name="net.jradius" level="warn" />
<AsyncLogger name="org.openid4java" level="warn" />
<AsyncLogger name="org.ldaptive" level="warn" />
<AsyncLogger name="com.hazelcast" level="warn" />
<AsyncLogger name="org.jasig.spring" level="warn" />
<!-- Log perf stats only to perfStats.log -->
<AsyncLogger name="perfStatsLogger" level="info" additivity="false" includeLocation="true">
<AppenderRef ref="casPerf"/>
</AsyncLogger>
<!-- Log audit to all root appenders, and also to audit log (additivity is not false) -->
<AsyncLogger name="org.apereo.inspektr.audit.support" level="info" includeLocation="true" >
<AppenderRef ref="casAudit"/>
</AsyncLogger>
<!-- All Loggers inherit appenders specified here, unless additivity="false" on the Logger -->
<AsyncRoot level="warn">
<AppenderRef ref="casFile"/>
<!--
For deployment to an application server running as service,
delete the casConsole appender below
-->
<AppenderRef ref="casConsole"/>
</AsyncRoot>
</Loggers>
</Configuration>

Binary file not shown.

114
checker-plugin/pom.xml Normal file
View File

@ -0,0 +1,114 @@
<project xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns="http://maven.apache.org/POM/4.0.0"
xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/maven-v4_0_0.xsd">
<modelVersion>4.0.0</modelVersion>
<groupId>com.baeldung</groupId>
<artifactId>checker-plugin</artifactId>
<packaging>jar</packaging>
<version>1.0-SNAPSHOT</version>
<name>checker-plugin</name>
<url>http://maven.apache.org</url>
<!-- https://checkerframework.org/manual/#maven -->
<properties>
<!-- These properties will be set by the Maven Dependency plugin -->
<annotatedJdk>${org.checkerframework:jdk8:jar}</annotatedJdk>
<!-- Uncomment to use the Type Annotations compiler. -->
<!--
<typeAnnotationsJavac>${org.checkerframework:compiler:jar}</typeAnnotationsJavac>
-->
</properties>
<dependencies>
<!-- Annotations from the Checker Framework: nullness, interning, locking, ... -->
<dependency>
<groupId>org.checkerframework</groupId>
<artifactId>checker-qual</artifactId>
<version>2.3.1</version>
</dependency>
<dependency>
<groupId>org.checkerframework</groupId>
<artifactId>checker</artifactId>
<version>2.3.1</version>
</dependency>
<dependency>
<groupId>org.checkerframework</groupId>
<artifactId>jdk8</artifactId>
<version>2.3.1</version>
</dependency>
<!-- The Type Annotations compiler. Uncomment if using annotations in comments. -->
<dependency>
<groupId>org.checkerframework</groupId>
<artifactId>compiler</artifactId>
<version>2.3.1</version>
</dependency>
</dependencies>
<build>
<plugins>
<plugin>
<!-- This plugin will set properties values using dependency information -->
<groupId>org.apache.maven.plugins</groupId>
<artifactId>maven-dependency-plugin</artifactId>
<executions>
<execution>
<goals>
<!--
Goal that sets a property pointing to the artifact file for each project dependency.
For each dependency (direct and transitive) a project property will be set which
follows the:
groupId:artifactId:type:[classifier]
form and contains the path to the resolved artifact. -->
<goal>properties</goal>
</goals>
</execution>
</executions>
</plugin>
<plugin>
<artifactId>maven-compiler-plugin</artifactId>
<version>3.6.1</version>
<configuration>
<source>1.8</source>
<target>1.8</target>
<!-- Uncomment the following line to use the type annotations compiler. -->
<!-- <fork>true</fork> -->
<compilerArguments>
<Xmaxerrs>10000</Xmaxerrs>
<Xmaxwarns>10000</Xmaxwarns>
</compilerArguments>
<annotationProcessors>
<!-- Add all the checkers you want to enable here -->
<annotationProcessor>org.checkerframework.checker.nullness.NullnessChecker</annotationProcessor>
<annotationProcessor>org.checkerframework.checker.interning.InterningChecker</annotationProcessor>
<annotationProcessor>org.checkerframework.checker.fenum.FenumChecker</annotationProcessor>
<annotationProcessor>org.checkerframework.checker.formatter.FormatterChecker</annotationProcessor>
<annotationProcessor>org.checkerframework.checker.regex.RegexChecker</annotationProcessor>
</annotationProcessors>
<compilerArgs>
<arg>-AprintErrorStack</arg>
<!-- location of the annotated JDK, which comes from a Maven dependency -->
<arg>-Xbootclasspath/p:${annotatedJdk}</arg>
<!--
-->
<!-- Uncomment the following line to use the type annotations compiler. -->
<!--
<arg>-J-Xbootclasspath/p:${typeAnnotationsJavac}</arg>
-->
<!-- Uncomment the following line to turn type-checking warnings into errors. -->
<arg>-Awarns</arg>
</compilerArgs>
</configuration>
</plugin>
</plugins>
</build>
</project>

View File

@ -0,0 +1,42 @@
package com.baeldung.typechecker;
import org.checkerframework.checker.fenum.qual.Fenum;
//@SuppressWarnings("fenum:assignment.type.incompatible")
public class FakeNumExample {
// Here we use some String constants to represents countries.
static final @Fenum("country") String ITALY = "IT";
static final @Fenum("country") String US = "US";
static final @Fenum("country") String UNITED_KINGDOM = "UK";
// Here we use other String constants to represent planets instead.
static final @Fenum("planet") String MARS = "Mars";
static final @Fenum("planet") String EARTH = "Earth";
static final @Fenum("planet") String VENUS = "Venus";
// Now we write this method and we want to be sure that
// the String parameter has a value of a country, not that is just a String.
void greetCountries(@Fenum("country") String country) {
System.out.println("Hello " + country);
}
// Similarly we're enforcing here that the provided
// parameter is a String that represent a planet.
void greetPlanets(@Fenum("planet") String planet) {
System.out.println("Hello " + planet);
}
public static void main(String[] args) {
FakeNumExample obj = new FakeNumExample();
// This will fail because we pass a planet-String to a method that
// accept a country-String.
obj.greetCountries(MARS);
// Here the opposite happens.
obj.greetPlanets(US);
}
}

View File

@ -0,0 +1,23 @@
package com.baeldung.typechecker;
public class FormatExample {
public static void main(String[] args) {
// Just enabling org.checkerframework.checker.formatter.FormatterChecker
// we can be sure at compile time that the format strings we pass to format()
// are correct. Normally we would have those errors raised just at runtime.
// All those formats are in fact wrong.
String.format("%y", 7); // error: invalid format string
String.format("%d", "a string"); // error: invalid argument type for %d
String.format("%d %s", 7); // error: missing argument for %s
String.format("%d", 7, 3); // warning: unused argument 3
String.format("{0}", 7); // warning: unused argument 7, because {0} is wrong syntax
}
}

View File

@ -0,0 +1,31 @@
package com.baeldung.typechecker;
import org.checkerframework.checker.nullness.qual.KeyFor;
import java.util.HashMap;
import java.util.Map;
public class KeyForExample {
private final Map<String, String> config = new HashMap<>();
KeyForExample() {
// Here we initialize a map to store
// some config data.
config.put("url", "http://1.2.3.4");
config.put("name", "foobaz");
}
public void dumpPort() {
// Here, we want to dump the port value stored in the
// config, so we declare that this key has to be
// present in the config map.
// Obviously that will fail because such key is not present
// in the map.
@KeyFor("config") String key = "port";
System.out.println( config.get(key) );
}
}

View File

@ -0,0 +1,28 @@
package com.baeldung.typechecker;
import org.checkerframework.checker.nullness.qual.MonotonicNonNull;
import java.util.Date;
public class MonotonicNotNullExample {
// The idea is we need this field to be to lazily initialized,
// so it starts as null but once it becomes not null
// it cannot return null.
// In these cases, we can use @MonotonicNonNull
@MonotonicNonNull private Date firstCall;
public Date getFirstCall() {
if (firstCall == null) {
firstCall = new Date();
}
return firstCall;
}
public void reset() {
// This is reported as error because
// we wrongly set the field back to null.
firstCall = null;
}
}

View File

@ -0,0 +1,27 @@
package com.baeldung.typechecker;
import org.checkerframework.checker.nullness.qual.NonNull;
import org.checkerframework.checker.nullness.qual.Nullable;
public class NonNullExample {
// This method's parameter is annotated in order
// to tell the pluggable type system that it can never be null.
private static int countArgs(@NonNull String[] args) {
return args.length;
}
// This method's parameter is annotated in order
// to tell the pluggable type system that it may be null.
public static void main(@Nullable String[] args) {
// Here lies a potential error,
// because we pass a potential null reference to a method
// that does not accept nulls.
// The Checker Framework will spot this problem at compile time
// instead of runtime.
System.out.println(countArgs(args));
}
}

View File

@ -0,0 +1,18 @@
package com.baeldung.typechecker;
import org.checkerframework.checker.regex.qual.Regex;
public class RegexExample {
// For some reason we want to be sure that this regex
// contains at least one capturing group.
// However, we do an error and we forgot to define such
// capturing group in it.
@Regex(1) private static String findNumbers = "\\d*";
public static void main(String[] args) {
String message = "My phone number is +3911223344.";
message.matches(findNumbers);
}
}

View File

@ -1 +1,4 @@
# Groovy
## Relevant articles: ## Relevant articles:

13
core-groovy/build.gradle Normal file
View File

@ -0,0 +1,13 @@
group 'com.baeldung'
version '1.0-SNAPSHOT'
apply plugin: 'groovy'
repositories {
mavenCentral()
}
dependencies {
compile 'org.codehaus.groovy:groovy-all:2.4.13'
testCompile 'org.spockframework:spock-core:1.1-groovy-2.4'
}

128
core-groovy/pom.xml Normal file
View File

@ -0,0 +1,128 @@
<?xml version="1.0" encoding="UTF-8"?>
<project xmlns="http://maven.apache.org/POM/4.0.0" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd">
<modelVersion>4.0.0</modelVersion>
<artifactId>core-groovy</artifactId>
<version>1.0-SNAPSHOT</version>
<packaging>jar</packaging>
<parent>
<groupId>com.baeldung</groupId>
<artifactId>parent-modules</artifactId>
<version>1.0.0-SNAPSHOT</version>
</parent>
<repositories>
<repository>
<id>central</id>
<url>http://jcenter.bintray.com</url>
</repository>
</repositories>
<dependencies>
<dependency>
<groupId>org.codehaus.groovy</groupId>
<artifactId>groovy</artifactId>
<version>2.4.13</version>
</dependency>
<dependency>
<groupId>org.codehaus.groovy</groupId>
<artifactId>groovy-all</artifactId>
<version>2.4.13</version>
</dependency>
<dependency>
<groupId>org.codehaus.groovy</groupId>
<artifactId>groovy-sql</artifactId>
<version>2.4.13</version>
</dependency>
<dependency>
<groupId>org.junit.jupiter</groupId>
<artifactId>junit-jupiter-engine</artifactId>
<version>${junit.jupiter.version}</version>
<scope>test</scope>
</dependency>
<dependency>
<groupId>org.junit.platform</groupId>
<artifactId>junit-platform-runner</artifactId>
<version>${junit.platform.version}</version>
<scope>test</scope>
</dependency>
<dependency>
<groupId>org.hsqldb</groupId>
<artifactId>hsqldb</artifactId>
<version>2.4.0</version>
<scope>test</scope>
</dependency>
<dependency>
<groupId>org.spockframework</groupId>
<artifactId>spock-core</artifactId>
<version>1.1-groovy-2.4</version>
<scope>test</scope>
</dependency>
</dependencies>
<build>
<plugins>
<plugin>
<groupId>org.codehaus.gmavenplus</groupId>
<artifactId>gmavenplus-plugin</artifactId>
<version>1.6</version>
<executions>
<execution>
<goals>
<goal>addSources</goal>
<goal>addTestSources</goal>
<goal>compile</goal>
<goal>compileTests</goal>
</goals>
</execution>
</executions>
</plugin>
<plugin>
<artifactId>maven-surefire-plugin</artifactId>
<version>${maven-surefire-plugin.version}</version>
</plugin>
<plugin>
<artifactId>maven-failsafe-plugin</artifactId>
<version>2.19.1</version>
<dependencies>
<dependency>
<groupId>org.junit.platform</groupId>
<artifactId>junit-platform-surefire-provider</artifactId>
<version>${junit.platform.version}</version>
</dependency>
</dependencies>
<executions>
<execution>
<id>junit5</id>
<goals>
<goal>integration-test</goal>
<goal>verify</goal>
</goals>
<configuration>
<includes>
<include>**/*Test5.java</include>
</includes>
</configuration>
</execution>
</executions>
</plugin>
</plugins>
</build>
<properties>
<project.build.sourceEncoding>UTF-8</project.build.sourceEncoding>
<kotlin-maven-plugin.version>1.1.2</kotlin-maven-plugin.version>
<kotlin-test-junit.version>1.1.2</kotlin-test-junit.version>
<kotlin-stdlib.version>1.1.2</kotlin-stdlib.version>
<kotlin-reflect.version>1.1.2</kotlin-reflect.version>
<kotlinx.version>0.15</kotlinx.version>
<mockito-kotlin.version>1.5.0</mockito-kotlin.version>
<junit.jupiter.version>5.0.0</junit.jupiter.version>
<junit.platform.version>1.0.0</junit.platform.version>
<junit.vintage.version>4.12.0</junit.vintage.version>
<junit4.version>4.12</junit4.version>
</properties>
</project>

View File

@ -0,0 +1,7 @@
package com.baeldung.json
class Account {
String id
BigDecimal value
Date createdAt
}

View File

@ -0,0 +1,27 @@
package com.baeldung.json
import groovy.json.JsonOutput
import groovy.json.JsonParserType
import groovy.json.JsonSlurper
class JsonParser {
Account toObject(String json) {
JsonSlurper jsonSlurper = new JsonSlurper()
jsonSlurper.parseText(json) as Account
}
Account toObjectWithIndexOverlay(String json) {
JsonSlurper jsonSlurper = new JsonSlurper(type: JsonParserType.INDEX_OVERLAY)
jsonSlurper.parseText(json) as Account
}
String toJson(Account account) {
JsonOutput.toJson(account)
}
String prettyfy(String json) {
JsonOutput.prettyPrint(json)
}
}

View File

@ -0,0 +1,229 @@
package com.baeldung.groovy.sql
import groovy.sql.GroovyResultSet
import groovy.sql.GroovyRowResult
import groovy.sql.Sql
import groovy.transform.CompileStatic
import static org.junit.Assert.*
import org.junit.Test
class SqlTest {
final Map dbConnParams = [url: 'jdbc:hsqldb:mem:testDB', user: 'sa', password: '', driver: 'org.hsqldb.jdbc.JDBCDriver']
@Test
void whenNewSqlInstance_thenDbIsAccessed() {
def sql = Sql.newInstance(dbConnParams)
sql.close()
sql.close()
}
@Test
void whenTableDoesNotExist_thenSelectFails() {
try {
Sql.withInstance(dbConnParams) { Sql sql ->
sql.eachRow('select * from PROJECT') {}
}
fail("An exception should have been thrown")
} catch (ignored) {
//Ok
}
}
@Test
void whenTableCreated_thenSelectIsPossible() {
Sql.withInstance(dbConnParams) { Sql sql ->
def result = sql.execute 'create table PROJECT_1 (id integer not null, name varchar(50), url varchar(100))'
assertEquals(0, sql.updateCount)
assertFalse(result)
result = sql.execute('select * from PROJECT_1')
assertTrue(result)
}
}
@Test
void whenIdentityColumn_thenInsertReturnsNewId() {
Sql.withInstance(dbConnParams) { Sql sql ->
sql.execute 'create table PROJECT_2 (ID IDENTITY, NAME VARCHAR (50), URL VARCHAR (100))'
def ids = sql.executeInsert("INSERT INTO PROJECT_2 (NAME, URL) VALUES ('tutorials', 'github.com/eugenp/tutorials')")
assertEquals(0, ids[0][0])
ids = sql.executeInsert("INSERT INTO PROJECT_2 (NAME, URL) VALUES ('REST with Spring', 'github.com/eugenp/REST-With-Spring')")
assertEquals(1, ids[0][0])
}
}
@Test
void whenUpdate_thenNumberOfAffectedRows() {
Sql.withInstance(dbConnParams) { Sql sql ->
sql.execute 'create table PROJECT_3 (ID IDENTITY, NAME VARCHAR (50), URL VARCHAR (100))'
sql.executeInsert("INSERT INTO PROJECT_3 (NAME, URL) VALUES ('tutorials', 'github.com/eugenp/tutorials')")
sql.executeInsert("INSERT INTO PROJECT_3 (NAME, URL) VALUES ('REST with Spring', 'github.com/eugenp/REST-With-Spring')")
def count = sql.executeUpdate("UPDATE PROJECT_3 SET URL = 'https://' + URL")
assertEquals(2, count)
}
}
@Test
void whenEachRow_thenResultSetHasProperties() {
Sql.withInstance(dbConnParams) { Sql sql ->
sql.execute 'create table PROJECT_4 (ID IDENTITY, NAME VARCHAR (50), URL VARCHAR (100))'
sql.executeInsert("INSERT INTO PROJECT_4 (NAME, URL) VALUES ('tutorials', 'https://github.com/eugenp/tutorials')")
sql.executeInsert("INSERT INTO PROJECT_4 (NAME, URL) VALUES ('REST with Spring', 'https://github.com/eugenp/REST-With-Spring')")
sql.eachRow("SELECT * FROM PROJECT_4") { GroovyResultSet rs ->
assertNotNull(rs.name)
assertNotNull(rs.url)
assertNotNull(rs[0])
assertNotNull(rs[1])
assertNotNull(rs[2])
assertEquals(rs.name, rs['name'])
assertEquals(rs.url, rs['url'])
}
}
}
@Test
void whenPagination_thenSubsetIsReturned() {
Sql.withInstance(dbConnParams) { Sql sql ->
sql.execute 'create table PROJECT_5 (ID IDENTITY, NAME VARCHAR (50), URL VARCHAR (100))'
sql.executeInsert("INSERT INTO PROJECT_5 (NAME, URL) VALUES ('tutorials', 'github.com/eugenp/tutorials')")
sql.executeInsert("INSERT INTO PROJECT_5 (NAME, URL) VALUES ('REST with Spring', 'github.com/eugenp/REST-With-Spring')")
def rows = sql.rows('SELECT * FROM PROJECT_5 ORDER BY NAME', 1, 1)
assertEquals(1, rows.size())
assertEquals('REST with Spring', rows[0].name)
}
}
@Test
void whenParameters_thenReplacement() {
Sql.withInstance(dbConnParams) { Sql sql ->
sql.execute 'create table PROJECT_6 (ID IDENTITY, NAME VARCHAR (50), URL VARCHAR (100))'
sql.execute('INSERT INTO PROJECT_6 (NAME, URL) VALUES (?, ?)', 'tutorials', 'github.com/eugenp/tutorials')
sql.execute("INSERT INTO PROJECT_6 (NAME, URL) VALUES (:name, :url)", [name: 'REST with Spring', url: 'github.com/eugenp/REST-With-Spring'])
def rows = sql.rows("SELECT * FROM PROJECT_6 WHERE NAME = 'tutorials'")
assertEquals(1, rows.size())
rows = sql.rows("SELECT * FROM PROJECT_6 WHERE NAME = 'REST with Spring'")
assertEquals(1, rows.size())
}
}
@Test
void whenParametersInGString_thenReplacement() {
Sql.withInstance(dbConnParams) { Sql sql ->
sql.execute 'create table PROJECT_7 (ID IDENTITY, NAME VARCHAR (50), URL VARCHAR (100))'
sql.execute "INSERT INTO PROJECT_7 (NAME, URL) VALUES (${'tutorials'}, ${'github.com/eugenp/tutorials'})"
def name = 'REST with Spring'
def url = 'github.com/eugenp/REST-With-Spring'
sql.execute "INSERT INTO PROJECT_7 (NAME, URL) VALUES (${name}, ${url})"
def rows = sql.rows("SELECT * FROM PROJECT_7 WHERE NAME = 'tutorials'")
assertEquals(1, rows.size())
rows = sql.rows("SELECT * FROM PROJECT_7 WHERE NAME = 'REST with Spring'")
assertEquals(1, rows.size())
}
}
@Test
void whenTransactionRollback_thenNoDataInserted() {
Sql.withInstance(dbConnParams) { Sql sql ->
sql.withTransaction {
sql.execute 'create table PROJECT_8 (ID IDENTITY, NAME VARCHAR (50), URL VARCHAR (100))'
sql.executeInsert("INSERT INTO PROJECT_8 (NAME, URL) VALUES ('tutorials', 'https://github.com/eugenp/tutorials')")
sql.executeInsert("INSERT INTO PROJECT_8 (NAME, URL) VALUES ('REST with Spring', 'https://github.com/eugenp/REST-With-Spring')")
sql.rollback()
def rows = sql.rows("SELECT * FROM PROJECT_8")
assertEquals(0, rows.size())
}
}
}
@Test
void whenTransactionRollbackThenCommit_thenOnlyLastInserted() {
Sql.withInstance(dbConnParams) { Sql sql ->
sql.withTransaction {
sql.execute 'create table PROJECT_9 (ID IDENTITY, NAME VARCHAR (50), URL VARCHAR (100))'
sql.executeInsert("INSERT INTO PROJECT_9 (NAME, URL) VALUES ('tutorials', 'https://github.com/eugenp/tutorials')")
sql.rollback()
sql.executeInsert("INSERT INTO PROJECT_9 (NAME, URL) VALUES ('REST with Spring', 'https://github.com/eugenp/REST-With-Spring')")
sql.rollback()
sql.executeInsert("INSERT INTO PROJECT_9 (NAME, URL) VALUES ('tutorials', 'https://github.com/eugenp/tutorials')")
sql.executeInsert("INSERT INTO PROJECT_9 (NAME, URL) VALUES ('REST with Spring', 'https://github.com/eugenp/REST-With-Spring')")
}
def rows = sql.rows("SELECT * FROM PROJECT_9")
assertEquals(2, rows.size())
}
}
@Test
void whenException_thenTransactionIsRolledBack() {
Sql.withInstance(dbConnParams) { Sql sql ->
try {
sql.withTransaction {
sql.execute 'create table PROJECT_10 (ID IDENTITY, NAME VARCHAR (50), URL VARCHAR (100))'
sql.executeInsert("INSERT INTO PROJECT_10 (NAME, URL) VALUES ('tutorials', 'https://github.com/eugenp/tutorials')")
throw new Exception('rollback')
}
} catch (ignored) {}
def rows = sql.rows("SELECT * FROM PROJECT_10")
assertEquals(0, rows.size())
}
}
@Test
void givenCachedConnection_whenException_thenDataIsPersisted() {
Sql.withInstance(dbConnParams) { Sql sql ->
try {
sql.cacheConnection {
sql.execute 'create table PROJECT_11 (ID IDENTITY, NAME VARCHAR (50), URL VARCHAR (100))'
sql.executeInsert("INSERT INTO PROJECT_11 (NAME, URL) VALUES ('tutorials', 'https://github.com/eugenp/tutorials')")
throw new Exception('This does not rollback')
}
} catch (ignored) {}
def rows = sql.rows("SELECT * FROM PROJECT_11")
assertEquals(1, rows.size())
}
}
/*@Test
void whenModifyResultSet_thenDataIsChanged() {
Sql.withInstance(dbConnParams) { Sql sql ->
sql.execute 'create table PROJECT_5 (ID IDENTITY, NAME VARCHAR (50), URL VARCHAR (100))'
sql.executeInsert("INSERT INTO PROJECT_5 (NAME, URL) VALUES ('tutorials', 'github.com/eugenp/tutorials')")
sql.executeInsert("INSERT INTO PROJECT_5 (NAME, URL) VALUES ('REST with Spring', 'github.com/eugenp/REST-With-Spring')")
sql.eachRow("SELECT * FROM PROJECT_5 FOR UPDATE ") { GroovyResultSet rs ->
rs['name'] = "The great ${rs.name}!" as String
rs.updateRow()
}
sql.eachRow("SELECT * FROM PROJECT_5") { GroovyResultSet rs ->
assertTrue(rs.name.startsWith('The great '))
}
}
}*/
}

View File

@ -0,0 +1,66 @@
package com.baeldung.json
import spock.lang.Specification
import java.text.SimpleDateFormat
class JsonParserTest extends Specification {
JsonParser jsonParser
void setup () {
jsonParser = new JsonParser()
}
def 'Should parse to Account given Json String' () {
given:
def json = '{"id":"1234","value":15.6}'
when:
def account = jsonParser.toObject(json)
then:
account
account instanceof Account
account.id == '1234'
account.value == 15.6
}
def 'Should parse to Account given Json String with date property' () {
given:
def json = '{"id":"1234","value":15.6,"createdAt":"2018-01-01T00:00:00+0000"}'
when:
def account = jsonParser.toObjectWithIndexOverlay(json)
then:
account
account instanceof Account
account.id == '1234'
account.value == 15.6
println account.createdAt
account.createdAt == Date.parse('yyyy-MM-dd', '2018-01-01')
}
def 'Should parse to Json given an Account object' () {
given:
Account account = new Account(
id: '123',
value: 15.6,
createdAt: new SimpleDateFormat('MM/dd/yyyy').parse('01/01/2018')
)
when:
def json = jsonParser.toJson(account)
then:
json
json == '{"value":15.6,"createdAt":"2018-01-01T00:00:00+0000","id":"123"}'
}
def 'Should prettify given a json string' () {
given:
String json = '{"value":15.6,"createdAt":"01/01/2018","id":"123456"}'
when:
def jsonPretty = jsonParser.prettyfy(json)
then:
jsonPretty
jsonPretty == '{\n "value": 15.6,\n "createdAt": "01/01/2018",\n "id": "123456"\n}'
}
}

View File

@ -30,3 +30,16 @@
- [The Difference Between map() and flatMap()](http://www.baeldung.com/java-difference-map-and-flatmap) - [The Difference Between map() and flatMap()](http://www.baeldung.com/java-difference-map-and-flatmap)
- [Merging Streams in Java](http://www.baeldung.com/java-merge-streams) - [Merging Streams in Java](http://www.baeldung.com/java-merge-streams)
- [“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)
- [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)
- [Iterable to Stream in Java](http://www.baeldung.com/java-iterable-to-stream)
- [Converting String to Stream of chars](http://www.baeldung.com/java-string-to-stream)
- [How to Iterate Over a Stream With Indices](http://www.baeldung.com/java-stream-indices)
- [Efficient Word Frequency Calculator in Java](http://www.baeldung.com/java-word-frequency)
- [Primitive Type Streams in Java 8](http://www.baeldung.com/java-8-primitive-streams)
- [Fail-Safe Iterator vs Fail-Fast Iterator](http://www.baeldung.com/java-fail-safe-vs-fail-fast-iterator)
- [Shuffling Collections In Java](http://www.baeldung.com/java-shuffle-collection)
- [Java 8 StringJoiner](http://www.baeldung.com/java-string-joiner)
- [Introduction to Spliterator in Java](http://www.baeldung.com/java-spliterator)

View File

@ -83,6 +83,41 @@
<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>
<dependency>
<groupId>com.codepoetics</groupId>
<artifactId>protonpack</artifactId>
<version>${protonpack.version}</version>
</dependency>
<dependency>
<groupId>io.vavr</groupId>
<artifactId>vavr</artifactId>
<version>${vavr.version}</version>
</dependency>
<dependency>
<groupId>one.util</groupId>
<artifactId>streamex</artifactId>
<version>${streamex.version}</version>
</dependency>
</dependencies> </dependencies>
<build> <build>
@ -249,6 +284,9 @@
<collections-generic.version>4.01</collections-generic.version> <collections-generic.version>4.01</collections-generic.version>
<commons-codec.version>1.10</commons-codec.version> <commons-codec.version>1.10</commons-codec.version>
<lombok.version>1.16.12</lombok.version> <lombok.version>1.16.12</lombok.version>
<vavr.version>0.9.0</vavr.version>
<protonpack.version>1.13</protonpack.version>
<streamex.version>0.6.5</streamex.version>
<!-- testing --> <!-- testing -->
<assertj.version>3.6.1</assertj.version> <assertj.version>3.6.1</assertj.version>

View File

@ -0,0 +1,5 @@
package com.baeldung.annotations;
@Deprecated
class ClassWithAnnotation {
}

View File

@ -0,0 +1,9 @@
package com.baeldung.annotations;
class ClassWithDeprecatedMethod {
@Deprecated
static void deprecatedMethod() {
}
}

Some files were not shown because too many files have changed in this diff Show More