Analysis and Architecture Process

Embed Size (px)

Citation preview

  • 8/9/2019 Analysis and Architecture Process

    1/50

    Analysis and Architecture Process

    Introduction to the Architect Process using Java technology.Describe the duties performed by a Java Architect.State how Java architecture design fits into the application development lifecycle.State the advantages of a distributed object architecture implementation.

    Explain the Advantages of such a Java Solution compared to alternative solutioncompared to alternative solution technologies such as C++.What Does an Architect Do?System Architecture in PerspectiveWhy Is an Architecture Needed?Architecture NotationBasic Three-Tier ArchitectureTier-to-Tier CommunicationDistributed Object CommunicationAdvantages of Distributed Object ArchitecturesDistributed Object FrameworksObject LanguagesBasic Three-Tier Java Technology Architecture

    Advantages of Three-Tier ArchitecturesComparison of Three-Tier Communication MechanismsOverall Java Technology ArchitectureJava Technology Architecture Issues

    Introduction to the Architect Process using Java technology.

    What is Software Architecture?

    Architeture is an overall structure of a system. Architecture take into consideration the theoverall working of the system. The architecture can consist of sub system which interfacewith other subsystem to provide the system. Architecture take into consideration thescalability, security, portability of the system. Architecture normally do not consider in

    implementation detail. Implementation do follow the architecture.

    Software architecture is the high-level structure of a software system. Importantproperties include:

    It is at a high-enough level of abstraction that the system can be viewed as awhole.

    The structure must support the functionality required of the system. Thus, thedynamic behavior of the system must be taken into account when designing thearchitecture.

    The structure--or architecture--must conform to the system qualities (also knownas non-functional requirements). These likely include performance, security andreliability requirements associated with current functionality, as well as flexibility orextensibility requirements associated with accommodating future functionality at areasonable cost of change.

    http://prasks.webahn.com/architect/ch1.html#Architect%20Processhttp://prasks.webahn.com/architect/ch1.html#Architect%20Processhttp://prasks.webahn.com/architect/ch1.html#ARCH%20FIThttp://prasks.webahn.com/architect/ch1.html#Architect%20Processhttp://prasks.webahn.com/architect/ch1.html#Architect%20Processhttp://prasks.webahn.com/architect/ch1.html#ARCH%20FIT
  • 8/9/2019 Analysis and Architecture Process

    2/50

  • 8/9/2019 Analysis and Architecture Process

    3/50

    Define any bottlenecksHow to work out a practical solution with

    Security Performance Cost

    Reusing existing technology and business logic in the legacy system. Programmers

    Develop package dependency diagrams..How the classes in different package interactDevelop deployment diagramsWhere the software components will reside in deployment.

    Object oriented design

    In this phase the implementation design is done. Client tier whether it is an applet orHTML is decided. All the classes with hierarchy is defined. Design patterns if any are used.

    Object reuse is considered.

    Architectural design ( revisited )

    Any architectural considerations arising due to the detailed implementational design isdiscussed.

    Example:If the client uses HTML then the server side servlet can be communicated via HTTP withoutany modification in the existing systems.If the client uses applet instead of HTML then consider HTTP tunneling on the server side isto be considered.

    Object creation

    The objects and code are implented.

    Architecture Notation

    UML, Unified Modeling Language by OMG , Object Management Group is the ArchitectureNotation.Class diagram

    A rectangle with three divisions for class name, attributes and methods

    Sequence diagram

    Basic Three-Tier Architecture

    Three-Tier Architecture has three layers User Interface layer, business logic layer andthe persistence layer.The three tier software architecture emerged in the 1990s to overcome the limitations of

  • 8/9/2019 Analysis and Architecture Process

    4/50

    the two tier architecture The third tier (middle tier server) is between the user interface(client) and the data management (server) components. This middle tier provides processmanagement where business logic and rules are executed and can accommodate hundredsof users (as compared to only 100 users with the two tier architecture) by providingfunctions such as queuing, application execution, and database staging. The three tierarchitecture is used when an effective distributed client/server design is needed thatprovides (when compared to the two tier) increasedperformance , flexibility,maintainability, reusability, and scalability, while hiding the complexity of distributedprocessing from the user.-Tier ArchitectureThe 3-tier architecture overcomes the weaknesses of the 2-tier and client/serverarchitectures. It contains a client workstation, a component server, and a database server.The user interface is on the client side while business logic and data management are indedicated tiers. Business logic resides on one machine where it can be easilymanaged.Successful implementation of a 3-tier architecture requires considerable appliedexperience.n-Tier ArchitectureThe n-tier architecture is the same as the 3-tier architecture, but it has multiple (n)component and data management servers. It can distribute components across multipleservers and can access data in multiple databases. However, it requires careful planning of

    component interfaces to enable re-use and sharing.

    Tier-to-Tier CommunicationCommunication between the userinterface and business tiers can beachieved by

    HTTP RMI Corba

    Dcom

    Communication between the businessand persistence tier can be achieved by

    Jdbc

    IDL to Com bridge // check

    HTTP

    HTML forms based client interacts with the servlet on the server. Server interacts with thebusiness layer and business layer interacts with the persistence layer.

    RMI

    This is a possible if the objects in the user interface and the business layers are all Javaobjects. The persistence layer is mostly accessed through JDBC. Other relational objectmapping of the data layer is also possible.

    Advantage of RMIObject are passed by value. The server/ client can reconstitute the objects easily.Data type can be any Java objects. Any Java objects can be passed as arguments.

    Arguments has to implement the serializable interface

  • 8/9/2019 Analysis and Architecture Process

    5/50

    Disadvantage of RMIHeterogeneous objects are not supported.

    CorbaIf the objects in the client layer and the business layer are heterogeneous, i.e. the objectsare implemented in C, C++ Java, Smalltalk then Corba is most suitable.

    Advantage of CorbaHeterogeneous objects are supported.

    Disadvantage of CorbaObjects are not passed by value, only the argument data is passed.The server/ client has to reconstitute the objects with the data.Only commonly accepted data types can be passed as arguments.

    DcomThis works best in windows environment.

    Distributed Object Communication

    Advantages Disadvantages

    HTTP Simple,

    Established

    Has to communicate to a Servlet, Java Servpages

    Cannot communicate to a Java class directly

    RMI Object are passed by value.

    The server/ client can reconstitute theobjects easily.

    Object are passed by reference

    Data type can be any Java objects.

    Any Java objects can be passed asarguments.

    Arguments has to implement the

    Serializable interface

    Heterogeneous objects are not supported.

    Corba Heterogeneous objects are supported. Objects are not passed by value, only theargument data is passed.

    The server/ client has to reconstitute the

  • 8/9/2019 Analysis and Architecture Process

    6/50

    objects with the data.

    Only commonly accepted data types can bepassed as arguments

    Dcom If windows is the deployment platformsuits well with the operating system

    This works in windows environment at best

    Distributed Object Frameworks

    Distributed Object Frameworks are RMI, Corba, Dcom, EJB.

    Basic Three-Tier Java Technology Architecture

    The three-Tier Java Technology Architectureis achieved by HTML, Applet, Java Applicationon the client. Servlet, Java Server Pages on the Middle Tier. JDBC communication to thepersistence or Database layer

    RMI

    // Explain later

    Java IDL

    // Explain later

    Client C to Mcomm.

    Middle M to Pcomm.

    Persistence

    HTML

    HTML with applet

    HTTP Servlet

    Java Server Pages

    JDBC RDBMSLegacyFile

    Java Application JRMP RMI Server JDBC RDBMSLegacyFile

    Java Application RMI- II0P EJB JDBC RDBMS

    LegacyFile

    Java Application

    ( Not a Java 3 tier)

    IIOP Corba JDBC RDBMSLegacyFile

  • 8/9/2019 Analysis and Architecture Process

    7/50

    Comparison of Three-Tier Communication MechanismsReview questions

    Where do the architectural design fit into the design phase

    In between the analysis and design phase

    What are the phases in ooad

    Requirement analysis, oo Analysis, Architectural design, oo design,Objectcreation.

    What is the requirement of a Java architect

    To analyze all possible solutions including non java solution

    To satisfy the customerJava Technology Architecture

    Customer ApplicationArchitecture AnalysisAdvantages of Three-Tier Java Technology ArchitecturesApplication Architecture DesignApplications, Servlets and CGI ScriptsTier Two ArchitectureCommunication Protocols in a Three-Tier ArchitectureRemote Method Invocation (RMI)Architecture Overview

    Object Naming and Locating

    Customer ApplicationAs an architect consider the infrastructure and the skills the customer has in place.

    What are the customers long term plans and goals.

    Consider:

    Is the application to be deployed via the Internet / intranet / extranet?

    If so, Java's security features would be a plus for the customer.

    Does it appear that the application may be quite volatile?

    Application maintenance is made more manageable in Java.(see about reduced client administration when using applets)

    http://prasks.webahn.com/architect/ch2.html#Customer%20Applicationhttp://prasks.webahn.com/architect/ch2.html#Architecture%20Analysishttp://prasks.webahn.com/architect/ch2.html#Customer%20Applicationhttp://prasks.webahn.com/architect/ch2.html#Architecture%20Analysis
  • 8/9/2019 Analysis and Architecture Process

    8/50

    Does the customer already have some in-house object oriented development skills?

    If not, obviously need to recommend some training.

    Is platform independence a big issue for the customer?

    If the customer has a large pool of developers skilled in Visual Basic, and theapplication is not going to be Internet / intranet / extranet deployed, then perhapsJava is not what the customer needs. Take another look at what the customer istrying to achieve and whether the customer is really ready for object technology.

    Architecture AnalysisSoftware architecture is the study of large software systems, from the perspective of

    their structure. This is in contrast to traditional computer science approaches to the designand creation of software systems, which emphasize data structures and algorithms overstructure.

    The study of software architecture concerns itself with achieving non-functional qualities(portability, scalability, performance, modifiability, integrability, etc.) in large systems.

    Software architectural analysis, in particular, looks at how to analyze existing systems, ordesigned (but not yet built) systems, with a view to predicting its non-functional qualities.Achieving software quality through architecture level analysis

    Establishing a process for architecture analysis and reviews.

    This includes codifying current best practices in industry.

    Searching for, and empirically validating, the building blocks of design at thearchitectural level, and inking this to the achievement of non-functional qualities.

    Devising a set of primitives with which to describe architectural mechanisms

    (the things that we informally think of as components and connectors).

    Adding tool support for architectural design and analysis.

    Advantages of Three-Tier Java Technology Architectures

    Two tier software architectureTwo tier application has two tier with

    Client tier providing user interface and business logic.Data tier providing the persistence.

    The two tier design allocates the user system interface exclusively to the client. It placesdatabase management on the server and splits the processing management between client

  • 8/9/2019 Analysis and Architecture Process

    9/50

    and server, creating two layers.In general, the user system interface client invokes services from the databasemanagement server. In many two tier designs, most of the application portion ofprocessing is in the client environment. The database management server usually providesthe portion of the processing related to accessing data (often implemented in storeprocedures and triggers). Clients commonly communicate with the server through SQLstatements. It should be noted that connectivity between tiers can be dynamically changeddepending upon the user's request for data and services.

    Advantage of two tier architectureTwo tier application was advantageous in ease of development, user interface andsecurity.

    Disdvantage of two tier architectureThe disadvantage of the two tier application was in the deployment phase.Whenever the application logic changed the two tier application needed the application tobe redistributed at each and every installed client computers.

    Costs and Limitations

    Scalability. The two tier design will scale-up to service 100 users on a network. Itappears that beyond this number of users, the performance capacity is exceeded. This isbecause the client and server exchange "keep alive" messages continuously, even when nowork is being done, thereby saturating the networkImplementing business logic in stored procedures can limit scalability because as moreapplication logic is moved to the database management server, the need for processingpower grows. Each client uses the server to execute some part of its application code, andthis will ultimately reduce the number of users that can be accommodated.

    Interoperability . The two tier architecture limits interoperability by using storedprocedures to implement complex processing logic (such as managing distributed databaseintegrity) because stored procedures are normally implemented using a commercial

    database management system's proprietary language. This means that to change orinteroperate with more than one type of database management system, applications mayneed to be rewritten. Moreover, database management system's proprietary languages aregenerally not as capable as standard programming languages in that they do not provide arobust programming environment with testing and debugging, version control, and librarymanagement capabilities.

    System administration and configuration . Two tier architectures can be difficult toadminister and maintain because when applications reside on the client, every upgrademust be delivered, installed, and tested on each client. The typical lack of uniformity in theclient configurations and lack of control over subsequent configuration changes increaseadministrative workload.

    Batch jobs . The two tiered architecture is not effective running batch programs. Theclient is typically tied up until the batch job finishes, even if the job executes on theserver; thus, the batch job and client users are negatively affected

    The three tier software architectureAn architeture evolved in the 1990s to overcome the limitation of the deployment

  • 8/9/2019 Analysis and Architecture Process

    10/50

    disadvantage of the two tier architecture. A middle tier was introduced inbetween theclient tier and data tier. The middle tier providing mangement of process. The businesslogic resided in the middle tier. The middle tier provided scalability by distributing thebusiness logic on various computers.The three tier architecture is used when an effectivedistributed client/server design is needed that provides increased performance, flexibility,maintainability, reusability, and scalability, while hiding the complexity of distributedprocessing from the user.

    By moving the business logic to the middle tier, client tier became thin client from a fatclient. The client requested business logic services from the middle tier. This made easy tochange the business logic in the middle tier without any redistribution of application to allinstalled client computers.

    Isolation of concernsThe major advantage is that the front end clients are clearly separated from the back enddata manipulation facilities. This allows details of the data storage mechanisms such aswhich database is used, record structure and field names to be abstracted away from theclient processes. All the front end sees is an abstract operation request which takes inputand output parameters.

    E nabling database migrationD atabase restructuring, upgrades, migration or other changes can be performed

    without thenecessity to stop or alter the client programs.

    F ront end modificationsS imilarly, new front end clients can be introduced or old ones removed without any

    need to modify thedatabases or provide new access mechanisms.

    D ata from multiple sources

    A client may require data from a number of servers. This can be handled easily because aController which automatically splits the data operation request into several sub-operations. Each sub-operation is then performed by the appropriate data agent and thecombined results forwarded to the calling client.

    Application Architecture Design// provide later

    Applications, Servlets and CGI Scripts

    What is a Servlet?A servlet is a web component, managed by a container, that generates dynamic

    content. Servlets aresmall, platform independent Java classes compiled to an architecture neutral bytecode that

    can beloaded dynamically into and run by a web server. Servlets interact with web clients via arequestresponse paradigm implemented by the servlet container. This request-response model isbased onthe behavior of the Hypertext Transfer Protocol (HTTP).

  • 8/9/2019 Analysis and Architecture Process

    11/50

    What is a Servlet Container?The servlet container, in conjunction with a web server or application server, provides thenetwork services over which requests and responses are set, decodes MIME basedrequests, and formats MIME based responses. A servlet container also contains andmanages servlets through their lifecycle.

    A servlet container can either be built into a host web server or installed as an add-oncomponent to a Web Server via that servers native extension API. Servlet Containers canalso be built into or possibly installed into web-enabled Application Servers.

    All servlet containers must support HTTP as a protocol for requests and responses, butmay alsosupport additional request / response based protocols such as HTTPS (HTTP over SSL).Theminimum required version of the HTTP specification that a container must implement isHTTP/1.0. It is strongly suggested that containers implement the HTTP/1.1 specification aswell.A Servlet Container may place security restrictions on the environment that a servletexecutes in.

    In a Java 2 Platform Standard Edition 1.2 (J2SE) or Java 2 Platform Enterprise Edition 1.2(J2EE) environment, these restrictions should be placed using the permission architecturedefined by Java 2 Platform. For example, high end application servers may limit certainaction, such as the creation of a Thread object, to insure that other components of thecontainer are not negatively impacted.

    Java Servlets provide web developers with a simple, consistent mechanism for extendingthe functionality of a web server and for accessing existing business systems. A servlet canalmost be thought of as an applet that runs on the server side -- without a face. JavaServlets have made many web applications possible.

    Servlets are the Java platform technology of choice for extending and enhancing Web

    servers. Servlets provide a component-based, platform-independent method for buildingweb-based applications, without the performance limitations of CGI programs. And unlikeproprietary server extension mechanisms (such as the Netscape Server API or Apachemodules), Servlets are server- and platform-independent. This leaves you free to select a"best of breed" strategy for your servers, platforms, and tools.

    Written in Java, Servlets have access to the entire family of Java APIs, including the JDBCAPI to access enterprise databases. Servlets also access library of HTTP-specific calls, andall the benefits of the mature Java language, including portability, performance,reusability, and crash protection.

    Today, Servlets are a popular choice for building interactive web applications. Third-partyServlet containers are available for Apache Web Server, iPlanet Web Server (formerly

    Netscape Enterprise Server), Microsoft IIS, and others. Servlet containers can also beintegrated with web-enabled application servers, such as BEA WebLogic ApplicationServer, IBM WebSphere, Netscape Application Server, and others.

    You might want to check out the latest information on JavaServer Pages (JSP). JSPtechnology is an extension of the servlet technology created to support authoring of HTMLand XML pages. It makes it easier to combine fixed or static template data with dynamic

  • 8/9/2019 Analysis and Architecture Process

    12/50

    content. Even if you're comfortable writing servlets, there are several compelling reasonsto investigate JSP technology as a complement to your existing work.

    Comparing Servlets with Other TechnologiesIn functionality, servlets lie somewhere between Common Gateway Interface (CGI)

    programs and proprietary server extensions such as the Netscape Server API (NSAPI) orApache Modules.Servlets have the following advantages over other server extension mechanisms:

    They are generally much faster than CGI scripts because a different process modelis used.

    In CGI a process is started for every request Servlet is started only once.

    Since a CGI process is started for every request, you cannot maintain the state onthe server.

    Think you need to add a sequence number to the client HTML saying " youaccesses this page "12" ( xx) times.For this you may need to add a hidden columnin the HTML and acesses it to increment and display the next time.Hence it is stateless

    They use a standard API that is supported by many web servers.

    They have all the advantages of the Java programming language, including ease ofdevelopment and

    platform independence.

    They can access the large set of APIs available for the Java platform.

    Servlets can handle requests in multithreading.

    In servlets , they are in memory for 24 hours x 7 days a week, so you can have avariable to hold the poolable resources such as database connection or userinformation.

    Servlets use Java, hence ultimate use of Java API, Java security, threading,accessing EJB is possible.

    A servlet can interact with other resources (files, databases, applets,applicationswritten in Java or in other languages) to construct the response that will be sentback to the client and, if needed, to save

  • 8/9/2019 Analysis and Architecture Process

    13/50

    information about the request-response interaction.

    With a servlet approach, the server can grant full access to local facilities, such asdatabases, and trust that the servlet itself will control the amount and precisenature of access that is effectively afforded to external users.

    Servlets can be client programs of other services, for example, when they are usedin distributed application systems.

    It is possible to invoke servlets from a local or remote disk across the network.

    Servlets can be chained. This means that one servlet can call another servlet, thusbecoming its client. It can also call several servlets in sequence.

    Servlets can be dynamically called from within HTML pages, using the special HTML tag. This function is also known as servlet tag technique.

    The Java Servlet API is protocol-independent. It does not assume anything aboutthe protocol used to transmit it on the Internet. You can write a servlet withouthaving to consider what the transmission protocol will be.

    Like all Java programs, servlets can use all the capabilities of the object orientedJava language

    They can be rapidly developed.

    A servlet service routine is only a thread and not an entire operating systemprocess. That is why a servlet can handle connections with multiple clients,accepting requests and downloading responses back to the

    multiple clients. This is a more efficient mechanism than using CGI-BINs.

    Servlets are portable. They run on a variety of servers without needing to berewritten.

    Memory access violations are not possible, so faulty servlets will not crash servers.

    Finally, Java servlets must respect the security rules of the Java platform wherethey run.

    Tier One Choices: Applet, Application, HTML, HTML + JavaScript

    The main performance hit in three-tier communication is the trip between tiers one andtwo (imagine a user in Australia using a browser to access an applet which is being

  • 8/9/2019 Analysis and Architecture Process

    14/50

    downloaded from the UK, and the server application and database live on a LAN situated inthe UK). HTTP is slow.

    For an Internet / intranet / extranet based application:Use an HTML form or forms only if trips between the client and server machines

    will be minimal and local validation of input is not required. Use HTML forms + JavaScriptif trips between the client and server machines will be minimal and some local validation ofinput is required. If the system is required to cope with users operating in differentlocales, for example, then applets would be a good choice because they can use ResourceBundles. Resource bundles are a feature of JDK1.1 so the applet must be run within abrowser which supports JDK1.1 (Version 4 browsers). The Version 4 browsers (i.e.Netscape 4.x and Internet Explorer 4.x do not consistently support the JDK1.1 eventmodel, so the Java plug-in will be required to standardize the situation). If the customerhas no control over the types of browsers which users of the system will be accessing thesystem with, then use HTML or HTML + JavaScript (note: HotJava does not supportJavaScript). The customer can really only control the browsers used by intranet users.

    The advantage of deploying an application using applets is that the user automatically getsthe latest version of the application because a new copy is downloaded each time (thereare settings on browsers to change this policy). This clearly reduces client-sideadministration drastically. If applications are chosen for tier one then these must be keptup-to-date manually. The advantage of using applications on tier one is that the appletsecurity restrictions do not apply. Applet security restrictions mean that untrusted appletscannot access local hard disk or local print services and may not connect to any machineother than that which it was downloaded from. Untrusted applets cannot obtaininformation about the client platform and they cannot load client libraries or DLLs. Thecannot run any programs or scripts on the client machine either. All JDK1.0 applets areuntrusted. In JDK1.1 and JDK1.2 applets may be signed, and signed applets may accesslocal hard disks and print services if the user chooses to trust them. In JDK1.2 theconcept of protection domains and policies is introduced, whereby the user can assign adegree of trust to a particular class or classes.

    Tier Two Choices: Servlet, Application

    If HTML forms (with or without JavaScript) are employed in the first tier, these mustcommunicate using HTTP to a Web server on the second tier. The Web server maycommunicate with non-Java code using, for example, CGI (Common Gateway Interface).CGI requests are handled by creating a new process for each request, which takes upconsiderable server resources, and severely limits the number of requests which can behandled.

    If applets are employed in the first tier, these are initially downloaded using HTTP and thenmay connect back to a servlet running within the Web server on tier two using RMI, oralternatively connect back to an application running on tier two using RMI. Servletrequests are handled in separate threads rather than separate processes, and so use far

    less system resources than CGI requests. Consequently the system can support manymore servlet requests than CGI requests

    Tier Three Choices:

    The existence of legacy data often means there is no choice on this tier. Javaapplications/servlets can interface to a RDBMS (Relational DataBase Management System)

  • 8/9/2019 Analysis and Architecture Process

    15/50

    using JDBC (it is possible to obtain JDBC drivers for almost all RDBMSs from either thedatabase vendor or from a third-party vendors if the database vendor cannot supply one).Non-Java programs (e.g. CGI programs) access RDBMSs using ODBC.

    Object-oriented applications sitting on the third tier can be accessed using CORBA (readabout Java IDL), and non object oriented applications sitting on the third tier can beaccessed using sockets (if a published interface exists).

    Obviously, a Java application sitting on the third tier can be accessed from the second tierusing RMI if the second tier app is Java.

    Map names to network objects like you would use a telephone directory. Naming servicesbind names to objects. A context is a se of name-to-binding objects. A naming servicelookup results in the named object being retrieved based on its name. The process ofusing a name to look up a named resource is called name resolution. Names can be atomic(index.html), compound (/java/index.class) or composite (http://ww.k.com/java/bu.class).

    Directory services build upon naming services. X.500, NDS and NIS are examples ofDirectory services of which NDS and NIS are proprietary. LDAP was created as a front end

    for X500 directory services but has replaced it on many servers. It is non-proprietary, runsover TCP/IP and is a manageable subset of X.500. version 3 is current. X.500 is for largedirectory services on WANs and LDAP is suited to large enterprises. X.500 requires the useof the higher-level OSI protocol layers;

    LDAP works over TCP/IP JNDI is an API for developing naming and directory service clientsthat work with multiple naming and directory services such as LDAP and NIS+ JMAPIprovides an integrated solution for system, network and service management ofdistributed systems. Java is suitable due to the heterogeneous state of distributedsystems.

    Communication Protocols in a Three-Tier Architecture

    HTTP, RMI, IIOP, JDBC, JDBC DBC (See module 1 also)

    The different methods of tier-to-tier communication are RMI (Remote Method Invocation),IIOP (Internet Inter-ORB Protocol), RPC (Remote Procedure Call) and Sockets.

    RMI : (Java app to Java app), runs over Java Remote Method Protocol (JRMP)IIOP : Internet Inter-ORB Protocol (Object-oriented app to object oriented app)(Theprotocol which CORBA runs over)RPC : Procedure call to another program.Sockets : Transfer a stream of bytes between two programs (programs communicatingusing sockets obviously need to agree on some sort of protocol)

    Both RMI and IIOP are object oriented: object call to method on another object. With RMIthe return values and parameters are objects. With IIOP the return values andparameters are structures. With RPC the return values and parameters are structures.RMI and CORBA are usually implemented on top of RPCs or sockets.

  • 8/9/2019 Analysis and Architecture Process

    16/50

    There are different communication models between the tiers:

    Asynchronous communication : Publish/subscribe model (based on events - like theJDK1.1 event model) Calling application just carries on processing after making a request.An example of this is message queuing. This model is not compromised by the networkbeing temporarily unavailable.

    Synchronous communication : Calling application waits for a response to its requestbefore continuing. This type of communication requires the network to be available.

    Conversationalcommunication : Calling application can either wait for a reply beforecontinuing processing, or carry on without waiting. This type of communication alsorequires the network to be available.

    Remote Method Invocation (RMI)

    Remote Method Invocation (RMI) enables the programmer to create distributed Java

    technology-based to Java technology-based applications, in which the methods of remoteJava objects can be invoked from other Java virtual machines, possibly on different hosts.A Java technology-based program can make a call on a remote object once it obtains areference to the remote object, either by looking up the remote object in thebootstrapnaming service provided by RMI or by receiving the reference as an argument ora return value. A client can call a remote object in a server, and that server can also be aclient of other remote objects. RMI uses object serialization to marshal and unmarshalparameters and does not truncate types, supporting true object oriented polymorphism.

    RMI applications are often comprised of two separate programs: a server and a client. Atypical server application creates some remote objects, makes references to themaccessible, and waits for clients to invoke methods on these remote objects. A typical

    client application gets a remote reference to one or more remote objects in the server andthen invokes methods on them. RMI provides the mechanism by which the server and theclient communicate and pass information back and forth. Such an application is sometimesreferred to as a distributed object application.

    Distributed object applications need to

    Locate remote objects: Applications can use one of two mechanisms to obtainreferences to remote objects. An application can register its remote objects withRMI's simple naming facility, the rmiregistry, or the application can pass and returnremote object references as part of its normal operation.

    Communicate with remote objects: Details of communication between remoteobjects are handled by RMI; to the programmer, remote communication looks likea standard Java method invocation.

  • 8/9/2019 Analysis and Architecture Process

    17/50

  • 8/9/2019 Analysis and Architecture Process

    18/50

    A stub for a remote object implements the same set of remote interfaces that the remoteobject implements. This allows a stub to be cast to any of the interfaces that the remoteobject implements. However, this also means that only those methods defined in a remoteinterface are available to be called in the receiving virtual machine.

    RMI provides a simple and direct model for distributed computation with Java objects.These objects can be new Java objects, or can be simple Java wrappers around an existingAPI. Java embraces the "Write Once, Run Anywhere model. RMI extends the Java model tobe run everywhere."

    Because RMI is centered around Java, it brings the power of Java safety and portability todistributed computing. You can move behavior, such as agents and business logic, to thepart of your network where it makes the most sense. When you expand your use of Javain your systems, RMI allows you to take all the advantages with you.

    RMI connects to existing and legacy systems using the standard Java native methodinterface JNI. RMI can also connect to existing relational database using the standardJDBC? package. The RMI/JNI and RMI/JDBC combinations let you use RMI to communicate

    today with existing servers in non-Java languages, and to expand your use of Java tothose servers when it makes sense for you to do so. RMI lets you take full advantage ofJava when you do expand your use.

    AdvantagesAt the most basic level, RMI is Java's remote procedure call (RPC) mechanism. RMI hasseveral advantages over traditional RPC systems because it is part of Java's objectoriented approach. Traditional RPC systems are language-neutral, and therefore areessentially least-common-denominator systems-they cannot provide functionality that isnot available on all possible target platforms.RMI is focused on Java, with connectivity to existing systems using native methods. Thismeans RMI can take a natural, direct, and fully-powered approach to provide you with adistributed computing technology that lets you add Java functionality throughout your

    system in an incremental, yet seamless way.The primary advantages of RMI are:

    Object Oriented: RMI can pass full objects as arguments and return values, not justpredefined data types. This means that you can pass complex types, such as a standardJava hashtable object, as a single argument. In existing RPC systems you would have tohave the client decompose such an object into primitive data types, ship those data types,and the recreate a hashtable on the server. RMI lets you ship objects directly across thewire with no extra client code.

    Mobile Behavior : RMI can move behavior (class implementations) from client to serverand server to client. For example, you can define an interface for examining employeeexpense reports to see whether they conform to current company policy. When an

    expense report is created, an object that implements that interface can be fetched by theclient from the server. When the policies change, the server will start returning a differentimplementation of that interface that uses the new policies. The constraints will thereforebe checked on the client side-providing faster feedback to the user and less load on theserver-without installing any new software on user's system. This gives you maximalflexibility, since changing policies requires you to write only one new Java class and installit once on the server host.

  • 8/9/2019 Analysis and Architecture Process

    19/50

    Design Patterns: Passing objects lets you use the full power of object orientedtechnology in distributed computing, such as two- and three-tier systems. When you canpass behavior, you can use object oriented design patterns in your solutions. All objectoriented design patterns rely upon different behaviors for their power; without passingcomplete objects-both implementations and type-the benefits provided by the designpatterns movement are lost.

    Safe and Secure: RMI uses built-in Java security mechanisms that allow your system tobe safe when users downloading implementations. RMI uses the security manager definedto protect systems from hostile applets to protect your systems and network frompotentially hostile downloaded code. In severe cases, a server can refuse to download anyimplementations at all.

    Easy to Write/Easy to Use : RMI makes it simple to write remote Java servers and Javaclients that access those servers. A remote interface is an actual Java interface. A serverhas roughly three lines of code to declare itself a server, and otherwise is like any otherJava object. This simplicity makes it easy to write servers for full-scale distributed objectsystems quickly, and to rapidly bring up prototypes and early versions of software fortesting and evaluation. And because RMI programs are easy to write they are also easy tomaintain.

    Connects to Existing/Legacy Systems : RMI interacts with existing systems throughJava's native method interface JNI. Using RMI and JNI you can write your client in Javaand use your existing server implementation. When you use RMI/JNI to connect to existingservers you can rewrite any parts of you server in Java when you choose to, and get thefull benefits of Java in the new code. Similarly, RMI interacts with existing relationaldatabases using JDBC without modifying existing non-Java source that uses thedatabases.

    Write Once, Run Anywhere : RMI is part of Java's "Write Once, Run Anywhere"approach. Any RMI based system is 100% portable to any Java Virtual Machine*, as is anRMI/JDBC system. If you use RMI/JNI to interact with an existing system, the code written

    using JNI will compile and run with any Java virtual machine.

    Distributed Garbage Collection: RMI uses its distributed garbage collection feature tocollect remote server objects that are no longer referenced by any clients in the network.Analogous to garbage collection inside a Java Virtual Machine, distributed garbagecollection lets you define server objects as needed, knowing that they will be removedwhen they no longer need to be accessible by clients.

    Parallel Computing: RMI is multi-threaded, allowing your servers to exploit Java threadsfor better concurrent processing of client requests.

    The Java Distributed Computing Solution : RMI is part of the core Java platformstarting with JDK? 1.1, so it exists on every 1.1 Java Virtual Machine. All RMI systems talk

    the same public protocol, so all Java systems can talk to each other directly, without anyprotocol translation overhead.

    Architecture Overview( To add later)

  • 8/9/2019 Analysis and Architecture Process

    20/50

    Object Naming and LocatingThe Java Naming and Directory Interface (JNDI) is a standard extension to the JavaTMplatform, providing Java technology-enabled applications with a unified interface tomultiple naming and directory services in the enterprise. As part of the Java Enterprise APIset, JNDI enables seamless connectivity to heterogeneous enterprise naming and directoryservices. Developers can now build powerful and portable directory-enabled applicationsusing this industry standard.

    Overview of the ArchitectureThe JNDI architecture consists of the JNDI API and the JNDI SPI. The JNDI API allows Java

    applications to access a variety of naming and directory services. The JNDI SPI is designedtobe used by arbitrary service providers including directory service providers. This enables avariety of directory and naming services to be plugged in transparently to the Javaapplication(which uses only the JNDI API). Figure 2 shows the JNDI architecture and includes a fewservice providers of directory and naming contexts as examples.

    Java Technology Architecture Details

    Architecture AnalysisCustomer AppraisalArchitecture Framework AssessmentCORBA Architecture OverviewMicrosoft DCOM ArchitectureComparison of Object FrameworksAssessing CORBA for the Architecture

    CORBA ApplicabilityCORBA Architecture Implementation ConsiderationsCORBA Implementation StagesApplet Design Critical IssuesApplet Design DetailsApplet Design ElementsApplet RulesTier Two Design ChoicesJava Interface Definition Language (IDL) Architecture Overview Tier Three Design

    Architecture Analysis

    Applet Design Critical Issues

    Applet DefinitionApplet is a small Java application which runs within / from a browser in the client tier ofthe application.Usually the applet is embedded in the HTML. The applet HTML tag is looks like

    http://prasks.webahn.com/architect/ch3.html#Architecture%20Analysishttp://prasks.webahn.com/architect/ch3.html#CORBA%20Architecturehttp://prasks.webahn.com/architect/ch3.html#Applet%20Design%20Criticalhttp://prasks.webahn.com/architect/ch3.html#Architecture%20Analysishttp://prasks.webahn.com/architect/ch3.html#CORBA%20Architecturehttp://prasks.webahn.com/architect/ch3.html#Applet%20Design%20Critical
  • 8/9/2019 Analysis and Architecture Process

    21/50

  • 8/9/2019 Analysis and Architecture Process

    22/50

    an Applet..\overview/test.html..\overview/test.html, the code and document bases wouldboth specify the someDirectory directory.

    Data that the applet always needs, or needs to rely on as a backup, is usually specifiedrelative to the code base. Data that the applet user specifies, often by using parameters, isusually specified relative to the document base.

    For security reasons, browsers limit the URLs from which untrusted applets can read. Forexample, most browsers don't allow untrusted applets to use ".." to get to directoriesabove the code base or document base. Also, since untrusted applets can't read filesexcept those on the applet's originating host, the document base isn't generally useful ifthe document and the untrusted applet are on different servers.

    The Applet class defines convenient forms of image-loading and sound-loading methodsthat let you specify images and sounds relative to a base URL. For example, assume anapplet is set up with one of the directory structures shown in the following figure.

    To create an Image object using the a.gif image file under imgDir, the applet can use thefollowing code:

    Image image = getImage(getCodeBase(), "imgDir/a.gif");

    Sending Messages to Other Applets

    Applets can find other applets and send messages to them, with the following securityrestrictions:

    Many browsers require that the applets originate from the same server. Many browsers further require that the applets originate from the same directory

    on the server (the same code base). The Java API requres that the applets be running on the same page, in the same

    browser window.

    Some browsers let applets invoke methods on other applets -- even applets on differentpages in the same browser -- as long as all of the applets come from the same code base.This method of interapplet communication isn't supported by the Java API, so it's possiblethat it will not be supported by all browsers.

    An applet can find another applet either by looking it up by name (using the AppletContextgetApplet method) or by finding all the applets on the page (using the AppletContextgetApplets method). Both methods, if successful, give the caller one or more Appletobjects. Once the caller finds an Applet object, the caller can invoke methods on theobject.

    Finding an Applet by Name: The getApplet Method

    The getApplet method looks through all of the applets on the current page to see if one ofthem has the specified name. If so, getApplet returns the applet's Applet object.By default, an applet has no name. For an applet to have a name, one must be specified inthe HTML code that adds the applet to a page. You can specify an applet's name in twoways:

  • 8/9/2019 Analysis and Architecture Process

    23/50

    By specifying a NAME attribute within the applet's tag. For example:. . .? By specifying a NAME parameter with a tag. For example:. . .

    Although at least one Java-enabled browser conducts a case-sensitive search, theexpected behavior is for the getApplet method to perform a case-insensitive search. Forexample, getApplet("old pal") and getApplet("OLD PAL") should both find an applet named"Old Pal".

    Every applet is implemented by creating a subclass of the Applet class. The followingfigure shows the inheritance hierarchy of the Applet class. This hierarchy determines muchof what an applet can do and how, as you'll see on the next few pages.

    What Applets Can and Can't Do

    Security RestrictionsEvery browser implements security policies to keep applets from compromising systemsecurity. This section describes the security policies that current browsers adhere to.However, the implementation of the security policies differs from browser to browser. Also,security policies are subject to change. For example, if a browser is developed for use onlyin trusted environments, then its security policies will likely be much more lax than thosedescribed here.

    Current browsers impose the following restrictions on any applet that is loaded over thenetwork:

    An applet cannot load libraries or define native methods. It cannot ordinarily read or write files on the host that's executing it. It cannot make network connections except to the host that it came from. It cannot start any program on the host that's executing it. It cannot read certain system properties. Windows that an applet brings up look different than windows that an application

    brings up.

    Each browser has a SecurityManager object that implements its security policies. When aSecurityManager detects a violation, it throws a SecurityException. Your applet can catch

    this SecurityException and react appropriately.

    Finding and Loading Data FilesWhenever an applet needs to load some data from a file that's specified with a relativeURL (a URL that doesn't completely specify the file's location), the applet usually uses

  • 8/9/2019 Analysis and Architecture Process

    24/50

    either the code base or the document base to form the complete URL. The code base,returned by the Applet getCodeBase method, is a URL that specifies the directory fromwhich the applet's classes were loaded. The document base, returned by the AppletgetDocumentBase method, specifies the directory of the HTML page that contains theapplet.Unless the tag specifies a code base, both the code base and document baserefer to the same directory on the same server. For example, in the figure in Test Drivingan Applet..\overview/test.html..\overview/test.html, the code and document bases wouldboth specify the someDirectory directory.Data that the applet always needs, or needs to rely on as a backup, is usually specifiedrelative to the code base. Data that the applet user specifies, often by using parameters, isusually specified relative to the document base.

    For security reasons, browsers limit the URLs from which untrusted applets can read. Forexample, most browsers don't allow untrusted applets to use ".." to get to directoriesabove the code base or document base. Also, since untrusted applets can't read filesexcept those on the applet's originating host, the document base isn't generally useful ifthe document and the untrusted applet are on different servers.

    Practical Considerations when Writing AppletsSecurity Restrictions

    One of the main goals of the Java environment is to make browser users feel securerunning any applet. To achieve this goal, we've started out conservatively, restrictingcapabilities perhaps more than necessary. As time passes, applets will probably get moreand more abilities.

    Each applet viewer has a SecurityManager object that checks for applet security violations.When a SecurityManager detects a violation, it creates and throws a SecurityExceptionobject. Generally, the SecurityException constructor prints a warning message to the

    standard output. An applet can catch SecurityExceptions and react appropriately, such asby reassuring the user and by resorting to a "safer" (but less ideal) way of accomplishingthe task.

    Some applet viewers swallow some SecurityExceptions, so that the applet never gets theSecurityException. For example, the JDK Applet Viewer's implementation of theAppletContext getApplet and getApplets methods simply catches and ignores anySecurityExceptions. The user can see an error message in the standard output, but at leastthe applet gets a valid result from the methods. This makes some sense, since getAppletsshould be able to return any valid applets it finds, even if it encounters invalid ones. (TheApplet Viewer considers an applet valid if it's loaded from the same host as the appletthat's calling getApplets.)

    Existing applet viewers (including Web browsers) impose the following restrictions:Applets cannot load libraries or define native methods.Applets can use only their own Java code and the Java API the applet viewer provides. At aminimum, each applet viewer must provide access to the API defined in the java.*packages.An applet cannot ordinarily read or write files on the host that is executing it.The JDK Applet Viewer actually permits some user-specified exceptions to this rule, but

  • 8/9/2019 Analysis and Architecture Process

    25/50

    Netscape Navigator 2.0, for example, does not. Applets in any applet viewer can read filesspecified with full URLs, instead of by a filename. A workaround for not being to write filesis to have the applet forward data to an application on the host the applet came from.

    An applet cannot make network connections except to the host that it came from.The workaround for this restriction is to have the applet work with an application on thehost it came from. The application can make its own connections anywhere on thenetwork. See Using a Server to Work Around Security Restrictions for an example.An applet cannot start any program on the host that is executing it.Again, an applet can work with a server-side application instead.An applet cannot read certain system properties.See Reading System Properties for more information.Windows that an applet brings up look different than windows that an application bringsup.Applet windows have some warning text and either a colored bar or an image. This helpsthe user distinguish applet windows from those of trusted applications.The following figures show a window brought up by a program that can run either as anapplet or as an application. The first figure shows what the window looks like when theprogram is run as an application on the Solaris platform. The second figure shows thewindow when the program runs as an applet within the Solaris Netscape Navigator 2.0browser.Working with a Server-Side ApplicationApplets, like other Java programs, can use the API defined in the java.net package tocommunicate across the network. The only difference is that, for security reasons, the onlyhost an applet can communicate with is the host it was delivered from.

    Depending on the networking environment an applet is loaded into, and depending on thebrowser that runs the applet, an applet might not be able to communicate with itsoriginating host. For example, browsers running on hosts inside firewalls often cannot getmuch information about the world outside the firewall. As a result, some browsers mightnot allow applet communication to hosts outside the firewall.

    It's easy to find out which host an applet came from. Just use the Applet getCodeBasemethod and the java.net.URL getHost method, like this:String host = getCodeBase().getHost();Once you have the right host name, you can use all the networking code that isdocumented in the CustomNetworking..\..\networking/index.html..\..\networking/index.html trail.

    3: Design Considerations

    When you begin a software project, ask yourself these three questions:

    How do I want to deliver my software to users? How can I design an application that is accessible to all potential users?

    How can I design an application that suits a global audience and requires minimaleffort to localize?

    Choosing an Application or an AppletAt the beginning of the development process, you must decide if you want to create astandalone application or an applet that is displayed in a web browser. The following figureshows the different environments for running applications and applets.

  • 8/9/2019 Analysis and Architecture Process

    26/50

    ( add fig later )

    When deciding between an application and an applet, the two main issues you need toconsider are distribution and security, including read and write permissions. If you decideto use an applet, you must also decide whether to display your applet in the user's currentbrowser window or in a separate browser window.For an example of an application that uses the Java look and feel, see MetalEditApplication. For an example of an applet, see Retirement Savings Calculator Applet. For alist of additional reading on applets, see Design for Applets.

    DistributionWhen deciding how to distribute your software, weigh the needs of both end users andadministrators. Don't forget to consider ease-of-use issues for:

    Initial distribution and installation of the software Maintenance of the software Updates to the software Daily access to the software

    At one extreme is the standalone application, distributed on a CD-ROM disc or a floppydisk and installed on the end user's local hard disk. Once the application is installed, userscan easily access it. In an enterprise environment, however, maintenance can becomplicated because separate copies of the application exist on each user's localcomputer. Distribution of the original application and subsequent updates require shipmentof the software to, and installation by, multiple users.In contrast, applets are simpler to distribute and maintain because they are installed on acentral web server. Using a web browser on their local machines, users can access thelatest version of the applet from anywhere on the intranet or Internet. Users, however,must download the applet over the network each time they start the applet.

    If you are creating an applet, make sure that your users have a browser that contains the

    JFC or that they are using JavaTM Plug-In. That way, users will not have to download theJFC every time they run the applet.

    Security IssuesAnother issue to consider is whether your software needs to read and write files.Standalone Java applications can read or write files on the user's hard disk just as otherapplications do. For example, the MetalEdit application reads and writes documents on theuser's local disk.In contrast, applets usually cannot access a user's hard disk because they are intended fordisplay on a web page, which might come from an unknown source. Applets are bettersuited for tasks that do not require access to a user's hard disk. For example, a web pagefor a bank might offer an applet that calculates home mortgage payments and printsresults, but does not save files on the customer's hard disk.

    You can also use applets as a front end to a central database. For example, the RetirementSavings Calculator applet enables company employees to select funds for their retirementcontribution and update the amount of their contribution in the company database.

    Placement of AppletsIf you decide to design an applet, you can display your applet in the user's current browserwindow or in a separate browser window.

  • 8/9/2019 Analysis and Architecture Process

    27/50

    Applets in the User's Current Browser WindowThe current browser window is well suited for displaying applets in which users perform asingle task. This approach enables users to perform the task and then resume otheractivities in the browser, such as surfing the web.

    An applet displayed in the current browser window should not include a menu bar--havinga menu bar in both the applet and the browser might confuse users. The mnemonicsassigned in the applet must also be different from the mnemonics used to control thebrowser window; otherwise, the mnemonics might conflict.

    A disadvantage of using the current browser window is that the applet terminates whenusers navigate to another web page. The current settings and data in the applet are lost.To use the applet again, users must navigate back to the page that contains the appletand reload the page.

    Applets in Separate Browser WindowsIf your applet involves more than one task or if users might visit other web pages beforecompleting the task, launch a separate browser window and display the applet there. Thisapproach enables users to interact with the applet and maintain the original browser

    window for other activities. Navigating to another web page in the original browser windowdoes not affect the applet in the separate browser window.Designing an applet for a separate browser window is simpler if you remove the browser'snormal menu and navigation controls. Doing so avoids confusion between the browser'smenu and controls and the applet's menus and controls. You also avoid potential conflictsbetween mnemonics in the two windows.

    CORBA Architecture Overview

    Overview of CORBAThe Common Object Request Broker Architecture (CORBA) is an emerging open distributed

    object computing infrastructure being standardized by the Object Management Group.CORBA automates many common network programming tasks such as object registration,location, and activation; request demultiplexing; framing and error-handling; parametermarshalling and demarshalling; and operation dispatching.

    The following figure illustrates the primary components in the OMG Reference Modelarchitecture. Descriptions of these components are available further below. Portions ofthese descriptions are based on material from

    Object Services -- These are domain-independent interfaces that are used by manydistributed object programs. For example, a service providing for the discovery of otheravailable services is almost always necessary regardless of the application domain. Twoexamples of Object Services that fulfill this role are:

    The Naming Service -- which allows clients to find objects based on names; The Trading Service -- which allows clients to find objects based on their properties.

  • 8/9/2019 Analysis and Architecture Process

    28/50

    There are also Object Service specifications for lifecycle management, security,transactions, and event notification, as well as many others

    Common Facilities -- Like Object Service interfaces, these interfaces are alsohorizontally-oriented, but unlike Object Services they are oriented towards end-userapplications. An example of such a facility is the Distributed Document Component Facility(DDCF), a compound document Common Facility based on OpenDoc. DDCF allows for thepresentation and interchange of objects based on a document model, for example,facilitating the linking of a spreadsheet object into a report document.

    Domain Interfaces -- These interfaces fill roles similar to Object Services and CommonFacilities but are oriented towards specific application domains. For example, one of thefirst OMG RFPs issued for Domain Interfaces is for Product Data Management (PDM)Enablers for the manufacturing domain. Other OMG RFPs will soon be issued in thetelecommunications, medical, and financial domains.

    Application Interfaces - These are interfaces developed specifically for a given

    application. Because they are application-specific, and because the OMG does not developapplications (only specifications), these interfaces are not standardized. However, if overtime it appears that certain broadly useful services emerge out of a particular applicationdomain, they might become candidates for future OMG standardization.

    CORBA ORB ArchitectureThe following figure illustrates the primary components in the CORBA ORB architecture.Descriptions of these components are available below the figure.

    ( Fig CORBA ORB Architecture later )

    Object Implementation -- This defines operations that implement a CORBA IDLinterface. Object implementations can be written in a variety of languages including C, C++, Java, Smalltalk, and Ada.

    Client -- This is the program entity that invokes an operation on an objectimplementation. Accessing the services of a remote object should be transparent to thecaller. Ideally, it should be as simple as calling a method on an object, i.e., obj->op(args).The remaining components in Figure 2 help to support this level of transparency.

    Object Request Broker (ORB) -- The ORB provides a mechanism for transparentlycommunicating client requests to target object implementations. The ORB simplifiesdistributed programming by decoupling the client from the details of the methodinvocations. This makes client requests appear to be local procedure calls. When a client

    invokes an operation, the ORB is responsible for finding the object implementation,transparently activating it if necessary, delivering the request to the object, and returningany response to the caller.

    ORB Interface -- An ORB is a logical entity that may be implemented in various ways(such as one or more processes or a set of libraries). To decouple applications from

  • 8/9/2019 Analysis and Architecture Process

    29/50

  • 8/9/2019 Analysis and Architecture Process

    30/50

    containing the Java applet that is needed to take advantage of the Plug-in environment.So what we are left with is a good technology with limitations on its deployment. I haveseen my share of projects that have stalled due to deployment issues of Java applets. Theproject managers assumed that by a certain date a particular version of Java would bewidely supported by browsers, and when that assumption failed to materialize, so did theirdeployment plans.Alternative ApproachesMany experts (including those from Sun itself) indicate that their preference is to use Javaon the server and rely on HTML to create the GUI that is to run on the browser. Thatapproach may make sense for a number of sites, but there are instances where HTML (oreven DHTML) simply cannot replace the richness and the interactivity that a live program(i.e., a Java applet) can provide. Applications that rely on rich presentation slides, real-time graphs and statistics, and sophisticated user interfaces rely on Java applets. So oneapproach that has seen success is not to abandon Java applets altogether, but to limit thefunctionality of an applet and rely more on back-end resources.For example, instead of having the applet perform time-consuming calculations and thendrawing a graph, have a back-end program do the calculations and then send to the appletjust the necessary data to draw the graph. Of course, this approach requires connectivitybetween the applet and server-side programs which is the topic of this article.There are a number of mechanisms where applets and server-side programs like servlets

    can communicate with each other. For example, an applet can make RMI calls to server-side processes or use CORBA to activate remote methods. Architecturally, processseparation using remote objects is an elegant solution, but there are deployment issueswith both CORBA and RMI. Many corporate firewalls block such traffic which in effecteliminates the above technologies as a communication choice.Another approach would be to refresh the HTML page containing the applet and pass newparameters to it. In this scenario, the server-side process would repaint the entire HTMLpage at a given time interval. As part of the repainting, the parameters to the applet areupdated. The applet will then display itself based on the new parameters. This is a one-way communication channel (the server sends messages to the applet) and is also veryinefficient.Relying on HTTPThe communication channel between an applet and a servlet must be simple and

    deployable in various environments. If you look at the essence of such communication, ittypically involves the applet initiating a request to the server-side program. This requestcontains some data. The server-side program must receive the request, interpret it andsend a response back to the applet. What I have just described is identical to how abrowser communicates with a Web server through HTTP. Java has built-in support for bothHTTP and URL-based connections. So all we have to do is to open a connection to a servletspecified by an URL and send data to it. Granted, HTTP is not the most efficient protocol,but it does provide a channel through which data exchange can be done and that is whatwe are after.Due to the applet security model, there is a restriction with the above approach. Theapplet can only communicate back to the server from which it came from. So wherever ourserver-side process is running, that's where the applet must come from. The server-sideprogram is free to open channels to other resources such as remote databases, CORBA

    objects, EJB servers, etc. So from the design perspective, we can still utilize the benefitsthat remote objects provide.The applet must know the URL of the server-side process. For our purposes, we use aservlet, but CGI scripts, JSP, ASP, or other server-side processes that can communicatevia HTTP can be used. Once we have the URL, we can open a connection and send data:

    String urlAddress = "http://www.someurl.com/someServlet"

  • 8/9/2019 Analysis and Architecture Process

    31/50

    java.net.URL url = new java.net.URL(urlAddress);

    java.net.URLConnection c = url.openConnection();

    This will give us the communication channel to the servlet. What we have to do next is to

    send the servlet some data in the context of a request. We don't want to restrict ourselvesto a particular data type. To facilitate this, we create an output stream and write our datain terms of bytes to it. Note that an instance of the ByteArrayOutputStream is used tocreate the actual DataOutputStream. If you look at the DataOutputStream class, you'll seea number of "write" methods for various data types. We use the writeUTF() method towrite a simple text message.

    ByteArrayOutputStream bytesOut = new ByteArrayOutputStream();

    DataOutputStream out = new DataOutputStream(bytesOut);

    out.writeUTF("Hello World");

    out.flush();

    Before sending our message, we need to calculate its size. To do that, we create an arrayof bytes that will store our data. The length of that array is the size of our data. We alsoneed to specify in our request the MIME type and the length of the request message data.

    byte buffer[] = bytesOut.toByteArray();c.setRequestProperty("Content-type","application/octet-stream");c.setRequestProperty("Content-length","" + buffer.length);

    Finally, we can create a new DataOutputStream to write the data to the connection weestablished earlier. The data we are writing out is simply the array of bytes we createdearlier.

    DataOutputStream out2 = new DataOutputStream(c.getOutputStream());

    out2.write(buffer)

    Architecture Analysis

    Taking Advantage of the Applet API

    The applet API lets you take advantage of the close relationship that applets have withWeb browsers. The API is provided by the java.applet package -- mainly by the Appletclass and the AppletContext interface. Thanks to the applet API, applets can do thefollowing:? Be notified by the browser of milestones.? Load data files specified relative to the URL of the applet or the page in which it isrunning.

  • 8/9/2019 Analysis and Architecture Process

    32/50

    ? Display short status strings.? Make the browser display a document.? Find other applets running in the same page.? Play sounds.? Get parameters specified by the user in the tag.

    Finding and Loading Data FilesWhenever an applet needs to load some data from a file that's specified with a relativeURL (a URL that doesn't completely specify the file's location), the applet usually useseither the code base or the document base to form the complete URL. The code base,returned by the Applet getCodeBase method, is a URL that specifies the directory fromwhich the applet's classes were loaded. The document base, returned by the AppletgetDocumentBase method, specifies the directory of the HTML page that contains theapplet.Unless the tag specifies a code base, both the code base and document baserefer to the same directory on the same server. For example, in the figure in Test Drivingan Applet..\overview/test.html..\overview/test.html, the code and document bases wouldboth specify the someDirectory directory.Data that the applet always needs, or needs to rely on as a backup, is usually specifiedrelative to the code base. Data that the applet user specifies, often by using parameters, isusually specified relative to the document base.

    Note: For security reasons, browsers limit the URLs from which untrusted applets canread. For example, most browsers don't allow untrusted applets to use ".." to get todirectories above the code base or document base. Also, since untrusted applets can't readfiles except those on the applet's originating host, the document base isn't generally usefulif the document and the untrusted applet are on different servers.

    The Applet class defines convenient forms of image-loading and sound-loading methodsthat let you specify images and sounds relative to a base URL. For example, assume anapplet is set up with one of the directory structures shown in the following figure.

    [PENDING: Figure. For the no-package case, imgDir and the class file are in the samedirectory. For the package case, imgDir and top package directory (com) are in the samedirectory.]To create an Image object using the a.gif image file under imgDir, the applet can use thefollowing code:Image image = getImage(getCodeBase(), "imgDir/a.gif");

    Sending Messages to Other AppletsApplets can find other applets and send messages to them, with the following securityrestrictions:? Many browsers require that the applets originate from the same server.

    ? Many browsers further require that the applets originate from the same directory on theserver (the same code base).? The Java API requres that the applets be running on the same page, in the samebrowser window.

    Note: Some browsers let applets invoke methods on other applets -- even applets ondifferent pages in the same browser -- as long as all of the applets come from the same

  • 8/9/2019 Analysis and Architecture Process

    33/50

    code base. This method of interapplet communication isn't supported by the Java API, soit's possible that it will not be supported by all browsers.

    An applet can find another applet either by looking it up by name (using the AppletContextgetApplet method) or by finding all the applets on the page (using the AppletContextgetApplets method). Both methods, if successful, give the caller one or more Appletobjects. Once the caller finds an Applet object, the caller can invoke methods on theobject.Finding an Applet by Name: The getApplet MethodThe getApplet method looks through all of the applets on the current page to see if one ofthem has the specified name. If so, getApplet returns the applet's Applet object.By default, an applet has no name. For an applet to have a name, one must be specified inthe HTML code that adds the applet to a page. You can specify an applet's name in twoways:? By specifying a NAME attribute within the applet's tag. For example:. . .? By specifying a NAME parameter with a tag. For example:. . .

    Browser Note: Although at least one Java-enabled browser conducts a case-sensitivesearch, the expected behavior is for the getApplet method to perform a case-insensitivesearch. For example, getApplet("old pal") and getApplet("OLD PAL") should both find anapplet named "Old Pal".

    Every applet is implemented by creating a subclass of the Applet class. The followingfigure shows the inheritance hierarchy of the Applet class. This hierarchy determines muchof what an applet can do and how, as you'll see on the next few pages.

    The Life Cycle of an AppletBelow is the Simple applet.

    You can't run applets.Here's what you'd see if you could:

    Note: Because some old browsers don't support 1.1, the above applet is a 1.0 version

    (here is the 1.0 code; here's the 1.1 code). To run the 1.1 version of the applet, go toexample-1dot1/Simple.html. For more information about running applets, refer to AboutOur Examples.

    Loading the Applet

  • 8/9/2019 Analysis and Architecture Process

    34/50

  • 8/9/2019 Analysis and Architecture Process

    35/50

    ? It can start running.? It can stop running.? It can perform a final cleanup, in preparation for being unloaded.The next page describes the four applet methods that correspond to these four types ofreactions.What Applets Can and Can't DoThis page gives an overview of both the restrictions applets face and the specialcapabilities they have. You'll find more details in the SecurityRestrictions..\practical/security.html..\practical/security.html lesson.Security RestrictionsEvery browser implements security policies to keep applets from compromising systemsecurity. This section describes the security policies that current browsers adhere to.However, the implementation of the security policies differs from browser to browser. Also,security policies are subject to change. For example, if a browser is developed for use onlyin trusted environments, then its security policies will likely be much more lax than thosedescribed here.Current browsers impose the following restrictions on any applet that is loaded over thenetwork:? An applet cannot load libraries or define native methods.? It cannot ordinarily read or write files on the host that's executing it.

    ? It cannot make network connections except to the host that it came from.? It cannot start any program on the host that's executing it.? It cannot read certain system properties.? Windows that an applet brings up look different than windows that an application bringsup.Each browser has a SecurityManager object that implements its security policies. When aSecurityManager detects a violation, it throws a SecurityException. Your applet can catchthis SecurityException and react appropriately.Applet CapabilitiesThe java.applet package provides an API that gives applets some capabilities thatapplications don't have. For example, applets can play sounds, which other programs can'tdo yet.Here are some other things that current browers and other applet viewers let applets do:

    ? Applets can usually make network connections to the host they came from.? Applets running within a Web browser can easily cause HTML documents to be displayed.

    ? Applets can invoke public methods of other applets on the same page.? Applets that are loaded from the local file system (from a directory in the user'sCLASSPATH) have none of the restrictions that applets loaded over the network do.? Although most applets stop running once you leave their page, they don't have to.

    Finding and Loading Data FilesWhenever an applet needs to load some data from a file that's specified with a relativeURL (a URL that doesn't completely specify the file's location), the applet usually uses

    either the code base or the document base to form the complete URL. The code base,returned by the Applet getCodeBase method, is a URL that specifies the directory fromwhich the applet's classes were loaded. The document base, returned by the AppletgetDocumentBase method, specifies the directory of the HTML page that contains theapplet.Unless the tag specifies a code base, both the code base and document baserefer to the same directory on the same server. For example, in the figure in Test Driving

  • 8/9/2019 Analysis and Architecture Process

    36/50

    an Applet..\overview/test.html..\overview/test.html, the code and document bases wouldboth specify the someDirectory directory.Data that the applet always needs, or needs to rely on as a backup, is usually specifiedrelative to the code base. Data that the applet user specifies, often by using parameters, isusually specified relative to the document base.

    Note: For security reasons, browsers limit the URLs from which untrusted applets canread. For example, most browsers don't allow untrusted applets to use ".." to get todirectories above the code base or document base. Also, since untrusted applets can't readfiles except those on the applet's originating host, the document base isn't generally usefulif the document and the untrusted applet are on different servers.

    The Applet class defines convenient forms of image-loading and sound-loading methodsthat let you specify images and sounds relative to a base URL. For example, assume anapplet is set up with one of the directory structures shown in the following figure.

    To create an Image object using the a.gif image file under imgDir, the applet can use thefollowing code:Image image = getImage(getCodeBase(), "imgDir/a.gif");

    Practical Considerations when Writing AppletsSecurity RestrictionsOne of the main goals of the Java environment is to make browser users feel securerunning any applet. To achieve this goal, we've started out conservatively, restrictingcapabilities perhaps more than necessary. As time passes, applets will probably get moreand more abilities.This page tells you about the current applet security restrictions, from the point of view ofhow they affect applet design. For more information on applet security, you should refer toMarianne Mueller's excellent document:Frequently Asked Questions - AppletSecurityhttp://java.sun.com/sfaq/http://java.sun.com/sfaq/

    Each applet viewer has a SecurityManager object that checks for applet security violations.When a SecurityManager detects a violation, it creates and throws a SecurityExceptionobject. Generally, the SecurityException constructor prints a warning message to thestandard output. An applet can catch SecurityExceptions and react appropriately, such asby reassuring the user and by resorting to a "safer" (but less ideal) way of accomplishingthe task.Some applet viewers swallow some SecurityExceptions, so that the applet never gets theSecurityException. For example, the JDK Applet Viewer's implementation of theAppletContext getApplet and getApplets methods simply catches and ignores anySecurityExceptions. The user can see an error message in the standard output, but at leastthe applet gets a valid result from the methods. This makes some sense, since getAppletsshould be able to return any valid applets it finds, even if it encounters invalid ones. (TheApplet Viewer considers an applet valid if it's loaded from the same host as the applet

    that's calling getApplets.)To learn about security managers and the kinds of security violations they can check for,see Introducing the SecurityManager..\..\essential/system/securityIntro.html..\..\essential/system/securityIntro.html.As the applet overview lesson mentioned, existing applet viewers (including Webbrowsers) impose the following restrictions:Applets cannot load libraries or define native methods.

  • 8/9/2019 Analysis and Architecture Process

    37/50

    Applets can use only their own Java code and the Java API the applet viewer provides. At aminimum, each applet viewer must provide access to the API defined in the java.*packages.An applet cannot ordinarily read or write files on the host that is executing it.The JDK Applet Viewer actually permits some user-specified exceptions to this rule, butNetscape Navigator 2.0, for example, does not. Applets in any applet viewer can read filesspecified with full URLs, instead of by a filename. A workaround for not being to write filesis to have the applet forward data to an application on the host the applet came from. Thisapplication can write the data files on its own host. See Working with a Server-SideApplication for more examples.An applet cannot make network connections except to the host that it came from.The workaround for this restriction is to have the applet work with an application on thehost it came from. The application can make its own connections anywhere on thenetwork. See Using a Server to Work Around Security Restrictions for an example.An applet cannot start any program on the host that is executing it.Again, an applet can work with a server-side application instead.An applet cannot read certain system properties.See Reading System Properties for more information.Windows that an applet brings up look different than windows that an application bringsup.

    Applet windows have some warning text and either a colored bar or an image. This helpsthe user distinguish applet windows from those of trusted applications.The following figures show a window brought up by a program that can run either as anapplet or as an application. The first figure shows what the window looks like when theprogram is run as an application on the Solaris platform. The second figure shows thewindow when the program runs as an applet within the Solaris Netscape Navigator 2.0browser.Working with a Server-Side ApplicationApplets, like other Java programs, can use the API defined in the java.net package tocommunicate across the network. The only difference is that, for security reasons, the onlyhost an applet can communicate with is the host it was delivered from.

    Note: Depending on the networking environment an applet is loaded into, and depending

    on the browser that runs the applet, an applet might not be able to communicate with itsoriginating host. For example, browsers running on hosts inside firewalls often cannot getmuch information about the world outside the firewall. As a result, some browsers mightnot allow applet communication to hosts outside the firewall.

    It's easy to find out which host an applet came from. Just use the Applet getCodeBasemethod and the java.net.URL getHost method, like this:String host = getCodeBase().getHost();Once you have the right host name, you can use all the networking code that isdocumented in the CustomNetworking..\..\networking/index.html..\..\networking/index.html trail.

    3: Design Considerations

    When you begin a software project, ask yourself these three questions:? How do I want to deliver my software to users?? How can I design an application that is accessible to all potential users?? How can I design an application that suits a global audience and requires minimal effortto localize?

  • 8/9/2019 Analysis and Architecture Process

    38/50

    Choosing an Application or an AppletAt the beginning of the development process, you must decide if you want to create astandalone application or an applet that is displayed in a web browser. The following figureshows the different environments for running applications and applets.Figure 17 Environments for Applications and Applets

    When deciding between an application and an applet, the two main issues you need toconsider are distribution and security, including read and write permissions. If you decideto use an applet, you must also decide whether to display your applet in the user's currentbrowser window or in a separate browser window.For an example of an application that uses the Java look and feel, see MetalEditApplication. For an example of an applet, see Retirement Savings Calculator Applet. For alist of additional reading on applets, see Design for Applets.

    DistributionWhen deciding how to distribute your software, weigh the needs of both end users andadministrators. Don't forget to consider ease-of-use issues for:? Initial distribution and installation of the software? Maintenance of the software? Updates to the software? Daily access to the softwareAt one extreme is the standalone application, distributed on a CD-ROM disc or a floppydisk and installed on the end user's local hard disk. Once the application is installed, userscan easily access it. In an enterprise environment, however, maintenance can becomplicated because separate copies of the application exist on each user's localcomputer. Distribution of the original application and subsequent updates require shipmentof the software to, and installation by, multiple users.In contrast, applets are simpler to distribute and maintain because they are installed on acentral web server. Using a web browser on their local machines, users can access thelatest version of the applet from anywhere on the intranet or Internet. Users, however,must download the applet over the network each time they start the applet.If you are creating an applet, make sure that your users have a browser that contains theJFC or that they are using JavaTM Plug-In. That way, users will not have to download theJFC every time they run the applet.

    Security IssuesAnother issue to consider is whether your software needs to read and write files.Standalone Java applications can read or write files on the user's hard disk just as otherapplications do. For example, the MetalEdit application reads and writes documents on theuser's local disk.In contrast, applets usually cannot access a user's hard disk because they are intended fordisplay on a web page, which might come from an unknown source. Applets are bettersuited for tasks that do not require access to a user's hard disk. For example, a web pagefor a bank might offer an applet that calculates home mortgage payments