Skip to content

Commit

Permalink
iluwatar#2898 Added more unit tests and refactored code
Browse files Browse the repository at this point in the history
  • Loading branch information
Ehspresso committed Apr 19, 2024
1 parent 7416e1c commit 5e9689e
Show file tree
Hide file tree
Showing 12 changed files with 205 additions and 134 deletions.
22 changes: 7 additions & 15 deletions publisher-subscriber/README.md → publish-subscribe/README.md
Original file line number Diff line number Diff line change
@@ -1,5 +1,5 @@
---
title: Publish-Subscribe pattern
title: Publish-Subscribe
category: Behavioral
language: en
tag:
Expand Down Expand Up @@ -135,7 +135,7 @@ public class TLender {
LOGGER.error("An error has occurred!", e);
}

TLender tLender = new TLender(topicCFName, topicName);
TLender lender = new TLender(topicCFName, topicName);

System.out.println ("TLender Application Started");
System.out.println ("Press enter to quit application");
Expand All @@ -151,11 +151,11 @@ public class TLender {
//Exit if user pressed enter or line is blank
if (line == null || line.trim().length() == 0) {
System.out.println("Exiting...");
tLender.exit();
lender.exit();
}
else { //publish the entered rate
double newRate = Double.parseDouble(line);
tLender.publishRate(newRate);
lender.publishRate(newRate);
}
}
} catch(IOException e) {
Expand Down Expand Up @@ -186,15 +186,6 @@ Initial rate is 6.0
Waiting for new rates...
Press enter to quit application

Running the class:

The class must be run after the TLender class is running since TLender spins up the activeMQ broker.

In order to see the messages being sent to multiple subscribers multiple instance of the TBorrower class need to be run. Either run multiple instances in an IDE or execute the following command in a command line from the root folder after generating the target folder:


mvn exec:java -Dexec.mainClass=com.iluwatar.publishersubscriber.TBorrower -Dexec.args="TopicCF RateTopic 6"

```java
public class TBorrower implements MessageListener {

Expand Down Expand Up @@ -282,7 +273,7 @@ public class TBorrower implements MessageListener {
System.exit(0);
}

TBorrower tBorrower = new TBorrower(topicCF, topicName, rate);
TBorrower borrower = new TBorrower(topicCF, topicName, rate);

try {
// Run until enter is pressed
Expand All @@ -291,7 +282,7 @@ public class TBorrower implements MessageListener {
System.out.println ("TBorrower application started");
System.out.println ("Press enter to quit application");
reader.readLine();
tBorrower.exit();
borrower.exit();
} catch (IOException ioe) {
ioe.printStackTrace();
}
Expand All @@ -316,6 +307,7 @@ public class TBorrower implements MessageListener {
```

## Class diagram
![alt text](./etc/publishsubscribe.urm.png "Publish Subscribe class diagram")

## Applicability

Expand Down
8 changes: 8 additions & 0 deletions publish-subscribe/USAGE.md
Original file line number Diff line number Diff line change
@@ -0,0 +1,8 @@
Running the Borrower class:

The class must be run after the TLender class is running since TLender spins up the activeMQ broker.

In order to see the messages being sent to multiple subscribers multiple instance of the TBorrower class need to be run. Either run multiple instances in an IDE or execute the following command in a command line from the root folder after generating the target folder:


mvn exec:java -Dexec.mainClass=com.iluwatar.publishsubscribe.Borrower -Dexec.args="TopicCF RateTopic 6"
7 changes: 1 addition & 6 deletions publisher-subscriber/pom.xml → publish-subscribe/pom.xml
Original file line number Diff line number Diff line change
Expand Up @@ -35,7 +35,7 @@
<artifactId>java-design-patterns</artifactId>
<version>1.26.0-SNAPSHOT</version>
</parent>
<artifactId>publishersubscriber</artifactId>
<artifactId>publishsubscribe</artifactId>

<dependencies>
<dependency>
Expand All @@ -58,11 +58,6 @@
<artifactId>xbean-spring</artifactId>
<version>4.24</version>
</dependency>
<dependency>
<groupId>log4j</groupId>
<artifactId>log4j</artifactId>
<version>1.2.17</version>
</dependency>
<dependency>
<groupId>org.apache.activemq.tooling</groupId>
<artifactId>activemq-junit</artifactId>
Expand Down
Original file line number Diff line number Diff line change
@@ -1,4 +1,4 @@
package com.iluwatar.publishersubscriber;
package com.iluwatar.publishsubscribe;

import lombok.extern.slf4j.Slf4j;
import javax.jms.BytesMessage;
Expand All @@ -19,14 +19,16 @@
import java.io.InputStreamReader;

@Slf4j
public class TBorrower implements MessageListener {
public class Borrower implements MessageListener {

private TopicConnection tConnection;
private TopicSession tSession;
private Topic topic;
private double currentRate;
private static final String ERROR = "An error has occured!";
private double newRate;

public TBorrower(String topicCFName, String topicName, double initialRate) {
public Borrower(String topicCFName, String topicName, double initialRate) {

currentRate = initialRate;

Expand All @@ -50,44 +52,37 @@ public TBorrower(String topicCFName, String topicName, double initialRate) {
tConnection.start();
System.out.println("Initial rate is " + currentRate + " \nWaiting for new rates...");
} catch(NamingException e) {
e.printStackTrace();
LOGGER.error("An error has occurred!", e);
System.exit(1);
LOGGER.error(ERROR, e);
} catch(JMSException e) {
e.printStackTrace();
LOGGER.error("An error has occurred!", e);
System.exit(1);
LOGGER.error(ERROR, e);
}
}

//This method is called asynchronously by the activeMQ broker
public void onMessage(Message message) {

try {
BytesMessage bMessage = (BytesMessage) message;
double newRate = ((BytesMessage) bMessage).readDouble();
double newRate = bMessage.readDouble();
setNewRate(newRate);

if (currentRate - newRate >= 1)
System.out.println("New Rate is " + newRate + " - Consider refinancing");
else
System.out.println("New Rate is " + newRate + " - Consider keeping current rate");
} catch(JMSException e) {
e.printStackTrace();
LOGGER.error("An error occurred!", e);
System.exit(1);
LOGGER.error(ERROR, e);
}
System.out.println("Waiting for new rates...");
}

private void exit() {
public boolean close() {
try {
tConnection.close();
return true;
} catch(JMSException e) {
e.printStackTrace();
LOGGER.error("An error has occurred!", e);
System.exit(1);
LOGGER.error(ERROR, e);
return false;
}
System.exit(0);
}

public static void main(String[] args) {
Expand All @@ -105,7 +100,7 @@ public static void main(String[] args) {
System.exit(0);
}

TBorrower tBorrower = new TBorrower(topicCF, topicName, rate);
Borrower borrower = new Borrower(topicCF, topicName, rate);

try {
// Run until enter is pressed
Expand All @@ -114,9 +109,10 @@ public static void main(String[] args) {
System.out.println ("TBorrower application started");
System.out.println ("Press enter to quit application");
reader.readLine();
tBorrower.exit();
} catch (IOException ioe) {
ioe.printStackTrace();
borrower.close();
System.exit(0);
} catch (IOException e) {
LOGGER.error(ERROR, e);
}
}

Expand All @@ -135,4 +131,8 @@ public Topic getTopic() {
public double getCurrentRate() {
return currentRate;
}

public double getNewRate() { return newRate; }

private void setNewRate(double newRate) { this.newRate = newRate; }
}
Original file line number Diff line number Diff line change
@@ -1,4 +1,4 @@
package com.iluwatar.publishersubscriber;
package com.iluwatar.publishsubscribe;

import lombok.extern.slf4j.Slf4j;
import org.apache.activemq.broker.BrokerService;
Expand All @@ -14,18 +14,23 @@
import javax.naming.InitialContext;
import javax.naming.NamingException;
import java.io.BufferedReader;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.util.Properties;

@Slf4j
public class TLender {
public class Lender {

private TopicConnection tConnection;
private TopicSession tSession;
private Topic topic;
private TopicPublisher publisher;
private static final String ERROR = "An error has occured!";

public TLender(String topicCFName, String topicName) {
public Lender(String topicCFName, String topicName) {

try {
//create context and retrieve objects from directory
Expand All @@ -44,17 +49,13 @@ public TLender(String topicCFName, String topicName) {

tConnection.start();
} catch(NamingException e) {
e.printStackTrace();
LOGGER.error("An error has occurred!", e);
System.exit(1);
LOGGER.error(ERROR, e);
} catch(JMSException e) {
e.printStackTrace();
LOGGER.error("An error has occurred!", e);
System.exit(1);
LOGGER.error(ERROR, e);
}
}

private void publishRate(double newRate) {
public void publishRate(double newRate) {

try {
//create JMS message
Expand All @@ -64,21 +65,18 @@ private void publishRate(double newRate) {
//publish message
publisher.publish(message);
} catch(JMSException e) {
e.printStackTrace();
LOGGER.error("An error has occurred!", e);
System.exit(1);
LOGGER.error(ERROR, e);
}
}

private void exit() {
public boolean close() {
try {
tConnection.close();
return true;
} catch(JMSException e) {
e.printStackTrace();
LOGGER.error("An error has occurred!", e);
System.exit(1);
LOGGER.error(ERROR, e);
return false;
}
System.exit(0);
}

public static void main(String[] args) {
Expand All @@ -90,26 +88,35 @@ public static void main(String[] args) {
topicCFName = args[0];
topicName = args[1];
} else {
System.out.println("Invalid arguments. Should be: ");
System.out.println("java TLender [factory] [topic]");
LOGGER.info("Invalid arguments. Should be: ");
LOGGER.info("java TLender [factory] [topic]");
System.exit(1);
}

try {
//Get configuration properties
Properties props = new Properties();
InputStream in = new FileInputStream("publish-subscribe/src/main/resources/config.properties");
props.load(in);
in.close();

// Create and start activeMQ broker. Broker decouples publishers and subscribers.
//Additionally brokers manage threads and asynchronous sending and receiving of messages.
// Additionally brokers manage threads and asynchronous sending and receiving of messages.
BrokerService broker = new BrokerService();
broker.addConnector("tcp://localhost:61616");
broker.addConnector(props.getProperty("ADDRESS"));
broker.start();

} catch(FileNotFoundException e) {
LOGGER.error(ERROR, e);
} catch(IOException e) {
LOGGER.error(ERROR, e);
} catch(Exception e) {
e.printStackTrace();
LOGGER.error("An error has occurred!", e);
LOGGER.error(ERROR, e);
}

TLender tLender = new TLender(topicCFName, topicName);
Lender lender = new Lender(topicCFName, topicName);

System.out.println ("TLender Application Started");
LOGGER.info("TLender Application Started");
System.out.println ("Press enter to quit application");
System.out.println ("Enter: Rate");
System.out.println("\ne.g. 6.8");
Expand All @@ -123,16 +130,16 @@ public static void main(String[] args) {
//Exit if user pressed enter or line is blank
if (line == null || line.trim().length() == 0) {
System.out.println("Exiting...");
tLender.exit();
lender.close();
System.exit(0);
}
else { //publish the entered rate
double newRate = Double.parseDouble(line);
tLender.publishRate(newRate);
lender.publishRate(newRate);
}
}
} catch(IOException e) {
e.printStackTrace();
LOGGER.error("An error has occurred!", e);
LOGGER.error(ERROR, e);
}
}

Expand Down
1 change: 1 addition & 0 deletions publish-subscribe/src/main/resources/config.properties
Original file line number Diff line number Diff line change
@@ -0,0 +1 @@
ADDRESS=tcp://localhost:61616
Loading

0 comments on commit 5e9689e

Please sign in to comment.