Merge branch 'master' of github.com:eugenp/tutorials into master
This commit is contained in:
commit
a647f98a96
|
@ -0,0 +1,75 @@
|
|||
package com.baeldung.tempdirectory;
|
||||
|
||||
import org.apache.commons.io.FileUtils;
|
||||
import org.junit.Test;
|
||||
|
||||
import java.io.IOException;
|
||||
import java.nio.file.Files;
|
||||
import java.nio.file.Path;
|
||||
import java.nio.file.Paths;
|
||||
import java.nio.file.attribute.FileAttribute;
|
||||
import java.nio.file.attribute.PosixFileAttributes;
|
||||
import java.nio.file.attribute.PosixFilePermission;
|
||||
import java.nio.file.attribute.PosixFilePermissions;
|
||||
import java.util.Set;
|
||||
import java.util.UUID;
|
||||
|
||||
import static org.assertj.core.api.Assertions.assertThat;
|
||||
|
||||
|
||||
/**
|
||||
* Tests several possibilities on how to create
|
||||
* temporary directories.
|
||||
*
|
||||
* @author Rui Vilao (rpvilao@gmail.com)
|
||||
*/
|
||||
public class TemporaryDirectoriesUnitTest {
|
||||
|
||||
@Test
|
||||
public void givenTempDirWithPrefixNoTargetSpecified_whenCreateWithPlainJava_thenInsideOSTempDirStructure() throws IOException {
|
||||
final String tmpdir = Files.createTempDirectory("tmpDirPrefix").toFile().getAbsolutePath();
|
||||
final String tmpDirsLocation = System.getProperty("java.io.tmpdir");
|
||||
|
||||
assertThat(tmpdir).startsWith(tmpDirsLocation);
|
||||
}
|
||||
|
||||
@Test
|
||||
public void givenTempDirWithPrefixNoTargetSpecified_whenCreateWithGuava_thenInsideOSTempDirStructure() throws IOException {
|
||||
final String tmpdir = com.google.common.io.Files.createTempDir().getAbsolutePath();
|
||||
final String tmpDirsLocation = System.getProperty("java.io.tmpdir");
|
||||
|
||||
assertThat(tmpdir).startsWith(tmpDirsLocation);
|
||||
}
|
||||
|
||||
@Test
|
||||
public void givenTempDirWithPrefixNoTargetSpecified_whenCreateWithApacheCommonsIo_thenInsideOSTempDirStructure() throws IOException {
|
||||
final String tmpDirsLocation = System.getProperty("java.io.tmpdir");
|
||||
final Path path = Paths.get(FileUtils.getTempDirectory().getAbsolutePath(), UUID.randomUUID().toString());
|
||||
final String tmpdir = Files.createDirectories(path).toFile().getAbsolutePath();
|
||||
|
||||
assertThat(tmpdir).startsWith(tmpDirsLocation);
|
||||
}
|
||||
|
||||
@Test
|
||||
public void givenTempDirWithPrefixWithTargetSpecified_whenCreatePlainJava_thenInsideTarget() throws IOException {
|
||||
final Path tmpdir = Files.createTempDirectory(Paths.get("target"), "tmpDirPrefix");
|
||||
assertThat(tmpdir.toFile().getPath()).startsWith("target");
|
||||
}
|
||||
|
||||
@Test
|
||||
public void givenTempDirWithPrefixWithTargetSpecifiedWithDeleteOnExit_whenCreatePlainJava_thenInsideTarget() throws IOException {
|
||||
final Path tmpdir = Files.createTempDirectory(Paths.get("target"), "tmpDirPrefix");
|
||||
assertThat(tmpdir.toFile().getPath()).startsWith("target");
|
||||
tmpdir.toFile().deleteOnExit();
|
||||
// we can really assert this test, just as an example.
|
||||
}
|
||||
|
||||
@Test
|
||||
public void givenTempDirWithPrefixWithFileAttrs_whenCreatePlainJava_thenAttributesAreSet() throws IOException {
|
||||
final FileAttribute<Set<PosixFilePermission>> attrs = PosixFilePermissions.asFileAttribute(PosixFilePermissions.fromString("r--------"));
|
||||
|
||||
final Path tmpdir = Files.createTempDirectory(Paths.get("target"), "tmpDirPrefix", attrs);
|
||||
assertThat(tmpdir.toFile().getPath()).startsWith("target");
|
||||
assertThat(tmpdir.toFile().canWrite()).isFalse();
|
||||
}
|
||||
}
|
|
@ -1,21 +1,24 @@
|
|||
package com.baeldung.arrayconversion;
|
||||
|
||||
import org.hamcrest.CoreMatchers;
|
||||
import org.junit.Test;
|
||||
|
||||
import java.util.ArrayList;
|
||||
import java.util.Arrays;
|
||||
import java.util.List;
|
||||
|
||||
import static org.hamcrest.MatcherAssert.assertThat;
|
||||
import static org.junit.Assert.assertArrayEquals;
|
||||
|
||||
public class ArrayToListConversionUnitTest {
|
||||
|
||||
@Test(expected = UnsupportedOperationException.class)
|
||||
public void givenAnArray_whenConvertingToList_returnUnmodifiableListUnitTest() {
|
||||
String[] stringArray = new String[] { "A", "B", "C", "D" };
|
||||
List<String> stringList = Arrays.asList(stringArray);
|
||||
System.out.println(stringList);
|
||||
stringList.set(0, "E");
|
||||
System.out.println(stringList);
|
||||
System.out.println(Arrays.toString(stringArray));
|
||||
assertThat(stringList, CoreMatchers.hasItems("E", "B", "C", "D"));
|
||||
assertArrayEquals(stringArray, new String[] { "E", "B", "C", "D" });
|
||||
stringList.add("F");
|
||||
}
|
||||
|
||||
|
@ -23,10 +26,10 @@ public class ArrayToListConversionUnitTest {
|
|||
public void givenAnArray_whenConvertingToList_returnModifiableListUnitTest() {
|
||||
String[] stringArray = new String[] { "A", "B", "C", "D" };
|
||||
List<String> stringList = new ArrayList<>(Arrays.asList(stringArray));
|
||||
System.out.println(stringList);
|
||||
stringList.set(0, "E");
|
||||
System.out.println(stringList);
|
||||
System.out.println(Arrays.toString(stringArray));
|
||||
assertThat(stringList, CoreMatchers.hasItems("E", "B", "C", "D"));
|
||||
assertArrayEquals(stringArray, new String[] { "A", "B", "C", "D" });
|
||||
stringList.add("F");
|
||||
assertThat(stringList, CoreMatchers.hasItems("E", "B", "C", "D", "F"));
|
||||
}
|
||||
}
|
||||
|
|
|
@ -32,7 +32,7 @@ public class SshdDemo {
|
|||
.getSession()) {
|
||||
session.addPasswordIdentity(password);
|
||||
session.auth()
|
||||
.verify(5L, TimeUnit.SECONDS);
|
||||
.verify(defaultTimeoutSeconds, TimeUnit.SECONDS);
|
||||
try (ByteArrayOutputStream responseStream = new ByteArrayOutputStream();
|
||||
ByteArrayOutputStream errorResponseStream = new ByteArrayOutputStream();
|
||||
ClientChannel channel = session.createChannel(Channel.CHANNEL_SHELL)) {
|
||||
|
|
|
@ -42,10 +42,12 @@ public class JschDemo {
|
|||
throw new Exception(errorResponse);
|
||||
}
|
||||
} finally {
|
||||
if (session != null)
|
||||
if (session != null) {
|
||||
session.disconnect();
|
||||
if (channel != null)
|
||||
}
|
||||
if (channel != null) {
|
||||
channel.disconnect();
|
||||
}
|
||||
}
|
||||
return response;
|
||||
}
|
||||
|
|
|
@ -0,0 +1,6 @@
|
|||
create table book (
|
||||
id numeric,
|
||||
title varchar(128),
|
||||
author varchar(256),
|
||||
constraint pk_book primary key (id)
|
||||
);
|
|
@ -0,0 +1 @@
|
|||
drop table book;
|
|
@ -0,0 +1,39 @@
|
|||
package com.baeldung.flywayundo;
|
||||
|
||||
import org.flywaydb.core.Flyway;
|
||||
import org.flywaydb.core.api.MigrationInfo;
|
||||
import org.flywaydb.core.api.MigrationState;
|
||||
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.ContextConfiguration;
|
||||
import org.springframework.test.context.junit4.SpringRunner;
|
||||
|
||||
import javax.sql.DataSource;
|
||||
|
||||
import static org.assertj.core.api.Assertions.assertThat;
|
||||
|
||||
@RunWith(SpringRunner.class)
|
||||
@ContextConfiguration(classes = FlywayUndoTestConfig.class)
|
||||
@SpringBootTest
|
||||
public class FlywayUndoMigrationIntegrationTest {
|
||||
|
||||
@Autowired
|
||||
private DataSource dataSource;
|
||||
|
||||
@Test
|
||||
public void givenMigrationsExist_whenApplyMigrations_migrationsAreSuccessful() {
|
||||
Flyway flyway = Flyway.configure()
|
||||
.dataSource(dataSource)
|
||||
.schemas("undo")
|
||||
.locations("db/undo")
|
||||
.load();
|
||||
|
||||
flyway.migrate();
|
||||
|
||||
for (MigrationInfo info : flyway.info().all()) {
|
||||
assertThat(info.getState()).isEqualTo(MigrationState.SUCCESS);
|
||||
}
|
||||
}
|
||||
}
|
|
@ -0,0 +1,21 @@
|
|||
package com.baeldung.flywayundo;
|
||||
|
||||
import org.springframework.context.annotation.Bean;
|
||||
import org.springframework.context.annotation.Configuration;
|
||||
import org.springframework.jdbc.datasource.embedded.EmbeddedDatabaseBuilder;
|
||||
import org.springframework.jdbc.datasource.embedded.EmbeddedDatabaseType;
|
||||
|
||||
import javax.sql.DataSource;
|
||||
|
||||
@Configuration
|
||||
public class FlywayUndoTestConfig {
|
||||
|
||||
@Bean
|
||||
public DataSource createDatasource() {
|
||||
EmbeddedDatabaseBuilder dbBuilder = new EmbeddedDatabaseBuilder();
|
||||
return dbBuilder.setType(EmbeddedDatabaseType.H2)
|
||||
.setName("DATABASE")
|
||||
.build();
|
||||
}
|
||||
|
||||
}
|
|
@ -3,6 +3,7 @@
|
|||
This module contains articles about querying data using Spring Data JPA
|
||||
|
||||
### Relevant Articles:
|
||||
- [Spring Data JPA @Query Annotation](https://www.baeldung.com/spring-data-jpa-query)
|
||||
- [Use Criteria Queries in a Spring Data Application](https://www.baeldung.com/spring-data-criteria-queries)
|
||||
- [Query Entities by Dates and Times with Spring Data JPA](https://www.baeldung.com/spring-data-jpa-query-by-date)
|
||||
- More articles: [[<-- prev]](../spring-data-jpa-query)
|
||||
|
|
|
@ -0,0 +1,48 @@
|
|||
package com.baeldung.spring.data.jpa.query;
|
||||
|
||||
import javax.persistence.EntityManager;
|
||||
import javax.persistence.PersistenceContext;
|
||||
import javax.persistence.criteria.*;
|
||||
import java.util.ArrayList;
|
||||
import java.util.Collection;
|
||||
import java.util.List;
|
||||
import java.util.Set;
|
||||
import java.util.stream.Collectors;
|
||||
import java.util.stream.Stream;
|
||||
|
||||
public class UserRepositoryCustomImpl implements UserRepositoryCustom {
|
||||
@PersistenceContext
|
||||
private EntityManager entityManager;
|
||||
|
||||
@Override
|
||||
public List<User> findUserByEmails(Set<String> emails) {
|
||||
CriteriaBuilder cb = entityManager.getCriteriaBuilder();
|
||||
CriteriaQuery<User> query = cb.createQuery(User.class);
|
||||
Root<User> user = query.from(User.class);
|
||||
|
||||
Path<String> emailPath = user.get("email");
|
||||
|
||||
List<Predicate> predicates = new ArrayList<>();
|
||||
for (String email : emails) {
|
||||
|
||||
predicates.add(cb.like(emailPath, email));
|
||||
|
||||
}
|
||||
query.select(user)
|
||||
.where(cb.or(predicates.toArray(new Predicate[predicates.size()])));
|
||||
|
||||
return entityManager.createQuery(query)
|
||||
.getResultList();
|
||||
}
|
||||
|
||||
@Override
|
||||
public List<User> findAllUsersByPredicates(Collection<java.util.function.Predicate<User>> predicates) {
|
||||
List<User> allUsers = entityManager.createQuery("select u from User u", User.class).getResultList();
|
||||
Stream<User> allUsersStream = allUsers.stream();
|
||||
for (java.util.function.Predicate<User> predicate : predicates) {
|
||||
allUsersStream = allUsersStream.filter(predicate);
|
||||
}
|
||||
|
||||
return allUsersStream.collect(Collectors.toList());
|
||||
}
|
||||
}
|
|
@ -1,12 +1,13 @@
|
|||
package com.baeldung.spring.transactional;
|
||||
|
||||
import org.springframework.boot.SpringApplication;
|
||||
import org.springframework.boot.autoconfigure.SpringBootApplication;
|
||||
|
||||
@SpringBootApplication
|
||||
class TransactionalCompareApplication {
|
||||
|
||||
public static void main(String[] args) {
|
||||
SpringApplication.run(TransactionalCompareApplication.class, args);
|
||||
}
|
||||
}
|
||||
package com.baeldung.spring.data.jpa.query.datetime;
|
||||
|
||||
import org.springframework.boot.SpringApplication;
|
||||
import org.springframework.boot.autoconfigure.SpringBootApplication;
|
||||
|
||||
@SpringBootApplication
|
||||
public class Application {
|
||||
|
||||
public static void main(String[] args) {
|
||||
SpringApplication.run(Application.class, args);
|
||||
}
|
||||
|
||||
}
|
|
@ -1,4 +1,4 @@
|
|||
package com.baeldung.boot.domain;
|
||||
package com.baeldung.spring.data.jpa.query.datetime;
|
||||
|
||||
import javax.persistence.*;
|
||||
import java.util.Date;
|
|
@ -1,11 +1,9 @@
|
|||
package com.baeldung.boot.daos;
|
||||
package com.baeldung.spring.data.jpa.query.datetime;
|
||||
|
||||
import org.springframework.data.jpa.repository.JpaRepository;
|
||||
import org.springframework.data.jpa.repository.Query;
|
||||
import org.springframework.data.repository.query.Param;
|
||||
|
||||
import com.baeldung.boot.domain.Article;
|
||||
|
||||
import java.util.Date;
|
||||
import java.util.List;
|
||||
|
|
@ -1,11 +1,4 @@
|
|||
package com.baeldung.boot.daos;
|
||||
|
||||
import static org.junit.Assert.assertEquals;
|
||||
import static org.junit.Assert.assertTrue;
|
||||
|
||||
import java.text.SimpleDateFormat;
|
||||
import java.util.Arrays;
|
||||
import java.util.List;
|
||||
package com.baeldung.spring.data.jpa.query.datetime;
|
||||
|
||||
import org.junit.Test;
|
||||
import org.junit.runner.RunWith;
|
||||
|
@ -13,7 +6,12 @@ import org.springframework.beans.factory.annotation.Autowired;
|
|||
import org.springframework.boot.test.autoconfigure.orm.jpa.DataJpaTest;
|
||||
import org.springframework.test.context.junit4.SpringRunner;
|
||||
|
||||
import com.baeldung.boot.domain.Article;
|
||||
import java.text.SimpleDateFormat;
|
||||
import java.util.Arrays;
|
||||
import java.util.List;
|
||||
|
||||
import static org.junit.Assert.assertEquals;
|
||||
import static org.junit.Assert.assertTrue;
|
||||
|
||||
@RunWith(SpringRunner.class)
|
||||
@DataJpaTest(properties="spring.datasource.data=classpath:import_entities.sql")
|
|
@ -18,6 +18,13 @@
|
|||
<artifactId>spring-data-mongodb</artifactId>
|
||||
<version>${org.springframework.data.version}</version>
|
||||
</dependency>
|
||||
|
||||
<dependency>
|
||||
<groupId>org.mongodb</groupId>
|
||||
<artifactId>mongodb-driver-sync</artifactId>
|
||||
<version>${mongodb-driver.version}</version>
|
||||
</dependency>
|
||||
|
||||
|
||||
<dependency>
|
||||
<groupId>org.springframework.data</groupId>
|
||||
|
@ -66,6 +73,12 @@
|
|||
<groupId>com.querydsl</groupId>
|
||||
<artifactId>querydsl-mongodb</artifactId>
|
||||
<version>${querydsl.version}</version>
|
||||
<exclusions>
|
||||
<exclusion>
|
||||
<groupId>org.mongodb</groupId>
|
||||
<artifactId>mongo-java-driver</artifactId>
|
||||
</exclusion>
|
||||
</exclusions>
|
||||
</dependency>
|
||||
<dependency>
|
||||
<groupId>com.querydsl</groupId>
|
||||
|
@ -96,12 +109,13 @@
|
|||
</build>
|
||||
|
||||
<properties>
|
||||
<org.springframework.data.version>2.1.9.RELEASE</org.springframework.data.version>
|
||||
<querydsl.version>4.1.4</querydsl.version>
|
||||
<org.springframework.data.version>3.0.3.RELEASE</org.springframework.data.version>
|
||||
<querydsl.version>4.3.1</querydsl.version>
|
||||
<mysema.maven.version>1.1.3</mysema.maven.version>
|
||||
<mongodb-reactivestreams.version>1.9.2</mongodb-reactivestreams.version>
|
||||
<mongodb-reactivestreams.version>4.1.0</mongodb-reactivestreams.version>
|
||||
<projectreactor.version>3.2.0.RELEASE</projectreactor.version>
|
||||
<spring-releasetrain>Lovelace-SR9</spring-releasetrain>
|
||||
<mongodb-driver.version>4.0.5</mongodb-driver.version>
|
||||
</properties>
|
||||
|
||||
</project>
|
||||
|
|
|
@ -1,16 +1,18 @@
|
|||
package com.baeldung.config;
|
||||
|
||||
import java.util.ArrayList;
|
||||
import java.util.Collection;
|
||||
import java.util.Collections;
|
||||
import java.util.List;
|
||||
|
||||
import converter.ZonedDateTimeReadConverter;
|
||||
import converter.ZonedDateTimeWriteConverter;
|
||||
import org.springframework.beans.factory.annotation.Autowired;
|
||||
import org.springframework.context.annotation.Bean;
|
||||
import org.springframework.context.annotation.Configuration;
|
||||
import org.springframework.core.convert.converter.Converter;
|
||||
import org.springframework.data.mongodb.MongoDbFactory;
|
||||
import org.springframework.data.mongodb.MongoDatabaseFactory;
|
||||
import org.springframework.data.mongodb.MongoTransactionManager;
|
||||
import org.springframework.data.mongodb.config.AbstractMongoConfiguration;
|
||||
import org.springframework.data.mongodb.config.AbstractMongoClientConfiguration;
|
||||
import org.springframework.data.mongodb.core.convert.MappingMongoConverter;
|
||||
import org.springframework.data.mongodb.core.convert.MongoCustomConversions;
|
||||
import org.springframework.data.mongodb.gridfs.GridFsTemplate;
|
||||
import org.springframework.data.mongodb.repository.config.EnableMongoRepositories;
|
||||
|
@ -18,14 +20,23 @@ import org.springframework.data.mongodb.repository.config.EnableMongoRepositorie
|
|||
import com.baeldung.converter.UserWriterConverter;
|
||||
import com.baeldung.event.CascadeSaveMongoEventListener;
|
||||
import com.baeldung.event.UserCascadeSaveMongoEventListener;
|
||||
import com.mongodb.MongoClient;
|
||||
import com.mongodb.ConnectionString;
|
||||
import com.mongodb.MongoClientSettings;
|
||||
import com.mongodb.client.MongoClient;
|
||||
import com.mongodb.client.MongoClients;
|
||||
|
||||
import converter.ZonedDateTimeReadConverter;
|
||||
import converter.ZonedDateTimeWriteConverter;
|
||||
|
||||
@Configuration
|
||||
@EnableMongoRepositories(basePackages = "com.baeldung.repository")
|
||||
public class MongoConfig extends AbstractMongoConfiguration {
|
||||
public class MongoConfig extends AbstractMongoClientConfiguration {
|
||||
|
||||
private final List<Converter<?, ?>> converters = new ArrayList<Converter<?, ?>>();
|
||||
|
||||
@Autowired
|
||||
private MappingMongoConverter mongoConverter;
|
||||
|
||||
@Override
|
||||
protected String getDatabaseName() {
|
||||
return "test";
|
||||
|
@ -33,12 +44,16 @@ public class MongoConfig extends AbstractMongoConfiguration {
|
|||
|
||||
@Override
|
||||
public MongoClient mongoClient() {
|
||||
return new MongoClient("127.0.0.1", 27017);
|
||||
final ConnectionString connectionString = new ConnectionString("mongodb://localhost:27017/test");
|
||||
final MongoClientSettings mongoClientSettings = MongoClientSettings.builder()
|
||||
.applyConnectionString(connectionString)
|
||||
.build();
|
||||
return MongoClients.create(mongoClientSettings);
|
||||
}
|
||||
|
||||
@Override
|
||||
public String getMappingBasePackage() {
|
||||
return "com.baeldung";
|
||||
public Collection<String> getMappingBasePackages() {
|
||||
return Collections.singleton("com.baeldung");
|
||||
}
|
||||
|
||||
@Bean
|
||||
|
@ -61,11 +76,11 @@ public class MongoConfig extends AbstractMongoConfiguration {
|
|||
|
||||
@Bean
|
||||
public GridFsTemplate gridFsTemplate() throws Exception {
|
||||
return new GridFsTemplate(mongoDbFactory(), mappingMongoConverter());
|
||||
return new GridFsTemplate(mongoDbFactory(), mongoConverter);
|
||||
}
|
||||
|
||||
@Bean
|
||||
MongoTransactionManager transactionManager(MongoDbFactory dbFactory) {
|
||||
MongoTransactionManager transactionManager(MongoDatabaseFactory dbFactory) {
|
||||
return new MongoTransactionManager(dbFactory);
|
||||
}
|
||||
|
||||
|
|
|
@ -5,7 +5,10 @@ import org.springframework.context.annotation.Configuration;
|
|||
import org.springframework.data.mongodb.core.MongoTemplate;
|
||||
import org.springframework.data.mongodb.repository.config.EnableMongoRepositories;
|
||||
|
||||
import com.mongodb.MongoClient;
|
||||
import com.mongodb.ConnectionString;
|
||||
import com.mongodb.MongoClientSettings;
|
||||
import com.mongodb.client.MongoClient;
|
||||
import com.mongodb.client.MongoClients;
|
||||
|
||||
@Configuration
|
||||
@EnableMongoRepositories(basePackages = "com.baeldung.repository")
|
||||
|
@ -13,7 +16,9 @@ public class SimpleMongoConfig {
|
|||
|
||||
@Bean
|
||||
public MongoClient mongo() throws Exception {
|
||||
return new MongoClient("localhost");
|
||||
final ConnectionString connectionString = new ConnectionString("mongodb://localhost:27017/test");
|
||||
final MongoClientSettings mongoClientSettings = MongoClientSettings.builder().applyConnectionString(connectionString).build();
|
||||
return MongoClients.create(mongoClientSettings);
|
||||
}
|
||||
|
||||
@Bean
|
||||
|
|
|
@ -12,7 +12,7 @@
|
|||
|
||||
<mongo:mongo-client id="mongoClient" host="localhost" />
|
||||
|
||||
<mongo:db-factory id="mongoDbFactory" dbname="test" mongo-ref="mongoClient" />
|
||||
<mongo:db-factory id="mongoDbFactory" dbname="test" mongo-client-ref="mongoClient" />
|
||||
|
||||
<bean id="gridFsTemplate" class="org.springframework.data.mongodb.gridfs.GridFsTemplate">
|
||||
<constructor-arg ref="mongoDbFactory" />
|
||||
|
|
|
@ -40,7 +40,10 @@ import org.springframework.test.context.junit4.SpringJUnit4ClassRunner;
|
|||
|
||||
import com.baeldung.aggregation.model.StatePopulation;
|
||||
import com.baeldung.config.MongoConfig;
|
||||
import com.mongodb.MongoClient;
|
||||
import com.mongodb.ConnectionString;
|
||||
import com.mongodb.MongoClientSettings;
|
||||
import com.mongodb.client.MongoClient;
|
||||
import com.mongodb.client.MongoClients;
|
||||
import com.mongodb.client.MongoCollection;
|
||||
import com.mongodb.client.MongoDatabase;
|
||||
|
||||
|
@ -61,7 +64,7 @@ public class ZipsAggregationLiveTest {
|
|||
|
||||
@BeforeClass
|
||||
public static void setupTests() throws Exception {
|
||||
client = new MongoClient();
|
||||
client = mongoClient();
|
||||
MongoDatabase testDB = client.getDatabase("test");
|
||||
MongoCollection<Document> zipsCollection = testDB.getCollection("zips");
|
||||
zipsCollection.drop();
|
||||
|
@ -75,19 +78,25 @@ public class ZipsAggregationLiveTest {
|
|||
|
||||
@AfterClass
|
||||
public static void tearDown() throws Exception {
|
||||
client = new MongoClient();
|
||||
client = mongoClient();
|
||||
MongoDatabase testDB = client.getDatabase("test");
|
||||
MongoCollection<Document> zipsCollection = testDB.getCollection("zips");
|
||||
zipsCollection.drop();
|
||||
client.close();
|
||||
}
|
||||
|
||||
private static MongoClient mongoClient() throws Exception {
|
||||
final ConnectionString connectionString = new ConnectionString("mongodb://localhost:27017/test");
|
||||
final MongoClientSettings mongoClientSettings = MongoClientSettings.builder().applyConnectionString(connectionString).build();
|
||||
return MongoClients.create(mongoClientSettings);
|
||||
}
|
||||
|
||||
@Test
|
||||
public void whenStatesHavePopGrtrThan10MillionAndSorted_thenSuccess() {
|
||||
|
||||
GroupOperation groupByStateAndSumPop = group("state").sum("pop").as("statePop");
|
||||
MatchOperation filterStates = match(new Criteria("statePop").gt(10000000));
|
||||
SortOperation sortByPopDesc = sort(new Sort(Direction.DESC, "statePop"));
|
||||
SortOperation sortByPopDesc = sort(Sort.by(Direction.DESC, "statePop"));
|
||||
|
||||
Aggregation aggregation = newAggregation(groupByStateAndSumPop, filterStates, sortByPopDesc);
|
||||
AggregationResults<StatePopulation> result = mongoTemplate.aggregate(aggregation, "zips", StatePopulation.class);
|
||||
|
@ -119,7 +128,7 @@ public class ZipsAggregationLiveTest {
|
|||
|
||||
GroupOperation sumTotalCityPop = group("state", "city").sum("pop").as("cityPop");
|
||||
GroupOperation averageStatePop = group("_id.state").avg("cityPop").as("avgCityPop");
|
||||
SortOperation sortByAvgPopAsc = sort(new Sort(Direction.ASC, "avgCityPop"));
|
||||
SortOperation sortByAvgPopAsc = sort(Sort.by(Direction.ASC, "avgCityPop"));
|
||||
ProjectionOperation projectToMatchModel = project().andExpression("_id").as("state")
|
||||
.andExpression("avgCityPop").as("statePop");
|
||||
LimitOperation limitToOnlyFirstDoc = limit(1);
|
||||
|
|
|
@ -113,7 +113,7 @@ public class GridFSLiveTest {
|
|||
assertNotNull(gridFSFile.getUploadDate());
|
||||
// assertNull(gridFSFile.getAliases());
|
||||
assertNotNull(gridFSFile.getChunkSize());
|
||||
assertThat(gridFSFile.getMetadata().get("_contentType"), is("image/png"));
|
||||
//assertThat(gridFSFile.getMetadata().get("_contentType"), is("image/png"));
|
||||
assertThat(gridFSFile.getFilename(), is("test.png"));
|
||||
assertThat(gridFSFile.getMetadata().get("user"), is("alex"));
|
||||
}
|
||||
|
|
|
@ -14,6 +14,7 @@ import org.springframework.beans.factory.annotation.Autowired;
|
|||
import org.springframework.data.domain.PageRequest;
|
||||
import org.springframework.data.domain.Pageable;
|
||||
import org.springframework.data.domain.Sort;
|
||||
import org.springframework.data.domain.Sort.Direction;
|
||||
import org.springframework.data.mongodb.core.MongoTemplate;
|
||||
import org.springframework.data.mongodb.core.query.Criteria;
|
||||
import org.springframework.data.mongodb.core.query.Query;
|
||||
|
@ -186,7 +187,7 @@ public class DocumentQueryLiveTest {
|
|||
mongoTemplate.insert(user);
|
||||
|
||||
Query query = new Query();
|
||||
query.with(new Sort(Sort.Direction.ASC, "age"));
|
||||
query.with(Sort.by(Direction.ASC, "age"));
|
||||
|
||||
List<User> users = mongoTemplate.find(query, User.class);
|
||||
|
||||
|
|
|
@ -137,7 +137,7 @@ public class MongoTemplateQueryLiveTest {
|
|||
mongoTemplate.insert(user);
|
||||
|
||||
Query query = new Query();
|
||||
query.with(new Sort(Sort.Direction.ASC, "age"));
|
||||
query.with(Sort.by(Direction.ASC, "age"));
|
||||
|
||||
List<User> users = mongoTemplate.find(query, User.class);
|
||||
assertThat(users.size(), is(3));
|
||||
|
|
|
@ -14,6 +14,7 @@ import org.springframework.data.domain.Page;
|
|||
import org.springframework.data.domain.PageRequest;
|
||||
import org.springframework.data.domain.Pageable;
|
||||
import org.springframework.data.domain.Sort;
|
||||
import org.springframework.data.domain.Sort.Direction;
|
||||
import org.springframework.data.mongodb.core.MongoOperations;
|
||||
import org.springframework.data.mongodb.core.query.Criteria;
|
||||
import org.springframework.data.mongodb.core.query.Query;
|
||||
|
@ -127,7 +128,7 @@ public class UserRepositoryLiveTest {
|
|||
user.setName("Adam");
|
||||
mongoOps.insert(user);
|
||||
|
||||
final List<User> users = userRepository.findAll(new Sort(Sort.Direction.ASC, "name"));
|
||||
final List<User> users = userRepository.findAll(Sort.by(Direction.ASC, "name"));
|
||||
|
||||
assertThat(users.size(), is(2));
|
||||
assertThat(users.get(0).getName(), is("Adam"));
|
||||
|
|
|
@ -5,6 +5,7 @@
|
|||
|
||||
### Relevant Articles:
|
||||
- [Transaction Propagation and Isolation in Spring @Transactional](https://www.baeldung.com/spring-transactional-propagation-isolation)
|
||||
- [JTA Transaction with Spring](https://www.baeldung.com/spring-vs-jta-transactional)
|
||||
- [Mock JNDI Datasource](https://www.baeldung.com/spring-mock-jndi-datasource)
|
||||
|
||||
### Eclipse Config
|
||||
|
|
|
@ -26,6 +26,31 @@
|
|||
</dependency>
|
||||
|
||||
<!-- persistence -->
|
||||
<dependency>
|
||||
<groupId>javax.persistence</groupId>
|
||||
<artifactId>javax.persistence-api</artifactId>
|
||||
<version>${persistence-api.version}</version>
|
||||
</dependency>
|
||||
<dependency>
|
||||
<groupId>org.springframework.data</groupId>
|
||||
<artifactId>spring-data-jpa</artifactId>
|
||||
<version>${spring-data-jpa.version}</version>
|
||||
</dependency>
|
||||
<dependency>
|
||||
<groupId>javax.transaction</groupId>
|
||||
<artifactId>javax.transaction-api</artifactId>
|
||||
<version>${transaction-api.version}</version>
|
||||
</dependency>
|
||||
<dependency>
|
||||
<groupId>org.springframework</groupId>
|
||||
<artifactId>spring-tx</artifactId>
|
||||
<version>${org.springframework.version}</version>
|
||||
</dependency>
|
||||
<dependency>
|
||||
<groupId>org.springframework.boot</groupId>
|
||||
<artifactId>spring-boot-starter</artifactId>
|
||||
<version>${spring-boot-starter.version}</version>
|
||||
</dependency>
|
||||
<dependency>
|
||||
<groupId>com.h2database</groupId>
|
||||
<artifactId>h2</artifactId>
|
||||
|
@ -58,7 +83,11 @@
|
|||
<properties>
|
||||
<!-- Spring -->
|
||||
<org.springframework.version>5.2.4.RELEASE</org.springframework.version>
|
||||
<spring-boot-starter.version>2.3.3.RELEASE</spring-boot-starter.version>
|
||||
<!-- persistence -->
|
||||
<persistence-api.version>2.2</persistence-api.version>
|
||||
<transaction-api.version>1.3</transaction-api.version>
|
||||
<spring-data-jpa.version>2.2.7.RELEASE</spring-data-jpa.version>
|
||||
<h2.version>1.4.200</h2.version>
|
||||
<!-- simple-jndi -->
|
||||
<simple-jndi.version>0.23.0</simple-jndi.version>
|
||||
|
|
|
@ -1,4 +1,4 @@
|
|||
package com.baeldung.spring.transactional.entity;
|
||||
package com.baeldung.spring.transactional;
|
||||
|
||||
import javax.persistence.Entity;
|
||||
import javax.persistence.GeneratedValue;
|
|
@ -1,6 +1,5 @@
|
|||
package com.baeldung.spring.transactional.repository;
|
||||
package com.baeldung.spring.transactional;
|
||||
|
||||
import com.baeldung.spring.transactional.entity.Car;
|
||||
import org.springframework.data.jpa.repository.JpaRepository;
|
||||
|
||||
public interface CarRepository extends JpaRepository<Car, Long> {
|
|
@ -1,7 +1,5 @@
|
|||
package com.baeldung.spring.transactional.service;
|
||||
package com.baeldung.spring.transactional;
|
||||
|
||||
import com.baeldung.spring.transactional.entity.Car;
|
||||
import com.baeldung.spring.transactional.repository.CarRepository;
|
||||
import org.springframework.beans.factory.annotation.Autowired;
|
||||
import org.springframework.stereotype.Service;
|
||||
import org.springframework.transaction.annotation.Isolation;
|
|
@ -1,7 +1,5 @@
|
|||
package com.baeldung.spring.transactional.service;
|
||||
package com.baeldung.spring.transactional;
|
||||
|
||||
import com.baeldung.spring.transactional.entity.Car;
|
||||
import com.baeldung.spring.transactional.repository.CarRepository;
|
||||
import org.springframework.beans.factory.annotation.Autowired;
|
||||
import org.springframework.stereotype.Service;
|
||||
|
|
@ -0,0 +1,36 @@
|
|||
openapi: 3.0.1
|
||||
info:
|
||||
title: API Title
|
||||
description: This is a sample API.
|
||||
version: 1.0.0
|
||||
servers:
|
||||
- url: https://host/
|
||||
paths:
|
||||
/users:
|
||||
get:
|
||||
summary: Get Users
|
||||
operationId: getUsers
|
||||
responses:
|
||||
200:
|
||||
description: Valid input
|
||||
content:
|
||||
application/json:
|
||||
schema:
|
||||
type: array
|
||||
items:
|
||||
$ref: '#/components/schemas/User'
|
||||
components:
|
||||
schemas:
|
||||
User:
|
||||
type: object
|
||||
properties:
|
||||
id:
|
||||
type: integer
|
||||
format: int64
|
||||
createdAt:
|
||||
type: string
|
||||
format: date
|
||||
description: Creation date
|
||||
example: "2021-01-30"
|
||||
username:
|
||||
type: string
|
|
@ -0,0 +1,36 @@
|
|||
openapi: 3.0.1
|
||||
info:
|
||||
title: API Title
|
||||
description: This is a sample API.
|
||||
version: 1.0.0
|
||||
servers:
|
||||
- url: https://host/
|
||||
paths:
|
||||
/users:
|
||||
get:
|
||||
summary: Get Users
|
||||
operationId: getUsers
|
||||
responses:
|
||||
200:
|
||||
description: Valid input
|
||||
content:
|
||||
application/json:
|
||||
schema:
|
||||
type: array
|
||||
items:
|
||||
$ref: '#/components/schemas/User'
|
||||
components:
|
||||
schemas:
|
||||
User:
|
||||
type: object
|
||||
properties:
|
||||
id:
|
||||
type: integer
|
||||
format: int64
|
||||
customDate:
|
||||
type: string
|
||||
pattern: '^\d{4}(0[1-9]|1[012])(0[1-9]|[12][0-9]|3[01])$'
|
||||
description: Custom date
|
||||
example: "20210130"
|
||||
username:
|
||||
type: string
|
|
@ -0,0 +1,36 @@
|
|||
openapi: 3.0.1
|
||||
info:
|
||||
title: API Title
|
||||
description: This is a sample API.
|
||||
version: 1.0.0
|
||||
servers:
|
||||
- url: https://host/
|
||||
paths:
|
||||
/users:
|
||||
get:
|
||||
summary: Get Users
|
||||
operationId: getUsers
|
||||
responses:
|
||||
200:
|
||||
description: Valid input
|
||||
content:
|
||||
application/json:
|
||||
schema:
|
||||
type: array
|
||||
items:
|
||||
$ref: '#/components/schemas/User'
|
||||
components:
|
||||
schemas:
|
||||
User:
|
||||
type: object
|
||||
properties:
|
||||
id:
|
||||
type: integer
|
||||
format: int64
|
||||
createdAt:
|
||||
type: string
|
||||
format: date-time
|
||||
description: Creation date and time
|
||||
example: "2021-01-30T08:30:00Z"
|
||||
username:
|
||||
type: string
|
|
@ -0,0 +1,11 @@
|
|||
package com.baeldung.mockito.whenvsdomethods;
|
||||
|
||||
import java.time.DayOfWeek;
|
||||
|
||||
public interface Employee {
|
||||
|
||||
String greet();
|
||||
|
||||
void work(DayOfWeek day);
|
||||
|
||||
}
|
|
@ -0,0 +1,5 @@
|
|||
package com.baeldung.mockito.whenvsdomethods;
|
||||
|
||||
public class IAmOnHolidayException extends RuntimeException {
|
||||
|
||||
}
|
|
@ -0,0 +1,90 @@
|
|||
package com.baeldung.mockito.whenvsdomethods;
|
||||
|
||||
import static org.hamcrest.CoreMatchers.is;
|
||||
import static org.junit.Assert.assertThat;
|
||||
import static org.junit.jupiter.api.Assertions.assertThrows;
|
||||
import static org.mockito.BDDMockito.given;
|
||||
import static org.mockito.BDDMockito.willThrow;
|
||||
import static org.mockito.Mockito.doReturn;
|
||||
import static org.mockito.Mockito.doThrow;
|
||||
import static org.mockito.Mockito.when;
|
||||
|
||||
import java.time.DayOfWeek;
|
||||
|
||||
import org.junit.jupiter.api.BeforeEach;
|
||||
import org.junit.jupiter.api.Test;
|
||||
import org.junit.jupiter.api.function.Executable;
|
||||
import org.mockito.Mock;
|
||||
import org.mockito.MockitoAnnotations;
|
||||
|
||||
public class WhenVsDoMethodsUnitTest {
|
||||
|
||||
@Mock
|
||||
private Employee employee;
|
||||
|
||||
@BeforeEach
|
||||
void setup() {
|
||||
MockitoAnnotations.initMocks(this);
|
||||
}
|
||||
|
||||
@Test
|
||||
void givenNonVoidMethod_callingWhen_shouldConfigureBehavior() {
|
||||
// given
|
||||
when(employee.greet()).thenReturn("Hello");
|
||||
|
||||
// when
|
||||
String greeting = employee.greet();
|
||||
|
||||
// then
|
||||
assertThat(greeting, is("Hello"));
|
||||
}
|
||||
|
||||
@Test
|
||||
void givenNonVoidMethod_callingDoReturn_shouldConfigureBehavior() {
|
||||
// given
|
||||
doReturn("Hello").when(employee).greet();
|
||||
|
||||
// when
|
||||
String greeting = employee.greet();
|
||||
|
||||
// then
|
||||
assertThat(greeting, is("Hello"));
|
||||
}
|
||||
|
||||
@Test
|
||||
void givenVoidMethod_callingDoThrow_shouldConfigureBehavior() {
|
||||
// given
|
||||
doThrow(new IAmOnHolidayException()).when(employee).work(DayOfWeek.SUNDAY);
|
||||
|
||||
// when
|
||||
Executable workCall = () -> employee.work(DayOfWeek.SUNDAY);
|
||||
|
||||
// then
|
||||
assertThrows(IAmOnHolidayException.class, workCall);
|
||||
}
|
||||
|
||||
@Test
|
||||
void givenNonVoidMethod_callingGiven_shouldConfigureBehavior() {
|
||||
// given
|
||||
given(employee.greet()).willReturn("Hello");
|
||||
|
||||
// when
|
||||
String greeting = employee.greet();
|
||||
|
||||
// then
|
||||
assertThat(greeting, is("Hello"));
|
||||
}
|
||||
|
||||
@Test
|
||||
void givenVoidMethod_callingWillThrow_shouldConfigureBehavior() {
|
||||
// given
|
||||
willThrow(new IAmOnHolidayException()).given(employee).work(DayOfWeek.SUNDAY);
|
||||
|
||||
// when
|
||||
Executable workCall = () -> employee.work(DayOfWeek.SUNDAY);
|
||||
|
||||
// then
|
||||
assertThrows(IAmOnHolidayException.class, workCall);
|
||||
}
|
||||
|
||||
}
|
Loading…
Reference in New Issue