SlideShare a Scribd company logo
1 of 13
Download to read offline
Include: Modularity using design patterns, Fault tolerance and Component based development in
the below java program.
import java.awt.BorderLayout;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.io.PrintWriter;
import java.lang.reflect.Member;
import java.net.ServerSocket;
import java.net.Socket;
import java.util.ArrayList;
import java.util.List;
import java.util.HashMap;
import java.util.Map;
import java.util.UUID;
import javax.swing.JButton;
import javax.swing.JFrame;
import javax.swing.JLabel;
import javax.swing.JOptionPane;
import javax.swing.JPanel;
import javax.swing.JTextField;
import MemberDetails.Observer;
import MemberDetails.Subject;
public class MemberServer {
private JFrame frame;
private JTextField idField;
private JTextField ipField;
private JTextField portField;
private JLabel statusLabel;
private static ServerSocket serverSocket;
private boolean isRunning;
private List<Member> members = new ArrayList<>();
public interface ServerInterface {
void startServer();
}
// Frame 1
public MemberServer() {
frame = new JFrame("Member Server");
frame.setLayout(new BorderLayout());
JPanel panel = new JPanel();
panel.setLayout(null);
JLabel idLabel = new JLabel("ID:");
idLabel.setBounds(10, 10, 100, 25);
panel.add(idLabel);
idField = new JTextField();
idField.setBounds(120, 10, 165, 25);
panel.add(idField);
JLabel ipLabel = new JLabel("IP Address:");
ipLabel.setBounds(10, 40, 100, 25);
panel.add(ipLabel);
ipField = new JTextField();
ipField.setBounds(120, 40, 165, 25);
panel.add(ipField);
JLabel portLabel = new JLabel("Port:");
portLabel.setBounds(10, 70, 100, 25);
panel.add(portLabel);
portField = new JTextField();
portField.setBounds(120, 70, 165, 25);
panel.add(portField);
// Start Server Button
JButton startButton = new JButton("Start Server");
startButton.setBounds(50, 110, 125, 25);
startButton.addActionListener(new ActionListener() {
@Override
public void actionPerformed(ActionEvent e) {
Frame2 frame = new Frame2();
frame.setVisible(true);
frame.setSize(500, 200);
frame.setResizable(false);
startServer();
}
});
panel.add(startButton);
// Quit Button
JButton quitButton = new JButton("Quit");
quitButton.setBounds(200, 110, 125, 25);
;
quitButton.addActionListener(new ActionListener() {
@Override
public void actionPerformed(ActionEvent e) {
System.exit(0);
}
});
panel.add(quitButton);
statusLabel = new JLabel();
statusLabel.setBounds(10, 140, 275, 25);
panel.add(statusLabel);
frame.add(panel, BorderLayout.CENTER);
frame.pack();
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
frame.setVisible(true);
frame.setSize(500, 200);
frame.setResizable(false);
}
// Frame 2
public class Frame2 extends JFrame {
public Frame2() {
setTitle("Member Server P2");
setSize(500, 200);
setLocationRelativeTo(null);
setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
}
}
// Start Server
private void startServer() {
String id = idField.getText();
String ip = ipField.getText();
int port = Integer.parseInt(portField.getText());
if (id.isEmpty() || ip.isEmpty() || port <= 0) {
statusLabel.setText("Please enter a valid ID, IP address, and port.");
return;
}
String uniqueId = UUID.randomUUID().toString();
statusLabel.setText("Server started with ID: " + uniqueId);
isRunning = true;
new Thread(new Runnable() {
@Override
public void run() {
try {
ServerSocket serverSocket = new ServerSocket(port);
while (isRunning) {
Socket socket = serverSocket.accept();
// process incoming connection from member
BufferedReader in = new BufferedReader(new InputStreamReader(socket.getInputStream()));
String id = in.readLine();
String ip = socket.getInetAddress().getHostAddress();
int port = socket.getPort();
// add member to server
Member member = new Member(id, ip, port);
members.add(member);
System.out.println("Member " + id + "has joined the server");
}
} catch (IOException e) {
statusLabel.setText("Error starting server: " + e.getMessage());
}
}
}).start();
}
public interface Subject {
void registerObserver(Observer observer);
void removeObserver(Observer observer);
void notifyObservers();
}
public class Server implements Subject {
private List<Member> members = new ArrayList<>();
private List<Observer> observers = new ArrayList<>();
private Member coordinator;
@Override
public void registerObserver(Observer observer) {
observers.add(observer);
}
@Override
public void removeObserver(Observer observer) {
observers.remove(observer);
}
@Override
public void notifyObservers() {
for (Observer observer : observers) {
observer.notifyUpdate();
}
}
public void addMember(Member member) {
if (members.isEmpty()) {
coordinator = member;
coordinator.informCoordinator();
} else {
member.receiveMembers(getMemberDetails());
broadcastMessage(member.getName() + " has joined the group.");
}
members.add(member);
notifyObservers();
}
public void removeMember(Member member) {
members.remove(member);
if (member.equals(coordinator)) {
coordinator = null;
electNewCoordinator();
notifyObservers();
}
broadcastMessage(member.getName() + " has left the group.");
}
private void electNewCoordinator() {
if (members.size() > 0) {
coordinator = members.get(0);
broadcastMessage(coordinator.getName() + " is now the new coordinator.");
coordinator.informCoordinator();
}
}
public List<Member> getMembers() {
return members;
}
private Map<String, MemberDetails> getMemberDetails() {
Map<String, MemberDetails> memberDetails = new HashMap<>();
for (Member member : members) {
memberDetails.put(member.getName(), new MemberDetails(member.getIpAddress(),
member.getPort()));
}
return memberDetails;
}
}
public void broadcastMessage(String message) {
for (Member member : members) {
member.receiveBroadcastMessage(message);
}
}
public void sendPrivateMessage(Member sender, String recipientName, String message) {
for (Member member : members) {
if (member.getName().equals(recipientName)) {
member.receivePrivateMessage(sender.getName(), message);
return;
}
}
}
public void handleUnresponsiveMember(Member member) {
members.remove(member);
broadcastMessage(member.getName() + " is unresponsive.");
}
}
public interface Observer {
void notifyUpdate();
}
// Setters and getters
public class Member implements Observer {
private String name;
private String ipAddress;
private int port;
private Server server;
public Member(String name, String ipAddress, int port) {
this.name = name;
this.ipAddress = ipAddress;
this.port = port;
}
@Override
public void notifyUpdate() {
System.out.println("The server has been updated.");
}
public void joinGroup(Server server) {
server.addMember(this);
}
public void leaveGroup(Server server) {
server.removeMember(this);
}
public void receiveMembers(Map<String, MemberDetails> memberDetails) {
members.clear();
members.addAll(memberDetails.values());
}
public void informCoordinator() {
System.out.println("I am the new coordinator.");
}
public void receiveBroadcastMessage(String message) {
System.out.println("[" + name + "] " + message);
}
public void receivePrivateMessage(String senderName, String message) {
System.out.println("[Private message from " + senderName + " to " + name + "] " + message);
}
public String getName() {
return name;
}
public String getIpAddress() {
return ipAddress;
}
public int getPort() {
return port;
}
}
class MemberDetails {
private String ipAddress;
private int port;
public MemberDetails(String ipAddress, int port) {
this.ipAddress = ipAddress;
this.port = port;
}
public String getIpAddress() {
return ipAddress;
}
public int getPort() {
return port;
}
public static void main(String[] args) {
new MemberServer();
}
}

More Related Content

Similar to Include- Modularity using design patterns- Fault tolerance and Compone.pdf

I need you to modify and change the loop in this code without changing.docx
I need you to modify and change the loop in this code without changing.docxI need you to modify and change the loop in this code without changing.docx
I need you to modify and change the loop in this code without changing.docx
hendriciraida
 
Need help on creating code using cart. The output has to show multip.pdf
Need help on creating code using cart. The output has to show multip.pdfNeed help on creating code using cart. The output has to show multip.pdf
Need help on creating code using cart. The output has to show multip.pdf
meerobertsonheyde608
 
Laporan multi client
Laporan multi clientLaporan multi client
Laporan multi client
ichsanbarokah
 
package net.codejava.swing.mail;import java.awt.Font;import java.pdf
package net.codejava.swing.mail;import java.awt.Font;import java.pdfpackage net.codejava.swing.mail;import java.awt.Font;import java.pdf
package net.codejava.swing.mail;import java.awt.Font;import java.pdf
sudhirchourasia86
 
Note Use Java Write a web server that is capable of processing only.pdf
Note Use Java Write a web server that is capable of processing only.pdfNote Use Java Write a web server that is capable of processing only.pdf
Note Use Java Write a web server that is capable of processing only.pdf
fatoryoutlets
 
JJUG CCC 2011 Spring
JJUG CCC 2011 SpringJJUG CCC 2011 Spring
JJUG CCC 2011 Spring
Kiyotaka Oku
 
ikh331-06-distributed-programming
ikh331-06-distributed-programmingikh331-06-distributed-programming
ikh331-06-distributed-programming
Anung Ariwibowo
 

Similar to Include- Modularity using design patterns- Fault tolerance and Compone.pdf (20)

I need you to modify and change the loop in this code without changing.docx
I need you to modify and change the loop in this code without changing.docxI need you to modify and change the loop in this code without changing.docx
I need you to modify and change the loop in this code without changing.docx
 
Hi, I need some one to help me with Design a client-server Chat so.pdf
Hi, I need some one to help me with Design a client-server Chat so.pdfHi, I need some one to help me with Design a client-server Chat so.pdf
Hi, I need some one to help me with Design a client-server Chat so.pdf
 
JavaExamples
JavaExamplesJavaExamples
JavaExamples
 
Socket Programming
Socket ProgrammingSocket Programming
Socket Programming
 
Protocol-Oriented Networking
Protocol-Oriented NetworkingProtocol-Oriented Networking
Protocol-Oriented Networking
 
Need help on creating code using cart. The output has to show multip.pdf
Need help on creating code using cart. The output has to show multip.pdfNeed help on creating code using cart. The output has to show multip.pdf
Need help on creating code using cart. The output has to show multip.pdf
 
java sockets
 java sockets java sockets
java sockets
 
Laporan multi client
Laporan multi clientLaporan multi client
Laporan multi client
 
package net.codejava.swing.mail;import java.awt.Font;import java.pdf
package net.codejava.swing.mail;import java.awt.Font;import java.pdfpackage net.codejava.swing.mail;import java.awt.Font;import java.pdf
package net.codejava.swing.mail;import java.awt.Font;import java.pdf
 
Laporan tugas network programming
Laporan tugas network programmingLaporan tugas network programming
Laporan tugas network programming
 
Note Use Java Write a web server that is capable of processing only.pdf
Note Use Java Write a web server that is capable of processing only.pdfNote Use Java Write a web server that is capable of processing only.pdf
Note Use Java Write a web server that is capable of processing only.pdf
 
Manual tecnic sergi_subirats
Manual tecnic sergi_subiratsManual tecnic sergi_subirats
Manual tecnic sergi_subirats
 
Lesson_07_Spring_Security_Register_NEW.pdf
Lesson_07_Spring_Security_Register_NEW.pdfLesson_07_Spring_Security_Register_NEW.pdf
Lesson_07_Spring_Security_Register_NEW.pdf
 
Speed up your Web applications with HTML5 WebSockets
Speed up your Web applications with HTML5 WebSocketsSpeed up your Web applications with HTML5 WebSockets
Speed up your Web applications with HTML5 WebSockets
 
JJUG CCC 2011 Spring
JJUG CCC 2011 SpringJJUG CCC 2011 Spring
JJUG CCC 2011 Spring
 
ikh331-06-distributed-programming
ikh331-06-distributed-programmingikh331-06-distributed-programming
ikh331-06-distributed-programming
 
Jason parsing
Jason parsingJason parsing
Jason parsing
 
Creating a Facebook Clone - Part XXVII - Transcript.pdf
Creating a Facebook Clone - Part XXVII - Transcript.pdfCreating a Facebook Clone - Part XXVII - Transcript.pdf
Creating a Facebook Clone - Part XXVII - Transcript.pdf
 
Ad java prac sol set
Ad java prac sol setAd java prac sol set
Ad java prac sol set
 
Durable functions 2.0 (2019-10-10)
Durable functions 2.0 (2019-10-10)Durable functions 2.0 (2019-10-10)
Durable functions 2.0 (2019-10-10)
 

More from RyanF2PLeev

Please provide the code and the explanation for Question 1-1 and 1-2-.pdf
Please provide the code and the explanation for Question 1-1 and 1-2-.pdfPlease provide the code and the explanation for Question 1-1 and 1-2-.pdf
Please provide the code and the explanation for Question 1-1 and 1-2-.pdf
RyanF2PLeev
 

More from RyanF2PLeev (20)

Please help me answer these questions below- 1- This organism is in th.pdf
Please help me answer these questions below- 1- This organism is in th.pdfPlease help me answer these questions below- 1- This organism is in th.pdf
Please help me answer these questions below- 1- This organism is in th.pdf
 
please help and explain thoroughly and show work- Thank you! 1- (.pdf
please help and explain thoroughly and show work- Thank you!      1- (.pdfplease help and explain thoroughly and show work- Thank you!      1- (.pdf
please help and explain thoroughly and show work- Thank you! 1- (.pdf
 
Please give me a heads up on- Communications and Servicing The Client.pdf
Please give me a heads up on- Communications and Servicing The Client.pdfPlease give me a heads up on- Communications and Servicing The Client.pdf
Please give me a heads up on- Communications and Servicing The Client.pdf
 
Population Mean formula is provided below- Identify - match the variab.pdf
Population Mean formula is provided below- Identify - match the variab.pdfPopulation Mean formula is provided below- Identify - match the variab.pdf
Population Mean formula is provided below- Identify - match the variab.pdf
 
Portfolio invested in stock- Portfolio invested in bond- Expected Retu.pdf
Portfolio invested in stock- Portfolio invested in bond- Expected Retu.pdfPortfolio invested in stock- Portfolio invested in bond- Expected Retu.pdf
Portfolio invested in stock- Portfolio invested in bond- Expected Retu.pdf
 
Points X-Y- and Z are locations on the topographic map bellow- Elevati.pdf
Points X-Y- and Z are locations on the topographic map bellow- Elevati.pdfPoints X-Y- and Z are locations on the topographic map bellow- Elevati.pdf
Points X-Y- and Z are locations on the topographic map bellow- Elevati.pdf
 
Plot the frequency of p in this population- Make sure you plot the fre.pdf
Plot the frequency of p in this population- Make sure you plot the fre.pdfPlot the frequency of p in this population- Make sure you plot the fre.pdf
Plot the frequency of p in this population- Make sure you plot the fre.pdf
 
Please help me with this from the Dental assistant class 112 Chart D.pdf
Please help me with this from the Dental assistant class 112   Chart D.pdfPlease help me with this from the Dental assistant class 112   Chart D.pdf
Please help me with this from the Dental assistant class 112 Chart D.pdf
 
Please help me with this question! 7-3 Another attacker Mallory interc.pdf
Please help me with this question! 7-3 Another attacker Mallory interc.pdfPlease help me with this question! 7-3 Another attacker Mallory interc.pdf
Please help me with this question! 7-3 Another attacker Mallory interc.pdf
 
please show your work -) T-Scores the question is referring to- 3- A.pdf
please show your work -)  T-Scores the question is referring to- 3- A.pdfplease show your work -)  T-Scores the question is referring to- 3- A.pdf
please show your work -) T-Scores the question is referring to- 3- A.pdf
 
Please explain how you reached the answer if applicable- 1- Find the.pdf
Please explain how you reached the answer if applicable-  1- Find the.pdfPlease explain how you reached the answer if applicable-  1- Find the.pdf
Please explain how you reached the answer if applicable- 1- Find the.pdf
 
Please review the guide by CoinTelegraph 1) Come up with an idea- thin.pdf
Please review the guide by CoinTelegraph 1) Come up with an idea- thin.pdfPlease review the guide by CoinTelegraph 1) Come up with an idea- thin.pdf
Please review the guide by CoinTelegraph 1) Come up with an idea- thin.pdf
 
Please provide the code and the explanation for Question 1-1 and 1-2-.pdf
Please provide the code and the explanation for Question 1-1 and 1-2-.pdfPlease provide the code and the explanation for Question 1-1 and 1-2-.pdf
Please provide the code and the explanation for Question 1-1 and 1-2-.pdf
 
Please provide a new answer- Do not copy and paste a response- Thank y.pdf
Please provide a new answer- Do not copy and paste a response- Thank y.pdfPlease provide a new answer- Do not copy and paste a response- Thank y.pdf
Please provide a new answer- Do not copy and paste a response- Thank y.pdf
 
Please identify the type of protein complex that will be recruited to.pdf
Please identify the type of protein complex that will be recruited to.pdfPlease identify the type of protein complex that will be recruited to.pdf
Please identify the type of protein complex that will be recruited to.pdf
 
Please help me with this question! 6- Certificates and PKI- (10 points.pdf
Please help me with this question! 6- Certificates and PKI- (10 points.pdfPlease help me with this question! 6- Certificates and PKI- (10 points.pdf
Please help me with this question! 6- Certificates and PKI- (10 points.pdf
 
Please help me with this question! 7- Kerberos- (15 points) The EECS D.pdf
Please help me with this question! 7- Kerberos- (15 points) The EECS D.pdfPlease help me with this question! 7- Kerberos- (15 points) The EECS D.pdf
Please help me with this question! 7- Kerberos- (15 points) The EECS D.pdf
 
Java Circle-java -Make the 'color' attribute private -Make a constr.pdf
Java  Circle-java   -Make the 'color' attribute private -Make a constr.pdfJava  Circle-java   -Make the 'color' attribute private -Make a constr.pdf
Java Circle-java -Make the 'color' attribute private -Make a constr.pdf
 
Jeters Company uses a periodic inventory system and reports the follow.pdf
Jeters Company uses a periodic inventory system and reports the follow.pdfJeters Company uses a periodic inventory system and reports the follow.pdf
Jeters Company uses a periodic inventory system and reports the follow.pdf
 
Jill Perry invested $10-000 for a 5- interest in a limited partnership.pdf
Jill Perry invested $10-000 for a 5- interest in a limited partnership.pdfJill Perry invested $10-000 for a 5- interest in a limited partnership.pdf
Jill Perry invested $10-000 for a 5- interest in a limited partnership.pdf
 

Recently uploaded

MuleSoft Integration with AWS Textract | Calling AWS Textract API |AWS - Clou...
MuleSoft Integration with AWS Textract | Calling AWS Textract API |AWS - Clou...MuleSoft Integration with AWS Textract | Calling AWS Textract API |AWS - Clou...
MuleSoft Integration with AWS Textract | Calling AWS Textract API |AWS - Clou...
MysoreMuleSoftMeetup
 
會考英文會考英文會考英文會考英文會考英文會考英文會考英文會考英文會考英文會考英文會考英文
會考英文會考英文會考英文會考英文會考英文會考英文會考英文會考英文會考英文會考英文會考英文會考英文會考英文會考英文會考英文會考英文會考英文會考英文會考英文會考英文會考英文會考英文
會考英文會考英文會考英文會考英文會考英文會考英文會考英文會考英文會考英文會考英文會考英文
中 央社
 
Transparency, Recognition and the role of eSealing - Ildiko Mazar and Koen No...
Transparency, Recognition and the role of eSealing - Ildiko Mazar and Koen No...Transparency, Recognition and the role of eSealing - Ildiko Mazar and Koen No...
Transparency, Recognition and the role of eSealing - Ildiko Mazar and Koen No...
EADTU
 
SURVEY I created for uni project research
SURVEY I created for uni project researchSURVEY I created for uni project research
SURVEY I created for uni project research
CaitlinCummins3
 
會考英聽會考英聽會考英聽會考英聽會考英聽會考英聽會考英聽會考英聽會考英聽會考英聽
會考英聽會考英聽會考英聽會考英聽會考英聽會考英聽會考英聽會考英聽會考英聽會考英聽會考英聽會考英聽會考英聽會考英聽會考英聽會考英聽會考英聽會考英聽會考英聽會考英聽
會考英聽會考英聽會考英聽會考英聽會考英聽會考英聽會考英聽會考英聽會考英聽會考英聽
中 央社
 
Spellings Wk 4 and Wk 5 for Grade 4 at CAPS
Spellings Wk 4 and Wk 5 for Grade 4 at CAPSSpellings Wk 4 and Wk 5 for Grade 4 at CAPS
Spellings Wk 4 and Wk 5 for Grade 4 at CAPS
AnaAcapella
 

Recently uploaded (20)

MuleSoft Integration with AWS Textract | Calling AWS Textract API |AWS - Clou...
MuleSoft Integration with AWS Textract | Calling AWS Textract API |AWS - Clou...MuleSoft Integration with AWS Textract | Calling AWS Textract API |AWS - Clou...
MuleSoft Integration with AWS Textract | Calling AWS Textract API |AWS - Clou...
 
Analyzing and resolving a communication crisis in Dhaka textiles LTD.pptx
Analyzing and resolving a communication crisis in Dhaka textiles LTD.pptxAnalyzing and resolving a communication crisis in Dhaka textiles LTD.pptx
Analyzing and resolving a communication crisis in Dhaka textiles LTD.pptx
 
An overview of the various scriptures in Hinduism
An overview of the various scriptures in HinduismAn overview of the various scriptures in Hinduism
An overview of the various scriptures in Hinduism
 
Mattingly "AI and Prompt Design: LLMs with NER"
Mattingly "AI and Prompt Design: LLMs with NER"Mattingly "AI and Prompt Design: LLMs with NER"
Mattingly "AI and Prompt Design: LLMs with NER"
 
會考英文會考英文會考英文會考英文會考英文會考英文會考英文會考英文會考英文會考英文會考英文
會考英文會考英文會考英文會考英文會考英文會考英文會考英文會考英文會考英文會考英文會考英文會考英文會考英文會考英文會考英文會考英文會考英文會考英文會考英文會考英文會考英文會考英文
會考英文會考英文會考英文會考英文會考英文會考英文會考英文會考英文會考英文會考英文會考英文
 
Transparency, Recognition and the role of eSealing - Ildiko Mazar and Koen No...
Transparency, Recognition and the role of eSealing - Ildiko Mazar and Koen No...Transparency, Recognition and the role of eSealing - Ildiko Mazar and Koen No...
Transparency, Recognition and the role of eSealing - Ildiko Mazar and Koen No...
 
SURVEY I created for uni project research
SURVEY I created for uni project researchSURVEY I created for uni project research
SURVEY I created for uni project research
 
ĐỀ THAM KHẢO KÌ THI TUYỂN SINH VÀO LỚP 10 MÔN TIẾNG ANH FORM 50 CÂU TRẮC NGHI...
ĐỀ THAM KHẢO KÌ THI TUYỂN SINH VÀO LỚP 10 MÔN TIẾNG ANH FORM 50 CÂU TRẮC NGHI...ĐỀ THAM KHẢO KÌ THI TUYỂN SINH VÀO LỚP 10 MÔN TIẾNG ANH FORM 50 CÂU TRẮC NGHI...
ĐỀ THAM KHẢO KÌ THI TUYỂN SINH VÀO LỚP 10 MÔN TIẾNG ANH FORM 50 CÂU TRẮC NGHI...
 
Mattingly "AI & Prompt Design: Named Entity Recognition"
Mattingly "AI & Prompt Design: Named Entity Recognition"Mattingly "AI & Prompt Design: Named Entity Recognition"
Mattingly "AI & Prompt Design: Named Entity Recognition"
 
會考英聽會考英聽會考英聽會考英聽會考英聽會考英聽會考英聽會考英聽會考英聽會考英聽
會考英聽會考英聽會考英聽會考英聽會考英聽會考英聽會考英聽會考英聽會考英聽會考英聽會考英聽會考英聽會考英聽會考英聽會考英聽會考英聽會考英聽會考英聽會考英聽會考英聽
會考英聽會考英聽會考英聽會考英聽會考英聽會考英聽會考英聽會考英聽會考英聽會考英聽
 
ESSENTIAL of (CS/IT/IS) class 07 (Networks)
ESSENTIAL of (CS/IT/IS) class 07 (Networks)ESSENTIAL of (CS/IT/IS) class 07 (Networks)
ESSENTIAL of (CS/IT/IS) class 07 (Networks)
 
Graduate Outcomes Presentation Slides - English (v3).pptx
Graduate Outcomes Presentation Slides - English (v3).pptxGraduate Outcomes Presentation Slides - English (v3).pptx
Graduate Outcomes Presentation Slides - English (v3).pptx
 
UChicago CMSC 23320 - The Best Commit Messages of 2024
UChicago CMSC 23320 - The Best Commit Messages of 2024UChicago CMSC 23320 - The Best Commit Messages of 2024
UChicago CMSC 23320 - The Best Commit Messages of 2024
 
OS-operating systems- ch05 (CPU Scheduling) ...
OS-operating systems- ch05 (CPU Scheduling) ...OS-operating systems- ch05 (CPU Scheduling) ...
OS-operating systems- ch05 (CPU Scheduling) ...
 
PSYPACT- Practicing Over State Lines May 2024.pptx
PSYPACT- Practicing Over State Lines May 2024.pptxPSYPACT- Practicing Over State Lines May 2024.pptx
PSYPACT- Practicing Over State Lines May 2024.pptx
 
Spellings Wk 4 and Wk 5 for Grade 4 at CAPS
Spellings Wk 4 and Wk 5 for Grade 4 at CAPSSpellings Wk 4 and Wk 5 for Grade 4 at CAPS
Spellings Wk 4 and Wk 5 for Grade 4 at CAPS
 
DEMONSTRATION LESSON IN ENGLISH 4 MATATAG CURRICULUM
DEMONSTRATION LESSON IN ENGLISH 4 MATATAG CURRICULUMDEMONSTRATION LESSON IN ENGLISH 4 MATATAG CURRICULUM
DEMONSTRATION LESSON IN ENGLISH 4 MATATAG CURRICULUM
 
Basic Civil Engineering notes on Transportation Engineering & Modes of Transport
Basic Civil Engineering notes on Transportation Engineering & Modes of TransportBasic Civil Engineering notes on Transportation Engineering & Modes of Transport
Basic Civil Engineering notes on Transportation Engineering & Modes of Transport
 
Observing-Correct-Grammar-in-Making-Definitions.pptx
Observing-Correct-Grammar-in-Making-Definitions.pptxObserving-Correct-Grammar-in-Making-Definitions.pptx
Observing-Correct-Grammar-in-Making-Definitions.pptx
 
Stl Algorithms in C++ jjjjjjjjjjjjjjjjjj
Stl Algorithms in C++ jjjjjjjjjjjjjjjjjjStl Algorithms in C++ jjjjjjjjjjjjjjjjjj
Stl Algorithms in C++ jjjjjjjjjjjjjjjjjj
 

Include- Modularity using design patterns- Fault tolerance and Compone.pdf

  • 1. Include: Modularity using design patterns, Fault tolerance and Component based development in the below java program. import java.awt.BorderLayout; import java.awt.event.ActionEvent; import java.awt.event.ActionListener; import java.io.BufferedReader; import java.io.IOException; import java.io.InputStreamReader; import java.io.PrintWriter; import java.lang.reflect.Member; import java.net.ServerSocket; import java.net.Socket; import java.util.ArrayList; import java.util.List; import java.util.HashMap; import java.util.Map; import java.util.UUID; import javax.swing.JButton; import javax.swing.JFrame; import javax.swing.JLabel; import javax.swing.JOptionPane; import javax.swing.JPanel; import javax.swing.JTextField; import MemberDetails.Observer;
  • 2. import MemberDetails.Subject; public class MemberServer { private JFrame frame; private JTextField idField; private JTextField ipField; private JTextField portField; private JLabel statusLabel; private static ServerSocket serverSocket; private boolean isRunning; private List<Member> members = new ArrayList<>(); public interface ServerInterface { void startServer(); } // Frame 1 public MemberServer() { frame = new JFrame("Member Server"); frame.setLayout(new BorderLayout()); JPanel panel = new JPanel(); panel.setLayout(null); JLabel idLabel = new JLabel("ID:"); idLabel.setBounds(10, 10, 100, 25); panel.add(idLabel); idField = new JTextField();
  • 3. idField.setBounds(120, 10, 165, 25); panel.add(idField); JLabel ipLabel = new JLabel("IP Address:"); ipLabel.setBounds(10, 40, 100, 25); panel.add(ipLabel); ipField = new JTextField(); ipField.setBounds(120, 40, 165, 25); panel.add(ipField); JLabel portLabel = new JLabel("Port:"); portLabel.setBounds(10, 70, 100, 25); panel.add(portLabel); portField = new JTextField(); portField.setBounds(120, 70, 165, 25); panel.add(portField); // Start Server Button JButton startButton = new JButton("Start Server"); startButton.setBounds(50, 110, 125, 25); startButton.addActionListener(new ActionListener() { @Override public void actionPerformed(ActionEvent e) { Frame2 frame = new Frame2(); frame.setVisible(true); frame.setSize(500, 200);
  • 4. frame.setResizable(false); startServer(); } }); panel.add(startButton); // Quit Button JButton quitButton = new JButton("Quit"); quitButton.setBounds(200, 110, 125, 25); ; quitButton.addActionListener(new ActionListener() { @Override public void actionPerformed(ActionEvent e) { System.exit(0); } }); panel.add(quitButton); statusLabel = new JLabel(); statusLabel.setBounds(10, 140, 275, 25); panel.add(statusLabel); frame.add(panel, BorderLayout.CENTER); frame.pack(); frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE); frame.setVisible(true);
  • 5. frame.setSize(500, 200); frame.setResizable(false); } // Frame 2 public class Frame2 extends JFrame { public Frame2() { setTitle("Member Server P2"); setSize(500, 200); setLocationRelativeTo(null); setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE); } } // Start Server private void startServer() { String id = idField.getText(); String ip = ipField.getText(); int port = Integer.parseInt(portField.getText()); if (id.isEmpty() || ip.isEmpty() || port <= 0) { statusLabel.setText("Please enter a valid ID, IP address, and port."); return; } String uniqueId = UUID.randomUUID().toString(); statusLabel.setText("Server started with ID: " + uniqueId);
  • 6. isRunning = true; new Thread(new Runnable() { @Override public void run() { try { ServerSocket serverSocket = new ServerSocket(port); while (isRunning) { Socket socket = serverSocket.accept(); // process incoming connection from member BufferedReader in = new BufferedReader(new InputStreamReader(socket.getInputStream())); String id = in.readLine(); String ip = socket.getInetAddress().getHostAddress(); int port = socket.getPort(); // add member to server Member member = new Member(id, ip, port); members.add(member); System.out.println("Member " + id + "has joined the server"); } } catch (IOException e) { statusLabel.setText("Error starting server: " + e.getMessage()); } } }).start();
  • 7. } public interface Subject { void registerObserver(Observer observer); void removeObserver(Observer observer); void notifyObservers(); } public class Server implements Subject { private List<Member> members = new ArrayList<>(); private List<Observer> observers = new ArrayList<>(); private Member coordinator; @Override public void registerObserver(Observer observer) { observers.add(observer); } @Override public void removeObserver(Observer observer) { observers.remove(observer); } @Override public void notifyObservers() { for (Observer observer : observers) { observer.notifyUpdate(); }
  • 8. } public void addMember(Member member) { if (members.isEmpty()) { coordinator = member; coordinator.informCoordinator(); } else { member.receiveMembers(getMemberDetails()); broadcastMessage(member.getName() + " has joined the group."); } members.add(member); notifyObservers(); } public void removeMember(Member member) { members.remove(member); if (member.equals(coordinator)) { coordinator = null; electNewCoordinator(); notifyObservers(); } broadcastMessage(member.getName() + " has left the group."); } private void electNewCoordinator() { if (members.size() > 0) {
  • 9. coordinator = members.get(0); broadcastMessage(coordinator.getName() + " is now the new coordinator."); coordinator.informCoordinator(); } } public List<Member> getMembers() { return members; } private Map<String, MemberDetails> getMemberDetails() { Map<String, MemberDetails> memberDetails = new HashMap<>(); for (Member member : members) { memberDetails.put(member.getName(), new MemberDetails(member.getIpAddress(), member.getPort())); } return memberDetails; } } public void broadcastMessage(String message) { for (Member member : members) { member.receiveBroadcastMessage(message); } } public void sendPrivateMessage(Member sender, String recipientName, String message) { for (Member member : members) {
  • 10. if (member.getName().equals(recipientName)) { member.receivePrivateMessage(sender.getName(), message); return; } } } public void handleUnresponsiveMember(Member member) { members.remove(member); broadcastMessage(member.getName() + " is unresponsive."); } } public interface Observer { void notifyUpdate(); } // Setters and getters public class Member implements Observer { private String name; private String ipAddress; private int port; private Server server; public Member(String name, String ipAddress, int port) { this.name = name; this.ipAddress = ipAddress;
  • 11. this.port = port; } @Override public void notifyUpdate() { System.out.println("The server has been updated."); } public void joinGroup(Server server) { server.addMember(this); } public void leaveGroup(Server server) { server.removeMember(this); } public void receiveMembers(Map<String, MemberDetails> memberDetails) { members.clear(); members.addAll(memberDetails.values()); } public void informCoordinator() { System.out.println("I am the new coordinator."); } public void receiveBroadcastMessage(String message) { System.out.println("[" + name + "] " + message); } public void receivePrivateMessage(String senderName, String message) {
  • 12. System.out.println("[Private message from " + senderName + " to " + name + "] " + message); } public String getName() { return name; } public String getIpAddress() { return ipAddress; } public int getPort() { return port; } } class MemberDetails { private String ipAddress; private int port; public MemberDetails(String ipAddress, int port) { this.ipAddress = ipAddress; this.port = port; } public String getIpAddress() { return ipAddress; } public int getPort() {
  • 13. return port; } public static void main(String[] args) { new MemberServer(); } }