Advertisement
Guest User

Untitled

a guest
Jan 21st, 2017
86
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
text 21.75 KB | None | 0 0
  1. package kažukauskasa_l3a;
  2.  
  3. import java.io.BufferedReader;
  4. import java.io.BufferedWriter;
  5. import java.io.FileReader;
  6. import java.io.FileWriter;
  7. import org.jcsp.lang.*;
  8. import java.util.ArrayList;
  9. import java.util.logging.Level;
  10. import java.util.logging.Logger;
  11.  
  12. class Globals
  13. {
  14. public static final int productsSize = 100;
  15. public static int ConsumersSize = 5,
  16. ProducersSize = 5,
  17. finishedProducers = 0,
  18. finishedConsumers = 0;
  19. public static final String dataFile = "KazukauskasMindaugas_L3_dat_1.txt"; // Pasalinami visi
  20. //public static final String dataFile = "KazukauskasMindaugas_L3_dat_2.txt"; // Nepasalina nei vieno
  21. //public static final String dataFile = "KazukauskasMindaugas_L3_dat_3"; // Pasalina tik dali
  22. public static final String resultsFile = "KazukauskasMindaugas_L3_rez.txt";
  23. public static boolean HaveProducersFinished(){
  24. return finishedProducers == ProducersSize;
  25. }
  26. public static boolean HaveConsumersFinished(){
  27. return finishedConsumers == ConsumersSize;
  28. }
  29. }
  30. //Action types for channels' communaction
  31. enum ActionType {
  32. insert, remove, producerFinished, consumerFinished
  33. }
  34.  
  35. //Class for keeping transfering data via channels
  36. class Action{
  37. public Object data;
  38. public ActionType actionType;
  39. public int processID = -1;
  40. }
  41.  
  42. /*
  43. * Class contains producer type products
  44. */
  45. class ProducerProducts
  46. {
  47. public String name;
  48. public int count;
  49. public double avg;
  50. public ProducerProducts()
  51. {
  52. name = "";
  53. count = 0;
  54. avg = 0.0;
  55. }
  56. }
  57. /*
  58. * Class contains consumer type products
  59. */
  60. class ConsumerProducts
  61. {
  62. public String consumer_name;
  63. public int count;
  64. public ConsumerProducts()
  65. {
  66. consumer_name = "";
  67. count = 0;
  68. }
  69. }
  70.  
  71. /*
  72. * Common array class
  73. */
  74. class Buffer
  75. {
  76. private ConsumerProducts[] B = new ConsumerProducts[Globals.productsSize];
  77. private int size;
  78.  
  79. public Buffer()
  80. {
  81. for (int i = 0; i < Globals.productsSize; i++)
  82. {
  83. B[i] = new ConsumerProducts();
  84. }
  85. size = 0;
  86. }
  87.  
  88. /**
  89. * Returns product name at index location
  90. * @param index product location in common array
  91. */
  92. public ConsumerProducts[] getItems() { return B; }
  93.  
  94. /**
  95. * Increments finished producers count
  96. */
  97. public int getSize() { return size; }
  98.  
  99. /**
  100. * Checks if product exists in common array
  101. * @param name product name
  102. */
  103. public int ifExists(String name)
  104. {
  105.  
  106. int index = -1;
  107. for (int i = 0; i < size; i++)
  108. {
  109. if (name.compareTo(B[i].consumer_name) == 0) //if finds in array
  110. {
  111. index = i;
  112. break;
  113. }
  114. }
  115. return index;
  116. }
  117.  
  118. public void WriteToArray(ConsumerProducts product)
  119. {
  120. int index = ifExists(product.consumer_name);
  121. if (index == -1)
  122. {
  123. index = RequestInsertIndex(product.consumer_name);
  124. insert(product.consumer_name, product.count, index);
  125. }
  126. else
  127. {
  128. B[index].count += product.count;
  129. }
  130. }
  131. // Grąžina, kiek masyve yra elementų.
  132. public ConsumerProducts ReadFromArray(ConsumerProducts product){
  133. ConsumerProducts temp = new ConsumerProducts();
  134. temp.consumer_name = product.consumer_name;
  135. temp.count = product.count;
  136. int index = ifExists(temp.consumer_name);
  137. if(index != -1){
  138. if (B[index].count <= temp.count){
  139. temp.count = temp.count - B[index].count;
  140. B[index].count = 0;
  141. }
  142. if (B[index].count > temp.count){
  143. B[index].count -= temp.count;
  144. temp.count = 0;
  145. }
  146. if (B[index].count == 0){
  147. remove(index);
  148. }
  149. }
  150. return temp;
  151. }
  152.  
  153. /**
  154. * Removes product from common array at index location
  155. * @param index product index in common array
  156. */
  157. public void remove(int index)
  158. {
  159. if (index == size - 1)
  160. {
  161. B[index].consumer_name = "";
  162. B[index].count = 0;
  163. }
  164. else
  165. {
  166. for (int i = index; i < size; i++)
  167. {
  168. B[i] = B[i + 1];
  169. }
  170. B[size - 1].consumer_name = "";
  171. B[size - 1].count = 0;
  172. }
  173. --size;
  174. }
  175. /**
  176. * Inserts product to index location in common array
  177. * @param name product name
  178. * @param index index to where insert product
  179. */
  180. public void insert(String name, int count, int index)
  181. {
  182. ConsumerProducts temp = new ConsumerProducts();
  183. temp.consumer_name = name;
  184. temp.count = count;
  185. size++;
  186. if (size == 1)
  187. {
  188. B[index] = temp;
  189. }
  190. else
  191. {
  192. for (int i = size; i > index + 1; i--)
  193. {
  194. B[i - 1] = B[i - 2];
  195. }
  196. B[index] = temp;
  197. }
  198. }
  199.  
  200. /**
  201. * Gets product index from common array
  202. * @param name product name
  203. */
  204. public int RequestInsertIndex(String name)
  205. {
  206. int index = -1;
  207. if (size == 0) return 0;
  208. if (size == 1)
  209. if (name.compareTo(B[0].consumer_name) > 0)
  210. return 1;
  211. else return 0;
  212. if (name.compareTo(B[size - 1].consumer_name) > 0)
  213. return size;
  214. for (int i = 0; i < size; i++)
  215. {
  216. if (name.compareTo(B[i].consumer_name) < 0)
  217. {
  218. index = i;
  219. return index;
  220. }
  221. }
  222. return index;
  223. }
  224. }
  225. //Procesas_00 class
  226. class Procesas_00 implements CSProcess {
  227. private ArrayList< ArrayList<ProducerProducts> > P; //Producers' data
  228. private ArrayList< ArrayList<ConsumerProducts> > C; //Consumers' data
  229. private ArrayList<ChannelOutput> ProducersChannels; //Channels for communicating with producers
  230. private ArrayList<ChannelOutput> ConsumersChannels; //Channels for communicating with consumers
  231. private ChannelInput ResultsChannel; //Channel for receiving final array for printing
  232.  
  233. public Procesas_00(ArrayList<ChannelOutput> ProducersChannels,
  234. ArrayList<ChannelOutput> ConsumersChannels,
  235. ChannelInput ResultsChannel)
  236. {
  237. this.P = new ArrayList<>();
  238. this.C = new ArrayList<>();
  239. this.ProducersChannels = ProducersChannels;
  240. this.ConsumersChannels = ConsumersChannels;
  241. this.ResultsChannel = ResultsChannel;
  242. }
  243.  
  244. @Override
  245. public void run(){
  246. try {
  247. //Gets data from file
  248. KažukauskasA_L3a.Read(P, C);
  249. } catch (Exception ex) {
  250. Logger.getLogger(KažukauskasA_L3a.class.getName()).log(Level.SEVERE, null, ex);
  251. }
  252. try {
  253. //Writes original data to results file
  254. KažukauskasA_L3a.writeTables(P, C);
  255. } catch (Exception ex) {
  256. Logger.getLogger(KažukauskasA_L3a.class.getName()).log(Level.SEVERE, null, ex);
  257. }
  258. //Distributes data to all producers
  259. for(int i = 0; i < P.size(); i++){
  260. ProducersChannels.get(i).write(P.get(i));
  261. }
  262. //Distributes data to all consumers
  263. for(int i = 0; i < C.size(); i++){
  264. ConsumersChannels.get(i).write(C.get(i));
  265. }
  266. //Reads final array data from manager process
  267. Buffer B = (Buffer) ResultsChannel.read();
  268. try {
  269. //Prints final array to results file
  270. KažukauskasA_L3a.writeResults(B);
  271. } catch (Exception ex) {}
  272. System.out.println("Distributor darbas baigtas");
  273. }
  274. }
  275. //Consumer class
  276. class Consumer implements CSProcess {
  277. private int processID; //saves consumer's process id
  278. private ArrayList<ConsumerProducts> products = new ArrayList<ConsumerProducts>(); //Saves which data to consume
  279. private ChannelInput inputDataChannel, //Channel to get data from procesas_00
  280. ConsumeResultChannel; //Channel to get info from manager about successful read from array
  281. private ChannelOutput outputChannel; //Channel with manager to consume items
  282.  
  283. public Consumer(ChannelInput inputDataChannel,
  284. ChannelOutput outputChannel, ChannelInput ConsumeResultChannel, int processID){
  285. this.inputDataChannel = inputDataChannel;
  286. this.outputChannel = outputChannel;
  287. this.ConsumeResultChannel = ConsumeResultChannel;
  288. this.processID = processID;
  289. }
  290.  
  291. @Override
  292. public void run(){
  293. //Reads data from procesas_00
  294. products = (ArrayList<ConsumerProducts>) inputDataChannel.read();
  295. int result, i = 0;
  296. while(products.size() > 0)
  297. {
  298. Action action = new Action();
  299. action.actionType = ActionType.remove;
  300. ConsumerProducts consProducts = new ConsumerProducts();
  301. consProducts.consumer_name = products.get(i).consumer_name;
  302. consProducts.count = products.get(i).count;
  303. action.data = consProducts;
  304. action.processID = processID;
  305. outputChannel.write(action);
  306. result = (int) ConsumeResultChannel.read();
  307. if(result == 0){
  308. products.remove(i);
  309. }
  310. else if (!Globals.HaveProducersFinished()){
  311. products.get(i).count = result;
  312. }
  313. else products.remove(i);
  314. if(i >= products.size()-1)
  315. i=0;
  316. else i++;
  317. }
  318. Action actionFinished = new Action();
  319. actionFinished.actionType = ActionType.consumerFinished;
  320. outputChannel.write(actionFinished);
  321. }
  322. }
  323. //Producer class
  324. class Producer implements CSProcess {
  325. private static ArrayList<ProducerProducts> products; //Saves which data to produce
  326. private ChannelInput inputDataChannel; //Channel to get data from procesas_00
  327. private ChannelOutput outputChannel; //Channel with manager to produce items
  328.  
  329. public Producer(ChannelInput inputDataChannel,
  330. ChannelOutput outputChannel){
  331. this.inputDataChannel = inputDataChannel;
  332. this.outputChannel = outputChannel;
  333. }
  334.  
  335. @Override
  336. public void run(){
  337. //Reads data from procesas_00
  338. products = (ArrayList<ProducerProducts>) inputDataChannel.read();
  339. for(ProducerProducts prod : products){
  340. Action action = new Action();
  341. action.actionType = ActionType.insert;
  342. ConsumerProducts consProducts = new ConsumerProducts();
  343. consProducts.consumer_name = prod.name;
  344. consProducts.count = prod.count;
  345. action.data = consProducts;
  346. outputChannel.write(action);
  347. }
  348. Action actionFinished = new Action();
  349. actionFinished.actionType = ActionType.producerFinished;
  350. outputChannel.write(actionFinished);
  351. }
  352. }
  353.  
  354. class Manager implements CSProcess{
  355. private ChannelInput inputChannel; //Channel for getting data from consumers and producers
  356. private ChannelOutput outputChannel; //Channel for sending data to procesas_00
  357. private ArrayList<ChannelOutput> ConsumeResultChannels; //Channel for communicating with consumer about successful read from data array
  358. private Buffer B; //Common data array
  359.  
  360. public Manager(ChannelOutput outputChannel, ChannelInput inputChannel, ArrayList<ChannelOutput> ConsumeResultChannels){
  361. this.B = new Buffer();
  362. this.ConsumeResultChannels = new ArrayList<>();
  363. this.outputChannel = outputChannel;
  364. this.inputChannel = inputChannel;
  365. this.ConsumeResultChannels = ConsumeResultChannels;
  366. }
  367.  
  368. @Override
  369. public void run(){
  370. while(!(Globals.HaveConsumersFinished() && Globals.HaveProducersFinished()))
  371. {
  372. //reads data from any2one channel from consumers and producers
  373. Action action = (Action) inputChannel.read();
  374. if(action.actionType == ActionType.insert){
  375. B.WriteToArray((ConsumerProducts) action.data);
  376. }
  377.  
  378. if(action.actionType == ActionType.remove){
  379. ConsumerProducts temp = new ConsumerProducts();
  380. temp = B.ReadFromArray((ConsumerProducts) action.data);
  381. Action result = new Action();
  382. result.data = temp;
  383. ConsumeResultChannels.get(action.processID).write(temp.count);
  384. }
  385.  
  386. if(action.actionType == ActionType.producerFinished){
  387. Globals.finishedProducers++;
  388. System.out.println("Producer finished");
  389. }
  390.  
  391. if(action.actionType == ActionType.consumerFinished){
  392. Globals.finishedConsumers++;
  393. System.out.println("Consumer finished");
  394. }
  395.  
  396. }
  397. System.out.println("Manager darbas baigtas");
  398. //sends final data to procesas_00
  399. outputChannel.write(B);
  400. }
  401. }
  402.  
  403. /**
  404. *
  405. * @author Aidas
  406. */
  407. public class KažukauskasA_L3a {
  408. public static void main(String[] args) throws Exception {
  409. One2OneChannel ManagerProcesas00Channel = Channel.one2one(); //Channel for manager and procesas_00 communication
  410. Any2OneChannel ProcessManagerChannel = Channel.any2one(); //Channel for producers, consumers and manager communication
  411.  
  412. ArrayList<One2OneChannel> Procesas00ProducersChannels = new ArrayList<>(); //Channels for procesas_00 and producers communication
  413. ArrayList<One2OneChannel> Procesas00ConsumersChannels = new ArrayList<>(); //Channels for procesas_00 and consumers communication
  414. ArrayList<One2OneChannel> ConsumerResultChannels = new ArrayList<>(); //Channels for manager and consumers communication
  415. ArrayList<ChannelOutput> Procesas00ProducerOutputChannels = new ArrayList<>(); //Output channels for procesas_00 and producers communication
  416. ArrayList<ChannelOutput> Procesas00ConsumerOutputChannels = new ArrayList<>(); //Output channels for procesas_00 and consumers communication
  417. ArrayList<ChannelOutput> ConsumerResultOutputChannels = new ArrayList<>(); //Output channels for manager and consumers communication
  418.  
  419. ArrayList<CSProcess> process = new ArrayList<>(); //List for processes to be executed
  420. //Initializing producers and attaching channels to them
  421. for(int i = 0; i < Globals.ProducersSize; i++){
  422. One2OneChannel channel = Channel.one2one();
  423. Procesas00ProducersChannels.add(channel);
  424. Producer producer = new Producer(channel.in(), ProcessManagerChannel.out());
  425. process.add(producer);
  426. }
  427. //Initializing consumers and attaching channels to them
  428. for(int i = 0; i < Globals.ConsumersSize; i++){
  429. One2OneChannel channel = Channel.one2one();
  430. Procesas00ConsumersChannels.add(channel);
  431. One2OneChannel resultChannel = Channel.one2one(); // Create result channel to receive data from Manager
  432. ConsumerResultChannels.add(resultChannel);
  433. int processID = i;
  434. Consumer consumer = new Consumer(channel.in(), ProcessManagerChannel.out(), resultChannel.in(), processID);
  435. process.add(consumer);
  436. }
  437. //Creating list of consumer and manager output channels
  438. ConsumerResultChannels.stream().forEach((resultChannel) -> {
  439. ConsumerResultOutputChannels.add(resultChannel.out());
  440. });
  441. //Initializing manager
  442. Manager manager = new Manager(ManagerProcesas00Channel.out(), ProcessManagerChannel.in(), ConsumerResultOutputChannels);
  443. process.add(manager);
  444. //Creating list of procesas00 and producers output channels
  445. Procesas00ProducersChannels.stream().forEach((channel) -> {
  446. Procesas00ProducerOutputChannels.add(channel.out());
  447. });
  448. //Creating list of procesas00 and consumers output channels
  449. Procesas00ConsumersChannels.stream().forEach((channel) -> {
  450. Procesas00ConsumerOutputChannels.add(channel.out());
  451. });
  452. //Initializing procesas_00
  453. Procesas_00 distributor = new Procesas_00(Procesas00ProducerOutputChannels,
  454. Procesas00ConsumerOutputChannels, ManagerProcesas00Channel.in());
  455. process.add(distributor);
  456.  
  457. Parallel parallel = new Parallel();
  458. parallel.addProcess(process.toArray(new CSProcess[process.size()]));
  459. parallel.run();
  460. System.out.println("Darbas baigtas!");
  461. }
  462.  
  463. /**
  464. * Reads one team from file
  465. * @param br data file reader buffer
  466. * @param team team's object
  467. * @throws Exception
  468. */
  469. static void Read(ArrayList< ArrayList<ProducerProducts>> P,
  470. ArrayList< ArrayList<ConsumerProducts>> C) throws Exception{
  471. String line;
  472. try (BufferedReader br = new BufferedReader(new FileReader(Globals.dataFile))) {
  473. // if ((line = br.readLine()) != null) {
  474. int ProducersSize = 0, ConsumersSize = 0, size = 0;
  475. //String[] splitString = line.split("\\s+");
  476. // ProducersSize = Integer.parseInt(splitString[0]);
  477. for(int i = 0; i < Globals.ProducersSize; i++){
  478. line = br.readLine();
  479. String[] splitString = line.split("\\s+");
  480. ArrayList<ProducerProducts> tempProducer = new ArrayList<>();
  481. size = Integer.parseInt(splitString[0]);
  482. for (int j = 0; j < size; j++){
  483. line = br.readLine();
  484. splitString = line.split("\\s+");
  485. ProducerProducts Pproducts = new ProducerProducts();
  486. Pproducts.name = splitString[0];
  487. Pproducts.count = Integer.parseInt(splitString[1]);
  488. Pproducts.avg = Double.parseDouble(splitString[2]);
  489.  
  490. tempProducer.add(Pproducts);
  491. }
  492. P.add(tempProducer);
  493. }
  494.  
  495. // line = br.readLine();
  496. // splitString = line.split("\\s+");
  497. //ConsumersSize = Integer.parseInt(splitString[0]);
  498. for(int i = 0; i < Globals.ConsumersSize; i++){
  499. ArrayList<ConsumerProducts> tempConsumer = new ArrayList<>();
  500. line = br.readLine();
  501. String[] splitString = line.split("\\s+");
  502. size = Integer.parseInt(splitString[0]);
  503. for (int j = 0; j < size; j++){
  504. line = br.readLine();
  505. splitString = line.split("\\s+");
  506. ConsumerProducts Cproducts = new ConsumerProducts();
  507. Cproducts.consumer_name = splitString[0];
  508. Cproducts.count = Integer.parseInt(splitString[1]);
  509.  
  510. tempConsumer.add(Cproducts);
  511. }
  512. C.add(tempConsumer);
  513. }
  514. //}
  515. }
  516. }
  517.  
  518. /**
  519. * Writes data to results file
  520. * @param resultsFile results file name
  521. * @param Producers producers data array
  522. * @param Consumers consumers data array
  523. * @param ProducersSize producers array size
  524. * @param ConsumersSize consumers array size
  525. */
  526. static void writeTables(ArrayList< ArrayList<ProducerProducts>> P,
  527. ArrayList< ArrayList<ConsumerProducts>> C) throws Exception
  528. {
  529. BufferedWriter bw = new BufferedWriter(new FileWriter(Globals.resultsFile));
  530. bw.close();
  531. try (BufferedWriter file = new BufferedWriter(new FileWriter(Globals.resultsFile, true))) {
  532. file.write("Producers size: " + Globals.ProducersSize + "\r\n\r\n");
  533.  
  534. for (int i = 0; i < Globals.ProducersSize; i++)
  535. {
  536. file.write("Producer " + (i+1));
  537. file.newLine();
  538. file.write(String.format("%10s %10s %10s \r\n", "Product", "Count", "Price"));
  539. file.write("---------------------------------\r\n");
  540. for (int j = 0; j < P.get(i).size(); j++)
  541. {
  542. file.write(j+1 + ") ");
  543. file.write(String.format("%10s %10s %10s \r\n", P.get(i).get(j).name,
  544. P.get(i).get(j).count, P.get(i).get(j).avg));
  545. }
  546. file.newLine();
  547. }
  548. file.newLine();
  549. file.write("---------------------------------\r\n");
  550. file.write("Consumers size: " + Globals.ProducersSize + "\r\n\r\n");
  551.  
  552. for (int i = 0; i < Globals.ConsumersSize; i++)
  553. {
  554. file.write("Consumer " + (i+1));
  555. file.newLine();
  556. file.write(String.format("%10s %10s \r\n", "Product", "Count"));
  557. file.write("---------------------------------\r\n");
  558. for (int j = 0; j < C.get(i).size(); j++)
  559. {
  560. file.write(j+1 + ") ");
  561. file.write(String.format("%10s %10s \r\n", C.get(i).get(j).consumer_name,
  562. C.get(i).get(j).count));
  563. }
  564. file.newLine();
  565. }
  566. file.newLine();
  567. file.flush();
  568. file.close();
  569. }
  570. }
  571.  
  572. /**
  573. * Writes data to results file
  574. * @param resultsFile results file name
  575. * @param Producers producers data array
  576. * @param Consumers consumers data array
  577. * @param ProducersSize producers array size
  578. * @param ConsumersSize consumers array size
  579. */
  580. static void writeResults(Buffer B) throws Exception
  581. {
  582. try (BufferedWriter file = new BufferedWriter(new FileWriter(Globals.resultsFile, true))) {
  583.  
  584. ConsumerProducts[] results = B.getItems();
  585. file.write("Rezultatai:\r\n");
  586. file.write("Masyvo dydis:" + B.getSize() + "\r\n");
  587. file.write(String.format("%10s %10s \r\n", "Product", "Count"));
  588. file.write("---------------------------------\r\n");
  589. for(int i = 0; i < B.getSize(); i++){
  590. file.write(String.format("%d %10s %10s\r\n", (i+1), results[i].consumer_name,
  591. results[i].count));
  592. }
  593. file.newLine();
  594. file.flush();
  595. file.close();
  596. }
  597. }
  598.  
  599. }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement