Merge remote-tracking branch 'upstream/master' into tutorials/binaryTreeJava

This commit is contained in:
Marcos 2017-12-10 19:29:33 +01:00
commit a91c6659d6
22 changed files with 490 additions and 47 deletions

View File

@ -0,0 +1,21 @@
package com.baeldung.array;
import org.openjdk.jmh.runner.Runner;
import org.openjdk.jmh.runner.options.Options;
import org.openjdk.jmh.runner.options.OptionsBuilder;
public class ArrayBenchmarkRunner {
public static void main(String[] args) throws Exception {
Options options = new OptionsBuilder()
.include(SearchArrayTest.class.getSimpleName()).threads(1)
.forks(1).shouldFailOnError(true).shouldDoGC(true)
.jvmArgs("-server").build();
new Runner(options).run();
}
}

View File

@ -1,78 +1,92 @@
package com.baeldung.array;
import org.junit.Test;
import org.openjdk.jmh.annotations.*;
import java.util.*;
import java.util.concurrent.TimeUnit;
public class SearchArrayTest {
@Test
public void searchArrayAllocNewCollections() {
@Benchmark
@BenchmarkMode(Mode.AverageTime)
@Warmup(iterations = 5)
@OutputTimeUnit(TimeUnit.MICROSECONDS)
public void searchArrayLoop() {
int count = 1000;
String[] strings = seedArray(count);
for (int i = 0; i < count; i++) {
searchLoop(strings, "T");
}
}
long startTime = System.nanoTime();
@Benchmark
@BenchmarkMode(Mode.AverageTime)
@Warmup(iterations = 5)
@OutputTimeUnit(TimeUnit.MICROSECONDS)
public void searchArrayAllocNewList() {
int count = 1000;
String[] strings = seedArray(count);
for (int i = 0; i < count; i++) {
searchList(strings, "W");
}
long duration = System.nanoTime() - startTime;
System.out.println("SearchList: " + duration / 10000);
startTime = System.nanoTime();
}
@Benchmark
@BenchmarkMode(Mode.AverageTime)
@Warmup(iterations = 5)
@OutputTimeUnit(TimeUnit.MICROSECONDS)
public void searchArrayAllocNewSet() {
int count = 1000;
String[] strings = seedArray(count);
for (int i = 0; i < count; i++) {
searchSet(strings,"S");
searchSet(strings, "S");
}
duration = System.nanoTime() - startTime;
System.out.println("SearchSet: " + duration / 10000);
startTime = System.nanoTime();
for (int i = 0; i < count; i++) {
searchLoop(strings, "T");
}
duration = System.nanoTime() - startTime;
System.out.println("SearchLoop: " + duration / 10000);
}
@Test
public void searchArrayReuseCollections() {
int count = 10000;
@Benchmark
@BenchmarkMode(Mode.AverageTime)
@Warmup(iterations = 5)
@OutputTimeUnit(TimeUnit.MICROSECONDS)
public void searchArrayReuseList() {
int count = 1000;
String[] strings = seedArray(count);
List<String> asList = Arrays.asList(strings);
Set<String> asSet = new HashSet<>(Arrays.asList(strings));
long startTime = System.nanoTime();
for (int i = 0; i < count; i++) {
asList.contains("W");
}
long duration = System.nanoTime() - startTime;
System.out.println("List: " + duration / 10000);
}
startTime = System.nanoTime();
@Benchmark
@BenchmarkMode(Mode.AverageTime)
@Warmup(iterations = 5)
@OutputTimeUnit(TimeUnit.MICROSECONDS)
public void searchArrayReuseSet() {
int count = 1000;
String[] strings = seedArray(count);
Set<String> asSet = new HashSet<>(Arrays.asList(strings));
for (int i = 0; i < count; i++) {
asSet.contains("S");
}
duration = System.nanoTime() - startTime;
System.out.println("Set: " + duration / 10000);
startTime = System.nanoTime();
for (int i = 0; i < count; i++) {
searchLoop(strings, "T");
}
duration = System.nanoTime() - startTime;
System.out.println("Loop: " + duration / 10000);
}
@Test
@Benchmark
@BenchmarkMode(Mode.AverageTime)
@Warmup(iterations = 5)
@OutputTimeUnit(TimeUnit.MICROSECONDS)
public void searchArrayBinarySearch() {
int count = 10000;
int count = 1000;
String[] strings = seedArray(count);
Arrays.sort(strings);
@ -81,7 +95,7 @@ public class SearchArrayTest {
Arrays.binarySearch(strings, "A");
}
long duration = System.nanoTime() - startTime;
System.out.println("Binary search: " + duration / 10000);
//System.out.println("Binary search: " + duration / 10000);
}

View File

@ -1,10 +1,10 @@
<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>flyway</artifactId>
<version>1.0</version>
<name>flyway</name>
<packaging>pom</packaging>
<description>A sample project to demonstrate Flyway migrations</description>
<parent>
@ -13,6 +13,10 @@
<version>1.0.0-SNAPSHOT</version>
</parent>
<modules>
<module>spring-flyway</module>
</modules>
<dependencies>
<dependency>
<groupId>mysql</groupId>
@ -20,6 +24,17 @@
<version>${mysql.version}</version>
</dependency>
</dependencies>
<dependencyManagement>
<dependencies>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-dependencies</artifactId>
<version>${spring.boot.version}</version>
<type>pom</type>
<scope>import</scope>
</dependency>
</dependencies>
</dependencyManagement>
<build>
<plugins>
<plugin>
@ -32,5 +47,6 @@
<properties>
<mysql.version>6.0.5</mysql.version>
<flyway-maven-plugin.version>4.0.3</flyway-maven-plugin.version>
<spring.boot.version>1.5.8.RELEASE</spring.boot.version>
</properties>
</project>

24
flyway/spring-flyway/.gitignore vendored Normal file
View File

@ -0,0 +1,24 @@
target/
!.mvn/wrapper/maven-wrapper.jar
### STS ###
.apt_generated
.classpath
.factorypath
.project
.settings
.springBeans
### IntelliJ IDEA ###
.idea
*.iws
*.iml
*.ipr
### NetBeans ###
nbproject/private/
build/
nbbuild/
dist/
nbdist/
.nb-gradle/

View File

@ -0,0 +1,57 @@
<?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>spring-flyway</artifactId>
<version>0.0.1-SNAPSHOT</version>
<packaging>jar</packaging>
<name>spring-flyway</name>
<description>Spring Boot Test Flyway Migrations</description>
<parent>
<artifactId>flyway</artifactId>
<groupId>com.baeldung</groupId>
<version>1.0</version>
<relativePath>../../flyway</relativePath>
</parent>
<properties>
<project.build.sourceEncoding>UTF-8</project.build.sourceEncoding>
<project.reporting.outputEncoding>UTF-8</project.reporting.outputEncoding>
<java.version>1.8</java.version>
</properties>
<dependencies>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-data-jpa</artifactId>
</dependency>
<dependency>
<groupId>org.flywaydb</groupId>
<artifactId>flyway-core</artifactId>
</dependency>
<dependency>
<groupId>org.projectlombok</groupId>
<artifactId>lombok</artifactId>
</dependency>
<dependency>
<groupId>com.h2database</groupId>
<artifactId>h2</artifactId>
</dependency>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-test</artifactId>
<scope>test</scope>
</dependency>
</dependencies>
<build>
<plugins>
<plugin>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-maven-plugin</artifactId>
</plugin>
</plugins>
</build>
</project>

View File

@ -0,0 +1,12 @@
package com.baeldung.springflyway;
import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;
@SpringBootApplication
public class SpringFlywayApplication {
public static void main(String[] args) {
SpringApplication.run(SpringFlywayApplication.class, args);
}
}

View File

@ -0,0 +1,28 @@
package com.baeldung.springflyway.entities;
import lombok.AllArgsConstructor;
import lombok.Builder;
import lombok.Data;
import lombok.NoArgsConstructor;
import javax.persistence.Entity;
import javax.persistence.GeneratedValue;
import javax.persistence.Id;
@Entity
@Data
@AllArgsConstructor
@NoArgsConstructor
@Builder
public class Customer {
@Id
@GeneratedValue
private Long id;
private String firstName;
private String lastName;
private String email;
}

View File

@ -0,0 +1,14 @@
package com.baeldung.springflyway.migration;
import org.flywaydb.core.api.migration.spring.SpringJdbcMigration;
import org.springframework.jdbc.core.JdbcTemplate;
public class V2__uk_lastname_customer implements SpringJdbcMigration {
final String CUSTOMER_LASTNAME_UK = "ALTER TABLE customer ADD CONSTRAINT uk_customer_lastname UNIQUE(last_name);";
@Override
public void migrate(final JdbcTemplate jdbcTemplate) throws Exception {
jdbcTemplate.execute(CUSTOMER_LASTNAME_UK);
}
}

View File

@ -0,0 +1,11 @@
package com.baeldung.springflyway.repositories;
import com.baeldung.springflyway.entities.Customer;
import org.springframework.data.jpa.repository.JpaRepository;
import java.util.Optional;
public interface CustomerRepository extends JpaRepository<Customer, Long> {
Optional<Customer> findByEmail(String email);
}

View File

@ -0,0 +1,28 @@
package com.baeldung.springflyway;
import com.baeldung.springflyway.entities.Customer;
import com.baeldung.springflyway.repositories.CustomerRepository;
import org.junit.Test;
import org.junit.runner.RunWith;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.test.context.SpringBootTest;
import org.springframework.test.context.junit4.SpringRunner;
import static org.junit.Assert.assertNotNull;
@RunWith(SpringRunner.class)
@SpringBootTest
public class CustomerRepositoryInitialMigrationTest {
@Autowired CustomerRepository customerRepository;
@Test
public void givenSchemaCreationMigration_whenTryingToCreateACustomer_thenSuccess() {
Customer customer = customerRepository.save(Customer
.builder()
.email("customer@email.com")
.build());
assertNotNull(customer.getId());
}
}

View File

@ -0,0 +1,35 @@
package com.baeldung.springflyway;
import com.baeldung.springflyway.entities.Customer;
import com.baeldung.springflyway.repositories.CustomerRepository;
import org.junit.Test;
import org.junit.runner.RunWith;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.test.context.SpringBootTest;
import org.springframework.test.context.junit4.SpringRunner;
import java.util.List;
import java.util.Optional;
import static org.junit.Assert.*;
@RunWith(SpringRunner.class)
@SpringBootTest
public class CustomerRepositoryInsertDataMigrationTest {
@Autowired CustomerRepository customerRepository;
@Test
public void givenASetInsertData_whenRunningMigrationsWithSuccess_thenASpecificCustomerIsFound() {
Optional<Customer> customerOptional = customerRepository.findByEmail("email@email.com");
assertTrue(customerOptional.isPresent());
}
@Test
public void givenASetInsertData_whenRunningMigrationsWithSuccess_thenASetOfCustomersIsFound() {
List<Customer> customers = customerRepository.findAll();
assertNotNull(customers);
assertEquals(customers.size(), 6);
}
}

View File

@ -0,0 +1,25 @@
package com.baeldung.springflyway;
import com.baeldung.springflyway.entities.Customer;
import com.baeldung.springflyway.repositories.CustomerRepository;
import org.junit.Test;
import org.junit.runner.RunWith;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.test.context.SpringBootTest;
import org.springframework.dao.DataIntegrityViolationException;
import org.springframework.test.context.junit4.SpringRunner;
@RunWith(SpringRunner.class)
@SpringBootTest
public class CustomerRepositoryNotNullConstraintMigrationTest {
@Autowired CustomerRepository customerRepository;
@Test(expected = DataIntegrityViolationException.class)
public void givenTheNotNullConstraintMigrations_whenInsertingACustomerWithNullEmail_thenThrowException() {
customerRepository.save(Customer
.builder()
.build());
}
}

View File

@ -0,0 +1,29 @@
package com.baeldung.springflyway;
import com.baeldung.springflyway.entities.Customer;
import com.baeldung.springflyway.repositories.CustomerRepository;
import org.junit.Test;
import org.junit.runner.RunWith;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.test.context.SpringBootTest;
import org.springframework.dao.DataIntegrityViolationException;
import org.springframework.test.context.junit4.SpringRunner;
@RunWith(SpringRunner.class)
@SpringBootTest(properties = {
"flyway.locations[0]=db/migration", "flyway.locations[1]=com/baeldung/springflyway/migration"
})
public class CustomerRepositoryUniqueConstraintJavaMigrationTest {
@Autowired CustomerRepository customerRepository;
@Test(expected = DataIntegrityViolationException.class)
public void givenTheUniqueConstraintMigrations_whenInsertingAnExistingLastNameCustomer_thenThrowException() {
customerRepository.save(Customer
.builder()
.lastName("LastName")
.build());
}
}

View File

@ -0,0 +1,27 @@
package com.baeldung.springflyway;
import com.baeldung.springflyway.entities.Customer;
import com.baeldung.springflyway.repositories.CustomerRepository;
import org.junit.Test;
import org.junit.runner.RunWith;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.test.context.SpringBootTest;
import org.springframework.dao.DataIntegrityViolationException;
import org.springframework.test.context.junit4.SpringRunner;
@RunWith(SpringRunner.class)
@SpringBootTest
public class CustomerRepositoryUniqueConstraintMigrationTest {
@Autowired CustomerRepository customerRepository;
@Test(expected = DataIntegrityViolationException.class)
public void givenTheUniqueConstraintMigrations_whenInsertingAnExistingEmailCustomer_thenThrowException() {
customerRepository.save(Customer
.builder()
.email("email@email.com")
.build());
}
}

View File

@ -0,0 +1 @@
spring.jpa.hibernate.ddl-auto=validate

View File

@ -0,0 +1,6 @@
create table if not exists customer (
id bigint AUTO_INCREMENT not null primary key,
first_name varchar(255) ,
last_name varchar(255) ,
email varchar(255)
);

View File

@ -0,0 +1,6 @@
insert into customer (first_name, last_name, email) values ('FirstName', 'LastName', 'email@email.com');
insert into customer (first_name, last_name, email) values ('FirstName1', 'LastName1', 'email1@email.com');
insert into customer (first_name, last_name, email) values ('FirstName2', 'LastName2', 'email2@email.com');
insert into customer (first_name, last_name, email) values ('FirstName3', 'LastName3', 'email3@email.com');
insert into customer (first_name, last_name, email) values ('FirstName4', 'LastName4', 'email4@email.com');
insert into customer (first_name, last_name, email) values ('FirstName5', 'LastName5', 'email5@email.com');

View File

@ -0,0 +1 @@
ALTER TABLE customer ALTER email SET NOT NULL;

View File

@ -0,0 +1 @@
ALTER TABLE customer ADD CONSTRAINT uk_customer_email UNIQUE(email);

View File

@ -6,6 +6,7 @@ import com.baeldung.hibernate.pojo.OrderEntry;
import com.baeldung.hibernate.pojo.OrderEntryIdClass;
import com.baeldung.hibernate.pojo.OrderEntryPK;
import com.baeldung.hibernate.pojo.PointEntity;
import com.baeldung.hibernate.pojo.PolygonEntity;
import com.baeldung.hibernate.pojo.Product;
import com.baeldung.hibernate.pojo.Phone;
import com.baeldung.hibernate.pojo.TemporalValues;
@ -79,6 +80,7 @@ public class HibernateUtil {
metadataSources.addAnnotatedClass(Car.class);
metadataSources.addAnnotatedClass(Bag.class);
metadataSources.addAnnotatedClass(PointEntity.class);
metadataSources.addAnnotatedClass(PolygonEntity.class);
Metadata metadata = metadataSources.buildMetadata();
return metadata.getSessionFactoryBuilder()

View File

@ -0,0 +1,38 @@
package com.baeldung.hibernate.pojo;
import com.vividsolutions.jts.geom.Polygon;
import javax.persistence.Entity;
import javax.persistence.GeneratedValue;
import javax.persistence.Id;
@Entity
public class PolygonEntity {
@Id
@GeneratedValue
private Long id;
private Polygon polygon;
public Long getId() {
return id;
}
public void setId(Long id) {
this.id = id;
}
public Polygon getPolygon() {
return polygon;
}
public void setPolygon(Polygon polygon) {
this.polygon = polygon;
}
@Override
public String toString() {
return "PolygonEntity{" + "id=" + id + ", polygon=" + polygon + '}';
}
}

View File

@ -1,10 +1,14 @@
package com.baeldung.hibernate;
import com.baeldung.hibernate.pojo.PointEntity;
import com.baeldung.hibernate.pojo.PolygonEntity;
import com.vividsolutions.jts.geom.Coordinate;
import com.vividsolutions.jts.geom.Geometry;
import com.vividsolutions.jts.geom.Point;
import com.vividsolutions.jts.geom.Polygon;
import com.vividsolutions.jts.io.ParseException;
import com.vividsolutions.jts.io.WKTReader;
import com.vividsolutions.jts.util.GeometricShapeFactory;
import org.hibernate.Session;
import org.hibernate.Transaction;
import org.junit.After;
@ -13,6 +17,7 @@ import org.junit.Test;
import javax.persistence.Query;
import java.io.IOException;
import java.util.List;
import static org.assertj.core.api.Assertions.assertThat;
import static org.junit.Assert.assertEquals;
@ -82,16 +87,58 @@ public class HibernateSpatialTest {
.containsOnly("POINT (1 1)", "POINT (1 2)", "POINT (3 4)");
}
@Test
public void shouldSelectAllPointsWithinRadius() throws ParseException {
insertPoint("POINT (1 1)");
insertPoint("POINT (1 2)");
insertPoint("POINT (3 4)");
insertPoint("POINT (5 6)");
Query query = session.createQuery("select p from PointEntity p where within(p.point, :circle) = true",
PointEntity.class);
query.setParameter("circle", createCircle(0.0, 0.0, 5));
assertThat(query.getResultList().stream().map(p -> ((PointEntity) p).getPoint().toString()))
.containsOnly("POINT (1 1)", "POINT (1 2)");
}
@Test
public void shouldSelectAdjacentPolygons() throws ParseException {
insertPolygon("POLYGON ((0 0, 0 5, 5 5, 5 0, 0 0))");
insertPolygon("POLYGON ((3 0, 3 5, 8 5, 8 0, 3 0))");
insertPolygon("POLYGON ((2 2, 3 1, 2 5, 4 3, 3 3, 2 2))");
Query query = session.createQuery("select p from PolygonEntity p where touches(p.polygon, :polygon) = true",
PolygonEntity.class);
query.setParameter("polygon", wktToGeometry("POLYGON ((5 5, 5 10, 10 10, 10 5, 5 5))"));
assertThat(query.getResultList().stream().map(p -> ((PolygonEntity) p).getPolygon().toString()))
.containsOnly("POLYGON ((0 0, 0 5, 5 5, 5 0, 0 0))", "POLYGON ((3 0, 3 5, 8 5, 8 0, 3 0))");
}
private void insertPoint(String point) throws ParseException {
PointEntity entity = new PointEntity();
entity.setPoint((Point) wktToGeometry(point));
session.persist(entity);
}
private void insertPolygon(String polygon) throws ParseException {
PolygonEntity entity = new PolygonEntity();
entity.setPolygon((Polygon) wktToGeometry(polygon));
session.persist(entity);
}
private Geometry wktToGeometry(String wellKnownText) throws ParseException {
WKTReader fromText = new WKTReader();
Geometry geom = null;
geom = fromText.read(wellKnownText);
return geom;
}
private static Geometry createCircle(double x, double y, double radius) {
GeometricShapeFactory shapeFactory = new GeometricShapeFactory();
shapeFactory.setNumPoints(32);
shapeFactory.setCentre(new Coordinate(x, y));
shapeFactory.setSize(radius * 2);
return shapeFactory.createCircle();
}
}