Merge remote-tracking branch 'upstream/master'

This commit is contained in:
Kevin Gilmore
2016-04-08 06:37:57 -05:00
231 changed files with 6117 additions and 737 deletions
@@ -2,27 +2,26 @@ package com.baeldung.unzip;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.io.IOException;
import java.util.zip.ZipEntry;
import java.util.zip.ZipInputStream;
public class UnzipFile {
public static void main(String[] args) throws FileNotFoundException, IOException {
String fileZip = "/opt/zipped/cities.zip";
byte[] buffer = new byte[1024];
ZipInputStream zis = new ZipInputStream(new FileInputStream(fileZip));
public static void main(final String[] args) throws IOException {
final String fileZip = "src/main/resources/compressed.zip";
final byte[] buffer = new byte[1024];
final ZipInputStream zis = new ZipInputStream(new FileInputStream(fileZip));
ZipEntry zipEntry = zis.getNextEntry();
while(zipEntry != null){
String fileName = zipEntry.getName();
File newFile = new File("/opt/unzipped/" + fileName);
FileOutputStream fos = new FileOutputStream(newFile);
final String fileName = zipEntry.getName();
final File newFile = new File("src/main/resources/unzipTest/" + fileName);
final FileOutputStream fos = new FileOutputStream(newFile);
int len;
while ((len = zis.read(buffer)) > 0) {
fos.write(buffer, 0, len);
}
fos.close();
fos.close();
zipEntry = zis.getNextEntry();
}
zis.closeEntry();
@@ -0,0 +1,43 @@
package com.baeldung.zip;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.io.IOException;
import java.util.zip.ZipEntry;
import java.util.zip.ZipOutputStream;
public class ZipDirectory {
public static void main(final String[] args) throws IOException {
final String sourceFile = "src/main/resources/zipTest";
final FileOutputStream fos = new FileOutputStream("src/main/resources/dirCompressed.zip");
final ZipOutputStream zipOut = new ZipOutputStream(fos);
final File fileToZip = new File(sourceFile);
zipFile(fileToZip, fileToZip.getName(), zipOut);
zipOut.close();
fos.close();
}
private static void zipFile(final File fileToZip, final String fileName, final ZipOutputStream zipOut) throws IOException {
if (fileToZip.isHidden()) {
return;
}
if (fileToZip.isDirectory()) {
final File[] children = fileToZip.listFiles();
for (final File childFile : children) {
zipFile(childFile, fileName + "/" + childFile.getName(), zipOut);
}
return;
}
final FileInputStream fis = new FileInputStream(fileToZip);
final ZipEntry zipEntry = new ZipEntry(fileName);
zipOut.putNextEntry(zipEntry);
final byte[] bytes = new byte[1024];
int length;
while ((length = fis.read(bytes)) >= 0) {
zipOut.write(bytes, 0, length);
}
fis.close();
}
}
@@ -2,22 +2,21 @@ package com.baeldung.zip;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.io.IOException;
import java.util.zip.ZipEntry;
import java.util.zip.ZipOutputStream;
public class ZipFile {
public static void main(String[] args) throws FileNotFoundException, IOException {
String sourceFile = "/opt/photos/photo.png";
FileOutputStream fos = new FileOutputStream("/opt/zipped/cities.zip");
ZipOutputStream zipOut = new ZipOutputStream(fos);
File fileToZip = new File(sourceFile);
FileInputStream fis = new FileInputStream(fileToZip);
ZipEntry zipEntry = new ZipEntry(fileToZip.getName());
public static void main(final String[] args) throws IOException {
final String sourceFile = "src/main/resources/zipTest/test1.txt";
final FileOutputStream fos = new FileOutputStream("src/main/resources/compressed.zip");
final ZipOutputStream zipOut = new ZipOutputStream(fos);
final File fileToZip = new File(sourceFile);
final FileInputStream fis = new FileInputStream(fileToZip);
final ZipEntry zipEntry = new ZipEntry(fileToZip.getName());
zipOut.putNextEntry(zipEntry);
byte[] bytes = new byte[1024];
final byte[] bytes = new byte[1024];
int length;
while((length = fis.read(bytes)) >= 0) {
zipOut.write(bytes, 0, length);
@@ -0,0 +1,33 @@
package com.baeldung.zip;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.io.IOException;
import java.util.Arrays;
import java.util.List;
import java.util.zip.ZipEntry;
import java.util.zip.ZipOutputStream;
public class ZipMultipleFiles {
public static void main(final String[] args) throws IOException {
final List<String> srcFiles = Arrays.asList("src/main/resources/zipTest/test1.txt", "src/main/resources/zipTest/test2.txt");
final FileOutputStream fos = new FileOutputStream("src/main/resources/multiCompressed.zip");
final ZipOutputStream zipOut = new ZipOutputStream(fos);
for (final String srcFile : srcFiles) {
final File fileToZip = new File(srcFile);
final FileInputStream fis = new FileInputStream(fileToZip);
final ZipEntry zipEntry = new ZipEntry(fileToZip.getName());
zipOut.putNextEntry(zipEntry);
final byte[] bytes = new byte[1024];
int length;
while((length = fis.read(bytes)) >= 0) {
zipOut.write(bytes, 0, length);
}
fis.close();
}
zipOut.close();
fos.close();
}
}
Binary file not shown.
Binary file not shown.
Binary file not shown.
@@ -0,0 +1 @@
Hello World!
@@ -0,0 +1 @@
Hello World!
@@ -0,0 +1 @@
My Name is John
@@ -0,0 +1 @@
My Name is Tom
@@ -0,0 +1 @@
My Name is Jane
@@ -1,5 +1,7 @@
package org.baeldung.java.io;
import static org.junit.Assert.assertEquals;
import java.io.IOException;
import java.io.StringWriter;
import java.io.Writer;
@@ -23,6 +25,8 @@ public class JavaXToWriterUnitTest {
final Writer targetWriter = new StringWriter().append(new String(initialArray));
targetWriter.close();
assertEquals("With Java", targetWriter.toString());
}
@Test
@@ -40,6 +44,8 @@ public class JavaXToWriterUnitTest {
charSink.write(buffer);
stringWriter.close();
assertEquals("With Guava", stringWriter.toString());
}
@Test
@@ -48,6 +54,8 @@ public class JavaXToWriterUnitTest {
final Writer targetWriter = new StringBuilderWriter(new StringBuilder(new String(initialArray)));
targetWriter.close();
assertEquals("With Commons IO", targetWriter.toString());
}
}
+1 -1
View File
@@ -60,7 +60,7 @@
<dependency>
<groupId>com.fasterxml.jackson.module</groupId>
<artifactId>jackson-module-jsonSchema</artifactId>
<version>2.6.0</version>
<version>2.7.2</version>
</dependency>
<dependency>
@@ -1,31 +0,0 @@
package com.baeldung.jackson.annotation.extra;
import com.fasterxml.jackson.annotation.JsonInclude;
import com.fasterxml.jackson.databind.annotation.JsonAppend;
@JsonAppend(attrs = {@JsonAppend.Attr(value = "appendedProperty", include = JsonInclude.Include.ALWAYS)})
public class AppendBean {
private int id;
private String name;
public AppendBean(int id, String name) {
this.id = id;
this.name = name;
}
public int getId() {
return id;
}
public void setId(int id) {
this.id = id;
}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
}
@@ -0,0 +1,58 @@
package com.baeldung.jackson.annotation.extra;
import com.fasterxml.jackson.databind.annotation.JsonAppend;
public class AppendBeans {
public static class BeanWithoutAppend {
private int id;
private String name;
public BeanWithoutAppend(int id, String name) {
this.id = id;
this.name = name;
}
public int getId() {
return id;
}
public void setId(int id) {
this.id = id;
}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
}
@JsonAppend(attrs = { @JsonAppend.Attr(value = "version") })
public static class BeanWithAppend {
private int id;
private String name;
public BeanWithAppend(int id, String name) {
this.id = id;
this.name = name;
}
public int getId() {
return id;
}
public void setId(int id) {
this.id = id;
}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
}
}
@@ -1,38 +1,69 @@
package com.baeldung.jackson.annotation.extra;
import static org.junit.Assert.*;
import static org.hamcrest.CoreMatchers.containsString;
import static org.hamcrest.CoreMatchers.instanceOf;
import static org.hamcrest.CoreMatchers.not;
import static org.junit.Assert.assertEquals;
import static org.junit.Assert.assertThat;
import org.junit.Test;
import java.io.IOException;
import java.util.ArrayList;
import java.util.List;
import org.junit.Test;
import com.baeldung.jackson.annotation.extra.AppendBeans.BeanWithAppend;
import com.baeldung.jackson.annotation.extra.AppendBeans.BeanWithoutAppend;
import com.baeldung.jackson.annotation.extra.IdentityReferenceBeans.BeanWithIdentityReference;
import com.baeldung.jackson.annotation.extra.IdentityReferenceBeans.BeanWithoutIdentityReference;
import com.fasterxml.jackson.core.JsonProcessingException;
import com.fasterxml.jackson.databind.ObjectMapper;
import com.fasterxml.jackson.databind.ObjectMapper.DefaultTyping;
import com.fasterxml.jackson.databind.ObjectWriter;
import com.fasterxml.jackson.module.jsonSchema.JsonSchema;
import com.fasterxml.jackson.module.jsonSchema.factories.SchemaFactoryWrapper;
public class ExtraAnnotationTest {
@Test
public void whenNotUsingJsonIdentityReferenceAnnotation_thenCorrect() throws JsonProcessingException {
ObjectMapper mapper = new ObjectMapper();
BeanWithoutIdentityReference bean = new BeanWithoutIdentityReference(1, "Bean Without Identity Reference Annotation");
String jsonString = mapper.writeValueAsString(bean);
assertThat(jsonString, containsString("Bean Without Identity Reference Annotation"));
}
@Test
public void whenUsingJsonIdentityReferenceAnnotation_thenCorrect() throws JsonProcessingException {
ObjectMapper mapper = new ObjectMapper();
IdentityReferenceBean bean = new IdentityReferenceBean(1, "Identity Reference Bean");
BeanWithIdentityReference bean = new BeanWithIdentityReference(1, "Bean With Identity Reference Annotation");
String jsonString = mapper.writeValueAsString(bean);
assertEquals("1", jsonString);
}
@Test
public void whenNotUsingJsonAppendAnnotation_thenCorrect() throws JsonProcessingException {
ObjectMapper mapper = new ObjectMapper();
BeanWithoutAppend bean = new BeanWithoutAppend(2, "Bean Without Append Annotation");
ObjectWriter writer = mapper.writerFor(BeanWithoutAppend.class).withAttribute("version", "1.0");
String jsonString = writer.writeValueAsString(bean);
assertThat(jsonString, not(containsString("version")));
assertThat(jsonString, not(containsString("1.0")));
}
@Test
public void whenUsingJsonAppendAnnotation_thenCorrect() throws JsonProcessingException {
ObjectMapper mapper = new ObjectMapper();
AppendBean bean = new AppendBean(2, "Append Bean");
String jsonString = mapper.writeValueAsString(bean);
assertThat(jsonString, containsString("appendedProperty"));
BeanWithAppend bean = new BeanWithAppend(2, "Bean With Append Annotation");
ObjectWriter writer = mapper.writerFor(BeanWithAppend.class).withAttribute("version", "1.0");
String jsonString = writer.writeValueAsString(bean);
assertThat(jsonString, containsString("version"));
assertThat(jsonString, containsString("1.0"));
}
@Test
@@ -40,7 +71,7 @@ public class ExtraAnnotationTest {
ObjectMapper mapper = new ObjectMapper();
NamingBean bean = new NamingBean(3, "Naming Bean");
String jsonString = mapper.writeValueAsString(bean);
assertThat(jsonString, containsString("bean_name"));
}
@@ -51,7 +82,7 @@ public class ExtraAnnotationTest {
mapper.acceptJsonFormatVisitor(PropertyDescriptionBean.class, wrapper);
JsonSchema jsonSchema = wrapper.finalSchema();
String jsonString = mapper.writeValueAsString(jsonSchema);
System.out.println(jsonString);
assertThat(jsonString, containsString("This is a description of the name property"));
}
@@ -86,7 +117,7 @@ public class ExtraAnnotationTest {
TypeIdResolverStructure.BeanContainer serializedContainer = new TypeIdResolverStructure.BeanContainer();
serializedContainer.setBeans(beans);
ObjectMapper mapper = new ObjectMapper();
String jsonString = mapper.writeValueAsString(serializedContainer);
assertThat(jsonString, containsString("bean1"));
@@ -1,33 +0,0 @@
package com.baeldung.jackson.annotation.extra;
import com.fasterxml.jackson.annotation.JsonIdentityInfo;
import com.fasterxml.jackson.annotation.JsonIdentityReference;
import com.fasterxml.jackson.annotation.ObjectIdGenerators;
@JsonIdentityInfo(generator = ObjectIdGenerators.PropertyGenerator.class, property = "id")
@JsonIdentityReference(alwaysAsId = true)
public class IdentityReferenceBean {
private int id;
private String name;
public IdentityReferenceBean(int id, String name) {
this.id = id;
this.name = name;
}
public int getId() {
return id;
}
public void setId(int id) {
this.id = id;
}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
}
@@ -0,0 +1,63 @@
package com.baeldung.jackson.annotation.extra;
import com.fasterxml.jackson.annotation.JsonIdentityInfo;
import com.fasterxml.jackson.annotation.JsonIdentityReference;
import com.fasterxml.jackson.annotation.ObjectIdGenerators;
public class IdentityReferenceBeans {
@JsonIdentityInfo(generator = ObjectIdGenerators.PropertyGenerator.class, property = "id")
public static class BeanWithoutIdentityReference {
private int id;
private String name;
public BeanWithoutIdentityReference(int id, String name) {
this.id = id;
this.name = name;
}
public int getId() {
return id;
}
public void setId(int id) {
this.id = id;
}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
}
@JsonIdentityInfo(generator = ObjectIdGenerators.PropertyGenerator.class, property = "id")
@JsonIdentityReference(alwaysAsId = true)
public static class BeanWithIdentityReference {
private int id;
private String name;
public BeanWithIdentityReference(int id, String name) {
this.id = id;
this.name = name;
}
public int getId() {
return id;
}
public void setId(int id) {
this.id = id;
}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
}
}
@@ -6,29 +6,28 @@
<attribute name="maven.pomderived" value="true"/>
</attributes>
</classpathentry>
<classpathentry kind="src" output="target/test-classes" path="src/test/java">
<attributes>
<attribute name="optional" value="true"/>
<attribute name="maven.pomderived" value="true"/>
</attributes>
</classpathentry>
<classpathentry excluding="**" kind="src" output="target/classes" path="src/main/resources">
<attributes>
<attribute name="maven.pomderived" value="true"/>
</attributes>
</classpathentry>
<classpathentry kind="src" output="target/test-classes" path="src/test/java">
<attributes>
<attribute name="optional" value="true"/>
<attribute name="maven.pomderived" value="true"/>
</attributes>
</classpathentry>
<classpathentry excluding="**" kind="src" output="target/test-classes" path="src/test/resources">
<attributes>
<attribute name="maven.pomderived" value="true"/>
</attributes>
</classpathentry>
<classpathentry kind="con" path="org.eclipse.jdt.launching.JRE_CONTAINER/org.eclipse.jdt.internal.debug.ui.launcher.StandardVMType/JavaSE-1.7">
<attributes>
<attribute name="maven.pomderived" value="true"/>
</attributes>
</classpathentry>
<classpathentry kind="con" path="org.eclipse.m2e.MAVEN2_CLASSPATH_CONTAINER">
<attributes>
<attribute name="maven.pomderived" value="true"/>
<attribute name="org.eclipse.jst.component.dependency" value="/WEB-INF/lib"/>
</attributes>
</classpathentry>
<classpathentry kind="con" path="org.eclipse.jdt.launching.JRE_CONTAINER/org.eclipse.jdt.internal.debug.ui.launcher.StandardVMType/JavaSE-1.8">
<attributes>
<attribute name="maven.pomderived" value="true"/>
</attributes>
@@ -1,6 +1,6 @@
<?xml version="1.0" encoding="UTF-8"?>
<projectDescription>
<name>sprint-data-redis</name>
<name>jooq-spring</name>
<comment></comment>
<projects>
</projects>
@@ -10,11 +10,6 @@
<arguments>
</arguments>
</buildCommand>
<buildCommand>
<name>org.springframework.ide.eclipse.core.springbuilder</name>
<arguments>
</arguments>
</buildCommand>
<buildCommand>
<name>org.eclipse.m2e.core.maven2Builder</name>
<arguments>
@@ -22,7 +17,6 @@
</buildCommand>
</buildSpec>
<natures>
<nature>org.springframework.ide.eclipse.core.springnature</nature>
<nature>org.eclipse.jdt.core.javanature</nature>
<nature>org.eclipse.m2e.core.maven2Nature</nature>
</natures>
+153
View File
@@ -0,0 +1,153 @@
<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>jooq-spring</artifactId>
<version>0.0.1-SNAPSHOT</version>
<properties>
<org.jooq.version>3.7.3</org.jooq.version>
<com.h2database.version>1.4.191</com.h2database.version>
<org.springframework.version>4.2.5.RELEASE</org.springframework.version>
<org.slf4j.version>1.7.18</org.slf4j.version>
<ch.qos.logback.version>1.1.3</ch.qos.logback.version>
<junit.version>4.12</junit.version>
</properties>
<dependencies>
<!-- jOOQ -->
<dependency>
<groupId>org.jooq</groupId>
<artifactId>jooq</artifactId>
<version>${org.jooq.version}</version>
</dependency>
<!-- Database Access -->
<dependency>
<groupId>com.h2database</groupId>
<artifactId>h2</artifactId>
<version>${com.h2database.version}</version>
</dependency>
<!-- Spring -->
<dependency>
<groupId>org.springframework</groupId>
<artifactId>spring-context</artifactId>
<version>${org.springframework.version}</version>
</dependency>
<dependency>
<groupId>org.springframework</groupId>
<artifactId>spring-jdbc</artifactId>
<version>${org.springframework.version}</version>
</dependency>
<!-- Logging -->
<dependency>
<groupId>org.slf4j</groupId>
<artifactId>slf4j-api</artifactId>
<version>${org.slf4j.version}</version>
<scope>runtime</scope>
</dependency>
<dependency>
<groupId>ch.qos.logback</groupId>
<artifactId>logback-classic</artifactId>
<version>${ch.qos.logback.version}</version>
<scope>runtime</scope>
</dependency>
<!-- Testing -->
<dependency>
<groupId>junit</groupId>
<artifactId>junit</artifactId>
<version>${junit.version}</version>
<scope>test</scope>
</dependency>
<dependency>
<groupId>org.springframework</groupId>
<artifactId>spring-test</artifactId>
<version>${org.springframework.version}</version>
<scope>test</scope>
</dependency>
</dependencies>
<build>
<plugins>
<plugin>
<groupId>org.codehaus.mojo</groupId>
<artifactId>properties-maven-plugin</artifactId>
<version>1.0.0</version>
<executions>
<execution>
<phase>initialize</phase>
<goals>
<goal>read-project-properties</goal>
</goals>
<configuration>
<files>
<file>src/main/resources/intro_config.properties</file>
</files>
</configuration>
</execution>
</executions>
</plugin>
<plugin>
<groupId>org.codehaus.mojo</groupId>
<artifactId>sql-maven-plugin</artifactId>
<version>1.5</version>
<executions>
<execution>
<phase>initialize</phase>
<goals>
<goal>execute</goal>
</goals>
<configuration>
<driver>${db.driver}</driver>
<url>${db.url}</url>
<username>${db.username}</username>
<password>${db.password}</password>
<srcFiles>
<srcFile>src/main/resources/intro_schema.sql</srcFile>
</srcFiles>
</configuration>
</execution>
</executions>
<dependencies>
<dependency>
<groupId>com.h2database</groupId>
<artifactId>h2</artifactId>
<version>${com.h2database.version}</version>
</dependency>
</dependencies>
</plugin>
<plugin>
<groupId>org.jooq</groupId>
<artifactId>jooq-codegen-maven</artifactId>
<version>${org.jooq.version}</version>
<executions>
<execution>
<phase>generate-sources</phase>
<goals>
<goal>generate</goal>
</goals>
<configuration>
<jdbc>
<driver>${db.driver}</driver>
<url>${db.url}</url>
<user>${db.username}</user>
<password>${db.password}</password>
</jdbc>
<generator>
<target>
<packageName>com.baeldung.jooq.introduction.db</packageName>
<directory>src/main/java</directory>
</target>
</generator>
</configuration>
</execution>
</executions>
</plugin>
</plugins>
</build>
</project>
@@ -0,0 +1,8 @@
#Database Configuration
db.driver=org.h2.Driver
db.url=jdbc:h2:~/jooq
db.username=sa
db.password=
#SQL Dialect
jooq.sql.dialect=H2
@@ -0,0 +1,34 @@
DROP TABLE IF EXISTS author_book, author, book;
CREATE TABLE author (
id INT NOT NULL PRIMARY KEY,
first_name VARCHAR(50),
last_name VARCHAR(50) NOT NULL
);
CREATE TABLE book (
id INT NOT NULL PRIMARY KEY,
title VARCHAR(100) NOT NULL
);
CREATE TABLE author_book (
author_id INT NOT NULL,
book_id INT NOT NULL,
PRIMARY KEY (author_id, book_id),
CONSTRAINT fk_ab_author FOREIGN KEY (author_id) REFERENCES author (id)
ON UPDATE CASCADE ON DELETE CASCADE,
CONSTRAINT fk_ab_book FOREIGN KEY (book_id) REFERENCES book (id)
);
INSERT INTO author VALUES
(1, 'Kathy', 'Sierra'),
(2, 'Bert', 'Bates'),
(3, 'Bryan', 'Basham');
INSERT INTO book VALUES
(1, 'Head First Java'),
(2, 'Head First Servlets and JSP'),
(3, 'OCA/OCP Java SE 7 Programmer');
INSERT INTO author_book VALUES (1, 1), (1, 3), (2, 1);
@@ -0,0 +1,19 @@
package com.baeldung.jooq.introduction;
import org.jooq.ExecuteContext;
import org.jooq.SQLDialect;
import org.jooq.impl.DefaultExecuteListener;
import org.springframework.jdbc.support.SQLErrorCodeSQLExceptionTranslator;
import org.springframework.jdbc.support.SQLExceptionTranslator;
public class ExceptionTranslator extends DefaultExecuteListener {
private static final long serialVersionUID = 649359748808106775L;
@Override
public void exception(ExecuteContext context) {
SQLDialect dialect = context.configuration().dialect();
SQLExceptionTranslator translator = new SQLErrorCodeSQLExceptionTranslator(dialect.name());
context.exception(translator.translate("Access database using jOOQ", context.sql(), context.sqlException()));
}
}
@@ -0,0 +1,76 @@
package com.baeldung.jooq.introduction;
import javax.sql.DataSource;
import org.h2.jdbcx.JdbcDataSource;
import org.jooq.SQLDialect;
import org.jooq.impl.DataSourceConnectionProvider;
import org.jooq.impl.DefaultConfiguration;
import org.jooq.impl.DefaultDSLContext;
import org.jooq.impl.DefaultExecuteListenerProvider;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.ComponentScan;
import org.springframework.context.annotation.Configuration;
import org.springframework.context.annotation.PropertySource;
import org.springframework.core.env.Environment;
import org.springframework.jdbc.datasource.DataSourceTransactionManager;
import org.springframework.jdbc.datasource.TransactionAwareDataSourceProxy;
import org.springframework.transaction.annotation.EnableTransactionManagement;
@Configuration
@ComponentScan({ "com.baeldung.jooq.introduction.db.public_.tables" })
@EnableTransactionManagement
@PropertySource("classpath:intro_config.properties")
public class PersistenceContext {
@Autowired
private Environment environment;
@Bean
public DataSource dataSource() {
JdbcDataSource dataSource = new JdbcDataSource();
dataSource.setUrl(environment.getRequiredProperty("db.url"));
dataSource.setUser(environment.getRequiredProperty("db.username"));
dataSource.setPassword(environment.getRequiredProperty("db.password"));
return dataSource;
}
@Bean
public TransactionAwareDataSourceProxy transactionAwareDataSource() {
return new TransactionAwareDataSourceProxy(dataSource());
}
@Bean
public DataSourceTransactionManager transactionManager() {
return new DataSourceTransactionManager(dataSource());
}
@Bean
public DataSourceConnectionProvider connectionProvider() {
return new DataSourceConnectionProvider(transactionAwareDataSource());
}
@Bean
public ExceptionTranslator exceptionTransformer() {
return new ExceptionTranslator();
}
@Bean
public DefaultDSLContext dsl() {
return new DefaultDSLContext(configuration());
}
@Bean
public DefaultConfiguration configuration() {
DefaultConfiguration jooqConfiguration = new DefaultConfiguration();
jooqConfiguration.set(connectionProvider());
jooqConfiguration.set(new DefaultExecuteListenerProvider(exceptionTransformer()));
String sqlDialectName = environment.getRequiredProperty("jooq.sql.dialect");
SQLDialect dialect = SQLDialect.valueOf(sqlDialectName);
jooqConfiguration.set(dialect);
return jooqConfiguration;
}
}
@@ -0,0 +1,85 @@
package com.baeldung.jooq.introduction;
import com.baeldung.jooq.introduction.db.public_.tables.Author;
import com.baeldung.jooq.introduction.db.public_.tables.AuthorBook;
import com.baeldung.jooq.introduction.db.public_.tables.Book;
import org.jooq.DSLContext;
import org.jooq.Record3;
import org.jooq.Result;
import org.jooq.impl.DSL;
import org.junit.Test;
import org.junit.runner.RunWith;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.dao.DataAccessException;
import org.springframework.test.context.ContextConfiguration;
import org.springframework.test.context.junit4.SpringJUnit4ClassRunner;
import org.springframework.transaction.annotation.Transactional;
import static org.junit.Assert.assertEquals;
@ContextConfiguration(classes = PersistenceContext.class)
@Transactional(transactionManager = "transactionManager")
@RunWith(SpringJUnit4ClassRunner.class)
public class QueryTest {
@Autowired
private DSLContext dsl;
Author author = Author.AUTHOR;
Book book = Book.BOOK;
AuthorBook authorBook = AuthorBook.AUTHOR_BOOK;
@Test
public void givenValidData_whenInserting_thenSucceed() {
dsl.insertInto(author).set(author.ID, 4).set(author.FIRST_NAME, "Herbert").set(author.LAST_NAME, "Schildt").execute();
dsl.insertInto(book).set(book.ID, 4).set(book.TITLE, "A Beginner's Guide").execute();
dsl.insertInto(authorBook).set(authorBook.AUTHOR_ID, 4).set(authorBook.BOOK_ID, 4).execute();
Result<Record3<Integer, String, Integer>> result = dsl.select(author.ID, author.LAST_NAME, DSL.count()).from(author).join(authorBook).on(author.ID.equal(authorBook.AUTHOR_ID)).join(book).on(authorBook.BOOK_ID.equal(book.ID))
.groupBy(author.LAST_NAME).fetch();
assertEquals(3, result.size());
assertEquals("Sierra", result.getValue(0, author.LAST_NAME));
assertEquals(Integer.valueOf(2), result.getValue(0, DSL.count()));
assertEquals("Schildt", result.getValue(2, author.LAST_NAME));
assertEquals(Integer.valueOf(1), result.getValue(2, DSL.count()));
}
@Test(expected = DataAccessException.class)
public void givenInvalidData_whenInserting_thenFail() {
dsl.insertInto(authorBook).set(authorBook.AUTHOR_ID, 4).set(authorBook.BOOK_ID, 5).execute();
}
@Test
public void givenValidData_whenUpdating_thenSucceed() {
dsl.update(author).set(author.LAST_NAME, "Baeldung").where(author.ID.equal(3)).execute();
dsl.update(book).set(book.TITLE, "Building your REST API with Spring").where(book.ID.equal(3)).execute();
dsl.insertInto(authorBook).set(authorBook.AUTHOR_ID, 3).set(authorBook.BOOK_ID, 3).execute();
Result<Record3<Integer, String, String>> result = dsl.select(author.ID, author.LAST_NAME, book.TITLE).from(author).join(authorBook).on(author.ID.equal(authorBook.AUTHOR_ID)).join(book).on(authorBook.BOOK_ID.equal(book.ID)).where(author.ID.equal(3))
.fetch();
assertEquals(1, result.size());
assertEquals(Integer.valueOf(3), result.getValue(0, author.ID));
assertEquals("Baeldung", result.getValue(0, author.LAST_NAME));
assertEquals("Building your REST API with Spring", result.getValue(0, book.TITLE));
}
@Test(expected = DataAccessException.class)
public void givenInvalidData_whenUpdating_thenFail() {
dsl.update(authorBook).set(authorBook.AUTHOR_ID, 4).set(authorBook.BOOK_ID, 5).execute();
}
@Test
public void givenValidData_whenDeleting_thenSucceed() {
dsl.delete(author).where(author.ID.lt(3)).execute();
Result<Record3<Integer, String, String>> result = dsl.select(author.ID, author.FIRST_NAME, author.LAST_NAME).from(author).fetch();
assertEquals(1, result.size());
assertEquals("Bryan", result.getValue(0, author.FIRST_NAME));
assertEquals("Basham", result.getValue(0, author.LAST_NAME));
}
@Test(expected = DataAccessException.class)
public void givenInvalidData_whenDeleting_thenFail() {
dsl.delete(book).where(book.ID.equal(1)).execute();
}
}
@@ -1,5 +1,6 @@
package com.baeldung.spring.data.es.config;
import org.elasticsearch.client.Client;
import org.elasticsearch.common.settings.ImmutableSettings;
import org.elasticsearch.node.NodeBuilder;
import org.slf4j.Logger;
@@ -17,20 +18,14 @@ import java.nio.file.Path;
import java.nio.file.Paths;
@Configuration
@EnableElasticsearchRepositories(basePackages = "com.baeldung.repository")
@EnableElasticsearchRepositories(basePackages = "com.baeldung.spring.data.es.repository")
@ComponentScan(basePackages = {"com.baeldung.spring.data.es.service"})
public class Config {
private static Logger logger = LoggerFactory.getLogger(Config.class);
@Bean
public NodeBuilder nodeBuilder() {
return new NodeBuilder();
}
@Bean
public ElasticsearchOperations elasticsearchTemplate() {
public Client client() {
try {
Path tmpDir = Files.createTempDirectory(Paths.get(System.getProperty("java.io.tmpdir")), "elasticsearch_data");
@@ -40,14 +35,19 @@ public class Config {
logger.debug(tmpDir.toAbsolutePath().toString());
return new ElasticsearchTemplate(nodeBuilder()
return new NodeBuilder()
.local(true)
.settings(elasticsearchSettings.build())
.node()
.client());
.client();
} catch (IOException ioex) {
logger.error("Cannot create temp dir", ioex);
throw new RuntimeException();
}
}
@Bean
public ElasticsearchOperations elasticsearchTemplate() {
return new ElasticsearchTemplate(client());
}
}
@@ -1,15 +0,0 @@
package com.baeldung.spring.data.es.dao;
import com.baeldung.spring.data.es.model.Article;
import org.springframework.data.domain.Page;
import org.springframework.data.domain.Pageable;
import org.springframework.data.elasticsearch.annotations.Query;
import org.springframework.data.elasticsearch.repository.ElasticsearchRepository;
public interface ArticleRepository extends ElasticsearchRepository<Article, String> {
Page<Article> findByAuthorsName(String name, Pageable pageable);
@Query("{\"bool\": {\"must\": [{\"match\": {\"authors.name\": \"?0\"}}]}}")
Page<Article> findByAuthorsNameUsingCustomQuery(String name, Pageable pageable);
}
@@ -1,23 +1,35 @@
package com.baeldung.spring.data.es.model;
import org.springframework.data.annotation.Id;
import org.springframework.data.elasticsearch.annotations.Document;
import org.springframework.data.elasticsearch.annotations.Field;
import org.springframework.data.elasticsearch.annotations.FieldIndex;
import org.springframework.data.elasticsearch.annotations.FieldType;
import org.springframework.data.elasticsearch.annotations.*;
import java.util.Arrays;
import java.util.List;
import static org.springframework.data.elasticsearch.annotations.FieldIndex.not_analyzed;
import static org.springframework.data.elasticsearch.annotations.FieldType.Nested;
import static org.springframework.data.elasticsearch.annotations.FieldType.String;
@Document(indexName = "blog", type = "article")
public class Article {
@Id
private String id;
@Field(type = FieldType.String, index = FieldIndex.not_analyzed)
@MultiField(
mainField = @Field(type = String),
otherFields = {
@NestedField(index = not_analyzed, dotSuffix = "verbatim", type = String)
}
)
private String title;
@Field(type = FieldType.Nested)
@Field(type = Nested)
private List<Author> authors;
@Field(type = String, index = not_analyzed)
private String[] tags;
public Article() {
}
@@ -49,12 +61,21 @@ public class Article {
this.authors = authors;
}
public String[] getTags() {
return tags;
}
public void setTags(String... tags) {
this.tags = tags;
}
@Override
public String toString() {
return "Article{" +
"id='" + id + '\'' +
", title='" + title + '\'' +
", authors=" + authors +
", tags=" + Arrays.toString(tags) +
'}';
}
}

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