276
Sun Microsystems, Inc. www.sun.com Architecture and Design Guide Sun Java™ Wireless Client Software 2.2 Java Platform, Micro Edition December 2008

Architecture and Design Guide by Oracle

Embed Size (px)

Citation preview

Page 1: Architecture and Design Guide by Oracle

Sun Microsystems, Inc.www.sun.com

Architecture and Design Guide

Sun Java™ Wireless Client Software 2.2

Java Platform, Micro Edition

December 2008

Page 2: Architecture and Design Guide by Oracle

Copyright © 2008 Sun Microsystems, Inc., 4150 Network Circle, Santa Clara, California 95054, U.S.A. All rights reserved.

Sun Microsystems, Inc. has intellectual property rights relating to technology embodied in the product that is described in this document. Inparticular, and without limitation, these intellectual property rights may include one or more of the U.S. patents listed athttp://www.sun.com/patents and one or more additional patents or pending patent applications in the U.S. and in other countries.

THIS PRODUCT CONTAINS CONFIDENTIAL INFORMATION AND TRADE SECRETS OF SUN MICROSYSTEMS, INC. USE,DISCLOSURE OR REPRODUCTION IS PROHIBITED WITHOUT THE PRIOR EXPRESS WRITTEN PERMISSION OF SUN MICROSYSTEMS,INC.

U.S. Government Rights - Commercial software. Government users are subject to the Sun Microsystems, Inc. standard license agreement andapplicable provisions of the FAR and its supplements.

This distribution may include materials developed by third parties.

Sun, Sun Microsystems, the Sun logo, Java, Solaris, HotSpot, J2ME, J2SE, J2EE, Java Developer Connection, Java Community Process, JCP,Javadoc, JDK, JavaCall, Java Card, phoneME and the Java Coffee Cup logo are trademarks or registered trademarks of Sun Microsystems, Inc.or its subsidiaries in the U.S. and other countries.

UNIX is a registered trademark in the U.S. and other countries, exclusively licensed through X/Open Company, Ltd.

Intel is a trademark or registered trademark of Intel Corporation or its subsidiaries in the United States and other countries.

OpenGL is a registered trademark of Silicon Graphics, Inc.

The PostScript logo is a trademark or registered trademark of Adobe Systems, Incorporated, which may be registered in certain jurisdictions.

Products covered by and information contained in this service manual are controlled by U.S. Export Control laws and may be subject to theexport or import laws in other countries. Nuclear, missile, chemical biological weapons or nuclear maritime end uses or end users, whetherdirect or indirect, are strictly prohibited. Export or reexport to countries subject to U.S. embargo or to entities identified on U.S. export exclusionlists, including, but not limited to, the denied persons and specially designated nationals lists is strictly prohibited.

DOCUMENTATION IS PROVIDED "AS IS" AND ALL EXPRESS OR IMPLIED CONDITIONS, REPRESENTATIONS AND WARRANTIES,INCLUDING ANY IMPLIED WARRANTY OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE OR NON-INFRINGEMENT,ARE DISCLAIMED, EXCEPT TO THE EXTENT THAT SUCH DISCLAIMERS ARE HELD TO BE LEGALLY INVALID.

Copyright © 2008 Sun Microsystems, Inc., 4150 Network Circle, Santa Clara, California 95054, États-Unis. Tous droits réservés.Sun Microsystems, Inc. détient les droits de propriété intellectuelle relatifs à la technologie incorporée dans le produit qui est décrit dans cedocument. En particulier, et ce sans limitation, ces droits de propriété intellectuelle peuvent inclure un ou plusieurs des brevets américains listésà l’adresse http://www.sun.com/patents et un ou plusieurs brevets supplémentaires ou les applications de brevet en attente aux États -Unis et dans d’autres pays.CE PRODUIT CONTIENT DES INFORMATIONS CONFIDENTIELLES ET DES SECRETS COMMERCIAUX DE SUN MICROSYSTEMS, INC.SON UTILISATION, SA DIVULGATION ET SA REPRODUCTION SONT INTERDITES SANS L AUTORISATION EXPRESSE, ECRITE ETPREALABLE DE SUN MICROSYSTEMS, INC.Droits du gouvernement des États-Unis - logiciel commercial. Les droits des utilisateur du gouvernement des États-Unis sont soumis auxtermes de la licence standard Sun Microsystems et aux conditions appliquées de la FAR et de ces compléments.

Cette distribution peut inclure des elements développés par des tiers.

Sun, Sun Microsystems, le logo Sun, Java, Solaris, HotSpot, J2ME, J2SE, J2EE, Java Developer Connection, Java Community Process, JCP,Javadoc, JDK, JavaCall, Java Card, phoneME et le logo Java Coffee Cup sont des marques de fabrique ou des marques déposées de SunMicrosystems, Inc., ou ses filiales, aux États-Unis et dans d’autres pays.

UNIX est une marque déposée aux États-Unis et dans d’autres pays et sous licence exclusive de X/Open Company, Ltd.

Intel est une marque déposée de Intel Corporation ou de sa filiale aux États-Unis et dans d’autres pays.

OpenGL est une marque déposée de Silicon Graphics, Inc.

Le logo PostScript est une marque de fabrique ou une marque déposée de Adobe Systems, Incorporated, laquelle pourrait à déposée danscertaines juridictions.Les produits qui font l’objet de ce manuel d’entretien et les informations qu’il contient sont régis par la législation américaine en matière decontrôlé des exportations et peuvent être soumis au droit d’autres pays dans le domaine des exportations et importations. Les utilisationsfinales, ou utilisateurs finaux, pour des armes nucléaires, des missiles, des armes biologiques et chimiques ou du nucléaire maritime,directement ou indirectement, sont strictement interdites. Les exportations ou réexportations vers des pays sous embargo des États-Unis, ouvers des entités figurant sur les listes d’exclusion d’exportation américaines, y compris, mais de maniéré non exclusive, la liste de personnesqui font objet d’un ordre de ne pas participer, d’une façon directe ou indirecte, aux exportations des produits ou des services qui sont régi parla législation américaine en matière de contrôlé des exportations et la liste de ressortissants spécifiquement désignes, sont rigoureusementinterdites.

LA DOCUMENTATION EST FOURNIE "EN L’ÉTAT" ET TOUTES AUTRES CONDITIONS, DÉCLARATIONS ET GARANTIES EXPRESSESOU TACITES SONT FORMELLEMENT EXCLUES, DANS LA MESURE AUTORISÉE PAR LA LOI APPLICABLE, Y COMPRIS NOTAMMENTTOUTE GARANTIE IMPLICITE RELATIVE A LA QUALITÉ MARCHANDE, A L’APTITUDE A UNE UTILISATION PARTICULIÈRE OU AL’ABSENCE DE CONTREFAÇON.

Page 3: Architecture and Design Guide by Oracle

Contents

Preface xxi

1. Software Overview 1

Specifications and APIs 1

Architecture 2

MIDP Services and Subsystems 3

Components 5

Control Flow 6

Device Interactions 7

2. Porting Overview 9

Build the Software on the Reference Platform 10

Run TCKs on the Reference Port 10

Set Up and Configure Your Device Development Environment 11

Port the JavaCall API 12

Functions and Naming 12

Directory Structure 13

Understanding the Event Module 13

The JavaCall Porting Process 14

3. Hardware and Software Requirements and Constraints 17

iii

Page 4: Architecture and Design Guide by Oracle

Data-Type Assumptions 18

Resource Limitations 18

Native Stack Size 18

AMS Resource Limitations 19

RMS Resource Limitations 19

The system.jam_space Property 20

The DEFAULT_TOTAL_SPACE Property 20

The STORAGE_SUITE_LIMIT Property 20

Networking Resource Limitations 21

Graphics Resource Limitations 21

Other Resources 21

4. Managing Properties and Constants 23

Introduction 23

Design 24

Input Files 25

Properties 28

Modifying Properties 28

▼ Adding Properties 28

Constants 29

Modifying Constants 29

▼ Adding Constants 29

Changing the Output Format of Constants 31

5. Using the Logging, Tracing, and Assertion Services 33

Building to Enable the Logging, Tracing, and Assertion Services 34

Dynamic Logging and a MIDlet’s JAD File 35

Using the Logging, Tracing, and Assertion APIs 36

Logging 36

iv Architecture and Design Guide • December 2008

Page 5: Architecture and Design Guide by Oracle

Adding Logging Channels 37

Tracing 38

Assertions 38

6. Porting the Record Management System 41

Design 42

Design Overview 42

External API and the Sandbox 43

Detailed Design 43

Design Rationale, Notes, and Considerations 43

Database Implementation 43

Detailed Design 44

Design Rationale, Notes, and Considerations 44

File System Access 45

Porting 45

7. File Organization and Naming 47

Source Code Organization 47

Naming Convention for Native Files 54

8. PCSL 57

PCSL Print Library 58

PCSL Memory Allocation Library 59

Porting malloc-Based Implementations 60

Porting the Heap-Based Implementation 61

PCSL File System Interface 62

PCSL Networking Library 64

Handles and Contexts 65

Alternative Networking Implementations 66

BSD Implementations 68

Contents v

Page 6: Architecture and Design Guide by Oracle

Socket-over-Serial Implementation 69

Notification 69

PCSL String Library 70

Porting Unicode Resource Names 72

About Radix 41 Encoding 73

Encoding for Non-English Resource Names 74

9. PutPixel Technology 75

Porting 75

Building 76

Testing 76

Tuning 76

10. Low-Level Graphics and Images Services 79

Description 79

External Interactions 80

Design 80

Graphics Rendering Component 81

Primitive Graphics Routines and Porting 81

Design Rationale, Notes, and Considerations 82

Graphics Context Component 83

Detailed Design 83

Image Component 84

Preprocessor Component 85

Decoder Component 87

Accessor Component 89

Image Storage Component 89

Renderer Component 90

Porting 90

vi Architecture and Design Guide • December 2008

Page 7: Architecture and Design Guide by Oracle

Porting the Primitive Graphics Group 91

Porting Checklist for Primitive Graphics 92

Drawing Graphics Primitives 93

Porting Image Manipulation Group 101

Mutable and Immutable Images 101

Porting Checklist for the Image Manipulation Group 105

Functions to Port 105

▼ Facilitating Porting of the Image Manipulation Group 105

String and Font Drawing and Accessing Group 107

Alert Sound Group 108

Vibrate and Backlight Group 108

Backlight Control Methods 108

Backlighting Porting Interface 109

Strategies for Porting Backlighting 109

Backlighting Duration 110

Vibration Control Methods 110

Vibration Porting Interface 110

Vibration Support 111

Network Indicator 112

Porting Strategies 112

Porting Issues 113

Porting Verification 113

Error Checking 113

Boundary Cases 113

Performance Tuning 114

11. Implementing the High-Level UI Using Adaptive User Interface Technology115

Design 115

Contents vii

Page 8: Architecture and Design Guide by Oracle

Customization 117

Property Loading and Skin Customization 117

Image Usage and Support 117

Compressed Images Compared With Uncompressed Images 118

ROMized Images Compared With File System Images 118

Storing Image Resources in the File System 118

Storing Image Resources in the ROM 119

RAW Format Platform Specification 120

Support for Virtual Keyboard 121

Porting Steps 121

12. Implementing the High-Level UI Using Platform Components 125

Overview 125

Component Dependencies 126

Porting Steps 127

Testing 130

13. Porting the Event Processing Service 133

Event System 134

▼ Submitting Native Events 136

Complete the Event Fields 136

Locking 137

Setting the MAX_EVENTS Constant 138

Types of Event Systems 138

Normal Mode 138

Slave Mode 140

Choosing Normal or Slave Mode 142

14. Application Management with the Java Platform 145

Native AMS 146

viii Architecture and Design Guide • December 2008

Page 9: Architecture and Design Guide by Oracle

AMS Functionality 146

External Interactions With AMS 149

MIDlet Suite Attributes 151

Extended MIDlet Attributes 152

Inter-MIDlet Communication 153

Using the Pipe Communication Protocol 154

Downloading Dynamic Components 156

Configuring the AMS for Dynamic Components 156

Defining the Location for Dynamic Content 157

Security Restrictions 158

Support for Clamshell Devices 158

Porting and Customizing 159

Strategies for Porting the AMS 159

Strategies for Customizing the AMS 160

Things to Consider 160

AMS UI Implementation 161

Configuration Examples 162

Default Implementation 162

Custom Installer 163

Default Application Manager 164

Custom Application Manager 165

15. MIDlet Auto Invocation 167

Design 168

Design Overview 169

Push Connection States 170

Design Rationale, Notes, and Considerations 171

Porting 172

Protocols 172

Contents ix

Page 10: Architecture and Design Guide by Oracle

Listening for Incoming Data 173

Message Buffering 173

User Interaction 174

MIDlet Concurrency 174

▼ Adding Network Protocols for Push 174

16. Runtime Security 177

Design Considerations 178

Native VM Startup Code and MIDlet Suite Loader 178

Class Loader 178

Security Token 179

Using the Service 179

Classes Protected by Security Tokens 179

Classes Used by Internal MIDlets 180

17. Permission Management 181

Design Overview 182

Security Handler 182

Permissions 182

Design Rationale, Notes, and Considerations 184

Policy Configuration 184

Implementations 185

New Permissions 185

▼ Adding a New Permission 185

New Domains 187

▼ Adding a New Domain 187

Using Permissions for Internal MIDlets 187

Finding the Status of a Security Certificate 188

18. Native Resource Management for Multitasking 189

x Architecture and Design Guide • December 2008

Page 11: Architecture and Design Guide by Oracle

Fixed Resource Policy 189

Open Resource Policy 190

Porting 191

19. Porting the Networking Subsystem 193

Generic Connection Framework and Protocol Implementations 194

Porting the Networking Subsystem 195

General Porting Considerations 197

Porting Considerations for HTTP 197

HTTP Requests Using Proxies 197

HTTP1.1 Persistent Connections 198

Porting Considerations for HTTPS 198

Porting HTTPS 198

Using the Java Wireless Client Software SSL Implementations 199

Porting Considerations for Server Socket 199

Network Monitoring 199

References 205

20. Porting the User Message Bundle Service 207

Design 207

Access Module 208

Behavior Module 208

Decoder-Encoder Component 209

Design Rationale, Notes, and Considerations 209

Porting 209

▼ Adding Additional Message Strings 210

Supporting a New Locale 210

▼ Supplying Locale-Specific Strings 210

Adding a Character Encoding 211

Contents xi

Page 12: Architecture and Design Guide by Oracle

Changing the Default Screen Orientation 213

Customizing the Screen Display 213

21. Games 215

Engineering and Device Requirements 215

Design 216

Sprites and Tiled Layers 217

Example Sprite 217

Example Tiled Layer 218

Layer Manager Component 219

Game Canvas Component 220

Design Rationale, Notes, and Considerations 220

Porting 220

Porting GameCanvas 221

Porting Sprite and TiledLayer 221

A. Performance Notes 223

Application Startup Time 223

Measuring Startup Time 223

Handling Startup Time Variance 224

Starting an Application 225

Optimizing a MIDlet for Improved Application Startup Time 226

Optimizing the System for Improved Application Startup Time 227

Minimizing the Static Initialization of System Classes 227

Controlling the JIT Compiler and Ahead-of-Time Compilation 228

Giving the VM Hints 228

Disabling the Class Verifier 230

Caching Images 230

▼ Caching JAR File Entries 231

xii Architecture and Design Guide • December 2008

Page 13: Architecture and Design Guide by Oracle

Runtime Performance 232

Performance Metrics 232

▼ Profiling the System 233

Runtime Optimizations 233

Caching 233

Indexing 234

Buffering 234

Memory Footprint 235

▼ Measuring Footprint 235

Minimizing Static and Dynamic Footprint 236

Heap Capacity for the Java Platform 236

▼ Minimizing the Space Used by AOT and JIT Compilation 237

Minimizing Full Garbage Collections at Startup 238

Summary 238

Glossary 241

Index 245

Contents xiii

Page 14: Architecture and Design Guide by Oracle

xiv Architecture and Design Guide • December 2008

Page 15: Architecture and Design Guide by Oracle

Figures

FIGURE 1-1 Overall Architecture 2

FIGURE 1-2 Component Implementation 5

FIGURE 1-3 Modular Architecture Supporting Multiple Implementations 6

FIGURE 1-4 Component Relationships and Flow Control 7

FIGURE 1-5 Possible APIs in Subsystems and Services 8

FIGURE 1-6 Porting Points 8

FIGURE 4-1 Configurator Work Flow for Constants and Properties 25

FIGURE 6-1 RMS Subsystem Components 42

FIGURE 8-1 Five PCSL Networking Implementations 67

FIGURE 10-1 Subsystem Interactions 80

FIGURE 10-2 drawLine Method Through Its C Call 82

FIGURE 10-3 Functions That Update Property Values and Functions Providing Data 83

FIGURE 10-4 Components of the Low-Level Graphics and Images Service Subsystem 85

FIGURE 10-5 Decoder Architecture 87

FIGURE 10-6 drawLine Method Through Its C Call 91

FIGURE 10-7 Graphics Class Coordinate System 94

FIGURE 10-8 Drawing a Line 95

FIGURE 10-9 Drawing Compared With Filling a Rectangle 96

FIGURE 10-10 Ellipse 96

FIGURE 10-11 Circle 97

xv

Page 16: Architecture and Design Guide by Oracle

FIGURE 10-12 0, 90, and -90 Degrees on a Circle 97

FIGURE 10-13 Boxed Ellipse 98

FIGURE 10-14 45 and -120 Degrees on a Circle 99

FIGURE 10-15 45 and -120 Degrees on an Ellipse 99

FIGURE 10-16 Boxed Circle and Ellipse, With a 45 Degree Angle 99

FIGURE 10-17 Drawing a Rectangle With Rounded Corners 100

FIGURE 12-1 Major Elements of the High-Level UI in a Java Wireless Client Software Port 126

FIGURE 12-2 High-Level GUI Components and Dependencies 127

FIGURE 13-1 Event Queue Components and Interactions 135

FIGURE 13-2 CLDC HotSpot Implementation Running in Normal Mode 139

FIGURE 13-3 CLDC HotSpot Implementation Running in Slave Mode 142

FIGURE 14-1 AMS Architecture on a Device 149

FIGURE 14-2 AMS Using Java Wireless Client Software Default Implementations 163

FIGURE 14-3 AMS Using Custom Installer 163

FIGURE 14-4 AMS With Custom Installer and Custom Suite Storage Implementation 164

FIGURE 14-5 AMS With Default Java Wireless Client Software Application Manager 165

FIGURE 14-6 AMS With Custom Native Application Manager 166

FIGURE 15-1 Push Connection’s State Transitions 171

FIGURE 20-1 User Message Bundle Service Components and Interactions 208

FIGURE 21-1 Interactions of Subsystems 215

FIGURE 21-2 Source Image for a Sprite 218

FIGURE 21-3 Example Animation Sequence 218

FIGURE 21-4 Source Image for a Set of Tiles 218

FIGURE 21-5 Tiled Layer 219

xvi Architecture and Design Guide • December 2008

Page 17: Architecture and Design Guide by Oracle

Tables

TABLE 1-1 Java Wireless Client Software Services 3

TABLE 1-2 Java Wireless Client Software Subsystems 4

TABLE 7-1 Java Wireless Client Software Subsystems and Libraries 48

TABLE 7-2 Native File Library Prefix Examples 55

TABLE 8-1 PCSL Technologies File System Locations 67

TABLE 10-1 Low-Level Graphics Constants 93

TABLE 14-1 Application Management Functionality 147

TABLE 14-2 Additional Test and Development Functionality 147

TABLE 14-3 AMS Interaction With Java Wireless Client Software Systems 149

TABLE 15-1 Auto Invocation Subsystem Interactions 168

TABLE 17-1 Permission Level 183

TABLE 17-2 Java Technology for the Wireless Industry Permission Levels 184

TABLE 19-1 Networking Subsystem Protocols 193

TABLE 19-2 Common Features Used by Java Classes 195

TABLE 19-3 Network Monitor Hooks (1) 200

TABLE 19-4 Network Monitor Hooks (2) 203

TABLE A-1 Initial Steps in the Procedure for Starting a MIDlet 225

xvii

Page 18: Architecture and Design Guide by Oracle

xviii Architecture and Design Guide • December 2008

Page 19: Architecture and Design Guide by Oracle

Code Examples

CODE EXAMPLE 4-1 Adding a New Element to a Property File 28

CODE EXAMPLE 4-2 constant_class Element in Constants Input File 30

CODE EXAMPLE 4-3 constant Element in constant_class Element of Input File 30

CODE EXAMPLE 5-1 MID_CONTROL_ARG Syntax 35

CODE EXAMPLE 5-2 Testing a Log Message’s Severity Against REPORT_LEVEL 36

CODE EXAMPLE 5-3 Using the if Statement Tests a Message’s Severity 37

CODE EXAMPLE 5-4 Adding a Channel Definition for a Bluetooth Module 37

CODE EXAMPLE 5-5 Using an if Statement to Test if TRACE_ENABLED is true 38

CODE EXAMPLE 5-6 if Statement for ASSERT_ENABLED 39

CODE EXAMPLE 10-1 midpLCDUIShowBacklight Interface 109

CODE EXAMPLE 10-2 midpLCDUIShowBacklight Interface Without Backlight Control 110

CODE EXAMPLE 10-3 Starting Vibration 111

CODE EXAMPLE 10-4 Stopping Vibration 111

CODE EXAMPLE 12-1 runMidlet Utility Syntax 130

CODE EXAMPLE 13-1 Code Completing a MidpEvent Data Structure 136

CODE EXAMPLE 14-1 JAD file descriptors 152

CODE EXAMPLE 14-2 Extended MIDlet attributes 152

CODE EXAMPLE 14-3 MIDlet server-side connection 155

CODE EXAMPLE 14-4 Client MIDlet connects to server-side MIDlet 155

CODE EXAMPLE 14-5 Transferring data between server-side and client MIDlets 155

xix

Page 20: Architecture and Design Guide by Oracle

CODE EXAMPLE 14-6 Closing the connection between MIDlets 155

CODE EXAMPLE 14-7 The installComponent interface 158

CODE EXAMPLE 17-1 Permission Extension. 186

CODE EXAMPLE 20-1 Setting the Screen Orientation 213

xx Architecture and Design Guide • December 2008

Page 21: Architecture and Design Guide by Oracle

Preface

This Guide provides information that is useful to consider before and during a portof the Sun JavaTM Wireless Client (SJWC) software, version 2.2, to your mobiledevice.

For more information on the steps and procedures you should follow to port theSJWC software, see the Sun Java Wireless Client Software Porting User’s Guide.

Before You Read This BookTo fully use the information in this document, you must have thorough knowledgeof the topics discussed in these documents:

■ JSR 139 Connected Limited Device Configuration 1.1

■ JSR 118 Mobile Information Device Profile 2.0

■ JSR 185 Java Technology for the Wireless Industry

■ JSR 248 Mobile Service Architecture

■ CLDC HotSpot™ Implementation Porting Guide

■ Skin Author’s Guide to Adaptive User Interface Technology

■ JSR 75 PDA Optional Packages for the J2ME Platform

■ JSR 82 Java APIs for Bluetooth

■ JSR 120 Short Message Service API

■ JSR 135 Mobile Media API

■ JSR 172 J2ME Web Services

■ JSR 177 Security and Trust Services API for J2ME

■ JSR 179 Location API for J2ME

Preface xxi

Page 22: Architecture and Design Guide by Oracle

■ JSR 180 SIP API for J2ME

■ JSR 205 Wireless Messaging API 2.0

■ JSR 211 Content Handler API

■ JSR 226 Scalable 2D Vector Graphics API for J2ME

■ JSR 234 Advanced Multimedia Supplements

■ JSR 238 Mobile Internationalization API

■ JSR 239 Java Binding for the OpenGL ES API

■ JSR 256 Mobile Sensor API

■ JSR 280 XML API for Java ME

How This Book Is OrganizedThis book contains the following chapters and appendices:

Chapter 1 is a basic overview of the Java Wireless Client software and how it works.

Chapter 2 is an overview of the porting process. This chapter provides a high-levelstrategy for porting the Java Wireless Client software to your device.

Chapter 3 lists the hardware and software required to successfully port the software,and describes some limitations of the software.

Chapter 4 documents how to manage properties and constants in Java WirelessClient software with a tool called the configurator.

Chapter 5 documents the design and porting of the logging and tracing subsystem ofthe Java Wireless Client software.

Chapter 6 documents the design of and strategies for porting the recordmanagement (RMS) subsystem.

Chapter 7 documents how the source base is organized and the conventions used fornaming native files.

Chapter 8 documents the Portable Common Services Library (PCSL) and its use inthe porting process.

Chapter 9 documents how to implement graphics, images, and fonts using PutPixeltechnology.

Chapter 10 documents the low-level graphics and images service.

xxii Architecture and Design Guide • December 2008

Page 23: Architecture and Design Guide by Oracle

Chapter 11 documents how to port the high-level user interface using Adaptive UserInterface Technology software (AUI Technology software).

Chapter 12 documents how to port the high-level user interface using platformcomponents.

Chapter 13 documents the design and porting of the event processing service.

Chapter 14 documents the design and porting of the application managementservice (AMS) subsystem.

Chapter 15 documents the design and porting of the MIDlet auto invocationsubsystem of the Java Wireless Client software.

Chapter 16 documents the design and use of the runtime security service.

Chapter 17 documents how the runtime security service uses permissionmanagement.

Chapter 18 documents native resource management policies used for multitasking.

Chapter 19 documents the design and porting of the networking subsystem of theJava Wireless Client software.

Chapter 20 documents the design and porting of the user message bundle subsystemused for internationalizing the Java Wireless Client software.

Chapter 21 documents the design and porting of the game subsystem of the JavaWireless Client software.

Appendix A describes how to analyze and tune the performance of the Java WirelessClient software.

Using Operating System CommandsThis document does not contain information on basic UNIX® operating system orMicrosoft Windows commands and procedures such as opening a terminal window,changing directories, and setting environment variables. See the softwaredocumentation that you received with your system for this information.

Preface xxiii

Page 24: Architecture and Design Guide by Oracle

Typographic Conventions

Shell Prompts

Related DocumentationThe following documentation is included with this release:

Typeface Meaning Examples

AaBbCc123 The names of commands, files,and directories; on-screencomputer output

Edit your .login file.Use ls -a to list all files.% You have mail.

AaBbCc123 What you type, whencontrasted with on-screencomputer output

% su

Password:

AaBbCc123 Book titles, new words or terms,words to be emphasized

Command-line variable; replacewith a real name or value

Read Chapter 6 in the User’s Guide.These are called class options.You must be superuser to do this.

To delete a file, type rm filename.

Shell Prompt

C shell %

TABLE P-1

Application Title

All Release Notes

Building Build Guide

Porting Issues and Overview Architecture and Design Guide

xxiv Architecture and Design Guide • December 2008

Page 25: Architecture and Design Guide by Oracle

In addition, you might find the following documentation helpful:

■ The Java Language Specification (Java Series), Second Edition by James Gosling, BillJoy, Guy Steele and Gilad Bracha. Addison-Wesley, 2000,http://java.sun.com/docs/books/jls/index.html.

■ The Java Specification Request (JSR), (J2ME Connected, Limited DeviceConfiguration) at http://jcp.org/jsr/detail/30.jsp (JSR 30)

■ Mobile Information Device Profile 2.0, athttp://jcp.org/jsr/detail/118.jsp (JSR 118)

■ Java Technology for the Wireless Industry, athttp://jcp.org/jsr/detail/185.jsp (JSR 185)

■ A full list of JSRs for the Java Platform, Micro Edition (Java ME platform),available at http://jcp.org/jsr/tech/j2me.jsp

■ KVM Debug Wire Protocol (KDWP) Specification, Sun Microsystems, Inc.,available as part of the CLDC (Connected Limited Device Configuration)download package.

Accessing Sun Documentation OnlineThe Source for Java Developers web site enables you to access Java platformtechnical documentation on the web athttp://java.sun.com/reference/docs/index.html.

Porting Procedures and Guidelines Porting Guide

Running SJWC Software and Using Tools Tools Guide

Multitasking Integration and Policies Multitasking Guide

Using Adaptive User Interface Technology (skins) Skin Author’s Guide to Adaptive UserInterface Technology

Viewing reference documentation created by theJavadoc™ tool

Java API Reference

Viewing reference documentation created by theDoxygen tool

Native API Reference

TABLE P-1

Application Title

Preface xxv

Page 26: Architecture and Design Guide by Oracle

Sun Welcomes Your CommentsWe are interested in improving our documentation and welcome your commentsand suggestions. Provide feedback to Sun athttp://java.sun.com/docs/forms/sendusmail.html.

xxvi Architecture and Design Guide • December 2008

Page 27: Architecture and Design Guide by Oracle

1

Software Overview

Java Wireless Client software is a high-performance Java ME platform stack formobile devices. Java Wireless Client software shortens the porting and integrationeffort with the following features:

■ It uses a modular architecture that supports multiple implementations withineach functional area (such as storage, networking, user interface, and so on).

■ It minimizes platform-specific code to achieve portability. Minimizing platform-specific code makes it easier to port Java Wireless Client software to a broad rangeof devices.

■ You can pick and choose the features you want on your device and implementthem as modules. This flexibility facilitates customizing your device’s featuresand functions for your customers.

Specifications and APIsJava Wireless Client software supports many components of Mobile ServiceArchitecture (MSA) (JSR 248). MSA is a comprehensive platform based on CLDCand MIDP. Here is a complete list of the APIs encompassed by Java Wireless Clientsoftware:

■ JSR 139 CLDC 1.1

■ JSR 118 MIDP 2.1

■ JSR 75 Personal Information Management (PIM) and FileConnection APIs

■ JSR 82 Bluetooth and OBEX APIs

■ JSR 120 Wireless Messaging API (WMA) 1.0

■ JSR 135 Mobile Media API (MMAPI) 1.1

■ JSR 172 Web Services

■ JSR 177 Security and Trust Services

Chapter 1 Software Overview 1

Page 28: Architecture and Design Guide by Oracle

■ JSR 179 Location

■ JSR 180 Session Initiation Protocol (SIP)

■ JSR 205 Wireless Messaging API (WMA) 2.0

■ JSR 211 Content Handler API (CHAPI)

■ JSR 226 Scalable 2D Vector Graphics (SVG)

■ JSR 234 Advanced Multimedia Supplements

■ JSR 238 Mobile Internationalization

■ JSR 239 Java Bindings for OpenGLTM Embedded Subsets

■ JSR 256 Mobile Sensors API

■ JSR 280 XML API for Java ME

In addition, Java Wireless Client software also supports JSR 239 OpenGL ES, anoptional API that is not part of MSA.

Consult the Java Community Process™ (JCP™) program web site,http://jcp.org/, for more information on any of these specifications.

ArchitectureIn very broad terms, the architecture of Java Wireless Client software looks like this:

FIGURE 1-1 Overall Architecture

Java Wireless Client software is everything that lies between the OS andapplications. (The OS layer sits directly below the JavaCall layer). The Java WirelessClient software includes:

■ The JavaCall™ layer distills the platform requirements of the entire platformdown to a single set of functions that must be ported. All porting is done at thesame layer, and the functions are consistently named and well documented.

■ Portable Common Services Library (PCSL) is a layer of low-layer services that areused by CLDC, MIDP, and some of the optional APIs.

2 Architecture and Design Guide • December 2008

Page 29: Architecture and Design Guide by Oracle

Note – In FIGURE 1-1, PCSL is a component within the MIDP/CLDC block.

■ Connected, Limited Device Configuration (CLDC) is an implementation of JSR139. It includes a virtual machine and core Java ME application APIs.

■ Mobile Information Device Profile (MIDP) is an implementation of JSR 118.

■ Optional package JSRs provide optional functionality supported under the MSA248 Specification. For a complete list of supported optional packages, see“Specifications and APIs” on page 1.

■ The Abstraction Layer is a set of functionality that allows all optional packages totalk to MIDP/CLDC through a common set of interfaces.

You don’t have to do any porting on PCSL, CLDC, MIDP, and the optional APIs,because they are internally ported to the JavaCall API already. To port to a newplatform, all you have to do is the implement the JavaCall API functions to performthe actual work in the underlying OS. For new development, the JavaCall API is alsorecommended.

For step-by-step instructions on porting to your platform, see the Sun Java WirelessClient Porting User’s Guide.

MIDP Services and SubsystemsThe MIDP component is composed of a modular set of services and subsystems.Services provide functionality that all subsystems use, such as logging. Subsystemsare high-level functional blocks, such as the user interface and networking.

The following table lists the Sun Java Wireless Client Software services.

TABLE 1-1 Java Wireless Client Software Services

Service Description

Logging and tracing Provides a way to collect information that developers can useduring a porting effort or at a later stage of productdevelopment.

Native memorymanagement

Provides a basic set of memory management routines, such asallocating and freeing memory, that all other subsystems use.

User message bundles Provides support for localization.

Chapter 1 Software Overview 3

Page 30: Architecture and Design Guide by Oracle

The following table lists the Java Wireless Client software subsystems.

Event processing Collects and dispatches system events such as userinteraction, networking, push events, I/O, and so on.

Security Determines trust in (and permissions for) MIDlet suites andprotects APIs.

Configuration Maintains constants and properties so that they have the samedefinition in both the Java platform layer (Java layer) and thenative platform layer. Also compiles in property values toavoid initialization overhead. See Chapter 4 for moreinformation.

TABLE 1-2 Java Wireless Client Software Subsystems

Subsystem Description

Application Management Software (AMS)and over-the-air (OTA) provisioning

Finds MIDlet suites, manages and executesthem on the device

Networking Sends and receives data

Push Receives a communication initiated by anexternal entity

Record Management System (RMS) Provides record-oriented persistent storage,enforces a permission policy for accessingthe records, and enforces size constraints onthe record store

Optional APIs Mobile Service Architecture (MSA)compliant optional APIs. These optionalAPIs are described in the Optional PackagesPorting Guide.

User Interface (LCDUI) Interacts with the end user of a devicethrough high-level and low-level user-interface components and supports games

TABLE 1-1 Java Wireless Client Software Services (Continued)

Service Description

4 Architecture and Design Guide • December 2008

Page 31: Architecture and Design Guide by Oracle

ComponentsJava Wireless Client software subsystems and services are made up of one or morecomponents called libraries. A library is a unit with an explicitly declared exportedinterface. One or more implementations of the interface can exist. Eachimplementation declares dependencies on other libraries whose interfaces it imports.A library can be implemented partially in the Java programming language andpartially in native code.

No code is shared between alternative implementations of the same exportedinterface. Shared code resides in a separate library, ensuring that the interfacebetween the shared and non-shared portion is explicitly declared. This separationmakes it easy to reuse shared code in new implementations.

Platform-independent code and platform-specific code are contained in separatelibraries. The interface between the platform-independent and platform-dependentlibraries constitutes the porting interface as shown in FIGURE 1-2.

FIGURE 1-2 Component Implementation

Each library can have multiple implementations, each tailored to a different type ofdevice. This architecture makes Java Wireless Client software easier to port andmakes it easier to optimize performance. FIGURE 1-3 describes this architecture.

Platform-independent libraries

Platform-dependent libraries

Porting API

Subsystem or service

Chapter 1 Software Overview 5

Page 32: Architecture and Design Guide by Oracle

FIGURE 1-3 Modular Architecture Supporting Multiple Implementations

When you port the Java Wireless Client software, you choose the set of libraries mostsuited to your system. For each library, you can either choose one of existingimplementations or provide your own implementation of the library’s exportedinterface. Because libraries are bound at compile time, this approach has no impacton runtime performance. The build system sets aside unused libraries andimplementations so the system’s footprint on the device is not increased.

Control FlowThe following diagram illustrates the relationship between the different JavaWireless Client software components. It highlights how control flows between thedifferent components.

Application (MIDlet)

Target platform

Libraries: Multipleimplementations of JavaWireless Client software

6 Architecture and Design Guide • December 2008

Page 33: Architecture and Design Guide by Oracle

FIGURE 1-4 Component Relationships and Flow Control

Device InteractionsThis section describes how Java Wireless Client software fits into the platformenvironment. It provides a general idea of what the porting points (areas ofinteraction between Java Wireless Client software and the device) are. The portingpoints are made possible by the APIs shown in FIGURE 1-2 and FIGURE 1-5.

FIGURE 1-5 Possible APIs in Subsystems and Services

PCSL

Hardware

Underlying OS/JavaCall API

CLDC

MIDP

Application

Platform-independentcode

Platform-specificCLDC code

Eventmanagementcode

Platform-specificMIDP code

Application

Target platform

Subsystemor

servicelibraries

Subsystemor

servicelibraries

Public APIs

Porting APIs

Internal APIs

Chapter 1 Software Overview 7

Page 34: Architecture and Design Guide by Oracle

FIGURE 1-6 shows a number of porting points. For example, one porting point bindsJava Wireless Client software low-level graphics primitives with the graphics libraryof your device. Another porting point manages applications, such as Java WirelessClient software, using native code to provide Over-the-Air (OTA) provisioningrequired by the MIDP 2.0 Specification.

FIGURE 1-6 Porting Points

Graphical display

Persistent storage Networking

LEDs

User interaction

Speaker

Application management

Java WirelessClient software

8 Architecture and Design Guide • December 2008

Page 35: Architecture and Design Guide by Oracle

2

Porting Overview

This chapter is a high-level overview of the porting process. It breaks the portingprocess into a series of discrete, general steps and provides a description andrationale for each step.

Note – The Sun Java Wireless Client Porting User’s Guide provides a step-by-stepprocess for porting the Sun Java Wireless Client software to a standalone orhandheld device. For more information, see that guide.

To port the Sun Java Wireless Client software, follow these general steps:

1. Build for one of the reference platforms. This verifies that you have most of theright tools available and understand at a high level how the build works. You getto practice building with a fully functional set of source code before starting theport to your own device. Consult the Build Guide for instructions on building JavaWireless Client software.

2. Run TCKs on the reference platform build. Configuring and running TCKs isnot a simple task, so doing this on a reference platform build gives you somepractice on a working build before you start porting to your own device.

3. Set up your device development system. You might need another compiler tobuild for your device. In addition, you need to understand or create mechanismsfor moving executables to your device, running them, and interacting with them.

4. Port the Sun Java Wireless Client software (and supporting optional packages)using the JavaCall API. As you complete each component, run tests to verifyyour implementation. For more information and the specific steps to take tocomplete your port, see Sun Java Wireless Client Porting User’s Guide.

Chapter 2 Porting Overview 9

Page 36: Architecture and Design Guide by Oracle

Build the Software on the ReferencePlatformThe first step in the porting process is to build and understand a Java Wireless Clientsoftware reference platform port.

By building a source base that is known to build correctly and to run on a specificplatform, you can become familiar with the source base and the process required tobuild the software. Because you can observe its behavior in a debugger while youwork on your port, the reference port is extremely helpful when you start to port thesoftware to your device.

Note – Be sure to document the process as you go so that it can be replicated byother developers in your organization.

The Build Guide describes how to build a reference platform port.

Run TCKs on the Reference PortTo demonstrate that your port conforms to the relevant specifications and iscompatible with other versions of the software, you must run the applicableTechnology Compatibility Kits (TCKs) on the finished product. The task ofconfiguring the TCKs and successfully running the tests is not a simple one. For thatreason, run the TCK on the reference port before you attempt to run it on yourported version of the software. By first running the TCK on the referenceimplementation, you know that all the tests run successfully and that no tests fail. Ifany tests fail, it is probably because you configured the test environment incorrectly.

After you successfully configure and run the TCK on the reference port, it is mucheasier to run the test suite on your ported version of the software.

Be sure to document the process as you go so that it can be replicated by otherdevelopers in your organization.

You must run the current applicable TCK for each portion of the Java Wireless Clientsoftware that you port.

10 Architecture and Design Guide • December 2008

Page 37: Architecture and Design Guide by Oracle

Note – As delivered, the Java Wireless Client software does not include all of thesoftware components necessary to pass all of the TCKs. For multimedia (bothMMAPI and AMMS), 3D graphics, and OpenGL® ES in particular, you mustintegrate third-party components before the corresponding TCK tests are passed.

Set Up and Configure Your DeviceDevelopment EnvironmentTo be able to port efficiently, you must set up your development environment so thatyou can download programs and data into your device and receive debugginginformation from the device. Specifically, your environment must enable you to dothe following tasks:

■ Build the system

■ Get the executable code onto the device

■ Run the code on the device

■ Understand what happens when the code runs

■ Load files or data onto the device

■ Read files or data from the device

Requirements differ depending on your development environment. For example, ifyou develop your port on a software emulator that runs on a computer system, youmight be able to accomplish this by simply copying files into the emulator and usingprintf statements to write to the console. On the other hand, if you develop on asimulator board, a development board, or directly on the device, this can be morecomplicated because it has no console. However, a serial port through which (withextra work) you can get output might be available.

Chapter 2 Porting Overview 11

Page 38: Architecture and Design Guide by Oracle

Port the JavaCall APIThe JavaCall API provides a set of classes and methods that allow you to portcomponents in the Java Wireless Client software quickly and easily. The Java MEprogramming language functions in each module - CLDC, PCSL, MIDP, and theoptional package APIs - have already been written to their corresponding JavaCallfunctions.

Your job is to implement the code that ties the bottom of the JavaCall layer to thenative OS. You do this by implementing the relevant JavaCall functions on a step-by-step basis, as described in the Sun Java Wireless Client Porting User’s Guide.

Functions and NamingJavaCall API functions are grouped by purpose into modules. Each module isrepresented by one or more header files which define the functions in the module.

The JavaCall API contains two types of functions:

■ javacall_ functions perform some work in the native OS, usually on behalf of aMIDlet application. When you port to your own device, you must implement thebody of these functions.

■ javanotify_ functions are called by the native OS when important thingshappen, like key presses, incoming messages, or other events. When you port toyour own device, you must write code that will call these functions at theappropriate times.

A module contains some mix of javacall_ functions and javanotify_ functions.

For example, javacall/interface/jsr120_wma/javacall_sms.h defines ahandful of functions related to sending and receiving text messages. It includes ajavacall_sms_send() function thatsends a text message and ajavanotify_incoming_sms() function that is called when a message is received.

Your job is to implement the javacall_sms_send() function to use theunderlying OS services to send a text message. In addition, you must write OS codethat calls javanotify_incoming_sms() when a message is received from thenetwork.

The JavaCall API functions are also classified as mandatory or optional. Mandatoryfunctions must be implemented for the software to work. Optional functions havedefault implementations, but you might be able to provide better performance orfunctionality by implementing them.

12 Architecture and Design Guide • December 2008

Page 39: Architecture and Design Guide by Oracle

The Java Wireless Client software documentation includes the JavaCall APIReference, which is an extremely useful way to view detailed information about theJavaCall API.

Directory StructureThe JavaCall API is distributed in the javacall and javacall-com subdirectoriesunder the main Java Wireless Client software directory. These subdirectories containthe header files that define the JavaCall API as well as a full implementation forWindows.

javacall and javacall-com have similar internal structures. The JavaCall APIheader files are contained in javacall/interface and javacall-com/interface. Each header file contains a set of related functions. The headerfiles for MIDP live in subdirectories of javacall/interface/midp. Header filesfor optional APIs are contained in directories corresponding to their defining JSR.For example, the JavaCall API for Bluetooth functionality is contained injavacall-com/interface/jsr82_bt.

The header files used by MIDP, and some optional packages at the same time, residein javacall/interface/common.

Optional APIs might have more than one header file that defines the correspondingJavaCall API. For example, the PIM and FileConnection APIs defined by JSR 75 arerepresented by these headers:

javacall-com/interface/jsr75_pim_fc/javacall_pim.h

javacall-com/interface/jsr75_pim_fc/javacall_fileconnection.h

The JavaCall API includes an implementation for Windows injavacall/implementation/win32_emul and javacall-com/implementation/win32_emul. The source files are organized in a structuresimilar to the structure for the header files. For example,javacall/implementation/win32_emul/midp/lcd.c is the implementation ofthe JavaCall API defined in javacall/interface/midp/javacall_lcd.h.

Understanding the Event ModuleThe JavaCall API’s Event module deserves special mention. Unlike many of theother modules, it does not directly implement some higher-level application APIfunctionality.

Chapter 2 Porting Overview 13

Page 40: Architecture and Design Guide by Oracle

Instead, the Events module is used for communication between your native, OS-level implementation and the Java platform. In its simplest form, it is a messagequeue for exchanging messages between native threads and the Java platformthread.

One thread is dedicated to the Java platform. The virtual machine runs in thisthread, and your implementation of the JavaCall API will make native OS calls to dothe works of applications running in the Java platform.

At the same time, one or more native threads will find out about important eventslike key presses, incoming messages, requests to pause or resume the Java platform,and so on. The code running in native threads needs a way to notify the Javaplatform about these important events. As you learned in the last section, you writethe native code that calls the javanotify_ functions as needed.

Internally, the JavaCall API uses the Event module to communicate notificationsfrom the native thread to the Java platform thread. Part of your job is to port theEvent module so that when your native code calls javanotify_ functions, the Javaplatform thread receives the corresponding notifications.

For example, when an application sends a text message, eventually the Java platformcalls javacall_sms_send(). Your implementation of javacall_sms_send()uses OS or device functions to queue a message for sending. The OS sends themessage, probably in its own thread. When the sending is finished, your native codecalls javanotify_sms_send_completed(). The JavaCall API takes care of usingthe Event module to pass a message back to the Java platform thread.

For more informaton on the Event module, see Chapter 13.

The JavaCall Porting ProcessAs described in the Sun Java Wireless Client Porting User’s Guide, the recommendedorder to port the Java Wireless Client JavaCall subsystems is:

1. Logging Facility

2. Memory System

3. Time and Timers

4. Filesystem APIs

5. LCD (Display) APIs

6. Event Handling

7. Keypress Events

8. Lifecycle Events

9. Milestone One: Run a ROMized interactive MIDlet

14 Architecture and Design Guide • December 2008

Page 41: Architecture and Design Guide by Oracle

10. Basic Networking and Socket Communication

11. Advanced Networking and Socket Commun ication

12. Font System

13. Annunciator

14. Predictive Text Input Support (optional)

15. Native Image Decoding (optional)

16. Implement Optional APIs, including some or all of the following:

■ JSR 75 File Connection and Personal Information Management APIs

■ JSR 82 Bluetooth API

■ JSR 120 Wireless Messaging API 1.0

■ JSR 135 Mobile Media API

■ JSR 177 Security and Trust Services API

■ JSR 179 Location and Landmark Store API

■ JSR 205 Wireless Messaging API 2.0

■ JSR 211 Content Handler API

■ JSR 234 Advanced Multimedia Supplements

■ JSR 256 Mobile Sensor API

17. Milestone Two: Run TCKs and Test Your Completed Port

Chapter 2 Porting Overview 15

Page 42: Architecture and Design Guide by Oracle

16 Architecture and Design Guide • December 2008

Page 43: Architecture and Design Guide by Oracle

3

Hardware and SoftwareRequirements and Constraints

You can build Java Wireless Client software on Microsoft Windows or Linux.

Get started with a self-hosted build, which means you build, run, and debug thesoftware on the same machine. This is a great way to get acquainted with the buildsystem and structure of Java Wireless Client software.

Later, you cross-compile, which is building on one platform but running on another.For example, you could use a desktop Linux machine to build executables for theARM-based Texas Instruments OMAP730 development board.

Java Wireless Client software contains reference ports to the Microsoft Windowsplatform and the Texas Instruments OMAP730 development board. The hostdevelopment environment for building the OMAP730 implementation is a Linuxsystem running on x86 hardware. This chapter lists some requirements andconstraints of the reference ports and the development environment. The ReleaseNotes contain additional information.

The source code makes some assumptions about the capabilities of the developmentenvironment and the port’s target device. In addition, because Java Wireless Clientsoftware is designed for small devices, it has resource constraints that this chapterdescribes.

In addition to the Java Wireless Client software source distribution, the CLDCHotSpot™ Implementation, Version 2.0 source distribution is required to create acomplete Java Technology for the Wireless Industry software implementation for thetarget device.

Chapter 3 Hardware and Software Requirements and Constraints 17

Page 44: Architecture and Design Guide by Oracle

Data-Type AssumptionsThe native code in the Java Wireless Client software expects some data types to bespecific sizes, as follows:

■ int - 32 bits

■ short - 16 bits

■ char - 8 bits signed

■ long - 32 bits

■ sizeof(void*) = sizeof(int)

Native code might behave unpredictably if the platform does not satisfy theseexpectations.

Resource LimitationsJava Wireless Client software is intended to run on resource-constrained devices.Unlike a desktop or server system, available memory and persistent storage arelimited. Some devices quit when excess native resources are requested.

This section lists areas in which you can limit resources in the initial phase of yourport. The section contains possibilities, not an exhaustive list, of all the resourcesJava Wireless Client software could use or consume. Consult the MIDP specificationfor details.

Native Stack SizeThe CLDC HotSpot implementation uses a single stack (a primordial stack) to runnative code. To conserve runtime memory, try to define the stack size to match yourtarget platform.

A Java Wireless Client software binary is a normal executable produced by yourtarget platform’s tool chain just like other native binaries. Java Wireless Clientsoftware uses the default C stack provided by the tool chain as its primordial stack.

Whether you can change the default stack size, and how you change it, depends onyour build tools and your target device’s operating system. See your tool and devicedocumentation for information.

18 Architecture and Design Guide • December 2008

Page 45: Architecture and Design Guide by Oracle

If you can change the stack size, its minimum size depends on a number of factors,such as the type and complexity of Java ME technology applications that your portwill run, and the stack usage of your device’s native functions. A stack size that istoo small can lead to stack corruptions.

Tip – On the ARM platform, typical game MIDlets require between 5 kilobytes and6 kilobytes of primordial stack to run reliably. Adding a safety margin of 2 kilobytesmakes the minimum stack size 8 kilobytes.

AMS Resource LimitationsYou can set the following values used by the application management system:

■ Maximum size of a Java Archive file (JAR file). Note that Java Technology for theWireless Industry specifies 64 kilobytes as the lowest this limit can be set.

■ Maximum length of an attribute in a Java Application Descriptor file (JAD file).

■ Maximum size of a JAD file. The Java Technology for the Wireless Industryminimum is not specified.

■ Maximum length of a MIDlet suite’s name.

■ Maximum length of a file name.

RMS Resource LimitationsIn brief, the current limitations are as follows:

■ The minimum RMS data size that should be supported on an explicit suite requestis 64 kilobytes (according to MSA specification 1.0).

■ The maximum RMS data size per suite is 200,000 bytes.

■ The maximum suite storage size for all installed MIDlet suites and their RMS datais 1,000,000 bytes.

Java Wireless Client software limits suite storage size, which is the common spaceavailable for MIDlet suites and their record stores. The maximum RMS record storesize is separately limited by the RMS implementation.

Chapter 3 Hardware and Software Requirements and Constraints 19

Page 46: Architecture and Design Guide by Oracle

The system.jam_space PropertyIf the system.jam_space property is set, it is used as the maximum space forMIDlet suites and their record stores.

For JavaCall builds, this property is defined in the following location:

javacall-com/configuration/sjwc/win32_emul/properties.xml

For non-JavaCall builds, the system.jam_space property is defined here, whereplatform is the platform on which you are building:

midp/src/configuration/configuration_xml/platform/properties.xml

The default value for system.jam_space is 1,000,000 bytes.

The DEFAULT_TOTAL_SPACE PropertyIf system.jam_space is not defined, then DEFAULT_TOTAL_SPACE is used. Thisvalue is defined here:

midp/src/core/storage/reference/native/midpStorage.c

The default value for DEFAULT_TOTAL_SPACE is 4 megabytes.

The STORAGE_SUITE_LIMIT PropertyThe maximum size for record stores per MIDlet suite is defined by the constantSTORAGE_SUITE_LIMIT, which can be different for each platform. This constant isdefined here:

midp/src/configuration/configuration_xml/platform/constants.xml

The default value is 200,000 bytes.

The amount of additional room available for a record store to grow is returned byRecordStore.getSizeAvailable(). This value is limited as follows:

min(INT_MAX, realAvailableSize)

This is important when removable media is used for storing the RMS files.

20 Architecture and Design Guide • December 2008

Page 47: Architecture and Design Guide by Oracle

Networking Resource LimitationsThe networking subsystem has a maximum number of HTTP connections that canbe open at any one time.

Graphics Resource LimitationsThe low-level graphics and images subsystem has the following limitations:

■ Maximum image height and width of a graphic or image, in pixels

■ Maximum size of an image, in pixels

Other ResourcesThe limits for many resource types are set in XML files inmidp/src/configuration/configuration_xml. Inside a directorycorresponding to your target platform, you’ll find XML files that contain limits fornetworking, memory, images, and other resources.

To change resource limits, edit the appropriate file and change the value. Then buildthe Java Wireless Client software again. For full details on how these values areincorporated into the build, see Chapter 4.

Chapter 3 Hardware and Software Requirements and Constraints 21

Page 48: Architecture and Design Guide by Oracle

22 Architecture and Design Guide • December 2008

Page 49: Architecture and Design Guide by Oracle

401

Managing Properties and Constants

You manage properties and constants in Java Wireless Client software with a toolcalled the Configurator. This chapter covers the tool’s design, how to use it tomanage properties and constant values, and how to use its output.

Note – You do not port the Configurator.

IntroductionThe Configurator is a development tool that runs on the desktop, not on the device.The Configurator maintains properties and constants. It assures that they are definedthe same in both the Java layer and the native platform layer.

Any Java Wireless Client software service or subsystem that calls theSystem.getProperty or Configuration.getProperty methods depends onthe Configurator. Any subsystem that uses at least one constant value in both theJava platform and native layers also depends on the Configurator.

The Configurator is is also used to manage localized strings. Each locale has an XMLfile that contains localized strings. These XML files are processed by theConfigurator at build time, generating C and Java programming language files andproviding localized strings at runtime.

The build system automatically runs the Configurator.

Chapter 4 Managing Properties and Constants 23

Page 50: Architecture and Design Guide by Oracle

DesignTwo of Java Wireless Client software’s goals are seemingly in conflict: It must behighly configurable and must have a minimal runtime footprint. The Configuratortool reconciles these goals by providing the ability to set the property and constantvalues for a particular platform, and then generate only those values.

The Configurator provides the following advantages:

■ Flexibility – The Configurator is able to process input files on a subsystem-by-subsystem (or service-by-service) basis.

■ Maintainability – The Configurator uses a number of files that fully describe JavaWireless Client software’s properties, constants, and localized string resources.The input files of the Configurator are divided by content type, platformdependence, and functional principles. The input files are maintained in knownlocations, so the values defined there are not scattered throughout the code baseor build system.

■ Improved Performance and Minimal Size – The Configurator enables the CLDCHotSpot Implementation ROMizer to compact and quicken the Java platform bytecodes for Java Wireless Client software. The ROMizer runs static initializers atruntime, then compacts the final ROM image. However, the ROMizer cannotcompact or quicken any class with a static initializer that calls native methods,nor can it compact or quicken any of that class’s subclasses. The Configuratormakes these calls unnecessary by ensuring that the Java platform and nativevalues for properties and constants are the same.

The Configurator is critical to the optimization of Java Wireless Client software. Itworks with the CLDC HotSpot Implementation ROMizer, which compacts andquickens the Java platform byte codes for Java Wireless Client software. TheROMizer enables classes for the Java platform classes (Java classes) to be linkeddirectly in the virtual machine. For information on the ROMizer utility, see the CLDCHotSpot Implementation Porting Guide.

As shown in FIGURE 4-1, the Configurator reads data from input files, processes thatdata, then writes files to be used at later stages of compilation or release. It generatesJava classes and associated native methods to support retrieving property andconstant values.

Note – If the system is built with the STATIC_PROPERTIES=true option, if youadd a property or constant, or update an existing value, you must rebuild the systembefore accessing new data in the Java Wireless Client source files. Otherwise, theproperties are in text files that can be edited without having to rebuild SJWC.

24 Architecture and Design Guide • December 2008

Page 51: Architecture and Design Guide by Oracle

FIGURE 4-1 Configurator Work Flow for Constants and Properties

Note – If the Java Wireless Client is built using the optionUSE_JAVACALL_PROPERTIES=true, the property output filejwc_properties.ini is generated instead of internal.config andsystem.config, as shown in FIGURE 4-1.

Input FilesThe Configurator finds input files in one of two ways.

First, you can add input file names to the INT_XML_FILES build variable.

The second method is to list the input file names inmidp/src/configuration/configuration_xml/platform/files.lst, which isread at build time.

You can examine an existing copy of files.lst to understand how constants aredefined. For example,midp/src/configuration/configuration_xml/javacall/files.lstreferences constants.xml, properties.xml, and rawimage.xml.

properties_static_data.c

internal.config

system.config

Configuratormerges theinput into a

single XML file,then generates

output files

Property output files:

Constant output files:

Various .java files as described in theinput files. For example,Constants.java andLocalizedStringsBase.java

For localized strings, .h and .c files aregenerated for each locale

Input for AUI skinproperties

(if AUI is used)

Input for localizedstrings

Input for constants

Input for properties

Chapter 4 Managing Properties and Constants 25

Page 52: Architecture and Design Guide by Oracle

As shown in FIGURE 4-1, input can be provided for properties, constants, AUItechnology skin properties (if AUI technology is used), and localized strings. Thevarious types of input can be combined into a single file or multiple files, and can bemixed and matched as you wish. Input files can also be based on platform type orany other criteria you wish to create.

For example, REPEAT_TIMEOUT and REPEAT_PERIOD are applicable only to thelinux_fb version of Java Wireless Client software because repeated key events onother platforms are supported by the underlying native system.

These input files must be organized in subdirectories of the directoryconfiguration_xml. For example:

midp/src/

configuration/

configuration_xml/

armsd/

linux_fb/

linux_qte/

stubs/

win32

share

chameleon/

l10n/

The share/ directory contains Configurator input common to all of the platforms.The share/ directory and any of the other platform directories can containalternative versions of the constants in constants_open and constants_fixed.They are selected based on the build resource policy defined by the USE_FIXEDbuild option.

In addition, the TARGET_DEVICE build option can be used to select alternateversions of input files within a specific platform. For example, the linux_qtedirectory contains constants, constants_omap730, and constants_x86.Setting the TARGET_DEVICE build option to omap730 or x86 during the build willcause the corresponding file to be used.

It is also possible to define platform-dependent properties inside the JavaCallcomponent. For an example, see the build optionCONFIGURATION_PROPERTIES_FILE=properties.xml injavacall-com/configuration/sjwc/win32_emul/environment.gmk. (Theproperties.xml file is also located in this directory.)

26 Architecture and Design Guide • December 2008

Page 53: Architecture and Design Guide by Oracle

Note – Input items must be unique in the merged XML file. If you provide differentitem values based on build flags, you must define these items in alternative inputXML files.

The Configurator tool expects its input files to be in XML format. The followingcharacteristics of Java Wireless Client software and its data make XML a goodsolution:

■ The structure of the data is simple, so the DTD can be in the file with the dataitself, or in a separate file that the subsystems can share.

■ The structures are flat, so a simple SAX parser with rudimentary error checkingcan be used instead of a full XML schema or DOM parser.

■ XML is flexible enough that any style and format differences can be unified withXSL transformations, yet each subsystem can extend the DTD according to itsneeds.

■ Because Java Wireless Client software requires JDK™ software version 1.4.1_01 orlater, which includes a SAX parser, you do not need to install extra software onbuild machines.

For constants, the Configurator uses the input to generate the Java programminglanguage and native source code to access the constants. It generates one class foreach unique package-class pair in the input XML file. It also generatescorresponding native header files that define the constants in #define statements.These are the files named Constants.java and midp_constants_data.h inFIGURE 4-1.

For properties, the Configurator uses the input to generate one of the followingtypes of files:

■ Source code – The file properties_static_data.c is shown in FIGURE 4-1.

■ Property files – These are the files named system.config (for properties with ascope of system) and internal.config (for properties with a scope ofinternal) in FIGURE 4-1, or a single file, jwc_properties.ini.

With the property files, the Configurator also provides a default implementation ofthe Configuration class and correspondingly, the native files that read theproperties from the .config files.

Using the Configurator to generate the property files is a fall-back mechanism formaximum flexibility during porting. Due to the speed and size impact of processingproperty files at runtime, however, do not make this part of a deployed solution.

Chapter 4 Managing Properties and Constants 27

Page 54: Architecture and Design Guide by Oracle

PropertiesThe Configurator requires the following information for properties:

■ Property name

■ Value

■ A setting that specifies whether the property is internal (only available to the JavaWireless Client software implementation) or system (also available to MIDlets)

■ A system callout to retrieve a default value

■ A comment (optional)

The Configurator uses a DTD shown to describe the input data for propertiesbecause the required information is diverse.

Modifying PropertiesTo change the value of an existing property, update the property’s XML element (theelement’s value attribute) in your properties input file.

▼ Adding PropertiesThe following steps describe how to add a new property.

1. Determine the attributes of the property.

The attributes are the property’s name, value, and scope. Optionally, you mightalso have as attributes a callout function name and a comment. If you define acallout function, you must also write a corresponding native function that has aname identical to the callout function name and a return type of char*.

For more information on the attributes, see the DTD.

2. Add a new element your properties input file.

For example:

CODE EXAMPLE 4-1 Adding a New Element to a Property File

<property Key="com.company.getDynamicValue"

Value=""

Scope="internal"

Callout="getDynamicValue"/>

28 Architecture and Design Guide • December 2008

Page 55: Architecture and Design Guide by Oracle

ConstantsThe Configurator requires the following information for constants:

■ The name of the package and class that contain the constant

■ The scope of the class that contains the constant

■ The comment associated with the class (optional)

■ The name of the constant

■ The data type

■ The value

■ The scope of the constant itself, as opposed to the class that holds it

■ The comment associated with the constant itself, as opposed to the commentassociated with the class that holds it (optional)

In addition, you can specify JavaOnly or NativeOnly attributes to restrict thegeneration of a constant.

The Configurator tool uses a DTD to describe the input data for global variables.

Modifying ConstantsMost constants define platform-specific values, such as the screen size of the device,the number of supported colors, and so on. Internal constants are also used. Theyare clearly marked with internal in the comment attribute. You must update theplatform-specific values to match your device, but can safely ignore the values ofinternal constants.

Follow this step to change the value of an existing constant:

● Update the constant’s XML element (the element’s Value attribute) in yourconstants input file.

▼ Adding ConstantsUse the Configurator to maintain consistency between the Java platform and nativelayers. If you need a new constant in only the native layer or Java layer (but notboth), do not to add it to the Configurator. Define the constant in your code. If youuse the Configurator for every constant, even those used in only one layer, youneedlessly increase Java Wireless Client software’s footprint.

Chapter 4 Managing Properties and Constants 29

Page 56: Architecture and Design Guide by Oracle

The following steps describe how to add a new constant.

1. Determine the attributes of the class from which the constant is accessed in theJava platform.

The attributes are the class’s package, name, and scope. Optionally, the class canalso have a comment associated with it. All Java Wireless Client softwareconstants are accessed in the Java layer from the com.sun.midp.configuratorpackage’s Constants class.

For more information on the attribute values, see the DTD.

2. Determine the attributes of the constant.

The attributes are the constant’s name, value, and scope. Optionally, the constantcan also have a type (the default is int) and a comment.

For more information on the attributes, see the DTD.

3. Add a constant_class element to your constants input file if an element withthe same package and class is not already in the file.

For example:

4. Add a new constant element to the appropriate constant_class element ofyour constants input file.

For example:

CODE EXAMPLE 4-2 constant_class Element in Constants Input File

<constant_class

Package="com.company.midp.Configurator"

Name="Constants"

Scope="public">

</constant_class>

CODE EXAMPLE 4-3 constant Element in constant_class Element of Input File

<constant_class Package="com.company.midp.Configurator"

Name="Constants"

Scope="public">

<constant Name="MyPlatformNewConstant"

Value="123"

Vscope="public"

Comment="This is a comment to keep track of my

MyPlatformNewConstant constant"/>

</constant_class>

30 Architecture and Design Guide • December 2008

Page 57: Architecture and Design Guide by Oracle

Changing the Output Format of ConstantsIf you must change the way constants are specified, modify the eXtensible StylesheetLanguage (XSL) files contantsJava.xsl and constantsNative.xsl located inthe midp/src/tool/configurator/xsl directory. The Configurator uses the XSLfiles to create the code for constants. Do not edit the XSL files if you want to use thedefault settings to generate the source code.

Chapter 4 Managing Properties and Constants 31

Page 58: Architecture and Design Guide by Oracle

32 Architecture and Design Guide • December 2008

Page 59: Architecture and Design Guide by Oracle

5

Using the Logging, Tracing, andAssertion Services

The Logging, Tracing, and Assertion services are three independent services thatmake use of one subsystem to assist in the debugging process. These servicesprovide a way to collect information about Java Wireless Client software.

The following is a brief description of each service:

■ logging Service - Collects generic information, from assertion validations tosystem metrics. Writes output to a file.

■ Tracing Service - Collects information about unexpected errors for which theprogrammer wants the error record to explicitly include the associatedThrowable or the location (if available) of stack trace information. Writes outputto a console.

■ Assertion Service - Used to double-check statements and conditions that must betrue. Depends upon the Logging Service.

Unlike desktop systems, small devices usually do not support calls like printf orSystem.err.println. The Logging, Tracing, and Assertion services provide a wayto capture information about how the software is performing during the porting anddebugging process.

Java Wireless Client software contains two implementations, one that logs to thePCSL print subsystem and another that disables logging and tracing. For example, aworking PCSL print subsystem provides you with the means to get output from thedevice by funneling all print activity through the device’s serial line, to a memorybuffer, or a to file on the device.

Note – Be sure to turn logging, tracing, and assertion functionality off in theproduction versions of your platform.

Chapter 5 Using the Logging, Tracing, and Assertion Services 33

Page 60: Architecture and Design Guide by Oracle

The Logging, Tracing, and Assertion services can report runtime information fromwithin both the native layer and the Java platform layer. It enables you todifferentiate between various types of information and their levels of importance. Itprovides compilation options so that you can control the type and importance ofinformation to log, including the production of binaries with no instrumentationcalls.

The API component provides both Java platform and native APIs. The APIs aresimilar because the Java platform API maps to the native API. The native API is thepublic interface to the implementation component.

The API component does not need to be ported because it does not change acrossplatforms. You can extend the Logging, Tracing, and Assertion services by addingadditional channels (see “Adding Logging Channels” on page 37). Channels areidentifiers for trace statements in the source code. A channel might identifyinformation coming from a particular subsystem.

Building to Enable the Logging, Tracing,and Assertion ServicesThe Logging Service has three implementations:

■ JavaCall

■ Static

■ Dynamic

To enable the Logging Service, you must set the appropriate variable at build time.For example, if you build Java Wireless Client software for a JavaCall platform (thedefault system build configuration), the JavaCall version of the Logging Service isincluded.

To enable the JavaCall version of the Logging Service, you must setUSE_JAVAUTIL_LOG_IMPLEMENTATION=true.

On a non-JavaCall platform (or if you build a JavaCall platform and setUSE_JAVAUTIL_LOG_IMPLEMENTATION=false), you have two options for settingup the Logging Service, a static implementation and a dynamic one. Static ordynamic logging is set using the USE_CONTROL_ARGS_FROM_JAD variable duringbuild time.

If USE_CONTROL_ARGS_FROM_JAD=false, a static logging implementation is built.A static logging implementation does not provide as much flexibility as a dynamicimplementation.

34 Architecture and Design Guide • December 2008

Page 61: Architecture and Design Guide by Oracle

If USE_CONTROL_ARGS_FROM_JAD=true, you provide the ability to specify logging,tracing, and assertion settings for certain MIDlet’s during installation of that MIDlet.(This is true regardless of the MIDlet’s global settings.) You also provide the abilityto change the MIDlet’s log settings during runtime.

Note – The increase of flexibility provided by dynamic logging also increases thefootprint of the Java Wireless Client software. For more information see, “Using theLogging, Tracing, and Assertion APIs” on page 36.

Dynamic Logging and a MIDlet’s JAD FileIf USE_CONTROL_ARGS_FROM_JAD=true is set during the Java Wireless Client buildprocess, then the dynamic logging capability allows you to use the Logging, Tracing,and Assertion services during a MIDlet’s installation, or during execution of theMIDlet during runtime. However, some modifications of a MIDlet’s JAD fileproperties are needed to make use of this capability.

To enable dynamic logging for a specific MIDlet, and control the MIDlet’s settingsduring runtime, you must modify the MIDP_CONTROL_ARG property in the MIDlet’sJAD file, using the syntax shown in CODE EXAMPLE 5-1.

CODE EXAMPLE 5-1 MID_CONTROL_ARG Syntax

As defined in the above JAD file syntax, the setReportLevel() method allowsyou to change the current report level during runtime. The enableTrace() andenableAsserts() methods make it possible to enable or disable these servicesduring runtime as well.

JAD_CONTROL_PARAM = “MIDP_CONTROL_ARGS” EQUAL *( “;” param)param = report_level / log_channel_param / permissions_param /trace_param / assert_paramreport_level_param = “report_level” EQUAL 1*DIGITlog_channels_param = “log channels” EQUAL 1*DIGIT *( “,” 1*DIGIT)permissions_param = “allow_all_permissions”trace_param = “enable_trace” EQUAL bool_valassert_param = “enable_assert” EQUAL bool_valbool_val = 0/1

Chapter 5 Using the Logging, Tracing, and Assertion Services 35

Page 62: Architecture and Design Guide by Oracle

Using the Logging, Tracing, andAssertion APIsThe Logging and Tracing services, while similar, differ in the types of informationthey are designed to store. The Logging Service collects generic information, rangingfrom assertion validations to system metrics. The Tracing service collectsinformation about unexpected errors for which the programmer wants the errorrecord to explicitly include the associated Throwable or the location or (if available)of stack trace information.

Whether you collect logging or tracing information, the Logging and Tracingservices affect the footprint and performance of your Java Wireless Client softwareport. The size of the effect depends on the number of calls to the service. Always usethese services in a way that enables you to compile it out of the system when yourport is stable. When compiled out, it no longer contributes footprint or performanceoverhead.

LoggingYou can control the logging level at compile time using the REPORT_LEVEL constant.In the Java platform, REPORT_LEVEL is a static final int field with a defaultvalue of ERROR. In native code, REPORT_LEVEL is defined using a preprocessorinteger variable.

To use the Java platform logging service in a way that it can be compiled out, use anif statement to test the log message’s severity against REPORT_LEVEL. This isshown in CODE EXAMPLE 5-2.CODE EXAMPLE 5-2 Testing a Log Message’s Severity Against REPORT_LEVEL

If the value of REPORT_LEVEL is set to a level higher than the log message’s severity(for example, if REPORT_LEVEL is CRITICAL and the message’s severity isWARNING) the compiler removes the code construct and no associated bytecodes areincluded in the resulting binary.

... // normal codepath statementsif (assertion_failed) {

if (Logging.REPORT_LEVEL <= Logging.ERROR) {Logging.report(Logging.ERROR, ..., logMessage);

}}

36 Architecture and Design Guide • December 2008

Page 63: Architecture and Design Guide by Oracle

To use the logging service in native code in a way that it can be compiled out, usethe #if directive to test the log message’s severity against REPORT_LEVEL. This isshown in CODE EXAMPLE 5-3.CODE EXAMPLE 5-3 Using the if Statement Tests a Message’s Severity

The existing Java Wireless Client software code uses the Logging Service in thismanner in both the Java platform layer and native layer.

Adding Logging ChannelsIf you add a new subsystem (for example, an OEM extension), you might want toadd a channel definition to differentiate its logging. Do not remove any existingchannels.

To add a channel identifier, add an entry to the configuration file for constants. SeeChapter 4 for more information. Once defined, you can use the new channelidentifier when you call the logging API from the Java platform layer and nativecode.

CODE EXAMPLE 5-4 adds a channel definition for a Bluetooth module to the constantsconfiguration file. The constant_class element is already in the file and it isincluded in the example to show you where to place your new channel definition.CODE EXAMPLE 5-4 Adding a Channel Definition for a Bluetooth Module

#if REPORT_LEVEL <= severityreportToLog(severity, ..., meaningfulMessage);

#endif

...<constant_class Package="com.sun.midp.services"Name="LogChannels" ...>...<constant Type="int"Name="LC_BLUETOOTH"Value="12000"VScope="public"Comment="My new Bluetooth module channel"/>

</constant_class>...

Chapter 5 Using the Logging, Tracing, and Assertion Services 37

Page 64: Architecture and Design Guide by Oracle

TracingYou can control whether the Tracing Service is enabled using the TRACE_ENABLEDconstant (static final boolean).

To use the trace() method in Java programming language code so that it can becompiled out, use an if statement to test whether TRACE_ENABLED is true. This isshown in CODE EXAMPLE 5-5.

If TRACE_ENABLED is false, the compiler removes the code construct and noassociated bytecodes are included in the resulting binary. The existing Java WirelessClient software code uses TRACE_ENABLED in this way.

Java Wireless Client software does not have a public native trace API because theCLDC HotSpot Implementation virtual machine does not provide the native meansto get stack trace information. Because of this, the trace method is only available atthe Java platform level.

AssertionsYou can control whether the Assertion Service is enabled using theASSERT_ENABLED constant (static final boolean).

The assertTrue() method reports a message to the Logging Service in the eventthe specified condition is false. The message string should include enoughdescription that someone reading the message has enough context to find the failedassertion.

To use the assertTrue() method in Java programming language code so that itcan be compiled out, use an if statement to test whether ASSERT_ENABLED is true.This is shown in CODE EXAMPLE 5-6.

CODE EXAMPLE 5-5 Using an if Statement to Test if TRACE_ENABLED is true

try {

... // normal codepath statements

} catch (OutOfMemoryError oom) {

if (Logging.TRACE_ENABLED) {

Logging.trace(oom, traceMessage);}

}

38 Architecture and Design Guide • December 2008

Page 65: Architecture and Design Guide by Oracle

CODE EXAMPLE 5-6 if Statement for ASSERT_ENABLED

If ASSERT_ENABLED is false, the compiler removes the code construct and noassociated bytecodes are included in the resulting binary.

Note – Java Wireless Client software does not have a public native assert API.

if (Logging.ASSERT.ENABLED){Logging.assertTrue(condition, meaningfulMessage);}

Chapter 5 Using the Logging, Tracing, and Assertion Services 39

Page 66: Architecture and Design Guide by Oracle

40 Architecture and Design Guide • December 2008

Page 67: Architecture and Design Guide by Oracle

6

Porting the Record ManagementSystem

This chapter discusses the design of and strategies for porting the recordmanagement service (RMS) subsystem. The RMS subsystem provides the recordstorage functionality required by the MIDP 2.0 Specification.

The MIDP 2.0 Specification enables MIDlets to create and destroy record stores, eachcontaining zero or more records. The space available to a MIDlet suite is devicespecific. By default, a MIDlet is given full access to any record stores created byMIDlets in its own MIDlet suite. A MIDlet can allow MIDlets from outside its suiteaccess to record stores it creates, providing them full or read-only access.

The RMS subsystem provides the functionality required to give MIDlets record-oriented persistent storage. It enforces an access permission policy, and optionallymight enforce record store size constraints. The RMS subsystem also providesMIDlets the ability to filter records, and to access to records in sorted order.

The following activities are outside the scope of the RMS subsystem:

■ Storage of MIDlet suites (JAR files, JAD files, and associated metadata). SeeChapter 14 for information on this task.

■ Storage of any metadata required by the MIDP runtime environment.

■ Support for a low-level file system, directories, and other OS functionality.

The record management service subsystem is closely tied in with the followingsubsystems and services:

■ AMS, particularly the Scheduler

■ Runtime security

■ Storage service (unless a device-specific database is used)

Chapter 6 Porting the Record Management System 41

Page 68: Architecture and Design Guide by Oracle

DesignThe record management service subsystem has the following design requirements:

■ Portability – The design has multiple porting layers to support more types ofdevices. For example, if a target device has a native database, it can plug into onelayer, while a target device with a file system uses the storage service. Ports cantake advantage of any storage a device provides.

■ Performance – This code must perform well for record stores of any size.

■ Enforcement of system limits – Some devices have limited storage space, havelimited file name support, or both. Java Wireless Client software must handlethese limitations.

Design OverviewFIGURE 6-1 shows a high-level overview of the RMS subsystem, which implements arecord-based storage on top of a file system.

FIGURE 6-1 RMS Subsystem Components

The shaded boxes indicate two potential porting levels for the RMS subsystem:

■ A platform with built-in record-management or database functionality can portRMS at the Java platform database implementation, ignoring the shaded boxes.

■ A platform that has a file system, but not a built-in record-management system ordatabase, uses the file system. See Chapter 8 for information on porting theservice.

Given that few devices have native record-management or database functionality,most platforms use the storage service. See “Porting” on page 45 for moreinformation.

Java platform database implementation

Java platform file system access

Storage service

External APIs(incorporating a sandbox for managing record access)

42 Architecture and Design Guide • December 2008

Page 69: Architecture and Design Guide by Oracle

The following sections describe the function and design of the components inFIGURE 6-1.

External API and the SandboxThe External RMS API and Sandbox component make the RMS APIs available toMIDlets, while ensuring that they follow the security policies defined in the MIDP2.0 Specification. The policies specify that a MIDlet is never able to access data notcreated by a MIDlet, nor external record stores that do not allow such access.

To enforce MIDP 2.0 security requirements, implementations must know thecurrently active MIDlet suite. The sandbox obtains this information from the AMS.

Detailed DesignThe External RMS API component is a thin layer that passes calls through toimplementation classes under it. Both the External RMS API and the sandbox areimplemented in the javax.microedition.rms.RecordStore class.

The sandbox obtains the unique system ID of the currently running MIDlet suitefrom the scheduler. The scheduler is part of the Application Management Service(AMS) subsystem. See Chapter 14 for information. When a MIDlet opens the recordstore of another suite, the sandbox checks whether the record store allows access. Seethe MIDP 2.0 Specification for the permission semantics.

Design Rationale, Notes, and ConsiderationsPlacing the sandbox in the RMS API component removes any dependencies of thedatabase implementation on the AMS. The absence of a dependency simplifiesreplacing the Java platform database component.

Database ImplementationThe database (the record store) component manages the storage of record stores andrecords. It has the following requirements:

■ Database management capabilities:

■ Create, delete, and open a database by unique suite and name identifier

■ List databases by suite (Used by AMS and RMS)

■ Delete databases by suite (Used by AMS)

Chapter 6 Porting the Record Management System 43

Page 70: Architecture and Design Guide by Oracle

■ Size of database by suite and in aggregate (Used by AMS)

■ Database functionality:

■ Record store meta-information: size, version, last modified, next recordidentifier, number of records, and owner

■ Record manipulation: add, delete, set, get, and size

Java Wireless Client software implements the database component on top of a filesystem by mapping a record store to two related files, an index file, and a datastorage file. The helper classes and native code manage the data file’s memory usage(amount of free space) and use the index file for record access (lookup, create, anddelete).

Detailed DesignA record store is mapped to two files: a database (.db) data file and an index (.idx)file.

The database file is an array of metadata, variable-length records, and free spacefrom deleted records. The database implementation component manages free space.It uses the best-fitting, existing free space for new records, and compacts the filewhen there is enough free space for a new record but the space is not contiguous.

The index file contains the offsets of records in the data file. It indexes the record byrecord identifier. The index is in a B-tree for fast access.

Design Rationale, Notes, and ConsiderationsJava Wireless Client software uses a different design from the MIDP 2.0 RI, toimprove runtime performance and portability. The differences are in the followingtasks:

■ Looking up offsets of records and free blocks – Java Wireless Client softwareuses a B-tree, which has a worst-case search time of O(log(n)). This allows quicklookup times for locations of records and best-fit free blocks.

The MIDP 2.0 RI stored record offsets and free block offsets in a linked list, has aworst-case search time of O(n).

■ Compacting the database file – Java Wireless Client software compacts thedatabase file when there is enough free space for a new record, but that space isnot contiguous. Compacting as space is needed keeps file space utilization high,and does not slow calls to close the record store.

The MIDP 2.0 RI compacted the database file when the record store is closed. Thismeans that often, closing the record store is slow.

44 Architecture and Design Guide • December 2008

Page 71: Architecture and Design Guide by Oracle

■ Space-available checking – By default, Java Wireless Client software does notperform this check.

The MIDP 2.0 RI performs a check for free space at the start of most calls thatmodifies or inserts records, or created record stores. The free-space check is timeconsuming.

When porting the RMS subsystem, if the target device has a native database, therecord store can be replaced with a layer mapping to the native databasefunctionality. Mapping the native database at this layer allows the reuse of thepublic API layer and the sandbox. See “Porting” on page 45 for more information.

File System AccessThe Java platform file system access component provides the file system capabilitiesrequired by the RMS database component. Most of the methods in the Java platformfile system access component are native.

The component defines file operations such as open, close, delete, truncate,read, and write. It also names record stores, confining the namespace of a recordstore to the scope of the creating application’s MIDlet suite.

This component exists for backward compatibility with older ports, as it is the codeboundry between the native and Java layers in the MIDP 1.0 release. You canimplement the database implementation component directly instead.

PortingWhich porting interface to use depends on the storage functionality available on thetarget. Keep the following guidelines in mind:

■ If the target has a POSIX-like API for the persistent storage subsystem (filesystem), start by porting the storage service. (See Chapter 8 for information.)

■ If the target has a native database, start by porting the database implementationcomponent.

■ If the target has neither a native database implementation nor a POSIX-like API,consider porting the storage service. Implementing that functionality has thefollowing advantages:

■ It is easier than implementing a native database.

■ It facilitates porting the AMS subsystem, which also uses the storagesubsystem.

Chapter 6 Porting the Record Management System 45

Page 72: Architecture and Design Guide by Oracle

Follow these steps to port the database implementation component:

1. Compare the database implementation methods to your device’s database API.

The implementation is in the directorymidp/src/rms/rms_base/classes/com/sun/midp/rms. Your API probablyhas more functionality than the RMS requires.

2. Determine whether you want to map each record store to separate nativedatabases or use one native database for all the record stores.

You can choose the latter only if you can provide a unique root for each recordstore. Otherwise, neither choice has an advantage.

3. Port two functions frommidp/src/rms/record_store/file_based/native/rms.c if you use anative RMS.

The two C functions are rmsdb_remove_record_stores_for_suite andrmsdb_suite_has_rms_data.

4. Remove the layers below the database implementation (except rms.c if youported the functions in Step 3).

When you port the database implementation component, your RMS does notneed the layers below it. The layers of the RMS are shown in FIGURE 6-1.

46 Architecture and Design Guide • December 2008

Page 73: Architecture and Design Guide by Oracle

7

File Organization and Naming

This chapter describes how the Java Wireless Client software source code isorganized and describes the naming conventions used for native files.

Source Code OrganizationThe following list shows the organization of the rest of the Java Wireless Clientsoftware source hierarchy. The files are located under the installDir/midp directory.

src/ – Top-level source directory

subsystemX/ – Top-level subsystem directory

subsystem.gmk – The subsystem makefile that combines the librarymakefiles for this subystem and defines settings common to the subsystem

libraryY/– Top-level library directory

libraryY/lib.gmk – Library makefile. Contains rules and settings specific tothis library.

libraryY/include – The libraryY exported native interface

libraryY/classes/ – Exported Java programming language interface

implementationZ/ – Implementation of this library

implementationZ/lib.gmk – Implementation makefile. Contains rules andsettings specific to this implementation.

implementationZ/libinfo.gmk – Implementation descriptor. Specifiesdependencies on other libraries.

implementationZ/include – Additional native exported interfaces specificto this implementation

Chapter 7 File Organization and Naming 47

Page 74: Architecture and Design Guide by Oracle

implementationZ/classes – Java programming language class files for thisimplementation

implementationZ/native – Native files for this implementation

SubsystemX represents a Java Wireless Client software subsystem or service such asthe record management system or the high-level user interface. LibraryY representsone of the libraries that constitute subsystemX. ImplementationZ is one of thealternative implementations of libraryY. TABLE 7-1 shows the Java Wireless Clientsoftware subsystems and their libraries. For libraries with more than oneimplementation, the alternative implementations are listed.

TABLE 7-1 Java Wireless Client Software Subsystems and Libraries

Subsystem Libraries Description

ams/ ams_api Public API defined by the MIDPspecification for the following:• javax.microedition.midlet.

MIDlet

• javax.microedition.midlet.MIDletState

• ChangeException

ams_base AMS functionality:• Initializes MIDP• Runs a MIDlet• Registers, unregisters and gets the

AMS isolate ID• Gets the current foreground isolate

ID and display

ams_jsr_interface Stub interfaces that handlefunctionality provided by optionalpackages

ams_util Miscellaneous AMS utilities:• Start and terminate a MIDlet• Verify a MIDlet suite• Change an isolate’s priority

app_image_gen Functionality required to generate abinary image from the MIDlet suiteclasses

app_image_gen_base Functionality to create an applicationimage file

48 Architecture and Design Guide • December 2008

Page 75: Architecture and Design Guide by Oracle

appmanager_ui Application manager UI-relatedfunctions:• Displays a splash screen• Displays a screen to enable MIDlet

selection• Changes a MIDlet suite’s settings• Shows a MIDlet suite’s information

appmanager_ui_resources Export resources (splash screenpicture) required by the applicationmanager UI

autotester Testing functionality provided byAutoTesterInterface

autotester_base Functionality required by theautotester library that is commonfor all implementations

cdc_application

example

installer The classes and functions that install aMIDlet suite

jams The Java programming languageimplementation of the AMS (JavaAMS)

jump_application

midlet_suite_info Simple attribute storage for MIDletsuites

mvm An MVM-specific API that starts aMIDlet suite in a new isolate

nams The API for a native AMS (NAMS)

nams_javacall

ota Discovery application and graphicalinstaller MIDlets

platform_request Native platformRequest() functionused to start a new process to handle agiven URI

suitestore Functions that deal with MIDlet suitestorage

verifier

TABLE 7-1 Java Wireless Client Software Subsystems and Libraries (Continued)

Subsystem Libraries Description

Chapter 7 File Organization and Naming 49

Page 76: Architecture and Design Guide by Oracle

automation/ The internal automation APIimplementation

configuration/ configuration_xml Configuration XML data

properties Functions that provide access to MIDPproperties from the Java platform

properties_port Functions that provide access to MIDPproperties from the native platform

core/ crc32 Functions that provide the CRC32checksum calculation

global_status Global status constants definitions

javautil Basic Java platform utility classes (forexample, DateParser)

kni_util Common helper functions on top ofKNI

libc_ext ANSI C extensions (for example,snprintf)

log Native and Java platform loggingsupport

log_base

memory Native heap memory facility

native_thread Native threading facility

resource_handler Functions that provide access tosystem resources

resource_manager Native platform resource accounting

services

storage Native storage abstraction layer

string String operations

suspend_resume

timer_queue Native timer queue for master mode

timezone Timezone information

vm_services Miscellaneous services provided by theVM (current time, current isolate ID,thread wait and signal)

demos/

TABLE 7-1 Java Wireless Client Software Subsystems and Libraries (Continued)

Subsystem Libraries Description

50 Architecture and Design Guide • December 2008

Page 77: Architecture and Design Guide by Oracle

events/ eventqueue Java platform and native platformevents and event queues

eventqueue_port Platform-specific event queueimplementation

eventsystem Event processing-specific functionary(master mode vs. slave mode), themain VM loop, event checking

input_port

mastermode_port Platform-specific master modeimplementations

slavemode_port Platform-specific slave modeimplementations

highlevelui/ annunciator Annunciators (sound, vibration,network indicators)

armsd_application ARMSD-specific services

directfb_application

fb_application Linux/FB-specific services

fb_port

javacall_application

keymap Mapping between key codes, gameactions, key names

lcdlf UI look and feel

lcdui Java platform high-level UI (displayand displayables)

lfjport Java platform look and feel portinginterface

lfpport Platform look and feel portinginterface

nativepti_port Platform-specific implementation fornative predictive text support

nim_port

pti_api Java platform interface to predictivetext support (javapti andnativepti implementations)

qte_application Linux Qt-specific services

TABLE 7-1 Java Wireless Client Software Subsystems and Libraries (Continued)

Subsystem Libraries Description

Chapter 7 File Organization and Naming 51

Page 78: Architecture and Design Guide by Oracle

win32_application Win32-specific services

wince_application

i18n/ i18n_main Functions that provide characterconversion and access to locale-specificinformation

i18n_port Interface to platform-specific characterconverters

links/ classes

i3test

native

lowlevelui/ graphics PutPixel and platform graphicsimplementations

graphics_api Java platform low-level UI (drawingprimitives, fonts, images)

graphics_util Common services for PutPixel andplatform graphics

platform_graphics_port Porting interface for platform graphics

media/ reference

mmapi/ classes

nuts/ include

reference

porting_demos/

protocol/ cdc_application

file Internal file access

gcf Base networking classes

http HTTP connections

https HTTPS connections

serial Serial port connections

serial_port Serial port connection porting interface

socket Socket connections

socket_notify Network event notification facility

ssl SSL connections

ssocket Server socket connections

TABLE 7-1 Java Wireless Client Software Subsystems and Libraries (Continued)

Subsystem Libraries Description

52 Architecture and Design Guide • December 2008

Page 79: Architecture and Design Guide by Oracle

udp Datagram connections

push/ nativepush_port A native (external) pushimplementation

push_api The Java platform push API andimplementation

push_gcf

push_server A low-level push implementation. Aninterface to subsystems providingresources on which push can beregistered.

push_timer A platform-specific alarm-based pushimplementation

restricted_crypto/

reference

rms/ record_index RMS index (linear, tree)

record_store Native interface to RMS

rms_api Java platform interface to RMS

rms_base Basic RMS utilities

rms_exc Java platform RMS exceptions

security/ crypto Interfaces to crypto functions and theexportable implementation classes

file_digest Classes used to create an unpredictabledigest of a file

internal_api_protection Classes used to protect public internalAPIs from unauthorized use

midp_permissions Policy used for grouping MIDPpermissions

native_dialog_port Switch library used for nativepermission dialogs

permission_dialog Classes used to enable the user to grantor deny a running MIDlet suite a MIDPpermission

pki The PKI certificate API

publickeystore Trusted public key storage

TABLE 7-1 Java Wireless Client Software Subsystems and Libraries (Continued)

Subsystem Libraries Description

Chapter 7 File Organization and Naming 53

Page 80: Architecture and Design Guide by Oracle

See the Build Guide for instructions about how to add a directory for your platform,as well as subsystems and libraries.

When you add a new library to the existing subsystem, put the exported nativeinterface of this library into a subdirectory named include. Then add one or moreimplementations of this interface into the respective subdirectories.

Naming Convention for Native FilesSubsystems and libraries use the following naming conventions.

■ Files whose names end with the _md suffix contain implementations of functionsthat use system-specific mechanisms that are likely to differ from device todevice. The _md suffix stands for “machine dependent.” The functions in thesefiles are not public.

secure_random Functions that provide unpredictablerandom data. Each implementation isdevice specific.

ssl/ reference

test/ common

tool/ chameleon

fontgen

imageutil

jadtool

l10ngen

mekeytool

upgradel10n

TABLE 7-1 Java Wireless Client Software Subsystems and Libraries (Continued)

Subsystem Libraries Description

54 Architecture and Design Guide • December 2008

Page 81: Architecture and Design Guide by Oracle

■ Native files in libraries that belong to the low-level UI and high-level UIsubsystems are named with the library-specific prefixes shown in TABLE 7-2.

TABLE 7-2 Native File Library Prefix Examples

Library Prefix

graphics_api

graphics

graphics_utilplatform_graphics_portannunciatorarmsd_applicationdirectfb_applicationfb_applicationjavacall_applicationkeymaplcdlf (lfjava, lfplatform implementations)lfjportlfpportqte_applicationwince_applicationwin32_application

gxapi_

gx_ (shared include files)gxj_ (putpixel)gxp_ (platform_graphics)gxutl_gxpport_anc_armsdapp_

directfbapp_ (unsupported)fbapp_jcapp_keymap_lcdlf_ (lfj_, lfp_)lfjport_lfpport_qteapp_

winceapp_ (unsupported)win32app_

Chapter 7 File Organization and Naming 55

Page 82: Architecture and Design Guide by Oracle

56 Architecture and Design Guide • December 2008

Page 83: Architecture and Design Guide by Oracle

8

PCSL

This chapter discusses how to use the Portable Common Services Library (PCSL) inthe porting process.

PCSL is the Portable Common Services Library. It is portable in the sense that itdefines a set of interfaces that higher-level implementations use. It is common in thatboth MIDP and CLDC implementations use the interfaces defined by PCSL.

PCSL is a family of different libraries:

■ Networking

■ File system

■ Memory allocation

■ Printing

■ String

These libraries are largely independent of each other and can be ported separately.However, some of the implementations do depend on other parts of PCSL. Forexample, the PCSL file system implementations rely on the PCSL memory allocationinterfaces.

A notable feature of PCSL is that multiple implementations of each porting interfaceare available. Each implementation resides in a module. When building PCSL, youchoose one implementation module for each library. For example, PCSL has twoimplementations of the networking interfaces: one that implements networkingusing BSD sockets, and another that sends network packets over a serial port. TheSoS module is useful during development and porting if a true network is notavailable.

Note – The SoS module is not suitable for use in production products.

On the other hand, the memory allocation library has two implementation modules:a malloc-based implementation and a heap-based implementation. Either moduleis suitable for use in production.

Chapter 8 PCSL 57

Page 84: Architecture and Design Guide by Oracle

Each PCSL library also contains a module consisting only of a set of stubs. This isnot an implementation. Rather, it is a skeleton that you can use to create an entirelynew implementation module. This is useful if none of the implementation modulesprovided in PCSL is a good match to the underlying platform.

When you build PCSL, be sure that the self tests are linked and then run the tests toverify that the build works. Note that the test results must be available though theoutput functionality described in “Set Up and Configure Your Device DevelopmentEnvironment” on page 11.

PCSL Print LibraryThe PCSL Print library is extremely simple and consists of a single function:pcsl_print(). This function takes a NULL-terminated string and prints it to animplementation-specific location. By itself, this function does not provide muchvalue. However, because all debugging and error messages in the system are passedthrough this function, it is possible to redirect all of this output by modifying or re-implementing this one function.

The PCSL Print library has two alternate implementations: one that prints to thestandard output (stdout) and one that prints to a file (file). Both implementationsalways flush their output so that no data is left in any internal buffers.

The stdout implementation sends output to the UNIX system standard outputstream. If your platform is a UNIX operating system or a similar system (forexample, Linux), use the stdout implementation. The process that invokes the JavaWireless Client software (such as a shell) can often conveniently redirect standardoutput without any change to the Java Wireless Client software itself.

The file implementation opens a file and sends its output to it. In thisimplementation, the PCSL Print library uses the file operations defined in the PCSLFile library. The file implementation of PCSL Print is useful if the UNIX systemstyle standard output stream is not available, or if it is difficult to redirect.

58 Architecture and Design Guide • December 2008

Page 85: Architecture and Design Guide by Oracle

PCSL Memory Allocation LibraryThe memory allocation library provides interfaces to allocate, resize, and deallocatedynamic memory. It also has functions to duplicate strings and to get informationabout heap memory allocated and available.

The PCSL memory allocation interface is defined in the pcsl_memory.h header file.

Dynamic memory allocation is one of the most-used functions in any softwaresystem. Therefore, the PCSL memory allocation library is one of the first librariesthat you port. The PCSL memory allocation library provides two differentimplementation modules. The first implementation, the malloc-basedimplementation, simply calls the standard C functions malloc(), calloc(),realloc(), and free(). If the underlying platform supports these functions, thenthe malloc-based library offers the quickest route forward.

The other implementation module, the heap-based implementation, implements itsown memory allocation within a contiguous block of memory. This implementationis suitable for production, and it is sometimes preferable to the malloc-basedimplementation. The heap-based implementation allocates from a single contiguousrange of memory and so is suitable for situations where the Java platform is limitedto a specific amount of memory, or if it is desirable for memory allocated by the Javaplatform to be kept separate from memory allocated by other parts of the system.

In addition, the heap-based implementation provides diagnostic facilities to detectthings like memory leaks and buffer overrun situations. Two modes are provided:debug and non-debug. In debug mode, C preprocessor macros are employed toprovide the file name and line number from which the function was called. Thisinformation is stored inside the heap structures, so that a heap block can beexamined to determine the location in the source code where it was allocated. Thisextra information is not present in non-debug mode.

In most PCSL libraries, the boundary between interface and implementation isestablished by declaring functions in C header files and providing multipleimplementations of those functions in different sets of C source files. The memoryallocation library defines the boundary between interface and implementationdifferently: instead of being based on C functions, it is based on C preprocessormacros. Suppose you use the malloc-based implementation. The main PCSLmemory allocation function is named pcsl_mem_malloc(). If this is a C function,the function simply turns around and calls malloc(). However, this incurs extrafunction call overhead for every memory operation. To avoid this overhead, thePCSL memory allocation library defines C preprocessor macros that compile out thisextra layer. Thus, in the malloc-based implementation module,pcsl_mem_malloc() is a C preprocessor macro that is defined to expand tomalloc().

Chapter 8 PCSL 59

Page 86: Architecture and Design Guide by Oracle

Given that the porting layer for the PCSL memory library is implemented through Cpreprocessor macros, the conventions for implementing the memory allocationinterfaces are unusual. The main header file pcsl_memory.h includes the followingstatements:

#include <pcsl_memory_impl.h>

/* ... */

#define pcsl_mem_malloc(x)

To develop a new implementation of the PCSL memory interfaces, you must providea header file named pcsl_memory_impl.h. In this file, you either definepcsl_mem_malloc_impl() as another preprocessor macro, or you can simplyprovide an ordinary extern C function declaration. Use similar techniques for theother pcsl_mem interfaces.

Porting malloc-Based ImplementationsConsider the following reminders when porting the malloc-based implementation:

■ The function pcsl_mem_malloc() must allocate and return a valid heap blockeven if the size passed is zero. Some system malloc() calls might return NULL inthis case. If this is true, a wrapper function must be added to handle this specialcase.

■ Some memory allocation implementations do not require initialization andfinalization functions. However, PCSL requires them. In this case, it is sufficient todefine the initialization and finalization as macros that evaluate to zero. Theexpressions must evaluate to zero, otherwise an error occurs.

■ If pcsl_mem_free() is passed a NULL pointer, it must handle it without error.The heap-based implementation module handles this internally. The malloc-based implementation includes a macro that checks for NULL before calling theunderlying free() function.

■ If the underlying platform provides malloc() and free() but not all ofcalloc(), realloc(), or strdup(), it is straightforward to implement any ofthe last three in terms of malloc(). The heap-based implementation has codethat implements these functions in terms of pcsl_mem_malloc() and can beused as an example.

■ The three functions pcsl_mem_get_total_heap(),pcsl_mem_get_free_heap(), and pcsl_mem_malloc_dump_memory()merely provide additional information about the state of the memory subsystem.However, because they are only used to provide information, it is adequate todefine these APIs as no-ops, especially if the underlying system APIs do notprovide a one-to-one mapping with these APIs.

60 Architecture and Design Guide • December 2008

Page 87: Architecture and Design Guide by Oracle

Chunky memory consists of memory blocks that can be shrunk or expanded afterthey are allocated. It is used by the Java platform heap to use memory efficientlybased on the current load of the VM. When an existing chunk of memory is adjusted,its starting address must remain unchanged.

The default implementation uses the Linux mmap function to implement thesechunky memory functions. If the underlying platform does not have a similarmechanism, you can simulate chunky memory with regular malloc by pre-allocating the maximum block size and adjusting end pointer or size upon adjustcalls. For an example, see “Porting the Heap-Based Implementation” on page 61.

Porting the Heap-Based ImplementationThe heap-based implementation is generic, requiring only a contiguous block ofmemory from which it allocates. This block of memory is initialized in two ways:

■ If PCSL_MEMORY_USE_STATIC is defined, the memory manager uses the stack forits available memory pool. For example:

static char PcslMemory[DEFAULT_POOL_SIZE];

■ If PCSL_MEMORY_USE_STATIC is not defined, it calls the C function malloc()and free() to allocate and free the memory pool. If malloc() and free() arenot available, you must substitute the appropriate functions. Note that youcannot use pcsl_mem_malloc() or pcsl_mem_free() here because thatcreates a circular dependency.

The chunked memory operations are implemented by three functions:

■ pcsl_mem_allocate_chunk()

■ pcsl_mem_adjust_chunk()

■ pcsl_mem_free_chunk()

These functions have generic implementations based on pcsl_mem_malloc andpcsl_mem_free. They do not require any porting.

Chapter 8 PCSL 61

Page 88: Architecture and Design Guide by Oracle

PCSL File System InterfaceThe PCSL file system interface provides the persistent storage functionality requiredto load classes, images, and to store JAR and JAD files.

The PCSL file system hides directory hierarchies by making the file system look flat.This feature enables Java Wireless Client software to work with file systems that donot support hierarchical directories. Note that the ability to list files is required bythe following interface functions:

■ pcsl_file_openfilelist

■ pcsl_file_getnextentry

■ pcsl_file_closefilelist

All file names are based on the 16-bit Unicode Standard. This feature allowsmaximum performance when the underlying platform supports the Unicode filesystem directly.

The PCSL file system interface is defined in the pcsl_file.h andpcsl_directory.h header files.

PCSL provides two file system implementation modules. The first implementation isbased on POSIX file system APIs and is suitable for use in production. The secondsimulates a file system in RAM and is suitable for use during development andporting. The POSIX module supports a hierarchy of directories, while the RAM-based module supports a flat namespace.

The first porting step is to determine what file system APIs are available on theunderlying platform. If POSIX APIs are available, or if the APIs available are POSIX-like, start with the POSIX implementation module and modify it as necessary for theplatform. If the file system API available is very different from the POSIX APIs, it isprobably necessary to create an implementation from scratch using the stubsmodule.

If the file system APIs are not available, or if some time is required to port to theavailable file system APIs, the porting effort can proceed by using the RAM-basedfile system implementation module. As noted previously, the RAM-based module isnot suitable for production. In particular, because it is RAM-based, its files are notpersistent. However, a file can be read later in the same test run and files can bepreloaded into the RAM-based file system.

62 Architecture and Design Guide • December 2008

Page 89: Architecture and Design Guide by Oracle

A PCSL file system implementation is required to implement the followingfunctions:

■ pcsl_file_init()

■ pcsl_file_finalize()

■ pcsl_file_open()

■ pcsl_file_close()

■ pcsl_file_read()

■ pcsl_file_write()

■ pcsl_file_unlink()

■ pcsl_file_truncate()

■ pcsl_file_seek()

■ pcsl_file_sizeofopenfile()

■ pcsl_file_sizeof()

■ pcsl_file_exist()

■ pcsl_file_commitwrite()

■ pcsl_file_rename()

■ pcsl_file_openfilelist()

■ pcsl_file_closefilelist()

■ pcsl_file_getfreespace()

■ pcsl_file_getusedspace()

■ pcsl_file_getnextentry()

■ pcsl_file_getfileseparator()

■ pcsl_file_getpathseparator()

■ pcsl_file_is_directory()

■ pcsl_file_mkdir()

■ pcsl_file_rmdir()

■ pcsl_file_getfreesize()

■ pcsl_file_gettotalsize()

■ pcsl_file_get_attribute()

■ pcsl_file_set_attribute()

■ pcsl_file_get_time()

See the pcsl_file.h and pcsl_directory.h header files for a completespecification of these functions.

Chapter 8 PCSL 63

Page 90: Architecture and Design Guide by Oracle

PCSL Networking LibraryThe PCSL Networking Library provides portable interfaces for client-side sockets aswell as for a variety of utility functions such as host name lookup. PCSL providessupport for datagrams and server-side sockets.

The APIs support asynchronous operation to avoid blocking the caller during along-running network operation. To this end, most of the networking operations aresplit into two parts: a start function and a finish function. The start function initiatesthe operation, and the finish function collects the results. A notification step mustalso occur between the start function and the finish function.

After an operation is started, the implementation must provide some means ofnotifying PCSL when the operation completes and is ready for the finish function tobe called. In some cases, notification originates within PCSL itself.

The start function and the finish function must each be called from a native methodbecause when the start function initiates an operation, it might return the codePCSL_NET_WOULDBLOCK. This indicates that the calling Java programming languagethread must be blocked, and that a notification context must be set up. When theoperation completes, notification occurs, and the calling Java platform thread (Javathread) is awakened. When a Java thread is awakened after was blocked in a nativemethod, the native method is restarted. This native method then calls the finishfunction. See the “Coding Styles for Long-running Native Methods” section inChapter 6 of the CLDC HotSpot™ Implementation Porting Guide for furtherinformation about this technique.

PCSL provides the following networking operations: open, read, write, close,and gethostbyname. Each function is prefixed with the string pcsl_socket_ forsocket operations and with the string pcsl_net_ for general networking utilities.The suffixes _start and _finish are used to name the start functions and finishfunctions. For example, the finish function for the write operation is namedpcsl_socket_write_finish().

Additionally, several other operations, including operations for getting and settingsocket options are available. These operations update and retrieve statesynchronously, so they have no start functions or finish functions.

64 Architecture and Design Guide • December 2008

Page 91: Architecture and Design Guide by Oracle

Note – Operations are not required to be asynchronous. The start function is notrequired to return PCSL_NET_WOULDBLOCK (which causes an eventual call to thefinish function) if the operation can be completed immediately. For example, ifpcsl_socket_read_start() is called and enough data is already available, thisfunction can return that data directly instead of returning the codePCSL_NET_WOULDBLOCK. In this case, no notification occurs, andpcsl_socket_read_finish() is not called.

A complete specification of the PCSL network APIs is provided in/network/pcsl_network.h.

Handles and ContextsA couple of abstractions are added to the PCSL networking APIs to make them bothportable and asynchronous. The APIs use a “handle” (a void * value) to representan open socket. The pcsl_socket_open_start() function creates and returns ahandle. The pcsl_socket_open_finish() function and the start- and finish-functions that implement the other socket operations (read, write, close, and soon) all take a handle as a parameter. The handle becomes invalid after the closeoperation completes. A handle can be a pointer to a block of allocated memory or itcan be a value like a UNIX system file descriptor (an int). If a handle is a pointer toallocated memory, the pcsl_socket_open_start() function must allocate it andone of the pcsl_socket_close_*() functions must deallocate it when the closeoperation completes.

The asynchronous nature of the APIs requires you to set up information aboutpending operations during the start function and carry across to the finish function.This is handled through the “context” object (another (void *) value). Each startfunction is allowed to create and return a context object. After notification isreceived, the system finds the proper context object and passes it to the finishfunction. The context can be a pointer to a block of allocated memory. In this case,the start function allocates the block and the finish function deallocates it. If animplementation does not need a context (for example, the context might bemaintained implicitly in the handle), the start function returns NULL for the context,and the finish function ignores the context parameter.

Chapter 8 PCSL 65

Page 92: Architecture and Design Guide by Oracle

Alternative Networking ImplementationsPCSL provides five alternative networking implementations. The winsockimplementation provides a binding to Microsoft Windows networking.

The javacall implementation provides a binding from PCSL to the JavaCallporting layer. If you have already implemented the JavaCall network APIs, then thePCSL javacall implementation can be used without modification.

The javacall implementation relies on JavaCall API notifications and JavaCall APIevents mechanism to deliver networking and socket events from the platform to theupper layers of the MIDP implementation. For more information, please see theJavaCall API documentation.

The five networking implementations are illustrated in the following diagram. TheSoS implementation implements sockets over a serial line. The BSD implementationuses the BSD UNIX system socket API. The BSD implementation has two variants: ageneric implementation that uses plain BSD sockets and a QTE-basedimplementation that wraps each socket inside a Qt object.

66 Architecture and Design Guide • December 2008

Page 93: Architecture and Design Guide by Oracle

FIGURE 8-1 Five PCSL Networking Implementations

The following table shows where the technologies listed in FIGURE 8-1 are located inthe Java Wireless Client software release.

TABLE 8-1 PCSL Technologies File System Locations

Implementation Directory Location

JavaCall pcsl_dir/network/javacall

WinSock pcsl_dir/network/winsock

SoS pcsl_dir/network/sos

SoS

BSD socketsand QTE

MIDP

QTE-Based BSDImplementation

pcsl_network.h

MIDP

JavaCallImplementation

pcsl_network.h

MIDP

WinSockImplementation

pcsl_network.h

Linux

MIDP

SoSImplementation

pcsl_network.h

pcsl_network_serial.hJavaCall

JavaCallPlatform

WinSock

Win32Platform

pcsl_network_na.h

BSD Common

BSD sockets QTE

BSD Common

BSD socketsImplementation

MIDP

Generic BSDImplementation

pcsl_network.h

pcsl_network_na.h

BSD Generic

BSD Common

pcsl_network.h

SoS

pcsl_serial_linux

BSD socketsImplementation

MIDP

Generic BSDImplementation

pcsl_network.h

pcsl_network_na.h

BSD Generic

BSD Common

Chapter 8 PCSL 67

Page 94: Architecture and Design Guide by Oracle

BSD ImplementationsThe implementations of the PCSL networking interfaces use the BSD socket APIs, forexample, socket(), bind(), and connect(). The BSD-based implementations aresuitable for production use. The BSD implementation places all sockets into non-blocking mode so that the PCSL start functions do not block the caller.

The BSD implementation has two variants: a generic one that uses socket descriptorsdirectly, and one that uses QTE. The generic implementation relies on external codeto call select() (or equivalent functionality) to determine when the socketoperation is complete. The QTE implementation wraps each socket into a VMSocketobject and sets up a QSocketNotifier object to handle notification of socket statechanges.

If your platform uses BSD sockets and has a callback-based notification scheme, startyour port with the BSD QTE implementation. If your platform uses BSD sockets butuses a select()- or poll()-based notification scheme, start your port with theBSD generic implementation.

PCSL provides an internal interface called the “notification adapter” that enablescode to be shared between the BSD generic and BSD QTE implementations. Thisinterface is defined in the header file/network/socket/bsd/pcsl_network_na.h.

Both BSD implementations create and use BSD socket descriptors, but only the QTEimplementation also creates VMSocket and QSocketNotifier objects. Thenotification adapter allows BSD common code to deal with sockets as abstracthandles. In the BSD generic case, the handle is simply the socket descriptor, whereasin the BSD QTE case, the handle is a pointer to a VMSocket object. You might findthe notification adapter interfaces useful if the platform supports BSD sockets butuses a notification scheme other than QTE.

pcsl_serial_linux.c pcsl_dir/network/serial/

BSD Sockets and QTE pcsl_dir/network/socket/bsd/qte

BSD Generic pcsl_dir/network/socket/bsd/generic

TABLE 8-1 PCSL Technologies File System Locations (Continued)

Implementation Directory Location

68 Architecture and Design Guide • December 2008

Page 95: Architecture and Design Guide by Oracle

Socket-over-Serial ImplementationThe SoS implementation simulates a network connection by sending packets over aserial line. This implementation is suitable for use during development and portingand is not typically put into production.

Instead of opening a socket for each network connection, the SoS implementationmultiplexes one or more network connections over a single serial port. Thisimplementation uses a low-level serial port API internally. PCSL provides animplementation of this low-level serial API for Linux-based systems.

Because the SoS implementation does not rely on any system libraries (except serialI/O), you have more control over the packets that are sent to the server and the waythose packets are handled. This control gives you the option to send debug data(pcsl_print() output) using the SoS implementation as auxiliary packets that theserver can decode and print in a console or debugging window.

To bring up SoS networking on a device with a serial port, first evaluate its serialAPIs. If they are similar to Linux or the UNIX system, you can start with the existingserial port code and bring up the SoS networking on top of that. If the device’s serialAPIs are different from the UNIX system, create an implementation of the low-levelserial API that maps the API calls to platform-specific serial port calls.

The low-level serial API is defined in/network/serial/pcsl_network_serial.h.

A Java programming language program written for the Java SE platform is providedto act as an SoS proxy server. The SoS proxy server opens a socket connection withthe other end and does all the networking operations on behalf of the actual device.Communication between the device and the proxy server is done using a methodsimilar to RPC. The proxy server also allows SoS connections to be demultiplexed tothe actual network connections. During development, it is useful to connect a deviceto a desktop workstation through a serial port, and then to connect the workstationto a local-area network.

NotificationTo initiate a network operation, the start function is called from a native method,and the calling Java thread is blocked. At this point, it is crucial that the platformhave some means of notifying PCSL when a networking operation is complete. Themeans for this notification is highly system specific. The alternative PCSLnetworking implementations handle notification differently.

The BSD generic implementation uses plain BSD socket descriptors, which have nointrinsic notification capability. Instead, this implementation requires external codeto call select() or poll() with this file descriptor. For example, if the CLDCHotSpot Implementation VM is running in normal mode (as opposed to slave

Chapter 8 PCSL 69

Page 96: Architecture and Design Guide by Oracle

mode), code in the JVMSPI_CheckEvents() function checks the socket descriptorto determine when an operation completes and to awaken the Java thread that wasblocked on the operation.

The BSD QTE implementation uses the QSocketNotifier mechanism, whichprovides a callback into PCSL code when a socket operation completes. Thisnecessitates a call from PCSL into the rest of the system. PCSL calls the functionNotifySocketStatusChanged() when a socket’s state changes. This function isnot provided by PCSL, but is provided externally as part of the upper layers of theMIDP implementation. This function is responsible for finding and awakening theJava programming language thread that was blocked on the socket operation.

Although it is not typical, initialization of the networking system on some platformsmay be asynchronous. In this case, PCSL provides a callback function that is passedas a parameter of pcsl_network_init_start() andpcsl_network_finalize_start(). When the network initialization orfinalization is completed, the following is the type of function that will be called:

typedef void (*PCSL_NET_CALLBACK) (int init, int status);

The SoS implementation does not use notification at all. Instead, it relies on the callerto poll or to sleep for a specific period of time until the operation is presumed to becomplete. As such, the SoS implementation is unsuitable for production use.

See Chapter 13 for further information on normal and slave modes.

PCSL String LibraryThe PCSL String Library provides portable interfaces for basic string operations.

The API defines an opaque pcsl_string type and contains functions for thecreation and manipulation of pcsl_string instances.

The first porting step is to determine an internal representation of pcsl_stringthat is optimal for the platform. The reference implementation provides apcsl_string definition based on UTF-16 encoding to match the internalrepresentation of Java programming language string objects. On Microsoft Windowsplatforms, it is reasonable to use the UTF-16 representation because the WindowsAPI functions support it. On platforms that do not support 16-bit characters, but dosupport UTF-8, it might be reasonable to select the UTF-8 internal representation toavoid repeated conversions of the same PCSL string to UTF-8.

It is also possible to have an internal PCSL string representation that caches differentencodings of the same string to achieve maximum performance.

70 Architecture and Design Guide • December 2008

Page 97: Architecture and Design Guide by Oracle

A PCSL string implementation is required to implement the following functions:

■ pcsl_string_is_active()

■ pcsl_string_initialize()

■ pcsl_string_finalize()

■ pcsl_string_length()

■ pcsl_string_utf16_length()

■ pcsl_string_utf8_length()

■ pcsl_string_convert_to_utf8()

■ pcsl_string_convert_to_utf16()

■ pcsl_string_convert_from_utf8()

■ pcsl_string_convert_from_utf16()

■ pcsl_string_equals()

■ pcsl_string_compare()

■ pcsl_string_cat()

■ pcsl_string_dup()

■ pcsl_string_append()

■ pcsl_string_append_char()

■ pcsl_string_append_buf()

■ pcsl_string_predict_size()

■ pcsl_string_substring()

■ pcsl_string_starts_with()

■ pcsl_string_ends_with()

■ pcsl_string_index_of()

■ pcsl_string_index_of_from()

■ pcsl_string_last_index_of()

■ pcsl_string_last_index_of_from()

■ pcsl_string_trim_from_end()

■ pcsl_string_trim()

■ pcsl_string_convert_to_jint()

■ pcsl_string_convert_from_jint()

■ pcsl_string_convert_to_jlong()

■ pcsl_string_convert_from_jlong()

■ pcsl_string_free()

■ pcsl_string_get_utf8_data()

■ pcsl_string_release_utf8_data()

Chapter 8 PCSL 71

Page 98: Architecture and Design Guide by Oracle

■ pcsl_string_get_utf16_data()

■ pcsl_string_release_utf16_data()

■ pcsl_string_is_null()

You must also provide definitions for the following macros:

■ PCSL_DEFINE_ASCII_STRING_LITERAL_START_MD

■ PCSL_DEFINE_ASCII_STRING_LITERAL_END_MD

■ PCSL_STRING_LITERAL_LENGTH_MD

■ PCSL_DEFINE_STATIC_ASCII_STRING_LITERAL_START_MD

■ PCSL_DEFINE_STATIC_ASCII_STRING_LITERAL_END_MD

■ PCSL_STRING_NULL_INITIALIZER_MD

Porting Unicode Resource NamesMIDP (including PCSL) allows Unicode symbols to be used in RMS resource names.These Unicode symbols may also be used in Sun Java Wireless Client software filenames. If your platform does not accetp Unicode characters, you must convert theUnicode symbols to ASCII and then substitute the ASCII symbols in place ofUnicode in the file names you port.

The engineer porting the Sun Java Wireless Client software can choose the wayUnicode resource names are transformed into ASCII file names. The defaultencoding system used by the Sun Java Wireless Client software is radix 41 encoding.It should be suitable in most porting cases.

Note – Other encoding schemes are possible. To use a different encoding scheme(for example, radix 64 or radix 85), reset the build flag ESCFILENAMES_MODULE=radix41 at build time to the new radix scheme. For more information, see the BuildGuide.

Conversion of Unicode symbols to ASCII characters is done by the PCSL subsystempcsl/escfilenames.

For specific information about radix 41 encoding:

1. Find the file pcsl/escfilenames/radix41/pcsl_esc_md.h.

72 Architecture and Design Guide • December 2008

Page 99: Architecture and Design Guide by Oracle

2. Find the definition of macro PCSL_ESC_MOREDIGITS_MD.

The ASCII characters shown here are the ones that will be used as “digits” inplace of Unicode encoding. For more information, see “About Radix 41 Encoding”on page 73.

The radix 41 encoding scheme also uses a number of escape characters. These escapecharacters can be used to escape a specific sequence of characters (for example, toescape non-English characters, such as Chinese or Korean). All escape characters aredefined via Sun Java Wireless Client software macros.

To find valid escape characters:

1. Find the file pcsl/escfilenames/radix41/pcsl_esc_md.h.

2. Find the following macros:

■ PCSL_ESC_SHIFT_TOGGLE_MD

■ PCSL_ESC_SHIFT1_MD

■ PCSL_ESC_PREV_BLOCK_MD

■ PCSL_ESC_TOGGLE_MD

■ PCSL_ESC_FULL_CODES_MD

Note – Escape symbols must not be used as digits.

About Radix 41 EncodingRadix 41 encoding uses 41 digits to replace Unicode symbols. The first 10 digits arethe numbers 0-9. The next 26 digits are the letters of the English alphabet, a-z. Intotal, this makes up 36 digits. The last five digits (to make 41) come from the firstfive digits shown in the macro PCSL_ESC_MOREDIGITS_MD.

Note – The other symbols shown in the macro PCSL_ESC_MOREDIGITS_MD are notneeded for radix 41 encoding, but may be used for other radix encoding schemes(for example, radix 64 or radix 85).

Other radix encoding schemes are defined in the macro ESCFILENAMES_MODULE, inthe same location as the other macros. If you change the default setting for the buildflag ESCFILENAMES_MODULE=radix41, the macro ESCFILENAMES_MODULE isreferenced for the new radix scheme.

Chapter 8 PCSL 73

Page 100: Architecture and Design Guide by Oracle

Encoding for Non-English Resource NamesIf the default encoding scheme provided by radix 41 is not sufficient for encodingnon-English resource names, it is possible to define your own digits and escapecharacters.

1. Think out a new name for your ESCFILENAMES_MODULE.

For example, you may want to call it myos (as in, my OS).

2. Choose the radix scheme you want to use.

Your choices are 16, 51, 64, and 85.

3. Copy the directory corresponding to the chosen radix under the new name. Forexample:

$ cp -r radix16 myos

4. In the file pcsl_esc_md.h modify the macros that define the digits and escapecharacters.

5. Run make using the new module, and using the donuts package. For example:

$ make PCSL_PLATFORM=javacall_i386_vc ESCFILENAMES_MODULE=myosclean all donuts

74 Architecture and Design Guide • December 2008

Page 101: Architecture and Design Guide by Oracle

9

PutPixel Technology

PutPixel technology is a Java Wireless Client software implementation of thegraphics, image, and font portions of the MIDP specification. PutPixel technologyprovides a quick and easy means to get graphics, image, and font functionalityrunning during the porting process.

PutPixel technology implements all of the MIDP graphics, image, and font APIs,however, by default it includes only a simple monospace bitmap English font.PutPixel technology supports the PNG image format and it provides optional JPEGsupport.

Note – The reference port on the Microsoft Windows platform and the linux_fbframebuffer are implemented using PutPixel technology.

PortingOne of the most difficult and time consuming parts of the porting process isimplementing the graphics, image, and font systems. PutPixel technology provides avery simple means to get these functions up and running. Use PutPixel technologyas part of the porting process and either replace it with a port to your platform’snative resources as described in Chapter 10 or use it in your production product.

The only porting step required to implement PutPixel technology is to define ascreen buffer into which it can render. By default, PutPixel technology rendersimages into the screen buffer using the 16-bit RGB 565 format. The RGB 565 formatallocates five bits for red, six bits for green, and five bits for blue. You can change thepixel format definition in the PutPixel technology porting interface header filegxj_putpixel.h.

Chapter 9 PutPixel Technology 75

Page 102: Architecture and Design Guide by Oracle

Define the screen buffer as a pointer to either a virtual screen buffer, or directly intothe hardware video buffer. Most systems use a double buffered screen buffer toavoid screen flicker. The system screen buffer is also specified in gxj_putpixel.h.

BuildingTo build Java Wireless Client software with PutPixel technology enabled, editmidp/src/lowlevelui/subsystem.gmk so that the value ofSUBSYSTEM_GRAPHICS_MODULES is set to the value putpixel.

TestingOnce the system is up and running, you can run tests to verify the functionality.Refer to the Tools Guide for details about running the appropriate unit tests. If youdecide to run your own tests, ROMize the code to reduce dependencies on othersubsystems, such as the file system.

TuningThe PutPixel technology code is highly tuned and requires no further optimization.If graphics performance seems slow, it is possible that screen buffer formatdefinitions might not be set up efficiently. Check gxj_putpixel.h to determine ifyou can optimize how the system gets and sets pixel values.

Performance can also be improved by replacing the default font library with thenative font engine. PutPixel technology comes with a simple monospace bitmap fontfor ASCII characters. You can use either of the following two methods to replace itwith platform font libraries:

■ If the platform has an API to render strings into a given destination screen buffer,port the implementation of the functions gx_draw_chars,gx_get_charswidth, and gx_get_fontinfo to use the platform font API.

■ Replace the font bitmap with the platform font bitmap definition. The defaultPutPixel technology character drawing function is then used to render the bitmap.

76 Architecture and Design Guide • December 2008

Page 103: Architecture and Design Guide by Oracle

You can add support for JPEG graphics by obtaining the libjpeg open sourcelibrary and using the Java Wireless Client software build system to build it. Specifythe following options either on the gnumake command line or inbuild/platform/Options.gmk:

■ USE_JPEG=true

■ JPEG_DIR=your-libjpeg-source-directory

Support for additional graphics formats such as GIF, and BMP is difficult to add. Ifadditional graphics formats are required, it is best to replace PutPixel technologywith a port to your platform’s native resources as described in Chapter 10.

Chapter 9 PutPixel Technology 77

Page 104: Architecture and Design Guide by Oracle

78 Architecture and Design Guide • December 2008

Page 105: Architecture and Design Guide by Oracle

10

Low-Level Graphics and ImagesServices

This chapter discusses the design and porting of the low-level graphics and imagesservice and its interactions with other parts of Java Wireless Client software. To bestunderstand this design, become familiar with the material in the followingdocuments:

■ MIDP 2.1 Specification.

■ The Java™ Virtual Machine Specification, Second Edition.

■ The Java™ Programming Language (3rd Edition).

■ KNI Specification, which is part of the documentation included with the CLDCReference Implementation. See http://java.sun.com/products/cldc/.

DescriptionThe low-level graphics and images service subsystem provides all of the low-levelgraphics and image functionality required by the MIDP 2.1 Specification. It has thefollowing components:

■ Graphics Rendering – Low-level graphics routines for Java Wireless Clientsoftware system.

■ Graphics Context – Manages the graphics context, which consists of thecontrolling parameters for the current graphics routines (such as line width, fontselected, and so on). The graphics contexts must remain synchronized betweenthe native platform and the Java platform.

■ Image Handling – Handles the decoding, storage, and rendering of images.

Chapter 10 Low-Level Graphics and Images Services 79

Page 106: Architecture and Design Guide by Oracle

External InteractionsThe low-level graphics and images service subsystem interacts with the followingJava Wireless Client software subsystems:

■ High-level UI subsystem

■ Gaming subsystem

■ File System

■ Networking

■ OS functionality

FIGURE 10-1 shows these interactions.

FIGURE 10-1 Subsystem Interactions

DesignJava Wireless Client software provides a highly optimized low-level graphics andimages service subsystem without sacrificing portability. More specifically, thesubsystem must provide the following functionality:

■ Optimized Performance and Footprint – A port must be able to use as manyavailable native features as possible to increase performance and reduce totalcode size.

■ Portability – Customers must be able to replace individual components with theavailable platform counterparts by making clearly defined changes.

■ Functionality Levels – Customers must be able to pick the combination ofcomponents appropriate for their devices.

High-level UI subsystem

Low-level graphics

Game subsystem

Native platform APIs

and image subsystem

Image Primitive

80 Architecture and Design Guide • December 2008

Page 107: Architecture and Design Guide by Oracle

For example, most devices provide at least some of the primitive graphicscapabilities that match MIDP’s graphics requirements. For these features, a singlelayer of indirection between the public APIs of thejavax.microedition.lcdui package and the platform-specific graphicslibraries is sufficient. However, many devices do not provide features such asdrawing arcs. For these features, devices might have to depend on Java WirelessClient software to provide more code between the public APIs and the platform-specific graphics libraries.

Initially, the low-level graphics and images service component targets thefollowing types of platforms:

■ Platforms with some, but not all, of the rich graphics APIs required by MIDP

■ Platforms with rich graphics APIs that are almost a one-to-one mapping toMIDP graphics APIs

■ Flexibility – The subsystem must be easily adapted to take advantage of specialplatform architectures (such as devices with dual processors or hardware graphicsaccelerators)

Graphics Rendering ComponentThe graphics rendering component provides the functionality of the Graphicsclass. It has drawing primitives for text, images, lines, rectangles, and arcs. It alsoprovides access to a display object (an instance of the classjavax.microedition.lcdui.Display) for obtaining device characteristics, suchas whether the system supports color and how many distinct gray levels areavailable. For a complete description of the Graphics class, refer to the MIDP 2.0Specification.

Primitive Graphics Routines and PortingFor performance, most of the methods for drawing graphics primitives call nativefunctions. For example, the Java method drawLine calls the corresponding native-layer function gxpport_draw_line. The native calls go through the KVM NativeInterface (KNI) before the platform routines are called. KNI combines highperformance and low memory overhead. See the KNI Specification, which is part ofthe CLDC documentation, for more information. The use of gx_draw_lineprovides a common interface between PutPixel technology and platform graphics.

The graphics porting layer, which uses KNI, is well defined. Each call to KNI isgiven the full class name followed by the method name, with an underscore (_) usedas a separator. The native function itself has the prefix gxpport_ followed by themethod name translated to follow the underscore naming convention. FIGURE 10-2shows this naming convention by using drawLine as an example.

Chapter 10 Low-Level Graphics and Images Services 81

Page 108: Architecture and Design Guide by Oracle

FIGURE 10-2 drawLine Method Through Its C Call

Because some native platforms do not have one-to-one mapping between the MIDPAPI and the native API, Java Wireless Client software provides a library of drawingprimitives called the Java Wireless Client software Native Platform Primitive Library(LNP). Java Wireless Client software Native Platform Primitive Library can be usedto supplement missing native-platform functionality. For example, most platformsdo not have an arc drawing function, so the LNP arc drawing functions provide it.

Design Rationale, Notes, and ConsiderationsThe architecture and design of the graphics rendering component is as simple aspossible to facilitate portability and performance. To maintain or improve thecomponent’s performance, use as much of the native primitive capabilities aspossible.

public native void drawLine(int x1, int y1, int x2, int y2);

KNIEXPORT KNI_RETURNTYPE_VOIDJava_javax_microedition_lcdui_Graphics_drawLine();

extern void gx_draw_line(jint pixel, const jshort *clip,const java_imagedata *dst, int dotted, int x1,int y1, int x2, int y2);

extern "C" void gxpport_draw_line(jint pixel, constjshort *clip,gxpport_mutableimage_native_handle dst,int dotted, int x1, int y1, int x2, int y2);

82 Architecture and Design Guide • December 2008

Page 109: Architecture and Design Guide by Oracle

Graphics Context ComponentThe graphics context component is a data structure that maintains the renderingsystem’s property values, including those used during rendering and those that holdpointers to the rendering area. These properties must be consistent between the Javaplatform layer and native code for correct behavior.

FIGURE 10-3 illustrates which functions can update the graphics context’s propertyvalues and which can provide data to the graphics context through their parameters.

FIGURE 10-3 Functions That Update Property Values and Functions Providing Data

Detailed DesignWhen Java Wireless Client software executes a rendering operation (native or Javaplatform), it must use the most recently updated values of the properties shown inFIGURE 10-3. Because all property values are set from within the Java platform, thoseoperations always have access to the correct values. However, the native code mustmake sure its values are current. You must decide on a method for synchronizationand the number of native graphics contexts to use.

setClipClip region Translate

translate

ColorsetColor, setGrayscale

Affected by: clipregion and translate

image renderingdrawImagedrawRegiondrawRGBcopyArea

FontsetFont Takes parameters:

coordinates andso onAffected by: clip region

translate, color, and font

drawChardrawCharsdrawStringdrawSubstring

Takes parameters:location coordinates andunicode data

Line stylesetStrokeStyle

Affected by: clip region,translate, color, and

drawLinedrawArcdrawRectdrawRoundRect

Affected by: clipregion, translate,

fillArcfillRectfillRoundRect

fillTriangle

Unicode data(parameters)

...(various parameters)

Location coordinates (such as x and y) (parameters)

Takes parameters:location coordinates

stroke style and colorTakes parameters:location coordinates

Chapter 10 Low-Level Graphics and Images Services 83

Page 110: Architecture and Design Guide by Oracle

Synchronization Method

The native code has two ways to make sure its values are current.

■ Mirror all of the properties in native code – Each time a Java method is called, anative call updates the corresponding native data structure.

■ Use a dirty bit to track the property values that have changed – Before a renderoperation, the native code queries the updated values.

Number of Native Graphics Contexts

The implementation of the graphics context component in the native layer alsodepends on whether multiple graphics contexts can be managed. It is likely that thenative code does not keep separate graphics contexts for each Graphics instance,but the rendering area of a Graphics instance must always be stored individually.

For example, consider two different cases: one in which an implementation supportsonly one platform-managed graphics context and another in which animplementation supports multiple graphics contexts.

With only one native graphics context, a native implementation must handle thefollowing situations:

■ Mapping the graphics context identifier to a graphics context structureimplemented in native code

■ Ensuring the graphics context is current

■ Ensuring the associated property values are current

With multiple native graphics contexts, the first two steps are unnecessary. Theimplementation must only ensure that the appropriate graphics context is active.

If the implementation mirrors all of the properties in native code (instead of using adirty bit), the native code does not need to check whether the property values arecurrent. Other function implementations are trivial.

Image ComponentThe image component is made up of the following parts:

■ Preprocessor – Decodes input image data for immutable images. Creates andinitializes image data for mutable images.

■ Storage – Manages storage of actual bits of images.

■ Accessor – Provides access to pixels of images. Handles logic to traverse thepixels. Also handles transformations.

■ Renderer – Renders image data into a specified graphics object’s destination.

84 Architecture and Design Guide • December 2008

Page 111: Architecture and Design Guide by Oracle

FIGURE 10-4 shows the interactions of the parts of the image component.

FIGURE 10-4 Components of the Low-Level Graphics and Images Service Subsystem

The image component requires access to information from the device, including bitdepth, storage of transparency, alpha information, and palette handling. Thisinformation is available at compile time. It must be available from a properties orconfiguration file.

Preprocessor ComponentThe preprocessor component converts input image data into a format usable by theJava Wireless Client software. It is always used when creating Image instances.

The MIDP 2.1 Specification discusses two kinds of images: mutable (images that canbe changed) and immutable (images that cannot be changed). All immutable imageshave associated data from which the image is created. Mutable images are designedto be rendered upon.

The preprocessor reads data from the specified source of immutable images andformats it. Formatting might include making copies of existing images or convertingraw bitmap data into an efficient internal representation.

The preprocessor initializes internal memory of a suitable size and format formutable images. It prepares the image for rendering. The image is the destination ofa Graphics instance.

lcdui.Image lcdui.Graphics

RenderingAccessor

Preprocessor

Immutable

Storage

Decoder ordecoders

Mutable

Chapter 10 Low-Level Graphics and Images Services 85

Page 112: Architecture and Design Guide by Oracle

Creating Immutable Images From an Image Data Source

Immutable images are always created from image data. Image data is obtained fromthe follow sources:

■ Java platform:

■ Input stream

■ URL

■ Byte array

■ int array of ARGB values

Because data from these sources is available only from the Java platform, it mustbe transferred to native code before creating the image.

■ Native layer:

■ Image

■ Image with a possible transformation, specified region, or both

Because the image was created by the low-level graphics and images servicesubsystem, a native representation exists that is accessible by the native code.

■ Native image:

The ability to use a native image requires adding an API that provides native-image access to the Java platform layer of the low-level graphics and imagesservice subsystem. It is an internal API. MIDlets must not be able to load imagesin native format. The ability to use native images is useful for two reasons:

■ Enhanced performance.

■ Theme support in the high-level UI. All themes are known prior to MIDletlaunch (for example, at port or installation time). Theme images can be hand-optimized for storage size and or platform speed.

Every port must reimplement both the native and Java platform code of thepreprocessor component. In addition, the method of specifying the URL of thenative image might differ for each port.

Creating Mutable Images With a Given Width and Height

Creating mutable images differs in functionality and implementation from creatingimmutable ones. Because a mutable image is designed to be rendered upon, amutable image has no source data to decode. Instead, the initial contents are alwayswhite pixels. In addition to initializing the pixels, creating a mutable imageinitializes the data structures for the destination of a Graphics object.

86 Architecture and Design Guide • December 2008

Page 113: Architecture and Design Guide by Oracle

Decoder ComponentThe decoder is used to create an immutable image from the bytes available from aninput stream, URL, or byte array. The decoder provides a consistent interface to thedecoding functions. It enables decoders for different image formats to be pluggedinto Java Wireless Client software easily. The decoder component makes thepreprocessor extensible.

The decoder is internal to the preprocessor. Its APIs are not exposed to any otherparts of the low-level graphics and images service subsystem, nor to any othersubsystems of Java Wireless Client software.

Java Wireless Client software supports the following image formats:

■ PNG

■ JPEG

■ ARGB bitmap

FIGURE 10-5 shows the decoder architecture.

FIGURE 10-5 Decoder Architecture

Implementing a Decoder

A Decoder for an image format can be implemented in one of two ways. The firstmethod is to implement the decoder within the Java Wireless Client software sourcebase. This method must be used for image formats for which a native decoder is notavailable. The decoder must provide the decoded image in either the native imageformat or a format that is supported by the rest of the image subsystem’scomponents. Storing the decoded image is done with the accessor’s write functions.See “Accessor Component” on page 89 for information.

Preprocessor and decoder components

byte array, input stream, URL

Java platform layer image source:

int array of RGB data

Native layer image sources:

image, with or without a transformation

mutable image

Chapter 10 Low-Level Graphics and Images Services 87

Page 114: Architecture and Design Guide by Oracle

The second method is to use a decoder implementation already on the device. Thissaves effort and gives the Java Wireless Client software a smaller footprint. Inaddition, optimizations to the decoder can be made independently because itsimplementation is de-coupled from the Java Wireless Client software source base.

Two scenarios utilize an existing decoder. In the first scenario, the decoder decodesdirectly into the native image-storage format. In this scenario, using the accessor tostore the decoded image might be inefficient. Instead, the storage module’s APIs canbe used. See “Image Storage Component” on page 89 for information.

In the second scenario, the decoder emits the decoded image as a stream of bytes. Inthis scenario, the accessor’s methods must receive the decoded image. They set thebitmap data values for an individual pixel, a scan line, or an entire region.

The decoder defines three types of errors to handle errors during decoding: thosedetectable before, during, and after decoding. The following list shows the errors,categorized by type:

■ Before decoding:

■ Invalid format

■ Insufficient data

■ During and after decoding:

■ Invalid sub format

■ Malformed data

■ Invalid memory access (implementation error)

The decoding functions can return the following values:

■ GXUTL_NATIVE_IMAGE_NO_ERROR

■ GXUTL_NATIVE_IMAGE_OUT_OF_MEMORY_ERROR

■ GXUTL_NATIVE_IMAGE_DECODING_ERROR

■ GXUTL_NATIVE_IMAGE_UNSUPPORTED_FORMAT_ERROR

Accessor ComponentThe accessor provides a generic interface to access the individual pixel data of anyimage. It also contains all logic to handle transformations, allowing traversal ofpixels in the image with transformations in effect.

The accessor performs the following functions:

■ Traversing and reading pixel data from storage

■ Traversing and reading pixel data with transformations in effect

■ Writing pixel data into storage

88 Architecture and Design Guide • December 2008

Page 115: Architecture and Design Guide by Oracle

The following javax.microedition.lcdui.Image method uses the accessordirectly:

void getRGB(int[] rgbData, int offset, int scanlength,

int x, int y, int width, int height)

Image Storage ComponentImage storage manages the storage area for image data, pixel data, and relatedinformation such as color palette. Specifically, it does the following tasks:

■ Manages (allocates and deallocates) memory for storing images.

■ Provides access to pointers that point to the following data:

■ Bitmap data

■ Transparency information

■ Palette information

■ Synchronizes a backing store for mutable images with a Graphics context. This isoptional and depends on the design of the graphics context.

Image storage can store image data in one of three ways:

■ Native bitmap structure – Using the native bitmap format saves code size andeffort. The disadvantage is it is dependent on the device APIs.

■ Native bitmap structure managed by Java Wireless Client software – Thisoption removes the dependency on the device APIs. The disadvantage is that eachport must optimize the component, and optimization requires effort.

■ Java platform byte array – Allocating the bitmap data in the Java platform layersimplifies memory management. The disadvantage is that it might impactperformance.

The decision on how to store different image formats requires careful considerationfor every platform. Most platforms support two types of native image storage: onetargeted towards rendering performance and the other towards storagecompactness. A MIDP port can decide to maintain this distinction, perhaps usingone for immutable images and the other for mutable images. A port can also, forsimplicity, sacrifice performance by using only one image storage format.

The following factors influence this decision:

■ Speed of rendering from image storage in different formats

■ Speed of access to individual pixel data

Chapter 10 Low-Level Graphics and Images Services 89

Page 116: Architecture and Design Guide by Oracle

Renderer ComponentThe renderer transfers all or some of the bits of a stored image onto the destinationof a Graphics object, possibly converting the bits to the destination format in theprocess.

Rendering is a separate part of the image component for performance. The renderercontains logic that determines the fastest code path to render bits from stored imageto the graphics context. Two main paths are available: one path is for rendering animmutable image, the other for rendering a mutable image. The paths are differentbecause the different types of images are expected to be stored in different formats.

PortingThis section discusses strategies for porting the low-level graphics and imagessubsystem. The low-level graphics and images subsystem provides the fundamentalgraphics functionality and image processing to the entire MIDP runtime system.Address this subsystem early in the porting process.

If your system does not provide direct mapping for the high-level user interfacesubsystem (for example, provides no native platform alert or dialog), the low-levelgraphics and images subsystem becomes responsible for rendering all the high-levelcomponents. Therefore, you must carefully monitor performance throughout theentire porting process. The major design goals for the low-level graphics and Imagesand images subsystem are high performance and portability.

To ease the porting effort, the porting interfaces are divided into the followinggroups:

■ Primitive graphics group

■ Image manipulation group

■ String and font drawing and accessing group

■ Alert sound group

■ Vibrate and backlight group

Each group has special porting APIs. The porting layer consists of native and Clanguage APIs.

You can choose the level at which you want to port the low-level graphics andimages subsystem. For a feature for which a native porting API is available, it mightbe possible to implement that feature entirely in Java programming language code.However, to improve performance, use the provided native porting APIs.

90 Architecture and Design Guide • December 2008

Page 117: Architecture and Design Guide by Oracle

Porting the Primitive Graphics GroupThe graphics porting layer, which uses KNI, is well defined. Each call to KNI isgiven the full class name followed by the method name, with an underscore (_) usedas a separator. The native function itself has the prefix gxpport_ followed by themethod name translated to follow the underscore naming convention. The use ofgx_draw_line provides a common interface between PutPixel technology andplatform graphics. FIGURE 10-6 shows this naming convention by using drawLine asan example.

FIGURE 10-6 drawLine Method Through Its C Call

Map all the primitive graphics routines and implement them. All C nativedeclarations of low-level primitive graphics porting routines are in the filegxpport_graphics.h. Your platform might not provide a one-to-one mapping forall the porting APIs. For routines missing from your platform, use the routinesavailable in the Java Wireless Client software release as a reference or write yourown. Refer to “Drawing and Filling Arcs” on page 96 for a detailed explanation ofhow to implement an arc drawing routine. For example, it is important todistinguish the differences between the coordinate system of your platform and thatspecified in the MIDP specification.

Java Wireless Client software includes a description of the LCDUI APIs, whichprovide a detailed explanation of each of the primitive graphics porting APIs.

public native void drawLine(int x1, int y1, int x2, int y2);

KNIEXPORT KNI_RETURNTYPE_VOIDJava_javax_microedition_lcdui_Graphics_drawLine();

extern "C" void gxpport_draw_line(jint pixel, constjshort *clip, gxpport_mutableimage_native_handledst, int dotted, int x1, int y1, int x2, int y2);

extern void gx_draw_line(jint pixel, const jshort *clip,const java_imagedata *dst, int dotted, int x1,int y1, int x2, int y2);

Chapter 10 Low-Level Graphics and Images Services 91

Page 118: Architecture and Design Guide by Oracle

Porting Checklist for Primitive GraphicsBefore you begin porting Primitive Graphics, step through the following checklist:

■ Does your platform support transparent images?

■ How many colors does your platform support?

■ How many transparency levels does your platform support?

■ What is the hexadecimal value of the erase color?

■ Does your platform support double buffering?

■ Does your platform support a pointer or a stylus?

■ If your platform supports a pointer, does it support pointer motion?

■ What is the color depth that you want to support in the MIDP runtime system?

■ Does your platform support key repeat events?

After you complete the checklist, enter the results as constants inside theconfiguration file. See the Chapter 4 for details about how to enter the constants inthe configuration file. These constants are necessary during the compilation of MIDP.Without them, the build system might not be able to complete the compilation anderrors can occur. Note that because they are needed at compile time, the ability todynamically change these properties while MIDP is running is not supported.

The following table lists the constants and descriptions related to low-level graphics.By modifying these values inside the constants configuration file, you can changethe platform behavior.

TABLE 10-1 Low-Level Graphics Constants

Property Description

DISPLAY_IS_COLOR Set to 1 (true) when color is supported.Set to 0 (false) when color is not supported.

DISPLAY_NUM_COLOR Number of colors the platform supports, in bytes.

DISPLAY_DEPTH Color depth that the platform supports, in bits per pixel(bpp).

ALPHA_LEVELS Number of alpha channel levels the platform supports.

ERASE_COLOR Color, in hex, used as the erase color (the color used to clearaway any existing pixels from a graphics object beforepainting the new pixels).

IS_DOUBLE_BUFFERED Set to 1 (true) when double-buffering is supported.Set to 0 (false) when double-buffering is not supported.

92 Architecture and Design Guide • December 2008

Page 119: Architecture and Design Guide by Oracle

Drawing Graphics PrimitivesThe Graphics class provides drawing primitives for text, images, lines, rectangles,and arcs. This section describe the graphics coordinate system, and how that affectsthe drawing of lines, rectangles, and filled rectangles. It also explains therequirements of drawing arcs.

Coordinate System Overview

A Graphics object has a coordinate system with its origin at the upper-left corner ofthe destination. The X-axis direction is positive towards the right, and the Y-axisdirection is positive downwards. The coordinate system and graphicsimplementation in the Java Wireless Client software assume that the device hassquare pixels. If your device does not have square pixels, you must modify the low-level graphics and Images subsystem to take the different pixel shape into account.An application must be able to rely on horizontal and vertical distances being equalon the device display.

The coordinate system represents locations between pixels, not the pixelsthemselves. The first pixel in the upper left corner of the display lies in the squarebounded by coordinates (0,0), (1,0), (0,1), and (1,1). This is shown in thefollowing figure.

POINTER_SUPPORTED Specifies whether both the platform and MIDPimplementation provide support for a pointer (press andrelease).Set to 1 (true) if you want runtime to support a pointer.Set to 0 (false) if you do not want to support a pointer.

MOTION_SUPPORTED Specifies whether both the platform and MIDPimplementation provides support for pointer motions.Set to 1 (true) when pointer motion is supported.Set to 0 (false) when pointer motion is not supported.

IMAGE_DEPTH Depth, in bits, of images supported by the platform. Thismight or might not be the same as the bit depth used by therest of the platform’s rendering system.

REPEAT_SUPPORTED Specifies whether both the platform and MIDPimplementation provides support for key repeat.Set to 1 (true) when key repeat is supported.Set to 0 (false) when key repeat is not supported.

TABLE 10-1 Low-Level Graphics Constants (Continued)

Property Description

Chapter 10 Low-Level Graphics and Images Services 93

Page 120: Architecture and Design Guide by Oracle

FIGURE 10-7 Graphics Class Coordinate System

Drawing Lines

A Graphics object must draw a line between the coordinates (x1,y1) and(x2,y2). In the coordinate system, that means that the line begins below and to theleft of (x1,y1), and ends below and to the left of (x2,y2). This is shown in thefollowing figure, which shows a line drawn from (2,2) to (6,6).

FIGURE 10-8 Drawing a Line

First pixel in theupper left corner

First pixel is belowand to the right ofcoordinate (2,2)

Last pixel is belowand to the right ofcoordinate (6,6)

94 Architecture and Design Guide • December 2008

Page 121: Architecture and Design Guide by Oracle

Drawing and Filling Rectangles

A Graphics object draws and fills rectangles such that a drawn rectangle is onepixel larger than a filled rectangle of the same requested height and width. That is,the MIDP 2.1 Specification says that the drawRect method, “Draws the outline ofthe specified rectangle... The resulting rectangle will cover an area (width + 1)pixels wide by (height + 1) pixels tall.” In contrast, the fillRect method fillsthe specified rectangle with the current color. For an example, see FIGURE 10-9.

FIGURE 10-9 shows two rectangles. The rectangle on the left shows the drawRectmethod drawing a rectangle starting at (0,0) with a width of 8 and height of 6. Therectangle on the right shows the fillRect method’s rectangle that starts at (0,0)and has a width of 8 and height of 6. That is, they correspond to the following calls:

drawRect(0, 0, 8, 6);

fillRect(0, 0, 8, 6);

FIGURE 10-9 Drawing Compared With Filling a Rectangle

Drawing and Filling Arcs

It can be difficult to understand the contract that the drawArc method must fulfill.This section explains its requirements. Note that the methods that draw and fill arcshave the same size relationship as that described in the previous section (“Drawingand Filling Rectangles” on page 95).

To draw an arc means to draw all or part of an ellipse. The mathematical definitionof an ellipse is:

x2/a2 + y2/b2 = 1

Chapter 10 Low-Level Graphics and Images Services 95

Page 122: Architecture and Design Guide by Oracle

The value of the variable a controls the width of the ellipse, and the value of thevariable b controls the height. If a = 2 and b = 1, the ellipse is twice as wide as it ishigh. It looks like this:

FIGURE 10-10 Ellipse

If a and b have the same value, the equation reduces to a circle:

(x2 + y2)/r2 = 1

The image is a circle as shown in FIGURE 10-11:

FIGURE 10-11 Circle

The drawArc method specification says:

Angles are interpreted such that 0 degrees is at the 3 o’clock position. Apositive value indicates a counter-clockwise rotation while a negativevalue indicates a clockwise rotation.

The specification uses the common convention that 0 degrees lies where the circlecrosses the positive x axis (sometimes referred to as 3:00 like in the specification).Positive degrees lie with the positive values on the y axis (they go counter-clockwise) and negative degrees lie with the negative values on the y axis (they goclockwise). The following figure shows the angles at 0, 90, and -90:

b

a

b

a

96 Architecture and Design Guide • December 2008

Page 123: Architecture and Design Guide by Oracle

FIGURE 10-12 0, 90, and -90 Degrees on a Circle

The specification then says:

The center of the arc is the center of the rectangle whose origin is (x, y)and whose size is specified by the width and height arguments.

The drawArc method has x, y, width, and height as four of its arguments.Remember that the coordinate system of a canvas has its origin (0,0) at the upper leftcorner, the numeric values of the x-coordinates monotonically increase from left toright, and the numeric values of the y-coordinates monotonically increase from topto bottom.

To draw an ellipse, the value of the variable a in the ellipse equation must be w/2and the variable b must be h/2. The center of the ellipse must be at (x+(w/2), y +(h/2)). Using these values creates an ellipse that is centered within the rectangle, asspecified by the method description. The ellipse is also tangent to the rectangle atfour points, which are the minimum and maximum radii of the ellipse. The ellipse isspecified by the rectangle’s width and height arguments, as specified by the methoddescription.

The following figure shows a canvas with an arc that meets these requirements. Thearc is a full ellipse. The figure shows the ellipse within the rectangle mentioned inthe specification. The rectangle is shown with a dashed line because it is not actuallydrawn on the canvas. The rectangle’s width is represented by the variable w, and itsheight is represented by the variable h.

x axis

y axis

0o

90o

-90o

Chapter 10 Low-Level Graphics and Images Services 97

Page 124: Architecture and Design Guide by Oracle

FIGURE 10-13 Boxed Ellipse

The final part of the specification covers what happens when the method is asked todraw only part of the ellipse. It says:

The angles are specified relative to the non-square extents of thebounding rectangle such that 45 degrees always falls on the line from thecenter of the ellipse to the upper right corner of the bounding rectangle.As a result, if the bounding rectangle is noticeably longer in one axis thanthe other, the angles to the start and end of the arc segment will beskewed farther along the longer axis of the bounds.

In a circle, the angles are not skewed, as shown in the 45 and -120 degree angles inthe following figure:

FIGURE 10-14 45 and -120 Degrees on a Circle

Canvas origin (0, 0)

(x, y)

(x+w, y+h)

w

h

b(h/2)

a(w/2)

(x+(w/2), y +(h/2))Center of ellipse

45o

-120o

98 Architecture and Design Guide • December 2008

Page 125: Architecture and Design Guide by Oracle

Skewing appears when the circle is stretched into an ellipse, as shown in thefollowing figure. The point that was 45 degrees on the circle is shifted so the angle ofthe line from the center to that point is no longer 45 degrees. Technically, 45 “degreesof arc” exists between the x axis and the labeled spot, but on paper the angle of theline from the center to that point is not really 45 degrees.

FIGURE 10-15 45 and -120 Degrees on an Ellipse

A port of this method must work the same way: It must use the start and end pointsof a partial arc as though the ellipse were a circle. To make sure that the skewinghappens correctly, the MIDP 2.0 Specification requires that 45 degrees always falls onthe line from the center of the ellipse to the upper right corner of the boundingrectangle, as shown by the circle and ellipse in the following figure. The figure againshows the bounding box with a dashed line. The figure also extends the 45-degreeline so that it touches the box.

FIGURE 10-16 Boxed Circle and Ellipse, With a 45 Degree Angle

The (x,y) coordinates of a point on a circle are calculated using sine and cosine. The(x,y) coordinates of the point at d degrees on a circle of radius r is:

(x = cos(d)*r, y = sin(d)*r)

For example, on a circle where r = 1, the (x,y) coordinates for the point that is at 30degrees are (cos(30), sin(30)).

The equation for the corresponding point at d degrees on an ellipse with axes a andb is (x = cos(d)*a, y = sin(d)*b).

45o

-120o

Chapter 10 Low-Level Graphics and Images Services 99

Page 126: Architecture and Design Guide by Oracle

Drawing and Filling Rectangles With Rounded Corners

Drawing and filling rectangles with rounded corners combines the previous twotopics, drawing rectangles and drawing arcs. The difference between drawing andfilling a rectangle with rounded corners is one pixel in height and width, asdiscussed in “Drawing and Filling Rectangles” on page 95. A MIDlet draws arectangle with rounded corners by specifying not only the starting pixel, the height,and the width of the rectangle, but also the width and height of the arc to use toround the corners.

The following figure shows a rectangle drawn with round corners using the calldrawRoundRect(0, 0, 30, 40, 4, 3). That is, the rectangle starts at the upperleft corner, and is 30 (+1) pixels wide, 40 (+1) pixels high, with corners rounded withan arc that is four pixels wide and three pixels high.

FIGURE 10-17 Drawing a Rectangle With Rounded Corners

Porting Image Manipulation GroupThe image component of the low-level graphics and images subsystem implementsthe javax.microedition.lcdui.Image class. This section explains how to portthis class to work on your device by interfacing the Java platform code with thenative platform functions that are available.

Arc is three pixels high

Arc is four pixels wide

100 Architecture and Design Guide • December 2008

Page 127: Architecture and Design Guide by Oracle

Mutable and Immutable ImagesThere are two types of images: mutable and immutable. These two types differlargely in their implementation, even though public APIs do not distinguishbetween the two.

The following sources that create an immutable image:

■ Image object

■ Image object, either a region or transformed

■ 32-bit ARGB data

■ Image data in one of formats supported by Java Wireless Client software (PNGand JPEG)

Immutable images are used only as a source of rendering, meaning they are used torender into the destination of a Graphics object as parameters to either theGraphics.drawImage or Graphics.drawRegion method call. Immutable imagescan be used within Alert, Choice, Form, or ImageItem objects. They can also beused as sources for Sprite and TiledLayer objects.

You must be careful to ensure that the implementation of the classes that useimmutable images as a source is compatible with the native format for immutableimages. For example, the implementation of ImageItem, if it uses a nativecomponent, must be able to use the native peer of an immutable image for reasonsof efficiency.

Mutable images are intended to be used to render upon. By calling the methodImage.getGraphics on a mutable Image, a Graphics object is obtained whosedestination is the mutable image. Mutable images can be used within Alert,Choice, Form, or ImageItem objects. When this is done, it behaves as if a snapshotof the image is taken at set time. Refer to “Alert Sound Group” on page 108 in thischapter for more details. For detailed information on ChoiceGroup, Form, andImageItem, see Chapter 12.

Mutable images can also be used as sources for Sprite and TiledLayer objects. Inthese cases, the contents must reflect the current state of the Image at render time.

For the sake of speed, the port must ensure that it is efficient for the internal storageof the mutable image to act as the destination of a Graphics object. Mutable imagesare always created empty (for instance, white pixels) and are not associated with anyalpha channel.

Image Creation APIs

The following javax.microedition.lcdui.Image methods use the preprocessormodule of the image component to create immutable images:

■ public static Image createImage(Image source)

Chapter 10 Low-Level Graphics and Images Services 101

Page 128: Architecture and Design Guide by Oracle

■ public static Image createImage(String name)

■ public static Image createImage(byte[] imageData, int imageOffset, int imageLength)

■ public static Image createImage(Image image, int x, int y, int width, int height,int transform)

■ public static Image createImage(InputStream stream)

■ public static Image createRGBImage(int[] rgb, int width, int height, boolean processAlpha)

The Image method uses the preprocessor module of the image component to createmutable images:

public static Image createImage(int width, int height)

Image Formats

MIDP 2.0 APIs for getting pixel data and creating images from RGB data use a 32-bitARGB format (eight bits for alpha and eight bits per channel RGB). This formatmight be inefficient to use in a device. If it is inefficient, the decision on the internalformat of the images depends on several factors:

■ Make mutable images as similar as possible to those provided by the hardware.The storage format of mutable images must not require conversions at rendertime. Mutable images can be widely used by the platform and the applications asan Image buffer, thus making performance critical.

■ Mutable images need not support transparency and alpha.

■ By calling getGraphics on an image it is possible to obtain a graphics object thatrenders to the mutable image. If the format of a mutable image is supported bythe hardware, rendering into this image is efficient.

■ Match the storage format for immutable images as closely as possible to thenative representation. However, immutable images are used only as the source forrendering. Therefore, if this code path is optimized, space-saving formats can beused for storing immutable images. For example, a 1-bit black-and-white PNGimage does not need to be converted to a 15-bit color image for rendering if therendering code for the 1-bit image is optimized.

■ Immutable images must support alpha channel.

■ Depending on the port’s requirements, the image format must be chosen to satisfythe platform’s performance and space requirements.

102 Architecture and Design Guide • December 2008

Page 129: Architecture and Design Guide by Oracle

Transparency and Alpha

The MIDP 2.1 Specification supports transparency in Portable Network Graphics(PNG) images. See http://www.w3.org/Graphics/PNG/ andhttp://www.libpng.org/pub/png/ for more information on Portable NetworkGraphics.

Transparency might exist only in immutable, off-screen images created from PNGimages or created from arrays of ARGB (alpha, red, green, blue) data. Moving animage that contains transparency data into a mutable Image instance (rendering it)changes the data into a native, opaque format and the transparency information islost.

One way an image can encode transparency is by designating one or more pixelcolors as transparent. Any pixel with the specified color is treated as fullytransparent. For PNG images, this is implemented using a tRNS chunk.

Another way that an image can encode transparency is by including an alpha valuewith each pixel. This is ARGB (alpha, red, green, blue) data. For a black and whiteimage, eight bits encode a pixel’s alpha value (00000000 is transparent and11111111 is opaque), and eight bits specify its color (00000000 is black and11111111 is white). For a color image, some number of bits encode a pixel’s alphavalue (all ones is fully opaque, all zeros is fully transparent, and values in betweenare semi-transparent) and the same number of bits specify the red, blue, and greenelements of each pixel. The number of bits is usually eight or 16. Java Wireless Clientsoftware uses eight. However, decoding images with 16-bit alpha channel issupported, and the resulting image has an alpha channel that is sampled down to 8bits.

An image can also use a palette alpha encoding technique that provides image datathat specifies the color of each pixel, and a chunk that specifies alpha values forcorresponding RGB values (a PLTE chunk).

A MIDP 2.0 compliant implementation must be able to render full transparency. Thatis, it must treat pixels with an alpha value of zero (or the color in a tRNS chunk) asfully transparent, and must treat pixels with alpha values greater than zero as non-transparent. The MIDP implementation might choose to treat non-transparent pixelsas opaque or to implement alpha blending, a technique that renders non-transparentpixels in a way that shows some of whatever is behind them.

A MIDP implementation that supports alpha blending can use either of twotechniques to interpret non-transparent pixels:

■ It can composite the non-transparent bits against the pixels on the screen. Thisprovides the best looking image, but takes a lot of processing. Java Wireless Clientsoftware uses this technique.

■ It can composite the non-transparent bits against some color, such as white. Thisprovides a good-looking image, and less processing is required. This technique isnot used by Java Wireless Client software.

Chapter 10 Low-Level Graphics and Images Services 103

Page 130: Architecture and Design Guide by Oracle

However you support transparency in your port, follow this general rule: Processtransparency data at decode time, for these reasons:

■ You have all the information at that time, so it is easier to make the picture lookas its creator intended it.

■ You might be able to combine processing steps to improve the look of the imagewhile decreasing processing time.

Note that the storage format, including the alpha channel, has an effect on theperformance of the following functions:

■ Creating

■ Rendering

■ Accessing (getRGB and sprite collision checking)

Transformations and Region Rendering

If the target device supports the transforming of images at render time, thiscapability is easily exploited by the architecture of the image subsystem (thefunction renderRegion for both mutable and immutable images must be ported totake advantage of this fact). However, if support for renderRegion is not provided,all the transformation code must be written at porting time.

Implementing transformed rendering involves the following high-level steps:

1. Set up pointers to the source data.

2. Obtain pixel data.

3. Convert to a renderable format if necessary.

4. Render to the destination.

This process is much faster in cases where pixel data is easily traversable andconversions are not necessary.

Porting Checklist for the Image Manipulation GroupPrior to porting the low-level graphics and image subsystem, use the followingchecklist to determine if porting requirements for the image component are met:

■ What image types are provided by the platform?

■ What are the supported color depths?

■ Is access available to the internal pixel data of the images?

■ What is the format for the source data used for image creation?

■ If more than one type of image is provided, is conversion between them possible?

104 Architecture and Design Guide • December 2008

Page 131: Architecture and Design Guide by Oracle

■ Are transformations possible on images at render time or at creation time?

■ How is transparency information stored?

■ What type of transparency or alpha is most efficient when using this platform?

■ Is transparency information maintained when the image is transformed?

■ Are different types of images optimized for different uses? For instance, one typemight be for image storage, another for portability, and another for images wherespeed is critical. Be sure that your images follow as close as possible to the servicehardware’s native format.

Functions to PortThe following files inmidp/src/lowlevelui/platform_graphics_port/include directory containthe declarations of platform-specific Image functions:

■ gxpport_immutableimage.h

■ gxpport_mutableimage.h

Platform-specific implementations of Image functions are in the directorymidp/src/lowlevelui/platform_graphics_port/port.

▼ Facilitating Porting of the Image Manipulation GroupFollowing these steps facilitates the porting process:

1. Create a mutable image with createImage(int width, int height).

Design and implement storage of a mutable image. The implementation mustpass the following tests:

■ Run getWidth and getHeight. The correct values must be returned.

■ Render the created image to screen. White pixels must be rendered.

2. Provide a graphics object that renders to a mutable image.

Provide functions to create a Graphics object that renders to a mutable image.The implementation must pass the following tests:

■ Render the mutable image to screen. White pixels must be rendered.

■ Render graphics primitives to the Graphics object obtained from the mutableimage.

■ Render the image to the screen. The mutable image’s contents must show theprimitives rendered onto it.

Chapter 10 Low-Level Graphics and Images Services 105

Page 132: Architecture and Design Guide by Oracle

3. Create immutable image from mutable image.

Design and implement storage for immutable images. The implementation mustpass the following tests:

■ Get properties for immutable images.

■ Render an ImmutableImage to screen. Must show content that is the same as themutable image used as source.

4. Implement createRGBImage.

The following results must be achieved from this step:

■ Design storage of alpha channel data and transparency values in immutableimages.

■ Design and implement passing of large amounts of data from Java programminglanguage code to native code.

■ Create immutable images from the data available from the Java programminglanguage resource.

The implementation must pass the following test: Image creation meets therequired performance goals.

5. Render transparent images.

Implement transparency and alpha blending at render time if the platformsupports it. The implementation must pass the following tests:

■ Render transparent images and alpha blending on a Graphics object whosedestination is a mutable image.

■ Render transparent images and alpha blending on a Graphics object whosedestination is a screen.

6. Access pixel data of images with getRGB.

Implement functions to access pixel data of mutable images and implementfunctions to access the pixel data of immutable images. The implementation mustpass the following tests:

■ Pixel data of created mutable image must be opaque white.

■ Pixel data of immutable images with alpha channel must return appropriatealpha values.

7. Create image from PNG and JPEG data.

Implement the interface to the PNG decoder and implement the interface to theJPEG decoder. The implementation must pass the following tests:

■ Match the pixel data of created images with the source image.

■ Decode source images with a color depth greater than the target system to a lowercolor depth appropriately.

■ Decode alpha and transparency information of the source image correctly.

106 Architecture and Design Guide • December 2008

Page 133: Architecture and Design Guide by Oracle

8. Render regions of images.

Render regions of immutable and mutable images with alpha blending. Theimplementation must pass the following tests:

■ Render regions of images correctly.

■ Meet performance goals.

9. Create transformed images from source image.

Implement transformations for image creation. The implementation must pass thefollowing tests:

■ Implement all eight transformations specified in the MIDP 2.0 specification.

■ Maintain alpha channel correctly when image is transformed.

10. Render transformed regions of images

Implement transformations for rendering. The implementation must pass thefollowing tests:

■ Achieve correct implementations of transformations.

■ Achieve correct alpha blending of transformed regions.

■ Meet performance goals.

String and Font Drawing and Accessing GroupWorking with a user interface designer, decide which font to map to the MIDP font.Three variables are involved in choosing a suitable font between your platform andthe MIDP specification: style, size, and face. Once you decide on the mapping, youcan start porting font-related APIs defined in gxpport_font.h andgxpport_graphics.h. Follow the example for the Microsoft Windows platformand the Texas Instruments OMAP730 development board. Be sure that your portingcode sets up and returns the font that you chose.

See TABLE 10-1 for a detailed explanation of the string and font porting APIs.

Note – This discussion pertains to the font used when drawing on the canvas. Donot confuse this font with the Java Wireless Client software platform componentfont, which is specific for the native high-level component in the Microsoft Windowsplatform and the Texas Instruments OMAP730 development board.

Chapter 10 Low-Level Graphics and Images Services 107

Page 134: Architecture and Design Guide by Oracle

Alert Sound GroupMap your platform sound to the MIDP alert sound. There are five types of alertsounds: ALARM, CONFIRMATION, ERROR, INFO, and WARNING. You are not requiredto have a unique sound for each type. However, be sure to at least distinguishERROR from the rest of the sound types.

The porting interface is defined in the anc_audio.h file in the directorymidp/src/highlevelui/annunciator/include/. It is defined asanc_play_sound (int soundType).

Tip – You can also use the Mobile Media API (MMAPI) if you plan to port it. Whenyou are done porting MMAPI, you can take advantage of its capabilities and have aricher sound for Alerts. You can start by removing the native porting interface andcalling the MMAPI sound API in Display.jpp in the following directory:midp/src/highlevelui/lcdui/reference/classes/javax/microedition/lcdui

Be careful regarding how many channels you intend to occupy as a platform usuallysupports a limited number of audio channels at any given time.

Vibrate and Backlight GroupThe platform-specific functions for the vibrate and backlight group are described inthis section.

Backlight Control MethodsDevices that support display illumination can provide MIDlets with the ability toflash the device’s light source through the Display.flashBacklight methoddefined in the MIDP 2.0 specification.

Backlighting Porting InterfaceThe low-level graphics and images subsystem accesses the device’s backlightthrough the interface defined in the anc_indicators.h file in the directorymidp/src/highlevelui/annunciator/include. The required functioninterface, anc_show_backlight, is shown in example CODE EXAMPLE 10-1:

108 Architecture and Design Guide • December 2008

Page 135: Architecture and Design Guide by Oracle

This is the only method that must be implemented for the backlight control to besupported by a new platform.

Strategies for Porting BacklightingThe implementation code for the backlight function is in theanc_model_indicator.cpp file in themidp/src/highlevelui/annunciator/platform_model/native directory. It usesdevice-specific library methods to toggle the backlight. Changing theimplementation to use the backlight control APIs of the new device is all that isrequired when porting this feature of MIDP to a new target platform.

If the target device does not have a backlight or if control of the light from a Javaprogramming language application is not desired on the system, implement theanc_show_backlight method and return KNI_FALSE as shown inCODE EXAMPLE 10-2:

CODE EXAMPLE 10-1 midpLCDUIShowBacklight Interface

/**

* Control the device’s backlight. Turn it on or off,

* toggle it, or check to see if control of the backlight

* is supported by the system without changing the light’s

* state.

*

* @param mode BACKLIGHT_ON to turn on the backlight,

* BACKLIGHT_OFF to turn off the backlight,

* BACKLIGHT_TOGGLE to toggle the backlight, and

* BACKLIGHT_IS_SUPPORTED to see if the system

* supports this function without changing the

* state of the backlight. <code>mode</code>

* values not listed above are ignored.

* @return KNI_TRUE if the device supports backlight

* control or KNI_FALSE otherwise

*/

jboolean anc_show_backlight(int mode)

Chapter 10 Low-Level Graphics and Images Services 109

Page 136: Architecture and Design Guide by Oracle

Backlighting DurationFew devices have system interfaces for illuminating or flashing screen lighting for aset duration. Because of this, the interface to the backlight is defined as a simpletoggle. Brightness of the on state of the display light is left to the platform, andtiming of the flash frequency or duration of illumination is done in the higher-levelJava platform library code.

If the native timing of the flash rate or the duration of the call is desired, or if it isprovided by a system API, the code from the Java platform layer for the backlightcontrol can be removed to reduce code size. You can find this code in thecom.sun.midp.lcdui.DisplayDeviceAccess class, which deals with timing theon and off toggles of the backlight.

Vibration Control MethodsSystems that vibrate as a user alert mechanism can provide MIDlets the ability tocontrol the device’s vibrator through the Display.vibrate method.

Vibration Porting InterfaceThe low-level graphics and images subsystem accesses the system’s vibratemechanism through the interface defined in the anc_vibrate.h file in the directorymidp/src/highlevelui/annunciator/include. The two necessary functioninterfaces anc_stop_vibrate and anc_start_vibrate are shown in thefollowing code examples:

CODE EXAMPLE 10-2 midpLCDUIShowBacklight Interface Without Backlight Control

/**

* An example anc_backlight implementation for a device

* that does not support backlight control.

*/

jboolean anc_show_backlight(int mode) {

(void) mode;

return KNI_FALSE; //not supported: always return false

}

110 Architecture and Design Guide • December 2008

Page 137: Architecture and Design Guide by Oracle

These are the only methods that must be implemented for the Java platform vibratecontrol to be supported on a new platform.

Vibration SupportThe system libraries to access vibration support on some devices might not exactlymatch the porting APIs. If they provide simple on and off or toggle support of thesystem vibrator, the cycle duration tracking can be handled with a wrapper of nativetimer code around the vibrate API. For an example of timer support written in theJava programming language, see the flashBacklight code in the classcom.sun.midp.lcdui.DisplayDeviceAccess.

CODE EXAMPLE 10-3 Starting Vibration

/**

* Vibrate porting function: Stop vibration.

*

* Platform must stop the vibration at once when

* this function is called.

* @return KNI_TRUE when the system supports

* vibrate control via this function,

* KNI_FALSE otherwise

*/

extern jboolean anc_stop_vibrate(void);

CODE EXAMPLE 10-4 Stopping Vibration

/**

* Vibrate porting function: Start vibration.

*

* Platform must start the vibration at once when

* this function is called.

*

* @param duration duration of the vibrate period.

* @return KNI_TRUE when the system supports

* vibrate control via this function,

* KNI_FALSE otherwise

*/

extern jboolean anc_start_vibrate(int duration);

Chapter 10 Low-Level Graphics and Images Services 111

Page 138: Architecture and Design Guide by Oracle

Network IndicatorThe platform must provide users with some type of visual indication of the networkusage when using the transport mechanisms specified in the MIDP 2.0 specification.

The specification does not mandate how this visual indication must be implemented.It is up to the platform to use the most effective means available to indicate anynetwork activity in a user-friendly manner. This could be done either as an icon onthe device’s display or by other visual means, such as controlling an LED on thedevice, if available.

Controlling whether or not to compile the network indicator code is easy in JavaWireless Client software. If your platform’s networking call already controls anindicator of some kind, you can simply set the property USE_NETWORK_INDICATORto false in the makefile located in installDir/build/platform-model/Options.gmk.Code relating to the network indicator is not compiled. Otherwise, you can use yourplatform’s own implementation for the network indicator. The interface can befound in the header file, anc_indicators.h in the workspace. Look for thefollowing text:

void anc_set_network_indicator(MIDPNetworkIndicatorState status);

The network indicator has three states: indicator on, indicator off, and toggle. Besure that the platform’s implementation checks the status and sets the indicator tothe correct state.

Tip – Even when in full-screen mode, it is the platform’s responsibility to provideusers with a visual indication of network usage.

Porting StrategiesFollow these general strategies for porting the low-level graphics and imagessubsystem:

■ Port incrementally. Work on each porting area one at a time. Do not try to port allthe functions simultaneously, which makes debugging difficult.

■ Port by example. You can start by looking at the Java Wireless Client softwareports for the Microsoft Windows platform and the Texas Instruments OMAP730development board included in the release.

■ Verify each step. Create some simple demonstrations. For example, create aMIDlet that draws a fill box using the whole screen area. Use these small demosto verify each step during the porting process.

112 Architecture and Design Guide • December 2008

Page 139: Architecture and Design Guide by Oracle

When you create the demonstration MIDlets, make sure they use only thosefeatures that have already been ported, such as the CLDC and the Basic SystemEvent.

Porting IssuesThis section discusses the following porting issues:

■ Porting verification

■ Error checking

■ Boundary cases

■ Performance tuning

Porting VerificationTo verify that your porting operation is successful and completed correctly, you canperform the following actions during the porting process:

■ Use some simple MIDlets to validate correct behavior

■ Use some of the interactive TCK tests on low-level graphics and Images

Error CheckingError checking routines are usually run prior to calling the porting API. Therefore, itis not necessary for the porting implementation to check for all error conditions. Forexample, in the porting API for drawing rectangle, gxpport_draw_rect, you donot need to check if the width or height is less then zero as the calling routinealready checks them. Refer to the header file for a detailed explanation andassumptions, if any.

Note, however, that if you directly implement the Java programming languageinterface, rather than using the porting API, you must check for errors passed fromthe Java platform layer.

Boundary CasesA mismatch between the MIDP coordinate system and your platform might occur.Pay special attention to those boundary cases where the parameters being passed inhave the values 0, 1, 2, or negative numbers. For example, your platform rectangle

Chapter 10 Low-Level Graphics and Images Services 113

Page 140: Architecture and Design Guide by Oracle

drawing routine might not draw anything when the height and width parametersare both 1 (that is, your platform coordinate system is inclusive). However, MIDPspecifies that a single pixel might be affected.

Performance TuningTo provide optimal graphics performance, the platform must provide a one-to-onemapping of APIs among low-level graphics drawing routines in the native platform,if possible. Ideally, a single call in the Java platform layer of a line drawing onlyrequires one KNI call into the native layer. It then calls the platform functiondirectly.

Consider reimplementing your platform library to add libraries that directly matchthose in the porting APIs (or directly map to the MIDP API) as it substantiallyincreases your platform’s performance and reduce the porting effort.

114 Architecture and Design Guide • December 2008

Page 141: Architecture and Design Guide by Oracle

11

Implementing the High-Level UIUsing Adaptive User InterfaceTechnology

This chapter describes how to port the high-level user interface using Adaptive UserInterface Technology software (AUI Technology software).

AUI Technology software (formerly known as project Chameleon) is a Javatechnology-based user interface implementation that allows for extensive visualcustomization and visual skinning. AUI Technology software is used to rapidlydeploy a high quality MIDP LCDUI implementation that closely mimics yourdevice’s native look and feel. This allows a deployment to forego the expensiveprocess of porting LCDUI to the device’s native platform. AUI Technology softwareallows user interface components such as the title bar, screen background, softbuttons, and higher-level components to be skinned in a way that closely resemblesthe device’s native counterparts. The end result is a user interface in which Javatechnology applications are nearly indistinguishable from the device’s nativeapplications.

AUI Technology software saves time and effort in reaching compliance with theMIDP 2.1 specification, and saves time with quality assurance and performancetesting.

DesignAUI Technology software is implemented in the following Java programminglanguage class packages:

■ javax.microedition.lcdui.*

■ com.sun.midp.chameleon.*

Chapter 11 Implementing the High-Level UI Using Adaptive User Interface Technology 115

Page 142: Architecture and Design Guide by Oracle

The javax.microedition.lcdui.* package contains the implementation of theMIDP LCDUI components such as Gauge, ChoiceGroup, and StringItem. AUITechnology software handles the rendering of these components and allows you toeasily configure the look and feel of the components by setting properties. Thecom.sun.midp.chameleon.* package contains the foundation AUI Technologysoftware implementation.

The chameleon class package is organized in the following manner:

■ com.sun.midp.chameleon

This is the top-level chameleon implementation package. In general, thispackage contains only high level screen constructs, such as basic layers, windows,and the paint logic for those objects.

■ com.sun.midp.chameleon.input

This package contains the chameleon text input support classes as well as thechameleon default input method implementations, such as numeric,alphanumeric, and symbol.

■ com.sun.midp.chameleon.layers

This package contains the chameleon concrete layer implementations, such asSoftButtonLayer, TitleLayer, and TickerLayer. These layers are combined to form awindow, such as the MIDPWindow class.

■ com.sun.midp.chameleon.skins

This package contains the skin definition classes. A skin class for each skinnableentity exists in AUI Technology software. Each class defines the skin’s properties,what they do, and their possible values. A good way to understand AUITechnology software’s capabilities is to read the API documentation for thispackage.

■ com.sun.midp.chameleon.skins.resources:

This package contains the resource classes associated with each skin in the skinspackage. The resource classes define property identifiers that the skin classes useto retrieve resource values from the system. This package also contains the fileskin.xml, which contains values for all the resource identifiers in the system.Properties configured in this file are ROMized at build time by theSkinROMizationTool. The SkinROMizationTool generates a file calledRomizedSkin.java. Never edit RomizedSkin.java directly.

For more information on the skin.xml file, see the Sun Java Wireless ClientSoftware Skin Author’s Guide to Adaptive User Interface Technology.

For more information on the SkinROMizationTool, see the Sun Java WirelessClient Software Tools Guide.

116 Architecture and Design Guide • December 2008

Page 143: Architecture and Design Guide by Oracle

CustomizationAUI Technology software provides for a great deal of customization through theconfiguration of properties. The complete list of properties and their functions canbe found in the Skin Author’s Guide to Adaptive User Interface Technology. This sectiondescribes how and where to apply property changes.

Property Loading and Skin CustomizationThe AUI Technology software is designed to support dynamic skin changes,allowing the user to change the look of the device on the fly. However, currently,AUI Technology software only supports a single static skin that mimics the device’snative look and feel.

Skin properties are compiled statically at build time. Although this can be timeconsuming, system startup performance is greatly enhanced by having theproperties compiled at build time and not read from an external property file eachtime the VM is started.

The configurable AUI Technology software properties can be found in followingdirectory:

midp/src/highlevelui/lcdlf/lfjava/classes/com/sun/midp/chameleon/skins/resources

Modify the file named skin.xml inmidp/src/configuration/configuration_xml/platform/ to customize theadaptive user interface default skin. After reading and understanding the SkinAuthor’s Guide to Adaptive User Interface Technology, you can apply changes to theskin.xml file. The system must then be rebuilt to test those changes.

Image Usage and SupportThe skinning functionality in AUI Technology software has extensive and flexiblesupport for images. Images can be in any format supported by the image decoder,such as PNG, and raw. Images can be loaded at runtime from the file system orROMized into the deployment bundle and used directly out of memory. Thefollowing sections describe advantages and disadvantages to each of theseapproaches.

Chapter 11 Implementing the High-Level UI Using Adaptive User Interface Technology 117

Page 144: Architecture and Design Guide by Oracle

Compressed Images Compared With UncompressedImagesA trade off between speed and size must be made when processing images.Compressed images (such as PNG and raw images) can be used in AUI Technologysoftware but they require decoding at startup, which imposes a performance penalty.Uncompressed images (such as raw platform format, and bmp) can also be used, butthese formats create a much larger footprint on disk or in the ROM image.

If resources permit, performance is improved by using an uncompressed format andtiling images using small image tiles.

Typically, the port stores the skin’s images in the platform’s native format. This wayno time is spent decoding images when they are loaded, regardless of whether theyare stored in the file system or in the ROM image itself.

ROMized Images Compared With File System ImagesAs mentioned previously, AUI Technology software supports the loading of imagesfrom either the local file system or directly from the ROM image. One advantage ofusing the local file system is that during development, images can quickly bereplaced for testing without rebuilding the ROM image. However, if the systemsupports the creation of images using memory directly referenced in the ROMimage, ROMizing the images in the platform’s native format provides the bestperformance. This option requires more storage space because the image data isuncompressed and stored entirely in the ROM image. Uncompressed ROMizedimage data is typically much larger, but if sufficient storage is available, theperformance gain is well worth the trade-off.

Another aspect to consider is the types of memory being used by the platform. Thefile system might be implemented on slow flash memory, while the ROM image islocated in faster memory. The opposite may also be true. It is possible that readingand decompressing an image from fast memory is faster than reading anuncompressed image from slow memory.

Storing Image Resources in the File SystemImages stored on the file system can be in PNG or raw formats. When you assign animage to an AUI Technology software property in skin.xml, the image name isspecified without an extension. When the AUI Technology software loads an imageat runtime, it first attempts to load this image from the ROM image. If the loadattempt fails (because the image is not ROMized), AUI Technology software addsthe .png extension to the image name specified in skin.xml, and then tries to loadthe file with that name. If image is again not loaded successfully (because the file is

118 Architecture and Design Guide • December 2008

Page 145: Architecture and Design Guide by Oracle

not found), the AUI Technology software adds the .raw extension to the imagename and attempts to load the file again. If the file is not successfully loaded, anerror occurs. To summarize, the AUI Technology software tries to load images usingthe name specified in skin.xml in the following order:

1. From the ROM image

2. From the file system with the .png extension appended

3. From the file system with the.raw extension appended

Java Wireless Client software includes a tool named ImageToRawTool that you canuse to convert PNG images to raw platform-specific image formats. See the ToolsGuide for more information about ImageToRawTool.

By default, PNG and raw images used by the AUI Technology software are stored inthe midp/src/highlevelui/lcdlf/lfjava/resource/skin directory. Duringthe build, they are copied into the output/lib directory and are loaded from thereat run time. You can choose a different directory path in which to store the imagesby specifying it as the value of the SUBSYSTEM_LCDLF_SKIN_RESOURCES_DIRmakefile variable from the command line.

Note – The directory path must be specified as an absolute path name.

Storing Image Resources in the ROMFor SkinRomizationTool to ROMize an image during the build, the PNG image(with .png extension) must be present in themidp/src/highlevelui/lcdlf/lfjava/resource/skin directory. ImageROMization is controlled by the Romize attribute in skin.xml. If an image’sRomize attribute is set to false, then the image is not ROMized during the buildand will be loaded at run time from the file system. If the image’s Romize attributeis set to true is not ROMized during the build and is loaded at run time from theROM image. See the Skin Author’s Guide to Adaptive User Interface Technology for moreinformation about SkinRomizationTool.

As part of the build, SkinRomizationTool loads the PNG images, converts theminto raw format (conversion is done in memory, so no .raw file is generated to thefile system), and then generates the lfj_image_rom.c file into theoutput/generated directory that contains the ROMized image data. Later in thebuild process lfj_image_rom.c is compiled with other source files.

Chapter 11 Implementing the High-Level UI Using Adaptive User Interface Technology 119

Page 146: Architecture and Design Guide by Oracle

RAW Format Platform SpecificationBecause platform graphic toolkits represent RAW image data differently, theSkinRomizationTool must know into which format it must convert images.Specify the RAW format in the file rawimage.xml located in the same directory asskin.xml. The file contains a single element named rawimage that has thefollowing three attributes: Format, Colors, and Endian.

Format Attribute

The value of the Format attribute specifies how the alpha, red, green, and bluecomponents of each pixel are represented. The currently supported values are ARGBand Putpixel.

In the ARGB representation, the pixel color components are arranged in thefollowing order: Alpha, Red, Green, Blue.

The ARGB representation is used in the linux_qte port because it is the formatused by the Qt graphic library.

The Putpixel representation corresponds to the pixel representation used in the JavaWireless Client software PutPixel graphic library. It is used in the linux_fb andwin32 ports.

Colors Attribute

The value of the Colors attribute specifies the number of bits used to represent thered, green and blue components (the alpha component is always an 8-bit value). TheJava Wireless Client software supports the values 888 and 565. The value 565specifies that each pixel representation allocate five bits for red, six bits for green,and five bits for blue. The 888 value specifies that each pixel representation allocateeight bits for red, eight bits for green, and eight bits for blue.

Endian Attribute

The value of the Endian attribute specifies which endian format the target platformuses. The possible values are Little and Big, where Little specifies that wordsstart with the least significant byte, and Big specifies that words start with the mostsignificant byte.

120 Architecture and Design Guide • December 2008

Page 147: Architecture and Design Guide by Oracle

This release of Java Wireless Client software does not support all combinations ofattribute values. The following combinations are supported in this release of JavaWireless Client software.

■ ARGB, 888, Little

■ ARGB, 888, Big

■ Putpixel, 565, Little

■ Putpixel, 565, Big

Because the RAW format is platform dependent, not all RAW variations aresupported. If your platform does not use one of the supported combinations, youmust add this support by modifying the following file:

midp/src/tool/imageutil/classes/com/sun/midp/imageutil/ImageToRawConverter.java

Support for Virtual KeyboardThe virtual keyboard allows the porting engineer leeway in defining the look andlayout of this feature. The graphical elements of the virtual keyboard are defined bythe keyboard_skin.xml file. For more information on the keyboard_skin.xmlfile, see the Skin Author’s Guide to Adaptive User Interface Technology.

The virtual keyboard feature is implemented by setting a variable at build time. Formore information on building the virtual keyboard, see the Build Guide.

A porting engineer can change many elements of the virtual keyboard. This is doneusing the Keyboard class and making modifications to the Keyboard.java file.

Porting StepsThe following high-level steps describe the process typically used for porting AUITechnology software. For more information, and for the specific procedural stepsused to port the Java Wireless Client software using the JavaCall porting layer, seethe Sun Java Wireless Client Software Porting Guide.

1. Define the screen sizes in the constants.xml file in the configuration, as wellas any other AUI Technology software specific constants.

All of the following AUI Technology software constants begin with the CHAM_prefix.

Chapter 11 Implementing the High-Level UI Using Adaptive User Interface Technology 121

Page 148: Architecture and Design Guide by Oracle

■ CHAM_USE_IMAGES (boolean)

When false, AUI Technology software does not attempt to load and use imageresources. This is useful for early ports when image support in low-levelgraphics might not be implemented yet.

■ CHAM_ROMIZED_IMAGES (boolean)

When false, AUI Technology software does not attempt to load imageresources from the ROM image and only attempts to load the resources fromthe file system. Set this value to true if you ROMized some or all of AUITechnology software’s image resources.

■ CHAM_WIDTH (int)

The width, in pixels, allotted on the display for AUI Technology software todisplay its screen contents.

■ CHAM_HEIGHT (int)

The height, in pixels, allotted on the display for AUI Technology software todisplay its screen contents.

■ CHAM_FULLHEIGHT (int)

The height, in pixels, allotted on the display for AUI Technology software todisplay its screen contents when in fullscreen mode. This might or might notbe greater than the CHAM_HEIGHT value. For example, the device might givemore pixels to AUI Technology software to show more of a game screen.

2. Port system events.

Prior to porting AUI Technology software, it is important to have a working eventprocessing service. Key press events must work correctly to test the AUITechnology software. For information about porting the event processing service,see Chapter 13 in this guide, and the Sun Java Wireless Client Software PortingGuide.

3. Port low-level graphics.

AUI Technology software relies on a functional low-level graphicsimplementation. This means that the primitive drawing functions - for example,drawLine(), drawRect(), and fillRect() in Graphics.java - must befunctional. It is possible to run the system without Image.java and thedrawImage() functions being implemented during a port’s initial stages. AUITechnology software resorts to solid fill colors when images are either notavailable or not implemented. You can use this characteristic to get visualfeedback about how the system is running prior to implementing image support.

122 Architecture and Design Guide • December 2008

Page 149: Architecture and Design Guide by Oracle

4. Port the predictive input library.

By using predictive text input, users can enter words often with a single key pressfor each character. For example, to enter the word “how,” user can press the 4, 6and 9 keys, eliminating the need for the extra key presses (4, 4, 6, 6, 6, 9) requiredin standard text entry mode. Predictive text is an input mode similar to thefollowing other modes:

■ Uppercase text entry

■ Lowercase text entry

■ Numerical text entry

■ Foreign language text entry

Use of the predictive text input mechanism is not mandatory for Java Technologyfor the Wireless Industry compliance. The predictive text API assumes that thehandset device already has dictionary functionality, and the API is used to exposethe dictionaries for use by the Java platform.

5. Review the Skin Author’s Guide to Adaptive User Interface Technology and chooseappropriate property and image values for the platform.

The AUI Technology software release includes default values and images that youcan use early in the porting process. After you have the software working, changethe property and image values to apply the device’s native look and feel to Javaplatform applications.

Note – Be sure to change the images in themidp/src/highlevelui/lcdlf/lfjava/resource directory and not in theoutput/lib directory. Images are copied to output/lib during the build andimages in that directory are overwritten.

Note – If you ROMize all image resources on your platform, remove them from themidp/src/highlevelui/common/resource directory so they are notunnecessarily duplicated in the file system when you deploy your bundle.

6. Build Java Wireless Client software.

Once you are able to build AUI Technology software and it works properly, youcan decide whether or not to tune the port’s image components. For example, allimages can be ROMized if file system support is not yet functional. Also, youmight initially use a compressed format and then later switch to an uncompressedformat to improve performance.

See the Sun Java Wireless Client Software Build Guide for more information aboutbuilding Java Wireless Client software.

Chapter 11 Implementing the High-Level UI Using Adaptive User Interface Technology 123

Page 150: Architecture and Design Guide by Oracle

124 Architecture and Design Guide • December 2008

Page 151: Architecture and Design Guide by Oracle

12

Implementing the High-Level UIUsing Platform Components

This chapter describes how to port the high-level user interface using the nativeplatform’s GUI components to provide a unified user interface library. The methodof porting described in this chapter requires much more time and effort than usingAUI Technology software as described in Chapter 11. Only use this method if AUITechnology software is not appropriate for your platform.

This chapter is intended to be used as an adjunct to the API documentation shippedwith Java Wireless Client software.

OverviewThe MIDP specification requires that a specific set of high-level GUI components beavailable for constructing the graphical user interface. Java Wireless Client softwareprovides services that help in the construction of these MIDP components. JavaWireless Client software constructs the full complement of MIDP components from asimpler set of platform components specified in the Java Wireless Client software high-level UI porting interface specification. The platform components are constructedfrom basic components provided by the platforms’s native operating system library.

You are responsible for creating a platform component adapter for each platformcomponent required by the Java Wireless Client software high-level UI portinginterface specification. The Java Wireless Client software constructs the MIDPcomponents using the platform component adapters. Because you write the platformcomponent adapters directly on your platform, you do not have to take the time tounderstand the internal functionality of the Java Wireless Client software.

FIGURE 12-1 shows the major elements of the high-level UI in a Java Wireless Clientsoftware port.

Chapter 12 Implementing the High-Level UI Using Platform Components 125

Page 152: Architecture and Design Guide by Oracle

FIGURE 12-1 Major Elements of the High-Level UI in a Java Wireless Client SoftwarePort

The porting interfaces are defined by a set of header files. The following two sets offunctions are defined:

■ Porting functions that you must implement based on the OS component library.These are called platform component adapters.

■ Callback functions provided by Java Wireless Client software for communicatingwith the Java platform. For example, user input can be converted to Java eventsby calling midpStoreEvent().

See the Native API reference for the list of header files that define the porting API.

Component DependenciesMany components depend on other components. For example, a List component isconstructed from the ChoiceGroup and Form components. This means that youneed to adopt a strategic approach to the porting process by creating constituentparts in the right order to create more complex components.

Also consider the requirements that other crucial parts of the system have forvarious GUI components. For example, the low-level graphics and images servicesand the AMS both require the Canvas component. Therefore, before you cancompletely port and test the AMS, you must implement the Canvas component. Inmany cases, a component’s functionality need not be fully implemented to satisfythe dependency.

Displayable look and feelimplementation (Java platform code)

Displayable(Java platform code)

Platform component adapter

OS component library

Displayable native peer(C code)

Porting interface

Native platform(Native code)

Java Wireless Clientsoftware

126 Architecture and Design Guide • December 2008

Page 153: Architecture and Design Guide by Oracle

FIGURE 12-2 shows the high-level GUI components and the components on whichthey depend.

FIGURE 12-2 High-Level GUI Components and Dependencies

Porting StepsFollowing are some strategic guidelines you can use during your port:

■ Be sure that the event system and the low-level graphics system are ported andworking before you port the high-level GUI components.

■ Implement the components iteratively.

• Label• Highlight (focus)• Focus• User input

ChoiceGroup

1 2

DateField Gauge String

ItemImageItem

CustomItem

Spacer

Canvas

MenuSoftButton

DateEditor Item

Alert

Form

TextBoxList

3 4

5 6 87

TextField

(Porting notrequired)

Chapter 12 Implementing the High-Level UI Using Platform Components 127

Page 154: Architecture and Design Guide by Oracle

■ Constituent components need not always be ported completely. Implement asmuch functionality as required to implement higher-level components. After youimplement higher-level components, return to finish the lower level components.This makes components available so that the porting of multiple components canproceed in parallel.

The following high-level steps describe the order in which a typical port mightproceed. The steps correspond to the numbers shown in FIGURE 12-2.

1. Implement the Canvas component.

The Canvas component is used to paint low-level graphics on the screen. Thelow-level graphics and images service and the AMS depend on the Canvascomponent.

The Canvas component depends on the SoftButton component because it mustbe able to map abstract commands to soft buttons. The Canvas component alsodepends on the Menu component because when an application uses a largenumber of abstract commands they are contained in a menu.

2. Implement the List component.

List is the most commonly used component and is used by the AMS. Theconstituent components (ChoiceGroup and Form) do not have to be completelyimplemented to support the List component. For example, the List componentonly requires single-item selection, so you can implement multiple-item selectionin the Form component later.

The following steps describe the order in which a typical port may proceed.

a. Implement the Item component.

The ChoiceGroup components requires basic Item component functionality.If it has not already been implemented you must implement the Itemcomponent now.

b. Implement the ChoiceGroup component.

The List component is implemented as a Form with a single ChoiceGroup.

c. Implement the Form component.

The Form component is the container for the ChoiceGroup component. Whileimplementing the Form component, be sure to implement the required Itemcomponent functionality.

3. Implement the TextBox component.

The TextBox component is used to enter URLs during over-the-air (OTA)installation. The TextBox component only requires single-item selection, so youcan implement multiple-item selection in the Form component later.

The following steps describe the order in which a typical port can proceed.

128 Architecture and Design Guide • December 2008

Page 155: Architecture and Design Guide by Oracle

a. Implement the Item component.

If you have not already implemented the Item component, implement it now.

b. Implement the TextField component.

The TextBox component is implemented as a form with a single text field.

c. Implement the Form component.

If you have not already implemented the Form component, implement it now.

4. Implement the Alert component.

Alerts are required by the AMS and the runtime security service.

The following steps describe the order in which a typical port may proceed.

a. Implement the Alert component with text content only.

Start by supporting simple text content.

b. Add support for image content.

Add the ability for the Alert to contain images.

c. Add support for the Gauge component.

Because the Gauge component depends on it, if you have not alreadyimplemented the Item component, implement it now.

5. Implement the StringItem component.

StringItem components are commonly used to construct complex Forms andare usually used for descriptive purposes.

Keep the following in mind while implementing the StringItem component:

■ StringItem components must be flexible. You must be able to lay them outcontinuously to fill the width of the screen.

■ The StringItem component must be able to accommodate different fontsizes.

■ The StringItem component must be displayable as both a button and as flattext. If your platform supports the display of flat buttons, you can unify theimplementation of the StringItem and Button components.

6. Implement the ImageItem component.

Implementing the ImageItem component is similar to the StringItemcomponent. One significant difference is that there are far fewer sizing constraintsbecause the dimensions of images are known.

If your platform supports the display of an image in a Button, you can unify theimplementation of the StringItem and button components.

Chapter 12 Implementing the High-Level UI Using Platform Components 129

Page 156: Architecture and Design Guide by Oracle

7. Implement the DateField component.

The DateField component is used to display and set dates and times.

The following steps describe the order in which a typical port can proceed.

a. Implement functionality to display a specified date and time.

b. Implement the DateEditor component.

The DateEditor component provides users with the means to change datesand times.

8. Implement the CustomItem component.

The CustomItem component provides a paintable Item component inside aForm.

The following steps describe the order in which a typical port can proceed.

a. Implement the off-screen buffer.

b. Implement capture functionality.

The CustomItem component must be able to capture user input events anddeliver them to the Java platform. Java Wireless Client software providescallback functions to deliver these events.

c. Visibility tracking and notification.

The CustomItem component must notify the Java platform when it becomesvisible or invisible because it is scrolled on or off the screen.

TestingIt is best to test your port as it progresses. Write your tests as MIDlets that testspecific component functionality, rather than a broad spectrum of components andfunctionality. The MIDP Reference Implementation includes MIDlets that exercisehigh-level UI functionality and can be used for testing. See the documentationincluded with the MIDP Reference Implementation for details.

If your device supports command-line input from a terminal, port the runMidletutility so that you can run MIDlet tests without full AMS functionality.1 TherunMidlet utility allows you to run an arbitrary MIDlet class directly from thecommand line. The following example shows the syntax for the runMidlet utility.CODE EXAMPLE 12-1 runMidlet Utility Syntax

1. Java Wireless Client software includes versions of runMidlet that work on the Linux operating system andthe Microsoft Windows operating system.

runMidlet -classpathext midlet.jar internal class_name

130 Architecture and Design Guide • December 2008

Page 157: Architecture and Design Guide by Oracle

If your device does not support terminal input, your platform’s AMS can callmidpRunMidletWithArgsCP() to run MIDlet tests. See the midp.h API referencedocumentation for details.

After your port is fully functional and stable, you can use the Java Technology forthe Wireless Industry TCK and any other available test suites to further test thehigh-level UI.

Chapter 12 Implementing the High-Level UI Using Platform Components 131

Page 158: Architecture and Design Guide by Oracle

132 Architecture and Design Guide • December 2008

Page 159: Architecture and Design Guide by Oracle

13

Porting the Event Processing Service

The event processing service enables a device’s native code to convert native eventsto a format that the Java platform event (Java event) system can understand. Ideally,an event is delivered to a Java platform object (Java object) by calling a method on it,however, this is not possible because the event originates from native code, andbecause CLDC HotSpot Implementation has no facility that enables native code tocall methods on Java objects. Instead, the native code places the native event into anevent queue. A Java thread calls into native code to retrieve the event from the eventqueue.

This chapter describes the native interfaces to the event queue. This chapter alsodescribes flow-of-control issues that determine when native code can place eventsinto the queue and when Java threads can remove events from the queue.

MIDP must be able to receive events from outside the Java platform. The way thatMIDP receives events depends, in part, on how the VM is invoked. See Section 10.4“Invoking the Virtual Machine” in the CLDC HotSpot™ Implementation Porting Guidefor information about invoking the VM.

The central issue regarding event delivery is control flow, which is highlighted bythe following questions:

■ How many native threads are running?

■ Which thread receives events?

■ Which thread runs the VM?

■ Does the system call MIDP to deliver events or MIDP query the system forevents?

The event processing service collects events from the native system in an eventqueue. These native events are converted into Java events, merged with a stream ofevents that originates from the Java layer, and are placed into a unified event queue.Events are processed one at a time. The processing of one event is always completedbefore the processing of the next event begins. This satisfies the event serialization

Chapter 13 Porting the Event Processing Service 133

Page 160: Architecture and Design Guide by Oracle

requirements of the MIDP LCDUI package. Serial event processing is also useful formanaging multi-threaded control flow that occurs in various portions of theimplementation.

Multiple Java threads handle control flow by posting events. The event stream fromthe native event queue and event stream from the Java platform are interleaved intoa unified Java event queue. The unified event queue is processed by a single Javathread.

Other subsystems that block threads, such as networking, multimedia, and WMA,cooperate with this service in conserving battery power when the VM is idle. Havethe subsystems register for an event instead of waiting until some external statechanges. This allows the VM to go to sleep waiting for the event, reducing CPUusage and thus conserving battery power.

Event SystemFIGURE 13-1 shows an overview of what happens when Java Wireless Client softwareprocesses an event.

134 Architecture and Design Guide • December 2008

Page 161: Architecture and Design Guide by Oracle

FIGURE 13-1 Event Queue Components and Interactions

The following steps describe the numbers shown in FIGURE 13-1:

1. The native event monitor (NEM) thread waits for a native event.

The NEM thread is a Java thread that monitors the arrival of native events.

2. The native system submits an event.

This is where your porting effort is focused and is described in more detail in“Submitting Native Events” on page 136 below.

3. The NEM thread wakes up.

4. The NEM thread converts the native event to a Java object and places the eventin the Java event queue.

5. The event dispatch thread processes the Java event.

The event dispatch thread pulls the next event from the event queue and choosesan event listener based on the type of event.

6. The event dispatch thread calls the appropriate event listener for thedispatched event.

Native events

Native event queue

Java eventqueue

Java events(repaint) Native event monitor

(Java thread)

1 3

2

Event dispatchthread

Event listeners

5

4

6

Native events

Chapter 13 Porting the Event Processing Service 135

Page 162: Architecture and Design Guide by Oracle

▼ Submitting Native EventsThe preceding section describes the entire event processing service. You areresponsible for implementing Step 2 (submitting native events). The following stepsdescribe the step-by-step functionality that your code must provide:

1. Declare a midpEvent data structure.

2. Use the MIDP_EVENT_INITIALIZE macro to initialize the midpEvent datastructure.

3. Complete the fields of the midpEvent data structure.

This is described in more detail in “Complete the Event Fields” on page 136.

4. Call the StoreMIDPEventInVmThread function to store the event in the eventqueue and to wake up the NEM thread.

The native event queue must be thread safe if multiple native threads have accessto it. To ensure that multiple access does not corrupt the queue, a locking systemis required. This is described in more detail in “Locking” on page 137.

5. Wait for the next native event.

How you wait is determined by your platform.

Note – The data structures and functions that you need to call are described in theNative API Reference. Refer to the section that describes midpEvents.h.

Complete the Event FieldsThe MidpEvent data structure is a C struct with several integer and stringfields. There are enough fields of each type to accommodate events that can occur inmost systems. Platform-specific event code transforms information received from theplatform by setting particular fields of the MidpEvent data structure. The type fieldof the event must always be set. For the other required fields, the meaning of thedata depend upon the particular event type. For example, the code sample shown inCODE EXAMPLE 13-1 shows a pen event being submitted into the native event queue.

CODE EXAMPLE 13-1 Code Completing a MidpEvent Data Structure

void handlePointerEvent(...) {

MidpEvent event;

MIDP_EVENT_INITIALIZE(event);

event.type = MIDP_PEN_EVENT; [defined in midpEvents.h]

136 Architecture and Design Guide • December 2008

Page 163: Architecture and Design Guide by Oracle

LockingOperations on the native event queue can occur on multiple threads, so you mustcreate a facility that protects the event queue from concurrent access. This isaccomplished through an event queue locking API defined in the midpServices.hheader file. This API defines create, lock, unlock, and destroy operations. Thefunctions defined by this API are called by the event queue code in MIDP and mustbe implemented by the platform-specific code.

The locking functions are described in the Native API Reference. Refer to the sectionthat describes midpServices.h, located in the “Misc. System Services” category.

You must implement the following functions:

■ midp_createEventQueueLock

■ midp_waitAndLockEventQueue

■ midp_unlockEventQueue

■ midp_destroyEventQueueLock

The semantics of these APIs are very similar to their equivalent POSIX threads(pthreads), and these functions can be implemented using the correspondingpthread functions:

■ pthread_mutex_init

■ pthread_mutex_lock

■ pthread_mutex_unlock

■ pthread_mutex_destroy

Circumstances exist in which a single thread is responsible for both submittingevents into the event queue and removing them. The VM is the only part of thesystem that removes events from the event queue. If the thread that runs the VM isalso the only thread that submits events into the event queue, it is not possible tohave concurrent access to the event queue. Even in this case, the locking functionsare still called and you must provide implementations of the locking functions, butthey can be empty.

event.intParam1 = PRESSED; [or DRAGGED or RELEASED]event.intParam2 = the x position of the event ;event.intParam3 = the y position of the event ;

StoreMIDPEventInVmThread(evt, 0);

}

CODE EXAMPLE 13-1 Code Completing a MidpEvent Data Structure

Chapter 13 Porting the Event Processing Service 137

Page 164: Architecture and Design Guide by Oracle

Note – It is important to understand that it is only possible to guard againstconcurrent access to the event queue if all of the events are submitted from the samethread. Certain parts of the platform, such as networking or multimedia, mightgenerate events from another thread. If any possibility exists that even a single eventmight be generated from some other thread, then the locking functions must beimplemented to guard against concurrent access.

Setting the MAX_EVENTS ConstantThe MAX_EVENTS constant limits the maximum number of events that can be placedin the native event queue at one time. You can change the value of MAX_EVENTS towork with the speed and memory requirements of your device. See Chapter 4 for thelocation of the MAX_EVENTS constant and instructions on modifying a constant’svalue.

Under most circumstances, events come in at a moderate rate and are processedquickly by the VM. However, if events occur at a high rate, and if the VM is not runfrequently enough or if its time slice is not long enough, events can start to build upin the native event queue. In most cases, the cluster of events lasts briefly. Forexample, if the user drags the pointer across the screen very quickly. The VMeventually catches up and drains the events from the queue. Set the value ofMAX_EVENTS to accommodate the largest expected flurry of events.

Types of Event SystemsThis section discusses the flow of control between the VM and the rest of the nativesystem, and how it interacts with event processing. Please refer to Chapter 10 of theCLDC HotSpot™ Implementation Porting Guide, “Implementing J2ME Profiles,” forinformation on the different modes in which the VM can be invoked, the APIs usedfor processing events, and code samples that illustrate use of these APIs.

Normal ModeIn normal mode, the main processing loop resides within the VM.

Note – Normal mode is often referred to as master mode because it iscomplementary to slave mode described later.

138 Architecture and Design Guide • December 2008

Page 165: Architecture and Design Guide by Oracle

The general flow of control in normal mode is as follows:

1. Platform-specific code initializes.

2. Platform-specific code calls JVM_Start(), which does not return until the VMexits.

3. The VM main loop time slices between Java threads and periodically callsJVMSPI_CheckEvents().

4. JVM_Start() returns when all Java threads exit or when VM termination isrequested.

This flow of control is illustrated in FIGURE 13-2.

FIGURE 13-2 CLDC HotSpot Implementation Running in Normal Mode

Javathread 1Initialization

Native eventcode

Javathread 2

CLDCVM

JVM_Start()

*

* Uses select() or poll() to check the status of pending I/O events, userinterface events, and other events. Unblocks threads as necessary.

JVMSPI_CheckEvents(...)

Chapter 13 Porting the Event Processing Service 139

Page 166: Architecture and Design Guide by Oracle

JVMSPI_CheckEvents() has several responsibilities. It must check for theoccurrence of any event that can possibly occur in the system. Some events, such asuser interface events, must be submitted into the event queue as described in “EventSystem” on page 134. Other events, such as network traffic, are destined for aparticular Java thread. The CheckEvents code must awaken the appropriate threadso that the network traffic can be processed. Finally, if no events are available, thecode must sleep for as long as the VM requests (possibly indefinitely).

For normal mode operation, MIDP provides a platform-independentimplementation of JVMSPI_CheckEvents(). In turn, this implementation relies onplatform-specific code to gather event information for it. This platform-specific coderesides in the checkForSystemSignal() function that you must implement aspart of your porting effort. Its responsibilities are similar to those ofJVMSPI_CheckEvents() but its parameters and return values are different. It mustconvert the event into a MidpEvent structure as previously described. In addition, itmust return information such as a file descriptor to the platform-independent layerso that any Java threads waiting for this event are awakened. This information isreturned in a MidpReentryData structure.

The checkForSystemSignal() function and the data structures it uses aredescribed in the midp_checkSysSignals.h header file.

Slave ModeIn slave mode, the main processing loop resides outside the VM. The general flow ofcontrol in slave mode looks like this:

1. Platform-specific code initializes.

2. Platform-specific code calls JVM_Start(), which returns immediately.

3. Platform-specific code runs a main loop that calls JVM_TimeSlice() to runJava threads for one time slice and checks for any events that occurred in thesystem, awakening Java threads as necessary.

4. The VM terminates when all Java threads exit, or when VM termination isrequested.

5. The platform-specific main loop exits.

The control flow in slave mode is inverted in relation to normal mode. In normalmode, the VM time-slices Java threads and calls platform-specific code periodicallyto check for events. In contrast, in slave mode, the platform-specific code calls theVM periodically and checks for events in between calls to the VM. The event-checking step for slave mode (Step 3) has the same responsibilities thatJVMSPI_CheckEvents() has for normal mode.

140 Architecture and Design Guide • December 2008

Page 167: Architecture and Design Guide by Oracle

Slave mode is necessary in cases where the main processing loop cannot reside inthe VM. An example of this occurs with user interface toolkits such as Qt. In a Qtenvironment, the main loop resides within the member functionQPEApplication::enter_loop(). This function calls Qt callbacks to deliverevents, and it blocks until an event is available.

JVM_TimeSlice() must be called repeatedly for Java threads to make progress. Ina Qt-based system, this can be accomplished by ensuring that an event is alwaysavailable for processing. Events are generated by setting up a timer event for a shorttime (or zero time) in the future. When the the timer event fires, the Qt calls theappropriate callback, which calls JVM_TimeSlice() and then reschedules a timerevent. Handling of events, (for example, for the user interface and the network) arehandled through other Qt callbacks.

This flow of control is illustrated in FIGURE 13-3.

FIGURE 13-3 CLDC HotSpot Implementation Running in Slave Mode

Initialization

*

* User interface events and pending I/O are handled through Qt events. Slothandling code is used to unblock threads.

Qt mainloop Qt object Qtimer

vm_slicer VMJava

thread 1Java

thread 2

JVM_SetConfig(SLAVE_MODE)JVM_Start()

QPEApplication::enter_loop()

JVM_TimeSlice(...)

JVM_TimeSlice(...)

Chapter 13 Porting the Event Processing Service 141

Page 168: Architecture and Design Guide by Oracle

Choosing Normal or Slave ModeThe preceding sections illustrate some of the issues to consider when choosingbetween normal and slave modes.

If your system has a call that reads events from an event queue, it might make senseto run the VM in normal mode. Place a call to the function that reads events in theimplementation of the checkForSystemSignal() function.

If your system controls the main loop and issues callbacks to deliver events, it mightmake sense to run the VM in slave mode. Write callbacks to submit events into theMIDP event queue. In addition, you must employ a technique (such as a timerevent) to ensure that JVM_TimeSlice() is called repeatedly.

For example, in a non-JavaCall implementation,midp_slavemode_schedule_vm_timeslice() can be used to request the VM toschedule a time slice to be executed as soon as possible. Themidp_slavemode_time_slice() method can then be called to execute bytecodesfor that time slice.

On a JavaCall platform, the javacall_schedule_vm_timeslice() can be usedto invoke platform-specific code, such as a timer setup, with the time slice thenexecuted by means of javanotify_vm_timeslice().

Both of these approaches - making system calls into the event queue or usingcallbacks to deliver events - run the entire system in a single native thread. If thesystem can support multiple native threads, it might be possible to run the VM innormal mode in its own native thread. This technique adds complexity because thecoupling between the system’s event processing and the submission of events to theVM using checkForSystemSignal() must be done in a thread-safe manner.However, running the VM in normal mode can provide increased throughput andresponsiveness if the OS can switch threads more quickly than time slices can bescheduled in the slave mode technique.

Note – To implement slave mode in your system, you must build the JavaCall andMIDP components using the SUBSYSTEM_EVENTS_MODULES=slave_mode flag. Formore information, see the Build Guide.

142 Architecture and Design Guide • December 2008

Page 169: Architecture and Design Guide by Oracle

Chapter 13 Porting the Event Processing Service 143

Page 170: Architecture and Design Guide by Oracle

144 Architecture and Design Guide • December 2008

Page 171: Architecture and Design Guide by Oracle

14

Application Management with theJava Platform

This chapter discusses how to port and customize the Application ManagementService (AMS) subsystem. Users interact with the AMS via the graphical userinterface (GUI) on their handset or device. The AMS also manages scheduling andother low-level operations between applications and the virtual machine.

The AMS is responsible for the following services:

■ Installing MIDlet suites

■ Updating MIDlet suites

■ Removing MIDlet suites

■ Displaying information about MIDlet suites

■ Invoking MIDlet suites

■ Managing communication between installed MIDlets

■ Dynamically downloading MIDlet suites

■ Updating MIDlet settings

This section describes the AMS and its interactions with other parts of the JavaWireless Client software.

Note – Although it is related to the AMS, because of its complexity, the pushsubsystem is described in its own chapter (Chapter 15).

Chapter 14 Application Management with the Java Platform 145

Page 172: Architecture and Design Guide by Oracle

Native AMSYou have two choices for integrating Java Wireless Client software with AMSfunctionality: Java AMS or the native AMS.

Java Wireless Client software provides a Java programming languageimplementation of the AMS (referred to as the Java AMS). The bulk of this chaptercovers the Java AMS.

The alternative to the Java AMS is to integrate Java Wireless Client software with anexternal AMS implemented in native code. This is called the native AMS or NAMS.Java Wireless Client software does not provide a NAMS implementation, but insteadprovides a native API (NAMS API) through which the external NAMSimplementation communicates with Java Wireless Client software. This API allowsan external implementation to initiate Java application state changes and to receivenotification when state changes occur.

The NAMS API is fully documented in the Native API Reference in the “NativeAMS” section, in particular in the file midpNativeAppManager.h. The top-levelURL to this area of the documentation is:

doxygen/html/group__nams.html

Note – The NAMS API is not thread safe. Therefore, any calls to the NAMS APImust be on the same native thread that runs the Java virtual machine.

AMS FunctionalityAMS is a catch-all term used to describe the functionality on a device that installs,lists, runs, and removes applications. The AMS is a group of components that can bemodified or replaced individually. For MIDlet suites, the AMS must provide all ofthe application management functionality required by the MIDP 2.1 Specification asshown in TABLE 14-1.

146 Architecture and Design Guide • December 2008

Page 173: Architecture and Design Guide by Oracle

Test and development devices might have the additional functionality shown inTABLE 14-2.

TABLE 14-1 Application Management Functionality

Application Management Functionality Description

Application Manager Interacts with users to manage applicationscurrently installed on the device.

Uninstaller Interacts with users to uninstall applications.Sometimes this functionality is part of theApplication Manager.

Discovery application Enables users to discover new applications toinstall over the air and automatically invokes thegraphical installer when they decide todownload one. The discovery application mightbe the existing web browser on the device.

Graphical installer Interacts with users to install an application overthe air.

Persistent application storage (suitestorage)

Stores applications and their data across multipleuses of the device.

MIDP runtime environment Runs installed MIDlets. This is the device’s Javaruntime environment and Java Wireless Clientsoftware extends it to run system applicationswritten as MIDlets, such as the discoveryapplication and graphical installer.

TABLE 14-2 Additional Test and Development Functionality

Additional Functionality Description

Autotester An application that the TCK testing frameworkuses to install and run sequences of tests withoutuser intervention.

Command-line MIDlet runner A command-line application that runs aninstalled MIDlet. It serves as an example of howto use the run function of the Java WirelessClient software C API.

Chapter 14 Application Management with the Java Platform 147

Page 174: Architecture and Design Guide by Oracle

FIGURE 14-1 shows the interactions of some of the components described in TABLE 14-1and TABLE 14-2.

FIGURE 14-1 AMS Architecture on a Device

Command-line MIDlet suite lister A command-line application that lists MIDletsuites. It serves as an example of how to use thelisting functions of the Java Wireless Clientsoftware C API.

Command-line MIDlet suite remover A command-line application that removesMIDlet suites. It can serve as an example of howto use the removal function of the Java WirelessClient software C API.

Public keystore manager A command-line application that adds andremoves MIDP software CAs to and from thetrusted keystore used by the Java Wireless Clientsoftware installer MIDlets.

TABLE 14-2 Additional Test and Development Functionality

Additional Functionality Description

Application Manager

MIDP RuntimeEnvironmentGraphical Installer

Discovery Application

Autotester

Uninstaller

PersistentApplication Storage

Invoke

Invoke

Invoke

Store andremoveMIDlet

suiteStore

MIDletsuite

Run testMIDlet

RetrieveMIDlet Get and set

MIDletsuite

information

Removesuite

RunMIDlet

suite

148 Architecture and Design Guide • December 2008

Page 175: Architecture and Design Guide by Oracle

External Interactions With AMSTABLE 14-3 shows how the AMS interacts with various Java Wireless Client softwaresystems.

The AMS also provides the following functionality:

■ Authenticates and authorizes signed applications for Java platform installers

■ Performs the following installation services for native and Java platforminstallers:

■ Parses and verifies JAD files

TABLE 14-3 AMS Interaction With Java Wireless Client Software Systems

System Description

Networking Uses HTTP and HTTPS.

Graphical window system Uses the GUI for user interaction.

File system Uses the following standard file system services: create,write bytes, read bytes, truncate, rename, and delete.

RMS Uses the following internal services:• Gets the RMS space used by the given MIDlet suite.• Gets the available space for a MIDlet suite.• Removes a MIDlet suite’s record stores.Note: AMS system MIDlets use standard RMS services.

Java virtual machine Uses the following internal services:• Gets a requested resource from the current MIDlet suite’s

JAR file.• Starts the virtual machine with the MIDletSuiteLoader

class.

Push Uses the following internal services:• Registers static push connections.• Removes all alarms and push connections for a MIDlet

suite.

Permission management Gets the default permissions for a suite.

Cryptographic system Uses the following services:• SHA-1 secure hash function• RSA public key decrypting• X.509 certificate parsing and verification• PKCS signature verification

Chapter 14 Application Management with the Java Platform 149

Page 176: Architecture and Design Guide by Oracle

■ Converts the JAD file and manifest files to Unicode from UTF-8

■ Extracts information from the JAD file

■ Parses and verifies manifest files

■ Extracts resources from JAR files

■ Compares the values of the attributes in the JAR file manifest and JAD files

■ Compares the versions of a MIDlet suite during suite updates

■ Performs MIDlet storage services for native installers, Java platform installers,and application managers, including the following functions:

■ Stores and updates a MIDlet suite

■ Gets a MIDlet suite’s previous installation information

■ Gets the size of a MIDlet suite, including RMS records and any otherinformation stored for that suite

■ Gets the application properties of a MIDlet suite

■ Gets a MIDlet suite’s current permissions

■ Gets the push interrupt settings of a MIDlet suite

■ Removes a MIDlet suite

■ Gets a list of all MIDlet suite identifiers

■ Runs a MIDlet

■ Optionally, preprocess images in the JAR file and creates a cache in persistentstorage to improve MIDlet startup time

■ Manages communication between installed MIDlets, for example, passing databetween one application and another

■ Provides the MIDlet auto-invocation (push) subsystem with a service to start aMIDlet after the user grants permission

■ Provides automated test functionality required for TCK testing

For a list of commands available for interacting with installed MIDlets, see the SunJava Wireless Client Software Tools Guide.

MIDlet Suite AttributesThe AMS is used to install, run, manipulate, and remove MIDlets in the Sun JavaWireless Client. MIDlets can be run alone, but are generally installed and managedas part of a MIDlet suite. That is, a JAR file containing more than one MIDlet.

150 Architecture and Design Guide • December 2008

Page 177: Architecture and Design Guide by Oracle

Each MIDlet suite has a JAD file that contains a list of attributes that giveinformation about the MIDlet suite, the MIDlets within it, and how the MIDletsshould be handled. (This information is also contained in the manifest that goes withthe JAR.)

For example, the JAD property MIDlet-Launch-Background:yes tells the AMSto launch the MIDlet directly to the background.

CODE EXAMPLE 14-1 shows the basic descriptors that can be found in a MIDlet suite’sJAD file. These basic descriptors are largely self-explanatory.

CODE EXAMPLE 14-1 JAD file descriptors

Extended MIDlet AttributesThe Sun Java Wireless Client software provides a set of extended MIDlet attributesthat can be used to specify more advanced characteristics of an individual MIDlet.These advanced attributes are useful to the AMS, tell it exactly how the MIDletshould be handled.

Note – Extended MIDlet attributes apply only to MIDlets within signed MIDletsuites. If a suite is unsigned, the extended attributes for a MIDlet are ignored. Formore information on signing MIDlet suites, see the Tools Guide.

Extended MIDlet attributes can be defined in both a MIDlet suite’s manifest file andJAD file, or only in its manifest file. If defined in both places, the value of anextended attribute must match. If an extended attribute is defined only in the JADfile, it is ignored.

CODE EXAMPLE 14-2 shows the extended MIDlet attributes.

MIDlet-1: starBurst, /SB_icon.png, starBurstMIDletMIDlet-Icon: /SB_icon.pngMIDlet-Jar-Size: 15450MIDlet-Jar-URL: starBurst.jarMIDlet-Name: starBurstMIDlet-Vendor: Chocolate Technology, Inc.MIDlet-Version: 1.0MicroEdition-Configuration: CLDC_HI-2.2MicroEdition-Profile: MIDP-2.2

Chapter 14 Application Management with the Java Platform 151

Page 178: Architecture and Design Guide by Oracle

CODE EXAMPLE 14-2 Extended MIDlet attributes

The following provides more information about the extended MIDlet attributes.

■ MIDlet-Heap-Size. Defines the maximum heap available for the MIDlet. If theAMS explicitly defines the maximum heap size available and the size defined inthe extended attribute is larger, the value of the extended attribute is ignored.

Note – In the Sun Java Wireless Client software, the maximum heap size is 1 MB forfixed policy and 4 MB for open policy. (Open policy is the default.)

■ MIDlet-Background-Pause. If the attribute value is yes, the pausedApp()method is called when the AMS moves the MIDlet to the background, and theMIDlet is moved to a paused state.

■ MIDlet-Launch-Background. If the attribute value is yes, the MIDlet is launcheddirectly to the background. Once a MIDlet is launched directly to the background,a user interacting with the AMS cannot move it to the foreground.

■ MIDlet-Launch-Power-On. If the attribute value is yes, the MIDlet is launchedevery time the JVM is started. If multiple MIDlets have this designation andlaunch when the VM is started, the order of launch is not controlled. If a MIDletis newly installed and the JVM is already running, the MIDlet is launched as soonas the installation process completes.

■ MIDlet-No-Exit. If the attribute value is yes, the MIDlet is only allowed to exitwhen the AMS calls the destroyApp() method.

Inter-MIDlet CommunicationThe Java Wireless Client software allows MIDlets installed in the AMS to shareinformation with other MIDlets, even if those MIDlets are not installed as part of thesame MIDlet suite. This information sharing between MIDlets is made possible bythe Pipe Communication Protocol (PCP), part of the Java platform’s GenericConnection Framework (GCF).

MIDlet-Heap-Size: 150kMIDlet-Background-Pause: yesMIDlet-Launch-Background: noMIDlet-Launch-Power-On: yesMIDlet-No-Exit: yes

152 Architecture and Design Guide • December 2008

Page 179: Architecture and Design Guide by Oracle

Note – Information sharing between MIDlets is only possible within a single virtualmachine instance, running in multithread (MVM) mode.

The ability of MIDlets to share information with other MIDlets provides manypossible enhancements for end user applications on a device.

For example, the user has a handset with an email application that came installedfrom the vendor and an address book application she later downloaded herself. Sheopens the email application and types in an address to send a message. The emailMIDlet opens a connection to the address book MIDlet and sends the typed-inaddress, asking if there is a name associated with it in the address book. If theanswer is “yes” the address book MIDlet returns the name and closes theconnection. The name then shows up in the address line instead of the address theuser typed in.

If the answer is “no,” the connection is kept open and when the message is sent, theemail MIDlet hands the address off to the address book MIDlet. The next time theuser opens her address book, the application asks her if she wants to provide a nameto go with the address it received from the email MIDlet.

Although neither MIDlet was installed into the device as part of the same MIDletsuite, the PCP mechanism has allowed both applications to communicate inside theAMS.

Using the Pipe Communication ProtocolThe Pipe Communication Protocol (PCP) is a platform-independent protocol thatmakes use of the Link and Service APIs to structure and fulfill communicationrequests. Therefore, this is no need to port this protocol.

A connection between two MIDlets is made using a connection request mechanismsimilar to a server socket connection request. But, instead of using a port number todefine the connection, the connection is defined using a MIDlet name and versionnumber.

The MIDlet name and version number is provided to a requesting MIDlet by aMIDlet connection server, which is part of the AMS functionality. The name andversion number is provided to the MIDlet connection server by a server-side MIDletwhen a connection is opened.

Note – The MIDlet’s opened pipe connection is considered a “server-side”connection, with the MIDlet connecting to it acting as the “client.”

The GCF connection string used in this mechanism takes the following format:

Chapter 14 Application Management with the Java Platform 153

Page 180: Architecture and Design Guide by Oracle

■ To open a server-side connection

“pipe://:pipe_server_name:pipe_version;”

■ To open a client connection

“pipe://*:pipe_name:pipe_version;”

When a MIDlet starts up inside the AMS, it opens a pipe connection and waits foranother MIDlet to connect to it, as shown in CODE EXAMPLE 14-3.

CODE EXAMPLE 14-3 MIDlet server-side connection

Once a MIDlet opens a server-side connection, a client MIDlet can connect to it, asshown in CODE EXAMPLE 14-4.

CODE EXAMPLE 14-4 Client MIDlet connects to server-side MIDlet

Once a server-client connection is made between two MIDlets, both opencommunication streams and transfer data, as shown in CODE EXAMPLE 14-5.

CODE EXAMPLE 14-5 Transferring data between server-side and client MIDlets

Once the requested data is transferred between the server-side and client MIDlets,the connection is torn down using appropriate close methods, as shown inCODE EXAMPLE 14-6.

CODE EXAMPLE 14-6 Closing the connection between MIDlets

PipeServerConnection serverConn=(PipeServerConnection) \

Connector.open(“pipe://:TestPipeConnection:1.0;”);

PipeConnection dataConn = (PipeConnection) \serverConn.acceptandOpen();

PipeConnection dataConn=(PipeConnection) \

Connector.open(“pipe://*:TestPipeConnection:1.0;”);

DataInputStream in = dataConn.openDataInputStream();DataOutputStream out = dataConn.openDataOutputStream();out.writeUTF(“text”);

out.close();in.close();dataConn.close();

154 Architecture and Design Guide • December 2008

Page 181: Architecture and Design Guide by Oracle

Once a server-side MIDlet closes a connection to a client MIDlet, another server-sideconnection can be opened, to wait for another client connection, as shownpreviously in CODE EXAMPLE 14-3.

Note – Best practice is to create a new thread for each incoming client.

Downloading Dynamic ComponentsThe Java Wireless Client software provides the ability to download and installdynamic components in the AMS. Dynamic components are sets of functionality (inthe form of JAR files) that can be loaded into the AMS and shared by all MIDlets andMIDlet suites installed on a device.

For example, a dynamic component could be functionality provided by a specificJava Specification Request (JSR). Once downloaded and installed, the files, classes,and functionality contained in the component’s JAR can be accessed by any MIDletsuite running in the AMS, as though the dynamic components were part of its ownsuite.

Note – This sharing of dynamic functionality is possible only when initiated by anOver the Air (OTA) request from the Component Manager. For more information onthe Component Manager, see “Configuring the AMS for Dynamic Components” onpage 156.

The Java Wireless Client software is configured by default not to allow downloadingand installation of dynamic components into the AMS. Therefore, to make thisfunctionality available, special steps must be taken. These steps are described in“Configuring the AMS for Dynamic Components” on page 156.

Dynamic components have the potential for mischief, so some security restrictionsare imposed upon their usage. For more information, see “Security Restrictions” onpage 158.

Configuring the AMS for Dynamic ComponentsTo configure the Java Wireless Client software to allow downloading and installationof dynamic components, you must set the following build flag during the systembuild process:

USE_DYNAMIC_COMPONENTS=true

Chapter 14 Application Management with the Java Platform 155

Page 182: Architecture and Design Guide by Oracle

Setting this flag to true when building the Java Wireless Client does the followingthree things:

1. The com.sun.midp.amsservices.AMSServices andcom.sun.midp.amsservices.ComponentInfo interfaces are compiled intothe system and become available to user applications (MIDlets).

2. Creates a Component Manager MIDlet that can be used to download specificdynamic content over the air from an URL.

3. Puts the Component Manager MIDlet into the Java Wireless Client software GUIin the Java AMS menu, just after the Installer and Certificate Manager MIDlets.

If USE_DYNAMIC_COMPONENTS=false is set, no dynamic component capabilitiesare available in the Java Wireless Client software. (This is the default setting.)

Defining the Location for Dynamic ContentThe current implementation of dynamic component capabilities in the Java WirelessClient software does not allow just any content to be downloaded from just anylocation. Rather, the location from which dynamic content can be downloaded mustbe specified at build time in the following file:

midp_dir/src/configuration/configuration_xml/share/suitestore_constants.xml

The administrator building the Java Wireless Client software (for example, a handsetmanufacturer) sets the download location in the suitestore_constants.xml fileby defining the AMS_CMGR_DEFAULT_COMPONENT_URL constant to some HTTPURL.

Once the download location is specified and the build is launched, the ability todownload dynamic content is built in to the Java Wireless Client software. When theend user of the device pulls up the Component Manager option through the AMSGUI menu item, the location listing for downloading dynamic content will be theone specified during the build process.

Note – The location defined in the suitestore_constants.xml file can be modified bya text field in the Component Manager MIDlet. For security purposes, it isrecommended that you remove this field during he porting process. To do this, editthe makeInstallDialog() method in the filemidp_dir/src/ams/dynamic_component_manager/reference/classes/com/sun/midp/appmanager/ComponentManager.java.

For more information on building the Java Wireless Client software, see the BuildGuide.

156 Architecture and Design Guide • December 2008

Page 183: Architecture and Design Guide by Oracle

Security RestrictionsOnce the ability to download dynamic components is built into the Java WirelessClient software, there are still restrictions upon its use.

That is, the com.sun.midp.amsservices.AMSServices API enabled by buildingin this dynamic capability can only be accessed by a signed MIDlet suite belongingto the “manufacturer” domain (or by ROMized MIDlets). Any unsigned MIDletattempting to use the API will cause a security exception to be thrown.

Any MIDlet having the correct security permissions can request installation of adynamic component in com.sun.midp.amsservices.AMSServices APIinstallComponent interface, as shown in CODE EXAMPLE 14-7.

CODE EXAMPLE 14-7 The installComponent interface

Support for Clamshell DevicesThe Sun Java Wireless Client software provides some support for clamshell devices,which have both an internal display (interactive when the device is open) and anexternal display (interactive when the device is shut).

When porting to the a clamshell device, a switch can be implemented between theinternal display and the external display.

Note – The Sun Java Wireless Client software assumes that the internal and externaldisplays have the same functionality and only one is active at a time. Othercapabilities (for example, different functionalities per display) are not supported.

To enable or disable an external display, when the clamshell is closed or opened, thenative platform should invoke the following function:

javanotify_clamshell_state_changed(javacall_lcd_clamshell_statestate)

When the Java platform is notified, the virtual machine is switched to the new state.It then notifies the native platform that the switch has been made by invokingjavacall_lcd_handle_clamshell().

public int installComponent(String url, String name)throws IOException, SecurityException;

Chapter 14 Application Management with the Java Platform 157

Page 184: Architecture and Design Guide by Oracle

The Java platform can then query the JavaCall porting layer for new screendimensions using the following functions:

■ javacall_lcd_get_screen_width()

■ javacall_lcd_get_screen_height()

The dimensions returned are expected to be the appropriate size for the new screendisplay being activated.

Porting and CustomizingThis section describes how to port and customize the Application ManagementService (AMS) subsystem.

Strategies for Porting the AMSPort the AMS in stages, initially using the default components. In later stages,replace the default components as desired. See the Build Guide for the option to useto eliminate AMS components from the build. Customization of the defaultcomponents is discussed later in “Strategies for Customizing the AMS” on page 160.

Because PCSL is used for suite storage, porting the default components is verysimple and consists of the following high-level steps.

1. Select the location of the MIDP application database by calling themidpSetAppDir(<appDir>) and midpSetConfigDir(<confDir>) functions.

2. Optionally, change the APP_DIR and CONFIG_DIR constants inmidp_dir/src/ams/example/ams_common_port/default/native/commandLineUtil_md.c

These constants can be changed to the desired subdirectories or to empty stringsif the device’s file system does not support subdirectories.

Note – The APP_DIR and CONFIG_DIR constants are used only for non-JavaCallports.

158 Architecture and Design Guide • December 2008

Page 185: Architecture and Design Guide by Oracle

Strategies for Customizing the AMSThe Java Wireless Client software AMS subsystem can be customized in a number ofways. This section includes a list of things to be aware of when you considercustomizing your AMS implementation. Following the list are some figures thatillustrate the ways that you can configure your AMS.

Things to ConsiderThe following list includes things to consider if you plan to customize your AMSimplementation.

■ For each component, decide whether to use the Java Wireless Client softwareimplementation or create a custom version.

■ If you use a native application manager, then you cannot use the Java WirelessClient software application manager.

■ You can use the Java Wireless Client software installer or you can write a customversion.

■ You can use the default Java Wireless Client software suite storage layer that usesPCSL file services, or you can write a custom version as long as you satisfy thesuite storage API that the runtime depends on.

■ For each Java Wireless Client software component, decide which customizationsto perform. For example:

■ If you use the Java Wireless Client software suite storage implementation, youcan customize the space requirement algorithm for the image cache inmidp/src/ams/ams_base/reference/native/imageCache.c. Becausespace in persistent storage is typically limited, the default implementation ofimage cache provides a basic algorithm that ensures at leastIMAGE_CACHE_THRESHOLD (defined in constants.xml) bytes of storageremain available during and after creation of the cache.

■ Modify the following file to download MIDlets from an operator-configured orSIM-based URL instead of asking the user.

midp/src/ams/ota/reference/classes/com/sun/midp/installer/DiscoveryApp.java

■ To add user billing, modify Installer.java.

■ Replace Application Manager screens by implementing the AppManagerUIand AppSettingsUI interfaces. These are located inmidp/src/ams/appmanager_ui/classes/com/sun/midp/appmanager.An alternative Application Manager UI implementation is discussed in “AMSUI Implementation” on page 161.

Chapter 14 Application Management with the Java Platform 159

Page 186: Architecture and Design Guide by Oracle

■ To change the foreground and background policies, modify the following files:

midp/src/ams/ams_base_cldc/reference/classes/com/sun/midp/main/MIDletProxyList.java

midp/src/ams/ams_base_cldc/reference/classes/com/sun/midp/main/MVMDisplayController.java

midp/src/ams/ams_base_cldc/reference/classes/com/sun/midp/main/DisplayController.java.

AMS UI ImplementationThe Application Manager consists of two parts. The first part is located inmidp/src/ams/appmanager_base and represents the core functionality. Thesecond part is responsible for the user interface and is located inmidp/src/ams/appmanager_ui.

The Application Manager screens are organized as an implementations of theAppManagerUI and the AppSettingsUI interfaces. To provide an alternative AMSUI implementation, the variable AMS_APPMANAGER_UI_IMPL_DIR should point tothe directory where the implementation resides. By default, the ApplicationManager reference implementation is used.

The Application Manager uses the following screens (all paths are to the referenceimplementation):

■ Main Displayable

midp/src/ams/appmanager_ui/reference/classes/com/sun/midp/appmanager/AppManagerUIImpl.java

■ MIDlet Selector screen

midp/src/ams/appmanager_ui/reference/classes/com/sun/midp/appmanager/MIDletSelector.java)

■ MIDlet Switcher

midp/src/ams/appmanager_ui/reference/classes/com/sun/midp/appmanager/MIDletSwitcher.java

■ Application Settings screen

midp/src/ams/appmanager_ui/reference/classes/com/sun/midp/appmanager/AppSettingsUIImpl.java

The main Displayable screen commonly contains a list of installed MIDlets andsystem MIDlets. This list is constructed by means of callbacks defined in theAppManagerUI interface (itemAppended and itemRemoved). It is up to the UIimplementor to sort the MIDlets or show folders if the Folder functionality issupported (set USE_AMS_FOLDERS=true at build time).

160 Architecture and Design Guide • December 2008

Page 187: Architecture and Design Guide by Oracle

The AppManagerUI implementation is notified when a MIDlet is started, exited orits state changed. To launch, update, bring to the foreground, remove or show aMIDlet’s properties dialog, the AppManagerUI implementation should call thecorresponding methods of AppManagerPeer.

The MIDlet Selector screen contains the list of MIDlets from a specified suite. Thisscreen is expected to be shown when the showMidletSelector() method ofAppManagerUI is called. It should be possible to launch or exit a MIDlet from thislist. The MIDlet Selector screen is used only for multi-MIDlet suites.

The MIDlet Switcher screen allows you to switch between running applications bymoving a selected application to the foreground. A dialog be shown when theshowMidletSwitcher() method of AppManagerUI is called.

The Application Settings screen is an implementation of the AppSettingsUIinterface. On this screen, the permission settings of available MIDlets can be viewedand changed.

Configuration ExamplesThe following figures illustrate ways that you can customize your AMSimplementation.

Default ImplementationFIGURE 14-2 shows the AMS configuration using the default Java Wireless Clientsoftware components. Note that the default suite storage implementation isreplaceable as long a the API is maintained. You can use a custom suite storageimplementation if the platform uses a native file viewer, or if the platform stores filesin a custom format, or if it uses different file names.

Chapter 14 Application Management with the Java Platform 161

Page 188: Architecture and Design Guide by Oracle

FIGURE 14-2 AMS Using Java Wireless Client Software Default Implementations

Custom InstallerFIGURE 14-3 shows the AMS configuration using a custom installer.

FIGURE 14-3 AMS Using Custom Installer

Custom Installer and Custom Suite Storage

FIGURE 14-4 shows the AMS configured with both a custom installer and a customsuite storage implementation. The custom suite storage implementation supports acustom storage format.

Suite storage APIJava Wireless Clientsoftware or custom

suite storage

Java WirelessClient software

runtime

Java WirelessClient software

installer

Java Wireless Clientsoftware

suite storage

Suite storage API

Java WirelessClient software

runtime

Custominstaller

162 Architecture and Design Guide • December 2008

Page 189: Architecture and Design Guide by Oracle

FIGURE 14-4 AMS With Custom Installer and Custom Suite Storage Implementation

Default Application ManagerFIGURE 14-5 shows the AMS using the default Java Wireless Client softwareapplication manager.

FIGURE 14-5 AMS With Default Java Wireless Client Software Application Manager

Customsuite storage

implementation

Customformat

Suite storage API

Java WirelessClient software

runtime

Java WirelessClient software

app. mgr.

Java WirelessClient software

runtime

Chapter 14 Application Management with the Java Platform 163

Page 190: Architecture and Design Guide by Oracle

Custom Application ManagerThe Sun Java Wireless Client software allows for implementation of a nativeApplication Manager (NAMS), with all other components implemented in the SunJava Wireless Client software.

To control which components are implemented by the Sun Java Wireless Clientsoftware and which are implemented by the native platform, there are several buildoptions that can be set. These include:

■ USE_NATIVE_APP_MANAGER

■ USE_NATIVE_INSTALLER

■ USE_NATIVE_SUITE_STORATE

■ USE_NATIVE_RMS

For information on these build options and how to set them, see the Build Guide.

Native Application Manager Configurations

Two NAMS configurations are of particular interest:

■ The native Application Manager UI only

■ The complete native Application Manager

The Sun Java Wireless Client software provides a sample implementation of thenative Application Manager for the Windows platform. The path is:

midp_dir/src/ams/example/nams_ui

For directions on how to build the sample native Application Manager, see the BuildGuide.

FIGURE 14-6 shows the AMS using a custom, native Application Manager thatinteracts with the runtime through the NAMS API.

164 Architecture and Design Guide • December 2008

Page 191: Architecture and Design Guide by Oracle

FIGURE 14-6 AMS With Custom Native Application Manager

Customnative app.

mgr.

NAMSAPI

Java WirelessClient software

runtime

Chapter 14 Application Management with the Java Platform 165

Page 192: Architecture and Design Guide by Oracle

166 Architecture and Design Guide • December 2008

Page 193: Architecture and Design Guide by Oracle

15

MIDlet Auto Invocation

This chapter discusses the design and porting of the MIDlet auto invocationsubsystem of Java Wireless Client software. The MIDlet auto invocation subsystemenables a MIDlet to be launched automatically at a particular time or when dataarrives across a network connection. Launching an application to handle dataarriving across a network connection is known as pushing data to the application.For that reason the subsystem is also referred to as the push subsystem.

The MIDP 2.0 Specification allows a MIDlet to be invoked in one of the followingthree ways:

■ Manually by the user

■ In response to an alarm (an absolute time at which the MIDlet is registered to berun)

■ In response to the networking subsystem receiving a message for the MIDlet

The last two ways (alarms and networking) are referred to as MIDlet auto invocationand are handled by the MIDlet auto invocation subsystem.

Chapter 15 MIDlet Auto Invocation 167

Page 194: Architecture and Design Guide by Oracle

The MIDlet auto invocation subsystem interacts with the subsystems and serviceslisted in TABLE 15-1.

The subsystem also requires access to the following device services:

■ System Timer - Gets the current time. The system timer must also signal the auto-invocation subsystem at a specified time in the future.

The system timer must be able to be multiplexed with networking and I/O(mouse, keyboard, and painting) signals to avoid polling.

■ System Networking - Listens for signals from inbound messages, connections, orboth.

Network signals must be able to be multiplexed with timer and I/O (mouse,keyboard, and painting) signals to avoid polling.

DesignThe MIDlet auto invocation subsystem must satisfy the push and alarmrequirements of the MIDP 2.0 Specification and Java Technology for the Wireless IndustrySpecification. It also has the following goals:

■ Portability – The system-dependent logic for listening for network data and thesystem timer must be separate from the general push connection list logic.

■ Resource Conservation – When listening for network data and the system timer,CPU use must be minimized.

TABLE 15-1 Auto Invocation Subsystem Interactions

Subsystem or Service Interaction

AMS subsystem • Scheduler - Finds out what MIDlets are running and has thecurrent MIDlet suite object to check for permission to launch.

• Installer - Registers inbound connections for MIDlets, basedon the JAD file.

• MIDletSuiteStorage - Starts MIDlets and gets MIDletproperties and interrupt settings. The MIDlet suite storagecomponent uses the subsystem’s push registry component toremove a MIDlet suite’s connections when the suite is deleted.

Networking subsystem Checks with the push registry when a MIDlet opens or closes aconnection type that supports push.

Storage service Holds persistent lists of alarms and inbound connections.

Security handler Handles the user interaction for granting permission to registerconnections and interrupt the current application.

168 Architecture and Design Guide • December 2008

Page 195: Architecture and Design Guide by Oracle

■ Prototyping and Test Development Support – The MIDlet auto invocationsubsystem must provide prototype connection implementations for deviceimplementors and test developers. The example protocols are SMS, CBS, TCP, andUDP.

Only the TCP and UDP prototypes work with the actual protocols and the SMSand CBS prototypes use UDP. See the Porting User’s Guide for more informationabout SMS and CBS prototypes and porting Bluetooth push connections.

Design OverviewThe MIDlet auto invocation subsystem has the following components:

■ Push Registry – Provides persistent lists of alarms and inbound connections thatcan invoke MIDlets.

The component gets persistent data storage from the storage service.

The component is used by internal push listeners, applications, and installers.

The push registry component has the following functionality:

■ Gets and uses information in the alarm list and push list

■ Saves and restores the alarm and push lists

■ Adds and deletes entries from the push list and the alarm list

■ Finds what MIDlet to launch for an incoming connection or alarm

■ Finds all of the incoming connections or alarms for a particular MIDlet

■ Internal Push Listener – Handles inbound connections and alarms when MIDP isrunning.

The internal push listener, running in its own thread, takes the following steps:

1. Waits on a native listening method that wakes up if either an alarm is triggered ordata has arrived on a network port

2. Determines whether it must launch a MIDlet in response to the alarm or data. If itmust launch a MIDlet, it proceeds to the next step. Otherwise, it goes back toStep 1.

3. Gets the parameters of the MIDlet to be launched.

4. If the source of the network data does not match the filter provided by theapplication, the push listener cannot get parameters. In this case, it goes back toStep 1; otherwise, it proceeds to the next step.

5. Determines whether the MIDlet to be launched is already running

6. If the MIDlet is already running, it determines the connection then goes back toStep 1. Otherwise, it proceeds to the next step.

Chapter 15 MIDlet Auto Invocation 169

Page 196: Architecture and Design Guide by Oracle

7. Determines whether the user wants to launch the MIDlet and saves the answer. Itdoes this using the current MIDletSuite object from the scheduler.

8. If the user does not want to interrupt the current MIDlet, it checks the connectionthen goes back to listening. Otherwise, it proceeds to the next step.

9. Sets the MIDlet to be the next MIDlet to execute by using the MIDletSuiteStorageAPI.

10. Uses the scheduler to shut down the current MIDlet suite. This stops the VM andtriggers the loading of the next suite.

■ External Push Listener – Handles inbound connections and alarms when MIDP isnot running (not yet implemented).

Push Connection StatesPush connections have the following states:

■ Available - Connection fields have been read from persistent storage, but no porthas been allocated yet

■ Checked In - Network port is allocated and being monitored for data by thelistener

■ Received Event - Push component has received a data-ready event on the portand the port is no longer being monitored by the listener

■ Launch Pending - Network port has data from a source the MIDlet wants and theport is no longer being monitored by the listener

■ Checked Out - The MIDlet is handling the network port and the port is not beingmonitored by the listener

FIGURE 15-1 shows the transitions between these states.

170 Architecture and Design Guide • December 2008

Page 197: Architecture and Design Guide by Oracle

FIGURE 15-1 Push Connection’s State Transitions

Design Rationale, Notes, and ConsiderationsThe internal push listener blocks, that is, it does not sit in a polling loop to seewhether events occur or alarm times have been reached. Instead, it interacts with theoperating system’s networking and timer APIs and is notified of events if they occur.This behavior is essential for conserving resources such as battery life.

For portability, much of the push registry and internal push listener is designed andimplemented in the Java programming language. Thread safety and permissionhandling rely on the Java platform.

Thread safety is of special concern if the system is currently installing a MIDlet suitewhen an alarm or incoming connection occurs. The subsystem must ensure theconsistency of the registry and thread safety, which is easier and more portable inthe Java programming language than in native code.

Available

Checked in

Received event

Launch pending

Checked out

Port allocated

Data detectedon the port

Source doesnot match

filter

Sourcematches

filter

MIDlet opens port

User deniespermission tolaunch MIDlet

MIDlet closesthe port

Chapter 15 MIDlet Auto Invocation 171

Page 198: Architecture and Design Guide by Oracle

Handling security permissions might require that an alert be displayed for the user.This is better done in the Java programming language, because KNI does not permitcallbacks into the Java platform layer.

PortingYou must always port the push registry, which has a native porting interface. See theNative API Reference for information. You can port the push listener components instages. Port the internal push listener’s alarm-based invocations followed by itsnetwork-based invocations, then implement the external push listener’s alarm-basedinvocations followed by its network-based invocations.

The external push listener component, which handles push notifications and alarmswhen the virtual machine is not running, is not implemented. You must design andimplement this component at porting time. The MIDP 2.0 Specification’s classdocumentation for the push registry outlines what is expected of a device in order tosupport push notifications and alarms.

A target device can provide push functionality in several ways. The following issuescan affect your design:

■ Which protocols that the target device accepts

■ How MIDP listens for messages

■ Buffering

■ Whether the target device supports running multiple MIDlets concurrently

■ How you handle user interaction

ProtocolsThe networking subsystem makes certain protocols available to the MIDlet autoinvocation subsystem. You can use one or more of these protocols to accept pushedmessages. For example, a MIDlet might use server sockets if they are supported on atarget device with a permanent IP address. You can also add protocols, such as theBluetooth protocols specified in Java APIs for Bluetooth (JSR 82). See “AddingNetwork Protocols for Push” on page 174 for more information.

When you determine which protocols to use for push, keep the followingrequirements in mind:

■ It must support static external identification like a phone number or IP address.For example, do not choose a socket or datagram if each deployed device is notassigned a globally unique Internet address.

172 Architecture and Design Guide • December 2008

Page 199: Architecture and Design Guide by Oracle

■ It must have separate channels or ports. For example, do not choose the commprotocol, because there is only one serial port.

Listening for Incoming DataMIDP must listen for inbound connection notifications, so that it can launch aMIDlet to handle the incoming message. It can listen using native blocking or apolling mechanism. Native blocking is preferable.

When the code for listening is external to the VM, the code can be simpler because itdoes not have to cooperate with the GUI. On most platforms you can use a timednetwork wait mechanism.

Message BufferingThe requirements for message buffering are protocol specific. Some protocols requireit but others do not. What is required is that if your port buffers messages, it mustprovide them to the launched MIDlet when the MIDlet opens the push connection.

Supporting datagram connections for push requires buffering of at least the firstmessage. Your implementation must be able to at least give the launched MIDlet thedatagram that caused it to start.

Supporting socket connections for push does not require any message buffering.Your port must only ensure that the launched MIDlet can open the connection, andaccept it if it has not timed out.

Java Wireless Client software buffers the first message and the inbound connectionsent to a MIDlet using the datagram protocol. It also accepts the inbound connectionfor a server socket. It uses the data from these operations to check whether theMIDlet registered to receive data from the message’s source. It conducts this checkbefore disturbing any running application.

If your device has limited space resources, you might want to limit messagebuffering for some protocols. For example, if your device supports SMS messaging,you might be able to cache only a fixed number of messages.

Chapter 15 MIDlet Auto Invocation 173

Page 200: Architecture and Design Guide by Oracle

User InteractionThe MIDlet auto invocation functionality cannot launch a MIDlet without the user’sacknowledgement. Users must be in control so that applications don't randomlydisrupt what they are doing.

The internal push listener requests the user’s permission before launching a pushedMIDlet. When you implement the external push listener, you must decide how topresent the request to interrupt the currently running MIDlet. Add the request-presentation code to the MIDlet suite loader, which is part of AMS. AMS isdescribed in Chapter 14.

MIDlet ConcurrencySome devices can run multiple MIDlets concurrently, while others can run only oneMIDlet at a time. Java Wireless Client software assumes the target device can onlyrun one MIDlet at a time. When a MIDlet is started because of an incoming messageor alarm and the user agrees to be interrupted, this component destroys the runningMIDlet to launch the pushed MIDlet.

▼ Adding Network Protocols for PushTo add a new protocol, follow these steps:

1. Add a protocol parameter, if required, to push native methods.

If the new protocol does not share the handles the same way as the othersupported protocols, add a protocol parameter like the one in the functionpushcheckout to the functions pushcheckin, pushfindfd, andfindPushBlockedHandle in push_server.c.

2. Test the change in Step 1 with the currently supported protocols.

Do this before adding the new protocol.

3. Add a new case for the protocol to push native methods.

Add the case to the functions pushProcessPort, pushDeleteEntry,pushcheckout, and pushfindfd. Also add it to the findPushBlockedHandlefunction, if you changed it in Step 1.

174 Architecture and Design Guide • December 2008

Page 201: Architecture and Design Guide by Oracle

4. In the native method that opens the protocol’s resource, check whether theresource is in use before opening it.

In the native method that the protocol’s class uses to open the native protocolresource, call the pushcheckout function before opening the native resource.Only open the native resource if the pushcheckout function does not return ahandle.

5. In the native finalizer and native method that closes the protocol’s resource,check whether the resource is being used before closing it.

Add a call to the pushcheckin function before closing the native resource andonly close the native resource if pushcheckin does not return successfully.

6. Provide special handling for opening a connection and reading if your protocoldoes not allow peeking.

Peeking is the ability to read data but not mark the data as read. If your protocoldoes not support peeking, modify the native method that reads data (or accepts aconnection) to get the data (or connection) cached by the function pushfindfdand only read (or accept a connection) if no data (or connection) is cached.

Chapter 15 MIDlet Auto Invocation 175

Page 202: Architecture and Design Guide by Oracle

176 Architecture and Design Guide • December 2008

Page 203: Architecture and Design Guide by Oracle

16

Runtime Security

This chapter discusses the design and use of the runtime security service. Theruntime security service restricts a MIDlet suite from using other MIDlet suites’classes and from using internal system-only classes.

Runtime security refers to any code in the system that protects restricted methodsfrom unauthorized access. All internal code depends on the runtime security service.

Before you port the runtime security service, become familiar with CLDC HotSpotImplementation.

The runtime security service has the following requirements:

■ External MIDlet suites must be restricted from the code of other suites.

■ External MIDlet suites must not be permitted to call restricted internal systemmethods.

■ Internal MIDP classes must still be able to access the methods they require, acrosspackage boundaries, even if the running MIDlet is not permitted to run thosemethods directly.

In addition, the runtime security service includes the following goals:

Small – Security cannot be turned off to save space, unlike the Java SE platform.

Fast – Security cannot be turned off to improve performance, unlike the Java SEplatform.

Unobtrusive – Implicit techniques, used whenever possible, keep the number ofexplicit security checks to a minimum.

The runtime security service is incorporated into the following components, each ofwhich fulfills part of the subsystem requirements:

■ Native virtual machine (VM) startup code and MIDlet suite loader

■ Class loader

It also defines one object, the security token.

Chapter 16 Runtime Security 177

Page 204: Architecture and Design Guide by Oracle

Design ConsiderationsThe following sections describe aspects of the runtime security system that areimportant for you to know about when you port it to your device.

Native VM Startup Code and MIDlet Suite LoaderJava Wireless Client software restricts a MIDlet suite from accessing the classes ofother suites by putting only that MIDlet suite’s JAR file in the class path beforestarting the virtual machine. The MIDlet suite loader can then only load the MIDletsuite’s own code when it loads the classes for running a MIDlet from the MIDletsuite.

Class LoaderThe runtime security service must keep external MIDlet suites from calling restrictedinternal system methods. Some protection is provided by the Java programminglanguage itself, which by default restricts access to a method or field by requiringthat the caller be in the method’s package or field’s package. This is commonlycalled package-private access.

Applications in the Java Platform, Standard Edition (Java SE platform) environmentcircumvent package-private access by defining classes in system packages.Applications cannot be permitted to use this workaround in MIDP, as it leads tosecurity checks between classes in the same package. The additional security checksincrease the amount of security code and decrease Java Wireless Client software’sperformance.

To keep applications from defining classes in system packages, Java Wireless Clientsoftware modifies the system class loader so that it loads internal packages only fromROM. Because Java Wireless Client software keeps application-defined systemclasses from ever being loaded, even if an application defines a system class.

178 Architecture and Design Guide • December 2008

Page 205: Architecture and Design Guide by Oracle

Security TokenJava Wireless Client software must restrict the access of an external MIDlet suite toresources intended for its use, but a permissible call from a MIDlet might result in acall to an internal class that has more access. Java Wireless Client software mustenable internal classes to perform a larger set of actions than the MIDlet callingthem.

Java Wireless Client software defines a security token object to enable internalclasses to perform sensitive actions. At initialization time, an internal security tokenis created and is passed to the internal classes that need it. Restricted internalmethods take a security token as an extra argument and they check it beforeperforming their task.

Internal methods can call restricted functions because they have a security token, butexternal MIDlets cannot call restricted functions directly because they do not have(and cannot obtain) a security token. A MIDlet’s access to restricted functionality islimited, whereas an internal method’s access is not.

Using the ServiceThis section contains advice on writing internal classes that are protected by asecurity token and writing internal classes that are used by optional internal MIDlets(such as classes used by the OTA installer).

Classes Protected by Security TokensWhen you design a class that is protected by a security token, check the securitytoken during the construction of the class rather than checking it in method calls.This minimizes the number of security checks, which improves the size andperformance of your port without jeopardizing security.

To follow this advice, write methods that would normally be static as instancemethods. An instance method does not require a security check because the check isdone when the instance is created. In contrast, a static method requires a securitycheck because it is called on the class and the security check in the constructor doesnot apply.

Chapter 16 Runtime Security 179

Page 206: Architecture and Design Guide by Oracle

Classes Used by Internal MIDletsAs you port the Java Wireless Client software, you might create classes that optionalinternal MIDlets use. An internal MIDlet, such as the OTA installer, provides asystem function. Internal MIDlets are part of the Java Wireless Client software andusers do not download them.

When you design a class that an internal MIDlet uses, do not protect access byrequiring a security token. Internal MIDlets do not have security tokens becausethey are applications, not system classes. No applications, even internal applications,have security tokens.

Instead of requiring a security token, protect access to your class by using thepermission protection service. This is the same protection service that other MIDletsuites use, but you can give your internal MIDlet broader permissions. See “UsingPermissions for Internal MIDlets” on page 187 for information.

180 Architecture and Design Guide • December 2008

Page 207: Architecture and Design Guide by Oracle

17

Permission Management

This chapter discusses the design, extension, and use of the permission managementservice. The permission management service implements the security modeldescribed in the MIDP 2.0 Specification and JTWI Specification.

Note – This service is typically not ported.

To implement the security model described in the MIDP 2.0 Specification, thepermission management service protects security-sensitive APIs by checking thepermissions of MIDlet suites. It handles push-interrupt queries so that a MIDlet isonly launched to handle an incoming message if the MIDlet is authorized to do so.

Subsystems with MIDlet-accessible security-sensitive APIs depend on thepermission management service. The permission management subsystem dependson the following subsystems:

■ MIDlet suite loader - Assigns the initial permissions to the internal MIDlet suite.Java Wireless Client software’s internal MIDlet suite provides system servicessuch as a graphical installer. See Chapter 14 for more information on the internalMIDlet suite.

■ Storage service - Holds the security information for the MIDP implementation.See Chapter 8 for more information.

■ Application management system:

■ Installer - Authenticates MIDlet suites and assigns their initial permissions.

■ Scheduler - Acts as the anchor of trust for the permission management service.Each MIDlet suite has its own Scheduler.

■ Application manager – Interacts with users to update permissions for installedMIDlet suites.

See Chapter 14 for more information.

Chapter 17 Permission Management 181

Page 208: Architecture and Design Guide by Oracle

■ High-level user interface – Interacts with the user to request authorization. Forexample, the display manager provides a way to preempt the display to ask theuser questions about a permission. See Chapter 11 for more information.

Design OverviewThe permission management service has two components: the security handlercomponent and the permissions component. The security handler componentensures that a MIDlet suite can perform only the actions for which it was authorized.The permissions component provides names, questions and answers for eachpermission, as well as supplying the initial permissions for each domain to theinstaller.

Security HandlerThe security handler component ensures that a MIDlet suite can perform only theactions for which it is authorized. The security handler depends on the followingcomponents:

■ AMS secure installer component, which determines whether the current MIDletsuite is trusted.

■ Scheduler of the AMS runtime environment component, which checks whetherthe current MIDlet suite is permitted to run a restricted method. Restrictedmethods use the scheduler and only complete their tasks if they receiveauthorization.

■ Permissions component (see “Permissions” on page 182) that interacts withrestricted methods and the scheduler to determine whether the current suite ispermitted to perform a particular action.

■ High-level user interface subsystem (see Chapter 11) that provides I/O to ask theuser‘s permission when the MIDlet suite’s permission level indicates that thequery is required.

PermissionsThe permissions component implements the permission levels defined in the MIDP2.0 Specification and controls how those permission levels are presented to the user.It uses the high-level user interface subsystem to present the information to the user.

182 Architecture and Design Guide • December 2008

Page 209: Architecture and Design Guide by Oracle

The MIDP 2.0 Specification defines the permission levels allow and never, as wellas three user-interaction levels for MIDP permissions: blanket, session, and oneshot. Each level has a possible value of yes or no. The blanket level has theadditional value of not asked. TABLE 17-1 summarizes the internal permission levelsassociated with the MIDP 2.0 Specification permission levels and their values.

When Java Wireless Client software presents a permission request to the user, it usesthe high-level user interface component to present runtime-security dialog screenswith yes-or-no questions. If the user chooses yes, the MIDlet proceeds normally(yes grants a permission). If the user chooses no, a security exception is thrown (nodenies permission).

In addition to answering questions as a MIDlet suite runs, users must be able tochange the user-interaction levels associated with installed MIDlet suites as part ofapplication management. For this task, the permissions component uses theapplication manager to present the users with settings screens. It enables changes toa permission function group, rather than a change to a single permission. A permissionfunction group is defined in the JTWI Specification, and consists of multiplepermissions grouped by similar function.

TABLE 17-1 Permission Level

Permission Level Description

Allow Yes, and do not allow the user to change the level

Never No, and do not allow the user to change the level

Blanket The user has not been asked; ask once

Blanket granted Yes, and do not ask again

User denied No, and do not ask again

Session Yes, and do not ask until next use of the application

Session denied No, and do not ask until the next use of the application

One shot Yes, and ask the next time the API is called

Denied No, and ask the next time the API is called

Chapter 17 Permission Management 183

Page 210: Architecture and Design Guide by Oracle

The JTWI Specification dictates the permission levels allowed for each permissionfunction group in the untrusted domain. The permission levels map to the internalpermission levels shown in TABLE 17-2.

Design Rationale, Notes, and ConsiderationsThe permission management service is implemented in the Java programminglanguage to speed development time, ensure high quality, and provide device-independent code. In addition to being device independent, most of the service isalso independent of specific permission domains. If you add a new domain orchange an existing one, you do not need to change the restricted APIs and thesecurity dialog screens. The exception to domain independence is the permissioncomponent. Some of its code relies on domain names.

Policy ConfigurationThe configuration of security policy is loaded by calling to the native API instead ofbeing hard-coded (in the Permissions class in the com/sun/midp/securitypackage). This enables the option to change the security policy configurationwithout the need to rebuild the VM image. The parameters that are loaded are:

■ domain names

■ group names

■ group permissions

■ permission levels for each group

TABLE 17-2 Java Technology for the Wireless Industry Permission Levels

Permission Level Permitted Internal Permission Levels

Blanket All permission levels except allow and never (allow and neverare not user permission levels)

Session • User denied

• Session

• Session denied

• One shot

• Denied

One shot • User denied

• One shot

• Denied

184 Architecture and Design Guide • December 2008

Page 211: Architecture and Design Guide by Oracle

■ messages used in the dialog boxes

ImplementationsCurrently there are two security policy implementations:

■ javacall platform - Contains functionality for loading configuration data from fileson the file system. Found in the filejavacall/implementation/win32_emul/midp/permissions.c

■ static (non-javacall) platform - Contains a policy configuration that supports MSA248-compliant platforms. Found in the filemidp/src/security/midp_permissions/reference/native/generic_policy_load.c

Two new configuration property values are defined:

■ security.policyfile - The name of the file that contains the policyconfiguration data. The default value is:

security.policyfile = “_policy.txt”

■ security.messagefile - The name of the file that contains the messages ofeach group. The default value is:

security.policyfile = “_function_groups.txt”

The policy files must be located in the config folder on the target device.

The midp build (midp/build/common/makefiles/MIDP.gmk) copies two policyconfigurations (MSA, JTWI) to the out/midp/appdb folder.

New PermissionsThe MIDP 2.0 Specification enables an implementation to add specific permissionsas long as they are not in the javax namespace. For example, you can add a newpermission to allow your device-specific public MIDlets to access a non-standardprotocol.

▼ Adding a New PermissionYou add a new permission by using the permission extensions mechanism. Followthese steps to add a new permission:

Chapter 17 Permission Management 185

Page 212: Architecture and Design Guide by Oracle

1. Create an XML file with your permission definitions, as shown inCODE EXAMPLE 17-1.

CODE EXAMPLE 17-1 Permission Extension.

Note – There are no naming conventions for permissions. However, they shoulddescribe, as concisely as possible, the tasks they protect.

2. Add the newly-created file to the list of extended permissions, like this:

PERMISSION_EXTENSIONS_LIST+$(MY_COMPONENT_DIR)/src/share/config/permissions.xml

3. Add the new permission string to the appropriate group in the policy file:

midp/src/security/midp_permissions/reference/config_policy.txt.JTWI

or

midp/src/security/midp_permissions/reference/policy.txt.MSA

4. If your new permission does not fit into an existing group of permissions,perform the following tasks.

a. Add a new group in the policy file and add the new permission string to thegroup.

b. Add the new group to each domain (listed at the end of the policy file) withthe appropriate permission value.

c. Add the new group to the Group list in the file. For example,midp/src/security/midp_permissions/reference/config/_function_groups.txt/JTWI

d. Add five strings to this group, in the following order:

■ The group visible name

■ Question for the Setting dialog

■ Setting disable choice string

<configuration><permissions><group ID=”READ_USER_DATA_GTOUP”>

<permission ID=”MY_READ_PERMISSION”Name=”com.my_company.util.Read”/>

</group></permissions></configuration>

186 Architecture and Design Guide • December 2008

Page 213: Architecture and Design Guide by Oracle

■ Title for the Runtime Permission dialog - This title is used for the dialog boxthat enables the user to set the user-interaction level of the permission.

■ Question for the Runtime Permission dialog - This question is used for thedialog box that enables the user to set the user-interaction level of thepermission.

New DomainsIf you need a new domain, add it to the policy file:

midp/src/security/midp_permissions/reference/config/_policy.txt.JTWI

or

midp/src/security/midp_permissions/reference/config/_policy.txt.MSA

▼ Adding a New DomainTo add a new domain to the Permissions class, follow these steps:

1. Add a new string constant (a public static final field) that names thedomain.

The convention for naming the constant is domainName_DOMAIN_NAME.

2. Modify the forDomain method to set the initial permission levels for thedomain.

Using Permissions for Internal MIDletsTo enable system applications (such as the graphical installer) to be developed in theJava programming language, system resources must be made available to them. JavaWireless Client software implements additional permissions to ensure that onlysystem applications can use these resources. The permission names arecom.sun.midp and com.sun.midp.ams.

Chapter 17 Permission Management 187

Page 214: Architecture and Design Guide by Oracle

Java Wireless Client software gives the additional permissions only to the internalMIDlet suite. This enables system applications to use the MIDP permission checkingsystem, as described in Chapter 17. If you write a new system MIDlet, add it to theinternal MIDlet suite so that it also receives the additional permissions.

Finding the Status of a SecurityCertificateThe Online Certificate Status Protocol (OCSP) enables an installed application todetermine the state of a security certificate by querying whether the certificate isvalid or has been revoked. An OCSP client (for example, an application that receivesa JAR file with a signed certificate) can issue a request to the issuer of the certificatefor confirmation of its validity, then suspends acceptance of the certificate until theissuer indicates that the certificate is still valid.

The OCSP Specification defines the data that must be exchanged between anapplication checking the status of a certificate and the server providing the status.

In structuring an OCSP request, the receiving application must include the followinginformation:

■ Protocol version

■ The request for confirmation of the certificate

■ The target certificate identifier (that is, the recipient of the request forconfirmation)

Upon reception, the certificate identifier determines if the request for confirmation iscorrectly formed. If it is, the certificate identifier returns information about thecertificate being queried, or returns an error message.

If a specific signed certificate is valid, the validity of the certificate is confirmed. Ifthe private key of the certificate has been compromised, or for other reasons thecertificate has been revoked (of example, the date of the certificate has expired), thisnon-validity is also confirmed.

Once the application issuing the request for confirmation of a signed certificatereceives an OCSP response from the target certificate identifier, the application canreject the signed security certificate and cancel the transaction (for example, adownload procedure) or accept the certificate anyway and continue with theoperation.

For more information, see the X.509 Public Key Infrastructure Online CertificateStatus Protocol Specification.

188 Architecture and Design Guide • December 2008

Page 215: Architecture and Design Guide by Oracle

18

Native Resource Management forMultitasking

The Java Wireless Client software includes a native resource manager that tracks theuse of native resources by each task1. The native resource manager enforces thesystem’s native resource policy.

The following two policies are provided by Java Wireless Client software:

■ Fixed resource policy

■ Open resource policy

Refer to the Multitasking Guide for more information about multitasking and how toset the resource policy at build time.

Fixed Resource PolicySystem resources are limited, and one way to ensure that they are allocated fairly isto use a fixed-partition resource management policy. This policy evenly divides theresource between the tasks. The maximum number of tasks is fixed.

When the system launches the AMS, the system allocates and reserves all systemresources required for the AMS task. The amounts are equal to the AMS taskresource limits as defined in the constants XML file.

When the system launches a user MIDlet in a new task, the system allocates andreserves all system resources. Each task used by different MIDlets gets the sameamount of system resources. The resource amounts are equal to the task’s resourcelimits and are set in the constants XML file.

1. At the Java platform level, each separate running Java platform application (Java application) within onevirtual machine is called a task. The API used to instantiate each task is a stripped-down version of the IsolateAPI defined in JSR 121. See The CLDC HotSpot Implementation Architecture Guide for more information.

Chapter 18 Native Resource Management for Multitasking 189

Page 216: Architecture and Design Guide by Oracle

If the Java AMS service cannot reserve enough resources, it does not launch a newtask. The application manager then tells the user that the application cannot bestarted due to the resource limit. If the native AMS (NAMS) service cannot reserveenough resources, it gets an error with a reason code through the callbackmechanism and must report the failure to the user.

With this policy, the maximum number of MIDlets that can run concurrently isalways the same because all system resources are equally distributed between usertasks.

The system tracks native resources and the Java application environment heap on aper-task basis. Note that certain resources are managed differently on differentplatforms. For example, images are managed as a native resources on Linuxplatforms, but are managed as part of the Java application environment heap onWindows platforms.

Open Resource PolicyIn this use case, all system resources are divided into two pools. The AMS pool isallocated and reserved for the AMS task, and the application pool is shared amongall application tasks. This policy treats memory differently than other resources inthe application pool. It always provides a task enough memory to bootstrap in orderto handle error conditions.

As with the fixed resource policy, the AMS task has a separate system resource limit.The rest of the system resources (except memory) form an application resource poolwhere resources are open for competition. Each resource in the pool has its ownresource limit defined in the constants XML file

A minimum amount of memory required to start an application task must beidentified and set in the XML file during porting. The system guarantees thespecified minimum amount of memory for any running application task at any time.Memory above the reserved minimum is open for competition among all applicationtasks.

The system tracks native resources and the Java application environment heap on aper-task basis. Note that certain resources are managed differently on differentplatforms. For example, images are managed as a native resources on Linuxplatforms, but as part of the Java application environment heap on Windowsplatforms. Images on Windows platforms are not managed as a native resource.

As in the fixed policy, the Java AMS service does not launch a MIDlet if it runs outof resources. The application manager informs the user that the application cannotbe started due to a resource limitation. The native AMS behaves the same as the JavaAMS under the open policy.

190 Architecture and Design Guide • December 2008

Page 217: Architecture and Design Guide by Oracle

PortingWhen you port a subsystem that manipulates a shared native resource, you mustdetermine the following:

■ Which resource policy to use

■ Whether the resource manager tracks that resource

■ Where in the subsystem the resource is allocated and released

■ How to reclaim the resource when a task exits

To determine if the resource manager tracks a particular resource, look for theresource in the enum in the midpResourceLimit.h file. Several native resources,such as networking and file handles, are already defined. If the native resource is notalready defined, add it to the enum and add a new set of policies to the constantsXML file. If the resource is already defined, set the corresponding values in theconstants XML file to reflect the number of instances of the native resource and thepolicy for the resource on the target platform.

Next, identify where in the subsystem the resource is allocated and released. Forexample, file handles are allocated when a file is opened and released when the fileis closed. Place calls from the resource manager’s API in the places where theresource is allocated. At each location, use one call to determine if the allocation cansucceed and another to decrement the amount available when the allocationsucceeds. Place calls from the resource manager’s API in the places where theresource is released. At each location, use a call to increment available resources.

You must also determine the correct error condition or exception to return if theallocation fails. For example, if all of the file handles are being used, the file openfails and throws an IOException to the invoking code. This is reasonable becauseall code that does I/O is already prepared to handle an IOException.

Finally, you must reclaim a task’s native resources when the task terminates. Onecommon way to do this is by associating the native resource with a Java object thathas a native finalizer. The native finalizer checks to see if the native resource must bereleased. If the finalizer releases the native resource, it must also increment theavailable resource count in the native resource manager. When you complete all foursteps, the native resource manager properly accounts for the resource and enforcesyour management policy.

Chapter 18 Native Resource Management for Multitasking 191

Page 218: Architecture and Design Guide by Oracle

192 Architecture and Design Guide • December 2008

Page 219: Architecture and Design Guide by Oracle

19

Porting the Networking Subsystem

This chapter describes how to port the networking subsystem of the Java WirelessClient software. The networking subsystem consists of the set of classes thatimplement the networking protocols. Applications use these protocols using theGeneric Connection Framework (GCF), and each protocol provides a class thatimplements the javax.microedition.io.Connection interface.

Note – Protocols required by the any of the optional packages are discussed in theappendix or chapter that describes how to port the optional package.

TABLE 19-1 lists the protocols that the networking subsystem provides to JavaWireless Client software.

TABLE 19-1 Networking Subsystem Protocols

Protocol Description

SocketConnection Client connection to a TCP server.

ServerSocketConnection Server for TCP clients.

DatagramConnection Interface for sending and receiving UDP datagrams.

SecureSocketConnection Socket connection with SSL 3.0. Java Wireless Clientsoftware supports RSA RC4 128 and 40 bit cipher suites anddoes not support client authentication.

HttpConnection Socket connection with the HTTP 1.1 protocol. Theconnection supports persistent connections, chunked data,and tunneling.

HttpsConnection HTTP connection that uses an SSL connection instead of anunsecured socket connection.

Chapter 19 Porting the Networking Subsystem 193

Page 220: Architecture and Design Guide by Oracle

The networking subsystem depends heavily on PCSL for its underlying networkingimplementations, and much of the networking subsystem is written in the Javaprogramming language. Once PCSL is ported, most of the networking subsystemcan be brought up quickly. See Chapter 8 for details about porting PCSL.

The push subsystem has some interdependencies with the networking subsystem.Networking protocols for which push functionality is provided must be supportedin the networking subsystem. For example, if push support is provided for serversockets, then server socket support must also be provided in the networkingsubsystem. For each protocol with push support, the push registry providesfunctions that hand off network connections and any cached data to the networkingsubsystem. The networking subsystem uses the functions when the “pushed”MIDlet opens a connection. See Chapter 15 for more information about the pushsubsystem.

Generic Connection Framework andProtocol ImplementationsThe networking subsystem is built on CLDC’s GCF. See the documentation for thejavax.microedition.io.Connector class in the CLDC specification. Theconnection that corresponds to the scheme from the URL passed to theConnector.open() method is implemented by instantiating a class namedProtocol that resides in the Java programming language packagecom.sun.midp.io.j2me.scheme. For example, if an application callsConnector.open("http://www.example.com"), the scheme is http. The entrypoint for the implementation of this protocol is found in the classcom.sun.midp.io.j2me.http.Protocol.

194 Architecture and Design Guide • December 2008

Page 221: Architecture and Design Guide by Oracle

The set of Java classes in this area use the common features listed in TABLE 19-2.

Some of the networking protocols are written entirely in the Java programminglanguage and depend only upon other networking protocols. These protocols do notrequire any explicit porting and are simply configured into or out of the system.Other networking protocols have native interfaces and might require additionalporting effort. This point is covered in the following steps for each networkingprotocol.

Porting the Networking SubsystemThe following high-level steps represent a reasonable path to port the networkingsubsystem. More detailed information is provided in the following sections.

1. Port PCSL.

PCSL has native-level support for basic networking utilities (for example, hostname lookup), sockets, and datagrams. PCSL porting is covered in Chapter 8.Implementing basic networking utilities and sockets is required, but the datagramimplementation is optional.

TABLE 19-2 Common Features Used by Java Classes

Feature Description

StreamConnectioninterface

All of the necessary functionality, except for the native interfaceto a native resource. The interface covers the many subtle,easily overlooked details in implementing the interface.

ConnectionBaseInterface interface

All dynamically loaded protocols must implement thisinterface. The implementation supplies common functionality.For example, it disconnects only when the connection and allstreams are closed, and throws an exception when a method iscalled after the connection is closed.

Common bufferingrequirements

Because some protocols have common buffering requirements,the networking subsystem provides classes with input andoutput buffering. For native resources that do not allowpeeking ahead in the buffer, the subsystem provides animplementation that reads ahead into the input buffer.

Network Initialization On some platforms, network protocols require nativeinitialization before the network can be used. For theseprotocols, the networking subsystem provides a class in thecom.sun.midp.io package that performs the native methodcall to initialize the network.

Chapter 19 Porting the Networking Subsystem 195

Page 222: Architecture and Design Guide by Oracle

2. Port the Socket protocol.

The Java platform classes that implement the socket protocol have nativeinterfaces that are implemented in by means of calls to PCSL. The Javaprogramming language level socket protocol is in turn used by higher-levelprotocols such as HTTP and SSL.

3. Port the HTTP protocol.

The HTTP implementation is a pure Java programming language implementation(Java implementation) that relies only on the Java implementation of the socketprotocol. Having TCP and HTTP available enables automated testing using theHTTP AutoTester. In addition, when the AMS is ported (see Chapter 14), theGraphical Installer uses HTTP to support OTA installation and manual testing.

Note – HTTP is the only protocol required to be supported in MIDP 2.0. Otherprotocols are optional. The following steps can therefore be performed in any order,or not at all, depending upon which protocols you decide must be supported in yourport. The exception is that HTTPS depends upon SSL having first been implemented.

4. (Optional) Port SSL protocol.

The critical cryptographic functions of SSL are implemented in native code. Thesource code to the native implementation and the corresponding porting interfaceare optionally available. The protocol functions of SSL (for example, thehandshake) are implemented in the Java programming language on top of thesocket protocol implementation.

5. (Optional) Port the HTTPS protocol.

The HTTPS implementation is written in the Java programming language directlyon top of the HTTP and SSL implementations. If these protocols are implemented,the HTTPS implementation can be brought up immediately.

6. Port the UDP Datagram protocol.

The Java classes that implement the datagram protocol have native interfaces thatare implemented by means of calls to PCSL. Port the PCSL datagramimplementation now if you have not done so already. The Java implementation ofdatagrams can then be integrated.

7. (Optional) Port the server socket protocol.

The server socket implementation has its own native interface that must beported. In addition, the server socket implementation also requires basicnetworking utilities from PCSL.

196 Architecture and Design Guide • December 2008

Page 223: Architecture and Design Guide by Oracle

General Porting ConsiderationsSome of the Java implementations of the networking protocols use buffering toincrease performance. This consumes about 4 kilobytes of Java platform heapmemory per connection.

Some of the protocol implementations depend upon each other. This implementationdependency is reflected in the APIs exposed to applications. For example, the HTTPimplementation uses the socket protocol implementation. Because the socketprotocol implementation is present, this implies that the socket: protocol is visibleto the application through the GCF. HTTP support is required, but if socket supportis not provided to applications, additional work is necessary.

Access to the socket: protocol must be disabled by modifying thejavax.microedition.io.Connector class. This class is provided as part of theCLDC HotSpot Implementation source bundle. Similar dependencies exist betweenSSL and the socket protocol, and between HTTPS and SSL.

Porting Considerations for HTTPThis section discusses porting issues that might arise with the HTTP protocolinvolving HTTP proxies and persistent connections.

HTTP Requests Using ProxiesJava Wireless Client software’s HTTP implementation can make requests through aproxy server. To have the device emulator use a proxy server, set the internal systemproperty com.sun.midp.io.http.proxy. See the Build Guide for moreinformation.

The HTTP implementation requires that HTTP proxy servers support the generictunneling mechanism for TCP-based protocols through web proxy servers.Tunneling is used instead of the normal HTTP proxy because many proxies cannothandle certain advanced HTTP 1.1 features correctly and because tunneling isalready implemented for HTTPS.

If you modify the HTTP porting-ready implementation to use a WAP gateway, theWAP gateway replaces the proxy access. To do this, replace references to the genericHTTP proxy with calls to a native WSP stack.

Chapter 19 Porting the Networking Subsystem 197

Page 224: Architecture and Design Guide by Oracle

HTTP1.1 Persistent ConnectionsThe MIDP 2.0 Specification supports HTTP 1.1 persistent connections.

Note – Do not change the porting-ready implementation to only include HTTP 1.0connection behavior.

Persistent connections have many advantages, but on small devices with limitedresources they can be a problem if they are not closed properly. Java Wireless Clientsoftware solves this problem by using the value of an internal system property to setthe time that a connection can remain open and unused. After the time limit, JavaWireless Client software closes the connection and removes it from the connectionpool.

The default value of the internal system propertycom.sun.midp.io.http.persistent_connection_linger_time is 60,000milliseconds. Change it for your device, if necessary. See the Build Guide forinformation about configuring internal system properties.

Porting Considerations for HTTPSThis section discusses porting issues that might arise with the HTTPS protocolinvolving HTTPS proxies and persistent connections.

Porting HTTPSJava Wireless Client software’s implementation of HTTPS extends its HTTPimplementation. It uses SSL to make secure connections and uses the sample webpublic key store for CA certificates. Java Wireless Client software’s HTTPSimplementation is compliant with HTTP over TLS as specified in RFC 2818, exceptthat it uses SSL 3.0 instead of TLS 1.0 (SSL 3.1).

Note – Java Wireless Client software’s implementation of HTTPS does not exposean API to control the handshake listener. Exposing such an API allows certaincertificate errors to be overridden by higher level applications. It must not bepossible for an end user to override policy decisions about expired certificates. Forsecurity reasons, your port must not expose this API either. If you do not export thisAPI, it is compliant with the MIDP 2.0 Specification.

198 Architecture and Design Guide • December 2008

Page 225: Architecture and Design Guide by Oracle

Using the Java Wireless Client Software SSLImplementationsThe Java Wireless Client software SSL implementation is provided for referencepurposes and is not intended for production use in devices. However, if thereference SSL reference implementation is used in a device you must provide securerandom data in the com.sun.crypto.PRand class.

Java Wireless Client software does not provide secure random data. Its seed is basedon time, which is predictable. You must change it so that it obtains an initial 128bytes (not bits) of unpredictable data from your native platform. Use RFC 1750Randomness Recommendations for Security as a guide for collecting the initial data. Seehttp://www.ietf.org/rfc/rfc1750.txt.

Porting Considerations for Server SocketThe server socket protocol has its own native interface. To port the server socketimplementation, you must provide implementations of the functions defined in theheader file serverSocketProtocol.h. The server socket implementation alsorelies on the basic networking utilities of PCSL, so PCSL must be present as well. Seethe Native API Reference for further details.

Network MonitoringThe network monitoring feature of Sun Java Wireless Client software allows you tosend information about significant protocol events to your runtime implementationwhen a MIDlet is run in Debug mode. This feature can be enabled for MIDP and forselected optional packages, such as Multimedia Message Service and Bluetooth, andis passed via the Lime mechanism.

To turn on the network monitoring function, you must build the JavaCall and MIDPcomponents with the build option USE_NETMON=true. For more information, seethe Build Guide.

When a MIDlet callsconnector.open(“scheme:address”), the VM constructs a classname string consisting of the following elements:

System.getProperty(javax.microedition.io.Connector.protocolpath)+ System.getProperty(microedition.platform) + Scheme + Protocol

Chapter 19 Porting the Networking Subsystem 199

Page 226: Architecture and Design Guide by Oracle

Note – The default for microedition.platform is j2me.

When the network monitoring functionality is off, the value of the propertyjavax.microedition.io.Connector.protocolpath is com.sun.midp.io.

When the network monitoring functionality is on, the value of thejavax.microedition.io.Connector.protocolpath is com.sun.kvem.io.

Network monitoring classes extend the appropriate MIDP classes. When overridemethods from a parent class are called, they send event notifications to your runtimeplatform.

Note – Network monitoring does not contain any platform-dependent code.

Details of network monitoring functionality are provided in TABLE 19-3 andTABLE 19-4.

TABLE 19-3 Network Monitor Hooks (1)

Protocol &(Scheme)

Parent Class Child Class Method

MultimediaMessageService(mms)

com.sun.midp.io.j2me.mms.Protocol

com.sun.kvem.io.j2me.mms.Protocol

send()receive()

BluetoothSerial PortProfile(btspp)

com.sun.jsr082.bluetooth.btspp.BTSPPConnectionImpl

com.sun.jsr082.bluetooth.btspp.BTSPPNotifierImpl

com.sun.jsr082.bluetooth.kvem.btspp.BTSPPNetmonConnection

com.sun.jsr082.bluetooth.kvem.btspp.BTSPPNetmonNotifier

BTSPPNetmonConnection()close()sendO()receiveO()

updateServiceRecord()close()

BluetoothLogical LinkControl andAdaptationProtocol(bt12cap)

com.sun.jsr082.bluetooth.btl2cap.L2CAPConnectionImpl

com.sun.jsr082.bluetooth.btl2cap.L2CAPNotifierImpl

com.sun.jsr082.bluetooth.kvem.btl2cap.L2CAPNetmonConnection

com.sun.jsr082.bluetooth.kvem.btl2cap.L2CAPNetmonNotifier

L2CAPNetmonConnection()close()sendData()receiveData()

doClose()updateServiceRecord()

200 Architecture and Design Guide • December 2008

Page 227: Architecture and Design Guide by Oracle

BluetoothGenericObjectExchangeProfile(btgoep)

com.sun.jsr082.obex.btgoep.BTGOEPConnection

com.sun.jsr082.obex.btgoep.BTGOEPNotifier

com.sun.jsr082.obex.kvem.btgoep.BTGOEPNetmonConnection

com.sun.jsr082.obex.kvem.btgoep.BTGOEPNetmonNotifier

BTGOEPNetmonConnection()close()write()read()

close()netmonUpdate()

Infrared DataAssociationObjectExchange(irdaobex)

com.sun.jsr082.obex.irdaobex.IrNativeConnection

com.sun.jsr082.obex.kvem.irdaobex.IrNetmonNativeConnection

IrNetmonNativeConnection()close()write()read()

TransmissionControlProtocalOBjectEXchange(tcpobex)

com.sun.jsr082.obex.tcpobex.TCPOBEXConnection

com.sun.jsr082.obex.kvem.tcpobex.TCPOBEXNetmonConnection

TCPOBEXNetmonConnection()close()write()read()

CellBroadcastShortMessageService

com.sun.midp.io.j2me.cbs.Protocol

com.sun.kvem.io.j2me.cbs.Protocol

receive()

ShortMessageService(sms)

com.sun.midp.io.j2me.sms.Protocol

com.sun.kvem.io.j2me.sms.Protocol

send()

ApplicationProtocol DataUnit(apdu)

com.sun.midp.io.j2me.apdu.Protocol

com.sun.kvem.io.j2me.apdu.Protocol

openPrim()

Java CardRemoteMethodInvocation(jsrmi)

com.sun.midp.io.j2me.jcrmi.Protocol

com.sun.kvem.io.j2me.jcrmi.Protocol

openPrim()

invokeImpl()

TABLE 19-3 Network Monitor Hooks (1)

Protocol &(Scheme)

Parent Class Child Class Method

Chapter 19 Porting the Networking Subsystem 201

Page 228: Architecture and Design Guide by Oracle

HypertextTransferProtocol(http)

com.sun.midp.io.j2me.http.Protocol

com.sun.kvem.io.j2me.http.Protocol

1)create newinput/outputstream2)read/write onebyte from/to theinput/outputstream3)read/writebuffer from/to theinput/outputstream4)closeinput/outputstream

SecureHypertextTransferProtocol(https)

com.sun.midp.io.j2me.https.Protocol

com.sun.kvem.io.j2me.https.Protocol

1)create newinput/outputstream2)read/write onebyte from/to theinput/outputstream3)read/writebuffer from/to theinput/outputstream4)closeinput/outputstream

SerialCommunication Protocol(comm)

com.sun.midp.io.j2me.comm.Protocol

com.sun.kvem.io.j2me.comm.Protocol

openPrim()disconnect()redBytesNonBlocking()writeBytes()setBaudRate()

SocketProtocol(socket)

com.sun.midp.io.j2me.socket.Protocol

com.sun.kvem.io.j2me.socket.Protocol

openPrim()open()disconnect()nonBufferedRead()writeBytes()setSocketOption()

TABLE 19-3 Network Monitor Hooks (1)

Protocol &(Scheme)

Parent Class Child Class Method

202 Architecture and Design Guide • December 2008

Page 229: Architecture and Design Guide by Oracle

Note – The information provided in TABLE 19-4 is a continuation of the informationprovided in TABLE 19-3.

ServersocketProtocol(serversocket)

com.sun.midp.io.j2me.serversocket.Socket

com.sun.kvem.io.j2me.serversocket.Protocol

(see SocketProtocol)

SecureSocketLayer(ssl)

com.sun.midp.io.j2me.ssl.Protocol

com.sun.kvem.io.j2me.ssl.Protocol

openPrim()close()read()write()setSocketOption()

DatagramProtocol(datagram)

com.sun.midp.io.j2me.datagram.Protocol

com.sun.kvem.io.j2me.datagram.Protocol

openPrim()send()receive()close()

TABLE 19-4 Network Monitor Hooks (2)

Lime Package Lime Class Lime Method Data

com.sun.kvem.netmon.mms MMSMsgReceiver sendreceived

mms message

com.sun.kvem.netmon.bluetooth

BluetoothMsgReceiver connectdisconnectwritereadupdateServiceRecorddisconnect

url

output datainput datarecord data

com.sun.kvem.netmon.bluetooth

BluetoothMsgReceiver connectdisconnectedwritereadnotifierDisconnectupdateServiceRecord

url

output datainput data

service datarecord

com.sun.kvem.netmon.obex ObexMsgReceiver connectdisconnectwriteread

url

output datainput data

TABLE 19-3 Network Monitor Hooks (1)

Protocol &(Scheme)

Parent Class Child Class Method

Chapter 19 Porting the Networking Subsystem 203

Page 230: Architecture and Design Guide by Oracle

com.sun.kvem.netmon.bluetooth

BluetoothMsgReceiver notifierDisconnectnotifierconnectupdateServiceRecord

urlservice datarecord

com.sun.kvem.netmon.obex ObexMsgReceiver connectdisconnectwriteread

url

output datainput data

com.sun.kvem.netmon.obex ObexMsgReceiver connectdisconnectwriteread

url

output datainput data

com.sun.kvem.netmon.sms SMSMsgReceiver openreceivedcloseopensendcloseopenreceivedclose

input message

urloutput message

input message

com.sun.kvem.netmon.apdu APDUMsgReceiver openexchangeAPDU

urlConnectionstatusAPDU commandAPDU response

com.sun.kvem.netmon.jcrmi

JCRMIMsgReceiver openresponseinvoke

response

urlAPDU responsemethod name,APDU responsAPDU response

com.sun.kvem.netmon.http HttpMsgReceiver newStream

updateMsgOneByteupdateMsgBuffclose

url anddirectionbytebuffer

TABLE 19-4 Network Monitor Hooks (2)

Lime Package Lime Class Lime Method Data

204 Architecture and Design Guide • December 2008

Page 231: Architecture and Design Guide by Oracle

ReferencesThe following references are helpful when porting the networking subsystem:

■ RFC 1750. Randomness Recommendations for Security –http://www.ietf.org/rfc/rfc1750.txt

■ RFC 2246. The TLS Protocol – http://www.ietf.org/rfc/rfc2246.txt

■ RFC 2817. Upgrading to TLS Within HTTP/1.1. This RFC describes HTTP tunneling,among other topics – http://www.ietf.org/rfc/rfc2817.txt

■ RFC 2818. HTTP over TLS – http://www.ietf.org/rfc/rfc2818.txt

com.sun.kvem.netmon.http HttpMsgReceiver newStream

updateMsgOneByteupdateMsgBuffclose

url anddirectionbytebuffer

com.sun.kvem.netmon.comm CommMsgReceiver connectdisconnectreadwritesetBaudRate

url and mode

input dataoutput datanew baud rate

com.sun.kvem.netmon.socket

SocketMsgReceiver connect url and mode//:port,READ_WRITE

com.sun.kvem.netmon.ssl SSLMsgReceiver connectdisconnectreadwritesetSocketOption

url and mode

input dataoutput dataoption nameand value

com.sun.kvem.netmon.datagram

DatagramMsgReceiver opensendreceive

receivedclose

url and modeoutput datanotificationsends beforereceiving isstartedinput datagram

TABLE 19-4 Network Monitor Hooks (2)

Lime Package Lime Class Lime Method Data

Chapter 19 Porting the Networking Subsystem 205

Page 232: Architecture and Design Guide by Oracle

■ WAP TLS Profile and Tunneling Specification. WAP-219-TLS-20010411-a. WirelessApplication Protocol Forum Ltd., 2001 –http://www.openmobilealliance.org

■ SSL 3.0 Draft Specification, November 1996 –http://wp.netscape.com/eng/ssl3/.

■ Luotonen, A., Tunneling TCP Based Protocols Through Web Proxy Servers – Also seethe (expired) Internet draft draft-luotonen-web-proxy-tunneling-01.txt,published in Luotonen, A., Web Proxy Servers. Prentice-Hall, 1977.

206 Architecture and Design Guide • December 2008

Page 233: Architecture and Design Guide by Oracle

20

Porting the User Message BundleService

This chapter describes the design and porting of the message bundle service.

Internationalization (I18N) is the process of designing an application so that it can beadapted to various languages, and regions without further engineering changes. Theprocess of adapting the application to a particular language or region is referred toas localization (L10N).

Note – The term internationalization is generally abbreviated as I18N because thereare 18 letters between the first “i” and the last “n.” The term localization isabbreviated as L10N because there are 10 letters between the “l” and the “n.”

Java Wireless Client software provides a basic framework for I18N: the messagebundle service. It is not the entire solution, but it eases localization by enabling youto add locale-specific components and translate text through either the Java layer oryour platform’s native layer.

The message bundle service does not depend on other Java Wireless Client softwareservices or subsystems. However, any Java Wireless Client software service orsubsystem that displays information to the user uses this subsystem.

DesignThe message bundle subsystem has three parts:

■ Access – Retrieving the localized strings

■ Locale-specific Content – The strings retrieved by the access component

Chapter 20 Porting the User Message Bundle Service 207

Page 234: Architecture and Design Guide by Oracle

■ Decoder-Encoder – Getting and giving strings that have the proper encodingfrom and to the user

FIGURE 20-1 shows this information flow. The shaded box shows the porting layer forthe message bundle service.

FIGURE 20-1 User Message Bundle Service Components and Interactions

Access ModuleThe access module holds the locale-independent code that includes the followingcomponents:

■ Constants associated with strings to be localized

■ Functions that get the requested strings

■ Specifications of the behaviors that all locales must handle

Behavior ModuleThe behavior module handles locale-specific content and behavior. It holds thestrings for the default locale (en_US) and also acts as a template for localization. Anew localized file is like the default locale, but with localized strings replacing theEnglish text of the messages and localized behavior replacing the default behaviorwhere appropriate.

Access component of the usermessage bundle

Request for a string to displayGet a string from a text box or field,

or display a string

Locale-specific content componentof the user message bundle

Decoder-Encoder component of theuser message bundle

208 Architecture and Design Guide • December 2008

Page 235: Architecture and Design Guide by Oracle

Decoder-Encoder ComponentThe decoder-encoder component ensures a proper translation between the characterencoding used in the locale, and the unicode used internally. That is, when thesystem reads in bytes, it decodes them from the native language’s characterencoding to Unicode. Similarly, when the system provides output, it first encodesthe Unicode strings into the character encoding of the native language.

This component is not entirely in the user message bundle service. Parts of it arelocated in the CLDC HotSpot Implementation.

Design Rationale, Notes, and ConsiderationsThis design has the following advantages:

■ It places all of the localized content and behavior in one file, which makesmaintenance easier.

■ It provides a discipline for adding new localizable strings that has these features:

■ Enables a compile-time check for the existence of the new localized string

■ Ensures that the default file is always up-to-date. A localization expert cancopy and localize the file, knowing that nothing is missing.

This design has the following disadvantages:

■ If a developer does not follow the conventions for localized strings, it is easier toaccidentally enter duplicate identifiers. Unlike a missing string, this error is notcaught at compile time.

■ It does not support real-time locale change. The message bundle is determinedwhen the MIDP runtime is started.

■ It is not backward compatible with the MIDP reference implementation.

PortingThe messages of the locale-specific content component are in thecom.sun.midp.l10n package. The messages have integer identifiers defined in thecom.sun.midp.i18n package. The identifiers are organized into ranges that groupthe values based on the Java Wireless Client software subsystem.

Chapter 20 Porting the User Message Bundle Service 209

Page 236: Architecture and Design Guide by Oracle

The following two scenarios might require you to update the message bundleservice:

■ Adding message strings when you port other Java Wireless Client softwaresubsystems. In this case you must change the locale-specific content component,as described in “Adding Additional Message Strings” on page 210.

■ Supporting a new locale requires you to update the locale-specific contentcomponent, as described in “Supplying Locale-Specific Strings” on page 210. Youmight also need to update the decoder-encoder component, as described in“Adding a Character Encoding” on page 211.

▼ Adding Additional Message StringsTo add a string, you must update both the message list and the identifiers.

1. Add the identifier for the message.

If you add a string to an existing subsystem, maintain the identifier ranges. If youadd a string for a new subsystem, add a new range.

2. Update the message list to add your new message.

Supporting a New LocaleSupporting a new locale involves one or both of the following tasks:

■ You must supply strings in the native locale for Java Wireless Client software todisplay to the user, as described in “Supplying Locale-Specific Strings” onpage 210.

■ If the new locale uses a special character encoding, such as Shift-JIS, you mustmodify the decoder-encoder component as described in “Adding a CharacterEncoding” on page 211.

▼ Supplying Locale-Specific StringsThe locale-specific content component in the com.sun.midp.l10n packageprovides a class that holds strings for the default locale, en_US. Use the class’ssource file as a template.

1. Copy the file and name the copy LocalizedStrings_locale.java, where localeis the standard abbreviation for the locale.

For example, a German localized strings file are namedLocalizedStrings_de.java.

210 Architecture and Design Guide • December 2008

Page 237: Architecture and Design Guide by Oracle

2. Change the class name in the file to match the file name.

3. Replace the English text of the messages with localized strings.

4. Replace the default behavior with localized behavior (date formats, first day ofthe week, and so forth) where appropriate.

Adding a Character EncodingThe system property microedition.encoding holds Java Wireless Clientsoftware’s default character encoding. The property value is ISO8859_1.

Java Wireless Client software uses the Java platform CLDC mechanism to implementa Java platform character encoding and has its own mechanism to implement anative layer character encoding.

Adding a Character Encoding in the Java Platform

Follow these steps to add a character encoding in the Java platform.

1. Create a directory to hold a new I18N module.

Name the directory midp/src/i18n/your_new_module.

2. Create a classes/com/sun/cldc/i18n/j2me subdirectory in the newmodule.

3. Implement two classes per encoding.

a. Put the classes in the com.sun.cldc.i18n.j2me package.

Call the source files yourEncoding_Reader and yourEncoding_Writer. forexample, ISO2022JP_Reader and ISO2022JP_Writer.

Place the source files in your module’s classes/com/sun/cldc/i18n/j2mesubdirectory.

b. Determine the superclasses for the new classes.

If your reader and writer are stream based, have them extendcom.sun.cldc.i18n.StreamReader andcom.sun.cldc.i18n.StreamWriter.

If your reader and writer are not stream based, have them extendjava.io.Reader and java.io.Writer.

c. Extend the superclasses’ methods.

See the CLDC 1.1 Specification for the list of methods that must be extended.

Chapter 20 Porting the User Message Bundle Service 211

Page 238: Architecture and Design Guide by Oracle

4. Add the new module to the build system.

See the Build Guide for instructions.

Adding a Character Encoding at the Native Layer

Follow these steps to add a native implementation of a decoder and encoder:

1. Create a directory to hold a new I18N module.

Name the directory midp/src/i18n/your-new-module.

2. Create subdirectories in your new module for native and Java platform layercode.

The subdirectory for native code is share/native.

The subdirectory for Java platform code isclasses/com/sun/cldc/i18n/j2me.

3. Create a file to hold your native code.

Call the file your_encoding.c. For example, ISO2022JP.c

4. In the new file, implement the API specified in thecom.sun.cldc.i18n.j2me.Conv class.

5. Implement two classes for the character encoding.

a. Put the classes in the com.sun.cldc.i18n.j2me package.

Call the source files yourEncoding_Reader and yourEncoding_Writer. Forexample, ISO2022JP_Reader and ISO2022JP_Writer.

Put the source files in your module’s classes/com/sun/cldc/i18n/j2mesubdirectory.

b. Have the reader and writer extend the Gen_Reader and Gen_Writerclasses of the com.sun.cldc.i18n.j2me package.

c. Implement constructors for the reader and writer.

The reader’s and writer’s constructors must provide the name of the encoderto their superclasses by calling super(encoding). For example, they might callsuper(ISO2022JP).

Your classes do not need to extend any methods other than the constructor.

6. Add the new module to the build system.

See the Build Guide for instructions.

212 Architecture and Design Guide • December 2008

Page 239: Architecture and Design Guide by Oracle

Changing the Default Screen OrientationThe default locale for the Java Wireless Client software is U.S. English (en-US).Therefore, the default screen presentation uses a left-to-right orientation.

However, some languages, such as Hebrew and Arabic, are read from right to left.When localizing for these languages, the Sun Java Wireless Client software allowsthe screen display to be customized to use a right-to-left orientation.

Customizing the Screen DisplayLeft-to-right screen orientation is found in the system properties file,properties.xml. It is set using the system parameter microedition.locale, asshown in CODE EXAMPLE 20-1.

The microedition.locale parameter sets the layout mode of the screen usingone of the following values:

■ LTR - left-to-right presentation (the default)

■ RTL - right-to-left presentation

Every language supported in the Java Wireless Client software is associated with oneof these screen orientations. Therefore, during the porting process, the portingengineer should be sure to check that the layout mode matches the language beingimplemented.

Changing the screen layout can be done as part of the build process, or duringruntime using the JavaCall API. For example, the screen layout could be changed bythe user via an interactive menu item that sets the screen to the desired layout.When the screen layout menu item is selected, the application sendsCHANGE_LOCALE_EVENT to MIDP and the layout is changed.

Both ways of changing the display are supported by the Java Wireless Clientsoftware.

CODE EXAMPLE 20-1 Setting the Screen Orientation

<property Key="microedition.locale"

Value="LTR"/>

Chapter 20 Porting the User Message Bundle Service 213

Page 240: Architecture and Design Guide by Oracle

214 Architecture and Design Guide • December 2008

Page 241: Architecture and Design Guide by Oracle

21

Games

This chapter discusses the design and porting of the games subsystem of JavaWireless Client software. The games subsystem provides capabilities required bymany arcade-style 2D games.

The games subsystem implements the classes in the packagejavax.microedition.lcdui.game. The subsystem supports sprites (includinganimation, transformations, and collision detection), tiled backgrounds (includinganimated tiles), compositing of multiple visual layers, synchronized screen painting,and key polling and latching.

The games subsystem interacts with the low-level graphics and image subsystemand the device’s native APIs, as FIGURE 21-1 shows.

FIGURE 21-1 Interactions of Subsystems

Engineering and Device RequirementsBefore you start to port the games service, you must meet the followingrequirements:

■ Be familiar with the material in the following documents:

■ MIDP 2.0 Specification, especially the graphics section.

Low-level graphics

Games subsystem

Native platform APIs

and images subsystem

Chapter 21 Games 215

Page 242: Architecture and Design Guide by Oracle

■ The Java™ Virtual Machine Specification, Second Edition.

■ The Java™ Programming Language (3rd Edition).

■ KNI Specification, which is part of the CLDC Reference Implementation’sdocumentation. See http://java.sun.com/products/cldc/.

■ Chapter 10.

■ Understand the following technologies:

■ Low-level graphics capability of your platform

■ MIDP 2.0 Display.flashBacklight method, and your device’s backlightcontrol APIs

■ MIDP 2.0 Display.vibrate method, and your device’s vibrator control APIs

■ Have already ported the following subsystems:

■ Low-level graphics and images subsystem

■ High-level user interface subsystem (specifically, you must have already portedthe display and canvas components)

You must also complete your port of the CLDC component of the Java WirelessClient software stack.

DesignThe games subsystem has the following design requirements and goals:

■ Maximize Code Reuse and Minimize Footprint – Achieved by implementing thegames package on top of the features available from the low-level graphics andimages subsystem

■ Performance – Achieved by taking advantage of the low-level graphics andimages subsystem, so optimizing that functionality also results in performanceimprovements in this subsystem

■ Flexibility – Encourage optimization for specific hardware capabilities duringport time

The games subsystem has three components:

■ Sprites and tiled layers – Visual elements for representing in-game objects

■ Layer manager – Handles the rendering of its layers

■ Game canvas – Extends the Canvas class with an off-screen graphics buffer thatcan be synchronously flushed to the display and the ability to poll for key statusrather than receive events

216 Architecture and Design Guide • December 2008

Page 243: Architecture and Design Guide by Oracle

Sprites and Tiled LayersThe Sprite and TiledLayer classes are subclasses of Layer. The Layer classdefines methods to position itself when it is rendered. A layer renders onto theGraphics object passed to it through the paint method. The layer is positionedwith respect to the origin of this Graphics object.

Both sprites and tiled layers use an Image object as the source for all renderingoperations. The image holds every frame of the sprite or every tile for the tiled layer.The frames and tiles are indexed as described in the MIDP 2.0 Specification.

For performance, the component caches the width and height of a frame or tile. Italso caches arrays for the x coordinates of the frames or tiles and the correspondingy coordinates. The array indices correspond to the frames’ or tiles’ index numbers.See the MIDP 2.0 Specification for more information on index numbers.

Sprites also have collision detection. Collisions occur when non-transparent pixels ina sprite touch another visual element: an image, tiled layer, or another sprite.Collision detection is implemented by querying for the transparency status ofintersecting collision regions. If two non-transparent pixels intersect, a collisionoccurs. This is accomplished because the backing stores of images, tiled layers, andsprites are all images.

Tiled layers can have animated tiles, as described in the MIDP 2.0 Specification. Tosupport animated tiles, the component maintains an “animated-to-static-tile” arraythat maps the negative of an animation index to the individual tile currently beingshown for the animation. For example, if the application developer supplies ananimation index of -1 for a particular cell, the system displays the tile at position 1in the animation-to-tile array.

Example SpriteFIGURE 21-2 shows a source image for a sprite. The component holds the number offrames (16), the source frame height (10), the source frame width (16), and thearrays of x and y coordinates. Following is the array of x coordinates:

[0, 16, 32, 48, 0, 16, 32, 48, 0, 16, 32, 48, 0, 16, 32, 48]

Following is the array of y coordinates:

[0, 0, 0, 0, 10, 10, 10, 10, 20, 20, 20, 20, 30, 30, 30, 30]

Chapter 21 Games 217

Page 244: Architecture and Design Guide by Oracle

FIGURE 21-2 Source Image for a Sprite

The application provides an array with the sequence of frames, such as this:

[0, 1, 2, 12, 13, 14, 8, 9, 10, 4, 5, 6, 3, 15, 11, 7]

Java Wireless Client software displays the frames in that order, as shown inFIGURE 21-3.

FIGURE 21-3 Example Animation Sequence

Example Tiled LayerFIGURE 21-4 shows a source image for a set of tiles.

FIGURE 21-4 Source Image for a Set of Tiles

The component caches the number of tiles (8), the source frame height (10), thesource frame width (10), and the arrays of x and y coordinates. Following is thearray of x coordinates:

[0, 0, 10, 20, 30, 0, 10, 20, 30]

Following is the array of y coordinates:

0

16 32 48

10

20

30

0

10 20 30

10

218 Architecture and Design Guide • December 2008

Page 245: Architecture and Design Guide by Oracle

[0, 0, 0, 0, 0, 10, 10, 10, 10]

During a rendering operation, the grid location (x, y) containing i, is drawn usingthe following algorithm:

■ The static tile of index i, if i is positive.

■ The current frame of the animated tile sequence -i, if i is negative.

■ A tile of index 0 is treated as empty. Nothing is rendered for cell locations withthis tile.

For example, assume the application specifies that an animated tile is needed, andthe first tile of its animation is tile 5. For this, the component provides an animationindex of -1, and the value (0, 5). Further assume that the application provides thefollowing values for the tiled layer’s grid:

[ 0, 0, 1, 3, 0, 0,

0, 1, 4, 4, 3, 0,

1, 4, 4, 4, 4, 3,

-1, -1, -1, -1, -1, -1]

In this case, the tiled layer is rendered as shown in FIGURE 21-5.

FIGURE 21-5 Tiled Layer

Layer Manager ComponentThe LayerManager class manages the rendering of multiple layers. The layermanager has a view window, which is the region to be rendered, and only renderslayers with coordinates in the view window.

When the layer manager paints the screen, it follows these steps:

1. Gets the graphics object.

2. Sets the clipping region to the view window.

Chapter 21 Games 219

Page 246: Architecture and Design Guide by Oracle

3. Renders the layers in the view window by calling the layer’s paint method withthe graphics object.

Game Canvas ComponentThe GameCanvas component provides an off-screen buffer with synchronousrepaints and the ability to poll for key events. The capabilities support application-specific game loops, in which applications can query the status of keys, advance thegame state, and synchronously update the display during each iteration of the loop.

The component implements the off-screen buffer as a mutable image and supplies itto applications through a Graphics object. Applications get the Graphics object bycalling the getGraphics method. The component provides synchronous repaintsby updating the screen only when the application flushes the Graphics object.

The application can turn off key events when it creates a game canvas. In this case,the application polls for keys instead of having key events propagate to it.

Design Rationale, Notes, and ConsiderationsThe games subsystem is implemented in the Java programming language forsimplicity and portability. It interacts heavily with the low-level graphics and imagessubsystem. For example, all sprites, tiled layers, and layer managers render onto aGraphics object. Sources of sprite frames and tiled layer tiles are Image objects. Agame canvas renders onto a Graphics object.

Your port must efficiently use the components of the low-level graphics and imagesubsystem. When you make device-specific optimizations for the underlyingGraphics and Image objects, maintain compatibility with the games subsystem.

PortingBecause Java Wireless Client software’s implementation of this subsystem iscompletely coded in the Java programming language, there are no native interfacesfor game implementation. This simplifies implementation and allows for platform-specific optimization.

Because the capabilities of devices vary drastically with respect to the functionalityin this package (for example, sprites), a port must be individually optimized to takeadvantage of these capabilities.

220 Architecture and Design Guide • December 2008

Page 247: Architecture and Design Guide by Oracle

Porting GameCanvasGameCanvas adds additional functionality to Canvas, particularly with respect tokey polling and synchronous flushing. Neither of these features require additionalnative APIs and can be implemented entirely in the Java programming language.

Depending on the port, it might be advantageous to replace some of theimplementation with native code. This is a decision that must be made during theport, after evaluating the features that the device offers.

Key polling can be implemented by short-circuiting all key events destined forCanvas (and its subclass GameCanvas) so that the key states are stored in a buffer inthe platform code. GameCanvas.getKeyStates might then be implemented sothat it reads and then clears the buffer. This avoids key events for Canvas beingpropagated through the usual event mechanism.

Synchronous flushing is currently implemented using a MutableImage as therendering buffer. If the platform provides a data structure that can be efficiently usedas the destination of a javax.microedition.lcdui.Graphics object, then thebuffer can be implemented using the data structure to avoid object creation andother overhead.

Porting Sprite and TiledLayer

Both classes are subclasses of Layer. However, Layer cannot be subclassed by thedeveloper, so any port has some freedom in implementing these classes.

Sprite and TiledLayer are very closely tied to the packagejavax.microedition.lcdui.Image. In its current implementation, the easiestway to speed the rendering performance of these classes is to optimizeGraphics.drawRegion with any operation that quickly transfers pixels of imagedata from the source to the destination.

However, to optimize the implementation for a specific device, you must ensure thatthe device’s representation of Sprite and TiledLayer can easily use an Image assource. This for creation and rendering purposes and also to implement pixel-levelcollision detection.

Collision detection can be implemented using a bounding box or at the individualpixel level. If the target device does not offer pixel-level detection, it might bepossible to reuse parts of the code that perform rendering transformed regions ofimages to do transformed traversal of pixels within Sprite and TiledLayer. Thisagain underlines the necessity to carefully design the relationship between therepresentation used for Image and Sprite and TiledLayer.

Chapter 21 Games 221

Page 248: Architecture and Design Guide by Oracle

222 Architecture and Design Guide • December 2008

Page 249: Architecture and Design Guide by Oracle

A

Performance Notes

This document describes how to analyze and tune the performance of the JavaWireless Client software for the following aspects of performance:

■ Application startup time

■ Runtime performance

■ Memory footprint

Application Startup TimeApplication startup is measured from the time a user starts an application to thetime when the application finishes painting the first interactive screen. Users mightperceive different application startup times for various reasons. For example, someapplications present splash screens while they load resources and initializethemselves. The splash screen is interactive because it enables the user to exit theMIDlet. However, it does not give the user full access to the MIDlet’s functionality,so a user might not consider the MIDlet started at that point.

Measuring Startup TimeThe Java Wireless Client software does not directly measure startup time. Instead, ituses the system’s timer to generate timestamps at particular points during thestartup process. In order to print the system time to the console at the pointsdescribed below, build the system with the parameter MEASURE_STARTUP set totrue in the following file:

midp/src/configuration/configuration_xml/platform/constants.xml

Appendix A Performance Notes 223

Page 250: Architecture and Design Guide by Oracle

The following list describes the output.

1. Before the VM starts and MIDP is initialized.

The output is: System Startup Time: Begin at systemTime

2. After a pre-installed MIDlet is launched, if the Java Wireless Client software usesa Java AMS.

The output is Application Startup Time: Begin at systemTime.

If your port uses the native AMS, add code to report this. The native AMS in theJava Wireless Client software does not include this code.

3. After the system paints the screen during a screen change event, if no priorscreens were active.

The output is Startup Time: End at systemTime.

4. When the system processes a MIDlet’s move to the foreground, after the systempaints the content of the MIDlet’s displayable.

The output is Startup Time: End at systemTime.

5. At the beginning of foreground and background switching.

The output is:

Switch To Background Time: Begin at systemTime

Switch To Foreground Time: Begin at systemTime

6. At the end of foreground/background switching.

The output is Startup Time: End at systemTime.

System startup time is the interval between point 1 and either point 3 or point 4,whichever comes first. Application startup time is the interval between point 2 andeither point 3 or point 4, whichever comes first.

Handling Startup Time VariancePerformance measurements vary from run to run, especially when measuringstartup time. The differences in time can be caused by the following factors:

■ Low system timer resolution

■ Unpredictable system activity, such as garbage collection (GC)

■ Other background activity in the VM, such as MIDlets running in the background

224 Architecture and Design Guide • December 2008

Page 251: Architecture and Design Guide by Oracle

Averaging a number of measurements keeps you from thinking that an unusuallyshort or long startup time is a typical interval. You could average in different ways,such as:

■ Launch a MIDlet a number of times (for example, ten) from the AMS and averagethe obtained times.

■ Start the Java Wireless Client software some number of times (such as ten).During each run, launch a MIDlet some number of times. Average the valuestaken from one launch (such as the second) from each run.

The first method is suitable unless there are variations between starting the firstMIDlet and starting subsequent ones. For example, if subsequent MIDlet starts causea GC, it provides variation in startup times. The second method reduces this impactbecause the MIDlets associated with the chosen launch always start under similarconditions.

Starting an ApplicationThis section focuses on application startup time.

The Java Wireless Client software uses different procedures depending uponwhether it is in single-tasking or multi-tasking mode. The following table describesthe initial steps.

Note – Steps 2 through 5 are the same in both releases.

TABLE A-1 Initial Steps in the Procedure for Starting a MIDlet

Step Single-Tasking Mode Multi-Tasking Mode

0 Terminate the current VM (Java AMSonly).

1 Start the new VM with theMIDletSuiteLoader class.

Start a new task with the classAppIsolateMIDletSuiteLoader.

2 Initialize MIDP subsystems and services. Initialize MIDP subsystems and services.

3 Create and register the MIDlet instance. Create and register the MIDlet instance.

4 Call the startApp method of the MIDlet. Call the startApp method of the MIDlet.

5 Paint the MIDlet’s displayable. Paint the MIDlet’s displayable.

Appendix A Performance Notes 225

Page 252: Architecture and Design Guide by Oracle

As implied by Step 0, the single-tasking mode with a native AMS does not have acurrent VM to terminate. However, Step 0 does not significantly affect applicationstartup time. With either type of AMS, the time required to get through the initialsteps of the initialization in single-tasking mode is about four times longer than inmulti-tasking mode. Values of about 40 milliseconds compared with 10 millisecondswere seen on typical platforms. This is about five to ten percent of startup time forthe simplest MIDlets.

Times are approximate because many things affect startup time. For example, if aport with a native AMS does not have a running VM when the MIDlet is launched,Step 1 does not launch a task, but starts a virtual machine. This negatively impactsstartup time for the first MIDlet launched. It does not impact other MIDlets becausethe Java Wireless Client software keeps executing a running VM even if it no longerhas active MIDlets. It does not include Step 0.

As another example, low memory can lengthen startup time. If memory is low,memory allocation can cause a GC, which dramatically lengthens startup time.Other system activity, such as the use of a just-in-time (JIT) compiler, can also affectstartup time. See “Optimizing the System for Improved Application Startup Time”on page 227 for more information.

Multitasking, then, has the following advantages and disadvantages for applicationstartup time:

■ It does not require cycling the VM or reloading system classes.

■ It has an AMS task running constantly, so shared resources are already loaded.Reloading shared resources can slow system startup.

■ It has less memory for user applications, which can cause system activity such asa GC.

Optimizing a MIDlet for Improved ApplicationStartup TimeAs noted in “Starting an Application” on page 225, the first step or steps (throughStep 1) of starting a simple application can take five to ten percent of a simpleapplication’s startup time. However, these same steps take a much smallerpercentage of the time for a complex MIDlet with a lot of startup time initialization.

226 Architecture and Design Guide • December 2008

Page 253: Architecture and Design Guide by Oracle

Because the first steps take a small percentage of time, the following suggestionsconcern the steps that a MIDlet writer can take to minimize the time required forStep 3 through Step 5:

■ Minimize the number and size of startup classes. Step 3 and Step 4 create aMIDlet’s main classes. The system uses class verification for each non-ROMizedclass it loads. Class verification slows startup time for MIDlets that load a lot ofclasses or large classes at this time. To improve startup time, have a MIDlet loadthe minimum number of classes when it starts.

■ Request only immediately required resources. Step 4 allocates and initializesMIDlet resources. Memory is one such resource and, as noted in “Starting anApplication” on page 225, the multitasking environment makes less memoryavailable to each MIDlet than an environment that runs only one MIDlet at atime. If memory is low, memory allocation can cause a GC, which dramaticallylengthens startup time. To minimize this risk, request only the resources yourMIDlet initially requires during MIDlet startup.

■ Keep the initial displayable simple. Step 5 paints the content of a MIDlet’sdisplayable. The time required for painting depends on the complexity of thedisplayable. Covering the background and other large surfaces with small tileimages, using many layers, and using many user-interface elements increases thetime required to paint the screen. Simpler screens take less time to paint, whichimproves startup time.

Optimizing the System for Improved ApplicationStartup TimeThe following sections provide suggestions for optimizing the Java Wireless Clientsoftware to improve application startup time.

Minimizing the Static Initialization of System ClassesStep 2 and Step 3 of MIDlet startup cause the initialization of many system classes.They are usually ROMized, so they load quickly. However, the system calls the staticinitializer associated with each class that it loads, and that can be time consuming.Avoid creating long or resource intensive static initializers in classes requested atstartup.

Appendix A Performance Notes 227

Page 254: Architecture and Design Guide by Oracle

Controlling the JIT Compiler and Ahead-of-TimeCompilationThe Java Wireless Client software has a JIT compiler. Using this compiler is optional,but if you use it your runtime performance can be up to four times better than usingthe interpreter only. It is especially beneficial to MIDlets that do calculations for 2Dor 3D graphics.

Unfortunately, although the JIT compiler’s strategy is to compile long-running andoften-called methods, it often compiles methods during startup that are only calledonce by the MIDlet or system. For these methods, compilation lengthens theMIDlet’s startup time without improving the MIDlet’s runtime performance.

To minimize this problem, specify the startup methods that are not called again andare not performance critical as methods not to be processed by the JIT compiler.Before building, specify the methods with the DontCompile property in themidp/build/common/config/rom.config file as follows:

DontCompile = methodName

Specify that methods be precompiled if they meet the following criteria:

■ You call performance-critical methods during startup

■ You call some methods often

■ You have very large methods

Precompiling at build time is called Ahead of Time Compilation (AOTC). AOTCgives you the benefits of compilation without using the JIT compiler during startup.Before building, specify AOTC for appropriate methods with the Precompileproperty in the midp/build/common/config/rom.config file as follows:

Precompile = methodName

Both the DontCompile and Precompile properties can have values that containthe * wild card. For example, the following is a short way to indicate that none ofthe methods of a particular class are to be compiled:

DontCompile = FullClassName.*

See the “Ahead-of-Time Compilation Support” and “ROMizer” chapters in theCLDC-HI Architecture Guide for further information about these mechanisms.

Giving the VM HintsUsing a static list of methods to control the JIT compiler improves startupperformance, but completely disabling the JIT compiler helps even more. Starting anapplication with the JIT compiler disabled can be up to 50 percent faster.

228 Architecture and Design Guide • December 2008

Page 255: Architecture and Design Guide by Oracle

The Java Wireless Client software has an optimization that disables the JIT compilerduring application startup. It reenables the JIT compiler after an application’sstartup phase is finished.

The optimization is designed to be more general than just disabling the JIT compiler.The optimization simply notifies the VM of the beginning and the ending of anapplication’s startup phase. The CLDC HotSpot Implementation can adjust anyinternal VM parameters during the application startup period. However, the currentadjustment only disables the JIT compiler.

The challenge in creating the VM-hinting optimization is determining the end of theapplication startup phase. The optimization uses the moment when a MIDletinstance is created and registered to the system. This is after startup Step 3. Thedecision makes system behavior less efficient than ending at Step 5 but that stepcannot be used because it is not reached by MIDlets that are designed to run in thebackground. Those MIDlets have no displayable. Similarly, startup Step 4 cannot beused because some MIDlets, especially those used for benchmarks, never leave thestartApp method.

The VM hinting is built into the Java Wireless Client software. You cannot turn it onor off using build time or run time options. However, you can use its internal API togive the VM hints about any additional startup that you add. For example, if youimplement an optional package that needs initialization when a MIDlet starts, youcan add a hint for your optional package in the same way that the product provideshints for its core startup activity.

The Java programming language API to use for giving the VM hints is part of thecom.sun.midp.main.MIDletSuiteLoader class interface:static public void vmBeginStartUp(SecurityToken token, int midletIsolateId)

static public void vmEndStartUp(SecurityToken token, int midletIsolateId)

Surround your initialization with calls to these methods. You can add any number ofVM hinting intervals, but you must make sure that each interval has both abeginning and an ending. You can nest intervals.

The vmBeginStartUp and vmEndStartUp methods call the native API provided bythe CLDC HotSpot Implementation:

void JVM_SetHint(int task_id, int hint, int param)

You can also use this native API to give the VM hints if you have implementedadditional initialization in both the Java programming language and native code.

Appendix A Performance Notes 229

Page 256: Architecture and Design Guide by Oracle

Disabling the Class VerifierThe Java Wireless Client software must verify a MIDlet’s non-ROMized classes.Verification at startup can be lengthy. The system can disable the class verifier toremove this delay. To make it possible for the system to disable the class verifier, setthe following options before building the system:

■ Set the CLDC HotSpot Implementation build option ENABLE_VERIFY_ONLY totrue.

■ Set the Java Wireless Client software build option USE_VERIFY_ONCE to true.

Disabling class verification introduces the possibility of creating security holes in thesystem. To ensure that the system is secure, the following additional requirementsmust be met.

■ The system must verify the MIDlet suite’s classes during its installation.

■ The system must confirm that the classes have not been changed sinceinstallation.

This optimization is possible because the Java Wireless Client software starts onlyinstalled MIDlets. The system verifies all classes in a MIDlet suite’s JAR file when itinstalls the MIDlet, and aborts the installation if any class fails. If the classes aresuccessfully verified, the system evaluates the hash value of the JAR file and saves itto secure persistent storage. When the system starts the MIDlet, the system checksfor the hash value. If the hash is present, and is the same as JAR file’s hash value, thesystem disables the class verifier when it starts the MIDlet. Otherwise, the systemuses the class verifier in the usual way.

When the USE_VERIFY_ONCE and ENABLE_VERIFY_ONLY build options are set, theJava Wireless Client software automatically fulfills the first requirement by verifyingthe MIDlet’s classes at install time. However, you must take special precautions toensure that the hash value is stored securely. If the hash value is not stored securely,an attacker could modify the JAR file, recompute the hash value, and overwrite thepreviously stored hash value. This would effectively bypass class verification andopen a large security hole.

Caching ImagesMIDlets can load image resources, such as logos and splash screens, during startupor at runtime. It can load different image resources at different times. Depending onthe characteristics of the target device, it might be faster to cache images on thedevice and get them from the cache at startup, instead of from the JAR file. Theimage caching optimization is controlled by the USE_IMAGE_CACHE build option,which is set to true by default.

230 Architecture and Design Guide • December 2008

Page 257: Architecture and Design Guide by Oracle

Loading an image from the JAR file requires two steps. The system must read theimage data and decompress it. If the image is in PNG format, which is likely becausePNG is the only format for which the MIDP 2.1 Specification guarantees support, thesystem must convert it to the platform’s native format. As an alternative, whenUSE_IMAGE_CACHE is set to true, the Java Wireless Client software caches all imageresources in a JAR file to the MIDlet suite’s persistent storage. The system caches theimages in the platform’s native image format.

The porting team can determine which of these methods is faster, because it dependson the speed from which persistent storage can be read. It might be faster to load asmall portion of data from the JAR file.

▼ Caching JAR File EntriesThe Java Wireless Client software provides caching for the entries (although not thecontent) of non-image resources in the JAR file. For example, it can cache the entriesassociated with byte codes. The cache stores any accessed entries of the JAR file, aswell as the entries traversed during an access request. The system then getsinformation from the cache, such as the entry’s location in the JAR file, to improvethe speed of executing subsequent requests.

Using an entry’s location is somewhat faster than searching for the entry from thebeginning of the JAR file. The optimization is best for MIDlets that load manyresources.

Follow these steps to enable caching of JAR file entries:

1. Set the CLDC Hotspot Implementation build optionENABLE_JAR_ENTRY_CACHE to true.

It is false by default.

2. Build the system.

3. Use the runtime option +CacheJarFileHandles.

The procedure for using a runtime option depends on your AMS as follows:

■ Java AMS - Put the runtime option at the front of the command line you use tostart the main system binary, runMIDlet. For example:

runMIDlet +CacheJarFileHandles internalcom.sun.midp.appmanager.MVMManager

Appendix A Performance Notes 231

Page 258: Architecture and Design Guide by Oracle

■ Native AMS - Provide the runtime option in your ported code as an argument tothe JVM_ParseOneArg function as shown in the following example:

If you have other runtime options for the VM, call JVM_ParseOneArg() in aloop.

Runtime PerformanceThis section covers the following aspects of improving runtime performance:

■ Performance metrics

■ Profiling the System

■ Runtime Optimizations

Performance MetricsEvaluating runtime performance requires metrics (benchmarks) that are measurable,persistent, and comparable. The following benchmarks, each of which reports anumeric value that you can compare across your Java Wireless Client softwareoptimizations, are widely accepted:

■ MorphMark

■ JBenchmark

■ JBenchmark2

■ Amark v1.3

■ TaylorBench

■ eembcBM

char *argv[] = { "+CacheJarFileHandles", 0};

{ ... JVM_ParseOneArg(1, argv); ...}

232 Architecture and Design Guide • December 2008

Page 259: Architecture and Design Guide by Oracle

▼ Profiling the SystemThe most effective way to improve runtime performance is to optimize the system’sbottlenecks. You find bottlenecks in the Java Wireless Client software by using thebuilt-in Java platform profiler. The following steps describe how to enable and runthe profiler.

1. Set the CLDC Hotspot Implementation build option ENABLE_WTK_PROFILER totrue.

2. Set the Java Wireless Client software build option USE_JAVA_PROFILER totrue.

3. Build the system.

4. Specify the runtime option +UseExactProfiler when you start the JavaWireless Client software.

Provide this parameter as you did the +CacheJarFileHandles parameter.

Enabling the profiler affects the execution speed of the Java Wireless Client softwarebut, as much as possible, the profiler excludes the time spent for its own activity.

The profiler automatically dumps the data it collects when a task exits or when theJava Wireless Client software exits.

Runtime OptimizationsMany optimizations are already built into the Java Wireless Client software. For evenbetter performance, you can apply the techniques in “Optimizing the System forImproved Application Startup Time” on page 227 as runtime optimizations. You canalso apply the following platform-specific optimizations to your port of the RecordManagement System (RMS).

CachingModern mobile devices often use flash memory to store persistent data. Flashmemory typically provides fast read operations but slower write operations. Tocompensate for the slower write operations, Java Wireless Client software write-caching is optimized. The system caches in memory the data to be written to theRMS and only writes it when the memory allotted to the cache is full or when anRMS storage area is closing. If a power failure or abnormal system terminationoccurs, unflushed data in the RMS cache might be lost, but the RMS does notbecome inconsistent.

Appendix A Performance Notes 233

Page 260: Architecture and Design Guide by Oracle

To control the size of the RMS write cache, set the value of the RMS_CACHE_LIMITconstant in the file constants.xml in the directorymidp/src/configuration/configuration_xml/platform.

The Java Wireless Client software does not have a read cache because the read speedof the cache’s memory is typically similar to the read speed of the storage memory.Read caching provides no benefit in this case and can even hurt performance due tocache maintenance overhead. If your device has a slower read speed for storagememory than for RAM, consider implementing read caching in your port.

Note that although the Java Wireless Client software does not have a read cache, itcan read from the write cache when necessary. If the system or a MIDlet tries to reada record that is still in the write cache, it receives the data in the write cache, not theolder data in storage memory.

IndexingThe RMS API provides a facility for MIDlets to retrieve records using recordidentifiers (recordIds). The com.sun.midp.rms.RecordStoreIndex classmaintains the offsets of each record identifier and free block. The class has animplementation that maintains a linear index and an implementation that maintainsa tree index.

The two index types store data differently and have different performancecharacteristics. The linear index stores the offsets in RAM in a linear data structurethat provides O(n) worst-case search time for the needed offset. The tree index storesthe offsets in separate RMS storage, which is partly loaded into RAM duringruntime. The tree index uses a B-tree structure that improves the worst-case searchtime to O(log(n)), but is more complex to maintain. If your device has slow writeoperations for its storage memory, the overhead to support the tree structure canexceed the benefit of a faster search.

Choose which index type to use based on the performance characteristics of yourdevice. Specify your choice with the USE_RMS_TREE_INDEX build option. Set itsvalue to true to use the tree index, and to false to use the linear index.

BufferingAn efficient way to use flash memory and other block devices is to read and writelarge blocks of data. Larger blocks of data require fewer read and write operations toprocess a given volume of data. To increase the amount of data available during awrite operation (that is, to provide a larger data block), the Java Wireless Clientsoftware uses internal write buffering when it flushes its cache.

234 Architecture and Design Guide • December 2008

Page 261: Architecture and Design Guide by Oracle

The Java Wireless Client software does not buffer RMS read operations. The reasonsare the same as those for not providing read caching. As with read caching, if yourdevice reads from storage memory more slowly than it reads from RAM, considerimplementing read buffering in your port.

Memory FootprintYou can measure the following two types of memory footprint:

■ Static footprint - The amount of memory the device needs to hold the programcode. The device might store the code on disk, on a flash card, in ROM, or insome other location.

■ Dynamic footprint - The amount of memory the Java Wireless Client softwareuses when it runs. The footprint varies depending on the product’s workload. Theproduct’s Java runtime environment has a dynamic footprint, as does its C/C++component. Both dynamic footprints consist of memory used for their code (thestatic footprint affects this number), their heaps, and their stacks.

▼ Measuring FootprintMeasuring static and dynamic footprints are platform-specific activities. JavaWireless Client software does not provide measurement tools, but this sectiondescribes techniques you can use.

The static footprint of the Java Wireless Client software with a Java AMS is the filesize of the system binary runMIDlet. System utilities, such as the Linux platformsize utility provide detailed information. The static footprint of the Java WirelessClient software with a native AMS is the sum of the sizes of all of the systembinaries.

Static footprint includes other application resources too, such as the system’s PNGfiles. The size of those resources change less frequently as you do your port, than thesize of the binary. Therefore, you probably need only check the size of your binariesas you improve your port.

The dynamic footprint, because it depends on the activity level of the Java WirelessClient software, is not a single number. To find a representative dynamic footprint,follow these steps.

Appendix A Performance Notes 235

Page 262: Architecture and Design Guide by Oracle

1. Decide the activity level to measure.

For example, you might measure the dynamic footprint when the system isrunning but no MIDlet suites have been started, or when the system is running aparticular MIDlet suite, such as a ‘Hello World!’ MIDlet.

2. Use system tools to measure the footprint at different times during the chosenactivity level.

System tools include the task manager on Windows platforms and a monitor ofRAM footprints on Linux platforms.

3. Use the measurements to compute an average value or find the maximum value.

Minimizing Static and Dynamic FootprintBecause devices have limited resources, this section shows you how to minimize thestatic and dynamic footprint of the Java Wireless Client software without hurtingstartup or runtime performance. See the book Java Platform Performance: Strategies andTactics (Addison Wesley, 2000) for more information on performance issues ingeneral, and the RAM footprint of a Java application in particular. Although thebook covers the Java SE platform, many of the ideas also apply to the Java MEplatform.

Two optimizations, code sharing of system classes and image sharing, are built intothe Java Wireless Client software. Sharing the Java platform system classes amongall tasks decreases the dynamic footprint. Instead of the footprint including the sizeof the system classes times the number of tasks, the footprint only includes the sizeof the system classes once. The software does not share users’ classes.

The Java Wireless Client software also shares system image resources. The tasks usethe images to render user interface (UI) elements. For example, all skin images areshared.

The following sections describe optimizations that you can make.

Heap Capacity for the Java PlatformThe VM allocates a heap for Java platform objects. That heap is part of the JavaWireless Client software’s common native heap. The default size of the Java platformheap is between one megabyte and four megabytes. If multitasking is not enabled,the default size is one megabyte minimum and maximum.

The JVM_SetHeapLimit API is provided to implement a user-administered spacein the Java platform heap. When this feature is on, the Java platform heap size is notadjustable. However, it is possible to set build flags to turn off theJVM_SetHeapLimit API, in which case the heap size is dynamically adjustable.

236 Architecture and Design Guide • December 2008

Page 263: Architecture and Design Guide by Oracle

When the JVM_SetHeapLimit API is disabled, you can control the minimum andmaximum sizes of the Java platform heap by using the following runtime options:

■ =HeapMinSize

■ =HeapCapacitySize

Provide these parameters as you did the +CacheJarFileHandles parameter. TheJava Wireless Client software passes your values to its VM. For example, to set theinitial size of the Java platform’s heap to four megabytes and the maximum size to16 megabytes, set the options as follows:

■ =HeapMin4M

■ =HeapCapacity16M

To help determine the required capacity of the Java platform heap, track the heap’ssize with the following APIs:.

■ public long java.lang.System.freeMemory()

■ public long java.lang.System.totalMemory()

Have your code request a full GC before calling these methods so that you getprecise values. Because getting the memory size this way is an expensive andperformance-impacting activity, consider using the following strategy to estimate thesize requirements of the Java platform heap:

■ Start the Java Wireless Client software with a =HeapCapacitySize option thatenables the application to start without an error.

■ Exit the Java Wireless Client software, and restart it with a smaller Size.

■ Repeat the previous step until you receive an error indicating that you are out ofmemory.

▼ Minimizing the Space Used by AOT and JITCompilationThe size of a compiled method can be up to eight times bigger than the size of themethod’s original bytecode. The following steps describe how to minimize thefootprint of compiled code.

1. Select the most time-intensive, frequently-used methods for AOTC andprohibit JIT compilation for large methods that are not performance critical andmethods called only once (such as static initializers).

Base your selections on collected profiler data or general reasoning. See“Controlling the JIT Compiler and Ahead-of-Time Compilation” on page 228 forinstructions on using the profiler.

Appendix A Performance Notes 237

Page 264: Architecture and Design Guide by Oracle

2. Use the Dontcompile and Precompile settings to implement your choices.

See “Controlling the JIT Compiler and Ahead-of-Time Compilation” on page 228for instructions.

Selecting methods to not compile and to precompile also improves performance inanother way. It stops the JIT compiler from creating and re-creating compiled codethat the system throws away when memory is low. The JIT compiler uses memoryfrom the Java platform heap to compile methods. When memory is low, the systemoften throws away the least-used code created by the JIT compiler. As part of thedeletion, the system reverts the methods to their uncompiled bytecodes. The JITcompiler might select those methods for recompilation when more memory becomesavailable.

Minimizing Full Garbage Collections at StartupThe Java Wireless Client software has a generational mark-sweep-compact garbagecollector that automatically reclaims memory from unused objects. It runs quicklyacross the new generation segment of the Java platform heap. However, when thenew generation segment is full, the garbage collector reclaims memory by doing afull GC. It also increases the size of the Java platform heap at this time, unless theheap has reached its maximum size.

Because a full GC creates a noticeable pause, which negatively impacts performance,it is best to minimize your chances of needing one during startup. To do this, startthe Java Wireless Client software with a reasonable minimum heap size. See theCLDC Hotspot Implementation Virtual Machine White Paper for details.

SummaryYou can improve performance of your Java Wireless Client software in many ways.To improve application startup time, use the following suggestions when you createMIDlets:

■ Minimize the number and size of the classes you create during startup.

■ Request only immediately required resources during initialization.

■ Keep your initial displayable simple.

Use the following suggestions to improve performance in your system:

■ Minimize the static initialization of the system classes used during applicationstartup.

■ Control the behavior of the JIT compiler.

238 Architecture and Design Guide • December 2008

Page 265: Architecture and Design Guide by Oracle

■ Use AOTC as necessary.

■ Give the VM hints regarding any additional startup blocks you add to the system.

■ Disable class verification for installed MIDlets.

■ Cache image resources if this is appropriate for your device.

■ Cache JAR file entries for faster resource loading.

■ Use proper caching, buffering, and indexing for RMS operations.

■ Increase memory in the Java platform heap to decrease the number of GCsrequired.

Appendix A Performance Notes 239

Page 266: Architecture and Design Guide by Oracle

240 Architecture and Design Guide • December 2008

Page 267: Architecture and Design Guide by Oracle

Glossary

API Application Programming Interface. A set of classes used by programmers towrite applications, which provide standard methods and interfaces andeliminate the need for programmers to reinvent commonly used code.

AMS Application Management Service. The system functionality that completestasks such as installing applications, updating applications, and switchingforegrounds.

Application list The screen that lists all of the installed applications. The user gets to this screenby pressing the Apps soft key on the home screen. The application list uses textcolor to show which applications are running. It also provides a system menuthat enables the user to perform application management tasks on thehighlighted application.

Background An application state in which the application does not receive events from itsinput stream and its displayable is not rendered to the screen.

CDC Connected Device Configuration. A Java ME platform configuration fordevices, it requires a minimum of 2 megabytes of memory and a networkconnection that is always on.

CLDC Connected Limited Device Configuration. A Java ME platform configurationfor devices with less than 512 kilobytes of RAM and an intermittent (limited)network connection, it uses a stripped-down Java virtual machine called theKVM, as well as several minimalist Java platform APIs for application services.

Configuration Defines the minimum Java runtime environment (for example, the combinationof a Java virtual machine and a core set of Java platform APIs) for a family ofJava ME platform devices.

Foreground The application state in which the application is rendered to the device displayand the input stream is passed to it.

Foreground switching Changing which application is in the foreground by shifting the focus from oneapplication to another.

GCF Generic Connection Framework. A part of CLDC, it improves networkconnectivity for wireless devices.

Glossary 241

Page 268: Architecture and Design Guide by Oracle

Home screen The main screen of the application manager. This is the screen the user seesafter they exit an application.

HTTP HyperText Transfer Protocol. The most commonly used Internet protocol,based on TCP/IP, which is used to fetch documents and other hypertextobjects from remote hosts.

HTTPS Secure HyperText Transfer Protocol. A protocol for transferring encryptedhypertext data using Secure Socket Layer (SSL) technology.

JAD file Java Application Descriptor file. A file provided in a MIDlet suite that containsattributes used by application management software (AMS) to manage theMIDlet’s life cycle, as well as other application-specific attributes used by theMIDlet suite itself.

JAR file Java Archive file. A platform-independent file format that aggregates manyfiles into one. Multiple applications written in the Java programming languageand their required components (.class files, images, sounds, and otherresource files) can be bundled in a JAR file and provided as part of a MIDletsuite.

Java CommunityProcessTM (JCPTM)

program Java Community Process program. An open organization of internationaldevelopers and licensees who develop and revise Java platform specifications,reference implementations, and technology compatibility kits using a formalsubmission and approval process.

Java ME platform Java Platform, Micro Edition. A group of specifications and technologies thatpertain to running the Java platform on small devices, such as cell phones,pagers, PDAs, and set-top boxes. More specifically, the Java ME platformconsists of a configuration (such as CLDC or CDC) and a profile (such as MIDPor Personal Basis Profile) tailored to a specific class of device.

Java SpecificationRequest (JSR) A proposal for developing new Java platform technology, which is reviewed,

developed, and finalized into a formal specification by the JCP program.

Java Virtual Machine A software “execution engine” that safely and compatibly executes the bytecodes in Java class files on a microprocessor.

KVM A Java virtual machine designed to run in small devices, such as cell phonesand pagers. The CLDC configuration is designed to run in a KVM.

LCD Liquid Crystal Display. A common kind of screen display often used in smalldevices.

LCDUI Liquid Crystal Display User Interface. A user interface toolkit for interactingwith LCD screens in small devices. More generally, a shorthand way ofreferring to the MIDP user interface APIs.

MIDlet An application written for MIDP.

242 Architecture and Design Guide • December 2008

Page 269: Architecture and Design Guide by Oracle

MIDlet suite A way of packaging one or more midlets for easy distribution and use. EachMIDlet suite contains a Java application descriptor file (.jad), which lists theclass names and files names for each MIDlet, and a Java Archive file (.jar),which contains the class files and resource files for each MIDlet.

MIDP Mobile Information Device Profile. A specification for a Java ME platformprofile, running on top of a CLDC configuration, which provides APIs forapplication life cycle, user interface, networking, and persistent storage insmall devices.

Obfuscation A technique used to complicate code by making it harder to understand whenit is de-compiled. Obfuscation makes it harder to reverse-engineer applicationsand therefore, steal them.

Optional Package A set of Java ME platform APIs that provides additional functionality byextending the runtime capabilities of an existing configuration and profile.

PNG Portable Network Graphics. An image format commonly used with MIDP thatcan be compressed, transmitted, and stored without losing image quality.

Preemption Taking a resource, such as the foreground, from another application.

Preverification Due to limited memory and processing power on small devices, the process ofverifying Java technology classes is split into two parts. The first part ispreverification and done off-device using the preverify tool. The second part,which is verification, is done on the device at runtime.

Profile A set of APIs added to a configuration to support specific uses of a mobiledevice. Along with its underlying configuration, a profile defines a completeand self-contained application environment.

Provisioning A mechanism for providing services, data, or both to a mobile device over anetwork.

Push Registry The list of inbound connections, across which entities can push data,maintained by the Java Wireless Client software. Each item in the list containsthe URL (protocol, host, and port) for the connection, the entity permitted topush data through the connection, and the application that receives theconnection.

RMI Remote Method Invocation. A feature of Java SE technology that enables Javatechnology objects running in one virtual machine to seamlessly invoke objectsrunning in another virtual machine.

RMS Record Management System. A simple record-oriented database that enables aMIDlet to persistently store information and retrieve it later. MIDlets can alsouse the RMS to share data.

SMS Short Message Service. A protocol allowing transmission of short text-basedmessages over a wireless network.

Glossary 243

Page 270: Architecture and Design Guide by Oracle

SOAP Simple Object Access Protocol. An XML-based protocol that allows objects ofany type to communicate in a distributed environment, it is most commonlyused to develop web services.

SSL Secure Sockets Layer. A protocol for transmitting data over the Internet usingencryption and authentication, including the use of digital certificates and bothpublic and private keys.

Sun Java Device TestSuite A set of Java programming language tests developed specifically for the

wireless marketplace, providing targeted, standardized testing for CLDC andMIDP on small and handheld devices.

SVM Single Virtual Machine. A mode of the Java Wireless Client software, it can runonly one MIDlet at a time.

task At the platform level, each separate application that runs within a single Javavirtual machine is called a task. The API used to instantiate each task is astripped-down version of the Isolate API defined in JSR 121. See the CLDCHotSpot Implementation Architecture Guide for more information.

TCP/IP Transmission Control Protocol/Internet Protocol. A fundamental Internetprotocol that provides for reliable delivery of streams of data from one host toanother.

WAE Wireless Application Environment. It provides an application framework forsmall devices, by leveraging other technologies such as WAP, WTP, and WSP.

WAP Wireless Application Protocol. A protocol for transmitting data between aserver and a client (such as a cell phone) over a wireless network. WAP in thewireless world is analogous to HTTP in the World Wide Web.

WMA Wireless Messaging API. A set of classes for sending and receiving ShortMessage Service messages.

(x) button The button the user presses to end a task. On a real device this is the End key.On Windows it is the End key and sometimes the power key on the phoneskin.

244 Architecture and Design Guide • December 2008

Page 271: Architecture and Design Guide by Oracle

Index

AAccess module, 208Adaptive User Interface Technology, 115

customization, 117porting high-level UI, 115

adding a new localeporting steps, 210

Alert sound types, 108alpha encoding

adding alpha values, 103palette, 103

alpha transparency, 103ALPHA_LEVEL constant, 93alpha-blending, 103API module for Logging and Tracing service, 34APP_DIR constant, 159application management subsystem

components of, 146Application Management System (AMS), 145, 159Application Manager, 147application startup time (performance tuning), 223ARGB data, 103ARGB format, 102audio channels, limited number, 108AUI technology (Adaptive User Interface

Technology), 115Auto MIDlet Invocation subsystem

porting issues, 172porting strategies, 172user interaction, 174using networking protocols, 172

AutoTester, 147

Bbacklight

duration, 110flash rate, 110

backlighting, 108Behavior module, 208blanket permission, 183building Java Wireless Client software, 10

Cchameleon class package, 116

com.sun.midp.chameleon, 116com.sun.midp.chameleon.layers, 116com.sun.midp.chameleon.skins, 116

channels reporting mechanism, 37channels, adding, 37circle, mathematical definition of, 96classes

Graphics, 81Image, 103javax.microedition.lcdui.Graphics, 93javax.microedition.lcdui.Image, 101LayerManager, 219RecordStore, 43Sprite, 217TiledLayer, 217

collision detection, 217Command-line MIDlet Runner, 147Command-line MIDlet Suite Lister, 148

245

Page 272: Architecture and Design Guide by Oracle

Command-line MIDlet Suite Remover, 148compacting source, 24compositing, 104CONFIG_SUBDIR constant, 159Configuration.getProperty method, 23configurator, 23 to 31

description of, 23design of, 24external interactions with, 23input for constants, 29XML format, 27XML-formatted files, 27

constant_class element, 30constants

ALPHA_LEVEL, 93APP_DIR, 159CONFIG_SUBDIR, 159DISPLAY_NUM_COLOR, 93ERASE_COLOR, 93IMAGE_DEPTH, 93Low-Level Graphics table of, 93MOTION_SUPPORTED, 93POINTER_SUPPORTED, 93REPEAT_SUPPORTED, 93

constants output, 27createImage, 105

Ddata types, sizes of, 18database files, 44DatagramConnection, 193Decoder, 87

error types, 88implementing, 88

device backlighting, 108Discovery Application, 147display illumination, 108Display Manager, 181Display.flashBacklight, 108Display.vibrate method, 110DISPLAY_DEPTH, 93DISPLAY_NUM_COLOR constant, 93drawArc method, 96, 97drawing

arcs, 96lines, 94

rectangles, 95rectangles with rounded corners, 100

drawRect method, 95

Eellipse

drawing, 96mathematical definition for, 96

emulator, porting with, 11ERASE_COLOR constant, 93event service

event locking, 137MIDP event structure, 136normal (master) mode, 138porting, 133slave mode, 140

eXtensible Stylesheet Language (XSL) files, 31External Push Listener, 170External RMS API, 43

Ffile system, PCSL library, 62file system, POSIX, 62files

midpIndicators.h, 109Options.gmk, 112storagePosix.c, 159

fillingarcs, 96rectangles, 95rectangles with rounded corners, 100

fillRect method, 95fixed resource management (multitasking), 189font mapping, 107font variables, 107

GGame Canvas component, 220Games subsystem

components of, 216porting GameCanvas, 221porting Sprite, 221porting TiledLayer, 221

Generic Connection Framework (GCF), 193, 194generic tunneling mechanism for TCP-based

protocols, 197

246 Architecture and Design Guide • December 2008

Page 273: Architecture and Design Guide by Oracle

Graphical Installer, 147Graphics class, 81, 93

drawing arcs, 96drawing lines, 94drawing rectangles, 95drawing rectangles with rounded corners, 100filling arcs, 96filling rectangles, 95filling rectangles with rounded corners, 100

graphics context, 83graphics context component, 84graphics porting layer, 82, 91graphics primitives

drawing methods, 81library of drawing primitives, 82

graphics rendering component, 81Graphics.drawImage method, 101Graphics.drawRegion method, 101

Hhandles (PCSL networking), 65host development environment, 17HTTP 1.1 persistent connections, 198HTTP protocol (porting), 197HTTP proxy servers, 197HTTP tunneling, 197HttpConnection protocol, 193HTTPS protocol, porting, 198HttpsConnection protocol, 193

IImage class, 103Image component, 84image formats, 102image rendering, 90Image storage component, 89Image.getGraphics, 101IMAGE_DEPTH constant, 93images, transforming, 104immutable images

creating, 86decoder, 87implementing decoders, 88storage formats, 101, 102

inbound connection notifications, listening for, 173

index files, 44Installer, 181Internal API Protection subsystem

restricting access to classes, 178Internal Push Listener, 169

defined, 169internationalization, 207

JJava Wireless Client software, 1

porting architecture, 7resource limitations, 18

javax.microedition.lcdui.Image class, 101,103

JIT compiler, 228JTWI permission levels, 184

LLayerManager class, 219locale-specific content component

porting, 210locking, event, 137Logging and Tracing service

API module, 34channels, 37code removal at compile time, 36

Logging and Tracing subsystemadding channels, 37

logging, definition of, 33, 36Low-Level Graphics and Images subsystem

components of, 79constants checklist, 92design requirements, 80external interactions, 80, 81, 86, 87Image component, 101image rendering, 104image transformation, 104improving performance, 91network indicator, 112optimizing performance, 114porting checklist for Image component, 105porting checklist for primitive graphics, 92porting steps for Image component, 105porting strategies for primitive graphics, 112porting verification, 113primitive graphics, 92vibration, 110

Index 247

Page 274: Architecture and Design Guide by Oracle

low-level graphics porting groups, 90

Mmalloc(), 60master mode (events), 138mathematical definitions

circle, 96ellipse, 96

memory managementporting requirements, 215

memory manager design, 80, 168, 216memory, PCSL library, 59message buffering, 173methods

drawArc, 96, 97drawRect, 95fillRect, 95

MIDlet Auto Invocation subsystemcomponents of, 169goals for, 168

MIDlet Suite Loader, 181MIDlet Suite Storage, 181MIDlet suites

performing authorized actions, 182MIDlets

optimizing startup time, 226performance tuning, 223tuning startup time, 223

MIDP 2.0, security model, 181MIDP permission checking system, 188MIDP permissions levels, 183MIDP Runtime Environment, 147midpIndicators.h file, 109MOTION_SUPPORTED constant, 93multiple MIDlets, running, 174multitasking

fixed resource management, 189open resource policy, 190porting resource issues, 191resource management, 189

mutable imagescreating, 87defined, 101storage formats, 102

Nnaming conventions of graphics drawing

methods, 91native bitmap format, 89Native Resource Management for Multitasking, 189native stack size, configuring, 18network connection states, 170network indicator, 112networking protocols

DatagramConnection, 193HttpConnection, 193HttpsConnection, 193SecureSocketConnection, 193ServerSocketConnection, 193SocketConnection, 193

networking, PCSL library, 64networking, porting, 193normal mode (events), 138

Oone shot permission, 183open resource policy (multitasking), 190Options.gmk file, 112

Ppalette alpha encoding, 103PCSL, 57

BSD networking, 68file system library, 62memory allocation library, 59network notification, 69networking library, 64print library, 58socket-over-serial networking, 69

performance tuning, 223 to 239application startup time, 223giving VM hints, 228

permission management subsystemadding new permissions, 185dependent systems, 181systems dependent on, 181

permissions, adding, 185Persistent Application Storage, 147PLTE chunk, 103PNG information, 103

248 Architecture and Design Guide • December 2008

Page 275: Architecture and Design Guide by Oracle

PNG transparency, 103porting, 103

POINTER_SUPPOERTED constant, 93porting

event processing service, 133graphics using PutPixel technology, 75HTTP protocol, 197HTTPS protocol, 198networking, 193networking subsystem, 195PCSL, 57user message bundle service, 210

porting points, 7porting SATSA optional packages, 223porting strategy, 9porting, heap-based implementation, 61porting, malloc-based implementation, 60POSIX file system, 62Preprocessor component, 85primitive graphics routines, 92primordial stack, 18print, PCSL library, 58properties

adding new, 28properties output, 27Public Keystore Manager, 148push protocol, 172PushRegistry, 169PutPixel technology, 75 to 77

building, 76porting, 75screen buffer, 75testing, 76tuning, 76

Rrecord management subsystem

functions of, 41porting strategies, 45

record management system (RMS), 41design requirements, 42

RecordStore class, 43renderer component, 90rendering images, 103rendering operation, 83

renderRegion, 104REPEAT_SUPPORTEDconstant, 93resource limitations, 18ROMizer, 24runtime information, reporting, 34runtime memory, conserving, 18runtime security

security token, 179runtime security service

design requirements, 177

SSandbox component of RMS, 43secure random data for SSL, 199SecureSocketConnection, 193Security and Trust Services API

porting of, 223security checks, avoiding multiple, 179security token, 179server socket, 199ServerSocketConnection, 193session permission, 183slave mode (events), 140SocketConnection, 193Sprite class, 217SSL implementation, 199startup time (measuring), 223storagePosix.c file, 159strategy, porting, 9System.getProperty method, 23

TTiledLayer class, 217tracing, definition of, 33, 36transforming, 104transparency, 103tRNS chunk, 103

UUser Message Bundle, 207user message bundle service

porting, 210

Index 249

Page 276: Architecture and Design Guide by Oracle

Vvibration support, 111

WWAP gateway, using a, 197

250 Architecture and Design Guide • December 2008