Added ReportLogger

Refactored all System.out and System.err to usage of logger
This commit is contained in:
Daniel Poustka 2021-01-03 14:32:59 +01:00
parent a0eca3740d
commit a6d22fc87b
18 changed files with 127 additions and 24 deletions

View File

@ -8,12 +8,16 @@ import cz.cvut.fel.sit.omo.foodchain.parser.ParserResult;
import cz.cvut.fel.sit.omo.foodchain.parser.ParserResultElement; import cz.cvut.fel.sit.omo.foodchain.parser.ParserResultElement;
import cz.cvut.fel.sit.omo.foodchain.product.Product; import cz.cvut.fel.sit.omo.foodchain.product.Product;
import cz.cvut.fel.sit.omo.foodchain.scenario.Scenario; import cz.cvut.fel.sit.omo.foodchain.scenario.Scenario;
import cz.cvut.fel.sit.omo.foodchain.util.ReportLogger;
import cz.cvut.fel.sit.omo.foodchain.util.Ticker; import cz.cvut.fel.sit.omo.foodchain.util.Ticker;
import org.xml.sax.SAXException; import org.xml.sax.SAXException;
import javax.xml.parsers.ParserConfigurationException; import javax.xml.parsers.ParserConfigurationException;
import java.io.IOException; import java.io.IOException;
import java.util.List; import java.util.List;
import java.util.logging.Level;
import java.util.logging.LogManager;
import java.util.logging.Logger;
public class FoodChain public class FoodChain
{ {
@ -22,12 +26,19 @@ public class FoodChain
public static void main(String[] args) public static void main(String[] args)
{ {
LogManager.getLogManager().reset();
Logger rootLogger = LogManager.getLogManager().getLogger("");
rootLogger.addHandler(new ReportLogger());
if(args.length < 4) if(args.length < 4)
{ {
parseChannels("conf/channels.xml"); parseChannels("conf/channels.xml");
parseNodes("conf/nodes.xml"); parseNodes("conf/nodes.xml");
parseProducts("conf/products.xml"); parseProducts("conf/products.xml");
parseScenarios("conf/scenarios.xml"); parseScenarios("conf/scenarios.xml");
rootLogger.log(Level.CONFIG,"Parsed default scenarios");
} }
else else
{ {
@ -35,6 +46,8 @@ public class FoodChain
parseNodes(args[2]); parseNodes(args[2]);
parseProducts(args[3]); parseProducts(args[3]);
parseScenarios(args[4]); parseScenarios(args[4]);
rootLogger.log(Level.CONFIG,"Parsed non-default scenarios");
} }
// getFactoryManager().getPoolDatabaseInstance().getChannelPoolInstance().findAll().stream().forEach(ch -> System.out.println(ch.getProductType())); // getFactoryManager().getPoolDatabaseInstance().getChannelPoolInstance().findAll().stream().forEach(ch -> System.out.println(ch.getProductType()));
@ -63,6 +76,7 @@ public class FoodChain
catch (ParserConfigurationException | SAXException | IOException e) catch (ParserConfigurationException | SAXException | IOException e)
{ {
System.err.println(e.getMessage()); System.err.println(e.getMessage());
} }
return ConfigurationParser.getElements(rootElementTag); return ConfigurationParser.getElements(rootElementTag);

View File

@ -2,14 +2,19 @@ package cz.cvut.fel.sit.omo.foodchain.factory;
import cz.cvut.fel.sit.omo.foodchain.channel.*; import cz.cvut.fel.sit.omo.foodchain.channel.*;
import cz.cvut.fel.sit.omo.foodchain.node.base.NodeBase;
import cz.cvut.fel.sit.omo.foodchain.parser.ParserResultElement; import cz.cvut.fel.sit.omo.foodchain.parser.ParserResultElement;
import cz.cvut.fel.sit.omo.foodchain.product.ProductType; import cz.cvut.fel.sit.omo.foodchain.product.ProductType;
import java.util.logging.Level;
import java.util.logging.Logger;
/** /**
* Factory for creating channels * Factory for creating channels
*/ */
public class ChannelFactory public class ChannelFactory
{ {
private static final Logger LOGGER = Logger.getLogger(ChannelFactory.class.getName());
/** /**
* Creates channel based on channel type (Fruit, Vegetable, Meat, Other). * Creates channel based on channel type (Fruit, Vegetable, Meat, Other).
* @param input data from channel that is created * @param input data from channel that is created
@ -26,11 +31,11 @@ public class ChannelFactory
} }
catch (IllegalArgumentException e) catch (IllegalArgumentException e)
{ {
System.err.println("! Wrong type of enum in ChannelFactory: " + e); LOGGER.log(Level.SEVERE, "! Wrong type of enum in ChannelFactory: " + e);
} }
catch (Exception e) catch (Exception e)
{ {
System.err.println("! Fatal error in ChannelFactory: " + e); LOGGER.log(Level.SEVERE, "! Fatal error in ChannelFactory: " + e);
} }
return c; return c;
} }

View File

@ -10,13 +10,15 @@ import cz.cvut.fel.sit.omo.foodchain.pool.ChannelPool;
import cz.cvut.fel.sit.omo.foodchain.product.ProductType; import cz.cvut.fel.sit.omo.foodchain.product.ProductType;
import java.util.Objects; import java.util.Objects;
import java.util.logging.Level;
import java.util.logging.Logger;
/** /**
* Factory for creating nodes * Factory for creating nodes
*/ */
public class NodeFactory public class NodeFactory
{ {
private static final Logger LOGGER = Logger.getLogger(NodeFactory.class.getName());
/** /**
* Creates Node based on input ParserResultElement. * Creates Node based on input ParserResultElement.
* @param input data from Node that is created * @param input data from Node that is created
@ -38,11 +40,11 @@ public class NodeFactory
} }
catch (IllegalArgumentException e) catch (IllegalArgumentException e)
{ {
System.err.println("! Wrong type of enum in NodeFactory: " + e.getMessage()); LOGGER.log(Level.SEVERE, "! Wrong type of enum in NodeFactory: " + e.getMessage());
} }
catch (Exception e) catch (Exception e)
{ {
System.err.println("! Fatal error in NodeFactory: " + e.getMessage()); LOGGER.log(Level.SEVERE, "! Fatal error in NodeFactory: " + e.getMessage());
} }
switch (Objects.requireNonNull(nodeType)) switch (Objects.requireNonNull(nodeType))

View File

@ -5,12 +5,17 @@ import cz.cvut.fel.sit.omo.foodchain.product.Product;
import cz.cvut.fel.sit.omo.foodchain.product.ProductState; import cz.cvut.fel.sit.omo.foodchain.product.ProductState;
import cz.cvut.fel.sit.omo.foodchain.product.ProductType; import cz.cvut.fel.sit.omo.foodchain.product.ProductType;
import java.util.logging.Level;
import java.util.logging.Logger;
/** /**
* Factory for creating products * Factory for creating products
*/ */
public class ProductFactory public class ProductFactory
{ {
private static final Logger LOGGER = Logger.getLogger(ProductFactory.class.getName());
/** /**
* Creates Product based on input ParserResultElement. * Creates Product based on input ParserResultElement.
* @param input data from Product that is created * @param input data from Product that is created
@ -31,11 +36,11 @@ public class ProductFactory
} }
catch (IllegalArgumentException e) catch (IllegalArgumentException e)
{ {
System.err.println("! Wrong type of enum in ProductFactory: " + e); LOGGER.log(Level.SEVERE, "! Wrong type of enum in ProductFactory: " + e.getMessage());
} }
catch (Exception e) catch (Exception e)
{ {
System.err.println("! Fatal error in ProductFactory: " + e); LOGGER.log(Level.SEVERE, "! Fatal error in ProductFactory: " + e.getMessage());
} }
return p; return p;
} }

View File

@ -14,13 +14,15 @@ import cz.cvut.fel.sit.omo.foodchain.scenario.*;
import java.util.Arrays; import java.util.Arrays;
import java.util.LinkedList; import java.util.LinkedList;
import java.util.List; import java.util.List;
import java.util.logging.Level;
import java.util.logging.Logger;
/** /**
* Factory for creating scenarios * Factory for creating scenarios
*/ */
public class ScenarioFactory public class ScenarioFactory
{ {
private static final Logger LOGGER = Logger.getLogger(ScenarioFactory.class.getName());
/** /**
* Creates Scenario based on input ParserResultElement. * Creates Scenario based on input ParserResultElement.
* @param input data from Scenario that is created * @param input data from Scenario that is created
@ -79,7 +81,7 @@ public class ScenarioFactory
} }
catch (IllegalArgumentException e) catch (IllegalArgumentException e)
{ {
System.err.println("! Wrong type of enum in ScenarioFactory: " + e); LOGGER.log(Level.SEVERE, "! Wrong type of enum in ScenarioFactory: " + e.getMessage());
} }
return s; return s;

View File

@ -6,6 +6,7 @@ import cz.cvut.fel.sit.omo.foodchain.operation.TransactionType;
import cz.cvut.fel.sit.omo.foodchain.product.Product; import cz.cvut.fel.sit.omo.foodchain.product.Product;
import javax.naming.InsufficientResourcesException; import javax.naming.InsufficientResourcesException;
import java.util.logging.Level;
/** /**
* Farmer node * Farmer node
@ -24,7 +25,7 @@ public class Farmer extends SellerNodeBase {
try { try {
createRequirement(TransactionType.SALE, product.getProductType(), product.getName(), product.getPrice()); createRequirement(TransactionType.SALE, product.getProductType(), product.getName(), product.getPrice());
} catch (InsufficientResourcesException e) { } catch (InsufficientResourcesException e) {
System.err.println(e.getMessage()); LOGGER.log(Level.WARNING, e.getMessage());
} }
} }
} }

View File

@ -16,12 +16,16 @@ import org.javamoney.moneta.Money;
import javax.money.MonetaryAmount; import javax.money.MonetaryAmount;
import javax.naming.InsufficientResourcesException; import javax.naming.InsufficientResourcesException;
import java.util.*; import java.util.*;
import java.util.logging.Level;
import java.util.logging.Logger;
/** /**
* Base class for all nodes * Base class for all nodes
*/ */
public class NodeBase implements ChannelObserver { public class NodeBase implements ChannelObserver {
protected static final Logger LOGGER = Logger.getLogger(NodeBase.class.getName());
private final Map<ChannelBase, ChannelSubscriptionType> subscribedChannels = new HashMap<>(); private final Map<ChannelBase, ChannelSubscriptionType> subscribedChannels = new HashMap<>();
private final List<Transaction> refusedTransactions = new LinkedList<>(); private final List<Transaction> refusedTransactions = new LinkedList<>();
private final List<RefusedRequirement> refusedRequirements = new LinkedList<>(); private final List<RefusedRequirement> refusedRequirements = new LinkedList<>();
@ -58,7 +62,7 @@ public class NodeBase implements ChannelObserver {
.filter(ch -> ch.getProductType().equals(product.getProductType())) .filter(ch -> ch.getProductType().equals(product.getProductType()))
.findAny().ifPresent(channel -> channel.addTransaction(transaction)); .findAny().ifPresent(channel -> channel.addTransaction(transaction));
} catch (InsufficientResourcesException e) { } catch (InsufficientResourcesException e) {
System.err.println(e.getMessage()); LOGGER.log(Level.WARNING, e.getMessage());
} }
} }
@ -76,7 +80,7 @@ public class NodeBase implements ChannelObserver {
.filter(ch -> ch.getProductType().equals(prevTransaction.getProduct().getProductType())) .filter(ch -> ch.getProductType().equals(prevTransaction.getProduct().getProductType()))
.findAny().ifPresent(channel -> channel.addTransaction(transaction)); .findAny().ifPresent(channel -> channel.addTransaction(transaction));
} catch (InsufficientResourcesException e) { } catch (InsufficientResourcesException e) {
System.err.println(e.getMessage()); LOGGER.log(Level.WARNING, e.getMessage());
} }
} }
@ -93,7 +97,7 @@ public class NodeBase implements ChannelObserver {
receiveTransaction((FinancialTransaction) transaction); receiveTransaction((FinancialTransaction) transaction);
} }
catch (Exception ex) { catch (Exception ex) {
System.err.println(ex.getMessage()); LOGGER.log(Level.WARNING, e.getMessage());
} }
} }
} }
@ -177,7 +181,7 @@ public class NodeBase implements ChannelObserver {
* @throws InsufficientResourcesException if product is unavailable * @throws InsufficientResourcesException if product is unavailable
*/ */
public void acceptRequirement(Requirement req) throws InsufficientResourcesException { public void acceptRequirement(Requirement req) throws InsufficientResourcesException {
System.out.println(this.nodeType.toString() + " accepted " + req.toString()); LOGGER.log(Level.INFO, this.nodeType.toString() + " accepted " + req.toString());
if (req.getTransactionType() == TransactionType.SALE) { if (req.getTransactionType() == TransactionType.SALE) {
createRequirement(TransactionType.PURCHASE, req.getProductType(), req.getProductName(), req.getPrice()); createRequirement(TransactionType.PURCHASE, req.getProductType(), req.getProductName(), req.getPrice());
} }
@ -323,7 +327,7 @@ public class NodeBase implements ChannelObserver {
acceptRequirement(requirement); acceptRequirement(requirement);
channel.disposeOf(requirement); channel.disposeOf(requirement);
} catch (InsufficientResourcesException e) { } catch (InsufficientResourcesException e) {
System.err.println(e.getMessage()); LOGGER.log(Level.WARNING, e.getMessage());
} }
} }
} }

View File

@ -3,11 +3,13 @@ package cz.cvut.fel.sit.omo.foodchain.operation;
import cz.cvut.fel.sit.omo.foodchain.node.base.NodeBase; import cz.cvut.fel.sit.omo.foodchain.node.base.NodeBase;
import cz.cvut.fel.sit.omo.foodchain.product.Product; import cz.cvut.fel.sit.omo.foodchain.product.Product;
import java.util.logging.Level;
import java.util.logging.Logger;
/** /**
* Operation for processing products in storage * Operation for processing products in storage
*/ */
public class Action extends OperationBase { public class Action extends OperationBase {
private final OperationBase lastOperation; private final OperationBase lastOperation;
private final Product product; private final Product product;
private final ProductOperationType type; private final ProductOperationType type;
@ -21,7 +23,8 @@ public class Action extends OperationBase {
duration = type.getDuration(); duration = type.getDuration();
product.setCurrentOperation(this); product.setCurrentOperation(this);
product.setStateToInAction(); product.setStateToInAction();
System.out.println(toString());
LOGGER.log(Level.INFO, toString());
} }
/** /**

View File

@ -4,6 +4,7 @@ import cz.cvut.fel.sit.omo.foodchain.node.base.NodeBase;
import javax.money.MonetaryAmount; import javax.money.MonetaryAmount;
import javax.naming.InsufficientResourcesException; import javax.naming.InsufficientResourcesException;
import java.util.logging.Level;
/** /**
* Operation for transporting money * Operation for transporting money
@ -19,7 +20,8 @@ public class FinancialTransaction extends Transaction {
this.transactionPaid = transactionPaid; this.transactionPaid = transactionPaid;
if (creator.getMoney().isLessThan(amount)) throw new InsufficientResourcesException("not enough money"); if (creator.getMoney().isLessThan(amount)) throw new InsufficientResourcesException("not enough money");
creator.subtractMoney(amount); creator.subtractMoney(amount);
System.out.println(toString());
LOGGER.log(Level.INFO, toString());
} }
/** /**

View File

@ -1,14 +1,18 @@
package cz.cvut.fel.sit.omo.foodchain.operation; package cz.cvut.fel.sit.omo.foodchain.operation;
import cz.cvut.fel.sit.omo.foodchain.factory.ScenarioFactory;
import cz.cvut.fel.sit.omo.foodchain.node.base.NodeBase; import cz.cvut.fel.sit.omo.foodchain.node.base.NodeBase;
import java.time.LocalDateTime; import java.time.LocalDateTime;
import java.util.logging.Logger;
/** /**
* Base class for all operations * Base class for all operations
*/ */
public abstract class OperationBase { public abstract class OperationBase {
protected static final Logger LOGGER = Logger.getLogger(OperationBase.class.getName());
private final LocalDateTime timeStart; private final LocalDateTime timeStart;
private LocalDateTime timeEnd; private LocalDateTime timeEnd;

View File

@ -5,6 +5,7 @@ import cz.cvut.fel.sit.omo.foodchain.product.Product;
import cz.cvut.fel.sit.omo.foodchain.product.ProductState; import cz.cvut.fel.sit.omo.foodchain.product.ProductState;
import javax.naming.InsufficientResourcesException; import javax.naming.InsufficientResourcesException;
import java.util.logging.Level;
/** /**
* Operation for transporting products * Operation for transporting products
@ -24,7 +25,8 @@ public class ProductTransaction extends Transaction {
product.setCurrentOperation(this); product.setCurrentOperation(this);
product.setStateToReadyForDispatch(); product.setStateToReadyForDispatch();
creator.getStorage().removeProduct(product); creator.getStorage().removeProduct(product);
System.out.println(toString());
LOGGER.log(Level.INFO, toString());
} }
/** /**

View File

@ -4,15 +4,19 @@ import cz.cvut.fel.sit.omo.foodchain.node.base.NodeBase;
import cz.cvut.fel.sit.omo.foodchain.operation.TransactionType; import cz.cvut.fel.sit.omo.foodchain.operation.TransactionType;
import cz.cvut.fel.sit.omo.foodchain.product.ProductState; import cz.cvut.fel.sit.omo.foodchain.product.ProductState;
import cz.cvut.fel.sit.omo.foodchain.product.ProductType; import cz.cvut.fel.sit.omo.foodchain.product.ProductType;
import cz.cvut.fel.sit.omo.foodchain.util.Ticker;
import org.javamoney.moneta.Money; import org.javamoney.moneta.Money;
import javax.money.MonetaryAmount; import javax.money.MonetaryAmount;
import javax.naming.InsufficientResourcesException; import javax.naming.InsufficientResourcesException;
import java.util.logging.Level;
import java.util.logging.Logger;
/** /**
* Requirement class * Requirement class
*/ */
public class Requirement { public class Requirement {
private static final Logger LOGGER = Logger.getLogger(Ticker.class.getName());
private final NodeBase creator; private final NodeBase creator;
private final TransactionType transactionType; private final TransactionType transactionType;
@ -31,7 +35,9 @@ public class Requirement {
this.price = price; this.price = price;
this.TTL = 3; this.TTL = 3;
this.id = counter++; this.id = counter++;
System.out.println(toString());
LOGGER.log(Level.INFO, toString());
} }
/** /**

View File

@ -4,6 +4,8 @@ import cz.cvut.fel.sit.omo.foodchain.node.base.NodeBase;
import cz.cvut.fel.sit.omo.foodchain.operation.ProductOperationType; import cz.cvut.fel.sit.omo.foodchain.operation.ProductOperationType;
import cz.cvut.fel.sit.omo.foodchain.product.Product; import cz.cvut.fel.sit.omo.foodchain.product.Product;
import java.util.logging.Level;
/** /**
* Step for starting action on product(s) * Step for starting action on product(s)
*/ */
@ -37,7 +39,7 @@ public class DoActionStep extends ScenarioStep {
} }
} }
catch (IllegalCallerException e) { catch (IllegalCallerException e) {
System.err.println(e.getMessage()); LOGGER.log(Level.SEVERE, e.getMessage());
} }
} }
} }

View File

@ -4,6 +4,8 @@ import cz.cvut.fel.sit.omo.foodchain.FoodChain;
import cz.cvut.fel.sit.omo.foodchain.node.Farmer; import cz.cvut.fel.sit.omo.foodchain.node.Farmer;
import cz.cvut.fel.sit.omo.foodchain.product.Product; import cz.cvut.fel.sit.omo.foodchain.product.Product;
import java.util.logging.Level;
/** /**
* Step for generating product from pool * Step for generating product from pool
*/ */
@ -21,7 +23,7 @@ public class GenerateProductStep extends ScenarioStep {
} }
else { else {
product = null; product = null;
System.err.println("Insufficient products in pool"); LOGGER.log(Level.SEVERE, "Insufficient products in pool");
} }
} }

View File

@ -1,8 +1,14 @@
package cz.cvut.fel.sit.omo.foodchain.scenario; package cz.cvut.fel.sit.omo.foodchain.scenario;
import cz.cvut.fel.sit.omo.foodchain.operation.OperationBase;
import java.util.logging.Logger;
/** /**
* Scenario step class * Scenario step class
*/ */
public abstract class ScenarioStep { public abstract class ScenarioStep {
protected static final Logger LOGGER = Logger.getLogger(ScenarioStep.class.getName());
abstract void execute(); abstract void execute();
} }

View File

@ -7,6 +7,7 @@ import org.javamoney.moneta.Money;
import javax.money.MonetaryAmount; import javax.money.MonetaryAmount;
import javax.naming.InsufficientResourcesException; import javax.naming.InsufficientResourcesException;
import java.util.logging.Level;
/** /**
* Step for sending requirements * Step for sending requirements
@ -44,7 +45,7 @@ public class SendRequirementStep extends ScenarioStep {
try { try {
node.createRequirement(tType, pType, pName, pPrice); node.createRequirement(tType, pType, pName, pPrice);
} catch (InsufficientResourcesException e) { } catch (InsufficientResourcesException e) {
System.err.println(e.getMessage()); LOGGER.log(Level.SEVERE, e.getMessage());
} }
} }
} }

View File

@ -0,0 +1,37 @@
package cz.cvut.fel.sit.omo.foodchain.util;
import java.util.logging.Handler;
import java.util.logging.Level;
import java.util.logging.LogRecord;
public class ReportLogger extends Handler
{
@Override
public void publish(LogRecord record) {
StringBuilder sb = new StringBuilder();
sb.append(record.getSourceClassName())
.append("#")
.append(record.getSourceMethodName())
.append(" - ")
.append(record.getMessage());
if(record.getLevel().equals(Level.WARNING) || record.getLevel().equals(Level.SEVERE))
{
System.err.println(sb.toString());
//todo add some outprint to report log
}
else
{
System.out.println(sb.toString());
//todo add some outprint to report log
}
}
@Override
public void flush() {
}
@Override
public void close() throws SecurityException {
}
}

View File

@ -2,16 +2,20 @@ package cz.cvut.fel.sit.omo.foodchain.util;
import cz.cvut.fel.sit.omo.foodchain.FoodChain; import cz.cvut.fel.sit.omo.foodchain.FoodChain;
import cz.cvut.fel.sit.omo.foodchain.channel.ChannelBase; import cz.cvut.fel.sit.omo.foodchain.channel.ChannelBase;
import cz.cvut.fel.sit.omo.foodchain.node.base.NodeBase;
import cz.cvut.fel.sit.omo.foodchain.pool.PoolDatabase; import cz.cvut.fel.sit.omo.foodchain.pool.PoolDatabase;
import cz.cvut.fel.sit.omo.foodchain.product.Product; import cz.cvut.fel.sit.omo.foodchain.product.Product;
import cz.cvut.fel.sit.omo.foodchain.scenario.Scenario; import cz.cvut.fel.sit.omo.foodchain.scenario.Scenario;
import javax.swing.*; import javax.swing.*;
import java.util.logging.Level;
import java.util.logging.Logger;
/** /**
* Creates artificial time for application * Creates artificial time for application
*/ */
public class Ticker { public class Ticker {
protected static final Logger LOGGER = Logger.getLogger(Ticker.class.getName());
private static Timer timer; private static Timer timer;
@ -20,7 +24,8 @@ public class Ticker {
*/ */
public static void start() { public static void start() {
timer = new Timer(1000, actionEvent -> { timer = new Timer(1000, actionEvent -> {
System.out.println("-----tick-----"); LOGGER.log(Level.INFO, "-----tick-----");
PoolDatabase db = FoodChain.getFactoryManager().getPoolDatabaseInstance(); PoolDatabase db = FoodChain.getFactoryManager().getPoolDatabaseInstance();
boolean productBool = db.getProductPoolInstance().findAll().stream().filter(Product::tick).count() == 0; // change duration of action boolean productBool = db.getProductPoolInstance().findAll().stream().filter(Product::tick).count() == 0; // change duration of action
boolean channelBool = db.getChannelPoolInstance().findAll().stream().filter(ChannelBase::tick).count() == 0; // change TTL of requirements boolean channelBool = db.getChannelPoolInstance().findAll().stream().filter(ChannelBase::tick).count() == 0; // change TTL of requirements