Uploaded by dedike2776

Java Solution set 5- Google Docs

advertisement
Advance Java Paper Set - 5
Q1. Answer any two question (2 marks):
1.
Define Socket
Ans: Socket is a buffer and a termination of the network.
4 Marks
It is an combination of Port, Protocol & IP Address which is used to make a
communication between same application install on the different computer
of the network.
2.
What is HttpURLConnection? List any three methods of HttpURLConnection.
Ans: The Java HttpURLConnection class is http specific URLConnection. It works for
HTTP protocol only. It also describes attributes of Website. It uses the
openConnection() method to make an object of it.
By the help of HttpURLConnection class, you can retrieve information of any HTTP
URL such as header information, status code, response code etc.The
java.net.HttpURLConnection is a subclass of URLConnection class.
The Three methods of HttpURLConnection are :
1) String getResponseCode()
2) int getRequestMethod()
3) String getResponseMessage()
3.
a.
Define the following:
Datagram : Datagrams are collection of information sent from one device to another
device via the established network. When the datagram is sent to the
targeted device, there is no assurance that it will reach to the target device
safely and completely. It may get damaged or lost in between.
b.
JDBC : JDBC stands for Java Database Connectivity. JDBC is a Java API to connect
and execute the query with the database. It is a part of JavaSE (Java Standard
Edition). JDBC API uses JDBC drivers to connect with the database.
4.
What are the advantages and disadvantages of Network Protocol Driver.
Ans: Advantage:
○ No client side library is required because of the application server
that can perform many tasks like auditing, load balancing, logging
etc.
Disadvantages:
○ Network support is required on client machine.
○ Requires database-specific coding to be done in the middle tier.
○ Maintenance of Network Protocol driver becomes costly because it
requires database-specific coding to be done in the middle tier.
Q2. Answer the following questions:
1.
Explain the Resultset Object.
3 Marks
Ans: The ResultSet Object is actually a tabular data set
It Consists of rows of data organised in uniform columns.
In JDBC, the Java program can see only one row of data at one time.
The program uses the next( ) method to go to the next row.
Once the program has a row, it can use the positional index(1 for the first column, 2
for the second column, and so on ) or the column name to get the field value by
using the getXXXX( ) methods.
next( )
getInt( )
getString( )
2.
Explain the JDBC Architecture with suitable diagrams.
Ans: JDBC Architecture consists of two layers :
4 Marks
JDBC API : This provides the application to JDBC Manager Connection.
JDBC Driver API : This supports the JDBC Manager to Driver Connection.
The JDBC API uses a driver manager and database specific driver to provide
transparent connectivity to heterogeneous databases.
The JDBC driver manager ensures that the correct driver is used to access each data
source. The driver manager is capable of supporting multiple concurrent drivers
connected to multiple heterogeneous databases.
JDBC enables you to construct SQL statements and embed them inside API calls.
You are essentially using JDBC to make a smooth transition between the SQL and
Java.
Your application sends a query to the database as SQL and gets the results back
through a Java object.
Consequently, every Java VM has the ability to talk to any ODBC-supported database
using this bridge.
Following is the architectural diagram:
3.
Explain the Statement Object with an example.
7 Marks
Ans: Statement Object :
Creating and Using Direct SQL Statements:
● A Statement object is created using the createStatement() method in the
Connection Object.
The most important methods are execute Query( ), executeUpdate( ), and execute( ).
The executeQuery ( ) method :
● As you create a Statement object with a SQL statement, the executeQuery()
method takes a SQL string. It passes the SQL string to the underlying data
source through the driver manager and gets the ResultSet back to the application
program. The executeQuery( ) method returns only one ResultSet.
● For those cases that return more than one ResultSet, theexecute( ) method should
be used.
Note:
● Only one ResultSet can be opened per Statement object at one time.
The executeUpdate ( ) method :
● For SQL statements that do not return a ResultSet such as the UPDATE,
DELETE, and DDL statements, the Statement object has the executeUpdate()
method that takes a SQL string and returns an integer. This integer indicates the
number of rows that are affected by the SQL statement.
● The following example program shows how to use the Statement class to access
a database
● In this example you will list all of the subjects (classes) available in our
enrollment, database and their location and day and times.
● The SOL statement for his is *SELECT Class ame, Localion. DaysAndTimes
FROM Classes"
● You will create a Statement Object and pass the SQL sting during the execute
Query() method call to get this data.
//Declare a method and some variables.
public void Listclasses( ) throws SQLException
{
int i, NoOfColumns;
String Classname, ClassLocation, ClassSchedule;
//Initialize and load the JDBC-ODBC driver.
Class. forName ("jdbc.o&bc .JabcOdbcDriver*);
//Make the connection object.
Connection ExICon = DriverManager. getConnection
"jdbc:odbc: StudentDB;uid='admin" ;pw='sa');
//Create a simple Statement object.
Statement Ex1Stmt = ExiCon. createStatement);
//Make a SQL string, pass it to the DEMS, and execute the Set staterent.
ResultSet Exlrs = ExiStmt. executeQuery( )
*SELECT Classlame, Location, DaysAndfimes FROM Classes*);
//Process each row until there are no more rows.
// And display the results on the console.
System.out.println(*ClassName, Location, Schedule*);
while (Exirs.next ( ) ) {
// Get the column values into Java variables
ClassName = Exirs.getString(1);
ClassLocation = Exirs.getString(2);
ClassSchedule = Exirs. getString (3);
System.out .printIn(Classlame, ClassLocation, ClassSchedule);
}
}
● As you can see, the program is very straightforward. You do the initial
connection and so on, and create a Statement object. Pass the SQL along with
the method executeQuery() call. The driver will pass the SQL string to the
DBMS, which will perform the query and return the results. After the statement
is done, the optimised execution plan is lost.
OR
1.
Explain Type 4 Driver with advantages and disadvantages.
Ans: Type 4 Driver : Thin Driver
3 Marks
The thin driver converts JDBC calls directly into the
vendor-specific database protocol. That is why it is known as thin
driver. It is fully written in Java language.
Advantage:
○ Better performance than all other drivers.
○ No software is required at client side or server side.
Disadvantage:
Drivers depend on the Database.
2.
Explain TCP/IP Server Socket.
Ans: TCP/IP Server Socket:
4 Marks
● The ServerSocket class is used to create servers that listen for
either local or remote client programs to connect to them on published ports.
● ServerSockets are quite different from normal Sockets.
● When you create a ServerSocket, it will register itself with the
system as having an interest in client connections.
● The constructors for ServerSocket reflect the port number that
you want to accept connections on and,
● optionally, how long you want the queue for said port to be.
● The queue length tells the system how many client
connections it can leave pending before it should simply refuse
connections.
● The default is 50.
● The constructors might throw an IOException under adverse
conditions.
ServerSocket(int port) throws
IOException
Creates server socket on the specified port
with a queue length of 50.
ServerSocket(int port, int maxQueue)
throws IOException
Creates a server socket on the specified port
with a maximum queue length of maxQueue
ServerSocket(int port. int maxQueue,
InetAddress localAddress)
throws lOException
Creates a server socket on the specified port
with a maximum queue length of
maxQueue.
On a multihomed host, localAddress
specifies the IP address to which this socket
binds.
3.
Write a Java Program for Client Datagram and Server Datagram.
Ans: Client Datagram:
7 Marks
import java.net.*;
public class Client
{
public static void main(String[] args) throws Exception
{
DatagramSocket clientSocket = new DatagramSocket(123);
String s = "Hello, server! How Are You";
byte[ ] b = s.getBytes();
InetAddress IA = InetAddress.getByName("Localhost");
DatagramPacket packet = new DatagramPacket(b, b.length, IA, 123);
clientSocket.send(packet);
clientSocket.close();
}
}
Server Datagram:
import java.net.*;
public class Client
{
public static void main(String[] args) throws Exception
{
DatagramSocket clientSocket = new DatagramSocket(123);
String s = "Hello, server! How Are You";
byte[ ] b = s.getBytes();
InetAddress IA = InetAddress.getByName("Localhost");
DatagramPacket packet = new DatagramPacket(b, b.length, IA, 123);
clientSocket.send(packet);
clientSocket.close();
}
}
Q3. Answer the following question:
1.
Explain the Callable Statement.
3 Marks
Ans:CallableStatement Object :
● Calling Stored Procedures (CallableStatement)
● For a secure, consistent, and manageable multi-tier client/server system, the
data access should allow the use of stored procedures.
● Stored procedures centralize the business logic in terms of manageability and
also in terms of running the query.
● Java applets running on clients with limited resources cannot be expected to run
huge queries.
● But the results are important to those clients. JDBC allows the use of stored
procedures by the CallableStatement class and with the escape clause string.
● §A CallableStatement object is created by the prepareCall() method in the
Connection object.
● The prepareCall() method takes a string as the parameter. This string, called an
escape clause, is of the form
{[ ? =] call <stored procedure name> {<parameter>, <parameter> …})
● The CallableStatement class supports parameters.
● These parameters are of the OUT kind from a stored procedure or the IN kind to
pass values into a stored procedure.
● The parameter marker (question mark) must be used for the return value (if any)
and any output arguments, because the parameter marker is bound to a program
variable in the stored procedure.
● Input arguments can be either literals or parameters.
● For a dynamic parameterized statement, the escape clause string takes the form:
{[? =] call <stored procedure name> [< ?>, < ?> ...]}
● The OUT parameters should be registered using the registerOutparameter()
method-as shown in following table before the call to the execute Query(),
execute Update(), or execute( ) methods.
2.
Explain URLConnection with its method.
3 Marks
Ans: URLConnection is a general-purpose class for accessing the attributes of a remote resource.
Once you make a connection to a remote server, you can use
URLConnection to inspect the properties of the remote object
before actually transporting it locally.
URLConnection defines several methods. Here is a sampling:
int getContentLength()
Returns the size in bytes of the content
associated with the resource. If the length is
unavailable, -1 is returned.
String getContentType()
Returns the type of content found in the
resource.
This is the value of the content-type header
field.
Returns null if the content type is not
available.
long getDate()
Returns the time and date of the response
represented in terms of milliseconds since
January 1, 1970 GMT.
long getexpiration()
Returns the expiration time and date of the
resource represented in terms of milliseconds
since January 1, 1970 GMT. Zero is returned
if the expiration date is unavailable.
● By using getHeaderField(),
○ you can obtain the value associated with a header key.
● By calling getHeaderFields(),
○ you can obtain a map that contains all of the headers.
3.
Write a Java Program to execute a query using Prepared Statement. 6 Marks
Ans: The simple Statement example can be improved in a couple of major ways.
//Declare class variables
Connection Con;
PreparedStatement PrepStnt;
boolean Initialized = false;
private void InitConnection( ) throws SQLException
{
//Initialize and load the JDBC-ODBC driver.
Class.forName ("jdbc.odoc.JdbcOdocDriver");
//Make the connection object,
Con = DriverManager.getConnection|
"jdbc:odbc:StudentDB;uid"admin*;pw=”sa”);
//Create a prepared Statement object.
PrepStmt = EXICon. prepareStatement |
"SELECT ClassName, Location, DaysAndtimes FROM Classes WHERE
ClassName = ?");
Initialized = True;
}
public void ListOneClass (String ListClassName) throws
SQLException {
int i, NoOfColumns;
String ClassName, ClassLocation, ClassSchedule;
if (! Initialized) {
InitConnection( )
}
/ /Set the SQL parameter to the one passed into this method
PrepStmt. setstring (l, LastClassName);
ResultSet Exirs = PrepStmt. executeQuery( )
//Process each row until there are no more rows and
//display the results on the console.
System. out.printIn ("Class Location Schedule");
while (EXirs.next( )) {
// Get the column values into Java variables
ClassName = ExIrs.getString(1);
ClassLocation = Exlrs.getString (2) ;
ClassSchedule = Exlrs.getString (3) ;
System.out .println (ClassName, ClassLocation, ClassSchedule) ;
}
}
OR
3.
Define InetAddress. Explain Factory method and Instance Method of 6 Marks
InetAddress.
Ans: The InetAddress class is used to encapsulate both the numerical IP address and the domain
name for that address.
● You interact with this class by using the name of an IP host,
which is more convenient and understandable than its IP
address.
● The InetAddress class hides the number inside.
● InetAddress can handle both IPv4 and IPv6 addresses.
Factory Methods:
● The InetAddress class has no visible constructors.
● To create an InetAddress object, you have to use one of the
available factory methods.
● Factory methods are merely a convention whereby static
methods in a class return an instance of that class
● Three commonly used InetAddress factory methods are shown
here:
● static InetAddress getLocalHost()
throws UnknownFostException
● static InetAddress getByName(String hostName)
throws UnknownHostException
● static InetAddress[ ] getAllByName(String hostName)
throws UnknownHostException
● The getLocalHost() method simply returns the InetAddress
object that represents the local host.
● The getByName() method returns an InetAddress for a host
name passed to it.
● If these methods are unable to resolve the host name, they
throw an UnknownHostException.
● The getAllByNamel( ) factory method returns an array of
InetAddresses that represent all of the addresses that a
particular name resolves to.
● It will also throw an UnknownHostException it can't resolve
the name to at least one address.
Instance Method :
● The InetAddress class has several other methods, which can be
used on the objects returned by the methods just discussed.
● Here are some of the more commonly used methods:
boolean equals(Object other) Returns true if this object has the same Internet
address as other.
byte[ ] getAddress( )
Returns a byte array that represents the object's IP
address in network byte order.
String getHostAddress( )
Returns a string that represents the host address
associated with the InetAddress object.
String getHostName( )
Returns a string that represents the host name
associated with the InetAddress object.
boolean isMulticastAddress( Returns true if this address is a multicast address.
)
Otherwise,it returns false.
String toString()
Returns a string that lists the host name and the IP
address for convenience.
Download