Software Architechture Lab Manual
Software Architechture Lab Manual
DEPARTMENT OF
COMPUTER SCIENCE & ENGINEERING
Software Architecture
Lab Manual
Session :
Advantages of Servlet:-
There are many advantages of Servlet over CGI. The web container creates threads for handling the
multiple requests to the Servlet. Threads have many benefits over the Processes such as they share a
common memory area, lightweight, cost of communication between the threads are low. The
advantages of Servlet are as follows:
1. Better performance: because it creates a thread for each request, not process.
2. Portability: because it uses Java language.
3. Robust: JVM
manages Servlets, so we don't need to worry about the memory leak, garbage collection, etc
4. Secure: because it uses java language.
Here, we are going to create the simple example to create the login form using servlet. We have used
oracle10g as the database. There are 5 files required for this application.
o index.html
o FirstServlet.java
o LoginDao.java
o SecondServlet.java
o web.xml
You must need to create a table userreg with name and pass fields. Moreover, it must have contained
some data. The table should be as:
index.html
1. <form action="servlet1" method="post">
2. Name:<input type="text" name="username"/><br/><br/>
3. Password:<input type="password" name="userpass"/><br/><br/>
4. <input type="submit" value="login"/>
5. </form>
FirstServlet.java
import java.io.IOException;
import java.io.PrintWriter;
import javax.servlet.RequestDispatcher;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
public class FirstServlet extends HttpServlet {
public void doPost(HttpServletRequest request, HttpServletResponse response)
throws ServletException, IOException {
response.setContentType("text/html");
PrintWriter out = response.getWriter();
String n=request.getParameter("username");
String p=request.getParameter("userpass");
if(LoginDao.validate(n, p)){
RequestDispatcher rd=request.getRequestDispatcher("servlet2");
rd.forward(request,response);
}
else{
out.print("Sorry username or password error");
RequestDispatcher rd=request.getRequestDispatcher("index.html");
rd.include(request,response);
}
out.close();
}
}
import java.sql.*;
public class LoginDao {
public static boolean validate(String name,String pass){
boolean status=false;
try{
Class.forName("oracle.jdbc.driver.OracleDriver");
Connection con=DriverManager.getConnection(
"jdbc:oracle:thin:@localhost:1521:xe","system","oracle");
PreparedStatement ps=con.prepareStatement(
"select * from userreg where name=? and pass=?");
ps.setString(1,name);
ps.setString(2,pass);
ResultSet rs=ps.executeQuery();
status=rs.next();
}catch(Exception e){System.out.println(e);}
return status;
}
}
WelcomeServlet.java
import java.io.IOException;
import java.io.PrintWriter;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
public class WelcomeServlet extends HttpServlet {
public void doPost(HttpServletRequest request, HttpServletResponse response)
throws ServletException, IOException {
response.setContentType("text/html");
PrintWriter out = response.getWriter();
String n=request.getParameter("username");
out.print("Welcome "+n);
out.close();
}
}
OUTPUT:-
Practical No 2
OBJECTIVE: -Write a program to demonstrate a struts application which accepts user inputs
and show input values.
THEORY: -
What is Struts is used to create a web application based on servlet and JSP. Struts depend on the
MVC (Model View Controller) framework. Struts application is a genuine web application. Struts
are thoroughly useful in building J2EE (Java 2 Platform, Enterprise Edition) applications because
struts take advantage of J2EE design patterns. Struts follows these J2EE design patterns including
MVC.
Features of Struts: Struts has the following features:
Struts encourages good design practices and modelling because the framework is
designed with “time-proven” design patterns.
Struts is almost simple, so easy to learn and use.
It supports many convenient features such as input validation and internationalization.
It takes much of the complexity out as instead of building your own MVC framework,
you can use struts.
Struts is very well integrated with J2EE.
Struts has large user community.
It is flexible and extensible; it is easy for the existing web applications to adapt the
struts framework.
Struts provide good tag libraries.
It allows capturing input form data into javabean objects called Action forms.
It also hands over standard error handling both programmatically and declaratively.
Working: -In the initialization phase, the controller rectifies a configuration file and used it to
deploy other control layer objects. Struts configuration is form by these objects combined together.
The struts configuration defines among other things the action mappings for an application. Struts
controller servlet considers the action mappings and routes the HTTP requests to other components
in the framework. Request is first delivered to an action and then to JSP. The mapping helps the
controller to change HTTP requests into application actions. The action objects can handle the
request from and responds to the client (generally a web browser). Action objects have access to
the applications controller servlet and also access to the servlet’s methods. When delivering the
control, an action objects can indirectly forward one or more share objects, including javabeans by
establish them in the typical situation shared by java servlets.
index.jsp
<%@ taglib uri="/struts-tags" prefix="s" %>
<s:form action="register">
<s:textfield name="name" label="UserName"></s:textfield>
<s:password name="password" label="Password"></s:password>
<s:textfield name="email" label="Email"></s:textfield>
<s:radio list="{'male','female'}" name="gender"></s:radio>
<s:select cssStyle="width:155px;"list="{'india','pakistan','other',}"
name="country" label="Country"></s:select>
s:submit value="register"></s:submit>
</s:form>
RegisterAction.java
package com.javatpoint;
public class RegisterAction {
private String name,password,email,gender,country;
//setters and getters
public String execute(){
int i=RegisterDao.save(this);
if(i>0){
return "success";
}
return "error";
}
}
RegisterDao.java
package com.javatpoint;
import java.sql.*;
public class RegisterDao {
public static int save(RegisterAction r){
int status=0;
try{
Class.forName("oracle.jdbc.driver.OracleDriver");
Connection con=DriverManager.getConnection(
"jdbc:oracle:thin:@localhost:1521:xe","system","oracle");
PreparedStatement ps=con.prepareStatement("insert into strutsuser values(?,?,?,?,?)");
ps.setString(1,r.getName());
ps.setString(2,r.getPassword());
ps.setString(3,r.getEmail());
ps.setString(4,r.getGender());
ps.setString(5,r.getCountry());
status=ps.executeUpdate();
}catch(Exception e){e.printStackTrace();}
return status;
}
struts.xml
<?xml version="1.0" encoding="UTF-8" ?>
<!DOCTYPE struts PUBLIC "-//Apache Software Foundation//DTD
Struts Configuration 2.1//EN" "http://struts.apache.org/dtds/struts-2.1.dtd">
<struts>
<package name="default" extends="struts-default">
<action name="register" class="com.javatpoint.RegisterAction">
<result name="success">register-success.jsp</result>
<result name="error">register-error.jsp</result>
</action>
</package>
</struts>
register-success.jsp
<%@ taglib uri="/struts-tags" prefix="s" %>
Welcome, <s:property value="name"></s:property>
register-error.jsp
<%@ taglib uri="/struts-tags" prefix="s" %>
Sorry, some error occured!
<s:include value="index.jsp"></s:include>
Practical No 3
Objective: Write a program to demonstrate Hibernate application to store employee object to the
database.
Theory: -
What is Hibernate: - Hibernate is a Java framework that simplifies the development of Java
application to interact with the database. It is an open source, lightweight, ORM (Object Relational
Mapping) tool. Hibernate implements the specifications of JPA (Java Persistence API) for data
persistence.
2) Fast Performance
The performance of hibernate framework is fast because cache is internally used in hibernate
framework. There are two types of cache in hibernate framework first level cache and second level
cache. First level cache is enabled by default.
OBJECTIVE: - Write a program to demonstrate getting system date time using NodeJS.
THEORY:- In Node.js date and time are handled with the JavaScript Date object. It is loaded by
default and requires no import of modules.
Getting Current Date and Time as YYYY-MM-DD hh:mm:ss
The current date and time can be fetched by first creating a new Date object. Thereafter methods of
the object can be called to get the date and time values.
To get the timestamp Date.now() method can be called. Note that this method returns the timestamp
in milliseconds. To get the timestamp as seconds we can divide it by 1000.
Getting Date and Time from Timestamp
In order to get the date and time values from a given timestamp, the timestamp is passed as a
parameter to the Date constructor.
Then the above-mentioned methods can be called to get a date and time string.
Note that JavaScript timestamps are specified as milliseconds, so if the given timestamp is in
seconds you will need to convert the same to milliseconds by multiplying with 1000.
PRACTICAL NO: 5
OBJECTIVE: -Write a program to demonstrate Angular Js directives getting firstname and
lastname and showing them in the next line, without refreshing the page
THEORY:- AngularJs was originally developed in 2008-2009 by Misko Hevery and Adam Abrons
and is now maintained by Google. AngularJS is a JavaScript open-source front-end framework that is
mainly used to develop single-page web applications (SPAs). It is a continuously growing and
expanding framework which provides better ways for developing web applications.
Key Points:
AngularJS is a JavaScript framework that is mainly used for Frontend Development.
It is used for making Single Page Applications (SPA).
It is open source and is completely free for everyone.
It uses the Model, View, Control (MVC) pattern for developing projects.
<!DOCTYPE html>
<html >
<head>
<script src="~/Scripts/angular.js"></script>
</head>
<body ng-app>
Enter Name: <input type="text" ng-model="name" /> <br />
data-ng-bind: <span data-ng-bind="name"></span><br />
data-ng:bind: <span data-ng:bind="name"></span><br />
data:ng:bind: <span data:ng:bind="name"></span><br />
x:ng:bind: <span x:ng:bind="name"></span><br />
ng:bind: <span ng:bind="name"></span><br />
x-ng-bind: <span x-ng-bind="name"></span><br />
x_ng_bind: <span x_ng_bind="name"></span><br />
ng_bind: <span ng_bind="name"></span>
</body>
</html>
PRACTICAL NO: 6
THEORY: -Stateless Session bean is a business object that represents business logic only. It
doesn't have state (data). In other words, conversational state between multiple method calls is not
maintained by the container in case of stateless session bean. The stateless bean objects are pooled
by the EJB container to service the request on demand. It can be accessed by one client at a time. In
case of concurrent access, EJB container routes each request to different instance.
EJB Container creates and maintains a pool of session bean first. It injects the dependency if then
calls the @PostConstruct method if any. Now actual business logic method is invoked by the client.
Then, container calls @PreDestory method if any. Now bean is ready for garbage collection.
To develop stateless bean application, we are going to use Eclipse IDE and glassfish 3 server. To
create EJB application, you need to create bean component and bean client.
File: AdderImplRemote.java
package com.javatpoint;
import javax.ejb.Remote;
@Remote
public interface AdderImplRemote {
int add(int a,int b);
}
File: AdderImpl.java
package com.javatpoint;
import javax.ejb.Stateless;
@Stateless(mappedName="st1")
public class AdderImpl implements AdderImplRemote {
public int add(int a,int b){
return a+b;
}
}
File: AdderImpl.java
package com.javatpoint;
import javax.naming.Context;
import javax.naming.InitialContext;
THEORY: -
What is JMS: - JMS (Java Message Service) is an API that provides the facility to create, send and
read messages. It provides loosely coupled, reliable and asynchronous communication. JMS is also
known as a messaging service. Messaging is a technique to communicate applications or software
components. JMS is mainly used to send and receive message from one application to another.
Requirement of JMS
Generally, user sends message to application. But, if we want to send message from one application
to another, we need to use JMS API. Consider a scenario, one application A is running in INDIA and
another application B is running in USA. To send message from A application to B, we need to use
JMS.
Advantage of JMS
1) Asynchronous: To receive the message, client is not required to send request. Message will arrive
automatically to the client.
Messaging Domains
There are two types of messaging domains in JMS.
1. Point-to-Point Messaging Domain
2. Publisher/Subscriber Messaging Domain
File: MySender.java
import java.io.BufferedReader;
import java.io.InputStreamReader;
import javax.naming.*;
import javax.jms.*;
File: MyReceiver.java
import javax.jms.*;
import javax.naming.InitialContext;
import javax.jms.*;
public class MyListener implements MessageListener {
THEORY:-The RMI (Remote Method Invocation) is an API that provides a mechanism to create
distributed application in java. The RMI allows an object to invoke methods on an object running in
another JVM.The RMI provides remote communication between the applications using two
objects stub and skeleton.
Stub
The stub is an object, acts as a gateway for the client side. All the outgoing requests are routed through
it. It resides at the client side and represents the remote object. When the caller invokes method on
the stub object, it does the following tasks: It initiates a connection with remote Virtual Machine
(JVM)
1. It writes and transmits (marshals) the parameters to the remote Virtual Machine (JVM),
2. It waits for the result
3. It reads (unmarshals) the return value or exception, and
4. It finally, returns the value to the caller.
skeleton
The skeleton is an object, acts as a gateway for the server-side object. All the incoming requests are
routed through it. When the skeleton receives the incoming request, it does the following tasks:
1. It reads the parameter for the remote method
2. It invokes the method on the actual remote object, and
3. It writes and transmits (marshals) the result to the caller.
Understanding requirements for the distributed applications
If any application performs these tasks, it can be distributed application.
1. The application needs to locate the remote method
2. It needs to provide the communication with the remote objects, and
3. The application needs to load the class definitions for the objects.
The RMI application have all these features, so it is called the distributed application.
RMI Example
In this example, we have followed all the 6 steps to create and run the rmi application. The client
application need only two files, remote interface and client application. In the rmi application, both
client and server interact with the remote interface. The client application invokes methods on the
proxy object, RMI sends the request to the remote JVM. The return value is sent back to the proxy
object and then to the client application.
1) create the remote interface
For creating the remote interface, extend the Remote interface and declare the RemoteException with
all the methods of the remote interface. Here, we are creating a remote interface that extends the
Remote interface. There is only one method named add () and it declares RemoteException.
import java.rmi.*;
public interface Adder extends Remote{
public int add(int x,int y)throws RemoteException;
In case, you extend the UnicastRemoteObject class, you must define a constructor that declares
RemoteException.
import java.rmi.*;
import java.rmi.server.*;
public class AdderRemote extends UnicastRemoteObject implements Add
{
AdderRemote()throws RemoteException{
super();
}
public int add(int x,int y){return x+y;}
3.Create the stub and skeleton objects using the rmic tool.
Next step is to create stub and skeleton objects using the rmi compiler. The rmic tool invokes the
RMI compiler and creates stub and skeleton objects.
rmic AdderRemote
import java.rmi.*;
import java.rmi.registry.*;
public class MyServer{
public static void main(String args[]){
try{
Adder stub=new AdderRemote();
Naming.rebind("rmi://localhost:5000/sonoo",stub);
}catch(Exception e){System.out.println(e);}
}
}
6.Create and run the client application
At the client we are getting the stub object by the lookup () method of the Naming class and invoking
the method on this object. In this example, we are running the server and client applications, in the
same machine so we are using localhost. If you want to access the remote object from another
machine, change the localhost to the host name (or IP address) where the remote object is located.
import java.rmi.*;
public class MyClient{
public static void main(String args[]){
try{
Adder stub=(Adder)Naming.lookup("rmi://localhost:5000/sonoo");
System.out.println(stub.add(34,4));
}catch(Exception e){}
}
}
For running this rmi example,
1) compile all the java files
javac *.java
THEORY: -
What is Routing?
Routing defines the way in which the client requests are handled by the application endpoints.
Implementation of routing in Node.js: There are two ways to implement routing in node.js
which are listed below:
By Using Framework
Without using Framework
Using Framework: Node has many frameworks to help you to get your server up and running.
The most popular is Express.js.
Routing with Express in Node: Express.js has an “app” object corresponding to HTTP. We define
the routes by using the methods of this “app” object. This app object specifies a call back function,
which is called when a request is received. We have different methods in app object for a different
type of request.
For handling all HTTP methods (i.e. GET, POST, PUT, DELETE etc.) use app.all()
method:
var express = require('express')
var app = express()
app.all('/', function(req, res) {
console.log('Hello Sir')
next() // Pass the control to the next handler
})
The next () is used to hand off the control to the next callback. Sometimes we use app.use() to
specify the middleware function as the callback. So, to perform routing with the Express.js
you have only to load the express and then use the app object to handle the callbacks
according to the requirement.
Routing without Framework: Using the frameworks is good to save time, but sometimes this
may not suit the situation. So, a developer may need to build up their own server without other
dependencies.
Now create a file with any name using .js extension and follow the steps to perform routing from
scratch:
Here we will use the built-in module of node.js i.e. http. So, First load http:
var http = require('http');
// http header
res.writeHead(200, {'Content-Type': 'text/html'});
if(url ==='/about') {
res.write(' Welcome to about us page');
res.end();
}
else if(url ==='/contact') {
res.write(' Welcome to contact us page');
res.end();
}
else {
res.write('Hello World!');
res.end();
}
}).listen(3000, function() {
Output :
PRACTICAL NO :10
PROJECT SCENARIO: Discuss Software Architecture Design for your project
development domain along with quality attributes you consider as prime. Which
architecture style, pattern and framework you prefer and why?
THEORY: -
Software architecture pattern plays a crucial role in its ability to scale and meet users’ demands over
the time. This discussion covers different types of software architecture patterns, their importance,
and comparative analysis to help you choose the best one.
Flaws in any software have a significant impact on the business of an organization. The main reason
for any software failure can be the selection of wrong software architecture patterns. But with prior
knowledge, you would be able to guide designers and developers in designing the components and
the ways they react.
It is often seen that companies start the process of application development without a formal
architecture in place. However, they tend to miss that the absence of an architectural pattern can force
the developing team to adopt a traditional pattern with no guidelines. Eventually, they end up with
codes that lack clear roles, responsibilities, and relationships with one another.
For instance, an online banking application would not require a complex architecture like a
microservices pattern. It can simply be developed using a client-server architecture for fetching
requests. But, without this planning, the application might become complex with no scope of going
back or losing a huge investment in the restructuring process. Planning an architecture pattern helps
in analysing risks beforehand and avoids any adverse impact on the business.
To have a clear understanding, let us explore what software architecture patterns are and a full
explanation of some of its types.
Even though an architectural pattern is a rough image or blueprint of your system, it’s not the actual
architecture. Instead, it’s a concept that helps you to understand the elements of software architecture.
There can be countless pieces of architecture that implement the same pattern. That’s why patterns
are known as “strictly described and commonly utilized.” The success of the system depends on
software architecture selection.
Famous examples of architectural patterns are microservices, message bus, service requester/
consumer, MVC pattern, MVVM, microkernel, n-tier, domain-driven design components, and
presentation-abstraction-control.
Software architecture patterns hold significant importance for it can solve various problems within
different domains. For instance, instead of depending on a single server, complex user requests can
be easily segmented into smaller chunks and distributed across multiple servers. In another example,
testing protocols can be simplified by dividing various segments of the software rather than testing
the whole thing at once.
Here are some more reasons why software architecture patterns are vital for any software application:
Providing Agility:
It is natural for software applications to undergo numerous modifications and iterations during
software development and even after production. Therefore, planning a core software architecture
beforehand provides agility to the application and makes future moderations effortless.
Problem Solving:
Prior planning and knowledge of a software architecture give a clear idea of how the application and
its components will function. With an architecture in place, the developing team can adopt the best
practices to resolve complex processes and solve any errors in the future.
Enhancing Productivity:
Irrespective of the skills and knowledge one has about a programming language, framework, or
application, there has to be certain standardized principles. With an appropriate application pattern
in place, the company can quickly grasp the project’s status. In addition, productivity rates improve
the moment an architecture pattern is in place to make the project scope clear.
Software architecture pattern vs. design pattern
There is a thin line between an architecture pattern and a design pattern, and most people get confused
between the two. For basics, let’s imagine your team given a task to build a house and live in it.
To begin with the task, they would first have to plan it out before placing bricks and cement on an
empty ground. Moreover, even after a house is planned, there is more to making it worth living –
they would need basic amenities like kitchen appliances, beddings, toiletries, and many more. In this
analogy, how the house should look represents architectural patterns, whereas the interior design of
the house represents the design patterns.
In a software system, architecture is considered when you have to create business logic, database
logic, UI, etc., whereas software design patterns are used while implementing business logic or
database logic.
SOFTWARE DEVELOPMENT MODEL:
We have chosen “Iterative Life-Cycle Model” for developing this application, because an iterative life cycle
does not attempt to start with a full requirement specification. Instead, the development begins by specifying
and implementing the parts of the software, which can then be reviewed in order to identify the further
requirements or in case any changes required. This process is then repeated, producing a new version of the
software in each cycle of the model.
The below diagram depicts the working of an Iterative Life Cycle Model:
In an iterative model we build and improve the product step by step. Hence it becomes easy to track
the defects at early stages. This helps in avoiding the downward flow of the defects.
Testing and debugging in smaller iterations is easy.
In iteration model we can get reliable feedback and insights from the user.
Progress can be measured clearly.
In iterative model less time is spent in documentation and more time is devoted in designing then
software.
Risks are identified and resolved during iterations, and each iteration is considered as a milestone. It
supports the changing requirements.