Merge remote-tracking branch 'central/master'

This commit is contained in:
Graham Cox 2017-08-23 08:24:18 +01:00
commit 23018fa208
53 changed files with 1526 additions and 47 deletions

View File

@ -0,0 +1,41 @@
<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.stackify</groupId>
<artifactId>logback-example</artifactId>
<version>0.0.1-SNAPSHOT</version>
<dependencies>
<dependency>
<groupId>ch.qos.logback</groupId>
<artifactId>logback-classic</artifactId>
<version>1.2.3</version>
</dependency>
<dependency>
<groupId>junit</groupId>
<artifactId>junit</artifactId>
<version>4.12</version>
</dependency>
<dependency>
<groupId>org.codehaus.janino</groupId>
<artifactId>janino</artifactId>
<version>3.0.7</version>
</dependency>
</dependencies>
<build>
<plugins>
<plugin>
<artifactId>maven-compiler-plugin</artifactId>
<version>3.5</version>
<configuration>
<source>1.8</source>
<target>1.8</target>
</configuration>
</plugin>
</plugins>
</build>
</project>

View File

@ -0,0 +1,28 @@
package com.stackify.logging;
import org.slf4j.Marker;
import ch.qos.logback.classic.Level;
import ch.qos.logback.classic.Logger;
import ch.qos.logback.classic.turbo.TurboFilter;
import ch.qos.logback.core.spi.FilterReply;
public class IgnoreLoggerFilter extends TurboFilter {
private String loggerName;
@Override
public FilterReply decide(Marker marker, Logger logger, Level level, String format, Object[] params, Throwable t) {
if (loggerName == null) {
return FilterReply.NEUTRAL;
} else if (loggerName.equals(logger.getName())) {
return FilterReply.DENY;
} else
return FilterReply.NEUTRAL;
}
public void setLoggerName(String loggerName) {
this.loggerName = loggerName;
}
}

View File

@ -0,0 +1,43 @@
package com.stackify.models;
public class Employee {
private String email;
private String name;
private double salary;
public Employee() {
}
public Employee(String email, String name, double salary) {
this.email = email;
this.name = name;
this.salary = salary;
}
public String getEmail() {
return email;
}
public void setEmail(String email) {
this.email = email;
}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public double getSalary() {
return salary;
}
public void setSalary(double salary) {
this.salary = salary;
}
}

View File

@ -0,0 +1,11 @@
package com.stackify.services;
import com.stackify.models.Employee;
public class EmployeeService {
public double calculateBonus(Employee user) {
return 0.1 * user.getSalary();
}
}

View File

@ -0,0 +1 @@
env=dev

View File

@ -0,0 +1,151 @@
<configuration debug="true">
<appender name="STDOUT" class="ch.qos.logback.core.ConsoleAppender">
<encoder>
<pattern>%d{HH:mm:ss.SSS} [%thread] %-5level %logger{50} - %msg%n</pattern>
</encoder>
<target>System.out</target>
</appender>
<property name="fileName" value="file.log" />
<property scope="context" resource="application.properties" />
<!-- configure appenders -->
<appender name="rollingFileAppender" class="ch.qos.logback.core.rolling.RollingFileAppender">
<rollingPolicy class="ch.qos.logback.core.rolling.TimeBasedRollingPolicy">
<fileNamePattern>log-%d{yyyy-MM-dd}.log</fileNamePattern>
<maxHistory>30</maxHistory>
<totalSizeCap>3GB</totalSizeCap>
</rollingPolicy>
<triggeringPolicy class="ch.qos.logback.core.rolling.SizeBasedTriggeringPolicy">
<maxFileSize>3MB</maxFileSize>
</triggeringPolicy>
<encoder>
<pattern>%d [%thread] %-5level %logger{50} - %msg%n</pattern>
</encoder>
</appender>
<appender name="roleSiftingAppender" class="ch.qos.logback.classic.sift.SiftingAppender">
<discriminator>
<key>userRole</key>
<defaultValue>ANONYMOUS</defaultValue>
</discriminator>
<sift>
<appender name="fileAppender" class="ch.qos.logback.core.FileAppender">
<file>${userRole}.log</file>
<layout class="ch.qos.logback.classic.PatternLayout">
<pattern>%d [%thread] %level %mdc %logger{50} - %msg%n</pattern>
</layout>
</appender>
</sift>
</appender>
<!-- configure layouts -->
<appender name="colorAppender" class="ch.qos.logback.core.ConsoleAppender">
<encoder class="ch.qos.logback.classic.encoder.PatternLayoutEncoder">
<pattern>%d %green([%thread]) %highlight(%level) %logger{50} - %msg%n</pattern>
</encoder>
</appender>
<appender name="htmlAppender" class="ch.qos.logback.core.FileAppender">
<encoder class="ch.qos.logback.core.encoder.LayoutWrappingEncoder">
<layout class="ch.qos.logback.classic.html.HTMLLayout">
<pattern>%thread%level%logger%msg</pattern>
</layout>
</encoder>
<file>log.html</file>
</appender>
<!-- configure filters -->
<appender name="STDOUT_LEVEL_FILTER_APPENDER" class="ch.qos.logback.core.ConsoleAppender">
<filter class="ch.qos.logback.classic.filter.LevelFilter">
<level>ERROR</level>
<onMatch>ACCEPT</onMatch>
<onMismatch>DENY</onMismatch>
</filter>
<encoder>
<pattern>%d{HH:mm:ss.SSS} [%thread] %-5level %logger{50} - %msg%n</pattern>
</encoder>
<target>System.err</target>
</appender>
<appender name="STDOUT_THRESHOLD_FILTER_APPENDER" class="ch.qos.logback.core.ConsoleAppender">
<filter class="ch.qos.logback.classic.filter.ThresholdFilter">
<level>WARN</level>
</filter>
<encoder>
<pattern>%d{HH:mm:ss.SSS} [%thread] %-5level %logger{50} - %msg%n</pattern>
</encoder>
</appender>
<appender name="STDOUT_EVALUATOR_FILTER_APPENDER" class="ch.qos.logback.core.ConsoleAppender">
<filter class="ch.qos.logback.core.filter.EvaluatorFilter">
<evaluator class="ch.qos.logback.classic.boolex.JaninoEventEvaluator">
<expression>return (level > DEBUG &amp;&amp; message.toLowerCase().contains("employee"));</expression>
</evaluator>
<OnMismatch>DENY</OnMismatch>
<OnMatch>NEUTRAL</OnMatch>
</filter>
<encoder>
<pattern>%d{HH:mm:ss.SSS} [%thread] %-5level %logger{50} - %msg%n</pattern>
</encoder>
</appender>
<!-- configure turbo filters -->
<turboFilter class="ch.qos.logback.classic.turbo.DuplicateMessageFilter">
<AllowedRepetitions>2</AllowedRepetitions>
</turboFilter>
<turboFilter class="com.stackify.logging.IgnoreLoggerFilter">
<LoggerName>ignoredColorLogger</LoggerName>
</turboFilter>
<!-- configure loggers -->
<logger level="info" name="rollingFileLogger" additivity="false">
<appender-ref ref="rollingFileAppender" />
</logger>
<logger level="info" name="htmlLogger" additivity="false">
<appender-ref ref="htmlAppender" />
</logger>
<logger level="info" name="roleSiftingLogger" additivity="false">
<appender-ref ref="roleSiftingAppender" />
</logger>
<logger level="info" name="colorLogger" additivity="false">
<appender-ref ref="colorAppender" />
</logger>
<logger level="info" name="ignoredColorLogger">
<appender-ref ref="colorAppender" />
</logger>
<logger level="info" name="levelFilterLogger" additivity="false">
<appender-ref ref="STDOUT_LEVEL_FILTER_APPENDER" />
</logger>
<logger level="info" name="thresholdFilterLogger" additivity="false">
<appender-ref ref="STDOUT_THRESHOLD_FILTER_APPENDER" />
</logger>
<logger level="info" name="evaluatorFilterLogger" additivity="false">
<appender-ref ref="STDOUT_EVALUATOR_FILTER_APPENDER" />
</logger>
<!-- configure root logger -->
<root level="INFO">
<appender-ref ref="STDOUT" />
</root>
<!-- configure root logger conditionally -->
<property scope="context" resource="application.properties" />
<if condition='property("env").equals("dev")'>
<then>
<root level="TRACE">
<appender-ref ref="STDOUT" />
</root>
</then>
</if>
</configuration>

View File

@ -0,0 +1,74 @@
package com.stackify.services;
import org.junit.Test;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.slf4j.MDC;
import com.stackify.models.Employee;
import ch.qos.logback.classic.Level;
public class EmployeeServiceTest {
private static final Logger logger = LoggerFactory.getLogger(Logger.ROOT_LOGGER_NAME);
private EmployeeService employeeService = new EmployeeService();
@Test
public void testAppenders() {
Logger rollingFileLogger = LoggerFactory.getLogger("rollingFileLogger");
rollingFileLogger.info("Testing rolling file logger");
MDC.put("userRole", "ADMIN");
Logger siftingLogger = LoggerFactory.getLogger("roleSiftingLogger");
siftingLogger.info("Admin Action");
}
@Test
public void testLayouts() {
Logger htmlLogger = LoggerFactory.getLogger("htmlLogger");
htmlLogger.error("Employee Information Update Failed");
htmlLogger.info("New Account Created");
Logger colorLogger = LoggerFactory.getLogger("colorLogger");
colorLogger.error("Employee Information Update Failed");
colorLogger.info("New Account Created");
}
@Test
public void testLogLevel() {
ch.qos.logback.classic.Logger rollingFileLogger = (ch.qos.logback.classic.Logger) LoggerFactory.getLogger("rollingFileLogger");
rollingFileLogger.setLevel(Level.DEBUG);
rollingFileLogger.debug("Testing Log Level");
}
@Test
public void testParameter() {
Employee employee = new Employee("john@gmail.com", "John", 2000);
if (logger.isDebugEnabled()) {
logger.debug("The bonus for employee: " + employee.getName() + " is " + employeeService.calculateBonus(employee));
}
logger.debug("The bonus for employee {} is {}", employee.getName(), employeeService.calculateBonus(employee));
}
@Test
public void testFilters() {
Logger levelFilterLogger = LoggerFactory.getLogger("levelFilterLogger");
levelFilterLogger.error("Employee Information Update Failed");
Logger thresholdFilterLogger = LoggerFactory.getLogger("thresholdFilterLogger");
thresholdFilterLogger.trace("Employee record inserted");
Logger evaluatorFilterLogger = LoggerFactory.getLogger("evaluatorFilterLogger");
evaluatorFilterLogger.debug("Employee account deactivated");
}
@Test
public void testIgnoredLogger() {
Logger colorLogger = LoggerFactory.getLogger("ignoredColorLogger");
colorLogger.info("Ignored Log Message");
}
@Test
public void testConditionalConfiguration() {
logger.trace("Employee record updated");
}
}

View File

@ -105,6 +105,92 @@
</executions>
</plugin>
<!-- /Neuroph -->
<!-- Reladomo -->
<plugin>
<artifactId>maven-antrun-plugin</artifactId>
<version>1.8</version>
<executions>
<execution>
<id>generateMithra</id>
<phase>generate-sources</phase>
<goals>
<goal>run</goal>
</goals>
<configuration>
<tasks>
<property name="plugin_classpath" refid="maven.plugin.classpath" />
<taskdef name="gen-reladomo" classpath="plugin_classpath"
classname="com.gs.fw.common.mithra.generator.MithraGenerator" />
<gen-reladomo
xml="${project.basedir}/src/main/resources/reladomo/ReladomoClassList.xml"
generateGscListMethod="true"
generatedDir="${project.build.directory}/generated-sources/reladomo"
nonGeneratedDir="${project.basedir}/src/main/java" />
<taskdef name="gen-ddl"
classname="com.gs.fw.common.mithra.generator.dbgenerator.MithraDbDefinitionGenerator"
loaderRef="reladomoGenerator">
<classpath refid="maven.plugin.classpath" />
</taskdef>
<gen-ddl
xml="${project.basedir}/src/main/resources/reladomo/ReladomoClassList.xml"
generatedDir="${project.build.directory}/generated-db/sql"
databaseType="postgres" />
</tasks>
</configuration>
</execution>
</executions>
<dependencies>
<dependency>
<groupId>com.goldmansachs.reladomo</groupId>
<artifactId>reladomogen</artifactId>
<version>${reladomo.version}</version>
</dependency>
<dependency>
<groupId>com.goldmansachs.reladomo</groupId>
<artifactId>reladomo-gen-util</artifactId>
<version>${reladomo.version}</version>
</dependency>
</dependencies>
</plugin>
<plugin>
<groupId>org.codehaus.mojo</groupId>
<artifactId>build-helper-maven-plugin</artifactId>
<version>3.0.0</version>
<executions>
<execution>
<id>add-source</id>
<phase>generate-sources</phase>
<goals>
<goal>add-source</goal>
</goals>
<configuration>
<sources>
<source>${project.build.directory}/generated-sources/reladomo</source>
</sources>
</configuration>
</execution>
<execution>
<id>add-resource</id>
<phase>generate-resources</phase>
<goals>
<goal>add-resource</goal>
</goals>
<configuration>
<resources>
<resource>
<directory>${project.build.directory}/generated-db/</directory>
</resource>
</resources>
</configuration>
</execution>
</executions>
</plugin>
<!-- /Reladomo-->
</plugins>
</build>
<dependencies>
@ -497,6 +583,16 @@
<artifactId>gt-swing</artifactId>
<version>${geotools.version}</version>
</dependency>
<dependency>
<groupId>com.goldmansachs.reladomo</groupId>
<artifactId>reladomo</artifactId>
<version>${reladomo.version}</version>
</dependency>
<dependency>
<groupId>com.goldmansachs.reladomo</groupId>
<artifactId>reladomo-test-util</artifactId>
<version>${reladomo.version}</version>
</dependency>
</dependencies>
<repositories>
<repository>
@ -563,6 +659,6 @@
<streamex.version>0.6.5</streamex.version>
<vavr.version>0.9.0</vavr.version>
<geotools.version>15.2</geotools.version>
<reladomo.version>16.5.1</reladomo.version>
</properties>
</project>
</project>

View File

@ -7,7 +7,7 @@ import net.openhft.chronicle.ExcerptAppender;
public class ChronicleQueue {
public static void writeToQueue(
static void writeToQueue(
Chronicle chronicle, String stringValue, int intValue, long longValue, double doubleValue)
throws IOException {
ExcerptAppender appender = chronicle.createAppender();

View File

@ -0,0 +1,15 @@
package com.baeldung.reladomo;
public class Department extends DepartmentAbstract {
public Department() {
super();
// You must not modify this constructor. Mithra calls this internally.
// You can call this constructor. You can also add new constructors.
}
public Department(long id, String name) {
super();
this.setId(id);
this.setName(name);
}
}

View File

@ -0,0 +1,4 @@
package com.baeldung.reladomo;
public class DepartmentDatabaseObject extends DepartmentDatabaseObjectAbstract
{
}

View File

@ -0,0 +1,25 @@
package com.baeldung.reladomo;
import com.gs.fw.finder.Operation;
import java.util.*;
public class DepartmentList extends DepartmentListAbstract
{
public DepartmentList()
{
super();
}
public DepartmentList(int initialSize)
{
super(initialSize);
}
public DepartmentList(Collection c)
{
super(c);
}
public DepartmentList(Operation operation)
{
super(operation);
}
}

View File

@ -0,0 +1,16 @@
package com.baeldung.reladomo;
public class Employee extends EmployeeAbstract
{
public Employee()
{
super();
// You must not modify this constructor. Mithra calls this internally.
// You can call this constructor. You can also add new constructors.
}
public Employee(long id, String name){
super();
this.setId(id);
this.setName(name);
}
}

View File

@ -0,0 +1,4 @@
package com.baeldung.reladomo;
public class EmployeeDatabaseObject extends EmployeeDatabaseObjectAbstract
{
}

View File

@ -0,0 +1,25 @@
package com.baeldung.reladomo;
import com.gs.fw.finder.Operation;
import java.util.*;
public class EmployeeList extends EmployeeListAbstract
{
public EmployeeList()
{
super();
}
public EmployeeList(int initialSize)
{
super(initialSize);
}
public EmployeeList(Collection c)
{
super(c);
}
public EmployeeList(Operation operation)
{
super(operation);
}
}

View File

@ -0,0 +1,54 @@
package com.baeldung.reladomo;
import java.io.InputStream;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import com.gs.fw.common.mithra.MithraManager;
import com.gs.fw.common.mithra.MithraManagerProvider;
public class ReladomoApplication {
public static void main(String[] args) {
try {
ReladomoConnectionManager.getInstance().createTables();
} catch (Exception e1) {
e1.printStackTrace();
}
MithraManager mithraManager = MithraManagerProvider.getMithraManager();
mithraManager.setTransactionTimeout(120);
try (InputStream is = ReladomoApplication.class.getClassLoader().getResourceAsStream("ReladomoRuntimeConfig.xml")) {
MithraManagerProvider.getMithraManager().readConfiguration(is);
Department department = new Department(1, "IT");
Employee employee = new Employee(1, "John");
department.getEmployees().add(employee);
department.cascadeInsert();
Department depFound = DepartmentFinder.findByPrimaryKey(1);
System.out.println("Department Name:" + department.getName());
Employee empFound = EmployeeFinder.findOne(EmployeeFinder.name().eq("John"));
System.out.println("Employee Id:" + empFound.getId());
empFound.setName("Steven");
empFound.delete();
Department depDetached = DepartmentFinder.findByPrimaryKey(1).getDetachedCopy();
mithraManager.executeTransactionalCommand(tx -> {
Department dep = new Department(2, "HR");
Employee emp = new Employee(2, "Jim");
dep.getEmployees().add(emp);
dep.cascadeInsert();
return null;
});
} catch (java.io.IOException e) {
e.printStackTrace();
}
}
}

View File

@ -0,0 +1,92 @@
package com.baeldung.reladomo;
import java.io.IOException;
import java.nio.file.Files;
import java.nio.file.Path;
import java.nio.file.Paths;
import java.sql.Connection;
import java.sql.SQLException;
import java.util.TimeZone;
import java.util.stream.Stream;
import org.h2.tools.RunScript;
import com.gs.fw.common.mithra.bulkloader.BulkLoader;
import com.gs.fw.common.mithra.bulkloader.BulkLoaderException;
import com.gs.fw.common.mithra.connectionmanager.SourcelessConnectionManager;
import com.gs.fw.common.mithra.connectionmanager.XAConnectionManager;
import com.gs.fw.common.mithra.databasetype.DatabaseType;
import com.gs.fw.common.mithra.databasetype.H2DatabaseType;
public class ReladomoConnectionManager implements SourcelessConnectionManager {
private static ReladomoConnectionManager instance;
private XAConnectionManager xaConnectionManager;
private final String databaseName = "myDb";
public static synchronized ReladomoConnectionManager getInstance() {
if (instance == null) {
instance = new ReladomoConnectionManager();
}
return instance;
}
private ReladomoConnectionManager() {
this.createConnectionManager();
}
private XAConnectionManager createConnectionManager() {
xaConnectionManager = new XAConnectionManager();
xaConnectionManager.setDriverClassName("org.h2.Driver");
xaConnectionManager.setJdbcConnectionString("jdbc:h2:mem:" + databaseName);
xaConnectionManager.setJdbcUser("sa");
xaConnectionManager.setJdbcPassword("");
xaConnectionManager.setPoolName("My Connection Pool");
xaConnectionManager.setInitialSize(1);
xaConnectionManager.setPoolSize(10);
xaConnectionManager.initialisePool();
return xaConnectionManager;
}
@Override
public BulkLoader createBulkLoader() throws BulkLoaderException {
return null;
}
@Override
public Connection getConnection() {
return xaConnectionManager.getConnection();
}
@Override
public DatabaseType getDatabaseType() {
return H2DatabaseType.getInstance();
}
@Override
public TimeZone getDatabaseTimeZone() {
return TimeZone.getDefault();
}
@Override
public String getDatabaseIdentifier() {
return databaseName;
}
public void createTables() throws Exception {
Path ddlPath = Paths.get(ClassLoader.getSystemResource("sql").toURI());
try (Connection conn = xaConnectionManager.getConnection(); Stream<Path> list = Files.list(ddlPath);) {
list.forEach(path -> {
try {
RunScript.execute(conn, Files.newBufferedReader(path));
} catch (SQLException | IOException exc) {
exc.printStackTrace();
}
});
}
}
}

View File

@ -0,0 +1,6 @@
<MithraRuntime>
<ConnectionManager className="com.baeldung.reladomo.ReladomoConnectionManager ">
<MithraObjectConfiguration className="com.baeldung.reladomo.Department" cacheType="partial"/>
<MithraObjectConfiguration className="com.baeldung.reladomo.Employee " cacheType="partial"/>
</ConnectionManager>
</MithraRuntime>

View File

@ -0,0 +1,11 @@
<MithraObject objectType="transactional">
<PackageName>com.baeldung.reladomo</PackageName>
<ClassName>Department</ClassName>
<DefaultTable>departments</DefaultTable>
<Attribute name="id" javaType="long" columnName="department_id" primaryKey="true"/>
<Attribute name="name" javaType="String" columnName="name" maxLength="50" truncate="true"/>
<Relationship name="employees" relatedObject="Employee" cardinality="one-to-many" reverseRelationshipName="department" relatedIsDependent="true">
Employee.departmentId = this.id
</Relationship>
</MithraObject>

View File

@ -0,0 +1,9 @@
<MithraObject objectType="transactional">
<PackageName>com.baeldung.reladomo</PackageName>
<ClassName>Employee</ClassName>
<DefaultTable>employees</DefaultTable>
<Attribute name="id" javaType="long" columnName="employee_id" primaryKey="true"/>
<Attribute name="name" javaType="String" columnName="name" maxLength="50" truncate="true"/>
<Attribute name="departmentId" javaType="long" columnName="department_id"/>
</MithraObject>

View File

@ -0,0 +1,4 @@
<Mithra>
<MithraObjectResource name="Department"/>
<MithraObjectResource name="Employee"/>
</Mithra>

View File

@ -11,10 +11,13 @@ import java.util.concurrent.TimeUnit;
import static org.awaitility.Awaitility.await;
import static org.awaitility.Awaitility.fieldIn;
import static org.awaitility.Awaitility.given;
import static org.awaitility.Awaitility.setDefaultPollDelay;
import static org.awaitility.Awaitility.setDefaultPollInterval;
import static org.awaitility.Awaitility.setDefaultTimeout;
import static org.awaitility.proxy.AwaitilityClassProxy.to;
import static org.hamcrest.Matchers.equalTo;
public class AsyncServiceUnitTest {
public class AsyncServiceLongRunningUnitTest {
private AsyncService asyncService;
@Before
@ -41,9 +44,9 @@ public class AsyncServiceUnitTest {
@Test
public void givenAsyncService_whenInitialize_thenInitOccurs_withDefualts() {
Awaitility.setDefaultPollInterval(10, TimeUnit.MILLISECONDS);
Awaitility.setDefaultPollDelay(Duration.ZERO);
Awaitility.setDefaultTimeout(Duration.ONE_MINUTE);
setDefaultPollInterval(10, TimeUnit.MILLISECONDS);
setDefaultPollDelay(Duration.ZERO);
setDefaultTimeout(Duration.ONE_MINUTE);
asyncService.initialize();
await().until(asyncService::isInitialized);

View File

@ -13,7 +13,7 @@ import net.openhft.chronicle.ChronicleQueueBuilder;
import net.openhft.chronicle.ExcerptTailer;
import net.openhft.chronicle.tools.ChronicleTools;
public class ChronicleQueueTest {
public class ChronicleQueueIntegrationTest {
@Test
public void givenSetOfValues_whenWriteToQueue_thenWriteSuccesfully() throws IOException {

View File

@ -11,7 +11,7 @@ import java.util.stream.LongStream;
import static org.assertj.core.api.AssertionsForInterfaceTypes.assertThat;
public class HLLUnitTest {
public class HLLLongRunningUnitTest {
@Test
public void givenHLL_whenAddHugeAmountOfNumbers_thenShouldReturnEstimatedCardinality() {

View File

@ -0,0 +1,38 @@
package com.baeldung.reladomo;
import static org.junit.Assert.*;
import org.junit.After;
import org.junit.Before;
import org.junit.Test;
import com.gs.fw.common.mithra.test.ConnectionManagerForTests;
import com.gs.fw.common.mithra.test.MithraTestResource;
public class ReladomoTest {
private MithraTestResource mithraTestResource;
@Before
public void setUp() throws Exception {
this.mithraTestResource = new MithraTestResource("reladomo/ReladomoTestConfig.xml");
final ConnectionManagerForTests connectionManager = ConnectionManagerForTests.getInstanceForDbName("testDb");
this.mithraTestResource.createSingleDatabase(connectionManager);
mithraTestResource.addTestDataToDatabase("reladomo/test-data.txt", connectionManager);
this.mithraTestResource.setUp();
}
@Test
public void whenGetTestData_thenOk() {
Employee employee = EmployeeFinder.findByPrimaryKey(1);
assertEquals(employee.getName(), "Paul");
}
@After
public void tearDown() throws Exception {
this.mithraTestResource.tearDown();
}
}

View File

@ -0,0 +1,7 @@
<MithraRuntime>
<ConnectionManager className="com.gs.fw.common.mithra.test.ConnectionManagerForTests">
<Property name="resourceName" value="testDb"/>
<MithraObjectConfiguration className="com.baeldung.reladomo.Department" cacheType="partial"/>
<MithraObjectConfiguration className="com.baeldung.reladomo.Employee " cacheType="partial"/>
</ConnectionManager>
</MithraRuntime>

View File

@ -0,0 +1,7 @@
class com.baeldung.reladomo.Department
id, name
1, "Marketing"
class com.baeldung.reladomo.Employee
id, name
1, "Paul"

View File

@ -0,0 +1,33 @@
package com.baeldung.logging.log4j2.tests;
import java.util.Random;
import org.apache.logging.log4j.LogManager;
import org.apache.logging.log4j.Logger;
import org.junit.Test;
public class LambdaExpressionsIntegrationTest {
private static final Logger logger = LogManager.getRootLogger();
@Test
public void whenCheckLogMessage_thenOk() {
if (logger.isTraceEnabled()) {
logger.trace("Numer is {}", getRandomNumber());
}
}
@Test
public void whenUseLambdaExpression_thenOk() {
logger.trace("Number is {}", () -> getRandomNumber());
logger.trace("Name is {} and age is {}", () -> getName(), () -> getRandomNumber());
}
private int getRandomNumber() {
return (new Random()).nextInt(10);
}
private String getName() {
return "John";
}
}

View File

@ -40,16 +40,38 @@
<artifactId>ratpack-hikari</artifactId>
<version>${ratpack.version}</version>
</dependency>
<dependency>
<groupId>io.ratpack</groupId>
<artifactId>ratpack-hystrix</artifactId>
<version>${ratpack.version}</version>
</dependency>
<dependency>
<groupId>io.ratpack</groupId>
<artifactId>ratpack-rx</artifactId>
<version>${ratpack.version}</version>
</dependency>
<dependency>
<groupId>io.ratpack</groupId>
<artifactId>ratpack-test</artifactId>
<version>${ratpack.version}</version>
<scope>test</scope>
</dependency>
<dependency>
<groupId>com.h2database</groupId>
<artifactId>h2</artifactId>
<version>1.4.193</version>
</dependency>
<dependency>
<groupId>org.apache.httpcomponents</groupId>
<artifactId>httpclient</artifactId>
<version>4.5.3</version>
</dependency>
<dependency>
<groupId>org.apache.httpcomponents</groupId>
<artifactId>httpcore</artifactId>
<version>4.4.6</version>
</dependency>
</dependencies>
<build>

View File

@ -0,0 +1,54 @@
package com.baeldung.hystrix;
import com.netflix.hystrix.HystrixCommand;
import com.netflix.hystrix.HystrixCommandGroupKey;
import com.netflix.hystrix.HystrixCommandProperties;
import org.apache.http.client.config.RequestConfig;
import org.apache.http.client.methods.HttpGet;
import org.apache.http.impl.client.HttpClientBuilder;
import org.apache.http.message.BasicHeader;
import org.apache.http.util.EntityUtils;
import java.net.URI;
import java.util.Collections;
/**
* @author aiet
*/
public class HystrixAsyncHttpCommand extends HystrixCommand<String> {
private URI uri;
private RequestConfig requestConfig;
HystrixAsyncHttpCommand(URI uri, int timeoutMillis) {
super(Setter
.withGroupKey(HystrixCommandGroupKey.Factory.asKey("hystrix-ratpack-async"))
.andCommandPropertiesDefaults(HystrixCommandProperties
.Setter()
.withExecutionTimeoutInMilliseconds(timeoutMillis)));
requestConfig = RequestConfig
.custom()
.setSocketTimeout(timeoutMillis)
.setConnectTimeout(timeoutMillis)
.setConnectionRequestTimeout(timeoutMillis)
.build();
this.uri = uri;
}
@Override
protected String run() throws Exception {
return EntityUtils.toString(HttpClientBuilder
.create()
.setDefaultRequestConfig(requestConfig)
.setDefaultHeaders(Collections.singleton(new BasicHeader("User-Agent", "Baeldung Blocking HttpClient")))
.build()
.execute(new HttpGet(uri))
.getEntity());
}
@Override
protected String getFallback() {
return "eugenp's async fallback profile";
}
}

View File

@ -0,0 +1,44 @@
package com.baeldung.hystrix;
import com.netflix.hystrix.HystrixCommandGroupKey;
import com.netflix.hystrix.HystrixCommandProperties;
import com.netflix.hystrix.HystrixObservableCommand;
import ratpack.http.client.HttpClient;
import ratpack.rx.RxRatpack;
import rx.Observable;
import java.net.URI;
/**
* @author aiet
*/
public class HystrixReactiveHttpCommand extends HystrixObservableCommand<String> {
private HttpClient httpClient;
private URI uri;
HystrixReactiveHttpCommand(HttpClient httpClient, URI uri, int timeoutMillis) {
super(Setter
.withGroupKey(HystrixCommandGroupKey.Factory.asKey("hystrix-ratpack-reactive"))
.andCommandPropertiesDefaults(HystrixCommandProperties
.Setter()
.withExecutionTimeoutInMilliseconds(timeoutMillis)));
this.httpClient = httpClient;
this.uri = uri;
}
@Override
protected Observable<String> construct() {
return RxRatpack.observe(httpClient
.get(uri, requestSpec -> requestSpec.headers(mutableHeaders -> mutableHeaders.add("User-Agent", "Baeldung HttpClient")))
.map(receivedResponse -> receivedResponse
.getBody()
.getText()));
}
@Override
protected Observable<String> resumeWithFallback() {
return Observable.just("eugenp's reactive fallback profile");
}
}

View File

@ -0,0 +1,55 @@
package com.baeldung.hystrix;
import com.netflix.hystrix.HystrixCommand;
import com.netflix.hystrix.HystrixCommandGroupKey;
import com.netflix.hystrix.HystrixCommandProperties;
import org.apache.http.client.config.RequestConfig;
import org.apache.http.client.methods.HttpGet;
import org.apache.http.impl.client.HttpClientBuilder;
import org.apache.http.message.BasicHeader;
import org.apache.http.util.EntityUtils;
import java.net.URI;
import java.util.Collections;
/**
* @author aiet
*/
public class HystrixSyncHttpCommand extends HystrixCommand<String> {
private URI uri;
private RequestConfig requestConfig;
HystrixSyncHttpCommand(URI uri, int timeoutMillis) {
super(Setter
.withGroupKey(HystrixCommandGroupKey.Factory.asKey("hystrix-ratpack-sync"))
.andCommandPropertiesDefaults(HystrixCommandProperties
.Setter()
.withExecutionTimeoutInMilliseconds(timeoutMillis)));
requestConfig = RequestConfig
.custom()
.setSocketTimeout(timeoutMillis)
.setConnectTimeout(timeoutMillis)
.setConnectionRequestTimeout(timeoutMillis)
.build();
this.uri = uri;
}
@Override
protected String run() throws Exception {
HttpGet request = new HttpGet(uri);
return EntityUtils.toString(HttpClientBuilder
.create()
.setDefaultRequestConfig(requestConfig)
.setDefaultHeaders(Collections.singleton(new BasicHeader("User-Agent", "Baeldung Blocking HttpClient")))
.build()
.execute(request)
.getEntity());
}
@Override
protected String getFallback() {
return "eugenp's sync fallback profile";
}
}

View File

@ -0,0 +1,30 @@
package com.baeldung.hystrix;
import ratpack.guice.Guice;
import ratpack.http.client.HttpClient;
import ratpack.hystrix.HystrixMetricsEventStreamHandler;
import ratpack.hystrix.HystrixModule;
import ratpack.server.RatpackServer;
import java.net.URI;
public class RatpackHystrixApp {
public static void main(String[] args) throws Exception {
final int timeout = Integer.valueOf(System.getProperty("ratpack.hystrix.timeout"));
final URI eugenGithubProfileUri = new URI("https://api.github.com/users/eugenp");
RatpackServer.start(server -> server
.registry(Guice.registry(bindingsSpec -> bindingsSpec.module(new HystrixModule().sse())))
.handlers(chain -> chain
.get("rx", ctx -> new HystrixReactiveHttpCommand(ctx.get(HttpClient.class), eugenGithubProfileUri, timeout)
.toObservable()
.subscribe(ctx::render))
.get("async", ctx -> ctx.render(new HystrixAsyncHttpCommand(eugenGithubProfileUri, timeout)
.queue()
.get()))
.get("sync", ctx -> ctx.render(new HystrixSyncHttpCommand(eugenGithubProfileUri, timeout).execute()))
.get("hystrix", new HystrixMetricsEventStreamHandler())));
}
}

View File

@ -0,0 +1,50 @@
package com.baeldung.hystrix;
import org.junit.AfterClass;
import org.junit.BeforeClass;
import org.junit.Test;
import ratpack.test.MainClassApplicationUnderTest;
import static org.hamcrest.CoreMatchers.containsString;
import static org.junit.Assert.assertThat;
/**
* @author aiet
*/
public class RatpackHystrixAppFallbackLiveTest {
static MainClassApplicationUnderTest appUnderTest;
@BeforeClass
public static void setup() {
System.setProperty("ratpack.hystrix.timeout", "10");
appUnderTest = new MainClassApplicationUnderTest(RatpackHystrixApp.class);
}
@Test
public void whenFetchReactive_thenGotFallbackProfile() {
assertThat(appUnderTest
.getHttpClient()
.getText("rx"), containsString("reactive fallback profile"));
}
@Test
public void whenFetchAsync_thenGotFallbackProfile() {
assertThat(appUnderTest
.getHttpClient()
.getText("async"), containsString("async fallback profile"));
}
@Test
public void whenFetchSync_thenGotFallbackProfile() {
assertThat(appUnderTest
.getHttpClient()
.getText("sync"), containsString("sync fallback profile"));
}
@AfterClass
public static void clean() {
appUnderTest.close();
}
}

View File

@ -0,0 +1,50 @@
package com.baeldung.hystrix;
import org.junit.AfterClass;
import org.junit.BeforeClass;
import org.junit.Test;
import ratpack.test.MainClassApplicationUnderTest;
import static org.hamcrest.CoreMatchers.containsString;
import static org.junit.Assert.assertThat;
/**
* @author aiet
*/
public class RatpackHystrixAppLiveTest {
static MainClassApplicationUnderTest appUnderTest;
@BeforeClass
public static void setup() {
System.setProperty("ratpack.hystrix.timeout", "5000");
appUnderTest = new MainClassApplicationUnderTest(RatpackHystrixApp.class);
}
@Test
public void whenFetchReactive_thenGotEugenProfile() {
assertThat(appUnderTest
.getHttpClient()
.getText("rx"), containsString("www.baeldung.com"));
}
@Test
public void whenFetchAsync_thenGotEugenProfile() {
assertThat(appUnderTest
.getHttpClient()
.getText("async"), containsString("www.baeldung.com"));
}
@Test
public void whenFetchSync_thenGotEugenProfile() {
assertThat(appUnderTest
.getHttpClient()
.getText("sync"), containsString("www.baeldung.com"));
}
@AfterClass
public static void clean() {
appUnderTest.close();
}
}

View File

@ -40,6 +40,22 @@
<artifactId>spring-boot-starter-security</artifactId>
</dependency>
<dependency>
<groupId>com.graphql-java</groupId>
<artifactId>graphql-spring-boot-starter</artifactId>
<version>3.6.0</version>
</dependency>
<dependency>
<groupId>com.graphql-java</groupId>
<artifactId>graphiql-spring-boot-starter</artifactId>
<version>3.6.0</version>
</dependency>
<dependency>
<groupId>com.graphql-java</groupId>
<artifactId>graphql-java-tools</artifactId>
<version>3.2.0</version>
</dependency>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-tomcat</artifactId>

View File

@ -0,0 +1,31 @@
package com.baeldung.graphql;
public class Author {
private String id;
private String name;
private String thumbnail;
public String getId() {
return id;
}
public void setId(String id) {
this.id = id;
}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public String getThumbnail() {
return thumbnail;
}
public void setThumbnail(String thumbnail) {
this.thumbnail = thumbnail;
}
}

View File

@ -0,0 +1,18 @@
package com.baeldung.graphql;
import java.util.List;
import java.util.Optional;
public class AuthorDao {
private List<Author> authors;
public AuthorDao(List<Author> authors) {
this.authors = authors;
}
public Optional<Author> getAuthor(String id) {
return authors.stream()
.filter(author -> id.equals(author.getId()))
.findFirst();
}
}

View File

@ -0,0 +1,17 @@
package com.baeldung.graphql;
import java.util.List;
import com.coxautodev.graphql.tools.GraphQLResolver;
public class AuthorResolver implements GraphQLResolver<Author> {
private PostDao postDao;
public AuthorResolver(PostDao postDao) {
this.postDao = postDao;
}
public List<Post> getPosts(Author author) {
return postDao.getAuthorPosts(author.getId());
}
}

View File

@ -0,0 +1,59 @@
package com.baeldung.graphql;
import java.util.ArrayList;
import java.util.List;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
@Configuration
public class GraphqlConfiguration {
@Bean
public PostDao postDao() {
List<Post> posts = new ArrayList<>();
for (int postId = 0; postId < 10; ++postId) {
for (int authorId = 0; authorId < 10; ++authorId) {
Post post = new Post();
post.setId("Post" + authorId + postId);
post.setTitle("Post " + authorId + ":" + postId);
post.setText("Post " + postId + " + by author " + authorId);
post.setAuthorId("Author" + authorId);
posts.add(post);
}
}
return new PostDao(posts);
}
@Bean
public AuthorDao authorDao() {
List<Author> authors = new ArrayList<>();
for (int authorId = 0; authorId < 10; ++authorId) {
Author author = new Author();
author.setId("Author" + authorId);
author.setName("Author " + authorId);
author.setThumbnail("http://example.com/authors/" + authorId);
authors.add(author);
}
return new AuthorDao(authors);
}
@Bean
public PostResolver postResolver(AuthorDao authorDao) {
return new PostResolver(authorDao);
}
@Bean
public AuthorResolver authorResolver(PostDao postDao) {
return new AuthorResolver(postDao);
}
@Bean
public Query query(PostDao postDao) {
return new Query(postDao);
}
@Bean
public Mutation mutation(PostDao postDao) {
return new Mutation(postDao);
}
}

View File

@ -0,0 +1,25 @@
package com.baeldung.graphql;
import java.util.UUID;
import com.coxautodev.graphql.tools.GraphQLMutationResolver;
public class Mutation implements GraphQLMutationResolver {
private PostDao postDao;
public Mutation(PostDao postDao) {
this.postDao = postDao;
}
public Post writePost(String title, String text, String category, String author) {
Post post = new Post();
post.setId(UUID.randomUUID().toString());
post.setTitle(title);
post.setText(text);
post.setCategory(category);
post.setAuthorId(author);
postDao.savePost(post);
return post;
}
}

View File

@ -0,0 +1,49 @@
package com.baeldung.graphql;
public class Post {
private String id;
private String title;
private String text;
private String category;
private String authorId;
public String getId() {
return id;
}
public void setId(String id) {
this.id = id;
}
public String getTitle() {
return title;
}
public void setTitle(String title) {
this.title = title;
}
public String getText() {
return text;
}
public void setText(String text) {
this.text = text;
}
public String getCategory() {
return category;
}
public void setCategory(String category) {
this.category = category;
}
public String getAuthorId() {
return authorId;
}
public void setAuthorId(String authorId) {
this.authorId = authorId;
}
}

View File

@ -0,0 +1,29 @@
package com.baeldung.graphql;
import java.util.List;
import java.util.stream.Collectors;
public class PostDao {
private List<Post> posts;
public PostDao(List<Post> posts) {
this.posts = posts;
}
public List<Post> getRecentPosts(int count, int offset) {
return posts.stream()
.skip(offset)
.limit(count)
.collect(Collectors.toList());
}
public List<Post> getAuthorPosts(String author) {
return posts.stream()
.filter(post -> author.equals(post.getAuthorId()))
.collect(Collectors.toList());
}
public void savePost(Post post) {
posts.add(0, post);
}
}

View File

@ -0,0 +1,17 @@
package com.baeldung.graphql;
import java.util.Optional;
import com.coxautodev.graphql.tools.GraphQLResolver;
public class PostResolver implements GraphQLResolver<Post> {
private AuthorDao authorDao;
public PostResolver(AuthorDao authorDao) {
this.authorDao = authorDao;
}
public Optional<Author> getAuthor(Post post) {
return authorDao.getAuthor(post.getAuthorId());
}
}

View File

@ -0,0 +1,17 @@
package com.baeldung.graphql;
import java.util.List;
import com.coxautodev.graphql.tools.GraphQLQueryResolver;
public class Query implements GraphQLQueryResolver {
private PostDao postDao;
public Query(PostDao postDao) {
this.postDao = postDao;
}
public List<Post> recentPosts(int count, int offset) {
return postDao.getRecentPosts(count, offset);
}
}

View File

@ -1,11 +1,14 @@
package org.baeldung.boot;
import com.baeldung.graphql.GraphqlConfiguration;
import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;
import com.baeldung.autoconfiguration.MySQLAutoconfiguration;
import org.springframework.context.annotation.Import;
@SpringBootApplication(exclude=MySQLAutoconfiguration.class)
@Import(GraphqlConfiguration.class)
public class DemoApplication {
public static void main(String[] args) {

View File

@ -0,0 +1,24 @@
type Post {
id: ID!
title: String!
text: String!
category: String
author: Author
}
type Author {
id: ID!
name: String!
thumbnail: String
posts: [Post]!
}
# The Root Query for the application
type Query {
recentPosts(count: Int, offset: Int): [Post]!
}
# The Root Mutation for the application
type Mutation {
writePost(title: String!, text: String!, category: String, author: String!) : Post!
}

View File

@ -12,17 +12,16 @@ import org.junit.AfterClass;
import org.junit.Before;
import org.junit.BeforeClass;
import org.junit.Test;
import com.baeldung.hibernate.manytomany.util.HibernateUtil;
import com.baeldung.hibernate.manytomany.model.Employee;
import com.baeldung.hibernate.manytomany.model.Project;
public class HibernateManyToManyAnnotationXMLConfigMainIntegrationTest {
public class HibernateManyToManyAnnotationMainIntegrationTest {
private static SessionFactory sessionFactory;
private Session session;
@BeforeClass
public static void beforeTests() {
sessionFactory = HibernateUtil.getSessionFactory();
@ -34,45 +33,39 @@ public class HibernateManyToManyAnnotationXMLConfigMainIntegrationTest {
session.beginTransaction();
}
@Test
public void givenSession_checkIfDatabaseIsPopulated() {
Employee employee1 = new Employee("Peter", "Oven");
public void givenData_whenInsert_thenCreatesMtoMrelationship() {
String[] employeeData = { "Peter Oven", "Allan Norman" };
String[] projectData = { "IT Project", "Networking Project" };
Set<Project> projects = new HashSet<Project>();
projects = employee1.getProjects();
int noProjects = projects.size();
assertEquals(0,noProjects);
Project project1 = new Project("IT Project");
assertNotNull(project1);
projects.add(project1);
Project project2 = new Project("Networking Project");
assertNotNull(project2);
projects.add(project2);
employee1.setProjects(projects);
assertNotNull(employee1);
Employee employee2 = new Employee("Allan", "Norman");
employee2.setProjects(projects);
assertNotNull(employee2);
session.persist(employee1);
session.persist(employee2);
session.getTransaction().commit();
session.close();
session = sessionFactory.openSession();
session.beginTransaction();
@SuppressWarnings("unchecked")
List<Project> projectList = session.createQuery("FROM Project").list();
assertNotNull(projectList);
for (String proj : projectData) {
projects.add(new Project(proj));
}
for (String emp : employeeData) {
Employee employee = new Employee(emp.split(" ")[0], emp.split(" ")[1]);
assertEquals(0, employee.getProjects().size());
employee.setProjects(projects);
assertNotNull(employee);
session.persist(employee);
}
}
@Test
public void givenSession_whenRead_thenReturnsMtoMdata() {
@SuppressWarnings("unchecked")
List<Employee> employeeList = session.createQuery("FROM Employee").list();
assertNotNull(employeeList);
for(Employee employee : employeeList) {
assertNotNull(employee.getProjects());
}
}
@After
public void tearDown() {
session.getTransaction().commit();
session.getTransaction()
.commit();
session.close();
}

View File

@ -23,11 +23,6 @@
<artifactId>kotlin-stdlib-jre8</artifactId>
<version>1.1.4</version>
</dependency>
<dependency>
<groupId>org.jetbrains.kotlin</groupId>
<artifactId>kotlin-reflect</artifactId>
<version>1.1.4</version>
</dependency>
<dependency>
<groupId>org.springframework</groupId>

View File

@ -2,6 +2,6 @@
<head>Welcome</head>
<body>
<h1>This is the body of the welcome view 2</h1>
<h1>This is the body of the welcome view</h1>
</body>
</html>

View File

@ -13,6 +13,11 @@
</parent>
<dependencies>
<dependency>
<groupId>com.insightfullogic</groupId>
<artifactId>lambda-behave</artifactId>
<version>0.4</version>
</dependency>
<dependency>
<groupId>com.google.guava</groupId>
<artifactId>guava</artifactId>

View File

@ -0,0 +1,24 @@
package com.baeldung.lambdabehave;
public class Calculator {
private int x;
private int y;
Calculator(int x, int y) {
this.x = x;
this.y = y;
}
public int add() {
return this.x + this.y;
}
public int divide(int a, int b) {
return a / b;
}
public int add(int a, int b) {
return a + b;
}
}

View File

@ -0,0 +1,54 @@
package com.baeldung.lambdabehave;
import com.insightfullogic.lambdabehave.JunitSuiteRunner;
import com.insightfullogic.lambdabehave.Suite;
import com.insightfullogic.lambdabehave.generators.Generator;
import com.insightfullogic.lambdabehave.generators.SourceGenerator;
import org.junit.runner.RunWith;
@RunWith(JunitSuiteRunner.class)
public class CalculatorTest {
private Calculator calculator;
{
Suite.describe("Lambda behave example tests", it -> {
it.isSetupWith(() -> {
calculator = new Calculator(1, 2);
});
it.should("Add the given numbers", expect -> {
expect.that(calculator.add()).is(3);
});
it.should("Throw an exception if divide by 0", expect -> {
expect.exception(ArithmeticException.class, () -> {
calculator.divide(1, 0);
});
});
it.uses(2, 3, 5)
.and(23, 10, 33)
.toShow("%d + %d = %d", (expect, a, b, c) -> {
expect.that(calculator.add(a, b)).is(c);
});
it.requires(2)
.example(Generator.asciiStrings())
.toShow("Reversing a String twice returns the original String", (expect, str) -> {
String same = new StringBuilder(str).reverse()
.reverse()
.toString();
expect.that(same)
.isEqualTo(str);
});
it.requires(2)
.withSource(SourceGenerator.deterministicNumbers(5626689007407L))
.example(Generator.asciiStrings())
.toShow("Reversing a String twice returns the original String", (expect, str) -> {
String same = new StringBuilder(str).reverse()
.reverse()
.toString();
expect.that(same)
.isEqualTo(str);
});
});
}
}