Professional Documents
Culture Documents
MCS 220 EM 2021-22
MCS 220 EM 2021-22
tech
• Telegram - https://t.me/DalalTechnologies
• YouTube-https://www.youtube.com/channel/UCilEr1rW-SIrJlJ5_ioKQfw
• Website-Https://DalalTechnologies.in
Singleton Pattern says that just"define a class that has only one instance and provides a global point of access
to it".
In other words, a class must ensure that only single instance should be created and single object can be used by all
other classes.
Early Instantiation:-
In such case, we create the instance of the class at the time of declaring the static data member, so instance of the
class is created at the time of classloading.
Let's see the example of singleton design pattern using early instantiation.
1. class A{
2. private static A obj=new A();//Early, instance will be created at load time
3. private A(){}
4.
5. public static A getA(){
6. return obj;
7. }
8.
9. public void doSomething(){
10. //write your code
11. }
12. }
Lazy Instantiation:
Let's see the simple example of singleton design pattern using lazy instantiation.
1. class A{
2. private static A obj;
3. private A(){}
Disclaimer/Note
These are just the sample of the answers/solution to some of the questions given in the assignments. Student should read and refer the official study material provided by
the university.
• Facebook-https://www.facebook.com/dalal.tech
• Telegram - https://t.me/DalalTechnologies
• YouTube-https://www.youtube.com/channel/UCilEr1rW-SIrJlJ5_ioKQfw
• Website-Https://DalalTechnologies.in
4.
5. public static A getA(){
6. if (obj == null){
7. synchronized(Singleton.class){
8. if (obj == null){
9. obj = new Singleton();//instance will be created at request time
10. }
11. }
12. }
13. return obj;
14. }
15.
16. public void doSomething(){
17. //write your code
18. }
19. }
A servlet life cycle can be defined as the entire process from its creation till the destruction. The following are the
paths followed by a servlet.
• The servlet is initialized by calling the init() method.
• The servlet calls service() method to process a client's request.
• The servlet is terminated by calling the destroy() method.
• Finally, servlet is garbage collected by the garbage collector of the JVM.
Now let us discuss the life cycle methods in detail.
The init() Method
The init method is called only once. It is called only when the servlet is created, and not called for any user requests
afterwards. So, it is used for one-time initializations, just as with the init method of applets.
The servlet is normally created when a user first invokes a URL corresponding to the servlet, but you can also specify
that the servlet be loaded when the server is first started.
When a user invokes a servlet, a single instance of each servlet gets created, with each user request resulting in a new
thread that is handed off to doGet or doPost as appropriate. The init() method simply creates or loads some data that
will be used throughout the life of the servlet.
The init method definition looks like this −
public void init() throws ServletException {
// Initialization code...
}
Disclaimer/Note
These are just the sample of the answers/solution to some of the questions given in the assignments. Student should read and refer the official study material provided by
the university.
• Facebook-https://www.facebook.com/dalal.tech
• Telegram - https://t.me/DalalTechnologies
• YouTube-https://www.youtube.com/channel/UCilEr1rW-SIrJlJ5_ioKQfw
• Website-Https://DalalTechnologies.in
The service () method is called by the container and service method invokes doGet, doPost, doPut, doDelete, etc.
methods as appropriate. So you have nothing to do with service() method but you override either doGet() or doPost()
depending on what type of request you receive from the client.
The doGet() and doPost() are most frequently used methods with in each service request. Here is the signature of
these two methods.
The doGet() Method
A GET request results from a normal request for a URL or from an HTML form that has no METHOD specified and it
should be handled by doGet() method.
public void doGet(HttpServletRequest request, HttpServletResponse response)
throws ServletException, IOException {
// Servlet code
}
These are just the sample of the answers/solution to some of the questions given in the assignments. Student should read and refer the official study material provided by
the university.
• Facebook-https://www.facebook.com/dalal.tech
• Telegram - https://t.me/DalalTechnologies
• YouTube-https://www.youtube.com/channel/UCilEr1rW-SIrJlJ5_ioKQfw
• Website-Https://DalalTechnologies.in
// Finalization code...
}
Architecture Diagram
The following figure depicts a typical servlet life-cycle scenario.
• First the HTTP requests coming to the server are delegated to the servlet container.
• The servlet container loads the servlet before invoking the service() method.
• Then the servlet container handles multiple requests by spawning multiple threads, each thread executing the
service() method of a single instance of the servlet.
Servlets are Java classes which service HTTP requests and implement the javax.servlet.Servlet interface. Web
application developers typically write servlets that extend javax.servlet.http.HttpServlet, an abstract class that
implements the Servlet interface and is specially designed to handle HTTP requests.
Q3. What are implicit objects in JSP? Briefly explain all the JSP implicit objects.
Ans:- JSP stands for Java Server Pages, and it’s a server side technology. It’s used for creating web
applications and dynamic web content. The main property of JSP is that we can insert our java code
inside our HTML page using JSP tag. JSP provides you platform-independent pages.
Total 9 implicit objects which are as follows
1. request: This is the object of HttpServletRequest class associated with the request.
2. response: This is the object of HttpServletResponse class associated with the response to the client.
3. config: This is the object of ServletConfig class associated with the page.
4. application: This is the object of ServletContext class associated with the application context.
5. session: This is the object of HttpSession class associated with the request.
6. page context: This is the object of PageContext class that encapsulates the use of server-specific features.
This object can be used to find, get or remove an attribute.
7. page object: The manner we use the keyword this for current object, page object is used to refer to the
current translated servlet class.
8. exception: The exception object represents all errors and exceptions which is accessed by the respective
jsp. The exception implicit object is of type java.lang.Throwable.
9. out: This is the PrintWriter object where methods like print and println help for displaying the content
to the client.
Disclaimer/Note
These are just the sample of the answers/solution to some of the questions given in the assignments. Student should read and refer the official study material provided by
the university.
• Facebook-https://www.facebook.com/dalal.tech
• Telegram - https://t.me/DalalTechnologies
• YouTube-https://www.youtube.com/channel/UCilEr1rW-SIrJlJ5_ioKQfw
• Website-Https://DalalTechnologies.in
The JSP request is an implicit object which is provided by HttpServletRequest. In the servlet, we have
to first import javax.servlet.http.HttpServletRequest then we have to create its object for taking input
from any HTML form as.
Syntax :
import javax.servlet.http.HttpServletRequest;
In JSP, the request object is implicitly defined so that you don’t have to create an object. JSP request
object is created by the web container for each request of the client. It’s used for getting the
parameter value, server name, server port, etc.
In the below example we are using a request object to display the username.
response object
This is the HttpServletResponse object associated with the response to the client. The response object
also defines the interfaces that deal with creating new HTTP headers. Through this object the JSP
programmer can add new cookies or date stamps, HTTP status codes, etc.
In JSP the response object is implicitly defined, so you don’t have to create an object. JSP response
object is created by the web container for each request of the client. It basically is used for redirecting
to any other resource.
In the below example we use the response object to send the user on Geeksforgeeks homepage.
Ans:-
1. Spring MVC :
Spring is widely used for creating scalable applications. For web applications Spring provides Spring
MVC framework which is a widely used module of spring which is used to create scalable web
applications. Spring MVC framework enables the separation of modules namely Model View,
Controller, and seamlessly handles the application integration. This enables the developer to create
complex applications also using plain java classes. The model object can be passed between view
and controller using maps. In this article, we will see how to set up a Spring MVC application in the
Eclipse IDE and understand how to make applications.
Disclaimer/Note
These are just the sample of the answers/solution to some of the questions given in the assignments. Student should read and refer the official study material provided by
the university.
• Facebook-https://www.facebook.com/dalal.tech
• Telegram - https://t.me/DalalTechnologies
• YouTube-https://www.youtube.com/channel/UCilEr1rW-SIrJlJ5_ioKQfw
• Website-Https://DalalTechnologies.in
2. Spring Boot :
Spring Boot is built on top of the conventional spring framework. So, it provides all the features of
spring and is yet easier to use than spring. Spring Boot is a microservice-based framework and
making a production-ready application in very less time. In Spring Boot everything is auto-
configured. We just need to use proper configuration for utilizing a particular functionality. Spring
Boot is very useful if we want to develop REST API. Spring Boot provides the facility to convert our
project into war or jar files. Also, the instance of Tomcat can be run on the cloud as well.
Q5. How a simple CRUD application can be developed using Hibernate? Explain briefly.
Ans:-
Step 1
First create the database schema and tables to perform the CRUD operations
Copy and run the below scripts in the MySQL command window or MySQL workbench(GUI Tool) –
> SQL Editor
mysql –u root –p
These are just the sample of the answers/solution to some of the questions given in the assignments. Student should read and refer the official study material provided by
the university.
• Facebook-https://www.facebook.com/dalal.tech
• Telegram - https://t.me/DalalTechnologies
• YouTube-https://www.youtube.com/channel/UCilEr1rW-SIrJlJ5_ioKQfw
• Website-Https://DalalTechnologies.in
1. desc users;
Step 2
Create a Java Maven web project in eclipse and setup Hibernate
Step 3
Create the hibernate configuration file
hibernate.cfg.xml
These are just the sample of the answers/solution to some of the questions given in the assignments. Student should read and refer the official study material provided by
the university.
• Facebook-https://www.facebook.com/dalal.tech
• Telegram - https://t.me/DalalTechnologies
• YouTube-https://www.youtube.com/channel/UCilEr1rW-SIrJlJ5_ioKQfw
• Website-Https://DalalTechnologies.in
Disclaimer/Note
These are just the sample of the answers/solution to some of the questions given in the assignments. Student should read and refer the official study material provided by
the university.
• Facebook-https://www.facebook.com/dalal.tech
• Telegram - https://t.me/DalalTechnologies
• YouTube-https://www.youtube.com/channel/UCilEr1rW-SIrJlJ5_ioKQfw
• Website-Https://DalalTechnologies.in
33.
34. <mapping resource="com/kb/mapping/user.hbm.xml"/>
35.
36. </session-factory>
37.
38. </hibernate-configuration>
We have added database settings and mapping resource in the above configuration file.
Step 4
Create a User model class under src/main/java/com/kb/model package
1. package com.kb.model;
2.
3. import java.util.Date;
4.
5. public class User {
6. private int id;
7. private String firstName;
8. private String lastName;
9. private Date dob;
10. private String email;
11. public int getId() {
12. return id;
13. }
14. public void setId(int id) {
15. this.id = id;
16. }
17. public String getFirstName() {
18. return firstName;
19. }
20. public void setFirstName(String firstName) {
21. this.firstName = firstName;
Disclaimer/Note
These are just the sample of the answers/solution to some of the questions given in the assignments. Student should read and refer the official study material provided by
the university.
• Facebook-https://www.facebook.com/dalal.tech
• Telegram - https://t.me/DalalTechnologies
• YouTube-https://www.youtube.com/channel/UCilEr1rW-SIrJlJ5_ioKQfw
• Website-Https://DalalTechnologies.in
22. }
23. public String getLastName() {
24. return lastName;
25. }
26. public void setLastName(String lastName) {
27. this.lastName = lastName;
28. }
29. public Date getDob() {
30. return dob;
31. }
32. public void setDob(Date dob) {
33. this.dob = dob;
34. }
35. public String getEmail() {
36. return email;
37. }
38. public void setEmail(String email) {
39. this.email = email;
40. }
41. }
Step 5
Create the mapping file for User Model under src/main/resources/com/kb/mapping folder(create
this folder if not exist)
user.hbm.xml
These are just the sample of the answers/solution to some of the questions given in the assignments. Student should read and refer the official study material provided by
the university.
• Facebook-https://www.facebook.com/dalal.tech
• Telegram - https://t.me/DalalTechnologies
• YouTube-https://www.youtube.com/channel/UCilEr1rW-SIrJlJ5_ioKQfw
• Website-Https://DalalTechnologies.in
Step 6
Create a new Utility class called HibernateUtil.java under src/main/java/com/kb/util package
1. package com.kb.util;
2.
3. import org.hibernate.SessionFactory;
4. import org.hibernate.cfg.Configuration;
5.
6. public class HibernateUtil {
7. private static final SessionFactory sessionFactory = buildSessionFactory();
8.
9. private static SessionFactory buildSessionFactory() {
10. try {
Disclaimer/Note
These are just the sample of the answers/solution to some of the questions given in the assignments. Student should read and refer the official study material provided by
the university.
• Facebook-https://www.facebook.com/dalal.tech
• Telegram - https://t.me/DalalTechnologies
• YouTube-https://www.youtube.com/channel/UCilEr1rW-SIrJlJ5_ioKQfw
• Website-Https://DalalTechnologies.in
Step 7
Create DAO class to interact with Database under src/main/java/com/kb/dao package
UserDao.java
1. package com.kb.dao;
2.
3. import java.util.ArrayList;
4. import java.util.List;
5.
6. import org.hibernate.Session;
7. import org.hibernate.Transaction;
Disclaimer/Note
These are just the sample of the answers/solution to some of the questions given in the assignments. Student should read and refer the official study material provided by
the university.
• Facebook-https://www.facebook.com/dalal.tech
• Telegram - https://t.me/DalalTechnologies
• YouTube-https://www.youtube.com/channel/UCilEr1rW-SIrJlJ5_ioKQfw
• Website-Https://DalalTechnologies.in
8. import org.hibernate.query.Query;
9.
10. import com.kb.model.User;
11. import com.kb.util.HibernateUtil;
12.
13. public class UserDao {
14.
15. //Create of CRUD
16. public void addUser(User user) {
17. Transaction trns = null;
18. Session session = HibernateUtil.getSessionFactory().openSession();
19. try {
20. trns = session.beginTransaction();
21. session.save(user);
22. session.getTransaction().commit();
23. } catch (RuntimeException e) {
24. if (trns != null) {
25. trns.rollback();
26. }
27. e.printStackTrace();
28. } finally {
29. session.flush();
30. session.close();
31. }
32. }
33.
34. //Read of CRUD
35. @SuppressWarnings("unchecked")
36. public List<User> getAllUsers() {
37. List<User> users = new ArrayList<User>();
Disclaimer/Note
These are just the sample of the answers/solution to some of the questions given in the assignments. Student should read and refer the official study material provided by
the university.
• Facebook-https://www.facebook.com/dalal.tech
• Telegram - https://t.me/DalalTechnologies
• YouTube-https://www.youtube.com/channel/UCilEr1rW-SIrJlJ5_ioKQfw
• Website-Https://DalalTechnologies.in
Disclaimer/Note
These are just the sample of the answers/solution to some of the questions given in the assignments. Student should read and refer the official study material provided by
the university.
• Facebook-https://www.facebook.com/dalal.tech
• Telegram - https://t.me/DalalTechnologies
• YouTube-https://www.youtube.com/channel/UCilEr1rW-SIrJlJ5_ioKQfw
• Website-Https://DalalTechnologies.in
68.
69. //Update of CRUD
70. public void updateUser(User user) {
71. Transaction trns = null;
72. Session session = HibernateUtil.getSessionFactory().openSession();
73. try {
74. trns = session.beginTransaction();
75. session.update(user);
76. session.getTransaction().commit();
77. } catch (RuntimeException e) {
78. if (trns != null) {
79. trns.rollback();
80. }
81. e.printStackTrace();
82. } finally {
83. session.flush();
84. session.close();
85. }
86. }
87.
88. //Delete of CRUD
89. public void deleteUser(int userid) {
90. Transaction trns = null;
91. Session session = HibernateUtil.getSessionFactory().openSession();
92. try {
93. trns = session.beginTransaction();
94. User user = (User) session.load(User.class, new Integer(userid));
95. session.delete(user);
96. session.getTransaction().commit();
97. } catch (RuntimeException e) {
Disclaimer/Note
These are just the sample of the answers/solution to some of the questions given in the assignments. Student should read and refer the official study material provided by
the university.
• Facebook-https://www.facebook.com/dalal.tech
• Telegram - https://t.me/DalalTechnologies
• YouTube-https://www.youtube.com/channel/UCilEr1rW-SIrJlJ5_ioKQfw
• Website-Https://DalalTechnologies.in
In the above class,we have created method for each CRUD operation and performing appropriate
operation in it.
Step 8
Create Service class to interact with DAO layer under src/main/java/com/kb/service package
UserService.java
1. package com.kb.service;
2.
3. import java.util.List;
4.
5. import com.kb.dao.UserDao;
6. import com.kb.model.User;
7.
8. public class UserService {
9.
10. private UserDao userDao;
11.
12. //Create of CRUD
13. public void addUser(User user) {
14. userDao.addUser(user);
Disclaimer/Note
These are just the sample of the answers/solution to some of the questions given in the assignments. Student should read and refer the official study material provided by
the university.
• Facebook-https://www.facebook.com/dalal.tech
• Telegram - https://t.me/DalalTechnologies
• YouTube-https://www.youtube.com/channel/UCilEr1rW-SIrJlJ5_ioKQfw
• Website-Https://DalalTechnologies.in
15. }
16.
17. //Read of CRUD
18. public List<User> getAllUsers() {
19. return userDao.getAllUsers();
20. }
21.
22. //Read of CRUD
23. public User getUserById(int userid) {
24. return userDao.getUserById(userid);
25. }
26.
27. //Update of CRUD
28. public void updateUser(User user) {
29. userDao.updateUser(user);
30. }
31.
32. //Delete of CRUD
33. public void deleteUser(int userid) {
34. userDao.deleteUser(userid);
35. }
36.
37. public UserDao getUserDao() {
38. return userDao;
39. }
40.
41. public void setUserDao(UserDao userDao) {
42. this.userDao = userDao;
43. }
44. }
Disclaimer/Note
These are just the sample of the answers/solution to some of the questions given in the assignments. Student should read and refer the official study material provided by
the university.
• Facebook-https://www.facebook.com/dalal.tech
• Telegram - https://t.me/DalalTechnologies
• YouTube-https://www.youtube.com/channel/UCilEr1rW-SIrJlJ5_ioKQfw
• Website-Https://DalalTechnologies.in
Step 9
Create Main client class to perform CRUD operations under src/main/java/com/kb/client package
UserClient.java
1. package com.kb.client;
2.
3. import java.text.ParseException;
4. import java.text.SimpleDateFormat;
5. import java.util.Date;
6.
7. import com.kb.dao.UserDao;
8. import com.kb.model.User;
9. import com.kb.service.UserService;
10.
11. public class UserClient {
12. public static void main(String[] args) {
13. UserService userService = new UserService();
14. UserDao userDao = new UserDao();
15. userService.setUserDao(userDao);
16.
17. // Add new user - Create of CRUD
18. User user1 = new User();
19. user1.setFirstName("John");
20. user1.setLastName("JC");
21. try {
22. Date dob = new SimpleDateFormat("yyyy-MM-dd").parse("1995-01-01");
23. user1.setDob(dob);
24. } catch (ParseException e) {
25. e.printStackTrace();
26. }
27. user1.setEmail("john@sample.com");
Disclaimer/Note
These are just the sample of the answers/solution to some of the questions given in the assignments. Student should read and refer the official study material provided by
the university.
• Facebook-https://www.facebook.com/dalal.tech
• Telegram - https://t.me/DalalTechnologies
• YouTube-https://www.youtube.com/channel/UCilEr1rW-SIrJlJ5_ioKQfw
• Website-Https://DalalTechnologies.in
Disclaimer/Note
These are just the sample of the answers/solution to some of the questions given in the assignments. Student should read and refer the official study material provided by
the university.
• Facebook-https://www.facebook.com/dalal.tech
• Telegram - https://t.me/DalalTechnologies
• YouTube-https://www.youtube.com/channel/UCilEr1rW-SIrJlJ5_ioKQfw
• Website-Https://DalalTechnologies.in
58. user1.setEmail("johnUpdated@sample.com");
59. user1.setId(1);
60. userService.updateUser(user1);
61.
62. // Delete user - Delete of CRUD
63. userService.deleteUser(1);
64.
65. }
66. }
output
We can see only one Record with Id “2” in the table as other record with id ”1” got inserted and deleted.
Initially started as an ORM framework, Hibernate has spun off into many projects, such as Hibernate
Search, Hibernate Validator, Hibernate OGM (for NoSQL databases), and so on.
Hibernate Architecture
The following diagram summarizes the main building blocks in hibernate architecture.
Disclaimer/Note
These are just the sample of the answers/solution to some of the questions given in the assignments. Student should read and refer the official study material provided by
the university.
• Facebook-https://www.facebook.com/dalal.tech
• Telegram - https://t.me/DalalTechnologies
• YouTube-https://www.youtube.com/channel/UCilEr1rW-SIrJlJ5_ioKQfw
• Website-Https://DalalTechnologies.in
Hibernate Architecture
Let’s understand what each block represents.
These are just the sample of the answers/solution to some of the questions given in the assignments. Student should read and refer the official study material provided by
the university.
• Facebook-https://www.facebook.com/dalal.tech
• Telegram - https://t.me/DalalTechnologies
• YouTube-https://www.youtube.com/channel/UCilEr1rW-SIrJlJ5_ioKQfw
• Website-Https://DalalTechnologies.in
@Entity
@Table(name = "EMPLOYEE")
public class Employee {
@Id @GeneratedValue
@Column(name = "id")
private int id;
@Column(name = "first_name")
private String firstName;
@Column(name = "last_name")
private String lastName;
@Column(name = "salary")
private int salary;
public Employee() {}
These are just the sample of the answers/solution to some of the questions given in the assignments. Student should read and refer the official study material provided by
the university.
• Facebook-https://www.facebook.com/dalal.tech
• Telegram - https://t.me/DalalTechnologies
• YouTube-https://www.youtube.com/channel/UCilEr1rW-SIrJlJ5_ioKQfw
• Website-Https://DalalTechnologies.in
Q7. Explain how Java Socket Extension (JSSE) is used in Web Security.
Ans:-
The Internet is a dangerous place. It's simply too easy to snoop, spoof, and steal unprotected information as it
travels over the wires. Last month, I wrote the final article in a series on X.509 certificates and public key
infrastructure (PKI), the technologies that secure most e-commerce activity on the Internet. Near the end of the
article, I suggested looking at the SSL (Secure Socket Layer) protocol to learn how X.509 certificates are used in
practice. SSL is the X.509 killer app -- nearly every browser and most popular Web and application servers support
it.
This month, I will explore SSL as implemented by the JSSE (Java Secure Socket Extension), and show you how to
build secure network applications in Java using SSL and JSSE.
Let's begin with a simple demonstration. JSSE provides an SSL toolkit for Java applications. In addition to the
necessary classes and interfaces, JSSE provides a handy command-line debugging switch that you can use
to watch the SSL protocol in action. In addition to providing useful information for debugging a recalcitrant
application, playing with the toolkit is a great way to get your feet wet with SSL and JSSE.
To run the demonstration, you must first compile the following class:
public
class Test
{
public
static
void
main(String [] arstring)
{
try
{
new java.net.URL("https://" + arstring[0] + "/").getContent();
}
catch (Exception exception)
{
exception.printStackTrace();
}
}
Disclaimer/Note
These are just the sample of the answers/solution to some of the questions given in the assignments. Student should read and refer the official study material provided by
the university.
• Facebook-https://www.facebook.com/dalal.tech
• Telegram - https://t.me/DalalTechnologies
• YouTube-https://www.youtube.com/channel/UCilEr1rW-SIrJlJ5_ioKQfw
• Website-Https://DalalTechnologies.in
Next, you need to turn on SSL debugging and run the above application. The application connects to the secure
Website that you specify on the command line using the SSL protocol via HTTPS. The first option loads the HTTPS
protocol handler. The second option, the debug option, causes the program to print out its behavior. Here's the
command (replace <host> with the name of a secure Web server):
Before I show you how to add that flexibility, let's take a quick look at SSL's features.
As its name suggests, SSL aims to provide applications with a secure socketlike toolkit. Ideally, it should be easy to
convert an application that uses regular sockets into an application that uses SSL.
It provides authentication, which helps ensure the legitimacy of the entities involved in a dialog.
It provides privacy. SSL helps warrant that a third party cannot decipher the dialog between two entities.
It maintains integrity. The use of a MAC (message authentication code), which is similar to a checksum, helps
guarantee that a dialog between two entities is not modified by a third party.
SSL relies heavily on both public-key and secret-key cryptography. It uses secret-key cryptography to bulk-encrypt
the data exchanged between two applications. SSL provides the ideal solution because secret-key algorithms are
both secure and fast. Public-key cryptography, which is slower than secret-key cryptography, is a better choice for
authentication and key exchange.
Sun's JSSE reference implementation comes with all the technology necessary to add SSL to your applications. It
includes RSA (Rivest-Shamir-Adleman) cryptography support -- the de facto standard for security on the Internet.
It includes an implementation of SSL 3.0 -- the current SSL standard -- and TLS (Transport Layer Security) 1.0, the
next generation of SSL. JSSE also provides a suite of APIs for creating and using secure sockets.
In JSSE, everything begins with the factory; there's a factory for SSL sockets and a factory for SSL server sockets.
Since generic sockets and server sockets are already quite fundamental to Java network programming, I'll assume
that you're familiar with the two and you understand their roles and differences. If you are not, I recommend
picking up a good book on Java network programming.
Disclaimer/Note
These are just the sample of the answers/solution to some of the questions given in the assignments. Student should read and refer the official study material provided by
the university.
• Facebook-https://www.facebook.com/dalal.tech
• Telegram - https://t.me/DalalTechnologies
• YouTube-https://www.youtube.com/channel/UCilEr1rW-SIrJlJ5_ioKQfw
• Website-Https://DalalTechnologies.in
SSLSocketFactory
Methods in the javax.net.ssl.SSLSocketFactory class fall into three categories. The first consists of a single static
method that retrieves the default SSL socket factory: static SocketFactory getDefault().
The second category consists of four methods inherited from javax.net.SocketFactory that mirror the four key
constructors found on the java.net.Socket class, and one method that wraps an existing socket with an SSL socket.
They each return an SSL socket:
String [] getDefaultCipherSuites()
String [] getSupportedCipherSuites()
A cipher suite is a combination of cryptographic algorithms that define a particular level of security for an SSL
connection. A cipher suite defines whether the connection is encrypted, whether content integrity is verified, and
how authentication occurs.
SSLServerSocketFactory
Methods on the javax.net.ssl.SSLServerSocketFactory class fall into the same three categories as SSLSocketFactory.
First, there is the single static method that retrieves the default SSL server socket factory: static
ServerSocketFactory getDefault().
The methods that return SSL server sockets mirror the constructors found in the java.net.ServerSocket class:
String [] getDefaultCipherSuites()
String [] getSupportedCipherSuites()
So far, the API is pretty straightforward.
SSLSocket
Things get interesting in the javax.net.ssl.SSLSocket class. I assume you are already familiar with the methods
provided by its parent, the Socket class, so I will concentrate on the methods that provide SSL-related functionality.
Like the two SSL factory classes, the first two methods listed below retrieve the enabled and supported SSL cipher
suites, respectively. The third method sets the enabled cipher suites. An application can use the third operation to
upgrade or downgrade the range of acceptable security that the application will allow:
String [] getEnabledCipherSuites()
String [] getSupportedCipherSuites()
void setEnabledCipherSuites(String [] suites)
Disclaimer/Note
These are just the sample of the answers/solution to some of the questions given in the assignments. Student should read and refer the official study material provided by
the university.
• Facebook-https://www.facebook.com/dalal.tech
• Telegram - https://t.me/DalalTechnologies
• YouTube-https://www.youtube.com/channel/UCilEr1rW-SIrJlJ5_ioKQfw
• Website-Https://DalalTechnologies.in
These two methods determine whether the socket can establish new SSL sessions, which maintain connection
details -- like the shared secret key -- between connections:
boolean getEnableSessionCreation()
void setEnableSessionCreation(boolean flag)
The next two methods determine whether the socket will require client authentication. The methods only make
sense when invoked on server mode sockets. Remember, according to the SSL specification, client authentication
is optional. For example, most Web applications don't require it:
boolean getNeedClientAuth()
void setNeedClientAuth(boolean need)
The methods below change the socket from client mode to server mode. This affects who initiates the SSL
handshake and who authenticates first:
boolean getUseClientMode()
void setUseClientMode(boolean mode)
Method void startHandshake() forces an SSL handshake. It's possible, but not common, to force a new handshake
operation in an existing connection.
Method SSLSession getSession() retrieves the SSL session. You will seldom need to access the SSL session directly.
The two methods listed below add and remove an SSL handshake listener object. The handshake listener object is
notified whenever an SSL handshake operation completes on the socket.
The first two methods listed below retrieve the enabled and supported SSL cipher suites. The third method sets
the enabled cipher suite:
String [] getEnabledCipherSuites()
String [] getSupportedCipherSuites()
void setEnabledCipherSuites(String [] suites)
These two methods control whether or not the server socket can establish new SSL sessions:
boolean getEnableSessionCreation()
void setEnableSessionCreation(boolean flag)
The following methods determine whether the accepted sockets will require client authentication:
boolean getNeedClientAuth()
void setNeedClientAuth(boolean flag)
The methods below change the accepted socket from client mode to server mode:
boolean getUseClientMode()
void setUseClientMode(boolean flag)
Disclaimer/Note
These are just the sample of the answers/solution to some of the questions given in the assignments. Student should read and refer the official study material provided by
the university.
• Facebook-https://www.facebook.com/dalal.tech
• Telegram - https://t.me/DalalTechnologies
• YouTube-https://www.youtube.com/channel/UCilEr1rW-SIrJlJ5_ioKQfw
• Website-Https://DalalTechnologies.in
A simple example
To make this toolkit tutorial clearer, I've included the source code for a simple server and a compatible client
below. It's a secure variation on the typical echo application that many introductory networking texts provide.
The server, shown below, uses JSSE to create a secure server socket. It listens on the server socket for connections
from secure clients. When running the server, you must specify the keystore to use. The keystore contains the
server's certificate. I have created a simple keystore that contains a single certificate. (See Resources to download
the certificate.)
import java.io.InputStream;
import java.io.InputStreamReader;
import java.io.BufferedReader;
import java.io.IOException;
import javax.net.ssl.SSLSocket;
import javax.net.ssl.SSLServerSocket;
import javax.net.ssl.SSLServerSocketFactory;
public
class EchoServer
{
public
static
void
main(String [] arstring)
{
try
{
SSLServerSocketFactory sslserversocketfactory =
(SSLServerSocketFactory)SSLServerSocketFactory.getDefault();
SSLServerSocket sslserversocket =
(SSLServerSocket)sslserversocketfactory.createServerSocket(9999);
SSLSocket sslsocket = (SSLSocket)sslserversocket.accept();
InputStream inputstream = sslsocket.getInputStream();
InputStreamReader inputstreamreader = new InputStreamReader(inputstream);
BufferedReader bufferedreader = new BufferedReader(inputstreamreader);
String string = null;
while ((string = bufferedreader.readLine()) != null)
{
System.out.println(string);
System.out.flush();
}
}
catch (Exception exception)
{
exception.printStackTrace();
}
}
}
Use the following command to start the server (foobar is both the name of the keystore file and its password):
Disclaimer/Note
These are just the sample of the answers/solution to some of the questions given in the assignments. Student should read and refer the official study material provided by
the university.
• Facebook-https://www.facebook.com/dalal.tech
• Telegram - https://t.me/DalalTechnologies
• YouTube-https://www.youtube.com/channel/UCilEr1rW-SIrJlJ5_ioKQfw
• Website-Https://DalalTechnologies.in
The client, shown below, uses JSSE to securely connect to the server. When running the client, you must specify
the truststore to use, which contains the list of trusted certificates. I have created a simple truststore that contains
a single certificate. (See Resources to download the certificate.)
import java.io.InputStream;
import java.io.OutputStream;
import java.io.InputStreamReader;
import java.io.OutputStreamWriter;
import java.io.BufferedReader;
import java.io.BufferedWriter;
import java.io.IOException;
import javax.net.ssl.SSLSocket;
import javax.net.ssl.SSLSocketFactory;
public
class EchoClient
{
public
static
void
main(String [] arstring)
{
try
{
SSLSocketFactory sslsocketfactory = (SSLSocketFactory)SSLSocketFactory.getDefault();
SSLSocket sslsocket = (SSLSocket)sslsocketfactory.createSocket("localhost", 9999);
InputStream inputstream = System.in;
InputStreamReader inputstreamreader = new InputStreamReader(inputstream);
BufferedReader bufferedreader = new BufferedReader(inputstreamreader);
OutputStream outputstream = sslsocket.getOutputStream();
OutputStreamWriter outputstreamwriter = new OutputStreamWriter(outputstream);
BufferedWriter bufferedwriter = new BufferedWriter(outputstreamwriter);
String string = null;
while ((string = bufferedreader.readLine()) != null)
{
bufferedwriter.write(string + '\n');
bufferedwriter.flush();
}
}
catch (Exception exception)
{
exception.printStackTrace();
}
}
}
Use the following command to start the client (foobar is both the name of the truststore file and its password):
Disclaimer/Note
These are just the sample of the answers/solution to some of the questions given in the assignments. Student should read and refer the official study material provided by
the university.
• Facebook-https://www.facebook.com/dalal.tech
• Telegram - https://t.me/DalalTechnologies
• YouTube-https://www.youtube.com/channel/UCilEr1rW-SIrJlJ5_ioKQfw
• Website-Https://DalalTechnologies.in
Q8. What is Role Based Login? Explain how user’s access can be restricted using Role Based Login.
Ans:-
Role-based access control (RBAC) refers to the idea of assigning permissions to users based on their role within
an organization. It offers a simple, manageable approach to access management that is less prone to error than
assigning permissions to users individually.
When using RBAC, you analyze the needs of your users and group them into roles based on common
responsibilities. You then assign one or more roles to each user and one or more permissions to each role. The
user-role and role-permissions relationships make it simple to perform user assignments since users no longer
need to be managed individually, but instead have privileges that conform to the permissions assigned to their
role(s).
Role-based access control (RBAC), also known as role-based security, is a mechanism that restricts system access.
It involves setting permissions and privileges to enable access to authorized users. Most large organizations use
role-based access control to provide their employees with varying levels of access based on their roles and
responsibilities. This protects sensitive data and ensures employees can only access information and perform
actions they need to do their jobs.An organization assigns a role-based access control role to every employee; the
role determines which permissions the system grants to the user.
For example, you can designate whether a user is an administrator, a specialist, or an end-user, and limit access to
specific resources or tasks. An organization may let some individuals create or modify files while providing others
with viewing permission only.
One role-based access control example is a set of permissions that allow users to read, edit, or delete articles in a
writing application. There are two roles, a Writer and a Reader, and their respective permission levels are
presented in this truth table. Using this table, you can assign permissions to each user.
Edit Yes No
Delete Yes No
Access control measures regulate who can view or use resources in a computing system, often relying on
authentication or authorization based on log-in credentials. They are essential to minimizing business risks.
Access control systems can be physical, limiting access to buildings, rooms, or servers, or they can be logical,
controlling digital access to data, files, or networks.
Disclaimer/Note
These are just the sample of the answers/solution to some of the questions given in the assignments. Student should read and refer the official study material provided by
the university.
• Facebook-https://www.facebook.com/dalal.tech
• Telegram - https://t.me/DalalTechnologies
• YouTube-https://www.youtube.com/channel/UCilEr1rW-SIrJlJ5_ioKQfw
• Website-Https://DalalTechnologies.in
Role-based access control can be complemented by other access control techniques. Examples of such types of
access control include:
The owner of a protected system or resource sets policies defining who can access it. DAC can involve physical or
digital measures, and is less restrictive than other access control systems, as it offers individuals complete control
over the resources they own. However, it is also less secure, because associated programs inherit security settings
and allow malware to exploit them without the knowledge of the end-user. You can use RBAC to implement DAC.
A central authority regulates access rights based on multiple levels of security. MAC involves assigning
classifications to system resources and the security kernel or operating system. Only users or devices with the
required information security clearance can access protected resources. Organizations with varying levels of data
classification, like government and military institutions, typically use MAC to classify all end users. You can use
role-based access control to implement MAC.
Other access control mechanisms could serve as alternatives to role-based access control.
Disclaimer/Note
These are just the sample of the answers/solution to some of the questions given in the assignments. Student should read and refer the official study material provided by
the university.
• Facebook-https://www.facebook.com/dalal.tech
• Telegram - https://t.me/DalalTechnologies
• YouTube-https://www.youtube.com/channel/UCilEr1rW-SIrJlJ5_ioKQfw
• Website-Https://DalalTechnologies.in
An access control list (ACL) is a table listing the permissions attached to computing resources. It tells the operating
system which users can access an object, and which actions they can carry out. There is an entry for each user,
which is linked to the security attributes of each object. ACL is commonly used for traditional DAC systems.
RBAC vs ACL
For most business applications, RBAC is superior to ACL in terms of security and administrative overhead. ACL is
better suited for implementing security at the individual user level and for low-level data, while RBAC better
serves a company-wide security system with an overseeing administrator. An ACL can, for example, grant write
access to a specific file, but it cannot determine how a user might change the file.
ABAC evaluates a set of rules and policies to manage access rights according to specific attributes, such as
environmental, system, object, or user information. It applies boolean logic to grant or deny access to users based
on a complex evaluation of atomic or set-valued attributes and the relationship between them.
In practical terms, this allows you to write rules in eXtensible Access Control Markup Language (XACML), using
key-value pairs like Role=Manager and Category=Financial.
RBAC vs ABAC
While RBAC relies on pre-defined roles, ABAC is more dynamic and uses relation-based access control. You can
use RBAC to determine access controls with broad strokes, while ABAC offers more granularity. For example, an
RBAC system grants access to all managers, but an ABAC policy will only grant access to managers that are in the
financial department. ABAC executes a more complex search, which requires more processing power and time, so
you should only resort to ABAC when RBAC is insufficient.
Role-based access control allows organizations to improve their security posture and comply with security
regulations. However, implementing role-based access control across an entire organization can be complex and
may result in pushback from stakeholders. To succeed in your move to RBAC, you should treat the implementation
process as a series of steps:
• Understanding your business needs—before you move to RBAC, you should run a comprehensive needs
analysis to examine job functions, supporting business processes and technologies. You should also consider
any regulatory or audit requirements and assess the current security posture of your organization. You may
also benefit from other types of access control.
• Planning the scope of implementation—identify the scope of your RBAC requirements and plan the
implementation to align with the organization’s needs. Narrow your scope to focus on systems or
applications that store sensitive data. This will also help your organization manage the transition.
• Defining roles—it will be easier to define your roles once you have performed the needs analysis and
understand how individuals perform their tasks. Watch out for common role design pitfalls like excessive or
insufficient granularity, role overlap, and granting too many exceptions for RBAC permissions.
• Implementation—the final phase involves rolling out the RBAC. Do this in stages, to avoid an overwhelming
workload and reduce disruption to the business. First, address a core group of users. Start with coarse-
Disclaimer/Note
These are just the sample of the answers/solution to some of the questions given in the assignments. Student should read and refer the official study material provided by
the university.
• Facebook-https://www.facebook.com/dalal.tech
• Telegram - https://t.me/DalalTechnologies
• YouTube-https://www.youtube.com/channel/UCilEr1rW-SIrJlJ5_ioKQfw
• Website-Https://DalalTechnologies.in
grained access control before increasing granularity. Collect feedback from users and monitor your
environment to plan the next stages of implementation.
Disclaimer/Note
These are just the sample of the answers/solution to some of the questions given in the assignments. Student should read and refer the official study material provided by
the university.