Practical slips programs : Software Architecture And Design pattern or IOT
S.Y.M.Sc(Comp. Sci.) Practical Examination
Practical Paper(CS-604-MJP) :
Lab Course on CS-601-MJ and CS-603-MJ
(Software Architecture & Design Pattern and Internet of Things)
Software Architecture And Design pattern or IOT Practical slips programs
Slip 1 :
Q.1 Write a Java Program to implement I/O Decorator for converting uppercase letters to lower case letters
import java.io.*;
// Decorator class that converts uppercase letters to lowercase
class LowerCaseInputStream extends InputStreamReader {
private Reader reader;
public LowerCaseInputStream(Reader reader) {
super(reader);
this.reader = reader;
}
@Override
public int read() throws IOException {
int data = reader.read();
if (data == -1) {
return -1; // End of stream
}
// Convert to lowercase if it's an uppercase letter
return Character.toLowerCase((char) data);
}
@Override
public int read(char[] cbuf, int off, int len) throws IOException {
int numCharsRead = reader.read(cbuf, off, len);
for (int i = off; i < off + numCharsRead; i++) {
cbuf[i] = Character.toLowerCase(cbuf[i]);
}
return numCharsRead;
}
}
public class IODecoratorExample {
public static void main(String[] args) {
try {
// Wrapping System.in with a BufferedReader and then LowerCaseInputStream
Reader reader = new LowerCaseInputStream(new BufferedReader(new InputStreamReader(System.in)));
BufferedReader br = new BufferedReader(reader);
System.out.println("Enter some text (uppercase will be converted to lowercase):");
String line;
while ((line = br.readLine()) != null) {
System.out.println("Converted text: " + line);
}
} catch (IOException e) {
e.printStackTrace();
}
}
}
Code Implementation:
1. WeatherStation.java
(Observable Class)
2. WeatherDisplay.java
(Observer Class)
3. Main.java
(Testing the Program)
1. Pizza
Interface
2. Concrete Pizza Classes
Each specific pizza will implement the Pizza
interface.
NyStyleCheesePizza.java
ChicagoStyleCheesePizza.java
3. PizzaStore Class with Factory Method
The PizzaStore
class will have a createPizza()
method that is overridden by subclasses to create different types of pizzas.
4. Concrete Pizza Store Subclasses
We can now create specific pizza stores (like NyPizzaStore
and ChicagoPizzaStore
) that will implement the createPizza()
method to create specific types of pizzas.
NyPizzaStore.java
ChicagoPizzaStore.java
5. Main Class to Test
Now, let's implement a Main
class to test the pizza store ordering process.
Output:
1. Define the Command Interface
The Command
interface defines a single method execute()
that all concrete commands must implement.
2. Create Concrete Command Classes
Each concrete command will implement the Command
interface and perform an action on the receiver. Here, let’s assume we have Light
and Fan
devices to control.
Light Commands
Fan Commands
3. Create the Remote Control (Invoker)
The RemoteControl
class has buttons (slots) that execute commands.
4. Test the Remote Control
Now, we can test the Remote Control by assigning commands to different buttons and pressing them.
Steps
- Define a
Command
interface withexecute()
andundo()
methods. - Create a
CeilingFan
receiver class that has various speed settings and an off state. - Implement concrete command classes (
CeilingFanLowCommand
,CeilingFanMediumCommand
,CeilingFanHighCommand
,CeilingFanOffCommand
) to set different fan speeds. - Each command will store the previous speed of the fan, allowing the
undo
method to revert to the previous state. - Test the functionality by changing fan speeds and using the
undo
feature.
Code Implementation
Step 1: Command Interface
Step 2: CeilingFan Receiver Class
The CeilingFan
class will have methods to set different speeds and a variable to keep track of its current speed.
Step 3: Concrete Command Classes
Each command class sets a specific speed for the fan and stores the previous speed so that it can be reverted with undo()
.
Step 4: Remote Control (Invoker) Class with Undo Functionality
Step 5: Testing the Ceiling Fan with Undo Functionality
Explanation
- Command Interface: Each command has an
execute
and anundo
method. - Concrete Commands: Commands store the previous speed before executing a new one, allowing them to revert with
undo()
. - RemoteControl (Invoker): Tracks the last executed command and calls
undo()
on it when the undo button is pressed. - Testing: This program will print each fan speed change, and when
undo()
is called, it will revert to the previous speed.
Example Output
Steps
- Define a
State
interface with methods for actions such as inserting a coin, ejecting a coin, turning the crank, and dispensing. - Create concrete state classes for each of the machine’s states.
- In the
GumballMachine
class, keep a reference to the current state and delegate actions to it, allowing for state transitions.
Code Implementation
Step 1: State
Interface
The State
interface declares actions available on the gumball machine.
Step 2: Concrete State Classes
Each concrete state class implements State
and handles actions accordingly.
Step 3: GumballMachine
Class
The GumballMachine
class manages the states and transitions.
Step 4: Testing the Gumball Machine
Explanation of the Output
- Insert Coin: The machine transitions from
NoCoinState
toHasCoinState
. - Turn Crank: This transitions to
SoldState
and dispenses a gumball. - Out of Gumballs: When the count of gumballs reaches zero, the machine goes into
SoldOutState
.
Sample Output
Step 1: Power on and Set Up the Raspberry Pi
- Connect the Raspberry Pi to a monitor, keyboard, and mouse.
- Insert the microSD card with Raspberry Pi OS (or another Linux OS) installed.
- Power on the Raspberry Pi by connecting it to a power source.
Once booted, log into the Raspberry Pi desktop environment or terminal.
Step 2: Open the Terminal
- Open the terminal application from the desktop or press
Ctrl + Alt + T
.
Step 3: Execute Common Linux Commands
You can try executing the following commands, which are commonly used for file and system management in Linux. Here’s a brief explanation and example usage of each:
ls
- List files and directories in the current directory.cd
- Change the directory.touch
- Create a new, empty file.mv
- Move or rename a file or directory.rm
- Remove files or directories.man
- Display the manual for a command.mkdir
- Create a new directory.rmdir
- Remove an empty directory.tar
- Archive files.gzip
- Compress a file with gzip.cat
- Display contents of a file.more
andless
- Display file contents page by page.ps
- Display currently running processes.sudo
- Execute a command with superuser privileges.cron
- Schedule recurring tasks (edit withcrontab
).chown
- Change ownership of a file or directory.chgrp
- Change the group ownership of a file or directory.ping
- Check network connectivity.
Tips for Running Commands
- Run
man <command>
to learn more about each command and its options. - Use
sudo
carefully as it grants administrator privileges. - Practice with caution when using commands like
rm
,chown
, orchmod
, as they can alter system files.
Step 1: Set Up Spring Boot Project
Create a Spring Boot project using Spring Initializr or your IDE and include these dependencies:
- Spring Web
- Spring Data JPA
- H2 Database
- Thymeleaf
Step 2: Define the Project Structure
The structure could look like this:
Step 3: Create the Model
Define an Employee
entity with fields for ID, name, department, and email.
Step 4: Create Repository Interface
Define an interface EmployeeRepository
that extends JpaRepository
.
Step 5: Create Service Class
The EmployeeService
will handle the business logic and communicate with the repository.
Step 6: Create Controller
The EmployeeController
will handle HTTP requests and direct to appropriate views.
Step 7: Configure H2 Database (application.properties)
Step 8: Create Thymeleaf Templates
employees.html
- Display List of Employees
add_employee.html
- Add Employee Form
edit_employee.html
- Edit Employee Form
Similar to add_employee.html
, but with fields pre-filled using employee data.
Step 9: Run the Application
Run the Spring Boot application and open the browser at http://localhost:8080/employees
to see the list of employees and perform CRUD operations.
Q.2 Write python programs on Pi : a) Read your name and print Hello message with name b) Read two numbers and print their sum, difference, product and division. c) Word and character count of a given string. d) Area of a given shape (rectangle, triangle and circle) reading shape and appropriate values from standard input.
a) Read Your Name and Print a Hello Message
b) Read Two Numbers and Print Their Sum, Difference, Product, and Division
c) Word and Character Count of a Given String
d) Area of a Given Shape (Rectangle, Triangle, Circle)
print("Invalid shape entered.")
Step 1: Define the FlyBehavior Interface
Step 2: Define Concrete Classes for FlyBehavior
Step 3: Define the QuackBehavior Interface
Step 4: Define Concrete Classes for QuackBehavior
Step 5: Create the Duck Class
The Duck class will use the FlyBehavior and QuackBehavior interfaces and delegate the behavior to the appropriate strategy.
Step 6: Create Concrete Duck Classes
Now, we can create specific types of ducks, each having a different combination of behaviors.
Step 7: Create the DuckSimulator to Test the Strategy Pattern
In the DuckSimulator class, we can simulate different ducks and behaviors.
Explanation:
- The Duck class is abstract and defines common behaviors (
performFly
,performQuack
,swim
), but the actual flying and quacking behaviors are delegated to the FlyBehavior and QuackBehavior interfaces, respectively. - Concrete duck types (like
MallardDuck
andModelDuck
) initialize their behaviors through the constructor. - The behaviors can be changed dynamically at runtime using the
setFlyBehavior
andsetQuackBehavior
methods.
Output:
Step-by-Step Solution:
Step 1: Define the BeatMode Interface
This will be the interface that we want to adapt the HeartModel to.
Step 2: Define the HeartModel Class
This class represents the heart and has its own way of beating.
Step 3: Create the HeartAdapter Class
The HeartAdapter will adapt the HeartModel to the BeatMode interface.
Step 4: Create the Client Code to Test the Adapter
The client will use the BeatMode interface without knowing about the underlying HeartModel class.
Explanation:
BeatMode Interface: This is the target interface that defines the method
beat()
. The client code expects objects of this type to perform the beating action.HeartModel Class: This is the existing class with a method
startBeating()
that is not compatible with theBeatMode
interface. It represents a heart in a specific mode that beats.HeartAdapter Class: This class acts as the adapter. It takes an instance of
HeartModel
and delegates thebeat()
method call to thestartBeating()
method ofHeartModel
. This makes theHeartModel
compatible with theBeatMode
interface.HeartClient: This is the client code that uses the
BeatMode
interface without knowing the underlying implementation. It works with theHeartAdapter
to interact with theHeartModel
.
Output:
Setup:
Before running these programs, ensure you have:
- The GPIO library installed. You can install it using:
- Proper connections for LEDs and switches. You can use a breadboard to connect the GPIO pins to LEDs and switches, ensuring you know which GPIO pins are connected to them.
a) Light an LED Through Python Program
This program will turn on an LED connected to a GPIO pin (e.g., GPIO17) when the program runs.
Explanation:
- This program uses GPIO pin 17 to control the LED.
- It turns the LED on for 5 seconds, then turns it off.
- The
GPIO.cleanup()
ensures that the GPIO settings are cleared when the program ends.
b) Get Input from Two Switches and Switch On Corresponding LEDs
This program will read input from two switches and turn on the corresponding LEDs based on the state of the switches.
Explanation:
- The program monitors two switches (connected to GPIO pins 18 and 23) and two LEDs (connected to GPIO pins 17 and 24).
- If a switch is pressed (input is
LOW
), the corresponding LED will turn on. If the switch is not pressed (HIGH
), the LED will turn off. - The program continues to monitor the switches in a loop, and a
try-except
block is used to cleanly handle the program termination (e.g., viaCtrl+C
).
c) Flash an LED at a Given On Time and Off Time Cycle, Where the Two Times Are Taken from a File
This program will read on and off times from a file (e.g., times.txt
) and flash an LED based on those times.
Sample File (times.txt
):
This means the LED will stay on for 2 seconds and off for 1 second.
Explanation:
- The program reads the on-time and off-time values from a file (
times.txt
). - It flashes the LED on for the specified
on_time
and off for the specifiedoff_time
in an infinite loop. - The
try-except
block ensures that the program can be stopped safely usingCtrl+C
, and the GPIO pins are cleaned up afterward.
Step-by-Step Solution:
Step 1: Define the Car
Interface
This interface will have a single method assemble()
.
Step 2: Concrete Implementation of Car
— Basic Car
Step 3: Decorator Class — CarDecorator
This will be a base class for all decorators. It implements the Car
interface and wraps a Car
object.
Step 4: SportsCar Decorator
This decorator class will add additional features specific to a sports car.
Step 5: LuxuryCar Decorator
This decorator class will add additional features specific to a luxury car.
Step 6: Client Code — Testing the Decorator Pattern
The client will create a basic car and then dynamically decorate it with different features.
Output:
Step 1: Define the Volt Class
The Volt
class represents the voltage and will have methods to get the voltage in different units.
Step 2: Define the Socket Class
The Socket
class represents a socket that provides 120V (constant voltage).
Step 3: Define the Adapter Class
In the Class Adapter design pattern, the adapter extends the existing class (Socket
) to modify the behavior. We will create an adapter that can return different voltages (3V, 12V, or 120V).
Step 4: Test the Adapter Pattern
Finally, we will create a main class to test the functionality of the Adapter
pattern by creating a SocketAdapter
and using it to get 3V, 12V, and 120V.
Output:
Explanation:
- Volt Class: This class represents a voltage and has a method
getVolts()
that returns the voltage. - Socket Class: This class produces a constant voltage of 120V by default, which is returned by the
getVolt()
method. - SocketAdapter Class: This class extends
Socket
and provides methods to convert the 120V to 3V, 12V, or 120V. It uses a helper methodconvertVolt()
to adjust the voltage based on the required value. - AdapterPatternTest: The test class creates an instance of
SocketAdapter
and calls its methods to get voltages of 3V, 12V, and 120V.
1. Command Interface
2. Receiver Classes
3. Concrete Command Classes
4. The Remote Control (Invoker)
5. Main Class to Test the Command Pattern
Explanation:
- Command Interface: Defines the
execute()
method which will be implemented by all concrete command classes. - Receiver Classes: The
Light
,GarageDoor
, andStereo
classes represent the devices being controlled. They perform the actions when their corresponding commands are executed. - Concrete Command Classes: These implement the
Command
interface and delegate the action to the appropriate method in the receiver class. For example,LightOnCommand
calls theon()
method of theLight
class. - Invoker: The
RemoteControl
class holds a list of commands and can execute the appropriate command when the button is pressed. ThesetCommand()
method binds a command to a button, andpressButton()
executes the command. - Main: In the
CommandPatternTest
class, we create instances of receivers and commands, set them in the remote control, and then simulate pressing buttons on the remote control to execute various actions.
Output:
1. Subsystems (Components)
2. Facade Class
3. Client Code (Test)
Explanation:
Subsystem Classes: These classes (
TV
,SoundSystem
,Lights
, andDVDPlayer
) represent the individual components of the home theater system. Each class has methods to control its respective functionality, such as turning on/off, adjusting volume, or playing a DVD.Facade Class (
HomeTheaterFacade
): This class provides a simplified interface to control all the components of the home theater system. It has methods likewatchMovie()
andendMovie()
that internally call the appropriate methods on the subsystem objects. The facade hides the complexity of interacting with each component.Client Code: In the
FacadePatternTest
class, we create instances of the subsystems (TV, SoundSystem, Lights, and DVDPlayer) and pass them to theHomeTheaterFacade
. The client can then simply callwatchMovie()
orendMovie()
without needing to deal with the individual components of the system.
Output:
1. Observer Interface
2. Concrete Observers (Hexadecimal, Octal, Binary)
3. Subject (DecimalNumber)
4. Main Program (Client Code)
Code Implementation:
1. Shape Interface
2. Concrete Products (Circle, Square, Rectangle)
3. Abstract Factory
4. Concrete Factories (2D and 3D)
5. Client Code
Explanation of the Code:
Shape Interface: This defines the
draw()
method that all concrete shapes (e.g., Circle, Square, Rectangle) must implement.Concrete Shapes:
Circle
,Square
, andRectangle
implement theShape
interface and provide their respectivedraw()
method implementations.
Abstract Factory (
ShapeFactory
): This interface defines acreateShape()
method, which will be used by concrete factories to create specific shapes based on input.Concrete Factories:
TwoDShapeFactory
is responsible for creating 2D shapes like Circle, Square, and Rectangle.ThreeDShapeFactory
can be extended to create 3D shapes like Sphere and Cuboid (though for simplicity, we're using placeholders in this example).
Client Code: The client (in this case,
AbstractFactoryPatternDemo
) interacts with the abstract factories to create shapes. It can use theTwoDShapeFactory
to create 2D shapes andThreeDShapeFactory
to create 3D shapes.
Weather Station Implementation:
1. WeatherStation (Observable)
2. WeatherDisplay (Observer)
Now, let's create an observer class WeatherDisplay
that will observe the WeatherStation object for changes in temperature, humidity, and pressure.
3. Main Program (Test the WeatherStation and WeatherDisplay)
Explanation:
WeatherStation Class:
- Inherits from
Observable
. - Contains private fields for temperature, humidity, and pressure.
- Provides the
setMeasurements()
method to set values for these fields and then callmeasurementsChanged()
to notify observers. - The
measurementsChanged()
method marks the object as changed and notifies all observers by callingnotifyObservers()
.
- Inherits from
WeatherDisplay Class:
- Implements the
Observer
interface. - When the observable (WeatherStation) calls
notifyObservers()
, theupdate()
method is triggered in this class. - The
update()
method retrieves the new measurements from the WeatherStation object and callsdisplay()
to show the updated values.
- Implements the
Main Program (WeatherStationApp):
- Creates a WeatherStation object and a WeatherDisplay object.
- Sets measurements on the WeatherStation, which triggers the
update()
method in the WeatherDisplay, displaying the updated weather information.
Sample Output:
Java Program to Implement the Factory Method Pattern:
1. Pizza Class (Abstract Base Class)
This class defines the methods that all pizzas will share.
2. Concrete Pizza Classes
Each of these classes represents a different style of pizza.
NYStyleCheesePizza Class:
ChicagoStyleCheesePizza Class:
3. PizzaStore Class (Factory Method)
The PizzaStore
class will define the abstract method createPizza()
that must be implemented by subclasses to return the specific type of pizza.
4. Concrete Pizza Stores
Each store subclass will implement the createPizza()
method, which will return the appropriate pizza based on the input type.
NYPizzaStore Class:
ChicagoPizzaStore Class:
5. Main Class to Test the Program
In the PizzaTestDrive
class, we will create instances of different pizza stores and order pizzas.
Output:
Explanation:
Pizza Class:
- The
Pizza
class is an abstract base class that defines the common behavior (prepare, bake, cut, and box) for all types of pizzas. - The
name
field is set in each subclass to specify the type of pizza.
- The
Concrete Pizza Classes (NYStyleCheesePizza, ChicagoStyleCheesePizza):
- These classes are specific implementations of pizza styles. They set the
name
of the pizza to reflect the style.
- These classes are specific implementations of pizza styles. They set the
PizzaStore Class:
- The
PizzaStore
class is the core of the Factory Method. TheorderPizza()
method callscreatePizza()
to get the pizza and then prepares, bakes, cuts, and boxes it. createPizza()
is an abstract method, which is implemented by the concrete pizza store classes (NYPizzaStore
,ChicagoPizzaStore
).
- The
Concrete Pizza Stores (NYPizzaStore, ChicagoPizzaStore):
- Each store implements
createPizza()
to return the correct type of pizza based on the order. - For example,
NYPizzaStore
will return aNYStyleCheesePizza
when"cheese"
is ordered.
- Each store implements
PizzaTestDrive Class:
- The main class simulates the pizza ordering process from different pizza stores. It demonstrates the Factory Method Pattern by showing how the creation of different pizza types is abstracted through the
PizzaStore
'screatePizza()
method.
- The main class simulates the pizza ordering process from different pizza stores. It demonstrates the Factory Method Pattern by showing how the creation of different pizza types is abstracted through the
Step 1: Start Raspberry Pi
- Power on the Raspberry Pi.
- Make sure it is connected to a monitor, keyboard, and mouse. Alternatively, you can connect to the Raspberry Pi using SSH if it is connected to your local network.
Step 2: Open the Command Terminal
Once the Raspberry Pi boots up:
- If you're using a GUI interface, open the Terminal by clicking on the Terminal icon or pressing
Ctrl + Alt + T
. - If you're using SSH, open your SSH client (e.g., PuTTY) and connect to your Raspberry Pi by using its IP address and login credentials.
Step 3: Execute the Various Linux Commands
Here is a list of common Linux commands and their usage. Execute these commands one by one in the terminal window.
1. ls
– List directory contents
This will list all the files and directories in the current working directory.
2. cd
– Change directory
Use this command to navigate to a different directory. Replace /path/to/directory
with the actual path.
3. touch
– Create an empty file
This will create a new empty file called myfile.txt
in the current directory.
4. mv
– Move or rename files
This will move the file myfile.txt
to the new directory. You can also use this command to rename files:
5. rm
– Remove files or directories
This will delete the file myfile.txt
.
To delete a directory (and its contents):
6. man
– View manual for commands
This will display the manual page for the ls
command. You can exit the manual by pressing q
.
7. mkdir
– Create a directory
This will create a new directory called mydirectory
.
8. rmdir
– Remove an empty directory
This will remove an empty directory called mydirectory
.
9. tar
– Archive files
This will create an archive called archive.tar
of the specified directory. The options used:
-c
: Create a new archive.-v
: Verbose mode (shows files being archived).-f
: Specifies the archive file name.
To extract the archive:
10. gzip
– Compress files
This will compress the file myfile.txt
into myfile.txt.gz
.
To decompress a .gz
file:
11. cat
– Concatenate and display file content
This will display the contents of myfile.txt
on the terminal.
12. more
– View file contents page by page
This will allow you to view the contents of myfile.txt
one page at a time.
13. less
– View file contents interactively
This is similar to more
, but allows you to scroll up and down interactively.
14. ps
– Display running processes
This will show a list of all running processes. ps aux
displays all processes, including those from other users.
15. sudo
– Execute commands with root privileges
This command updates the package list on your Raspberry Pi. sudo
is used to execute commands with elevated privileges.
16. cron
– Schedule tasks to run at specified times
This will open the cron jobs editor. You can use it to schedule tasks to run at specific times. A cron job entry might look like this:
This would run /path/to/script.sh
every day at 5:00 AM.
17. chown
– Change file owner and group
This will change the owner and group of myfile.txt
to pi
.
18. chgrp
– Change group ownership
This will change the group ownership of myfile.txt
to pi
.
19. ping
– Send ICMP Echo Request
This will send a ping request to google.com
to check the network connectivity. To stop the ping process, press Ctrl+C
.
20. etc
– Directory for configuration files
In Linux, /etc
is a directory that holds configuration files for the system. You can list files in /etc
with:
Steps:
- InputStream: We will use
InputStream
orReader
as the base interface for reading data. - Decorator: We will create a decorator class that extends
InputStreamReader
orBufferedReader
, which will modify the input data (convert it to lowercase) while reading. - Concrete Component: The concrete class will read input normally.
- Client: The client will use the decorator to read the input with modified behavior (in this case, converting all uppercase letters to lowercase).
Java Program:
1. I/O Decorator Pattern for Lowercase Conversion
2. Test Class for Using the Lowercase Decorator
Explanation:
LowerCaseInputStream
Class:- It extends
FilterInputStream
, which is a subclass ofInputStream
. TheFilterInputStream
class is used to decorate an existing input stream. - The
read()
method is overridden to convert the character read to lowercase usingCharacter.toLowerCase()
before returning it. - The second
read(byte[] b, int off, int len)
method is also overridden to convert the entire byte array of characters to lowercase.
- It extends
IOTest
Class:- A test case where we simulate user input by creating a
ByteArrayInputStream
from a string (input
). - The
LowerCaseInputStream
decorator wraps theByteArrayInputStream
and converts all input characters to lowercase. - We then read and print the data from the stream. As expected, all characters are converted to lowercase.
- A test case where we simulate user input by creating a
Output:
Comments
Post a Comment
hey