Merge remote-tracking branch 'eugenp/master'

This commit is contained in:
DOHA 2017-08-23 23:18:49 +02:00
commit 3f1d94fe3c
78 changed files with 1730 additions and 424 deletions

View File

@ -1,11 +1,11 @@
import java.util.Arrays;
import java.util.Collections;
import java.util.List;
public class BinarySearch {
public int runBinarySearch() {
int[] sortedArray = { 0, 1, 2, 3, 4, 5, 5, 6, 7, 8, 9, 9 };
int key = 6;
public int runBinarySearchIteratively(int[] sortedArray, int key, int low, int high) {
int low = 0;
int high = sortedArray.length - 1;
int index = Integer.MAX_VALUE;
while (low <= high) {
@ -23,4 +23,31 @@ public class BinarySearch {
}
return index;
}
public int runBinarySearchRecursively(int[] sortedArray, int key, int low, int high) {
int middle = (low + high) / 2;
if (high < low) {
return -1;
}
if (key == sortedArray[middle]) {
return middle;
} else if (key < sortedArray[middle]) {
return runBinarySearchRecursively(sortedArray, key, low, middle - 1);
} else {
return runBinarySearchRecursively(sortedArray, key, middle + 1, high);
}
}
public int runBinarySearchUsingJavaArrays(int[] sortedArray, Integer key) {
int index = Arrays.binarySearch(sortedArray, key);
return index;
}
public int runBinarySearchUsingJavaCollections(List<Integer> sortedList, Integer key) {
int index = Collections.binarySearch(sortedList, key);
return index;
}
}

View File

@ -1,14 +1,41 @@
import java.util.Arrays;
import java.util.List;
import org.junit.Assert;
import org.junit.Test;
public class BinarySearchTest {
int[] sortedArray = { 0, 1, 2, 3, 4, 5, 5, 6, 7, 8, 9, 9 };
int key = 6;
int expectedIndexForSearchKey = 7;
int low = 0;
int high = sortedArray.length - 1;
List<Integer> sortedList = Arrays.asList(0, 1, 2, 3, 4, 5, 5, 6, 7, 8, 9, 9);
@Test
public void givenASortedArrayOfIntegers_whenBinarySearchRunForANumber_thenGetIndexOfTheNumber() {
public void givenASortedArrayOfIntegers_whenBinarySearchRunIterativelyForANumber_thenGetIndexOfTheNumber() {
BinarySearch binSearch = new BinarySearch();
int expectedIndexForSearchKey = 7;
Assert.assertEquals(expectedIndexForSearchKey, binSearch.runBinarySearch());
Assert.assertEquals(expectedIndexForSearchKey, binSearch.runBinarySearchIteratively(sortedArray, key, low, high));
}
@Test
public void givenASortedArrayOfIntegers_whenBinarySearchRunRecursivelyForANumber_thenGetIndexOfTheNumber() {
BinarySearch binSearch = new BinarySearch();
Assert.assertEquals(expectedIndexForSearchKey, binSearch.runBinarySearchRecursively(sortedArray, key, low, high));
}
@Test
public void givenASortedArrayOfIntegers_whenBinarySearchRunUsingArraysClassStaticMethodForANumber_thenGetIndexOfTheNumber() {
BinarySearch binSearch = new BinarySearch();
Assert.assertEquals(expectedIndexForSearchKey, binSearch.runBinarySearchUsingJavaArrays(sortedArray, key));
}
@Test
public void givenASortedListOfIntegers_whenBinarySearchRunUsingCollectionsClassStaticMethodForANumber_thenGetIndexOfTheNumber() {
BinarySearch binSearch = new BinarySearch();
Assert.assertEquals(expectedIndexForSearchKey, binSearch.runBinarySearchUsingJavaCollections(sortedList, key));
}
}

View File

@ -0,0 +1,47 @@
package com.baeldung.string;
import org.junit.Test;
import static org.junit.Assert.assertEquals;
import static org.junit.Assert.assertNotEquals;
import static org.junit.Assert.assertTrue;
public class CharSequenceVsStringUnitTest {
@Test
public void givenUsingString_whenInstantiatingString_thenWrong() {
CharSequence firstString = "bealdung";
String secondString = "baeldung";
assertNotEquals(firstString, secondString);
}
@Test
public void givenIdenticalCharSequences_whenCastToString_thenEqual() {
CharSequence charSequence1 = "baeldung_1";
CharSequence charSequence2 = "baeldung_2";
assertTrue(charSequence1.toString().compareTo(charSequence2.toString()) > 0);
}
@Test
public void givenString_whenAppended_thenUnmodified() {
String test = "a";
int firstAddressOfTest = System.identityHashCode(test);
test += "b";
int secondAddressOfTest = System.identityHashCode(test);
assertEquals(firstAddressOfTest, secondAddressOfTest);
}
@Test
public void givenStringBuilder_whenAppended_thenModified() {
StringBuilder test = new StringBuilder();
test.append("a");
int firstAddressOfTest = System.identityHashCode(test);
test.append("b");
int secondAddressOfTest = System.identityHashCode(test);
assertEquals(firstAddressOfTest, secondAddressOfTest);
}
}

View File

@ -0,0 +1,31 @@
package org.baeldung.java.lists;
import java.util.Arrays;
import java.util.List;
import java.util.stream.Collectors;
import org.apache.commons.lang3.StringUtils;
import org.junit.Test;
public class ListToSTring {
@Test
public void whenListToString_thenPrintDefault() {
List<Integer> intLIst = Arrays.asList(1, 2, 3);
System.out.println(intLIst);
}
@Test
public void whenCollectorsJoining_thenPrintCustom() {
List<Integer> intList = Arrays.asList(1, 2, 3);
System.out.println(intList.stream()
.map(n -> String.valueOf(n))
.collect(Collectors.joining("-", "{", "}")));
}
@Test
public void whenStringUtilsJoin_thenPrintCustom() {
List<Integer> intList = Arrays.asList(1, 2, 3);
System.out.println(StringUtils.join(intList, "|"));
}
}

View File

@ -1,15 +0,0 @@
<project xmlns="http://maven.apache.org/POM/4.0.0" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd">
<modelVersion>4.0.0</modelVersion>
<groupId>com.baeldung.easyrules</groupId>
<artifactId>easy-rules</artifactId>
<version>1.0.0-SNAPSHOT</version>
<dependencies>
<dependency>
<groupId>org.jeasy</groupId>
<artifactId>easy-rules-core</artifactId>
<version>3.0.0</version>
</dependency>
</dependencies>
</project>

View File

@ -1,20 +0,0 @@
package com.baeldung.easyrules;
import org.jeasy.rules.annotation.Action;
import org.jeasy.rules.annotation.Condition;
import org.jeasy.rules.annotation.Rule;
@Rule(name = "Hello World rule", description = "Always say hello world")
public class HelloWorldRule {
@Condition
public boolean when() {
return true;
}
@Action
public void then() throws Exception {
System.out.println("hello world");
}
}

View File

@ -1,21 +0,0 @@
package com.baeldung.easyrules;
import org.jeasy.rules.api.Facts;
import org.jeasy.rules.api.Rules;
import org.jeasy.rules.api.RulesEngine;
import org.jeasy.rules.core.DefaultRulesEngine;
public class Launcher {
public static void main(String... args) {
// create facts
Facts facts = new Facts();
// create rules
Rules rules = new Rules();
rules.register(new HelloWorldRule());
// create a rules engine and fire rules on known facts
RulesEngine rulesEngine = new DefaultRulesEngine();
rulesEngine.fire(rules, facts);
}
}

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

@ -14,9 +14,135 @@
<groupId>com.esotericsoftware</groupId>
<artifactId>kryo</artifactId>
<version>${kryo.version}</version>
</dependency>
<dependency>
<groupId>com.h2database</groupId>
<artifactId>h2</artifactId>
<version>${h2.version}</version>
</dependency>
<dependency>
<groupId>junit</groupId>
<artifactId>junit</artifactId>
<version>${junit.version}</version>
<scope>test</scope>
</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>
<build>
<plugins>
<plugin>
<groupId>org.apache.maven.plugins</groupId>
<artifactId>maven-compiler-plugin</artifactId>
<version>${maven-compiler-plugin.version}</version>
<configuration>
<source>1.8</source>
<target>1.8</target>
</configuration>
</plugin>
<!-- 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>
<properties>
<kryo.version>4.0.1</kryo.version>
<h2.version>1.4.196</h2.version>
<reladomo.version>16.5.1</reladomo.version>
<junit.version>4.12</junit.version>
<maven-compiler-plugin.version>3.6.2</maven-compiler-plugin.version>
</properties>
</project>

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

@ -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

@ -105,6 +105,7 @@
</executions>
</plugin>
<!-- /Neuroph -->
</plugins>
</build>
<dependencies>
@ -565,4 +566,3 @@
<geotools.version>15.2</geotools.version>
</properties>
</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

@ -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,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

@ -1,23 +0,0 @@
<project xmlns="http://maven.apache.org/POM/4.0.0" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd">
<modelVersion>4.0.0</modelVersion>
<groupId>com.baeldung.openltablets</groupId>
<artifactId>openl-tablets</artifactId>
<version>0.0.1-SNAPSHOT</version>
<properties>
<project.build.sourceEncoding>UTF-8</project.build.sourceEncoding>
<project.reporting.outputEncoding>UTF-8</project.reporting.outputEncoding>
<java.version>1.8</java.version>
</properties>
<dependencies>
<dependency>
<groupId>org.openl</groupId>
<artifactId>org.openl.core</artifactId>
<version>5.19.4</version>
</dependency>
<dependency>
<groupId>org.openl.rules</groupId>
<artifactId>org.openl.rules</artifactId>
<version>5.19.4</version>
</dependency>
</dependencies>
</project>

View File

@ -1,23 +0,0 @@
package com.baeldung.openltablets.model;
public class Case {
private User user;
private int hourOfDay;
public User getUser() {
return user;
}
public void setUser(final User user) {
this.user = user;
}
public int getHourOfDay() {
return hourOfDay;
}
public void setHourOfDay(final int hourOfDay) {
this.hourOfDay = hourOfDay;
}
}

View File

@ -1,20 +0,0 @@
package com.baeldung.openltablets.model;
public enum Greeting {
GOOD_MORNING("Good Morning"),
GOOD_AFTERNOON("Good Afternoon"),
GOOD_EVENING("Good Evening"),
GOOD_NIGHT("Good Night");
private final String literal;
private Greeting(final String literal) {
this.literal = literal;
}
public String getLiteral() {
return literal;
}
}

View File

@ -1,14 +0,0 @@
package com.baeldung.openltablets.model;
public class User {
private String name;
public String getName() {
return name;
}
public void setName(final String name) {
this.name = name;
}
}

View File

@ -1,7 +0,0 @@
package com.baeldung.openltablets.rules;
import com.baeldung.openltablets.model.Case;
public interface IRule {
void helloUser(final Case aCase, final Response response);
}

View File

@ -1,31 +0,0 @@
package com.baeldung.openltablets.rules;
import java.time.LocalDateTime;
import org.openl.rules.runtime.RulesEngineFactory;
import org.openl.runtime.EngineFactory;
import com.baeldung.openltablets.model.Case;
import com.baeldung.openltablets.model.User;
public class Main {
private IRule instance;
public static void main(String[] args) {
Main rules = new Main();
User user = new User();
user.setName("Donald Duck");
Case aCase = new Case();
aCase.setUser(user);
aCase.setHourOfDay(23);
rules.process(aCase);
}
public void process(Case aCase) {
final EngineFactory<IRule> engineFactory = new RulesEngineFactory<IRule>(getClass().getClassLoader()
.getResource("openltablets/HelloUser.xls"), IRule.class);
instance = engineFactory.newEngineInstance();
instance.helloUser(aCase, new Response());
}
}

View File

@ -1,24 +0,0 @@
package com.baeldung.openltablets.rules;
import java.util.HashMap;
import java.util.Map;
public class Response {
private String result;
private Map<String, String> map = new HashMap<>();
public Response() { }
public String getResult() {
return result;
}
public void setResult(final String s) {
result = s;
}
public Map<String, String> getMap() {
return map;
}
}

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

@ -1,15 +0,0 @@
<project xmlns="http://maven.apache.org/POM/4.0.0" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd">
<modelVersion>4.0.0</modelVersion>
<groupId>com.baeldung.rulebook</groupId>
<artifactId>rulebook</artifactId>
<version>1.0.0-SNAPSHOT</version>
<dependencies>
<dependency>
<groupId>com.deliveredtechnologies</groupId>
<artifactId>rulebook-core</artifactId>
<version>0.6.2</version>
</dependency>
</dependencies>
</project>

View File

@ -1,17 +0,0 @@
package com.baeldung.rulebook;
import com.deliveredtechnologies.rulebook.lang.RuleBookBuilder;
import com.deliveredtechnologies.rulebook.model.RuleBook;
public class HelloWorldRule {
public RuleBook<Object> defineHelloWorldRules() {
return RuleBookBuilder.create()
.addRule(rule -> rule.withNoSpecifiedFactType()
.then(f -> System.out.print("Hello ")))
.addRule(rule -> rule.withNoSpecifiedFactType()
.then(f -> System.out.println("World")))
.build();
}
}

View File

@ -1,12 +0,0 @@
package com.baeldung.rulebook;
import com.deliveredtechnologies.rulebook.FactMap;
public class Launcher {
public static void main(String[] args) {
HelloWorldRule ruleBook = new HelloWorldRule();
ruleBook.defineHelloWorldRules()
.run(new FactMap<>());
}
}

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

@ -1,70 +0,0 @@
package com.baeldung.autowired;
import java.util.ArrayList;
import java.util.List;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.CommandLineRunner;
import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;
import org.springframework.context.annotation.Bean;
import org.springframework.stereotype.Service;
@SpringBootApplication
public class TypesOfBeanInjectionSpring {
private final UserService userService;
@Autowired // the @Autowired can even be omitted, in case there's only one explicit constructor
public TypesOfBeanInjectionSpring(UserService userService) {
this.userService = userService;
}
public static void main(String[] args) {
SpringApplication.run(TypesOfBeanInjectionSpring.class, args);
}
@Bean
CommandLineRunner runIt() {
return args -> {
userService.listUsers()
.stream()
.forEach(System.out::println);
};
}
}
class User {
private String name;
public User(String name) {
this.name = name;
}
// getters and setters ...
public String getName() {
return this.name;
}
public String toString() {
return name;
}
}
interface UserService {
List<User> listUsers();
}
@Service
class UserServiceImpl implements UserService {
@Override
public List<User> listUsers() {
ArrayList<User> users = new ArrayList<>(3);
users.add(new User("Snoopy"));
users.add(new User("Woodstock"));
users.add(new User("Charlie Brown"));
return users;
}
}

View File

@ -1,25 +0,0 @@
package com.baeldung.autowired;
import org.junit.Assert;
import org.junit.Test;
import org.junit.runner.RunWith;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.test.context.SpringBootTest;
import org.springframework.test.context.junit4.SpringRunner;
@RunWith(SpringRunner.class)
@SpringBootTest
public class TypesOfBeanInjectionSpringIntegrationTest {
@Autowired
UserService userService;
private static final String[] expected = new String[] { "Snoopy", "Woodstock", "Charlie Brown" };
@Test
public void givenDI_whenInjectObject_thenUserNamesAreListed() {
Assert.assertArrayEquals(expected, userService.listUsers()
.stream()
.map(User::getName)
.toArray());
}
}

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 givenData_whenInsert_thenCreatesMtoMrelationship() {
String[] employeeData = { "Peter Oven", "Allan Norman" };
String[] projectData = { "IT Project", "Networking Project" };
Set<Project> projects = new HashSet<Project>();
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_checkIfDatabaseIsPopulated() {
Employee employee1 = new Employee("Peter", "Oven");
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);
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);
});
});
}
}

View File

@ -1,19 +1,19 @@
package com.baeldung.undertow.ftp;
import java.nio.file.Paths;
import io.undertow.Undertow;
import io.undertow.server.handlers.resource.PathResourceManager;
import java.nio.file.Paths;
import static io.undertow.Handlers.resource;
public class FileServer {
public static void main(String[] args) {
Undertow server = Undertow.builder().addHttpListener(8080, "localhost")
.setHandler(resource(new PathResourceManager(Paths.get(System.getProperty("user.home")), 100))
.setDirectoryListingEnabled(true))
.build();
.setHandler(resource(new PathResourceManager(Paths.get(System.getProperty("user.home")), 100))
.setDirectoryListingEnabled(true))
.build();
server.start();
}

View File

@ -8,9 +8,10 @@ import java.util.Set;
import io.undertow.security.idm.Account;
import io.undertow.security.idm.Credential;
import io.undertow.security.idm.IdentityManager;
import io.undertow.security.idm.PasswordCredential;
public class CustomIdentityManager implements io.undertow.security.idm.IdentityManager {
public class CustomIdentityManager implements IdentityManager {
private final Map<String, char[]> users;
@ -53,12 +54,7 @@ public class CustomIdentityManager implements io.undertow.security.idm.IdentityM
private static final long serialVersionUID = 1L;
private final Principal principal = new Principal() {
@Override
public String getName() {
return id;
}
};
private final Principal principal = () -> id;
@Override
public Principal getPrincipal() {

View File

@ -1,10 +1,5 @@
package com.baeldung.undertow.secure;
import java.util.Collections;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import io.undertow.Undertow;
import io.undertow.io.IoCallback;
import io.undertow.security.api.AuthenticationMechanism;
@ -19,6 +14,11 @@ import io.undertow.security.impl.BasicAuthenticationMechanism;
import io.undertow.server.HttpHandler;
import io.undertow.server.HttpServerExchange;
import java.util.Collections;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
public class SecureServer {
public static void main(String[] args) {
@ -28,14 +28,16 @@ public class SecureServer {
final IdentityManager idm = new CustomIdentityManager(users);
Undertow server = Undertow.builder().addHttpListener(8080, "localhost").setHandler(addSecurity((exchange) -> {
final SecurityContext context = exchange.getSecurityContext();
exchange.getResponseSender().send("Hello " + context.getAuthenticatedAccount().getPrincipal().getName(),
IoCallback.END_EXCHANGE);
}, idm)).build();
Undertow server = Undertow.builder()
.addHttpListener(8080, "localhost")
.setHandler(addSecurity(SecureServer::setExchange, idm)).build();
server.start();
}
private static void setExchange(HttpServerExchange exchange) {
final SecurityContext context = exchange.getSecurityContext();
exchange.getResponseSender().send("Hello " + context.getAuthenticatedAccount().getPrincipal().getName(), IoCallback.END_EXCHANGE);
}
private static HttpHandler addSecurity(final HttpHandler toWrap, final IdentityManager identityManager) {
@ -43,7 +45,7 @@ public class SecureServer {
handler = new AuthenticationCallHandler(handler);
handler = new AuthenticationConstraintHandler(handler);
final List<AuthenticationMechanism> mechanisms = Collections
.<AuthenticationMechanism> singletonList(new BasicAuthenticationMechanism("Baeldung_Realm"));
.singletonList(new BasicAuthenticationMechanism("Baeldung_Realm"));
handler = new AuthenticationMechanismsHandler(handler, mechanisms);
handler = new SecurityInitialHandler(AuthenticationMode.PRO_ACTIVE, identityManager, handler);
return handler;

View File

@ -16,15 +16,7 @@ public class SocketServer {
public static void main(String[] args) {
Undertow server = Undertow.builder().addHttpListener(8080, "localhost")
.setHandler(path().addPrefixPath("/baeldungApp", websocket((exchange, channel) -> {
channel.getReceiveSetter().set(new AbstractReceiveListener() {
@Override
protected void onFullTextMessage(WebSocketChannel channel, BufferedTextMessage message) {
final String messageData = message.getData();
for (WebSocketChannel session : channel.getPeerConnections()) {
WebSockets.sendText(messageData, session, null);
}
}
});
channel.getReceiveSetter().set(getListener());
channel.resumeReceives();
})).addPrefixPath("/", resource(new ClassPathResourceManager(SocketServer.class.getClassLoader(),
SocketServer.class.getPackage())).addWelcomeFiles("index.html")))
@ -33,4 +25,16 @@ public class SocketServer {
server.start();
}
private static AbstractReceiveListener getListener() {
return new AbstractReceiveListener() {
@Override
protected void onFullTextMessage(WebSocketChannel channel, BufferedTextMessage message) {
final String messageData = message.getData();
for (WebSocketChannel session : channel.getPeerConnections()) {
WebSockets.sendText(messageData, session, null);
}
}
};
}
}