commit
aba7e71359
16
.gitignore
vendored
16
.gitignore
vendored
@ -19,6 +19,7 @@
|
||||
.idea/
|
||||
*.iml
|
||||
*.iws
|
||||
out/
|
||||
|
||||
# Mac
|
||||
.DS_Store
|
||||
@ -27,6 +28,9 @@
|
||||
log/
|
||||
target/
|
||||
|
||||
# Gradle
|
||||
.gradle/
|
||||
|
||||
spring-openid/src/main/resources/application.properties
|
||||
.recommenders/
|
||||
/spring-hibernate4/nbproject/
|
||||
@ -62,3 +66,15 @@ jmeter/src/main/resources/*-JMeter.csv
|
||||
**/dist
|
||||
**/tmp
|
||||
**/out-tsc
|
||||
**/nbproject/
|
||||
**/nb-configuration.xml
|
||||
core-scala/.cache-main
|
||||
core-scala/.cache-tests
|
||||
|
||||
|
||||
persistence-modules/hibernate5/transaction.log
|
||||
apache-avro/src/main/java/com/baeldung/avro/model/
|
||||
jta/transaction-logs/
|
||||
software-security/sql-injection-samples/derby.log
|
||||
spring-soap/src/main/java/com/baeldung/springsoap/gen/
|
||||
/report-*.json
|
@ -4,7 +4,7 @@ before_install:
|
||||
- echo "MAVEN_OPTS='-Xmx2048M -Xss128M -XX:+CMSClassUnloadingEnabled -XX:+UseG1GC -XX:-UseGCOverheadLimit'" > ~/.mavenrc
|
||||
|
||||
install: skip
|
||||
script: travis_wait 60 mvn -q install -Pdefault
|
||||
script: travis_wait 60 mvn -q install -Pdefault-first,default-second -Dgib.enabled=true
|
||||
|
||||
sudo: required
|
||||
|
||||
|
@ -5,9 +5,9 @@
|
||||
<groupId>com.baeldung</groupId>
|
||||
<artifactId>JGit</artifactId>
|
||||
<version>1.0-SNAPSHOT</version>
|
||||
<name>JGit</name>
|
||||
<packaging>jar</packaging>
|
||||
<url>http://maven.apache.org</url>
|
||||
<name>JGit</name>
|
||||
|
||||
<parent>
|
||||
<groupId>com.baeldung</groupId>
|
||||
|
@ -28,14 +28,14 @@ public class Log {
|
||||
System.out.println("Had " + count + " commits overall on current branch");
|
||||
|
||||
logs = git.log()
|
||||
.add(repository.resolve("remotes/origin/testbranch"))
|
||||
.add(repository.resolve(git.getRepository().getFullBranch()))
|
||||
.call();
|
||||
count = 0;
|
||||
for (RevCommit rev : logs) {
|
||||
System.out.println("Commit: " + rev /* + ", name: " + rev.getName() + ", id: " + rev.getId().getName() */);
|
||||
count++;
|
||||
}
|
||||
System.out.println("Had " + count + " commits overall on test-branch");
|
||||
System.out.println("Had " + count + " commits overall on "+git.getRepository().getFullBranch());
|
||||
|
||||
logs = git.log()
|
||||
.all()
|
||||
|
@ -1,3 +1,5 @@
|
||||
package com.baeldung.jgit;
|
||||
|
||||
import com.baeldung.jgit.helper.Helper;
|
||||
import org.eclipse.jgit.lib.ObjectLoader;
|
||||
import org.eclipse.jgit.lib.ObjectReader;
|
||||
|
43
README.md
43
README.md
@ -2,41 +2,42 @@
|
||||
The "REST with Spring" Classes
|
||||
==============================
|
||||
|
||||
Here's the Master Class of REST With Spring (price changes permanently next Friday): <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)**
|
||||
Here's the Master Class of REST With Spring (along with the newly announced Boot 2 material): <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)**
|
||||
|
||||
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)**
|
||||
**[>> 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
|
||||
Java and Spring Tutorials
|
||||
================
|
||||
|
||||
This project is **a collection of small and focused tutorials** each covering a single and well defined area of development.
|
||||
Most of the tutorial projects are focused on the `Spring Framework` (and `Spring Security`).
|
||||
This project is **a collection of small and focused tutorials** - each covering a single and well defined area of development in the Java ecosystem.
|
||||
A strong focus of these is, of course, the Spring Framework - Spring, Spring Boot and Spring Security.
|
||||
In additional to Spring, the following technologies are in focus: `core Java`, `Jackson`, `HttpClient`, `Guava`.
|
||||
|
||||
|
||||
Building the project
|
||||
====================
|
||||
To do the full build, do: `mvn install -Pdefault -Dgib.enabled=false`
|
||||
To do the full build, do: `mvn clean install`
|
||||
|
||||
|
||||
Working with the code in Eclipse
|
||||
================================
|
||||
Any IDE can be used to work with the projects, but if you're using Eclipse, consider the following.
|
||||
|
||||
- import the included **formatter** in Eclipse:
|
||||
`https://github.com/eugenp/tutorials/tree/master/eclipse`
|
||||
Building a single module
|
||||
====================
|
||||
To build a specific module run the command: `mvn clean install` in the module directory
|
||||
|
||||
|
||||
Running a Spring Boot module
|
||||
====================
|
||||
To run a Spring Boot module run the command: `mvn spring-boot:run` in the module directory
|
||||
|
||||
#Running Tests
|
||||
|
||||
The command `mvn clean install` will run the unit tests in a module.
|
||||
To run the integration tests, use the command `mvn clean install -Pintegration-lite-first`
|
||||
|
||||
|
||||
|
||||
CI - Jenkins
|
||||
================================
|
||||
This tutorials project is being built **[>> HERE](https://rest-security.ci.cloudbees.com/job/tutorials-unit/)**
|
||||
|
||||
### Relevant Articles:
|
||||
================================
|
||||
|
||||
- [Apache Maven Standard Directory Layout](http://www.baeldung.com/maven-directory-structure)
|
||||
- [Apache Maven Tutorial](http://www.baeldung.com/maven)
|
||||
- [Designing a User Friendly Java Library](http://www.baeldung.com/design-a-user-friendly-java-library)
|
||||
|
@ -1,13 +1,9 @@
|
||||
<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/maven-v4_0_0.xsd">
|
||||
<modelVersion>4.0.0</modelVersion>
|
||||
|
||||
<groupId>com.mabsisa</groupId>
|
||||
<artifactId>Twitter4J</artifactId>
|
||||
<packaging>jar</packaging>
|
||||
<version>1.0-SNAPSHOT</version>
|
||||
<name>Twitter4J</name>
|
||||
<url>http://maven.apache.org</url>
|
||||
<packaging>jar</packaging>
|
||||
|
||||
<parent>
|
||||
<groupId>com.baeldung</groupId>
|
||||
@ -23,27 +19,6 @@
|
||||
</dependency>
|
||||
</dependencies>
|
||||
|
||||
<build>
|
||||
<finalName>${project.artifactId}</finalName>
|
||||
<resources>
|
||||
<resource>
|
||||
<directory>src/main/resources</directory>
|
||||
</resource>
|
||||
</resources>
|
||||
<plugins>
|
||||
<plugin>
|
||||
<groupId>org.apache.maven.plugins</groupId>
|
||||
<artifactId>maven-surefire-plugin</artifactId>
|
||||
<version>${maven-surefire-plugin.version}</version>
|
||||
<configuration>
|
||||
<excludes>
|
||||
<exclude>**/ApplicationTest.java</exclude>
|
||||
</excludes>
|
||||
</configuration>
|
||||
</plugin>
|
||||
</plugins>
|
||||
</build>
|
||||
|
||||
<properties>
|
||||
<twitter4j-stream.version>4.0.6</twitter4j-stream.version>
|
||||
</properties>
|
||||
|
@ -1,135 +0,0 @@
|
||||
<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>
|
||||
|
||||
<parent>
|
||||
<artifactId>parent-modules</artifactId>
|
||||
<groupId>com.baeldung</groupId>
|
||||
<version>1.0.0-SNAPSHOT</version>
|
||||
</parent>
|
||||
|
||||
<dependencies>
|
||||
<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>${mysql.connector.version}</version>
|
||||
</dependency>
|
||||
<dependency>
|
||||
<groupId>org.slf4j</groupId>
|
||||
<artifactId>slf4j-simple</artifactId>
|
||||
<version>${org.slf4j.version}</version>
|
||||
</dependency>
|
||||
</dependencies>
|
||||
|
||||
<build>
|
||||
<plugins>
|
||||
<plugin>
|
||||
<groupId>org.apache.maven.plugins</groupId>
|
||||
<artifactId>maven-compiler-plugin</artifactId>
|
||||
<version>${maven-compiler-plugin.version}</version>
|
||||
<configuration>
|
||||
<source>${java.version}</source>
|
||||
<target>${java.version}</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>${mysql.connector.version}</version>
|
||||
</dependency>
|
||||
</dependencies>
|
||||
</plugin>
|
||||
<plugin>
|
||||
<groupId>org.apache.maven.plugins</groupId>
|
||||
<artifactId>maven-surefire-plugin</artifactId>
|
||||
<version>${maven-surefire-plugin.version}</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>
|
||||
|
||||
<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>
|
||||
|
||||
<properties>
|
||||
<activejdbc.version>1.4.13</activejdbc.version>
|
||||
<environments>development.test,development</environments>
|
||||
<mysql.connector.version>5.1.34</mysql.connector.version>
|
||||
</properties>
|
||||
|
||||
</project>
|
@ -1,19 +0,0 @@
|
||||
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);
|
||||
}
|
||||
|
||||
}
|
@ -1,51 +0,0 @@
|
||||
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();
|
||||
}
|
||||
}
|
3
akka-http/README.md
Normal file
3
akka-http/README.md
Normal file
@ -0,0 +1,3 @@
|
||||
## Relevant articles:
|
||||
|
||||
- [Introduction to Akka HTTP](https://www.baeldung.com/akka-http)
|
47
akka-http/pom.xml
Normal file
47
akka-http/pom.xml
Normal file
@ -0,0 +1,47 @@
|
||||
<?xml version="1.0"?>
|
||||
<project
|
||||
xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd"
|
||||
xmlns="http://maven.apache.org/POM/4.0.0"
|
||||
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance">
|
||||
|
||||
<modelVersion>4.0.0</modelVersion>
|
||||
<artifactId>akka-http</artifactId>
|
||||
<name>akka-http</name>
|
||||
|
||||
<parent>
|
||||
<artifactId>parent-modules</artifactId>
|
||||
<groupId>com.baeldung</groupId>
|
||||
<version>1.0.0-SNAPSHOT</version>
|
||||
</parent>
|
||||
|
||||
<dependencies>
|
||||
<dependency>
|
||||
<groupId>com.typesafe.akka</groupId>
|
||||
<artifactId>akka-http_2.12</artifactId>
|
||||
<version>${akka.http.version}</version>
|
||||
</dependency>
|
||||
<dependency>
|
||||
<groupId>com.typesafe.akka</groupId>
|
||||
<artifactId>akka-stream_2.12</artifactId>
|
||||
<version>${akka.stream.version}</version>
|
||||
</dependency>
|
||||
<dependency>
|
||||
<groupId>com.typesafe.akka</groupId>
|
||||
<artifactId>akka-http-jackson_2.12</artifactId>
|
||||
<version>${akka.http.version}</version>
|
||||
</dependency>
|
||||
<dependency>
|
||||
<groupId>com.typesafe.akka</groupId>
|
||||
<artifactId>akka-http-testkit_2.12</artifactId>
|
||||
<version>${akka.http.version}</version>
|
||||
<scope>test</scope>
|
||||
</dependency>
|
||||
</dependencies>
|
||||
|
||||
<properties>
|
||||
<project.build.sourceEncoding>UTF-8</project.build.sourceEncoding>
|
||||
<project.reporting.outputEncoding>UTF-8</project.reporting.outputEncoding>
|
||||
<akka.http.version>10.0.11</akka.http.version>
|
||||
<akka.stream.version>2.5.11</akka.stream.version>
|
||||
</properties>
|
||||
</project>
|
26
akka-http/src/main/java/com/baeldung/akkahttp/User.java
Normal file
26
akka-http/src/main/java/com/baeldung/akkahttp/User.java
Normal file
@ -0,0 +1,26 @@
|
||||
package com.baeldung.akkahttp;
|
||||
|
||||
public class User {
|
||||
|
||||
private final Long id;
|
||||
|
||||
private final String name;
|
||||
|
||||
public User() {
|
||||
this.name = "";
|
||||
this.id = null;
|
||||
}
|
||||
|
||||
public User(Long id, String name) {
|
||||
this.name = name;
|
||||
this.id = id;
|
||||
}
|
||||
|
||||
public String getName() {
|
||||
return name;
|
||||
}
|
||||
|
||||
public Long getId() {
|
||||
return id;
|
||||
}
|
||||
}
|
41
akka-http/src/main/java/com/baeldung/akkahttp/UserActor.java
Normal file
41
akka-http/src/main/java/com/baeldung/akkahttp/UserActor.java
Normal file
@ -0,0 +1,41 @@
|
||||
package com.baeldung.akkahttp;
|
||||
|
||||
import akka.actor.AbstractActor;
|
||||
import akka.actor.Props;
|
||||
import akka.japi.pf.FI;
|
||||
import com.baeldung.akkahttp.UserMessages.ActionPerformed;
|
||||
import com.baeldung.akkahttp.UserMessages.CreateUserMessage;
|
||||
import com.baeldung.akkahttp.UserMessages.GetUserMessage;
|
||||
|
||||
|
||||
class UserActor extends AbstractActor {
|
||||
|
||||
private UserService userService = new UserService();
|
||||
|
||||
static Props props() {
|
||||
return Props.create(UserActor.class);
|
||||
}
|
||||
|
||||
@Override
|
||||
public Receive createReceive() {
|
||||
return receiveBuilder()
|
||||
.match(CreateUserMessage.class, handleCreateUser())
|
||||
.match(GetUserMessage.class, handleGetUser())
|
||||
.build();
|
||||
}
|
||||
|
||||
private FI.UnitApply<CreateUserMessage> handleCreateUser() {
|
||||
return createUserMessageMessage -> {
|
||||
userService.createUser(createUserMessageMessage.getUser());
|
||||
sender().tell(new ActionPerformed(String.format("User %s created.", createUserMessageMessage.getUser()
|
||||
.getName())), getSelf());
|
||||
};
|
||||
}
|
||||
|
||||
private FI.UnitApply<GetUserMessage> handleGetUser() {
|
||||
return getUserMessageMessage -> {
|
||||
sender().tell(userService.getUser(getUserMessageMessage.getUserId()), getSelf());
|
||||
};
|
||||
}
|
||||
|
||||
}
|
@ -0,0 +1,49 @@
|
||||
package com.baeldung.akkahttp;
|
||||
|
||||
import java.io.Serializable;
|
||||
|
||||
public interface UserMessages {
|
||||
|
||||
class ActionPerformed implements Serializable {
|
||||
|
||||
private static final long serialVersionUID = 1L;
|
||||
|
||||
private final String description;
|
||||
|
||||
public ActionPerformed(String description) {
|
||||
this.description = description;
|
||||
}
|
||||
|
||||
public String getDescription() {
|
||||
return description;
|
||||
}
|
||||
}
|
||||
|
||||
class CreateUserMessage implements Serializable {
|
||||
|
||||
private static final long serialVersionUID = 1L;
|
||||
private final User user;
|
||||
|
||||
public CreateUserMessage(User user) {
|
||||
this.user = user;
|
||||
}
|
||||
|
||||
public User getUser() {
|
||||
return user;
|
||||
}
|
||||
}
|
||||
|
||||
class GetUserMessage implements Serializable {
|
||||
private static final long serialVersionUID = 1L;
|
||||
private final Long userId;
|
||||
|
||||
public GetUserMessage(Long userId) {
|
||||
this.userId = userId;
|
||||
}
|
||||
|
||||
public Long getUserId() {
|
||||
return userId;
|
||||
}
|
||||
}
|
||||
|
||||
}
|
@ -0,0 +1,70 @@
|
||||
package com.baeldung.akkahttp;
|
||||
|
||||
import java.util.Optional;
|
||||
import java.util.concurrent.CompletionStage;
|
||||
import java.util.concurrent.TimeUnit;
|
||||
|
||||
import akka.actor.ActorRef;
|
||||
import akka.actor.ActorSystem;
|
||||
import akka.http.javadsl.marshallers.jackson.Jackson;
|
||||
import akka.http.javadsl.model.StatusCodes;
|
||||
import akka.http.javadsl.server.HttpApp;
|
||||
import akka.http.javadsl.server.Route;
|
||||
import akka.pattern.PatternsCS;
|
||||
import akka.util.Timeout;
|
||||
import com.baeldung.akkahttp.UserMessages.ActionPerformed;
|
||||
import com.baeldung.akkahttp.UserMessages.CreateUserMessage;
|
||||
import com.baeldung.akkahttp.UserMessages.GetUserMessage;
|
||||
import scala.concurrent.duration.Duration;
|
||||
import static akka.http.javadsl.server.PathMatchers.*;
|
||||
|
||||
class UserServer extends HttpApp {
|
||||
|
||||
private final ActorRef userActor;
|
||||
|
||||
Timeout timeout = new Timeout(Duration.create(5, TimeUnit.SECONDS));
|
||||
|
||||
UserServer(ActorRef userActor) {
|
||||
this.userActor = userActor;
|
||||
}
|
||||
|
||||
@Override
|
||||
public Route routes() {
|
||||
return path("users", this::postUser)
|
||||
.orElse(path(segment("users").slash(longSegment()), id ->
|
||||
route(getUser(id))));
|
||||
}
|
||||
|
||||
private Route getUser(Long id) {
|
||||
return get(() -> {
|
||||
CompletionStage<Optional<User>> user = PatternsCS.ask(userActor, new GetUserMessage(id), timeout)
|
||||
.thenApply(obj -> (Optional<User>) obj);
|
||||
|
||||
return onSuccess(() -> user, performed -> {
|
||||
if (performed.isPresent())
|
||||
return complete(StatusCodes.OK, performed.get(), Jackson.marshaller());
|
||||
else
|
||||
return complete(StatusCodes.NOT_FOUND);
|
||||
});
|
||||
});
|
||||
}
|
||||
|
||||
private Route postUser() {
|
||||
return route(post(() -> entity(Jackson.unmarshaller(User.class), user -> {
|
||||
CompletionStage<ActionPerformed> userCreated = PatternsCS.ask(userActor, new CreateUserMessage(user), timeout)
|
||||
.thenApply(obj -> (ActionPerformed) obj);
|
||||
|
||||
return onSuccess(() -> userCreated, performed -> {
|
||||
return complete(StatusCodes.CREATED, performed, Jackson.marshaller());
|
||||
});
|
||||
})));
|
||||
}
|
||||
|
||||
public static void main(String[] args) throws Exception {
|
||||
ActorSystem system = ActorSystem.create("userServer");
|
||||
ActorRef userActor = system.actorOf(UserActor.props(), "userActor");
|
||||
UserServer server = new UserServer(userActor);
|
||||
server.startServer("localhost", 8080, system);
|
||||
}
|
||||
|
||||
}
|
@ -0,0 +1,35 @@
|
||||
package com.baeldung.akkahttp;
|
||||
|
||||
import java.util.ArrayList;
|
||||
import java.util.List;
|
||||
import java.util.Optional;
|
||||
|
||||
public class UserService {
|
||||
|
||||
private final static List<User> users = new ArrayList<>();
|
||||
|
||||
static {
|
||||
users.add(new User(1l, "Alice"));
|
||||
users.add(new User(2l, "Bob"));
|
||||
users.add(new User(3l, "Chris"));
|
||||
users.add(new User(4l, "Dick"));
|
||||
users.add(new User(5l, "Eve"));
|
||||
users.add(new User(6l, "Finn"));
|
||||
}
|
||||
|
||||
public Optional<User> getUser(Long id) {
|
||||
return users.stream()
|
||||
.filter(user -> user.getId()
|
||||
.equals(id))
|
||||
.findFirst();
|
||||
}
|
||||
|
||||
public void createUser(User user) {
|
||||
users.add(user);
|
||||
}
|
||||
|
||||
public List<User> getUsers(){
|
||||
return users;
|
||||
}
|
||||
|
||||
}
|
@ -0,0 +1,50 @@
|
||||
package com.baeldung.akkahttp;
|
||||
|
||||
import akka.actor.ActorRef;
|
||||
import akka.actor.ActorSystem;
|
||||
import akka.http.javadsl.model.ContentTypes;
|
||||
import akka.http.javadsl.model.HttpEntities;
|
||||
import akka.http.javadsl.model.HttpRequest;
|
||||
import akka.http.javadsl.testkit.JUnitRouteTest;
|
||||
import akka.http.javadsl.testkit.TestRoute;
|
||||
import org.junit.Test;
|
||||
|
||||
public class UserServerUnitTest extends JUnitRouteTest {
|
||||
|
||||
ActorSystem system = ActorSystem.create("helloAkkaHttpServer");
|
||||
|
||||
ActorRef userActorRef = system.actorOf(UserActor.props(), "userActor");
|
||||
|
||||
TestRoute appRoute = testRoute(new UserServer(userActorRef).routes());
|
||||
|
||||
@Test
|
||||
public void whenRequest_thenActorResponds() {
|
||||
|
||||
appRoute.run(HttpRequest.GET("/users/1"))
|
||||
.assertEntity(alice())
|
||||
.assertStatusCode(200);
|
||||
|
||||
appRoute.run(HttpRequest.GET("/users/42"))
|
||||
.assertStatusCode(404);
|
||||
|
||||
appRoute.run(HttpRequest.DELETE("/users/1"))
|
||||
.assertStatusCode(200);
|
||||
|
||||
appRoute.run(HttpRequest.DELETE("/users/42"))
|
||||
.assertStatusCode(200);
|
||||
|
||||
appRoute.run(HttpRequest.POST("/users")
|
||||
.withEntity(HttpEntities.create(ContentTypes.APPLICATION_JSON, zaphod())))
|
||||
.assertStatusCode(201);
|
||||
|
||||
}
|
||||
|
||||
private String alice() {
|
||||
return "{\"id\":1,\"name\":\"Alice\"}";
|
||||
}
|
||||
|
||||
private String zaphod() {
|
||||
return "{\"id\":42,\"name\":\"Zaphod\"}";
|
||||
}
|
||||
|
||||
}
|
@ -14,18 +14,19 @@
|
||||
<dependencies>
|
||||
<dependency>
|
||||
<groupId>com.typesafe.akka</groupId>
|
||||
<artifactId>akka-stream_2.11</artifactId>
|
||||
<artifactId>akka-stream_${scala.version}</artifactId>
|
||||
<version>${akkastreams.version}</version>
|
||||
</dependency>
|
||||
<dependency>
|
||||
<groupId>com.typesafe.akka</groupId>
|
||||
<artifactId>akka-stream-testkit_2.11</artifactId>
|
||||
<artifactId>akka-stream-testkit_${scala.version}</artifactId>
|
||||
<version>${akkastreams.version}</version>
|
||||
</dependency>
|
||||
</dependencies>
|
||||
|
||||
<properties>
|
||||
<akkastreams.version>2.5.2</akkastreams.version>
|
||||
<scala.version>2.11</scala.version>
|
||||
</properties>
|
||||
|
||||
</project>
|
4
algorithms-genetic/.gitignore
vendored
Normal file
4
algorithms-genetic/.gitignore
vendored
Normal file
@ -0,0 +1,4 @@
|
||||
/target/
|
||||
.settings/
|
||||
.classpath
|
||||
.project
|
6
algorithms-genetic/README.md
Normal file
6
algorithms-genetic/README.md
Normal file
@ -0,0 +1,6 @@
|
||||
## Relevant articles:
|
||||
|
||||
- [Introduction to Jenetics Library](http://www.baeldung.com/jenetics)
|
||||
- [Ant Colony Optimization](http://www.baeldung.com/java-ant-colony-optimization)
|
||||
- [Design a Genetic Algorithm in Java](https://www.baeldung.com/java-genetic-algorithm)
|
||||
- [The Traveling Salesman Problem in Java](https://www.baeldung.com/java-simulated-annealing-for-traveling-salesman)
|
64
algorithms-genetic/pom.xml
Normal file
64
algorithms-genetic/pom.xml
Normal file
@ -0,0 +1,64 @@
|
||||
<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>algorithms-genetic</artifactId>
|
||||
<version>0.0.1-SNAPSHOT</version>
|
||||
<name>algorithms-genetic</name>
|
||||
|
||||
<parent>
|
||||
<groupId>com.baeldung</groupId>
|
||||
<artifactId>parent-modules</artifactId>
|
||||
<version>1.0.0-SNAPSHOT</version>
|
||||
</parent>
|
||||
|
||||
<dependencies>
|
||||
<dependency>
|
||||
<groupId>org.apache.commons</groupId>
|
||||
<artifactId>commons-math3</artifactId>
|
||||
<version>${commons-math3.version}</version>
|
||||
</dependency>
|
||||
<dependency>
|
||||
<groupId>commons-codec</groupId>
|
||||
<artifactId>commons-codec</artifactId>
|
||||
<version>${commons-codec.version}</version>
|
||||
</dependency>
|
||||
<dependency>
|
||||
<groupId>org.projectlombok</groupId>
|
||||
<artifactId>lombok</artifactId>
|
||||
<version>${lombok.version}</version>
|
||||
<scope>provided</scope>
|
||||
</dependency>
|
||||
<dependency>
|
||||
<groupId>io.jenetics</groupId>
|
||||
<artifactId>jenetics</artifactId>
|
||||
<version>${io.jenetics.version}</version>
|
||||
</dependency>
|
||||
<dependency>
|
||||
<groupId>org.assertj</groupId>
|
||||
<artifactId>assertj-core</artifactId>
|
||||
<version>${org.assertj.core.version}</version>
|
||||
<scope>test</scope>
|
||||
</dependency>
|
||||
</dependencies>
|
||||
|
||||
<build>
|
||||
<pluginManagement>
|
||||
<plugins>
|
||||
<plugin>
|
||||
<groupId>org.codehaus.mojo</groupId>
|
||||
<artifactId>exec-maven-plugin</artifactId>
|
||||
<version>${exec-maven-plugin.version}</version>
|
||||
</plugin>
|
||||
</plugins>
|
||||
</pluginManagement>
|
||||
</build>
|
||||
|
||||
<properties>
|
||||
<commons-math3.version>3.6.1</commons-math3.version>
|
||||
<io.jenetics.version>3.7.0</io.jenetics.version>
|
||||
<org.assertj.core.version>3.9.0</org.assertj.core.version>
|
||||
<commons-codec.version>1.11</commons-codec.version>
|
||||
</properties>
|
||||
|
||||
|
||||
</project>
|
@ -0,0 +1,38 @@
|
||||
package com.baeldung.algorithms;
|
||||
|
||||
import java.util.Scanner;
|
||||
|
||||
import com.baeldung.algorithms.ga.annealing.SimulatedAnnealing;
|
||||
import com.baeldung.algorithms.ga.ant_colony.AntColonyOptimization;
|
||||
import com.baeldung.algorithms.ga.binary.SimpleGeneticAlgorithm;
|
||||
|
||||
public class RunAlgorithm {
|
||||
|
||||
public static void main(String[] args) throws InstantiationException, IllegalAccessException {
|
||||
Scanner in = new Scanner(System.in);
|
||||
System.out.println("Run algorithm:");
|
||||
System.out.println("1 - Simulated Annealing");
|
||||
System.out.println("2 - Simple Genetic Algorithm");
|
||||
System.out.println("3 - Ant Colony");
|
||||
int decision = in.nextInt();
|
||||
switch (decision) {
|
||||
case 1:
|
||||
System.out.println(
|
||||
"Optimized distance for travel: " + SimulatedAnnealing.simulateAnnealing(10, 10000, 0.9995));
|
||||
break;
|
||||
case 2:
|
||||
SimpleGeneticAlgorithm ga = new SimpleGeneticAlgorithm();
|
||||
ga.runAlgorithm(50, "1011000100000100010000100000100111001000000100000100000000001111");
|
||||
break;
|
||||
case 3:
|
||||
AntColonyOptimization antColony = new AntColonyOptimization(21);
|
||||
antColony.startAntOptimization();
|
||||
break;
|
||||
default:
|
||||
System.out.println("Unknown option");
|
||||
break;
|
||||
}
|
||||
in.close();
|
||||
}
|
||||
|
||||
}
|
4
algorithms-miscellaneous-1/.gitignore
vendored
Normal file
4
algorithms-miscellaneous-1/.gitignore
vendored
Normal file
@ -0,0 +1,4 @@
|
||||
/target/
|
||||
.settings/
|
||||
.classpath
|
||||
.project
|
18
algorithms-miscellaneous-1/README.md
Normal file
18
algorithms-miscellaneous-1/README.md
Normal file
@ -0,0 +1,18 @@
|
||||
## Relevant articles:
|
||||
|
||||
- [Validating Input With Finite Automata in Java](http://www.baeldung.com/java-finite-automata)
|
||||
- [Example of Hill Climbing Algorithm](http://www.baeldung.com/java-hill-climbing-algorithm)
|
||||
- [Monte Carlo Tree Search for Tic-Tac-Toe Game](http://www.baeldung.com/java-monte-carlo-tree-search)
|
||||
- [Binary Search Algorithm in Java](http://www.baeldung.com/java-binary-search)
|
||||
- [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)
|
||||
- [String Search Algorithms for Large Texts](http://www.baeldung.com/java-full-text-search-algorithms)
|
||||
- [Check If a String Contains All The Letters of The Alphabet](https://www.baeldung.com/java-string-contains-all-letters)
|
||||
- [Find the Middle Element of a Linked List](http://www.baeldung.com/java-linked-list-middle-element)
|
||||
- [Calculate Factorial in Java](https://www.baeldung.com/java-calculate-factorial)
|
||||
- [Find Substrings That Are Palindromes in Java](https://www.baeldung.com/java-palindrome-substrings)
|
||||
- [Find the Longest Substring without Repeating Characters](https://www.baeldung.com/java-longest-substring-without-repeated-characters)
|
||||
- [Permutations of an Array in Java](https://www.baeldung.com/java-array-permutations)
|
||||
- [Generate Combinations in Java](https://www.baeldung.com/java-combinations-algorithm)
|
88
algorithms-miscellaneous-1/pom.xml
Normal file
88
algorithms-miscellaneous-1/pom.xml
Normal file
@ -0,0 +1,88 @@
|
||||
<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>algorithms-miscellaneous-1</artifactId>
|
||||
<version>0.0.1-SNAPSHOT</version>
|
||||
<name>algorithms-miscellaneous-1</name>
|
||||
|
||||
<parent>
|
||||
<groupId>com.baeldung</groupId>
|
||||
<artifactId>parent-modules</artifactId>
|
||||
<version>1.0.0-SNAPSHOT</version>
|
||||
</parent>
|
||||
|
||||
<dependencies>
|
||||
<dependency>
|
||||
<groupId>org.apache.commons</groupId>
|
||||
<artifactId>commons-math3</artifactId>
|
||||
<version>${commons-math3.version}</version>
|
||||
</dependency>
|
||||
<dependency>
|
||||
<groupId>com.google.guava</groupId>
|
||||
<artifactId>guava</artifactId>
|
||||
<version>${guava.version}</version>
|
||||
</dependency>
|
||||
<dependency>
|
||||
<groupId>commons-codec</groupId>
|
||||
<artifactId>commons-codec</artifactId>
|
||||
<version>${commons-codec.version}</version>
|
||||
</dependency>
|
||||
<dependency>
|
||||
<groupId>org.projectlombok</groupId>
|
||||
<artifactId>lombok</artifactId>
|
||||
<version>${lombok.version}</version>
|
||||
<scope>provided</scope>
|
||||
</dependency>
|
||||
<dependency>
|
||||
<groupId>org.assertj</groupId>
|
||||
<artifactId>assertj-core</artifactId>
|
||||
<version>${org.assertj.core.version}</version>
|
||||
<scope>test</scope>
|
||||
</dependency>
|
||||
<dependency>
|
||||
<groupId>com.github.dpaukov</groupId>
|
||||
<artifactId>combinatoricslib3</artifactId>
|
||||
<version>3.3.0</version>
|
||||
</dependency>
|
||||
</dependencies>
|
||||
|
||||
<build>
|
||||
<pluginManagement>
|
||||
<plugins>
|
||||
<plugin>
|
||||
<groupId>org.codehaus.mojo</groupId>
|
||||
<artifactId>exec-maven-plugin</artifactId>
|
||||
<version>${exec-maven-plugin.version}</version>
|
||||
</plugin>
|
||||
</plugins>
|
||||
</pluginManagement>
|
||||
</build>
|
||||
|
||||
<reporting>
|
||||
<plugins>
|
||||
<plugin>
|
||||
<groupId>org.codehaus.mojo</groupId>
|
||||
<artifactId>cobertura-maven-plugin</artifactId>
|
||||
<version>2.7</version>
|
||||
<configuration>
|
||||
<instrumentation>
|
||||
<ignores>
|
||||
<ignore>com/baeldung/algorithms/dijkstra/*</ignore>
|
||||
</ignores>
|
||||
<excludes>
|
||||
<exclude>com/baeldung/algorithms/dijkstra/*</exclude>
|
||||
</excludes>
|
||||
</instrumentation>
|
||||
</configuration>
|
||||
</plugin>
|
||||
</plugins>
|
||||
</reporting>
|
||||
|
||||
<properties>
|
||||
<commons-math3.version>3.6.1</commons-math3.version>
|
||||
<org.assertj.core.version>3.9.0</org.assertj.core.version>
|
||||
<commons-codec.version>1.11</commons-codec.version>
|
||||
<guava.version>27.0.1-jre</guava.version>
|
||||
</properties>
|
||||
|
||||
</project>
|
@ -98,7 +98,7 @@ public class FindKthLargest {
|
||||
|
||||
private int randomPartition(Integer arr[], int left, int right) {
|
||||
int n = right - left + 1;
|
||||
int pivot = (int) (Math.random()) % n;
|
||||
int pivot = (int) (Math.random() * n);
|
||||
swap(arr, left + pivot, right);
|
||||
return partition(arr, left, right);
|
||||
}
|
@ -0,0 +1,123 @@
|
||||
package com.baeldung.algorithms.permutation;
|
||||
|
||||
import java.util.Arrays;
|
||||
import java.util.Collections;
|
||||
|
||||
public class Permutation {
|
||||
|
||||
public static <T> void printAllRecursive(T[] elements, char delimiter) {
|
||||
printAllRecursive(elements.length, elements, delimiter);
|
||||
}
|
||||
|
||||
public static <T> void printAllRecursive(int n, T[] elements, char delimiter) {
|
||||
|
||||
if(n == 1) {
|
||||
printArray(elements, delimiter);
|
||||
} else {
|
||||
for(int i = 0; i < n-1; i++) {
|
||||
printAllRecursive(n - 1, elements, delimiter);
|
||||
if(n % 2 == 0) {
|
||||
swap(elements, i, n-1);
|
||||
} else {
|
||||
swap(elements, 0, n-1);
|
||||
}
|
||||
}
|
||||
printAllRecursive(n - 1, elements, delimiter);
|
||||
}
|
||||
}
|
||||
|
||||
public static <T> void printAllIterative(int n, T[] elements, char delimiter) {
|
||||
|
||||
int[] indexes = new int[n];
|
||||
for (int i = 0; i < n; i++) {
|
||||
indexes[i] = 0;
|
||||
}
|
||||
|
||||
printArray(elements, delimiter);
|
||||
|
||||
int i = 0;
|
||||
while (i < n) {
|
||||
if (indexes[i] < i) {
|
||||
swap(elements, i % 2 == 0 ? 0: indexes[i], i);
|
||||
printArray(elements, delimiter);
|
||||
indexes[i]++;
|
||||
i = 0;
|
||||
}
|
||||
else {
|
||||
indexes[i] = 0;
|
||||
i++;
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
public static <T extends Comparable<T>> void printAllOrdered(T[] elements, char delimiter) {
|
||||
|
||||
Arrays.sort(elements);
|
||||
boolean hasNext = true;
|
||||
|
||||
while(hasNext) {
|
||||
printArray(elements, delimiter);
|
||||
int k = 0, l = 0;
|
||||
hasNext = false;
|
||||
for (int i = elements.length - 1; i > 0; i--) {
|
||||
if (elements[i].compareTo(elements[i - 1]) > 0) {
|
||||
k = i - 1;
|
||||
hasNext = true;
|
||||
break;
|
||||
}
|
||||
}
|
||||
|
||||
for (int i = elements.length - 1; i > k; i--) {
|
||||
if (elements[i].compareTo(elements[k]) > 0) {
|
||||
l = i;
|
||||
break;
|
||||
}
|
||||
}
|
||||
|
||||
swap(elements, k, l);
|
||||
Collections.reverse(Arrays.asList(elements).subList(k + 1, elements.length));
|
||||
}
|
||||
}
|
||||
|
||||
public static <T> void printRandom(T[] elements, char delimiter) {
|
||||
|
||||
Collections.shuffle(Arrays.asList(elements));
|
||||
printArray(elements, delimiter);
|
||||
}
|
||||
|
||||
private static <T> void swap(T[] elements, int a, int b) {
|
||||
|
||||
T tmp = elements[a];
|
||||
elements[a] = elements[b];
|
||||
elements[b] = tmp;
|
||||
}
|
||||
|
||||
private static <T> void printArray(T[] elements, char delimiter) {
|
||||
|
||||
String delimiterSpace = delimiter + " ";
|
||||
for(int i = 0; i < elements.length; i++) {
|
||||
System.out.print(elements[i] + delimiterSpace);
|
||||
}
|
||||
System.out.print('\n');
|
||||
}
|
||||
|
||||
public static void main(String[] argv) {
|
||||
|
||||
Integer[] elements = {1,2,3,4};
|
||||
|
||||
System.out.println("Rec:");
|
||||
printAllRecursive(elements, ';');
|
||||
|
||||
System.out.println("Iter:");
|
||||
printAllIterative(elements.length, elements, ';');
|
||||
|
||||
System.out.println("Orderes:");
|
||||
printAllOrdered(elements, ';');
|
||||
|
||||
System.out.println("Random:");
|
||||
printRandom(elements, ';');
|
||||
|
||||
System.out.println("Random:");
|
||||
printRandom(elements, ';');
|
||||
}
|
||||
}
|
@ -0,0 +1,54 @@
|
||||
package com.baeldung.algorithms.string;
|
||||
|
||||
import java.util.HashMap;
|
||||
import java.util.HashSet;
|
||||
import java.util.Map;
|
||||
import java.util.Set;
|
||||
|
||||
public class LongestSubstringNonRepeatingCharacters {
|
||||
|
||||
public static String getUniqueCharacterSubstringBruteForce(String input) {
|
||||
String output = "";
|
||||
for (int start = 0; start < input.length(); start++) {
|
||||
Set<Character> visited = new HashSet<>();
|
||||
int end = start;
|
||||
for (; end < input.length(); end++) {
|
||||
char currChar = input.charAt(end);
|
||||
if (visited.contains(currChar)) {
|
||||
break;
|
||||
} else {
|
||||
visited.add(currChar);
|
||||
}
|
||||
}
|
||||
if (output.length() < end - start + 1) {
|
||||
output = input.substring(start, end);
|
||||
}
|
||||
}
|
||||
return output;
|
||||
}
|
||||
|
||||
public static String getUniqueCharacterSubstring(String input) {
|
||||
Map<Character, Integer> visited = new HashMap<>();
|
||||
String output = "";
|
||||
for (int start = 0, end = 0; end < input.length(); end++) {
|
||||
char currChar = input.charAt(end);
|
||||
if (visited.containsKey(currChar)) {
|
||||
start = Math.max(visited.get(currChar) + 1, start);
|
||||
}
|
||||
if (output.length() < end - start + 1) {
|
||||
output = input.substring(start, end + 1);
|
||||
}
|
||||
visited.put(currChar, end);
|
||||
}
|
||||
return output;
|
||||
}
|
||||
|
||||
public static void main(String[] args) {
|
||||
if(args.length > 0) {
|
||||
System.out.println(getUniqueCharacterSubstring(args[0]));
|
||||
} else {
|
||||
System.err.println("This program expects command-line input. Please try again!");
|
||||
}
|
||||
}
|
||||
|
||||
}
|
@ -0,0 +1,90 @@
|
||||
package com.baeldung.algorithms.string;
|
||||
|
||||
import java.util.HashSet;
|
||||
import java.util.Set;
|
||||
|
||||
public class SubstringPalindrome {
|
||||
|
||||
public Set<String> findAllPalindromesUsingCenter(String input) {
|
||||
final Set<String> palindromes = new HashSet<>();
|
||||
if (input == null || input.isEmpty()) {
|
||||
return palindromes;
|
||||
}
|
||||
if (input.length() == 1) {
|
||||
palindromes.add(input);
|
||||
return palindromes;
|
||||
}
|
||||
for (int i = 0; i < input.length(); i++) {
|
||||
palindromes.addAll(findPalindromes(input, i, i + 1));
|
||||
palindromes.addAll(findPalindromes(input, i, i));
|
||||
}
|
||||
return palindromes;
|
||||
}
|
||||
|
||||
private Set<String> findPalindromes(String input, int low, int high) {
|
||||
Set<String> result = new HashSet<>();
|
||||
while (low >= 0 && high < input.length() && input.charAt(low) == input.charAt(high)) {
|
||||
result.add(input.substring(low, high + 1));
|
||||
low--;
|
||||
high++;
|
||||
}
|
||||
return result;
|
||||
}
|
||||
|
||||
public Set<String> findAllPalindromesUsingBruteForceApproach(String input) {
|
||||
Set<String> palindromes = new HashSet<>();
|
||||
if (input == null || input.isEmpty()) {
|
||||
return palindromes;
|
||||
}
|
||||
if (input.length() == 1) {
|
||||
palindromes.add(input);
|
||||
return palindromes;
|
||||
}
|
||||
for (int i = 0; i < input.length(); i++) {
|
||||
for (int j = i + 1; j <= input.length(); j++)
|
||||
if (isPalindrome(input.substring(i, j))) {
|
||||
palindromes.add(input.substring(i, j));
|
||||
}
|
||||
}
|
||||
return palindromes;
|
||||
}
|
||||
|
||||
private boolean isPalindrome(String input) {
|
||||
StringBuilder plain = new StringBuilder(input);
|
||||
StringBuilder reverse = plain.reverse();
|
||||
return (reverse.toString()).equals(input);
|
||||
}
|
||||
|
||||
public Set<String> findAllPalindromesUsingManachersAlgorithm(String input) {
|
||||
Set<String> palindromes = new HashSet<>();
|
||||
String formattedInput = "@" + input + "#";
|
||||
char inputCharArr[] = formattedInput.toCharArray();
|
||||
int max;
|
||||
int radius[][] = new int[2][input.length() + 1];
|
||||
for (int j = 0; j <= 1; j++) {
|
||||
radius[j][0] = max = 0;
|
||||
int i = 1;
|
||||
while (i <= input.length()) {
|
||||
palindromes.add(Character.toString(inputCharArr[i]));
|
||||
while (inputCharArr[i - max - 1] == inputCharArr[i + j + max])
|
||||
max++;
|
||||
radius[j][i] = max;
|
||||
int k = 1;
|
||||
while ((radius[j][i - k] != max - k) && (k < max)) {
|
||||
radius[j][i + k] = Math.min(radius[j][i - k], max - k);
|
||||
k++;
|
||||
}
|
||||
max = Math.max(max - k, 0);
|
||||
i += k;
|
||||
}
|
||||
}
|
||||
for (int i = 1; i <= input.length(); i++) {
|
||||
for (int j = 0; j <= 1; j++) {
|
||||
for (max = radius[j][i]; max > 0; max--) {
|
||||
palindromes.add(input.substring(i - max - 1, max + j + i - 1));
|
||||
}
|
||||
}
|
||||
}
|
||||
return palindromes;
|
||||
}
|
||||
}
|
@ -0,0 +1,31 @@
|
||||
package com.baeldung.algorithms.string;
|
||||
|
||||
import org.junit.jupiter.api.Test;
|
||||
|
||||
import static org.junit.jupiter.api.Assertions.assertEquals;
|
||||
import static com.baeldung.algorithms.string.LongestSubstringNonRepeatingCharacters.getUniqueCharacterSubstring;
|
||||
import static com.baeldung.algorithms.string.LongestSubstringNonRepeatingCharacters.getUniqueCharacterSubstringBruteForce;
|
||||
|
||||
public class LongestSubstringNonRepeatingCharactersUnitTest {
|
||||
|
||||
@Test
|
||||
void givenString_whenGetUniqueCharacterSubstringBruteForceCalled_thenResultFoundAsExpectedUnitTest() {
|
||||
assertEquals("", getUniqueCharacterSubstringBruteForce(""));
|
||||
assertEquals("A", getUniqueCharacterSubstringBruteForce("A"));
|
||||
assertEquals("ABCDEF", getUniqueCharacterSubstringBruteForce("AABCDEF"));
|
||||
assertEquals("ABCDEF", getUniqueCharacterSubstringBruteForce("ABCDEFF"));
|
||||
assertEquals("NGISAWE", getUniqueCharacterSubstringBruteForce("CODINGISAWESOME"));
|
||||
assertEquals("be coding", getUniqueCharacterSubstringBruteForce("always be coding"));
|
||||
}
|
||||
|
||||
@Test
|
||||
void givenString_whenGetUniqueCharacterSubstringCalled_thenResultFoundAsExpectedUnitTest() {
|
||||
assertEquals("", getUniqueCharacterSubstring(""));
|
||||
assertEquals("A", getUniqueCharacterSubstring("A"));
|
||||
assertEquals("ABCDEF", getUniqueCharacterSubstring("AABCDEF"));
|
||||
assertEquals("ABCDEF", getUniqueCharacterSubstring("ABCDEFF"));
|
||||
assertEquals("NGISAWE", getUniqueCharacterSubstring("CODINGISAWESOME"));
|
||||
assertEquals("be coding", getUniqueCharacterSubstring("always be coding"));
|
||||
}
|
||||
|
||||
}
|
@ -0,0 +1,83 @@
|
||||
package com.baeldung.algorithms.string;
|
||||
|
||||
import static org.junit.Assert.assertEquals;
|
||||
import java.util.HashSet;
|
||||
import java.util.Set;
|
||||
import org.junit.Test;
|
||||
|
||||
public class SubstringPalindromeUnitTest {
|
||||
|
||||
private static final String INPUT_BUBBLE = "bubble";
|
||||
private static final String INPUT_CIVIC = "civic";
|
||||
private static final String INPUT_INDEED = "indeed";
|
||||
private static final String INPUT_ABABAC = "ababac";
|
||||
|
||||
Set<String> EXPECTED_PALINDROME_BUBBLE = new HashSet<String>() {
|
||||
{
|
||||
add("b");
|
||||
add("u");
|
||||
add("l");
|
||||
add("e");
|
||||
add("bb");
|
||||
add("bub");
|
||||
}
|
||||
};
|
||||
|
||||
Set<String> EXPECTED_PALINDROME_CIVIC = new HashSet<String>() {
|
||||
{
|
||||
add("civic");
|
||||
add("ivi");
|
||||
add("i");
|
||||
add("c");
|
||||
add("v");
|
||||
}
|
||||
};
|
||||
|
||||
Set<String> EXPECTED_PALINDROME_INDEED = new HashSet<String>() {
|
||||
{
|
||||
add("i");
|
||||
add("n");
|
||||
add("d");
|
||||
add("e");
|
||||
add("ee");
|
||||
add("deed");
|
||||
}
|
||||
};
|
||||
|
||||
Set<String> EXPECTED_PALINDROME_ABABAC = new HashSet<String>() {
|
||||
{
|
||||
add("a");
|
||||
add("b");
|
||||
add("c");
|
||||
add("aba");
|
||||
add("bab");
|
||||
add("ababa");
|
||||
}
|
||||
};
|
||||
|
||||
private SubstringPalindrome palindrome = new SubstringPalindrome();
|
||||
|
||||
@Test
|
||||
public void whenUsingManachersAlgorithm_thenFindsAllPalindromes() {
|
||||
assertEquals(EXPECTED_PALINDROME_BUBBLE, palindrome.findAllPalindromesUsingManachersAlgorithm(INPUT_BUBBLE));
|
||||
assertEquals(EXPECTED_PALINDROME_INDEED, palindrome.findAllPalindromesUsingManachersAlgorithm(INPUT_INDEED));
|
||||
assertEquals(EXPECTED_PALINDROME_CIVIC, palindrome.findAllPalindromesUsingManachersAlgorithm(INPUT_CIVIC));
|
||||
assertEquals(EXPECTED_PALINDROME_ABABAC, palindrome.findAllPalindromesUsingManachersAlgorithm(INPUT_ABABAC));
|
||||
}
|
||||
|
||||
@Test
|
||||
public void whenUsingCenterApproach_thenFindsAllPalindromes() {
|
||||
assertEquals(EXPECTED_PALINDROME_BUBBLE, palindrome.findAllPalindromesUsingCenter(INPUT_BUBBLE));
|
||||
assertEquals(EXPECTED_PALINDROME_INDEED, palindrome.findAllPalindromesUsingCenter(INPUT_INDEED));
|
||||
assertEquals(EXPECTED_PALINDROME_CIVIC, palindrome.findAllPalindromesUsingCenter(INPUT_CIVIC));
|
||||
assertEquals(EXPECTED_PALINDROME_ABABAC, palindrome.findAllPalindromesUsingCenter(INPUT_ABABAC));
|
||||
}
|
||||
|
||||
@Test
|
||||
public void whenUsingBruteForceApproach_thenFindsAllPalindromes() {
|
||||
assertEquals(EXPECTED_PALINDROME_BUBBLE, palindrome.findAllPalindromesUsingBruteForceApproach(INPUT_BUBBLE));
|
||||
assertEquals(EXPECTED_PALINDROME_INDEED, palindrome.findAllPalindromesUsingBruteForceApproach(INPUT_INDEED));
|
||||
assertEquals(EXPECTED_PALINDROME_CIVIC, palindrome.findAllPalindromesUsingBruteForceApproach(INPUT_CIVIC));
|
||||
assertEquals(EXPECTED_PALINDROME_ABABAC, palindrome.findAllPalindromesUsingBruteForceApproach(INPUT_ABABAC));
|
||||
}
|
||||
}
|
4
algorithms-miscellaneous-2/.gitignore
vendored
Normal file
4
algorithms-miscellaneous-2/.gitignore
vendored
Normal file
@ -0,0 +1,4 @@
|
||||
/target/
|
||||
.settings/
|
||||
.classpath
|
||||
.project
|
19
algorithms-miscellaneous-2/README.md
Normal file
19
algorithms-miscellaneous-2/README.md
Normal file
@ -0,0 +1,19 @@
|
||||
## Relevant articles:
|
||||
|
||||
- [Dijkstra Algorithm in Java](http://www.baeldung.com/java-dijkstra)
|
||||
- [Introduction to Cobertura](http://www.baeldung.com/cobertura)
|
||||
- [Test a Linked List for Cyclicity](http://www.baeldung.com/java-linked-list-cyclicity)
|
||||
- [Introduction to JGraphT](http://www.baeldung.com/jgrapht)
|
||||
- [A Maze Solver in Java](http://www.baeldung.com/java-solve-maze)
|
||||
- [Create a Sudoku Solver in Java](http://www.baeldung.com/java-sudoku)
|
||||
- [Displaying Money Amounts in Words](http://www.baeldung.com/java-money-into-words)
|
||||
- [A Collaborative Filtering Recommendation System in Java](http://www.baeldung.com/java-collaborative-filtering-recommendations)
|
||||
- [Check If Two Rectangles Overlap In Java](https://www.baeldung.com/java-check-if-two-rectangles-overlap)
|
||||
- [Calculate the Distance Between Two Points in Java](https://www.baeldung.com/java-distance-between-two-points)
|
||||
- [Find the Intersection of Two Lines in Java](https://www.baeldung.com/java-intersection-of-two-lines)
|
||||
- [Round Up to the Nearest Hundred](https://www.baeldung.com/java-round-up-nearest-hundred)
|
||||
- [Calculate Percentage in Java](https://www.baeldung.com/java-calculate-percentage)
|
||||
- [Converting Between Byte Arrays and Hexadecimal Strings in Java](https://www.baeldung.com/java-byte-arrays-hex-strings)
|
||||
- [Convert Latitude and Longitude to a 2D Point in Java](https://www.baeldung.com/java-convert-latitude-longitude)
|
||||
- [Reversing a Binary Tree in Java](https://www.baeldung.com/java-reversing-a-binary-tree)
|
||||
- [Find If Two Numbers Are Relatively Prime in Java](https://www.baeldung.com/java-two-relatively-prime-numbers)
|
96
algorithms-miscellaneous-2/pom.xml
Normal file
96
algorithms-miscellaneous-2/pom.xml
Normal file
@ -0,0 +1,96 @@
|
||||
<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>algorithms-miscellaneous-2</artifactId>
|
||||
<version>0.0.1-SNAPSHOT</version>
|
||||
<name>algorithms-miscellaneous-2</name>
|
||||
|
||||
<parent>
|
||||
<groupId>com.baeldung</groupId>
|
||||
<artifactId>parent-modules</artifactId>
|
||||
<version>1.0.0-SNAPSHOT</version>
|
||||
</parent>
|
||||
|
||||
<dependencies>
|
||||
<dependency>
|
||||
<groupId>org.apache.commons</groupId>
|
||||
<artifactId>commons-math3</artifactId>
|
||||
<version>${commons-math3.version}</version>
|
||||
</dependency>
|
||||
<dependency>
|
||||
<groupId>commons-codec</groupId>
|
||||
<artifactId>commons-codec</artifactId>
|
||||
<version>${commons-codec.version}</version>
|
||||
</dependency>
|
||||
<dependency>
|
||||
<groupId>org.projectlombok</groupId>
|
||||
<artifactId>lombok</artifactId>
|
||||
<version>${lombok.version}</version>
|
||||
<scope>provided</scope>
|
||||
</dependency>
|
||||
<dependency>
|
||||
<groupId>org.jgrapht</groupId>
|
||||
<artifactId>jgrapht-core</artifactId>
|
||||
<version>${org.jgrapht.core.version}</version>
|
||||
</dependency>
|
||||
<dependency>
|
||||
<groupId>org.jgrapht</groupId>
|
||||
<artifactId>jgrapht-ext</artifactId>
|
||||
<version>${org.jgrapht.ext.version}</version>
|
||||
</dependency>
|
||||
<dependency>
|
||||
<groupId>pl.allegro.finance</groupId>
|
||||
<artifactId>tradukisto</artifactId>
|
||||
<version>${tradukisto.version}</version>
|
||||
</dependency>
|
||||
<dependency>
|
||||
<groupId>org.assertj</groupId>
|
||||
<artifactId>assertj-core</artifactId>
|
||||
<version>${org.assertj.core.version}</version>
|
||||
<scope>test</scope>
|
||||
</dependency>
|
||||
</dependencies>
|
||||
|
||||
<build>
|
||||
<pluginManagement>
|
||||
<plugins>
|
||||
<plugin>
|
||||
<groupId>org.codehaus.mojo</groupId>
|
||||
<artifactId>exec-maven-plugin</artifactId>
|
||||
<version>${exec-maven-plugin.version}</version>
|
||||
</plugin>
|
||||
</plugins>
|
||||
</pluginManagement>
|
||||
</build>
|
||||
|
||||
<reporting>
|
||||
<plugins>
|
||||
<plugin>
|
||||
<groupId>org.codehaus.mojo</groupId>
|
||||
<artifactId>cobertura-maven-plugin</artifactId>
|
||||
<version>${cobertura-maven-plugin.version}</version>
|
||||
<configuration>
|
||||
<instrumentation>
|
||||
<ignores>
|
||||
<ignore>com/baeldung/algorithms/dijkstra/*</ignore>
|
||||
</ignores>
|
||||
<excludes>
|
||||
<exclude>com/baeldung/algorithms/dijkstra/*</exclude>
|
||||
</excludes>
|
||||
</instrumentation>
|
||||
</configuration>
|
||||
</plugin>
|
||||
</plugins>
|
||||
</reporting>
|
||||
|
||||
<properties>
|
||||
<commons-math3.version>3.6.1</commons-math3.version>
|
||||
<tradukisto.version>1.0.1</tradukisto.version>
|
||||
<org.jgrapht.core.version>1.0.1</org.jgrapht.core.version>
|
||||
<org.jgrapht.ext.version>1.0.1</org.jgrapht.ext.version>
|
||||
<org.assertj.core.version>3.9.0</org.assertj.core.version>
|
||||
<commons-codec.version>1.11</commons-codec.version>
|
||||
<cobertura-maven-plugin.version>2.7</cobertura-maven-plugin.version>
|
||||
</properties>
|
||||
|
||||
</project>
|
@ -0,0 +1,28 @@
|
||||
package com.baeldung.algorithms;
|
||||
|
||||
import java.util.Scanner;
|
||||
|
||||
import com.baeldung.algorithms.slope_one.SlopeOne;
|
||||
|
||||
public class RunAlgorithm {
|
||||
|
||||
public static void main(String[] args) throws InstantiationException, IllegalAccessException {
|
||||
Scanner in = new Scanner(System.in);
|
||||
System.out.println("1 - Slope One");
|
||||
System.out.println("2 - Dijkstra");
|
||||
int decision = in.nextInt();
|
||||
switch (decision) {
|
||||
case 1:
|
||||
SlopeOne.slopeOne(3);
|
||||
break;
|
||||
case 2:
|
||||
System.out.println("Please run the DijkstraAlgorithmLongRunningUnitTest.");
|
||||
break;
|
||||
default:
|
||||
System.out.println("Unknown option");
|
||||
break;
|
||||
}
|
||||
in.close();
|
||||
}
|
||||
|
||||
}
|
@ -0,0 +1,110 @@
|
||||
package com.baeldung.algorithms.conversion;
|
||||
|
||||
import java.math.BigInteger;
|
||||
|
||||
import javax.xml.bind.DatatypeConverter;
|
||||
|
||||
import org.apache.commons.codec.DecoderException;
|
||||
import org.apache.commons.codec.binary.Hex;
|
||||
|
||||
import com.google.common.io.BaseEncoding;
|
||||
|
||||
public class HexStringConverter {
|
||||
|
||||
/**
|
||||
* Create a byte Array from String of hexadecimal digits using Character conversion
|
||||
* @param hexString - Hexadecimal digits as String
|
||||
* @return Desired byte Array
|
||||
*/
|
||||
public byte[] decodeHexString(String hexString) {
|
||||
if (hexString.length() % 2 == 1) {
|
||||
throw new IllegalArgumentException("Invalid hexadecimal String supplied.");
|
||||
}
|
||||
byte[] bytes = new byte[hexString.length() / 2];
|
||||
|
||||
for (int i = 0; i < hexString.length(); i += 2) {
|
||||
bytes[i / 2] = hexToByte(hexString.substring(i, i + 2));
|
||||
}
|
||||
return bytes;
|
||||
}
|
||||
|
||||
/**
|
||||
* Create a String of hexadecimal digits from a byte Array using Character conversion
|
||||
* @param byteArray - The byte Array
|
||||
* @return Desired String of hexadecimal digits in lower case
|
||||
*/
|
||||
public String encodeHexString(byte[] byteArray) {
|
||||
StringBuffer hexStringBuffer = new StringBuffer();
|
||||
for (int i = 0; i < byteArray.length; i++) {
|
||||
hexStringBuffer.append(byteToHex(byteArray[i]));
|
||||
}
|
||||
return hexStringBuffer.toString();
|
||||
}
|
||||
|
||||
public String byteToHex(byte num) {
|
||||
char[] hexDigits = new char[2];
|
||||
hexDigits[0] = Character.forDigit((num >> 4) & 0xF, 16);
|
||||
hexDigits[1] = Character.forDigit((num & 0xF), 16);
|
||||
return new String(hexDigits);
|
||||
}
|
||||
|
||||
public byte hexToByte(String hexString) {
|
||||
int firstDigit = toDigit(hexString.charAt(0));
|
||||
int secondDigit = toDigit(hexString.charAt(1));
|
||||
return (byte) ((firstDigit << 4) + secondDigit);
|
||||
}
|
||||
|
||||
private int toDigit(char hexChar) {
|
||||
int digit = Character.digit(hexChar, 16);
|
||||
if(digit == -1) {
|
||||
throw new IllegalArgumentException("Invalid Hexadecimal Character: "+ hexChar);
|
||||
}
|
||||
return digit;
|
||||
}
|
||||
|
||||
public String encodeUsingBigIntegerToString(byte[] bytes) {
|
||||
BigInteger bigInteger = new BigInteger(1, bytes);
|
||||
return bigInteger.toString(16);
|
||||
}
|
||||
|
||||
public String encodeUsingBigIntegerStringFormat(byte[] bytes) {
|
||||
BigInteger bigInteger = new BigInteger(1, bytes);
|
||||
return String.format("%0" + (bytes.length << 1) + "x", bigInteger);
|
||||
}
|
||||
|
||||
public byte[] decodeUsingBigInteger(String hexString) {
|
||||
byte[] byteArray = new BigInteger(hexString, 16).toByteArray();
|
||||
if (byteArray[0] == 0) {
|
||||
byte[] output = new byte[byteArray.length - 1];
|
||||
System.arraycopy(byteArray, 1, output, 0, output.length);
|
||||
return output;
|
||||
}
|
||||
return byteArray;
|
||||
}
|
||||
|
||||
public String encodeUsingDataTypeConverter(byte[] bytes) {
|
||||
return DatatypeConverter.printHexBinary(bytes);
|
||||
}
|
||||
|
||||
public byte[] decodeUsingDataTypeConverter(String hexString) {
|
||||
return DatatypeConverter.parseHexBinary(hexString);
|
||||
}
|
||||
|
||||
public String encodeUsingApacheCommons(byte[] bytes) throws DecoderException {
|
||||
return Hex.encodeHexString(bytes);
|
||||
}
|
||||
|
||||
public byte[] decodeUsingApacheCommons(String hexString) throws DecoderException {
|
||||
return Hex.decodeHex(hexString);
|
||||
}
|
||||
|
||||
public String encodeUsingGuava(byte[] bytes) {
|
||||
return BaseEncoding.base16()
|
||||
.encode(bytes);
|
||||
}
|
||||
|
||||
public byte[] decodeUsingGuava(String hexString) {
|
||||
return BaseEncoding.base16()
|
||||
.decode(hexString.toUpperCase());
|
||||
}
|
||||
}
|
Some files were not shown because too many files have changed in this diff Show More
Loading…
x
Reference in New Issue
Block a user