mc0078 set 2 solved winter 2012

21
1.Explain the following in the context of Streams in Java: a.Stream Classes :- The FileInputStream and FileOutputStream Classes These streams are classified as mode streams as they read and write data from disk files. The classes associated with these streams have constructors that allows you to specify the path of the file to which they are connected. The FileInputStream class allows you to read input from a file in the form of a stream. The FileOutputStream class allows you to write output to a file stream.Example FileInputStream inputfile = new FileInputStream (“Employee.dat”); FileOutputStream outputfile = new FileOutputStream (“binus.dat”); The BufferedInputStream and BufferedOutputStream Classes The BufferedInputStream class creates and maintains a buffer for an input stream. This class is used to increase the efficiency of input operations. This is done by reading data from the stream one byte at a time. The BufferedOutputStream class creates and maintains a buffer for the output stream. Both the classes represents filter streams. The DataInputStream and DataOutputStream Classes The DataInputStream and DataOutputStream classes are filter streams that allow the reading and writing of Java primitive data types. The DataInputStream class provides the capability to read primitive data types from an input stream. It implements the methods presents in the DataInput interface. Methods of the DataInputStream class Method Explanation boolean readBoolean () Reads one byte and returns true if that byte is nonzero, false if it is zero. byte readByte () Reads a byte as an 8-bit signed value. char readChar () Reads a Unicode character.

Upload: pandit-ankit-vashishta

Post on 30-Oct-2014

120 views

Category:

Documents


3 download

DESCRIPTION

MC0078 SET 2 SOLVED WINTER 2012

TRANSCRIPT

Page 1: MC0078 SET 2 SOLVED WINTER 2012

1.Explain the following in the context of Streams in Java:

a.Stream Classes:-

The FileInputStream and FileOutputStream Classes These streams are classified as mode streams as they read and write data from disk files. The classes associated with these streams have constructors that allows you to specify the path of the file to which they are connected. The FileInputStream class allows you to read input from a file in the form of a stream. The FileOutputStream class allows you to write output to a file stream.Example

FileInputStream inputfile = new FileInputStream (“Employee.dat”);

FileOutputStream outputfile = new FileOutputStream (“binus.dat”);

The BufferedInputStream and BufferedOutputStream Classes

The BufferedInputStream class creates and maintains a buffer for an input stream. This class is used to increase the efficiency of input operations. This is done by reading data from the stream one byte at a time. The BufferedOutputStream class creates and maintains a buffer for the output stream. Both the classes represents filter streams.

The DataInputStream and DataOutputStream Classes The DataInputStream and DataOutputStream classes are filter streams that allow the reading and writing of Java primitive data types. The DataInputStream class provides the capability to read primitive data types from an input stream. It implements the methods presents in the DataInput interface.

Methods of the DataInputStream class Method Explanation boolean readBoolean () Reads one byte and returns true if

that byte is nonzero, false if it is zero.

byte readByte () Reads a byte as an 8-bit signed value.

char readChar () Reads a Unicode character. int readInt () Reads an integer value.

Methods of the DataOutputStream Class Method Explanation void writeChar (int v ) Writes a character to the output

stream. void writeLong (long v) Writes a long integer to the

output stream. void writeInt (int v ) Writes an integer to the output

stream. The ByteArrayInputStream and ByteArrayOutputStream Classes These classes allow you to read and write to an array of bytes. Method Explanation ByteArrayInputStream (byte [] b) Creates an input stream of the array of

Page 2: MC0078 SET 2 SOLVED WINTER 2012

byes int size () Returns the total number of bytes

written to the stream.

b. Random Access Files:- The term random access means that data can be read from or written to random locations within a file. In all the above mentioned streams, data is read and written as a continuous stream of information. Java provides the RandomAccessFile class to perform I/O operations a t specified locations within a file. The RandomAccessFile class implements the DataInput and DataOutput interfaces for performing I/O using the primitive data types. The RandomAccessFile class also supports permissions like read and write, and allows files to be accessed in read-only and read-write modes.

Creating a Random Access File There are two ways to create a random access file- using the pathname as a string or using an object of the File class. RandomAccessFile (String pathname, String mode); RandomAccessFile (File name, String mode); Example randomFile = new RandomAccessFile (“iotets.txt”,”rw”); or File file1 = new File (“iotest.txt”); RandomAccessFile randomFile = new RandomAccessFile (file1, “rw”);

The second argument is the mode argument that determines whether you have read-only or read/write (rw) access to the file. The RandomAccessFile class has several methods that allow random access to the content within the file. Method Explanation void seek (long pos ) Sets the file pointer to a particular

location inside the file. long getFilePointer () Return the current location of the file

pointer. long length () Returns the length of the file, in bytes.

2.Explain the following with respect to Servlets in Java:

a. Web Architecture:-

2-tier Architecture Typical client/server systems are all 2-tiered in nature where the application resides entirely on the client PC and database resides on a remote server. But 2-tier systems have some disadvantages such as:

The processing load is given to the PC while more powerful server acts as a traffic controller between the application and the database.

Maintenance is the greatest problem. Imagine a situation where there is a small modification to be done in the application program. Then in case of a 2-tier architecture system, it is

Page 3: MC0078 SET 2 SOLVED WINTER 2012

necessary to go to each client machine and make the necessary modifications to the programs loaded on them.

That is the reason why the modern web applications are all developed based on 3-tier architecture.

N-tier Architecture Although the title of this section is given as N-Tier architecture, here the concentration is on the 3-tier architecture. Basic reason for this is that any web application developed based on N-tier architecture functions just similar to typical 3-tier architecture.

First-Tier:

Basically the presentation Layer.

Represented by the GUI kind of thing.

Middle-Tier :

Application Logic

Third-Tier :

Data that is needed for the application.

The basic idea behind 3-tier architecture is that to separate application logic from the user interface. This gives the flexibility to the design of the application as well as ease of maintenance. If you compare this with 2-tier architecture, it is very clear that in 3-tier architecture the application logic can be modified without affecting the user interface and the database.

Typical Web Application

A typical web application consists of following steps to complete a request and response.

Web application will collect data from the user. (First tier)

Send a request to the web server.

Run the requested server program. (Second and third tier)

Package up the data to be presented in the web browser.

Send it back to the browser for display. (First tier)

b. Servlet Life cycle:- Now that you have seen the basic structure of a servlet, let’s review the process by which a server invokes a servlet. This process can be broken down into the nine steps as follows:

Page 4: MC0078 SET 2 SOLVED WINTER 2012

1. The server loads the servlet when it is first requested by the client or if configured to do so, at server start-up. The servlet may be loaded from either a local or a remote location using the standard Java class loading facility.

This step is equivalent to the following code: Class c=Class.forName(“com.sourcestream.MyServlet”); It should be noted that when referring to servlets, the term load often refers to the process of both loading and instantiating the servlet.

2. The server creates one or more instances of the servlet class. Depending on implementation. The server may create a single instance that services all requests through multiple threads or create a pool of instances from which one chosen to service each new request. This step is equivalent to the following Java code:

Servlet s=(Servlet) c.newInstance (); where ‘c’ is the same Class object created in previous step.

3. The server constructs a ServerConfig object that provides initialization information to the servlet.

4. The server calls the servlet’s init () method, passing the object constructed in step 3 as a parameter. The init () method is guaranteed to finish execution prior to the servlet processing the first request. If the server has created multiple servlet instances (step 2), the init () method is called one time for each instance.

5. The server constructs a ServletRequest or HttpServletRequest object from the data included in the client’s request. It also constructs a ServletResponse or HttpServletResponse object that provides methods for customizing the server’s response. The type of object passed in these two parameters depends on whether the servlet extends the GenericServlet class or the HttpServlet class, respectively.

6. The server calls the servlet’s service() method passing the objects constructed in step 5 as parameters. When concurrent requests arrive, multiple service() methods can run in separate threads.

7. The service () method processes the client request by evaluating the ServletRequest or HttpServletRequest object and responds using ServletResponse or HttpServletResponse object.

8. If the server receives another request for this servlet, the process begins again at step 5.

9. When instructed to unload the servlet, perhaps by the server administrator or programmatically by the servlet itself, the server calls the servlet’s destroy() method. The servlet is then eligible for garbage collection.

The above mentioned nine steps illustrate the entire lifecycle of a servlet.

3.Describe the following with respect to Beans in Java:

a. Bound Properties:- Bound properties support the PropertyChangeListener (in the API reference documentation) class.

Page 5: MC0078 SET 2 SOLVED WINTER 2012

Sometimes when a Bean property changes, another object might need to be notified of the change, and react to the change. Whenever a bound property changes, notification of the change is sent to interested listeners. The accessor methods for a bound property are defined in the same way as those for simple properties. However, you also need to provide the event listener registration methods forPropertyChangeListener classes and fire a PropertyChangeEvent (in the API reference documentation) event to the PropertyChangeListener objects by calling their propertyChange methods The convenience PropertyChangeSupport (in the API reference documentation) class enables your bean to implement these methods. Your bean can inherit changes from the PropertyChangeSupportclass, or use it as an inner class. In order to listen for property changes, an object must be able to add and remove itself from the listener list on the bean containing the bound property. It must also be able to respond to the event notification method that signals a property change. The PropertyChangeEvent class encapsulates property change information, and is sent from the property change event source to each object in the property change listener list with the propertyChange method.

Implementing Bound Property Support Within a Bean To implement a bound property in your application, follow these steps:

1. Import the java.beans package. This gives you access to the PropertyChangeSupport class.

2. Instantiate a PropertyChangeSupport object. This object maintains the property change listener list and fires property change events. You can also make your class a PropertyChangeSupport subclass.

3. Implement methods to maintain the property change listener list. Since a PropertyChangeSupport subclass implements these methods, you merely wrap calls to the property-change support object's methods.

4. Modify a property's set method to fire a property change event when the property is changed.

Creating a Bound Property To create the title property as a bound property for the MyBean component in the NetBeans GUI Builder, perform the following sequence of operations:

1. Right-click the Bean Patterns node in the MyBean class hierarchy.

2. Select Add|Property from the pop-up menu.

3. Fill the New Property Pattern form as shown on the following figure and click OK.

Page 6: MC0078 SET 2 SOLVED WINTER 2012

the title property and the multicast event source pattern PropertyChangeListener were added to the Bean Patterns structure. You can also modify existing code generated in the previous lesson to convert the title and lines properties to the bound type as follows (where newly added code is shown in bold): import java.awt.Graphics; import java.beans.PropertyChangeListener; import java.beans.PropertyChangeSupport; import java.io.Serializable; import javax.swing.JComponent; /** * Bean with bound properties.

*/

public class MyBean

extends JComponent implements Serializable { private String title; private String[] lines = new String[10]; private final PropertyChangeSupport pcs = new PropertyChangeSupport( this ); public String getTitle() { return this.title; } public void setTitle( String title ) { String old = this.title;

Page 7: MC0078 SET 2 SOLVED WINTER 2012

this.title = title; this.pcs.firePropertyChange( "title", old, title ); } public String[] getLines() { return this.lines.clone(); } public String getLines( int index ) { return this.lines[index]; } public void setLines( String[] lines )

{ String[] old = this.lines; this.lines = lines; this.pcs.firePropertyChange( "lines", old, lines ); } public void setLines( int index, String line ) { String old = this.lines[index]; this.lines[index] = line; this.pcs.fireIndexedPropertyChange( "lines", index, old, lines ); } public void addPropertyChangeListener( PropertyChangeListener listener ) { this.pcs.addPropertyChangeListener( listener ); } public void removePropertyChangeListener( PropertyChangeListener listener ) { this.pcs.removePropertyChangeListener( listener ); } protected void paintComponent( Graphics g ) { g.setColor( getForeground() ); int height = g.getFontMetrics().getHeight(); paintString( g, this.title, height ); if ( this.lines != null )

{

int step = height; for ( String line : this.lines ) paintString( g, line, height += step ); } } private void paintString( Graphics g, String str, int height ) { if ( str != null ) g.drawString( str, 0, height ); }

}

Page 8: MC0078 SET 2 SOLVED WINTER 2012

b. Constrained Properties:- A bean property is constrained if the bean supports the Vetoable ChangeListener(in the API reference documentation) and Property ChangeEvent(in the API reference documentation) classes, and if the set method for this property throws a PropertyVetoException(in the API reference documentation). Constrained properties are more complicated than bound properties because they also support property change listeners which happen to be vetoers. The following operations in the setXXX method for the constrained property must be implemented in this order:

1. Save the old value in case the change is vetoed.

2. Notify listeners of the new proposed value, allowing them to veto the change.

3. If no listener vetoes the change (no exception is thrown), set the property to the new value. The accessor methods for a constrained property are defined in the same way as those for simple properties, with the addition that the setXXX method throws a PropertyVetoException exception. The syntax is as follows: public void setPropertyName(PropertyType pt) throws PropertyVetoException {code}

Handling Vetoes If a registered listener vetoes a proposed property change by throwing a PropertyVetoException exception, the source bean with the constrained property is responsible for the following actions:

Catching exceptions.

Reverting to the old value for the property.

Issuing a new VetoableChangeListener.vetoableChange call to all listeners to report the reversion.

The VetoableChangeListener class throws a PropertyVetoException and handles the PropertyChangeEvent event fired by the bean with the constrained property.

The VetoableChangeSupport provides the following operations:

Keeping track of VetoableChangeListener objects.

Issuing the vetoableChange method on all registered listeners.

Catching any vetoes (exceptions) thrown by listeners.

Informing all listeners of a veto by calling vetoableChange again, but with the old property value as the proposed "new" value.

Creating a Constrained Property To create a constrained property, set the appropriate option in the New Property Pattern form as shown on the following figure.

Page 9: MC0078 SET 2 SOLVED WINTER 2012

that the Multicast Source Event Pattern - vetoableChangeListener was added to the Bean Patterns hierarchy. You can also modify the existing code generated in the previous lesson to make the title and lines properties constrained as follows (where newly added code is shown in bold): import java.io.Serializable; import java.beans.PropertyChangeListener; import java.beans.PropertyChangeSupport; import java.beans.PropertyVetoException; import java.beans.VetoableChangeListener;

import java.beans.VetoableChangeSupport;

import java.awt.Graphics; import javax.swing.JComponent; /** * Bean with constrained properties. */ public class MyBean extends JComponent implements Serializable { private String title; private String[] lines = new String[10]; private final PropertyChangeSupport pcs = new PropertyChangeSupport( this ); private final VetoableChangeSupport vcs = new VetoableChangeSupport( this ); public String getTitle() { return this.title; }

Page 10: MC0078 SET 2 SOLVED WINTER 2012

/** * This method was modified to throw the PropertyVetoException * if some vetoable listeners reject the new title value */ public void setTitle( String title ) throws PropertyVetoException { String old = this.title;

this.vcs.fireVetoableChange( "title", old, title );

this.title = title; this.pcs.firePropertyChange( "title", old, title ); } public String[] getLines() { return this.lines.clone(); } public String getLines( int index ) { return this.lines[index]; } /** * This method throws the PropertyVetoException * if some vetoable listeners reject the new lines value */ public void setLines( String[] lines ) throws PropertyVetoException { String[] old = this.lines; this.vcs.fireVetoableChange( "lines", old, lines ); this.lines = lines; this.pcs.firePropertyChange( "lines", old, lines ); } public void setLines( int index, String line ) throws PropertyVetoException { String old = this.lines[index]; this.vcs.fireVetoableChange( "lines", old, line );

this.lines[index] = line;

this.pcs.fireIndexedPropertyChange( "lines", index, old, line ); } public void addPropertyChangeListener( PropertyChangeListener listener ) { this.pcs.addPropertyChangeListener( listener ); } public void removePropertyChangeListener( PropertyChangeListener listener ) { this.pcs.removePropertyChangeListener( listener ); } /**

Page 11: MC0078 SET 2 SOLVED WINTER 2012

* Registration of the VetoableChangeListener */ public void addVetoableChangeListener( VetoableChangeListener listener ) { this.vcs.addVetoableChangeListener( listener ); } public void removeVetoableChangeListener( VetoableChangeListener listener ) { this.vcs.removeVetoableChangeListener( listener ); } protected void paintComponent( Graphics g ) { g.setColor( getForeground() );

int height = g.getFontMetrics().getHeight();

paintString( g, this.title, height ); if ( this.lines != null ) { int step = height; for ( String line : this.lines ) paintString( g, line, height += step ); } } private void paintString( Graphics g, String str, int height ) { if ( str != null ) g.drawString( str, 0, height );

}

c. Indexed Properties:-

An indexed property is an array of properties or objects that supports a range of values and enables the accessor to specify an element of a property to read or write. Indexed properties are specified by the following methods: //Methods to access individual values public PropertyElement getPropertyName(int index) public void setPropertyName(int index, PropertyElement element) and //Methods to access the entire indexed property array public PropertyElement[] getPropertyName()

public void setPropertyName(PropertyElement element[])

that the distinction between the get and set methods for indexed properties is subtle. The get method either has an argument that is the array index of the property, or returns an array. The set method either has two arguments, namely an integer array index and the property element object that is being set, or has the entire array as an argument. Creating an Indexed Property

To create an indexed property for your MyBean component, right-click the Bean Patterns node and select Add|Indexed Property from the pop-up menu. Set up Non-Index Options as shown in the following figure.

Page 12: MC0078 SET 2 SOLVED WINTER 2012

The code in the Source window will be changed automatically as follows: import java.awt.Graphics;

import java.io.Serializable;

import javax.swing.JComponent; /** * Bean with simple property 'title'. */ public class MyBean extends JComponent implements Serializable { private String title; public String getTitle() { return this.title; } public void setTitle( String title ) { this.title = title; } protected void paintComponent( Graphics g ) {

Page 13: MC0078 SET 2 SOLVED WINTER 2012

g.setColor( getForeground() ); int height = g.getFontMetrics().getHeight(); if ( this.title != null ) g.drawString(this.title, 0, height ); } /** * Holds value of property lines. */ private String[] lines;

/**

* Indexed getter for property lines. * @param index Index of the property. * @return Value of the property at index. */ public String getLines(int index) { return this.lines[index]; } /** * Getter for property lines. * @return Value of property lines. */ public String[] getLines() { return this.lines; } /** * Indexed setter for property lines. * @param index Index of the property. * @param lines New value of the property at index. */ public void setLines(int index, String lines) { this.lines[index] = lines; } /** * Setter for property lines. * @param lines New value of property lines. */ public void setLines(String[] lines) { this.lines = lines;

}

} Add the following code to the MyBean.java component to present the user with a list of choices. You can provide and change these choices at design time. (Newly added code is shown in bold.) import java.awt.Graphics; import java.io.Serializable; import javax.swing.JComponent; /** * Bean with a simple property "title" * and an indexed property "lines".

Page 14: MC0078 SET 2 SOLVED WINTER 2012

*/ public class MyBean extends JComponent implements Serializable { private String title; private String[] lines = new String[10]; public String getTitle() { return this.title; } public void setTitle( String title ) { this.title = title; } public String[] getLines() { return this.lines.clone();

}

public String getLines( int index ) { return this.lines[index]; } public void setLines( String[] lines ) { this.lines = lines; } public void setLines( int index, String line ) { this.lines[index] = line; } protected void paintComponent( Graphics g ) { g.setColor( getForeground() ); int height = g.getFontMetrics().getHeight(); paintString( g, this.title, height ); if ( this.lines != null ) { int step = height; for ( String line : this.lines ) paintString( g, line, height += step ); } } private void paintString( Graphics g, String str, int height ) { if ( str != null ) g.drawString( str, 0, height ); }

}

Page 15: MC0078 SET 2 SOLVED WINTER 2012

4.Describe the following with respect to CORBA:

a. Implementing a CORBA Client:- This section covers what you need to know to use CORBA objects from the Java programming language. It examines OMG IDL interfaces, the Java programming language binding for IDL interfaces, object references, and requests, how to obtain object references, and how, as a client, to create distributed objects. After reading this section and completing the exercises, you should be able to write a client using the Java programming language. Again, the stock example is used to illustrate the client's model of CORBA.

CORBA Objects are Described by IDL Interfaces The OMG Interface Definition Language IDL supports the specification of object interfaces. An object interface indicates the operations the object supports, but not how they are implemented. That is, in IDL there is no way to declare object state and algorithms. The implementation of a CORBA object is provided in a standard programming language, such as the Java programming language or C++. An interface specifies the contract between code using the object and the code implementing the object. Clients only depend on the interface. IDL interfaces are programming language neutral. IDL defines language bindings for many different programming languages. This allows an object implementor to choose the appropriate programming language for the object. Similarly, it allows the developer of the client to choose the appropriate and possibly different programming language for the client. Currently, the OMG has standardized on language bindings for the C, C++, Java, Ada, COBOL, Smalltalk, Objective C, and Lisp programming languages. So by using OMG IDL, the following can be described without regards to any particular programming language: Modularized object interfaces Operations and attributes that an object supports Exceptions raised by an operation Data types of an operation return value, its parameters, and an object's attributesThe IDL data types are: Basic data types (long, short, string, float...) Constructed data types (struct, union, enum, sequence) Typed object references The any type, a dynamically typed value Again, IDL says nothing about object implementations. Here's the IDL interface for the example stock objects:

Page 16: MC0078 SET 2 SOLVED WINTER 2012

Module StockObjects { Struct Quote { String symbol; Long at_time; double price; long volume; }; exception Unknown{}; interface Stock { // Returns the current stock quote. Quote get_quote() raises(Unknown); // Sets the current stock quote. void set_quote(in Quote stock_quote); // Provides the stock description, // e.g. company name. readonly attribute string description; }; interface StockFactory { Stock create_stock( in string symbol, in string description ); }; };

Object References and Requests Clients issue a request on a CORBA object using an object reference. An object reference identifies the distributed object that will receive the request. Here's a Java programming language code fragment that obtains a Stock object reference and then it uses it to obtain the current price of the stock. Note that the code fragment does not directly use CORBA types; instead it uses the Java types that have been produced by the IDL to Java compiler

Stock theStock = ... try { Quote current_quote = TheStock.get_quote(); } catch (Throwable e) { }

b.Object Implementations:- This section describes what you need to know to implement a simple CORBA object in the Java programming language. It examines the Java server-side language binding for IDL, implementing objects and servers, implementation packaging issues, and CORBA object adaptors. After completing this section, you should be able to write a simple CORBA object and server in the Java programming language. Again, the stock example is used to illustrate the implementation model of CORBA.CORBA object implementations are completely invisible to their clients. A client can only depend on the IDL interface. In the Java programming language, or C++, this is not the case. The user of an object declares variables by a class name; doing so makes the code depend on much more than just the interface. The client depends on the object implementation programming language, the name of the class, the implementation class hierarchy, and, in C++, even the object layout. The complete encapsulation for CORBA objects means the object implementor has much more freedom. Object implementations can be provided in a number of supported programming languages. This is not necessarily the same one the clients are written in. (Of course, here everything is in the Java programming language, but CORBA does notrequire this.) The same interface can be implemented in multiple ways. There is no limit. In the stock example, the following are possible implementations of the Stock interface: A stock implementation class written in the Java programming language that obtains values from a commercial feed A stock implementation class written in C++ that accesses a database on the Internet A stock implementation written in Smalltalk that guesses stock prices

Page 17: MC0078 SET 2 SOLVED WINTER 2012