Advertisement
Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- package kažukauskasa_l3a;
- import java.io.BufferedReader;
- import java.io.BufferedWriter;
- import java.io.FileReader;
- import java.io.FileWriter;
- import org.jcsp.lang.*;
- import java.util.ArrayList;
- import java.util.logging.Level;
- import java.util.logging.Logger;
- class Globals
- {
- public static final int productsSize = 100;
- public static int ConsumersSize = 5,
- ProducersSize = 5,
- finishedProducers = 0,
- finishedConsumers = 0;
- public static final String dataFile = "KazukauskasMindaugas_L3_dat_1.txt"; // Pasalinami visi
- //public static final String dataFile = "KazukauskasMindaugas_L3_dat_2.txt"; // Nepasalina nei vieno
- //public static final String dataFile = "KazukauskasMindaugas_L3_dat_3"; // Pasalina tik dali
- public static final String resultsFile = "KazukauskasMindaugas_L3_rez.txt";
- public static boolean HaveProducersFinished(){
- return finishedProducers == ProducersSize;
- }
- public static boolean HaveConsumersFinished(){
- return finishedConsumers == ConsumersSize;
- }
- }
- //Action types for channels' communaction
- enum ActionType {
- insert, remove, producerFinished, consumerFinished
- }
- //Class for keeping transfering data via channels
- class Action{
- public Object data;
- public ActionType actionType;
- public int processID = -1;
- }
- /*
- * Class contains producer type products
- */
- class ProducerProducts
- {
- public String name;
- public int count;
- public double avg;
- public ProducerProducts()
- {
- name = "";
- count = 0;
- avg = 0.0;
- }
- }
- /*
- * Class contains consumer type products
- */
- class ConsumerProducts
- {
- public String consumer_name;
- public int count;
- public ConsumerProducts()
- {
- consumer_name = "";
- count = 0;
- }
- }
- /*
- * Common array class
- */
- class Buffer
- {
- private ConsumerProducts[] B = new ConsumerProducts[Globals.productsSize];
- private int size;
- public Buffer()
- {
- for (int i = 0; i < Globals.productsSize; i++)
- {
- B[i] = new ConsumerProducts();
- }
- size = 0;
- }
- /**
- * Returns product name at index location
- * @param index product location in common array
- */
- public ConsumerProducts[] getItems() { return B; }
- /**
- * Increments finished producers count
- */
- public int getSize() { return size; }
- /**
- * Checks if product exists in common array
- * @param name product name
- */
- public int ifExists(String name)
- {
- int index = -1;
- for (int i = 0; i < size; i++)
- {
- if (name.compareTo(B[i].consumer_name) == 0) //if finds in array
- {
- index = i;
- break;
- }
- }
- return index;
- }
- public void WriteToArray(ConsumerProducts product)
- {
- int index = ifExists(product.consumer_name);
- if (index == -1)
- {
- index = RequestInsertIndex(product.consumer_name);
- insert(product.consumer_name, product.count, index);
- }
- else
- {
- B[index].count += product.count;
- }
- }
- // Grąžina, kiek masyve yra elementų.
- public ConsumerProducts ReadFromArray(ConsumerProducts product){
- ConsumerProducts temp = new ConsumerProducts();
- temp.consumer_name = product.consumer_name;
- temp.count = product.count;
- int index = ifExists(temp.consumer_name);
- if(index != -1){
- if (B[index].count <= temp.count){
- temp.count = temp.count - B[index].count;
- B[index].count = 0;
- }
- if (B[index].count > temp.count){
- B[index].count -= temp.count;
- temp.count = 0;
- }
- if (B[index].count == 0){
- remove(index);
- }
- }
- return temp;
- }
- /**
- * Removes product from common array at index location
- * @param index product index in common array
- */
- public void remove(int index)
- {
- if (index == size - 1)
- {
- B[index].consumer_name = "";
- B[index].count = 0;
- }
- else
- {
- for (int i = index; i < size; i++)
- {
- B[i] = B[i + 1];
- }
- B[size - 1].consumer_name = "";
- B[size - 1].count = 0;
- }
- --size;
- }
- /**
- * Inserts product to index location in common array
- * @param name product name
- * @param index index to where insert product
- */
- public void insert(String name, int count, int index)
- {
- ConsumerProducts temp = new ConsumerProducts();
- temp.consumer_name = name;
- temp.count = count;
- size++;
- if (size == 1)
- {
- B[index] = temp;
- }
- else
- {
- for (int i = size; i > index + 1; i--)
- {
- B[i - 1] = B[i - 2];
- }
- B[index] = temp;
- }
- }
- /**
- * Gets product index from common array
- * @param name product name
- */
- public int RequestInsertIndex(String name)
- {
- int index = -1;
- if (size == 0) return 0;
- if (size == 1)
- if (name.compareTo(B[0].consumer_name) > 0)
- return 1;
- else return 0;
- if (name.compareTo(B[size - 1].consumer_name) > 0)
- return size;
- for (int i = 0; i < size; i++)
- {
- if (name.compareTo(B[i].consumer_name) < 0)
- {
- index = i;
- return index;
- }
- }
- return index;
- }
- }
- //Procesas_00 class
- class Procesas_00 implements CSProcess {
- private ArrayList< ArrayList<ProducerProducts> > P; //Producers' data
- private ArrayList< ArrayList<ConsumerProducts> > C; //Consumers' data
- private ArrayList<ChannelOutput> ProducersChannels; //Channels for communicating with producers
- private ArrayList<ChannelOutput> ConsumersChannels; //Channels for communicating with consumers
- private ChannelInput ResultsChannel; //Channel for receiving final array for printing
- public Procesas_00(ArrayList<ChannelOutput> ProducersChannels,
- ArrayList<ChannelOutput> ConsumersChannels,
- ChannelInput ResultsChannel)
- {
- this.P = new ArrayList<>();
- this.C = new ArrayList<>();
- this.ProducersChannels = ProducersChannels;
- this.ConsumersChannels = ConsumersChannels;
- this.ResultsChannel = ResultsChannel;
- }
- @Override
- public void run(){
- try {
- //Gets data from file
- KažukauskasA_L3a.Read(P, C);
- } catch (Exception ex) {
- Logger.getLogger(KažukauskasA_L3a.class.getName()).log(Level.SEVERE, null, ex);
- }
- try {
- //Writes original data to results file
- KažukauskasA_L3a.writeTables(P, C);
- } catch (Exception ex) {
- Logger.getLogger(KažukauskasA_L3a.class.getName()).log(Level.SEVERE, null, ex);
- }
- //Distributes data to all producers
- for(int i = 0; i < P.size(); i++){
- ProducersChannels.get(i).write(P.get(i));
- }
- //Distributes data to all consumers
- for(int i = 0; i < C.size(); i++){
- ConsumersChannels.get(i).write(C.get(i));
- }
- //Reads final array data from manager process
- Buffer B = (Buffer) ResultsChannel.read();
- try {
- //Prints final array to results file
- KažukauskasA_L3a.writeResults(B);
- } catch (Exception ex) {}
- System.out.println("Distributor darbas baigtas");
- }
- }
- //Consumer class
- class Consumer implements CSProcess {
- private int processID; //saves consumer's process id
- private ArrayList<ConsumerProducts> products = new ArrayList<ConsumerProducts>(); //Saves which data to consume
- private ChannelInput inputDataChannel, //Channel to get data from procesas_00
- ConsumeResultChannel; //Channel to get info from manager about successful read from array
- private ChannelOutput outputChannel; //Channel with manager to consume items
- public Consumer(ChannelInput inputDataChannel,
- ChannelOutput outputChannel, ChannelInput ConsumeResultChannel, int processID){
- this.inputDataChannel = inputDataChannel;
- this.outputChannel = outputChannel;
- this.ConsumeResultChannel = ConsumeResultChannel;
- this.processID = processID;
- }
- @Override
- public void run(){
- //Reads data from procesas_00
- products = (ArrayList<ConsumerProducts>) inputDataChannel.read();
- int result, i = 0;
- while(products.size() > 0)
- {
- Action action = new Action();
- action.actionType = ActionType.remove;
- ConsumerProducts consProducts = new ConsumerProducts();
- consProducts.consumer_name = products.get(i).consumer_name;
- consProducts.count = products.get(i).count;
- action.data = consProducts;
- action.processID = processID;
- outputChannel.write(action);
- result = (int) ConsumeResultChannel.read();
- if(result == 0){
- products.remove(i);
- }
- else if (!Globals.HaveProducersFinished()){
- products.get(i).count = result;
- }
- else products.remove(i);
- if(i >= products.size()-1)
- i=0;
- else i++;
- }
- Action actionFinished = new Action();
- actionFinished.actionType = ActionType.consumerFinished;
- outputChannel.write(actionFinished);
- }
- }
- //Producer class
- class Producer implements CSProcess {
- private static ArrayList<ProducerProducts> products; //Saves which data to produce
- private ChannelInput inputDataChannel; //Channel to get data from procesas_00
- private ChannelOutput outputChannel; //Channel with manager to produce items
- public Producer(ChannelInput inputDataChannel,
- ChannelOutput outputChannel){
- this.inputDataChannel = inputDataChannel;
- this.outputChannel = outputChannel;
- }
- @Override
- public void run(){
- //Reads data from procesas_00
- products = (ArrayList<ProducerProducts>) inputDataChannel.read();
- for(ProducerProducts prod : products){
- Action action = new Action();
- action.actionType = ActionType.insert;
- ConsumerProducts consProducts = new ConsumerProducts();
- consProducts.consumer_name = prod.name;
- consProducts.count = prod.count;
- action.data = consProducts;
- outputChannel.write(action);
- }
- Action actionFinished = new Action();
- actionFinished.actionType = ActionType.producerFinished;
- outputChannel.write(actionFinished);
- }
- }
- class Manager implements CSProcess{
- private ChannelInput inputChannel; //Channel for getting data from consumers and producers
- private ChannelOutput outputChannel; //Channel for sending data to procesas_00
- private ArrayList<ChannelOutput> ConsumeResultChannels; //Channel for communicating with consumer about successful read from data array
- private Buffer B; //Common data array
- public Manager(ChannelOutput outputChannel, ChannelInput inputChannel, ArrayList<ChannelOutput> ConsumeResultChannels){
- this.B = new Buffer();
- this.ConsumeResultChannels = new ArrayList<>();
- this.outputChannel = outputChannel;
- this.inputChannel = inputChannel;
- this.ConsumeResultChannels = ConsumeResultChannels;
- }
- @Override
- public void run(){
- while(!(Globals.HaveConsumersFinished() && Globals.HaveProducersFinished()))
- {
- //reads data from any2one channel from consumers and producers
- Action action = (Action) inputChannel.read();
- if(action.actionType == ActionType.insert){
- B.WriteToArray((ConsumerProducts) action.data);
- }
- if(action.actionType == ActionType.remove){
- ConsumerProducts temp = new ConsumerProducts();
- temp = B.ReadFromArray((ConsumerProducts) action.data);
- Action result = new Action();
- result.data = temp;
- ConsumeResultChannels.get(action.processID).write(temp.count);
- }
- if(action.actionType == ActionType.producerFinished){
- Globals.finishedProducers++;
- System.out.println("Producer finished");
- }
- if(action.actionType == ActionType.consumerFinished){
- Globals.finishedConsumers++;
- System.out.println("Consumer finished");
- }
- }
- System.out.println("Manager darbas baigtas");
- //sends final data to procesas_00
- outputChannel.write(B);
- }
- }
- /**
- *
- * @author Aidas
- */
- public class KažukauskasA_L3a {
- public static void main(String[] args) throws Exception {
- One2OneChannel ManagerProcesas00Channel = Channel.one2one(); //Channel for manager and procesas_00 communication
- Any2OneChannel ProcessManagerChannel = Channel.any2one(); //Channel for producers, consumers and manager communication
- ArrayList<One2OneChannel> Procesas00ProducersChannels = new ArrayList<>(); //Channels for procesas_00 and producers communication
- ArrayList<One2OneChannel> Procesas00ConsumersChannels = new ArrayList<>(); //Channels for procesas_00 and consumers communication
- ArrayList<One2OneChannel> ConsumerResultChannels = new ArrayList<>(); //Channels for manager and consumers communication
- ArrayList<ChannelOutput> Procesas00ProducerOutputChannels = new ArrayList<>(); //Output channels for procesas_00 and producers communication
- ArrayList<ChannelOutput> Procesas00ConsumerOutputChannels = new ArrayList<>(); //Output channels for procesas_00 and consumers communication
- ArrayList<ChannelOutput> ConsumerResultOutputChannels = new ArrayList<>(); //Output channels for manager and consumers communication
- ArrayList<CSProcess> process = new ArrayList<>(); //List for processes to be executed
- //Initializing producers and attaching channels to them
- for(int i = 0; i < Globals.ProducersSize; i++){
- One2OneChannel channel = Channel.one2one();
- Procesas00ProducersChannels.add(channel);
- Producer producer = new Producer(channel.in(), ProcessManagerChannel.out());
- process.add(producer);
- }
- //Initializing consumers and attaching channels to them
- for(int i = 0; i < Globals.ConsumersSize; i++){
- One2OneChannel channel = Channel.one2one();
- Procesas00ConsumersChannels.add(channel);
- One2OneChannel resultChannel = Channel.one2one(); // Create result channel to receive data from Manager
- ConsumerResultChannels.add(resultChannel);
- int processID = i;
- Consumer consumer = new Consumer(channel.in(), ProcessManagerChannel.out(), resultChannel.in(), processID);
- process.add(consumer);
- }
- //Creating list of consumer and manager output channels
- ConsumerResultChannels.stream().forEach((resultChannel) -> {
- ConsumerResultOutputChannels.add(resultChannel.out());
- });
- //Initializing manager
- Manager manager = new Manager(ManagerProcesas00Channel.out(), ProcessManagerChannel.in(), ConsumerResultOutputChannels);
- process.add(manager);
- //Creating list of procesas00 and producers output channels
- Procesas00ProducersChannels.stream().forEach((channel) -> {
- Procesas00ProducerOutputChannels.add(channel.out());
- });
- //Creating list of procesas00 and consumers output channels
- Procesas00ConsumersChannels.stream().forEach((channel) -> {
- Procesas00ConsumerOutputChannels.add(channel.out());
- });
- //Initializing procesas_00
- Procesas_00 distributor = new Procesas_00(Procesas00ProducerOutputChannels,
- Procesas00ConsumerOutputChannels, ManagerProcesas00Channel.in());
- process.add(distributor);
- Parallel parallel = new Parallel();
- parallel.addProcess(process.toArray(new CSProcess[process.size()]));
- parallel.run();
- System.out.println("Darbas baigtas!");
- }
- /**
- * Reads one team from file
- * @param br data file reader buffer
- * @param team team's object
- * @throws Exception
- */
- static void Read(ArrayList< ArrayList<ProducerProducts>> P,
- ArrayList< ArrayList<ConsumerProducts>> C) throws Exception{
- String line;
- try (BufferedReader br = new BufferedReader(new FileReader(Globals.dataFile))) {
- // if ((line = br.readLine()) != null) {
- int ProducersSize = 0, ConsumersSize = 0, size = 0;
- //String[] splitString = line.split("\\s+");
- // ProducersSize = Integer.parseInt(splitString[0]);
- for(int i = 0; i < Globals.ProducersSize; i++){
- line = br.readLine();
- String[] splitString = line.split("\\s+");
- ArrayList<ProducerProducts> tempProducer = new ArrayList<>();
- size = Integer.parseInt(splitString[0]);
- for (int j = 0; j < size; j++){
- line = br.readLine();
- splitString = line.split("\\s+");
- ProducerProducts Pproducts = new ProducerProducts();
- Pproducts.name = splitString[0];
- Pproducts.count = Integer.parseInt(splitString[1]);
- Pproducts.avg = Double.parseDouble(splitString[2]);
- tempProducer.add(Pproducts);
- }
- P.add(tempProducer);
- }
- // line = br.readLine();
- // splitString = line.split("\\s+");
- //ConsumersSize = Integer.parseInt(splitString[0]);
- for(int i = 0; i < Globals.ConsumersSize; i++){
- ArrayList<ConsumerProducts> tempConsumer = new ArrayList<>();
- line = br.readLine();
- String[] splitString = line.split("\\s+");
- size = Integer.parseInt(splitString[0]);
- for (int j = 0; j < size; j++){
- line = br.readLine();
- splitString = line.split("\\s+");
- ConsumerProducts Cproducts = new ConsumerProducts();
- Cproducts.consumer_name = splitString[0];
- Cproducts.count = Integer.parseInt(splitString[1]);
- tempConsumer.add(Cproducts);
- }
- C.add(tempConsumer);
- }
- //}
- }
- }
- /**
- * Writes data to results file
- * @param resultsFile results file name
- * @param Producers producers data array
- * @param Consumers consumers data array
- * @param ProducersSize producers array size
- * @param ConsumersSize consumers array size
- */
- static void writeTables(ArrayList< ArrayList<ProducerProducts>> P,
- ArrayList< ArrayList<ConsumerProducts>> C) throws Exception
- {
- BufferedWriter bw = new BufferedWriter(new FileWriter(Globals.resultsFile));
- bw.close();
- try (BufferedWriter file = new BufferedWriter(new FileWriter(Globals.resultsFile, true))) {
- file.write("Producers size: " + Globals.ProducersSize + "\r\n\r\n");
- for (int i = 0; i < Globals.ProducersSize; i++)
- {
- file.write("Producer " + (i+1));
- file.newLine();
- file.write(String.format("%10s %10s %10s \r\n", "Product", "Count", "Price"));
- file.write("---------------------------------\r\n");
- for (int j = 0; j < P.get(i).size(); j++)
- {
- file.write(j+1 + ") ");
- file.write(String.format("%10s %10s %10s \r\n", P.get(i).get(j).name,
- P.get(i).get(j).count, P.get(i).get(j).avg));
- }
- file.newLine();
- }
- file.newLine();
- file.write("---------------------------------\r\n");
- file.write("Consumers size: " + Globals.ProducersSize + "\r\n\r\n");
- for (int i = 0; i < Globals.ConsumersSize; i++)
- {
- file.write("Consumer " + (i+1));
- file.newLine();
- file.write(String.format("%10s %10s \r\n", "Product", "Count"));
- file.write("---------------------------------\r\n");
- for (int j = 0; j < C.get(i).size(); j++)
- {
- file.write(j+1 + ") ");
- file.write(String.format("%10s %10s \r\n", C.get(i).get(j).consumer_name,
- C.get(i).get(j).count));
- }
- file.newLine();
- }
- file.newLine();
- file.flush();
- file.close();
- }
- }
- /**
- * Writes data to results file
- * @param resultsFile results file name
- * @param Producers producers data array
- * @param Consumers consumers data array
- * @param ProducersSize producers array size
- * @param ConsumersSize consumers array size
- */
- static void writeResults(Buffer B) throws Exception
- {
- try (BufferedWriter file = new BufferedWriter(new FileWriter(Globals.resultsFile, true))) {
- ConsumerProducts[] results = B.getItems();
- file.write("Rezultatai:\r\n");
- file.write("Masyvo dydis:" + B.getSize() + "\r\n");
- file.write(String.format("%10s %10s \r\n", "Product", "Count"));
- file.write("---------------------------------\r\n");
- for(int i = 0; i < B.getSize(); i++){
- file.write(String.format("%d %10s %10s\r\n", (i+1), results[i].consumer_name,
- results[i].count));
- }
- file.newLine();
- file.flush();
- file.close();
- }
- }
- }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement