SCMAD
SCMAD
SCMAD
SCMAD
Certification
StudyGuide
SCMAD:Sun Certified Mobile Application Developer for the Java, Study Guide
SCMAD Certification Exam Objectives
Section 1: JTWI (JSR 185) and Overview / JTWI-compliant Wireless Applications 1.1 Identify the goals and characteristics of the JTWI specification (JSR 185), including the mandatory specifications, conditionally required specifications, and the minimum configuration. Compare the relationship and differences between JTWI and other wireless Java technologies. 1.2 Develop portable applications that are compatible with the requirements and restrictions an application programmer must adhere to, in order to ensure compatibility with a JTWI-compliant device, including resource minimums (eg. standard-size application), clock resolution, and the use of preferred MIME names as applicable to CLDC 1.0/1.1, MIDP 2.0, WMA 1.1, and MMAPI 1.1). Section 2: CLDC (1.0 / 1.1) 2.1 Identify correct and incorrect statements or examples about the requirements and scope of the CLDC specification, including the differences between 1.0 and 1.1. 2.2 Describe the ways in which a CLDC virtual machine does and does not adhere to the Java Language Specification (JLS) and the Java Virtual Machine specification. 2.3 Identify correct and incorrect statements or examples about CLDC classes including those derived from J2SE, and the CLDC-specific classes, including identifying which core J2SE classes are NOT included in CLDC, or have different behaviors (example: java.lang.String, io classes, etc.) 2.4 Given the differences and limitations of exception/error handling with CLDC devices, handle exceptions correctly. 2.5 Wirte code that effectively manages memory / garbage collection. Section 3: Security (both CLDC and MIDP) 3.1 Given a set of requirements, design and build applications given CLDC-specified application-level security, including the sandbox model. 3.2 Identify correct and incorrect statements or examples about untrusted MIDlet suites. 3.3 Explain trusted MIDlet suite security authorization and permissions, including the process for MIDlet suite signing.
3.4 Explain requirements and process of using X.509 PKI authentication for MIDlet
4.1 Write code using the Generic Connection framework specified by CLDC, recognizing its characteristics, use, classes, and interfaces. This may include identification of the class hierarchy and relationships of the Generic Connection framework. 4.2 Write code for MIDP 2.0 networking, and issues and limitations related to HTTP, HTTPS, and TCP/IP sockets and Datagrams, recognizing which connections are required and which are optional, as well as comparing the issues related to TCP/IP and UDP Datagrams. 4.3 Write code using the MIDP 2.0 classes in the javax.microedition.io package, including code that correctly opens, closes, and uses a network connection, using the implications of network blocking operations, scheme, connection number limitations, and character encoding. 4.4 Given a problem scenario, troubleshoot networking issues for MIDP 2.0. Section 5 -- Application Model /Delivery / Lifecycle / Provisioning 5.1 Explain the specification guarantees for: browsing for MIDlet suites, transferring MIDlet suites, using HTTP, push registries, basic authentication, installing and updating MIDlet suites, invoking MIDlet suites, and deleting MIDlet suites. 5.2 Identify correct and incorrect statements or examples about the MIDP application model, including: the MIDP execution environment, MIDlet suites, MIDlet suite packaging (including the manifest and the application descriptor), discovering available services on the device, discovering which version of MIDP/CLDC is on the device. 5.3 Develop applications that correctly reflect a MIDlet's application lifecycle, including: the purpose of the MIDlet class, communication with the application management software, platform request API, valid MIDlet states and transitions, and the behavior that should and should NOT be implemented within different lifecycle methods (including the constructor). 5.4 Deploy a MIDP 2.0 application with the correct use of JAD files and manifests. 5.5 Given an installation failure, analyze the problem, , and develop possible resolutions. 5.6 Given a set of requirements, develop applications that correctly implement MIDP 2.0 support for delayed or scheduled activities using timers and background threads. Section 6: MIDP Persistent Storage 6.1 Develop code that correctly implements handling, sharing and removing RecordStores within MIDlet suites. 6.2 Develop code that correctly implements adding, retrieving, modifying, and deleting individual records in a RecordStore, and converting RecordStore record data to and from
7.2 Develop applications that correctly use MIDP 2.0 Push Registry including discovery, dynamic vs. static, and recognizing the types of connections that can and cannot be accepted. Section 8 -- MIDP UI API 8.1 Given a scenario, develop MIDP 2.0-compliant user interfaces, recognizing portability requirements and limitations (e.g. double-buffering not guaranteed), and performance issues (e.g. using inner classes, freeing memory buffers, etc.). 8.2 Discuss the MIDP user interface high-level API including concurrency, portability, structure of the API, and interplay with the application manager. 8.3 Explain the MIDP user interface low-level API including font support, repainting, and coordinate system. 8.4 Given a set of requirement, develop interactive MIDP 2.0 user interface code with proper event-handling (including both the high-level and low-level APIs, repainting and threading issues). 8.5 Identify correct and incorrect statements or examples about the classes (including the class hierarchy) within the javax.microedition.lcdui package. 8.6 Compare and contrast high-level and low-level APIs, including layout techniques. 8.7 Explain requirements, issues, class hierarchy, and relationships between items and screens. section 9: MIDP Game API 9.1 Given a scenario, develop code using the MIDP Game API package to improve performance and reduce application size. 9.2 Compare and contrast the use of MIDP's GameCanvas class vs. the MIDP low-level Canvas.
9.3 Given a set of requirements, develop code using MIDP's LayerManager class. 9.4 Given a set of requirements, develop code using MIDP's Layer, Sprite and TiledLayer classes.
10.2 Given a set of requirements, develop code that correctly uses MIDP support for sound including audio playback, tone generation, media flow controls (start, stop, etc.), media type controls (volume, tone), and media capabilities using "Manager", "Player", and "Control" objects, recognizing the difference between required vs. optional features. 10.3 Develop code that correctly uses MMAPI support for playback and recording of media, including the use of the "DataSource", "Player", and "Manager" objects, support for audio and video capture and playback, system properties queries, recognizing the difference between required and optional features. 10.4 Identify correct and incorrect statements or examples about the media class hierarchies in both MIDP 2.0 and MMAPI 1.1. Section 11: Wireless Messaging API 1.1 (WMA) 11.1 Describe the WMA's basic support for sending and receiving messages, and the Generic Connection Framework. 11.2 Explain the WMA's support for SMS and Cell Broadcast capabilities. 11.3 Identify correct and incorrect statements or examples about WMA including the WMA addressing scheme, client vs. server connections, WMA-related exceptions, WMA-related security issues, message size limitation, message creation, sending, synchronous vs. asynchronous message receipt, and the relationship between WMA and Push Registry.
1) Which are true about JTWI 1.0? A) CLDC 1.1 is the minimum CLDC requirement. B) CLDC 1.0 is the minimum CLDC requirement. C) A JTWI-compliant device must support a MIDlet suite JAR size up to 64 KB. D) A JTWI-compliant device must support a MIDlet suite JAR size up to 128 KB. E) MIDP 2.0 is required. F) WMA 1.1 is an optional specification. ==============================
2) Which is true about MMAPI and JTWI? A) All of MMAPI must be implemented in a JTWI-compliant device. B) A JTWI device must implement all of the MMAPI, PLUS additional media APIs. C) A JTWI device must implement a subset, but not all, of the MMAPI. D) A JTWI device must implement ONLY a subset, and never all, of the MMAPI. E) A JTWI device must support media types explicitly defined in JTWI, regardless of whether they are specified in MMAPI. ==============================
3) A FAKE drag and drop Given the list of classes below, put a "B" next to those which exist in both J2SE and CLDC 1.1, put a "C" for those which exist ONLY in CLDC 1.1 (but not in J2SE) and put a "J" next to those which exist ONLY in J2SE (but not in CLDC 1.1).
ArrayList ThreadGroup Float Socket BufferedOutputStream Stack StreamConnection FileOutputStream VirtualMachineError NoClassDefFoundError IllegalAccessError ==============================
5) Which are true about MIDlets? A) Classes in one suite have restricted access to classes in a other suites. B) Classes in one suite have full access to classes in another suite, as long as both suites are trusted. C) Classes in one suite can never access classes in other suites. ==============================
6) Which are true? A) A MIDlet can never be installed in an untrusted domain. B) A MIDlet suite can be installed in an untrusted domain ONLY if the suite is signed with an x.509 PKI certificate. C) A MIDlet can be installed in an untrusted domain if the suite is authenticated with an invalid cx.509 PKI certificate. D) a MIDlet can be installed in an untrusted domain if it is not signed with a x.509 PKI certificate. E) An untrusted suite can request permissions in the JAR manifest.
============================== 7) Which are true? A) A suite using x.509 PKI authentication must have a midlet-permission JAD attribute. B) Suites using x.509 PKI authentication must have a security certificate inside the META-INF directory. C) A suite using x.509 PKI authentication must use base64 encoding for the certificate. ============================== 8) Which connection String goes with the SocketConnection interface? A) socket://:4242 B) http://foo.sun.com C) socket:162.101.4.100:4242 D) datagram://:4242 ============================== 9) Which are true? A) A MIDP 2.0 device is guaranteed to be able to create an HTTP connection to a server that supports HTTP 1.1. B) A MIDP 2.0 device can NOT create HTTP connections. C) A MIDP 2.0 device is not required to support HTTP 1.1, but it may. ============================== 10) What is the function of the Application Descriptor? [on real exam, you would not answer this as an essay, but I didn't have time to come up with good answers for it ]
10
============================== 16) Put an "H" next to the code or class from the high-level MIDP 2.0 API, and and an "L" next to those from the low-level API. Put a "E" for those things that could apply to either high-level or low-level, depending on how they're used. When we use "...", assume that whatever you don't see is correct. new Command(...); Form f = new Form(); graphicsObject.setColor(...); new Canvas(...); paint(Graphics g) { } Sprite LayerManager
J2ME Code Camp J2ME programming camp will show experienced Java application developers how to write Java applications for Wireless devices such as cell phones and two-way pagers that are compliant with the Mobile Information Device Profile (MIDP). With labs.
10
11
11
12
12
13
13
14
Q1 Which connection String goes with the SocketConnection interface? 1. socket://:4242 2. http://foo.sun.com 3. socket://162.101.4.100:4242 4. datagram://:4242
14
15
Q2 (Posted on Java Ranch) I have some questions regarding the Signed MIDlet Suite with x.509 PKI? 1. Can I create a root certifcate or a protected domain? 2. How the signer associates a protected domain with a signed MIDlet during the signing procedure? 3. Does the signer has the control which the protected domain or root certificate to use to sign a MIDlet suite? 4. Do I need a root certificate during the signing procedure? 5. If a device has more than one root certificate, how do I know a signed MIDlet is associated which protected domain?
MIDP Persistent Storage Simple record orientate database and is called the Record Management System (RMS) Persistent across multiple invocations of Midlet Midlets within a Midlet Suite are allowed to create multiple record stores (*5 is guaranteed by JTWI) as long as they have different names Record Stores are uniquely named using "Midlet Suite Name + Name of Record Store" Midlet Suite Name comes from MIDlet_Vendor + MIDlet_Name from the jad Record Store Names are case sensitive upto 32 Unicode characters No locking. All operations are atomic, synchronous so no corruption occurs Be careful when threading though as if two threads try and update the same record you dont know who will "win" Time / Date stamps are longs in format used by System.getCurrentTimeMillis() Record Store timestamped when it was last modified Also has a version which is incremented each time a modification occurs Midlets within a Midlet Suite can access one anothers record stores directly. New APIs in MIDP 2.0 explicitly allow this. Starting from MIDP 2.0 record stores can be shared between Suites as long as they have been created with the AUTHMODE_ANY parameter When using RecordStore.getRecord() it returns a copy of the record Access controls defined when Record Stores are created Access controls enforced on Open RecordEnumeration enumerateRecords(RecordFilter filter, RecordComparator comparator, boolean keepUpdated) There are three ways to create/open
15
16
public static RecordStore openRecordStore(String recordStoreName, String vendorName, String suiteName) recordStoreName - the MIDlet suite unique name for the record store, consisting of between one and 32 Unicode characters inclusive. createIfNecessary - if true, the record store will be created if necessary authmode - the mode under which to check or create access. Must be one of AUTHMODE_PRIVATE or AUTHMODE_ANY. This argument is ignored if the RecordStore exists. writable - true if the RecordStore is to be writable by other MIDlet suites that are granted access. This argument is ignored if the RecordStore exists. vendorName - the vendor of the owning MIDlet suite suiteName - the name of the MIDlet suite Records
Arrays of bytes DataInputStream / DataOutputStream - ByteArrayInputStream / ByteArrayOutputStream to pack and unpack Records uniquely indentified (PK) within a Record Store by their record id (integer) First record is 1 (not 0 as you may think as its an "array" of bytes - very annoying!) On adding a record the record id increases by 1 If you delete a record then it is unusable ever again, does not 'free' it up.
RecordComparator int compare(byte[] rec1, byte[] rec2) Returns PRECEDES if rec1 precedes rec2 in sort order, or FOLLOWS if rec1 follows rec2 in sort order, or EQUIVALENT if rec1 and rec2 are equivalent in terms of sort order. RecordEnumeration A class representing a bidirectional record store Record enumerator. The RecordEnumeration logically maintains a sequence of the recordId's of the records in a record store. The enumerator will iterate over all (or a subset, if an optional record filter has been supplied) of the records in an order determined by an optional record comparator. By using an optional RecordFilter, a subset of the records can be chosen that match the supplied filter. This can be used for providing search capabilities. By using an optional RecordComparator, the enumerator can index through the records in an order determined by the comparator. This can be used for providing sorting capabilities.
16
17
If, while indexing through the enumeration, some records are deleted from the record store, the recordId's returned by the enumeration may no longer represent valid records. To avoid this problem, the RecordEnumeration can optionally become a listener of the RecordStore and react to record additions and deletions by recreating its internal index. Use special care when using this option however, in that every record addition, change and deletion will cause the index to be rebuilt, which may have serious performance impacts. Allows an easy way to run over a set of records. After processing no need to recreate the enumeration if you need to do it again, just call reset(). If the underlying store has changed in some way just call rebuild()
RecordFilter boolean matches(byte[] candidate) The record to consider. Within this method, the application must treat this parameter as read-only. RecordListener Can be added to a record store (any number). Automatically removed once store is closed recordAdded(RecordStore recordStore, int recordId) recordChanged(RecordStore recordStore, int recordId) recordDeleted(RecordStore recordStore, int recordId) Resources Comprehensive intro from Sun site Good intro from the IBM Site about RMS Javadoc for MIDP2.0 RecordStore Clarifications - CLDC 1.0 Allow a MIDlet suite to create upto 10 simultanously running threads Record elapsed time in increments not to exceed 40ms. Things like garbage collection affects this so at least 80% of test attempts MUST meet the requirement Names for encodings must support preferred MIME name as defined optional label Must support basic methods for String compareTo(), regionMatches() and Character equals(), isLowerCase(), isUpperCase(), isDigit(), toLowerCase(), toUpperCase(), digit() Unicode version 3.0 must be supported although only the subset of ISO Latin1 range of characters Cusomer Time Zone IDs CustomID: GMT Sign Hours (Minutes) +/- Digit Digit Digit Digit Digit 0 <= Hours <= 23, 0 <= Minutes <=59 TimeZone.getTimeZone("GMT-8").getId() => GMT-08:00 Clarifications - MIDP 2.0 Allow creation of at least 5 independent record stores Must support HTTP 1.1
17
18
JPEG & JFIF must be supported. Mandatory image format in MIDP 2.0 is PNG but this is a lossless format and may consumer more space than necessary for images PNG & JFIF color depths upto 32, must support images upto 32768. Even though devices do not need to have color displays they must be able to process color images. Timer, 40ms 80% of attempts Create a minimum of 5 running Timers Implement a method for selecting a phone number from the device phone book when the user is editing TextBox or TextField where the constraint is TextField.PHONENUMBER TextField.EMAILADDR must allow ANY characters (you could restrict it in the original specification Allow 'Push Registry Alarm Events'. If no other security mechanisms in place then this function must NOT be allowed without explicit user permission. Identification of JTWI via a system property, System.getProperty("microedition.jtwi.version") - "1.0"
Clarifications WMA 1.1 Must support SMS If GSM Cell Broadcasts are supported then it must support acces via this API Must support SMS Push (MIDP 2.0 Push). This is for sophisticated server side applications pushing information to phones. If no other security mechanism the not allowed without explicit user permission. Does not mandate any specific implementation Security
See CLDC for security it takes care of MIDP 2.0 takes care of Authentication, Authorization, End to End Security There is no support for running native code The only protection specified is the Untrusted domain All MIDP 1.0 Midlets are by default Untrusted Allowed permissions are allowed without user confirmation User permissions need the user to authorize them
Session - valid from the time of invocation of a MIDlet suite until it terminates. Must prompt the user on or before the first invocation of the API or function that is proteced. The next time the MIDlet is run the user must be reprompted. Oneshot - Must prompt the user EVERY time an invocation of a protected API Blanket - valid for every invocation of an API by a MIDlet suite until it is uninstalled or the permission is changed by the user
Certificates Base64 encoding is used for encoding signature of jar The certificate path includes the signer certificate and any necessary certificates but omitting the root certificate. The root certificate will be found on the device.
18
19
Each certificate in the path is encoded (using base64 but without line breaks) and inserted into the application descriptor as: MIDlet-Certificate-<n>-<m>: <base64 encoding of a certificate>= <n>:= a number equal to 1 for first certification path in the descriptor or 1 greater than the previous number for additional certification paths. This defines the sequence in which the certificates are tested to see if the corresponding root certificate is on the device. See the Authenticating a MIDlet suite section below. So first on is MIDlet-Certificate-1-1 <m>:= a number equal to 1 for the signer's certificate in a certification path or 1 greater than the previous number for any subsequent intermediate certificates. The signature of the JAR is created with the signers private key according to the EMSA-PKCS1-v1_5 encoding method of PKCS #1 version 2.0 standard [RFC2437]. The signature is base64 encoded, formatted as a single MIDlet-Jar-RSASHA1 attribute without line breaks and inserted in the application descriptor. MIDlet-Jar-RSA-SHA1: <base64 encoding of Jar signature> Application descriptors without the MIDlet-Jar-RSA-SHA1 attribute are not authenticated but are installed and invoked as untrusted MIDlet suites. If the jar IS signed then the certificate needs to exist AND it needs to be verified, if it doesnt then the MIDlet will not be installed. Note, you can still install without a JAD! In the jad there are two attributes for setting permissions. In this example it needs HTTP but SMS is optional (the midlet will cope). If HTTP is not available then installation will be aborted. MIDlet-Permissions: javax.microedition.io.Connector.http MIDlet-Permissions-Opt: javax.wireless.messaging.sms.send Note, the manifest is protected because it is within a signed jar but the jad is not Because of this, if there is a mismatch in permissions in the jad / manifest in a 'trusted' MIDlet it will fail to install, untrusted will be okay. This is new in MIDP 2.0 rms, media and game api's all available to an untrusted without explicit user confirmation Midlet.checkPermission() Get the status of the specified permission. If no API on the device defines the specific permission requested then it must be reported as denied. If the status of the permission is not known because it might require a user interaction then it should be reported as unknown. 0 if the permission is denied; 1 if the permission is allowed; -1 if the status is unknown CLDC - Connected Limited Device Configuration 1.1 (JSR 139) The CLDC defines a "lowest common denominator" approach to defining what a device needs to support. It covers
Java Language and JVM features Core Java Libaries Input and Output Security Networking Internationalisation Study Guide From www.ePlanetLabs.com
19
20
Application Life Cycle management User Interface Event Handling End to End Security (thats MIDP 2.0)
Overview Goal is "lowest common denominator" Majority are a subset of J2SE and J2EE Because of j2me device constraints, needed reworking - especially networking Classes that are a subset are contained within java.lang, java.util, java.io Reworked specific CLDC classes contained within javax.microedition.io.* Vector, Stack, Hashtable, Enumeration are the collection classes to use (ie olde world 1.1 stuff!) and not the Collection framework introdiced in JDK1.2 The following System properties are available Settings for the Untrusted Domain microedition.platform Name of the host platform microedition.encoding Default character encoding microedition.configuration Name and version ie "CLDC-1.1" microedition.profiles Names of supported profiles In detail CLDC is as follows:
Differences between CLDC 1.0 and CLDC 1.1 Architecture, Sandbox, JVM Adherence Class File Verification, File Format and Class Loading General Connection Framework (GCF)
Networking Networking builds on top of the GCF (General Connection Framework) and basically consists of a number of <Type>Connection classes that will be returned by the Connector class which creates ALL connections All connections contained within javax.microedition.io.* Only http and https connections are mandated by MIDP 2.0 Connection Classes outwith GCF CommConnection Logical serial port comm:100; HttpConnection HTTP connection. http:// Necessary methods and constants HttpsConnection https:// to establish a secure network connection. SecureConnection Secure socket stream ssl://host.com:79 ServerSocketConnection Server socket stream connection. socket://:79 SocketConnection Socket stream connection. socket://host.com:79 UDPDatagramConnection Datagram connection which knows datagram://host:port
20
21
Where {scheme} is the name of a protocol such as http. The {target} is normally some kind of network address, but protocols may regard this as a fairly flexible field when the connection is not network oriented. Any {parms} are formed as a series of equates on the form ";x=y" such as ;type=a. An optional second parameter may be specified to the open function. The is a mode flag that indicated to the protocol handler the intentions of the calling code. The options here are to specify if the connection is going to be read (READ), written (WRITE), or both (READ_WRITE). The validity of these flag settings is protocol dependent. For instance a connection for a printer would not allow read access, and would throw an IllegalArgumentException if this was attempted. Omitting this parameter results in READ_WRITE being used by default. An optional third parameter is a boolean flag to indicate if the calling code has been written in such a way as to handle timeout exceptions. If this is selected the protocol may throw an InterruptedIOException when it detects a timeout condition. This flag is only a hint to the protocol handler and it is no guarantee that such exceptions will be throws. Omitting this parameter results in no exceptions being thrown. The timeout period is not specified in the open call because this is protocol specific. Protocol implementors can either hardwire an appropriate value or read them from an external source such as the system properties. A ConnectionNotFoundException is thrown if the target name cannot be found or if the requested protocol is not supported
CommConnection A "logical" serial port is defined as a logical connection through which bytes are transferring serially A URI with the type and parameters is used to open the connection. The scheme (defined in RFC 2396) must be:comm:<port identifier>[<optional parameters>] The optional params are: baudrate, bitsperchar, stopbits, parity, none, blocking, autocts, autorts The security model may be applied on the invocation of the Connector.open() method with a valid serial port connection string setBaudRate() may not be honoured if underlying hardware cant cope. Use getBaudRate() to check what it actually is Find out valid identifiers for a device using System.getProperty("microedition.commports"); HttpConnection The connection exists in one of three states:
21
22
Setup, in which the request parameters can be set Connected, in which request parameters have been sent and the response is expected Closed, the final state, in which the HTTP connection has been terminated
After an output stream has been opened by the openOutputStream or openDataOutputStream methods, attempts to change the request parameters via setRequestMethod or the setRequestProperty are ignored. Once the request parameters have been sent, these methods will throw an IOException. When an output stream is closed via the OutputStream.close or DataOutputStream.close methods, the connection enters the Connected state. When the output stream is flushed via the OutputStream.flush or DataOutputStream.flush methods, the request parameters MUST be sent along with any data written to the stream. HttpsConnection getPort() overriden to return a different default(443) than http (80) A secure connection MUST be implemented by one or more of the following specifications:
HTTP over TLS as documented in RFC 2818 and TLS Protocol Version 1.0 as specified in RFC 2246. SSL V3 as specified in The SSL Protocol Version 3.0 WTLS as specified in WAP Forum Specifications June 2000 (WAP 1.2.1) conformance release - Wireless Transport Layer Security document WAP199. WAP(TM) TLS Profile and Tunneling Specification as specified in WAP-219TLS-20010411-a
HTTPS is the secure version of HTTP (IETF RFC2616), a request-response protocol in which the parameters of the request must be set before the request is sent. In addition to the normal IOExceptions that may occur during invocation of the various methods that cause a transition to the Connected state, CertificateException (a subtype of IOException) may be thrown to indicate various failures related to establishing the secure link. The secure link is necessary in the Connected state so the headers can be sent securely. The secure link may be established as early as the invocation of Connector.open() and related methods for opening input and output streams and failure related to certificate exceptions may be reported. SecureConnection This interface defines the secure socket stream connection. A secure connection is established using Connector.open with the scheme "ssl" and the secure connection is established before open returns. Extends javax.microedition.io.SocketConnection If the secure connection cannot be established due to errors related to certificates a CertificateException is thrown. One extra method SecurityInfo getSecurityInfo() throws IOException
22
23
A secure socket is accessed using a generic connection string with an explicit host and port number. The host may be specified as a fully qualified host name or IPv4 number. e.g. ssl://host.com:79 defines a target socket on the host.com system at port 79. Note that RFC1900 recommends the use of names rather than IP numbers for best results in the event of IP number reassignment. A secure connection MUST be implemented by one or more of the following specifications:
TLS Protocol Version 1.0 as specified in RFC 2246. SSL V3 as specified in The SSL Protocol Version 3.0 WAP(TM) TLS Profile and Tunneling Specification as specified in WAP-219TLS-20010411-a
SocketConnection A socket is accessed using a generic connection string with an explicit host and port number. The host may be specified as a fully qualified host name or IPv4 number. e.g. socket://host.com:79 defines a target socket on the host.com system at port 79. Every StreamConnection provides a Connection object as well as an InputStream and OutputStream to handle the I/O associated with the connection. Each of these interfaces has its own close() method. For systems that support duplex communication over the socket connection, closing of the input or output stream SHOULD shutdown just that side of the connection. e.g. closing the InputStream will permit the OutputStream to continue sending data. Once the input or output stream has been closed, it can only be reopened with a call to Connector.open(). The application will receive an IOException if an attempt is made to reopen the stream. getAddress() getPort() return the remote address of the socket getLocalAddress() geLocalPort() return the local address of the socket Alternatively use the System Property to find out hostname System.getProperty("microedition.hostname"); ServerSocketConnection A server socket is accessed using a generic connection string with the host omitted. For example, socket://:79 defines an inbound server socket on port 79. The host can be discovered using the getLocalAddress() method. The acceptAndOpen() method returns a SocketConnection instance. In addition to the normal StreamConnection behavior, the SocketConnection supports accessing the IP end point addresses of the live connection and access to socket options that control the buffering and timing delays associated with specific application usage of the connection. Access to server socket connections may be restricted by the security policy of the device. Connector.open MUST check access for the initial server socket connection and acceptAndOpen MUST check before returning each new SocketConnection. A server socket can be used to dynamically select an available port by omitting both the host and the port parameters in the connection URL string.
23
24
UDPDatagramConnection Defines a datagram connection which knows it's local end point address. The protocol is transaction oriented, and delivery and duplicate protection are not guaranteed. Applications requiring ordered reliable delivery of streams of data should use the SocketConnection. A UDPDatagramConnection is returned from Connector.open() in response to a request to open a datagram:// URL connection string. If the connection string omits both the host and port fields in the URL string, then the system will allocate an available port. The local address and the local port can be discovered using the accessor methods within this interface. The syntax described here for the datagram URL connection string is also valid for the Datagram.setAddress() method used to assign a destination address to a Datagram to be sent. e.g., =datagram://host:port = CertificateException Contained within javax.microedition.pki The CertificateException encapsulates an error that occurred while a Certificate is being used. If multiple errors are found within a Certificate the more significant error should be reported in the exception. Application Delivery / Lifecycle startApp() throws MIDletStateChangeException destroyApp() throws MIDletStateChangeException pauseApp() MIDlet
Class that all Midlets must subclass javax.microedition.midlet.MIDlet Must provide a no arg constructor getAppProperty(String key) Provides a MIDlet with a mechanism to retrieve named properties from the application management software. The properties are retrieved from the combination of the application descriptor file and the manifest. If an attributes in the descriptor has the same name as an attribute in the manifest the value from the descriptor is used and the value from the manifest is ignored. MIDlets must be fully installed or not at all, partial installs are thrown away. MIDlets must not call System.exit() this will throw a SecurityException. Use destroyApp() instead. boolean platformRequest() If the platform has the appropriate capabilities and resources available, it SHOULD bring the appropriate application to the foreground and let the user interact with the content, while keeping the MIDlet suite running in the background. If the platform does not have appropriate capabilities or resources available, it MAY wait to handle the URL request until after the MIDlet suite exits. In this case, when the requesting MIDlet suite exits, the platform MUST then bring the appropriate application (if one exists) to the foreground to let the user interact with the content. This is a nonblocking method. In addition, this method does NOT queue multiple requests.
24
25
Lastly the return boolean value indicates whether the MIDlet should exit first before making the call. resumeRequest() Provides a MIDlet with a mechanism to indicate that it is interested in entering the Active state. Calls to this method can be used by the application management software to determine which applications to move to the Active state. When the application management software decides to activate this application it will call the startApp method. The application is generally in the Paused state when this is called. Even in the paused state the application may handle asynchronous events such as timers or callbacks.
JAD (Java Application Descriptor) & Manifest JAD Files must be served using MIME Type text/vnd.sun.j2me.app-descriptor There are 5 mandatory elements in a jad and 5 in a manifest - but they are different! Attributes Jad / Description Attribute Required? Manifest MIDlet-Name Required Both MIDlet-Version Required Both MIDlet-Vendor Required Both MIDlet-Jar-URL Required JAD MIDlet-Jar-Size Required JAD MicroEditionRequired Manifest eg. MIDP 2.0 Profile MicroEditionRequired Manifest eg. CLDC 1.0 Configuration MIDlet-Icon Optional= Both MIDletOptional Both Description MIDlet-Info-URL Optional Both MIDlet-Data-Size Optional Both Ask AMS to provide a Text Message to MIDLET-DeleteOptional JAD the user when prompted to confirm Confirm deletion of suite MIDlet-DeleteOptional JAD POST Request sent to confirm deletion Notify MIDlet-InstallPOST Request sent to confirm Optional JAD Notify installation Over the Air Provisioning (OTA) When updating the RMS Data should be preserved platformRequest() may be used to update a currently running application When installing over OTA the header should contain User-Agent, AcceptLanguage, and Accept headers - this is so the server can serve out the most appropriate midlet (might be different for different phones or languages)
25
26
User should be notified if attempting to install an older or newer version of an installed MIDlet Device does not need to support MIDlet updates Usually HTTP GET requests used to request a MIDlet but this is not mandated by the specification and can be implementation dependent RMS Data should be kept when updating a midlet
Example JAD MIDlet-Jar-URL: portencross.jar MIDlet-Jar-Size: 15012 MIDlet-Name: PxStatus MIDlet-Vendor: Portencross MIDlet-Version: 0.3 MIDlet-1: PxStatus, /icon.png, org.portencross.j2me.serverstatus.ServerStatusMIDlet MIDlet-Data-Size: 0 MIDlet-Description: Status Midlet for Server Monitoring MicroEdition-Profile:MIDP 1.0 MicroEdition-Configuration:CLDC 1.0 Push Registry (MIDP 2.0) Allows MIDlets to set themselves up to be launched automcatically without user initiation Allows both Timer and Network initiation SMS and CBS are valid protocols but they are only optional Application Management System (AMS) Has List of inbound connections List of Timer Alarms List of MIDlets Consumers of Inbound Connections List of MIDlets Consumers of Timer Alarms Inbound Connections Message Based (such as SMS) Stream Based (such as TCP socket) Packet Based (such as Datagrams) For Static Address specify the port, otherwise for dynamic just specify the protocol (sms, socket or datagram) and a port will be automatically assigned Connector.open("<protocol>://<:port>) Retrieve the hostname using System.getProperty("microedition.hostname") When a stream connection received by the AMS times out for a application not currently running the behavior is not specified what should happen When a Push Event arrives, the AMS is allowed to shut down the running app in order to start the required application Filtering is ignored for CBS Port number filtering is ignored for SMS Push Registration There are two types of registration
26
27
Dynamic Registration - Occurs at runtime using the PushRegistry API. Only use if you want to catch exceptions. Static Registration - Occurs during the installation of the MIDlet Suite using the MIDlet-Push attribute in the JAD. This is usual. Use either method to register inboud connections, timer-based activation can be registered only at runtime. It is possible to create a push activated headless MIDlet but doing so would confuse the User so dont!
PushRegistry The javax.microedition.io.PushRegistry extends basic Object class This is a new class since MIDP 2.0 All methods are static, Maintains a list of inbound connections. An application can register the inbound connections with an entry in the application descriptor file or dynamically by calling the registerConnection() method. MIDlet-Push-<n>:<Connection-URL>, <MIDletClassName>, <AllowedSender> Allowed Sender is the address or address range of the senders permitted to send events. This is also known as a filter. An asterisk(*) to match any number of characters and a question mark(?) to match a single character can be used in the filtering field as wild cards. <n> is valid integer greater than 0. Note, if there is a break, say 1,2,3,5 then 5 would be ignorned as they have to be contiguous Connection-URL for SMS would be the Phones Telephone Number (and port) If the requested local address <Connection-URL> is already in use then installationn will fail. MIDlet-Push-1: socket://:5000, MyPushMidlet, * MIDlet-Permissions: javax.microedition.io.PushRegistry, javax.microedition.io.Connector.serversocket The requirements for buffering of messages are specific to each protocol used for Push and are defined separately for each protocol. There is no general requirement related to buffering that would apply to all protocols. If the implementation buffers messages, these messages MUST be provided to the MIDlet when the MIDlet is started and it opens the related Connection that it has registered for Push. When datagram connections are supported with Push, the implementation MUST guarantee that when a MIDlet registered for datagram Push is started in response to an incoming datagram, at least the datagram that caused the startup of the MIDlet is buffered by the implementation and will be available to the MIDlet when the MIDlet opens the UDPDatagramConnection after startup. When socket connections are supported with Push, the implementation MUST guarantee that when a MIDlet registered for socket Push is started in response to an incoming socket connection, this connection can be accepted by the MIDlet by opening the ServerSocketConnection after startup, provided that the connection hasn't timed out meanwhile. registerAlarm() , registerConnection() are the only two methods that throw Exceptions (ClassNotFoundException) listConnections(boolean available) if true, only return the list of connections with input available, otherwise return the complete list of registered connections for the current MIDlet suite. Use this (true) to see if it was activated by a Push Connection. Study Guide From www.ePlanetLabs.com
27
28
registerConnection(String connection, String midlet, String filter) does the same as the JAD attribute All SMS messages must be delivered to the application once it has started
Why not AWT? When using AWT event objects are created dynamically. Limited CPU and memory of MID cant cope with this. AWT has a rich feature set with functionality like window managers which are not needed AWT assumes some interaction models like a mouse, where most MIDs only have the keypad for user input. Structure of MIDP UI Displayable | -----------------| | Canvas Screen (Low Level) (High Level) Only one Displayable object may be visibile at a time Each Displayable can have a Title, Ticker and a set of Commands Display acts as the "window" manager. setCurrent(Displayable) displays the object and replaces the previous Display can now flashBacklight() and vibrate(int duration) to attract the users attention High Level Designed more for business applications where portability is key. High level abstraction with little control over look and feel (uses native) Actual drawing is performed by the implementation Navigation and scrolling encapsulated byt the implementation Cannot access concrete input devices like individual keys All classes are subclases of Screen. This class takes care of all user interaction. Low Level Little abstraction, need precise control Full control over what is drawn on the display Listen for primitive events like key presses Access to concrete keys Subclasses of Canvas & Graphics 3 Categories of Displayable Screens that encapsulate complex user components like Lists Generic Screens (instances of Form class) that can contain Item objects to represent interface - populate with as many objects as needed Study Guide From www.ePlanetLabs.com
28
29
Interplay with Application Manager getDisplay() callable from Midlet constructor until destroyApp() Display object is same object until destroyApp() is called The Displayable object set by setCurrent() is not changed by the application manager startApp() may call setCurrent() for first screen, only visible after startApp() returns. Since pauseApp() could be called while this is going on and then startApp() would be recalled do not do any intialisation here pauseApp() release as many threads as possible destroyApp() Delete created objects Event Handling Four kinds of UI Callbacks
Abstract commands that are part of the high level API Low Level events that represent single key presses + releases Canvas.paint() Runnable.run() method request by a call to Display.callSerially() All UI callbacks are serialized so they will never occur in parallel. Assured processing of previous event has finished before calling the next On exception. Canvas.serviceRepaints() causes Canvas.paint() and waits for it to complete. This occurs even if caller of serviceRepaints() is iteself within an active call back. Note, there is a potential deadlock here. This is because application Threads can synchronize with themselves and with event callbacks by locking any Object according to the sync policy of the app. Now serviceRepaints() may call another Thread to call paint(). If serviceRepaints() holds a lock so that the paint() method needs it could block! So, serviceRepaints() should not hold any locks needed by the paint() method Timer events are not considered UI events and run concurrently with UI event call backs Applications may have their Timer Callbacks call Display.callSerially() so that work triggered by timer events can be serialized with the UI Event Callbacks Commands are installed to Displayable with addCommand() The implementation does not actually implement any of the semantics of Command, just uses them as a mapping
TextField
A TextField has a maximum size, which is the maximum number of characters that can be stored in the object at any time (its capacity). This limit is enforced when the TextField instance is constructed, when the user is editing text within the TextField, as well as when the application program calls methods on the TextField that modify its contents. The maximum size is the maximum stored capacity and is unrelated to the number of characters that may be displayed at any given time. The number of characters displayed and their arrangement into rows and columns are determined by the device. Constraints usually what you cant do , ie UNEDITABLE
29
30
Creates a new Gauge object with the given label, in interactive or noninteractive mode (user changable), with the given maximum and initial values. The maximum value must be greater than zero, otherwise an exception is thrown. The initial value must be within the range zero to maxValue, inclusive. If the initial value is less than zero, the value is set to zero. If the initial value is greater than maxValue, it is set to maxValue.
Alert
An alert is a screen that shows data to the user and waits for a certain period of time before proceeding to the next screen. An alert is an ordinary screen that can contain text (String) and image, and which handles events like other screens. Alert Types: ALARM, CONFIRMATION, ERROR, INFO, WARNING Alert Types can also play sounds
Ticker
Implements a "ticker-tape," a piece of text that runs continuously across the display. The direction and speed of scrolling are determined by the implementation. While animating, the ticker string scrolls continuously. That is, when the string finishes scrolling off the display, the ticker starts over at the beginning of the string. The same ticker may be shared by several Screen objects There is no API provided for starting and stopping the ticker. Implementation is allowed to pause the scrolling for power consumption purposes
Command & CommandListener Creates a new command object with the given label, type, and priority. public Command(String label, int commandType, int priority)
label - the label string commandType - the command's type, one of BACK, CANCEL, EXIT, HELP, ITEM, OK, SCREEN, or STOP priority - the command's priority value
CommandListener is used for High Level API Events (Screen or Canvas). Indicates that a command event has occurred on Displayable d. One method public void commandAction(Command c, Displayable d)
c - a Command object identifying the command. This is either one of the applications have been added to Displayable with addCommand(Command) or is the implicit SELECT_COMMAND of List. d - the Displayable on which this event has occurred Study Guide From www.ePlanetLabs.com
30
31
Item & Item Listeners Item - A superclass for components that can be added to a Form and Alert. All Item objects have a label field, which is a string that is attached to the item. The label is typically displayed near the component when it is displayed within a screen. This means that the implementation tries to keep the label on the same horizontal row with the item or directly above the item. If the screen is scrolling, the implementation tries to keep the label visible at the same time with the Item. Item.setLayout() - It is illegal to call this method if this Item is contained within an Alert. Item objects can have an associated default Command Object static final int LAYOUT_2 A layout directive indicating that new MIDP 2.0 layout rules are in effect for this Item. If this bit is clear, indicates that MIDP 1.0 layout behavior applies to this Item. Items do not have command objects. Use the following listeners ItemStateListener - This interface is used by applications which need to receive events that indicate changes in the internal state of the interactive items within a Form screen. One method itemStateChanged(Item item) ItemCommandListener - A listener type for receiving notification of commands that have been invoked on Item objects. An Item can have Commands associated with it. When such a command is invoked, the application is notified by having the commandAction() method called on the ItemCommandListener that had been set on the Item with a call to setItemCommandListener(). One method commandAction(Command c, Item item) CustomItem - Subclasses are responsible for their visual appearance including sizing and rendering and choice of colors, fonts and graphics. Subclasses are responsible for the user interaction mode by responding to events generated by keys, pointer actions, and traversal actions. Finally, subclasses are responsible for calling Item.notifyStateChanged() to trigger notification of listeners that the CustomItem?'s value has changed. Choice Listener Choice - UI components implementing selection from predefined number of choices within a Form screen. EXCLUSIVE - is a choice having exactly one element selected at time. IMPLICIT - is a choice in which the currently focused item is selected when a Command is initiated. Not accepted by ChoiceGroup? MULTIPLE - is a choice that can have arbitrary number of elements selected at a time. POPUP - is a choice having exactly one element selected at a time. Not accepted by List TEXT_WRAP_DEFAULT - Constant for indicating that the application has no preference as to wrapping or truncation of text element contents and that the implementation should use its default behavior. TEXT_WRAP_OFF - Constant for hinting that text element contents should be limited to a single line. TEXT_WRAP_ON - Constant for hinting that text element contents should be wrapped to to multiple lines if necessary to fit available content space. Both List and ChoiceGroup? can have images
31
32
Canvas & Low Level Event Listeners Can mix and match low and high level. eg an Options menu (high level Form) from a low level Canvas. This is because Canvas is subclass of Displayable which you can attach commands to. hideNotify() showNotify() if Canvas has been obscured Canvas has a full screen mode where title and ticher are not displayed All low level events are contained within the Canvas class
=keyPressed(int keyCode) , keyReleased(int keyCode) keyRepeated(int keyCode) not necessarily on all devices. Call boolean hasRepeatedEvents() to check
However, to use this effectively, use the game mapping code public class TextCanvas extends Canvas public void keyPressed(int KeyCode) { int action = getGameAction(keyCode); switch(action) { case LEFT: moveBlockLeft();break; case FIRE: fire();break; } } Canvas has the same type of methods for pointer events but not usually available. Call boolean hasPointerEvents() to check first. MIDP Game API The API is comprised of five classes (Displayable) | (Canvas) | | GameCanvas (Layer) | --------LayerManager | Sprite TiledLayer
GameCanvas Provides basic 'screen' functionality for a game, in addition to standard Canvas methods, also provides ability to query the current state of the game keys, synchronous graphics flushing A dedicated buffer is created for each GameCanvas instance. Therefore it is preferable to re-use a single GameCanvas instance in the interests of minimizing heap usage Constructor allows suppression. If the developer only needs to query key status using the getKeyStates method, the regular key event mechanism can be suppressed for game keys while this GameCanvas is shown. If not needed by the application, the suppression of key events may improve performance
32
33
by eliminating unnecessary system calls to keyPressed, keyRepeated and keyReleased methods. Can assume that the contents of this buffer are modified only by calls to the Graphics object(s) obtained from the GameCanvas instance The buffer is initially filled with white pixels. Typically put the full Game Loop in here to check for input, implement game logic and render the updated user interface getKeyStates() Gets the states of the physical game keys. Each bit in the returned integer represents a specific key on the device. A key's bit will be 1 if the key is currently down or has been pressed at least once since the last time this method was called. The bit will be 0 if the key is currently up and has not been pressed at all since the last time this method was called. This latching behavior ensures that a rapid key press and release will always be caught by the game loop, regardless of how slowly the loop runs. This method returns 0 unless the GameCanvas is currently visible as reported by Displayable.isShown(). However simulataneous presses of multiple keys are not guaranteed to be detected due to underlying hardware. flushGraphics() Flushes the off-screen buffer to the display. The size of the flushed area is equal to the size of the GameCanvas. The contents of the offscreen buffer are not changed as a result of the flush operation. This method does not return until the flush has been completed, so the app may immediately begin to render the next frame to the same buffer once this method returns. This method does nothing and returns immediately if the GameCanvas is not currently shown or the flush request cannot be honored because the system is busy. There is also an overloaded method which will just flush a specified region getGraphics() A new Graphics object is created and returned each time this method is called; therefore, the needed Graphics object(s) should be obtained before the game starts then re-used while the game is running. // Get the Graphics object for the off-screen buffer Graphics g = getGraphics(); while (true) { // Check user input and update positions if necessary int keyState = getKeyStates(); if ((keyState & LEFT_PRESSED) != 0) { sprite.move(-1, 0); } else if ((keyState & RIGHT_PRESSED) != 0) { sprite.move(1, 0); } // Clear the background to white g.setColor(0xFFFFFF); g.fillRect(0,0,getWidth(), getHeight()); // Draw the Sprite sprite.paint(g); // Flush the off-screen buffer
33
34
Abstract class that represents a visual element in a game and provides basic attributes such as location, size and visibility
LayerManager For games that employ several layers the LayerManager simplifies game development by automating the rendering process. It allows the developer to set a view window that represents the users view of the game. The LayerManager automatically renders the games Layers to implement the desired view Maintains an ordered list to which Layers can be appended, inserted and removed. A Layer's index correlates to its z-order; the layer at index 0 is closest to the user while the Layer with the highest index is furthest away from the user. The indices are always contiguous; that is, if a Layer is removed, the indices of subsequent Layers will be adjusted to maintain continuity. append(Layer l) - Appends a Layer to this LayerManager. The Layer is appended to the list of existing Layers such that it has the highest index (i.e. it is furthest away from the user). The Layer is first removed from this LayerManager if it has already been added. insert(Layer l, int index) Inserts a new Layer in this LayerManager at the specified index. The Layer is first removed from this LayerManager if it has already been added. Throws an IndexOutOfBoundsException if the index is less than 0 or greater than the number of Layers already added to the this LayerManager remove(Layer l) Removes the specified Layer from this LayerManager. This method does nothing if the specified Layer is not added to the this LayerManager. Default width and height is set to Integer.MAX_VALUE and the default view window is at (0,0) Sprite
Basic animated layer that can display one of serveral graphical frames. The frames are all of equal size and are provided by a single Image object. In addition to animating the frames sequentially a custom sequence can also be set to animation the frames in an arbitary manner. The sprite class also provides various transformations (flip and rotation) and collision detection methods that simplify the implementation of a games logic. Each frame is assigned a unique index number. The frame located in the upper-left corner of the Image is assigned an index of 0. The remaining frames are then numbered consecutively in row-major order (indices are assigned across the first row, then the second row, and so on). The method getRawFrameCount() returns the total number of raw frames. If a Sprite has 4 frames, its default frame sequence is {0, 1, 2, 3} The developer must manually switch the current frame in the frame sequence. This may be accomplished by calling setFrame(int), prevFrame(), or nextFrame().
34
35
7 Different types of transforms can be applied to a Sprite (8 if you include TRANS_NONE). The reference pixel is the center point of all transforms. getX(), get() return the top left corner If an invalid value is in the frame sequence (ie lower than 0 or the number of frames) it throws an ArrayIndexOutOfBoundsException setImage() If the new frame set has fewer frames than the previous frame set, then: The current frame will be reset to entry 0, Any custom frame sequence will be discarded and the frame sequence will revert to the default frame sequence for the new frame set. boolean collidesWith(Image image, int x, int y, boolean pixelLevel) Checks for a collision between this Sprite and the specified Image with its upper left corner at the specified location. boolean collidesWith(Sprite s, boolean pixelLevel) Checks for a collision between this Sprite and the specified Sprite. boolean collidesWith(TiledLayer t, boolean pixelLevel) Checks for a collision between this Sprite and the specified TiledLayer.
TiledLayer Enables a developer to create large areas o graphical content without the resource usagage that a large image object would require. It is a comprised of a graid of caless, and each cell can display one of several tiles whose corresponding pixel data can be changed very rapidly. Very usefull for animating large groups of cells such as areas of water. createAnimatedTile() Creates a new animated tile and returns the index that refers to the new animated tile. It is initially associated with the specified tile index (either a static tile or 0). The indices for animated tiles are always negative. The first animated tile shall have the index -1, the second, -2, etc. Wherever possible animated tiles should be used instead of animating tile appearance fileCells() Fills a region cells with the specific tile. The cells may be filled with a static tile index, an animated tile index, or they may be left empty (index 0). public void fillCells(int col, int row, int numCols, int numRows, int tileIndex)= col - the column of top-left cell in the region row - the row of top-left cell in the region numCols - the number of columns in the region numRows - the number of rows in the region tileIndex - the Index of the tile to place in all cells in the specified region Throws: IndexOutOfBoundsException - if the rectangular region defined by the parameters extends beyond the bounds of the TiledLayer grid IllegalArgumentException - if numCols is less than zero IllegalArgumentException - if numRows is less than zero IndexOutOfBoundsException - if there is no tile with index tileIndex Wireless Messaging API WMA Classes all found under javax.wireless.messaging.*
35
36
Maximum SMS Message Length depends on the encoding and whether there are optional headers present. This Java API supports the use of port numbers to specify a Java application as the target The design of messaging functionality is similar to the datagram functionality that is used or the UDP in the GCF Permissions for WMA based on javax.microedition.io.Connector.<type> where type will be cbs, sms, http, socket etc.
Client Mode String url = "sms://+5550000:12345"; MessageConnection conn = (MessageConnection) Connector.open(ur); TextMessage msg = (TextMessage) conn.newMessage(MessageConnection.TEXT_MESSAGE); msg.setPayLoadText("Hello"); conn.send(msg); Server Mode String url = "sms://:12345"; MessageConnection conn = (MessageConnection) Connector.open(url); TextMessage message = (TextMessage) conn.receive(); String receivedText = message.getPayloadText(); MessageConnection Extends Connection from the GCF Two types of MessageConnection BINARY_MESSAGE, TEXT_MESSAGE numberOfSegments(Message msg) Returns the number of segments in the underlying protocol that would be needed for sending the specified Message. Note that this method does not actually send the message. It will only calculate the number of protocol segments needed for sending the message. A connection can be defined as server mode or client mode. An application can have a number of MessageConnection objects open simulataneously An IOException is thrown when any method (except close), which is declared to throw an IOException, is called on the MessageConnection after the connection has been closed. send() IllegalArgumentException - if the message is incomplete or contains invalid information. This exception is also thrown if the payload of the message exceeds the maximum length for the given messaging protocol. One specific case when the message is considered to contain invalid information is if the Message is not of the right type to be sent using this MessageConnection; the Message should be created using the newMessage() method of the same MessageConnection as will be used for sending it to ensure that it is of the right type. CBS does not take an address - its a broadcast! Applications can only accept CBS, not send them. If they try an IOException will be thrown Some port numbers are reserved for things like WAP services so you cant send them via SMS to them and if you a SecurityException will be thrown
36
37
MessageListener The MessageListener interface provides a mechanism for the application to be notified of incoming messages. When an incoming message arrives, the notifyIncomingMessage() method is called. The application MUST retrieve the message using the receive() method of the MessageConnection. If multiple messages arrive very closely together in time, the implementation has the option of calling this listener from multiple threads in parallel. Applications MUST be prepared to handle this and implement any necessary synchronization as part of the application code, while obeying the requirements set for the listener method. Message
This package is designed to work with Message objects that may contain different elements depending on the underlying messaging protocol. This is different from Datagrams that are assumed always to be just blocks of binary data. An adapter specification for a given messaging protocol may define further interfaces derived from the Message interfaces included in this generic specification. The wireless messaging protocols that are accessed via this API are typically of store-and-forward nature, unlike network layer datagrams. Thus, the messages will usually reach the recipient, even if the recipient is not connected at the time of sending the message. This may happen significantly later if the recipient is disconnected for a long time. Sending, and possibly also receiving, these wireless messages typically involves a financial cost to the end user that cannot be neglected. Therefore, applications should not send many messages unnecessarily. getTimestamp() Returns the timestamp indicating when this message has been sent. Note, cell broadcasts (cbd) do not contain any timestamps
TextMessage This is a subinterface of Message which contains methods to get and set the text payload. The setPayloadText method sets the value of the payload in the data container without any checking whether the value is valid in any way. Methods for manipulating the address portion of the message are inherited from Message. When text that is too large for the message is passed in no exception is thrown BinaryMessage This is a subinterface of Message which contains methods to get and set the binary data payload. The setPayloadData() method sets the value of the payload in the data container without any checking whether the value is valid in any way. Methods for manipulating the address portion of the message are inherited from Message. Message Payload Concatenation GSM Standard specifies two mechanisms for concatenation, implementation can use either
37
38
For received messages, implementation MUST accept messages with both mechanisms Implementations of the API must support at least 3 SMS protocol messages to be received and concatenated together Assume 16 bit reference number length when estimating how many SMS protocol messages it will take to send a given message Depends on the Optional Headers Encoding (GSM 7 bit, 8 bit binary, UCS-2alphabet 16 bit) and if the port number is present
Permissions Send an SMS javax.wireless.messaging.sms.send Receive a SMS javax.wireless.messaging.sms.receive Q1 Which of the following two are valid methods to open a record store? a) RecordStore.openRecordStore(String recordName, boolean create)
b) RecordStore.openRecordStore(String recordName, boolean create, int authmode) c) RecordStore.openRecordStore(String recordName, boolean create, int authmode, boolean writable) d) RecordStore.openRecordStore(String recordName, String vendorName, String suitName, int authmode)
a) AUTHMODE_PRIVATE means only the single MIDlet that created the RecordStore can access the RecordStore.
b) AUTHMODE_PRIVATE means only the MIDlet suite that created the RecordStore can access the RecordStore. c) AUTHMODE_ANY means any other MIDlet from any MIDlet suite can access and modify the RecordStore. d) The owning MIDlet suite can always access the RecordStore and can set the authentication mode.
38
39
c) It returns the amount of memory available to both invoking RecordStore and the implementation to store any RecordStore relevant data.
d) It returns the amount of memory available to implementation to store Meta data of invoking RecordStore.
Q4 Consider the following snippet of code with the assumption that the code is in the right context
try{
RecordStore rs = RecordStore.openRecordStore("HData", true); String first = "firstRecord"; rs.addRecord(first.getBytes(), 0, first.length()); RecordStore rs1 = RecordStore.openRecordStore("HData", true); String second = "secondRecord"; rs1.addRecord(second.getBytes(),0, second.length()); System.out.println(new String(rs.getRecord(2))); }catch(RecordStoreException r){ System.out.println(r); } .
What will be the output? a) The code will throw an exception at run time because the openRecordStore is called twice. Study Guide From www.ePlanetLabs.com
39
40
b) The code will throw InvalidRecordIDException at run time. c) Will compile and run without any problem. d) the code will ignore the second request of openRecordStore().
Q5 What will be the outcome of the following code snippet assuming that the code is with right context?
try{
RecordStore rs = RecordStore.openRecordStore ("HData", true); String first = "firstRecord"; rs.addRecord(first.getBytes(), 0, first.length()); RecordEnumeration enum = rs.enumerateRecords(null, null, false); byte[] a = enum.getRecord(); byte[] b = enum.getRecord();
}catch(RecordStoreException r){ }
a) Will throw an exception at second call of getRecord() b) The values of both arrays a and b will be same. c) The value of byte array b will be null d) compile time error
40
41
b) When a MIDlet suit is removed from the platform associated record stores will not be removed. c) The first record of a given Record Store will have the recordID equals to 0. d) The names of the Record Stores are case sensitive.
Q7 Assume all the objects are valid and no layer is appended to LayerManager
layerManager.append(aLayer); layerManager.append(bLayer); layerManager.append(cLayer); layerManager.append(dLayer); Layer temp = layerManager.remove(bLayer); layerManager.append(eLayer); What is the index of eLayer?
a) 2 b) 3 c) 4 d) 5
Q8 What is true about collision rectangle of Sprite a) Its default value is exactly the size of the image. b) This rectangle may used for collision detection. c) Could be set programmatically. d) Could be of smaller then the image but not of the larger size.
41
42
Q10 What is true about TiledLayer? a) Animated tiles are not supported in TileLayer. b) Its a rectangular grid of cells typically used for Games background. c) A tile index of 0 indicates that the cell is empty. d) -ve index values are not allowed
Q11 Suppose we have an image image.png with height 150 and width 50 pixel what will be outcome ofthe following code snippet assuming the image.png is available and other relevant classes are available Sprite sprite = new Sprite(image.png, 100,50); a) the program will fail at compile time. b) the program will fail at runtime with IllegalArgumentException. c) the program will run successfully with only one frame of size 100 by 50. d) the program will run successfully with three frames of 50 by 50.
42
43
a) If condition is false, a collision is detected only if opaque pixels collide. b) Both Sprites must be visible in order for a collision to be detected. c) Any transforms applied to the Sprites are automatically accounted for. d) Both spriteA and spriteB should be of equal size.
a) This class is been added in MIDP 2.0. b) Frame sequence of sprite class starts from 1. c) The developer must programatically switch the current frame in the frame sequence of Sprite in order to get animation affect. d) ReferencePixel is a constant pixel at 0,0 coordinates of a given Sprite.
Q14 Which of the followings are legal index sequence of a Sprite consisting of four frames 0,1,2 and 3 a) 3,2,1,-1, b) 4, 3, 2, 1 c) 0,0,2,3,1,0,3,2,1,3 d) 2,2,2,2
Q15 The minimum no of application threads must be supported by JTWI 1.0 compliant devices : a) 5
43
44
b) 10 c) Unlimited. d) Support of application threads not mandatory. Q16 What is true for MIDP 2.0 compliant implementations?
a) MUST support MIDP 1.0 and MIDP 2.0 MIDlets and MIDlet Suites. b) MUST implement the OTA User Initiated Provisioning specification. c) MUST incorporate one or more supported protocols for push. d) MUST provide support for accessing HTTP 1.1 servers. e) MAY provide support for secure HTTP connections.
a) MUST support PNG image transparency. b) MUST include support for additional image formats. c) MUST support Tone Generation in the media package. d) MUST implement the mechanisms needed to support Untrusted MIDlet Suites. e) SHOULD NOT allow copies to be made of any MIDlet suite unless the device implements a copy protection mechanism.
Q18 Which of the following two controls must be available to MIDP 2.0 compliant devices?
a) VolumeControl b) ToneControl
44
45
a) True b) False
Q20 How you can delete a single MIDlet from a MIDlet suit installed on the device?
a) By calling the method MIDlet.destroy(this) b) By calling the method MIDlet.destroy(this.getClassName()) c) By calling the method MIDlet.destroy(System.getProperty(midlet.name.this)) d) Single midlet cant be deleted if installed with other MIDlets in a MIDlet suite .
1 public class MyMIDlet extends MIDlet{ 2 public MyMIDlet(boolean condition){ 3} 4 public void startApp(){ 5} 6 7 public void pauseApp(){ Study Guide From www.ePlanetLabs.com
45
46
a) Compile and run successfully b) Compile time error at line 10 c) Compile time error at line 2 d) Runtime Exception
46
47
Q25 Which of the following Displayable direct or indirect sub-classes are Abstract? select two
Q26 Which of the following are valid command types of Command class? a) BACK b) CANCEL c) CLOSE d) FORWARD e) GO Q27 Which of the following are true about Ticker?
47
48
. mForm.setCommandListener (aListener); mForm.setCommandListener (bListener); .. What is true a) Only aListener is associated with mForm. b) Only bListener is associated with mForm. c) Compile time error cant add two listeners of same type to a form. d) Both listener will receive the command events.
Q29 What will be the output of the following code? Assuming all the objects are valid and the layout is not yet set
StringItem sItem = new StringItem (Hello, We are in the middle); sItem.setLayout(Item.LAYOUT_DEFAULT | Item.LAYOUT_LEFT); form.append(sItem); a) Compile time error cant use default layout with left layout. b) Runtime exception IlligalArgumentException. c) Will compile and run successfully with StringItem at the default position defined by implementation. d) Will compile and run successfully with StringItem at left position.
48
49
Q30 Which of the followings are true for the default state of a newly created Items: a) The Item is not contained within ("owned by") any container. b) There are no Commands present. c) The default Command is null. d) The ItemCommandListener is null. e) The layout directive value is LAYOUT_LEFT.
Q31 What will be the behaviour of the TextField if we pass the string through its constructor with more than the allowed maximum limit?
a) Runtime Exception. b) Depends on implementation. c) The String will get trimmed from the last. d) The TextField will increase its size .
a) No support for Daemon threads is available. b) Support for thread groups are available. c) Support for finalize() method has been added. d) Thread Class doesnt support notify() and notifyAll() methods.
49
50
Q34 Which of the following classes has been added to CLDC1.1? a) Reference b) StringBuffer c) Integer d) WeakReference Q35 What are the requirements of CLDC sandbox model?
a) Programmer cant modify the class loading mechanism. b) Programmer can wirte native code. c) Native code can be invoked using Runtime.exec() method d) Classes must be verified either by the CLDC preverifier and runtime verifier but not by both.
Q36 What is true about security consideration in CLDC? a) Programmer can use the native libraries supplied by device manufacturer as the part of J2ME. b) Programmer cant override profile specific or manufacturer specific packages. c) Programmer can modify the lookup order if the application is trusted. d) Java application can load classes from its own jar and other downloaded jars.
50
51
Q37 Which of the following API need explicit confirmation from user for untrusted MIDlets?
Q38 What does the user permission type blanket means? a) User will be asked every time for permission. b) Once granted user will not be consulted or asked for permission for the life of the midlet. c) User will be asked once in the start every time the application will run. d) User will not be asked for all other types of permission as well. Q39 Which of the following statements are true about Application Management software?
a) It is responsible to provide facilities for installing and browsing midlets. b) APS use HTTP for transferring JAD and JAR files. c) To ask for permissions is not the responsibility of AMS. d) An untrusted midlet suit can update a trusted midlet. Q40 Which of the followings are true?
a) Amidlet suit can contain more than one midlet. b) main() method is the starting point of midlets. c) Midlet suit must contain at least one class which extends MIDlet. d) No-args constructor is not necessary for MIDlet class.
51
52
Q41 Which of followings are the correct ways to find the version of midp specification?
a) System.getProperty (microedition.profiles); b) System.getAppProperty (MicroEdition-Profiles); c) Midlet.getAppProperty (MicroEdition-profile); d) Midlet.getProperty(microedition.profiles); Q42 Which of the following are true for MIDlet class method platformRequest(String URL)
a) The method will through IllegalArgumentException for epmty string for URL. b) This is a non-blocking method call. c) We can initiate voice calls using URL string tel://msisdn-number>. d) Currently there is no permission mechanism for platformRequest method. Q43 Which of the following method can be used for the following scenarioThe application wants to call a Task myTask after 30 seconds and at an average rate of 2 tasks per minute. And if one delayed by a second next should start a second earlier. a) scheduleAtFixedRate(myTask, 30, 30) b) scheduleAtFixedRate( myTask, new Date(System.currentTimeMillis()), 60) c) schedule(myTask, 30, 30) b) schedule( myTask, new Date(System.currentTimeMillis()), 60)
Q44 Which of the following Error classes are part of CLDC 1.1 a) java.lang.NoClassDefFoundError b) java.lang.VirtualMemoryError c) java.lang.SecurityError d) java.lang.OutofMemoryError Q45 Consider the following line for Midlet permission MIDlet-Permissions-Opt: javax.microedition.io.Connector.http What will happen if the permission refused?
a) Midlet will not be installed. b) Midlet will install but with limited functionality.
52
53
Q46 Consider the following line of Permission MIDlet-Permission-Opt: javax.microedition.io.Connector.socket and the device doesnt support the socket connections what will happen?
a) The application will install normally as it is device fault. b) The application will not be installed. c) The SecurityException will be thrown. d) The ConnectionNotFoundException will be thrown.
Q47 Which of the following are legal values for allowed senders in push registry permission?
a) ???.???.???.??? b) 127.?3??.*.* c) 127.*.*.*? d) 127.40.70.333 Q48 Consider the following JAD file MIDlet-1: HelloUI, HelloUI.png, HelloUI MIDlet-Jar-Size: 7876 MIDlet-Jar-URL: HelloUI.jar MIDlet-Name: HelloUI MIDlet-Vendor: SmartSolutions MIDlet-Version: 1.0 MicroEdition-Configuration: CLDC-1.0 MicroEdition-Profile: MIDP-1.0 MIDlet-Push-1: datagram://:4000, HelloUI, * MIDlet-Push-2: socket://:4001, HelloUI, * MIDlet-Permissions: javax.microedition.io.PushRegistry And suppose that port 4000 is already reserved but not port 4001. What will happen when the user will try to installed the application a) Application will install with the warning that 4001 is already in use. b) Application will install but the push mechanism of the application will not run. c) Application will not install because of port 4001 is already in use. d) Aapplication will not install because more than one push permissions are not allowed per MIDlet.
53
54
a) The named MIDlet HelloUI must be registered in the descriptor file or the jar file manifest with a MIDlet-<n> record. T b) Midlet HelloUI will be executed at every 10000 milliseconds from current time. F c) if a wakeup time is already registered, the previous value will be returned, otherwise 1 will be returned. F d) the method can throw ClassNotFoundException or ConnectionNotFoundException but not SecurityException. F
Q50 Which of the following is the correct signature of registerConnection method of PushRegistry? a) public static void registerConnection(String connection, String midlet, String filter) throws ClassNotFoundException,IOException
b) public void registerConnection(String connection, String midlet, String filter) throws ClassNotFoundException,IOException c) public static void registerConnections(String[] connection, String[] midlet, String[] filter) throws ClassNotFoundException,IOException d ) public static void registerConnection(String connection, String midlet, String filter) throws IOException
a) The PushRegistry supports more than one outstanding wake up timer per MIDlet in the current suite.
54
55
b) The application descriptor file must include information about static connections that are needed by the MIDlet suite. c) If all the static Push declarations in the application descriptor can not be fulfilled during the installation, then the MIDlet suite must not be installed. d) A call from a MIDlet to Connector.open() on a connection reserved for its suite will always succeed, assuming the suite does not already have the connection open.
Q52 which of the following methods are available in PushRegistry class regardless of method parameters a) getFileter() b) registerAlarm() c) unregisterAlarm() d) registerConnection() e) unregisterConnection() f) listAllConnections()
Q53 Which of the following interfaces or classes directly or indirectly implements StreamConnection Interface? a) InputConnection b) ContentConnection c) SecureConnection d) StreamConectionNotifier
Q54 Which of the followings Strings are correct url format for Connection classes a) "http://www.j2mecertification.com: 8080;mock=1" b) "www.bbc.co.uk" c) "comm.: com0;baudrate=1920" d) "socket:localhost:5500"
55
56
a) The return type would be SocketConnection. b) This connection can be used for sending and receiving data. c) Calling getLocalPort() after casing con object to appropriate type will return -1. d) Calling getAddress() after casting con object to appropriate type will return the local host address.
Q56 Consider the following code snippet String ports = System.getProperty("microedition.commports"); If the code is called in right context within a MIDlet which of the following is true?
a) Name of the first available comm port. b) Name of the all available ports separated by , comma. c) The output is device dependent. d) Devices cant expose more than one port.
Q57 What could cause IOException in a networking class? a) If the target URL could not be found. b) I/O error while opening or closing a connection. c) If the connection closed twice. d) When a connection has been closed, access to any of its methods except close(). Q58 What is true about networking classes? a) StreamConnectionNotifiers method acceptAndOpen() is a blocking method. b) Using close method twice on same connection will result in Exception. c) Using the setBuadeRate(int rate) of CommComunication guaranties the buadeRate be set to the given value. d) If the host portion is not specified in a datagram URL, then the connection will be treated as server connection. Q59 A JTWI 1.0 complaint device MUST be capable of : a) If implement the MMAPI, 1.1 must be the minimum version. b) The minmum configuration is CLDC 1.1. c) WMA support is not mandatory. d) 256 KB must be the minimum volatile memory for java runtime. Study Guide From www.ePlanetLabs.com
56
57
a) Messaging protocol SMS guaranty the order or sequence of the messages. b) WMA-based SMS implementations must support at least three SMS-protocol segments for a single message. c) Message types are not restricted to available types in WMA 1.1. d) We can send messages with Message object value set to null.
Q61 Which of the following are legal message types (WMA 1.1) to be passed in MessageConnection interfaces method newMessage(String type) a) MessageConnection.TEXT b) MesssageConnection.Binary c) MessageConnection.IMAGE d) text e) BINARY
Q62 Which of the following methods are of MessageConnection interface: a) newMessage( String type, String address, Message msg) b) sendMessage(Message msg) c) send(Message msg) d) numberOfSegments(Message msg)
Q63 What will be the output of the following code snippet assuming that it is in right context and all the variables are available also the port 5555 is available ? try { ... ... MessageConnection cbs = (MessageConnection) Connector.open(cbs://:5555); TextMessage tmsg = (TextMessage)mc.newMessage (MessageConnection.TEXT_MESSAGE); tmsg.setAddress(url);
57
58
a) compile time error at setPayloadText() method line. b) runtime NullPointerException at setPayloadText() method. c) runtime IOException at setPayloadText() method. d) runtime IOExceptoin while trying to send the message at send() method of MessageConnection interface .
Q64 What is true about TextMessages a) The maximum length of a single segment TextMessage is 152 bytes. b) If a character present in the message is not of GSM-7 bit encoding the whole message will be treated as UCS-2 16 bit encoding. c) The maximum no of characters in single segment UCS-2 text encoding is 70. d) A text message with 160 non UCS-2 characters will always be sent exactly in 1 segment. Q65 What will be the output of following code snippet assuming the code is right context and that content mymusic.mp3 is available 1 ... 2 try { 3 Player player = Manager.createPlayer 4 ("http://www.j2mecertification.com/mymusic.mp3); 5 player.start(); 6 player.setLoopCount(-1); 7 catch(MediaException e) { 8} 9 ...
a) IllegalArgumentException at line 6. b) IllegalStateException at line 6. c) Will run successfully and the player will loop the content indefinitely. d) Direct call to start method is illegal, runtime Exception at line 5.
58
59
Q66 Which of the following are legal ways to create a player from Manager in MMAPI 1.1? a) createPlayer( DataSource source, String type) b) createPlayer( InputStream stream, String type) c) createPlayer( String locator, String type) d) createPlayer( String locator)
Q67 What is true about DataSource? a) Its start() method starts playing the content. b) It implements the controllable interface. c) DataSource is fully functional concrete class. d) For a valid DataSource getStreams() method will always return more than one streams. Q68 Which of the following control interfaces are available in MMAPI 1.0? a) RateControl b) SpeedControl c) StopTimeControl d) FramePositioningControl e) FrameSpeedControl f) GUIControl
Q69 What is true about MMAPI a) Devices implementing MMAPI must implement all the features of API. b) Devices implementing MMAPI must support at least one media type and one control. c) The constant ToneControl.C4 defines the middle C with value 60. d) MIDP 2.0 doesnt support creation of player via DataSource Answers Q1
AT BF
59
60
Q3 CT
Q4 AF BF CT DF
Since more than one midlet can acess record store ... Couldn't be a problem
Q5 DT The method to obtain records from RecordEnumeration is nextRecord() not getRecord() and if we replace it with nextRecord() then the right answer would be runtime exception InvalidRecordIDException (because no more records available) the best practice is to call hasNextElement() before making call to nextRecord. It is J2SE and you are SCJP.
Q6 AT BF
60
61
RecordID starts with 1 not with 0. Do you know layers of game starts from ?
Q7 BT
Layer indexing starts with 0. Also The indices are always contiguous; that is, if a Layer is removed, the indices of subsequent Layers will be adjusted to maintain continuity. We can count no of layers present from zero.
Q8 AT BT CT DF Could be smaller or larger in case of larger size the pixels outside the image will be considered transparent. Q9 A F What is the use of x and y when both calling and 's' have their own collision rectangles BT C F We need the position where to put the image for finding the collision D T We have the details
If both items are visible there is no need for x and y otherwise we need positioning details
Q10 A F It is the most advantageous feature of tiled layer to have animated tiles. BT C T That also means the index of TiledLayer must start from 1 D F -ve indices are used for animated tiles
61
62
Q11
A F Option 'a' cannt be the answer as this is not compile time issue. C and D the height and width of frames should be integer multiple to image which is not the case here B T Since the arguments are incorrect i.e. IllegalArgumentException
Q12 A F The reverse is true B T Yes we cann't do the collision virtually C T Should be because its visibility would have changed so the collision rectangels(s) D F And of same color... of course not
Q13 A T The whole package of game APIs is added in MIDP2.0. B F No it starts from zero but in TiledLayer the 0 is reserve for blank cells. C T The whole point is to give the control to developer otherwise animated gifs would have been enough. D F We can move the reference pixel by calling definReferencePixel() method of Sprite class that way we can have additional benifits more from transformations.
Q14 AF BF CT DT There is no concept of any extra frame(s) other than the available W e can repeat frames as many times as we want or can use the same frame any no of times but typically we use different frames.
62
63
Q16 A T offcourse B T not all devices support other means like cable, infrared or bluetooth so one should be comman in all i.e OTA over the air provisioning C F it si suggestion that they should support for push D T either directly or by gateway services. E F https support is necessary in MIDP2.0
Q17 AT B F It is allowed to support more but not required. CT D T Thats how you practice with untrusted midlets. E T Sounds True.
Q18 AT BT CF DF EF Remember that it is not mandatory for a MIDP2.0 compliant device to implement MMAPI and the only guarantied controls for MIDP 2.0 devices is Volume and Tone controls.
Q19 AT
63
64
Q21 DT The MIDlet class must have a no-arg constructor. It is not a java language rule i.e no compile time error but AMS will thruogh IllegalAccessException while trying to run the MIDlet
Q22 AT In the part before '/' typically we describe type of file like text,audio or image that way we can eliminate options c and d vnd is basically for vendor and java is not a vendor name but sun is so eliminate option B. Q23
BT CT All the other classes are available in CLDC 1.1 but not new to it.
64
65
Q26 AT BT C F We do have STOP and EXIT but not close D F These command types are not for mp3 players. EF
Q27 A T Possible by calling setTicker() on displayable typically screens and passing the same Ticker object's reference B F The methods are setTicker() and getTicker(). Remember we can't add more than one Ticker at a time so we cant add it. C T The Sole purpose of Ticker e.g. headlines DF
Q28 BT setCommandListener() removes the previous command Listener if associated with the calling Displayable and sets the new one
Q29 A F can't be compile time error in all cases BF CF DT LAYOUT_DEFAULT has value of zero and has no effect when combined with others.
65
66
Q31 BT Althoug C looks more accurate but here is the text from specs "An IllegalArgumentException is thrown if the length of the initial contents string exceeds maxSize. However, the implementation may assign a maximum size smaller than the application had requested. If this occurs, and if the length of the contents exceeds the newly assigned maximum size, the contents are truncated from the end in order to fit, and no exception is thrown. " Q32 AT BF C F There si no support for finalize atall D F Imagine threads without them
Q34 AT BF CF
66
67
Q35 AT BF CF DF There is no JNI the device can provide libraries which inturn use th native code but not the developer. There is no runtime.exec() Should be verified by both
Q36 AT BT CF DF
Q37 AT BF CF DT All the Classes which potentially can use the network resources needs permissions.
Q38 BT
Q39 AT BT CF DF
67
68
Q40 AT BF CT DF
Q41 AT BF CT DF
Q43 AT
Q44 AT BT CF DT
68
69
Q46 DT
Q47 A, C and D
Q49
AT B F Not every C F Zero will be returned who can remember that? D F Can throw all three Exceptions. Three out of six methods of PushRegistry class retreive info getMidlet(), getFilter(), listConnections() all other mthods which disturb registry can throw Security Exception
Q50 AT Eliminate option B as all methods of PushRegistry class are static. There is always a possibility of wrong string for midlet class name resulting in MIDlet not found Exception.
69
70
Q51 AF BT CT DT
Q52 AT BT CF DT ET FF
Q55 AT BT CF DF
70
71
Q56 BT
Q57 A F That is not an IO problem B T Must be C F Closing the connection twice has no effect D T When it is closed no IO is possible.
Q58 AT BF CF DT
Q60 A F Store and forward mechanism doesnt guarranty this at all BT C T Currently there are two types text and binary but not limited to this. D F But payload text could be null.
71
72
Q62 A F why pass message object when creating one or if cloning then why other details are given. B F MessageConnection sends messages only so the method is send() not sendMessage(...) CT DT
Q63 DT P ayload could be set to null value. IOException has nothing to do at setPayload...(...) method. CBS connection types cant send messages.
Q64 A F Could be 160 if port is not defined B T The encoding scheme will be changed to UCS-2 16 bit encoding. CT D T Not in the case if port no is present
Q66 A F DataSource can itself tell you what type it got by calling getContentType() so no need for passing type info
72
73
Q68 AT BF CT DT EF FT
Q69 AF B T If not why they are implementing CT D T DataSource class is not available in MIDP2.0. Q: A: How do I install J2ME application into my phone? There are two ways to install our J2ME applications on your phone. 1) You can use our WAP site. You should set up your phone's WAP Settings according to the settings you get from your mobile carrier. Then you need to visit our WAP site : wap.wildec.com. Go to Games section, select a game, select your phone model and your phone will prompt you to download the game to your phone. Choose Yes, and the game will appear on your phone. 2) You can use a cable or IR connection if your phone allows this. Download the game files you want to install on your phone (JAD & JAR files). Connect your phone to your computer using either cable or IR connection. Send the downloaded JAD & JAR files to your phone using software provided by your phone manufacturer. Q: How do I install your PalmOS software? A: To install any of our software you first have to download it from our site. The archive you download contains two prc files: MIDP.prc and GameName.prc; to play the game you have to install both on your palm. You do not have to install MIDP.prc if you already have it installed but you need to have it to run any of our games.We recommend that
73
74
site.
Q: I run the PalmOS game and it produces "Cannot find KVM on this device" error A: This error means that you do not have MIDP installed on your PDA. Read the Installation notes above and install MIDP. MIDP is a new technological solution from Sun Microsystems designed for mobile devices programming. If you have trouble downloading MIDP, you can download it here: Symbian OS (Nokia 9210). for Palm OS, for Q: How do I register your PalmOS software? A: To register the game you first have to download it and run it. If you have trouble doing this, read installation and running notes above. Every time you run the unregistered game, the registration screen is shown. It includes basic registration notes and a KEY1, which you have to write down. Then you have to buy the game in our products section.When you buy the game, you are given a Personal Identification Number(PIN). After this you have to login by the PIN you get (or by Username and Password if you already have a personal account) and enter KEY1. Upon doing this, you will be given KEY2, that you have to enter in the registration form of the game on your PALM(handheld). If KEY2 is correct, the game will be registered. If the registration fails, check if the KEY1 currently generated by the game corresponds to KEY1 you entered on the site. 1. General questions 1. What is JavaME (formerly called Java 2 Micro Edition)? To quote Sun's website: A highly optimized Java runtime environment, JavaME TM technology specifically addresses the vast consumer space, which covers the range of extremely tiny commodities such as smart cards or a pager all the way up to the set-top box, an appliance almost as powerful as a computer. Basically, JavaME is an umbrella term that refers to the collection of virtual machines, APIs and related elements that provide Java to handheld and embedded computing devices. Table of Contents 2. What is a configuration? A configuration defines a virtual machine and the minimum APIs that must be present. In defining the virtual machine, the configuration specifies the minimum amount of memory that must be present as well as the minimum processor type and speed. Table of Contents 3. What is a profile?
74
75
A profile refers to the APIs for a specific domain. For example, the MIDP (Mobile Information Device Profile, description below ) defines the APIs that are made available for pervasive computing devices such as mobile phones, wireless PDAs and similar devices. Table of Contents 4. Can I use more than one profile at a time? Yes, provided that the virtual machine and device supports the functionality for the additonal profile. For example, OEMs can provide their own profiles in addition to the MIDP to allow MIDlets to access device-specific features of their device, such as the information contained in the SIM card on a phone. However, if such a profile were provide by an OEM such as Nokia, this profile wouldn't be portable to other devices, such as Motorola. Another point to bring up is that, in order to use an optional API, it must already be present on the targeted device. For example, the MobileMedia API defines APIs for accessing such elements as the digital camera on a device. Developers can use these APIs to write camera-aware applications. However, merely writing an application against these APIs and loading the application on a device will not give you access to the camera. The APIs for the optional profile must be supported by the virtual machine itself as well. If support is not built into the virtual machine, then those optional features will not be available. Table of Contents 5. What devices are currently JavaME-enabled? A list of devices can be found here . Table of Contents 6. Where does PersonalJava fit into JavaME? PersonalJava was a previous implementation of Java for pervasive devices, based on Java 1.1. It is unrelated to JavaME. However, the Personal profile will fill the vacancy left by PersonalJava. Table of Contents 7. I've ported the KVM/CVM to [some platform]. Can I distribute/sell my port? NOTE: The FAQ maintainers are not lawyers and this answer should not be construed as legal advice. With this understood, you may read the
75
76
When you downloaded the reference implementation, you agreed to the Sun Community Source License, which forbids you from distributing the source code for the reference implementation to anybody not also a licensee (section d, part i). You can only distribute binaries for evaluation purposes and cannot sell the ported VM (section d, part ii). Table of Contents 8. What are the minimum fields that must be present in a MIDlet suite's manifest? The manifest must contain at least the following fields: MIDlet-Name * MIDlet-Version * MIDlet-Vendor * MIDlet-# (where # is the MIDlet number, one for each MIDlet) MicroEdition-Profile MicroEdition-Configuration
*
Table of Contents 9. What are the minimum fields that must be present in a JAD file? A Java Application Descriptor must contain, at the minimum, the following fields: MIDlet-Name * MIDlet-Version * MIDlet-Vendor * MIDlet-Jar-URL MIDlet-Jar-Size
*
Table of Contents 10. I've heard the term J2ME, but not JavaME. What's JavaME? At JavaOne 2005, Sun announced a new naming convention for Java technologies . With this change, the micro-edition technologies were renamed to be Java ME, dropping the "2" in the name to avoid confusing customers or building an expectation for some future J3ME.
76
77
2. Developer Community 1. Are there any JavaME-specific newsgroups, discussion forums or mailing lists? There are several, infact. NAME URL http://archives.java.sun.com/cldcfeedback.html http://archives.java.sun.com/kvminterest.html http://archives.java.sun.com/j2me-cdcinterest.html http://www.forum.nokia.com http://www.howardforums.com
comp.lang.java.programmer comp.lang.java.programmer CLDC-FEEDBACK KVM-INTEREST J2ME-CDC-INTEREST Forum Nokia Howard Forums Table of Contents 2. Where can I find archives for [some] mailing list on JavaME-related topics? The following is an incomplete list of archives where past messages are stored for some JavaME-related mailing lists: KVM-INTEREST mailing list archives CLDC-FEEDBACK mailing list archives J2ME-CDC-INTEREST mailing list archives iDEN Developer's SDKLIST Table of Contents 3. The Connected Limited Device Configuration 1. What are the minimum requirements for the CLDC? For a device to support the CLDC, it must have at minimum: 16-/32-bit RISC/CISC processor 160k of memory (128k of which is for the VM and APIs) some form of network connectivity Table of Contents 2. I want/need to use native methods. How can I do this?
77
78
The simple answer is: you can't . JNI is not available within the resource constrained KVM. Some people will then bring up the KNI as an alternative/solution. This is, however, an incorrect answer and not a solution. The KNI is a Sunspecific porting layer, introduced into the reference implementation for the MIDP 2.0 and the CLDC 1.0.4. The purpose of this layer is to make porting these and future reference implementations to new platforms, and cannot be used as a means of linking native code at runtime. Table of Contents 3. Does the CLDC support floating point operations? The CLDC 1.0 specification does not support floating point math. However, support for floating point math was introduced with the CLDC 1.1 specification . If you're working with a device that is built on the CLDC 1.0 specification and you need floating point math capabilities, you can download and use the MathFP library. Table of Contents 4. The Mobile Information Device Profile 1. What is the MIDP? The MIDP defines a set of APIs for mobile devices, such as cell phones and low-end PDAs (higher-end PDAs will better benefit from more powerful profiles such as the Personal Profile ). Table of Contents 2. What is the current version of the MIDP specification? There are currently two versions of the MIDP specification: version 1.0 and version 2.0 (reference to as MIDP-NG or MIDP Next Generation). The 1.0 specification was the first profile released under the JavaME umbrella in 2000. The 2.0 specification was released in 2002 and addressed many of the shortcomings of the original specification. The 2.0 specification is also backwards compatible with 1.0. Table of Contents 3. What does the acronym LCDUI stand for? There are several sources of conflicting information on this subject. This link claims that it stands for "Limited Connected Device UI", while this link claims that it stands for "Liquid Crystal Display UI", and JavaME
78
79
Enterprise Development claims it stands for "Least Common Denominator UI". So, I went to the source (or, more exactly, I asked a question in the KVMINTEREST mailing list and received a response) and asked for the definition. What I was told was: ...I emailed Jim [Jim Van Peursem] (MIDP 2.0 lead). He looked through his notes. He says that in Mark V. [Mark VandenBrink] (MIDP 1.0 lead) and Roger R's [Roger Riggs] MIDP 1.0 book, Mark calls it "Limited Connected Device" UI. I trust this as the ultimate source for the information. Table of Contents 4. Is MIDP available for the Palm OS? In June, 2003, Palm announced an alliance with IBM to release IBM's WebSphere Micro Environment on their Tungsten line of handheld devices. You can also download MIDP4Palm , which was the first MIDP platform released for the PalmOS. Read this for a note on the previously announced PDA Profile . Table of Contents 5. I don't have Java installed in /usr/local/java/jdkx.xx/x86/bin! How do I build the MIDP reference implementation? There are several macros used by the makefile to determine where elements exist on the system. One, ALT_BOOTDIR , tells the makefile where Java is installed. By redefining this macro in the commandline to point to where Java's installed on your system, the build should complete (barring any other differences between your system and the expections of the makefile). Assuming your JDK is installed in /usr/lib/j2se/1.3 (the default for Debian with JDK 1.3 installed), you would use the following commandline: make ALT_BOOTDIR=/usr/lib/j2se/1.3
Table of Contents 6. Can I access the address book on my PDA from my MIDlet?
79
80
Personal Information Manager APIs - Enables the developer to access the native personal information management data that resides on the device, including the address book, calendar, and to-do lists. FileConnection APIs - Gives the developer access to file systems on the device, such as external memory cards. These APIs will be implemented by the VM vendor on other JavaME profiles, such as the MIDP and Personal (and Personal Basis) Profile , and will enhance the CLDC . Table of Contents 6. The Connected Device Configuration 1. What are the minimum requirements for the CDC? For a device to support the CDC, it must have at minimum: 32-bit RISC/CISC processor 2M RAM some form of network connectivity Table of Contents 7. The Foundation Profile 1. Why can't I find any UI classes in the Foundation profile? The Foundation profile, when used by itself, is intended for embedded and headless devices; i.e., devices that have no user interface, such as routers and gateway devices.
80
81
There are other profiles, such as the Personal Profile , that are intended to run on top of the Foundation profile. Table of Contents 8. The Personal (and Personal Basis) Profile 1. What is the Personal Profile? The Personal Profile is the JavaME replacement for PersonalJava . Table of Contents 2. What is the difference between the Personal Profile and the Personal Basis Profile? The Personal Basis Profile ( JSR-129 )defines a minimal set of user interface APIs. The Personal Profile ( JSR-62 ) builds on the APIs from the Personal Basis Profile. The Personal Profile is intended to be the next step in the migration path from PersonalJava and, as such, needs to support the full feature set of PersonalJava. The Personal Basis Profile is intended to address devices less capable than those targeted by the Personal Profile, providing a scaled down API set. Table of Contents 3. I'm not using RedHat Linux. How do I build the reference implementation? The build environment requires a few macros be defined at the commandline to tell it the locations for your JDK, the shell to use and the location for specific GNU tools. The following table lists the macros and the values necessary to perform the build on a Debian Linux system: MACRO NAME JDK_HOME SHELL CVM_GNU_TOOLS_PATH Table of Contents 9. Device Communications 1. What is the Generic Connection Framework? DESCRIPTION The root of your JDK installation. The path to the shell used for executing commands. The location for the standard GNU toolset. VALUE ON DEBIAN /usr/lib/j2se/1.3 /bin/bash /usr/bin
81
82
The Generic Connection Framework is the paradigm used for creating javax.microedition.io.Connection objects that support different protocols. A URI defining the protocol and remote end-point for the network connection is passed to the javax.microedition.io.Connector class via one of the open() methods and a javax.microedition.io.Connection -type object is returned, ready to connect to the end-point. Table of Contents 2. I want to create a TCP/UDP/other connection with a server. Can I do this with MIDP? Yes, if the device supports such a connection. The only required protocol is HTTP, but the OEM can provide other protocols as well. Table of Contents 3. How do I create a server socket with the GCF? You don't. With the the GCF , there is no support for server sockets. However, you can instead create a javax.microedition.io.StreamConnectionNotifier instance and invoke its acceptAndOpen() API. The following snippet demonstrates how to do this: public void waitForConnection() { // change the port number to be whatever is appropriate for your application StreamConnectionNotifier server = (StreamConnectionNotifier )Connector.open("serversocket://:10000"); StreamConnection conn = server.acceptAndOpen(); // do something useful with the new connection }
Table of Contents 4. Can I dial a telephone number from my MIDlet? The MIDP 1.0 specification does not provide an API for doing this. The OEM, though, is free to add any additional profiles they wish to the mix. The MIDP 2.0 specification includes platformRequest(String) method in the javax.microedition.midlet.MIDlet class. The telephone number can be passed in the form tel:<number> as defined in RFC 2806 . Table of Contents
82
83
The MIDP 2.0 specification includes platformRequest(String) which OEMs can use to provide this information if they so choose. Table of Contents 6. When I'm using HTTP connections, I get the message 'java.io.IOException: exceeded the configured maximum number of connections'. Why? The answer involves the java.io.InputStream and java.io.OutputStream objects related to the javax.microedition.io.HttpConnection object in use. If you're using either input or output streams, it is necessary to close them after you've finished with the connection. Otherwise, the underlying implementation is most likely keeping the javax.microedition.io.Connection object open. Simply call close() on all related streams and it should solve the problem. Also, be sure you're not using persistent connections if you're going to multiple servers during an application's sessions. Table of Contents 7. Can I determine the IP address for my device with my MIDlet? No. Not all MIDP devices use IP-based networking, and the MIDP expert group didn't include an API for determining the address for those devices that do. Table of Contents 8. How do I setup persistent HTTP connections with a server? In HTTP 1.1, persistent connections are the default behavior required by the specification. So, no special coding is required to suggest to the device that the underlying connection should be maintained between HTTP requests. See the next question for information on how to turn off persistent connections. Table of Contents
83
84
Table of Contents 10. Then can I re-use the same HttpConnection object more than once? No, you cannot use the same object more than once. The HttpConnection object represents exactly ONE round-trip connection with the server and, as such, cannot be used for transmitting data more than one. The connection object can exist in one of three states: 1) Setup , 2) Connected and 3) Closed and, when it moves to a new state, it can not return to a previous state. So, when data is sent to the server, the connection has moved from the setup state into the connected state. In the connected state, the connection can only receive data from the server and cannot send any more data to the server. When the incoming data has been received and the InputStream objects closed (or the connection itself is closed, but I'm assuming you were diligent and closed your input and output streams first <g>), the connection moves into the closed state and no further data can be read from the connection. Any attempt to use methods from a previous state on a connection object will result in an IOException being thrown. If what you're trying to accomplish is persistent connections, please see this frequently asked question . Table of Contents 11. Can I send SMS/MMS messages from my MIDlet? You can send SMS messages, provided the device hosting your MIDlet supports JSR-120 , the Wireless Messaging API 1.0. If your device supports version 2.0 of this specification, then you will be able to send MMS messages as well. Table of Contents Study Guide From www.ePlanetLabs.com
84
85
Not with MIDP 1.0. According to the specification, javax.microedition.lcdui.Form only has APIs for appending elements using an instance of java.lang.String (which is a shortcut to creating an instance of javax.microedition.lcdui.StringItem , javax.microedition.lcdui.Image (which is a shortcut to creating an instance of javax.microedition.lcdui.ImageItem or javax.microedition.lcdui.Item . There's no way to create a new subclass of javax.microedition.lcdui.Item since the single abstract method, paint() , has package (default) protection. It is also against the licensing agreement (per section e, subsection iv) to create a new subclass in the javax.* package hierarchy. Finally, even if the licensing agreement were ignored, most VMs will ignore any class in the java[x].* hierarchy. In MIDP 2.0, the class javax.microedition.lcdui.CustomItem was introduced. Subclassing this class will allow you to create new elements that can be added to forms. Table of Contents 2. I can create an Image from an array of bytes. Can I do the reverse and get an array of bytes from an Image? Unfortunately, no. There's no API available for extracting anything more than the image's width, height, an instance of javax.microedition.lcdui.Graphics and mutability. With the MIDP 2.0 you can get the raw bytes from an instance of javax.microedition.lcdui.Image through the getRGB() API. Table of Contents 3. How do I get notification of high level key events from within a Form, TextArea or List within the MIDP? The high level user interface APIs in javax.microedition.lcdui do not give you access to the low level key events. These events are only available to classes which extend javax.microedition.lcdui.Canvas . There is an alternative, though it may not meet the requirements above. The javax.microedition.lcdui.ItemStateListener interface defines a contract for objects that will be notified of state changes within a javax.microedition.lcdui.Form object. However, there is no specific set of conditions under which these notifications are sent; i.e., it is up to the device/VM vendor to decide when and if notifications will be sent. So, notifications will vary greatly between different devices and VM implementations.
85
86
When you create an instance of Command you can only specify a label, a command type and a priority. The MIDP implementation uses the type and priority of the commands to be displayed to determine how the commands will be presented to the user. It will also make a best effort to map keys to the appropriate button for that device; i.e., if the device normally displays OK buttons on the right side, then it will attempt to present your command of type Command.OK on the right side. Also, not all MIDs have softkeys. For example, the RIM Blackberry displays the Command s as menu items. On such a device, there's no concept of a softkey. Instead, on such devices, the implementation will use the priority of the Command s as well as their type in order to group and sort them prior to displaying them to the user. So, be sure that each command within each group has a unique priority. Table of Contents 6. When I run my MIDlet in the emulator, my image loads fine. But, when I run on a device, the image isn't displayed. Verify that your image file is present in your MIDlet suite's JAR file and that it's JAR entry is the same as your code expects; i.e., if you're using Image.createImage("/foo.png") , then there must be a JAR entry named /foo.png or else the MIDP implementation will throw an IOException . Remember, also, that filenames are case sensitive and that you have to use the full entry name for the image. Table of Contents 11. Security 1. Can I load a class from outside of my MIDlet suite? No. The MIDlet is limited to only loading classes from within it's suite. This prevents hackers from loading dangerous classes. It also prevents a
86
87
device from using precious bandwidth for loading classes over the air or via low-bandwidth network connections. Table of Contents 12. Runtime Activities 1. How do I read a file from my JAR? To read a file from your MIDlet suite's JAR file, use the java.lang.class.getResourceAsStream() API. Table of Contents 2. How can I tell my device to automatically load my MIDlet when [something] happens? With MIDP 1.0, there's no way to automatically launch a MIDlet either at device startup or upon reception of some data. With MIDP 2.0, there's the concept of the push registry , which allows a MIDlet to register itself for network and timer initiated MIDlet activation. Take a look at the javax.microedition.io.PushRegistry class Javadocs for more details on using the push registry. Table of Contents 3. What happens to my threads when my MIDlet is suspended? On most devices, the only thread that is suspended is the main application thread for the MIDlet. Any other thread that was started by the MIDlet will most likely (but not always) continue running. Table of Contents 4. What system properties are available to determine the device type at runtime? The following system properties are available, as of MIDP 2.0, to help determine the type of device on which the MIDlet suite is running: microedition.platform microedition.encoding Identifies the device type or host platform, or returns null if the value is undefined The default character encoding.
microedition.configuration The configuration this device has implemented. microedition.profiles The profiles this device has implemented.
87
88
A list of properties is also defined here . Table of Contents 5. I would like to get the physical location of the handset. Is this possible? To get the handset's location, you would have to have a handset that supports the Location API for JavaME . With this API you can get the location for the handset at runtime. Unless the OEM has implemented this API on the handset, you will not be able to determine the physical location of the device. Table of Contents 13. Developing Software For JavaME 1. What are the minimum tools I need to begin development? Minimally, you will need: JDK version 1.3 or higher the reference implementation for the targeted profile the reference implementation for the targeted configuration the ANT build utility (click here for an example build.xml file) The reference implementations provide the APIs for compiling the application. They also provide the preverifier, which performs the initial verification of the created byte code. This saves the device from having to perform initial verification, which can be resource expensive. It also inserts extra information into the byte code which is needed by the VM, but which is ignored by the J2SE VM, so compiled classes can be shared between JavaME and J2SE. This all said, I would now recommend instead that you download Sun's Wireless Toolkit 2.x or later , Eclipse 3.x or later and EclipseME . This gives the most complete environment for JavaME development for the price. Table of Contents 2. What would a minimal ANT build.xml file look like? I've removed the ANT example from the FAQ. It is recommended that, rather than using this example for most tasks, you use the Antenna suite of ANT tasks. With Antenna, all of the more awkward tasks, such as preverification, obfuscation and the launching of emulators, have already
88
89
3. Where can I find the various reference implementations for J2ME configurations and profiles? Download the CLDC reference implementations here . Download the MIDP reference implementations here . Download the CDC reference implementations here . Download the Foundation Profile reference implementations here . Download the Personal Basis Profile reference implementations here . Download the Personal Profile reference implementations here . Download the RMI Optional Packages reference implentations here . Table of Contents 4. I installed the Sun Wireless Toolkit. Why can't I run the sample MIDlets? This answer assumes you're running in a Unix/Linux environment, and installed using the root account. When the toolkit was installed, it created the directory structure with root as owner (assuming you didn't install the product as yourself in your home directory, or one to which you have write access). The file access permissions for the tree are root.[ staff on my system] rwxr-sr-x . As you can tell from this, only members of the owning group can read the directories where the toolkit was installed. In addition, only root can write to the directory tree. So, unless you are running the toolkit as root (not a very good practice at all) you will not be able to run any of the samples for the toolkit until you make some changes to the directory structure. The best thing to do is to go into the JavaMEwtk/apps directory and change the permissions to allow the owning group to write to the directories as well. From the installation directory, execute the command: find apps -type d -exec chmod 775 {} \;
This will descend into each directory and change the permissions to allow members of the owning group to write to the directories, but will not allow anybody to change the files in the directories. This way, the source code will still be read-only, but users will be able to compile and execute them. Table of Contents 5. What would the MIDP equivalent of Hello World! look like? 6. import javax.microedition.lcdui.Command; import Study Guide From www.ePlanetLabs.com
89
90
javax.microedition.midlet.MIDlet; public class HelloWorld extends MIDlet implements CommandListener { public HelloWorld() { } 13. public void startApp() { Form form = new Form("Hello world!"); 14. form.addCommand(new Command("Exit",Command.EXIT,1)); 15. form.setCommandListener(this); 16. Display.getDisplay(this).setCurrent(form); } public void 17. pauseApp() { } public void destroyApp(boolean unconditional) { } 18. public void commandAction(Command c,Displayable d) { 19. if(c.getCommandType() == Command.EXIT) { notifyDestroyed(); } } } 12.
Table of Contents 20. When I attempt to obfuscate my MIDlet suite, Retroguard dies. Why? It is a problem with the way obfuscation works in Java. Most obfuscators will begin altering the bytecode by traversing the methods and classes used by your MIDlet, and then examines the methods and classes used by those methods, to obfuscate the code. When RetroGuard hits a native method (for example, one within the MIDP API that's implemented in the KVM rather than in Java code), it cannot handle the situation and returns an error. If you're using an archive or subdirectory in your classpath for RetroGuard that contains a working version of the MIDP API, RetroGuard is hitting one or more of the above-mentioned native code references. It is this that is causing the failure during obfuscation. The solution is to use the file emptyapi.zip , which comes with the Wireless Toolkit. This archive provides all of the public interfaces used by the MID Profile without any of the underlying implementation code or references to any native methods.
90
91
21. When I preverify my classes, I get the message "Class loading error: Bad major version number". Why? My guess is that you're using JDK version 1.4 or higher. The problem is that the byte code format generated by the 1.4 and later compiler is incompatible with earlier versions of the preverify executable that you're using. To fix the problem, upgrade your toolkit to the latest version and see if that fixes the problem. If you're using the latest tool, or if your tool vendor hasn't upgraded their tools, then you can use the following commandline: javac {whatever arguments you normally use} -target 1.1 {your more arguments}
This will cause the compiler to produce pre-1.4 byte code. If you're using J2SDK 5, then you'll want to add the following commandline argument instead: javac {whatever arguments you normally use} -source 1.2 -target 1.2
Table of Contents 22. How do I use JDWPI to debug a MIDlet running in the Wireless Toolkit's emulator? To access the emulator using sockets, start the emulator and include the following command line argument: -Xrunjdwp:transport=dt_socket,address=[the local port],server=y,suspend=y
replacing [the local port] with an available port number. Then, give the same port number to your debugger in order to connect to the emulator. To access the emulator using shared memory, start the emulator and, instead of specifying a port, specify the name of the shared memory page using the following command line argument: -Xrunjdwp:transport=dt_shmem,address=[the shared memory page],server=y,suspend=y
91
92
replacing [the shared memory page] with a unique memory pagename. Then give the same name to your debugger in order to access the shared memory. Table of Contents 23. How can I see debugging output from my Motorola iDEN phone? You need to connect your iDEN phone to a serial port on your computer using a data cable. Then, from a terminal application (set to 19200bps , issue the following command: AT+WS46=252;+WS45=0;+IAPPL=2;D
This will cause all output sent to System.out and System.err to be sent to the serial port and, finally, to your terminal application. Table of Contents 24. How do I add images and other resources to my project in the Wireless Toolkit? You copy these and any other files into the res (short for resources) directory beneath your application's directory. Within your code you would refer to them using "/res/[filename]". Table of Contents 14. Writing games using JavaME 1. Is there an editor to help me build the tiled layers for my game backgrounds? Yes, there are a few. For Windows, there is Tile Studio , World Creator and Mappy . Table of Contents 15. Provisioning A Device 1. How do I download my MIDlet suite onto my cell phone or wireless device? This depends on the device in question. There are two ways to put a MIDlet suite onto a device: Over-the-air (OTA) provisioning Provisioning via data cable
92
93
Over-the-air provisioning is when the application is downloaded from a web or portal site and installed onto the device. An overview of OTA provisioning can be found here . The basic flow is that the device retrieves the JAD file from a web or portal site and determines whether the MIDlet suite can install onto the device. If the suite is acceptable (i.e., it's new to the device, or it's the same or more recent version of an installed suite, and it's not too big [if there's a size restriction imposed by the carrier]) then the user is prompted if they want continue with the installation. If the user accepts, then the MIDlet suite is downloaded over the air and installed onto the device. Provisioning via a data cable is more direct in its approach. Software is provided by the OEM and is used to connect to the device normally via a serial or USB cable connected to the device, such as the cradle for a Palm or RIM, or the data cable for the Motorola phones. Using this software, the developer browses the local file system and selects the JAR and JAD files to install onto the device. The software then negotiates a connection with the device and uploads the MIDlet suite. Table of Contents 2. What are the MIME types for JAR and JAD files? In order for a web server to host a MIDlet suite, it has to be configured to send the property content types when sending a JAR and JAD file. To do so, the following MIME types must be configured for the server: FILE TYPE JAR JAD EXTENSION .jar .jad MIME TYPE application/java-archive text/vnd.sun.j2me.app-descriptor
To set these values in Apache2, add the following lines to your /etc/apache2/apache2.conf file: AddEncoding application/java-archive jar AddEncoding text/vnd.sun.j2me.app-descriptor jad Table of Contents 3. I want to test my MIDlet suite on my PC. What can I use? Well, the first answer is to use the emulators that ship with Sun's Wireless Toolkit , being sure to grab the appropriate version for the MIDP version you're targeting. Additionally, nearly every device manufacturer has their own emulators available for their devices. Motorola, Nokia and RIM even ship either
93
94
complete IDEs (such as Metrowerks Code Warrior and Nokia's Developer Suite for J2ME . For those looking for a Java-based solution, there is an (incomplete at this time) emulator written in Java called ME4SE that is an emulator built of Java 2 Standard Edition. It includes the ability to run the MIDlet within an applet in a user's web browser. There is also the MicroEmulator project which has built a MIDP emulator using the JDK 1.1. This would allow MIDlets to be demonstrated from within older browsers. Another tool that provides a pure Java environment for emulator a MID is the MPowerplayer SDK . To quote their website: The mpowerplayer software developer kit includes the mpowerplayer as a standalone application. It's a pure Java emulator implementing MIDP 2.0 and MMAPI, suitable for integration with your favorite environment and IDE. Table of Contents 4. I keep getting the message 'invalid file' when trying to install my MIDlet suite. What's the problem? There are several potential reasons for this problem showing up: You have missing or incorrectly formatted mandatory attributes in your JAD file. For Motorola phones, the limitations of the Mandatory attributes are: MIDlet-Name (max 32 character) MIDlet-Version MIDlet-Vendor (max 32 characters) MIDlet-JAR-URL (up to 256 characters) MIDlet-JAR-Size (must match JAR file size in bytes) The version of the MIDP and/or CLDC specified is not supported by the handset itself The attributes that are in both the JAD file and the MIDlet suite's manifest do not match. Be sure to check the files with a hex editor to ensure that one or the other does not have a special character in it One or more classes in the MIDlet suite refer to classes not found on the handset; for example, your MIDlet suite uses the Wireless Messaging APIs but those APIs aren't present on the handset. The value for the MIDlet-Data-Size (if used) exceeds maximum value for the handset (for Motorola V300,V400, V525, V500 and V600 this size is 512k, or 524,288 bytes). Table of Contents 16. Motorola-Specific Questions 1. How do I determine the firmware version of my iDEN phone?
94
95
Table of Contents 2. How do I determine the firmware version of my V-series phone? On my V400 (and my V300 at work) I press the following sequence: *#9999#
Although this same information is also available if you go to MENU -> Settings -> Phone Status -> Other Information , where each field is selectable individually. Table of Contents 3. How do I handle incoming phone calls from Java? On the i730 it's: Settings -> Phone Calls -> Java App Control -> [your MIDlet]
Table of Contents 4. How do I make my application permanent on a Motorola handset? ( NOTE: this is unverified by the FAQ maintainers) Enter the sequence "#*#159#*#" while in the Java menu on the phone. Then choose to mark the app as a "Permanent App". It will then not be uninstallable unless the user re-enters the key sequence and marks the app as uninstallable. Permissions for the app can also be set here as well. Table of Contents 5. I'm getting the error message 'Invalid File' when downloading to a Motorola handset. Why? There are serveral possibilities: Missing or incorrectly formatted mandatory JAD Attributes. The limitations of the Mandatory attributes are: MIDlet-Name (max 32 character), MIDlet-Version MIDlet-Vendor (max 32 characters),
95
96
MIDlet-JAR-URL (up to 256 characters), MIDlet-JAR-Size (must match JAR file size in bytes) MIDP or CLDC compile version of MIDlet is not supported by the handset. JAD attributes do not match the Manifest in the JAR - check these files using a Hex Editior in case there are some "special" characters inserted in either file which do not appear in your text editor. Class usage compiled into the MIDlet which does not exist in the handset. MIDlet-Data-Size (if used) exceeds maximum value (v300,v400, v525, v500, v600) = 512k (524288 bytes). Table of Contents 17. Nextel-Specific Questions 1. What do the letters NXTL stand for on the RIM Blackberry? As your device connects to the network, you'll notice in the upper-right corner of the display the letters "NXTL". These letters will individually cycle through upper- and lower-case states before finally (hopefully) becoming all upper-case, which signals a good connection to the network. But, why does it do this? What do these characters mean? I have the answer. After having spent some time on the phone with Nextel's technical support I was given this explanation for what each character stands for: N Cellular network connectivity X T L Walky-talky feature connectivity Packet data network connectivity Network registration
Table of Contents 18. Nokia-Specific Questions 1. How do I install software onto my Nokia handset? There are multiple ways to install sofware onto your Nokia handset: Over-the-air provisioning Via infrared connection or data cable Via Bluetooth To install over-the-air, you need to have a data plan with your wireless carrier. For Series 40 and 60 phones, go to the Services screen and
96
97
select Bookmarks Setup a link to your JAD file (or to the page hosting the JAD file) by selection Options and then New bookmark . Once it's setup, go back to the Bookmarks screen and click the call button (or click Options and then Go to ) to open the link. Then follow the prompts to download and install the MIDlet suite. To install via irDA, you need to have installed the appropriate PC Suite software from Nokia's website. Once installed, you can connect the handset to your PC and use the Application Installer too to deploy your application onto your handset. For Bluetooth installation, you need to first connect to your handset via Bluetooth. Then, simply push the JAR and JAD files onto the handset. You should receive a message stating that new files were received and you need only follow the prompts to complete the installation process. Table of Contents 2. How do I determine the firmware version of my Nokia phone? With your handset, press the following key sequence: #*0000*
Table of Contents 19. Samsung-Specific Questions 1. On my Samsung A600 my MIDlet never gets notified when the user presses the END key. The unverified answer (I've never talked with someone from Samsung) seems to be that, when the END key is pressed, the A600 does not notify the MIDlet but instead stops the VM itself from executing. So, rather than receiving a callback (either MIDlet.pauseApp() or Canvas.hideNotify() ) notification, your application will just stop . If you're writing a time-sensitive application, then you should probably put some sort of time checking into your code and attempt to detect such situations. In my case, I wrote a game that had the side-effect of the player losing on time when the END key was pressed. To solve the problem, I had my core loop grab the time when it started and the time when it was finished a single iteration. If that time value was greater than a normal update event, then it assumed the END key had been pressed and modified the game time accordingly. Table of Contents 20. Sony/Ericsson-Specific Questions
97
98
1. When my app tries to make a network connection it freezes until I press a button. If you're working in full-screen mode, what's happening is that the "Allow network access" prompt is being displayed but isn't visible since the app's controlling the entire screen. The workaround for this is to switch to nonfull screen mode prior to making the first network access attempt, then switch back to full screen mode afterward. Table of Contents 21. SprintPCS-Specific Questions 1. I have a JAR/JAD that works fine in the emulator. But, when I download to my Sprint phone, I get a 90x error, and invalid descriptor message and the JAR/JAD won't download. Why? The reason is going to be either of both of the following elements missing from your JAD file: either there's no MIDlet-Data-Size entry (which is necessary) or your MIDlet-Jar-URL does not have the full URL for the JAR file; i.e., it has filename.jar instead of http://yourwebsite/filename.jar . SprintPCS phones require the full URL for your MIDlet suite in order to download and install it to your handset. Table of Contents 2. I followed the sugggestions above for fixing my JAR/JAD, but I still can't download them to my phone. Why? This is related to Sprint's WAP gateway. It caches entries for increased performance, but at the expense of getting to updated material. Unfortunately, unless you have administrative rights to your webserver and can configure it to give content a short TTL, the only way you can get around this problem is to use a different name for the JAR and JAD everytime you upload a version to test. My (Darryl's) personal strategy when testing on sprint phones is to just use a rolling series of filenames; i.e., the first set I put on my server is a1.jar and a1.jad . After I've downloaded this, I delete the files and test. When I have to fix something and redeploy, I then deploy files a2.jar and a2.jad . When I've finally gotten the point where I'm satisfied with the code and ready to hand it over to QA and my product manager, then I finally deploy the files with the proper name. Table of Contents 3. What are the sound APIs for SprintPCS's VM?
98
99
To play sounds on a Sprint device, you need to first create an instance of the com.sprintpcs.media.Clip class, providing it with either the full path to the sound file in your JAR, or an array of bytes that comprise the sound file. Once you have a Clip , you then pass it to one of the com.sprintpcs.media.Player class's static methods: play(Clip clip,int repeat) , which plays the clip for the specified number of repetitions, but will end the clip should another one be played playBackground(Clip clip,int repeat) , which plays the clip for the specified number of repetitions. The sound will be paused when another sound is played, and will continue until that sound is completed. Table of Contents 22. T-Mobile-Specific Questions 1. Sometimes my T-Mobile handset has Internet connectivity and sometimes it doesn't. Why? This answer assumes two things: You're in an area where there is no T-Mobile coverage, and You're in an area where Cingular and at least one other carrier is present (such as North Carolina) If these assumptions are correct, then you need to manually select your network and choose Cingular . At least here in North Carolina, T-Mobile has no network coverage and so has a sharing agreement with Cingular. When I use a T-Mobile device, it sometimes selects AT&T rather than Cingular and will have no Internet connectivity. Simply switching it back to Cingular solves the problem, for me anyway. Table of Contents 23. Vodafone-Specific Questions 1. What does the MIDxlet-Resident JAD property represent? This indicates whether the MIDlet will remain active in memory (resident) in the background and able to process events. Table of Contents
99
100
What are the main differences between programming for a J2ME JVM, and programming for a J2SE JVM? Most obviously, the J2ME programmer has access only to a reduced range of basic API classes. There is no built-in API support for file handling, RMI, JDBC, JNDI, multimedia (but this is changing), or the AWT/Swing user interface models. Some of this functionality is replaced by J2ME-specific classes. For example, the Java package javax.microedition.io.lcdui provides a class library for a simple widget-based user interface. javax.microedition.io provides an implementation of the HTTP protocol. As well as these API and library differences, there are subtle differences in how J2ME JVMs work. For example, there is no JVM support for floating-point arithmetic (not even a double data type or Double class). Garbage collection is simplified - there are no soft references (yet), and finalize() methods are never called. Of course, the limited memory availability in a J2ME device will require much more careful use of instances than J2SE developers will be used to. It will be necessary to reuse objects rather than creating new ones, and the developer will have to help the garbage collector more explicitly by nulling unwanted object references. What is a `configuration'? In J2ME jargon, a `configuration' is a set of hardware functionality made available to applications through a JVM. J2ME defines two basic configurations: CDC and CLDC (see below). What are CDC and CLDC? Connected Device Configuration and Connected Limited Device Configuration. These are the specifications for the basic JVMs that a J2ME device must support. CDC is for bigger devices, such as set-top boxes and PDAs. These will typically have more memory and more robust network connectivity. CLDC is for smaller devices such as mobile phones and pagers. CDC and CLDC are not really APIs (although CLDC does specify a basic API), but run-time environments. The APIs are exposed to the developer through a set of `profiles' (see below). In practice, there appears to be much more interest in CLDC, as most J2ME developers are working on mobile phone and low-end PDA applications. CDC implementations are available for upmarket PDAs like Compaq's iPAQ range. What is a profile? `Profile' is J2ME jargon for the API exposed by the J2ME implementation. The situation is complicated by the fact that CLDC also defines an API, but in reality this API cannot be separated from the API exposed by the profile. There are four basic profiles defined by the J2ME specifications, of which only one - MIDP - is of much interest at the moment. The MIDP profile is based on the CLDC JVM. The others, Foundation, Basis, and Personal, are based on CDC. What is MIDP? MIDP (Mobile Information Device Profile) is the API exposed by small mobile devices with graphical displays. MIDP is supported by most mobile phones, pagers, and low-end PDAs. It is not by any means the only J2ME profile (API set) defined, but it is the most widely supported.
100
101
The user interface has been extended to support such things as pop-up windows, and active strings and images Greater control of screen layout, including the ability to set constraints on the sizes of items on a form Custom form items: applications are no longer limited to the basic set of form items, but can implement new types in Java Support for simple audio playback (MIDP2.0 devices must support a small subset of the features in the MMAPI. Vendors can support MMAPI as well, of course) Sprite API to simplify screen management in graphical applications, particularly games Support for HTTPS, raw TCP/IP and UDP, and serial ports Application settings now provide for a configuration by which MIDlets can be activated by external events. This is is called the `push architecture' in the documentation. A MIDP2.0 device must be able to retrieve MIDlet suites by over-the-air (OTA) access. In fact, most MIDP1.0 devices support OTA provisioning, but it was not compulsory. Support for `signed MIDlets'. Like a Java applet, a MIDlet can now be signed, that is have appended to it an encrypted hash of its contents. The signature provides a robust method for determining the identity of the distributor of the MIDlet. The operator of the device can use that knowledge to choose to allow the MIDlet greater access to the device's runtime environment.
Must a MIDP2.0 device support the multimedia API and wireless messaging API? These are defined as optional packages, and therefore need not be implemented by MIDP2.0 devices. However, MIDP2.0 devices must support basic wave audio, as defined in the MIDP2.0 specification. What is LCDUI? The user interface model user by MIDP. It is not clear what `LCD' actually stands for. The balance of opinion is that the letters `LCD' has the same meaning that they do in CLDC, but it isn't clear why they aren't in the same order. I prefer the other widely-used interpretation: lowest common denominator. Try it, and you'll see why. In the MIDP documentation, you'll see reference to the `high-level user interface' and the `low-level user interface'. I don't really like these terms, because they sort of give the impression that the high-level user interface is an abstraction of the low-level user interface, or that one is based on the other. However, this isn't true at all in MIDP. The `high-level user interface' is the programming model based on forms and widgets, while the low-level user interface is the Canvas class and the graphics primitives. I prefer the terms `formbased' and `canvas-based'.
101
102
What are the Foundation, Basis, and Personal profiles? These are APIs based on the CDC JVM. The Foundation profile (API) provides a basic Java class library, but no graphical user interface. The Basis profile provides, in addition, a lightweight graphical user interface based on the `xlet' model. The Personal profile is the most complex, and supports the full AWT graphical programming model. Programming graphical applications for the Personal profile is therefore much like programming ordinary workstation applications in AWT. The Personal profile also supports Java applets. All three CDC profiles can be extended to support RMI and JDBC, but vendors are not required to support them. How does JavaCard fit into all this? JavaCard is a JVM optimised for running on embedded systems like security cards. It has its own specification and programming model, and is not really connected with CDC, CLDC, or MIDP. How does PersonalJava fit into all this? PersonalJava was an early attempt at a JVM for small devices. It is not related to the current J2ME effort. However, the Personal Profile on the CDC platform provides a similar level of functionality to PersonalJava. Is MIDP a layer on top of CLDC? Sort of. However, it is wrong to assume that MIDP is, or even can be, implemented using only the CLDC API. To the developer, the MIDP and CLDC APIs exist side-by-side. For example, the MIDP API allows screen management, but there is no CLDC support for screens, even at the pixel level. MIDP2.0 offers support for networking operations such as raw TCP/IP sockets, but CLDC only offers HTTP support. It would be strange if a higher-level abstraction offered lower-level functionality than the thing it abstracts. In practice, developers working with CLDC devices are actually working with MIDP, and there are no other standards-based user interface models for CLDC. As a result, it is not really productive to try to distinguish the MIDP layer from the CLDC layer. What is the K Virtual Machine? K (kilobyte) Virtual Machine (KVM) is a reference implementation of a CLDC JVM from Sun Microsystems. KVM forms the basis for a number of commercial J2ME devices, and also of the MIDP emulator in Sun's Wireless Toolkit product. However, it is a popular misconception that KVM and CLDC are synonymous. KVM is a piece of code, CLDC is a specification. CLDC implementation exist that are not based on KVM. What versions exist of MIDP and CLDC? At the time of writing, there were two versions of CLDC: 1.0 and 1.1. Version 1.1 is a significant enhancement over 1.0, and includes more sophisticated memory management and floating point support. The latest version of MIDP is 2.0 (also called `MIDP-NG') which is, again, a significant enhancement over 1.0. Unfortunately, MIDP2.0 support does not require CLDC1.1, only CLDC1.0. So MIDP2.0 applications cannot take advantage of the new CLDC1.1 features, or at least cannot do so in a portable way. This situation is likely to persist, because the hardware requirements for supporting MIDP2.0 are actually somewhat less than for supporting CLDC1.1. As a result, there are MIDP2.0 mobile phones that could probably not support CLDC1.1. At the time of writing (Spring 1993) there are relatively few MIDP2.0 devices on the market, and most developers are still targeting MIDP1.0. Study Guide From www.ePlanetLabs.com
102
103
What are `optional packages'? These are extensions to the basic profiles defined by specification, but not mandatory. Some devices support them, most don't. They are in various states of development.
The MMAPI (multimedia API) profile provides support for streaming video and audio The WMA (wireless messaging API) provides support for, er.., wireless message (SMS, etc) The PDA profile provides access to the standard application data manipulated by a PDA device, such as calendars and address books. The FCA (File Access API) profile provides facilities to read and write files on devices that have the concept of a file
Are J2SE and J2ME JVMs bytecode compatible? In theory, all J2SE JVMs are bytecode compatible. For example, a class compiled with one vendor's compiler tools should behave identically on another vendors JVM. However, classes compiled with a J2SE compiler will not necessarily work on a CLDC JVM. The reason for this is that CLDC is necessarily less sophisticated than a full-scale JVM, and cannot do the iterative bytecode verification that a proper JVM has to do. As a result, CLDC developers typically compile Java using an ordinary Java compiler, then convert the standard bytecode it into CLDC-compatible bytecode using one of the various tools that are available (see below). How large can a CLDC/MIDP application be? There are main limits to consider: the size of the application's bytecode, and the memory it uses at run time. The latter may comprise both volatile (stack, heap) elements and non-volatile (record store) elements, and is harder to estimate. The bytecode limit depends on two things: the limit imposed by the hardware device, which will almost always be somewhat less than its total non-volatile memory capacity, and the limit imposed by the provisioning mechanism. If you are downloading the application from a PC by a cable or infra-red link, this limit is likely to be unproblematic. For over-the-air provisioning (see below) you may run into limits imposed by the network operators. Ultimately, an OTA download will be implemented by an HTTP response, and it simplifies the network operator's equipment if it can be assumed that every HTTP response will fit into a single data packet on whatever the underlying carrier is. I believe (but I am happy to be corrected) that the worst culprits limit the download size to 8 kB. That's right, eight kilobytes. In practice, most MIDP devices, even mobile phones, can cope with applications whose bytecode sizes are about 32 kB without too much stress, but you may have to upload them using a cable. But for maximum portability, bear in mind that the MIDP specification only requires that a device provide a total of 8 kB of non-volatile storage. At runtime, the application will consume stack and heap space. These will usually be drawn from the device's volatile memory, which need by no larger than 32 kB to comply with the specification. 128 kB is more usual. An application may also use non-volatile storage, or which only 8 kB need be provided (in addition to that required by CLDC itself). Again, 128 kB is more usual. How can I reduce the memory footprint of my application? First consider how much effort you want to expend on this. Modern MIDP/CLDC devices have far more memory than the original specifications envisaged. If you must reduce
103
104
Don't create separate classes to act as event listeners - use a class that already exists. For example, use your MIDlet's main class as the event listener for form events, rather than creating a separate class. Remember that even the most trivial, anonymous inner class requires 200 bytes of bytecode, plus some state information for each instance. Where possible, use ordinary named classes, not inner classes. It is conventional in AWT programming to use inner classes to act as event listeners. The state information required to support an instance of an inner class can be surprisingly extensive, because of the way that inner classes are managed by the JVM. Don't subclass the built-in classes unless you have to. For example, you could create a subclass of Form to serve as your applications main user interface, but you could also use an ordinary Form object, and drive it from the MIDlet's main class. Subclassing Form is more `OO', but imposes adds a few hundred bytes to the footprint. Every class you subclass has the same effect. Don't subclass your own classes unless you have to. The flatter your class hierarchy, the few the classes; the fewer the classes, the smaller the bytecode. Don't put your classes into packages. J2ME applications are self-contained, so there is no prospect for name clashes between applications. The packages names have to be stored in the bytecode, on every occasion that a class is defined or referenced. A better solution than de-packaging all your code is to use a software tool to do it. Bytecode obfuscators do this as part of their normal operation. Remember that array initialisations translate into lots of repeated bytecode operations. So initializing an array of month names like this: String[] months = {"January", "February"... generates a surprising amount of bytecode. If you have very large arrays of strings or numbers, it generates less bytecode to define it in a long, delimited String, and split it into individual values in a loop. This may seem mad, but it's true.
If you have to support multiple locales, plan on distributing different versions of the application for different locales, rather than supporting multiple locales in the same application. There's no point providing a load of French and Japanese text if the user wants to see only Italian. If an application creates a Java instance, and knows that it is no longer required, it should re-use if with different data, or set it to null. Re-use is the preferred option, where this is practicable, but setting to null will help the garbage collector determine which objects are out of scope.
What Java version does a J2ME device support? When developers ask this question, they are usually concerned with the range of API support available. However, as has been explained, J2ME presents a very limited API, which does not correspond to any of the standard Sun JVMs. As a result, the correct
104
105
answer to this question may be misleading. Strictly speaking, J2ME devices have to support the same language syntax and semantics as Sun JDK 1.3, with the exceptions described above - no floating point support, limited garbage collection, etc. However, developers should not assume that any of the standard JDK 1.3 classes are available, but should instead refer o the API documentation for the configuration and profile they are targeting. J2ME development procedures and tools How do I compile Java source code for a MIDP application? The usual method is as follows:
Compile using an ordinary Java compiler Convert the classes to CLDC format Create a manifest file containing configuration information Package the classes and manifest into a JAR file, including any other required files such as images and sounds
The JAR file can then be deployed to the device, or run on an emulator (see below). When compiling the source code, it is helpful to tell the compiler not to compile against the standard J2SE class library, because most of it doesn't exist in CLDC. Instead, the compiler should refer only to CLDC and MIDP classes. You should be able to get JAR files of these classes from vendors of mobile devices, or use the archives included with Sun's Wireless Toolkit. With the Sun JDK, specify the classpath like this: javac -bootclasspath [path_to_CLDC_jar]:[path_to_MIDP_jar] -g:none ... The switch -g:none tells the compiler not to include any debugging information. This is important with mobile applications, because there is often a limit to the size of the application that can be transferred to the device. After compiling the source code to .class files, the next step is to convert the bytecode in the .class files to CLDC format. This is not a trivial job. The CLDC JVM assumes that each method in each class that has any kind of looping or branching operation in it is supplied with a `stack map', which is essentially a table of all the possible flows of execution through the method. With a standard JVM, this analysis of flow is carried out by the bytecode verifier as an iterative process when each class is loaded. Since a CLDC JVM cannot be guaranteed to have the CPU resources to undertake this task, or at least undertake it in a reasonable time, the information must be inserted into the bytecode before deployment. This process is called preverification. Sun's Wireless Toolkit includes a preverifier, but there are other preverifier implementations in the works (see below for why). After preverification, the modified classes are archived along with a manifest file, ready for deployment. The manifest contains information about the MIDlet classes included in the JAR, and the versions of MIDP and CLDC the application expects. For maximum portability, the developer should provide, in addition to the JAR file, a `JAD' file. This is simply a text file containing the same information as the manifest in the JAR.
105
106
How do I deploy a MIDP application? This varies from device to device. Vendors generally provide PC software to upload MIDP applications to their devices, either by cable or infra-red link, and it may also be possible to download from a Web server. With WAP phones and the like, it may be possible to download the application through data connection. In J2ME jargon, this is called over-the-air (OTA) provisioning. Some devices expect to be able to download a JAD file before retrieving the JAR file itself, so if you are providing MIDP application from a WAP site, you should link to JAD files, not JAR files. The reason for this is that data connection speeds from mobile phones are not terribly fast, and the phone should not have to go to the trouble of downloading a large JAR file, only to find out that it can't support the application because it expects the wrong MIDP version. What does the Wireless Toolkit do? Sun's wireless toolkit (WTK) automates the development steps described above compilation, preverification, and packaging. It provides a nice graphical user interface for doing this as a one-click operation. It also includes a MIDP emulator for testing applications. The emulator is configurable to the extend that you can change the keypad layout and screen size. This is very useful if you are targeting a particular device or range of devices. How is developing for an emulator different from developing for a hardware device? The emulator supplied with the WTK is a fairly realistic simulation of a MIDP device, down to the telephone-style keypad and display. However, the emulator does run on a real JVM, and may not have the memory constraints of a real hardware device. It may also allow Java operation that would not work at all on a hardware device, such as floating-point arithmetic. One notable omission in the WTK emulator is the ability to simulate the pausing of a MIDlet. When a MIDlet is loaded, it remains in the active state (see below) until it is terminated. As a result, it is difficult to test that your startApp() and pauseApp() methods are properly complementary to each other. The developer should therefore take particular care to code the resource allocation and deallocation strategy properly. Why is Sun's WTK only officially supported on Windows? Because the preverifier tool it includes was originally developed for Windows (see below), and has only recently been ported to Unix. What is wrong with the WTK's preverifier? There is nothing wrong with it in so far as it does the job. The problem is that it was written in C, for the Microsoft Windows platform. It has since been ported to Solaris and Linux, but Sun does not support these new versions (yet). Problems with porting the preverifier limit the platforms on which the WTK will run. What is clearly required is a preverifier written in Java, so that the whole J2ME development process can be platform neutral. There are a number of open-source and commercial projects underway to develop such support. What is the file emptyapi.zip that is supplied with the WTK? It is an archive containing all the same classes and methods as the real MIDP/CLDC APIs, but all empty. This is provided as a workaround for a limitation in the RetroGuard bytecode obfuscator. It appears that RetroGuard gets hung up when any class is defined Study Guide From www.ePlanetLabs.com
106
107
What other J2ME tools are available? Modern versions of the Ant build tool integrate the Sun preverifier, at least on platforms that support it. This makes it straightforward to use Ant to automate the development of J2ME applications. The SunONE Studio IDE now has complete IDE support for J2ME development, including compilation, preverification, emulation, and source-level debugging. I understand that there is a J2ME-specific version of JBuilder as well, although I've not used it. Most mobile phone vendors provide their own J2ME development tools and emulators. MIDP/CLDC programming What is a MIDlet? A MIDlet is a Java class that forms the interface between the application and the operating system in a MIDP device. The MIDP platform provides a basic, do-nothing MIDlet class javax.microedition.midlet.MIDlet. Application developers extend this class, overriding the appropriate base-class methods. A J2ME application must include at least one MIDlet, in addition to any supporting classes the application needs. All are packaged into a JAR file for distribution. What is a the `Hello world' of MIDP? As far as I know, the following is the simplest MIDP application that can display a message on a graphical display. import javax.microedition.lcdui.*; import javax.microedition.midlet.*; public class HelloWorld extends MIDlet { public void startApp() { Display d = Display.getDisplay(this); Form f = new Form ("Hello World"); d.setCurrent(f); } public void destroyApp(boolean force) { } public void pauseApp() { } } You could also implement `Hello world' by creating a custom Canvas class and drawing the text using graphics primitives. What is a MIDlet `suite'? A group of MIDlets distributed in a single JAR file. The significance of a `suite' is that MIDlets in the same suite have greater ability to share external resources (e.g., nonvolatile data) than separate MIDlets.
107
108
What is the MIDlet lifecycle? A MIDlet is either in the active state or the paused state. When it is first loaded by the MIDP runtime environment, it will be in the paused state. The runtime will generally call the method startApp() to signal that the MIDlet should now activate itself. Whenever the application is idle, the runtime can, in principle, put the MIDlet back into the paused state. When it is paused, the application will not receive user interface events. On a mobile phone, for example, the runtime may pause a MIDlet if an incoming telephone call is detected. The runtime will call pauseApp() to indicate that it has done this. The developer should use startApp() and pauseApp to allocate and release resources that the application needs whilst it is running. When the operator is finished with the MIDlet, the runtime will destroy it. Before it does this, it calls the method destroyApp() method. The MIDlet must deallocate resources here as it does when it enters the paused state. However, this deallocation should not be done carelessly, as a MIDlet can be destroyed when it is in the paused state, as well as the active state. In the MIDP documents, `destroyed' is described as being one of the states that the MIDlet may be in. This terminology raises a philosophical problem: if something is destroyed, it no longer exists; how can something that doesn't exist have a state? Apart from the philosophical issue, `destroyed' is not really a state, because the MIDlet cannot leave the destroyed state and enter any other state. How can a MIDlet terminate itself? It calls its own notifyDestroyed() method. The runtime then cleans up the MIDlet. Note that the runtime does not call destroyApp() when the application terminates itself, only when the runtime terminates it. As a result, the application typically calls its own destroyApp() method before calling notifyDestroyed(). How can a MIDlet put itself into the paused state when it is active? It calls its own notifyPaused() method. As an application can always pause itself (it does not require the permission of the MIDP runtime to do this), it must deallocate any allocated resources before pausing. The runtime will not call pauseApp(). How can a MIDlet put itself into the active state when it is paused? The simple answer is that it calls its own resumeRequest() method. However, this raises the question: how does the MIDlet get to run any code when it is in the paused state? If it is paused, one would imagine that it does not have the ability to run the resumeRequest() method. However, an application in the paused state is not forbidden to run any code; it just doesn't get user interface events. If the application has spawned another thread, for example, that thread may continue to run even when the application is paused. More commonly, an application may set an asynchronous timer to wake itself up after a certain length of time. A request to resume is exactly that: a request. The runtime need not honour that request. Contrast this with the ability of the MIDlet to pause or terminate itself - no permission is required to do these things. As a result, a MIDlet should not reallocate its resources before or after calling resumeRequest(). Instead, it should wait for the runtime to call startApp(). How does the MIDP user interface model compare to AWT? Conceptually it is very similar. Each user interface widget is an instance of a class. Some widgets can contain other widgets, so complex displays can be built (within the constraints of the screen size). Some widgets generate events, which can be handled by
108
109
the application. The display manager is responsible for placing widgets, not the application. However, MIDP is much simpler than AWT, and immeasurably simpler than Swing. There is no explicit menu support (where would the menu go?), nor can the developer (until recently) create entirely new user interface widgets. There is no windowing: although one screen can be raised on top of another, the top screen obscures the bottom one completely. Is the MIDP user interface model confusing and inconsistent? Seen from the context of AWT or Swing, the MIDP user interface model certainly appears to lack internal consistency, and not comply with even the mist rudimentary objected-oriented design principles. Here some examples... Consider the difference between the TextField class and the TextBox class. Both are areas of text, editable by the operator. Both look and behave much the same. The TextField is intended to be embedded within a form, along with other user interface elements, while the TextBox occupies the whole display in its own right. Both have similar, but not identical, methods for manipulating and retrieving the contents. However, despite their similarity these two objects do not extend a common base class, nor implement a common interface. Compare this with the List and ChoiceGroup classes. A List is a list-selection user interface element that occupies the whole display (as a TextBox does), while ChoiceGroup is a similar element intended to be embedded in a form (like TextField). This time the two classes do implement a common interface. There appears to be no logical explanation for the differences between these two different pairs of classes. It is also not obvious why there needs to be a distinction between TextBox and TextField in the first place. If there were no TextBox class, a similar effect could be obtained by creating a form containing only a single TextField. A similar argument can be advanced in respect of List. In any case, why is it that text and choice boxes can be screens in their own right, while other elements that can exist on a form (such as images, gauges, and plain strings) cannot? The classes List, Form, Alert and TextBox as subclasses of Screen. The other thing that can form a screen in its own right is a Canvas, but Canvas is not a subclass of Screen, it is a subclass of Displayable, which is also the base class for Screen. In other words, Canvas is at the same position in the class hierarchy as the abstract base class of all the other screen types. It is not clear what, say, List and Alert have in common that Canvas does not have. A possible answer is that List and Alert cannot receive raw keyboard input, while Canvas can. But there is no logical reason that I can suggest why Screen subclasses should not be able to process raw keyboard input if they want to. One more example: form items can be subclassed to change their behaviour. However, many of the important methods in these classes cannot be overridden by subclasses, so subclassing is of limited value. If the intention was that these classes should not be subclassed at all, they could have been declared as final. However, they aren't defined as final, and so there must be circumstances in which it is sensible to subclass them. But the subclasses can only modify the behaviour of the superclasses in very limited ways; in particular, the subclasses cannot override paint() and thereby change how the items are displayed. There appears to be no reason why form items can be subclassed at all, if the main reason for needing to subclass them is prohibited. What are we to make of all this? The MIDP user interface model is the ultimate triumph of practicality over design elegance. MIDP applications have to run in very little memory, and an instance of a class that has fewer base classes in its parentage has a smaller memory footprint than an instance that has more. At the same time, each additional class in the API set occupies a piece of the device's firmware. As a result, the MIDP model provides separate classes for user interface elements that are likely - in the Study Guide From www.ePlanetLabs.com
109
110
kinds of applications that MIDP supports - to form complete screens. It does not provide such classes for elements that are unlikely to form a complete screen. For example, there is a whole-screen TextBox object, but no whole-screen static string or image. There is no logical reason for this, but these additional classes would take up more firmware capacity. Similarly, while a TextBox could be simulated by a form containing a TextField, the latter would require more memory at run time. It is not self-evident, I think, that these design choices represent the best compromise between logicality and practicality. However, there is at least an arguable case that they do, or at least that the did. If you read the answer to the question above ``How do I reduce the memory footprint of my application?'', you'll notice that the MIDP API designers have done nothing more than the answer to that question recommends. The troubling question at present is whether an API based on such fanatical memory saving is appropriate in modern mobile devices. Are there AWT implementations for CLDC that can be used instead of the MIDP user interface model? There are, for certain devices. See, for example, kAWT. To provide a decent implementation of AWT, low-level access to the hardware is required. There is thus no fully portable AWT implementation. It's worth bearing in mind that the decision not to use AWT as the user interface model for MIDP was not taken lightly; a full implementation of AWT is likely to have at least a 100 kB memory footprint. You might get away with this on a PDA, but it's doubtful that you'll be able to support mobile phones. Are there AWT implementations that run on top of MIDP? Yes, there are AWT compatibility libraries for MIDP. However, they generally only provide AWT-style programming support on MIDP devices, not full AWT functionality. Consider the problem of implementing an AWT BorderLayout, for example. There are no MIDP API calls that will produce this style of layout, so no AWT compatibility library that runs on top of MIDP can produce a BorderLayout. Moreover, even where an AWT component can be implemented in a way that is logically equivalent in MIDP, it may not look the same. For example, a compatibility library may implement an AWT MenuBar using the nearest MIDP equivalent, but it won't look like a menu bar in an AWT application running on a workstation, or even in an applet. Bear in mind that an AWT compatibility library is likely to add about 100 kB to the size of your application. How difficult is it to port AWT applications to MIDP? For an application of any complexity, this is fairly difficult. The event handling model and user interface class hierarchy are very different. There are many things that AWT can do that MIDP can't do. Using an AWT compatibility library will probably make the job a bit easier, at the expense of increasing the application size quite a lot. Are there other user interface models apart from MIDP's that will run on CLDC? Sure, but they are all vendor specific. The good thing about using a vendor-specific user interface model like Motorola's `LWT' is that it is implemented in firmware, so it doesn't bloat the application in the way that using an AWT compatibility library would. The bad that about using a vendor-specific user interface model is that it is vendor-specific. How does a MIDP application deal with the wide diversity of input devices? A MIDP device may have as few as four keys, but some have full QWERTY keyboards or pointers. This presents a challenge for the developer. MIDP supports two different
110
111
input strategies: form-based input (typically used when a Form object is the current displayable), and raw keyboard input (typically used when a Canvas object is the current displayable). With form-based input, the methods by which data is entered into the form elements, and the method of navigation between form elements, are all vendor-specific. For example, if the operator has a mobile phone that requires multiple keypresses to enter alphanumeric data, the MIDP application should not have to worry about this. The device will arrange that the data entered - however this is achieved by the operator - is presented to the application as ordinary Java Strings. Similarly, if the device has a fourway arrow keypad, the MIDP implementation may map arrow operations to navigation operations. The way it does this will be different if the device has only a two-way arrow keypad, or if it has no navigation controls at all. For the developer, all that is really important is to create the form elements, and process their contents when the form is submitted. With raw-keyboard input, the application receives raw key codes as integers. This method of input usually requires considerable developer effort to make portable, as there is no correspondence between key codes and, for example, ASCII character values. However, if the application only requires a small number of keys, you may be able to use the `game keys' mechanism. Here the device vendor allocates certain keys to correspond to typical gaming actions: up, down, left, right, fire, etc. If the device has an arrow keypad, the `up' game action might be mapped to the `up' arrow key, for example. If the device has only a number keypad, a typical approach is to map game actions to number keys. This is all vendor specific; the device vendor should indicate to the user which keys form the standard game actions on that particular device. The vendor's MIDP implementation must then provide an method Canvas.getGameAction() that translates vendor-specific key codes into vendor-neutral game actions. What all this means in practice is that if your application accepts raw keyboard input, but is restricted to handling a few stereotypical keyboard actions, you can do this in a portable way. More sophisticated raw keyboard processing will require a fair amount of work if multiple devices must be supported. Whether the application uses form-based input or raw keyboard input, it can still take advantage of MIDP's rudimentary menu facility. The application adds `commands' (instances of the Command class) to the displayable object, and these are mapped to either keys or a menu by the device. For example, if you add two commands to a displayable, and the device has two action buttons under the screen, then it may map one command to each action button. If there are more than a few commands in the `menu', then the device may display a real menu when the operator presses a particular key. The exact implementation details are vendor-specific. Because the user interface of a MIDP device is generally rather impoverished, it helps the user if selecting common or popular operations can be accomplished in a minimum of user interface operations. As a result, when the application adds commands to a displayable, it gives each one a priority. The MIDP implementation can then try to map high-priority commands to more prominent buttons, and relegate low-priority commands to a menu. How do I create and display a form-based user interface? Create an instance of the Form class. Create instances of the objects you want on the form. Append the objects to the form. Get the current display object, and call its setCurrent() method to raise the form on the display. In practice, you will have to add at least one Command object to the form, or the user won't have any way to submit the form.
111
112
How do I create and display a user interface that isn't form-based? Create an instance of a class that extends the Canvas class. This class must override the paint() method, and draw its display using graphics primitives. Get the current display object, and call its setCurrent() method to raise the canvas on the display. You can process raw keyboard input by overriding the keyPressed() method, or by adding commands to the canvas, or both. Can I mix form-based and canvas-based displays on the same screen? In general, no. You can't add a Canvas object to a Form, nor vice versa. MIDP is not that logical. Nor can you easily create a custom form element and draw it yourself in MIDP1.0 (see below). What you can do, if you have the time and enthusiasm, is to create your own entirely new user interface model using objects that draw themselves on a Canvas object. You could even handle pointer events if you are targeting a platform that supports points, and provide the missing functionality in MIDP. However, this is not a trivial task. Can I create custom form elements (other than TextField, etc)? In MIDP1.0, tricky. There is no provision for this in the API, and although you can create subclasses of the standard form items like TextField, there is no public paint() method that you can override. You can override the (package access) callPaint() method, but only be creating a subclass in the javax.microedition.lcdui package, a highly dubious practice. The problem is that the reason methods are given package access, rather than protected access, is to discourage developers creating subclasses. It is part of the general contract of Java development that package-private methods in any class can change from one release of software to the next, and clients of that class have no grounds for complaint if it does. This unsatisfactory state of affairs is fixed in MIDP2.0. You can create custom form items in addition to the basic built-in items. A custom form item behaves much like a Canvas embedded in a form. What is an Alert? An alert is a kind of pre-defined form, which has a caption and a message. It is intended for displaying error or warning messages during an application. You can put up an alert by creating an instance of the Alert class and passing it to Display.setCurrent(), just as you would to display a canvas or form. Despite the similarity between an Alert and a form, Alert is not a subclass of Form (sigh). An Alert can be self-lowering, that is, it can take itself off the display after a certain time elapses. Can I do console-style I/O in a MIDlet? In general, no. Such operations may be supported by vendors, but they aren't defined in the MIDP specification. You can do console-style output by creating a TextBox object and appending text to it line-by-line, but this is not the sort of application that MIDP was intended for. The MIDP implementation is not required to do anything useful in response to a call to System.out.println(), and generally won't (see next question). Where does System.out.println() go? In an emulator, System.out.println() usually outputs to the emulator console or log. In a real device, it may just get junked. However, some devices echo standard output and
112
113
standard error to their serial ports, so if you plug in a terminal or terminal emulator, you might be able to see the output. What image file formats does MIDP support? PNG V1.0. Within the PNG format, only compression method `0' is supported. Interlaced PNGs are supported, but there is no advantage to using interlacing with MIDP applications, as the whole image is read and rendered before being transferred to the display. In fact, on most devices doing an image read in one thread suspends all other threads, so you can't even read an image on a background thread and render it bit by bit. In any case, images for use with MIDP application are unlikely to be slow large as to benefit from interlaced rendering. Can a MIDP application handle pointer events? Yes; you can override the pointerMoved() and pointerDragged() methods in Canvas. How can I reduce flicker on my animated Canvas flicker? As a general proposition, an application that does any kind of animation or rapid display update should minimise the amount of screen that is drawn on each update. However, in a MIDP application the screen is likely to be quite small, and the overhead involved in calculating which area to redraw can easily exceed the time take to redraw the whole display. If you do redraw the whole display, however, you'll see a marked flicker as you erase the background and redraw all the content. The solution to this problem is to draw the display off the main screen, then transfer the complete display to the screen as a block transfer operation. This is called `double buffering'. Some MIDP devices do their own double buffering. Typically, the Graphics object passed to the Canvas's paint() method is not the context of the real display, but an offscreen buffer. When the paint method returns, the device transfers the buffer to the screen. However, all MIDP applications should do their own double buffering, unless they are sure it is being done by the hardware. It isn't difficult to implement, and it isn't difficult to find out if the hardware is doing it. See the outline code below. import javax.microedition.lcdui.*; import javax.microedition.midlet.*; class MainCanvas extends Canvas { protected Image offscreen; //... other instance variables /** * Construct a new canvas, and check for double-buffering */ MainCanvas() { // ... initialise if (!isDoubleBuffered ()) offscreen = Image.createImage (getWidth (), getHeight ()); }
113
114
You can read an image from a file, and you can create an image from a byte array. But you can't read an image from a file and then get a byte array from it. Consequently, you can't easily process the data in an image supplied as a file (so you can't, say, adjust image contrast programmatically). You may be able to use Class.getResourceAsStream() to read the image into memory, but you'd still have to parse out the pixel data yourself. You can't get raw keyboard events at all in a form-based user interface, or from any item in it. The extremely useful methods in java.util.Date that split a time and date into hours, minutes, etc., are officially deprecated in JDK1.2 and later, but every developer I know still uses them. In the J2ME documentation, these methods are shown as absent completely, and may well not be supported at all in J2ME JVMs. This is probably true of all deprecated methods, but the omission of the Date.get methods is particular irritating. Although Java developers are frequently exhorted to use the ArrayList class instead of the (broadly compatible) Vector class, MIDP/CLDC provides no ArrayList class, only Vector. There is no support for `button' components on forms. In other words, you can't invoke an action by selecting a component with the navigation keys and `pressing' it. MIDP2.0 does support `active' string items, however, which offer similar functionality. An application cannot get a graphics context for redrawing a Canvas except in the paint method. In particular, you can't redraw the canvas in a background thread: the thread must call repaint() on the Canvas, and let the Canvas redraw
114
115
itself. This limitation makes it easier to implement double-buffering of the display in hardware. What have you got against the MIDP user interface? The astute reader will notice, I'm sure, that the things I have been complaining above result in part from exactly the techniques I recommend myself in the questions above on minimising memory requirements. There is nothing wrong with the user interface when seen from the perspective of an 8kB bytecode limit. The designers compromised logical consistency and strict OO principles in order to provide something that would work in such a restricted environment. But one has to ask whether it is still necessary to be as fastidious about memory conservation now that technology has moved on. The Nokia 6600 has 6Mb of internal memory, expandable by plug-in cards. It supports MIDP2.0. Yet MIDP2.0 still has the same illogicalities that MIDP1.0 had; it has to, to retain backward compatibility. In some ways, it would have been better if MIDP2.0 had provided an entirely new user interface model. Why is there no support for custom classloaders in CLDC/MIDP? Because, in theory, to provide custom classloader support would be to allow a MIDlet to interact with classes in a different MIDlet suite. This would be a security hazard. Can a CLDC/MIDP application use native method calls? The CLDC Specification mandates that CLDC code be forbidden to make native method calls. This is for security reasons. In any case, if you know how to make native method calls on your MIDP hardware device, you probably have the wherewithal to write the application using a programming language that produces native code, such as C or C++. One of the main advantages of using Java - cross-device portability - is lost as soon as you start using native methods, so if you need to call native code, you may as well work in C++. What do the line numbers mean in an exception stack trace from the WTK? In an ordinary Java application, when an exception is thrown the JVM will attempt to attach source code line numbers to the elements of the stack trace, provided that debugging information was compiled in. WTK does not do this; a stack trace will look like this: java.lang.ArithmeticException at HelloWorld.startApp(+25) at javax.microedition.midlet.MIDletProxy.startApp(+7) at com.sun.midp.midlet.Scheduler.schedule(+266) at com.sun.midp.main.Main.runLocalClass(+28) at com.sun.midp.main.Main.main(+116) The numbers `+25', `+7', etc., correspond to the position in the bytecode where the exception was thrown, relative to the start of the method. The only procedure I know to translate this into an exact line number in the source is to compare the source listing with the output of javap -c on the class. This command gives the dissassembled bytecode, which you can relate back to the source listing. Why would I want to obfuscate J2ME classes? Bytecode obfuscators replace the meaningful names of variables, classes, and methods in your code with gibberish. The obfuscated classes continue to work the same, but are much harder to reverse engineer. Obfuscation is often used by distributors of Java
115
116
applications to protect their trade secrets, such as how particular algorithms work. In a J2ME application, however, obfuscation has the additional benefit of tending to produce slightly smaller classes. This reduces the memory footprint of the application, and the time taken to upload it to the device. How does an application schedule regular timer events? Best shown by example: Timer timer = new Timer(); timer.scheduleAtFixedRate (new TheTimerTask(this), 0, millisecondInterval); //... public class TheTimerTask extends TimerTask { public void run() { /* Do whatever */ } } Timer events are still delivered when the application is paused. Can a CLDC/MIDP application parse XML? In principle, certainly. The difficulty might be getting an XML parser into the limited memory of the device. There are a number of J2ME-friendly parsers around, including nanoXML and kXML. If you are using XML for communications, you may prefer to use something like WBXML instead, as it is structurally the same as XML but much more compact. Obviously you will only be able to do this if you have control over both ends of the communications link. WBXML is a binary representation of XML, in which each element name is replaced by a numeric token. Some parsers, such as kXML, have builtin support for WBXML format. What do I do if I need floating-point maths support? The first question you should ask is whether you really, really need decimal maths (rather than integers), or whether you'd be better off scaling your quantities to integers instead. For example, you could represent the sum of money `twelve pounds and five pence' as the decimal number 12.05 (pounds). But you could equally well represent it as 1205 (pence). Provided all your amounts are in pence, you'll still get the right answer (in pence) when you add, subtract, multiply, or divide them (but watch out for rounding errors). Things are a bit more complicated when you need to scale different quantities by different amounts. For example, if you multiply velocity in metres per second, by time in seconds, you get distance in metres. Suppose you have velocities of millimetres per second, and times of milliseconds? If you scale both these quantities by a factor of 1000, how much will you have to correct the final answer by? Unless you are a physicist, you probably aren't very familiar with working this things out. If you really do need decimal arithmetic, your next question should be whether you need floating point maths, or whether fixed point would do. Fixed point is much easier to implement, and it perfectly satisfactory for financial and most engineering applications. It's no different in principle to the process of scaling described above, but with the scaling factors handled automatically by the implementation. There are a number of J2ME-friendly fixed-point maths libraries around. It would also be possible to port one of the standard floating-point libraries to CLDC, but the memory footprint is likely to be excessive.
116
117
Should I use vendor-specific extensions to the CLDC/MIDP APIs? Most vendor-specific extensions are exactly that; there is very little uniformity across the industry. Using these extensions reduces the portability of your applications. On the other hand, CLDC/MIDP provides a high-level abstraction of device functionality. You won't be able to use MIDP, for example, to change the display contrast or place voice calls. If you need to do this kind of thing, you are stuck with using vendor-specific extensions for the time being. File and data management Can a CLDC/MIDP application read or write files? Not necessarily. Most CLDC hardware would not recognise a file anyway. To support files you need some sort of bulk non-volatile storage. However, the lack of files does not indicate a complete lack of non-volatile storage: the application can use the record store API (see below). What is a record store? A record store is the only form of persistent storage that a CLDC device is required to support. A record store is a set of unformatted data elements, each identified by a unique integer. There are API calls to create and delete record stores, and to insert, remove, and search the elements. The elements themselves are exposed to the application as byte arrays, and if they are to have any internal structure, then the application must impose it. In this sense, records in a record store a like files, except that (1) the files are numbered, not named, and (2) each record element must be read or written in one operation. Because CLDC applications can be multi-threaded, the use of record stores is a rare example of an occasion where concurrency management can be troublesome to a CLDC developer. The record store implementation will synchronise access to the external non-volatile memory to the extent that each read or write is atomic. However, there are no transactional semantics or locking in record stores. If one thread of execution reads the same record twice, and another thread modifies the record between the other threads two reads, then the two reads will get different values. Vendors of relational databases go to some lengths to protect against this sort of problem, but such measures would be difficult to implement in a CLDC device. It is therefore the developer's responsibility to ensure that different threads do not attempt to read and write the same records at the same time if this would upset the application logic. What can a record store? A individual record contains a unique integer ID, and a byte array of arbitrary length. So you can store anything in a record that you can represent as a byte array. What if you want to store the state of a Java object? Your first thought might be to serialise the whole object into a ByteArrayOutputStream, then copy the bytes to the record. This is less easy than it should be, because there is no built-in support for serialisation in CLDC. So you'll need to equip your persistent classes with methods to save their state as a byte array, and regenerate their state from a byte array. Not rocket science, but more work for the developer. Can record stores be shared between MIDlet applications? In MIDP1.0 (which is the most widely-supported version at present) MIDlets can read and write record stores created by other MIDlets in the same MIDlset suite (that is,
117
118
deployed in the same JAR file). MIDP2.0 adds support for shared record stores: when a record store is created, the creating application can specify whether its record store is to be accessible to other MIDlet suites or not. Can record stores be synchronised between devices? There is no provision for this in the MIDP specification, so if such a feature is provided, it is vendor-specific. Can record stores be synchronised between mobile devices and workstations or servers? There is no provision for this in the MIDP specification, but it could be implemented (with some difficulty) by the developer. As the only communication mechanism supported by MIDP1.0 is HTTP (see below), your best bet would be to write a MIDlet that sends and retrieves the records to and from a web server using HTTP requests. The web server would provide a web application (based on servlets, perhaps) that receives the record store elements from the device, and synchronises them with its own version of the record store. If the record store element on the server is more up to date than that on the device (because it has been modified by a different application) then the server could send back to the device the modifications it needs to make to its own record store. The process of synchronisation is, of course, much more straightforward if it is oneway. If the purpose of the synchronisation is just to provide a backup feature for the record store, then the synchronisation logic is quite simple. The device will either send a whole record store (backup) or retrieve a whole record store (retrieve). Things are much more complex if the record store could be updated at both ends of the link. Then the process of synchronisation is not just a case of copying a batch of records from one place to another, but requires inspecting the relative timestamps of each record in the record store. It is wrong (and potentially destructive) to assume that just because one record store (say `Store1') was updated more recently than the other (`Store2'), then synchronisation consists only of transferring updates from Store1 to Store2. Suppose that within Store1, Record1 was modified at 1pm and Record2 at 5pm. In Store2, Record1 was modified at 3pm. Clearly Store1 has the later modification time: Record2 at 5pm. But, in fact, Store2 is more up to date in respect of Record1: 3pm rather than 1pm. So the flow of updates is in both directions. It should also be clear that the modification timestamp of the data store itself is of absolutely no value in synchronisation - you must timestamp each record. Unfortunately (sigh) the CLDC record store implementation provides no support for timestamping records. I do not know if this is an oversight (it is a reasonable one - designing database synchronisation logic is a specialist job), or if the types of device that CLDC supports don't have the required functionality in their firmware. I'm reasonably sure that the record store implementation in PalmOS - for which much of the original KVM development was targeted - does not timestamp records. What this means for the developer is that you have to encode a timestamp into each record in the record store, along with the real data. This in turn means that you can't implement a general record-store synchronisation application on the web server, because the application needs to know how to unpack each record and extract the timestamp. Thus the MIDlet logic and the server-side synchronisation logic have to be maintained together.
118
119
Can a record store be encrypted? You might want to encrypt a record store to protect access to it other than through the application that manages it. It would defeat the purpose of securing an application against unauthorised use, if the hacker could simply read the record store at the operating system level (on PalmOS, the record stores seen by MIDP can also be downloaded to a PC). There is no built-in support for data encryption in MIDP/CLDC. However, it is not difficult to implement a Java version of an algorithm of, say, IDEA or Blowfish. You'll only need a dozen lines of Java code. Alternatively, find an open-source project that has already done it. See, for example, Bouncy Castle. Networking and communications What networking operations can a MIDP application perform? MIDP defines a networking API called the Generic Connection Framework (GCF). This is a highly abstract representation of the fundamental things that an application can to do over a network, that is, send data and receive data. To use the GCF, the application supplies a URL to the (static) Connector class, and gets back an object that implements the InputConnection and OutputConnection interfaces. Methods on these interfaces allow the creation of input and output streams to the remote system. These streams can then be used to send and receive data. Apart from the URL itself, no part of this process depends on the network protocol. In practice, a MIDP device will probably support only HTTP, and unless the URL begins http:// the connection will usually fail. Moreover, an HTTP transaction consists of more than simply establishing a data stream in each direction. The device will probably need to set specific HTTP request header items, and parse the HTTP response headers. As a result, MIDP provides a specific implementation of an HTTP connection called, unsurprisingly, HttpConnection. The application can cast the result of the Connector.open() to an HttpConnection, and then do HTTP-specific things on the connection. MIDP2.0 extends the GCF by providing API classes for other protocol types, such as raw TCP/IP, UDP, and HTTPS. However, the fact that these classes exist should not fool the developer into assuming that these protocols will be supported. For example, WAP phones do not talk TCP/IP; their HTTP support is based on lower-level WAP protocols, not TCP. So you may still find that you can't open a low-level TCP socket. Even if the device supports other protocols, and the service provider can carry them, you may still find that you have to contend with firewalls. It would seem sensible to stick to HTTP for the time being. In principle this isn't a restriction; you can tunnel other protocols on top of HTTP easily enough. In practice it means extra work for the developer. Can I create a server (listening) socket in a MIDP application? There is no real equivalent of java.net.ServerSocket, but you can create a socket in such a way that it blocks until an inbound connection is detected. Here is a snippet of code that demonstrates the technique in MIDP1.0. StreamConnectionNotifier serverSocket = (StreamConnectionNotifier) Connector.open("serversocket://:12345"); StreamConnection conn = serverSocket.acceptAndOpen(); In MIDP2.0, a more elegant way of doing this is: ServerSocketConnection scn =
119
120
SocketConnection sc = (SocketConnection) scn.acceptAndOpen(); The MIDP2.0 version gives the application a real, TCP/IP socket whose own properties can be manipulated independently of the server socket. The MIDP1.0 version only provides the application with a preconfigured stream. In practice, neither version will work unless the device and the service provider are prepared to support TCP/IP (and they aren't required to). Why does my application run out of network connections after a while? This behaviour is frequently reported, and usually arises because the developer hasn't understood the relationship between the Connection objects and the data streams derived from it. In an ordinary Java sockets application, if you derive an InputStream and OutputStream from a Socket, the physical socket resource is actually held in the socket object. In MIDP, the physical resources modelling the connection live in the streams, not the socket. If you don't explicitly close the streams, the underlying socket resource remains connected. Eventually, you run out of sockets. As a result, it is considered good practice in MIDP programming to close the connection as soon as the streams have been established. For example: connection = (HttpConnection) Connector.open ("http://...", Connector.READ); InputStream is = connection.openInputStream(); connection.close(); // Read from the input stream... is.close(); The a regular Java programmer this looks odd, because it would be assumed that closing the socket closes the streams. Can a MIDlet determine the IP number of its host? Probably not in any robust way. Mobile devices don't necessarily use IP. In MIDP2.0, a device can open a ServerSocketConnection, and then call its getLocalAddress() method to get its own address. However, this comes back as a String, which is not guaranteed to contain an IP number. Even if it does, the application will have to parse it. Can a MIDlet determine the telephone number of the mobile phone hosting it? Not in any portable way, because the MIDP specification is not limited to mobile phones. The MIDP2.0 API provides a method MIDlet.platformRequest() that a MIDlet can call to ask the runtime system for platform specific data. It is envisaged that telephone details will be made available this way. Of course, this is still vendor-specific, but at least does not require the use of vendor-specific classes. What is J2ME? J2ME is a versions of Java or as Sun Microsystems puts an edition of Java that is deisgned for Mobile devices and other environments. J2ME developers use a JAVA compiler, WirelessToolKit, and a Obfuscator to preverify the classes, compile and package the classed in a JAR and JAD combination. What Can J2ME Be Used For?
120
121
Java was orginaly started to deploy on mobile devices such as Star7 and thus J2ME returns Sun to these roots. J2ME is deployed on such mobile devices as handsets, PDAs, SmartPhones, and RIMs in the mobile sector. It also is deployed in other small resource environments such as DigitalTV/InteractiveTV(iTV/javaTV), Automobiles/Jets( ?Telemactics), and etc. What is the Syntax Like? J2ME is similar to Java in that it uses the same syntax with some slight modifications. Unlike general java or J2SE, J2ME is not standalone in nature and thus their is not main method but a different set of methods that form a standard midlet. An Example of a Midlet
//must be saved as same name that JAd referrers to as .java extension package com.shareme.moonbuzz.midp; import javax.microedition.midlet.*; import javax.microedition.lcdui.*;
/** * @author Fred Grott */ public abstract class MoonBuzz extends MIDlet implements CommandListener {
/*
121
122
Cache.numItemsPerLevelRec = Cache.setItemsPerLevel(3); Cache.numItemsPerPreferencesRec = Cache.setItemsPerPrefs(3); Cache.isPrefsInitialized = RecordStores.isPrefs(1); if (Cache.isPrefsInitialized=false){ Cache.isPrefsInitialized = RecordStores.intitializePrefsRMS( Cache.shakeMe, Cache.soundMe, Cache.levelMe); Cache.isHighScoreInitialized = RecordStores.intitializeLevelRMS(Cache.zeroScore);
122
123
123
124
notifyDestroyed();
124
125
public void commandAction(Command command, Displayable displayable) { if (command == exitCommand) { notifyDestroyed(); } } } Each application in J2ME has one class that is a midlet with the methods of startApp. pauseApp, and destroyApp. A Visual Demo Here is a simple Pong J2ME game demo as a jav applet which you can play to see how apps work in a mobile device such as a handset. Pong Game on c55 Siemens handset What is Needed To Get Started? To start coding in J2ME you need a WirelessToolKit and a java Obfuscator for J2ME. You will also need emulators/sdk for the device you are targeting. Some developers will add an IDE and J2ME Ant extensions, such as Antenna or J2ME Polish, to this list but there is a light J2ME code editor in Sun's WirelessToolKit. Common J2ME Problems J2ME as implemented on cell phone devices does not properly call the pauseApp method in the midlet correctly and thus you have to check if the canvas isVisible within the midlet application. J2ME is commonly deployed to devices with different screen sizes and input methods and thus you need to adjust for this in using images and code detecting user input.
The platform Java 2 Microedition (J2ME) implements technologies as various as the SMS, the GSM/GPRS, the PDA, the WAP, etc. This is why this FAQ tries to approach in turn the whole of these fields. What the J2ME? Java 2 Microedition is a platform JAVA concue to function on embarked terminals. The mobile version telephony of the J2ME is consisted a virtual machine JAVA (KVM) as well as a directed continuation API mobile telephony. (MIDP or DoJa and CLDC). high
125
126
"Kilobyte Virtual Machine" is the heart of the language JAVA in an embarked terminal. Concue to function in an environment limited in term of memory, energy, access network. This KVM is accompanied by the API ones by two types: Configurations and Profile. high What does a Configuration, one Profile? A Configuration is contitue of API basic giving access to the functions of the virtual machine JAVA. Within the J2ME, there are two type of Configuration: the CLDC (Connected Limited Device Configuration) and the CDC (Connected Device Configuration). The CLDC is directed final Mobile (with a KVM) and the CDC is used on terminals of the type decoder canal+, therefore out of our matter. One Profiles is an API concue to benefit the best from a type of precise terminal (size of the screen, eran tactile, type of network...). There are several types of Profile whose MIDP (Mobile Information Device Profile) is used the most. The PDAP (PDA Profiles), the Multi-media one Profiles are now available, others are under development by SUN Microsystems. high What the CLDC? The CLDC (Connected Limited Device Configuration) consists of API a basic nccessaire with the language java (java.lang, java.io, java.util) as well as API specialized in the mobile access network: javax.microedtion.io. What the MIDP? The MIDP (Mobile Device Information Profiles) is API high level JAVA allowing the management of the user interface, the management of the interface network, the management of a base of data on the mobile. This API is to date that which you find on your mobiles "compatible J2ME". A FAQ is devoted to him: FAQ MIDP . high What DoJa? DoJa (Docomo Java) is a Japanese version of the MIDP. It is API is optimized for the terminals I-mode of NttDocomo. One can note a management improved of the graphic interface compared to the MIDP such as it is specified by Sun Microsystem. A FAQ is devoted to him: FAQ DoJa high A relationship with the SMS? The SMS (Shorts Message Service), you know it (yes same you customer SFR, it acts of the true name of the "TEXTO":). The J2ME specified by SUN On the other hand did not
126
127
Wap (Wireless Protocol Application) was a large commercial failure in Europe, but that do not please say that it is deceased for as much. It is used today basic for a multitude of protocols, of which the J2ME. In order to communicate with the world exterior (here Internet) telephone J2ME uses Wireless Session Protocol (WSP). high A relationship with Stk? SimToolkit is a technology JAVA implente on your chart SIM (Subscriber Identity Module). This techology nom JAVACARD allows an interaction with the mobile telephone ansi that with chart SIM. Its use more running in the world of the company remains the management of fleet. A menu generated by the JAVA application makes it possible to update menus on the telephone like on a distant waiter (via SMS or session WAP). The J2ME does not allow yet a communication with an application JAVACARD. The J2ME will be very of same quickly able to communicate with chart SIM of the subscriber (with the study at Orange, for example via the concept of certificates as in the Applet JAVA J2ME Overview
Configurations
Base configuration for a range of devices Connected Limited Device Configuration (CLDC) Connected Device Configuration (CDC)
Profiles
Additions to configurations for a particular device CS 683 Fall 04 Connected Limited Device Configuration (CLDC) Basic cell phone & PDA
A 16-bit or 32-bit processor clock speed of 16MHz or higher At least 160 KB of non-volatile memory
127
128
Low power consumption, often operating on battery power Connectivity to some kind of network, often with a wireless, intermittent connection and limited bandwidth
32-bit microprocessor/controller 2MB of RAM for Java 2.5 MB of ROM Java Doc 18, J2ME Intro Slide # 6
Java Card
Call centers
Applications & services on embedded devices 1MB persistent storage + run-time cache
PersonalJava
Java TV API
JavaPhone API
Direct telephony control Datagram messaging Address book and calendar information User profile access Power monitoring Application installation CS 683 Fall 04 Doc 18, J2ME Intro Slide # 7
128
129
Basic Profile for Cell phones & PDAs Versions 1.0 & 2.0 Included in J2ME Wireless Toolkit 2.1 MIDP for Palm OS
http://java.sun.com/products/midp4palm/ Based on MIDP 1.0 Wireless Messaging API (WMA) Platform-independent access to wireless communication resources like Short Message Service (SMS)
Included in J2ME Wireless Toolkit 2.1 Doc 18, J2ME Intro Slide # 8
CS 683 Fall 04
Connected Limited Device Configuration (CLDC)Profiles & API Mobile Media API (MMAPI)
Audio Video Time-based multimedia support Included in J2ME Wireless Toolkit 2.1
Emergency call boxes Parking meters Wireless modules in home alarm systems Industrial metering devices
Location API
129
130
Targets mobile phones Establish and manage multimedia IP sessions Doc 18, J2ME Intro Slide # 9
CS 683 Fall 04
Connected Limited Device Configuration (CLDC)Profiles & API Security and Trust Services API (SATSA)
Extends the security features ofJ2ME Cryptographic APIs Digital signature service User credential management
Mobile 3D Graphics API Scalable, small-footprint, interactive 3D API for use on mobile devices J2ME Web Services APIs (WSA) Web services for J2ME Bluetooth API By Motorola/Freescale Status unknown CS 683 Fall 04 Connected Limited Device Configuration (CLDC) Java Limitations
No Floating point
130
131
Security J2SE security model not used Code runs in a sandbox Class Verification Must run byte-code verifier by hand before running application CS 683 Fall 04 Packages from J2SE java.io ByteArrayInputStream DataInputStream InputStream OutputStream PrintStream Writer java.lang Boolean Class Math Short System java.util Calendar Random TimerTask Date Stack TimeZone Hashtable Timer Vector Byte Integer Object String Thread Character Long Runtime StringBuffer Throwable ByteArrayOutputStream DataOutputStream InputStreamReader OutputStreamWriter Reader Doc 18, J2ME Intro Slide # 11
Some classes are based on JDK 1.1.8 or earlier Some classes are smaller than their J2SE equivalents CS 683 Fall 04 Doc 18, J2ME Intro Slide # 12
131
132
Example will use Unix path conventions Assume that the Wireless Toolkit (WTK) is installed in /pathtoWTK/WTK2.1 CS 683 Fall 04 Running the Example the Hard Way Create a directory, MySample, for your project Create subdirectories:
classes src
132
133
tmpclasses
Place the source in file MySample.java and place file in directory src In the directory MySample compile using: javac -d tmpclasses -bootclasspath /pathtoWTK/WTK2.1/lib/cldcapi10.jar:/pathtoWTK/WTK2.1/lib/midpapi20.jar -classpath tmpclassese:classes src/*javapreverify -classpath Then run /pathtoWTK/WTK2.1/bin/preverify -classpath /pathtoWTK/WTK2.1/lib/cldcapi10.jar:/pathtoWTK/WTK2.1/lib/midpapi20.jar -d classes tmpclasses CS 683 Fall 04 Doc 18, J2ME Intro Slide # 15 Running the Example the Hard Way Continued Create the file MANIFEST.MF MIDlet-1: MySample, MySample.png, MySample MIDlet-Name: MySample MIDlet-Vendor: Unknown MIDlet-Version: 1.0 MicroEdition-Configuration: CLDC-1.0 MicroEdition-Profile: MIDP-2.0 Create the jar file using jar cfm MySample.jar MANIFEST.MF -C classes . Create the file MySample.jad MIDlet-1: MySample, MySample.png, MySample MIDlet-Jar-Size: 1433 MIDlet-Jar-URL: MySample.jar MIDlet-Name: MySample MIDlet-Vendor: Roger Whitney MIDlet-Version: 1.0 MicroEdition-Configuration: CLDC-1.0 MicroEdition-Profile: MIDP-2.0 Run the emulator CS 683 Fall 04 Doc 18, J2ME Intro Slide # 16
133
134
Click on New Project. Enter the Project name and class name as shown below
Click on Create Project. A setting window will open up. Accept the defaults by clicking ok in that window. CS 683 Fall 04 Running the Example the Easy Way Continued Place the source code for the class in the file WTK2.1/apps/FirstExample/src/MySample.java In the ktoolbar main window click on the Build button. When the build compiles successfully then click on the Run button. Doc 18, J2ME Intro Slide # 17
CS 683 Fall 04
134
135
When loaded MIDlet Starts in the Paused state Normal instance initialization is done If constructor throws an exception the MIDlet is destroyed CS 683 Fall 04 Doc 18, J2ME Intro Slide # 20
135
136
If a non-transient failures
CS 683 Fall 04 startApp() Verse Constructor MIDlet can have a no argument constructor Use constructor to create resources once
Use startApp() for resources that need action each time move to active state CS 683 Fall 04 Two Programs with the Same Behavior public class MySample extends MIDlet { public MySample() { } public void startApp() { Form form = new Form( "First Program" ); form.append( "Hello World" ); Display.getDisplay(this).setCurrent( form ); } public void pauseApp() {} public void destroyApp( boolean unconditional ) { } } public class MySample extends MIDlet { Doc 18, J2ME Intro Slide # 22
136
137
public MySample() { Form form = new Form( "First Program" ); form.append( "Hello World" ); Display.getDisplay(this).setCurrent( form ); } public void startApp() {} public void pauseApp() {} public void destroyApp( boolean unconditional ) { } } CS 683 Fall 04 pauseApp() protected abstract void pauseApp() Called when MIDlet is moved to Paused state from Active state If a runtime exception occurs in pauseApp()
destroyApp() protected abstract void destroyApp(boolean unconditional) throws MIDletStateChangeException Called when MIDlet is to enter the Destroyed state Should
If unconditional is false MIDlet can throw MIDletStateChangeException to signal not to destroy it CS 683 Fall 04 notifyDestroyed() public final void notifyDestroyed() MIDlet uses to notify it has entered the Destroyed state destroyApp() will not be called MIDlet must perform same operations as done by destroyApp() Doc 18, J2ME Intro Slide # 24
137
138
Jar to load or install tel:<number> a phone number to call Doc 18, J2ME Intro Slide # 27
138
139
public class MySample extends MIDlet { public MySample() { Form form = new Form( "First Program" ); form.append( "Hello World" ); Display.getDisplay(this).setCurrent( form ); } public void startApp() { System.out.println( Start); } public void pauseApp() { System.out.println( Pause); } public void destroyApp( boolean unconditional ) { System.out.println( Good bye); } } System.out can be used for debugging. When run in the simulator, the output is put in the console, not the phone J2ME performance tips
Java tuning tips for J2ME. This is pretty wide-ranging, but mostly focused on the size of the application. Graphics performance is the next along, then usability. See also the tips page on user perceptions.
Optimizing hash functions: generating a perfect hash function For years, Jonathan Hardwick's old but classic site was the only coherent Java performance tuning site on the web "Cutting Edge Java Game Programming" MIDP tips The smallest "Hello World" MIDP memory tuning Benchmarking Mobile & wireless devices Minimizing bytecode size for J2ME Flicker-free graphics with the Mobile Information Device Profile J2ME game building MIDP GUI programming
139
140
Nice article on understanding bytecodes by Peter Haggar, Added 2000-10-23, Author of "Practical Java" Performance tuning embedded Java Reusing objects in embedded Java Object recycling part 2 Chapter 2, "Java: Fat and Slow?", of "Java 2 Micro Edition: Professional Developer's Guide" Porting to KVM The Javap disassembler Good Java practices, some of which are good for performance. The performance of games on J2ME Minimizing space taken by HTTP downloads Timers and low-level GUI display effects J2ME apps, with a discussion of the needs to balance performance Using Timers (java
The following detailed tips have been extracted from the raw tips page http://www.onjava.com/pub/a/onjava/2001/01/25/hash_functions.html Optimizing hash functions: generating a perfect hash function (Page last updated January 2001, Added 2001-02-21, Author Jack Shirazi, Publisher OnJava). Tips:
Minimal perfect hash maps do not require any excess memory, but may impose significant overheads on the map.
http://www.cs.cmu.edu/~jch/java/optimization.html For years, Jonathan Hardwick's old but classic site was the only coherent Java performance tuning site on the web. He built it while doing his PhD. It wasn't updated beyond March 1998, when he moved to Microsoft, but most tips are still useful and valid. The URL is for the top page, there are another eight pages. Thanks Jonathan. (Page last updated March 1998, Added 2000-10-23, Author Jonathan Hardwick, Publisher Hardwick). Tips:
If size is a constraint: use SDK classes wherever possible; inherit whatever possible; put common code in one place; initialize big arrays at runtime by parsing a string; use short names;
http://library.cs.tuiasi.ro/programming/java/cutting_edge_java_game_programming/ewto c.html "Cutting Edge Java Game Programming". Oldish but still useful intro book to games programming using Java. (Page last updated 1996, Added 2001-06-18, Author Neil Bartlett, Steve Simkin , Publisher Coriolis). Tips:
Use a dissassembler (e.g. like javap) to determine which of various alternative coding formulations produces smaller bytecode. To reduce the number of class files and their sizes: use the SDK classes as much as possible; and implement common functionality in one place only.
140
141
Make HTTP requests in a background thread. Use an asynchronous messaging model. Use WBXML to compress XML messages.
http://www.sys-con.com/java/article.cfm?id=1533 The smallest "Hello World" (Page last updated July 2002, Added 2002-07-24, Author Norman Richards, Publisher Java Developers Journal). Tips:
Use the -g:none option to strip debugging bytes from classfiles. Most bytes in Java class files are from the constant pool, then the method declarations. The constant pool includes class and method names as well as strings. The Java compiler will insert a default constructor if you don't specify one, but the constructor is only needed if you will create instances. You can remove the constructor if you will not be creating instances. Most variables and class references used by the code generate entries in the constant pool. Reusing already existing constant pool entries for class/method/variable names reduces the class file size.
http://wireless.java.sun.com/midp/ttips/memory/ MIDP memory tuning (Page last updated June 2002, Added 2002-07-24, Author Jonathan Knudsen, Publisher Sun). Tips:
Use an obfuscator to minimize the size of classes. Minimize resource sizes by using as few images as possible, and using fewer colors in the images you do use. Use as few objects as possible. Dereference objects (set them to null) when they're no longer useful so they will be garbage-collected. Catch OutOfMemoryErrors on all allocations, or at least the large ones. Don't let an OutOfMemoryError take your application by surprise. MIDlets use three types of memory: program memory, heap, and persistent storage. Each of these may be scarce and they should all be treated with respect.
http://www.sys-con.com/java/article.cfm?id=1280 Benchmarking (Page last updated January 2002, Added 2002-01-25, Author Glenn Coates & Carl Barratt, Publisher Java Developers Journal). Tips:
In J2ME, software accelerators may improve speed, but they may also consume excessive power compared to a processor that executes Java as its native language.
141
142
Prototype to determine the performance of your device. Wireless transmissions require testing to determine if the transfer rates and processing times are acceptable. Attempt to create applications that can accomplish 80% or more of their operations through the touch of a single key/button or the "tap" or touch of the stylus to the screen. Trying to manipulate a very small scroll bar on a small screen can be an exercise in hand-eye coordination. Horizontal scrolling should be avoided at all costs. Use "jump-to" buttons rather than scrollbars. Try to avoid having the user remember any data, or worse, having to compare data across screens. Performance will always be a concern in J2ME. Avoid garbage generation: Use StringBuffer for mutable strings; Pool reusable instances of objects like DateFormat; Use System.gc() to jump-start or push the garbage collection process. Compile the code with debugging information turned off using the -g:none switch. This increases performance and reduces its footprint. Avoid deep hierarchies in your class structure. Consider third-party JVMs, many are faster than the Sun ones. Small XML parsers and micro databases are available for purchase where necessary.
http://developer.java.sun.com/developer/J2METechTips/2002/tt0226.html Minimizing bytecode size for J2ME (Page last updated February 2002, Added 2002-0325, Author Eric Giguere, Publisher Sun). Tips:
Eliminate unnecessary features. Avoid inner classes: make the main class implement the required Listener interfaces and handle the callbacks there. Use built-in classes if functionality is close enough, and work around their limitations. Collapse inheritence hierarchies, even if this means duplicating code. Shorten all names (packages, classes, methods, data variables). Some obfuscators can do this automatically. MIDP applications are completely selfcontained, so you can use the default package with no possible name-clash. Convert array initialization from code to extract data from a binary string or data file. Array initialization generates many bytecodes as each element is separately initialized.
http://developer.java.sun.com/developer/J2METechTips/2001/tt0725.html Flicker-free graphics with the Mobile Information Device Profile (Page last updated July 2001, Added 2001-08-20, Author Eric Giguere, Publisher Sun). Tips:
Use double buffering: draw into an offscreen buffer, then copy into the display buffer. Copying buffers is very fast on most devices, while directly drawing to a display sometimes causes users to see a flicker, as individual parts of the display
142
143
are updated. Double buffering avoids flickering by combining multiple individual drawing operations into a single copy operation. Use the Canvas.isDoubleBuffered() method, to determine if double buffering is already automatically used: on some implementations the Canvas object's paint method is already a Graphics object of an offscreen buffer managed by the system. (The system then takes care of copying the offscreen buffer to the display.) Use javax.microedition.lcdui.Image class to create an offscreen memory buffer, and use Graphics to draw to the offscreen buffer and to copy the contents of the offscreen buffer onto the display. The offscreen buffer is created by calling one of the Image.createImage methods. Double buffering does have some overhead: if only making small changes to the display, it might be slower to use double buffering. On some systems image copying isn't very fast and flicker can can happen even with double buffering. Keep the number of offscreen buffers to a minimum. There is a memory penalty to pay for double buffering: the offscreen memory buffer can consume a large amount of memory. Free the offscreen buffer whenever the canvas is hidden (use the canvas' hideNotify() and showNotify() methods.)
http://portals.devx.com/Nokia/Article/6218 J2ME game building (Page last updated April 2002, Added 2002-05-19, Author Dale Crowley, Publisher DevX). Tips:
J2ME device memory and speeds are very limited which affects everything from the data-loading speed to the frame/refresh rate, and seriously limits the ability to animate characters or otherwise rapidly change the screen. Smart graphics is important: you need to draw clear, concise images at extremely low resolutions and with very small palettes. Animated characters need dynamic, easily-read poses which avoid kicks looking like a dance steps, or punches looking like an arm waves. Use public variables in your classes, rather than using accessors. This is technically bad programming practice but it saves bytecode space. Be extra careful to place things in memory only when they are in use. For example, discard an introduction splash screen after display. Try to reduce the number of classes used. Combine classes into one if they vary only slightly in behavior. Every class adds size overheads. Remember that loading and installing applications into J2ME phones is a relatively slow process.
http://www.onjava.com/pub/a/onjava/excerpt/wirelessjava_ch5/index3.html MIDP GUI programming (Page last updated March 2002, Added 2002-03-25, Author Qusay Mahmoud, Publisher OnJava). Tips:
Applications with high screen performance needs, like games, need finer control over MIDP screens and should use the javax.microedition.lcdui package which provides the low-level API for handling such cases. Always check the drawing area dimensions using Canvas.getHeight() and Canvas.getWidth() [so that you don't draw unnecessarily off screen].
143
144
Not all devices support color. Use Display.isColor() and Display.numColors( ) to determine color support and avoid color mapping [overheads]. Double buffering is possible by using an offscreen Image the size of the screen. Creating the image: i = Image.createImage(width, height); Getting the Graphics context for drawing: i.getGraphics(); Copying to the screen g.drawImage(i, 0, 0, 0); Check with Canvas.isDoubleBuffered(), and don't double-buffer if the MIDP implementation already does it for you. To avoid deadlock paint() should not synchronize on any object already locked when serviceRepaints() is called. Entering alphanumeric data through a handheld device can be tedious. If possible, provide a list of choices from which the user can select.
http://www.developer.ibm.com/library/articles/programmer/haggar_bytecode.html Nice article on understanding bytecodes by Peter Haggar, Added 2000-10-23, Author of "Practical Java". Explains why a synchronized method is faster than a functionally identical synchronized block. (Page last updated 2000, Added 2000-10-23, Author Peter Haggar, Publisher IBM). Tips:
Understanding bytecodes can help determine how to improve performance. It can also help you to create smaller sized class files. Use the -g:none option to make files class smaller [or use a better optimizing compiler]
http://www.onjava.com/pub/a/onjava/synd/2001/08/15/embedded.html Performance tuning embedded Java (Page last updated August 2001, Added 2001-0820, Author Vincent Perrier, Publisher OnJava). Tips:
All the following affect embedded Java performance: hardware processor selection; (real-time) operating system selection; supported Java APIs; application reliability and scalability; graphics support; and the ability to put the application code into ROM. Various approaches for boosting bytecode execution speed include: a JIT compiler (usually too big for embedded systems); an ahead-of-time compiler (requires more ROM, may disallow or slowdown dynamically loaded classes); a dynamic adaptive compiler (half-way house between last two options); putting the Java application code into ROM; rewriting the JVM interpretation loop in assembly; using a Java hardware accelerator. Use the lightweight graphical toolkit. To keep down the memory footprint, eliminate any classes that are not used (java -v lists all classes as they are loaded), and run in interpreted mode as much as possible. Benchmark results are not necessarily applicable to your application [article reviews the applicability of standard and proprietary benchmarks].
http://www.microjava.com/articles/techtalk/recycle Reusing objects in embedded Java (Page last updated July 2001, Added 2001-07-20, Author Angus Muir and Roman Bialach, Publisher Micro Java). Tips:
144
145
A lot of object creation and destruction can lead to a fragmented heap, which reduces the ability to create further objects. Define the bulk of memory you need (buffers, etc.) up-front at initialization, and use object pooling to avoid further creation or destruction of objects. Throwing/catching exceptions are tremendously expensive. Pooling is not always faster than object creation.
http://www.microjava.com/articles/techtalk/recylcle2 Object recycling part 2 (Page last updated February 2002, Added 2002-02-22, Author Angus Muir and Roman Bialach, Publisher Micro Java). Tips:
The efficiency of pooling objects compared to creating and disposing of objects is highly dependent on the size and complexity of the objects. Object pools have deterministic access and reclamation costs for both CPU and memory, whereas object creation and garbage collection can be less deterministic.
http://www.microjava.com/chapter2 Chapter 2, "Java: Fat and Slow?", of "Java 2 Micro Edition: Professional Developer's Guide" referenced from http://www.microjava.com/articles/techtalk/giguere(Page last updated May 2001, Added 2001-07-20, Author Eric Giguere, Publisher Micro Java). Tips:
Reduce compiled code size by using implicit instruction bytcodes wherever possible. For example, limiting a method to four or fewer local variables (three on non-static methods as "this" takes the first slot), allows the compiler to use implicit forms of instructions (such as aload, iload, fload, astore, istore, fstore, and so on). Similarly numbers -1, 0, 1, 2, 3, 4 ,5 have special bytecodes Java class files are standalone - no data is shared between class files. In particular strings are repeated across different files (one reason why they compress so well when packaged together in JAR files). An empty class compiles to about 200 bytes, of which only 5 bytes are bytecode. There are no instructions for initializing complete arrays in the Java VM. Instead, compilers must generate a series of bytecodes that initialize the array element by element. This can make array initialization slow, and adds bytecode to the class. You can reduce bytecode bloat from array initialization by encoded values in strings and using those strings initialize the arrays. Explicitly set references to null when they are no longer needed to ensure that the objects can be garbage collected. Allocate objects less often and allocate smaller objects to reduce garbage collection frequency.
http://www.microjava.com/articles/techtalk/kvmprogramming Porting to KVM (Page last updated February 2002, Added 2002-02-22, Author Shiuh-Lin Lee, Publisher Micro Java). Tips:
Minimize program runtime size. Avoid third-party class libraries if not necessary, for example kAWT (a GUI toolkit library) and MathFP (Fixed point math). Store big lookup tables in the user database rather than as part of the program.
145
146
Call GC functions manually. Dispose of Objects; close the database and the network connections as soon as they are no longer needed. Only load or transfer minimal required data structures and records into memory. Avoid float and double calculations. Avoid data conversions: store and use the data in the final required format, or execute conversions on the server. Use client caching. Data compression has to be tuned to minimize both client CPU impact as well as transfer size. Use tabbed panels to hold different groups of information. Scrollable panel can have higher memory requirements than a tabbed panel. Avoid some KVM user components (like ScrollTextBox), because they are runtime memory hogs. Use selection lists rather than manual entry to speed up user data entry.
http://developer.java.sun.com/developer/TechTips/2000/tt0829.html The Javap disassembler (Page last updated August 2000, Added 2001-04-20, Author Stuart Halloway, Publisher Sun). Tips:
[Article describes using the javap disassembler, useful for identifying exactly what the code has been compiled into].
http://www.joot.com/articles/practices.html Good Java practices, some of which are good for performance. (Page last updated January 2001, Added 2001-01-19, Author Dave Jarvis, Publisher JOOT). Tips:
Reduce code size by: obfuscating code; compression in jar files; excluding the manifest in jar files; reordering variable declarations; eliminating dead code; using protected methods.
http://www.javaworld.com/javaworld/jw-03-2001/jw-0309-games.html The performance of games on J2ME (Page last updated March 2001, Added 2001-0321, Author Jason R. Briggs, Publisher JavaWorld). Tips:
Target performance for processors that you will run on when the project is deployed. Implementing the ImageProducer interface and setting an image's pixels directly eliminates one or two steps in the MemoryImageSource option and seems to be about 10 percent to 20 percent faster on average. Raw frame rate display, without taking account of the time taken to draw an image, runs from 2 frames per second (fps) to 400 fps, depending on processor and JVM. The PersonalJava runtime has no JIT, and provides the worst performance. With a JIT it might be usable. [Article includes references to a number of hardware based Java implementations, i.e. Java enabled CPUs.]
http://developer.java.sun.com/developer/qow/archive/153/index.jsp Minimizing space taken by HTTP downloads (Page last updated October 2001, Added 2001-10-22, Authors Gary Adams and Eric Giguere, Publisher Sun). Tips:
146
147
Use HttpConnection.getLength() to determine the number of bytes needed to to hold the data from a download. Use a ByteArrayOutputStream to accumulate results if the content length is indeterminate. The best performance is obtained from a 1.1 compliant webserver using persistent connections.
http://www.microjava.com/articles/techtalk/display?PageNo=1 Timers and low-level GUI display effects (Page last updated September 2001, Added 2001-10-22, Author Roman Bialach, Publisher Micro Java). Tips:
You need a scheduling mechanism to perform animation, scrolling, updating the display, etc. The paint() method on the Canvas is called by the system only if it thinks that it needs to repaint it. So we need another timer to repaint the screen on a regular basis. Use a timer to periodically call repaint().
http://www.sys-con.com/java/article2a.cfm?id=732 J2ME apps, with a discussion of the needs to balance performance (Page last updated June 2001, Added 2001-07-20, Author Glenn Coates, Publisher Java Developers Journal). Tips:
J2ME devices have limited processing power, so performance is important and must be considered for the target device. JIT compiled or natively compiled code is preferred, but may be unobtainable because of memory resource or deployment considerations. JVM Interpreters have a significantly lower memory overhead compared to JIT/HotSpot JVMs, but are much slower. Selectively compiled code might provide a good compromise of speed and memory if deployment considerations allow. The application does not need to be lightning fast in order to have a responsive user interface. The perception of speed is important, for example, the user interface should give immediate feedback. JVM slection for the J2ME device is pivotal to achieving the required performance. Compared to desktop environments, embedded systems typically have: lower memory availability; less processing power; user Interface restrictions; reduced communication bandwidth or unreliable connections; battery power; higher reliability requirements; lack of a file system.
http://developer.java.sun.com/developer/J2METechTips/2001/tt0416.html Using Timers (java.util.Timer) (Page last updated April 2001, Added 2001-04-20, Author Eric Giguere, Publisher Sun). Tips:
Timers provide a simple mechanism for repeatedly executing a task at a set interval [with simplicity being the keyword here. Don't look for anything sophisticated like thread interrupt control].
147
148
J2ME Overview J2ME (Java 2 Micro Edition) is a family of APIs that specify application platforms that are typically implemented by embedded or handheld devices. Handheld devices include PDAs (Personal Digital Assistants) and high-end mobile phones. These platforms are typically limited in memory capacity and I/O capabilities, although they do have the ability to transfer data over low bandwidth, intermittent wireless connections. J2ME Stacks
CLDC Requirements: monochrome 96x54 pixel display 2-way wireless network input device (keypad, touch screen) 128 Kb for CLDC/MIDP classes + 32 Kb for KVM CLDC Classes Interfaces and exceptions not shown.
148
149
149
150
Creating a New Project and Midlet Applications that run on a MIDP/CLDC platform are called midlets. By pressing the "New Project" button we create a new project named Examples containing a midlet defined in a file named HelloWorld.class:
The console window informs us that it has created a project directory named Examples containing src, res, and lib subdirectories:
150
151
Other subdirectories have been created as well. We must save our .java files in the Examples\src subdirectory. HelloWorld.java The file Examples\src\HelloWorld.java is created using an ordinary text editor. It begins by importing several J2ME packages: import javax.microedition.lcdui.*; import javax.microedition.midlet.*; The declaration of the HelloWorld class follows: public class HelloWorld extends MIDlet { // Device's display window and main screen: private Display theDisplay; private Screen mainScreen; public HelloWorld() { theDisplay = Display.getDisplay(this); mainScreen = new TextBox( "Example 1", "Hello World", 50, TextField.ANY); } // Lifecycle methods: protected void startApp() { theDisplay.setCurrent(mainScreen); } protected void destroyApp(boolean unconditional) { } protected void pauseApp() { } } Notice that HelloWorld extends MIDlet. Two instance variables are declared and subsequently initialized by the constructor. theDisplay represents the display window of the PDA or mobile phone. mainScreen represents the screen that theDisplay is supposed to display. This is accomplished in startApp() method by the line: theDisplay.setCurrent(mainScreen);
151
152
startApp() is one of three lifecycle methods every midlet must define. In most of our examples the other two have empty bodies. We can think of theDisplay as a mini web browser and mainWindow as a type of web page. In our example, mainPage is a text box titled "Example 1" and containing the text "Hello World". Running HelloWorld Pressing the Build button on the toolbar causes the Wireless Toolkit to compile all .java files in the current project's src subdirectory. The corresponding .class files are placed in the classes subdirectory. Next, the .class files are pre-verified. If a .class file passes various security checks, it is tagged as verified. All of the project's verified files are placed in an archive file called Examples.jad. This file is placed in the bin subdirectory. Pressing the Run button on the toolbar causes the Wireless Toolkit to start a mobile phone simulator. The Examples application suite is "downloaded" to the "phone," which displays the suite's midlets in its window. Currently, HelloWorld is the only midlet. Launching this midlet causes the window to display the midlet's main page. Use the red "hang up" button to terminate the midlet.
J2ME APIs HelloWorld extended the MIDlet class and contains references to a Display object (theDisplay) and a TextBox object (mainScreen). TextBox extends the Screen class,
152
153
MIDlet
HelloWorld
Display
getDisplay() 1 setCurrent()
Displayable
+mainScreen
TextBox
<<Abstract>>
<<Abstract>>
Screen
Canvas
paint()
Typically, a midlet creates a collection of displayable objects-- screens and/or canvases: Displayable[] displayables = new Displayable[N]; for (int i = 0; i < N; i++) { // create displayables[i] } The midlet responds to user input commands by selecting a displayable object from this collection, then asking the display to display it with the command: theDisplay.setCurrent(displayables[next]); Here's a more comprehensive class diagram showing the lcdui package:
153
154
Command
0..* <<Int erface>>
CommandListener
0..1 0.. 1 <<Int erface>>
<<Abstract>>
Ticker
0..1
Displayable
title
ItemCommandListener
<<Abstract>>
Screen
Alert
Form
1 * <<Abstract>>
List
TextBox
Item
StringItem TextField
ImageItem DateField
ChoiceGroup
First notice that in addition to text boxes, there are three other types of screens: alerts (a message dialog that flashes on the display), forms (a control panel containing control items such as labels, text fields, and buttons), and lists. A displayable can fire and handle commands. A command is fired when the user presses keypad buttons when the displayable is the current window. When a command is fired, a command object is passed to the commandAction() method of each registered command listener. Typically, the midlet is the command listener. Form items also fire commands. When an item command is fired, a command object is passed to the commandAction() method of each registered item command listener. Typically, the midlet or the parent form is the item command listener.
154
155
Active
Commands and The Midlet as a Command Processor To demonstrate commands and command processing, let's add a new midlet to the Examples project. Pressing the Settings button on the Wireless Toolkit toolbar displays the Settings dialog. Pressing the Add button at the bottom of this dialog allows us to add a new project called navigator contained in the CommandProcessor.class file:
155
156
Running the Command Processor Here are some screen shots of the Navigator running on the simulator. Notice that the opening screen now shows the Examples suite contains two midlets. Selecting the navigator midlet causes the midlet's first screen to appear. The screen is titled "Screen 0" and displays the question "Shall we go to screen 1?". That's all Navigator allows users to do: to navigate from screen i to screen j. Notice that the phone's soft buttons are labeled Back and Menu. The Back button will allow us to return to the midlet's previous screen. The menu button displays a list of commands the current screen can fire:
156
157
Here's what the menu items do: cmmd_0: displays an unimplemented warning screen OK: displays suggested screen (screen 1) Help: displays special help screen" Exit: terminates midlet Cancel: Return to previous screen Here are some shots of these other screens:
157
158
CommandProcessor.java The command processor midlet has much in common with HelloWorld. Instead of a single screen, the constructor will create an array of five screens plus a help screen. The startApp() method will display screen[0] in theDisplay.
158
159
Creating Screens Each screen is created in the constructor by calls to the makeScreen() helper method. CommandProcessor() { theDisplay = Display.getDisplay(this); for(int i = 0; i < MAX_SCREENS; i++) screens[i] = makeScreen(i); String helpText = "Command processors navigate between screens"; helpScreen = new Alert("Help", helpText, null, AlertType.INFO); ((Alert)helpScreen).setTimeout(Alert.FOREVER); helpScreen.addCommand(CMD_BACK); helpScreen.setCommandListener(this); } The makeScreen() method creates a type of screen called an Alert. An alert is a warning or confirmation that flashes on the display, only in our case we are setting the duration of the flash to be forever (users will have to get rid of the alert by navigating to another Study Guide From www.ePlanetLabs.com
159
160
Handling Commands The CommandProcessor implements the CommandListener interface. This means that it must implement a commandAction() method and that it can subsequently be registered as a listener for the screens. A typical commandAction() implementation uses a switch statement that dispatches to a sub-handler based on the type of the input command. In most cases, a new screen is selected and is set as theDisplay's current displayable:
160
161
Simple Menu MIDP provides a screen and an i9tem for making choices. Both implement the Choice interface, which defines three different choice styles: Choice.IMPLICIT, Choice.MULTIPLE, and Choice.EXPLICIT:
161
162
Item
Choice
Screen
List
ChoiceGroup
Using the arrows, the user can highlight an item, then press the select button or the soft button labeled "Main". An alert appears momentarily that displays the index of the item selected.
162
163
Implementation The main menu is created out of a list of string items. The main menu fires a command called CMD_MAIN. The command handler gets the index of the selected item from the main menu. public class Cascade extends MIDlet implements CommandListener { // main menu + items: private Display theDisplay; String[] items = {"Item 1", "Item 2", "Item 3"}; private List mainMenu = new List("Main", Choice.IMPLICIT, items, null); // pre-defined commands: private final static Command CMD_EXIT = new Command("Exit", Command.EXIT, 1); private final static Command CMD_MAIN = new Command("Main", Command.ITEM, 1); public Cascade() { theDisplay = Display.getDisplay(this); mainMenu = new List("Main", Choice.IMPLICIT, items, null); mainMenu.setSelectCommand(CMD_MAIN); mainMenu.addCommand(CMD_EXIT); mainMenu.setCommandListener(this); } // lifecycle methods: protected void destroyApp(boolean unconditional) { } protected void pauseApp() { } protected void startApp() { theDisplay.setCurrent(mainMenu); } // Command handler method: public void commandAction(Command c, Displayable d) { switch(c.getCommandType()) { case Command.ITEM: String text = "Item selected = "; selection += items[mainMenu.getSelectedIndex()]; Alert a = new Alert("Warning", text, null, AlertType.INFO); theDisplay.setCurrent(a); break; case Command.EXIT: destroyApp(false); notifyDestroyed(); break; } // switch } // commandAction() }
163
164
Stack Calculator Navigator is an example of a Menu-Driven user interface. Another common UI is the form or control panel. For example, a stack calculator UI is a form containing a text field that displays the top of the stack, and six buttons labeled +, *, -, /, PUSH, and POP. Pressing one of the arithmetic buttons causes the top two numbers on the stack to be replaced by their sum, product, difference, or integer quotient. The PUSH button pushes the number entered in the Top field onto the top of the stack. The POP button removes the top most number on the stack. Here are screen shots showing the result of 53 PUSH, 12 PUSH, and 5 PUSH:
The stack now looks like this: (5, 12, 53) The following screen shots show the result of +, *, -:
164
165
Pressing + then * causes the following changes to the stack: (5, 12, 53) -> (17, 53) -> (901) Pressing the - button causes an error, because there aren't two numbers left on the stack to be replaced. Implementation The Calculator midlet not only implements the CommandListener interface, it also implements the ItemCommandListener interface. This is the interface for all objects that can handle the commands fired by items on a form.
165
166
Building the Form The constructor creates a new form, calcForm, then uses the Form.append() method to add items such as text fields and buttons to the form: Calculator() { display = Display.getDisplay(this); calcForm = new Form("Stack Calculator"); numField = new TextField("Top: ", "", 50, TextField.DECIMAL); calcForm.append(numField); addButton("+", false); addButton("*", false); addButton("-", false); addButton("/", true); addButton("PUSH", false); addButton("POP", true); calcForm.addCommand( new Command("Exit", Command.EXIT, 1)); calcForm.setCommandListener(this); } Creating and adding buttons is done by a helper method called addButton(). This method creates a StringItem in the form of a button. The command fired by this button will be a custom item command which can be identified by its label, name. The midlet will be the listener for this command. The item is given some layout flags before it is added to the form:
166
167
Executing Commands Another variant of commandAction() must be implemented by ItemCommandListeners. Our implementation is based on a multi-way conditional that uses the command's label to determine which low-level handler should be invoked: void commandAction(Command c, Item item) { try { if (c.getLabel().equals("+")) calcStack.add(); else if (c.getLabel().equals("*")) calcStack.mul(); else if (c.getLabel().equals("-")) calcStack.sub(); else if (c.getLabel().equals("/")) calcStack.div(); else if (c.getLabel().equals("POP")) calcStack.pop(); else if (c.getLabel().equals("PUSH")) { Integer a1 = Integer.valueOf(numField.getString()); calcStack.push(a1); AlertType.INFO.playSound(display); } } catch (Exception e) { String gripe = "Error: " + e; Alert a = new Alert("Error", gripe, null, AlertType.ERROR); display.setCurrent(a); } } A Calculator Bean A midlet may use helper objects (erroneously called beans to emphasize its reusability). Our Calculator midlet uses a calculator bean to handle all of the application-specific logic and data:
167
168
Notice that the numbers stored on the stack are Integers. That's because many PDAs don't support floating point arithmetic. Model-View-Control Pattern The Calculator midlet instantiates the Model-View-Controller design pattern.
View
*
Model
Controller
* 1 1 In this pattern the Model component (CalcBean) is responsible for storing application data (the stack of numbers) and implementing application logic (add, mul, push, etc.) The model does not know about the View and Controller components. Controller components are responsible for receiving and handling user input commands. In out example the Calculator midlet performs this task. View components are responsible for user output. The calcForm plays this role in our example. In general, displayables (screens and canvases) are views.
168
169
Persistence and Record Stores MIDP platforms provide persistence in the form of sequential-access record stores. A record is an array of bytes. In the following example we store pairs of names and phone numbers. The user interface provides typical browser commands:
Implementation Here are the necessary includes: import javax.microedition.lcdui.*; import javax.microedition.midlet.*; import javax.microedition.rms.*; import java.io.*; Data Access Objects A DAO decouples an application from the technology used to access secondary memory. It does this by presenting simple read/write operations to the client, while encapsulating the low-level access details. Our DAO assumes the record store is named "Addresses". An array of 64 bytes serves as our temporary storage for a single record:
169
170
170
171
AddressBook.java The Address Book midlet uses a single form for displaying the name and phone of the current record:
171
172
172
173
void addButton(String name) { Command cmmd = new Command(name, Command.ITEM, 1); StringItem item = new StringItem(name, null, Item.BUTTON); item.setDefaultCommand(cmmd); item.setItemCommandListener(this); int mask = Item.LAYOUT_2 | Item.LAYOUT_CENTER | Item.LAYOUT_EXPAND; item.setLayout(item.getLayout() | mask); recForm.append(item); } Handling Commands The item command handler simply calls the appropriate DAO methods: void commandAction(Command c, Item item) { try { if (c.getLabel().equals("Next")) { nameField.setString(dao.read()); numField.setString(dao.read()); } else if (c.getLabel().equals("Save")) { dao.write(nameField.getString()); dao.write(numField.getString()); } else if (c.getLabel().equals("Del")) { dao.delete(); // delete name dao.delete(); // delete phone } } catch (Exception e) { String gripe = "Error: " + e; Alert a = new Alert("Error", gripe, null, AlertType.ERROR); theDisplay.setCurrent(a); } } void commandAction(Command c, Displayable d) { if (c.getCommandType() == Command.EXIT) { destroyApp(false); notifyDestroyed(); } } J2ME (Part III) Graphics Programming Recall that the device display displays the current displayable, which can be a screen or a canvas:
173
174
Display
getDisplay() setCurrent()
1 <<Abstract>> title
Displayable
<<Abstract>>
<<Abstract>>
Screen
Canvas
paint()
Graphics
To do graphics programming, we need to set the current displayable to a custom canvas: class GraphicsDemo extends MIDlet { private Display theDisplay = Display.getDisplay(this); private Canvas canvas = new DemoCanvas(); public void startApp() { theDisplay.setCurrent(canvas); } // etc. } A custom canvas implements the paint() method: class DemoCanvas extends Canvas { public void paint(Graphics g) { // paint on g } // etc. } A standard example is a paint program that allows the user to move a cursor around the screen with the pointer control. In the "Pen Up" state, no line is drawn as the cursor moves. In the "Pen Down" state, a line is drawn:
174
175
The Paint Midlet The Paint midlet constructor creates a Paint canvas that fires three commands: "Pen Up", "Pen Down", and "Erase":
175
176
176
177
Graphical Contexts and the Point Class Every Canvas subclass must implement the abstract paint() method. This method is automatically called when the device decides the screen needs to be refreshed, or when the application calls one of the variants of the repaint() method. The paint() method is passed a new graphical context object of type Graphics. This object provides methods for drawing shapes, lines, and text. The canvas is provided with a coordinate system. The origin is the upper left corner, the x-axis runs across the top of the canvas, the y-axis runs backwards down the left edge of the canvas. The unit of measurement is the PIXEL. To make things easier, we declare a point class. When a point renders itself, it draws a solid 5 x 5 rectangle: class Point { public int xc = 0, yc = 0; public static final int DIAM = 5; public Point(int x, int y) { xc = x; yc = y; } public Point(Point p) { xc = p.xc; yc = p.yc; } public void paint(Graphics g) { g.fillRect(xc, yc, DIAM, DIAM); } } The Canvas Our PaintCanvas maintains a cursor point and a vector of points contained in the drawing: class PaintCanvas extends Canvas { public static final int DELTA = 5; // cursor speed public Point cursor = new Point(5, 5); public boolean penUp = false; public Vector points = new Vector(); public void erase() { points.removeAllElements(); repaint(); } public void paint(Graphics g) { ... } public void keyPressed(int keyCode) { ... } } The paint() method must clear the canvas by drawing a large white solid rectangle. After the cursor is drawn, the points vector is traversed and each member is drawn:
177
178
Canvases may receive low-level events from the device. When a key is pressed, the keyPressed() method is automatically called. This method moves the cursor slightly, adds the cursor position to the vector if the pen state is down, then asks the device to redraw the graphics: void keyPressed(int keyCode) { switch (getGameAction(keyCode)) { case Canvas.UP: cursor.yc = (cursor.yc < 0)? getHeight():(cursor.yc - DELTA); break; case Canvas.DOWN: cursor.yc = (cursor.yc + DELTA) % getHeight(); break; case Canvas.LEFT: cursor.xc = (cursor.xc < 0)? getWidth(): (cursor.xc - DELTA); break; case Canvas.RIGHT: cursor.xc = (cursor.xc + DELTA) % getWidth(); break; case 0: // no game action, use num pad instead } if (!penUp) points.addElement(new Point(cursor)); repaint(); } Games and Multi-Threading MIDP also requires conforming devices to provide support for multi-threading. This is useful for game programming, where sprites are moved by threads while the main thread listens for user inputs. In this example, a new bouncing "ball" is created each time the user presses 1. Pressing the "Kill" soft button kills all of the balls. Each ball is moved by its own thread of control:
178
179
The Bounce Midlet The Bounce application is a slight variation of the Paint application. The Bounce midlet uses a Bounce canvas instead of a Paint canvas. The bounce canvas only fires a KILL command, which is handled by the midlet by calling the erase() method of the canvas:
179
180
180
181
When the user presses 1, the keyPressed() method creates a new ball and adds it to the vector: void keyPressed(int keyCode) { if (keyCode == Canvas.KEY_NUM1) { Ball b = new Ball(); balls.addElement(b); b.start(); } } Ball Class A ball is like a point derived from Thread. It is declared as an inner class so that it can access the methods and fields of the outer Canvas class. A random number generator is used to compute the initial position of the ball:
181
182
The run() method perpetually calls the move() method, then repaints the portion of the canvas containing the former and current positions of the ball: void run() { while(!halt) { move(); repaint(oldxc - 5, oldyc - 5, 15, 15); // sleep for 10 msecs to be cooperative: try { Thread.sleep(10); } catch(InterruptedException e) {} } } The paint() method simply draws a blue solid rectangle: void paint(Graphics g) { int oldColor = g.getColor(); g.setColor(0, 0, 255); g.fillRect(xc, yc, 5, 5); g.setColor(oldColor); } MIDP/CLDC Clients MIDP/CLDC platforms can also run client software for network applications. For example, a web server might service J2ME and WAP mini-browsers as well as desk-top browsers.
182
183
Browser
WAP Device
J2ME Device
Web Server
<<JDBC>>
DBase
183
184
<<Interface>>
Connection
<<Interface>>
<<Interface>>
InputConnection
OutputConnection
<<Interface>>
StreamConnection
<<Int erface>>
<<Int erface>>
CommConnection
ContentConnection
<<Interface>>
SocketConnection
<<Int erface>>
HttpConnection
An Echo Client Our client simply specifies a URL and a request. The server echos the request back to the client:
184
185
The Sever Proxy A client-side server proxy decouples the application from the technology used to send messages across process boundaries. The main method-- postRequest()-- writes a string into a data output stream that comes from an HTTP connection. The response is read using the getData() method:
185
186
Helper Methods The server will need to know the type of client. This information is determined from the HTTP header, which mentions that the client is a MIDP device: private void setUserAgentHeader(HttpConnection conn) throws IOException { String header = "Profile=" ; header += System.getProperty("microedition.profiles"); header += " Configuration="; header += System.getProperty("microedition.configuration"); conn.setRequestProperty("User-Agent", header); } The getData() method reads from a data input stream associated with the connection. The data is read on character at a time until a sentinel value of -1 signals the end of the message:
186
187
The Client Midlet The midlet uses a form to gather the request and URL. A text box will be used to display the server's response: public class Client extends MIDlet implements CommandListener { // soft button commands: private final static Command CMD_EXIT = new Command("Exit", Command.EXIT, 1); private final static Command CMD_OK = new Command("OK", Command.OK, 1); private final static Command CMD_BACK = new Command("Back", Command.BACK, 1); // Device display window, screens, & fields: private Display theDisplay; private Form mainScreen; private TextField urlField, reqField; private TextBox responseScreen; // server connection: private ServerProxy server; public Client() { ... } // Lifecycle methods: protected void destroyApp(boolean unconditional) { } protected void pauseApp() { } protected void startApp() { theDisplay.setCurrent(mainScreen); } // Command handler: public void commandAction(Command c, Displayable d) { ... } } // Client The Constructor
187
188
The Command Handler: The command handler reads the information in the text fields, then uses the server proxy to connect with the real server: public void commandAction(Command c, Displayable d) { switch(c.getCommandType()) { case Command.BACK: theDisplay.setCurrent(mainScreen); break; case Command.OK: String url = urlField.getString(); String req = reqField.getString(); String resp = server.postRequest(url, req); responseScreen.setString(resp); theDisplay.setCurrent(responseScreen); break; case Command.EXIT: destroyApp(false); notifyDestroyed(); break; } // switch } // commandAction() } A Web-Based Echo Server The echo server is implemented as a pair of servlets. A J2EE compliant web server (such as Tomcat) will pass the client's request to the indicated servlet. The servlet sends an HTML or text response back to the client. We employ the Model-View-Controller pattern on the server-side, too. The role of the controller is played by a dispatcher servlet, which determines which view should be
188
189
displayed. In our servlet the determination of the view depends on the type of client: IE browser, WAP client, J2ME client, I-Mode client, etc: public class Dispatcher extends HttpServlet { // client types: public static final String IE_HEADER = "MSIE 5"; public static final String WAP_HEADER = "UP"; public static final String IMODE_HEADER = "Pixo"; public static final String J2ME_HEADER = "MIDP"; protected void doPost( ... ) { ... } protected void dispatch( ... ) { ... } } The doPost() method is automatically called by the server when HTTP POST requests are received: void doPost( HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { String viewPath = "/unknownView"; try { String userAgent = request.getHeader("User-Agent"); if (userAgent.indexOf(IE_HEADER) != -1) viewPath = "/IEView"; else if (userAgent.indexOf(WAP_HEADER) != -1) viewPath = "/WAPView"; else if (userAgent.indexOf(IMODE_HEADER) != -1) viewPath = "/ImodeView"; else if (userAgent.indexOf(J2ME_HEADER) != -1) viewPath = "/J2meView"; else viewPath = "/IEView"; } catch(Exception e) { } dispatch(request, response, viewPath); } // processRequest() The actual dispatch is done by a special method that asks the server to redirect the request to a particular view: void dispatch( HttpServletRequest request, HttpServletResponse response, String page) throws ServletException, java.io.IOException { ServletContext container = getServletContext(); RequestDispatcher dispatcher = container.getRequestDispatcher(page); dispatcher.forward(request, response); }
189
190
J2ME View Servlet As its name indicates, a view servlet plays the role of a view. It might fetch dynamic content from the model, which might be played by a DAO object connected to a data base using JDBC. In our case there is no dynamic content other than the request itself: public class J2meView extends HttpServlet { protected void doPost( HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { try { response.setContentType("text/plain"); PrintWriter out = response.getWriter(); out.println("Hello J2ME, you sent: "); BufferedReader in = request.getReader(); String msg = in.readLine().trim(); out.println(msg); } catch(Exception e) { } } } J2ME[tm] Wireless Toolkit The J2ME[tm] Wireless Toolkit is for developing MIDP-compliant applications targeted for devices such as cellular phones and two-way pagers. The download includes tools, documentation, an emulation environment, ready-to-run examples, and a module to integrate with Forte[tm] for Java[tm] Community Edition, providing a complete development environment to write and test applications. J2ME Wireless Toolkit installs easily, and development and testing within this GUI environment requires absolutely no extra system configurations. What You Need You will need the following to run the Toolkit on your PC: Hardware
Processor with at least a 166-MHZ CPU (If using with Forte for Java Community Edition, 300-MHZ CPU) Memory 64 Mbytes (If using with Forte for Java Community Edition, 128 Mbytes) Hard Disk Space 15 Mbytes (If using with Forte for Java Community Edition, 30 Mbytes)
Software
Microsoft Windows 98 Operating System J2ME Wireless Toolkit Java[tm] 2 Standard Edition (J2SE[tm]) Version 1.3 JDK must be version 1.3, or during installation you'll be given the options to download J2SE 1.3 or cancel installation.
190
191
Forte[tm] for Java Community Edition (Optional) Any text editor (Needed only if you are NOT using Forte[tm] for Java Community Edition)
Toolkit Components APIs and Demos: Mobile Information Device Profile (MIDP) and Connected Limited Device Configuration (CLDC) APIs are provided, eliminating the need for separate downloads. In addition, the demo applications are MIDP-compliant. Development Tools: Simply naming your project and application enable the Toolkit to write a JAD file. The KToolBar makes it easy to compile, build, and execute a Java application with the Emulator to your target emulation device at the click of a button. In addition, the Emulator supplies run-time logging of events, including method tracing, garbage collection, class loading and thrown exceptions, and the option of running the tools from the command line. J2ME Wireless Module: This plug-in module runs the development tools under Forte for Java Community Edition. This option eliminates the need for a separate text editor and enables developers to write, test, and run applications from within one GUI development environment. Installing the Toolkit To install the Toolkit: 1. Download the Toolkit. 2. Double-click the j2me_wireless_toolkit-1_0.exe installer icon. 3. If you are going to be using Forte for Java Community Edition, select Custom from the Setup Type dialog. 4. Make certain the name of the install directory does not have spaces. 5. When installation is complete, drop the Toolkit icon onto the desktop or Taskbar for convenience. No system configurations are necessary. Once the Toolkit has located the J2SE software and has everything else it needs, you are ready to use the J2ME Wireless Toolkit. Running Example in Toolkit The J2ME Wireless Toolkit supplies example demos, ready to run in the device emulators. Start the Toolkit by:
Or:
191
192
Click the Start button Select Programs Select the directory name you had given at installation time, then click KToolbar.
Opening Screen of the Wireless Toolkit The following steps walk you through running an example demo: 1. Click the Open Project button. A dialog called Open Project appears with the apps directory structure listed. 2. Select example and click Open Project as the image shows:
Another window appears, stating that the project "example" is loaded. 3. In the Device menu, select the desired emulation device for testing, then click the Run button. Pager was selected for this article, the menu button clicked and Done selected, resulting in the following:
192
193
Pager Emulation
4. Test the example in different emulation devices by selecting another emulation from the device menu, then clicking the Run button. Creating New Projects The steps in developing your own projects within the Toolkit is slightly different but equally simple. This article uses the FirstMIDlet example code from the article, "Wireless Application Programming" by Qusay Mahmoud, with the project name TestApplication: 1. Click the New Project button. A New Project window appears, asking for a project name and MIDlet class name.
2. Click Create Project. A Settings for project "TestApplication" window appears. Change any values necessary for your application in this window. The first tabbed pane displays required values, a second pane shows optional values that can be added to the MIDlet, and the MIDlets pane allows other midlets to be added, removed, or edited:
193
194
3. Click OK. The Toolkit creates a directory under apps with the project name you typed. In this case, TestApplication, and a TestApplication window appears, specifying path instructions about where source and resources files need to be saved in the message console:
Save files to the specified directories. 4. Click the Build button. The MIDlet, or MIDlets, if you've added more than one, are compiled and preverified without having to type out long commands in a terminal window. The
194
195
results of the appear in the message console, ending with Build Complete if no errors were encountered. 5. Select a emulation device from the Device menu, then click Run. Test the device and note the system and tracing outputs are displayed on the message console. 6. For more testing, change to another device, and click Run again. The Settings buttons allows you to change values as necessary. The User Guide that comes with the download contains useful information about the application development cycle, MIDlet attributes, the files in each of the installed directories, and device types and portability. It also includes instruction on configuring the emulator, using the Toolkit from the command line, and accessing Toolkit from within Forte for Java Community Edition. PRACTICE QUESTIONS OF JAVA and J2EE
1.
A B C D E F
It is a fault-tolerance mechanism It is achieved by taking cold back ups Each replica attempts to process each request but extra calls may be intercepted via an interceptor State changes are logged and periodically flushed to the replicas State is synchronized only when the primary service fails Each replica is identical to the main service.
Choices A, C and F are correct. Active Replication is a fault tolerance mechanism where each replica is identical to the main service and attempts to service each request. An interceptor is used to block extra responses. Active replication is similar in concept to Hot Backups. Hence choices A, C and F are correct. Active Replication is not achieved through cold backups. In cold backups, the replicas are not constantly updated. Their state is synchronized with the primary service in regular intervals. In the event that the primary service fails, one of the replicas has to be synchronized (perhaps with data from a storage device) before it can service requests. Hence choice B is incorrect. Choice D refers to the concept of Warm Backus. In warm backups, only the primary service responds to requests. However all activity is constantly logged. Periodically these logs may also get flushed to the replicas. When the primary service fails, a replica takes over after its state is synchronized with the logs. Hence choice D is incorrect.
195
196
2 A B C D E
Which of the following are benefits of Server Clustering? Replication High Security Easy Manageability Load Balancing Fault Tolerance
Choices A, D and E are correct. Through the use of replicas, server clusters increase the reliability and availability of a system. They provide a fault tolerance mechanism with load distribution and load balancing capabilities. Hence choices A, D and E are correct. J2EE applications offer security features through Identification, Authentication and Authorization mechanisms. In addition they also provide APIs that allow secure communication, encryption of messages and so on. This is not a feature of server clusters though. Hence choice B is incorrect. Managing multiple servers is always a harder than managing just one server. Hence easy manageability may not always be true with distributed platforms. With J2EE, due to clear roles and responsibilities of tiers and layers, applications may be relatively easier to manage than other distributed systems. However manageability is not the best asset of distributed systems. Hence choice C is incorrect.
196
197
Choice E is correct. In the diagram, A and B are classes, C is an interface and D is a class that implements C. Hence Choice E is correct. Choice A is incorrect because <<Interface>> C is not a class and you can only extend classes, not implement them. Choice B is the reverse of choice A but again incorrect because C is an interface, not a class. Choice C is incorrect because it claims that the interface C implements class D, whereas in reality class D implements interface C. Choice D is incorrect because it claims that D is an interface. And C is a class, while it is the other way round.
A B C D E F
Primary Service and all replicas respond to all requests Primary Service randomly delegates requests to one of the secondary replicas Primary service handles all requests State is periodically synchronized between the Primary service and all replicas It is similar to hot backup It is similar to Warm Backup
Choices C, D and F are correct. In Passive Replication, the primary service handles all requests. The state of the replicas is periodically synchronized. In the event that the primary service fails, one of the replicas takes over after its state is synchronized (with log files, for example.) In concept, passive replication is similar to that of Warm Backups. Hence choices C, D and F are correct. Only in Active Replication, the primary service and all replicas respond to all requests. Hence choice A is incorrect. Choice B seems to indicate that Passive replication uses some kind of load distribution mechanism. Hence choice B is incorrect. Passive replication is similar to warm backups as opposed to active replication, which is similar to hot backups. Hence choice E is incorrect.
4 A
197
198
Choice D is correct. Common Object Request Broker Architecture (CORBA) is a standard for distributed communication involving applications written using different languages. Hence choice D is accurate. Queues are the mechanism by which two parties communicate in a Point-to-Point asynchronous messaging paradigm. Hence choice A is incorrect. Choice B indicates that CORBA is a methodology, as opposed to a standard and is incorrect. Topics are the mechanism through with Publish Subscribe messaging is accomplished. Choice C is incorrect. Although choice E talks about distributed object systems, it is referring to pure Java objects. CORBA is used object distribution involving different languages. Hence choice E is incorrect. 5 A B C D RMI-IIOP does not provide which of the following capabilities? Remote Method Invocation Stub Downloads Objects pass by value (state only) Distributed Garbage Collection
Choices B and D are correct. RMI-IIOP does not support Stub downloads and distributed garbage collection. Hence choices B and D are correct. Both Remote Method Invocation and Objects pass by value are supported by RMI-IIOP. Hence choices A and C are incorrect.
6 A B C D
Which of the following are not true about Screen Scrapers? Screen scrapers function as Terminal Emulators on one end and as Object Interfaces on the other. Screen Scraping may be a useful tool when used in conjunction with the offboard servers. Changes to legacy UI has little or no impact on the new GUI Screen Scraping is best used when the legacy clients have loose coupling with other tiers.
Choices C and D are correct. When using screen scrapers, any changes to the legacy user interface will also affect the new GUI. Also screen scraping is the best alternative only if the existing UI is very tightly coupled with the business tier of the legacy application. Hence choices C and D are false and therefore the correct choices. Choices A and B are true about screen scrapers and hence incorrect.
198
199
7 Which of the following methods may be present in the Home Interface of an Entity Bean? A B C D E create() findByPrimaryKey() remove() locateByPrimaryKey() retrieveBean()
Choices A, B and C are correct. The Home Interface provides methods for creation, location and removal of beans. Hence you could find create(), findByPrimaryKey() and remove() methods in the bean's Home Interface. Choices A, B and C are therefore correct. There are no methods like locateByPrimaryKey() and retrieveBean() in the Home Interface. Hence choices D and E are incorrect.
8 A B C D
Undefined Primary Keys refers to? Refers to Entity Beans that do not use Primary Keys Primary Keys that are defined during development Primary Keys that remain undefined until the bean is deployed Entity Beans cannot have undefined Primary Keys
Choice C is correct. One problem with container-managed persistence in EJB 1.0 was that the bean developer had to define the primary key during development. This forced the developer to make assumptions thus limiting the bean's portability across databases. EJB 1.1 allows the primary key to remain undefined until deployment. Hence choice C is correct. Choice A is incorrect because all entity beans must have a serializable primary key that can be used to uniquely identify an entity bean in the database. Undefined Primary Keys are not defined during development. Hence choice B is incorrect. Choice D is incorrect because it indicates that Entity Beans are not allowed to have undefined Primary Keys. This was true in EJB1.0 but not in EJB1.1.
9 A B C D
Which of the following are valid life cycle states for a Stateless Session Bean? Does not Exist Pooled State Method Ready Pool Passive
199
200
The two valid states in a Stateless Session Bean's life cycle are 'Does Not Exist' and 'Method Ready Pool.' When Beans are not instantiated they are said to be in the 'Does Not Exist' state. Beans transition from 'Does Not Exist' to 'Method Ready Pool' when instantiated. The container does this automatically, as needed. Hence choices A and C are correct. Pooled and Passive are not valid states in the lifecycle of a Stateless Session Bean. Hence choices B and D are incorrect.
10 A B
Both CMT and BMT may be used with Entity and Session Beans. True or False? True False
Choice B is correct With EJB1.1 only Session Beans with <transaction-type> equal to 'Bean' can have beanmanaged transactions. Entity Beans are not allowed to be BMT beans. Hence choice B is correct.
11 A session bean called SomeBean has a method called someMethod(), which calls someOtherMethod (same bean) followed by someOtherBeanMethod() of SomeOtherBean. SomeOtherBean is an Entity Bean with CMT. Which of the following is true?
A B C D
SomeOtherBean has no control on the transaction since it is a CMT bean. SomeOtherBean has full access to the UserTransaction object through which it can control the transaction. SomeOtherBean has access only to the transaction methods in EJBContext, which gives it the power to veto transactions. SomeOtherBean has access on the transaction only if the method had RequiresNew set as its transaction attribute.
Choice C is correct. Only BMT beans have access to the User-Transaction from the EJBContext. The EJBContext provides the methods setRollbackOnly() and getRollbackOnly(), to provide CMT beans access to the transaction. The setRollbackOnly() method gives a bean the power to veto a transaction. Hence choice C is correct. Choice A is incorrect because the entity bean has the capability to veto the transaction. Choice B is incorrect because CMT beans only have the power to veto user transactions. Choice D makes an incorrect argument and is thus wrong.
200
201
A B C D
Maintaining a smaller pool of Stateless Beans to serve a large number of clients. Providing Database Connection Pooling Persistence of Entity Beans Passivation of Stateful Beans
Choice C is correct. Persistence of Entity beans is the ability to save data represented by the bean into a database. It is not a resource management technique. Choice C is false and therefore correct. Maintaining a smaller number of beans to serve a larger number of clients is a very clever resource management technique. It is also an example of the Flyweight Design Pattern. Choice A is thus a resource management technique and therefore incorrect. Database connection pooling, a similar concept as bean pools, is also a good resource management technique. Choice B is therefore incorrect. With Stateful Session Beans, the container uses passivation to manage memory. In passivation the state of the bean is serialized and its memory freed up for reuse by other services. Hence bean passivation is a memory management technique making choice D incorrect.
13 A B C D E F G
Which of the following are invalid states in the life of a Stateful Session Bean? Does Not Exist Method Ready Pool Method Ready in Transaction Method Ready Ready Pooled Passive
Choices B, E and F are correct. The valid life cycle states of a Stateful Session Bean are 'Does Not Exist', 'Method Ready', 'Method Ready in Transaction' and 'Passive'. 'Method Ready Pool' is a life cycle state of Stateless Session Beans. 'Pooled' and 'Ready' are life cycle states of Entity Beans. Hence choices B, E and F are correct.
14 A B C D
What is the sequence of steps in the life cycle of a Stateless Session Bean? class.newInstance(), setSessionContext (ctx), ejbCreate() ejbCreate(), setSessionContext (ctx), class.newInstance() class.newInstance(), ejbCreate(), setSessionContext (ctx) setSessionContext (ctx), ejbCreate(), class.newInstance()
Choice A is correct.
201
202
When Stateless Session Beans transition from 'Does Not Exist' to 'Method Ready Pool', the container invokes newInstance(), setSessionContext() and ejbCreate() methods. Hence choice A is correct. Although choices B, C and D have the same methods, the order in which they appear to be called is wrong. Therefore choices B, C and D are incorrect.
15 A B C D
HTTPS is defined as HTTP with Security HTTP on secure line HTTP over SSL HTTP with SSL
Choice C is correct HTTPS stands for HTTP over SSL. With HTTPS, SSL sits above the TCP-IP layer and below the application protocol layer. Hence choice C is correct.
16 A B C D E
Choice B and D are correct. HTTP (HyperText Transfer Protocol) is a transport mechanism for MIME (Multipurpose Internet Mail Extensions) documents. MIME documents often contain HTML (HyperText Markup Language) code for display in browser windows. HTTP consists of a request sent by the client to the server, followed by a response sent from the server back to the client. HTTP uses TCP/IP as the underlying transport and network protocols. The following is taken from: http://www.w3.org/Protocols/Activity.html "Whenever a client accesses a document, an image, a sound bite etc. HTTP/1.0 creates a new TCP connection and as soon as it is done, it is immediately dismissed and never reused." "HTTP/1.1 fixes this in two ways. First, it allows the client to reuse the same TCP connection (persistent connections) again and again when talking to the same server. Second, it makes sure that the courier carries as much information as possible (pipelining) so that it doesn't have to run back and forth as much. That is, not only does HTTP/1.1 use less TCP connections, it also makes sure that they are better used. The result is less traffic jam and faster delivery." The following is taken from:
202
203
http://www.w3.org/Protocols/HTTP/HTTP2.html "HTTP is a protocol with the lightness and speed necessary for a distributed collaborative hypermedia information system. It is a generic stateless object-oriented protocol, which may be used for many similar tasks such as name servers, and distributed object-oriented systems, by extending the commands, or 'methods', used." Hence choices B and D are correct. Since choices A and C are the opposite, they are incorrect. HTTP can be made secure by using 'HTTP over SSL' or HTTPS. But by itself, HTTP is not secure. Hence choice E is incorrect.
17 A B C D
Asynchronous communication is achieved by using: Remote Procedure Calls RMI/IIOP Message Oriented Middleware CORBA
Choice C is correct. Message Oriented Middleware or MOM is used for asynchronous messaging between applications. Most popular implementations support Point to Point (one to one) and Publish Subscribe (one to many) messaging. Hence choice C is correct. Remote Procedure Calls are used for synchronous communication between applications. CORBA and RMI/IIOP are two protocols that support RPC based communication. Hence choices A, B and D are incorrect.
18 A B C D
Which of the following is not part of the Messaging architecture: Decentralized messaging using IP Multicasting Decentralized messaging using Secure Sockets Layer (SSL) Use of virtual channels called Queues Use of virtual channels called Topics
Choice B is correct. Only choice B is not a standard paradigm in messaging architecture. Hence choice B is correct. IP Multicasting can be used as a technique for decentralized messaging. Queues and Topics are used with Point to Point and Publish Subscribe messaging. Hence choices A, C and D are incorrect.
19 A B C
In P2P, clients send messages to: A designated queue Multiple Queues A specific node for redistribution to subscribers
203
204
Choice A is correct. P2P or Point to Point messaging is used for one to one communication between two components or applications. In the P2P model, message producers send messages to a designated queue. Hence choice A is correct. Although it is possible to mimic Publish Subscribe architecture by sending P2P messages to multiple queues, it is not a standard practice. Hence choice B is incorrect. In Publish Subscribe architecture, messages are sent to a specific node for redistribution to subscribers. Hence choice C is incorrect. CORBA is an RPC protocol and is not used for asynchronous messaging. Hence choice D is incorrect.
20 Happy Joe Banking Corporation is building a Banking application to provide online access to their account holders. They have chosen 2 SUN 450s for their web server cluster and 1 SUN E10000 for their application server. The business requirements indicate that to become a customer, a person must have at least a primary checking account with the bank. Further since the customer will be using the Internet to view confidential information, security is considered paramount. What do you understand about the requirements of the system? A The need for Security is a classic example of a functional service level requirement and the checking account rule, an example of non-functional QoS requirement. B The discussion about Security and the mandatory checking account both illustrate functional service level requirements. C Neither Security nor the mandatory Checking Account is an example of any kind of requirements, theoretically speaking. D Security is an Architectural non-functional requirement and the Mandatory Checking Account a functional design requirement. E They are both examples of Business Use Cases. Choice D is correct. Successful software architecture deals with addressing the non-functional service level requirements of a system. The Design process takes all the functional business requirements into account. Security is considered a non-functional requirement and specific business rules, such as the one described with the checking account are considered functional requirements. D is the only choice that accurately describes this. A is incorrect because the functional and non-functional requirements are flipped over. B is incorrect because only one of them is a functional requirement. C is incorrect because as described above, one of them is a functional requirement and the other, a non-functional requirement. Finally E is incorrect because business analysis may start with use cases (where the checking account rules may be captured), but this discussion is specifically questioning functional vs. non-functional requirements.
204
205
21 In an interview between the senior management of Happy Joe Banking Corporation and the J2EE application architect Scott Khosla, the following points were discussed: I. The system needed to respond within 5 seconds II. The system is needed to have a 99.9% uptime III. HJBC was in the process of acquiring another bank which would add two hundred thousand customers to their already existing half million. IV. Each phase of the SDLC was to have a clear sign off process. V. The development team was expected to provide a detailed unit test plan and user documentation. VI. In order to ensure privacy, HTTPS was to be used. 22 A B C D E What non-functional requirements were discussed? Scalability, Availability, Extensibility, Manageability and Security Performance, Reliability, Elaboration, Transition, Documentation and Security Specification, Elaboration, Construction, Transition, Use Cases and Security Performance, Availability, Scalability and Security Reliability, Availability, Scalability, Manageability and Security
Choice D is correct. The non-functional service level requirements discussed are Performance (system needs to respond within 5 seconds), Availability (system is needed to have a 99.9% uptime), Scalability (additional two hundred thousand subscribers), and Security (HTTPS is to be used.) Hence choice D is correct. There is no mention of extensibility (ability to easily add or extend functionality) and Manageability (ability to monitor the health of the system.) Hence choice A is incorrect. Specification, Elaboration, Construction, Transition, Documentation and use cases are not non-functional service level requirements. Hence choices B and C are incorrect. While scalability and reliability may be related (will the system perform as reliably when more users operate on it), there is no mention of reliability in the question. Hence choice E is incorrect.
23 N-tier applications show better performance than 2-tier applications because they are modular in nature, which means that they can be scaled easily, by tuning components and containers individually. True/False ? A B True False
Choice A is correct. N-Tier applications (especially those based on J2EE) are designed to be very modular in nature. The tiers and layers separate roles and responsibilities of each component and
205
206
container. Hence components and containers can be individually targeted and scaled as needed. This results in better performance. Hence choice A is correct.
24 Moon Microsystems has a web-based solution that was originally built using Servlets. However, in recent months, the IS manager has asked developers to use JSP technology with Java Scriptlets embedded in HTML code. Scott Khosla, the architect, however is insisting that the code be modularized and that EJBs be used instead of Servlets and JSP for business logic processing. In asking developers to modularize existing code, what software development technique is Scott asking the developers to follow? A B C D Code Break up Code engineering Code Tiering Code Factoring
Choice D is correct. Software applications have a tendency to grow in complexity over time. When that happens, they become difficult to extend, maintain and modify. They also become hard to understand. Code factoring is a modularization technique that deals with the separation of responsibilities in code. Factored code has loose coupling and minimal dependencies, making components and code more reusable. Hence choice D is correct. There are no concepts like code break up, code engineering or code tiering. Hence choices A, B and C are incorrect.
A B C D
(i) represents an object and (ii) a class (ii) represents a package and (i) a class (i) represents a class and (ii) an object (i) and (ii) both represent components
Choice C is correct. In the above diagram Aclass represents a class and: Aclass represents an object. Hence choice C is correct.
206
207
26
A B C D E F G
Choice D is correct. Option D shows a diagram with two packages A and B. Package A has a dependency with Package B. Hence choice D is correct. In option A, class A extends class B. Hence choice A is incorrect. In option B, class A implements interface B. Hence choice B is incorrect. In option C, class A has an association relationship with interface B. Hence choice C is incorrect. In option E, Package B has a dependency with Package A. Hence choice E is incorrect. Since options B and E are incorrect, choices F and G are incorrect.
27
207
208
A Changes to classes in the Customer package may only impact the Order package B Changes to classes in the Customer package will impact Order and OrderLine packages. C Changes to the OrderLine package will impact the Customer package D Changes to the Customer package will have no impact on the other two packages Choice A is correct. The package Order has a dependency with the package Customer. Hence any changes in the Customer Package could impact the Order Package. Hence choice A is correct. (Fowler 109)"A dependency between two packages exists if any dependency exists between any two classes in the packages." Since Customer and OrderLine have no dependencies, choices B and C are incorrect. Changes to the Customer package may impact the Order package. Hence choice D is incorrect.
28
208
209
A B C D E
1 A can have 2 Bs associated with it 1 A can have 4 Bs associated with it 1 A can have 2 to 4 Bs associated with it 1 A can have exactly 2 or 4 Bs associated with it The multiplicity indicated is only legal in the Booch method, not in UML
Choices A, B and D are correct. The multiplicity between A and B shown by (2,4) indicates that an A may have exactly 2 or 4 Bs associated with it. Hence choices A, B and D are correct. Choice C is incorrect because a 2 to 4 multiplicity would be indicated as (2..4) The multiplicity shown is perfectly legal in UML. Choice E is therefore incorrect.
29 Fragile Oars, a manufacturer of boating supplies has a mainframe based legacy application for customer and order management. Recently, Fragile Oars embarked on a project to add Internet presence to its products and services and hence created a company website. Since then, its management has realized the importance of having an eFront and wants to start conducting business over the Internet. Fragile Oars wants to use Applets as the front-end. What is the best method to connect to this legacy system?
A B C D
Using the same applets Using different applets Using Java Server Pages Using Java Servlets
Choice D is correct. The best approach in this case is to have the applets talk to Servlets that can act as mediators between the applets and the Legacy system. Hence choice D is correct. Applets and JSP are used to construct the view of an MVC application. They should not be used as controllers for dispatching requests. Hence choices B and C are incorrect.
30 Baby Bell is a new local Telephony provider in Chicago, IL. It has a legacy application for the B2B transactions with Verizon, the Incumbent Local Exchange Carrier (ILEC.) Baby Bell frequently purchases blocks of Telephone numbers from the ILEC using a CORBA RPC call. There numbers are then assigned to the customers in
209
210
sequence. Sometimes customers request vanity numbers, in which case, a custom synchronous query is made on the ILEC's operational support system, to check for number's availability. If Baby Bell were to rewrite its existing legacy code using newer J2EE technology, what technology would you choose so that both the block purchase and the individual query might be accommodated? A Java Applet technology for the CORBA call and custom socket programming for vanity number requests. B Java Servlet API for the CORBA call and JSP for the custom socket programming C Entity EJBs for both D Session EJBs for both E JNDI for both F MQ Series with a JMS based solution for both Choice D is correct. Session beans can be used for making both the CORBA call for block purchase of telephone numbers and the custom synchronous call to request a special vanity number. Hence choice D is correct. Both operations represent business processes involving partner OSS. integration. Applets are not used for modeling the business workflow of a system. Hence choice A is incorrect. JSP represent the view construction process in an MVC application. They should not be used for processing business logic. Hence choice B is incorrect. Entity beans represent the business model of an application and provide a representation of enterprise data. They are not to be used for workflow processing which is better accomplished by using Session Beans. Hence choice C is incorrect. JNDI provides Naming and Directory interfaces not workflow processing. Hence choice E is incorrect. The question specifically says that a synchronous mechanism is to be used for the vanity number request. The CORBA RPC call for TN reservation is also synchronous. MQ Series is a MOM used for messaging. Messaging is an inherently asynchronous communication mechanism. Hence choice F is incorrect.
31 Julia Fractals Inc. is building a J2EE based application for Order Entry and management of their fractal software. Once the order is taken, it is submitted to a relational database. A provisioning system then queries data and makes appropriate calls to various subsystems using JMS on MQ Series. What design pattern is JMS an example of here? A B C D E Observer Mediator Adapter Bridge Visitor
Choice D is correct.
210
211
Bridge (GOF 151)"Decouple an abstraction from its implementation so that the two can vary independently." In this case JMS is the abstraction. The implementation could be MQ Series, TIBCO Rendezvous and Vitria Businessware. Hence choice D is correct. Observer (GOF 293)"Define a one-to-many dependency between objects so that when one object changes state, all its dependents are notified and updated automatically." Hence choice A is incorrect. Mediator (GOF 273)"Define an object that encapsulates how a set of objects interact. Mediator promotes loose coupling by keeping objects from referring to each other explicitly, and lets you vary their interaction independently." Hence choice B is incorrect. Adapter (GOF 139)"Convert the interface of a class into another interface clients expect. Adapter lets classes work together that couldn't otherwise because of incompatible interfaces." Hence choice C is incorrect. Visitor (GOF 331)"Represent an operation to be performed on the elements of an object structure. Visitor lets you define a new operation without changing the classes of the elements on which it operates." Hence choice E is incorrect.
32 What design pattern best explains the use of the stub and the skeleton in CORBA based RPC applications? A B C D E Factory Method Singleton Strategy Proxy Decorator
Choice D is correct. Proxy (GOF 207)"Provide a surrogate or placeholder for another object to control access to it." Hence choice E is incorrect. The applicability section (GOF 208) defines 'remote proxy' as"A remote proxy provides a local representative for an object in a different address space." Using the stub and the skeleton, CORBA based applications provide local representatives for distributed objects. Hence choice D is correct. Factory Method (GOF 107)"Define an interface for creating an object, but let subclasses decide which class to instantiate. Factory method lets a class defer instantiation to subclasses." Hence choice A is incorrect. Singleton (GOF 127)"Ensure a class only has one instance, and provide a global point of access to it." Hence choice B is incorrect. Strategy (GOF 315)"Define a family of algorithms, encapsulate each one and make them interchangeable. Strategy lets the algorithm vary independently from clients that use it." Hence choice C is incorrect. Decorator (GOF 175)"Attach additional responsibilities to an object dynamically. Decorators provide a flexible alternative to subclassing for extending functionality." Hence choice E is incorrect.
211
212
33 An application has three Stateless Session Beans - SB1, SB2 and SB3. The stubs that implement the respective Home Interfaces are SH1, SH2 and SH3. A client application performs a JNDI lookup to obtain a reference to one of these Home Objects. This is then narrowed and used to create the remote reference to the corresponding remote object. What design pattern best explains the creation of the Remote Object, in this case? A B C D E Prototype Builder Factory Method Business delegate Service Locator
Choice C is correct. Factory Method (GOF 107)"Define an interface for creating an object, but let subclasses decide which class to instantiate. Factory method lets a class defer instantiation to subclasses." Hence the closest pattern this concept is similar to is the Factory Method pattern. Therefore choice C is correct. Prototype (GOF 117)" Specify the kinds of objects to create using a prototypical instance, and create new objects by copying this prototype." Hence choice A is incorrect. Builder (GOF 97)"Separate the construction of a complex object from its representation so that the same construction process can create different representations." Hence choice B is incorrect. The following is taken from: http://java.sun.com/blueprints/patterns/BusinessDelegate.html "In distributed applications, lookup and exception handling for remote business components can be complex. When applications use business components directly, application code must change to reflect changes in business component APIs. These problems can be solved by introducing an intermediate class called a business delegate, which decouples business components from the code that uses them. The Business Delegate pattern manages the complexity of distributed component lookup and exception handling, and may adapt the business component interface to a simpler interface for use by views." Hence choice D is incorrect. The following is taken from: http://java.sun.com/blueprints/patterns/ServiceLocator.html "Enterprise applications require a way to look up the service objects that provide access to distributed components. Java 2 Platform, Enterprise Edition (J2EE) applications use Java Naming and Directory Interface (JNDI) to look up enterprise bean home interfaces, Java Message Service (JMS) components, data sources, connections, and connection factories. Repetitious lookup code makes code difficult to read and maintain. Furthermore, unnecessary JNDI initial context creation and service object lookups can cause performance problems.
212
213
The Service Locator pattern centralizes distributed service object lookups, provides a centralized point of control, and may act as a cache that eliminates redundant lookups. It also encapsulates any vendor-specific features of the lookup process." Hence choice E is incorrect.
34 When remote calls are made on the container provided implementations of the EJBHome and EJBObject, various transactional and security checks are applied before the call is actually passed on to the bean instance. The Container provided implementations of EJBHome and EJBObject are performing what Design Pattern's task? A B C D E Command Adapter Bridge Decorator Facade
Choice D is correct. The intent of the Decorator pattern as described by GOF (175) -"Attach additional responsibilities to an object dynamically. Decorators provide a flexible alternative to subclassing for extending functionality." A request intended for a component is routed to the decorator instead. The decorator forwards the request to the component. It may perform pre or post processing tasks before or after forwarding the request. J2EE is filled with examples of the use of design patterns. The container provided implementations of EJBHome and EJBObject decorate bean classes by providing transactional and security functionalities. Choice A is incorrect because Command is used to encapsulate a request as an object (GOF 233.) Choice B is incorrect because Adapter (GOF 139) converts the interface of a class into another interface clients expect. Choice C is incorrect because Bridge (GOF 151) decouples an abstraction from its implementation so that the two can vary independently and choice E is incorrect because Faade (GOF 185) provides a unified interface to a set of interfaces in a subsystem.
35 Compact Computers is a small computer assembly company. Their online application allows customers to pick and choose accessories to build their own PCs. The accessories are: i. Processor - 800Mhz, 1Ghz, 1.2Ghz ii. HDD - 40 GB, 60 GB, 80 GB iii. Memory - 128 MB, 256 MB, 512 MB
213
214
Choice B is correct. Builder (GOF 97) separates the construction of a complex object from its representation so that the same construction process can create different representations. Here the complex object is a computer. A computer is always made up of exactly one processor, one HDD and one Memory stick (problem description.) However there is no predetermined formula for combining the parts. Hence Builder is the best pattern here and B is therefore the right answer. Answer A is incorrect because Factory Method (GOF 107) defines an interface for creating an object but lets subclasses decide which class to instantiate. You may use factories of factories to construct a complex object, but by itself, the Factory method is good for creating one out of many. Example: create one processor out of a set of three processors. Answer C is incorrect because Prototype (GOF 117) specifies the kinds of objects to create using a prototypical instance. Example: Given a processor, if you were asked to create a computer that used multi processors, this would be a good option. Answer D is incorrect because Abstract Factory (GOF 87) provides an interface for creating a family of related or dependent objects. If the question had defined a relation such as 'A computer of 800 MHz processor can only be coupled with a 40 GB HDD and 128 MB RAM stick', this would have been an ideal solution. Answer E is incorrect because Singleton (GOF 127) ensures that a class has only one instance (or a well-defined number of variable instances) and appropriate global pointers are available to the instance(s).
36 Ibid is an e-auction house that auctions refurbished products. Each product has a minimum bid price. Buyers can query the system for a list of products and then select a product to bid on. They can then place a higher bid on the selected product. Transactional Integrity is very important as dirty reads, non-repeatable reads and phantom reads can lead to data inconsistency. What technology combination might be most suitable for addressing Ibid's needs?
A Applets for presentation and JTA/JTS for transactional integrity B HTML and JSP for presentation, and Servlets for data retrieval and transaction management. C Servlets and JSP for presentation, a stateful session bean with DAO for list retrieval and a stateless session bean for transaction management.
214
215
The Model 2 architecture (based on the Model View Controller pattern) suggests that Servlets and JSP be used in the presentation tier. JSP combine template data with dynamic data to display dynamic content to the user. Servlets act as front controllers, and forward requests to appropriate events in the business logic tier. Unless concurrent use of shared data is involved, it may be an overkill to use Entity beans (as in the example of a simple list retrieval.) The list retrieval is therefore best accomplished by using a session bean with a Data Access Object (DAO.) Since the bidding represents concurrent use of shared data, this is best accomplished by using an Entity bean. Choice A is incorrect because this would not be an ideal application for applets. Choice B is incorrect because it suggests the use of Servlets for all retrieval and updates. Although possible, this is not recommended in the J2EE best practices as an ideal way when dealing with complex applications. Choice C is incorrect because it is suggesting that a stateless session bean be used for managing concurrent access to shared data, something best done by entity beans. Choice E is incorrect because though it may be suited for smaller applications that are not very transactional in nature, the discussion specifically talks about the need for transactional integrity. Therefore this is not the recommended solution.
37 Heartbreak Hospital has two applications - Patient Registration System and Patient Billing System. Patient Billing, an older application has CORBA interfaces for updating Billing Information. The newer Patient Registration system was built as a Java based Application. Heartbreak now wants to automatically update Billing Information from the Patient Registration Application. What Java technology may be most suited for this? A B C D E F RMI-JRMP RMI-JNI RMI-IIOP EJB Java IDL Java-CORBA Bridge
Choice E is correct. The following is taken from: http://java.sun.com/j2se/1.3/docs/guide/idl/ "Java IDL adds CORBA (Common Object Request Broker Architecture) capability to the Java platform, providing standards-based interoperability and connectivity. Java IDL enables distributed Web-enabled Java applications to transparently invoke operations on remote network services using the industry standard IDL (Object Management Group
215
216
Interface Definition Language) and IIOP (Internet Inter-ORB Protocol) defined by the Object Management Group." Hence choice E is correct. RMI-JRMP is used for distributed processing in a pure Java environment. Hence choice A is incorrect. There is no indication whether the Patient Billing system supports JNI. Hence choice B is incorrect. RMI-IIOP is useful when dealing with EJB applications. Hence choices C and D are incorrect. There is no such thing as a Java-CORBA bridge. The Java IDL API performs that function. Hence choice F is incorrect.
38 In which of the following cases would an application not necessarily benefit from the use of Enterprise Java Beans? A B C D Small Scale deployment Large scale deployment Transactional in nature No Transactional requirements
Choices A and D are correct. Enterprise Java Beans are best used with large and complex enterprise applications with high deployment and transactional requirements. Hence choices A And D are correct.
39 The container applies what memory management techniques in the case of Session Beans? A B C D Bean Pooling Bean Passivation Bean Persistence Bean Purge
Choices A and B are correct. While EJBs offer business services, EJB Containers offer many peripheral services such as memory management, persistence, transactions and so on. Bean Pooling (in the case of Stateless Session Beans) and Bean Passivation (in the case of Stateful Session Beans and Entity Beans) are two techniques the container uses for managing memory. Hence choices A and B are correct. Bean persistence refers to persisting the data represented by Entity Beans to physical storages such as Relational, Object or other databases. It has nothing to do with memory management. Therefore choice C is incorrect. There is nothing called Bean Purge. Beans are removed when the client calls the remove() method on the Home Interface (Stateful Session Beans) and when the container decides (in the case of Stateless Session Beans and Entity Beans which
216
217
reside in Bean Pools when not in use.) In the case of Entity Beans, the remove() method also deletes the data the bean instance represents. Hence choice D is incorrect.
40 Outstanding Perf is a perfume manufacturing company. The management is currently in the process of architecting a new J2EE based solution for their online catalog. If performance is paramount and session state needs to be managed as well, it would be preferable to use HTTP and HTTPSession object as opposed to using HTTPS. True/False? A B True False
Choice A is correct. The question specifies that performance is important. There is no mention of the security requirements. Apart from providing Session State, HTTPS includes additional functionality for allowing secure communication between the client and the server. Because of all the extra processing with encryption and decryption, HTTPS is slower than HTTP. Hence in this case, it may be preferable to use HTTP (which is stateless) with HTTPSession Object (to store state on the server.) Hence choice A is correct.
41 Staledexho, A renowned catering company has just contracted your services to track their orders. An online menu is available, for each country serviced. Customers choose what they want, the quantity and provide relevant billing information. Fed Ex ships the food in a special container. What classes and APIs are you most likely to use to support Internationalization? A B C D E F Locale Collection Interface ListIterator ResourceBundle KeyStore OutputStreamWriter
Choices A, D and F are correct. The following is taken from: http://developer.java.sun.com/developer/technicalArticles/Intl/IntlIntro/ "Locales are used throughout the Java class libraries to customize how data is presented and formatted. They affect language choice, collation, calendar usage, date and time formats, number and currency formats, and many other culturally sensitive data
217
218
representations. If you intend to create international Java applications, you'll definitely use the java.util.Locale class. There's no getting around it; you'll use Locales to create well-behaved, internationalized, multilingual Java applications. So, if you haven't had time to explore all the JDK 1.1 international features yet, you'll get a clearer understanding of the core of the internationalization model, the Locale, as you read and understand the descriptions and examples in this article. A Locale is a relatively simple object. It identifies a specific language and a geographic region. In fact, the only significant contents of a Locale object are language and country. Although superficially these attributes are not particularly impressive, they represent a very rich and interesting set of information. A Locale object represents the language and cultural preferences of a geographic area. Language is a fairly easy idea to grasp; cultural preferences may not be immediately clear. Dates, time, numbers, and currency are all examples of data that is formatted according to cultural expectations. Cultural preferences are tightly coupled to a geographic area; that's why country is an important element of locale. Together these two elements (language and country) provide a precise context in which information can be presented. Using Locale, you can present information in the language and form that is best understood and appreciated by the user. Resource Bundles - This internationalization feature of the JDK provides a mechanism for separating user interface (UI) elements and other locale-sensitive data from the application logic in a program. Separating locale-sensitive elements from other code allows easy translation. It allows you to create a single code base for an application even though you may provide 30 different language versions. Although you might be predisposed to think of text only, remember that any localizable element is a resource, including buttons, icons, and menus. The JDK uses resource bundles to isolate localizable elements from the rest of the application. The resource bundle contains either the resource itself or a reference to it. With all resources separated into a bundle, the Java application simply loads the appropriate bundle for the active locale. If the user switches locales, the application just loads a different bundle. Resource bundle names have two parts: a base name and a locale suffix. For example, suppose you create a resource bundle named MyBundle. Imagine that you have translated MyBundle for two different locales, ja_JP and fr_FR. The original MyBundle will be your default bundle; the one used when others cannot be found, or when no other locale-specific bundles exist. However, in addition to the default bundle, you'll create two more bundles. In the example these bundles would be named MyBundle_ja_JP and MyBundle_fr_FR. The ResourceBundle.getBundle method relies on this naming convention to search for the bundle used for the active locale. The java.util.ResourceBundle class is abstract, which means you must use a subclass of ResourceBundle. The JDK provides two subclasses: PropertyResourceBundle and ListResourceBundle. If these don't meet your needs, you can create your own subclass of ResourceBundle." The following is taken from: http://java.sun.com/docs/books/tutorial/i18n/text/stream.html "The java.io package provides classes that allow you to convert between Unicode character streams and byte streams of non-Unicode text. With the InputStreamReader class, you can convert byte streams to character streams. You use the OutputStreamWriterclass to translate character streams into byte streams." Thus we can see that Locale, ResourceBundle and OutputStreamWriter play a vital role in Java Internationalization. Hence choices A, D and F are correct.
218
219
42 by: A B C D
The conversion between 16-bit Unicode and 8-bit local encoding formats is done
MessageFormat and NumberFormat Locale and ResourceBundle Properties files InputStreamReader and OutputStreamWriter
Choice D is correct. The following is taken from: http://java.sun.com/docs/books/tutorial/i18n/text/stream.html "The java.io package provides classes that allow you to convert between Unicode character streams and byte streams of non-Unicode text. With the InputStreamReader class, you can convert byte streams to character streams. You use the OutputStreamWriterclass to translate character streams into byte streams." Hence choice D is correct. MessageFormat, NumberFormat, Locale, ResourceBundle and properties files are all used in I18N. These are not however used for conversion between Unicode character format and local 8-bit byte streams. Hence choices A, B and C are incorrect.
43 Fire Hall, manufacturers of fire extinguishers, is building a corporate Intranet and wants its employees to access payroll information via the Internet. They are planning to use Applets, because of its richer GUI capabilities. The View401K applet requires a Java 1.4 plug in on the host where it is being executed. This applet will read data cached on a temporary directory in the host to calculate 401K distributions. What are your observations on the use of Applets for this purpose? A The Applet technology is not a viable solution for this application because applets are subjected to the sandbox model, which prevents them from reading from or writing to the host where they are being executed. B The Applet technology is a viable solution for this application because the Security policy of the Java 2 Platform is totally flexible. Choice B is correct. The following is taken from: http://java.sun.com/docs/books/tutorial/security1.2/overview/index.html "JDK 1.1 introduced the concept of a "signed applet," as illustrated in the next figure. A digitally signed applet is treated like local code, with full access to resources, if the public key used to verify the signature is trusted. Unsigned applets are still run in the sandbox.
219
220
JDK 1.2 introduces a number of improvements over JDK 1.1. First, all code, regardless of whether it is local or remote, can now be subject to a security policy. The security policy defines the set of permissions available for code from various signers or locations and can be configured by a user or a system administrator. Each permission specifies a permitted access to a particular resource, such as read and write access to a specified file or directory or connect access to a given host and port. The runtime system organizes code into individual domains, each of which encloses a set of classes whose instances are granted the same set of permissions. A domain can be configured to be equivalent to the sandbox, so applets can still be run in a restricted environment if the user or the administrator so chooses. Applications run unrestricted, as before, by default but can optionally be subject to a security policy." As we can see, the Java 2 Security model is totally flexible. Hence choice B is correct.
44
A SSL runs above high-level application protocols such as HTTP and LDAP B SSL runs below TCP-IP C SSL runs above TCP-IP and below application protocols D SSL does not have anything to do with either the application or the network layer in the OSI model Choice C is correct. The following is taken from: http://developer.netscape.com/docs/manuals/security/sslin/contents.htm "The Transmission Control Protocol/Internet Protocol (TCP/IP) governs the transport and routing of data over the Internet. Other protocols, such as the HyperText Transport Protocol (HTTP), Lightweight Directory Access Protocol (LDAP), or Internet Messaging Access Protocol (IMAP), run "on top of" TCP/IP in the sense that they all use TCP/IP to support typical application tasks such as displaying web pages or running email servers. The SSL protocol runs above TCP/IP and below higher-level protocols such as HTTP or IMAP. It uses TCP/IP on behalf of the higher-level protocols, and in the process allows an SSL-enabled server to authenticate itself to an SSL-enabled client, allows the client to authenticate itself to the server, and allows both machines to establish an encrypted connection." Therefore choice C is correct. Choice A is incorrect because it suggests that SSL runs above application protocols. Choice B is incorrect because it suggests that SSL runs below TCP/IP. SSL runs between TCP/IP and HTTP. Hence choice D is incorrect.
220
221
45 What happens when the remove() method is called on the Home Interface of an Entity Bean? A B C D E The remote reference is invalidated The bean instance is destroyed The bean instance is Passivated The data represented by the bean instance is deleted from the database The Bean Instance moves from pooled state to ready state
Choices A and D are correct. The remove() method, in the case of Entity Beans, invalidates the client stub, and deletes the data represented by the bean, from the database. Hence choices A and D are correct. The bean instance is returned to the pool. It is not destroyed when the remove() method is called on an Entity Bean. Therefore choice B is incorrect. The container passivates the bean instance whenever required (for memory management.) It is not a consequence of the remove() method though. Hence choice C is incorrect. The Bean instance moves from the Ready State to the Pooled State upon removal, not the other way round as the point suggests. Hence choice E is incorrect.
46 A B C D
What types of transactions are supported by Enterprise Java Beans? Implicit Declarative Transactions Explicit JTA based transactions Either A or B (based on vendor implementation) Both A and B
Choice D is correct. Enterprise Java Beans specification supports both Implicit Declarative transactions and explicit Java Transaction API (JTA) based transactions. Hence choice D is correct.
47 With Entity Beans, the container automatically generates implementations of all find methods at deployment time. True/False? A B True False
221
222
The container only generates implementations of the find methods at deployment time, in the case of Container Managed Persistence.
48 A B C D
What does the ejbCreate() method return in the case of Entity Beans in EJB 1.1? A remote reference to the EJBObject for both BMP and CMP beans The Bean's Primary Key for both BMP and CMP beans A reference to itself in BMP and NULL in CMP NULL value of type BeanPK in CMP and Primary Key in BMP
Choice D is correct. In EJB1.0, the ejbCreate() method returned void. In EJB1.1, a null value of the bean's primary key type is returned by the ejbCreate() method (in CMP.) In BMP, the ejbCreate() method returns the primary key of the newly created entity. Hence choice D is correct. The Container intercepts the return value from the Bean and returns a remote reference to the remote object, to the calling client. Hence choice A is incorrect. Choice B suggests that the Primary Key of the newly created instance is returned in both CMP and BMP. Hence it is incorrect. The Bean instance never returns a reference to itself upon creation. Hence choice C is incorrect.
49 You have just started a new job working for a top finance company and you have been asked to provide a user-friendly interface to an existing mainframe application. You don't have any access to the mainframes source code. What is the best technique for this? A It can't be done. B Use a screen scraper. C Re-write the main frame using Java and high-end Unix servers. Although it may take some time to do this in the long run this will benefit the company. D Write a Java front end then use CORBA to communicate with the mainframe. E Use the Java Native Interface (JNI) to communicate with the mainframe. F Use object Mapping F Use JMS B is correct choice.
222
223
The key to this question is that you don't have access to the mainframes source code. A screen scraper emulates a mainframe terminal. Basically the screen scraper logs on to the mainframe like a normal user and sends requests to the mainframe and then reads the response. The problem with a screen scraper is that if you change any of the mainframes code there is always the possibility that the screen scraper will stop working.Choice A is incorrect because it can be done. Choice C would take far too long, would cost too much and is not what the customer wants. Choice D, E and F are not appropriate are would require access to the mainframes source code. Choice G is incorrect because there is no mention that the mainframe supports a messaging system. Some of them do and even provide interfaces for JMS however as it's not stated in the question then this is not the right answer.
50 The company you have been working for has released the next generation of its sales system. You have several very powerful servers and a few basic servers at your disposal. A network expert has suggested that in order to get the best possible performance out of these machine you use reverse proxy load balancing? What is reverse proxy load balancing? A Splitting requests evenly amongst all back end servers B The proxy sits behind the backend servers monitoring the performance of each one. When it notices one is being used too much it will automatically forward requests to a different server. C Splitting requests amongst all back end servers depending on the amount of spare CPU time each server has available. D A technique used to target certain requests to certain backend servers, e.g. All Servlet requests from one server. All static HTML from another. E A way of filtering out certain requests. It is used to protect against denial of service attacks Choice D is correct. Reverse proxy load balancing is generally used when you have servers with different amounts of CPUs and Memory. You might have some really powerful servers just to be used for SSL sessions and others to handle static html. Using this will maximise the performance of your applicationChoice A is a description of round-robin load distribution. Choice B doesn't describe any particular method of load balancing. Choice C is an inaccurate description of reverse-proxy load balancing and you would need access to the mainframes source code to do this. Choice E is a cross between a firewall and a standard proxy server this does not do any load balancing.
223
224
51 You are working for a web design company and one of your clients would like to convert their website that currently uses Perl and CGI scripts over to a language that is easier to maintain and reuse. Their website is a sports betting website where the customer is able to logon and place bets on a variety of different sporting events. What would you replace this with? A B C D JSP/Servlets JSP/Servlets/EJBs JMS ASP
Choice B is correct. The key to this question is that the site offers the facility to place bets online. Therefore transactions are involved and this means that Enterprise Java Beans need to be used. It is very hard to implement transactions with just Servlets and JSPs. Hence choice B is correct. Choice A is incorrect because transactions are involved. JMS is the messaging package of the J2EE and therefore C is incorrect. And choice D well, enough said!
52 You are in charge on converting an existing web based solution over to the appropriate J2EE technology. What should you use? The website offers the customers price comparisons on a variety of different products. Revenue is generated by click through sales when the customer has found the best price. A B C D JSP, Servlets JSP, Servlets, EJBs Applets, EJBs No need to change it PERL/CGI scripts is the best solution.
Choice A is correct. The key to this question is that the revenue is generated by click through sales; this implies that there are no transactions involved. If transactions were involved then you would use EJBs as well. Choices B and C are incorrect because there are no transactions involved in this application. PERL/CGI scripts are harder to maintain than Java code so choice D is not the best option.
53 Your 3-tier application has been deployed in a production environment and has been running smoothly for over 3 months. However recently due to a Television campaign you're getting 3 times the normal volume of traffic. To cope with this you decided to introduce Round-Robin load balancing. How is round robin load balancing going to help with the extra traffic? A Splitting requests evenly amongst all back end servers B The proxy sits behind the backend servers monitoring the performance of each one. When it notices one is being used too much it will automatically forward requests to a different server.
224
225
C Splitting requests amongst all back end servers depending on the amount of spare CPU time each server has available. D A technique used to target certain requests to certain backend servers, e.g. All Servlet requests from one server. All static HTML from another. Choice A is correct. Round-Robin load balancing is the process of splitting requests evenly irrespective of the request type (i.e. SSL, JSP, HTML). If you have 3 servers as the first request comes in it goes to the first sever, second request to the second server and the third request to the third server. As the fourth request comes in the process starts again and so this request is forwarded to the first server. Choices B and C are not descriptions of any known load-balancing technique. Choice D is a description of reverse proxy load balancing. This is generally used when you have servers with different amounts of CPUs and Memory. You might have some really powerful servers just to be used for SSL sessions and others to handle static html. Using this will maximise the performance of your application.
54 A Fortune 500 company wishes to add new functionality to its existing sales system and has contracted you as the lead architect for the project. The legacy system has been written in C++ and they wish to keep this system running although they may switch over to full Java solution later, depending on the performance of the new extra functionality. How will connect to this legacy system? A Wrap the application using JNI and make it accessible using RMI. B Rewrite the C++ code in Java. This shouldn't be too hard because it's converting from one object-orientated language to another. C Use a screen scraper. D Use CORBA to talk to the C program then get the CORBA to talk to the RMI server. Choice A is correct. JNI stands for Java Native Interface and is used to allow Java to communicate with programs written in languages like C. In effect you are wrapping the C code to make it available to Java. For example you will wrap a C method called debitAccount(int amount) with a similar Java method, the Java method will just call the C method. This means you can now make the method accessible via RMIChoice B is incorrect because this is not what customer wants, you must stick to the requirements. It would be inappropriate to use a screen scraper here so choice C is incorrect. Although choice D might be possible, to get this to work would take far more work than is actually required. You would need to get the C and CORBA programs working first then try and interface CORBA and RMI, which is not necessary, in this case.
225
226
55 The IT company you are working currently doesn't offer the facility for customers to buy PCs bundled with printers. Luckily they have just struck a deal with another printer company. The list of printers they offer is maintained in a database that runs on one of the printer companies servers. You need to connect to this database however you don't have a JDBC driver that you can install on the server. The database server does have an ODBC driver installed on it. How do you connect to the database? A You can't, change the data store. B Get the printer company to write a web page that you can pass SQL requests to. (You would simply send SQL queries as POST requests and the output would be the ResultSet) This should be implemented securely using SSL with client and server authentication C Wrap some JNI access code around the OBDC driver then connect using JDBC. D (Don't implement the solution using Java. E Send the database requests as JMS method calls F Use the JDBC-OBDC bridge driver. Choice F is correct. The key to this question is that with the JDBC-ODBC you are not connecting to the database directly you are connecting to the ODBC driver instead. So it doesn't matter what the database is as along as there is an ODBC driver available.Choice A is incorrect because it can be done. Although choice B may work it is not the best solution, the JDBC-ODBC Bridge is the best solution. You don't need to wrap JNI code around the ODBC driver to connect to it. Hence choice C is incorrect. Choice D is incorrect because it is possible to connect to the data source using Java. Choice E is incorrect because there is no mention of any Message server in the question and this is not suitable technology for the job.
56 A work colleague has been describing a mainframe application that your company uses to maintain their sales data. He says that the next application you will need to design will involve screen scraping, as he can't see how else the connection to the mainframe will be possible. What is screen scraping? A A plastic tool to get ice off a car windscreen. B A program that interacts with a mainframe passing requests from the users directly to custom written code that you have added in the mainframe. C A program that emulates a mainframe terminal and passes user input to the mainframe. D A program that's supplied by the mainframe for Java programs to interact with. E Your colleague is wrong. It will be quite easy to connect directly to the mainframe using Java. F A program that uses JNI to access the mainframe. G A program that use JMS to send messages to the mainframe. Note this only works if the mainframe has a message server built into it. Choice C is correct.
226
227
A screen scraper emulates a mainframe terminal. Basically the screen scraper logs on to the mainframe like a normal user and sends requests to the mainframe and then reads the response. The problem with a screen scraper is that if you change any of the mainframes code there is always the possibility that the screen scraper will stop working.Choice A maybe true but it's not the right kind of screen scraper! Choices B and F require that you have access to the mainframes source code. Screen scrapers are written as and when they are needed, the mainframe vendor does not supply them so choice D is incorrect. Your colleague is right. Therefore choice E is incorrect. Choice G is incorrect because although you can communicate with mainframes via JMS the process is different from screen scraping.
57 You are working for a company with a worldwide presence; their offices are spread across many countries and over many computer networks. Virtual private networks have been set up to increase security. What are Virtual Private Networks are where are they created? (VPNs) A A network created between two other networks (these are not located in the same place, geographically). Encryption and Authentication are used in the VPN. Normally the VPN is a network on top of an untrusted network (like the Internet). B The area between two firewalls. You let traffic from the Internet into this area (through the first firewall) but not through the second firewall (to your secure network). C The secure (inner) network as described in answer B. D A network created between two other networks (these are not located in the same place, geographically). Encryption and Authentication are NOT used in the VPN. Normally the VPN is a network on top of a trusted network (like the Internet). Choice A is correct. The answer given in choice A explains what a Virtual Private Network is (VPN). Choice B describes a DMZ; choice C the local area network in the DMZ and choice D is incorrect because encryption and authentication are used in the VPN.
58
A The process of converting a class diagram to Java code. B A program that emulates a mainframe terminal and passes user input to the mainframe. C The process of building object wrappers around Java interfaces. This allows the legacy system to interact with your Java application. D The process of building object wrappers around legacy interfaces. This makes the legacy system available in an OO fashion. Choice D is correct.
227
228
Object mapping is used when accessing legacy systems. You need access to the legacy system's source code in order to do this. Choice A sounds plausible but is incorrect. Choice B is a description of a screen scraper. There is no need to build object wrappers around Java interfaces. Choice C describes the opposite. Hence choice C is incorrect.
59 You are the lead architect for a project that will require you interfacing with existing CORBA systems. You are planning to use Java IDL to integrate with these other systems. Which of the following statements about Java IDL are true? A Allows Java to use CORBA B Should be used when most of your new Java applications will be entirely Java based. C Should be used if you have already been using CORBA for a while and wish to carry on with some CORBA systems D Java IDL has nothing to do with CORBA. To communicate with CORBA you will need to use JNI (Java native interface) and J2C (Java 2 CORBA)t +Same as E expect you won't need to use JNI. E Java IDL should be used when servicing messaging requests from CORBA clients. Choices A and C are correct. The following is taken from:http://java.sun.com/j2se/1.3/docs/guide/idl/index.htmlJava IDL adds CORBA (Common Object Request Broker Architecture) capability to the Java platform, providing standards-based interoperability and connectivity. Java IDL enables distributed Web-enabled Java applications to transparently invoke operations on remote network services using the industry standard IDL (Object Management Group Interface Definition Language) and IIOP (Internet Inter-ORB Protocol) defined by the Object Management Group. Runtime components include Java ORB for distributed computing using IIOP communication. Choice B is incorrect because you should use RMI-IIOP instead of Java IDL. Choices D and E are not true as Java IDL adds CORBA capability to the Java platform. Choice F is incorrect because Java IDL shouldn't be used when servicing requests from CORBA clients and the reference to messaging is a red herring.
60 You are designing an Enterprise Application to provide a way for customers to buy products from many companies through one standard site. The application servers you have use the EJB specification 1.1. You have a customer bean and are not sure whether to use CMP or BMP. When should you use CMP? A B C D When performance is essential and you are storing standard data types. When performance is not essential and you are storing standard data types. When performance is essential and you are storing complex data types. When performance is not essential and you are storing complex data types.
Choice B is correct.
228
229
Please note that this is referencing EJB1.1This is a time dependent question as technologies have changed. When Sun wrote the EJB specification 1.1 Application Servers weren't very efficient at generating SQL used for persistence and it used to be recommended that you use BMP instead. However App Servers have improved and some would argue that CMP is now more efficient than BMP. In the SCEA guidebook by Cade it says BMP will out perform CMP. When the exam is updated to EJB 2.0, the answer to this question would probably change.Choice A is incorrect because BMP can be more efficient than CMP. CMP cannot cope with mapping complex data types to a database very efficiently. Hence choice C is incorrect. Even if performance is not an issue, it is still recommended that you use BMP when storing complex data types. Therefore choice D is incorrect.
61 You've written all the UML diagrams you need for your companies online store. Other developers and architects have approved them. Now you are deciding which Enterprise Beans will use Container Managed Persistence (CMP) and which will use Bean Managed Persistence (BMP). When should you use BMP?
A B C D
When performance is essential and you are storing standard data types. When performance is not essential and you are storing standard data types. When performance is essential and you are storing complex data types. When performance is not essential and you are storing complex data types.
Choices A, C and D are correct. Please note that this is referencing EJB1.1This is a time dependent question as technologies have changed. When Sun wrote the EJB specification 1.1 Application Servers weren't very efficient at generating SQL used for persistence and it used to be recommended that you use BMP instead. However App Servers have improved and some would argue that CMP is now more efficient than BMP. In the SCEA guidebook by Cade it says BMP will out perform CMP. When the exam is updated to EJB 2.0, the answer to this question would probably change.Choice C is incorrect because using Container Managed Persistence will increase the portability of the Enterprise Bean and should be used wherever possible.
62 Your company has won a contract with a major supermarket company to allow customers to do their grocery shopping online. As this will involve a huge number of shoppers you have decided to opt for a J2EE solution. When creating the Enterprise Beans to be used in this application what components do you need?
229
230
A A Home interface, A Remote Interface and a class that implements either the SessionBean or EntityBean interfaces. B A Home interface and a class that implements either the SessionBean or EntityBean interfaces. C A Remote interface and a class that implements either the SessionBean or EntityBean interfaces. D A Remote interface and a class that implements the EnterpriseBean interface. E An EJBObject interface, a Remote interface and a class that implements either the SessionBean or EntityBean interfaces. F An EJBObject interface, a Home interface and a class that implements either the SessionBean or EntityBean interfaces. Choice A is correct. You need a Home interface that has create() and find() methods, a Remote interface to define your business methods, and a class that implements either the SessionBean or EntityBean interfaces.Choice B is incorrect because you also need a Remote interface. Choice C is incorrect because you also need a Home interface. Choice D is incorrect because you need the Home interface and a class that implements either the SessionBean or EntityBean interfaces. Choices E and F are incorrect because you don't need an EJBObject interface.
63 What is the difference between Stateful session beans and stateless session beans? A Stateful session beans are pooled and Stateless session beans aren't. B A Stateful session bean can persist its state through a server crash but a Stateless session bean can't. C A Stateful session bean can remember its state with a client, like a conversation but a Stateless session bean can't. D A Stateful session bean uses a Primary Key interface to maintain persistence. Choice C is correct. An example use for a stateful session bean would be a shopping basket because it maintains its state. However a stateless session bean can't and instead should be used as a service e.g. credit card validation. A stateful session bean cannot survive a server crash, as none of its data is permanently stored like Entity beans.Choice A is incorrect because Stateless session beans are pooled. Choice B is incorrect because a stateful session bean cannot survive a server crash. Choice D is incorrect because the data in a stateful session bean is not stored on a database and therefore there is no Primary Key interface for stateful session beans.
64
What is the difference between stateful Session beans and Entity beans?
230
231
Choices B and C are correct. Entity beans represent data on a database whereas session beans represent workflow. It is very expensive to create Entity beans and the code can become quite complicated. Hence you should use the Session-Faade pattern, where the customer talks to a Session bean which in turn talks to the Entity bean.Choice B is incorrect because session beans cannot survive a server crash and in choice D the description is the other way around.
65 You have an application that will be used for customers to buy service engineers time and extend warranties online. You have several different Enterprise Beans in this application for example, Customer, Warranties, CreditCardValidation etc. It's a long time since you've coded EJBs (normally your time is spent designing applications at a higher level) and you've forgotten which methods should go in which interface. What methods do you put in the Remote interface? A Defines create(), find(), remove(Object) methods. B Defines signatures of EJB's business methods. C Defines the persistence of the bean, e.g. how to persist etc. D Defines all methods that the client can call on the EJB. E You don't need a Remote interface for an EJB. An EJB consists of a Home interface and an EJBObject interface.
Choices B and D are correct. The Remote interface is used to define all of the methods that can be called by the client on the Enterprise Bean. If you try and call a method that exists in the Enterprise bean class but hasn't been defined here you will get a RemoteException.The methods in choice A are defined the Home interface. Choice C describes information that would be found in the deployment descriptor and application server. Choice E is incorrect because a remote interface (that implements javax.ejb.EJBObject) is required.
66 You are designing an Enterprise Bean to represent a customer in your new application. You have many methods for this EJB for example:createAccount()deductAmount()create()find()Which of these methods needs to go in the Home Interface and what is it used for? A B Defines create(), find(), remove (Object) methods. Defines signatures of EJB's business methods.
231
232
C Defines the persistence of the bean, e.g. how to persist etc. D Defines all methods that the client can call on the EJB. E The createAccount(), deductAmount() methods need to go in the Home interface as it defines the business methods. Choice A is correct. The Home interface defines the create(), find(), and remove() methods.The Remote interface is used to define all of the methods that can be called by the client on the Enterprise Bean. If you try and call a method that exists in the Enterprise bean class but hasn't been defined in the remote interface, you will get a RemoteException.Choice B is incorrect because these are methods defined in the Remote interface. Choice C describes information that would be found in the deployment descriptor and the application server. Choices D and E describe the Remote interface.
67 A B C D
Select the most appropriate use for an Entity Bean? Store state for a particular client. To store data permanently such as financial data. Store state for any client, not any in particular. Provide a service to the client.
Choice B is correct. The key to this question is"select the most appropriate" there are a two possible right answers. (B) Is the most correct because it has the word permanently in the answer. Entity beans represent data on a database. It might be possible to argue that (A) is also right because maybe that is a customer Entity Bean storing their address and personal details. But there is no reference to permanent data storage. Hence (B) is the better answer.Choice C would require either a stateless or stateful session bean. The reason it could be either is because it says"not any particular client". Choice D would typically require a stateless session bean.
68 You've managed to work out what the next big online shop will be way ahead of everyone else, and are currently designing it. Although the design is still in a rough stage and you have yet to secure sponsors to take it into production you have already decided on some of the Enterprise Beans that you will need. You know you will need a customer EJB, Shopping basket EJB, another EJB to be used when accessing data on a legacy system. You know you will need many more but what would be an appropriate use for a Stateless Session Bean? A B C D To represent a shopping basket. Provide a service to the client. Store state for a particular client. To access data on a legacy system.
Choice B is correct.
232
233
Stateless session beans can't remember which client they were last talking to and any data they might hold is not saved in a database. Stateless session beans are used to provide a service. E.g. credit card validation. Choice A is incorrect because a shopping basket would require state (a Stateful Session Bean). Choice C would require a Stateful Session Bean or Entity Bean depending on whether the data needed to be permanently stored for that client. Although choice D is possible this isn't the most appropriate use for a stateless session bean.
69 In a Catalog Enterprise Bean, (used in an online sports shopping site) you have code that will be executed when ejbPassivate() and ejbActivate() are called. The code is used to perform basic house keeping tasks. You need to know when the code will execute so which of the following statements are true? A B C D ejbPassivate() is called prior to passivation. ejbPassivate() is called immediately after passivation. ejbActivate() is called prior to activation. ejbActivate() is called immediately after activation.
Choices A and D are correct. The descriptions in choices B and C are the wrong way round.
70 You have never worked with J2EE application servers before and are about to release your first 3-Tier application. Your company already has a strong customer base so you expect a huge volume of traffic over the first few days of the launch. You're not to sure how your application server will cope with all the customers but a colleague reassures you that the Enterprise beans are pooled and the performance of the system will be fine. What are the benefits of bean pooling? A Improves response time between client and bean B Means you need fewer instances of the beans and therefore increases scalability. C Means you need fewer instances of the beans but this does nothing for increasing scalability. D Means you keep more instances of the beans in memory but this improves performance of the Application server ten fold. Choice B is correct. Bean pooling is just like database connection pooling. There is no point having a few thousand instances in memory when you could get by with 50. When a bean is in a
233
234
pooled state it is not associated with any particular client.The following are wrong because:You could argue that by bean pooling it reduces the load on the application server and this indirectly improves the response time. However this choice (A) is not the most appropriate. Choice C is incorrect because bean pooling does increase scalability. Choice D is incorrect because you keep fewer instances of the beans in memory.
71
Which of the following statements are true with regards to bean pooling?
A The EJB specifies how many instances to pool at deployment time. B Although bean pooling improves performance it doesn't offer any advantages in Scalability terms. C If your server has enough memory you should avoid bean pooling. D The application server depending on the beans usage decides the number of instances to pool. Choice A is correct. You can say how many instances should be pooled at deployment time.Choice B is incorrect because bean pooling does increase scalability. There is no need to avoid bean pooling and if you didn't do it the amount of memory you would need would be far too expensive. Hence choice C is incorrect. The number of beans to pool is set at deployment time. Hence choice D is also incorrect.
72 Its not just Stateless Session beans that are pooled, Entity beans are as well. True/False? A B TRUE FALSE
The above statement is true. Yes they are both pooled to reduce the load on the Application server.
73 A B C D
When should RMI over IIOP be used? RMI over IIOP is used all the time with standard RMI. When performance doesn't matter. When you are dealing with a pure Java system, no legacy systems etc. When RMI is used with Enterprise Javabeans.
Choice D is correct. The following is taken from:http://java.sun.com/j2se/1.3/docs/guide/idl/jidlFAQ.htmlRMIIIOP - If you are writing most of your new applications using the Java programming language, but need to maintain legacy applications written in other programming
234
235
languages as well, you will probably want to use Java RMI with its IIOP compiler option.Choice A is incorrect because JRMP is the standard for RMI. Whether you use IIOP or JRMP is irrelevant in terms of performance. Hence choice B is incorrect. You should use standard JRMP in the case choice C describes.
74 As part of your online shopping site you need customers to be able to pay for their goods securely. You have decided that you will use SSL with 128bit encryption to transmit the credit card details. What port number does HTTPS run on and can it be configured to run elsewhere? A B C D E 8443 and yes it can run elsewhere 8443 and no it can not run elsewhere it must run on this port 443 and yes it can run elsewhere 622 and yes it can run elsewhere 443 and no it can not run elsewhere it must run on this port
Choice C is correct. As a standard HTTPS runs on port 443 but it can be configured to run elsewhere. With web servers such as Tomcat the SSL port is 8443.
75 You are designing an application that will use JRMP over IIOP. The Network engineers at your company would like to know what port you intend to use to access the internet and other networks so that they can make it available on the companies firewall. What port do you ask for? A B C D E 443 535 1099 8443 80
Choice C is correct. JRMP runs on port 1099 as standard although it is possible to run it on a different port.Choice A is the standard SSL port number. IIOP uses port 535. Web servers such as Tomcat use the port 8443 for SSL. And choice E is the standard HTTP port. Although you wish to access the internet you are not making http requests.For more information please refer to the following URL:http://www.iana.org/assignments/port-numbers
76 A B C
You need to replace ASP scripts. What J2EE technology do you use? JMS, JSP and Servlets JSP and Servlets JTA, JSP and Servlets
235
236
Choice B is correct. ASP and JSP have a very similar syntax so it makes sense to replace ASP with JSP. You should also try and extract parts from the ASP script that perform controller operations or other processing and implement them as Servlets. Choice A is incorrect because the Java Message Service and has nothing to do with web pages. There is no mention of transactions in the questions and if there was it would probably be better to use EJBs as well so choice C is incorrect. Although choice D is possible this is not the best answer as there would be too much work involved in creating the Applets.
77 As part of your new application you need to connect to a database. You don't have any access to the database server so you can't change the ODBC driver that's currently installed. How do you connect? A B C D CORBA JMS-JNI JDBC-ODBC bridge JDBC
Choice D is correct. The key to this question is that you don't need to install a new ODBC driver or anything like that, you can connect to the database directly via JDBCCORBA is used for distributed systems not database connectivity so choice A is incorrect. Choice B wouldn't work and choice C isn't necessary, as the question doesn't say that you can't use a normal JDBC driver.
78 A B Java. C D
When would you choose RMI-JRMP over CORBA? When you are designing a pure Java solution. When you are designing a solution that will not be pure Java but will mainly be in When you will interact with applications written in other languages such as C/C++ When performance is essential.
Choice A is correct. The following is taken from:http://java.sun.com/j2se/1.3/docs/guide/idl/index.htmlThis is a fundamental question and it's important to understand the distinction between these two ways of integrating the Java programming language with CORBA. Java IDL is for CORBA programmers who want to program in the Java programming language based on interfaces defined in CORBA Interface Definition Language (IDL). This is "business as usual" CORBA programming, supporting Java in exactly the same way as other languages like C++ or COBOL. RMI-IIOP (Remote Method Invocation over Internet
236
237
Inter-ORB Protocol) is for Java programmers who want to program to the RMI interfaces, but use IIOP as the underlying transport. RMI-IIOP provides interoperability with other CORBA objects implemented in various languages - but only if all the remote interfaces are originally defined as Java RMI interfaces. It is of particular interest to programmers using Enterprise JavaBeans (EJB), since the remote object model for EJBs is RMIbased.You would use RMI-IIOP in choice B. In choice C you would use CORBA. CORBA actually slightly outperforms RMI. Hence choice D is also incorrect.
79 You have a distributed system that is not made up entirely of Java objects (some of them are CORBA) what technology should you use? A B C D RMI-JRMP CORBA Rewrite the objects so the system in entirely Java based RMI-IIOP
Choice B is correct. The following is taken from:http://java.sun.com/j2se/1.3/docs/guide/idl/jidlFAQ.htmThere are several scenarios that will define how you will want to create distributed CORBA applications. Here are some of them: Java IDL - If you have been developing CORBA applications using IDL for some time, you will probably want to stay in this environment. Create the interfaces using IDL, and define the client and server applications using the Java programming language to take advantage of its "Write Once, Run AnywhereTM" portability, its highly productive implementation environment, and its very robust platform. RMI-JRMP - If all of your applications are written in the Java programming language, you will probably want to use Java RMI to enable communication between Java objects on different virtual machines and different physical machines. Using Java RMI without its IIOP option leverages its strengths of code portability, security, and garbage collection. RMI-IIOP - If you are writing most of your new applications using the Java programming language, but need to maintain legacy applications written in other programming languages as well, you will probably want to use Java RMI with its IIOP compiler option.RMI-JRMP would be used in an all Java solution so choice A is incorrect. There is no need to rewrite the objects so the system in entirely Java based so choice C is incorrect. There already are CORBA objects so although choice D is possible it is not the most appropriate answer.
80
A This is the standard, and is used all the time. B When you have to use a database that has an ODBC driver but the JDBC driver doesn't exist.
237
238
When you are connecting to a database running on a Windows server (NT, 2000 When you need faster response times.
Choice B is correct. You are basically connecting to the ODBC driver as opposed to directly to the database.Choice A is incorrect; normally you would just connect directly via JDBC. Whether you are connecting to a database running on a Windows server (NT, 2000 etc) makes no difference at all. Hence choice C is incorrect. The JDBC-ODBC bridge will not increase performance as described in choice D.
81 You have had enough with all the UML tools on the market as none do exactly what you want them to. So you've decided to design your own. However when designing it you realize that certain parts will be really complicated for example you have a Diagram object that is made up of lots of other objects. This diagram object can be used for a variety of different diagrams including class and sequence diagrams. When you create it you only want to specify its type and content. What pattern should you use? A B C D Abstract Factory Factory Method Builder Decorator
Choice C is correct. The builder pattern separates the construction and representation of an object. The client is shielded from the objects construction only needing to specify it's content and type.The Abstract Factory pattern is used for creating many objects that are dependent on each other. Hence choice A is incorrect. The Factory Method pattern provides an interface for creating an object that allows either sub classes or helper classes to create that object. Hence choice B is also incorrect. The Decorator pattern isn't used to build objects. It adds extra functionality to existing objects. Hence choice D is incorrect.
82 You need to interface with an existing application. You have full access to the source code and UML diagrams from the existing application. Part of the requirements implies that you will need to connect unrelated objects together. You want to know whether the Bridge pattern or the Adapter pattern will be suitable. Which of the following are true about the Bridge and Adapter patterns? A The Adapter pattern implements an interface known to its clients and provides an instance of a class not known to its clients. B The Bridge pattern implements an interface known to its clients and provides an instance of a class not known to its clients. C The Adapter pattern creates a separation between abstractions and classes that implement those abstractions.
238
239
D The Bridge pattern creates a separation between abstractions and classes that implement those abstractions. Choices A and D are correct. As the answers state the Adapter pattern implements an interface known to its clients and provides an instance of a class not known to its clients. And the Bridge pattern creates a separation between abstractions and classes that implement those abstractions. Choices B and C are incorrect because the descriptions are the other way around.
83 As part of your new application you need to create a custom class loader so that you can implement with custom security. So you need to create objects without knowing the class of the objects or how to create them. What pattern should you use for this? A B C D E Abstract factory Factory Method Builder Prototype Singleton
Choice D is correct. This pattern is used to create new objects by copying its prototype.The Abstract factory pattern is used for creating many objects that are dependent on each other. Therefore choice A is incorrect. The Factory Method pattern provides an interface for creating an object defers creation to either sub classes or helper classes. Hence choice B is incorrect. The Builder pattern separates the construction and representation of an object. The client is shielded from the objects construction only needing to specify it's content and type. Choice C is therefore incorrect. The Singleton pattern creates either one or a variable number of instances of a class making choice E incorrect.
84 You are creating a web application for an online product ordering system. You will be using data from several different databases and to reduce the load on the databases you have decided to use connection pooling. You have a ConnectionPool class and you want one pool for each database however you will have to connect to a variable number of databases. What pattern should you use? A B C D E Abstract factory Factory Method Builder Prototype Singleton
Choice E is correct.
239
240
The Singleton doesn't just create a single instance it can also be used to create a variable number of instances of a class.The Abstract factory pattern is used for creating many objects that are dependent on each other so choice A is incorrect. The Factory Method pattern provides an interface for creating an object defers creation to either sub classes or helper classes. Hence choice B is incorrect. The Builder pattern separates the construction and representation of an object. The client is shielded from the objects construction only needing to specify it's content and type. Choice C is hence incorrect. The Prototype pattern is used to create new objects by copying its prototype. Choice D is therefore incorrect.
85 You are interfacing with a server that is running as a JMS server and email server. Basically your company has an online shopping store and when a customer buys something you need to send an email confirmation. Email requests will be sent as JMS messages so as to reduce the load on the email server. Does JMS provide the implementations to allow you to send these messages to the email server? True/False? A B TRUE FALSE
The above statement is False. The JMS only defines interfaces there are no implementation classes in the package. So you will need to write all of the implementations yourself.
86 A B
Choice A is correct. Point-to-Point messaging is typically used where a client application sends a message to another application. This is the one-to-one messaging paradigm. In contrast, Publish Subscribe, allows broadcast communication (one-to-many.)
87 Your have decided to let people shopping at your site receive confirmation emails when they buy online. The emails will not contain their credit card numbers but will contain the amount they have been charged. A JMS request to an email server will be used to do this. However you are worried about how secure this will be but a college reassures you that JMS has security built into it. Is this true? True/False? A B TRUE FALSE
240
241
88 You've designed an application that allows customers to buy chapters of ebooks. Due to the success of the project this will be launched as a worldwide application. In the process of converting this application to be suitable for worldwide use, which of the following will you use? A Java runs with already as standard 16bit characters as standard so you don't need to use any particular classes to change the text. All primitive objects can be used. B java.text package C java.lang.Integer Class D java.lang.Number Class E java.international package F java.Unicode package Choice B is correct. The java.text package contains classes such as MessageFormat and NumberFormat, these classes are used to layout text in the appropriate way.Choice A is incorrect; primitive objects cannot be used. Choices C and D are incorrect because the way numbers are displayed is different in most countries. The packages named in choices E and F don't exist.
89 A B C D E
Which of the following are used in Internationalization? java.lang.Long Class java.lang.Float Class java.lang.Number Class java.lang.String class char primitive class
Choices D and E are correct. The String and char primitive classes are used in the process of Internationalization.Choices A, B and C are all incorrect because its the way numbers are displayed that is different in most countries.
90
A To store information about the program, like an external configuration file. B To store parts of the program that is Locale sensitive, e.g. the text on a message window.
241
242
Choice B is correct. A ResourceBundle is used to store all parts of a program that you will need to change as part of Internationalization. For example you could put the text for dialog messages there and when it came to displaying the dialog, the program will look up and retrieve the appropriate text based on the country of the user.Choice A is incorrect because the ResourceBundle doesn't store any information about the program like an external configuration file. The ResourceBundle doesn't give you any access to local resources. Hence choice C is incorrect. The properties of the user's environment, language and a region are found in the users system properties, not the ResourceBundle. Hence choice D is also incorrect.
91 You have been brought in from another project to help some colleagues with the documentation of an application they have been working on. You need to show groups of classes as subsystems. What type of UML diagram will you use? A B C D Collaboration Diagram Class Diagram Package Diagram Use case Diagram
Choice C is correct. A package diagram is used to show groups of classes that belong together. Choice A is incorrect because a Collaboration Diagram is a type of interaction diagram. A Class Diagram shows individual classes. Hence choice B is incorrect. A Use case Diagram depicts a scenario that the system would be involved in. Thus choice D is also incorrect.For more information about UML:http://www.uml.org/
92
A B C D
Class A inherits from Class B Class B inherits from Class A Class B will send messages to Class A Class A will send message to Class B
242
243
This diagram shows generalization (or inheritance). Note: Normally the sub class is be shown below the ancestor, though that is not a UML constraint.Choice A is incorrect because it is the other way around. Choices C and D are both incorrect because the empty triangle wouldn't be there in the diagram if messages were being sent.For more information about UML:http://www.uml.org/
93
A B C D
Choice B is correct. This is a package and it represents a group of classes.The symbol is incorrect for it to be a component. Hence choice A is incorrect. For this to be part of a collaboration diagram it would need to interact with another object. Hence choice C is incorrect. If it were a super class, another class would need to extend from it. So choice D is also incorrect.For more information about UML:http://www.uml.org/
94
A B C D
It is a class called AName It is a static class called AName It is an object called AName It is an interface
Choice C is correct.
243
244
You can tell this is an object because its name is underlined. The following is taken from (Cade 42):"If the element name is underlined, then it is an instance of an element. You can precede an element name with a : and have an anonymous instance. You can place a name in front of the : and have a named instance of an element."Choices A and B are incorrect because the name is underlined. Choice D is incorrect because the symbol would have the word interface above it like this: <<interface>> if it were an interface.For more information about UML:http://www.uml.org/
95
When should you use Java IDL and when should you use RMI-IIOP?
A You should use Java IDL when using Enterprise Javabeans. B You should use RMI-IIOP when using Enterprise Javabeans. C You HAVE to use RMI-IIOP when using Enterprise Javabeans. D Java IDL can be used even if the remote interfaces were originally defined as RMI interfaces. E RMI-IIOP can be used with CORBA only if the remote interfaces were originally defined as RMI interfaces. F RMI-IIOP can be used with CORBA even if not all of the remote interfaces were originally defined as RMI interfaces. G It comes down to programmer preference as both can be used in all situations. Choices B and E are correct. The following is taken from:http://java.sun.com/j2se/1.3/docs/guide/idl/index.htmlThis is a fundamental question and it's important to understand the distinction between these two ways of integrating the Java programming language with CORBA. Java IDL is for CORBA programmers who want to program in the Java programming language based on interfaces defined in CORBA Interface Definition Language (IDL). This is "business as usual" CORBA programming, supporting Java in exactly the same way as other languages like C++ or COBOL. RMI-IIOP (Remote Method Invocation over Internet Inter-ORB Protocol) is for Java programmers who want to program to the RMI interfaces, but use IIOP as the underlying transport. RMI-IIOP provides interoperability with other CORBA bjects implemented in various languages - but only if all the remote interfaces are originally defined as Java RMI interfaces. It is of particular interest to programmers using Enterprise JavaBeans (EJB), since the remote object model for EJBs is RMI-based. Choice A is incorrect; Java IDL has nothing to do with Enterprise Javabeans. In choice C you can use JRMP instead of IIOP if you want. So this choice is incorrect. Choice D is incorrect because Java IDL requires CORBA interfaces not RMI interfaces. Choice F is incorrect as all the interfaces must be defined as RMI interfaces. Choice G is incorrect because although sometimes
244
245
Java-IDL and RMI-IIOP could be used for the same thing, generally a situation will suit one more than the other.
96 You have an online shopping application that has been deployed for some time. Previously all sales had been diverted to another company. Because of the popularity of your site now, you have decided that your application will handle credit card sales, going forward. You will use JMS to send requests to charge credit cards to a separate server. You need an instant response as to whether the credit card transaction was approved. What type of messaging do you use? A B C D E Publish/Subscribe Point-to-Point Topic Messaging Instant Messaging You wouldn't use messaging
Choice E is correct. If you need an instant response you probably wouldn't use messaging. The idea of messaging is that you can send messages to other applications and let them process the messages in their own time. For this solution it will be better to use an EJB and directly query the credit card validation server.Choice A suggests that messages will be broadcast (one-to-many.) For credit card validations, there is no need to broadcast the request. Besides the question says that an"instant response is required." Messaging is inherently asynchronous. Hence choice A is incorrect.Point-to-Point or P2P is a one-toone messaging architecture. JMS does provide APIs that allow send-and-forget and send-and-respond messages. Though a synchronous request is mimicked here, messaging architecture, unlike RPC models, is not truly synchronous. Note: In some P2P implementations (where a synchronous response is required using messaging), the sender puts the message in a queue. The receiver polls its queue and reads the message. The receiver then sends a response to another queue, which the sender is polling for responses and so on. So though the credit card validation can be achieved through P2P messaging, if a synchronous RPC call is available, that would be the preferred option.Topic Messaging is the same as Publish Subscribe. Hence choice C is incorrect. Instant Messaging refers to a method of chatting on the Internet. Hence choice D is incorrect.
97 You are working for a company that aims to provide its customers with the facility to buy and sell shares online. You have been looking through the requirements document and notice that the process of selling/transferring shares is very complicated due to the constant price change. Hence you are required to control transactions at a
245
246
very fine level of granularity. Should you use CMT or BMT?CMT = Container Managed TransactionBMT = Bean Managed Transaction A B CMT BMT
Choice B is correct. BMT gives you the developer much greater control over the transaction. As the developer, you can start the transaction where you want and end it where you want.CMT does however give you the advantage of not having to worry about code related to the transaction you can just focus on the business logic instead.The following is taken from: http://java.sun.com/j2ee/tutorial/1_3-fcs/doc/Transaction4.html In a bean-managed transaction, the code in the session or message-driven bean explicitly marks the boundaries of the transaction. An entity bean cannot have beanmanaged transactions; it must use container-managed transactions instead. Although beans with container-managed transactions require less coding, they have one limitation: When a method is executing, it can be associated with either a single transaction or no transaction at all. If this limitation will make coding your bean difficult, you should consider using bean-managed transactions.
98 You have contracted by a company to assess an application currently deployed in production. The application meets all of the company's original requirements and is coping well with the current number of users. The company is quite happy with it. It has been written using PERL and CGI scripts and there are no transactions in this system. What do you recommend they do? A Migrate the solution to ASP based solution. B Migrate the solution to JSP and Servlets. In the future this will be more maintainable solution. C Keep it the way it is. D Migrate to JSP/Servlets and an Application server. In the future this will be more maintainable solution. Choice C is correct. The key to this question is:The application meets all of the company's original requirements and is coping with current number of users. The company is quite happy with it.There is no need to change an application that does everything it is supposed to do. Choice B is technically correct, JSP and Servlets will be more maintainable than PERL/CGI scripts but it is not the most appropriate answer. Choice D isn't correct for the same reasons as choice B, in addition to the fact that there appears to be no clear need for using an Application Server (there are no transactions and there is no mention of persistence requirements.) Choice A is also incorrect for the same reasons as choice B.
246
247
99 You have been contracted by a company to examine an existing system. It consists of PL/SQL stored procedures a JSP/Tomcat cluster of web servers and an Oracle database. The owners are saying that maintenance is their biggest problem, every time they try and change code they run into problems. What do you recommend they do? A Move the PL/SQL business logic into Servlets B There shouldn't be any problems with maintenance as the business logic has already been separated from the presentation and data store (PL/SQL stored procedures). C Separate the business logic by using an Application Server. D Look through the code making sure it is structured well and commented, separating any duplicated code into a common class. Choice C is correct. The key to this question is that the business logic has been implemented as PL/SQL stored procedures. This means there is a tight coupling between the data store and the business logic. This will have a direct affect on the maintenance of the application. To improve this the best thing to do would be move the business logic from the PL/SQL scripts to an Application Server and use Enterprise Beans. Another reason why this is the best choice is because they are already using JSP and Tomcat web servers. So the Application Server will integrate well into this solution. You could move the business logic into Servlets as suggested in choice A but this would create tight coupling between the business logic and presentation code. The application would still be hard to maintain, with problem areas at a different place. Choice B is incorrect as there is tight coupling between the data store and business logic. Even if the code is properly structured and commented there will still be tight coupling between the data stoe and business logic so choice D is incorrect.
100 You have a method that can execute in a transaction as part of that transaction but it doesn't matter if it doesn't. What is the correct attribute in the deployment descriptor? A B C D E Supports Not Supported Mandatory Required Leave is empty as this is the default setting
247
248
Choice A is correct. A method must support execution within a transactional scope, if it is to be executed as part of a transaction. The word 'supports' also implies that although it can be part of a transaction, it doesn't have to. 'Not Supported' implies the method cannot be executed as part of a transaction. 'Mandatory' and 'Required' imply that the method must be executed as part of a transaction. Leaving the deployment descriptor empty is not the default setting for 'supports.'
101
A Isolatable means only 1 transaction can execute at a time. B Isolatable means the transaction is the same as other transactions in structure. C Isolatable means a transaction must execute without the interference from other processes or transactions. D Isolatable means the transaction was started and finished in the same VM. E Durable means the transaction is the same as other transactions in structure. F Durable means the integrity of the underlying data source is maintained. G Durable means data must be written to the data source before the transaction is complete. H Durable means the transaction was started and finished in the same VM. Choices C and G are correct.ACID stands for Atomic, Consistent, Isolatable and Durable. All transactions must adhere to this. Isolatable means a transaction must execute without the interference from other processes or transactions. And Durable means data must be written to the data source before the transaction is complete.
102 You are writing an application that will allow people to communicate directly with each other. The application will consist of a frame with two panels, they will type their messages in the top panel and read messages in the bottom panel. What is the best way to implement this application, as an Applet or a standard Java application? A B As an Applet. As a standard Java application.
Choice B is correct. The reason for choosing the standard Java application over an Applet is all due to security restrictions. In the question is says that the users will need to communicate directly with each other, not back to the server from which the applet was downloaded. This wouldn't be allowed under standard Applet security permissions and although the security settings can be fully customized to allow applets to connect to different machine that is not what applets were designed for. Another key point to the question is that there is no requirement that this communication tool be made available over the web. So creating this as a standard Java application is the most appropriate choice.
248
249
103
A Works for both Entity and Session beans. B It is more flexible than BMT. Can handle transactions at a much finer granularities than BMT. C It is less flexible than BMT. Cannot handle transactions at a finer granularity than BMT. D Does not work for both Entity and Session beans.
Choices A and C are correct. Entity Beans can only use Container Managed Transactions (CMT) but Session Beans can use either CMT or Bean Managed Transactions (BMT). So choice D is the other way around. CMT is less flexible than BMT and cannot handle transactions at the same level of granularity as BMT, so choice B is incorrect as well.The following is taken from:http://java.sun.com/j2ee/tutorial/1_3-fcs/doc/Transaction3.htmlIn an enterprise bean with container-managed transactions, the EJB container sets the boundaries of the transactions. You can use container-managed transactions with any type of enterprise bean: session, entity, or message-driven. Container-managed transactions simplify development because the enterprise bean code does not explicitly mark the transaction's boundaries. The code does not include statements that begin and end the transaction.http://java.sun.com/j2ee/tutorial/1_3-fcs/doc/Transaction4.htmlIn a beanmanaged transaction, the code in the session or message-driven bean explicitly marks the boundaries of the transaction. An entity bean cannot have bean-managed transactions; it must use container-managed transactions instead. Although beans with container-managed transactions require less coding, they have one limitation: When a method is executing, it can be associated with either a single transaction or no transaction at all. If this limitation will make coding your bean difficult, you should consider using bean-managed transactions.
104 You are developing an online shopping store for an art gallery. The company aims to bring fine art to the masses and expects a huge volume of traffic through the site. The site allows customers to pay for goods and arrange delivery methods using credit cards. You have read through the requirements and have a rough design in your head. Which of the following is the most appropriate rough design for this site? A Have an Entity Bean to represent the customer. Use a Servlet to manage the users session and use BMT to manage the transactions. B Have an Entity Bean to represent the customer. Use a Stateful Session Bean to manage the users session and use BMT to manage the transactions. C Have an Entity Bean to represent the customer. Use a Servlet to manage the users session and use CMT to manage the transactions. D Have an Entity Bean to represent the customer. Use a Stateful Session Bean to manage the users session and use CMT to manage the transactions.
249
250
The key to this question is the choice of Transactions Bean Managed Transactions or Container Managed Transactions. There is no need to control transactions at a fine level of granularity and Entity Beans cannot take part in BMT. Hence CMT may be a better choice. The Servlet is a more appropriate choice for handling the users session however you would still need another Stateful Session Bean for the business logic of the application.The following is taken from:http://java.sun.com/j2ee/tutorial/1_3fcs/doc/Transaction3.htmlIn an enterprise bean with container-managed transactions, the EJB container sets the boundaries of the transactions. You can use containermanaged transactions with any type of enterprise bean: session, entity, or messagedriven. Container-managed transactions simplify development because the enterprise bean code does not explicitly mark the transaction's boundaries. The code does not include statements that begin and end the transaction.http://java.sun.com/j2ee/tutorial/1_3-fcs/doc/Transaction4.htmlIn a beanmanaged transaction, the code in the session or message-driven bean explicitly marks the boundaries of the transaction. An entity bean cannot have bean-managed transactions; it must use container-managed transactions instead. Although beans with container-managed transactions require less coding, they have one limitation: When a method is executing, it can be associated with either a single transaction or no transaction at all. If this limitation will make coding your bean difficult, you should consider using bean-managed transactions.
105
When would you use the DAO pattern in regards to a Stateful Session Bean?
DAO = Date Access Object CMP = Container Managed Persistence BMP = Bean Managed Persistence A B C D E F When using CMP to reduce dependence on underlying data store. When using BMP to reduce dependence on underlying data store. When using BMP to increase performance. When using CMP to increase performance. You wouldn't use a DAO with Stateful Session Beans. When writing to a temporary store when ejbPassivate() is called
Choice E is correct. You would normally use a DAO with BMP Entity Beans or Stateless Session Beans. Entity Beans permanently persist data and can survive server crashes. Choices C and D are incorrect because you would never use a DAO with CMP irrespective of the type of bean you were dealing with. The Data Access Object does not improve the performance of your application.When you use Bean Managed Persistence you are writing all the SQL needed to persist the bean yourself. This means that you are using database specific SQL and the same SQL might not work with a different database vendor. For simple operations like Catalog Retrieval, a Stateless Session Bean is often employed with DAO as well.The flow for such operations often looks like:JSPController (Request Processor / Request Dispatcher)Service LocatorSession BeanDAODatabaseWith
250
251
both BMP Entity Beans and Stateless Session Beans, the Data Access Object pattern (DAO) is used to reduce the dependency between Enterprise Beans and the underlying database. This means that the data object manages the connection to the data source and if the data source changes you only need update this one object, the change doesn't affect the rest of your application.With Stateful Session Beans, the data is never permanently stored in a database. Therefore they cannot survive a server crash. Stateful Session Beans, as the name suggests, are used for maintaining conversational state with clients. They are generally more expensive in terms of resources (they are not pooled) and are therefore not normally used for simple database operations such as catalog retrieval.
106 What is the most important item in this list that should be considered when designing an application? A B C D E F G H I J Scalability Maintainability Reliability Meeting the needs of the customer Performance Ensuring the application is produced on time and within budget Secure That the application is technically the best possible solution Availability Extensibility
Choice D is correct. The most important consideration when designing an application is that it meets the needs of the customer. Ensuring the application is produced on time and within budget is something that should be done but it is not the number one concern. The application does not have to be the best possible solution under the circumstances. As long as it meets the customer''s needs, it is considered adequate. Performance - A measure of the system in terms of response time or number of transactions per unit time. Load Distribution (e.g. DNS Round Robin) and Load Balancing are two techniques that aid in higher performance. Other development and deployment related tasks such as Application Tuning, Server Tuning, and Database Tuning also help the system perform better.Scalability - The ability of a system to perform and behave in a satisfactory manner with increases in load.Reliability - The ability of a system to assure the integrity and consistency of the application and all its data as the load increases.Availability - The ability of a system to assure that all services and resources are always accessible. This can be achieved through fault tolerance (the ability to prevent system failures in the event of service(s) / component(s) failures, commonly implemented via redundancy) techniques such as Active and Passive Replication.Extensibility - The ability to easily add new functionality to the existing system. This can be achieved by using best practices and well-defined architecture and design techniques.Maintainability - Ability to easily correct flaws in the existing system.Security - The ability to protect a system and
251
252
all its components and services against potential attacks. Security attacks generally try to compromise confidentiality and integrity of the system. Sometimes they also take the form of 'Denial of Service' (DoS) attacks that bring down a system by flooding it with messages. Security can be addressed by the use of technologies (firewalls, DMZ, data encryption, Digital Certificates and so on) and methodologies (good security policies and procedures.)Manageability - The ability to monitor and perform preventive maintenance on a system.
107 Which list shows the correct order of Enterprise Beans in terms of resources?Note: Heaviest to lightest. A B C D E F Stateful Session Bean, Stateless Session Bean, Entity Bean Entity Bean, Stateful Session Bean, Stateless Session Bean Stateful Session Bean, Entity Bean, Stateless Session Bean Entity Bean, Stateless Session Bean, Stateful Session Bean Stateless Session Bean, Stateful Session Bean, Entity Bean Stateless Session Bean, Entity Bean, Stateful Session Bean
Choice B is correct. An Entity Bean is the heaviest bean in terms of resources usage. The state of an Entity Bean is permanently persisted in a database. Making a connection to the database is expensive in terms of CPU time so this bean has to be the most expensive. Stateful Session Beans maintain their state by the Container writing the beans state to a temporary store such as a file. Stateless Session Beans are least expensive because they have no state to persist, even temporarily.
108 You need to maintain a user's session for a web application. Which protocol do you use? Note: There is no secure data in this application. A B C D E IIOP HTTPS SHTTP HTTP JRMP
Choice D is correct. This is a trick question. At first you would think that the best possible choice would be to use HTTPS. However all the question is actually asking is how to maintain a user's session. This can be done through URL re-writing, cookies or letting the web server handle the session. Most modern web servers can track clients and maintain sessions
252
253
109 You are designing an application to be used to edit photographs. The aim of the application is to provide effects such as converting a color picture to black and white, enlarging certain areas of the print, creating a watercolor effect etc. At the moment the application is structured so that the photographic image is represented by one object, other objects represent each effect and a control object is used to co-ordinate with these objects. When the user selects the color to black and white effect it changes the state of the Color object to Black and White. This then needs to co-ordinate with the control object and apply the effect. Basically as the state of the effects objects changes it need to co-ordinate with the photographic image object.Which design pattern do you use? A B C D E F Chain of Responsibility. Notifier Observer Mediator Command State
Choice D is correct. The key to this question is that this application uses a Control object to co-ordinate state changes between objects. The Mediator pattern allows you to co-ordinate state changes between other objects by using one object. There is no design pattern called the Notifier in the Gang of Four book or in the J2EE blueprint patterns catalog. Mediator - (GOF 273):"Define an object that encapsulates how a set of objects interact. Mediator promotes loose coupling by keeping objects from referring to each other explicitly, and it lets you vary their interaction independently."The other patterns were:Chain of Responsibility - (GOF 223):"Avoid coupling the sender of a request to its receiver by giving more than one object a chance to handle the request. Chain the receiving objects and pass the request along the chain until an object handles it."Command - (GOF 233):"Encapsulate a request as an object, thereby letting you parameterize clients with different requests, queue or log requests, and support undoable operations"State - (GOF 305):"Allow an object to alter its behaviour when its internal state changes. The object will appear to change its class."Strategy - (GOF 315):"Define a family of algorithms, encapsulate each one, and make them interchangeable. Strategy lets the algorithm vary independently from clients that use it."
110 You are designing an application that will need to use SSL to transmit data securely from one application to another. You know that you can easily get hold of
253
254
existing implementations of SSL to use in your application but you'd like to learn more about SSL and have decided to implement your own version. You know that as part of the SSL handshake the client and server must agree a method of encryption. The problem is you don't know which method of encryption that will be. Which design pattern will help with this? Note: This is not a web-based application. A B C D E Decorator Interpreter Strategy Composite Template Method
Choice C is correct. There are really only two possible answers for this question, the Strategy pattern and the Template Method pattern. The Strategy pattern is the better choice because the algorithms are encapsulated so that they can be used interchangeably. So you can add RSA, DES, etc. and then during the handshake the server can select the appropriate encryption object.Strategy - (GOF 315):"Define a family of algorithms, encapsulate each one, and make them interchangeable. Strategy lets the algorithm vary independently from clients that use it."The other patterns were:Interpreter - (GOF 243):"Given a language, define a representation for its grammar along with an interpreter that uses the representation to interpret sentences in the language."Decorator - (GOF 175):"Attach additional responsibilities to an object dynamically. Decorators provide a flexible alternative to subclassing for extending functionality."Composite - (GOF 163):"Compose objects into tree structures to represent part-whole hierarchies. Composite lets clients treat individual objects and compositions of objects uniformly."Template Method - (GOF 325):"Define the skeleton of an algorithm in an operation, deferring some steps to subclasses. Template Method lets subclasses redefine certain steps of an algorithm without changing the algorithm's structure."
111 You are a Computer Science lecturer at a top University. You are giving a presentation of a new piece of software you have written. Basically you have written the next generation spell checker, the reason yours is so good is that it can learn the common typing mistakes of an individual user. You have already sold licenses to many major software vendors and plan to retire in the Sun. However before you go they all require slight changes in the logic to suit their individual needs. What design pattern will help you slightly change the logic in a class to be used in many applications? A B C D E Strategy Adapter Mediator Interpreter Template Method
Choice E is correct. Template Method - (GOF 325):"Define the skeleton of an algorithm in an operation, deferring some steps to subclasses. Template Method lets subclasses redefine certain
254
255
steps of an algorithm without changing the algorithm's structure."The other design patterns:Strategy - (GOF 315):"Define a family of algorithms, encapsulate each one, and make them interchangeable. Strategy lets the algorithm vary independently from clients that use it."Mediator - (GOF 273):"Define an object that encapsulates how a set of objects interact. Mediator promotes loose coupling by keeping objects from referring to each other explicitly, and it lets you vary their interaction independently."Interpreter (GOF 243):"Given a language, define a representation for its grammar along with an interpreter that uses the representation to interpret sentences in the language."
112
A You need two unconnected objects to be able to send messages to each other. B You need two connected objects to be able to send messages to each other. C You need to create a new operation on an object and you will change the classes of elements on which it operates. D You need to create a new operation on an object without changing the classes of elements on which it operates.
Choice D is correct. To solve the problem described in choice A, you would use the Adapter pattern. There is no problem described in choice B as the objects are already connected and would be able to send messages to each other. In the Visitor pattern you don't change the classes of elements on which it operates.Visitor - (GOF 331):"Represent an operation to be performed on the elements of an object structure. Visitor lets you define a new operation without changing the classes of the elements on which it operates."
113 You have been reading the Gang of Four pattern book again and you suddenly notice a similarity between a design pattern and publish-subscribe messaging. What design pattern is similar to publish-subscribe messaging? A B C D E F G Publisher pattern. Flyweight pattern. Observer pattern. Chain of Responsibility pattern. Subscribe pattern. Visitor pattern. Proxy pattern.
Choice C is correct. The observer pattern is similar to publish-subscribe messaging. There are no patterns called Publisher or Subscribe in the Gang of Four pattern book.Observer - (GOF 293):"Define a one-to-many dependency between objects so that when one object changes state, all its dependents are notifies and updated automatically."The other
255
256
patterns were:Visitor - (GOF 331):"Represent an operation to be performed on the elements of an object structure. Visitor lets you define a new operation without changing the classes of the elements on which it operates."Chain of Responsibility - (GOF 223):"Avoid coupling the sender of a request to its receiver by giving more than one object a chance to handle the request. Chain the receiving objects and pass the request along the chain until an object handles it."Flyweight - (GOF 195):"Use sharing to support large numbers of fine-grained objects efficiently."Proxy - (GOF 207): "Provide a surrogate or placeholder for another object to control access to it."Publish Subscribe Messaging: Generally Pub/Sub is used when a one to many broadcast of messages is required. 'Producers' sends messages to many clients via virtual channels called 'Topics.' 'Consumers' receive messages by subscribing to topics. Consumers receive a copy of all messages in the topic they have subscribed to. The Publish Subscribe Architecture is generally a push-based model. Consumers may optionally establish 'durable' subscriptions that allow them to collect messages after periods of inactivity.
114 Which statements describe Publish-Subscribe Messaging and which describe Point To Point Messaging? A B C D E F Publish-Subscribe Messaging is a message queue system. Publish-Subscribe Messaging = One sender and one receiver. Point To Point Messaging = N senders and one receiver. Publish-Subscribe Messaging = 1 sender and n receivers. Point To Point Messaging is a message queue system. Point To Point Messaging = One sender and one receiver.
Choices D and F are correct. Publish/Subscribe is like someone publishing one message on a bulletin board and that message being read by/emailed to many subscribers. (One - many). Point to point messaging is a one-to-one relationship e.g. a message from one application to another. (From one point to one other point)For more detailed explanations:Publish Subscribe Messaging: Generally Pub/Sub is used when a one to many broadcast of messages is required. 'Producers' sends messages to many clients via virtual channels called 'Topics.' 'Consumers' receive messages by subscribing to topics. Consumers receive a copy of all messages in the topic they have subscribed to. The Publish Subscribe Architecture is generally a push-based model. Consumers may optionally establish 'durable' subscriptions that allow them to collect messages after periods of inactivity.Point-to-Point Messaging: Point-to-point: The point to point messaging model allows both 'send and receive' and 'send and forget' messages, via virtual channels called 'queues.' The p2p model typically uses a 'pull' or 'polling' model. In this model, clients generally request messages from queues.
256
257
Choice B is correct. CORBA only moves the state of an object but RMI moves the objects behavior as well. Choice A is not appropriate as it is a stateful protocol and is not a framework for moving objects. Choices D and E are incorrect as they are both names of protocols used by RMI and CORBA respectively. These are both protocols, not frameworks for moving objects.
116 Which of the following is an accurate description of what the java.text package used for with regards to Internationalization? A B C D Contains dictionaries of foreign languages. Contains classes used to read text in foreign languages. Contains classes that support locale-specific manipulation of text. Contains classes used to convert text into languages that use special symbols.
Choice C is correct. The following is taken from:http://java.sun.com/j2se/1.3/docs/api/java/text/packagesummary.htmlProvides classes and interfaces for handling text, dates, numbers, and messages in a manner independent of natural languages. This means your main application or applet can be written to be language-independent, and it can rely upon separate, dynamically linked localized resources. This allows the flexibility of adding localizations for new localizations at any time.
117 A B C D
Which of the following statements about the Properties class are true? Is used to get access to local system resources such as files etc To store information about the program, like an external configuration file. It should only be used to store Strings. It should be used to store all types of objects.
Choice C is correct. Although choice D is technically correct this kind of use is strongly discouraged (see below for an explanation). The Properties class stores no information about the Program and gives you no access to local system resources so choices A and B are incorrect.The
257
258
following is taken from:http://java.sun.com/j2se/1.3/docs/api/java/util/Properties.htmlThe Properties class represents a persistent set of properties. The Properties can be saved to a stream or loaded from a stream. Each key and its corresponding value in the property list is a string. A property list can contain another property list as its "defaults"; this second property list is searched if the property key is not found in the original property list. Because Properties inherits from Hashtable, the put and putAll methods can be applied to a Properties object. Their use is strongly discouraged as they allow the caller to insert entries whose keys or values are not Strings. The setProperty method should be used instead. If the store or save method is called on a "compromised" Properties object that contains a non-String key or value, the call will fail.
118 You've designed an application that allows customers to buy chapters of ebooks. Due to the success of the project this will be launched as a worldwide application. You need to be able to get access to the users environment to tell what language your application should display the text in. What class will help you do this? A B C D E F G Localization class Properties class Locale class National class International class Environment class Runtime class
Choice C is correct. There are no classes called Localization, National, International and Environment as part of the Java Development Kit. The following is taken from:http://java.sun.com/j2se/1.3/docs/api/java/util/Locale.htmlA Locale object represents a specific geographical, political, or cultural region. An operation that requires a Locale to perform its task is called locale-sensitive and uses the Locale to tailor information for the user. For example, displaying a number is a locale-sensitive operation--the number should be formatted according to the customs/conventions of the user's native country, region, or culture.The Properties class represents a persistent set of properties. The Properties can be saved to a stream or loaded from a stream. Each key and its corresponding value in the property list is a string.Every Java application has a single instance of class Runtime that allows the application to interface with the environment in which the application is running. The current runtime can be obtained from the getRuntime method.
258
259
119
A B C D
Class1 has a public attribute called AnAttribute Class1 has a private attribute called AnAttribute Class2 has a public attribute called AnAttribute Class2 has a private attribute called AnAttribute
Choice D is correct. The diagram shown here is a class diagram. Attributes are shown above methods. The symbols used to describe visibility in UML are:+ public, # protected, - privateFor more information about UML please go to:http://www.uml.org/
120 You have been developing a 3-Tier web application to sell imported cars at huge discounts to customers. You have many types of customers, ranging from individuals to corporate customers. You have Entity Beans to represent the Cars and Stateful Session Beans for the business logic involved in pricing and selling a car. In the Session Bean there are methods that apply discounts depending on who the customer is. You only want the client to be able to execute these methods for corporate customers. Is it possible to specify which methods can and can't be executed on a Session Bean or will this kind of security need to be coded by the developer? A B C Yes this is possible. No this will need to be coded by the Developer. It is not possible to do this even by writing you own code.
Choice A is correct. It is possible to specify who is allowed to access to business methods. Firstly you define security roles e.g. <security-role> <description>A corporate customer</description> <role-name>Corporate</role-name> </security-role> Then you can grant method permissions, e.g. <method-permission>
259
260
121 A B C D
Choice C is correct. The diagram shown here is a Component diagram. To see examples of other diagrams please visit:http://www.uml.org/
122 You work colleague is always boasting about how fast his PC is. So as a lighthearted joke you decide to write an applet to slow his PC down. Basically you are going to write an applet that tries to work out the square roots of huge numbers. In order to use up his resources, your applet will spawn a new thread every twenty to thirty seconds. Will this work or would the Java security manager stop it. A It will work. B The security manager kill the Applet as soon as it tries to use more resources than are specified in the security.policy file. C The Applet will only use up the memory it's initially allocated and therefore won't use up any more resources than that. Choice A is correct. Although Applets have very tight restrictions and execute within a sandbox they can actually use as many system resources as the operating system allows them. There is no reference to the amount of memory an Applet can use in the security.policy file so choice B is incorrect. Choice C is almost right but not the most appropriate choice. The operating system will allocate memory initially for the JVM to run in but it is possible for this to be extended once the JVM is running but this is entirely dependent on the operating system.
260
261
123 You have been given a JAR file that has been signed by a 3rd Party Vendor. A Trusted Certificate Authority (CA) has signed the 3rd Party Vendors certificate. Is it possible to add any more classes to this JAR file?True/False? A B Yes No
Choice A is correct. When you sign a JAR file you are not signing the JAR file itself but individual files it contains. This means you can use a tool like WinZip to add new files (classes, images etc) to the existing JAR file without necessarily invalidating the signature. Note: The files that have been added won't be signed. ________________________________ Done upto here on 22.2.03 124 You are working on a new application that will help your company co-ordinate sales data across different departments. The aim is that everyone has the same sales data at the same time. This project needs to be finished as soon as possible. You have therefore bought some third party code to speed up the development process. The code has been signed and is packaged in a jar file. To test the signature the vendor of the software has emailed you the public key. What do you know about it? A The code is fully tested and performs the task it was designed for. B The jar file contains no malicious code. C The code could not have been modified after it was signed. D If the public key doesn't validate the signature then you know all the code is malicious. E The code could not have been modified after it was signed. F If the public key validates the signature then you know all the code is safe. G None of the above. Choice G is correct. There are two key elements to this question. Firstly this is a question about digital signatures, not digital certificates and secondly you were emailed the public key to validate the signature. You haven't been passed the public key in a secure fashion so how do you know that someone hasn't altered the code signed it and then intercepted the key that you were going to use to validate the signature. Digital certificates solve this problem and validate that a public key belongs to its real owner.Just because the code is signed it doesn't mean that it is fully tested and does what it is supposed to do. Choices B, C, D, E and F are incorrect because you don't know if you have the real public key to validate the signature.
125 You should use EJBs even if there is NO data to persist in your application but there are transactions.True/False?
261
262
Choice A is correct. It is recommended that you use Enterprise Javabeans if Transactions are involved in the application. See below for more details.The following is taken from:http://java.sun.com/j2ee/tutorial/1_3-fcs/doc/EJBConcepts2.htmlThe application must be scalable. To accommodate a growing number of users, you may need to distribute an application's components across multiple machines. Not only can the enterprise beans of an application run on different machines, but their location will remain transparent to the clients. Transactions are required to ensure data integrity. Enterprise beans support transactions, the mechanisms that manage the concurrent access of shared objects. The application will have a variety of clients. With just a few lines of code, remote clients can easily locate enterprise beans. These clients can be thin, various, and numerous.
126 A B C D
In EJB 2.0 what is the Component interface? The interface that Message-Driven Beans must implement There is no component interface in EJB 2.0. The new name for the Home interface. The new name for the Remote interface.
Choice D is correct. Note: This type of question will not be in the EJB 1.1 version of the SCEA but is likely to be in the EJB 2.0 version of the SCEA. Message-Driven beans don't implement any interfaces in EJB 2.0. The Component interface is the new name for the Remote interface as introduced in the EJB 2.0 specification. Remote Interface (Component Interface in EJB 2.0): Defines the Bean's business methods. The Remote Interface extends javax.ejb.EJBObject.Home Interface: Defines the Bean's life cycle methods creation, location and removal. The Home Interface extends javax.ejb.EJBHome. Note that the create method is optional for Entity Beans. This is useful when you do not want to clients to be able to insert data into the database.
127 You are working on a new application that will help your company co-ordinate sales data across different departments. The aim is to have everyone access the same sales data at all times. This project needs to be finished as soon as possible and you have bought some third party code to speed up the development process. The code has been signed using a digital certificate and packaged in a jar file. What do you know about it? Note: Digital certificates have been provided that have been signed by a trusted Certificate Authority. A B C The jar file contains no malicious code. The jar file was signed by the 3rd party vendor The jar file contents may contain malicious code.
262
263
Choice C is correct. All you actually know is that the code has been signed using the 3rd party vendors private certificate. You don't know that it was actually signed by the 3rd party vendor. For example if the certificate was copied or stolen then there is no guarantee that the thief hasn't distributed code signed with the stolen certificate. The jar file may contain malicious code or it may not, that is all you can guarantee. Just because code is signed doesn't mean it is fully tested and does what it was supposed to do. Choice E is therefore incorrect.
128 You have been contracted by a movie memorabilia company to set up an online shop. The company buys bulk goods from movie sets (stage props, costumes, gadgets etc), splits them into single items and then auctions them. The company used to hire sports halls or community centers to auction items in a traditional manner. They predict that by moving to an online solution they will reach a wider audience and make a greater profit despite the initial investment that the new system will involve. What is the most suitable initial design in the list below? A The business logic will be handled in a Servlet B The business logic will be handled in a Stateful Session Bean C Use Container Managed Transactions D Use Bean Managed Transactions E The customer will be represented wth an Entity Bean F There is no need for a customer bean as a customers interaction with the site is just business logic and will be handled in the Servlet/Stateful Session Bean G Use Container Managed Persistence H Use Bean Managed Persistence I The sale items will be represented with an Entity Bean J The sale items will be stored directly on a database Choices B, D, E, G and I are correct. This is question is really 5 mini questions. If the business logic is put into the Servlet you are creating Fat clients with presentation and business logic tightly coupled. Therefore it is more appropriate to use a Stateful Session Bean especially since the Bean can be used in the Session Faade pattern (See below). The site is an online auction site with bids being placed at different times. This implies that transactions will need to be handled at a very fine level of granularity therefore Bean Managed Transactions is the most appropriate choice. The customer and sales items both need to be persisted so they should be implemented as Entity Beans. The Entity Beans (customer and sales items) would not be complicated objects so Container Managed Persistence would be the better choice.Session Faade:A client should never"talk" directly to an Entity EJB. Instead a Session to Entity
263
264
pattern called a Session-Faade should be used. As the name suggests, this pattern is based on the GoF Faade pattern. The Session Facade provides a simple interface to a complex subsystem. The simple interface is the Session Bean and the Complex subsystem is the Entity Bean. The client talks to the Session Bean, which in turn communicates with the Entity Bean.
129 You have an application that is running in a DMZ that your company has set up. There are two firewalls, the first filters out packets based on destination ports other than port 80 (allows standard HTTP requests). The second filters out packets based on the origin IP address (only allows company IP addresses through). Can you connect to the application running in the DMZ from your Home computer? Note: The application running in the DMZ is on port 80. True/False? A B True False
The above statement is True. DMZ stands for Demilitarized zone. To set up a DMZ you need two firewalls and you create 3 separate regions. The different regions are the internet, DMZ (in the middle) and the third is your network. You would have a server in the DMZ that is accessible to both the public and your network. The internet may not access your network but they can access the server in the DMZ. Your network must access the internet through the server in the DMZ.The key to this question is that you are not trying to connect to an application within the second firewall that filters out requests based on IP address. So you could definitely connect to the application from home.A Useful link:http://www.saintrochtree.com/network-advices/000004.htm
130 The Enterprise JavaBean 2.0 specification has introduced the notion of local Clients. What are Local Clients and why were they introduced? A Local Clients should be used when the web server is running on the same machine as the application server. B Local Clients should be used when Session Beans need to communicate with Entity Beans.t ;Beans in the same Virtual Machine should use local Clients. C Local Clients have been introduced to make testing code easier. D Local Clients have been introduced to improve maintainability. E Local Clients have been introduced to improve performance. F Local Clients should be used when the database is running on the same machine as the application server. Choices C and F are correct. Note: This type of question will not be in the EJB 1.1 version of the SCEA but is likely to be in the EJB 2.0 version of the SCEA.Prior to the Enterprise JavaBean 2.0 specification
264
265
all Bean clients were seen as remote clients. This meant that if a Session Bean needed to talk to an Entity Bean inside the same Virtual Machine it would still need to make a remote call. This obviously had a direct impact on performance. In EJB 2.0 Enterprise Beans can now treat other beans in the same VM as local clients. Local Clients can access the beans through its local and local home interfaces.Remote clients use passby-value but Local clients use pass-by-reference.For more information please see:http://java.sun.com/products/ejb/2.0.html
131 Which of the following offers an accurate description of Message-Driven Enterprise Beans? A Message-Driven beans are just a new way of describing a JMS message. This has been formalized with the EJB 2.0 specification. B A Message-Driven bean is an enterprise bean that allows J2EE applications to process messages asynchronously. C A Message-Driven bean is an enterprise bean that allows J2EE applications to process messages synchronously. D A Message-Driven bean is used when you need to interact with messaging systems other than JMS. E A Message-Driven bean is like a Session Bean except that if the server is busy it will put the Message-Driven beans' method requests in a queue and execute them one at a time to reduce the load on the Application Server.
Choice B is correct. Note: This type of question will not be in the EJB 1.1 version of the SCEA but is likely to be in the EJB 2.0 version of the SCEA.As stated in choice B a Message-Driven bean is an enterprise bean that allows J2EE applications to process messages asynchronously. Choice C is incorrect because messages are sent asynchronously. Choices A, D and E are all factually incorrect. For more information about Message-Driven beans see below.The following is taken from:http://java.sun.com/j2ee/tutorial/1_3fcs/doc/EJBConcepts5.htmlA message-driven bean is an enterprise bean that allows J2EE applications to process messages asynchronously. It acts as a JMS message listener, which is similar to an event listener except that it receives messages instead of events. The messages may be sent by any J2EE component--an application client, another enterprise bean, or a Web component--or by a JMS application or system that does not use J2EE technology. Message-driven beans currently process only JMS messages, but in the future they may be used to process other kinds of messages.
132 What's the biggest difference between Message-Driven Beans and Entity and Session Beans?
265
266
Note: This type of question will not be in the EJB 1.1 version of the SCEA but is likely to be in the EJB 2.0 version of the SCEA.Choice A is incorrect, Message-Driven beans don't have Home or Remote interfaces, they just have a bean class. The state of Message-Driven beans is not persisted like Entity beans. So choice C is incorrect.The following is taken from:http://java.sun.com/j2ee/tutorial/1_3fcs/doc/EJBConcepts5.htmlThe most visible difference between message-driven beans and session and entity beans is that clients do not access message-driven beans through interfaces. Unlike a session or entity bean, a message-driven bean has only a bean class.
133
A If you need to send any JMS message. B When you need to use an external service such as a credit card validation service and performance is essential. C When you need to send JMS messages asynchronously. D When you need to send JMS messages synchronously. Choice C is correct. Note: This type of question will not be in the EJB 1.1 version of the SCEA but is likely to be in the EJB 2.0 version of the SCEA.Choice B is incorrect, Message-Driven beans will not increase the performance of a service. Choice D is the other way around and choice A is factually incorrect.The following is taken from:http://java.sun.com/j2ee/tutorial/1_3fcs/doc/EJBConcepts5.htmlSession beans and entity beans allow you to send JMS messages and to receive them synchronously, but not asynchronously. To avoid tying up server resources, you may prefer not to use blocking synchronous receives in a server-side component. To receive messages asynchronously, use a message-driven bean.
134 You are developing an application that will have to support a huge number of users. You are worried about the performance of the application because you need to
266
267
use many Entity Beans. A work colleague has suggested using the Value Object design pattern. What is the pattern and how will it benefit you? A A snapshot of the state of an Entity Bean at a particular time. B An object that is used instead of an Entity Bean. For example if you were going to use a Customer bean you would create a Customer Value Object and the Application Server would use this instead. A Stateful Session Bean would control it. C An object that is used instead of an Entity Bean. For example if you were going to use a Customer bean you would create a Customer Value Object and the Application Server would use this instead. A Stateless Session Bean would control it. D There is no such thing as a Value Object design pattern. E There is a Value Object design pattern but it would not be appropriate to use it here. F A Value Object is the state of an Entity Bean that is kept in memory by the Application Server. (Its state is periodically persisted.) G A Value Object is the state of an Entity Bean that is kept in memory by the Application Server. (Its state is not persisted and the data becomes stale after a while.) Choice A is correct. Note: This type of question will not be in the EJB 1.1 version of the SCEA but is likely to be in the EJB 2.0 version of the SCEA.Every time you access an Entity Bean there is a significant overhead, as the call must go across the network and through the container to access the bean. One way to reduce the number of calls you need to make to Entity beans is by using the Value Object pattern. A Value Object (VO) is a snapshot of the state of an Entity Bean at a particular time. The idea is that a client will require more than one value from an Entity bean so instead of making several calls to an Entity Bean a Value Object is created containing all of these values. This Value Object is downloaded by the client so they can make the same calls only this time locally and directly on the bean. A Value Object is normally implemented as a JavaBean and is made immutable because there is no data synchronization (the JavaBean only provides getter methods).
135 Your have been contracted by a company to upgrade their online shopping application. Their site sells health care insurance to customers at huge discounts. The process of buying insurance is complicated. They have however tried to simplify it as much as possible for the customer. When the customer arrives at their site to register, they fill out a 40-question questionnaire covering basic health and lifestyle information. The answers are then used for selecting the most appropriate level of insurance. (Each customer does NOT get a custom health care insurance agreement; they get the most suitable one out of a choice of 30). The customer then has the opportunity to purchase the insurance within seven days before the quote becomes void. Based on the rough description of the system which of the following is the most suitable design? Note: This question should be based upon the EJB 2.0 specification.
267
268
A The Customer should be an Entity Bean B The business logic should be represented with a Stateful Session Bean. C The business logic should be represented with a Servlet. D The system should use CMT. E Should use BMT. F The Health Plan should be an Entity Bean that supports local clients. G The Health Plan should be a Stateful Session Bean. H The Health Plan should be a Stateful Session Bean that supports local clients. I There is no need for Customer Bean as there is no need to store the customers details just the Health Plan they bought. J The Customer should be an Entity Bean that supports local clients.
Choices B, D, F and J are correct. Note: This type of question will not be in the EJB 1.1 version of the SCEA but is likely to be in the EJB 2.0 version of the SCEA.The data that needs to be persisted are the customer data and the Customer's Health Plans data (which one out of the 30 different plans.) Although the process of buying health care insurance sounds complicated (40question questionnaire) the data that actually needs to be stored is very simple (customer id, health plan id etc). This means that CMT is more appropriate than BMT (choice E is therefore incorrect.) There is no benefit in putting the business logic in a Servlet, there still needs to be a Session Bean to talk to the Customer and Health Plan Entity Beans. It is also possible to use the Entity Beans local client interfaces (introduced in EJB 2.0) which will improve the performance of the application.
136 A B C D
What are the benefits of synchronous messaging? Less coupling between the sender and receiver. Network doesn't have to be available. Does not block the sender. Good for transaction processing.
Choice D is correct. Choices A, B and C are all describing asynchronous messaging. Synchronous, tightly coupled communication between distributed components: This is the model of CORBA, RMI, EJB and so on. The programming model is called Remote Procedure Call (RPC).Asynchronous, loosely coupled communication between components: This is the Message Oriented Middleware or MOM model. The programming model is called Messaging.
268
269
137 A B
Can you use BMT (Bean Managed Transactions) with Entity Beans? True/False? Yes No
Choice B is correct. Entity Beans can only use Container Managed Transactions (CMT) but Session Beans can use either CMT or Bean Managed Transactions (BMT). CMT is less flexible than BMT and can't handle transactions at the same level of granularity as BMT.The following is taken from:http://java.sun.com/j2ee/tutorial/1_3-fcs/doc/Transaction3.htmlIn an enterprise bean with container-managed transactions, the EJB container sets the boundaries of the transactions. You can use container-managed transactions with any type of enterprise bean: session, entity, or message-driven. Container-managed transactions simplify development because the enterprise bean code does not explicitly mark the transaction's boundaries. The code does not include statements that begin and end the transaction.http://java.sun.com/j2ee/tutorial/1_3-fcs/doc/Transaction4.htmlIn a bean-managed transaction, the code in the session or message-driven bean explicitly marks the boundaries of the transaction. An entity bean cannot have bean-managed transactions; it must use container-managed transactions instead. Although beans with container-managed transactions require less coding, they have one limitation: When a method is executing, it can be associated with either a single transaction or no transaction at all. If this limitation will make coding your bean difficult, you should consider using bean-managed transactions.
138 A B BMP. C D E F G
How has Container-Managed Persistence Changed from EJB 1.1 - 2.0? There has been no change with CMP but BMP has changed. The performance of CMP has been improved so it no now more efficient than The Bean class is now an abstract class. You no longer need a deployment descriptor. CMP doesn't exist in EJB 2.0 because BMP out performs CMP. You define the fields to be persisted in the Remote interface. You define the fields to be persisted in the Home interface.
Choice C is correct. Note: This type of question will not be in the EJB 1.1 version of the SCEA but is likely to be in the EJB 2.0 version of the SCEA.The following is taken from:http://developer.java.sun.com/developer/technicalArticles/ebeans/EJB20CMP/Prior to the EJB 2.0 specification, a client stored and accessed persistent data via an entity bean's instance variables. With the introduction of the 2.0 specification, you can
269
270
designate instance variables to be container-managed persistence fields (cmp fields) or container-managed relationship fields (cmr fields). You define these cmp and cmr fields in the deployment descriptor. You retrieve and set the values of these cmp and cmr fields using public get and set methods defined in an entity bean. Similar to the JavaBeans model, you do not access the instance variables directly, but instead use the entity bean's get and set methods to retrieve and set these instance variables. (An enterprise bean does not declare these instance variables.) Furthermore, you use the deployment descriptor to specify the relationships between entity beans. These relationship specifications serve as the schema definition, so that when the bean is deployed, the bean relationships may be captured in a relational database. For example, a relationship between two beans specified in the deployment descriptor may appear as a foreign key relationship in a relational database. Choice A is incorrect because CMP has been reviewed in EJB 2.0. Choices F, G and D are incorrect as specified in the above paragraphs. The performance of CMP has improved but not to the point where it is more efficient than BMP so choice B and E are incorrect.
139 What are the benefits of the J2EE Blueprints Fast Lane Reader design pattern and when should it be used? A When you the performance of an application is essential and you need to perform lots of read/write actions. B Should be used when reading large amounts of read only data. C Increases maintainability. D Should be used when you need to access data that becomes stale very quickly. E Can reduce the amount of code needed. F Increases the amount of code needed. Choices B and E are correct.The following is taken from:http://java.sun.com/blueprints/patterns/FastLaneReader.htmlSometimes applications access data in a tabular fashion, such as when browsing a catalog or a list of names or when exporting data in batches for use elsewhere. This kind of data access is usually read-only. In such situations, using entity beans to represent persistent data incurs overhead and provides little benefit. Entity beans are best for coarse-grained access to individual business entities, and are not effective for read-only access to large quantities of tabular data. The Fast Lane Reader design pattern provides a more efficient way to access tabular, read-only data. A fast lane reader component directly accesses persistent data using JDBCTM components, instead of using entity beans. The result is improved performance and less coding, because the component represents data in a form that is closer to how the data are used. Choice F is incorrect because the Fast Lane Reader can reduce the amount of code needed. Choice C is not the most appropriate answer because although there is less coding involved it does not have a direct affect on the maintainability of the application. (It may even reduce maintainability by increasing the coupling between the data store and business logic). Choice A is incorrect because the Fast Lane Reader pattern should only be used with Read Only data. Although choice D is feasible it is not the most appropriate choice.
270
271
140
In which of the following situations would you use the Observer pattern?
A When you need to have objects notified of events but you don't know which objects would have such needs, or if you will need to add more objects to receive such notification, at a later date. B You want one object to monitor when the state of another object but you don't want the object being monitored to need to send any messages regarding its state. C When the instances of your class can be use interchangeable and you want to reduce the number of instances created in order to improve performance. D You are building an online auction site to sell rare and collectable toys. You want customers to be notified of bids on items they are bidding for in as close to real time as possible. You would use the Observer pattern to notify the customer objects of changes in the auction object. E When you need to co-ordinate state changes between other objects by using one object. Choices A and D are correct. The observer pattern is used to notify an objects dependents' when that object changes state. Choice E is a description of the Mediator pattern. Choice C is incorrect because the Observer pattern does not reduce the number of instances you need to create. Choice B is almost correct except that messages are sent when the object being monitored changes state.Observer - (GOF 293): "Define a one-to-many dependency between objects so that when one object changes state, all its dependents are notifies and updated automatically."Mediator - (GOF 273):"Define an object that encapsulates how a set of objects interact. Mediator promotes loose coupling by keeping objects from referring to each other explicitly, and it lets you vary their interaction independently."
141 You need to access a complex object in a recursive waybuilding the object from other objects. This is an example of which pattern? A B C D E Abstract Factory Factory Method Builder Composite Recursive Builder
Choice D is correct. This is a bit of a trick question; you would assume that you would need to use a creational pattern such as the Builder or Abstract Factory to do this <Prototype could be applicable as well, if we are not building a family or an aggregate object, but simply prototyping existing objects>. The key is that you need to recursively build a composite object from other objects. This is an example of the Composite pattern. There is no such pattern as the Recursive Builder so choice E is incorrect.Composite - (GOF 163):
271
272
"Compose objects into tree structures to represent part-whole hierarchies. Composite lets clients treat individual objects and compositions of objects uniformly."The other patterns were:Abstract Factory - (GOF 87): "Provide an interface for creating families of related or dependent objects without specifying their concrete classes."Factory Method (GOF 107): "Define an interface for creating an object, but let subclasses decide, which class to instantiate. Factory Method lets a class defer instantiation to subclasses."Builder - (GOF 97): "Separate the construction of a complex object from its representation so that the same construction process can create different representations."&&Sanjay"need to build a complex object" almost certainly suggests that we are talking about a creational pattern. I understand the tricky nature of the question, however I was wondering if the question needed to be reworded as"accessing a complex object" or something. Has been updated
142
A When you need classes to be notified of events but you don't know which classes or if you will need to add more at a later date. B When the instances of your class can be used interchangeably and you want to reduce the number of instances created in order to improve performance. C When the instances of your class cannot be used interchangeable and you need to convert them so that they are interchangeable. Choice B is correct. Choice A is a description of the Observer pattern. Choice C is incorrect because the instances of your class can be used interchangeably in the Flyweight pattern. Flyweight (GOF 195):"Use sharing to support large numbers of fine-grained objects efficiently."
143 You are currently designing your own Desktop Publishing application, as you have not found any that do exactly what you want with existing applications. As part of the design you are using a Controller to which you send all GUI requests. Not all objects can process the same commands. For example you can't select the spell check tool when an image has the focus. To stop any possible errors you would like to filter out some of the messages as they are passed from these objects to the Controller object. What pattern could you use? A B C D E F Firewall Proxy Adapter Observer Chain of Responsibility Filter
Choice B is correct.
272
273
Firewall and Filter are not design patterns. In this scenario what you are essentially trying to do is filter all packets that don't meet a certain set of requirements. This behavior is just like a Proxy server dropping packets from certain IP address etc.Proxy (GOF 207): "Provide a surrogate or placeholder for another object to control access to it."The other patterns:Adapter - (GOF 139):"Convert the interface of a class into another interface clients expect. Adapter lets classes work together that couldn't otherwise because of incompatible interfaces."Observer - (GOF 293):"Define a one-to-many dependency between objects so that when one object changes state, all its dependents are notifies and updated automatically."Chain of Responsibility - (GOF 223):"Avoid coupling the sender of a request to its receiver by giving more than one object a chance to handle the request. Chain the receiving objects and pass the request along the chain until an object handles it."
144
A When you need to co-ordinate state changes between other objects by using one object. B When you need to add functionality to a class without changing its interface. C When you need to create a separation between abstractions and classes that implement those abstractions. D You need a class that will be used in lots of different applications where the logic will only change slightly. Choice A is correct. The Mediator pattern allows you to co-ordinate state changes between many objects by using one mediator object. Choice B is a description of the Decorator pattern. The Strategy pattern is described in choice D and choice C describes the Bridge pattern. Mediator - (GOF 273):"Define an object that encapsulates how a set of objects interact. Mediator promotes loose coupling by keeping objects from referring to each other explicitly, and it lets you vary their interaction independently."
145 A prospective employer is describing the existing architecture of a solution that is currently in production. He says that it's a 3-tier system with 3 clustered web servers; a server for the Oracle database with the business logic implemented using PL/SQL scripts. What is true about this system? A B C D E F This solution has fat clients This solution has thin clients There is a good separation of business logic The solution has good Scalability There is a poor separation of business logic The solution has poor scalability
273
274
The key to this question is the fact that the business logic has been implemented using PL/SQL stored procedures. This means the business logic is on the same server as the database and therefore this is a 2-tier system not a 3-tier system as your prospective employer suggests. There is a very tight coupling between the data store and the business logic this has a direct affect on the potential scalability of this system. When you think of 2-Tier systems you would normally associate them with Fat clients. However as the business logic has been implemented using PL/SQL scripts this system will have thin clients making choice A incorrect. Choice C is incorrect because the business logic and data store are tightly coupled. This tight coupling will have a direct affect on scalability. You may not be able to horizontally scale this system (adding more machines); vertical scaling might be easier (add more memory and CPUs.) But even with vertical scaling you would always run the risk of a network bottleneck making choice D is incorrect as well.
146 Your have been contracted by a company to help them improve the performance of their sales application. You have suggested that the hardware the application is currently deployed on (2 web servers and a database server) be migrated to 3 web servers, an application server and a database server (all on different machines.) You assure them that all the software re-writes needed will be well worth it in the end. What are the characteristics of your suggested architecture? A B C D E F G Fat Clients Thin Clients Good separation of business logic Good Scalability Poor separation of business logic Poor scalability There is no difference in the separation of business logic
Choices B, C and D are correct. The system you have suggested they migrate to is a 3-tier system. The characteristics of a 3-tier system are thin clients, good separation of business logic and good scalability. This is due to the fact that each tier is separate from the other (for example it would be possible to change the data store without affecting the business logic.)Choice A is incorrect; the suggested system has thin clients, the business logic residing on the application server, in the middle tier. Since there is a good separation of business logic, choices E and G are incorrect. Choice F is incorrect the 3-tier nature of the system makes it very scalable.
147 Your boss is raving about the new 3-Tier architecture that your company's sales application will be deployed on. He says that this architecture will solve all the existing problems. Is he right, or does a 3-Tier architecture have the potential to introduce any new problems?
274
275
A B C D E F G
Fat Clients Thin Clients Poor scalability Poor manageability Reduced performance Reduced separation of business logic Single point of failure
Choice D is correct. The only problem a 3-Tier architecture could have is the potential for poor manageability. The separation of tiers creates thin clients and distributes business logic processing. However because of the distributed nature of the servers, there could be manageability problems. With J2EE solutions however, the potential for such problems is limited because J2EE tiers and layers have very well defined roles and responsibilities. Choice A is incorrect because Fat clients are a characteristic of 2-Tier architecture where the business logic is implemented on the client side. Thin clients are good. Therefore choice B is incorrect. A 3-Tier architecture has excellent scalability, including horizontal scalability, making choice C incorrect. It's possible to argue that a 3-Tier architecture may not perform as well as a single machine containing your web server, business logic and database. However as soon as you introduce a significant amount of users a 3-Tier architecture would out perform a single machine. Therefore choice E is correct. Choice F is incorrect because a 3-Tier architecture actually increases the separation of business logic. Choice G is incorrect because a"single Point of failure" is not a problem that a 3Tier architecture introduces. Although it may have a single point of failure, with careful design you can avoid such pitfalls easily. This is much harder to do with 2-Tier architecture and impossible with 1-Tier architecture.
148 You have written an application to allow customers to reserve tables at their favourite restaurants. In return your company receives 10% of whatever the customer spends at the restaurant. At the moment, the application is being run on a single Apache web server using PERL and CGI scripts for presentation and business logic with a separate server for the Sybase database containing the restaurant details. What are the most notable weaknesses of this architecture? A B C D E Fat Clients Thin Clients Scalability Potential Network bottlenecks Performance
Choices A,C and D are correct. The architecture being described here is a 2-Tier architecture. The key as to whether this system has fat or thin clients is that there is no reference to stored procedures. Generally if the business logic resides on the server it is in the form of stored
275
276
procedures. We therefore assume that all the business logic is in the PERL and CGI scripts. The reason for poor scalability is due to the tight coupling of business logic and client presentation (fat clients). There is always a potential of a network bottleneck in 2Tier architectures because all requests have to go to one data store.Choice B in incorrect as there is no mention of stored procedures in the scenario we assume that the business logic has been implemented in PERL and CGI scripts on the client side. Performance is not the best answer here and so choice F is incorrect.
149 You have just bought a brand new dual processor server with over 3 Gigabytes of memory, the fastest server in its class. This server will host Apache Web server (shipped with the Oracle Database) and an Oracle 8i database. What are the most notable weaknesses of this architecture? A B C D Scalability Manageability Security Performance
Choice A is correct. You can only vertically scale this system (add memory, CPUs etc). As soon as this system comes under a heavy load you would have to separate the Apache web server from the Oracle database and build up a cluster of web servers. This would be hard to do as the Oracle database and Apache web server are so tightly coupled.Note: A system can still be scalable even if it is only one machine providing it has a good separation of the business logic, data store and client presentation. Choice B is incorrect because this system would be easy to manage as everything is in one place. Choice C is incorrect, you don't need to authenticate yourself to other machines or send traffic across the network to other machines. Choice D is incorrect because although the system would perform really well under light traffic as soon as it had heavy loads of traffic the performance would drop dramatically.
150 A B C D E
When should Java IDL be used? When performance is essential (Performance is more important than scalability). When accessing RMI servers. When servicing requests from RMI clients. When accessing existing CORBA servers. When servicing requests from CORBA clients.
Choice D is correct. The following is taken from:http://java.sun.com/j2se/1.3/docs/guide/idl/index.htmlThis is a fundamental question and it's important to understand the distinction between these two ways of integrating the Java programming language with CORBA. Java IDL is for
276
277
CORBA programmers who want to program in the Java programming language based on interfaces defined in CORBA Interface Definition Language (IDL). This is "business as usual" CORBA programming, supporting Java in exactly the same way as other languages like C++ or COBOL. Although CORBA can slightly out perform RMI that is not a reason to use Java IDL so choice A is incorrect. In choices B and C you would use RMI-JRMP and inc choice E you would use RMI-IIOP.
151 You have just started a new job working for a top finance company and you have been asked to provide a user-friendly interface to an existing mainframe application. You don't have any access to the mainframes source code. What is the best technique for this? A It can't be done. B Use a screen scraper. C Re-write the main frame using Java and high-end Unix servers. Although it may take some time to do this in the long run this will benefit the company. D Write a Java front end then use CORBA to communicate with the mainframe. E Use the Java Native Interface (JNI) to communicate with the mainframe. F Use object Mapping G Use JMS Choice B is correct. The key to this question is that you don't have access to the mainframes source code. A screen scraper emulates a mainframe terminal. Basically the screen scraper logs on to the mainframe like a normal user and sends requests to the mainframe and then reads the response. The problem with a screen scraper is that if you change any of the mainframes code there is always the possibility that the screen scraper will stop working.Choice A is incorrect because it is possible to add a GUI to the system. Choice C would take far too long, cost too much and is not what the customer wants. Choices D, E and F would all require access to the mainframes source code. Choice G is incorrect because there is no mention that the mainframe supports a messaging system. Some of them do and even provide interfaces for JMS however as it is not stated in the question it is not the right answer.
152 You are working for a company that has yet to realize the full potential of Java. You offer to show them some of the great things Java can do by integrating a new application with an existing CORBA system. Your bosses will then assess the performance and reliability of this new system. How will you connect your RMI application to the CORBA system? A B C D Use Java-IDL This is a standard feature of RMI. Can't be done. Can only be done by using JNI.
277
278
Choice A is correct. The following is taken from:http://java.sun.com/j2se/1.3/docs/guide/idl/jidlFAQ.htmThere are several scenarios that will define how you will want to create distributed CORBA applications. Here are some of them: Java IDL - If you have been developing CORBA applications using IDL for some time, you will probably want to stay in this environment. Create the interfaces using IDL, and define the client and server applications using the Java programming language to take advantage of its "Write Once, Run Anywhere TM" portability, its highly productive implementation environment, and its very robust platform. RMI-JRMP - If all of your applications are written in the Java programming language, you will probably want to use Java RMI to enable communication between Java objects on different virtual machines and different physical machines. Using Java RMI without its IIOP option leverages its strengths of code portability, security, and garbage collection. RMI-IIOP - If you are writing most of your new applications using the Java programming language, but need to maintain legacy applications written in other programming languages as well, you will probably want to use Java RMI with its IIOP compiler option.Choice B is incorrect because this is not a standard feature of RMI. Choice C is incorrect because it can be done. You don't need to use JNI to do this so choice D is incorrect. At present the existing systems all use CORBA. Therefore it is better to use Java IDL. Hence choice E is also incorrect.
153 You are working for a car leasing company and you need to integrate with one of their mainframe applications. You should do this using either object mapping or screen scraping. When should you use object mapping? A B C D You should always use screen scrapers when you have the option. When you have access to the mainframes code. When you don't have access to the mainframes code. When you are short of time and need a quick solution.
Choice B is correct. Object mapping is the process of building object wrappers around legacy interfaces. This makes the legacy system available in an OO fashion. You need access to the legacy systems source code in order to do this.A screen scraper emulates a mainframe terminal. Basically the screen scraper logs on to the mainframe like a normal user and sends requests to the mainframe and then reads the response. The problem with a screen scraper is that if you change any of the mainframes code there is always the possibility that the screen scraper will stop working. Any change to the mainframe might break the screen scraper and screen scrapers are only really used when you don't have access to the mainframes source code so choice A is incorrect. Choice C is incorrect because you would use a screen scraper if you didn't have access to the mainframes source code. In choice D you would probably use a screen scraper.
278
279
154 You have just joined a new company and have spent some time chatting with the network administrator. He has mentioned that one of the servers is an off-board server. What is an off-board server? A B C D Another way to describe a standard proxy server. Another type of a screen-scraping program, (Like an object mapping one). A server that runs within the DMZ. A proxy for a legacy system.
Choice D is correct. An off-board server is simply a proxy server for a legacy system.
155 You are designing an online cinema ticket booking application. At the moment you plan to have a controller to maintain user sessions, a customer component to hold personal details, a credit card validation component, a set of GUI screens and a cinema component with details of all movies and seating capacities. What should be used for each component? A The controller should be a Stateful Session bean. The customer should be a Stateful Session bean. The cinema component should be a Stateful Session bean. The credit card validation component should be an Entity bean. B The controller should be a Servlet. The customer should be a Stateful Session bean. The cinema component should be a Stateful Session bean. The credit card validation component should be an Entity bean. C The controller should be a Stateful Session bean. The customer should be a Servlet. The cinema component should be a Stateful Session bean. The credit card validation component should be a Stateful Session bean. D The controller should be a Servlet. The customer should be a Servlet. The cinema component should be a Stateful Session bean. The credit card validation component should be a Stateful Session bean. E The controller should be a Stateful Session bean. The customer should be an Entity bean. The cinema component should be an Entity bean. The credit card validation component should be a Stateless Session bean. F The controller should be a Servlet. The cinema component should be a Stateful Session bean. The cinema component should be an Entity bean. The credit card validation component should be a Stateless Session bean. G The controller should be a Stateful Session bean. The customer should be an Entity bean. The cinema component should be an Entity bean. The credit card validation component should be a Stateless Session bean. H The controller should be a Servlet. The customer should be an Entity bean. The cinema component should be an Entity bean. The credit card validation component should be a Stateless Session bean. I Make the GUI using JSP pages J Make the GUI an applet
279
280
The controller could be implemented as either a Servlet or a Stateful Session Bean but it makes more sense from a resources point of view to implement this as a Servlet. The customer and cinema component need data to be stored permanently so these should be Entity beans. The process of validating the credit card is a service so this should be a Stateless Session Bean. JSP pages is a better choice than the applet because it means that the system can be used by a greater number of people because there is no dependency on the Java plug in.
156 You have an Enterprise Bean that represents a customer's account. One of the methods that this bean provides is deductCost(float amount) This method is used when a customer buys something from your company's website. This method must be executed as part of an existing transaction. What is the correct attribute setting in the deployment descriptor? A B C D REQUIRED REQUIRES NEW SUPPORTS MANDATORY
Choice D is correct. If the calling client does not have a transaction (i.e. the transaction hasn't already started) a javax.transaction.TransactionRequiredException will be thrown.Choice A is incorrect as REQUIRED will create a new Transaction if a transaction does not already exist whereas the question says it must be part of an existing transaction. Choice B is incorrect because REQUIRES NEW will create a new Transaction anyway. SUPPORTS will not force the method to execute in a transaction. Hence choice C is also incorrect.
157 You have a method that can't be executed in a transaction. What is the correct attribute in the deployment descriptor? A B C D Leave it empty this is the default. NEVER NOT SUPPORTED NO_TRANSACTIONS
Choice B is correct. As the name suggests"NEVER" is the right answerChoice A is incorrect because leaving the deployment descriptor empty is not the default for NEVER. NOT SUPPORTED just suspends the transaction making choice C incorrect. NO_TRANSACTIONS is not a valid attribute. Hence choice D is also incorrect.
280
281
158 You have been reading up of the Gang of Four patterns and you notice that the Home interface of an Enterprise Javabean is actually based on one of the patterns. Which pattern is the Home Interface of an Enterprise Javabean based on? A B C D Singleton Facade Builder Factory Method
Choice D is correct. This Factory Method pattern provides an interface for creating an object that allows either sub classes or helper classes to create that object.The Singleton pattern creates either 1 or a variable number of instances of a class. So choice A is incorrect. The Faade pattern provides a simple interface to a complex subsystem. Thus choice B is incorrect. The Builder pattern separates the construction and representation of an object. The client is shielded from the object's construction and it only needs to specify content and type. Hence choice C is also incorrect.
159 You've been developing a chat application so that members of your team can keep in touch with each other irrespective of their location. You decided to implement the application as a Java Applet. In order to make sure the user has the latest version, you require the applet to connect back to the server it was downloaded from and check with a file there. Can this be done with JDK 1.3 or 1.4 without modifying the browser's policy files? True/False? A B True False
The above statement is True. The key to this question is that the applet is only connecting back to the server it was downloaded from, and reading a file. This has always been permitted and is permitted with both JDK 1.3 and 1.4. The applet wouldn't be allowed to read a file on the client's machine or connect to machines other than the one it was downloaded from.Note: You may think that if the applet has been downloaded then it must automatically be the latest one, this isn't true as most browser cache applets.
160 You are writing an Enterprise Javabean to represent a Flight in a Travel agency application. One of the developers recommended that you use Bean Managed Persistence (BMP) for the EJB. What is true about BMP? A B C Improves your ability to move your EJB from one Application server to another. Reduces your ability to move your EJB from one Application server to another. Improves your ability to move your EJB from one data store to another.
281
282
Choice C is correct. When you use Bean Managed Persistence you are writing all the SQL needed to persist the bean yourself. This means that the SQL would have been tailored to the data store you are using and the same SQL might not work with a different database vendor. You can cancel this out by using a Data Access Object. The Data Access Object pattern (DAO) is used to reduce the dependency between Enterprise Beans and the underlying database. This means that the data object manages the connection to the data source and if the data source changes you only need update this one object, the change doesn't affect the rest of your application.
161
A Atomic means a transaction must execute completely or not at all. B Atomic means a transaction must execute completely or log where it was stopped. C Consistent means a transaction must execute completely or log where it was stopped. D Atomic means the transaction is the same as other transactions in structure. E Consistent means the transaction is the same as other transactions in structure. F Consistent means the transaction was started and finished within the specified time. G Consistent means that the integrity of the underlying data source is always maintained. Choices A and G are correct. ACID stands for Atomic, Consistent, Isolatable and Durable. All transactions must adhere to this. Atomic means 'a transaction must execute completely or not at all.' Consistent means 'the integrity of the underlying data source is always maintained.'
162 You are working late at the office one day when the security guard informs that you have to leave as the building is closed for the evening. As you are working on a big project you decide to continue your work at home. However when you try to connect to the application from home you get no response. You are trying to connect to your RMIJRMP application; the port is available on the firewall, what is the most likely reason why you can't connect? A The port on the firewall isn't really available.
282
283
B The company's proxy servers are filtering out your request based upon your IP address. C You have typed the connection address incorrectly. D Your application is only listening for internal requests and you will need to change setting in the security.policy file if you wish to connect from home. E Your company knows that most hacking takes place at night and takes all of its systems off-line during the night. Choice B is correct. The most likely explanation here is that your company's firewall is filtering your requests out based upon your IP address. You would need to get your home IP address added to the list that the firewall trusts (and this won't be easy if you're using DHCP!)Choices A and C are both possible but not the very likely here. Hence these answers are incorrect. Choices D and E are not factually correct.
163
A Entity beans are stored in memory by the Application server. B Entity beans are not persisted C They are serialized and stored on a database. D They are NOT serialized but rather stored in a persistent storage medium such as a database. E It is up to the developer, than can either be serialized or mapped directly. Choice D is correct. A bean normally represents a row in the database. Each field that is persisted is typically mapped to a database. The bean itself is not stored in the database, as the class is the same for all bean instances of the same typeit's just the values that change. If beans were serialized when they where stored on the database you would have to de-serialize each one when you were doing a find operation (by criteria). When Entity Beans are passivated (the state to the bean is written to file), serialization may be used depending on the Application server, although most servers probably also synchronize the state with the database as well.Storing them in memory is not persistence. If the server crashes, all the data would be lost. Therefore choice A is incorrect. As Entity beans are persisted, choice B is incorrect. Choices C and E are incorrect because Entity Beans are not serialized.
164 Which of the following statements are true?Note: This question assumes that the no-args constructor and setEntityContext() method have already been called. A Entity Beans start in the"ready" state and move into the"pooled" state only after ejbActivate() has been called on them.
283
284
B Entity Beans start in the"pooled" state and move into the"ready" state only after ejbActivate() has been called on them. C Entity Beans aren't pooled. D Entity Beans are never in either state. Choice B is correct. Entity Beans start in the pooled state (this is assuming that the no-args constructor and setEntityContext method has been called). Then when ejbActivate() is called, they move into the ready state and return to the pooled state when ejbPassivate() is called.
165 A B
How do you find a particular Entity Bean? Call various find methods defined in the Home interface. Call various find methods defined in the Remote interface.
Choice A is correct. The Home interface defines the create(), find(), and remove() methods and the finder methods are used for locating beans.The Remote Interface is used to define all of the methods that can be called by the client on the Enterprise Bean. If you try and call a method that exists in the Enterprise bean class but not in the Remote Interface, you will get a RemoteException.
166 A B C D E F
Which statements are true? ejbFind() returns the Primary Key. The find method/s in the Home interface return an EJBObject or an Enumeration. The find method/s in the Home interface return a Primary Key. ejbFind() returns an EJBObject. The find method/s in the Remote interface return an EJBObject. The find method/s in the Remote interface return a Primary Key.
Choices A and B are correct. The Home interface defines the create(), find(), and remove() methods.The Remote Interface is used to define all of the methods that can be called by the client on the Enterprise Bean. If you try and call a method that exists in the Enterprise bean class but not in the Remote Interface, you will get a RemoteException.Choice C is incorrect because the find method in the Home interface returns an EJBObject or an Enumeration. Choice D is incorrect because ejbFind() returns the Primary Key. The find methods are not defined in the Remote interface so choices E and F are incorrect.
284
285
167 You are at home trying to work on an application you're developing for your company. You want to log on to your machine at work and develop code for your application however you are having some trouble connecting directly to the application (running on port 1099). What is the most likely reason that you can't connect? A A typing error in the connection details. B Your company is filtering traffic based upon IP address C Traffic is being filtered based upon the port number requested. D You need to update the security manager that is being used with the application to allow external connections. E There is a bug in your program stopping anyone from connecting whether internal or external. Choice C is correct. As you are able to connect to your desktop PC you know that your company doesn't filter traffic based upon IP address. Therefore the most likely reason you can't connect is because you are requesting a different port and the firewall is filtering that traffic. Although it's possible that a typing error in the connection details may be stopping you connecting it isn't the most likely reason. So choice A is incorrect. You wouldn't be able to connect to your desktop PC if your company was filtering traffic based upon IP address. So choice B is incorrect. When you connect to your application from within the office you are still connecting via a socket. So you would not be able to connect at work either if there was a problem with the security manager. Hence choice D is incorrect. Although choice E is possible it is not the most likely reason.
168 You know that Java allows you to run JRMP over HTTP, to tunnel through firewalls but does Java allow you to run CORBA over HTTP?(CORBA uses IIOP). True/False? A B Yes No
Choice B is correct. The key to the question is what does Java allow you to do. Java has no direct relationship with CORBA so the answer is No. However if the question was rephrased slightly for example using Java is it possible to tunnel IIOP over HTTP then the answer would be yes (most firewalls are configured to only let HTTP / HTTPS requests through).
169 You are working for an investment bank. You have written an applet to display the current price of the shares that traders have selected for monitoring. For the applet to work, it needs to authenticate who the client is. It does this by reading a file held locally on the client's machine. You know that applets can't read files stored on a local machine by default. So you have placed the applet in a jar file and that is code signed by
285
286
a trusted certificate authority. Is signing the code enough for the applet to be able to read the local file? Note: This is based on JDK 1.3 and 1.4 A B C D it. E Yes it would work fine without limitation as the code is signed. No the security manager of the browser would prohibit this. The applet would have been able to read the file already under JDK 1.3 and 1.4. As long as the code is signed is doesn't matter which certificate authority signed It may or may not work depending on the browser's security policy.
Choice E is correct. Even if the code is signed, the browser's policy file may refuse it permission to perform certain tasks. The policy file will need to grant necessary permissions such as:grant signedBy"signingKey" { Permission java.io.FilePermission"local_file","read";}to allow the applet to read local files.Choice A is incorrect because it depends on the browsers security policy file. Choice B is incorrect because the security manager might not prohibit this. The applet wouldn't automatically be able to read the file. So choice C is incorrect. It would matter which certificate authority signed it, if you have not chosen to trust a particular certificate authority the code might as well not be signed at all! So choice D is also incorrect.
170 You are developing an application to be used at a major bank. Security is a crucial element and you have decided to use JAAS. The GUI will be based on the MVC framework and it uses swing. The application will connect people in the same office so that they can all securely review the same financial data. What protocol should you use to do this? A B C D IIOP JRMP HTTP HTTPS
Choice B is correct. As there is no reference to this being a web based solution and all of the staff are in the same office there is no need to use HTTPS. JRMP is the most appropriate answer.There is no mention of the need for Entity Beans or interfacing with a CORBA system so choice A is incorrect. Choices C and D are incorrect because this is not being used over the web.
171
A It is used primary by Servlets to locate other services such as JMS. A good example of this pattern would be a web based login facility. If a client enters an incorrect
286
287
password their need to be redirected to a different but their session needs to be maintained across the application. B It is used to catalog Enterprise Beans so that other beans can find them quickly and efficiently. For example if you need to forward request from a Session Bean to an Entity Bean then the Session Bean requests the location of the Entity Bean from the Service Locator object. The Service Locator looks in a table (like a HashMap) and returns the Entity Beans location. C The Service Locator pattern can improve performance by introducing a caching facility. D There is a slight loss of performance when using the Service Locator pattern but this is out weighed by the improved maintainability of the code. E None of the definitions of the Service Locator pattern are accurate. F The Service Locator pattern is used to hide the complexities of initial object creation, EJB lookups and object re-creation. G Multiple clients can reuse the same Service Locator pattern. Choices C, F and G are correct. The following is taken from Core J2EE Patterns: Best Practices and Design Strategies page 369 "Use a Service Locator object to abstract all JNDI usage and to hide the complexities of initial context creation, EJB home object lookup, and EJB object recreation. Multiple clients can reuse the Service Locator object to reduce code complexity, provide a single point of control, and improve performance by providing a caching facility."Choice A is describing a standard web based login but this has nothing to do with the Service Locator pattern. Choice B sounds plausible but this is not how the Service Locator pattern is used. Choice D is incorrect as there is an increase not a loss of performance when using this pattern. Choice E is incorrect as there are accurate descriptions of the Service Locator pattern amongst the answers.Some useful links: http://developer.java.sun.com/developer/technicalArticles/J2EE/patterns/ http://java.sun.com/blueprints/ Useful book: Core J2EE Patterns: Best Practices and Design Strategies - ISBN: 0130648841A sample chapter is available here: http://www.sun.com/books/catalog/crupi/index_Table+of+Contents.html Note: This type of question will probably feature in the new EJB 2.0 specification version of the SCEA certification.
172
A When you don't have access to any spare ports of the Firewall and need to tunnel your application through an existing port. B To break out of prison. C When you do have access to spare ports of the Firewall and are able to use them. So you tunnel your application out of one of these new ports that was created just for your application.
287
288
Choice A is correct. Tunnelling is used to pass one protocol through a port that it does not, by default run on. For example if the only free port on the firewall was port 80 and you needed to pass JRMP through the firewall you would "tunnel" JRMP through the firewall. (JRMP by standard runs on port 1099). Basically JRMP would run on top of HTTP. However Tunnelling should generally be avoided and should only be used as a last resort. You use tunnelling when you don't have access to a particular port. So choice C is incorrect. RMI-IIOP is unrelated to tunnelling. Choice B is incorrect because stealing the key from the guard would be easier!
173 You are working for a small to medium sized business that has just started to use servers to host J2EE Applications (its own and clients'.) However since its launch into this new area there have been three separate instances of hacks involving access of sensitive sales information. A security consultant has been brought in to assess the situation and he recommends that your company use a DMZ. What is a DMZ? A The network behind a firewall that's protected from the Internet. B The region inside the inner firewall (we are assuming that there are two firewalls). This network is called the DMZ. C The network outside of the outer firewall. This could be the Internet or other client networks. (We are assuming that there are two firewalls). D A region between two firewalls. The Internet would come in through the first firewall but only systems within the first firewall in the DMZ can go through the second firewall. Choice D is correct. DMZ stands for Demilitarized zone. To set up a DMZ you need two firewalls with which you create 3 separate regions. The different regions are the internet, DMZ (in the middle) and your network. You would have a server in the DMZ that would be accessible to both the public and employees in your local network. The internet connections will not have access your network though they will be able to access the server in the DMZ. Your network will access the internet through the server in the DMZ. Choice A is just describing the process of using a firewall. The region described in choice B is your network the DMZ is the area between the two firewalls. Choice C describes the internet not a DMZ.A Useful link: http://www.saintrochtree.com/network-advices/000004.htm
174 You are designing a web-based application for an online recipe site. Although this may not seem that popular, the estimated number of unique visitors to the site is 100000 per day. The site is purely informational, you can't buy recipes or upload your
288
289
The above statement is False. The key to this question is that there are no transactions and there is no data to persist. All you are sending to the client are HTML web pages; even if you were to use JSPs/Servlets you still wouldn't use an Application server. In a situation like this you have to think of what the Application server should actually do? In this case there is nothing for it to do.
175 You are an enterprise consultant for one of the Fortune 500 companies. You have been discussing a possible design for a 3-tier application with a prospective client. They know very little about Java and are asking you if Java is always the best solution. Your response is that although normally for each project many factors have to be considered before selecting the programming language and framework, because this is a 3-tier architecture Java is definitely the best solution. Is this true? True/False? A B TRUE FALSE
The above statement is False. It is impossible to make sweeping statements such as Java is always the best solution for 3-tier architectures. A project needs to be looked at individually and then assessed. You may think that one project naturally suits a full Java implementation only to find out that a company has already heavily invested in a different technology or that you don't have the resources (employees with skills in Java based technologies) to implement a solution.
176 You are designing a 3-tier architecture for a new application your company intends to deploy as part of it's marketing strategy. This application will allow users to book rental cars over the web and is estimated to save the company millions over the next few years. Due to the sheer number of users, you have decided to use the Front Controller pattern. Which of the following statements describe the Front Controller pattern?
289
290
A The Front Controller pattern is primarily used as a cheap alternative to a CISCO router. It is used as a software alternative to a hardware load balancer. B Provides a central point of entry C Provides a central point of entry for load balancing D The controller manages client requests, security, delegation of business processing, error handling, view selection and content creation strategies. E The controller manages the client's request including delegating business processing, error handling, view selection and content creation strategies. But is does not have anything to do with security. F The Front Controller is just another way of describing the Controller out of the Model View Controller architecture. G The Front Controller is just using the Controller out of the Model View Controller architecture for load balancing. Choices B and D are correct. The following is taken from Core J2EE Patterns: Best Practices and Design Strategies page 369"Use a controller as the initial point of contact for handling a request. The controller manages the handling of the request, including invoking security services such as authentication and authorization, delegating business processing, managing the choice of an appropriate view, handling errors, and managing the selection of content creation strategies. The main aim of the Front Controller pattern is to centralize view management. For example if a web page is moved all the links to it would need to be updated by using this pattern you can pass all requests through the Front Controller only needing to make changes in one place. The Front Controller is classified by Sun as a Presentation Tier pattern. Choices A and B are incorrect because the Front Controller has nothing to do with load balancing. Choice E is incorrect as the Front Controller can invoke security services and choices F and G are incorrect because the Front Controller does not represent the Controller out of the MVC architecture. Some useful links: http://developer.java.sun.com/developer/technicalArticles/J2EE/patterns/ http://java.sun.com/blueprints/patterns/j2ee_patterns/front_controller/index.html http://java.sun.com/blueprints/ Useful book: Core J2EE Patterns: Best Practices and Design Strategies - ISBN: 0130648841A sample chapter is available here: http://www.sun.com/books/catalog/crupi/index_Table+of+Contents.html Note: This type of question will probably feature in the new EJB 2.0 specification version of the SCEA certification.
177 You are designing a complex set of classes that provides a secure framework for other programmers to use. The idea behind this framework is that it will allow other programmers to write secure programs without getting bogged down with the complexities of writing secure applications. What sort of design pattern is being used here?
290
291
A B C D
Choice B is correct. Facade - (GOF 185): "Provide a unified interface to a set of interfaces in a subsystem. Facade defines a higher-level interface that makes the subsystem easier to use. "The other patterns are described below: Adapter - (GOF 139):"Convert the interface of a class into another interface clients expect. Adapter lets classes work together that couldn't otherwise because of incompatible interfaces. "Composite - (GOF 163):"Compose objects into tree structures to represent part-whole hierarchies. Composite lets clients treat individual objects and compositions of objects uniformly. "Decorator - (GOF 175):"Attach additional responsibilities to an object dynamically. Decorators provide a flexible alternative to sub classing for extending functionality. "Mediator - (GOF 273):"Define an object that encapsulates how a set of objects interact. Mediator promotes loose coupling by keeping objects from referring to each other explicitly, and it lets you vary their interaction independently."
178 What is the difference between the abstract factory pattern and the factory method pattern? A The factory method makes objects that should be used together. This is not the case for the abstract factory. B The abstract factory pattern provides an interface for creating a family of objects whereas factory method provides an interface for creating one object C In the abstract factory pattern the objects that the factory makes are to be used together. This is not necessarily true in the factory method pattern. D The factory method pattern is used when the class does not know the class of the object it must create. But in the abstract factory this is known in advance. E The factory method and abstract factory are essentially the same pattern but two different names are used to describe them depending on the circumstances when they are implemented. Choice B is correct. Both the Abstract Factory and Factory Method are Creational patterns. Abstract Factory - (GOF 87): "Provide an interface for creating families of related or dependent objects without specifying their concrete classes. "Factory Method - (GOF 107): "Define an interface for creating an object, but let subclasses decide, which class to instantiate. Factory Method lets a class defer instantiation to subclasses. "Choice A offers a description of the abstract factory pattern not the factory method. The descriptions in
291
292
choices C and D are the wrong way round. Choice E is incorrect as the two patterns are different.
179 You're designing a paint application and as part of the user interface you have a toolbar along the left hand side of the screen. Each of the icons on the toolbar has different actions when you are using different tools. The way you've structured it, the application is required to pass commands from one object to another. When the appropriate object receives the command, it handles the request. This is an example of which pattern? A B C D E Command Chain of Responsibility Adapter Interpreter Strategy
Choice B is correct. Chain of Responsibility - (GOF 223):"Avoid coupling the sender of a request to its receiver by giving more than one object a chance to handle the request. Chain the receiving objects and pass the request along the chain until an object handles it. "Below are descriptions of the other patterns: Command - (GOF 233):"Encapsulate a request as an object, thereby letting you parameterize clients with different requests, queue or log requests, and support undoable operations "Interpreter - (GOF 243):"Given a language, define a representation for its grammar along with an interpreter that uses the representation to interpret sentences in the language. "Adapter - (GOF 139):"Convert the interface of a class into another interface clients expect. Adapter lets classes work together that couldn't otherwise because of incompatible interfaces. "Strategy - (GOF 315):"Define a family of algorithms, encapsulate each one, and make them interchangeable. Strategy lets the algorithm vary independently from clients that use it."
180 You've had enough of you existing IDE (Integrated Development Environment) and have started work on designing your own. At the moment you're working on the undo part of the application, basically you need to be able to roll an object back so its previous state. What pattern would you use to do this? A B C D Memento State Mediator Rollback
292
293
Memento - (GOF 283):"Without violating encapsulation, capture and externalise an object's internal state so that the object can be restored to this state later. "Choices D, E and F are not names of patterns. Rollback is something you would do if a transaction were terminated halfway through. Transaction is self-explanatory. ACID stands for Atomic, Consistent, Isolatable and Durable. All transactions must adhere to this. Below are descriptions of the other patterns: State - (GOF 305):"Allow an object to alter its behavior when its internal state changes. The object will appear to change its class. "Mediator - (GOF 273):"Define an object that encapsulates how a set of objects interact. Mediator promotes loose coupling by keeping objects from referring to each other explicitly, and it lets you vary their interaction independently."
181
A B C D
Object 1 calls the method call1() on Object 2 Object 2 executes its own method call3(). This method in turn creates Object 3. Object 1 executes its own method call1(). This method in turn creates Object 2. Object 2 calls the method call3() on Object 3
Choices A and D are correct. The diagram shows a UML sequence diagram. This type of diagram shows the interaction of different objects. Time is shown from the top of the page descending. The white rectangles on the dotted lines show the objects life. Method calls are made from one object to another. In this diagram Object 1 calls Object 2's method call1(). Where the arrow begins, the object represents the caller, and where it ends, the object called. The text above the arrow is the name of the method.For more information about UML:http://www.uml.org/
293
294
182 A B C D E F
What are the benefits of asynchronous messaging? Less coupling between the sender and receiver. Provides an instant response. Does not block the sender. Good for transaction processing. "You can't get an instant response. Network doesn't have to be available.
Choices A, C and F are correct. The main difference between asynchronous messaging and synchronous messaging is that synchronous provides an instant response. This means that when using asynchronous messaging, clients do not have not wait for responses; they send messages and then carry on with what they were doing. This reduces the coupling between the sender and receiver and it also means that the network doesn't have to be available. Choices B and D are incorrect because they describe synchronous messaging. Although choice E is correct it is not a benefit of synchronous messaging.
183 You are designing an online shopping application to make it easier for customers to order products from your company. The aim is that the majority of customers buying over the phone will start using the web instead. When customers purchases goods online they will use credit cards and will require an instant response as to whether the sale has been approved or not. (Note the credit card validation is carried out by another very powerful system.) What type of messaging should be used? A Synchronous messaging B Asynchronous messaging C You shouldn't be using messaging at all as it's not transactional. D You could use messaging because it is transactional however it's not advised, as the system would never perform well enough for an instant response.
Choice A is correct. Synchronous messaging provides an instant response and is therefore the right answer. It is always arguable as to whether messaging should be used if you require an instant response but if you do decide to use messaging then you should always use synchronous messaging when needing an instant response. Choice B is incorrect because asynchronous messaging does not provide an instant response. You can make messaging transactional by creating your own transactions in your code. Hence choice C is incorrect. Choice D is arguable too, but it is not the most appropriate answer because the question suggests that the system the messages will be sent to is very powerful and will be able to cope with the volume of traffic. So choice D would be
294
295
184 A B
What should be used if you don't need an instant response from a message? Synchronous messaging Asynchronous messaging
Choice B is correct. Synchronous messaging provides an instant response therefore asynchronous messaging is correct. Synchronous, tightly coupled communication between distributed components: This is the model of CORBA, RMI, EJB and so on. The programming model is called Remote Procedure Call (RPC).Asynchronous, loosely coupled communication between components: This is the Message Oriented Middleware or MOM model. The programming model is called Messaging.
185 You overheard two colleagues arguing about the difference between Localization and Internationalization. They turn to you to ask you to settle the argument. What is the difference between Localization and Internationalization? A Internationalization is the process of preparing a program to be used in a country other than England. B Internationalization is the process of preparing a program to be used in any country. C Localization is the process of preparing a program to be used in a country other than England. D Localization is the process of preparing a program to be used in any country. Choice B is correct. Internationalization: Adapting a program for use in any country is called Internationalization. Localization: The process of adapting a program for use in a particular country is referred to as Localization. During Localization the language of the text, message icons, colors used, dialogs, number formats, time representation and even sorting algorithms are subject to change. Choice A is incorrect because it is the other way around. Choices C and D are not accurate descriptions of Localization.
295
296
186 You have an existing mail order application that runs as an applet on the customer's browser. The applet connects to your server to retrieve product information. (Note all data is sent securely over SSL) What would you expect to change to meet the needs of users in different countries? A B C D E F G GUI text, e.g. Message box text etc. Security login procedures Dates Numbers, e.g. Currency The way the program writes to binary files. Icons, Images The way the program writes to text files.
Choices A, C, D, F and G are correct. List of items that may be subject to Internationalization: Language for Messages Formats - Numeric, Date and so on Dictionary sort order Currency symbol and position Tax and other legal rules Cultural preferences You would not need to change the way you wrote to binary files but you may need to change the way you write to text files because of the Unicode to 8 bit differences.
187 Your company has a custom operating system that it developed for some robotics hardware to be used in their research departments. One of the researchers has written a cut down Virtual Machine to run on this OS. You have started to develop some software to run on this VM however you need to convert the Unicode to 8 bit characters. In order to do this you will need to use: A B C D FileWriter OutputStreamWriter BufferedWriter StreamWriter
Choice B is correct. The OutputStreamWriter can be used to convert Unicode into 8 bit characters. Normally this is used in Internationalization to convert Unicode into local character encoding but it would work well in this situation. Choices A, C and D serve different purposes in the java.io package. Java support for Internationalization Properties Locale Resource Bundle Unicode Java.text Package InputStreamReader OutputStreamWriter
188
296
297
A B C D
Choice B is correct. The InputStreamReader can be used to convert 8 bit characters to Unicode. Choices A, C and D serve different purposes in the java.io package.Java support for Internationalization: Properties Locale Resource Bundle Unicode Java.text Package InputStreamReader OutputStreamWriter
189
A Aggregation defines a part of relationship but both objects can exist independently. But with composite aggregation if one part is removed then the other part will be removed. Think of a plane the wings have a composite aggregation relationship with the body of the plane. B Composite Aggregation defines a part of relationship but both objects can exist independently. But with aggregation if one part is removed then the other part will be removed. Think of a plane, the wings have an aggregation relationship with the body of the plane. Choice A is correct. As the answer states aggregation defines a part of relationship but both objects can exist independently. But with composite aggregation if one part is removed then the other part will be removed. The following is taken from: http://www.moskalyuk.com/edu/uml/interview_questions.htm Composition is a stronger form of aggregation. The object which is "contained" in another object is expected to live and die with the object which "contains" it. Composition is represented in the UML by a darkened diamond. An example of a composite relation is a Book and Chapter. A Book "has a" Chapter, and the Chapter cannot exist without the Book. For more information about UML please go to: http://www.uml.org/
190 You are looking at a class diagram that another developer has drawn. You notice a solid black diamond and a line linking two classes together. What does the black diamond imply in UML? A B C D E Aggregation Association Composite Aggregation / Composition Dependency Inheritance/Generalization
297
298
Composite Aggregation / Composition is shown by a solid black diamond. Aggregation defines a part of relationship but both objects can exist independently. But with composite aggregation if one part is removed then the other part will be removed. Think of a plane the wings have a composite aggregation relationship with the body of the plane. Note: Inheritance and Generalization are used to describe the same thing. The same is also true about Composite Aggregation and Composition. Aggregation is shown as a white diamond (the diamond shape is a black outline with the centre white). Association is just a single line linking classes/objects; this can have multiplicity and direction. The following is taken from:http://www.moskalyuk.com/edu/uml/interview_questions.htm Composition is a stronger form of aggregation. The object which is "contained" in another object is expected to live and die with the object which "contains" it. Composition is represented in the UML by a darkened diamond. An example of a composite relation is a Book and Chapter. A Book "has a" Chapter, and the Chapter cannot exist without the Book. For more information about UML:http://www.uml.org/
191 What does a triangular arrow shape with a solid line mean in UML? (The triangle is an outline, and not solid) A B C D E Aggregation Association Composite Aggregation / Composition Dependency Inheritance/Generalization
Choice E is correct. In UML Inheritance/Generalization is shown with a triangular arrow shape. So whenever you extend a class, you are inheriting from the class you are extending. Note: Inheritance and Generalization are used to describe the same thing. The same is also true about Composite Aggregation and Composition. Aggregation is shown a white diamond (the diamond shape is a black outline with the centre white). Association is just a single line linking classes/objects; this can have multiplicity and direction. Composite Aggregation / Composition is shown by a solid black diamond. For more information about UML:http://www.uml.org/
192 You are studying a class diagram of an exiting system so that the new functionality you are adding uses the existing class attributes wherever possible. What do the following symbols mean in UML with regards to visibility? A B # public, + protected, - private + public, - protected, # private
298
299
Choice C is correct. As the answer states the + # - symbols represent the following levels of visibility.+ Public# Protected- Private For more information about UML please go to:http://www.uml.org/
193 A B C D E F G
Which of the following are true about Vertical Scalability? (Achieved by adding servers to the system Achieved by adding capacity (memory, CPU and so on) It is generally more expensive than Horizontal scaling Decreases manageability Requires few or no changes to the system architecture Not supported by J2EE Has little or no impact on the reliability and availability of the system
Choices B, E and G are correct. Vertical Scalability, by definition means increasing a system's capacity by adding memory, processors and so on. Of the two types of Scalability (Vertical and Horizontal), Vertical Scalability is the easier to achieve because it involves few changes to the existing system's architecture. Also adding more CPU or memory to an existing system does not have any impact on reliability or availability because if the system or component fails, in the absence of redundant systems, availability and reliability would suffer. Hence choices B, E and G are correct. Choice A is incorrect because it actually describes Horizontal Scalability, which is achieved by adding more servers to a system. Horizontal Scalability is tougher to achieve because the architecture should inherently support a multi-server environment. However once implemented, it has a positive impact on the system's reliability and availability because it provides fault tolerance capabilities. Choice C is incorrect because generally it is cheaper to add capacity than to add entire new systems. Choice D is incorrect because adding capacity should have no impact on the manageability of a system. Choice F is incorrect because Vertical Scalability is easy to achieve. Most J2EE vendors also provide support for the more difficult Horizontal Scalability.
194
Which of the following are not true about 2-tier architecture models?
299
300
Clients may be validation intensive, consequently requiring powerful hardware. Any change to one tier typically affects both tiers. Represents a single point of failure. Each client makes a direct connection with the server They are not very maintainable They are quite manageable
Choices B, C and F are correct. The question asks for points about 2-tier client/server systems that are not true. Choice B is untrue because a change to one tier need not necessarily affect the other tier. For example consider an Order Entry system where the users need to see transaction history for individual customers. A new screen can be developed to take data from the transaction tables and display it on the client. In this example, no changes are required on the server. Consider an alternate example where a stored procedure accessing data spread in multiple tables now queries a materialized view. No changes would be required to clients that call the stored procedure, as long as all input and output remains the same. Although it may be true in many cases, Client/Server architectures do not always represent single points of failure. With single database servers, of course if the server fails, clients may not be able to connect to the database. However in multi-database applications, if parts of the client or server fail, other parts of the system may still be accessible. Hence choice C is a right answer. 2-tier architectures are not very manageable. Although the servers can be managed centrally, client PCs are always distributed at user locations and it is very difficult to troubleshoot them without local staff. Hence choice F is a right answer. Choice A correctly reflects what happens on a client in 2-tier applications. Choice D explains how clients interact with the database and choice E clearly lists that 2-tier architectures are not easily maintainable because of constant software updates required on the clients. Hence they are all incorrect answers.
195
300
301
In the above diagram A B C D Class A inherits from Class B Class B inherits from Class A Class B has a dependency to Class A Class A has an aggregation to Class B
Choice B is correct. From the diagram it can be inferred that A and B are concrete classes and B extends A. This is shown by the generalization relationship between B and A. Hence choice B is correct. Choice A is incorrect because class A does not inherit from class B. Choice C is incorrect because the relationship between the classes A and B is generalization, not dependency. Finally choice D is incorrect because A has an aggregation relationship with Interface C, not class B.
196 A B C D E F
In a UML class diagram Private, Protected and Public attributes are shown by -, +,# +, -,hash #, -, + -,#, + +,#, #, +, -
Choice D is correct. In UML notation, access modifiers are shown by the signs -, # and + to represent Private, Protected and Public. Hence choice D is correct. All other choices show incorrect combinations.
301
302
197 Which of the following may be used for synchronously communicating with legacy systems? A B C D E F G IIOP HTTP SHTML JRMP with JNI SMTP RMI / IIOP MOM
Choices A, D and F are correct. IIOP (Internet Inter Operable Protocol) is the protocol used by CORBA. JRMP (Java Remote Method Protocol) is the protocol used by Java-RMI. RMI / IIOP is EJB1.1's protocol. All three of these methods are examples of RPC (Remote Procedure calls) based communication, which is inherently synchronous in nature. Note that there are exceptions (event handling in CORBA and Message Driven Beans in EJB2.0), but generally speaking RPC is used for synchronous communication. Hence A, D and F are correct. HTTP, SHTML and SMTP are unrelated jargons, used for confusing the reader. Message Oriented Middleware (MOM) is used for asynchronous messaging. Hence choices B, C, E and G are incorrect.
198
A Providing Single-Sign on to a Java based application B Delegating complex processing to a separate server C Enable secure remote access to a mainframe by forwarding SSL requests to serial connections D As a database for storing the public keys of valid Certification Authorities (CA) E For performing symmetric key cryptography Choice C is correct. An off-board server is used enable secure remote access to mainframes. This is done typically done by forwarding SSL requests to the mainframes via serial connections, as indicated by choice C. An off-board server does not provide single sign on capabilities to a J2EE application. It is also not an application server that can take up complex business logic processing. An Off board server does not store public keys of trusted Certification Authorities (CA) or perform symmetric key encryption. Hence choices A, B, D and E are all incorrect.
302
303
199 Company ABC has a predominantly EJB based J2EE application that has be accessed by CORBA clients. Which connectivity option would you recommend? A B C D E RMI-JRMP RMI with JNI Java IDL RMI-IIOP HTTP tunneling
Choice D is correct. RMI-IIOP stands for Remote Method Invocation (using IIOP as the transport.) This is the protocol supported by EJB1.1 Hence choice D is correct. RMI-JRMP is used only when dealing with native Java clients. The question talks about CORBA clients but does not say anything about pure Java clients. Hence choice A is incorrect. There is also no mention of JNI support. Hence choice B is incorrect. Java IDL is useful when you have a predominantly CORBA based application. Hence choice C is incorrect. HTTP tunneling is a way to allow protocols to masquerading as other protocols and bypass firewall restrictions. Hence choice E is incorrect.
200 A B C D E
Which of the Classes and Interfaces need to be created by a bean developer? Home Interface Distributed Interface Remote Interface Bean Class Bean Interface
Choices A, C and D are correct. When developing EJB applications, developers need to create the Home Interface, the Remote Interface and the Bean Class. Hence choices A, C and D are correct. There is no such thing as the Distributed Interface or the Bean Interface. Hence choices B and E are incorrect.
201 A B C D
The Remote Interface of an Enterprise Bean extends from: java.ejb.EJBRemote javax.ejb.RemoteInterface javax.ejb.EJBObject javax.rmi.RemoteReference
Choice C is correct.
303
304
Remote Interfaces of EJBs extend from javax.ejb.EJBObject. Hence choice C is correct. Though it sounds likely, A, B and D are incorrect because there is no interface called EJBRemote, RemoteInterface or RemoteReference.
202 A B C D E
Which of the following are not applicable to the Primary Key Class? It must implement the java.io.Serializable interface It must provide a default constructor It must override hashCode() and equals() Cannot be undefined if the PK is a Compound Primary Key Primitive wrappers cannot be used when dealing with Single field keys
Choices D and E are correct. The question says 'not applicable' and only choices D and E are not true. Compound Primary Keys can remain undefined until deployment time and primitive wrappers can be used with dingle field keys. Hence choices D and E are correct. Choices A, B and C are true about Primary Keys and therefore incorrect choices.
203
A All attributes of a Stateless Session bean have to be set to null prior to passivation. B All non-transient and non-serializable fields of a Stateful Session Bean have to be set to null in the ejbPassivate() method. C The container uses Passivation on Stateful and Stateless Session Beans to allow pooling and swapping which are good techniques for resource management. D Passivation only applies to Entity Beans and not to Session Beans. Choice B is correct. When a bean is about to be passivated, the container calls the ejbPassivate() method. At this time, the bean instance can close all open resources and set all non-transient non-serializable fields to null. Hence choice B is correct. Stateless Session Beans are not passivated. Hence choice A is incorrect. While Stateful Session Beans are pooled and swapped, Stateless Session Beans are not. Hence choice C is incorrect. In addition to Entity Beans, Stateful Session Beans are passivated as well. Hence choice D is incorrect.
304
305
204 When a call is made to a single-entity find method in an entity bean, the ObjectNotFoundException is thrown indicating that the requested entity was not found. What happens to the transaction? A It is automatically rolled back since it is an application exception. B It is not automatically rolled back since it is a system exception. C It is not automatically rolled back since it is an application exception. D It is automatically rolled back since it is a system exception. E It may or may not automatically rollback based on container specific implementation. Choice C is correct. The question deals with the ability to differentiate between system exceptions and application exceptions, and their impact on transactions. The container throws the ObjectNotFoundException to indicate that the entity requested by the single entity find method was not found. When this happens, the transaction is not typically rolled back. Hence choice C is correct. Application exceptions are thrown in response to errors encountered in the processing of business logic. Application exceptions do not cause transactions to roll back. Hence choice A is incorrect. The ObjectNotFoundException is not a system exception. Hence choice B is incorrect. Again choice D indicates that the ObjectNotFoundException is a system exception and is therefore incorrect. Choice E indicates that it is up to the container to either roll back the transaction or not, which is incorrect.
205 A B C D E
Which of the following services does the EJB Container provide? Object Distribution Life Cycle Management Integrated Web Server and Servlet Engine Just in Time management Java Runtime Engine Transaction Management
Choices A, B and E are correct. The EJB developer is only responsible to developing the core service that the component provides. All other services are decorations provided by the container. For example, the container provides object distribution via the Home Interface and Remote Interface implementations and manages the life cycle of Beans. It also provides transaction management capabilities. Hence choices A, B and E are correct. Many popular EJB vendors provide a web server and a Servlet engine as well. But that is not a responsibility of the EJB Container. Hence choice C is incorrect. Choice D, mentions something about just in time management JRE, irrelevant jargon meant to throw off the reader. Hence choice D is incorrect.
305
306
206
When a client calls the create() on a Stateless Session Bean's Remote Interface,
A The newInstance() method is invoked by the container B The ejbCreate() method is called by the container C Passivated instance is activated and attached to the EJB Object D The Container takes an instance from the Method Ready Pool and attaches it to the EJB Object. Choice D is correct. With Stateless Session Beans, a new instance is not created each time a client request comes in. Instead, the container manages a pool of bean instances, and when a client requests the service (via a create method), an instance from the pool is assigned to service the request. Hence choice D is correct. The newInstance() method and the ejbCreate() method are invoked by the container to set up the instances in the bean pool and are not called with each create() method called by the client. Hence choices A and B are incorrect. Choice C is incorrect because Stateless Session Beans are not passivated or activated.
207
The container will synchronize an Entity Bean's state with the database,
A After every setXxx() method B When a client calls the ejbLoad() or ejbStore() method C When the container thinks its appropriate based on various factors including the Transactional Context. D When the connection.flush() method is called. Choice C is correct. In CMP, the container automatically handles synchronization between the bean and the database. With BMP the developer is responsible for providing the logic for database synchronization. In both cases however, the container decides when the synchronization should occur, based on various activities such as transactions, concurrency and resource management. Hence choice C is correct. It is not guaranteed that data will be synchronized after each set method. Again this is because the container decides when to synchronize data. Hence choice A is incorrect. The methods ejbLoad() and and ejbStore() are considered callback methods - the container uses them to communicate with the entity when it is about to or just has synchronized database state. Hence clients do not make calls to these methods. Choice B is therefore incorrect. There is no method called connectionFlush(). Hence choice D is incorrect.
208
306
307
Choice C is correct. Although port numbers are configurable, the default ports for HTTPS and HTTP are 443 and 80. Hence choice C is correct. Port 21 is used with FTP, port 110 is used with POP3 and port 119 is used with NNTP. Hence choices A and D are incorrect. Choice B has the port numbers in the reverse order. Hence choice B is incorrect.
209 A browser client C1 opens an SSL session with Server S1 on port 443. C1 then opens a new browser window and opens an SSL session with Server S2 (while the SSL session with S1 is active in the other browser window.) At the same time client C2 opens an SSL session with S1 on 443 as well. Which of the following statements are false? A B time. C D Client C1 cannot be engaged in two SSL connections as the same time. S1 cannot be engaged in two SSL connections on the same port at the same C1 can have multiple SSL connections open at the same time. S1 can have multiple SSL connections open at the same time.
Choices A and B are correct. Note that the question asks you which choices are false. Since clients can simultaneously engage in multiple SSL connections (through different browser instances) and servers can support multiple concurrent SSL connections, only choices A and B are false and therefore the right answers. Choices C and D are true and therefore incorrect.
210 A B C D
Messaging is achieved by: Synchronous tightly coupled communication between distributed components Asynchronous loosely coupled communication between components Using Stubs and Skeletons Marshalling and unmarshalling of data
Choice B is correct. Messaging is a middleware architecture that is used for asynchronous communication. This is generally achieved through a store-and-forward mechanism. All message
307
308
producers and message consumers communicate to each other via a Message Oriented Middleware. Message consumers receive messages via a polling mechanism or a server-push mechanism. Hence choice B is correct. Synchronous tightly coupled communication is a feature of RPC middleware applications. Hence choice A is incorrect. Stubs and Skeletons are used to Marshall and unmarshall data in distributed RPC environments. Hence choices C and D are incorrect.
211 A B C D
Messaging supports which of the following two models: Point to Point Envelope/Letter Publish/Subscribe Send to List
Choices A and C are correct. There are two models available in Messaging. Point-to-Point is typically used for a one to one communication and Publish Subscribe is used when messages need to be broadcast to a group of subscribers. Hence choices A and C are correct. The envelope-content is not a messaging paradigm. It is an example used to illustrate how messages are constructed when using Simple Object Access Protocol (SOAP.) Hence choice B is incorrect. There is no paradigm called Send to List. Publish Subscribe is used for one to many communication. Hence choice D is incorrect.
212 A B C D
Which of the following is not true about RPC? RPC attempts to mimic the behavior of a system that runs in one process When a remote procedure is invoked, the caller is blocked until the procedure completes and returns control RPC is asynchronous in nature RPC is tightly coupled
Choice C is correct. The question is asking what is false about RPC. Only choice C, which says that RPC is asynchronous in nature, is false. Therefore choice C is correct. Choices A, B and D are true statements about RPC based communication and hence incorrect.
308
309
213 What is the difference between Maintainability and Manageability in Software Engineering? A Manageability is the ability to correct flaws in the system whereas maintainability is the ability to ensure the continued health of the system. B Maintainability is the ability to correct flaws in the system whereas manageability is the ability to ensure the continued health of the system. C Maintainability deals with ensuring that the system is always reliable and accessible whereas manageability deals with the ability to add functionality to the system. D They are both the same. Choice B is correct. Maintainability (Cade 8),"is the ability to correct flaws in the existing system without impacting other components of the system" and manageability (Cade 9)"is the ability to manage the system to ensure the continued health of a system with respect to scalability, reliability, availability, performance and security." Hence choice B is correct. The definitions in choice A are in the reverse order and incorrect in choice C. Choice D is trying to say that the two non-functional requirements refer to the same thing. Hence they are all incorrect.
214 A B C D E F G
Which of the following are not considered tiers in a J2EE based n-tier model? Client Tier Web Tier EJB Integration Tier EIS Tier EIS Integration Tier Legacy Connectivity Tier JCA Tier
Choices C, F and G are correct. The question is asking what choices are not considered as J2EE tiers. There are no tiers called 'EJB Integration Tier', 'Legacy Connectivity Tier' or 'JCA Tier.' Hence choices C, F and G are correct. J2EE applications have the following tiers: Client (Browsers, Applications, Applets, Mobile clients and so on), Web (presentation tier consisting of JSP as view and Servlets as controllers), EJB (Business Tier, consisting of EJB and supporting classes), EIS Integration (Java classes that integrate to the Enterprise Information System tier) and finally the EIS tier (relational databases, XML databases, ERP systems and so on.) Hence choices A, B, D and E are all valid J2EE application tiers and therefore incorrect.
309
310
215 A B C D
Which of the following are true about client/server based applications? Clients are typically used for data presentation, validation and for processing business logic. Most client/server applications follow the Model2 architecture as opposed to ntier applications that follow Model3. In client/server applications, the client normally consists of the view, controller and parts of the model. In typical client/server applications, the presentation tier (windows) generally talks to controller (a data dispatcher), which then talks to objects that represent the enterprise data. Client/server applications generally have fat clients and sometimes, fat servers as well. Hence both the client and the server could offer portability problems.
Choices A, C and E are correct. In 2-tier applications, clients are typically used for data presentation, validation of user inputs and processing of business logic. Hence choice A is correct. If you compare the functions performed by the client with the MVC pattern, the client performs the duties of the view, the controller and parts of the model. The client interacts with the database and retrieves data. This data is then assembled into the required view. For example, a window that shows all orders taken in 1 day sorted by the customer number. The client thus acts as the view in MVC. When some search criteria is entered and the user presses a button to retrieve necessary data, the client appropriately dispatches the request to the database interaction object that retrieves the necessary data. Here the client acts as the controller. Most database interaction is encapsulated in a set of database access objects. These objects perform business rules processing. Here the client performs the job of the MVC model. Some logic is also encapsulated on the server side via triggers and stored procedures. Hence it is possible that the database also performs some model tasks in 2tier applications. Hence choice C is correct. Client/server applications frequently suffer from fat clients or fat servers or a combination of both. This is because either all the logic is coded in the client (4GL scripting language) or all the logic is coded on the server (through stored procedures and triggers) or a combination of both. This results in poor portability of such applications. Hence choice E is correct. Choice B indicates that 2-tier applications follow Model2 architecture whereas n-tier applications follow Model3 architecture. This is untrue, because it is n-tier applications that normally follow the Model2 architecture. Hence choice B is incorrect. Although object oriented client/server platforms may offer the tools to decouple windows and database interaction objects that is not a normal feature in 2-tier applications. Hence choice D is incorrect.
216 In n-tier models, which tier is best suited for implementing the view, and controller components of an MVC application? A Client Tier
310
311
Choice B is correct. n-tier models typically follow a Model2 architecture where each tier has specific responsibilities. The view and most of the controller components are generally placed in the Web Tier (note: in some Model2 architectures, some controller components are also placed in the business logic tier.) Hence choice B is correct. Choice A is incorrect because the client tier is not responsible for the view and controller objects. Choice C is incorrect because there no such tier as MVC tier. Choices D, E and F are incorrect because none of them hold the view components (although some controller components may be present in the Business logic tier.)
217 Which of the following are not service level requirements that affect software architecture? A B C D E F G Detailed Design Performance Reliability Training Availability Security Design Patterns
Choices A, D and G are correct. Service level requirements (Cade 6) or Quality of Service (QoS) requirements are those that are needed by an application to satisfy the business requirements of a system. Performance, Scalability, Reliability, Availability, Extensibility, Maintainability, Manageability and Security are Non-functional service level requirements. While choices A and D illustrate important aspects of a software project, they are not considered QoS requirements. Although choice D describes a best practice that is frequently used by good designers, it too is not a Service level requirement. Hence choices A, D and G are correct. Performance, Reliability, Availability and Security are service level requirements and therefore choices B, C, E and F are incorrect.
311
312
Which of the following UML diagrams may be best suited for a Business Analyst? Deployment Class Use Case Activity Collaboration Sequence
Choice C is correct. Use Case diagrams (Cade 43)"show a set of use cases and actors and their relationships. Use Case diagrams show the static view of a system. These diagrams are especially important in organizing and modeling the behaviors of a system." Use case diagrams are frequently used by Business Analysts to capture business requirements of a system. Choice C is therefore correct. Deployment diagrams (Cade 50)"show the configuration of run time processing nodes and the components that live within these nodes. Deployment diagrams address the static view of the architecture." Architects frequently use deployment diagrams. Choice A is therefore incorrect. A class diagram (Cade 44)"shows a set of classes, interfaces and collaborations and their relationshipsClass diagrams address the static design view of a system." Software designers frequently use class diagrams. Choice B is therefore incorrect. Activity diagrams (Cade 48)"are a special kind of state chart diagram that show the flow from activity to activity within the system. This type of diagram is important in modeling the function of a system and emphasizing the flow of control among objects." Designers and Developers frequently use Activity diagrams. Hence choice D is incorrect. A Collaboration diagram (Cade 46)"is an interaction diagram that emphasizes the structural organization of objects that send and receive messages." Designers and developers frequently use Interaction diagrams. Choice E is therefore incorrect. Sequence Diagrams (Cade 46) are"interaction diagrams that emphasize the time ordering of messages." Interaction diagrams address the dynamic view of a system and are frequency used by designers and developers. Hence choice F is incorrect.
219 Since a dependency exists between two packages if a dependency exists between any two classes in the packages, it can be deduced that all package dependencies are transitive in nature. True/False? A B True False
Choice B is correct. Package Diagrams (Fowler 108)"show packages of classes and the dependencies among them A dependency exists between two elements if changes to the definition of one element may cause changes to the otherA dependency between two packages exists if any dependency exists between any two classes in the packagesWith
312
313
packages dependencies are non-transitive." The question makes an argument that all package dependencies are transitive in nature, which is false. Hence choice B is correct.
220
A B C
The Session Facade Object The Acct Object The AcctWebImpl Object
Choice C is correct. The diagram shows a Collaboration Diagram (Collaboration diagrams are Interaction diagrams and they address the dynamic view of a system. They emphasize on the structural organization of objects. Read the SCEA for J2EE Study Guide for more information.) 1.1.1 Represents an initialization method called by the value object AcctWebImpl on itself upon construction.
221 Megasoft Corporation has a old application that uses a legacy database. Recently Megasoft made a decision to develop the front-end code for the application using the Java Applet technology. At this time however, Megasoft is not interested migrating its data to a relational database. In the order of importance, which of the following may be the best approach to connect to the legacy database. A B C JDBC-Bridge, Database Middleware, JDBC Database Middleware, JDBC-ODBC bridge, JDBC JDBC, Database Middleware, JDBC-ODBC bridge
313
314
Updating the data storage tier (Jaworski 532.) "If the data storage tier of a legacy system utilizes a relational database system, JDBC may be used to provide connectivity to legacy databases. In most cases, legacy databases will not support a pure JDBC driver. If the existing system provides ODBC support, the JDBC-ODBC Bridge can be used. If the database uses custom drivers, it might be possible to find database middleware that supports the custom driver and either an ODBC or JDBC interface." It is therefore preferable to try for pure JDBC driver support, failing which one may opt for a JDBCODBC Bridge. If that too is not possible, then a database middleware may be used. Choice D is therefore correct. Although choices A, B and C give the same three alternatives, they are in incorrect orders of preference. Hence choices A, B and C are incorrect.
222 Michael Fell runs a computer assembly company. He purchases parts from a wholesale parts distributor. Fell has a legacy application to track purchases of parts and sale of computers. Although the current system is very inflexible, the GUI is not very tightly coupled to the business layer. As an architect, what medium to long-term solution would you offer, given that Fell does not want to do away with his entire application yet? A Use Screen Scraping and Off-board server to provide information to a Java based application. B Refactor the legacy code to make it flexible. C Rewrite the inflexible parts of the application alone using Servlets D Decouple the existing front-end and replace it with a J2EE based solution E Replace the inflexible parts with a flexible ERP solution Choice D is correct. The key in this question is that the GUI is not very tightly coupled to the business layer. This means that the GUI can be decoupled form the system fairly easily. Further, the question asks for a medium to long-term solution. Thus in this case, using a J2EE based front-end may be preferable. Hence choice D is correct. The use of screen scrapers may have been the best short-term solution. However it is certainly not the best medium to long-term approach. Hence choice A is incorrect. Code re-factoring is not an alternative here. The question does not say anything about what the legacy system is written in and whether is easy to modularize its code. Hence choice B is incorrect. The question only mentions about changing the GUI. They are not looking to rewrite all inflexible parts of the system. Hence choice C is incorrect. Choice E is incorrect because it refers to replacing all inflexible parts of the system. Further there is no indication anywhere in the question that an ERP solution might make it more flexible. 223 Which design pattern can be used to create a family of dependent objects?
314
315
A B C D E
Choice D is correct. Abstract Factory (GOF 87)"Provide an interface for creating families of related or dependent objects without specifying their concrete classes." Hence choice D is correct. Factory Method (GOF 107)" Define an interface for creating an object, but let subclasses decide which class to instantiate. Factory method lets a class defer instantiation to subclasses." Hence choice A is incorrect. Prototype (GOF 117)" Specify the kinds of objects to create using a prototypical instance, and create new objects by copying this prototype." Hence choice B is incorrect. Builder (GOF 97)"Separate the construction of a complex object from its representation so that the same construction process can create different representations." Hence choice C is incorrect. Singleton (GOF 127)" Ensure a class only has one instance, and provide a global point of access to it." Hence choice E is incorrect.
224 Pensacola, a Florida based soda company has just started operations in Dallas, TX to counter competition from Dr. Pepper. Pensacola believes that using a J2EE based application will put them ahead of the competition. Their new architect is suggesting that Session Beans be used to provide a unified interface to the Entity Beans in the system. The use of session beans here illustrates the use of what design pattern? A B C D E F Flyweight Proxy Faade Decorator Adapter Bridge
Choice C is correct. Fa ade (GOF 185)"Provide a unified interface to a set of interfaces in a subsystem." The following is taken from: http://java.sun.com/blueprints/corej2eepatterns/Patterns/SessionFacade.html "Use a session bean as a facade to encapsulate the complexity of interactions between the business objects participating in a workflow. The Session Facade manages the business objects, and provides a uniform coarse-grained service access layer to clients." Hence choice C is correct. Flyweight (GOF 195)"Use sharing to support large numbers of fine-grained object efficiently." Hence choice A is incorrect. Proxy (GOF 207)"Provide a surrogate or placeholder for another object to control access to it." Hence choice B is incorrect.
315
316
Decorator (GOF 175)"Attach additional responsibilities to an object dynamically. Decorators provide a flexible alternative to subclassing for extending functionality." Hence choice D is incorrect. Adapter (GOF 139)"Convert the interface of a class into another interface clients expect. Adapter lets classes work together that couldn't otherwise because of incompatible interfaces." Hence choice E is incorrect. Bridge (GOF 151)"Decouple an abstraction from its implementation so that the two can vary independently." Hence choice F is incorrect.
225 One of the advantages of using Stateless Session Beans is that they are lightweight objects and do not have conversational state overheads. Further, the container swaps these bean instances in and out of the bean pool to appropriately manage resources. This allows the container to use fewer instances of the bean to service a larger number of clients. What design pattern is being illustrated here? A B C D E Decorator Factory Faade Flyweight Visitor
Choice D is correct. Flyweight (GOF 195)"Use sharing to support large numbers of fine-grained object efficiently." Here the container uses fewer instances of Stateless Session Beans to service a larger number of clients. Hence choice D is correct. Decorator (GOF 175)"Attach additional responsibilities to an object dynamically. Decorators provide a flexible alternative to subclassing for extending functionality." Hence choice A is incorrect. Factory Method (GOF 107)" Define an interface for creating an object, but let subclasses decide which class to instantiate. Factory method lets a class defer instantiation to subclasses." Hence choice B is incorrect. Facade (GOF 185)"Provide a unified interface to a set of interfaces in a subsystem." Hence choice C is incorrect. Visitor (GOF 331)"Represent an operation to be performed on the elements of an object structure. Visitor lets you define a new operation without changing the classes of the elements on which it operates." Hence choice E is incorrect.
226 You can traverse through the elements of many Java Collection objects because they provide a way to access their elements sequentially. What design pattern is used here? A Visitor
316
317
Choice D is correct. Iterator (GOF 257)"Provide a way to access the elements of an aggregate object sequentially without exposing its underlying representation." Hence choice D is correct. Visitor (GOF 331)"Represent an operation to be performed on the elements of an object structure. Visitor lets you define a new operation without changing the classes of the elements on which it operates." Hence choice A is incorrect. Observer (GOF 293)"Define a one-to-many dependency between objects so that when one object changes state, all its dependents are notified and updated automatically." Hence choice B is incorrect. Builder (GOF 97)"Separate the construction of a complex object from its representation so that the same construction process can create different representations." Hence choice C is incorrect. Proxy (GOF 207)"Provide a surrogate or placeholder for another object to control access to it." Hence choice E is incorrect. Decorator (GOF 175)"Attach additional responsibilities to an object dynamically. Decorators provide a flexible alternative to subclassing for extending functionality." Hence choice F is incorrect.
227 Compact Computers is a small computer assembly company. Any customer currently has the following choices for a PC: (i) (ii) (iii) 800 MHz processor, 40 GB HDD, 128 MB RAM 1 GHz processor, 60 GB HDD, 256 MB RAM 1.2 GHz processor, 80 GB HDD, 512 MB RAM
The use of what design pattern would ensure that only the legal combinations could be sold? A B C D E Factory Method Builder Prototype Abstract Factory Singleton
Choice D is correct. This question needs you to apply your knowledge of design patterns. We are dealing with families of related objects. Abstract Factory (GOF 87)"Provide an interface for creating families of related or dependent objects without specifying their concrete classes."
317
318
The applicability section of Abstract Factory (GOF 88) indicates that this pattern is to be used when: A system should be configured with one of multiple families of products A family of related product objects is to be used together and the constraint needs to be enforced. Hence Abstract Factory is the right pattern for this problem. Choice D is therefore correct. Factory Method (GOF 107)" Define an interface for creating an object, but let subclasses decide which class to instantiate. Factory method lets a class defer instantiation to subclasses." Hence choice A is incorrect. Builder (GOF 97)"Separate the construction of a complex object from its representation so that the same construction process can create different representations." Hence choice B is incorrect. Prototype (GOF 117)" Specify the kinds of objects to create using a prototypical instance, and create new objects by copying this prototype." Hence choice C is incorrect. Singleton (GOF 127)" Ensure a class only has one instance, and provide a global point of access to it." Hence choice E is incorrect.
228 Inaccu Weather has a web site where people can check the weather forecast of a city for up to five days in advance. The data comes to Inaccu Weather through a specialized custom feed that directly updates a relational database. If the company can expect between fifty to hundred concurrent hits in to their site, which of the following Java based technologies may be best suited for their needs? A Servlets and JSP for presentation and Session Beans with DAO for retrieval. B Servlets and JSP for presentation and CMP Beans for retrieval C Servlets and JSP for presentation and BMP Beans for retrieval D Applets for presentation and either Entity or Session Beans for retrieval E Servlets and JSP for presentation with Java classes encapsulating all database access. Choice E is correct. The key points are: Low traffic that this site will be encountering The fact that the data is not modified through the site. All database access is going to be for simple read-only data. From these points we can summarize that the use of EJBs will be overkill for such a simple application. However you still do not want to embed data access logic directly into Servlets, as that would not be a very modular approach. Hence use Servlets and JSP for presentation and Java classes to encapsulate interactions with the database. Choice E is therefore correct. While choice A is a straightforward Model2 technique for this system, the use of EJB is not required here. Hence choice A is incorrect. Note that if the traffic becomes much higher and they wish to migrate to an EJB solution, choice A would become the best candidate.
318
319
We have discussed that the use of EJB is not necessary for this application. Further there is no concurrent use of shared data. Hence Entity beans are definitely not the ideal choice. Choice B and C are therefore incorrect. Choice D indicates the use of Applets and EJB. Applets are best used when better GUI capability is required. In this example, JSP is a perfectly good solution. In any case, this choice refers to the use of EJB (already discussed as extra baggage for this problem.) Hence choice D is incorrect.
229 Toysrfuss, a national toy store is creating a new e-front for Order processing. Customers have to create an account to transact with them, although an account is not required for browsing the catalog. Customers can browse items and add them to a shopping cart. They can then proceed to checkout. At this time, they can update quantities and submit the order. What technologies may be best suited for this application? A B C D E F G H JSP for presentation and Servlets as controllers. Servlets for presentation and JSP as controller. Stateless Session Bean for Shopping cart Stateless session bean for catalog retrieval. Stateful Session bean for shopping cart. Stateful session bean for Order update. Entity bean for Catalog retrieval Entity bean for Order update.
Choices A, D, E and H are correct. The use of JSP for presentation and Servlets for controllers is consistent with the Model 2 approach. Hence A is a right choice. Choice B is the opposite of choice A and therefore incorrect. Choice C is incorrect because it is suggesting the use of a Stateless Session bean for the management of the shopping cart. Since stateless beans do not maintain any conversational state, they cannot be used for this purpose. The use of a stateless session bean for catalog retrieval is consistent with the Model 2 architecture and a recommended best practice. Choice D is therefore correct. Stateful Session Beans hold conversational state. Hence the management of a shopping cart is a good example of their use. E is therefore correct. Stateful Session beans are not very useful for updating order information. F is therefore incorrect. Entity beans for catalog retrieval are overkill because Entity beans are best used when shared data is being concurrently accessed or heavy transactional DML statements are required. G is therefore incorrect. Entity beans represent the enterprise data of a system and perform specialized DML operations like inserts, deletes and updates. They would be perfect for updating order information. H is therefore a correct choice.
319
320
230 Of the following scenarios, which one may be best suited for the use of Entity Enterprise Beans? A Calculation of tax information, based on data retrieved by two other Entity Beans B To maintain shopping cart state for an online application C To retrieve product catalogs based on a search criteria D To allow concurrent access to shared data, as in the case of on an online auction house's application. Choice D is correct. While Entity beans model business concepts, usually persisted as records in some kind of database, it is not necessary to use Entity beans every time you interact with the database. In fact from a performance point of view, simple selects and retrieval can be just as easily done using Session Beans with Data Access Objects (DAO.) Entity Beans are best used when you are dealing with concurrent access to shared data, where transactions, concurrency and integrity play a vital role. Hence choice D is correct. Choice A refers to using existing data and performing some calculation on it. This can be best achieved through a Stateless Session Bean. Hence choice A is incorrect. Choice B talks about maintaining conversational state. This is best dome with Stateful Session Beans. Hence choice B is incorrect. Retrieval of product catalogs is a simple query. Again this can be done through Stateless Session Beans and DAO. Hence choice C is incorrect.
231 Most EJB servers show high degree of availability. Server clusters are an example of how this is functionality is achieved. What key advantages might server clusters offer in an EJB environment? A B C D E Load distribution Location transparency Caching capability Load balancing capability 2PC (Two phase commit) capability
Choices A and D are correct. Server clusters increase availability and redundancy in a system. They also provide fault tolerance. With clusters, requests can be distributed so that multiple servers share the load. Some servers may also offer the sophistication to determine which servers are under utilized so that load can be balanced. Hence choices A and D are correct.
320
321
Location Transparency is achieved through Object Distribution. This is a feature of all distributed systems. Hence choice B is incorrect. Various vendors may offer a variety of tools for better resource management. Caching may be one such capability. It has nothing to do with a multi-server environment though. Hence choice C is incorrect. Two phase commit (2PC) may be a feature offered by many J2EE vendors for addressing distributed transactions. Again this is not a feature of server clustering. Hence choice E is incorrect.
232 Status Quo is an emerging B2C company that has a portal through which customers can purchase clay jewelry. Since the order process involves a shopping cart, session management and secure access are required. How would you manage this? A B C D Use HTTP since it is a stateful protocol Use HTTPS since it is a stateful protocol Use SOAP for state and security management. Use CGI with cookies for state management.
Choice B is correct. HTTPS is a secure and stateful protocol. Choice A is incorrect because HTTP is inherently stateless. Choice C is incorrect because SOAP is an RPC mechanism, not a state management mechanism. Choice D is incorrect because CGI programs are server side processes (comparable to Java Servlets.) They do not manage session state.
233 Chocolat, an exotic chocolate maker in France is planning to provide an e-front for chocolate sales. FedEx would ship the packages to various national and international locations. In order to customize the customer's interaction with the system and to make his / her overall shopping experience more pleasant, Chocolat has decided to support Internationalization. What are some of the common things they would need to consider? A B C D E F Language for messages. Formats (numeric, date and so on.) DMZ requirements Taxes and legal rules. RSA MD5
321
322
This question deals with Internationalization. Language for messages, formats (numbers, date and so on), taxes and legal rules are all subject to Internationalization. Hence A, B and D are correct. Choice C refers to a security mechanism where a demilitarized zone is created between two firewalls and is irrelevant to I18N. RSA and MD5 are security terminology used with cryptography. Therefore choices E and F are incorrect.
234 A sample program ships with 2 properties files - Base.properties, Base_fr.properties. If the current Locale, Locale.ENGLISH has no matching properties file, what will happen when the ResourceBundle.getBundle method is called with 'Base' and Locale. English as parameters? A Since a matching properties file is not found, an exception is thrown B This would not pose a problem because when a matching properties file is not found, the default properties file is used instead. Choice B is correct. When the getBundle() method is called on ResourceBundle, it checks to see if a class or property file is available for the base parameter's current locale. If neither is available, it uses the default. In this case Base.Properties will be used. Hence choice B is correct.
235
A The logical separation of tiers in a J2EE application. Example: the separation between the Web Tier and the EJB Tier B The logical separation of layers in a J2EE application. Example: The separation between the Operating System and the EJB Container. C A type of protection offered by proxy firewalls, currently only available to the U.S armed forces under National Security laws. D The region between two firewalls Choice D is correct. Demilitarized Zone (DMZ) is an area between two firewalls. The outer firewall lets requests to publicly accessible services in. It will reject all other requests. The inner firewall will protect the company's internal network and prevent requests coming into the DMZ from passing through it. Choice D is therefore correct. Choices A, B and C are all incorrect.
236 ScreamWorks, a cinema multiplex, has a website from which you may download signed applets with the latest trailers, show timings and so on. The Applet works on Java 1.3 or higher. The applet needs to write user preferences to a temp file in the host
322
323
machine (where it is being executed). Is that possible? Note that the client has defined a usePolicy and the java.policy has granted no persmissions for the applet
A Applets cannot be used here because even signed applets are untrusted if the necessary permissions are not granted B The sandbox model does not apply to signed applets. Hence this will pose no problem. Choice A is correct. This question expects you to be familiar with the changes in the Java 2 Security model. In JDK1.2 and higher, all code local and remote can be subjected to a security policy. By default, remote code will be constrained to the old Sandbox model. However if a policy file is created with grant privileges, an applet will be restricted to the grants whether or not it is signed. Hence choice A is correct.
237 A B C D E F
Which of the following are valid methods in Entity EJBs? ejbActivate() observe() ejbRetrieve() ejbStore() ejbDestroy() ejbRemove()
Choices A, D and F are correct. Entity Beans are subject to activation and Passivation. The container informs the bean that the bean is about to be passivated or activated through the two callback methods - ejbPassivate() and ejbActivate(). EjbStore() is a callback method used during database synchronization. EjbRemove() is called when the client wishes to remove the data the bean represents, from the database. Hence choices A, D and F are correct. EjbSave(), ejbRetrieve() and ejbDestroy() are not valid methods for EJBs. Hence choices B, C and E are incorrect.
238 What does the term Atomicity mean in the context of ACID transactional properties and Enterprise Java Beans?
A B C D
Integrity of underlying data Non Interference from other processes or systems Complete execution or no execution at all Maintenance of all data changes in physical storage
323
324
Choice C is correct. Atomicity (Monson-Haefel 2nd edition 275)"To be atomic, a transaction must execute completely or not at all." Hence choice C is correct. Choice A refers to 'Consistency.' Hence it is incorrect. Choice B refers to 'Isolation.' Hence it is incorrect. Choice D refers to 'Durability.' Hence it is incorrect. 239 Which of the following statements about 'Not Supported' and 'Never' transactional attributes are true? A Not Supported' suspends any transaction until the method is completed whereas 'Never' throws a RemoteException when called with a transaction. B Never' suspends any transaction until the method is completed whereas 'Not Supported' throws a RemoteException. C If the method is called without any transactional scope, both attributes will work identically. D If the method is called with a transactional scope, both attributes will work identically. Choices A and C are correct. Choice A describes how the transactional attributes 'Not Supported' and 'Never' work. A is therefore correct. B is the inverse of A and therefore incorrect. C describes a situation where a method with transactional attribute 'Not Supported' or 'Never' is called without a transactional scope. In this case they both behave identically. Choice C is therefore correct. Choice D indicates that under both circumstances the method will execute identically. This is incorrect because a 'Never' method will throw a 'RemoteException' if called with a transaction. D is therefore incorrect.
240 EJB1.1 has support for undefined Primary Keys. This means that the Primary Key can be undefined until deployment time. When we use defined Primary Keys, the Bean class and the Interfaces use the BeanPK type to identify the key. What do the Bean class and the Interfaces refer to in the case of undefined Primary Keys?
A Though the Primary Key itself can be undefined, its name must be predetermined. The Bean class and the Interfaces use this name. B An instance of java.util.Enumeration C An instance of java.lang.Class D An instance of java.lang.Object Choice D is correct.
324
325
EJB 1.1 has support for undefined Primary Keys, which means that they can be deferred until deployment time. When undefined Primary Keys are used, the Bean class and its interfaces can refer to the undefined key using java.lang.Object. Choice A gives some incorrect information to throw you off. Choices B and C are incorrect because you cannot use java.lang.Enumeration or java.lang.Class for referring to undefined Primary Keys. 241 Which of the following statements is true about DNS Round Robin?
A It considers actual load on machines before routing requests. B It uses a random generator to decide which server to route a request to. C It routs requests to one server until a configured threshold is reached and then sends subsequent requests to the next server. D Each Request is sent to subsequent server in the list, after the end is reached it starts with the first server again. Choice D is correct. DNS Round Robin is a method is load distribution by which a set of servers is allowed to process incoming requests in sequence. The first request goes to the first server, the second to the second server and so on. When the end is reached, the next request starts from the first server again. Hence choice D is correct. Note that DNS Round Robin is a good load distribution technique, not a load balancing technique. Since requests get processed sequentially in DNS Round Robin, the current load on a server is not taken into account before a new request is delegated to a server. In load balancing techniques however, the load on individual servers is monitored before additional requests are sent to them. Hence choice A is incorrect. DNS Round Robin allows servers to process requests sequentially, not in a random fashion. Hence choice B is incorrect. With load balancing techniques, a load monitor may check for the current load on a primary server before deciding to delegate subsequent requests to another server. This is not true of DNS Round Robin though. Hence choice C is incorrect. 242 A B C D Generally speaking what is the relevance between Performance and Security? They are not related to each other in any way t 4High Security generally results in high performance High performance is a pre-requisite for secure systems Security and Performance are inversely proportional Low performance systems cannot be secure
Choice D is correct. One of the key aspects of security is encryption and decryption of data. Data encryption ensures that sensitive data will be protected against eavesdropping and tampering. A concept called 'cryptography' is used for accomplishing this. The two popular types of cryptography are 'Public Key Cryptography' or 'Asymmetric Key Cryptography' and 'Symmetric Key Cryptography.' In both forms, a combination of Cryptographic algorithms
325
326
(ciphers) and hashing algorithms protect the data from intruders. The data is decrypted at the receiver's end and becomes intelligible again. All this work results in extra overheads. Hence generally increased security results in a lower performance. Choice D is therefore correct. Higher security results in lower performance. Hence choices A and B are incorrect. A high performance is not a technical pre-requisite for secure systems although it may be a good idea to increase performance wherever possible to offset the performance loss due to higher security. Hence choice C is incorrect. Many poorly engineered secure systems exhibit poor performance. Hence choice E is incorrect.
243
In the above diagram: A B C D E F A has an association relationship with C C has an association relationship with A A has a composition relationship with C C has a composition relationship with A A has an aggregation relationship with C C has an aggregation relationship with A
Choice E is correct. Aggregate relationship in UML is denoted with an open diamond on one side of an association relationship. In the above diagram, class A has an aggregate relationship with Interface C. Generally this means that at runtime, class A will hold a reference to an object that implements Interface C. Hence choice E is correct. The interface C does not have an association, aggregation or composition relationship with class A. Choices B and D and F are therefore incorrect.
326
327
If class A had a solid diamond instead of an open diamond, it would have represented a composition. Hence choice C is incorrect.
244
A B C D E
Object Interaction Diagram Collaboration Diagram State Diagram Sequence Diagram Activity Diagram
Choice D is correct. The diagram shown above represents a Sequence diagram. A sequence diagram is an interaction diagram that shows the time ordering of events. Choice D is therefore correct.
245 A B C
CORBA specification does not provide support for which of the following? Naming Service Container managed Persistence Security
327
328
Choice B is correct. CORBA does not provide support for 'Container Managed Persistence.' CMP is a concept only supported by the EJB specification. Hence choice B is correct. CORBA has support for Naming, Security, Transactions, Events and Concurrency control. Hence the other choices are incorrect.
246 Company ABC has a legacy application that can be accessed via CORBA. The company wants to integrate new Java based development with the existing legacy services. At this time no new services are planned. If the legacy application were primarily to be used as a CORBA server, which connectivity option would you recommend? A B C D E RMI-JRMP RMI with JNI Java IDL RMI-IIOP HTTP tunneling
Choice C is correct. The key here is that the existing legacy system supports a CORBA interface and no new services are being currently planned. If Java code is primarily going to access CORBA services, the recommended connectivity tool is Java IDL. Java IDL gives Java code CORBA capability. Hence choice C is the correct answer. RMI-JRMP should be used when dealing with distributed applications, all written primarily in Java. Hence choice A is incorrect. The question does not specify anything about the legacy code's JNI capability. However it specifically mentions about CORBA compatibility. Hence choice B is incorrect. RMI-IIOP is the protocol used with EJB. The legacy system is coded with a CORBA interface and the question mentions that no new coding is anticipated. So EJBs are not a good choice for this problem. Hence choice D is incorrect. When you wish to communicate with a system whose firewall does not permit requests of a certain protocol, the requests are sometimes masqueraded as HTTP requests. This concept is called HTTP tunneling. Hence choice E is incorrect.
328
329
247 Which of the following defines a standard architecture for connecting the J2EE platform to heterogeneous EIS applications? A B C D E J2SE Java Web Start JDBC JMS JCA
Choice E is correct. The following is taken from: http://java.sun.com/j2ee/connector/ "The J2EE Connector architecture provides a Java solution to the problem of connectivity between the many application servers and EISs already in existence. By using the J2EE Connector architecture, EIS vendors no longer need to customize their product for each application server. Application server vendors who conform to the J2EE Connector architecture do not need to add custom code whenever they want to add connectivity to a new EIS." Hence choice E is correct. J2SE is a platform that provides"the compiler, tools, runtimes and APIs for developing, deploying and running applets and applications in the Java programming language." Hence choice A is incorrect. The following is taken from: http://java.sun.com/products/javawebstart/ "Java TM Web Start -- a technology for simplifying deployment of Java applications-gives you the power to launch full-featured applications with a single click from your Web browser. You can now download and launch applications, such as a complete spreadsheet program or an Internet chat client, without going through complicated installation procedures." Hence choice B is incorrect. The following is taken from: http://java.sun.com/products/jdbc/ "JDBCTM technology is an API that lets you access virtually any tabular data source from the Java TM programming language. It provides cross-DBMS connectivity to a wide range of SQL databases, and now, with the new JDBC API, it also provides access to other tabular data sources, such as spreadsheets or flat files. The JDBC API allows developers to take advantage of the Java platform's "Write Once, Run Anywhere TM" capabilities for industrial strength, cross-platform applications that require access to enterprise data. With a JDBC technology-enabled driver, a developer can easily connect all corporate data even in a heterogeneous environment." Hence choice C is incorrect. The following is taken from: http://java.sun.com/products/jms/
329
330
"The JMS API improves programmer productivity by defining a common set of messaging concepts and programming strategies that will be supported by all JMS technology-compliant messaging systems." While you may be able to communicate with EIS systems using JMS (if the EIS supports JMS), it is not a standardized architecture for connecting to heterogeneous EIS applications. Hence choice D is incorrect.
248 Which of the following methods is optional in the Home Interface of an Entity Bean? A B C D Create() FindByPrimaryKey() Remove() None of the above
Choice A is correct. Sometimes when you do not want the clients of an EJB application to add data to your system, you may choose not to provide a create method in the Home Interface of the Enterprise bean. The create method is therefore optional. Hence choice A is correct.
249 A B C D E F G
The Bean class provides implementations for which of the following methods? Methods in the Bean's Home Interface Methods in the Bean's Remote Interface EJB Callback methods A, B and C A and B A and C B and C
Choices A, B and C are correct. The Bean class has implementations for the methods corresponding to the methods in the Home and Remote Interfaces, and the bean's callback methods. Hence choice D is correct.
250
330
331
A B C D
They leave Method Ready Pool state to enter Does not Exist State. They leave Method Ready state to enter Stateful State. They leave Method Ready state to enter Passivated or Does not Exist state. They never leave the Method Ready state.
Choice C is correct. The valid lifecycle states of a Stateful Session Bean are Does Not Exist, Method Ready, Method Ready (in TX) and Passive. The Bean instance leaves the Method Ready state to enter the Passive State (through Passivation) or the Does Not Exist State (through removal). Hence choice C is correct. Method Ready Pool is not a valid state for Stateful Session Beans because the specifications do not mandate the container to maintain a bean pool for Stateful Session Beans. Note that some containers may internally use some kind of pooling mechanism for achieving higher performance. Hence choice A is incorrect. There is no Stateful State in the lifecycle of a Stateful Session Bean. Choice B is therefore incorrect. Stateful Beans leave the Method Ready State to enter Does not Exist or Passive State. Hence choice D is incorrect.
251 A session bean called SomeBean has a method called someMethod(), which calls someOtherMethod (same bean) followed by someOtherBeanMethod() of SomeOtherBean. If SomeMethod() starts a BMT transaction, which of the following are true? A SomeOtherMethod also has to be use BMT since it's part of the same bean. B SomeOtherMethod can use BMT or CMT, because transactions are defined at the method level in the deployment descriptor. C If SomeOtherBean is a Session Bean, it has to necessarily use BMT since the caller is a BMT method. D If SomeOtherBean is a Session Bean, it may use either BMT or CMT. E If SomeOtherBean is an Entity Bean, it may use either BMT or CMT. F If SomeOtherBean is an Entity Bean, it must necessarily use only CMT. Choices A, D and F are correct. A Bean may be defined as either a BMT bean or a CMT bean. One cannot have some methods of a bean participating in Container Managed Transactions and other methods participating in Bean Managed Transactions. Hence choice A is correct. Session Beans may either be defined as CMT beans or BMT beans whereas Entity beans can only be CMT beans. Hence choices D and F are correct.
331
332
SomeOtherBean is a different Bean. It may either be defined as a BMT bean or a CMT bean. Just because the calling bean is in a BMT transaction, all the other beans do not have to be BMT beans as well. Hence choice C is incorrect. Entity Beans can only be CMT beans. Hence choice E is incorrect.
252 In EJB 1.1 the EJB timeout property may be added to the Bean's deployment descriptor for easier declarative life cycle management. True/False? A B True False
The above statement is False. In EJB 1.0, the timeout period was specified in the deployment descriptor and defined as number of seconds. Between two business method invocations, the timer was reset. In EJB 1.1 however, the deployer is allowed to set the timeout in a vendor dependent manner. Hence the above statement is false.
253 A B2C company uses J2EE based technologies for its e-commerce storefront. In order to increase scalability and availability they plan to add capacity to their existing server and also add a new server. Which of the following statements are true? A Adding capacity will improve scalability, as more memory would allow better bean pooling. B Adding a server would be difficult, as EJB servers cannot span multiple physical machines. C The proposal not does address horizontal scalability. D The proposal addresses both vertical and horizontal scalability. E Adding a server to the system would be easy as EJB vendors generally support fault tolerant mechanisms via server clustering.
332
333
The proposal to add capacity and an additional server address the issue of scalability. Adding capacity is an example of Vertical Scalability and adding a new server is an example of Horizontal Scalability. Additional servers also improve availability because of redundancy and fault tolerance. Hence choices A, D and E are correct. Most J2EE vendors provide multi-server support. Hence choice B is incorrect. Adding a new server is an example of Horizontal scalability. Hence choice C is incorrect.
254 Company ABC Inc. has an existing J2EE application that provides an EJB interface. ABC Inc. is writing a new J2EE based application for enhanced MIS reporting. Which of the technologies listed below would be ideal for this? A B C D RMI/JRMP with JNI Java IDL RMI / IIOP JMS
Choice C is correct. The key here is that ABC Inc. is using a primarily EJB based application. The protocol used in EJB is RMI-IIOP. Hence choice C is correct. The question clearly says that the existing application is in EJB. There is no legacy connectivity involved here. Hence choice A is inappropriate and therefore incorrect. Java IDL is primarily used when a majority of the code needs a CORBA interface. Since the existing code is already in EJB, there is no need for Java IDL here. Hence choice B is incorrect. JMS is useful when you want to send messages to other applications asynchronously via a Message Oriented Middleware. Hence option D is incorrect as well.
255 A B C
A firewall blocks all requests except those on ports 80 and 443. IIOP requests Can be processed because IIOP always works on port 80 Cannot be processed because port 80 belongs to a different protocol Can be processed by SSL
333
334
Choice E is correct. Tunneling is a concept that allows requests of one protocol to masquerade as requests of another protocol, so that they may bypass the firewall. In the case of HTTP tunneling, requests try to pass of as HTTP requests. Hence choice E is correct. Port 80 is the standard port for HTTP requests, not CORBA requests. Hence choice A is incorrect. Although port 80 may be used for HTTP, that does not mean that CORBA requests cannot be processed. As it happens, HTTP tunneling will allow CORBA requests looking like HTTP requests to pass through port 80. Hence choice B is incorrect. SSL stands for Secure Sockets Layer. SSL is a protocol that exists above TCP/IP and below application level protocols. SSL does not process CORBA requests. Hence choice C is incorrect. While firewalls may block requests of certain protocols, there is no concept called HTTP blocking. Hence choice D is incorrect.
256 A B C D
Applications exchange messages through: Active channels called Networks Active Channels called Message Brokers Virtual Channels called Digests Virtual Channels called Destinations
Choice D is correct.
257
A Subscribers receive a copy of every message. B It is a Pull (Polling) based model. C It is a push-based model. D It is generally used when one publisher wishes to send a message to one subscriber.
334
335
Choices A and C are correct. In the Publish/Subscribe messaging paradigm the publisher broadcasts a message to the Message Oriented Middleware (MOM.) The MOM then typically uses a server-push mechanism to try to push a copy of the message to every subscriber who showed interest in the topic. Optionally a subscriber may also register as a durable subscriber, in which case the message will have guaranteed delivery. Hence choices A and C are correct. The Point-to-Point (P2P) model is a queue-based model where the message consumer typically polls the queue for incoming messages. Publish/Subscribe, on the other hand is a push-based model. Hence choice B is incorrect. Publish/Subscribe is generally used for a one to many type of communication while P2P is typically used for a one to one communication. Hence choice D is incorrect.
258
A A specified node, which is then re-distributed to all subscribers. B Directly to all subscribers in the Topic subscription list. C A designated queue. D A component transaction monitor such as an EJB Server for further processing by a message driven bean. Choice A is correct. The Publish subscribe model of messaging is a one to many messaging paradigm where the publisher typically sends a message to a centralized node. The node then broadcasts the message to all the topic subscribers, who have registered their interest in the topic. This allows the publisher and the subscribers to be decoupled. Further if the subscriber is registered as a durable subscriber, he will receive the message ultimately even if he is currently inactive. The MOM provider can thus guarantee delivery and any Quality of Service requirements pertaining to the message delivery. Although possible, choice B is not the ideal implementation method, because it couples publishers and subscribers. Most MOM providers use a server process that communicates with client processes for establishing heartbeats and for communicating messages. Choice C is incorrect because it refers to the Point-to-Point messaging model, which is typically a one to one communication between two parties. Choice D is incorrect because the Message Driven Bean is a message listener. So the best use of a message driven bean would be as a subscriber.
335
336
259 1-tier applications represent a single point of failure, although typically, changes to one part of the system do not generally affect the whole system. True/False? A B True False
Choice B is correct. 1-tier systems represent a single point of failure. Further if any changes are made to one part of the system, typically the whole system may be affected because of a high degree of tight coupling. Hence choice B is correct.
260
A N-Tier systems are distributed over many systems and hence always present a maintenance problem. B N-Tier systems are generally component based and are therefore quite easy to maintain. C Since N-Tier systems do not use database stored procedures or triggers for business logic processing, they are generally very slow. D Since N-Tier systems are container based, many N-Tier systems can be easily scaled (both vertically and horizontally). E N-Tier systems suffer from only one drawback over client/server systems - N-Tier systems do not take advantage of resource sharing techniques such as connection pooling. F N-Tier systems can use various techniques for Identification, Authentication and Authorization and are therefore considered quite secure. Choices A, C and E are correct. This is a discussion about the benefits vs. drawbacks of N-Tier applications. Note that the question says 'not true.' Though N-Tier systems are distributed over many systems, when architected and designed well, they do not present any maintenance problems. This is because they are highly modular (component-container based) and it is relatively easy to correct problems in one tier without impacting other tiers. Therefore A is a correct choice. N-Tier systems can also yield high performance. They can be highly optimized at each tier. Server clusters can be used where bottlenecks are encountered, connection pools can be used by applications to acquire and release connections (a process more effective that creation and destruction of connections) and so on. Hence choice C is a correct choice.
336
337
Though not relevant to the discussion it should be noted that putting all business rules in the database tier reduces database portability and also violates tier encapsulation. Hence it is not considered a J2EE best practice to use stored procedures and triggers extensively for business logic processing. As opposed to client/server systems, N-Tier systems generally make extensive use of resource sharing capabilities. Bean Pools and Connection pools are good examples. Hence E is a right answer. B, D and F are good examples of other capabilities of N-Tier systems.
261 In general, 1-tier applications are less horizontally scalable than 3-tier applications, although from a scalability point of view, client/server applications are the most scalable. True/False? A True B False The above statement is False. This is a trick question. It starts out by making a true statement although that is not the main stem of the question. The main stem seems to indicate that Client/Server applications are the most scalable types of applications. That is incorrect because N-Tier applications are modular and therefore individual components can be targeted for scaling.
262 A B C D E
Which of the following do not aid a system's extensibility? Modularizing Code Using well defined software design patterns Using Servlets to manage distributed database access Using JSP Scriptlets to locate Enterprise beans Using Data Access Objects when Session Beans or BMP Entity beans have to communicate to the database.
Choices C and D are correct. Extensibility refers to a systems ability to incorporate new functionality with ease. Writing Database access code within Servlets or using JSP for locating Enterprise Java Beans
337
338
Modularized code, good design practices using patterns, and encapsulating database access with a DAO all make the code easy to maintain, thus rendering the system easily extensible.
263
A B C D E F G
A' has an association relationship with 'B' 'B' has an association relationship with 'A' 'A' extends 'B' 'A' has a composition relation with 'B' 'B' has a composition relationship with 'A' 'A' has an aggregation relationship with 'B' 'B' has an aggregation relationship with 'A'
Choice D is correct. The relationship between class A and class B represents the strongest form of association - composition. A solid diamond near the object that will instantiate the other object in the association, denotes a composition relationship. Class A does not have an association or aggregation (open diamond near A) relationship with class B. Class A also does not extend B (open triangle near B.) Hence all other choices are incorrect.
264
338
339
Choice F is correct. The diagram denotes a package diagram. A package diagram (Fowler 108) shows packages of classes and the dependencies among them. Choice F is correct.
265 A B
Interaction diagrams represent the dynamic view of a system. Interaction diagrams may represent static or dynamic views of the system. C Interaction diagrams are polymorphic. D Interaction diagrams are isomorphic. E Interaction diagrams only show time ordering of messages. F Interaction diagrams may show the structural organization of the objects that send or receive messages. Choices A, D and F are correct. Interaction diagrams (Fowler 67) are models that describe how groups of objects collaborate in some behavior. There are two kinds of Interaction diagrams - Sequence diagrams and Collaboration diagrams. (Cade 46) Interaction diagrams address the dynamic view of a system. A sequence diagram emphasizes on the time ordering of messages whereas a collaboration diagram emphasizes the structural organization of the objects that send or receive messages.
339
340
Sequence diagrams and Collaboration diagrams are also isomorphic (you can take one and transform it to the other.) Hence choices A, D and F are correct. Interaction diagrams do not describe the static view of a system. Hence choice B is incorrect. Interaction diagrams are isomorphic, nor polymorphic. Hence choice C is incorrect. Interaction diagrams show either the time ordering of messages (sequence diagrams) or the structural organization of objects (collaboration diagrams.) Hence choice E is incorrect.
266
From the diagram, it can be inferred that: A B C D E A can only have 2 or 4 Bs associated with it A can have 2 to 4 (4 not inclusive) Bs associated with it A can have 2 to 4 (2 not inclusive) Bs associated with it A can have either 2 or 4 Bs associated with it but not 3 A can have 3 Bs associated with it
Choice E is correct. The multiplicity shown above translates into (A can have 2 to 4 Bs associated with it.) Choice E says that A can have 3 Bs associated with it and is therefore correct.
267 Nopester Inc., a CD manufacturer uses Metallic Corporation for making jewel cases. When the inventory of jewel cases falls under the reorder level, Nopester communicates with Metallic via faxes. Nopester now wants to build a solution for its supply chain management. Metallic uses a legacy system that supports CORBA interfaces for other companies to interface to them with. Metallic's servers are protected by firewalls and will only let HTTP or HTTPS requests through. What is Nopester's best option here? A Since Metallic will not let CORBA requests through, Nopester should continue sending faxes. B Nopester should take its business away to Metallic's competitors. C Nopester should use the popular SOAP protocol since SOAP requests communicate over HTTP.
340
341
One of the most common interconnection problems that arise in third party integrations is that of security. Most companies have strict security policies and only allow access to the ports that support HTTP and HTTPS. Therefore CORBA requests generally have to masquerade as HTTP requests to get through the firewall. While this beats the very purpose of the firewall, such implementations are quite common. This concept is called HTTP tunneling. Hence choice D is correct. Choice A is incorrect for obvious reasons. What is the point of automation if we still want to use a paper based solution? Choice B is incorrect because businesses do not change partners due to minor software issues. Choice C is incorrect because there is no mention of whether Metallic supports SOAP in the discussion.
268 Syracuse Sobers is a National Hockey League team in upstate New York. They currently use a mainframe-based application for talent procurement and management. Their team currently visits various schools and universities across the country. When they find an interesting candidate, they enter his profile details in hand held devices. Later the information is faxed to Syracuse, where another set of users enters the data into the mainframe. Given that the Sobers do not want to incur too much capital and operational expense in rewriting the application, what would be the quickest way of giving them an Internet based profile management system? A Rewrite the system using Applets. B Rewrite the system using Model2 Architecture based solution. C Use screen scraper for obtaining an object interface and off-board server for forwarding requests. D Use RMI with JNI. t +Enable HTTP tunneling and use CORBA calls. Choice C is correct. The key here is 'less expensive' and 'quickest.' Hence the best method under the given circumstances is the combined use of Screen Scrapers and an off-board server. Choice C is therefore correct.
341
342
Rewriting the system is time consuming and also cost intensive. Hence choices A and B are incorrect. There is no mention of the legacy application supporting JNI. The question mentions that it is a mainframe-based application, making screen scrapers the safest bet. Hence choice D is incorrect. There is also no mention of CORBA support. Hence choice E is incorrect.
269 A Philadelphia based cable company is using J2EE for their Customer Management system. The system uses a combination of HTML and JSP for presentation. Java Servlets are used as Controllers. All Servlets have access to a ServletContext object, which functions as a Container to the shared resources of the Servlets. The ServletContext object best exemplifies what design pattern? A B C D E Iterator Mediator Interpreter State Singleton
Choice E is correct. Singleton (GOF 127)" Ensure a class only has one instance, and provide a global point of access to it." In the example cited above, all Servlets use a common ServletContext object as a container for the shared resources. This is a perfect example of the Singleton Design Pattern. Hence choice E is correct. Iterator (GOF 257)"Provide a way to access the elements of an aggregate object sequentially without exposing its underlying representation." Hence choice A is incorrect. Mediator (GOF 273)"Define an object that encapsulates how a set of objects interact. Mediator promotes loose coupling by keeping objects from referring to each other explicitly, and lets you vary their interaction independently." Hence choice B is incorrect. Interpreter (GOF 243)"Given a language, define a representation for its grammar along with an interpreter that uses the representation to interpret sentences in the language." Hence choice C is incorrect. State (GOF 305)"Allow an object to alter its behavior when its internal state changes. The object will appear to change its class." Hence choice D is incorrect.
270 Since Stateful Session Beans are not pooled as their Stateless counterparts, the container uses Passivation and activation techniques for better resource management. What design pattern is close to the concept of Passivation, as described here?
342
343
Choice E is correct. Memento (GOF 283)"Without violating encapsulation, capture and externalize an object's internal state so that the object can be restored to this state later." With Stateful Session Beans the container externalizes the state of the bean via Passivation for better memory management. When required, a bean in the passive state can be brought back to the Method Ready state via activation. Hence choice E is correct. Composite (GOF 163)"Compose objects into tree structures to represent part-whole hierarchies. Composite lets clients treat individual objects and composites of objects uniformly." Choice A is irrelevant here and therefore incorrect. Flyweight (GOF 195)"Use sharing to support large numbers of fine-grained object efficiently." Hence choice B is therefore incorrect. Template Method (GOF 325)"Define a skeleton of an algorithm in an operation, deferring some steps to subclasses. Template Method lets subclasses redefine certain steps of an algorithm without changing the algorithm's structure." Choice C is therefore incorrect. Command (GOF 233)"Encapsulate a request as an object, thereby letting you parameterize clients with different requests, queue or log requests, and support undoable operations." Choice D is therefore incorrect. Chain of Responsibility (GOF 223)" Avoid coupling the sender of a request to its receiver by giving more than one object a chance to handle the request." Chain the receiving objects and pass the request along the chain until an object handles it." Choice F is therefore incorrect.
271 Heaven's Stairway, an e-auction house allows sellers to put up items for sale. Potential buyers can subscribe an interest in these items. When somebody updates the cost with a higher price, the new price information is sent to a JMS based middleware. The MOM then intimates all subscribers of the event. What design pattern is illustrated in the discussion here? A B Service to Worker Fast Lane Reader
343
344
Choice C is correct. Observer (GOF 293)"Define a one-to-many dependency between objects so that when one object changes state, all its dependents are notified and updated automatically." In the example above, when someone (message producer) updates the bid price, the MOM has to send a message to all interested subscribers (message consumers.) This is a good example of the Observer Design Pattern. Hence choice C is correct. The following is taken from: http://java.sun.com/blueprints/corej2eepatterns/Patterns/ServiceToWorker.html Service to Worker:"Combine a controller and dispatcher with views and helpers (see Front Controller and View Helper also) to handle client requests and prepare a dynamic presentation as the response. Controllers delegate content retrieval to helpers, which manage the population of the intermediate model for the view. A dispatcher is responsible for view management and navigation and can be encapsulated either within a controller or a separate component." Examples of Service to Worker pattern can be seen in popular Model2 Frameworks such as Struts and Web Application Framework (WAF.) This pattern is not relevant to this situation and choice A is therefore incorrect. The following is taken from: "The Fast Lane Reader design pattern provides a more efficient way to access tabular, read-only data. A fast lane reader component directly accesses persistent data using JDBCTM components, instead of using entity beans. The result is improved performance and less coding, because the component represents data in a form that is closer to how the data are used." When EJBs are not required in an application (smaller applications) and JSP pages need to access the database to retrieve information, they may use helper classes, which in turn instantiate DAOs to access data. A JSP page retrieving catalog information through the CatalogHelper class and the CatalogDAO is a good example of the Fast Lane Reader Pattern. Hence choice B is incorrect.
Visitor (GOF 331)"Represent an operation to be performed on the elements of an object structure. Visitor lets you define a new operation without changing the classes of the elements on which it operates." Choice D is therefore incorrect. Publish/Subscribe is a messaging architecture, not a design pattern. Hence choice E is incorrect.
344
345
272 In JMS based applications components never interact with each other directly. The messages are always sent to the MOM and the MOM stores and forwards them to the recipients. This concept helps avoid explicit references and promotes loose coupling. The MOM is acting as a/an: A B C D E Interpreter Visitor Mediator Service Locator Service to Worker
Choice C is correct. Mediator (GOF 273)"Define an object that encapsulates how a set of objects interact. Mediator promotes loose coupling by keeping objects from referring to each other explicitly, and lets you vary their interaction independently." In this example, the MOM decouples the message producers and consumers from referring to each other directly, thus acting as a Mediator. Choice C is therefore correct. Interpreter (GOF 243)"Given a language, define a representation for its grammar along with an interpreter that uses the representation to interpret sentences in the language." Hence choice A is incorrect. Visitor (GOF 331)"Represent an operation to be performed on the elements of an object structure. Visitor lets you define a new operation without changing the classes of the elements on which it operates." Choice B is therefore incorrect. The following is taken from: http://java.sun.com/blueprints/patterns/ServiceLocator.html "The Service Locator pattern centralizes distributed service object lookups, provides a centralized point of control, and may act as a cache that eliminates redundant lookups. It also encapsulates any vendor-specific features of the lookup process." In Model2 architectures, Controllers may use Service Locators to delegate business events. Choice D is therefore incorrect. The following is taken from: http://java.sun.com/blueprints/corej2eepatterns/Patterns/ServiceToWorker.html Service to Worker:"Combine a controller and dispatcher with views and helpers (see Front Controller and View Helper also) to handle client requests and prepare a dynamic presentation as the response. Controllers delegate content retrieval to helpers, which manage the population of the intermediate model for the view. A dispatcher is responsible for view management and navigation and can be encapsulated either within a controller or a separate component." Examples of Service to Worker pattern can be seen in popular Model2 Frameworks such as Struts and Web Application Framework (WAF.) This pattern is not relevant to this situation and choice E is therefore incorrect.
345
346
273 Compact Computers is a small computer assembly company. Its online application allows customers to pick and choose accessories to build their own PCs. The accessories are: i. Processor - 800Mhz, 1Ghz, 1.2Ghz ii. HDD - 40 GB, 60 GB, 80 GB iii. Memory - 128 MB, 256 MB, 512 MB Customers choose parts and quantities during the order. For example, a customer could choose a second HDD as a secondary hard drive or purchase additional RAM. What design pattern may be optimal for implementing a suitable design here?
A B C D E F
Choice B is correct. Prototype (GOF 117)"Specify the kinds of objects to create using a prototypical instance, and create new objects by copying this prototype." In this example, the key is that using prototypical instances (for Hard Drives and RAM), you can create multiple instances of the required part. Hence choice B is correct. Factory Method (GOF 107)" Define an interface for creating an object, but let subclasses decide which class to instantiate. Factory method lets a class defer instantiation to subclasses." Factory Method pattern is used when concrete factory classes are required for creating subclasses. Hence choice A is incorrect. Singleton (GOF 127)" Ensure a class only has one instance, and provide a global point of access to it." Hence choice C is incorrect. Template Method (GOF 325)"Define a skeleton of an algorithm in an operation, deferring some steps to subclasses. Template Method lets subclasses redefine certain steps of an algorithm without changing the algorithm's structure." Choice D is therefore incorrect. The following is taken from: http://java.sun.com/blueprints/patterns/BusinessDelegate.html "In distributed applications, lookup and exception handling for remote business components can be complex. When applications use business components directly, application code must change to reflect changes in business component APIs.
346
347
These problems can be solved by introducing an intermediate class called a business delegate, which decouples business components from the code that uses them. The Business Delegate pattern manages the complexity of distributed component lookup and exception handling, and may adapt the business component interface to a simpler interface for use by views." Hence choice E is incorrect. Builder (GOF 97)"Separate the construction of a complex object from its representation so that the same construction process can create different representations." Builder is used to create a complex object made up of specific types of parts. Here we know the parts but not their quantities. Hence Builder is inappropriate here and therefore choice F is incorrect.
274 Doomingdale's has an online application where customers may browse the latest season's catalogs. At this time no e-commerce is planned. What J2EE technology is best suited for this application. Note that a study of Internet traffic over the last two years in a similar company indicated that the site can expect up to five hundred thousand hits a day although during Thanksgiving, when sales are at the highest, it could get ten to twenty times higher, perhaps even more. A B C D E F Java Servlets JSP with Java classes CMP Entity Beans BMP Entity Beans Stateless Session Beans with DAO Stateful Session Beans with DAO
Choice E is correct. The key here is the nature of the application. No e-commerce is planned at this time, so there may not be any order transactions requiring Entity Beans. However the site can expect half a million hits each day, the number increasing exponentially during holiday seasons, indicating that perhaps Session Beans should be considered for the application. Catalog retrieval can be done with simple Session beans and DAO. Hence choice E is correct. Choice A and B are not suitable because using just Java Servlets and JSP alone may not be the best solution in a system involving heavy usage. As stated earlier, Entity Beans are not necessary here because there is no transactional processing. Choices C and D are therefore incorrect. Stateless Session Beans are sufficient for performing simple database retrieval operations. Stateful Session Beans are only required when conversational state needs to be maintained, as in the case of e-commerce applications with shopping carts. Hence choice F is incorrect.
347
348
275 Hiatus Regency is a popular resort hotel. It has four regional headquarters in the U.S. There is also a national headquarters in Gaithersburg, MD. All calls made to the toll-free 800 numbers are routed to the nearest call center. If the requested city falls outside the region, the call gets rerouted from the call center appropriately. Hiatus requires a nightly update of all transactions to the national headquarters for nationwide batch reporting. What J2EE technology may be best suited for this? A B C D E F G Java-IDL RMI-JRMP EJB JTA/JTS JCA JMS JAF
Choice F is correct. Whenever asynchronous communication is required, messaging is the best option. Most MOM implementations provide guaranteed delivery and high QoS levels. Further, messaging decouples the producer and consumer and can be used when bandwidth availability is limited, since no synchronous response is required. The key here is the nightly update clearly indicating the asynchronous nature of the communication. Hence choice F is correct. Java-IDL, RMI-JRMP and EJB are used for synchronous communication. Hence choices A, B and C are incorrect. JTA/JTS is used to manage user-defined transactions and is irrelevant to this discussion. Hence choice D is incorrect. The following is taken from: http://java.sun.com/j2ee/connector/ "The J2EE Connector architecture provides a Java solution to the problem of connectivity between the many application servers and EISs already in existence. By using the J2EE Connector architecture, EIS vendors no longer need to customize their product for each application server. Application server vendors who conform to the J2EE Connector architecture do not need to add custom code whenever they want to add connectivity to a new EIS." Hence choice E is incorrect. The following is taken from: http://java.sun.com/products/javabeans/glasgow/jaf.html "With the JavaBeans TM Activation Framework standard extension, developers who use Java TM technology can take advantage of standard services to determine the type of an arbitrary piece of data, encapsulate access to it, discover the operations available on it, and to instantiate the appropriate bean to perform said operation(s). For example, if a
348
349
browser obtained a JPEG image, this framework would enable the browser to identify that stream of data as an JPEG image, and from that type, the browser could locate and instantiate an object that could manipulate, or view that image." Hence choice G is incorrect.
276 Which of the following situations may be best suited for implementation using Servlets and JSP? A B C D E F Need large scale deployment Need heavy use of transactions Need to process dynamic requests from HTTP clients Need access to relational databases through a generic set of APIs To function as Intercepting filters, request processors and request dispatcher When static templates are combined with data to form dynamic HTML output
Choices C, E and F are correct. Servlets and JSP are best suited for applications where there is a need for processing dynamic requests from HTTP clients. In Model2 architectures, Servlets are used as Controllers and are responsible for processing incoming requests, and dispatching them to appropriate handlers. JSP are used as views to combine static templates with dynamic data to form HTML or XML output. Hence choices C, E and F are correct. When an application involves large-scale deployment and heavy transactional requirements, EJBs are the best technology. Hence choices A and B are incorrect. JDBC is used to access relational databases through a generic set of APIs. Hence choice D is incorrect.
277
A Bean instances are created during startup, thus avoiding the expense of creation, each time a client requests it. B Bean pooling allows load distribution over several machines. C Bean pooling is the container's way of balancing load - moving future requests from client to a different machine, if load increases are encountered. D Allows a container to use beans as flyweights. Choices A and D are correct.
349
350
One of the advantages of using stateless session beans are that they are light weight objects and can therefore be used in situations that do not require any conversational state management. The container makes use of this capability to create a pool of instances that can be used to service client requests. When a request is serviced, the bean instance is moved back to the pool. Thus the expense of creation is avoided each time a client request comes in. Further the concept of using a smaller number of instances to service a large number of clients is referred to as the Flyweight pattern (GOF 195), the case with bean pooling. Therefore choices A and D are correct. Bean pooling is not responsible for load distribution (something accomplished by DNS Round Robin.) Some containers working under a clustered environment achieve load balancing. Again this is not a benefit of bean pooling. Hence choices B and C are incorrect.
278 A B C D
What are the valid life-cycle states an Entity Bean can exist in? Does Not Exist, Pooled, Method Ready Does Not Exist Ready, Ready (in TX), Passivated Does Not Exist, Method Ready Pool Does Not Exist, Pooled, Ready
Choice D is correct. The valid lifecycle states for an Entity Bean are Does Not Exist, Pooled and Ready. Hence choice D is correct. Entity Beans do not have a Method Ready state. Hence choice A is incorrect. When Entity Beans are passivated, they enter the pooled state. Also, there is no Method Ready (in TX) state for Entity Beans. Hence choice B is incorrect. The Method Ready Pool state is a lifecycle state for Stateless Session Beans, not Entity Beans. Hence choice C is incorrect.
279 A company has a third party billing system that provides C++ API access. In the current architecture, a daemon process listens on a specified port on the server for incoming payloads. The incoming payloads are then decoded to the form command <tab> data. Once the command is known, the process calls the appropriate API with the data. The company is trying to move to a Java based solution. However, until the billing system is upgraded, they will still need to use the C++ bases APIs. What Protocol may be best suited for achieving this?
350
351
A B C class D E F
RMI-JRMP with JNI wrappers for the API calls RMI-IIOP (Stateless session beans making the API calls) Custom socket programming to replace the C++ daemon process with a Java HTTP request making a CGI call for the Billing updates JINI based program to interface to the APIs JCA to make the API call
Choice A is correct. The key here is that the billing system supports C++ based APIs. The new code is being written in the Java platform. The best approach here is to write RMI-JRMP code to talk to the billing system and have JNI wrappers there to communicate with the C++ APIs. Hence choice A is correct. The question says that the billing system only supports C++ APIs. Hence choice B is incorrect. While custom Java socket programming may be used on the server side to replace the C++ process, in order to call the APIs, C++ wrappers will still be required. Hence choice C is incorrect. HTTP, JINI and JCA do not satisfy the requirement of the C++ wrapper need. Hence choices D, E and F are also incorrect.
280
A The java.text package contains classes and interfaces for handling text in a locale-sensitive way. B The java.text package contains the Locale class and classes for Date and Time. C The java.util package contains classes for importing and exporting non-Unicode character data. D The java.util package contains the Locale class and classes for Date and Time Choices A and D are correct. The java.text and java.util packages are used to support Java Internationalization. The java.text package has classes and interfaces for handling locale specific text and the java.util package containes the Locale class and other classes for Date and Time manipulation. Hence choices A and D are correct.
351
352
The InputStreamReader and OutputStreamWriter classes handle non-Unicode character data conversion. These classes are found in the java.io package. Hence choice C is incorrect.
281 The representation of a set of cultural and language preferences is done using which class? A java.util.LanguagePreference B java.text.MessageFormat C ResourceBundle D Locale Choice D is correct. The following is taken from: http://java.sun.com/products/jdk/1.1/docs/guide/intl/intl.doc.html#26726 "A Locale object represents a specific geographical, political, or cultural region. An operation that requires a locale to perform its task is called locale-sensitive and uses the Locale object to tailor information for the user. For example, displaying a number is a locale-sensitive operation- the number should be formatted according to the customs and conventions of the user's native country, region, or culture." Hence choice D is correct. There is no LanguagePreference class. Regional preferences are addressed through various I18N features such as ResourceBundle, Locale and so on. Hence choice A is incorrect. The following is taken from: http://java.sun.com/products/jdk/1.1/docs/guide/intl/intl.doc.html#24167 "The class MessageFormat provides a means to produce concatenated messages in language-neutral way. The MessageFormat object takes a set of objects, formats them, and then inserts the formatted strings into the pattern at the appropriate places." Hence choice B is incorrect. The following is taken from: http://java.sun.com/products/jdk/1.1/docs/guide/intl/intl.doc.html#23039
352
353
"The class ResourceBundle is an abstract base class representing containers of resources. Programmers create subclasses of ResourceBundle that contain resources for a particular locale. New resources can be added to an instance of ResourceBundle, or new instances of ResourceBundle can be added to a system without affecting the code that uses them. Packaging resources as classes allows developers to take advantage of Java's class loading mechanism to find resources. Resource bundles contain locale-specific objects. When a program needs a localespecific resource, a String object for example, the program can load it from the resource bundle that is appropriate for the current user's locale. In this way, the programmer can write code that is largely independent of the user's locale isolating most, if not all, of the locale-specific information in resource bundles." Hence choice C is incorrect.
282 What is the difference in the Java Security model between JDK 1.1 and JDK1.2 with regards to applets? A There is no difference between the two JDK versions in question. Applets are always confined to the sandbox. B In JDK 1.1, applets are never trusted and in JDK 1.2 they always are. C JDK 1.2 fixed a flaw in the JDK 1.1 security policy. There are no security holes in JDK 1.2 because Applets are never trusted. D In JDK 1.1 only signed applets were trusted whereas in JDK 1.2, any applet with the right security permissions can be trusted. Choice D is correct. The following is taken from: http://java.sun.com/docs/books/tutorial/security1.2/overview/index.html "JDK 1.1 introduced the concept of a "signed applet," as illustrated in the next figure. A digitally signed applet is treated like local code, with full access to resources, if the public key used to verify the signature is trusted. Unsigned applets are still run in the sandbox. Signed applets are delivered, with their respective signatures, in signed JAR (Java Archive) files. JDK 1.2 introduces a number of improvements over JDK 1.1. First, all code, regardless of whether it is local or remote, can now be subject to a security policy. The security policy defines the set of permissions available for code from various signers or locations and can be configured by a user or a system administrator. Each permission specifies a permitted access to a particular resource, such as read and write access to a specified file or directory or connect access to a given host and port. The runtime system organizes code into individual domains, each of which encloses a set of classes whose instances are granted the same set of permissions. A domain can be configured to be equivalent to the sandbox, so applets can still be run in a restricted
353
354
environment if the user or the administrator so chooses. Applications run unrestricted, as before, by default but can optionally be subject to a security policy." As we can see, the Java 2 Security model is totally flexible. Hence choice D is correct. Choices A, B and C are incorrect because there are differences between the JDK 1.1 and JDK 1.2 security model and signed applets were trusted in JDK 1.1 whereas all applets are subject to a security policy in JDK 1.2.
283
A B C D
Validate Client to Server Validate Server to Client Allow client and server to choose cryptographic algorithm Use symmetric key encryption to generate shared secrets
Choices B and C are correct. When a client tries to establish an SSL connection with a server, the server identifies itself to the client. The client may optionally identify itself to the server. The client and the server then choose the best cryptographic algorithm. Public Key Cryptography is used to generate shared secrets and Symmetric Key Cryptography is then used for communication. Hence choices B and C are correct. The client's validation to the server is an optional step in the SSL handshake. Hence choice A is incorrect. Public Key Cryptography is used to generate shared secrets. Hence choice D is incorrect.
284 When a Stateful Session Bean is passivated, what activities should the developer perform in the ejbPassivate() method?
A B C D
Close all open resources Set transient fields to NULL Set Non-transient fields to NULL Set non-transient non-serializable fields to NULL
354
355
During Passivation, it is the developer's responsibility to ensure that all open resources are closed and all non-transient non-serializable fields are set to NULL. Therefore choices A and D are correct. There is no need to set transient fields to NULL. They will not be serialized anyway. Therefore choice B is incorrect. If Non-transient fields are set to NULL, there is no point in serializing the bean instance. Hence choice C is incorrect.
285 Session Bean SB1 calls a method in another Session Bean SB2. If the calling Bean has a transactional scope, with which of the following attributes in SB2, will the transaction not be propagated? A B C D E F Supports Required Not Supported Requires New Mandatory Never
Choices C, D and F are correct. The following is taken from: http://java.sun.com/blueprints/guidelines/designing_enterprise_applications_2e/transacti ons/transactions7.html "Transaction Attributes: A transaction attribute is a value associated with a method of an enterprise bean that uses container-managed transaction demarcation. A transaction attribute is defined for an enterprise bean method in the bean's deployment descriptor, usually by an application component provider or application assembler. The transaction attribute controls how the EJB container demarcates transactions of enterprise bean methods. In most cases, all methods of an enterprise bean will have the same transaction attribute. For optimization purposes, it is possible to have different attributes for different methods. For example, an enterprise bean may have methods that do not need to be transactional. A transaction attribute must be specified for the methods in the component interface of a session bean and for the methods in the component and home interfaces of an entity bean. Required - If the transaction attribute is Required, the container ensures that the enterprise bean's method will always be invoked with a JTA transaction. If the calling client is associated with a JTA transaction, the enterprise bean method will be invoked in the same transaction context. However, if a client is not associated with a transaction, the container will automatically begin a new transaction and try to commit the transaction when the method completes.
355
356
RequiresNew - If the transaction attribute is RequiresNew, the container always creates a new transaction before invoking the enterprise bean method and commits the transaction when the method returns. If the calling client is associated with a transaction context, the container suspends the association of the transaction context with the current thread before starting the new transaction. When the method and the transaction complete, the container resumes the suspended transaction. NotSupported - If the transaction attribute is NotSupported, the transactional context of the calling client is not propagated to the enterprise bean. If a client calls with a transaction context, the container suspends the client's transaction association before invoking the enterprise bean's method. After the method completes, the container resumes the suspended transaction association. Supports - It the transaction attribute is Supports and the client is associated with a transaction context, the context is propagated to the enterprise bean method, similar to the way the container treats the Required case. If the client call is not associated with any transaction context, the container behaves similarly to the NotSupported case. The transaction context is not propagated to the enterprise bean method. Mandatory - The transaction attribute Mandatory requires the container to invoke a bean's method in a client's transaction context. If the client is not associated with a transaction context when calling this method, the container throws javax.transaction.TransactionRequiredException if the client is a remote client or javax.ejb.TransactionRequiredLocalException if the client is a local client. If the calling client has a transaction context, the case is treated as Required by the container. Never - The transaction attribute Never requires that the enterprise bean method explicitly not be called within a transaction context. If the client calls with a transaction context, the container throws java.rmi.RemoteException if the client is a remote client or javax.ejb.EJBException if the client is a local client. If the client is not associated with any transaction context, the container invokes the method without initiating a transaction." With Not Supported, Requires New and Never, the existing transaction's scope will not be propagated. Therefore choices C, D and F are correct and choices A, B and E are incorrect.
286 A B C D
The findByXxx() method in the Home Interface of an entity bean returns An Instance of java.lang.Object An instance of the Remote Reference to the bean An instance of java.util.Enumeration An instance of the Bean class.
356
357
The finder methods return either an instance of the Remote Reference to the bean or an instance of java.lang.Enumeration (if multiple rows are found.) Therefore choices B and C are correct. The finder methods never return an instance of java.lang.Object. Choice A is therefore incorrect. The bean class is never explicitly returned to the client. The client always only works with the remote reference to the bean class. Choice D is therefore incorrect.
287 With Bean Managed Persistence, what are the developer's responsibilities in terms of data synchronization?
A The DML statements for inserting, deleting and updating data are coded in appropriate methods and the client program is responsible for synchronizing data by calling the methods appropriately. B The DML statements for inserting, deleting and updating data are coded in appropriate methods but since ejbLoad() and ejbStore() are callback methods, the container makes calls to them, as needed. Choice B is correct. With BMP, although the code necessary for inserting, deleting and updating data is provided by the developer, the container still decides when to synchronize the Bean's state with the database. The container makes this decision based on various activities including the current transactional context and so on. The client does not call the callback methods explicitly. Hence choice B is correct.
Choice A is incorrect because it suggests that it is the client's responsibility to invoke the callback methods.
288 i. ii.
Under which of the following conditions should you use an Entity Bean? The bean represents a business entity, not a procedure. The bean's state must be persistent. If the bean instance terminates or if the J2EE server is shut down, the bean's state still exists in persistent storage (a database).
357
358
A Choice (i) only B Choice (ii) only C Choice (i) or (ii) depending on whether the Container is EJB 1.0 compliant or EJB 1.1 compliant D Both choice (i) and (ii) Choice D is correct. Entity Beans are best used when the bean represents a business entity and when the bean's state must be persistent. Hence choice D is correct. i. The bean represents a business entity, not a procedure. ii. The bean's state must be persistent. If the bean instance terminates or if the J2EE server is shut down, the bean's state still exists in persistent storage (a database). ############################################
358