Merge remote-tracking branch 'eugenp/master'

This commit is contained in:
DOHA 2017-08-20 13:12:10 +02:00
commit d76aa38def
23 changed files with 1276 additions and 533 deletions

View File

@ -0,0 +1,28 @@
<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>thread-pools</artifactId>
<version>0.0.1-SNAPSHOT</version>
<dependencies>
<dependency>
<groupId>ch.qos.logback</groupId>
<artifactId>logback-classic</artifactId>
<version>1.2.3</version>
</dependency>
</dependencies>
<build>
<plugins>
<plugin>
<artifactId>maven-compiler-plugin</artifactId>
<version>3.5.1</version>
<configuration>
<source>1.8</source>
<target>1.8</target>
</configuration>
</plugin>
</plugins>
</build>
</project>

View File

@ -0,0 +1,28 @@
package com.stackify.models;
public class Employee {
private String name;
private double salary;
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;
}
public Employee(String name, double salary) {
super();
this.name = name;
this.salary = salary;
}
}

View File

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

View File

@ -0,0 +1,64 @@
package com.stackify.threadpools;
import java.math.BigInteger;
import java.util.ArrayList;
import java.util.Collection;
import java.util.List;
import java.util.concurrent.ForkJoinTask;
import java.util.concurrent.RecursiveTask;
import java.util.stream.IntStream;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
public class FactorialTask extends RecursiveTask<BigInteger> {
private static final Logger logger = LoggerFactory.getLogger(Logger.ROOT_LOGGER_NAME);
private static final long serialVersionUID = 1L;
private int start = 1;
private int n;
private static final int THRESHOLD = 20;
public FactorialTask(int n) {
this.n = n;
}
public FactorialTask(int start, int n) {
logger.info("New FactorialTask Created");
this.start = start;
this.n = n;
}
@Override
protected BigInteger compute() {
if ((n - start) >= THRESHOLD) {
return ForkJoinTask.invokeAll(createSubtasks())
.stream()
.map(ForkJoinTask::join)
.reduce(BigInteger.ONE, BigInteger::multiply);
} else {
return calculate(start, n);
}
}
private Collection<FactorialTask> createSubtasks() {
List<FactorialTask> dividedTasks = new ArrayList<>();
int mid = (start + n) / 2;
dividedTasks.add(new FactorialTask(start, mid));
dividedTasks.add(new FactorialTask(mid + 1, n));
return dividedTasks;
}
private BigInteger calculate(int start, int n) {
logger.info("Calculate factorial from " + start + " to " + n);
return IntStream.rangeClosed(start, n)
.mapToObj(BigInteger::valueOf)
.reduce(BigInteger.ONE, BigInteger::multiply);
}
}

View File

@ -0,0 +1,102 @@
package com.stackify.threadpools;
import java.math.BigInteger;
import java.util.concurrent.Callable;
import java.util.concurrent.ExecutionException;
import java.util.concurrent.Executor;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;
import java.util.concurrent.ForkJoinPool;
import java.util.concurrent.Future;
import java.util.concurrent.LinkedBlockingQueue;
import java.util.concurrent.ScheduledExecutorService;
import java.util.concurrent.ScheduledThreadPoolExecutor;
import java.util.concurrent.ThreadPoolExecutor;
import java.util.concurrent.TimeUnit;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import com.stackify.models.Employee;
import com.stackify.services.EmployeeService;
public class ThreadsApplication {
private static final Logger logger = LoggerFactory.getLogger(Logger.ROOT_LOGGER_NAME);
public static void main(String[] args) {
testExecutor();
testExecutorService();
testScheduledExecutorService();
testThreadPoolExecutor();
testForkJoinPool();
}
private static EmployeeService employeeService = new EmployeeService();
public static void testExecutor() {
Executor executor = Executors.newSingleThreadExecutor();
executor.execute(() -> System.out.println("Single thread pool test"));
}
public static void testExecutorService() {
Employee employee = new Employee("John", 2000);
ExecutorService executor = Executors.newFixedThreadPool(10);
Callable<Double> callableTask = () -> {
return employeeService.calculateBonus(employee);
};
Future<Double> future = executor.submit(callableTask);
try {
if (future.isDone()) {
double result = future.get();
System.out.println("Bonus is:" + result);
}
} catch (InterruptedException | ExecutionException e) {
e.printStackTrace();
}
executor.shutdown();
}
public static void testScheduledExecutorService() {
Employee employee = new Employee("John", 2000);
ScheduledExecutorService executor = Executors.newScheduledThreadPool(10);
Callable<Double> callableTask = () -> {
return employeeService.calculateBonus(employee);
};
Future<Double> futureScheduled = executor.schedule(callableTask, 2, TimeUnit.MILLISECONDS);
try {
System.out.println("Bonus:" + futureScheduled.get());
} catch (InterruptedException | ExecutionException e) {
e.printStackTrace();
}
executor.scheduleAtFixedRate(() -> System.out.println("Fixed Rate Scheduled"), 2, 2000, TimeUnit.MILLISECONDS);
executor.scheduleWithFixedDelay(() -> System.out.println("Fixed Delay Scheduled"), 2, 2000, TimeUnit.MILLISECONDS);
}
public static void testThreadPoolExecutor() {
ThreadPoolExecutor fixedPoolExecutor = (ThreadPoolExecutor) Executors.newFixedThreadPool(10);
ThreadPoolExecutor cachedPoolExecutor = (ThreadPoolExecutor) Executors.newCachedThreadPool();
ThreadPoolExecutor executor = new ThreadPoolExecutor(4, 6, 60, TimeUnit.SECONDS, new LinkedBlockingQueue<Runnable>());
executor.setMaximumPoolSize(8);
ScheduledThreadPoolExecutor scheduledExecutor = (ScheduledThreadPoolExecutor) Executors.newScheduledThreadPool(5);
}
public static void testForkJoinPool() {
ForkJoinPool pool = ForkJoinPool.commonPool();
logger.info("Thread Pool Created");
BigInteger result = pool.invoke(new FactorialTask(100));
System.out.println(result.toString());
}
}

File diff suppressed because it is too large Load Diff

View File

@ -0,0 +1,187 @@
package com.baeldung.geotools;
import java.io.File;
import java.io.Serializable;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import org.geotools.data.DataUtilities;
import org.geotools.data.DefaultTransaction;
import org.geotools.data.Transaction;
import org.geotools.data.shapefile.ShapefileDataStore;
import org.geotools.data.shapefile.ShapefileDataStoreFactory;
import org.geotools.data.simple.SimpleFeatureSource;
import org.geotools.data.simple.SimpleFeatureStore;
import org.geotools.feature.DefaultFeatureCollection;
import org.geotools.feature.simple.SimpleFeatureBuilder;
import org.geotools.feature.simple.SimpleFeatureTypeBuilder;
import org.geotools.geometry.jts.JTSFactoryFinder;
import org.geotools.referencing.crs.DefaultGeographicCRS;
import org.geotools.swing.data.JFileDataStoreChooser;
import org.opengis.feature.simple.SimpleFeature;
import org.opengis.feature.simple.SimpleFeatureType;
import com.vividsolutions.jts.geom.Coordinate;
import com.vividsolutions.jts.geom.GeometryFactory;
import com.vividsolutions.jts.geom.Point;
public class ShapeFile {
private static final String FILE_NAME = "shapefile.shp";
public static void main(String[] args) throws Exception {
DefaultFeatureCollection collection = new DefaultFeatureCollection();
GeometryFactory geometryFactory = JTSFactoryFinder.getGeometryFactory(null);
SimpleFeatureType TYPE = DataUtilities.createType("Location", "location:Point:srid=4326," + "name:String");
SimpleFeatureType CITY = createFeatureType();
SimpleFeatureBuilder featureBuilder = new SimpleFeatureBuilder(CITY);
addLocations(featureBuilder, collection);
File shapeFile = getNewShapeFile();
ShapefileDataStoreFactory dataStoreFactory = new ShapefileDataStoreFactory();
Map<String, Serializable> params = new HashMap<String, Serializable>();
params.put("url", shapeFile.toURI()
.toURL());
params.put("create spatial index", Boolean.TRUE);
ShapefileDataStore dataStore = (ShapefileDataStore) dataStoreFactory.createNewDataStore(params);
dataStore.createSchema(CITY);
// If you decide to use the TYPE type and create a Data Store with it,
// You will need to uncomment this line to set the Coordinate Reference System
// newDataStore.forceSchemaCRS(DefaultGeographicCRS.WGS84);
Transaction transaction = new DefaultTransaction("create");
String typeName = dataStore.getTypeNames()[0];
SimpleFeatureSource featureSource = dataStore.getFeatureSource(typeName);
if (featureSource instanceof SimpleFeatureStore) {
SimpleFeatureStore featureStore = (SimpleFeatureStore) featureSource;
featureStore.setTransaction(transaction);
try {
featureStore.addFeatures(collection);
transaction.commit();
} catch (Exception problem) {
problem.printStackTrace();
transaction.rollback();
} finally {
transaction.close();
}
System.exit(0); // success!
} else {
System.out.println(typeName + " does not support read/write access");
System.exit(1);
}
}
public static SimpleFeatureType createFeatureType() {
SimpleFeatureTypeBuilder builder = new SimpleFeatureTypeBuilder();
builder.setName("Location");
builder.setCRS(DefaultGeographicCRS.WGS84);
builder.add("Location", Point.class);
builder.length(15)
.add("Name", String.class);
SimpleFeatureType CITY = builder.buildFeatureType();
return CITY;
}
public static void addLocations(SimpleFeatureBuilder featureBuilder, DefaultFeatureCollection collection) {
Map<String, List<Double>> locations = new HashMap<>();
double lat = 13.752222;
double lng = 100.493889;
String name = "Bangkok";
addToLocationMap(name, lat, lng, locations);
lat = 53.083333;
lng = -0.15;
name = "New York";
addToLocationMap(name, lat, lng, locations);
lat = -33.925278;
lng = 18.423889;
name = "Cape Town";
addToLocationMap(name, lat, lng, locations);
lat = -33.859972;
lng = 151.211111;
name = "Sydney";
addToLocationMap(name, lat, lng, locations);
lat = 45.420833;
lng = -75.69;
name = "Ottawa";
addToLocationMap(name, lat, lng, locations);
lat = 30.07708;
lng = 31.285909;
name = "Cairo";
addToLocationMap(name, lat, lng, locations);
GeometryFactory geometryFactory = JTSFactoryFinder.getGeometryFactory(null);
for (Map.Entry<String, List<Double>> location : locations.entrySet()) {
Point point = geometryFactory.createPoint(new Coordinate(location.getValue()
.get(0),
location.getValue()
.get(1)));
featureBuilder.add(point);
featureBuilder.add(name);
SimpleFeature feature = featureBuilder.buildFeature(null);
collection.add(feature);
}
}
private static void addToLocationMap(String name, double lat, double lng, Map<String, List<Double>> locations) {
List<Double> coordinates = new ArrayList<>();
coordinates.add(lat);
coordinates.add(lng);
locations.put(name, coordinates);
}
private static File getNewShapeFile() {
String filePath = new File(".").getAbsolutePath() + FILE_NAME;
JFileDataStoreChooser chooser = new JFileDataStoreChooser("shp");
chooser.setDialogTitle("Save shapefile");
chooser.setSelectedFile(new File(filePath));
int returnVal = chooser.showSaveDialog(null);
if (returnVal != JFileDataStoreChooser.APPROVE_OPTION) {
System.exit(0);
}
File shapeFile = chooser.getSelectedFile();
if (shapeFile.equals(filePath)) {
System.out.println("Error: cannot replace " + filePath);
System.exit(0);
}
return shapeFile;
}
}

View File

@ -0,0 +1,27 @@
package com.baeldung.geotools;
import static org.junit.Assert.assertNotNull;
import org.geotools.feature.DefaultFeatureCollection;
import org.geotools.feature.simple.SimpleFeatureBuilder;
import org.junit.Test;
import org.opengis.feature.simple.SimpleFeatureType;
public class GeoToolsUnitTestTest {
@Test
public void givenFeatureType_whenAddLocations_returnFeatureCollection() {
DefaultFeatureCollection collection = new DefaultFeatureCollection();
SimpleFeatureType CITY = ShapeFile.createFeatureType();
SimpleFeatureBuilder featureBuilder = new SimpleFeatureBuilder(CITY);
ShapeFile.addLocations(featureBuilder, collection);
assertNotNull(collection);
}
}

View File

@ -0,0 +1,24 @@
<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</version>
<name>easy-rules</name>
<parent>
<groupId>com.baeldung</groupId>
<artifactId>parent-modules</artifactId>
<version>1.0.0-SNAPSHOT</version>
</parent>
<dependencies>
<dependency>
<groupId>org.jeasy</groupId>
<artifactId>easy-rules-core</artifactId>
<version>3.0.0</version>
</dependency>
</dependencies>
</project>

View File

@ -0,0 +1,20 @@
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

@ -0,0 +1,21 @@
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,29 @@
<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>1.0</version>
<name>openl-tablets</name>
<parent>
<groupId>com.baeldung</groupId>
<artifactId>parent-modules</artifactId>
<version>1.0.0-SNAPSHOT</version>
</parent>
<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

@ -0,0 +1,23 @@
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

@ -0,0 +1,20 @@
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

@ -0,0 +1,14 @@
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

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

View File

@ -0,0 +1,31 @@
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

@ -0,0 +1,24 @@
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

@ -0,0 +1,24 @@
<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</version>
<name>rulebook</name>
<parent>
<groupId>com.baeldung</groupId>
<artifactId>parent-modules</artifactId>
<version>1.0.0-SNAPSHOT</version>
</parent>
<dependencies>
<dependency>
<groupId>com.deliveredtechnologies</groupId>
<artifactId>rulebook-core</artifactId>
<version>0.6.2</version>
</dependency>
</dependencies>
</project>

View File

@ -0,0 +1,17 @@
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

@ -0,0 +1,12 @@
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

@ -14,11 +14,6 @@
</properties>
<dependencies>
<dependency>
<groupId>io.undertow</groupId>
<artifactId>undertow-core</artifactId>
<version>1.4.18.Final</version>
</dependency>
<dependency>
<groupId>io.undertow</groupId>
<artifactId>undertow-servlet</artifactId>