#970 single logging framework should be enforced (#982)

* #496 Add pipeline module to parent pom 

* #496: Add main application class and test for pipeline

* #496: Checkstyle format and add log messages on pipeline stages 🎨

* #496: Fill readme sections of pipeline 

* #496: Javadocs and checkstyle formatting 🎨

* #496: Follow PMD checks and add more explanation as block comment on App.java

* #496: Apply requested PR changes by iluwatar 🎨

* #970: Replace log4j usage on commander pattern to Slf4j API 🎨

* #970: Replace log4j usage on dao pattern to Slf4j API 🎨

* #970: Replace log4j usage on data mapper pattern to Slf4j API 🎨

* #970: Remove log4j dependency on data transfer object pom 🔥

* #970: Replace log4j usage on module pattern to Slf4j API 🎨

* #970: Replace log4j usage on serverless pattern to Slf4j API 🎨

This also removes the aws log4j dependency

* #970: Remove unnecessary gitignore line for log4j.xml 🔥

* #970: Remove remaining remnants of log4j 🔥

* #970: Replace System.out logging with appropriate logging methods 🎨

* #970: Replace System.out method references to Logger::info 🎨
This commit is contained in:
Joshua Jimenez 2019-10-14 04:41:11 +08:00 committed by Ilkka Seppälä
parent 72b174619f
commit cfdfedbd2e
50 changed files with 163 additions and 410 deletions

1
.gitignore vendored
View File

@ -16,5 +16,4 @@ datanucleus.log
/bin/ /bin/
/bin/ /bin/
*.log *.log
data-mapper/src/main/resources/log4j.xml
event-sourcing/Journal.json event-sourcing/Journal.json

View File

@ -30,11 +30,14 @@ import java.util.List;
import java.util.Map; import java.util.Map;
import org.junit.jupiter.api.Test; import org.junit.jupiter.api.Test;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
/** /**
* Tests that Collection Pipeline methods work as expected. * Tests that Collection Pipeline methods work as expected.
*/ */
public class AppTest { public class AppTest {
private static final Logger LOGGER = LoggerFactory.getLogger(AppTest.class);
private List<Car> cars = CarFactory.createCars(); private List<Car> cars = CarFactory.createCars();
@ -61,7 +64,7 @@ public class AppTest {
new Car("Jeep", "Comanche", 1990, Category.JEEP))); new Car("Jeep", "Comanche", 1990, Category.JEEP)));
Map<Category, List<Car>> modelsFunctional = FunctionalProgramming.getGroupingOfCarsByCategory(cars); Map<Category, List<Car>> modelsFunctional = FunctionalProgramming.getGroupingOfCarsByCategory(cars);
Map<Category, List<Car>> modelsImperative = ImperativeProgramming.getGroupingOfCarsByCategory(cars); Map<Category, List<Car>> modelsImperative = ImperativeProgramming.getGroupingOfCarsByCategory(cars);
System.out.println("Category " + modelsFunctional); LOGGER.info("Category " + modelsFunctional);
assertEquals(modelsExpected, modelsFunctional); assertEquals(modelsExpected, modelsFunctional);
assertEquals(modelsExpected, modelsImperative); assertEquals(modelsExpected, modelsImperative);
} }

View File

@ -36,10 +36,5 @@
<artifactId>junit-jupiter-engine</artifactId> <artifactId>junit-jupiter-engine</artifactId>
<scope>test</scope> <scope>test</scope>
</dependency> </dependency>
<dependency>
<groupId>log4j</groupId>
<artifactId>log4j</artifactId>
<version>1.2.17</version>
</dependency>
</dependencies> </dependencies>
</project> </project>

View File

@ -1,41 +0,0 @@
#
# The MIT License
# Copyright © 2014-2019 Ilkka Seppälä
#
# Permission is hereby granted, free of charge, to any person obtaining a copy
# of this software and associated documentation files (the "Software"), to deal
# in the Software without restriction, including without limitation the rights
# to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
# copies of the Software, and to permit persons to whom the Software is
# furnished to do so, subject to the following conditions:
#
# The above copyright notice and this permission notice shall be included in
# all copies or substantial portions of the Software.
#
# THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
# IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
# FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
# AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
# LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
# OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
# THE SOFTWARE.
#
#Define root logger options
log4j.rootLogger=TRACE, file, console
#Define console appender
log4j.appender.console=org.apache.log4j.ConsoleAppender
logrj.appender.console.Target=System.out
log4j.appender.console.layout=org.apache.log4j.PatternLayout
log4j.appender.console.layout.ConversionPattern=%d{yyyy-MM-dd} %d{HH:mm:ss} %5p[%t] %m%n
#Define rolling file appender
log4j.appender.file=org.apache.log4j.RollingFileAppender
log4j.appender.file.File=/log/logFile.log
log4j.appender.file.Append=true
log4j.appender.file.ImmediateFlush=true
log4j.appender.file.MaxFileSize=10MB
log4j.appender.file.MaxBackupIndex=5
log4j.appender.file.layout=org.apache.log4j.PatternLayout
log4j.appender.file.layout.ConversionPattern=%d %d{HH:mm:ss} %5p[%t] %m%n

View File

@ -23,7 +23,6 @@
package com.iluwatar.commander; package com.iluwatar.commander;
import java.util.ArrayList; import java.util.ArrayList;
import org.apache.log4j.Logger;
import com.iluwatar.commander.employeehandle.EmployeeHandle; import com.iluwatar.commander.employeehandle.EmployeeHandle;
import com.iluwatar.commander.exceptions.DatabaseUnavailableException; import com.iluwatar.commander.exceptions.DatabaseUnavailableException;
import com.iluwatar.commander.exceptions.ItemUnavailableException; import com.iluwatar.commander.exceptions.ItemUnavailableException;
@ -37,6 +36,8 @@ import com.iluwatar.commander.queue.QueueDatabase;
import com.iluwatar.commander.queue.QueueTask; import com.iluwatar.commander.queue.QueueTask;
import com.iluwatar.commander.queue.QueueTask.TaskType; import com.iluwatar.commander.queue.QueueTask.TaskType;
import com.iluwatar.commander.shippingservice.ShippingService; import com.iluwatar.commander.shippingservice.ShippingService;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
/** /**
*<p>Commander pattern is used to handle all issues that can come up while making a *<p>Commander pattern is used to handle all issues that can come up while making a
@ -86,7 +87,7 @@ public class Commander {
private final long messageTime; private final long messageTime;
private final long employeeTime; private final long employeeTime;
private boolean finalSiteMsgShown; private boolean finalSiteMsgShown;
static final Logger LOG = Logger.getLogger(Commander.class); static final Logger LOG = LoggerFactory.getLogger(Commander.class);
//we could also have another db where it stores all orders //we could also have another db where it stores all orders
Commander(EmployeeHandle empDb, PaymentService pService, ShippingService sService, Commander(EmployeeHandle empDb, PaymentService pService, ShippingService sService,
@ -125,27 +126,27 @@ public class Commander {
String transactionId = shippingService.receiveRequest(order.item, order.user.address); String transactionId = shippingService.receiveRequest(order.item, order.user.address);
//could save this transaction id in a db too //could save this transaction id in a db too
LOG.info("Order " + order.id + ": Shipping placed successfully, transaction id: " + transactionId); LOG.info("Order " + order.id + ": Shipping placed successfully, transaction id: " + transactionId);
System.out.println("Order has been placed and will be shipped to you. Please wait while we make your" LOG.info("Order has been placed and will be shipped to you. Please wait while we make your"
+ " payment... "); + " payment... ");
sendPaymentRequest(order); sendPaymentRequest(order);
return; return;
}; };
Retry.HandleErrorIssue<Order> handleError = (o,err) -> { Retry.HandleErrorIssue<Order> handleError = (o,err) -> {
if (ShippingNotPossibleException.class.isAssignableFrom(err.getClass())) { if (ShippingNotPossibleException.class.isAssignableFrom(err.getClass())) {
System.out.println("Shipping is currently not possible to your address. We are working on the problem " LOG.info("Shipping is currently not possible to your address. We are working on the problem "
+ "and will get back to you asap."); + "and will get back to you asap.");
finalSiteMsgShown = true; finalSiteMsgShown = true;
LOG.info("Order " + order.id + ": Shipping not possible to address, trying to add problem to employee db.."); LOG.info("Order " + order.id + ": Shipping not possible to address, trying to add problem to employee db..");
employeeHandleIssue(o); employeeHandleIssue(o);
} else if (ItemUnavailableException.class.isAssignableFrom(err.getClass())) { } else if (ItemUnavailableException.class.isAssignableFrom(err.getClass())) {
System.out.println("This item is currently unavailable. We will inform you as soon as the item becomes " LOG.info("This item is currently unavailable. We will inform you as soon as the item becomes "
+ "available again."); + "available again.");
finalSiteMsgShown = true; finalSiteMsgShown = true;
LOG.info("Order " + order.id + ": Item " + order.item + " unavailable, trying to add problem to employee " LOG.info("Order " + order.id + ": Item " + order.item + " unavailable, trying to add problem to employee "
+ "handle.."); + "handle..");
employeeHandleIssue(o); employeeHandleIssue(o);
} else { } else {
System.out.println("Sorry, there was a problem in creating your order. Please try later."); LOG.info("Sorry, there was a problem in creating your order. Please try later.");
LOG.error("Order " + order.id + ": Shipping service unavailable, order not placed.."); LOG.error("Order " + order.id + ": Shipping service unavailable, order not placed..");
finalSiteMsgShown = true; finalSiteMsgShown = true;
} }
@ -183,7 +184,7 @@ public class Commander {
order.paid = PaymentStatus.Done; order.paid = PaymentStatus.Done;
LOG.info("Order " + order.id + ": Payment successful, transaction Id: " + transactionId); LOG.info("Order " + order.id + ": Payment successful, transaction Id: " + transactionId);
if (!finalSiteMsgShown) { if (!finalSiteMsgShown) {
System.out.println("Payment made successfully, thank you for shopping with us!!"); LOG.info("Payment made successfully, thank you for shopping with us!!");
finalSiteMsgShown = true; finalSiteMsgShown = true;
} }
sendSuccessMessage(order); sendSuccessMessage(order);
@ -193,7 +194,7 @@ public class Commander {
Retry.HandleErrorIssue<Order> handleError = (o,err) -> { Retry.HandleErrorIssue<Order> handleError = (o,err) -> {
if (PaymentDetailsErrorException.class.isAssignableFrom(err.getClass())) { if (PaymentDetailsErrorException.class.isAssignableFrom(err.getClass())) {
if (!finalSiteMsgShown) { if (!finalSiteMsgShown) {
System.out.println("There was an error in payment. Your account/card details may have been incorrect. " LOG.info("There was an error in payment. Your account/card details may have been incorrect. "
+ "Meanwhile, your order has been converted to COD and will be shipped."); + "Meanwhile, your order has been converted to COD and will be shipped.");
finalSiteMsgShown = true; finalSiteMsgShown = true;
} }
@ -204,7 +205,7 @@ public class Commander {
try { try {
if (o.messageSent.equals(MessageSent.NoneSent)) { if (o.messageSent.equals(MessageSent.NoneSent)) {
if (!finalSiteMsgShown) { if (!finalSiteMsgShown) {
System.out.println("There was an error in payment. We are on it, and will get back to you " LOG.info("There was an error in payment. We are on it, and will get back to you "
+ "asap. Don't worry, your order has been placed and will be shipped."); + "asap. Don't worry, your order has been placed and will be shipped.");
finalSiteMsgShown = true; finalSiteMsgShown = true;
} }

View File

@ -24,6 +24,8 @@ package com.iluwatar.commander.messagingservice;
import com.iluwatar.commander.Service; import com.iluwatar.commander.Service;
import com.iluwatar.commander.exceptions.DatabaseUnavailableException; import com.iluwatar.commander.exceptions.DatabaseUnavailableException;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
/** /**
* The MessagingService is used to send messages to user regarding their order and * The MessagingService is used to send messages to user regarding their order and
@ -32,6 +34,7 @@ import com.iluwatar.commander.exceptions.DatabaseUnavailableException;
*/ */
public class MessagingService extends Service { public class MessagingService extends Service {
private static final Logger LOGGER = LoggerFactory.getLogger(MessagingService.class);
enum MessageToSend { enum MessageToSend {
PaymentFail, PaymentTrying, PaymentSuccessful PaymentFail, PaymentTrying, PaymentSuccessful
@ -74,7 +77,7 @@ public class MessagingService extends Service {
MessageRequest req = (MessageRequest) parameters[0]; MessageRequest req = (MessageRequest) parameters[0];
if (this.database.get(req.reqId) == null) { //idempotence, in case db fails here if (this.database.get(req.reqId) == null) { //idempotence, in case db fails here
database.add(req); //if successful: database.add(req); //if successful:
System.out.println(sendMessage(req.msg)); LOGGER.info(sendMessage(req.msg));
return req.reqId; return req.reqId;
} }
return null; return null;

View File

@ -24,6 +24,8 @@ package com.iluwatar.converter;
import com.google.common.collect.Lists; import com.google.common.collect.Lists;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import java.util.ArrayList; import java.util.ArrayList;
import java.util.List; import java.util.List;
@ -35,6 +37,8 @@ import java.util.List;
* objects between types. * objects between types.
*/ */
public class App { public class App {
private static final Logger LOGGER = LoggerFactory.getLogger(App.class);
/** /**
* Program entry point * Program entry point
* *
@ -45,16 +49,16 @@ public class App {
UserDto dtoUser = new UserDto("John", "Doe", true, "whatever[at]wherever.com"); UserDto dtoUser = new UserDto("John", "Doe", true, "whatever[at]wherever.com");
User user = userConverter.convertFromDto(dtoUser); User user = userConverter.convertFromDto(dtoUser);
System.out.println("Entity converted from DTO:" + user); LOGGER.info("Entity converted from DTO:" + user);
ArrayList<User> users = Lists.newArrayList(new User("Camile", "Tough", false, "124sad"), ArrayList<User> users = Lists.newArrayList(new User("Camile", "Tough", false, "124sad"),
new User("Marti", "Luther", true, "42309fd"), new User("Kate", "Smith", true, "if0243")); new User("Marti", "Luther", true, "42309fd"), new User("Kate", "Smith", true, "if0243"));
System.out.println("Domain entities:"); LOGGER.info("Domain entities:");
users.forEach(System.out::println); users.stream().map(User::toString).forEach(LOGGER::info);
System.out.println("DTO entities converted from domain:"); LOGGER.info("DTO entities converted from domain:");
List<UserDto> dtoEntities = userConverter.createFromEntities(users); List<UserDto> dtoEntities = userConverter.createFromEntities(users);
dtoEntities.forEach(System.out::println); dtoEntities.stream().map(UserDto::toString).forEach(LOGGER::info);
} }
} }

View File

@ -40,10 +40,6 @@
<artifactId>junit-jupiter-engine</artifactId> <artifactId>junit-jupiter-engine</artifactId>
<scope>test</scope> <scope>test</scope>
</dependency> </dependency>
<dependency>
<groupId>log4j</groupId>
<artifactId>log4j</artifactId>
</dependency>
<dependency> <dependency>
<groupId>com.h2database</groupId> <groupId>com.h2database</groupId>
<artifactId>h2</artifactId> <artifactId>h2</artifactId>
@ -53,49 +49,4 @@
<artifactId>mockito-core</artifactId> <artifactId>mockito-core</artifactId>
</dependency> </dependency>
</dependencies> </dependencies>
<build>
<!--
log4j.xml file will be copied both in ${project.build.outputDirectory}
and ${project.build.directory}. Thanks to Sean Patrick Floyd
(http://stackoverflow.com/questions/5637532/maven-how-to-place-resource-file-together-with-jar)
-->
<resources>
<resource> <!-- regular processing for every resource file -->
<directory>src/main/resources</directory>
</resource>
<resource> <!-- processing with a different output directory for log4j.xml -->
<directory>src/main/resources</directory>
<includes>
<include>log4j.xml</include>
</includes>
<targetPath>..</targetPath> <!-- relative to target/classes i.e. ${project.build.directory} -->
</resource>
</resources>
<plugins>
<!--
This will exclude log4j.xml file from generated JAR
-->
<plugin>
<groupId>org.apache.maven.plugins</groupId>
<artifactId>maven-jar-plugin</artifactId>
<version>2.6</version>
<configuration>
<excludes>
<exclude>log4j.xml</exclude>
</excludes>
<archive>
<manifest>
<addClasspath>true</addClasspath>
</manifest>
</archive>
</configuration>
</plugin>
</plugins>
</build>
</project> </project>

View File

@ -31,8 +31,9 @@ import java.util.stream.Stream;
import javax.sql.DataSource; import javax.sql.DataSource;
import org.apache.log4j.Logger;
import org.h2.jdbcx.JdbcDataSource; import org.h2.jdbcx.JdbcDataSource;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
/** /**
* Data Access Object (DAO) is an object that provides an abstract interface to some type of * Data Access Object (DAO) is an object that provides an abstract interface to some type of
@ -50,7 +51,7 @@ import org.h2.jdbcx.JdbcDataSource;
*/ */
public class App { public class App {
private static final String DB_URL = "jdbc:h2:~/dao"; private static final String DB_URL = "jdbc:h2:~/dao";
private static Logger log = Logger.getLogger(App.class); private static Logger log = LoggerFactory.getLogger(App.class);
private static final String ALL_CUSTOMERS = "customerDao.getAllCustomers(): "; private static final String ALL_CUSTOMERS = "customerDao.getAllCustomers(): ";
/** /**
@ -94,7 +95,7 @@ public class App {
addCustomers(customerDao); addCustomers(customerDao);
log.info(ALL_CUSTOMERS); log.info(ALL_CUSTOMERS);
try (Stream<Customer> customerStream = customerDao.getAll()) { try (Stream<Customer> customerStream = customerDao.getAll()) {
customerStream.forEach((customer) -> log.info(customer)); customerStream.forEach((customer) -> log.info(customer.toString()));
} }
log.info("customerDao.getCustomerById(2): " + customerDao.getById(2)); log.info("customerDao.getCustomerById(2): " + customerDao.getById(2));
final Customer customer = new Customer(4, "Dan", "Danson"); final Customer customer = new Customer(4, "Dan", "Danson");
@ -105,7 +106,7 @@ public class App {
customerDao.update(customer); customerDao.update(customer);
log.info(ALL_CUSTOMERS); log.info(ALL_CUSTOMERS);
try (Stream<Customer> customerStream = customerDao.getAll()) { try (Stream<Customer> customerStream = customerDao.getAll()) {
customerStream.forEach((cust) -> log.info(cust)); customerStream.forEach((cust) -> log.info(cust.toString()));
} }
customerDao.delete(customer); customerDao.delete(customer);
log.info(ALL_CUSTOMERS + customerDao.getAll()); log.info(ALL_CUSTOMERS + customerDao.getAll());

View File

@ -22,6 +22,9 @@
*/ */
package com.iluwatar.dao; package com.iluwatar.dao;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import java.sql.Connection; import java.sql.Connection;
import java.sql.PreparedStatement; import java.sql.PreparedStatement;
import java.sql.ResultSet; import java.sql.ResultSet;
@ -35,15 +38,13 @@ import java.util.stream.StreamSupport;
import javax.sql.DataSource; import javax.sql.DataSource;
import org.apache.log4j.Logger;
/** /**
* An implementation of {@link CustomerDao} that persists customers in RDBMS. * An implementation of {@link CustomerDao} that persists customers in RDBMS.
* *
*/ */
public class DbCustomerDao implements CustomerDao { public class DbCustomerDao implements CustomerDao {
private static final Logger LOGGER = Logger.getLogger(DbCustomerDao.class); private static final Logger LOGGER = LoggerFactory.getLogger(DbCustomerDao.class);
private final DataSource dataSource; private final DataSource dataSource;

View File

@ -1,41 +0,0 @@
<?xml version="1.0" encoding="UTF-8" ?>
<!--
The MIT License
Copyright © 2014-2019 Ilkka Seppälä
Permission is hereby granted, free of charge, to any person obtaining a copy
of this software and associated documentation files (the "Software"), to deal
in the Software without restriction, including without limitation the rights
to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
copies of the Software, and to permit persons to whom the Software is
furnished to do so, subject to the following conditions:
The above copyright notice and this permission notice shall be included in
all copies or substantial portions of the Software.
THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
THE SOFTWARE.
-->
<!DOCTYPE log4j:configuration SYSTEM "log4j.dtd">
<log4j:configuration debug="true"
xmlns:log4j='http://jakarta.apache.org/log4j/'>
<appender name="console" class="org.apache.log4j.ConsoleAppender">
<layout class="org.apache.log4j.PatternLayout">
<param name="ConversionPattern" value="%d{yyyy-MM-dd HH:mm:ss} %-5p %c{1}:%L - %m%n" />
</layout>
</appender>
<root>
<level value="INFO" />
<appender-ref ref="console" />
</root>
</log4j:configuration>

View File

@ -37,9 +37,5 @@
<artifactId>junit-jupiter-engine</artifactId> <artifactId>junit-jupiter-engine</artifactId>
<scope>test</scope> <scope>test</scope>
</dependency> </dependency>
<dependency>
<groupId>log4j</groupId>
<artifactId>log4j</artifactId>
</dependency>
</dependencies> </dependencies>
</project> </project>

View File

@ -22,9 +22,10 @@
*/ */
package com.iluwatar.datamapper; package com.iluwatar.datamapper;
import java.util.Optional; import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.apache.log4j.Logger; import java.util.Optional;
/** /**
* The Data Mapper (DM) is a layer of software that separates the in-memory objects from the * The Data Mapper (DM) is a layer of software that separates the in-memory objects from the
@ -39,7 +40,7 @@ import org.apache.log4j.Logger;
*/ */
public final class App { public final class App {
private static Logger log = Logger.getLogger(App.class); private static Logger log = LoggerFactory.getLogger(App.class);
private static final String STUDENT_STRING = "App.main(), student : "; private static final String STUDENT_STRING = "App.main(), student : ";

View File

@ -1,41 +0,0 @@
<?xml version="1.0" encoding="UTF-8" ?>
<!--
The MIT License
Copyright © 2014-2019 Ilkka Seppälä
Permission is hereby granted, free of charge, to any person obtaining a copy
of this software and associated documentation files (the "Software"), to deal
in the Software without restriction, including without limitation the rights
to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
copies of the Software, and to permit persons to whom the Software is
furnished to do so, subject to the following conditions:
The above copyright notice and this permission notice shall be included in
all copies or substantial portions of the Software.
THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
THE SOFTWARE.
-->
<!DOCTYPE log4j:configuration SYSTEM "log4j.dtd">
<log4j:configuration debug="true"
xmlns:log4j='http://jakarta.apache.org/log4j/'>
<appender name="console" class="org.apache.log4j.ConsoleAppender">
<layout class="org.apache.log4j.PatternLayout">
<param name="ConversionPattern" value="%d{yyyy-MM-dd HH:mm:ss} %-5p %c{1}:%L - %m%n" />
</layout>
</appender>
<root>
<level value="INFO" />
<appender-ref ref="console" />
</root>
</log4j:configuration>

View File

@ -37,9 +37,5 @@
<artifactId>junit-jupiter-engine</artifactId> <artifactId>junit-jupiter-engine</artifactId>
<scope>test</scope> <scope>test</scope>
</dependency> </dependency>
<dependency>
<groupId>log4j</groupId>
<artifactId>log4j</artifactId>
</dependency>
</dependencies> </dependencies>
</project> </project>

View File

@ -22,6 +22,9 @@
*/ */
package com.iluwatar.dirtyflag; package com.iluwatar.dirtyflag;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import java.util.List; import java.util.List;
import java.util.concurrent.Executors; import java.util.concurrent.Executors;
import java.util.concurrent.ScheduledExecutorService; import java.util.concurrent.ScheduledExecutorService;
@ -48,6 +51,8 @@ import java.util.concurrent.TimeUnit;
* when needed. {@link World} mainly serves the data to the front-end. * when needed. {@link World} mainly serves the data to the front-end.
*/ */
public class App { public class App {
private static final Logger LOGGER = LoggerFactory.getLogger(App.class);
/** /**
* Program execution point * Program execution point
*/ */
@ -59,9 +64,9 @@ public class App {
@Override @Override
public void run() { public void run() {
List<String> countries = world.fetch(); List<String> countries = world.fetch();
System.out.println("Our world currently has the following countries:-"); LOGGER.info("Our world currently has the following countries:-");
for (String country : countries) { for (String country : countries) {
System.out.println("\t" + country); LOGGER.info("\t" + country);
} }
} }
}, 0, 15, TimeUnit.SECONDS); // Run at every 15 seconds. }, 0, 15, TimeUnit.SECONDS); // Run at every 15 seconds.

View File

@ -22,6 +22,10 @@
*/ */
package com.iluwatar.dirtyflag; package com.iluwatar.dirtyflag;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import javax.xml.crypto.Data;
import java.io.BufferedReader; import java.io.BufferedReader;
import java.io.File; import java.io.File;
import java.io.FileReader; import java.io.FileReader;
@ -37,6 +41,8 @@ import java.util.List;
*/ */
public class DataFetcher { public class DataFetcher {
private static final Logger LOGGER = LoggerFactory.getLogger(DataFetcher.class);
private final String filename = "world.txt"; private final String filename = "world.txt";
private long lastFetched; private long lastFetched;
@ -62,7 +68,7 @@ public class DataFetcher {
File file = new File(classLoader.getResource(filename).getFile()); File file = new File(classLoader.getResource(filename).getFile());
if (isDirty(file.lastModified())) { if (isDirty(file.lastModified())) {
System.out.println(filename + " is dirty! Re-fetching file content..."); LOGGER.info(filename + " is dirty! Re-fetching file content...");
List<String> data = new ArrayList<String>(); List<String> data = new ArrayList<String>();
try (BufferedReader br = new BufferedReader(new FileReader(file))) { try (BufferedReader br = new BufferedReader(new FileReader(file))) {

View File

@ -22,6 +22,9 @@
*/ */
package com.iluwatar.event.queue; package com.iluwatar.event.queue;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import java.io.BufferedReader; import java.io.BufferedReader;
import java.io.IOException; import java.io.IOException;
import java.io.InputStreamReader; import java.io.InputStreamReader;
@ -39,6 +42,8 @@ import javax.sound.sampled.UnsupportedAudioFileException;
* items from the queue at a later time. * items from the queue at a later time.
*/ */
public class App { public class App {
private static final Logger LOGGER = LoggerFactory.getLogger(App.class);
/** /**
* Program entry point. * Program entry point.
* *
@ -51,7 +56,7 @@ public class App {
audio.playSound(audio.getAudioStream("./etc/Bass-Drum-1.wav"), -10.0f); audio.playSound(audio.getAudioStream("./etc/Bass-Drum-1.wav"), -10.0f);
audio.playSound(audio.getAudioStream("./etc/Closed-Hi-Hat-1.wav"), -8.0f); audio.playSound(audio.getAudioStream("./etc/Closed-Hi-Hat-1.wav"), -8.0f);
System.out.println("Press Enter key to stop the program..."); LOGGER.info("Press Enter key to stop the program...");
try (BufferedReader br = new BufferedReader(new InputStreamReader(System.in))) { try (BufferedReader br = new BufferedReader(new InputStreamReader(System.in))) {
br.read(); br.read();
} }

View File

@ -81,7 +81,7 @@ public class ConsoleAdministration {
} }
private static String readString(Scanner scanner) { private static String readString(Scanner scanner) {
System.out.print("> "); LOGGER.info("> ");
return scanner.next(); return scanner.next();
} }
} }

View File

@ -82,7 +82,7 @@ public class ConsoleLottery {
} }
private static String readString(Scanner scanner) { private static String readString(Scanner scanner) {
System.out.print("> "); LOGGER.info("> ");
return scanner.next(); return scanner.next();
} }
} }

View File

@ -122,7 +122,7 @@ public class LotteryConsoleServiceImpl implements LotteryConsoleService {
} }
private String readString(Scanner scanner) { private String readString(Scanner scanner) {
System.out.print( "> " ); logger.info( "> " );
return scanner.next(); return scanner.next();
} }
} }

View File

@ -23,6 +23,8 @@
package com.iluwatar.masterworker; package com.iluwatar.masterworker;
import com.iluwatar.masterworker.system.ArrayTransposeMasterWorker; import com.iluwatar.masterworker.system.ArrayTransposeMasterWorker;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
/** /**
* <p>The <b><em>Master-Worker</em></b> pattern is used when the problem at hand can be solved by dividing into * <p>The <b><em>Master-Worker</em></b> pattern is used when the problem at hand can be solved by dividing into
@ -46,6 +48,7 @@ import com.iluwatar.masterworker.system.ArrayTransposeMasterWorker;
public class App { public class App {
private static final Logger LOGGER = LoggerFactory.getLogger(App.class);
/** /**
* Program entry point. * Program entry point.
* @param args command line args * @param args command line args
@ -60,10 +63,9 @@ public class App {
ArrayResult result = (ArrayResult) mw.getResult(input); ArrayResult result = (ArrayResult) mw.getResult(input);
if (result != null) { if (result != null) {
ArrayUtilityMethods.printMatrix(inputMatrix); ArrayUtilityMethods.printMatrix(inputMatrix);
System.out.println("");
ArrayUtilityMethods.printMatrix(result.data); ArrayUtilityMethods.printMatrix(result.data);
} else { } else {
System.out.println("Please enter non-zero input"); LOGGER.info("Please enter non-zero input");
} }
} }

View File

@ -22,6 +22,9 @@
*/ */
package com.iluwatar.masterworker; package com.iluwatar.masterworker;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import java.util.Random; import java.util.Random;
/** /**
@ -30,6 +33,7 @@ import java.util.Random;
public class ArrayUtilityMethods { public class ArrayUtilityMethods {
private static final Logger LOGGER = LoggerFactory.getLogger(ArrayUtilityMethods.class);
/** /**
* Method arraysSame compares 2 arrays @param a1 and @param a2 * Method arraysSame compares 2 arrays @param a1 and @param a2
* and @return whether their values are equal (boolean). * and @return whether their values are equal (boolean).
@ -100,9 +104,9 @@ public class ArrayUtilityMethods {
//prints out int[][] //prints out int[][]
for (int i = 0; i < matrix.length; i++) { for (int i = 0; i < matrix.length; i++) {
for (int j = 0; j < matrix[0].length; j++) { for (int j = 0; j < matrix[0].length; j++) {
System.out.print(matrix[i][j] + " "); LOGGER.info(matrix[i][j] + " ");
} }
System.out.println(""); LOGGER.info("");
} }
} }

View File

@ -37,9 +37,5 @@
<artifactId>junit-jupiter-engine</artifactId> <artifactId>junit-jupiter-engine</artifactId>
<scope>test</scope> <scope>test</scope>
</dependency> </dependency>
<dependency>
<groupId>log4j</groupId>
<artifactId>log4j</artifactId>
</dependency>
</dependencies> </dependencies>
</project> </project>

View File

@ -22,9 +22,10 @@
*/ */
package com.iluwatar.module; package com.iluwatar.module;
import java.io.PrintStream; import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.apache.log4j.Logger; import java.io.PrintStream;
/** /**
* The ConsoleLoggerModule is responsible for showing logs on System Console * The ConsoleLoggerModule is responsible for showing logs on System Console
@ -34,7 +35,7 @@ import org.apache.log4j.Logger;
*/ */
public final class ConsoleLoggerModule { public final class ConsoleLoggerModule {
private static final Logger LOGGER = Logger.getLogger(ConsoleLoggerModule.class); private static final Logger LOGGER = LoggerFactory.getLogger(ConsoleLoggerModule.class);
private static ConsoleLoggerModule singleton = null; private static ConsoleLoggerModule singleton = null;

View File

@ -22,12 +22,13 @@
*/ */
package com.iluwatar.module; package com.iluwatar.module;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import java.io.FileNotFoundException; import java.io.FileNotFoundException;
import java.io.FileOutputStream; import java.io.FileOutputStream;
import java.io.PrintStream; import java.io.PrintStream;
import org.apache.log4j.Logger;
/** /**
* The FileLoggerModule is responsible for showing logs on File System * The FileLoggerModule is responsible for showing logs on File System
* <p> * <p>
@ -36,7 +37,7 @@ import org.apache.log4j.Logger;
*/ */
public final class FileLoggerModule { public final class FileLoggerModule {
private static final Logger LOGGER = Logger.getLogger(FileLoggerModule.class); private static final Logger LOGGER = LoggerFactory.getLogger(FileLoggerModule.class);
private static FileLoggerModule singleton = null; private static FileLoggerModule singleton = null;

View File

@ -1,41 +0,0 @@
<?xml version="1.0" encoding="UTF-8" ?>
<!--
The MIT License
Copyright © 2014-2019 Ilkka Seppälä
Permission is hereby granted, free of charge, to any person obtaining a copy
of this software and associated documentation files (the "Software"), to deal
in the Software without restriction, including without limitation the rights
to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
copies of the Software, and to permit persons to whom the Software is
furnished to do so, subject to the following conditions:
The above copyright notice and this permission notice shall be included in
all copies or substantial portions of the Software.
THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
THE SOFTWARE.
-->
<!DOCTYPE log4j:configuration SYSTEM "log4j.dtd">
<log4j:configuration debug="true"
xmlns:log4j='http://jakarta.apache.org/log4j/'>
<appender name="console" class="org.apache.log4j.ConsoleAppender">
<layout class="org.apache.log4j.PatternLayout">
<param name="ConversionPattern" value="%d{yyyy-MM-dd HH:mm:ss} %-5p %c{1}:%L - %m%n" />
</layout>
</appender>
<root>
<level value="INFO" />
<appender-ref ref="console" />
</root>
</log4j:configuration>

View File

@ -22,8 +22,9 @@
*/ */
package com.iluwatar.module; package com.iluwatar.module;
import org.apache.log4j.Logger;
import org.junit.jupiter.api.Test; import org.junit.jupiter.api.Test;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import java.io.BufferedReader; import java.io.BufferedReader;
import java.io.FileNotFoundException; import java.io.FileNotFoundException;
@ -45,7 +46,7 @@ import static org.junit.jupiter.api.Assertions.assertNull;
*/ */
public final class FileLoggerModuleTest { public final class FileLoggerModuleTest {
private static final Logger LOGGER = Logger.getLogger(FileLoggerModuleTest.class); private static final Logger LOGGER = LoggerFactory.getLogger(FileLoggerModuleTest.class);
private static final String OUTPUT_FILE = "output.txt"; private static final String OUTPUT_FILE = "output.txt";
private static final String ERROR_FILE = "error.txt"; private static final String ERROR_FILE = "error.txt";

View File

@ -1,24 +0,0 @@
#
# The MIT License
# Copyright © 2014-2019 Ilkka Seppälä
#
# Permission is hereby granted, free of charge, to any person obtaining a copy
# of this software and associated documentation files (the "Software"), to deal
# in the Software without restriction, including without limitation the rights
# to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
# copies of the Software, and to permit persons to whom the Software is
# furnished to do so, subject to the following conditions:
#
# The above copyright notice and this permission notice shall be included in
# all copies or substantial portions of the Software.
#
# THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
# IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
# FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
# AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
# LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
# OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
# THE SOFTWARE.
#
domainapp.dom.modules.simple.QSimpleObject=UnusedFormalParameter

View File

@ -143,7 +143,6 @@
<version>${datanucleus-maven-plugin.version}</version> <version>${datanucleus-maven-plugin.version}</version>
<configuration> <configuration>
<fork>false</fork> <fork>false</fork>
<log4jConfiguration>${basedir}/log4j.properties</log4jConfiguration>
<verbose>true</verbose> <verbose>true</verbose>
<props>${basedir}/datanucleus.properties</props> <props>${basedir}/datanucleus.properties</props>
</configuration> </configuration>

View File

@ -49,7 +49,6 @@ public final class SimpleAppSystemInitializer {
private static class SimpleAppSystemBuilder extends IsisSystemForTest.Builder { private static class SimpleAppSystemBuilder extends IsisSystemForTest.Builder {
public SimpleAppSystemBuilder() { public SimpleAppSystemBuilder() {
withLoggingAt(org.apache.log4j.Level.INFO);
with(testConfiguration()); with(testConfiguration());
with(new DataNucleusPersistenceMechanismInstaller()); with(new DataNucleusPersistenceMechanismInstaller());

View File

@ -36,7 +36,6 @@ public class BootstrappingGlue extends CukeGlueAbstract {
@Before(value = {"@integration"}, order = 100) @Before(value = {"@integration"}, order = 100)
public void beforeScenarioIntegrationScope() { public void beforeScenarioIntegrationScope() {
org.apache.log4j.PropertyConfigurator.configure("logging.properties");
SimpleAppSystemInitializer.initIsft(); SimpleAppSystemInitializer.initIsft();
before(ScenarioExecutionScope.INTEGRATION); before(ScenarioExecutionScope.INTEGRATION);

View File

@ -36,7 +36,6 @@ public abstract class SimpleAppIntegTest extends IntegrationTestAbstract {
@BeforeClass @BeforeClass
public static void initClass() { public static void initClass() {
org.apache.log4j.PropertyConfigurator.configure("logging.properties");
SimpleAppSystemInitializer.initIsft(); SimpleAppSystemInitializer.initIsft();
// instantiating will install onto ThreadLocal // instantiating will install onto ThreadLocal

View File

@ -216,26 +216,6 @@
<artifactId>hsqldb</artifactId> <artifactId>hsqldb</artifactId>
</dependency> </dependency>
<!-- <dependency> <groupId>postgresql</groupId> <artifactId>postgresql</artifactId>
<version>9.1-901.jdbc4</version> </dependency> -->
<!-- mvn install:install-file -Dfile=sqljdbc4.jar \ -DgroupId=com.microsoft.sqlserver
\ -DartifactId=jdbc \ -Dversion=4.0 \ -Dpackaging=jar -->
<!-- <dependency> <groupId>com.microsoft.sqlserver</groupId> <artifactId>sqljdbc4</artifactId>
<version>4.0</version> </dependency> -->
<dependency>
<groupId>org.lazyluke</groupId>
<artifactId>log4jdbc-remix</artifactId>
<exclusions>
<exclusion>
<groupId>org.slf4j</groupId>
<artifactId>slf4j-api</artifactId>
</exclusion>
</exclusions>
</dependency>
<dependency> <dependency>
<groupId>junit</groupId> <groupId>junit</groupId>
<artifactId>junit</artifactId> <artifactId>junit</artifactId>

View File

@ -50,6 +50,8 @@ import de.agilecoders.wicket.core.Bootstrap;
import de.agilecoders.wicket.core.settings.IBootstrapSettings; import de.agilecoders.wicket.core.settings.IBootstrapSettings;
import de.agilecoders.wicket.themes.markup.html.bootswatch.BootswatchTheme; import de.agilecoders.wicket.themes.markup.html.bootswatch.BootswatchTheme;
import de.agilecoders.wicket.themes.markup.html.bootswatch.BootswatchThemeProvider; import de.agilecoders.wicket.themes.markup.html.bootswatch.BootswatchThemeProvider;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
/** /**
@ -72,6 +74,7 @@ import de.agilecoders.wicket.themes.markup.html.bootswatch.BootswatchThemeProvid
*/ */
public class SimpleApplication extends IsisWicketApplication { public class SimpleApplication extends IsisWicketApplication {
private static final Logger LOGGER = LoggerFactory.getLogger(SimpleApplication.class);
private static final long serialVersionUID = 1L; private static final long serialVersionUID = 1L;
/** /**
@ -124,7 +127,7 @@ public class SimpleApplication extends IsisWicketApplication {
servletRequest.getSession().invalidate(); servletRequest.getSession().invalidate();
} }
} catch (Exception e) { } catch (Exception e) {
System.out.println(e); LOGGER.error(e.getMessage());
} }
return super.newWebRequest(servletRequest, filterPath); return super.newWebRequest(servletRequest, filterPath);
} }

View File

@ -32,12 +32,12 @@ import java.util.Arrays;
*/ */
class ConvertToCharArrayHandler implements Handler<String, char[]> { class ConvertToCharArrayHandler implements Handler<String, char[]> {
private final Logger logger = LoggerFactory.getLogger(ConvertToCharArrayHandler.class); private static final Logger LOGGER = LoggerFactory.getLogger(ConvertToCharArrayHandler.class);
@Override @Override
public char[] process(String input) { public char[] process(String input) {
char[] characters = input.toCharArray(); char[] characters = input.toCharArray();
logger.info(String.format("Current handler: %s, input is %s of type %s, output is %s, of type %s", LOGGER.info(String.format("Current handler: %s, input is %s of type %s, output is %s, of type %s",
ConvertToCharArrayHandler.class, input, String.class, Arrays.toString(characters), Character[].class)); ConvertToCharArrayHandler.class, input, String.class, Arrays.toString(characters), Character[].class));
return characters; return characters;

View File

@ -30,7 +30,7 @@ import org.slf4j.LoggerFactory;
*/ */
class RemoveAlphabetsHandler implements Handler<String, String> { class RemoveAlphabetsHandler implements Handler<String, String> {
private final Logger logger = LoggerFactory.getLogger(RemoveAlphabetsHandler.class); private static final Logger LOGGER = LoggerFactory.getLogger(RemoveAlphabetsHandler.class);
@Override @Override
public String process(String input) { public String process(String input) {
@ -46,7 +46,7 @@ class RemoveAlphabetsHandler implements Handler<String, String> {
} }
String inputWithoutAlphabetsStr = inputWithoutAlphabets.toString(); String inputWithoutAlphabetsStr = inputWithoutAlphabets.toString();
logger.info(String.format("Current handler: %s, input is %s of type %s, output is %s, of type %s", LOGGER.info(String.format("Current handler: %s, input is %s of type %s, output is %s, of type %s",
RemoveAlphabetsHandler.class, input, String.class, inputWithoutAlphabetsStr, String.class)); RemoveAlphabetsHandler.class, input, String.class, inputWithoutAlphabetsStr, String.class));
return inputWithoutAlphabetsStr; return inputWithoutAlphabetsStr;

View File

@ -30,7 +30,7 @@ import org.slf4j.LoggerFactory;
*/ */
class RemoveDigitsHandler implements Handler<String, String> { class RemoveDigitsHandler implements Handler<String, String> {
private final Logger logger = LoggerFactory.getLogger(RemoveDigitsHandler.class); private static final Logger LOGGER = LoggerFactory.getLogger(RemoveDigitsHandler.class);
@Override @Override
public String process(String input) { public String process(String input) {
@ -46,7 +46,7 @@ class RemoveDigitsHandler implements Handler<String, String> {
} }
String inputWithoutDigitsStr = inputWithoutDigits.toString(); String inputWithoutDigitsStr = inputWithoutDigits.toString();
logger.info(String.format("Current handler: %s, input is %s of type %s, output is %s, of type %s", LOGGER.info(String.format("Current handler: %s, input is %s of type %s, output is %s, of type %s",
RemoveDigitsHandler.class, input, String.class, inputWithoutDigitsStr, String.class)); RemoveDigitsHandler.class, input, String.class, inputWithoutDigitsStr, String.class));
return inputWithoutDigitsStr; return inputWithoutDigitsStr;

View File

@ -56,10 +56,8 @@
<logback.version>1.2.3</logback.version> <logback.version>1.2.3</logback.version>
<aws-lambda-core.version>1.1.0</aws-lambda-core.version> <aws-lambda-core.version>1.1.0</aws-lambda-core.version>
<aws-java-sdk-dynamodb.version>1.11.289</aws-java-sdk-dynamodb.version> <aws-java-sdk-dynamodb.version>1.11.289</aws-java-sdk-dynamodb.version>
<aws-lambda-log4j.version>1.0.0</aws-lambda-log4j.version>
<aws-lambda-java-events.version>2.0.1</aws-lambda-java-events.version> <aws-lambda-java-events.version>2.0.1</aws-lambda-java-events.version>
<jackson.version>2.8.5</jackson.version> <jackson.version>2.8.5</jackson.version>
<log4j.version>1.2.17</log4j.version>
<jaxb-api.version>2.3.1</jaxb-api.version> <jaxb-api.version>2.3.1</jaxb-api.version>
<jaxb-impl.version>2.3.2</jaxb-impl.version> <jaxb-impl.version>2.3.2</jaxb-impl.version>
<annotation-api.version>1.3.2</annotation-api.version> <annotation-api.version>1.3.2</annotation-api.version>
@ -304,11 +302,6 @@
<artifactId>mongo-java-driver</artifactId> <artifactId>mongo-java-driver</artifactId>
<version>${mongo-java-driver.version}</version> <version>${mongo-java-driver.version}</version>
</dependency> </dependency>
<dependency>
<groupId>log4j</groupId>
<artifactId>log4j</artifactId>
<version>${log4j.version}</version>
</dependency>
<dependency> <dependency>
<groupId>javax.xml.bind</groupId> <groupId>javax.xml.bind</groupId>
<artifactId>jaxb-api</artifactId> <artifactId>jaxb-api</artifactId>

View File

@ -60,11 +60,6 @@
<artifactId>aws-lambda-java-events</artifactId> <artifactId>aws-lambda-java-events</artifactId>
<version>${aws-lambda-java-events.version}</version> <version>${aws-lambda-java-events.version}</version>
</dependency> </dependency>
<dependency>
<groupId>com.amazonaws</groupId>
<artifactId>aws-lambda-java-log4j</artifactId>
<version>${aws-lambda-log4j.version}</version>
</dependency>
<dependency> <dependency>
<groupId>com.fasterxml.jackson.core</groupId> <groupId>com.fasterxml.jackson.core</groupId>
<artifactId>jackson-core</artifactId> <artifactId>jackson-core</artifactId>

View File

@ -27,7 +27,10 @@ import com.amazonaws.services.lambda.runtime.RequestHandler;
import com.amazonaws.services.lambda.runtime.events.APIGatewayProxyRequestEvent; import com.amazonaws.services.lambda.runtime.events.APIGatewayProxyRequestEvent;
import com.amazonaws.services.lambda.runtime.events.APIGatewayProxyResponseEvent; import com.amazonaws.services.lambda.runtime.events.APIGatewayProxyResponseEvent;
import com.iluwatar.serverless.baas.model.Person; import com.iluwatar.serverless.baas.model.Person;
import org.apache.log4j.Logger; import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import java.util.Map;
/** /**
* find person from persons collection * find person from persons collection
@ -36,13 +39,15 @@ import org.apache.log4j.Logger;
public class FindPersonApiHandler extends AbstractDynamoDbHandler<Person> public class FindPersonApiHandler extends AbstractDynamoDbHandler<Person>
implements RequestHandler<APIGatewayProxyRequestEvent, APIGatewayProxyResponseEvent> { implements RequestHandler<APIGatewayProxyRequestEvent, APIGatewayProxyResponseEvent> {
private static final Logger LOG = Logger.getLogger(FindPersonApiHandler.class); private static final Logger LOG = LoggerFactory.getLogger(FindPersonApiHandler.class);
private static final Integer SUCCESS_STATUS_CODE = 200; private static final Integer SUCCESS_STATUS_CODE = 200;
@Override @Override
public APIGatewayProxyResponseEvent handleRequest(APIGatewayProxyRequestEvent apiGatewayProxyRequestEvent, public APIGatewayProxyResponseEvent handleRequest(APIGatewayProxyRequestEvent apiGatewayProxyRequestEvent,
Context context) { Context context) {
LOG.info(apiGatewayProxyRequestEvent.getPathParameters()); Map<String, String> pathParameters = apiGatewayProxyRequestEvent.getPathParameters();
pathParameters.keySet().stream().map(key -> key + "=" + pathParameters.get(key)).forEach(LOG::info);
Person person = this.getDynamoDbMapper().load(Person.class, apiGatewayProxyRequestEvent Person person = this.getDynamoDbMapper().load(Person.class, apiGatewayProxyRequestEvent
.getPathParameters().get("id")); .getPathParameters().get("id"));

View File

@ -27,7 +27,8 @@ import com.amazonaws.services.lambda.runtime.RequestHandler;
import com.amazonaws.services.lambda.runtime.events.APIGatewayProxyRequestEvent; import com.amazonaws.services.lambda.runtime.events.APIGatewayProxyRequestEvent;
import com.amazonaws.services.lambda.runtime.events.APIGatewayProxyResponseEvent; import com.amazonaws.services.lambda.runtime.events.APIGatewayProxyResponseEvent;
import com.iluwatar.serverless.baas.model.Person; import com.iluwatar.serverless.baas.model.Person;
import org.apache.log4j.Logger; import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import java.io.IOException; import java.io.IOException;
@ -38,7 +39,7 @@ import java.io.IOException;
public class SavePersonApiHandler extends AbstractDynamoDbHandler<Person> public class SavePersonApiHandler extends AbstractDynamoDbHandler<Person>
implements RequestHandler<APIGatewayProxyRequestEvent, APIGatewayProxyResponseEvent> { implements RequestHandler<APIGatewayProxyRequestEvent, APIGatewayProxyResponseEvent> {
private static final Logger LOG = Logger.getLogger(SavePersonApiHandler.class); private static final Logger LOG = LoggerFactory.getLogger(SavePersonApiHandler.class);
private static final Integer CREATED_STATUS_CODE = 201; private static final Integer CREATED_STATUS_CODE = 201;
private static final Integer BAD_REQUEST_STATUS_CODE = 400; private static final Integer BAD_REQUEST_STATUS_CODE = 400;

View File

@ -27,8 +27,8 @@ import com.iluwatar.serverless.faas.ApiGatewayResponse;
import com.amazonaws.services.lambda.runtime.Context; import com.amazonaws.services.lambda.runtime.Context;
import com.amazonaws.services.lambda.runtime.RequestHandler; import com.amazonaws.services.lambda.runtime.RequestHandler;
import com.iluwatar.serverless.faas.LambdaInfo; import com.iluwatar.serverless.faas.LambdaInfo;
import org.apache.log4j.BasicConfigurator; import org.slf4j.Logger;
import org.apache.log4j.Logger; import org.slf4j.LoggerFactory;
import java.util.HashMap; import java.util.HashMap;
import java.util.Map; import java.util.Map;
@ -39,13 +39,12 @@ import java.util.Map;
*/ */
public class LambdaInfoApiHandler implements RequestHandler<Map<String, Object>, ApiGatewayResponse> { public class LambdaInfoApiHandler implements RequestHandler<Map<String, Object>, ApiGatewayResponse> {
private static final Logger LOG = Logger.getLogger(LambdaInfoApiHandler.class); private static final Logger LOG = LoggerFactory.getLogger(LambdaInfoApiHandler.class);
private static final Integer SUCCESS_STATUS_CODE = 200; private static final Integer SUCCESS_STATUS_CODE = 200;
@Override @Override
public ApiGatewayResponse handleRequest(Map<String, Object> input, Context context) { public ApiGatewayResponse handleRequest(Map<String, Object> input, Context context) {
BasicConfigurator.configure();
LOG.info("received: " + input); LOG.info("received: " + input);
return new ApiGatewayResponse return new ApiGatewayResponse

View File

@ -1,29 +0,0 @@
#
# The MIT License
# Copyright © 2014-2019 Ilkka Seppälä
#
# Permission is hereby granted, free of charge, to any person obtaining a copy
# of this software and associated documentation files (the "Software"), to deal
# in the Software without restriction, including without limitation the rights
# to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
# copies of the Software, and to permit persons to whom the Software is
# furnished to do so, subject to the following conditions:
#
# The above copyright notice and this permission notice shall be included in
# all copies or substantial portions of the Software.
#
# THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
# IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
# FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
# AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
# LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
# OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
# THE SOFTWARE.
#
log = .
log4j.rootLogger = DEBUG, LAMBDA
log4j.appender.LAMBDA=com.amazonaws.services.lambda.runtime.log4j.LambdaAppender
log4j.appender.LAMBDA.layout=org.apache.log4j.PatternLayout
log4j.appender.LAMBDA.layout.conversionPattern=%d{yyyy-MM-dd HH:mm:ss} <%X{AWSRequestId}> %-5p %c:%L - %m%n

View File

@ -22,6 +22,9 @@
*/ */
package com.iluwatar.spatialpartition; package com.iluwatar.spatialpartition;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import java.util.ArrayList; import java.util.ArrayList;
import java.util.Enumeration; import java.util.Enumeration;
import java.util.Hashtable; import java.util.Hashtable;
@ -52,6 +55,7 @@ import java.util.Random;
*/ */
public class App { public class App {
private static final Logger LOGGER = LoggerFactory.getLogger(App.class);
static void noSpatialPartition(int height, int width, static void noSpatialPartition(int height, int width,
int numOfMovements, Hashtable<Integer, Bubble> bubbles) { int numOfMovements, Hashtable<Integer, Bubble> bubbles) {
@ -73,7 +77,7 @@ public class App {
} }
for (Integer key : bubbles.keySet()) { for (Integer key : bubbles.keySet()) {
//bubbles not popped //bubbles not popped
System.out.println("Bubble " + key + " not popped"); LOGGER.info("Bubble " + key + " not popped");
} }
} }
@ -101,7 +105,7 @@ public class App {
} }
for (Integer key : bubbles.keySet()) { for (Integer key : bubbles.keySet()) {
//bubbles not popped //bubbles not popped
System.out.println("Bubble " + key + " not popped"); LOGGER.info("Bubble " + key + " not popped");
} }
} }
@ -119,7 +123,7 @@ public class App {
Bubble b = new Bubble(rand.nextInt(300), rand.nextInt(300), i, rand.nextInt(2) + 1); Bubble b = new Bubble(rand.nextInt(300), rand.nextInt(300), i, rand.nextInt(2) + 1);
bubbles1.put(i, b); bubbles1.put(i, b);
bubbles2.put(i, b); bubbles2.put(i, b);
System.out.println("Bubble " + i + " with radius " + b.radius + " added at (" + b.x + "," + b.y + ")"); LOGGER.info("Bubble " + i + " with radius " + b.radius + " added at (" + b.x + "," + b.y + ")");
} }
long start1 = System.currentTimeMillis(); long start1 = System.currentTimeMillis();
@ -128,8 +132,8 @@ public class App {
long start2 = System.currentTimeMillis(); long start2 = System.currentTimeMillis();
App.withSpatialPartition(300,300,20,bubbles2); App.withSpatialPartition(300,300,20,bubbles2);
long end2 = System.currentTimeMillis(); long end2 = System.currentTimeMillis();
System.out.println("Without spatial partition takes " + (end1 - start1) + "ms"); LOGGER.info("Without spatial partition takes " + (end1 - start1) + "ms");
System.out.println("With spatial partition takes " + (end2 - start2) + "ms"); LOGGER.info("With spatial partition takes " + (end2 - start2) + "ms");
} }
} }

View File

@ -22,6 +22,9 @@
*/ */
package com.iluwatar.spatialpartition; package com.iluwatar.spatialpartition;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import java.util.ArrayList; import java.util.ArrayList;
import java.util.Hashtable; import java.util.Hashtable;
import java.util.Random; import java.util.Random;
@ -32,6 +35,7 @@ import java.util.Random;
*/ */
public class Bubble extends Point<Bubble> { public class Bubble extends Point<Bubble> {
private static final Logger LOGGER = LoggerFactory.getLogger(Bubble.class);
final int radius; final int radius;
@ -54,7 +58,7 @@ public class Bubble extends Point<Bubble> {
} }
void pop(Hashtable<Integer, Bubble> allBubbles) { void pop(Hashtable<Integer, Bubble> allBubbles) {
System.out.println("Bubble " + this.id + " popped at (" + this.x + "," + this.y + ")!"); LOGGER.info("Bubble " + this.id + " popped at (" + this.x + "," + this.y + ")!");
allBubbles.remove(this.id); allBubbles.remove(this.id);
} }

View File

@ -22,6 +22,9 @@
*/ */
package com.iluwatar.tls; package com.iluwatar.tls;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import java.util.Calendar; import java.util.Calendar;
import java.util.Date; import java.util.Date;
import java.util.concurrent.ExecutorService; import java.util.concurrent.ExecutorService;
@ -64,6 +67,8 @@ import java.util.concurrent.Future;
* @author Thomas Bauer, 2017 * @author Thomas Bauer, 2017
*/ */
public class App { public class App {
private static final Logger LOGGER = LoggerFactory.getLogger(App.class);
/** /**
* Program entry point * Program entry point
* *
@ -99,11 +104,11 @@ public class App {
// a correct run should deliver 20 times 15.12.2015 // a correct run should deliver 20 times 15.12.2015
// and a correct run shouldn't deliver any exception // and a correct run shouldn't deliver any exception
System.out.println("The List dateList contains " + counterDateValues + " date values"); LOGGER.info("The List dateList contains " + counterDateValues + " date values");
System.out.println("The List exceptionList contains " + counterExceptions + " exceptions"); LOGGER.info("The List exceptionList contains " + counterExceptions + " exceptions");
} catch (Exception e) { } catch (Exception e) {
System.out.println("Abnormal end of program. Program throws exception: " + e); LOGGER.info("Abnormal end of program. Program throws exception: " + e);
} }
executor.shutdown(); executor.shutdown();
} }
@ -121,7 +126,7 @@ public class App {
Calendar cal = Calendar.getInstance(); Calendar cal = Calendar.getInstance();
cal.setTime(dt); cal.setTime(dt);
// Formatted output of the date value: DD.MM.YYYY // Formatted output of the date value: DD.MM.YYYY
System.out.println( LOGGER.info(
cal.get(Calendar.DAY_OF_MONTH) + "." + cal.get(Calendar.MONTH) + "." + +cal.get(Calendar.YEAR)); cal.get(Calendar.DAY_OF_MONTH) + "." + cal.get(Calendar.MONTH) + "." + +cal.get(Calendar.YEAR));
} }
return counter; return counter;
@ -138,7 +143,7 @@ public class App {
int counter = 0; int counter = 0;
for (String ex : res.getExceptionList()) { for (String ex : res.getExceptionList()) {
counter++; counter++;
System.out.println(ex); LOGGER.info(ex);
} }
return counter; return counter;
} }

View File

@ -22,6 +22,9 @@
*/ */
package com.iluwatar.tls; package com.iluwatar.tls;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import java.text.DateFormat; import java.text.DateFormat;
import java.text.SimpleDateFormat; import java.text.SimpleDateFormat;
import java.util.concurrent.Callable; import java.util.concurrent.Callable;
@ -40,6 +43,8 @@ import java.util.concurrent.Callable;
* @author Thomas Bauer, 2017 * @author Thomas Bauer, 2017
*/ */
public class DateFormatCallable implements Callable<Result> { public class DateFormatCallable implements Callable<Result> {
private static final Logger LOGGER = LoggerFactory.getLogger(DateFormatCallable.class);
// class variables (members) // class variables (members)
private ThreadLocal<DateFormat> df; //TLTL private ThreadLocal<DateFormat> df; //TLTL
// private DateFormat df; //NTLNTL // private DateFormat df; //NTLNTL
@ -72,7 +77,7 @@ public class DateFormatCallable implements Callable<Result> {
*/ */
@Override @Override
public Result call() { public Result call() {
System.out.println(Thread.currentThread() + " started executing..."); LOGGER.info(Thread.currentThread() + " started executing...");
Result result = new Result(); Result result = new Result();
// Convert date value to date 5 times // Convert date value to date 5 times
@ -90,7 +95,7 @@ public class DateFormatCallable implements Callable<Result> {
} }
System.out.println(Thread.currentThread() + " finished processing part of the thread"); LOGGER.info(Thread.currentThread() + " finished processing part of the thread");
return result; return result;
} }

View File

@ -25,6 +25,8 @@ package com.iluwatar.typeobject;
import java.io.FileNotFoundException; import java.io.FileNotFoundException;
import java.io.IOException; import java.io.IOException;
import org.json.simple.parser.ParseException; import org.json.simple.parser.ParseException;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
/**<p>Type object pattern is the pattern we use when the OOP concept of creating a base class and /**<p>Type object pattern is the pattern we use when the OOP concept of creating a base class and
* inheriting from it just doesn't work for the case in hand. This happens when we either don't know * inheriting from it just doesn't work for the case in hand. This happens when we either don't know
@ -45,6 +47,7 @@ import org.json.simple.parser.ParseException;
public class App { public class App {
private static final Logger LOGGER = LoggerFactory.getLogger(App.class);
/** /**
* Program entry point. * Program entry point.
* @param args command line args * @param args command line args
@ -62,9 +65,9 @@ public class App {
CellPool pool = new CellPool(numOfRows * numOfRows + 5); CellPool pool = new CellPool(numOfRows * numOfRows + 5);
CandyGame cg = new CandyGame(numOfRows, pool); CandyGame cg = new CandyGame(numOfRows, pool);
if (round > 1) { if (round > 1) {
System.out.println("Refreshing.."); LOGGER.info("Refreshing..");
} else { } else {
System.out.println("Starting game.."); LOGGER.info("Starting game..");
} }
cg.printGameStatus(); cg.printGameStatus();
end = System.currentTimeMillis(); end = System.currentTimeMillis();
@ -72,13 +75,13 @@ public class App {
pointsWon += cg.totalPoints; pointsWon += cg.totalPoints;
end = System.currentTimeMillis(); end = System.currentTimeMillis();
} }
System.out.println("Game Over"); LOGGER.info("Game Over");
if (pointsWon >= toWin) { if (pointsWon >= toWin) {
System.out.println(pointsWon); LOGGER.info("" + pointsWon);
System.out.println("You win!!"); LOGGER.info("You win!!");
} else { } else {
System.out.println(pointsWon); LOGGER.info("" + pointsWon);
System.out.println("Sorry, you lose!"); LOGGER.info("Sorry, you lose!");
} }
} }
} }

View File

@ -24,6 +24,8 @@ package com.iluwatar.typeobject;
import java.util.ArrayList; import java.util.ArrayList;
import com.iluwatar.typeobject.Candy.Type; import com.iluwatar.typeobject.Candy.Type;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
/** /**
* The CandyGame class contains the rules for the continuation of the game and has * The CandyGame class contains the rules for the continuation of the game and has
@ -31,6 +33,9 @@ import com.iluwatar.typeobject.Candy.Type;
*/ */
public class CandyGame { public class CandyGame {
private static final Logger LOGGER = LoggerFactory.getLogger(CandyGame.class);
Cell[][] cells; Cell[][] cells;
CellPool pool; CellPool pool;
int totalPoints; int totalPoints;
@ -57,21 +62,21 @@ public class CandyGame {
} }
void printGameStatus() { void printGameStatus() {
System.out.println(""); LOGGER.info("");
for (int i = 0; i < cells.length; i++) { for (int i = 0; i < cells.length; i++) {
for (int j = 0; j < cells.length; j++) { for (int j = 0; j < cells.length; j++) {
String candyName = cells[i][j].candy.name; String candyName = cells[i][j].candy.name;
if (candyName.length() < 20) { if (candyName.length() < 20) {
int totalSpaces = 20 - candyName.length(); int totalSpaces = 20 - candyName.length();
System.out.print(numOfSpaces(totalSpaces / 2) + cells[i][j].candy.name LOGGER.info(numOfSpaces(totalSpaces / 2) + cells[i][j].candy.name
+ numOfSpaces(totalSpaces - totalSpaces / 2) + "|"); + numOfSpaces(totalSpaces - totalSpaces / 2) + "|");
} else { } else {
System.out.print(candyName + "|"); LOGGER.info(candyName + "|");
} }
} }
System.out.println(""); LOGGER.info("");
} }
System.out.println(""); LOGGER.info("");
} }
ArrayList<Cell> adjacentCells(int yIndex, int xIndex) { ArrayList<Cell> adjacentCells(int yIndex, int xIndex) {
@ -121,7 +126,7 @@ public class CandyGame {
} }
void handleChange(int points) { void handleChange(int points) {
System.out.println("+" + points + " points!"); LOGGER.info("+" + points + " points!");
this.totalPoints += points; this.totalPoints += points;
printGameStatus(); printGameStatus();
} }