Compare commits

...

69 Commits

Author SHA1 Message Date
Daniel Poustka
faffec4f1c Fixed NodeFactory enum check 2020-12-26 15:46:57 +01:00
Nikita Iryupin
853bf05ee5 Moving nodes classes to directories, create new enum, limit sellers and purchasers 2020-12-26 15:43:33 +01:00
Nikita Iryupin
3aaa5c72e6 Merge branch 'feature/factory_impl' into develop 2020-12-26 15:08:36 +01:00
Daniel Poustka
6acad973fd Added small fixes in ScenarioFactory 2020-12-26 14:39:14 +01:00
Daniel Poustka
cbfe3617f2 Merge remote-tracking branch 'origin/feature/factory_impl' into feature/factory_impl 2020-12-26 14:34:58 +01:00
Tomáš Musil
0fbe472261 Implemeneted tick (basic) 2020-12-26 14:23:14 +01:00
Nikita Iryupin
624b18bd79 Merge branch 'feature/factory_impl' into develop
# Conflicts:
#	src/main/java/cz/cvut/fel/sit/omo/foodchain/product/Product.java
2020-12-26 12:43:37 +01:00
Tomáš Musil
21f5d14406 Implemented ScenarioFactory 2020-12-26 12:40:31 +01:00
Daniel Poustka
a459317c69 Merge remote-tracking branch 'origin/feature/factory_impl' into feature/factory_impl 2020-12-26 11:39:00 +01:00
Tomáš Musil
e58392f5be Improved object generation 2020-12-26 11:36:06 +01:00
Tomáš Musil
0ba95a1728 Improved object generation 2020-12-26 11:31:57 +01:00
Nikita Iryupin
d6eb56a3ad Replace bulder of Money to Money.of 2020-12-26 11:28:04 +01:00
Daniel Poustka
3fd3e36c76 Merge branch 'develop' into feature/factory_impl 2020-12-26 11:17:56 +01:00
Nikita Iryupin
e31a80ec69 Fix Money dependency in pom 2020-12-26 11:17:32 +01:00
Daniel Poustka
cfbe22d6c1 Fixed config path 2020-12-26 11:09:59 +01:00
Daniel Poustka
01e43e20a7 Fixed path to config 2020-12-26 10:35:53 +01:00
Daniel Poustka
b77e9a690a Fixed startMoney for Nodes and Product 2020-12-26 10:30:22 +01:00
Daniel Poustka
015d558afe Merge branch 'develop' into feature/factory_impl
# Conflicts:
#	src/main/java/cz/cvut/fel/sit/omo/foodchain/factory/NodeFactory.java
#	src/main/java/cz/cvut/fel/sit/omo/foodchain/product/Product.java
2020-12-26 10:26:27 +01:00
Daniel Poustka
bd5c5f1a98 Fixed Node subscription 2020-12-26 10:22:36 +01:00
Tomáš Musil
0bb5af4968 Changed constructors 2020-12-26 10:19:30 +01:00
Daniel Poustka
22369d7b70 Fixed some stuff 2020-12-26 10:16:42 +01:00
Daniel Poustka
643bf23c0b Added channel and nodes parsing into main
Small refactoring
2020-12-25 20:47:39 +01:00
Nikita Iryupin
88543d0c68 Adding TODO and fixing after-merging code 2020-12-25 19:03:26 +01:00
Nikita Iryupin
270654e5ea Merge branch 'feature/channel_impl' into develop
# Conflicts:
#	src/main/java/cz/cvut/fel/sit/omo/foodchain/FoodChain.java
#	src/main/java/cz/cvut/fel/sit/omo/foodchain/node/NodeBase.java
2020-12-25 18:56:21 +01:00
Nikita Iryupin
9d4bb41b54 Merge branch 'feature/factory_impl' into develop 2020-12-25 18:51:34 +01:00
Nikita Iryupin
43dd1adb91 Merge branch 'feature/scenario_impl' into develop 2020-12-25 18:50:31 +01:00
Tomáš Musil
9e8627cb86 Added money to Product 2020-12-25 18:46:06 +01:00
Daniel Poustka
8aa2c490c1 Fixed Product constructor usage 2020-12-25 18:45:57 +01:00
Tomáš Musil
ba84dfefe4 Added configuration and ChannelSubstcriptionType 2020-12-25 18:39:29 +01:00
Daniel Poustka
76ca92e676 Removed stuff 2020-12-25 17:48:46 +01:00
Daniel Poustka
7a92d623ac Added config parse of channels to the FoodChain
Fixed stuff in factories
2020-12-25 17:46:55 +01:00
Daniel Poustka
71ef11f7e2 Added NodeFactory 2020-12-25 17:21:42 +01:00
Tomáš Musil
e3e289b9fd Implemented more Steps, fixed some bugs, added helper methods 2020-12-25 17:17:49 +01:00
Nikita Iryupin
5e96891696 Start working on scenario, steps, iterator 2020-12-25 16:44:15 +01:00
Daniel Poustka
bce2b74ef2 Added ChannelFactory and ProductFactory make methods 2020-12-25 16:33:25 +01:00
Daniel Poustka
a6d4a423e0 Merge branch 'develop' into feature/factory_impl 2020-12-25 15:55:31 +01:00
Daniel Poustka
43eb9a2464 Added nothing in fact... 2020-12-25 15:53:17 +01:00
Nikita Iryupin
d9d15d2428 Merge branch 'feature/pool_parser_impl' into develop 2020-12-25 15:39:05 +01:00
Nikita Iryupin
2013cad84a Merge branch 'feature/operation_impl' into develop 2020-12-25 15:38:41 +01:00
Nikita Iryupin
f1cad5d636 Merge branch 'feature/node_impl' into develop 2020-12-25 15:38:24 +01:00
Nikita Iryupin
e73762eec4 Some more fixes of NodeBase 2020-12-25 12:30:21 +01:00
Nikita Iryupin
6a7fc972fd Added functions (need consultation) 2020-12-23 16:46:08 +01:00
Tomáš Musil
42cc9d6ebb Implemented Requirement, added Ticker 2020-12-23 13:18:13 +01:00
Tomáš Musil
666abbe2e1 Implemented ConfigurationParser + result, removed IPool 2020-12-23 12:34:44 +01:00
Nikita Iryupin
4193fdade4 Initialize branch 2020-12-22 19:57:22 +01:00
Nikita Iryupin
de87d1780d Initialize branch 2020-12-22 17:05:07 +01:00
Nikita Iryupin
6f7c11a878 After-merge repair, delete all unnecessary interfaces 2020-12-22 16:54:31 +01:00
Nikita Iryupin
e0b53db736 Merge branch 'feature/operation_impl' into develop 2020-12-22 16:37:51 +01:00
Nikita Iryupin
371b47ac31 Merge branch 'feature/node_impl' into develop 2020-12-22 16:37:15 +01:00
Tomáš Musil
127bdd1270 Added end to Transaction and Action, improved Signature 2020-12-22 16:33:40 +01:00
Daniel Poustka
8b47edd07b Merge remote-tracking branch 'origin/feature/channel_impl' into feature/channel_impl 2020-11-30 16:11:43 +01:00
Nikita Iryupin
90ff7af47e Added observer and observable interface, implemented observable on ChannelBase 2020-11-30 16:10:49 +01:00
Nikita Iryupin
d3378d37d4 Fixed intterface and abstract class after consultansion 2020-11-30 15:39:49 +01:00
Daniel Poustka
32468b44f0 Changed current operation from IOperation to OperationBase 2020-11-30 15:23:07 +01:00
Daniel Poustka
2b57aa8dfe Added current operation to the Product 2020-11-30 15:20:36 +01:00
Nikita Iryupin
bd653482e5 Fixing initialization 2020-11-30 15:04:00 +01:00
Nikita Iryupin
5f481a6e48 Added some methods 2020-11-30 09:04:33 +01:00
Nikita Iryupin
62fa46e6c2 Fixed interface and added some methods 2020-11-29 18:03:30 +01:00
Tomáš Musil
9119ebb8ce Implemented Operation and Signature packages (basic) 2020-11-28 13:09:35 +01:00
Daniel Poustka
5a6fc28b76 Implemented channel and product basic stuff. 2020-11-23 16:39:48 +01:00
Nikita Iryupin
7815e0df70 Adds TODO 2020-11-23 15:51:15 +01:00
Nikita Iryupin
c9c34d4f46 Adds TODO 2020-11-23 15:50:38 +01:00
Nikita Iryupin
8a90a07ef7 Adds TODO 2020-11-23 15:50:08 +01:00
Nikita Iryupin
5e4ea372d0 Renamed classes, added more interface methods 2020-11-23 15:35:45 +01:00
Tomáš Musil
021c194839 Added more classes and interfaces 2020-11-21 12:57:55 +01:00
Nikita Iryupin
1d04bb6dc7 Added project, added some classes and interfaces 2020-11-21 11:59:32 +01:00
Daniel Poustka
2924024ae4 Modified Class diagram 2020-11-21 10:30:30 +01:00
Daniel Poustka
cdce93bce3 added Class diagram 2020-11-13 19:02:04 +01:00
Nikita Iryupin
8f3848e895 Ear diagram 2020-11-10 14:58:25 +01:00
68 changed files with 2071 additions and 0 deletions

4
.gitignore vendored
View File

@ -0,0 +1,4 @@
.idea
target
*.idb

BIN
EAR diagrams/FoodChain.eap Normal file

Binary file not shown.

2
FoodChain.iml Normal file
View File

@ -0,0 +1,2 @@
<?xml version="1.0" encoding="UTF-8"?>
<module type="JAVA_MODULE" version="4" />

12
conf/channels.xml Normal file
View File

@ -0,0 +1,12 @@
<?xml version="1.0" encoding="UTF-8" ?>
<!DOCTYPE channels [
<!ELEMENT channels (channel)*>
<!ELEMENT channel (#PCDATA)>
<!ATTLIST channel
type CDATA #REQUIRED>
]>
<channels>
<channel type="MEAT"></channel>
<channel type="VEGETABLE"></channel>
<channel type="FRUIT"></channel>
</channels>

27
conf/nodes.xml Normal file
View File

@ -0,0 +1,27 @@
<?xml version="1.0" encoding="UTF-8" ?>
<!DOCTYPE nodes [
<!ELEMENT nodes (node)*>
<!ELEMENT node (money|channels)*>
<!ATTLIST node
type CDATA #REQUIRED>
<!ELEMENT money (#PCDATA)>
<!ELEMENT channels (#PCDATA)>
]>
<nodes>
<node type = "Farmer">
<money>100</money>
<channels>MEAT PURCHASE;VEGETABLE PURCHASE;FRUIT PURCHASE</channels>
</node>
<node type = "Processor">
<money>0</money>
<channels>MEAT SALE_AND_PURCHASE;VEGETABLE SALE_AND_PURCHASE;FRUIT SALE_AND_PURCHASE</channels>
</node>
<node type = "Distributor">
<money>1500</money>
<channels>MEAT SALE_AND_PURCHASE;VEGETABLE SALE_AND_PURCHASE;FRUIT SALE_AND_PURCHASE</channels>
</node>
<node type = "Customer">
<money>250</money>
<channels>MEAT SALE;VEGETABLE SALE;FRUIT SALE</channels>
</node>
</nodes>

55
conf/products.xml Normal file
View File

@ -0,0 +1,55 @@
<?xml version="1.0" encoding="UTF-8" ?>
<!DOCTYPE products [
<!ELEMENT products (product)*>
<!ELEMENT product (name|type|price)*>
<!ELEMENT name (#PCDATA)>
<!ELEMENT type (#PCDATA)>
<!ELEMENT price (#PCDATA)>
]>
<products>
<product>
<name>jablko</name>
<type>FRUIT</type>
<price>5</price>
</product>
<product>
<name>hruška</name>
<type>FRUIT</type>
<price>7</price>
</product>
<product>
<name>banán</name>
<type>FRUIT</type>
<price>10</price>
</product>
<product>
<name>okurka</name>
<type>VEGETABLE</type>
<price>3</price>
</product>
<product>
<name>paprika</name>
<type>VEGETABLE</type>
<price>5</price>
</product>
<product>
<name>rajče</name>
<type>VEGETABLE</type>
<price>3</price>
</product>
<product>
<name>vepřové</name>
<type>MEAT</type>
<price>20</price>
</product>
<product>
<name>hovězí</name>
<type>MEAT</type>
<price>50</price>
</product>
<product>
<name>kuřecí</name>
<type>MEAT</type>
<price>30</price>
</product>
</products>

29
conf/scenarios.xml Normal file
View File

@ -0,0 +1,29 @@
<?xml version="1.0" encoding="UTF-8" ?>
<!DOCTYPE scenarios [
<!ELEMENT scenarios (scenario)*>
<!ELEMENT scenario (steps)*>
<!ATTLIST scenario
type CDATA #REQUIRED>
<!ELEMENT steps (#PCDATA)>
]>
<scenarios>
<scenario type="Farmer">
<steps>
generate
generate
generate
generate
generate
generate
generate
generate
generate
</steps>
</scenario>
<scenario type="Customer">
<steps>
pass
sendreq PURCHASE FRUIT jablko
</steps>
</scenario>
</scenarios>

24
pom.xml Normal file
View File

@ -0,0 +1,24 @@
<?xml version="1.0" encoding="UTF-8"?>
<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>cz.cvut.fel.sit.omo.foodchain</groupId>
<artifactId>FoodChain</artifactId>
<version>1.0-SNAPSHOT</version>
<dependencies>
<dependency>
<groupId>org.javamoney</groupId>
<artifactId>moneta</artifactId>
<version>1.4.2</version>
<type>pom</type>
</dependency>
</dependencies>
<properties>
<maven.compiler.target>14</maven.compiler.target>
<maven.compiler.source>14</maven.compiler.source>
</properties>
</project>

View File

@ -0,0 +1,129 @@
package cz.cvut.fel.sit.omo.foodchain;
import cz.cvut.fel.sit.omo.foodchain.channel.ChannelBase;
import cz.cvut.fel.sit.omo.foodchain.factory.FactoryManager;
import cz.cvut.fel.sit.omo.foodchain.node.base.NodeBase;
import cz.cvut.fel.sit.omo.foodchain.parser.ConfigurationParser;
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.product.Product;
import cz.cvut.fel.sit.omo.foodchain.scenario.Scenario;
import cz.cvut.fel.sit.omo.foodchain.util.Ticker;
import org.xml.sax.SAXException;
import javax.xml.parsers.ParserConfigurationException;
import java.io.IOException;
import java.util.List;
public class FoodChain
{
private static FactoryManager factoryManager = new FactoryManager();
public static void main(String[] args)
{
parseChannels();
parseNodes();
parseProducts();
parseScenarios();
// getFactoryManager().getPoolDatabaseInstance().getChannelPoolInstance().findAll().stream().forEach(ch -> System.out.println(ch.getProductType()));
// getFactoryManager().getPoolDatabaseInstance().getNodePoolInstance().findAll().stream().forEach(ch -> System.out.println(ch));
// getFactoryManager().getPoolDatabaseInstance().getProductPoolInstance().findAll().stream().forEach(ch -> System.out.println(ch.getProductType() + " " + ch.getName()));
// getFactoryManager().getPoolDatabaseInstance().getScenarioPoolInstance().findAll().stream().forEach(ch -> ch.getSteps().stream().forEach(s -> System.out.println(s)));
Ticker.start();
while (Ticker.getTimer().isRunning());
}
public static FactoryManager getFactoryManager()
{
return factoryManager;
}
// todo maybe some refactoring needed?
// add other entities
public static void parseChannels()
{
try
{
// parse channel configuration
ConfigurationParser.parseDocument("conf/channels.xml");
ParserResult parserResult = ConfigurationParser.getElements("channel");
List<ParserResultElement> elements = parserResult.getElements();
for (ParserResultElement el : elements)
{
ChannelBase res = getFactoryManager().getChannelFactoryInstance().makeChannel(el);
getFactoryManager().getPoolDatabaseInstance().getChannelPoolInstance().add(res);
}
}
catch (ParserConfigurationException | SAXException | IOException e)
{
System.err.println(e.getMessage());
}
}
public static void parseNodes()
{
try
{
// parse channel configuration
ConfigurationParser.parseDocument("conf/nodes.xml");
ParserResult parserResult = ConfigurationParser.getElements("node");
List<ParserResultElement> elements = parserResult.getElements();
for (ParserResultElement el : elements)
{
NodeBase res = getFactoryManager().getNodeFactoryInstance().makeNode(el);
getFactoryManager().getPoolDatabaseInstance().getNodePoolInstance().add(res);
}
}
catch (ParserConfigurationException | SAXException | IOException e)
{
System.err.println(e.getMessage());
}
}
public static void parseProducts()
{
try
{
// parse channel configuration
ConfigurationParser.parseDocument("conf/products.xml");
ParserResult parserResult = ConfigurationParser.getElements("product");
List<ParserResultElement> elements = parserResult.getElements();
for (ParserResultElement el : elements)
{
Product res = getFactoryManager().getProductFactoryInstance().makeProduct(el);
getFactoryManager().getPoolDatabaseInstance().getProductPoolInstance().add(res);
}
}
catch (ParserConfigurationException | SAXException | IOException e)
{
System.err.println(e.getMessage());
}
}
public static void parseScenarios()
{
try
{
// parse channel configuration
ConfigurationParser.parseDocument("conf/scenarios.xml");
ParserResult parserResult = ConfigurationParser.getElements("scenario");
List<ParserResultElement> elements = parserResult.getElements();
for (ParserResultElement el : elements)
{
Scenario res = getFactoryManager().getScenarioFactoryInstance().makeScenario(el);
getFactoryManager().getPoolDatabaseInstance().getScenarioPoolInstance().add(res);
}
}
catch (ParserConfigurationException | SAXException | IOException e)
{
System.err.println(e.getMessage());
}
}
}

View File

@ -0,0 +1,96 @@
package cz.cvut.fel.sit.omo.foodchain.channel;
import cz.cvut.fel.sit.omo.foodchain.operation.Transaction;
import cz.cvut.fel.sit.omo.foodchain.product.ProductType;
import cz.cvut.fel.sit.omo.foodchain.requirement.Requirement;
import cz.cvut.fel.sit.omo.foodchain.util.ChannelObserver;
import cz.cvut.fel.sit.omo.foodchain.util.Observable;
import java.util.*;
import java.util.stream.Collectors;
public abstract class ChannelBase implements Observable {
protected ProductType productType;
protected Queue<Requirement> requirements;
protected Queue<Transaction> transactions;
private Set<ChannelObserver> subscribers;
public ChannelBase(ProductType type)
{
this.requirements = new LinkedList<>();
this.transactions = new LinkedList<>();
this.subscribers = new HashSet<>();
this.productType = type;
}
public ChannelBase()
{
this.requirements = new LinkedList<>();
this.transactions = new LinkedList<>();
this.subscribers = new HashSet<>();
this.productType = ProductType.OTHER;
}
public Queue<Transaction> getTransactions()
{
return this.transactions;
}
public Queue<Requirement> getCurrentRequirements()
{
return this.requirements;
}
/**
* Adds new requirement to the requirement Queue
* @param requirement requirement
*/
public void addRequirement(Requirement requirement)
{
this.requirements.add(requirement);
}
public boolean tick() {
requirements.forEach(Requirement::tick);
requirements = requirements.stream().filter(r -> r.getTTL() > 0).collect(Collectors.toCollection(LinkedList::new));
notifyAllObservers();
return requirements.size() != 0;
}
@Override
public void notifyAllObservers(){
subscribers.forEach(subscriber -> requirements.forEach(subscriber::update));
}
@Override
public void attach(ChannelObserver observer){
subscribers.add(observer);
}
@Override
public void detach(ChannelObserver observer){
subscribers.remove(observer);
}
/**
* Adds new transaction to the transaction Queue
* @param transaction transaction
*/
public void addTransaction(Transaction transaction)
{
this.transactions.add(transaction);
}
/**
* Clears all requirements from this channel
*/
public void clearRequirements()
{
this.requirements.clear();
}
public ProductType getProductType() {
return productType;
}
}

View File

@ -0,0 +1,6 @@
package cz.cvut.fel.sit.omo.foodchain.channel;
public enum ChannelSubscriptionType {
SALE, PURCHASE, SALE_AND_PURCHASE
}

View File

@ -0,0 +1,11 @@
package cz.cvut.fel.sit.omo.foodchain.channel;
import cz.cvut.fel.sit.omo.foodchain.product.ProductType;
public class FruitChannel extends ChannelBase
{
public FruitChannel()
{
super(ProductType.FRUIT);
}
}

View File

@ -0,0 +1,11 @@
package cz.cvut.fel.sit.omo.foodchain.channel;
import cz.cvut.fel.sit.omo.foodchain.product.ProductType;
public class MeatChannel extends ChannelBase
{
public MeatChannel()
{
super(ProductType.MEAT);
}
}

View File

@ -0,0 +1,11 @@
package cz.cvut.fel.sit.omo.foodchain.channel;
import cz.cvut.fel.sit.omo.foodchain.product.ProductType;
public class OtherChannel extends ChannelBase
{
public OtherChannel()
{
super();
}
}

View File

@ -0,0 +1,11 @@
package cz.cvut.fel.sit.omo.foodchain.channel;
import cz.cvut.fel.sit.omo.foodchain.product.ProductType;
public class VegetableChannel extends ChannelBase
{
public VegetableChannel()
{
super(ProductType.VEGETABLE);
}
}

View File

@ -0,0 +1,50 @@
package cz.cvut.fel.sit.omo.foodchain.factory;
import cz.cvut.fel.sit.omo.foodchain.channel.*;
import cz.cvut.fel.sit.omo.foodchain.parser.ParserResultElement;
import cz.cvut.fel.sit.omo.foodchain.product.ProductType;
public class ChannelFactory
{
/**
* Creates channel based on channel type (Fruit, Vegetable, Meat, Other)
* @param input data from channel is created
* @return created Channel (FruitChannel, VegetableChannel, MeatChannel, OtherChannel)
*/
public ChannelBase makeChannel(ParserResultElement input)
{
ChannelBase c = null;
try
{
ProductType channelType = ProductType.valueOf(input.getAttribute("type"));
c = makeChannelFromChannelType(channelType);
}
catch (IllegalArgumentException e)
{
System.err.println("! Wrong type of enum in ChannelFactory: " + e);
}
catch (Exception e)
{
System.err.println("! Fatal error in ChannelFactory: " + e);
}
return c;
}
private ChannelBase makeChannelFromChannelType(ProductType typeOfChannel)
{
switch (typeOfChannel)
{
case FRUIT:
return new FruitChannel();
case VEGETABLE:
return new VegetableChannel();
case MEAT:
return new MeatChannel();
case OTHER:
return new OtherChannel();
}
return null;
}
}

View File

@ -0,0 +1,75 @@
package cz.cvut.fel.sit.omo.foodchain.factory;
import cz.cvut.fel.sit.omo.foodchain.pool.PoolDatabase;
import cz.cvut.fel.sit.omo.foodchain.util.Singleton;
import java.lang.reflect.InvocationTargetException;
public class FactoryManager
{
public NodeFactory getNodeFactoryInstance()
{
try
{
return Singleton.getInstance(NodeFactory.class);
}
catch (IllegalAccessException | InstantiationException | NoSuchMethodException | InvocationTargetException e)
{
e.printStackTrace();
}
return null;
}
public ChannelFactory getChannelFactoryInstance()
{
try
{
return Singleton.getInstance(ChannelFactory.class);
}
catch (IllegalAccessException | InstantiationException | NoSuchMethodException | InvocationTargetException e)
{
e.printStackTrace();
}
return null;
}
public ScenarioFactory getScenarioFactoryInstance()
{
try
{
return Singleton.getInstance(ScenarioFactory.class);
}
catch (IllegalAccessException | InstantiationException | NoSuchMethodException | InvocationTargetException e)
{
e.printStackTrace();
}
return null;
}
public ProductFactory getProductFactoryInstance()
{
try
{
return Singleton.getInstance(ProductFactory.class);
}
catch (IllegalAccessException | InstantiationException | NoSuchMethodException | InvocationTargetException e)
{
e.printStackTrace();
}
return null;
}
public PoolDatabase getPoolDatabaseInstance()
{
try
{
return Singleton.getInstance(PoolDatabase.class);
}
catch (IllegalAccessException | InstantiationException | NoSuchMethodException | InvocationTargetException e)
{
e.printStackTrace();
}
return null;
}
}

View File

@ -0,0 +1,78 @@
package cz.cvut.fel.sit.omo.foodchain.factory;
import cz.cvut.fel.sit.omo.foodchain.FoodChain;
import cz.cvut.fel.sit.omo.foodchain.channel.ChannelSubscriptionType;
import cz.cvut.fel.sit.omo.foodchain.node.*;
import cz.cvut.fel.sit.omo.foodchain.node.base.NodeBase;
import cz.cvut.fel.sit.omo.foodchain.node.enums.NodeType;
import cz.cvut.fel.sit.omo.foodchain.parser.ParserResultElement;
import cz.cvut.fel.sit.omo.foodchain.pool.ChannelPool;
import cz.cvut.fel.sit.omo.foodchain.product.ProductType;
import java.util.Objects;
public class NodeFactory
{
/**
* Creates Node based on input ParserResultElement
* @param input data from Node is created
* @return created Node
*/
public NodeBase makeNode(ParserResultElement input)
{
NodeBase n = null;
NodeType nodeType = null;
String subsChannels = "";
double startMoney = 0;
try
{
nodeType = NodeType.valueOf(input.getAttribute("type"));
subsChannels = input.getChild("channels");
startMoney = Double.parseDouble(input.getChild("money"));
}
catch (IllegalArgumentException e)
{
System.err.println("! Wrong type of enum in NodeFactory: " + e.getMessage());
}
catch (Exception e)
{
System.err.println("! Fatal error in NodeFactory: " + e.getMessage());
}
switch (Objects.requireNonNull(nodeType))
{
case Farmer:
n = new Farmer(startMoney);
break;
case Processor:
n = new Processor(startMoney);
break;
case Distributor:
n = new Distributor(startMoney);
break;
case Seller:
n = new Seller(startMoney);
break;
case Customer:
n = new Customer(startMoney);
break;
default:
}
if (n != null)
{
String[] subs = subsChannels.split(";");
for (String s : subs)
{
String[] el = s.split(" ");
ChannelPool temp = FoodChain.getFactoryManager().getPoolDatabaseInstance().getChannelPoolInstance();
n.subscribeToChannel(temp.findByType(ProductType.valueOf(el[0])), ChannelSubscriptionType.valueOf(el[1]));
}
}
return n;
}
}

View File

@ -0,0 +1,39 @@
package cz.cvut.fel.sit.omo.foodchain.factory;
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.ProductState;
import cz.cvut.fel.sit.omo.foodchain.product.ProductType;
public class ProductFactory
{
/**
* Creates Product based on input ParserResultElement
* @param input data from Product is created
* @return created Product
*/
public Product makeProduct(ParserResultElement input)
{
Product p = null;
try
{
String name = input.getChild("name");
ProductType productType = ProductType.valueOf(input.getChild("type"));
//ProductState productState = ProductState.valueOf(input.getChild("state"));
double price = Double.parseDouble(input.getChild("price"));
//p = new Product(name, price, productType, productState);
p = new Product(name, productType, price);
}
catch (IllegalArgumentException e)
{
System.err.println("! Wrong type of enum in ProductFactory: " + e);
}
catch (Exception e)
{
System.err.println("! Fatal error in ProductFactory: " + e);
}
return p;
}
}

View File

@ -0,0 +1,85 @@
package cz.cvut.fel.sit.omo.foodchain.factory;
import cz.cvut.fel.sit.omo.foodchain.FoodChain;
import cz.cvut.fel.sit.omo.foodchain.node.Customer;
import cz.cvut.fel.sit.omo.foodchain.node.Farmer;
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.TransactionType;
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.ProductType;
import cz.cvut.fel.sit.omo.foodchain.scenario.*;
import java.util.Arrays;
import java.util.LinkedList;
import java.util.List;
public class ScenarioFactory
{
/**
* Creates Scenario based on input ParserResultElement
* @param input data from Scenario is created
* @return created Scenario
*/
public Scenario makeScenario(ParserResultElement input)
{
Scenario s = null;
NodeBase node = null;
try
{
String nodeType = input.getAttribute("type");
node = FoodChain.getFactoryManager().getPoolDatabaseInstance().getNodePoolInstance().findAll().stream()
.filter(ch -> ch.getClass().getSimpleName().equals(nodeType)).findFirst().orElse(null);
String[] steps = Arrays.stream(input.getChild("steps").split("\n")).filter(st -> !st.strip().equals("")).toArray(String[]::new);
List<ScenarioStep> scenarioSteps = new LinkedList<>();
ScenarioStep scenarioStep = null;
for (String step : steps)
{
String[] parts = step.strip().split(" ");
switch (parts[0])
{
case "generate":
scenarioStep = new GenerateProductStep((Farmer) node);
break;
case "consume":
scenarioStep = new ConsumeProductStep((Customer) node);
break;
case "doaction":
if (parts.length == 2)
{
scenarioStep = new DoActionStep(node, ProductOperationType.valueOf(parts[1]));
}
else
{
Product p = FoodChain.getFactoryManager().getPoolDatabaseInstance().getProductPoolInstance().findAll().stream()
.filter(pr -> pr.getName().equals(parts[2])).findFirst().orElse(null);
scenarioStep = new DoActionStep(node, ProductOperationType.valueOf(parts[1]), p);
}
break;
case "sendreq":
scenarioStep = new SendRequirementStep(node, TransactionType.valueOf(parts[1]), ProductType.valueOf(parts[2]), parts[3]);
break;
case "pass":
scenarioStep = new PassStep();
break;
}
scenarioSteps.add(scenarioStep);
}
s = new Scenario(scenarioSteps);
}
catch (IllegalArgumentException e)
{
System.err.println("! Wrong type of enum in ScenarioFactory: " + e);
}
catch (Exception e)
{
System.err.println("! Fatal error in ScenarioFactory: " + e);
}
return s;
}
}

View File

@ -0,0 +1,20 @@
package cz.cvut.fel.sit.omo.foodchain.node;
import cz.cvut.fel.sit.omo.foodchain.node.base.BuyerNodeBase;
import cz.cvut.fel.sit.omo.foodchain.node.enums.NodeType;
import java.util.Random;
public class Customer extends BuyerNodeBase {
public Customer(double startMoney) {
super(startMoney);
allowedSeller = NodeType.Distributor;
allowedPurchaser = NodeType.None;
}
public void consumeProduct() {
int i = new Random().nextInt(getStorage().size());
getStorage().remove(i);
}
}

View File

@ -0,0 +1,13 @@
package cz.cvut.fel.sit.omo.foodchain.node;
import cz.cvut.fel.sit.omo.foodchain.node.base.RetailerNodeBase;
import cz.cvut.fel.sit.omo.foodchain.node.enums.NodeType;
public class Distributor extends RetailerNodeBase {
public Distributor(double startMoney) {
super(startMoney);
allowedSeller = NodeType.Seller;
allowedPurchaser = NodeType.Customer;
}
}

View File

@ -0,0 +1,20 @@
package cz.cvut.fel.sit.omo.foodchain.node;
import cz.cvut.fel.sit.omo.foodchain.node.base.SellerNodeBase;
import cz.cvut.fel.sit.omo.foodchain.node.enums.NodeType;
import cz.cvut.fel.sit.omo.foodchain.operation.TransactionType;
import cz.cvut.fel.sit.omo.foodchain.product.Product;
public class Farmer extends SellerNodeBase {
public Farmer(double startMoney) {
super(startMoney);
allowedSeller = NodeType.None;
allowedPurchaser = NodeType.Processor;
}
public void generateProduct(Product product) {
storeProduct(product);
createRequirement(TransactionType.SALE, product.getProductType(), product.getName());
}
}

View File

@ -0,0 +1,13 @@
package cz.cvut.fel.sit.omo.foodchain.node;
import cz.cvut.fel.sit.omo.foodchain.node.base.RetailerNodeBase;
import cz.cvut.fel.sit.omo.foodchain.node.enums.NodeType;
public class Processor extends RetailerNodeBase {
public Processor(double startMoney) {
super(startMoney);
allowedSeller = NodeType.Farmer;
allowedPurchaser = NodeType.Seller;
}
}

View File

@ -0,0 +1,13 @@
package cz.cvut.fel.sit.omo.foodchain.node;
import cz.cvut.fel.sit.omo.foodchain.node.base.RetailerNodeBase;
import cz.cvut.fel.sit.omo.foodchain.node.enums.NodeType;
public class Seller extends RetailerNodeBase {
public Seller(double startMoney) {
super(startMoney);
allowedSeller = NodeType.Processor;
allowedPurchaser = NodeType.Distributor;
}
}

View File

@ -0,0 +1,16 @@
package cz.cvut.fel.sit.omo.foodchain.node.base;
import cz.cvut.fel.sit.omo.foodchain.node.interfaces.IBuyerNode;
import cz.cvut.fel.sit.omo.foodchain.product.Product;
public class BuyerNodeBase extends NodeBase implements IBuyerNode {
public BuyerNodeBase(double m){
super(m);
}
@Override
public void buyProduct(Product product) {
}
}

View File

@ -0,0 +1,159 @@
package cz.cvut.fel.sit.omo.foodchain.node.base;
import cz.cvut.fel.sit.omo.foodchain.channel.ChannelBase;
import cz.cvut.fel.sit.omo.foodchain.channel.ChannelSubscriptionType;
import cz.cvut.fel.sit.omo.foodchain.node.enums.NodeType;
import cz.cvut.fel.sit.omo.foodchain.operation.*;
import cz.cvut.fel.sit.omo.foodchain.product.Product;
import cz.cvut.fel.sit.omo.foodchain.product.ProductType;
import cz.cvut.fel.sit.omo.foodchain.requirement.Requirement;
import cz.cvut.fel.sit.omo.foodchain.signature.Signature;
import cz.cvut.fel.sit.omo.foodchain.signature.SignatureManager;
import cz.cvut.fel.sit.omo.foodchain.util.ChannelObserver;
import org.javamoney.moneta.Money;
import javax.money.MonetaryAmount;
import java.util.HashMap;
import java.util.LinkedList;
import java.util.List;
import java.util.Map;
public class NodeBase implements ChannelObserver {
private final Map<ChannelBase, ChannelSubscriptionType> subscribedChannels;
private final List<Product> products;
private final List<Transaction> refusedTransactions;
private final MonetaryAmount money;
protected NodeType allowedSeller;
protected NodeType allowedPurchaser;
public NodeBase() {
subscribedChannels = new HashMap<>();
products = new LinkedList<>();
refusedTransactions = new LinkedList<>();
money = Money.of(0, "USD");
}
public NodeBase(double m) {
subscribedChannels = new HashMap<>();
products = new LinkedList<>();
refusedTransactions = new LinkedList<>();
money = Money.of(m, "USD");
}
public void sendTransaction(Product product, NodeBase node) {
Transaction transaction = new ProductTransaction(this, node, TransactionType.SALE, product);
subscribedChannels.keySet().stream()
.filter(ch -> ch.getProductType().equals(product.getProductType()))
.findAny().ifPresent(channel -> channel.addTransaction(transaction));
}
public void sendTransaction(MonetaryAmount amount, NodeBase node, ProductTransaction prevTransaction) {
Transaction transaction = new FinancialTransaction(this, node, TransactionType.PURCHASE, amount, prevTransaction);
subscribedChannels.keySet().stream()
.filter(ch -> ch.getProductType().equals(prevTransaction.getProduct().getProductType()))
.findAny().ifPresent(channel -> channel.addTransaction(transaction));
}
public void receiveTransaction(ProductTransaction transaction) {
}
public void receiveTransaction(FinancialTransaction transaction) {
}
public void refuseTransaction(Transaction transaction) {
transaction.endTransaction();
refusedTransactions.add(transaction); //TODO maybe need more work on it
}
public Transaction readNextTransaction(ChannelBase channel) {
//TODO
return null;
// return channel.getNextTransaction();
}
public void createRequirement(TransactionType tType, ProductType pType, String pName) {
Requirement req = new Requirement(this, tType, pType, pName);
subscribedChannels.keySet().stream()
.filter(ch -> ch.getProductType().equals(pType))
.findAny().ifPresent(channel -> channel.addRequirement(req));
}
public void acceptRequirement(Requirement requirement) {
System.out.println(this.getClass().getSimpleName() + " accepted " + requirement.toString());
}
public void subscribeToChannel(ChannelBase channel, ChannelSubscriptionType type) {
subscribedChannels.put(channel, type);
channel.attach(this);
}
public void unsubscribeFromChannel(ChannelBase channel) {
subscribedChannels.remove(channel);
}
public void doAction(ProductOperationType action, Product product) {
Action actionProcess = new Action(this, product, action);
}
public void doAction(ProductOperationType action) {
//create new action
}
public void storeProduct(Product product) {
this.products.add(product);
}
public void storeProducts(List<Product> products) {
this.products.addAll(products);
}
public Product getProductFromStorage(String name, ProductType type) {
return products.stream().filter(ch -> ch.getProductType() == type && ch.getName().equals(name)).findFirst().orElse(null);
}
public List<Product> getStorage() {
return products;
}
public Signature generateSignature(Transaction transaction) {
return SignatureManager.signTransaction(transaction);
}
public boolean validateSignature(Transaction transaction) {
return SignatureManager.validateSignature(transaction);
}
boolean senderPurchaserCheck(Requirement req) {
String simpleName = req.getCreator().getClass().getSimpleName();
return !req.getCreator().equals(this) &&
(((allowedSeller == NodeType.valueOf(simpleName) || allowedSeller == NodeType.All) && (req.getTransactionType() == TransactionType.SALE)) ||
((allowedPurchaser == NodeType.valueOf(simpleName) || allowedPurchaser == NodeType.All) && req.getTransactionType() == TransactionType.PURCHASE));
}
@Override
public void update(Requirement requirement) {
if (senderPurchaserCheck(requirement))
acceptRequirement(requirement);
}
}

View File

@ -0,0 +1,26 @@
package cz.cvut.fel.sit.omo.foodchain.node.base;
import cz.cvut.fel.sit.omo.foodchain.node.interfaces.IBuyerNode;
import cz.cvut.fel.sit.omo.foodchain.node.interfaces.ISellerNode;
import cz.cvut.fel.sit.omo.foodchain.product.Product;
public class RetailerNodeBase extends NodeBase implements IBuyerNode, ISellerNode {
public RetailerNodeBase(double startMoney) {
super(startMoney);
}
@Override
public void sellProduct(Product product) {
}
@Override
public void addMargin(Product product) {
}
@Override
public void buyProduct(Product product) {
}
}

View File

@ -0,0 +1,20 @@
package cz.cvut.fel.sit.omo.foodchain.node.base;
import cz.cvut.fel.sit.omo.foodchain.node.interfaces.ISellerNode;
import cz.cvut.fel.sit.omo.foodchain.product.Product;
public class SellerNodeBase extends NodeBase implements ISellerNode {
public SellerNodeBase(double startMoney) {
super(startMoney);
}
@Override
public void sellProduct(Product product) {
}
@Override
public void addMargin(Product product) {
}
}

View File

@ -0,0 +1,5 @@
package cz.cvut.fel.sit.omo.foodchain.node.enums;
public enum NodeType {
Farmer, Processor, Distributor, Seller, Customer, None, All
}

View File

@ -0,0 +1,8 @@
package cz.cvut.fel.sit.omo.foodchain.node.interfaces;
import cz.cvut.fel.sit.omo.foodchain.product.Product;
public interface IBuyerNode {
void buyProduct(Product product);
}

View File

@ -0,0 +1,10 @@
package cz.cvut.fel.sit.omo.foodchain.node.interfaces;
import cz.cvut.fel.sit.omo.foodchain.product.Product;
public interface ISellerNode {
void sellProduct(Product product);
void addMargin(Product product);
}

View File

@ -0,0 +1,48 @@
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.product.Product;
public class Action extends OperationBase {
private final OperationBase lastOperation;
private final Product product;
private final ProductOperationType type;
private int duration;
public Action(NodeBase node, Product product, ProductOperationType type) {
super(node);
this.product = product;
this.type = type;
lastOperation = product.getCurrentOperation();
duration = type.getDuration();
product.setCurrentOperation(this);
product.setStateToReadyForDispatch();
}
private void endAction() {
this.setTimeEnd();
product.setStateToAvailable();
}
public boolean tick() {
if (duration == 0) {
endAction();
return false;
}
else duration--;
return true;
}
public OperationBase getLastOperation() {
return lastOperation;
}
public Product getProduct() {
return product;
}
public ProductOperationType getType() {
return type;
}
}

View File

@ -0,0 +1,25 @@
package cz.cvut.fel.sit.omo.foodchain.operation;
import cz.cvut.fel.sit.omo.foodchain.node.base.NodeBase;
import javax.money.MonetaryAmount;
public class FinancialTransaction extends Transaction {
private final MonetaryAmount amount;
private final ProductTransaction transactionPaid;
public FinancialTransaction(NodeBase creator, NodeBase receiver, TransactionType type, MonetaryAmount amount, ProductTransaction transactionPaid) {
super(creator, receiver, type);
this.amount = amount;
this.transactionPaid = transactionPaid;
}
public MonetaryAmount getAmount() {
return amount;
}
public ProductTransaction getTransactionPaid() {
return transactionPaid;
}
}

View File

@ -0,0 +1,34 @@
package cz.cvut.fel.sit.omo.foodchain.operation;
import cz.cvut.fel.sit.omo.foodchain.node.base.NodeBase;
import java.time.LocalDateTime;
public class OperationBase {
private final LocalDateTime timeStart;
private LocalDateTime timeEnd;
private final NodeBase nodeCreator;
OperationBase(NodeBase node) {
nodeCreator = node;
timeStart = LocalDateTime.now();
}
public LocalDateTime getTimeStart() {
return timeStart;
}
public LocalDateTime getTimeEnd() {
return timeEnd;
}
public void setTimeEnd() {
this.timeEnd = LocalDateTime.now();
}
public NodeBase getNodeCreator() {
return nodeCreator;
}
}

View File

@ -0,0 +1,22 @@
package cz.cvut.fel.sit.omo.foodchain.operation;
public enum ProductOperationType {
STORE_MEAT(10, -8);
private final int duration;
private final int temperature;
ProductOperationType(int duration, int temperature) {
this.duration = duration;
this.temperature = temperature;
}
public int getDuration() {
return duration;
}
public int getTemperature() {
return temperature;
}
}

View File

@ -0,0 +1,38 @@
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.product.Product;
public class ProductTransaction extends Transaction {
private final OperationBase lastOperation;
private final Product product;
private final ProductOperationType type;
public ProductTransaction(NodeBase creator, NodeBase receiver, TransactionType transactionType, Product product) {
super(creator, receiver, transactionType);
this.product = product;
type = null;
lastOperation = product.getCurrentOperation();
product.setCurrentOperation(this);
product.setStateToReadyForDispatch();
}
@Override
public void endTransaction() {
super.endTransaction();
product.setStateToAvailable();
}
public OperationBase getLastOperation() {
return lastOperation;
}
public Product getProduct() {
return product;
}
public ProductOperationType getType() {
return type;
}
}

View File

@ -0,0 +1,46 @@
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.signature.Signature;
import cz.cvut.fel.sit.omo.foodchain.signature.SignatureManager;
public abstract class Transaction extends OperationBase {
private final TransactionType transactionType;
private final Signature signature;
private final NodeBase nodeReceiver;
Transaction(NodeBase creator, NodeBase receiver, TransactionType type) {
super(creator);
transactionType = type;
nodeReceiver = receiver;
signature = SignatureManager.signTransaction(this);
System.out.println(toString());
}
public void endTransaction() {
this.setTimeEnd();
}
public TransactionType getTransactionType() {
return transactionType;
}
public Signature getSignature() {
return signature;
}
public NodeBase getNodeReceiver() {
return nodeReceiver;
}
@Override
public String toString() {
return "Transaction{" +
"transactionType=" + transactionType +
", signature=" + (signature != null) +
", nodeCreator=" + getNodeCreator().getClass().getSimpleName() +
", nodeReceiver=" + nodeReceiver.getClass().getSimpleName() +
'}';
}
}

View File

@ -0,0 +1,6 @@
package cz.cvut.fel.sit.omo.foodchain.operation;
public enum TransactionType {
SALE, PURCHASE
}

View File

@ -0,0 +1,52 @@
package cz.cvut.fel.sit.omo.foodchain.parser;
import org.w3c.dom.Document;
import org.w3c.dom.Node;
import org.w3c.dom.NodeList;
import org.xml.sax.SAXException;
import javax.xml.parsers.DocumentBuilder;
import javax.xml.parsers.DocumentBuilderFactory;
import javax.xml.parsers.ParserConfigurationException;
import java.io.File;
import java.io.IOException;
public class ConfigurationParser {
private static Document activeDocument;
public static void parseDocument(String name) throws ParserConfigurationException, IOException, SAXException {
DocumentBuilderFactory factory = DocumentBuilderFactory.newInstance();
factory.setValidating(true);
factory.setIgnoringElementContentWhitespace(true);
DocumentBuilder builder = factory.newDocumentBuilder();
File file = new File(name);
activeDocument = builder.parse(file);
}
public static ParserResult getElements(String tag) {
NodeList elements = activeDocument.getElementsByTagName(tag);
ParserResult resultList = new ParserResult();
for (int i = 0; i < elements.getLength(); i++) {
Node tmpNode = elements.item(i);
ParserResultElement element = new ParserResultElement();
for (int j = 0; j < tmpNode.getAttributes().getLength(); j++) {
element
.addAttribute(
tmpNode
.getAttributes()
.item(j)
.getNodeName(),
tmpNode
.getAttributes()
.item(j)
.getTextContent());
}
for (int j = 0; j < tmpNode.getChildNodes().getLength(); j++) {
element.addChild(tmpNode.getChildNodes().item(j).getNodeName(), tmpNode.getChildNodes().item(j).getTextContent());
}
resultList.addElement(element);
}
return resultList;
}
}

View File

@ -0,0 +1,4 @@
package cz.cvut.fel.sit.omo.foodchain.parser;
public class ConsoleParser {
}

View File

@ -0,0 +1,22 @@
package cz.cvut.fel.sit.omo.foodchain.parser;
import java.util.LinkedList;
import java.util.List;
public class ParserResult {
private final List<ParserResultElement> elements;
public ParserResult() {
elements = new LinkedList<>();
}
public void addElement(ParserResultElement element) {
elements.add(element);
}
public List<ParserResultElement> getElements() {
return elements;
}
}

View File

@ -0,0 +1,57 @@
package cz.cvut.fel.sit.omo.foodchain.parser;
import java.util.HashMap;
import java.util.LinkedList;
import java.util.Map;
public class ParserResultElement {
private String name;
private Map<String, String> attributes;
private Map<String, String> children;
public ParserResultElement() {
children = new HashMap<>();
attributes = new HashMap<>();
}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public Map<String, String> getAttributes() {
return attributes;
}
public void setAttributes(Map<String, String> attributes) {
this.attributes = attributes;
}
public void addAttribute(String key, String value) {
attributes.put(key, value);
}
public String getAttribute(String key) {
return attributes.get(key);
}
public Map<String, String> getChildren() {
return children;
}
public void setChildren(Map<String, String> children) {
this.children = children;
}
public void addChild(String key, String value) {
children.put(key, value);
}
public String getChild(String key) {
return children.get(key);
}
}

View File

@ -0,0 +1,11 @@
package cz.cvut.fel.sit.omo.foodchain.pool;
import cz.cvut.fel.sit.omo.foodchain.channel.ChannelBase;
import cz.cvut.fel.sit.omo.foodchain.product.ProductType;
public class ChannelPool extends PoolListBase<ChannelBase> {
public ChannelBase findByType(ProductType type) {
return findAll().stream().filter(ch -> ch.getProductType().equals(type)).findFirst().orElse(null);
}
}

View File

@ -0,0 +1,6 @@
package cz.cvut.fel.sit.omo.foodchain.pool;
import cz.cvut.fel.sit.omo.foodchain.node.base.NodeBase;
public class NodePool extends PoolListBase<NodeBase> {
}

View File

@ -0,0 +1,44 @@
package cz.cvut.fel.sit.omo.foodchain.pool;
import cz.cvut.fel.sit.omo.foodchain.util.Singleton;
import java.lang.reflect.InvocationTargetException;
public class PoolDatabase {
public ChannelPool getChannelPoolInstance() {
try {
return Singleton.getInstance(ChannelPool.class);
} catch (IllegalAccessException | InstantiationException | NoSuchMethodException | InvocationTargetException e) {
e.printStackTrace();
}
return null;
}
public NodePool getNodePoolInstance() {
try {
return Singleton.getInstance(NodePool.class);
} catch (IllegalAccessException | InstantiationException | NoSuchMethodException | InvocationTargetException e) {
e.printStackTrace();
}
return null;
}
public ProductPool getProductPoolInstance() {
try {
return Singleton.getInstance(ProductPool.class);
} catch (IllegalAccessException | InstantiationException | NoSuchMethodException | InvocationTargetException e) {
e.printStackTrace();
}
return null;
}
public ScenarioPool getScenarioPoolInstance() {
try {
return Singleton.getInstance(ScenarioPool.class);
} catch (IllegalAccessException | InstantiationException | NoSuchMethodException | InvocationTargetException e) {
e.printStackTrace();
}
return null;
}
}

View File

@ -0,0 +1,32 @@
package cz.cvut.fel.sit.omo.foodchain.pool;
import java.util.LinkedList;
import java.util.List;
public abstract class PoolListBase<T> {
List<T> pool;
public PoolListBase() {
pool = new LinkedList<T>();
}
public List<T> findAll() {
return pool;
}
public void add(T element) {
pool.add(element);
}
public void remove(T element) {
pool.remove(element);
}
public void clear() {
pool.clear();
}
public boolean contains(T element) {
return pool.contains(element);
}
}

View File

@ -0,0 +1,6 @@
package cz.cvut.fel.sit.omo.foodchain.pool;
import cz.cvut.fel.sit.omo.foodchain.product.Product;
public class ProductPool extends PoolListBase<Product> {
}

View File

@ -0,0 +1,6 @@
package cz.cvut.fel.sit.omo.foodchain.pool;
import cz.cvut.fel.sit.omo.foodchain.scenario.Scenario;
public class ScenarioPool extends PoolListBase<Scenario> {
}

View File

@ -0,0 +1,161 @@
package cz.cvut.fel.sit.omo.foodchain.product;
import cz.cvut.fel.sit.omo.foodchain.operation.Action;
import cz.cvut.fel.sit.omo.foodchain.operation.OperationBase;
import org.javamoney.moneta.Money;
import javax.money.Monetary;
import javax.money.MonetaryAmount;
public class Product
{
private ProductState productState;
private ProductType productType;
private OperationBase currentOperation;
private MonetaryAmount money;
private String name;
/**
* Creates Product with default state AVAILABLE
* @param name name of product
* @param productType type of product
*/
public Product(String name, ProductType productType)
{
this.name = name;
this.productType = productType;
this.productState = ProductState.AVAILABLE;
this.money = Money.of(0, "USD");
}
public Product(String name, ProductType productType, double m)
{
this.name = name;
this.productType = productType;
this.productState = ProductState.AVAILABLE;
this.money = Money.of(m, "USD");
}
/**
* Creates Product
* @param name name of product
* @param productType type of product
* @param productState state of product
*/
public Product(String name, ProductType productType, ProductState productState)
{
this.name = name;
this.productType = productType;
this.productState = productState;
this.money = Money.of(0, "USD");
}
public Product(String name, ProductType productType, ProductState productState, double m)
{
this.name = name;
this.productType = productType;
this.productState = productState;
this.money = Money.of(m, "USD");
}
public boolean tick() {
try {
return ((Action) currentOperation).tick();
}
catch (Exception e) {
return false;
}
}
// "State machine methods"
/**
* Set current product state to AVAILABLE
*/
public void setStateToAvailable()
{
this.productState = ProductState.AVAILABLE;
}
/**
* Set current product state to READY_FOR_DISPATCH. Throws IllegalStateException if the product is not AVAILABLE.
*/
public void setStateToReadyForDispatch()
{
if(this.productState.equals(ProductState.AVAILABLE))
this.productState = ProductState.READY_FOR_DISPATCH;
else
throw new IllegalStateException("Cannot set state READY_FOR_DISPATCH. Product is not AVAILABLE!");
}
/**
* Set current product state to IN_TRANSIT. Throws IllegalStateException if the product is not READY_FOR_DISPATCH.
*/
public void setStateToInTransit()
{
if(this.productState.equals(ProductState.READY_FOR_DISPATCH))
this.productState = ProductState.IN_TRANSIT;
else
throw new IllegalStateException("Cannot set state IN_TRANSIT. Product is not READY_FOR_DISPATCH!");
}
/**
* Set current product state to READY_FOR_RECEPTION. Throws IllegalStateException if the product is not READY_FOR_RECEPTION.
*/
public void setStateToReadyForReception()
{
if(this.productState.equals(ProductState.IN_TRANSIT))
this.productState = ProductState.READY_FOR_RECEPTION;
else
throw new IllegalStateException("Cannot set state READY_FOR_RECEPTION. Product has not been in transit!");
}
/*
public void setProductState(ProductState productState)
{
this.productState = productState;
}*/
//Getters & Setters
public ProductState getProductState()
{
return productState;
}
public ProductType getProductType()
{
return productType;
}
public void setProductType(ProductType productType)
{
this.productType = productType;
}
public String getName()
{
return name;
}
public void setName(String name)
{
this.name = name;
}
public OperationBase getCurrentOperation()
{
return currentOperation;
}
public void setCurrentOperation(OperationBase currentOperation)
{
this.currentOperation = currentOperation;
}
public MonetaryAmount getMoney() { return money; }
public void setMoney(MonetaryAmount money) { this.money = money; }
}

View File

@ -0,0 +1,6 @@
package cz.cvut.fel.sit.omo.foodchain.product;
public enum ProductState
{
AVAILABLE, READY_FOR_DISPATCH, IN_TRANSIT, READY_FOR_RECEPTION;
}

View File

@ -0,0 +1,6 @@
package cz.cvut.fel.sit.omo.foodchain.product;
public enum ProductType
{
MEAT, FRUIT, VEGETABLE, OTHER;
}

View File

@ -0,0 +1,19 @@
package cz.cvut.fel.sit.omo.foodchain.reporting;
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.operation.OperationBase;
public class ReportTextFileVisitor {
public void visit(NodeBase node){
}
public void visit(OperationBase operationBase){
}
public void visit(ChannelBase channel){
}
}

View File

@ -0,0 +1,4 @@
package cz.cvut.fel.sit.omo.foodchain.reporting;
public class ReportingManager {
}

View File

@ -0,0 +1,58 @@
package cz.cvut.fel.sit.omo.foodchain.requirement;
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.product.ProductType;
public class Requirement {
private final NodeBase creator;
private final TransactionType transactionType;
private final ProductType productType;
private final String productName;
private int TTL;
public Requirement(NodeBase creator, TransactionType transactionType, ProductType productType, String productName) {
this.creator = creator;
this.transactionType = transactionType;
this.productType = productType;
this.productName = productName;
TTL = 3;
System.out.println(toString());
}
public void tick() {
TTL--;
}
public NodeBase getCreator() {
return creator;
}
public TransactionType getTransactionType() {
return transactionType;
}
public ProductType getProductType() {
return productType;
}
public String getProductName() {
return productName;
}
public int getTTL() {
return TTL;
}
@Override
public String toString() {
return "Requirement{" +
"creator=" + creator.getClass().getSimpleName() +
", transactionType=" + transactionType +
", productType=" + productType +
", productName='" + productName + '\'' +
", TTL=" + TTL +
'}';
}
}

View File

@ -0,0 +1,17 @@
package cz.cvut.fel.sit.omo.foodchain.scenario;
import cz.cvut.fel.sit.omo.foodchain.node.Customer;
public class ConsumeProductStep extends ScenarioStep {
private final Customer node;
public ConsumeProductStep(Customer node) {
this.node = node;
}
@Override
void execute() {
node.consumeProduct();
}
}

View File

@ -0,0 +1,32 @@
package cz.cvut.fel.sit.omo.foodchain.scenario;
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.product.Product;
public class DoActionStep extends ScenarioStep {
private final NodeBase nodeBase;
private final ProductOperationType productOperationType;
private final Product product;
public DoActionStep(NodeBase node, ProductOperationType productOperationType, Product product){
this.nodeBase = node;
this.productOperationType = productOperationType;
this.product = product;
}
public DoActionStep(NodeBase node, ProductOperationType productOperationType){
this(node, productOperationType, null);
}
@Override
void execute() {
if (product != null){
nodeBase.doAction(productOperationType, product);
}
else {
nodeBase.doAction(productOperationType);
}
}
}

View File

@ -0,0 +1,29 @@
package cz.cvut.fel.sit.omo.foodchain.scenario;
import cz.cvut.fel.sit.omo.foodchain.FoodChain;
import cz.cvut.fel.sit.omo.foodchain.node.Farmer;
import cz.cvut.fel.sit.omo.foodchain.product.Product;
public class GenerateProductStep extends ScenarioStep {
private final Farmer node;
private final Product product;
private static int counter = 0;
public GenerateProductStep(Farmer node) {
this.node = node;
if (counter < FoodChain.getFactoryManager().getPoolDatabaseInstance().getProductPoolInstance().findAll().size()) {
product = FoodChain.getFactoryManager().getPoolDatabaseInstance().getProductPoolInstance().findAll().get(counter);
counter++;
}
else {
product = null;
System.err.println("Insufficient products in pool");
}
}
@Override
void execute() {
node.generateProduct(product);
}
}

View File

@ -0,0 +1,7 @@
package cz.cvut.fel.sit.omo.foodchain.scenario;
public class PassStep extends ScenarioStep {
@Override
void execute() {}
}

View File

@ -0,0 +1,36 @@
package cz.cvut.fel.sit.omo.foodchain.scenario;
import java.util.Iterator;
import java.util.List;
public class Scenario {
List<ScenarioStep> steps;
Iterator<ScenarioStep> stepIterator;
public Scenario() {
//steps = //TODO init
stepIterator = steps.listIterator(0);
}
public Scenario(List<ScenarioStep> steps) {
this.steps = steps;
stepIterator = steps.listIterator(0);
}
boolean execute() {
if (!stepIterator.hasNext()) {
// stepIterator = steps.listIterator(0);
return false;
}
stepIterator.next().execute();
return true;
}
public boolean tick() {
return execute();
}
public List<ScenarioStep> getSteps() {
return steps;
}
}

View File

@ -0,0 +1,5 @@
package cz.cvut.fel.sit.omo.foodchain.scenario;
public abstract class ScenarioStep {
abstract void execute();
}

View File

@ -0,0 +1,24 @@
package cz.cvut.fel.sit.omo.foodchain.scenario;
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.product.ProductType;
public class SendRequirementStep extends ScenarioStep {
private final NodeBase node;
private final TransactionType tType;
private final ProductType pType;
private final String pName;
public SendRequirementStep(NodeBase node, TransactionType tType, ProductType pType, String pName) {
this.node = node;
this.tType = tType;
this.pType = pType;
this.pName = pName;
}
@Override
void execute() {
node.createRequirement(tType, pType, pName);
}
}

View File

@ -0,0 +1,39 @@
package cz.cvut.fel.sit.omo.foodchain.signature;
import cz.cvut.fel.sit.omo.foodchain.operation.Transaction;
import java.time.LocalDateTime;
import java.util.UUID;
public class Signature {
private final String managerCode;
private final Transaction transaction;
private final LocalDateTime signedDate;
private final UUID uuid;
public Signature(String code, Transaction transaction) {
managerCode = code;
this.transaction = transaction;
signedDate = LocalDateTime.now();
uuid = UUID.randomUUID();
}
public Transaction getTransaction(String code) {
if (code.equals(managerCode))
return transaction;
return null;
}
public LocalDateTime getSignedDate(String code) {
if (code.equals(managerCode))
return signedDate;
return null;
}
public UUID getUuid(String code) {
if (code.equals(managerCode))
return uuid;
return null;
}
}

View File

@ -0,0 +1,17 @@
package cz.cvut.fel.sit.omo.foodchain.signature;
import cz.cvut.fel.sit.omo.foodchain.operation.Transaction;
public class SignatureManager {
private static final String MANAGER_CODE = "iW91AJWNOCmX1pbpLlW0";
public static Signature signTransaction(Transaction transaction) {
return new Signature(MANAGER_CODE, transaction);
}
public static boolean validateSignature(Transaction transaction) {
return transaction.equals(transaction.getSignature().getTransaction(MANAGER_CODE))
&& transaction.getSignature().getUuid(MANAGER_CODE).equals(transaction.getSignature().getTransaction(MANAGER_CODE).getSignature().getUuid(MANAGER_CODE));
}
}

View File

@ -0,0 +1,7 @@
package cz.cvut.fel.sit.omo.foodchain.util;
import cz.cvut.fel.sit.omo.foodchain.requirement.Requirement;
public interface ChannelObserver {
void update(Requirement requirement);
}

View File

@ -0,0 +1,7 @@
package cz.cvut.fel.sit.omo.foodchain.util;
public interface Observable {
void attach(ChannelObserver channelObserver);
void detach(ChannelObserver channelObserver);
void notifyAllObservers();
}

View File

@ -0,0 +1,27 @@
package cz.cvut.fel.sit.omo.foodchain.util;
import java.lang.reflect.Constructor;
import java.lang.reflect.InvocationTargetException;
import java.util.HashMap;
import java.util.Map;
public class Singleton {
private static final Singleton instance = new Singleton();
@SuppressWarnings("rawtypes")
private final Map<Class, Object> mapHolder = new HashMap<>();
private Singleton() {
}
public static <T> T getInstance(Class<T> tClass) throws NoSuchMethodException, InvocationTargetException, IllegalAccessException, InstantiationException {
if (!instance.mapHolder.containsKey(tClass)) {
Constructor<T> cons = tClass.getConstructor();
Object object = cons.newInstance();
instance.mapHolder.put(tClass, object);
}
return (T) instance.mapHolder.get(tClass);
}
}

View File

@ -0,0 +1,33 @@
package cz.cvut.fel.sit.omo.foodchain.util;
import cz.cvut.fel.sit.omo.foodchain.FoodChain;
import cz.cvut.fel.sit.omo.foodchain.channel.ChannelBase;
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.scenario.Scenario;
import javax.swing.*;
public class Ticker {
private static Timer timer;
public static void start() {
timer = new Timer(500, actionEvent -> {
System.out.println("tick");
PoolDatabase db = FoodChain.getFactoryManager().getPoolDatabaseInstance();
boolean productBool = db.getProductPoolInstance().findAll().stream().filter(Product::tick).count() == 0; // change duration of action
boolean scenarioBool = db.getScenarioPoolInstance().findAll().stream().filter(Scenario::tick).count() == 0; // do next step in scenario
boolean channelBool = db.getChannelPoolInstance().findAll().stream().filter(ChannelBase::tick).count() == 0; // change TTL of requirements
// db.getNodePoolInstance().findAll().forEach(n -> n.tick()); // maybe unnecessary
if (channelBool && productBool && scenarioBool) stop();
});
timer.start();
}
public static void stop() {
timer.stop();
}
public static Timer getTimer() { return timer; }
}